content stringlengths 42 6.51k |
|---|
def _index_matching_predicate(seq, pred):
"""Return index of first item matching predicate.
Args:
seq - a list.
pred - a function with one argument, returning True or False.
Returns:
index or None
"""
for i, v in enumerate(seq):
if pred(v):
return i
... |
def RPL_STATSUPTIME(sender, receipient, message):
""" Reply Code 242 """
return "<" + sender + ">: " + message |
def set_underline(level: int, length: int) -> str:
"""Create an underline string of a certain length
:param level: The underline level specifying the symbol to use
:param length: The string length
:return: Underline string
"""
underline_symbol = ["`", "#", "*", "-", "^", '"', "="]
symbol_st... |
def _ParseArgs(j2objc_args):
"""Separate arguments passed to J2ObjC into source files and J2ObjC flags.
Args:
j2objc_args: A list of args to pass to J2ObjC transpiler.
Returns:
A tuple containing source files and J2ObjC flags
"""
source_files = []
flags = []
is_next_flag_value = False
for j2obj... |
def axial_to_cubic(col, slant):
"""
Convert axial coordinate to its cubic equivalent.
"""
x = col
z = slant
y = -x - z
return x, y, z |
def strStr(haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
length_h = len(haystack)
length_n = len(needle)
for i in range(length_h - length_n + 1):
if haystack[i:i + length_n] == needle:
return i
return -1 |
def rsa_ascii_decode(x:int,x_len:int) -> str:
"""
I2OSP aka RSA's standard ascii decoder. Decodes the integer X into
multiple bytes and finally converts those ASCII codepoints into an
ASCII string.
:param x: Integer X to be converted to string.
:param x_len: the length that the string will be.
:return: A string... |
def _fix_structure(fields, seq):
"""Returns a string with correct # chars from db struct line.
fields should be the result of line.split('\t')
Implementation notes:
Pairing line uses strange format: = is pair, * is GU pair, and
nothing is unpaired. Cells are not padded out to the start... |
def Hllp(l, lp, x):
""" Fiber collision effective window method auxiliary function """
if l == 2 and lp == 0:
return x ** 2 - 1.
if l == 4 and lp == 0:
return 1.75 * x**4 - 2.5 * x**2 + 0.75
if l == 4 and lp == 2:
return x**4 - x**2
if l == 6 and lp == 0:
return 4.12... |
def evaluateIdentifier(gold, pred):
"""
Performs an intrinsic evaluation of a Complex Word Identification approach.
@param gold: A vector containing gold-standard labels.
@param pred: A vector containing predicted labels.
@return: Precision, Recall and F-1.
"""
#Initialize variables:
precisionc = 0
precisio... |
def file_path(name):
"""
Shortcut function to get the relative path to the directory
which contains the data.
"""
return "./data/%s" % name |
def get_center_coords(bounds):
""" description:
Return if center coords from bounds dict
usage:
ui_utils.get_center_coords(obj.info['bounds'])
tags: ui, android, center, coords
"""
x = bounds['left'] + (bounds['right'] - bounds['left']) / 2
y = bounds['top'] + ... |
def parse_list_result(match_list, raw_list):
"""Checks that a list of values matches the form specified in a format list.
Entries in the match_list can either be tuples or single values. If a
single value, e.g. a string or integer, then the corresponding entry in the
raw_list must match exactly. For ... |
def oct2hex(x):
"""
Convert octal string to hexadecimal string.
For instance: '32' -> '1a'
"""
return hex(int(x, 8))[2:] |
def set_view_timeout(config):
"""Set timeout duration for generating static images."""
return config["settings"].get("view_timeout", 60) |
def all_permutations(options):
"""
Generates a list of all possible permutations of a list of options
"""
solutions = [[]]
for option_set in options:
solutions = [item + [option]
for item in solutions
for option in option_set]
return solutions |
def dump_datetime(value):
"""Deserialize datetime object into string form for JSON processing."""
if value is None:
return None
return value.strftime("%Y-%m-%d") + ' ' + value.strftime("%H:%M:%S") |
def CombineImages(center, left, right, measurement, correction):
"""
Combine the image paths from `center`, `left` and `right` using the correction factor `correction`
Returns ([imagePaths], [measurements])
"""
imagePaths = []
imagePaths.extend(center)
imagePaths.extend(left)
imagePaths.... |
def my_square(y):
"""takes a value and return the squared value.
uses the * operator
"""
return(y ** 2) |
def to_byte(string):
""" convert byte to string in pytohn2/3
"""
return string.encode() |
def distance(num1, num2, num3):
""" CHECK IF ABSOLUTE DISTANCE IS CLOSE OR FAR AWAY {CLOSE = 1, FAR >=2}
:param:num1:num2:num3
:type:int
:return if absolute distance
:rtype:bool
"""
if abs(num1 - num2) is 1 or abs(num1 - num3) is 1:
return True
elif abs(num1 - num2) >= 2:
... |
def is_output(port):
"""Judge whether the port is an output port."""
try:
return port.mode == 'w'
except Exception:
return False |
def volumeFraction(concentration=1,molWeight=17,density=1.347):
""" molWeight is kDa
concentration in mM
density g/ml
"""
concentration_mg_ml = concentration*molWeight
volume_fraction = concentration_mg_ml/density/1e3
return volume_fraction |
def log2(num: int) -> int:
"""
Integer-valued logarigthm with base 2.
If ``n`` is not a power of 2, the result is rounded to the smallest number.
"""
return num.bit_length() - 1 |
def validate_distance(distance: float) -> float:
"""
Validates the distance of an object.
:param distance: The distance of the object.
:return: The validated distance.
"""
if distance < 0:
raise ValueError("The distance must be zero or positive.")
return distance |
def sum_digits(s):
""" assumes s a string
Returns an int that is the sum of all of the digits in s.
If there are no digits in s it raises a ValueError exception.
For example, sum_digits("a;35d4") returns 12. """
ans = 0
ValueErrorCnt = 0
for element in s:
try:
... |
def _format_explain_result(explain_result):
"""format output of an `explain` mongo command
Return a dictionary with 2 properties:
- 'details': the origin explain result without the `serverInfo` part
to avoid leaing mongo server version number
- 'summary': the list of execution statistics (i.e. d... |
def make_file_safe_api_name(api_name):
"""Make an api name safe for use in a file name"""
return "".join([c for c in api_name if c.isalpha() or c.isdigit() or c in (".", "_", "-")]) |
def RedFilter(c):
"""Returns True if color can be classified as a shade of red"""
if (c[0] > c[1]) and (c[0] > c[2]) and (c[1] == c[2]): return True
else: return False |
def recursively_find_changes(s, token):
"""
method 2 recursively find the method
# result: 73682
"""
# line continuation token? \ or implicit without any token like C++
#stop of the recursive method
if len(token) == 1:
if s%token[0] == 0: # s=0 ? return 1;
... |
def _get_path(dir_name):
"""
Get path.
"""
if dir_name:
path = dir_name + "/"
else:
path = ""
return path |
def remove_des(name):
"""
remove 'Class A Common Stock' and 'Common Stock' from listing names
"""
if name.endswith("Class A Common Stock"):
name = name[:-21]
if name.endswith("Common Stock"):
name = name[:-13]
return name |
def pickdate(target, datelist):
""" Pick the date from a list of tuples.
target: an index > 1
"""
return list(
map(
lambda x : (x[0], x[target]),
datelist
)
) |
def collatz(number):
"""An algorithm that no matter what positive number you give, it will return 1."""
number = int(number)
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result |
def calculate_dmr(delay_list: list, deadline: float) -> float:
"""Returns the node's deadline miss ratio (DMR)."""
miss = 0
for delay in delay_list:
if delay > deadline:
miss += 1
return miss/len(delay_list) |
def get_from_module(attrname):
"""
Returns the Python class/method of the specified |attrname|.
Typical usage pattern:
m = get_class("this.module.MyClass")
my_class = m(**kwargs)
"""
parts = attrname.split('.')
module = '.'.join(parts[:-1])
m = __import__(module)
for comp... |
def split(string, divider):
"""Splits a string according at the first instance of a divider."""
pieces = string.split(divider)
return [pieces[0].strip(), divider.join(pieces[1:])] |
def from_s3_input(slug, file):
""" Returns the S3 URL for an input fiule required by the DAG. """
return (
'{{ conf.get("core", "reach_s3_prefix") }}'
'/%s/%s'
) % (slug, file) |
def forwardToName(fwdLambda):
"""Unwrap a 'forward definition' lambda to a name.
Maps functions like 'lambda: X' to the string 'X'.
"""
if hasattr(fwdLambda, "__code__"):
if fwdLambda.__code__.co_code == b't\x00S\x00':
return fwdLambda.__code__.co_names[0]
if fwdLambda.__cod... |
def hex2dec(inp,verbose=True):
"""This code has been converted from the IDL source code
at http://www.astro.washington.edu/docs/idl/cgi-bin/getpro/library32.html?HEX2DEC
Convert hexadecimal representation to decimal integer.
Explanation : A hexadecimal string is converted to a decimal in... |
def validate_fixed(datum, schema, **kwargs):
"""
Check that the data value is fixed width bytes,
matching the schema['size'] exactly!
Parameters
----------
datum: Any
Data being validated
schema: dict
Schema
kwargs: Any
Unused kwargs
"""
return isinstance... |
def find_sponsor(sponsorid, sponsor_dictionary):
"""
Given a sponsorid, find the org with that sponsor. Return True and URI
if found. Return false and None if not found
"""
try:
uri = sponsor_dictionary[sponsorid]
found = True
except:
uri = None
found = False
... |
def agg_across_entities(entity_lists_by_doc):
"""
Return aggregate entities in descending order by count.
"""
if not entity_lists_by_doc or len(entity_lists_by_doc) == 0:
return []
result_set = {}
for doc_id in entity_lists_by_doc.keys():
cur_list = entity_lists_by_doc[doc_id]
... |
def _obscure_email_part(part):
"""
For parts longer than three characters, we reveal the first two characters and obscure the rest.
Parts up to three characters long are handled as special cases.
We reveal no more than 50% of the characters for any part.
:param part:
:return:
"""
if n... |
def isStateKey(key):
"""
:returns: C{True} iff this key refers to a state feature
:rtype: bool
"""
return '\'s ' in key |
def Cross3(a, b):
"""Return the cross product of two vectors, a x b."""
(ax, ay, az) = a
(bx, by, bz) = b
return (ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx) |
def parse_file_string(filestring):
"""
>>> parse_file_string("File 123: ABC (X, Y) Z")
('ABC (X, Y) Z', '')
>>> parse_file_string("File 123: ABC (X) Y (Z)")
('ABC (X) Y', 'Z')
>>> parse_file_string("File: ABC")
('ABC', '')
>>> parse_file_string("File 2: A, B, 1-2")
('A, B, 1-2', '')
... |
def dmp_copy(f, u):
"""Create a new copy of a polynomial `f` in `K[X]`. """
if not u:
return list(f)
v = u-1
return [ dmp_copy(c, v) for c in f ] |
def _format_training_params(params):
"""Convert dict pof parameters to the CLI format
{"k": "v"} --> "--k v"
Args:
params (dict): Parameters
Returns:
str: Command line params
"""
outputs = []
for k, v in params.items():
if isinstance(v, bool):
if v:
... |
def append_keys(results, search_key, keys):
""" defaultdict(list) behaviour for keys record
If search_key exists in results the keys list is appended
to the list stored at that key. Otherwise a new list containing
the keys is created and stored at that key.
Args:
result... |
def Kelvin_F(Fahrenheit):
"""Usage: Convert to Kelvin from Fahrenheit
Kelvin_F(Fahrenheit)"""
return (Fahrenheit-32) * 5/9 + 273.15 |
def _get_spec_for_keyword(t_spec, key):
"""Grabs the var tuple for a specific key.
Needed since variable name is in tuple
:param t_spec: Thrift spec for function/class
:param key: Variable key name to get
:return: None or spec tuple
"""
for _, arg_spec in t_spec.items():
if arg_spec[... |
def generate_region_info(region_params):
"""Generate the region_params list in the tiling parameter dict
Args:
region_params (dict):
A dictionary mapping each region-specific parameter to a list of values per fov
Returns:
list:
The complete set of region_params sort... |
def strformat_to_bytes(strformat):
"""
Convert a string (e.g. "5M") to number of bytes (int)
"""
suffixes = {'B': 1}
suffixes['K'] = 1000*suffixes['B']
suffixes['M'] = 1000*suffixes['K']
suffixes['G'] = 1000*suffixes['M']
suffixes['T'] = 1000*suffixes['G']
suffix = strformat[-1... |
def is_anion_cation_bond(valences, ii, jj):
"""
Checks if two given sites are an anion and a cation.
:param valences: list of site valences
:param ii: index of a site
:param jj: index of another site
:return: True if one site is an anion and the other is a cation (from the valences)
"""
... |
def get_aligned_size(n: int) -> int:
"""
Return the smallest multiple of 4KiB not less than the total of the loadable
segments. (In other words, the size will be returned as-is if it is an
exact multiple of 4KiB, otherwise it is rounded up to the next higher
multiple of 4KiB.)
"""
return n ... |
def _year_number_to_string(year):
"""Converts year from number to string.
:param year: Integer year.
:return: year_string: String in format "yyyy" (with leading zeros if
necessary).
"""
return '{0:04d}'.format(int(year)) |
def create_prof_dict(profs):
""" Creates a dictionary of professors with key being their pid """
professors = {}
for p in profs:
if (p['pid'] not in professors.keys()
and p['last_name'] != None):
professors[p['pid']] = p
professors[p['pid']]['reviews'] = []
return pro... |
def area_trapezium(base1: float, base2: float, height: float) -> float:
"""
Calculate the area of a trapezium.
>>> area_trapezium(10, 20, 30)
450.0
>>> area_trapezium(-1, -2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative v... |
def create_node_instance_task_dependencies(graph, tasks_and_node_instances, reverse=False):
"""
Creates dependencies between tasks if there is an outbound relationship between their node
instances.
"""
def get_task(node_instance_id):
for task, node_instance in tasks_and_node_instances:
... |
def has_time_layer(layers):
"""Returns `True` if there is a time/torque layer in `layers.
Returns `False` otherwise"""
return any(layer.time for layer in layers if not layer.is_basemap) |
def atof(text):
""" This function is auxiliary for the natural sorting of the paths names"""
try:
retval = float(text)
except ValueError:
retval = text
return retval |
def htk_to_ms(htk_time):
"""
Convert time in HTK (100 ns) units to ms
"""
if type(htk_time)==type("string"):
htk_time = float(htk_time)
return htk_time / 10000.0 |
def iobes_iob(tags):
"""
IOBES -> IOB
"""
new_tags = []
for i, tag in enumerate(tags):
if tag == 'rel':
new_tags.append(tag)
elif tag.split('-')[0] == 'B':
new_tags.append(tag)
elif tag.split('-')[0] == 'I':
new_tags.append(tag)
eli... |
def is_end_of_file(fp):
"""
check if it is the end of file.
"""
read_size = 8
dummy = fp.read(8)
if len(dummy) != read_size:
return True
else:
fp.seek(-read_size, 1)
return False |
def benchmark_sort_key(benchmark):
"""Returns the key that may be used to sort benchmarks by label."""
if not "label" in benchmark:
return ""
return benchmark["label"] |
def psi(alpha, t):
"""Evaluate Paul's wavelet"""
return 1./(t+1J)**(alpha+1) |
def to_number(X):
"""Convert the input to a number."""
try:
return X.item()
except AttributeError:
return X |
def isValidMove(x, y):
"""
Return True if the coordinates are on the board, otherwise False.
"""
return x >= 0 and x <= 59 and y >= 0 and y <= 14 |
def _build_jinja2_expr_tmp(jinja2_exprs):
"""Build a template to evaluate jinja2 expressions."""
exprs = []
tmpls = []
for var, expr in jinja2_exprs.items():
tmpl = f"{var}: >-\n {{{{ {var} }}}}"
if tmpl not in tmpls:
tmpls.append(tmpl)
if expr.strip() not in exprs:
... |
def argtest(*args):
""" Test filter: returns arguments as a concatenated string. """
return '|'.join(str(arg) for arg in args) |
def dijkstra_path(graph, start):
"""
Find the shortest paths between nodes using dijkstra algorithm.
:param list graph: List of lists(adjacency matrix), that represents the graph.
:param int start: Starting vertex. Search runs from here.
:returns: List with the shortest paths to all possible nodes... |
def calcMeanSD(useme):
"""
A numerically stable algorithm is given below. It also computes the mean.
This algorithm is due to Knuth,[1] who cites Welford.[2]
n = 0
mean = 0
M2 = 0
foreach x in data:
n = n + 1
delta = x - mean
mean = mean + delta/n
M2 = M2 + delta*(x ... |
def grv(struct, position):
"""
This function helps to convert date information for showing proper filtering
"""
if position == "year":
size = 4
else:
size = 2
if struct[position][2]:
rightnow = str(struct[position][0]).zfill(size)
else:
if position == "year":... |
def join_bucket_paths(*items):
"""
Build bucket path
:param items: list[str] -- path items
:return: str -- path
"""
return '/'.join(item.strip('/ ') for item in items) |
def sort_minio_node_candidates(nodes):
"""
to select a candidate node for minio install
we sort by
- amount of cpu: the node with the most cpu but least used
- amount of sru: the node with the most sru but least used
"""
def key(node):
return (-node['total_resources']['cru'],
... |
def describe_stats(state_dict):
"""Describe and render a dictionary. Usually, this function is called on a ``Solver`` state dictionary,
and merged with a progress bar.
Args:
state_dict (dict): the dictionary to showcase
Returns:
string: the dictionary to render.
"""
stats_displ... |
def BigUnion(iter):
"""
:param iter: Iterable collection of sets
:return: The union of all of the sets
"""
union = set()
for s in iter:
union.update(s)
return union |
def canonical_url(url):
"""Strip URL of protocol info and ending slashes
"""
url = url.lower()
if url.startswith("http://"):
url = url[7:]
if url.startswith("https://"):
url = url[8:]
if url.startswith("www."):
url = url[4:]
if url.endswith("/"):
url = url[:-1... |
def group_mols_by_container_index(mol_lst):
"""Take a list of MyMol.MyMol objects, and place them in lists according to
their associated contnr_idx values. These lists are accessed via
a dictionary, where they keys are the contnr_idx values
themselves.
:param mol_lst: The list of MyMol.MyMol object... |
def _get_layer_name(name):
"""
Extracts the name of the layer, which is compared against the config values for
`first_conv` and `classifier`.
The input is, e.g., name="res_net/remove/fc/kernel:0". We want to extract "fc".
"""
name = name.replace(":0", "") # Remove device IDs
name = name.re... |
def norm3d(x, y, z):
"""Calculate norm of vector [x, y, z]."""
return (x * x + y * y + z * z) ** 0.5 |
def _split_vars(input_str: str) -> list:
"""Split variables into a list.
This function ensures it splits variables based on commas not inside
default values or annotations but those between variables only. Brackets,
commas, and parentheses inside strings will not count.
"""
input_str = input_st... |
def performance_data(label, value, uom="", warn="", crit="", mini="", maxi=""):
"""
defined here: http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN201
"""
formatted_string = "%(label)s=%(value)s%(uom)s;%(warn)s;%(crit)s;%(mini)s;%(maxi)s" % locals()
# Get rid of spaces
formatted_s... |
def int_tuple(arg):
"""Convert a string of comma separated numbers to a tuple of integers"""
args = arg.split(',')
try:
return tuple([int(e) for e in args])
except ValueError:
raise ValueError('Expected a comma separated list of integers, ' +
'found %s' % arg) |
def preprocessing(Time):
"""Returns important range of time in which the celebrities enter the room
params: Time {2D array containing entering and leaving time of each celebrity}"""
impRange= Time.copy()
impRange = list(set([a[0] for a in impRange]))
impRange.sort()
return impRange |
def calc_tree_width(height, txcount):
"""Efficently calculates the number of nodes at given merkle tree height"""
return (txcount + (1 << height) - 1) >> height |
def square(number: int) -> int:
"""Calculate the number of grains.
:param number: int - the number of square on the chessboard.
:return: int - the number of grains on the given square number.
"""
if not 1 <= number <= 64:
raise ValueError("square must be between 1 and 64")
return 1 <<... |
def parse_ndenovo_exac(info, clinSig):
"""Rm benign variants greater than 1% bc these were used to train mpc"""
if clinSig == 'Benign':
if 'ANN=' in info:
if 'af_exac_all' in info:
exac = info.split('af_exac_all=')[1].split(';')[0]
if float(exac) > 0.01:
... |
def lookup(list_dicts, key, val):
""" Find key by value in list of dicts and return dict """
if val == "":
return None
r = next((d for d in list_dicts if d[key] == val), None)
if r is None:
raise(ValueError(val + " not found"))
return r |
def pipe(obj, func, *args, **kwargs):
"""
Apply a function ``func`` to object ``obj`` either by passing obj as the
first argument to the function or, in the case that the func is a tuple,
interpret the first element of the tuple as a function and pass the obj to
that function as a keyword argument w... |
def single_number(nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
for num in nums:
i ^= num
return i |
def mel2hz(mel):
"""Convert Mel frequency to frequency.
Args:
mel:Mel frequency
Returns:
Frequency.
"""
return 700 * (10**(mel / 2595.0) - 1) |
def _is_raster_path_band_formatted(raster_path_band):
"""Return true if raster path band is a (str, int) tuple/list."""
if not isinstance(raster_path_band, (list, tuple)):
return False
elif len(raster_path_band) != 2:
return False
elif not isinstance(raster_path_band[0], str):
re... |
def insert_dash_between_odds_common(number: int) -> str:
"""Inserts dash between two odd numbers.
Examples:
>>> assert insert_dash_between_odds_common(113345566) == "1-1-3-345-566"
"""
index: int = 0
result: str = str()
while index != len(str(number)):
result += str(number)[inde... |
def bubble_sort(seq):
"""
Implementation of bubble sort.
O(n2) and thus highly ineffective.
"""
size = len(seq) -1
for num in range(size, 0, -1):
for i in range(num):
if seq[i] > seq[i+1]:
temp = seq[i]
seq[i] = seq[i+1]
seq[i+1... |
def padding_string(pad, pool_size):
"""Get string defining the border mode.
Parameters
----------
pad: tuple[int]
Zero-padding in x- and y-direction.
pool_size: list[int]
Size of kernel.
Returns
-------
padding: str
Border mode identifier.
"""
if pad ... |
def getDetailsName(viewName):
"""
Return Details sheet name formatted with given view.
"""
return 'Details ({})'.format(viewName) |
def dictcopy3( lev1, depth=3 ):
"""For a dictionary, makes a copy, to a depth of 3. Non-dictionaries are not copied unless they behave like dictionaries."""
if depth<1:
return lev1
try:
lev2 = dict().fromkeys(lev1)
except: # Nothing to copy: lev1 isn't a dict or even a suitable list, ... |
def is_zip(file_type) -> bool:
"""
Check if the given file is a ZIP
Returns:
bool: Whether it's a ZIP file or not
"""
mimes = {
'application/zip',
'application/octet-stream',
'application/x-zip-compressed',
'multipart/x-zip'
}
for v in mimes:
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.