content stringlengths 42 6.51k |
|---|
def generate_county_dcids(countyfips):
"""
Args:
countyfips: a county FIPS code
Returns:
the matching dcid for the FIPS code
"""
if countyfips != 59:
dcid = "dcid:geoId/" + str(countyfips).zfill(5)
else:
dcid = "dcid:country/USA"
return dcid |
def get_divisable(row):
"""Get numbers from row where one divides another without rest."""
for index, num in enumerate(row[:-1]):
for other_num in row[index + 1:]:
if num % other_num == 0 or other_num % num == 0:
return sorted([num, other_num], reverse=True) |
def is_image_active(image):
"""Check the image status.
This check is needed in case the Glance image is stuck in queued status
or pending_delete.
"""
return str(getattr(image, 'status', None)) == "active" |
def g_iter(n):
"""Return the value of G(n), computed iteratively.
>>> g_iter(1)
1
>>> g_iter(2)
2
>>> g_iter(3)
3
>>> g_iter(4) #1*3+ 2*2 + 3*1
10
>>> g_iter(5) #1*3+ 2*2 + 3*1 + 2*3 + 3*2
22
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'g_iter... |
def temperate_seasons(year=0):
"""Temperate seasons.
Parameters
----------
year : int, optional
(dummy value).
Returns
-------
out : dict
integers as keys, temperate seasons as values.
Notes
-----
Appropriate for use as 'year_cycles' function in :class:`Calenda... |
def flatland_space_stations(n, c):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/flatland-space-stations/problem
Flatland is a country with a number of cities, some of which have space stations. Cities are numbered consecutively
and each has a road of 1km length connecting it to the next cit... |
def make_cybox_object(ctype, desc = "", extended_properties = {}):
"""
makes a cybox object (that goes in cybox list then container)
"""
cybox_object = {}
cybox_object["type"] = ctype
cybox_object['description'] = desc
cybox_object['extended_properties'] = extended_properties
ret... |
def center_y(cell_lower_left_y, cell_height, y0, word_height):
""" This function centers text along the y-axis
:param cell_lower_left_y: Lower left y-coordinate
:param cell_height: Height of cell in which text appears
:param y0: Lower bound of text (sometimes can be lower than cell_lower_left_y (i.e., ... |
def _GetNumLinesNeeded(text, max_line_width):
"""
:param text:
:param max_line_width:
"""
if max_line_width == 0:
return 1
lines = text.split('\n')
num_lines = len(lines) # number of original lines of text
max_line_len = max([len(l) for l in lines]) # longest line
... |
def number_of_friends(user):
"""how many friends?"""
return len(user["friends"]) |
def make_collection(iterable_or_singleton, type=list):
"""Make a collection from either an iterable of elements or a singleton element."""
try:
iterator = iter(iterable_or_singleton)
return type(iterator)
except TypeError:
return type((iterable_or_singleton,)) |
def sum_ap(N, d):
"""Return the sum of an arithmetic sequence."""
n = N // d
return (n * (2 * d + (n - 1) * d)) // 2 |
def matrix_multiply_1xm_nxm(a, b):
"""
Multiply a 1xM matrix and a NxM matrix.
:param a: 1xM matrix
:param b: NxM matrix
:return:
"""
result = [[0] * len(b[0]) for _ in range(len(a))]
for i in range(len(a)):
# iterate through columns of b
for j in range(len(b[0])):
... |
def median(data):
"""
Find the integer median of the data set.
"""
if not data:
return 0
sdata = sorted(data)
if len(data) % 2 == 0:
return (sdata[len(data) // 2] + sdata[len(data) // 2 - 1]) / 2
else:
return sdata[len(data) // 2] |
def is_anagram(s1, s2):
"""RETURN : True/False if anagram"""
return set(s1) == set(s2) |
def rank_items(items):
""" Get a rank for each item that is computed by price/weight """
for item in items:
item['rank'] = (item['price'] * 1.0) / (item['weight'] * 1.0) # I use 1.0 to get floats
return items |
def sign(x: float) -> float:
"""Return a float's sign."""
return 1.0 if x > 0.0 else -1.0 |
def ext_key(name):
"""Get the sort key for extensions."""
i = name.find('_')
if i >= 0:
k = name[:i]
if k in ('ARB', 'KHR', 'OES'):
return (0, name)
return (1, name) |
def get_stack_elements(stack, data):
"""
extracts top 3 elements from data from stack, e.g.
if data is 'words' then returns up to top 3 words
if data is 'tags' returns top 3 POS tags
returns '' if elements is not available
"""
depth = len(stack)
if depth >= 3:
return data[st... |
def _serialize_hcons(hcons):
"""Serialize [HandleConstraints] into the SimpleMRS encoding."""
toks = ['HCONS:', '<']
for hc in hcons:
toks.extend(hc)
# reln = hcon[1]
# toks += [hcon[0], rel, str(hcon.lo)]
toks += ['>']
return ' '.join(toks) |
def _unpack_uint16(data):
"""Convert 2 bytes in little-endian to an integer."""
assert len(data) == 2
return int.from_bytes(data, 'little') |
def best_score(a_dictionary):
"""
gets the best value from a dictionary (greatest integer)
"""
win_n = 0
winner = None
if type(a_dictionary) is dict:
for (key, value) in a_dictionary.items():
if value > win_n:
win_n = value
winner = key
ret... |
def POWER(number, power):
"""Raise a number to a given power.
Parameters
----------
number : float or int
number you would like to raise a power to.
power : float or int
number that you would like the number argument raised to.
Returns
-------
int or float
The n... |
def prod_ratio(x, y):
"""
Given floats :math:`x, y \\in \\mathbb{R}`, return the quantity
.. math::
\\frac{xy}{x+y}.
Parameters
----------
x : `float`
y : `float`
Returns
-------
`float`
"""
return (x*y)/(x+y) |
def inner(bra, ket):
"""Inner product of basis states bra and ket"""
return 0 if bra == 0 or ket == 0 else bra == ket |
def get_info_val(value):
"""Return info element value"""
if value == '':
value = '(Empty value)'
return value |
def exec_and_return(executable):
""" Uses Python's exec command, and obtains its return value """
# To understand this code: https://bugs.python.org/issue4831
fresh_locals = {}
exec('return_value = ' + executable, globals(), fresh_locals)
return fresh_locals['return_value'] |
def GetControlFlag(controlDR, controlDV, preciseFlag, controlRR, controlRV, controlAltFreq):
"""
This will ``check if the control sample passes or not``
:param int controlDR: int representing number of reference reads for control reported by delly
:param int controlDV: int representing number of varian... |
def compressed(x, selectors):
"""
compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
"""
return [d for d, s in zip(x, selectors) if s] |
def _WX(s, wx):
"""Returns TRUE if s contains string wx"""
if wx == '':
return 0
# special case for blowing/drifting snow
ix = s.find(wx)
if wx == 'SN' and ix > 1:
if s[ix-2:ix] in ('BL', 'DR'):
return 0
return ix >= 0 |
def get_first_arg(args, kwargs, name):
"""Returns named argument assuming it is in first position.
Returns None if not found.
Args:
args (tuple or list): args from function.
kwargs (dict): kwargs from function.
name (str): argument name
"""
try:
return kwargs[name]
... |
def strplural(n, name, nonumber=False, s=''):
"""
Returns the plural or singular of a string
Parameters
----------
n : integer
The plural or singular is based on this number.
name : string
String for which a plural is requested.
nonumber : boolean
If true, don't prep... |
def format_float(x, n_digits=3):
"""Format floating point number for output as string.
Parameters
----------
x : float
Number.
n_digits : int, optional
Number of decimal digits to round to.
(Default: 3)
Returns
-------
s : str
Formatted string.
"""
... |
def mergeIndiciesToValuesByMap(valueList, valueIndexMap):
"""Package a list of stats for REST delivery according to the corrisponding
valueIndexMap.
"""
if len(valueList) != len(valueIndexMap):
raise Exception("Stats: Value list and value index map did not match.")
return {valueIndexMa... |
def get_Met_vals(Mk):
"""
Based on the script BackRuns_OneSite_ByDay.ksh, retrieves various file properties based on the global Mk value
:param Mk: integer globalMetMk
:return: dictionary of variables
"""
d = dict()
if Mk == 3:
d['MetType'] = 'GLOUM6'
d['MetDefnFileName'] =... |
def _nextpow2(i):
"""
Find the next power of 2 for number i
"""
n = 1
while n < i:
n *= 2
return n |
def is_off(param: str):
"""Returns True if parameter in "off" values"""
values = ["", "None", "none", "F", "f"]
if str(param).lower() in values:
return True
else:
return False |
def has_resected_pair(unresected_idx, resected_imgs, img_adjacency):
"""Return true if unresected_idx image has matches to >= 1 currently resected image(s) """
for idx in resected_imgs:
if img_adjacency[unresected_idx][idx] == 1 or img_adjacency[idx][unresected_idx] == 1:
return True
ret... |
def _camel_to_snake(src_string):
"""Convert camelCase string to snake_case."""
dst_string = [src_string[0].lower()]
for c in src_string[1:]:
if c in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
dst_string.append("_")
dst_string.append(c.lower())
else:
dst_string.append... |
def ordered_groupby(collection, column):
"""Group collection by a column, maintaining the key
order from the collection.
Args:
collection (list): List of flat dictionaries.
column (str): Column (dict key) by which to group the list.
Returns:
grouped (dict): Dict of the column to... |
def set_output(state: bool):
"""
Sets the output state.
"""
return f"OUT{int(state)}" |
def is_wellformed(conjunction):
"""
Parameters
----------
conjunction : list
Returns
-------
bool
True if it is wellformed, otherwise False.
"""
nr_of_elements = len(conjunction)
elements = set()
for line in conjunction:
if len(line) != nr_of_elements:
... |
def has_refseq(db_list):
"""
Return the index of the list where the 'RefSeq' string is located.
Otherwise return None
:param db_list: A list of db names taken as the first element of the tuples in a
Swissprot.record.cross_references list
:return: int: index or None
"""
if 'RefSeq' in db_... |
def get_server_ip(server):
"""
:param server:
:return:
"""
props = server['properties'].split('|')
for prop in props:
if prop.startswith('defaultInterfaceAddress'):
ip = prop.split('=')[1]
return ip |
def joinstr( sep, *args ):
"""Join the arguments after converting them to a string"""
return sep.join( map( str, args ) ) |
def encode(data):
"""
Encodes a bytes object into a netstring and returns the result as another bytes object.
"""
return (str(len(data)).encode('ascii') + b':' + data + b',') |
def _set_cmap(cmap, grayscale):
"""Set the colourmap."""
if cmap is None:
cmap = 'gray' if grayscale else None
return cmap |
def lm2idx(l, m):
""" Spherical Harmonics (l, m) to linear index
:param l: 0-based
:param m:
:return: 0-based index
"""
return l ** 2 + (l + m) |
def is_uri_option(number):
"""
checks if the option is part of uri-path, uri-host, uri-port, uri-query
:param number:
:return:
"""
if number == 3 | number == 7 | number == 11 | number == 15:
return True
return False |
def missing_number2(input_array):
"""
:type nums: List[int]
:rtype: int
"""
tot_sum = (len(input_array)*(len(input_array) + 1))/2
for i in input_array:
tot_sum = tot_sum -i
return tot_sum |
def _CreateLinkProperty(name, label, url):
"""Returns a dict containing markdown link to show on dashboard."""
return {'a_' + name: '[%s](%s)' % (label, url)} |
def make_repr(_class):
"""Create a user-friendly represention of an object."""
from asyncio import iscoroutine
def _process_attrs(_dir):
for attr in _dir:
if not attr.startswith("_"):
attr_val = getattr(_class, attr)
if callable(attr_val):
... |
def parse_number(strnumber):
"""
Parse a single number of HPGL2 coordinates.
:param strnumber: String containing a number
from a coordinate data block, possibly with a leading sign.
:type strnumber: str
:return: The number in floating point.
:rtype: float
"""
return float(strnumber... |
def parse_configuration(configuration):
"""
"Python (C:\Python34\python.exe)" becomes ("Python", "C:\Python34\python.exe")
"BBC micro:bit" becomes ("BBC micro:bit", "")
"""
parts = configuration.split("(", maxsplit=1)
if len(parts) == 1:
return configuration, ""
else:
return... |
def microsecs_to_sec(microsec):
"""
Given mircoseonds returns seconds
:param: microseconds
:type: integer
:returns: seconds :type: integer
"""
if type(microsec) is not int:
raise ValueError("microsec must be integer")
return float(microsec) / 1000000 |
def shell_sort(lst):
"""
Sorts list using shell sort
:param lst:
:return: number of comparisons
"""
height = len(lst) // 2
comp = 0
while height > 0:
for i in range(height, len(lst)):
pos = lst[i]
j = i
cur_comp = 0
while j >= heigh... |
def _get_relationships(notation):
"""
Return the list of orthology relationships to keep.
ENSEMBL homology relationships are defined in:
https://www.ensembl.org/info/genome/compara/homology_types.html
Posible values to this function are '1:1', '1:n' and 'm:n'.
>>> _get_relationships('1:1')
... |
def _get_first_occurrence_for(iterable, wanted_object):
"""
Get the first occurrence of an object in an iterable.
Parameters
----------
iterable : iterable
The iterable containing the object.
wanted_object : object
The object to be found.
Returns
-------
index : int... |
def get_optional(param, kwargs, object_class):
"""Wrapper for optional params init."""
result = object_class(kwargs[param]) if param in kwargs else ''
return result |
def valid_integer(integer_str):
"""
Returns true if string given is a valid integer
"""
try:
int(integer_str)
except ValueError:
return False
return True |
def type_dir(klass):
"""like dir() but returns accumulated dictionary over base classes
Useful to get object elements without invoking them (eg.: for property type resolution).
"""
content = dict()
ns = getattr(klass, '__dict__', None)
if ns is not None:
content.update(klass.__dict__)
... |
def calc_hebrew_grammar(probs):
"""
:param probs: list of negative log likelihoods for a Hebrew corpus
:return: grammaticality of corpus
"""
grammar = 0
for idx in range(0, len(probs), 16):
grammar -= probs[idx + 1] + probs[idx + 5] + probs[idx + 9] + probs[idx + 13]
grammar -= p... |
def list_found_duplicates(in_list):
"""
Check list for duplicate entries. Return True if duplicates found,
and False if not duplicates found.
>>> in_list = ["hallo", "hello"]
>>> list_found_duplicates(in_list)
False
>>> in_list = ["hallo", "hello", "hollo", "hello"]
>>> list_found_dupli... |
def count_hierarchy(usr_id, level, parent_hierarchy, hierarchy):
""" Counts the level children """
if level > 8:
return
hierarchy[level] += len(parent_hierarchy[usr_id])
for child_id in parent_hierarchy[usr_id]:
count_hierarchy(child_id, level + 1, parent_hierarchy, hierarchy)
ret... |
def pkg_comp_version(v1, v2):
"""
Given version v1 and v2,
with format MM.mm.bb and tokens
[MM, mm, bb]
let's compare them token by
token, converting tokens starting with a 0
in decimals
"""
def leading_zeroes(v):
res = 0
for x in v:
if x == "0":
... |
def Trimmen_3(trim_2_2):
"""
Deze functie kijkt of de lengte van de read groter is dan 30 .
Wanneer dit niet zo is wordt de read als leeg gereturned.
Anders wordt er niks met de read gedaan.
"""
if len(trim_2_2) < 30:
return ""
else:
return trim_2_2 |
def _strictly_tril_size(n):
"""Unique elements outside the diagonal
"""
return n * (n-1) // 2 |
def heartbeat_interval(n):
"""
Interval in seconds that we desire heartbeats based on number of workers
"""
if n <= 10:
return 0.5
elif n < 50:
return 1
elif n < 200:
return 2
else:
return 5 |
def max_len(seq_list):
"""Returns the maximum sequence length within the given list of lists."""
lmax=0
for seq in seq_list:
lmax=max( lmax, len(seq) )
return lmax |
def round_to_quarter(value):
"""
This function is used to round a value to the nearest quarter.
Examples:
3.82 >> 3.75
6.91 >> 7.0
5.23 >> 5.25
2.11 >> 2.0
"""
return round(value*4)/4 |
def get_privilege_matches_for_resource_type(resource_type_matches):
""" Given the response from get_resource_type_matches_from_arn(...), this will identify the relevant privileges.
"""
privilege_matches = []
for match in resource_type_matches:
for privilege in match["service"]["privileges"]:
... |
def polyToBox(poly:list):
""" Converts a polygon in COCO lists of lists format to a bounding box in [x, y, w, h]. """
xmin = 1e10
xmax = -1e10
ymin = 1e10
ymax = -1e10
for poly_comp in poly:
for i in range(len(poly_comp) // 2):
x = poly_comp[2*i + 0]
y = poly_comp[2*i + 1]
xmin = min(x, xmin)
xma... |
def gauss_jordan(m, eps = 1.0/(10**10)):
"""Puts given matrix (2D array) into the Reduced Row Echelon Form.
Returns True if successful, False if 'm' is singular.
NOTE: make sure all the matrix items support fractions! Int matrix will NOT work!
Written by Jarno Elonen in April 2005, released into Public... |
def get_nrSEC_varname(num):
"""
Get necessary input nr sec variables
:param num: number e.g. 02
:return: list of variables.
"""
SOA = 'nrSOA_SEC'
SO4 = 'nrSO4_SEC'
if type(num) is int:
num = '%02.0f' % num
return [SOA + num, SO4 + num]
# fl = ['nrSOA%s'] |
def ratio(list1, list2):
"""
list1: previous
list2: current
return: intersection(previous & current) / current
"""
if len(list1)==0 or len(list2)==0:
return
ret = sum([1 for i in list2 if i in list1]) / len(list2)
return ret |
def _get_chunks(seg_dur, audio_id, audio_duration):
"""
Returns list of chunks
"""
num_chunks = int(audio_duration / seg_dur) # all in milliseconds
chunk_lst = [
audio_id + "_" + str(i * seg_dur) + "_" + str(i * seg_dur + seg_dur)
for i in range(num_chunks)
]
return chunk_... |
def absolute_value_text_2(number: int) -> str:
"""
Creates correct string using string techniques.
:param number: the length and type of the output string
:return: a string of pluses or minuses based on the input value
"""
if '-' in str(number):
return '-' * (-1 * int(number))
else:... |
def binary_search_for_left_range(mz_values, left_range):
"""
Return the index in the sorted array where the value is larger or equal than left_range
:param mz_values:
:param left_range:
:return:
"""
l = len(mz_values)
if mz_values[l - 1] < left_range:
raise ValueError("No value b... |
def get_marginal_protein_obs(p: int, r_max: int):
"""Get the observable for a marginalized protein abundance."""
marginal = ''
for r in range(r_max-1):
marginal += f'x_{r}_{p} + '
marginal += f'x_{r_max-1}_{p}'
return {'name': f'x_p{p}', 'formula': marginal} |
def get_input_filtering_cycles(size_in):
"""Cycles required to perform filtering of received values."""
# Based on thesis profiling
return 39*size_in + 135 |
def tb(s):
""" Encodes strings for compatibility
with Python 3.
"""
return s.encode() |
def get_loss_direction(a, b):
"""
Return a tensor with values in {-1, 0, 1} implementing the following function
`f(a, b) = (a + b - b * (1 - a)) - 1`.
The desired effect is
* a=1, b=1 -> 1
* a=1, b=0 -> 0
* a=0, b=1 -> -1
* a=0, b=0 -> -1
:param a: A [d1, ..., dN] tensor with v... |
def is_complement(data):
"""
Check if the entry is on the - strand.
"""
strand = data["strand"]
if not strand:
return None
return strand == "-" |
def find_clusters( trajectory_pairs ):
"""
Identifies clusters of trajectories which could be stitched together.
Parameters
----------
trajectory_pairs : list of 2-tuples of ints
List of 2-tuples of particle IDs, containing potential matched pairs of
trajectories across channels... |
def concatenate_data_dictionaries(D1, D2, selection_keys_list=[]):
"""
Concatenate dictionaries.
:param D1: first dictionary.
:param D2: second dictionary.
:return: the concatenated dictionaries.
"""
D3 = {}
if len(selection_keys_list) == 0:
keys = set(list(D1.keys()) + list(D2.k... |
def strip_dash(text):
""" Strip leading dashes from 'text' """
if not text:
return text
return text.strip("-") |
def as_dict(keys, values):
"""Take two iterables, one with keys and other
with values and return a dict
"""
try:
_ = iter(keys)
except TypeError:
return {keys: values}
return dict(zip(keys, values)) |
def sigmoid_secureml(x):
"""A crude piecewise lienar approximation of sigmoid."""
if x < -0.5:
return 0.0
elif x > 0.5:
return 1.0
else:
return x + 0.5 |
def year_list(x):
"""Return the elements of x that can be cast to year (int)."""
lst = []
for i in x:
try:
int(i) # this is a year
lst.append(i)
except ValueError:
pass
return lst |
def stringsed(instring, sedstring):
""" apply a sedstring to a string. """
seds = sedstring.split('/')
fr = seds[1].replace('\\', '')
to = seds[2].replace('\\', '')
mekker = instring.replace(fr,to)
return mekker |
def calculateSleepFactor(scansPerRead, LJMScanBacklog):
"""Calculates how much sleep should be done based on how far behind stream is.
@para scansPerRead: The number of scans returned by a eStreamRead call
@type scansPerRead: int
@para LJMScanBacklog: The number of backlogged scans in the LJM buff... |
def isAnagram(test, original):
""" is_anagram == PEP8 (forced mixedCase by CodeWars) """
return sorted(a for a in test.lower() if a.isalnum()) \
== sorted(b for b in original.lower() if b.isalnum()) |
def recall(tp, fn):
"""
Computes precision
Args:
tp (int): true positive
fn (int): false negative
Returns:
float: precision
"""
try:
return float(tp) / (tp + fn)
except ZeroDivisionError:
return 0 |
def str2int(s):
"""Convert a byte string to an integer.
@param s: byte string representing a positive integer to convert
@return: converted integer
"""
s = bytearray(s)
r = 0
for c in s:
r = (r << 8) | c
return r |
def dump_datetime(value):
"""Deserialize datetime object into string form for JSON processing."""
if value is None:
return None
# return datetime.strptime(str(value), '%Y-%m-%d %H:%M:%S')
return value.strftime("%Y-%m-%d") + ' ' + value.strftime("%H:%M:%S") |
def fullfile(root, name, ext):
"""
:param root:
:param name:
:param ext:
:return: the root, name, and extension of the pfile
"""
import os.path
return os.path.join(root,name+ext) |
def _format_data(test_data):
"""Format data string to store in test case."""
result = '[\n'
for data_set in test_data:
result += ' {\n'
for key, value in data_set.items():
if not value:
value = "''"
result += ' \'{}\': {},\n'.format(key, valu... |
def remove_trailing_slash(ze_url):
"""Remove the trailing slash"""
if ze_url and ze_url[-1] == '/':
ze_url = ze_url[:-1]
return ze_url |
def get_release_status(release):
"""
:param release: helm release metadata
:return: status name of release
"""
return release['info']['status'] |
def compare_range(a, astart, aend, b, bstart, bend):
"""Compare a[astart:aend] == b[bstart:bend], without slicing.
"""
if (aend-astart) != (bend-bstart):
return False
for ia, ib in zip(range(astart, aend), range(bstart, bend)):
if a[ia] != b[ib]:
return False
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.