content stringlengths 42 6.51k |
|---|
def extract_times_from_individuals(individuals, warm_up_time, class_type):
"""
Extract waiting times and service times for all individuals and proceed to extract
blocking times for just class 2 individuals. The function uses individual's records
and determines the type of class that each individual is, ... |
def reverse(sentence):
""" split original sentence into a list, then append elements of the old list to the new list starting from last to first. then join the list back toghether. """
original = sentence.split()
reverse = []
count = len(original) - 1
while count >= 0:
reverse.ap... |
def set_compilation_options(opts, compilation_options=None):
"""Set the IPU compilation options for the session.
.. code-block:: python
# Create a device with debug execution profile flag set to "compute_sets"
opts = create_ipu_config()
opts = set_compilation_options(opts,
compilation_... |
def remove_leading_zeros(string: str) -> str:
"""Removes leading zeros from the given string, if applicable.
Parameters
----------
string: str
The string to remove leading zeros from. This string must represent an
integer value (i.e. it cannot contain a decimal point or any other
... |
def delta_g(g, g0, qg, qg0):
"""Gera o delta g"""
if g0 < g:
return (g0 - g) - qg
else:
return (g0 - g) + qg0 |
def mat_inter(box1, box2):
"""
whether two bbox is overlapped
"""
# box=(xA,yA,xB,yB)
x01, y01, x02, y02 = box1
x11, y11, x12, y12 = box2
lx = abs((x01 + x02) / 2 - (x11 + x12) / 2)
ly = abs((y01 + y02) / 2 - (y11 + y12) / 2)
sax = abs(x01 - x02)
sbx = abs(x11 - x12)
say = ... |
def create_options(f107=1, time_independent=1, symmetrical_annual=1,
symmetrical_semiannual=1, asymmetrical_annual=1,
asymmetrical_semiannual=1, diurnal=1, semidiurnal=1,
geomagnetic_activity=1, all_ut_effects=1, longitudinal=1,
mixed_ut_long=1... |
def hamming2(s1, s2):
"""Calculate the Hamming distance between two bit strings"""
assert len(s1) == len(s2)
return sum(c1 != c2 for c1, c2 in zip(s1, s2)) |
def percent_btn(value):
"""Convert the current value to a percentage in decimal form."""
try:
x = float(value)
return x / 100
except ValueError:
return "ERROR" |
def ERR_BANNEDFROMCHAN(sender, receipient, message):
""" Error Code 474 """
return "ERROR from <" + sender + ">: " + message |
def ternary_point_kwargs(
alpha=1.0,
zorder=4,
s: float = 25,
marker="X",
):
"""
Plot point to a ternary figure.
"""
return dict(
alpha=alpha,
zorder=zorder,
s=s,
marker=marker,
) |
def get_lines_len(word_sizes):
"""return the length of all the lines that are 0 weperated"""
line_lens=[]
current_line_len=0
for dim in word_sizes:
if dim==0:
line_lens.append(current_line_len)
current_line_len=0
else:
current_line_len+=dim[0]
ret... |
def broadcast(i, n):
"""Broadcasts i to a vector of length n."""
try:
i = list(i)
except:
i = [i]
reps, leftovers = divmod(n, len(i))
return (i * reps) + i[:leftovers] |
def wilkinson_algorithm(values, binwidth):
"""Wilkinson's algorithm to distribute dots into horizontal stacks."""
ndots = len(values)
count = 0
stack_locs, stack_counts = [], []
while count < ndots:
stack_first_dot = values[count]
num_dots_stack = 0
while values[count] < (bi... |
def constructTableQuery(ch, index):
"""helper function for characterInTableName"""
payload = "' OR EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='test' AND TABLE_NAME LIKE '"
tableStr = ""
if(index == "no index"):
tableStr += "%" + ch + "%"
elif(index >= 0):
tab... |
def get_colors(scores, top_emotion):
"""Map colors to emotion `scores`"""
red = green = blue = 0
# For warm and cold emotions, return solid color
if top_emotion == 'anger':
color = (255, 0, 0) # red
return color
elif top_emotion == 'fear':
color = (255, 255, 0) # yellow
... |
def parseargs(string:str):
"""Split a given string into individual arguments, seperated into key:arg for <key>=(' or ")<arg>(same char as start)"""
arg = {}
# ([%-%w]+)=([\"'])(.-)%2
# '([\w]+)=([\"\'])(.*)'
# '([-\w]+)=([\"\']*)'
## pattern = re.compile('([\w]+)=([\"\'])(.*)')
## print(patter... |
def compute_in_degrees(digraph):
""" take in param graph, output in degree dictionary """
graph = {}
for node in digraph:
graph[node] = 0
for node in digraph:
for itr in digraph[node]:
graph[itr] += 1
return graph |
def normalize(path):
"""Replace spaces with underscores, everything to lowercase, remove double
slashes
:returns: normalized string
"""
return path.replace(" ", "_").lower().replace("//", "/") |
def link_format(name, url):
"""make markdown link format string
"""
return "["+name+"]"+"("+url+")" |
def _map_parameters_to_vars(px):
"""Return map `{a: x, b: x, ...}`."""
d = {d['a']: k for k, d in px.items()}
d.update((d['b'], k) for k, d in px.items())
return d |
def get_value(data, value):
"""Retrieve weather value."""
try:
if value == "@mps":
return round(float(data[value]) * 3.6, 1)
return round(float(data[value]), 1)
except (ValueError, IndexError, KeyError):
return None |
def quadratic_mag_model(data, a, b, c, d, e, f):
"""
Return the value of a three-dimenstional function linear in temperature and
metallicity (with cross-term) and quadratic in the third term (nominally
magnitude).
Parameters
----------
data : array-like with dimensions (3, n)
The id... |
def raise_mask(dqarr, bitmask):
"""
Function that raises (sets) all the bits in 'dqarr' contained
in the bitmask.
:Parameters:
dqarr: numpy array or integer
numpy array which represents a dq plane (or part of it).
The function also works when dqarr is a sca... |
def numestate_incolour(colour:str) -> int:
"""Return the number of fields in given colour."""
if colour in {'brown','blue'}:
return 2
return 3 |
def word_count(text):
"""
This function counts amount
of each given symbol
in the text
"""
count = {}
for c in set(text):
count[c] = text.count(c)
return count |
def _unique_deps(new_deps_list):
"""Unique dependency list, for duplicate items only keep the later ones."""
result = []
deps = set()
for dep in reversed(new_deps_list):
if dep not in deps:
result.append(dep)
deps.add(dep)
return list(reversed(result)) |
def moving_average_filter(val, filtered_val_prev, zeta):
"""
Basic moving average filter
zeta = 1 -> ignore prev. vals
zeta = 0 -> ignore current val
"""
filtered_val = (1-zeta)*filtered_val_prev + zeta*val
return filtered_val |
def sbfiz(value, lsb, width, size):
"""Signed Bitfield Insert in Zero"""
if value & (1 << (width - 1)):
# Extend sign
sign_ext = (1 << (8 * size)) - (1 << (lsb + width))
return ((value & ((1 << width) - 1)) << lsb) | sign_ext
else:
return (value & ((1 << width) - 1)) << lsb |
def step(x0: float, x1: float, p: float):
"""
Interplates step=wise between two values such that when p<0.5
the interpolated value is x0 and otherwise it's x1
"""
return x0 if p < 0.5 else x1 |
def chunk_string(input_str, length):
"""
Splits a string in to smaller chunks.
NOTE: http://stackoverflow.com/questions/18854620/
:param input_str: The input string to chunk.
:type input_str: str
:param length: The length of each chunk.
:type length: int
:return: A list of the input str... |
def section_is_higher(smoke_map, center, adjacent):
""" True if the adjacent section is higher than the center (the point we're evaluating)"""
if adjacent is None:
return True
else:
return smoke_map[adjacent[0]][adjacent[1]] > center |
def format_results(results, separator):
"""
:param results:
:param separator:
:return:
"""
if results.get('matched_bibcode', None):
match = separator.join([str(results.get(field, '')) for field in ['source_bibcode', 'matched_bibcode', 'confidence', 'score', 'comment']])
if resul... |
def get_netconnect_config(d_cfg):
"""Convert app configuration to netconnect configuration
"""
nc_cfg = {}
if d_cfg['connection_type'] == 'wifi_client':
wcfg = d_cfg['wifi']
cfg = {}
cfg['wifi_client'] = {}
cfg['name'] = 'wlan0'
cfg['ipv4'] = wcfg['ipv4']
... |
def first_not_null(str_one, str_two):
"""
It returns the first not null value, or null if both are null.
Note that if the output of this function is null and it is used as string,
the EL library converts it to an empty string. This is the common behavior
when using firstNotNull() in node configurat... |
def tab_in_leading(s):
"""Returns True if there are tabs in the leading whitespace of a line,
including the whitespace of docstring code samples."""
n = len(s) - len(s.lstrip())
if not s[n:n + 3] in ['...', '>>>']:
check = s[:n]
else:
smore = s[n + 3:]
check = s[:n] + smore[:... |
def add_box(width, height, depth):
"""
This function takes inputs and returns vertex and face arrays.
no actual mesh data creation is done here.
"""
verts = [
(+1.0, +1.0, 0.0),
(+1.0, -1.0, 0.0),
(-1.0, -1.0, 0.0),
(-1.0, +1.0, 0.0),
(+1.0, +1.0, +2.0),
... |
def seven_interp(x, a0, a1, a2, a3, a4, a5, a6):
"""``Approximation degree = 7``
"""
return (
a0
+ a1 * x
+ a2 * (x ** 2)
+ a3 * (x ** 3)
+ a4 * (x ** 4)
+ a5 * (x ** 5)
+ a6 * (x ** 6)
) |
def _convert_bool_to_str(var, name):
"""Convert input to either 'yes' or 'no' and check the output is yes or no.
Args:
var (str or bool): user input
name (str): name of the variable.
Returns:
out (str): "yes" or "no".
"""
if var is True:
out = "yes"
elif var is... |
def indict(thedict, thestring):
"""
https://stackoverflow.com/questions/55173864/how-to-find-whether-a-string-either-a-key-or-a-value-in-a-dict-or-in-a-dict-of-d
"""
if thestring in thedict:
return True
for val in thedict.values():
if isinstance(val, dict) and indict(val, thestring):... |
def two_strings_are_substrings(string1, string2):
"""
Check if either `string1` or `string2` is a substring of its partner.
Useful for checking if one Sample ID is a substring of another Sample ID or vice versa
:param string1: str
:param string2: str
:return:
"""
return (string1 in stri... |
def dp_fib_cs(n: int):
"""A dynamic programming version of Fibonacci, constant space"""
a = 1 # f(n-2)
b = 1 # f(n-1)
for i in range(2, n):
a, b = b, a + b
return b |
def _center_just(text: str, width: int):
"""Pads the provided string left and right such that it has a specified width and is centered.
Args:
text (str): The string to pad.
width (int): The desired width of the padded ``text``.
Returns:
str: The padded ``text``.
"""
len_di... |
def split_fields(fields: str = '', delimiter: str = ';') -> dict:
"""Split str fields of Demisto arguments to SNOW request fields by the char ';'.
Args:
fields: fields in a string representation.
delimiter: the delimiter to use to separate the fields.
Returns:
dic_fields object for ... |
def merge(old, new):
"""Merge dicts"""
for key, value in new.items():
if key in old and isinstance(old[key], dict):
old[key] = merge(old[key], value)
else:
old[key] = value
return old |
def selection(triple, variables):
"""Apply selection on a RDF triple"""
bindings = set()
if variables[0] is not None:
bindings.add((variables[0], triple[0]))
if variables[1] is not None:
bindings.add((variables[1], triple[1]))
if variables[2] is not None:
bindings.add((variab... |
def solve(_n, tree):
"""
Given a list of list of tokens:
. (empty), or # (tree), compute the
number of trees one would encounter
if one traverses the 2D grid along
a slope of (3, 1).
:param _n: The number of rows in the
2D grid.
:param tree: The 2D grid as a list of list.
... |
def _xmlcharref_encode(unicode_data, encoding):
"""Emulate Python 2.3's 'xmlcharrefreplace' encoding error handler."""
chars = []
# Step through the unicode_data string one character at a time in
# order to catch unencodable characters:
for char in unicode_data:
try:
chars.append(char.encode(encoding, 'strict... |
def _get_batch_size(params, hparams, config):
"""Batch size determined by params dict, HParams, and RunConfig."""
# If params specifies batch size, use that. TPUEstimator passes batch size in
# params.
batch_size = params and params.get("batch_size")
# If not set, then we're running on CPU/GPU, so use the ba... |
def enum_value(value, text=None, is_default=False):
"""Create dictionary representing a value in an enumeration of possible
values for a command parameter.
Parameters
----------
value: scalar
Enumeration value
text: string, optional
Text representation for the value in the front... |
def int_parameter(level, maxval):
"""Helper function to scale `val` between 0 and maxval .
Args:
level: Level of the operation that will be between [0, `PARAMETER_MAX`].
maxval: Maximum value that the operation can have. This will be scaled to
level/PARAMETER_MAX.
Returns:
An int that result... |
def write_txt(w_path, val):
"""Write text file from the string input.
"""
with open(w_path, "w") as output:
output.write(val + '\n')
return None |
def dpdx(a, x, y, order=4):
"""Differential with respect to x
:param a:
:param x:
:param y:
:param order:
:return:
"""
dpdx = 0.0
k = 1 # index for coefficients
for i in range(1, order + 1):
for j in range(i + 1):
if i - j > 0:
dpdx = dpdx + ... |
def reverse_complement(fragment):
"""
provides reverse complement to sequences
Input:
sequences - list with SeqRecord sequences in fasta format
Output:
complementary_sequences -
list with SeqRecord complementary sequences in fasta format
"""
# complementary_sequences = []
# for s... |
def impact_seq(impact_list):
"""String together all selected impacts in impact_list."""
impact_string = ''
connector = '-'
for impact in impact_list:
impact_string += connector + impact.text.strip()
return impact_string |
def Af_to_stick(Af):
"""
Given the final-state amplitudy Af, return a stick list
Af: a dictionary of array([energy, amplitude])
"""
return [ [Af[conf][0].real, float(abs(Af[conf][1]) ** 2)] for conf in Af] |
def get_rule_short_description(tool_name, rule_id, test_name, issue_dict):
"""
Constructs a short description for the rule
:param tool_name:
:param rule_id:
:param test_name:
:param issue_dict:
:return:
"""
if issue_dict.get("short_description"):
return issue_dict.get("short... |
def map_to_duration(arr):
"""
This is a bit crude - creates many too many subdivisions
"""
arr = [int(x * 63 + 1)/16 for x in arr]
return arr |
def escape_string(s, encoding='utf-8'):
""" escape unicode characters """
if not isinstance(s, bytes):
s = s.encode(encoding=encoding)
return s.decode('unicode-escape', errors='ignore') |
def dataset_is_mnist_family(dataset):
"""returns if dataset is of MNIST family."""
return dataset.lower() == 'mnist' or dataset.lower() == 'fashion-mnist' |
def _getMatchingLayers(layer_list, criterionFn):
"""Returns a list of all of the layers in the stack that match the given criterion function, including substacks."""
matching = []
for layer in layer_list:
if criterionFn(layer):
matching.append(layer)
if hasattr(layer, 'layerStack... |
def copy_dict_reset(source_dict):
"""Copy a dictionary and reset values to 0.
Args:
source_dict (dict): Dictionary to be copied.
Returns:
new_dict (dict): New dictionary with values set to 0.
"""
new_dict = {}
for key in source_dict.keys():
new_dict[key] = 0... |
def trimmed(value):
""" Join a multiline string into a single line
'\n\n one\ntwo\n\n three\n \n ' => 'one two three'
"""
return ' '.join((line.strip()
for line in value.splitlines()
if line.strip())) |
def has_letter(word):
""" Returns true if `word` contains at least one character in [A-Za-z]. """
for c in word:
if c.isalpha(): return True
return False |
def row_major_form_to_ragged_array(flat, indices):
"""Convert [1, 2, 3, 5, 6], [0, 3] to
[[1,2,3], [5,6]] for serialization
"""
endices = indices[1:] + [None]
return [flat[start:end] for start, end in zip(indices, endices)] |
def get_shift_value(old_centre, new_centre):
"""
Calculates how much to shift old_centre to the new_centre
:param old_centre: float
:param new_centre: float
:return:
"""
diff = old_centre - new_centre
if old_centre < new_centre: # <=
if diff > 0:
return -diff
if... |
def arnonA_long_mono_to_string(mono, latex=False, p=2):
"""
Alternate string representation of element of Arnon's A basis.
This is used by the _repr_ and _latex_ methods.
INPUT:
- ``mono`` - tuple of pairs of non-negative integers (m,k) with `m
>= k`
- ``latex`` - boolean (optional, de... |
def parse_float(val):
"""parses string as float, ignores -- as 0"""
if val == '--':
return 0
return float(val) |
def packet_read(idn, reg0, width):
""" Create an instruction packet to read data from the DXL control table.
NOTE: The namesake function in dxl_commv1 serves a specfic purpose. However, this is just a filler here.
We use this function to fit with the old code. Helps with backward compatibility.
... |
def process_legislator_data(raw_data):
"""
Clean & (partially) flatten the legislator data
Args:
raw_data (list of nested dictionaries):
Legislator data from
Returns:
dict where key is Bioguide ID and values are legislator info
"""
legislator_data = {}
for leg i... |
def Cmatrix(rater_a, rater_b, min_rating=None, max_rating=None):
"""
Returns the confusion matrix between rater's ratings
"""
assert(len(rater_a) == len(rater_b))
if min_rating is None:
min_rating = min(rater_a + rater_b)
if max_rating is None:
max_rating = max(rater_a + rater_b)... |
def is_number(v):
"""Test if a value contains something recognisable as a number.
@param v: the value (string, int, float, etc) to test
@returns: True if usable as a number
@see: L{normalise_number}
"""
try:
float(v)
return True
except:
return False |
def is_alive(thread):
"""Helper to determine if a thread is alive (handles none safely)."""
if not thread:
return False
return thread.is_alive() |
def non_increasing(arr):
"""
Returns the monotonically non-increasing array
"""
best_min = arr[0]
return_arr = []
for val in arr:
return_arr.append(min(best_min, val))
if(val<best_min):
best_min = val
return return_arr |
def string_to_int(value, dp=0):
"""Converts a homie string to a python bool"""
try:
return round(int(value), dp)
except ValueError:
return 0 |
def getvalueor(row, name, mapping={}, default=None):
"""Return the value of name from row using a mapping and a default value."""
if name in mapping:
return row.get(mapping[name], default)
else:
return row.get(name, default) |
def parse_configurable_as_list(value):
"""
For string values with commas in them, try to parse the value as a list.
"""
if ',' in value:
return [token.strip() for token in value.split(',') if token]
else:
return [value] |
def recover_path(goal: tuple, path_to: dict) -> list:
"""Recover and return the path from start to goal."""
path = [goal]
previous = path_to[goal]
while previous:
path.append(previous)
previous = path_to[previous]
path.reverse()
return path |
def _linear_interpolation(x, X, Y):
"""Given two data points [X,Y], linearly interpolate those at x."""
return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0]) |
def remove_prefix(text: str, prefix: str) -> str:
"""Removes a prefix from a string, if present at its beginning.
Args:
text: string potentially containing a prefix.
prefix: string to remove at the beginning of text.
"""
if text.startswith(prefix):
return text[len(prefix):]
... |
def extract_variable_name(attribute_name: str):
"""
Function used to transform attribute names into cheetah variables
attribute names look like standard shell arguments (--attr-a),
so they need to be converted to look more like python variables (attr_a)
Parameters
----------
attribute_name ... |
def decode_result(found):
"""
Decode the result of model_found()
:param found: The output of model_found()
:type found: bool
"""
return {True: 'Countermodel found', False: 'No countermodel found', None: 'None'}[found] |
def get_dtype(i):
"""
Identify bit depth for a matrix of maximum intensity i.
"""
depths = [8, 16]
for depth in depths:
if i <= 2 ** depth - 1:
return "uint%d" % (depth,)
return "uint" |
def poly(x, coefficients):
"""
Compute a polynome, useful for transformation laws
parameters:
x: Variable for the polynome
coefficients: list of coefficients
returns: float result of the polynome
"""
poly = 0
for i, coef in enumerate(coefficients):
poly += coe... |
def squarify(bbox, squarify_ratio, img_width):
"""
Changes is the ratio of bounding boxes to a fixed ratio
:param bbox: Bounding box
:param squarify_ratio: Ratio to be changed to
:param img_width: Image width
:return: Squarified boduning box
"""
width = abs(bbox[0] - bbox[2])
height = abs(bbox[1] - bbox[3])
w... |
def copy_project_id_into_json(context, json, project_id_key='project_id'):
"""Copy the project_id from the context into the JSON request body.
:param context:
The request context object.
:param json:
The parsed JSON request body.
:returns:
The JSON with the project-id from the h... |
def diff_dict(src, dst):
"""
find difference between src dict and dst dict
Args:
src(dict): src dict
dst(dict): dst dict
Returns:
(dict) dict contains all the difference key
"""
diff_result = {}
for k, v in src.items():
if k not in dst:
diff_res... |
def should_run_stage(stage, flow_start_stage, flow_end_stage):
"""
Returns True if stage falls between flow_start_stage and flow_end_stage
"""
if flow_start_stage <= stage <= flow_end_stage:
return True
return False |
def new(o, key, cls):
"""
Method will construct given class if key exists in a object
or return None
:param o: object from which key is extracted
:param key: name of the filed which is tested and extracted later on
:param cls: cls which is constructed
:return:
"""
if key in o:
... |
def make_safe(value, delimiter):
"""
Recursively parse transcription lists into strings for saving
Parameters
----------
value : list or None
Object to make into string
delimiter : str
Character to mark boundaries between list elements
Returns
-------
str
S... |
def win(word_list):
"""
Check the user has guessed the right word or not.
Arguments:
word_list -- the word list.
Returns:
True/False -- return True if the word has been guessed right alse return false.
"""
if '_' not in word_list:
return True
else:
return... |
def det(r1, r2, r3):
"""Calculates the determinant of a 3x3 matrix with rows as args.
Args:
r1: First row
r2: Second row
r3: Third row
Returns:
Determinant of matrix [r1,r2,r3]. Functionally equivalent to
jnp.linalg.det(jnp.array([r1,r2,r3])), but jits 10x faster for large batch.
"""
r... |
def refresh_from_weebly_json(obj, resp_json, json_mapping):
"""
refresh an object from weebly json, returns true if changed
"""
changed = False
for mapping in json_mapping:
json_attr = mapping[0]
obj_attr = mapping[1]
mapping_fn = mapping[2] if len(mapping) >= 3 else None
... |
def sort_x_by_y(x, y):
"""Sort a list of x in the order of sorting y"""
return [xx for _, xx in sorted(zip(y, x), key=lambda pair: pair[0])] |
def _power_fit(ln, lb0, gamm1):
"""A power law fit given some parameters"""
return lb0 + gamm1 * (ln - 13.6) |
def map_lp_status(lp_status):
"""Map a launchpad status to a storyboard priority.
"""
# ('todo', 'inprogress', 'invalid', 'review', 'merged')
if lp_status in ('Unknown', 'New', 'Confirmed', 'Triaged',
"Incomplete (with response)",
"Incomplete (without response... |
def is_kind_of_class(obj, a_class):
"""create instance"""
return True if (isinstance(obj, a_class)) else False |
def get_pad_shape(auto_pad, input_spatial_shape, kernel_spatial_shape, strides_spatial, output_spatial_shape):
"""
return padding shape of conv2d or pooling,
! borrow from onnx
Args:
auto_pad: string
Args:
input_spatial_shape: list[int]
Args:
kernel_spatial_shape: list[in... |
def cumsum(x):
"""The cumulative sum of an array."""
total = 0
sums = []
for el in x:
total += el
sums.append(total)
return sums |
def changeFormatiCLIP(imgFormat):
""" Changes the image format for the iCLIP plot.
Positional arguments:
imgFormat -- Image format to use.
"""
return {'toImageButtonOptions' : {'filename' : 'iCLIP', 'width' : None,
'scale' : 1.0, 'height' : None, 'format' : imgFormat} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.