content stringlengths 42 6.51k |
|---|
def count(iterable):
""" Return the count of an iterable. Useful for generators. """
c = 0
for i in iterable:
c += 1
return c |
def filter_measurements(measurements, csc_name, topic_name):
"""Filter full list of measurements looking for CSC plus topic name.
Parameters
----------
measurements : list[str]
The list of all available measurements.
csc_name : str
Name of the CSC to filter on.
topic_name : str
... |
def get_intervals(times):
"""
Return intervals to xAxis on the graphic
:param times: times collection
:return: times in the format of the graphic
"""
return [time.value for time in times] |
def merge(incoming={}, output={}, overwrite=False):
"""
Resursively merges two dictionaries by taking inputs from the 'incoming' dictionary and overlaying them upon the 'output' dictionary.
By default, no values in the resulting dictionary will be overwritten if present in both.
Passing 'overwrite=True' will flip ... |
def find_indexes(b):
"""This function is similar to the 'find' a MATLAB function"""
return [i for (i, vals) in enumerate(b) if vals] |
def check_permitted_value(permitted_dict, provided_key):
"""Get a key/value mapping from a dict of permitted value.
If the key is not found in the dictionary, raise a KeyError with a more
descriptive message of the error.
Parameters
----------
permitted_dict : dict
A dictionary of vali... |
def row_to_resource(row):
"""
Transforms raw row from resource's table to resource representation
>>> import pprint
>>> pprint.pprint(row_to_resource({
... 'resource': {'name': []},
... 'ts': 'ts',
... 'txid': 'txid',
... 'resource_type': 'Patient',
... 'meta': {'... |
def getOCC(L):
"""
Returns the OCC data structure such that OCC[c][k] is the number of times char c appeared in L[1], ..., L[k]
"""
s = set(L)
d = dict()
occ = dict()
for c in set(L):
d[c] = 0
occ[c] = [0] * len(L)
for i in range(len(L)):
c = L[i]
d[c] += 1
... |
def check_input_data(data):
"""
This function is used to check if input data are accepted or not
Args:
data: input data
Returns: True or false
"""
if 'uri' in data.keys() and 'type' in data.keys() and 'part' in data.keys() and 'index' in data.keys():
return True
else:
... |
def speedup(t1, t):
"""Returns the list of speedup."""
return [t1 / tp for tp in t] |
def calculate_metrics(array_sure, array_possible, array_hypothesis):
""" Calculates precision, recall and alignment error rate as described in "A Systematic Comparison of Various
Statistical Alignment Models" (https://www.aclweb.org/anthology/J/J03/J03-1002.pdf) in chapter 5
Args:
array_sure: ... |
def isDefinitelyNotEqual_Solver(state, a, b):
"""
Does 'a' definitely not equal 'b', i.e., is it impossible for them to be equal.
More expensive than isDefinitelyNotEqual() (above), because it takes into account
the current context.
May catch some cases where 'a' definitely does not equal 'b' i... |
def _clamp(n, minn, maxn):
"""Returns the number n after fixing min and max thresholds.
minn and maxn are scalars that represent min and max capacities.
clamp ensures that capacities are within min/max thresholds
and sets n to minn or maxn if outside of thresholds, such that
minn < n < maxn
"""
... |
def flatten_soap_dict(simple_fields, address_fields, comma_field, soap_dict):
"""For all four FSRS models, we need to copy over values, flatten address
data, flatten topPaid, convert comma fields"""
model_attrs = {}
for field in simple_fields:
model_attrs[field] = soap_dict.get(field)
for pr... |
def in_static_dir(filepath, static_dirs):
"""See if filepath is contained within a directory contained in
static_dirs."""
for directory in static_dirs:
if filepath.startswith(directory):
return True
else:
return False |
def r(line):
"""
Selects rho from a given line.
"""
r, _ = line
return r |
def keyvalue2str(k, v):
"""
A function to convert key - value convination to string.
"""
body = ''
if isinstance(v, int):
body = "%s = %s " % (k, v)
else:
body = """%s = "%s" """ % (k, v)
return body |
def join_strings(strings, join_char="_"):
"""Join list of strings with an underscore.
The strings must contain string.printable characters only, otherwise an exception is raised.
If one of the strings has already an underscore, it will be replace by a null character.
Args:
strings: iterable of... |
def octal_to_str(octal):
"""Function: octal_to_stropenfile
Description: Convert an octal number to a string representation of Linux
file permissions.
Arguments:
(input) octal -> Octal number (i.e. 755, 644).
(output) result -> String representation (i.e. rwxr-xr-x).
"""
... |
def create_board(size):
"""Create the initial board, using size given by the user"""
board = []
try:
for _ in range(0, size):
tmp = []
for _ in range(0, size):
tmp.append(None)
board.append(tmp)
return board
except TypeE... |
def get_all_categories(product_list):
"""
Function to get a unique list of categories out of the list of products.
:param product_list: List of products
:return: dict with category names as keys
"""
categories_dict = dict()
for product in product_list:
if product['category_name'] no... |
def cards_to_string(cards):
"""
convert list of Card objects to string for db deck field
:param cards:
:return:
"""
return ','.join(map(lambda x: str(x.as_number()), cards)) |
def is_chinese(char: str) -> bool:
"""
Checks if a given character is in Chinese.
:param char: Character to check
:return: Whether character is a Chinese character
"""
char_ord = ord(char)
if char_ord < 3400:
return False
# CJK Unified Ideographs
if (
0x4e00 <= ... |
def compute_summary_sum(summary):
"""Compute sum of all summary counts (except: all)
:param summary: Summary counts (as dict).
:return: Sum of all counts (as integer).
"""
counts_sum = 0
for name, count in summary.items():
if name == "all":
continue # IGNORE IT.
c... |
def snana_ob_type_name(type_no: int):
"""
Retuens the type name in string for the type numbers in the ZTF dataset.
Parameters
----------
type_no: int
type number whose corresponding string is to be fetched.
Returns
-------
str: String with the type name.
"""
if type_no ... |
def tile_is_solid(tid):
"""
Return whether a tile is solid or not based on its ID.
Arguments:
tid: the tile ID
Returns: whether the tile is solid
"""
return tid in (2, 3, 5) |
def get_scores(count, pred_total, gold_total):
"""
Args:
Returns:
"""
if pred_total != gold_total:
return 0, 0, 0
elif count == pred_total:
return 1, 1, 1
return 0, 0, 0 |
def single_ped_posteriors_strs(num_variables=4, val_set=("0", "1")):
"""
@Params
num_variables = number of ped locations
@Returns
list of strings. Strings have the format: 'o_{i}={val}', where val is in val_set
"""
res = []
for i in range(num_variables):
for flag in val_set:
... |
def _check_parameters_transform(imgs, confounds):
"""A helper function to check the parameters and prepare for processing
as a list.
"""
if not isinstance(imgs, (list, tuple)) or \
isinstance(imgs, str):
imgs = [imgs, ]
single_subject = True
elif isinstance(imgs, (list, t... |
def cut_between(s, first, last):
"""slice the given hex string (s) between (first) and (last)"""
try:
start = s.index(first) + len(first)
end = s.index(last, start)
return s[start:end]
except ValueError:
return "" |
def args(*params):
"""Constructs a dict from a list of arguments for sending a CBOR command.
None elements will be omitted.
:param params: Arguments, in order, to add to the command.
:return: The input parameters as a dict.
"""
return dict((i, v) for i, v in enumerate(params, 1) if v is not Non... |
def format_attribute_value(value):
"""Apply random rules we have to the attribute values"""
# XXX This function is a terrible temporary hack that needs to go away
for suffix in ['.ig.local', '.innogames.net']:
if value.endswith(suffix):
value = value[:-len(suffix)]
return value.repla... |
def _delete_edge(edges_from, n, to):
"""
Removes an edge from the graph.
@param edges_from structure which contains the edges (will be modified)
@param n first vertex
@param to second vertex
@return the edge
"""
le = edg... |
def calc_check_digit(number):
"""Calculate the check digit for personal codes. The number passed
should not have the check digit included."""
# note that this algorithm has not been confirmed by an independent source
weights = (2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9)
check = sum(w * int(n) for w, n in z... |
def capitalize_first(x):
"""
This function upper-cases only the first letter, unlike
.capitalize() that leaves the other letters uppercase. It
leaves other letters as they were.
"""
return x[0].capitalize() + x[1:] if len(x) > 0 else x |
def convertToCamelCase(input, firstIsLowercase=False):
"""Given an input string of words (separated by space), converts
it back to camel case.
'Foo Bar' (firstIsLowercase=False) --> 'FooBar'
'Foo Bar' (firstIsLowercase=True) --> 'fooBar'
'foo bar' (firstIsLowercase=False) --> 'FooBar'
Args:
input (str)... |
def format_title(data):
"""Formats the event name."""
code = data["event_code"]
if code == "1":
return "ProcessCreation"
elif code == "2":
return "ProcessChangedFileCreationTime"
elif code == "3":
return "NetworkConnection"
elif code == "4":
return "SysmonServiceS... |
def __chr_hex(c):
"""xx"""
return str(hex(ord(c))) |
def is_valid_drm(drm):
"""
Verifies if a parsed DRM dict has the minimum required fields.
Args:
drm (dict): the DRM dict to be validated.
Returns:
(bool): True if the DRM is valid. Otherwise, False.
"""
required_keys = ("identifiers", "fields")
return all(key in drm for ke... |
def validate_gene_sets(genesets, var_names, context=None):
"""
Check validity of gene sets, return if correct, else raise error.
May also modify the gene set for conditions that should be resolved,
but which do not warrant a hard error.
Argument gene sets may be either the REST OTA format (list of ... |
def unpack_singleton(x):
"""
Return original except when it is a sequence of length 1 in which case return the only element
:param x: a list
:return: the original list or its only element
"""
if len(x) == 1:
return x[0]
else:
return x |
def int_(value):
"""
Generate an int object
"""
return {'$OBJECT': 'int', 'int': value} |
def epochJulian2JD(Jepoch):
#----------------------------------------------------------------------
"""
Convert a Julian epoch to a Julian date
:param Jepoch:
Julian epoch (in format nnnn.nn)
:type Jepoch:
Floating point number
:Returns:
Julian date
:Reference:
See :func:`JD2epochJulian`
:Notes... |
def suggestDType(x):
"""Return a suitable dtype for x"""
if isinstance(x, list) or isinstance(x, tuple):
if len(x) == 0:
raise Exception('can not determine dtype for empty list')
x = x[0]
if hasattr(x, 'dtype'):
return x.dtype
elif isinstance(x, float):
retur... |
def _list_difference(l1, l2):
"""list substraction compatible with Python2"""
# return l1 - l2
return list(set(l1) - set(l2)) |
def filter_none(items):
"""Remove instances of None from a list of items."""
return [item for item in items if item is not None] |
def convert(number: int) -> str:
"""
Similar to FizzBuzz, create the string based on factors of the given number
:param number: Given number
:return: Created string
"""
res = ""
sounds = {
3: 'Pling',
5: 'Plang',
7: 'Plong'
}
for num, sound in soun... |
def _recursive_parse_xml_to_dict(xml):
"""Recursively parses XML contents to python dict.
We assume that `object` tags are the only ones that can appear
multiple times at the same level of a tree.
Args:
xml: xml tree obtained by parsing XML file contents using lxml.etree
Returns:
Pyth... |
def _list_to_hash(lst):
"""Convert a flat list of key value pairs to a hash"""
return {lst[i]: lst[i+1] for i in range(0, len(lst), 2)}; |
def first(item, vec):
"""return the index of the first occurrence of item in vec"""
for i, v in enumerate(vec):
if item == v:
return i
return -1 |
def get_unique_list_values(list_to_review):
"""Helper function, takes in a list as a single argument and returns a unique list.
"""
unique_list = []
# traverse for all elements
for item in list_to_review:
# check if exists in unique_list or not
if item not in unique_l... |
def get_state_values(event, event_tag='new'):
"""
Retrieves the states from a state change event and
returns them as a dictionary of state name/state value pairs.
- event:
The SPARKL event as returned by `sparkl listen`.
- event_tag:
Either `old` or `new` (default). ... |
def arduino_map(x, in_min, in_max, out_min, out_max):
"""Return x mapped from in range to out range.
>>> arduino_map(0, 0, 10, 100, 1000)
100
>>> arduino_map(5, 0, 10, 100, 1000)
550
>>> arduino_map(10, 0, 10, 100, 1000)
1000
>>> arduino_map(0, 10, 0, 100, 1000)
1000
>>> ar... |
def convert_perm(m):
"""
Convert tuple m of non-negative integers to a permutation in
one-line form.
INPUT:
- ``m`` - tuple of non-negative integers with no repetitions
OUTPUT: ``list`` - conversion of ``m`` to a permutation of the set
1,2,...,len(m)
If ``m=(3,7,4)``, then one can vi... |
def get_word_counts(words):
"""Count the number of times a word appears in the words dict
Args:
words: A list of words
Returns:
A dict with the word as key and the count as value
"""
word_counts = {}
for word in words:
if word_counts.get(word) is None:
word_... |
def stations_by_river(stations):
"""Takes in a list of station objects, returns a dictionary of rivers (keys) matched to a list of their corresponding stations (values)"""
output_dict = dict()
for station in stations:
if station.river in output_dict:
output_dict[station.river].append(station)
else:
output_... |
def is_prime(p, DEBUG = False):
"""Finds out if a number is prime.
if p is a prime, let s be the maximal power of 2 dividing p-1,
so that p-1 = 2^s*d, such that d is odd.
Then for any 1 <= n <= p-1, either
n^d = 1 (mod p)
or
n^(2^(j)*d) = -1 (mod p) for some integer j with D: {0 <= j ... |
def steer_towards_point_controller(x, y, v):
"""
Given an intermediate goal point and a (constant) linear velocity, calculates the
angular velocity that will steer the robot towards the goal such that the robot
moves in a circular arc that passes through the intermediate goal point.
Arguments
-... |
def featDenorm(featuresNorm, mean, std):
"""Denormalize features by mean and standard deviation
Args:
features_norm (np.array): normlized np.array
mean (float): average of the array elements
std (np.array): standard deviation, a measure of the spread of the array elements
Returns:... |
def one_minute_update(timer, avg_summed, counter):
"""
This function determines if one minute has passed between printing 1 minute
average heart rate, and prints 1 minute average if one minute has elapsed
:param float timer: the current time in seconds since last 1 minute span
:param int avg_summed... |
def clamp(value, mn, mx):
"""Clamp the value to the the given minimum and maximum."""
return max(min(value, mx), mn) |
def find_determinant(matrix: list) -> float:
""" Find the determinant of a 2*2 matrix
Only 2*2 matrices are supported. Anything else will raise a TypeError """
if len(matrix) == 2:
return (matrix[0][0]*matrix[1][1])-(matrix[0][1]*matrix[1][0])
else:
raise TypeError("Only 2*2 matrices ar... |
def twos_comp(n, b):
"""Calculates the two's complement of a given number.
Parameters
----------
n : int
Number to calculate its two's complement.
b : int
Number of bits.
Examples
--------
Given `bits` = 3 and `n` = 4 (0b100), twos_comp(4, 3) equals -4 (0b100).
Give... |
def mat31_mod(b, m):
"""Compute moduli of a 3x1 matrix.
Parameters
----------
b : 'list' ['float']
3x1 matrix.
m : 'float'
modulus.
Returns
-------
res : 'list' ['float']
3x1 matrix.
"""
res = [0, 0, 0]
for i in range(3):
res[i] = int(b[i] - ... |
def intersection_over_union(boxA, boxB):
"""
Intersection over union of two bounding boxes.
:param boxA: bounding box A. Format: [xmin, ymin, xmax, ymax]
:param boxB: bounding box B.
:return: intersection over union score.
"""
# determine the (x, y)-coordinates of the intersection rectangle
... |
def _entity_skill_id(skill_id):
"""Helper converting a skill id to the format used in entities.
Arguments:
skill_id (str): skill identifier
Returns:
(str) skill id on the format used by skill entities
"""
skill_id = skill_id[:-1]
skill_id = skill_id.replace('.', '_')
skill_... |
def _unduplicate_field_names(field_names):
"""Append a number to duplicate field names to make them unique. """
res = []
for k in field_names:
if k in res:
i = 1
while k + "_" + str(i) in res:
i += 1
k += "_" + str(i)
res.append(k)
retu... |
def inverse_mutation(tour, index, step):
"""
Return new tour based on inverse mutation of sequence
[index,step] of tour of self
"""
inverse_tour = []
# check wether section wraps around
if index + step > len(tour):
inverse_tour = tour[index:] + tour[:index]
index = 0
else... |
def Parameters(heartbeat=0,
hostname=NotImplemented,
password=None,
port=5672,
username=None,
virtual_host="/"):
"""Connection parameters with sensible defaults."""
return {
'heartbeat': heartbeat,
'hostname': hostname,
... |
def argsort(seq):
"""
Generate the sorted arguments of a collection of values
Parameters
----------
seq : dict
Returns
-------
list
list of keys sorted by value
"""
return sorted(range(len(seq)), key=seq.__getitem__) |
def millions(x, pos):
"""The two args are the value and tick position."""
return '${:1.1f}M'.format(x*1e-6) |
def unpackRangeBits(ur1, ur2, ur3, ur4):
"""Given the ulUnicodeRange1, ulUnicodeRange2, ulUnicodeRange3,
ulUnicodeRange4 values from the OS/2 table, return a set of bit numbers.
>>> unpackRangeBits(0x0, 0x0, 0x0, 0x0)
set()
>>> unpackRangeBits(0x1, 0x0, 0x0, 0x0)
{0}
>>>... |
def ClearCombiningFunctionUnlessBasicSpecSet(ref, args, req=None):
"""Clear basic field (and default combine function) if spec not provided."""
del ref # unused
if req is None:
return req
if not args.IsSpecified('basic_level_spec'):
req.accessLevel.reset('basic')
return req |
def knot_hash(dayinput):
"""
second half solver day 10:
"""
suffix = [17, 31, 73, 47, 23]
knot = [i for i in range(256)]
sub_lengths = []
for x in dayinput:
sub_lengths.append(ord(x))
sub_lengths += suffix
current = skip = 0
for x in range(64):
for length in sub_l... |
def join_prefix(values, num):
"""Produce a string joining first `num` items in the list and indicate
total number total number of items.
"""
if len(values) <= 1:
return "".join(values)
if len(values) <= num:
return ", ".join(values[:-1]) + " and " + values[-1]
return "%s and %d o... |
def section(name):
"""
Returns regex matching the specified section. Case is ignored in name.
"""
return r'(?<=\n)={2,} *' + fr'(?i:{name})' + r' *={2,}' |
def bytes_to_int(b:bytes):
"""Take bytes as input and return associated integer."""
return int().from_bytes(b,"big") |
def _adjacent_verts(facets, vert):
"""Find the adjacent vertices in a hull to the given vertex.
Args:
facets (list of sets of ints): Convex hull facets, each item represents
a facet, with the contents of the set being its vertex indices.
vert (int): Vertex index to find vertices adj... |
def ip_to_tuple(ip):
"""Parse IP string and return (ip, port) tuple.
Arguments:
ip -- IP address:port string. I.e.: '127.0.0.1:8000'.
"""
ip, port = ip.split(':')
return (ip, int(port)) |
def get_N2(nvols, TR, LP, HP):
"""
Get the high frequency point
Parameters
----------
TR : float
Temporal Resolution
nvols : int
Number of volumes
LP : float
LowPass High Cutoff Frequency
HP : float
HighPass Low Cutoff Frequency
Returns
... |
def alias(language='en', value=''):
"""Create and return an alias (dict)"""
a = {}
if len(value) == 0:
a[language] = [{'language': language, 'value': ''}]
else:
a[language] = [{'language': language, 'value': val} for val in value]
return a |
def upload_gtf_product(transformed_gtf, bucket, existing_names):
"""Execute upload of a GTF product to GCS
"""
source_blob_name = transformed_gtf
target_blob_name = source_blob_name.replace('output/', '')
# Check if this file was already uploaded
if target_blob_name in existing_names:
p... |
def _decrement_pin_index(index):
"""Validate then decrement the pin index.
The pins internally are numbered from zero but externally from 1
"""
valid_indexes = (1, 2, 3, 4)
if index not in valid_indexes:
raise ValueError(f"GPIO pin index must be in {valid_indexes}"
... |
def normalize_identity(my_string: str) -> str:
"""
Return identity if string
:param my_string: string
:return: my_string
"""
if my_string and isinstance(my_string, str):
return my_string
else:
return '' |
def get_direction(ball_vector: list) -> int:
"""Get direction to navigate robot to face the ball
Args:
ball_vector (list of floats): Current vector of the ball with respect
to the robot.
Returns:
int: 0 = forward, -1 = right, 1 = left
"""
if -0.13 <= ball_vector[1] <= 0... |
def get_enrichment_analysis_name_from_file_name(fn):
"""
Output from ChromHMM Overlap Enrichment usually denotes the enrichment analysis name as the file names existing in the coordinate directory: For example: mutation_occ1.bed.gz
We want the enrichment_analysis_name to be mutation_occ1
"""
return (fn.split(".")... |
def indent(string):
""" indent string
>>> indent('abc\\ndef\\n')
'\\tabc\\n\\tdef\\n'
"""
return '\n'.join(
'\t' + line if line else ''
for line in string.split('\n')
) |
def unique_and_sort(full_list):
""" Remove duplicates from a list, and sort items based on how many times they appear
Items appearing more frequently in the original list will appear earlier in the returned list.
Parameters
----------
full_list : list
A list of items, each with an `id` att... |
def bs_cost(bw, bf, nodes=1, depth=1, max_depth=16, total=1):
"""
Estimate the number of leg evaluations performed in a Beam Search,
with a given beam width (`bw`) and branch factor (`bf`), to
reach a score of `max_depth`.
"""
if depth == max_depth:
return total
n = nodes * bf
to... |
def _ply_header(num_vertices, num_faces, use_vertex_colors=False):
"""
Return a string representing the PLY format header for the given data properties.
"""
hdr_top = """ply
format ascii 1.0
comment Generated by Brainload
"""
hdr_verts = """element vertex %d
property float x
property float y
proper... |
def get_param_value_by_name(parameters, name):
"""
Return the value from the conditions parameters given the param name.
:return: Object
"""
for p in parameters:
if p['name'] == name:
return p['value'] |
def get_target_indices(cl_prototypes):
"""Computes the list target indices for the current
conservation law prototype
Arguments:
cl_prototypes: dict that contains target indices for every monomer
@type dict
Returns:
Raises:
"""
return [
cl_prototypes[monomer]['tar... |
def make_input(tokens, pid = 0):
"""
make input for util.build_index
"""
s = []
for t in tokens:
if len(t[0]) > 0:
s.append( t[0] + ' ' + str(pid) + '_' + str(t[1]) + '_' + str(t[2]) )
if t [0] == '.':
s.append ('')
return s |
def replace_html(s):
"""
:param s: str
:return: str
"""
s = s.replace('"', '"')
s = s.replace('&', '&')
s = s.replace('<', '<')
s = s.replace('>', '>')
s = s.replace(' ', ' ')
s = s.replace(r'\/', '/')
return s |
def simple_cactus_of(summary):
"""Returns a cactus from a single summary (no averaging etc.,
just believe the values for any non-timeout result with a valid
retcode).
"""
tt = []
for run in summary['runs']:
if run['result'] != 'OK': continue
if run['return_code'] not in (10, 20):... |
def R_hill(mp, m_st, a_r,rp):
"""
compute the hill radius of a planet
Parameters:
----------
mp: array-like;
mass of the planet in same unit as m_st
m_st: array-like;
mass of the star
a_r: array-like;
scaled semi-major axis
rp: arr... |
def is_stepwise_motion(melody, position):
"""
Returns true if the note at position in the melody is in the middle of a
step-wise movement in a single direction.
"""
pre_note = melody[position - 1]
note = melody[position]
post_note = melody[position + 1]
step_to = abs(pre_note - note)
... |
def edit_distance(s1: str, s2: str) -> int:
"""Compute edit distance between two strings using dynamic programmic.
Lifted from: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python"""
if len(s1) < len(s2):
return edit_distance(s2, s1)
# len(s1) >= len(s2)
... |
def spliterator(bad_string):
"""Split a comma separated string into a list, removing any white space while your there."""
if bad_string:
return bad_string.replace(' ', '').split(',') |
def rmFromList(lst, thing=''):
"""Removes all values matching thing from a list"""
lst = list(lst)
for i in range(len(lst)-1, -1, -1):
if lst[i] == thing:
del lst[i]
return lst |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.