content stringlengths 42 6.51k |
|---|
def assert_model_predictions_correct(
y_pred: float,
y_pred_perturb: float,
):
"""Assert that model predictions are the same."""
if y_pred == y_pred_perturb:
return True
else:
return False |
def filter_modules(model_state_dict, modules):
"""Filter non-matched modules in module_state_dict.
Args:
model_state_dict (OrderedDict): trained model state_dict
modules (list): specified module list for transfer
Return:
new_mods (list): the update module list
"""
new_mods = ... |
def mb_to_hgt(Psta, mslp=1013.25): # METERS
"""Convert millibars to expected altitude, in meters."""
return (1-(Psta/mslp)**0.190284)*44307.69396 |
def F_to_C(Tf):
"""convertit une temperature de Fahrenheit en Celsius"""
Tc = (Tf-32)*5/9
return Tc |
def _spark_filter_successive_chunks(chunk_1, chunk_2):
"""
Return the chunk having the highest 'chunk_index' between chunk X and Y
inputs are a tuple composed of (current chunk index, last point of current chunk, first point of previous chunk)
:param chunk_1: first chunk to compare
:type chunk_1: ... |
def process_medians(helst, shelst, authlst):
"""
>>> medians_he = [12, 130, 0, 12, 314, 18, 15, 12, 123]
>>> medians_she = [123, 52, 12, 345, 0, 13, 214, 12, 23]
>>> books = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
>>> process_medians(helst=medians_he, shelst=medians_she, authlst=books)
{'... |
def filter_OD(origins, destinations):
"""
takes lists of origins and destinations in (1D notation)
and returns list of tuples with OD coorinates
"""
if len(origins) == len(destinations):
return list(zip(origins, destinations))
else:
return [] |
def get_english_chapter_count(book):
"""
A helper function to return the number of chapters in a given book in the English version of the Bible.
:param book: Name of the book
:type book: str
:return: Number of chapters in the book. 0 usually means an invalid book or unsupported translation.
:rt... |
def format_error_code(errorCode: int, descriptions: list) -> str:
"""Emergency error code -> description.
Args:
errorCode: Error code to check.
descriptions: Description table with (code, mask, description) entries.
Returns:
Text error description.
"""
description = 'Unknow... |
def getHTMLOf(url):
"""
@param url a valid URL string
@return HTML of page at given URL
"""
import urllib
from urllib import request
return request.urlopen(request.Request(url)).read() |
def create_report(info):
"""Create a report with a list of auto included zcml."""
if not info:
# Return a comment. Maybe someone wants to automatically include this
# in a zcml file, so make it a proper xml comment.
return ["<!-- No zcml files found to include. -->"]
report = []
... |
def diwt2do(Di, WT):
"""Calculate pipe outer diameter from inner diameter and wall thickness.
"""
return Di + 2 * WT |
def getPairedPaths(cur_path, time2path, path2time, same_time=True):
"""
Get edges from the same time or (closed time if same_time = False).
Parameters
----------
cur_path: integer
name of the current edge / path
time2path: dictionary
time as key and list of edges / paths as valu... |
def genotype(gt: tuple) -> int:
"""Convert genotype tuple to dosage (0/1/2)"""
return None if gt == (None, None) else gt[0] + gt[1] |
def clean_action_name(action: str) -> str:
"""Cleans the given action to be used in the texts"""
return action.replace("-", " ").capitalize() |
def is_ends_with_underscore(value: str):
"""Does value end with underscore."""
if value == "":
return False
else:
return value[-1] == '_' |
def adding_odds(range1, range2):
"""
Function that sums all ods numbers between range 1 and range 2 (both inclusive)
Args:
range1(int): first range
range2(int): second range
Returns:
sum of all ods numbers between two ranges
"""
some_list = []
... |
def lerp(value1=0.0, value2=1.0, parameter=0.5):
"""
Linearly interpolates between value1 and value2 according to a parameter.
Args:
value1: First interpolation value
value2: Second interpolation value
parameter: Parameter of interpolation
Returns:
The linear intepolatio... |
def get_xpath_for_possible_available_time_element(day_index: int) -> str:
"""
The element showing potential available times displayed in the results are found in divs having the xpath:
'/html/body/div[4]/div[2]/div/div[5]/div/div[3]/div/div[2]/div[N]/div[1]/a'
... |
def error_rate(error_count, total):
"""
Calculate the error rate, given the error count and the total number
of words.
Args:
error_count (int): Number of errors.
total (int): Total number of words (of the same type).
Returns:
tuple (int, int, float): The error count, the to... |
def convert_link(link, idx):
"""Convert the D3 JSON link data into a Multinet-style record."""
return {
"_key": str(idx),
"_from": f"""people/{link["source"]}""",
"_to": f"""people/{link["target"]}""",
} |
def translate_priority(priority: str) -> str:
"""Translate to new Jira priority types.
Jira changed how their priority names, so some translation is
necessary if migrating from an older Jira.
Args:
priority: A ticket priority.
Returns:
A valid Jira priority.
"""
if priorit... |
def colorFromAngle(angle):
"""
Converts numbers into colors for shading effects.
"""
return (int(230*(angle/450)), int(230*(angle/450)), 250) |
def read_template(file_name):
"""reads the tex content from a file and returns it as a string"""
# open file
with open(file_name, 'r') as file:
# skip lines until we read a latex comment marker
for line in file:
if len(line) > 0 and line[0] == '%': break
# add lines to the template until we ... |
def get_plain_text(values, strip=True):
"""Get the first value in a list of values that we expect to be plain-text.
If it is a dict, then return the value of "value".
:param list values: a list of values
:param boolean strip: true if we should strip the plaintext value
:return: a string or None
... |
def make_twin(indices):
"""
Swaps to interfaces to give the tuple with opposite orientation. That is given a triangle with orientation
(i,j,k) this function return the same triangle with orientation (j,i,k)
:param indices:
:return:
"""
return indices[1], indices[0], indices[2] |
def grounding_dict_to_list(groundings):
"""Transform the webservice response into a flat list."""
all_grounding_lists = []
for entry in groundings:
grounding_list = []
for grounding_dict in entry:
grounding_list.append((grounding_dict['grounding'],
... |
def p_dict_has_key( dct, key ):
""" If `dct` is a dictionary AND has the `key`, then return True, Otherwise return False """
return ( isinstance( dct, dict ) and (key in dct) ) |
def strip_suffix(string_in, suffix):
"""
Strip a suffix from a string
"""
if string_in.endswith(suffix):
return string_in[:-len(suffix)]
return string_in |
def get_side(a, b, p):
"""Get which side cone is on relative to vehicle absolute coordinates"""
return (p[0]-a[0])*(b[1]-a[1]) - (p[1]-a[1])*(b[0]-a[0]) |
def check_list(in_lst, dtype=str):
"""Helper function to ensure input is a list of correct data type."""
assert isinstance(in_lst, (list, dtype, tuple))
if isinstance(in_lst, list):
for itm in in_lst:
assert isinstance(itm, dtype)
else:
in_lst = [in_lst]
return in_lst |
def infer_records(columns):
""" inferring all entity records of a sentence
Args:
columns: columns of a sentence in iob2 format
Returns:
entity record in gave sentence
"""
records = dict()
for col in columns:
start = 0
while start < len(col):
end = s... |
def zero_pad_value(value: int) -> str:
"""
Zero pad the provided value and return string.
"""
return "0" + str(value) if value < 10 else str(value) |
def Interpolator(X, Y, TimeleftIndex, TimeRightIndex,YValue):
"""
Interpolate exact time Y == YValue using 4 points around closest data point to YValue
Returns a tuple with time and error associated.
"""
Y1 = Y[TimeleftIndex]
Y2 = Y[TimeRightIndex]
X2 = X[TimeRightIndex]
X1 = X[Timeleft... |
def clean_bath_text(x):
"""
Cleanes the bathrooms_text field from AirBnB datasource.
This has only been tested for data obtained from Washington DC. For a new city you may need to update the list.
x = is the input of the bathroom_text field.
"""
if isinstance(x, str):
return(x... |
def SplitRange(regression):
"""Splits a range as retrieved from clusterfuzz.
Args:
regression: A string in format 'r1234:r5678'.
Returns:
A list containing two numbers represented in string, for example
['1234','5678'].
"""
if not regression:
return None
revisions = regression.split(':')
... |
def predict_species_orig(sepal_width=None,
petal_length=None,
petal_width=None):
""" Predictor for species from model/52952081035d07727e01d836
Predictive model by BigML - Machine Learning Made Easy
"""
if (petal_width is None):
return u'Iris... |
def skip_if(cursor, offset, date_key):
"""Return True if we want to skip a particular date"""
# Useful to skip work that already has been done
return int(date_key) < 20191228 |
def repr_format(obj, *args, **kwargs):
"""
Helper function to format objects into strings in the format of:
ClassName(param1=value1, param2=value2, ...)
:param obj: Object to get the class name from
:param args: Optional tuples of (param_name, value) which will ensure ordering during format
... |
def clamp(value, range_min, range_max):
"""Clamp a value within a range."""
return min(max(value, range_min), range_max) |
def myfunction(x):
"""Return the square of the value."""
if isinstance(x, int):
xx = x * x
else:
xx = None
return xx |
def group_episodes_by_writer(episodes):
"""Utilizes a dictionary to group individual episodes by a contributing writer. The writer's
name comprises the key and the associated value comprises a list of one or more episode
dictionaries. Duplicate keys are NOT permitted.
Format:
{
< wr... |
def base_name(name):
"""Returns name without overload index.
"""
i = name.find('_')
if i != -1:
return name[:i]
return name |
def isequal(angle, X, dx):
"""isequal function. Is angle equal X?"""
try:
if float(angle) == X:
return True
else:
return False
except ValueError:
return False |
def calculate_relative_enrichments(results, total_pathways_by_resource):
"""Calculate relative enrichment of pathways (enriched pathways/total pathways).
:param dict results: result enrichment
:param dict total_pathways_by_resource: resource to number of pathways
:rtype: dict
"""
return {
... |
def get_source_location_by_offset(source: str, offset: int) -> int:
"""Retrieve the Solidity source code location based on the source map
offset.
:param source: The Solidity source to analyze
:param offset: The source map's offset
:return: The offset's source line number equivalent
"""
ret... |
def get_val(d, keys):
"""Helper for getting nested values from a dict based on a list of keys."""
for key in keys:
d = d[key]
return d |
def mysql_stat(server, args_array, **kwargs):
"""Method: mysql_stat
Description: Function stub holder for mysql_perf.mysql_stat.
Arguments:
(input) server -> Server instance.
(input) args_array -> Stub holder for dictionary of args.
(input) **kwargs
class_cfg -> Stub... |
def isinstancetype(__type, type_class):
"""Recursive isinstance for types."""
__t = __type
while __t is not None:
if isinstance(__t, type_class):
return True
__t = __t.parent
return False |
def _search_for_existing_group(user, group):
"""Test if a group with a given source tag that the user is a member of already exists in the organization.
This is used to determine if the group has already been created and if new maps and apps that belong to the same group should be shared to the same group.
... |
def slash_escape(err):
""" codecs error handler. err is UnicodeDecode instance. return
a tuple with a replacement for the unencodable part of the input
and a position where encoding should continue"""
# print err, dir(err), err.start, err.end, err.object[:err.start]
thebyte = err.object[err.start:er... |
def add_scores ( sumscores, scores ):
"""Calculate the avg scores for each positions in a width window.
"""
n = len(scores)
for score_win in scores:
for (p,s) in score_win:
sumscores[p-1] += s
return True |
def filter_candidates(text, candidates):
"""
Filters completion candidates by the text being entered.
"""
return [x for x in candidates if x.startswith(text)] |
def countWords(text:str)->dict:
"""Prototype of a function counting number of appeareances of words in a text."""
word_count = {}
text = text.lower() # to prevent counting We and we as different words
skips = [".",",",";",":","'"]
for character in skips:
text = text.replace(character,"")
... |
def string_from_ids(ids):
"""
Concatenates the ids with ',' to do only one request for all ids
@:return
A concatenated string
"""
return ','.join(ids) |
def format_template(template: str, values: dict) -> str:
"""
Function to process `for` loops in our own simple
template language. Use for loops as so:
{{ for item in list }}
...
{{ endfor }}
"""
loop = ""
loop_elem = ""
loop_iter = ""
in_loop = False
output = ... |
def _method_info_from_argv(argv=None):
"""Command-line -> method call arg processing.
- positional args:
a b -> method('a', 'b')
- intifying args:
a 123 -> method('a', 123)
- json loading args:
a '["pi", 3.14, null]' -> method('a', ['pi', 3.14, None])
- keyword a... |
def splitFilename(filename):
"""
Pass in a standard style rpm fullname
Return a name, version, release, epoch, arch, e.g.::
foo-1.0-1.i386.rpm returns foo, 1.0, 1, i386
1:bar-9-123a.ia64.rpm returns bar, 9, 123a, 1, ia64
"""
if filename[-4:] == '.rpm':
filename = filen... |
def asFloatOrNone(val):
"""Converts floats, integers and string representations of either to floats.
If val is "NaN" (case irrelevant) or "?" returns None.
Raises ValueError or TypeError for all other values
"""
# check for NaN first in case ieee floating point is in use
# (in which case float(... |
def adjust_cluster_indices(clusters, subtoken_map, sent_start, sent_end):
"""
Adjust cluster indices to reflect their position within an individual sentence.
"""
adjusted_clusters = []
for cluster in clusters:
for span in cluster:
if span[0] >= sent_start and span[1] <= sent_end:... |
def parse_int(s):
"""
trim alphabets
"""
return int(float(''.join(i for i in s if (not i.isalpha())))) |
def from_python(value):
"""
Returns value prepared for storage. This is required for search because
some Python types cannot be converted to string and back without changes
in semantics, e.g. bools (True-->"True"-->True and False-->"False"-->True)
and NoneType (None-->"None"-->"None")::
>>>... |
def type_unpack(type):
""" return the struct and the len of a particular type """
type = type.lower()
s = None
l = None
if type == 'short':
s = 'h'
l = 2
elif type == 'ushort':
s = 'H'
l = 2
elif type == 'int':
s = 'i'
l = 4
elif type == 'u... |
def _unique_paths(m: int, n: int, memo = {}):
"""
@ref https://leetcode.com/problems/unique-paths/
@ref https://youtu.be/oBt53YbR9Kk Dynamic Programming - Learn to Solve
Algorithmic Problems & Coding Challenges. freeCodeCamp.com
@details 62. Unique Paths.
How many possible unique paths are the... |
def parse_float(n):
"""
Securely converts a non-numeric value to float.
"""
try:
return float(n)
except ValueError:
return float("nan") |
def tapcodeConvert(sentence: str, tap: str = " ", sep: str = ".", outputSep: str = " ") -> str:
"""
Convert TapCode to decimal values
Args:
Sentence (String): Tapcode to convert
Tap (String): Tap string ("." by default)
Sep (String): Separator ("... |
def format_number(n, max_length):
"""
Get number in String, in a format fitting in the max_length specified
:param n: number to transform in String
:param max_length: maximum length authorized to display that number
:return: a String representing this number fitting in the desired size
"""
... |
def distance_helper(initial_velocity, acceleration, time):
"""
Calculates the distance traveled given the initial velocity, acceleration, and time, Helper function to the distance
function.
:param initial_velocity: Integer initial velocity
:param acceleration: Integer acceleration
:param time: Integer time
:r... |
def get_domain(url):
""" Return the domain part of an url """
# Taken from https://www.quora.com/How-do-I-extract-only-the-domain-name-from-an-URL
if url is None:
return None
return url.split('//')[-1].split('/')[0] |
def compute_energy(moon):
"""
>>> compute_energy([[8,-12,-9], [-7,3,0]])
290
>>> compute_energy([[13,16,-3],[3,11,5]])
608
"""
kin_energy = 0
pot_energy = 0
for i in range(3):
kin_energy += abs(moon[1][i])
pot_energy += abs(moon[0][i])
return kin_energy*pot_energ... |
def RemoveNullTokens(in_ptkns):
"""This function just gets rid of useless empty tokens in the path ('', '.')
(However if '' appears at the beginning of a path, we leave it alone.)
"""
out_ptkns = []
for i in range(0, len(in_ptkns)):
if ((in_ptkns[i] != '.') and
((in_ptkns... |
def circulate(n):
"""
n: an int or a str of int
output: a set of "circulations" of n, including n itself
note: for definition of circulations, see question
"""
numSet = set()
numStr = str(n)
numLen = len(numStr)
if numLen is 1:
numSet.add(n)
return numSet
for... |
def run_length_encode(n):
"""Generates the run-length encoded version of `n`
https://en.wikipedia.org/wiki/Run-length_encoding
"""
prev = None
count = 0
output = []
for d in str(n):
if prev is None:
count = 1
prev = d
elif d == prev:
cou... |
def image_name(src):
"""
:param src: path
:return: file name
"""
return src.split('/')[-1] |
def solution(string):
"""Returns a reversed string with built in splice function."""
return(string[::-1]) |
def maybe_encode(value):
"""If the value passed in is a str, encode it as UTF-8 bytes for Python 3
:param str|bytes value: The value to maybe encode
:rtype: bytes
"""
try:
return value.encode("utf-8")
except AttributeError:
return value |
def firewall_rule_group_update_payload(passed_keywords: dict) -> dict:
"""Create a properly formatted firewall rule group payload.
{
"diff_operations": [
{
"from": "string",
"op": "string",
"path": "string"
}
],
"di... |
def format_isolate_name(isolate):
"""
Take a complete or partial isolate ``dict`` and return a readable isolate name.
:param isolate: a complete or partial isolate ``dict`` containing ``source_type`` and ``source_name`` fields.
:type isolate: dict
:return: an isolate name
:rtype: str
"""
... |
def is_wrapped(transformer):
"""Check if a transformer is wrapped.
Args:
transformer: A transformer instance
Returns:
bool: True if transformer is wrapped, otherwise False.
"""
return hasattr(transformer, "is_wrapped") |
def get_cos_theta(s, d):
"""Calculate the cosine of the contact angle.
Args:
s: A float (or numpy array): the spreading coefficient.
d: A float (or numpy array): the drying coefficient.
Returns:
The cosine of the contact angle as a float or numpy array.
"""
return -(s - d) ... |
def code_snippet(snippet):
"""Change a string-typed code snippet into Markdown-style code fence.
# Argument
snippet: `str`. A code snippet.
# Return
`str`: Markdown-style code fence.
"""
return '```python\n{}\n```'.format(snippet) |
def check_for_victory(board):
"""
the function analyzes the board status in order to check if
the player using 'O's or 'X's has won the game
"""
row_len = len(board)
col_len = len(board[0])
#Row check
for row_list in board:
result = len(row_list) > 0 and all(elem == row_list[0] f... |
def dcs_caption_from_id(dcs_id,dcs_json_data):
"""
Find Caption from an DataCore Id
"""
for item in dcs_json_data:
if item["Id"] == dcs_id:
return str(item["Caption"]) |
def boobies(text):
"""- prints boobies!"""
boob = "\u2299"
out = text.strip()
out = out.replace('o', boob).replace('O', boob).replace('0', boob)
if out == text.strip():
return "Sorry I couldn't turn anything in '{}' into boobs for you.".format(out)
return out |
def result_format(task, clf, ftype, fscope, token, partition, res):
"""
Helper function to produce result dictionary (for use in dataframe)
"""
return {
"task": task,
"classifier": clf,
"feature_type": ftype,
"feature_scope": fscope,
"token": token,
"parti... |
def takeids(cblist, rows_var):
""" Take check button list and returns Employee ids for continue operation.
Show warning message if selected 'all' button for critical operation (flag warning).
Return tuples of (id, rownum) of check button
"""
rowsnum = tuple([i-1 for (i, var) in enumerate(cblist) if... |
def map_geometries(func, obj):
"""
Returns the result of passing every geometry in the given geojson object
through func.
:param func: Function to apply to tuples
:type func: function
:param obj: A geometry or feature to extract the coordinates from.
:type obj: GeoJSON
:return: The resu... |
def dlist(src):
"""
Convert dicts with numeric keys to lists
:param src: {"a": {"b": {"0":"red", "1":"blue"}, "c": "foo"}}
:return: {"a": {"b": ["red", "blue"], "c": "foo"}}
"""
if isinstance(src, dict):
for k in src:
src[k] = dlist(src[k])
if set(src) == set([str(k)... |
def contains_digits(input_str):
"""Receives input string and checks if it contains
one or more digits."""
digi_range = [str(i) for i in range(10)]
return any(c in digi_range for c in list(input_str.lower())) |
def get_remote_file_name(url):
"""Create a file name from the url
Args:
url: file location
Returns:
String representing the filename
"""
array = url.split('/')
name = url
if len(array) > 0:
name = array[-1]
return name |
def _get_docstring_type_name(var_doc: str) -> str:
"""
Get the string of argument or return value type's description
from docstring.
Parameters
----------
var_doc : str
Docstring's part of argument or return value.
Returns
-------
type_name : str
Argument or return ... |
def selection_sort(items):
"""Sort given items by finding minimum item, swapping it with first
unsorted item, and repeating until all items are in sorted order.
Running time: O(n**2) As it loops through the whole array for each element
Memory usage: O(1) Sorting is done in place on the array
"""
... |
def show_g(t):
"""[(g,p),[lst]]"""
return (t[0] [0]) |
def abbreviation(a, b):
"""https://www.hackerrank.com/challenges/abbr"""
n = len(b)
m = len(a)
memo = [[False]*(m + 1) for _ in range(n + 1)]
memo[0][0] = True
for i in range(n + 1):
for j in range(m + 1):
if i == 0 and j > 0:
memo[i][j] = a[j - 1].islower(... |
def escape(s, quote=None):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated."""
s = s.replace('&', '&')
s = s.replace('<', '<')
s = s.replace('>', '>')
if quote:
s ... |
def line_and_column(text, position):
"""Return the line number and column of a position in a string."""
position_counter = 0
for idx_line, line in enumerate(text.splitlines(True)):
if (position_counter + len(line.rstrip())) >= position:
return (idx_line, position - position_counter)
... |
def format_size(size: int) -> str:
"""Formats the size of a file into MB
Input:
- size: size of a file in bytes
Output:
- formatted string showing the size of the file in MB
"""
return "%3.1f MB" % (size/1000000) if size is not None else size |
def _get_default_annual_spacing(nyears):
"""
Returns a default spacing between consecutive ticks for annual data.
"""
if nyears < 11:
(min_spacing, maj_spacing) = (1, 1)
elif nyears < 20:
(min_spacing, maj_spacing) = (1, 2)
elif nyears < 50:
(min_spacing, maj_spacing) = (... |
def sortbylength(data, lang_ids, maxlen=500):
"""
:param data: List of tuples of source sentences and morph tags
:param lang_ids: List of lang IDs for each sentence
:param maxlen: Maximum sentence length permitted
:return: Sorted data and sorted langIDs
"""
src = [elem[0] for elem in data]
tgt = [elem[1... |
def sqlInsertStrFromList (table,aList,dbType='postgres'):
"""Take a list and make an insert string.
This works with dictionaries too. Here is a quick example:
>>> aList = [('one',1),('2','two'),('threepoint',3.)]
>>> sqlInsertStrFromList('myTable',aList,dbType='sqlite')
"insert into myTable (one,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.