content stringlengths 42 6.51k |
|---|
def inverse_dead_zone(motor_output, dead_zone):
"""This is the inverted dead zone code which is important for Talons."""
if abs(motor_output) < .00001: #floating point rounding error workaround.
return 0
elif motor_output > 0:
return (motor_output*(1-dead_zone))+dead_zone
else:
return (-motor_output*(dead_zone-1))-dead_zone |
def _flatten(coll):
""" Flatten list and convert elements to int
"""
if isinstance(coll, list):
return [int(a) for i in coll for a in _flatten(i)]
else:
return [coll] |
def _get_mapping_id_name(imgs):
"""
Args:
imgs (dict): dict of image info.
Returns:
id2name (dict): mapping image id to name.
name2id (dict): mapping image name to id.
"""
id2name = {}
name2id = {}
for image_id, image in imgs.items():
file_name = image['file_name']
id2name[image_id] = file_name
name2id[file_name] = image_id
return id2name, name2id |
def _Chunk(items, chunk_size):
"""Breaks a long list into sub-lists of a particular size."""
chunks = []
for i in range(0, len(items), chunk_size):
chunks.append(items[i:i + chunk_size])
return chunks |
def kpoints_str_pwin(lst, shift=[0,0,0]):
"""[3,3,3] -> " 3 3 3 0 0 0"
Useful for pwscf input files, card K_POINTS.
Parameters
----------
lst : sequence (3,)
shift : sequence (3,), optional
"""
return ' '.join(map(str, lst+shift)) |
def csvservercputimes(cputimes):
"""
Return a csv string of this server total and each processor's cpu times
(usr, sys, idle) in ticks.
"""
rval = ''
for i in range(len(cputimes)):
rval += ", ".join(str(x) for x in cputimes[i])
return rval |
def left(direction):
"""rotates the direction counter-clockwise"""
return (direction + 3) % 4 |
def append_concat_predictions(y_batch, predictions):
"""
Args:
y_batch (torch.Tensor or list):
predictions (list): accumulation list where all the batched predictions are added
Returns:
list: predictions list with the new tensor appended
"""
if isinstance(y_batch, list):
predictions += y_batch
else:
predictions.append(y_batch)
return predictions |
def game_core_binary(number):
""" Use binary search as find algorithm """
count = 0
lower_bound = 0
upper_bound = 100
while True:
count += 1
guess = lower_bound + (upper_bound - lower_bound) // 2
if guess == number:
return count
if guess > number:
upper_bound = guess
elif guess == lower_bound:
lower_bound += 1
else:
lower_bound = guess |
def assign_labels_colors(labels, colors):
"""
Takes a list of labels and colors and assigns a unique label to each color. Returns a color_list of length(labels).
The colors will loop around if the number of unique labels are more than the number of unique colors
:param labels:
:param colors:
:return: color_list
"""
col_idx = 0
label2col = {}
col_list = []
for i in range(len(labels)):
if labels[i] in label2col:
col_list.append(label2col[labels[i]])
else:
col = colors[col_idx % len(colors)]
col_idx += 1
label2col[labels[i]] = col
col_list.append(col)
return col_list |
def identifier_to_label(identifier):
"""Tries to convert an identifier to a more human readable text label.
Replaces underscores by spaces and may do other tweaks.
"""
txt = identifier.replace("_", " ")
txt = txt.replace(" id", "ID")
txt = dict(url="URL").get(txt, txt)
txt = txt[0].upper() + txt[1:]
return txt |
def ex3_pickle_name(n, jump_rate):
"""build name for pickle file
Parameters
------
n: float
`n` population
Returns
------
f_name : str
return `f_name` file name to save pickle as
"""
f_name = f"rjmcmc_ukf_gcs_agents_{n}_jump_rate{jump_rate}.pkl"
return f_name |
def relation_to_string(relation_tuple):
"""Convert an apt relation to a string representation.
@param relation_tuple: A tuple, (name, version, relation). version
and relation can be the empty string, if the relation is on a
name only.
Returns something like "name > 1.0"
"""
name, version, relation_type = relation_tuple
relation_string = name
if relation_type:
relation_string += " %s %s" % (relation_type, version)
return relation_string |
def same_type(values, types):
"""Check if values are belongs to same type or type tuple.
:param collections.Iterable values: values to check type similarity
:param tuple|type types: type or tuple of types
"""
return all(map(lambda it: isinstance(it, types), values)) |
def parse_console(vm_console, key_types=('ssh-ed25519', 'ecdsa-sha2-nistp256')):
"""Parse SSH keys from AWS vm console.
"""
begin = "-----BEGIN SSH HOST KEY KEYS-----"
end = "-----END SSH HOST KEY KEYS-----"
keys = []
if not vm_console:
return None
# find SSH signatures
p1 = vm_console.find(begin)
if p1 < 0:
return None
p2 = vm_console.find(end, p1)
if p2 < 0:
return None
# parse lines
klines = vm_console[p1 + len(begin):p2]
for kln in klines.split('\n'):
pos = kln.find('ecdsa-')
if pos < 0:
pos = kln.find('ssh-')
if pos < 0:
continue
kln = kln[pos:].strip()
ktype, kcert, kname = kln.split(' ')
if ktype not in key_types:
continue
keys.append((ktype, kcert))
if not keys:
raise IOError("Failed to get SSH keys")
return keys |
def split_args_for_flags(args):
"""Returns `split_args, other_args` for `args`.
Split occurs using the last occurrence of `--` in `args`.
If `arg` does not contain `--` returns `args, []`.
"""
for i in range(len(args) - 1, -1, -1):
if args[i] == "--":
return args[i + 1 :], args[:i]
return args, [] |
def test_conflict_post(N):
"""A 1-SAT problem that requires N variables to all be true, and the first one to also be false"""
return [[-1]] + [[i+1] for i in range(N)] |
def add_snmp(data, interfaces):
"""
Format data for adding SNMP to an engine.
:param list data: list of interfaces as provided by kw
:param list interfaces: interfaces to enable SNMP by id
"""
snmp_interface = []
if interfaces: # Not providing interfaces will enable SNMP on all NDIs
interfaces = map(str, interfaces)
for interface in data:
interface_id = str(interface.get("interface_id"))
for if_def in interface.get("interfaces", []):
_interface_id = None
if "vlan_id" in if_def:
_interface_id = "{}.{}".format(interface_id, if_def["vlan_id"])
else:
_interface_id = interface_id
if _interface_id in interfaces and "type" not in interface:
for node in if_def.get("nodes", []):
snmp_interface.append(
{"address": node.get("address"), "nicid": _interface_id}
)
return snmp_interface |
def part1_and_2(lines, draw_diagonal=False):
"""
Part1: Consider only horizontal and vertical lines.
Part2: Consider horizontal, vertical, *and* diagonal lines.
All diagonal lines will be exactly 45 degrees
At how many points do at least two lines overlap?
"""
# create the empty graph
graph = dict()
for y in range(0,1000):
graph[y] = [0 for x in range(1000)]
# draw lines:
for line in lines:
x1, y1, x2, y2 = line[0], line[1], line[2], line[3]
# vertical line:
if x1 == x2:
for i in range(min(y1, y2), max(y1, y2)+1):
graph[i][x1] += 1
# horizontal line:
elif y1 == y2:
for i in range(min(x1, x2), max(x1, x2)+1):
graph[y1][i] += 1
# everything else must be a diagonal line:
elif draw_diagonal:
if x1 > x2:
# ensure x increases from x1 to x2
x1, y1, x2, y2 = line[2], line[3], line[0], line[1]
while x1 <= x2:
graph[y1][x1] += 1
x1 += 1
if y1 < y2: # downhill slope
y1 += 1
else: # uphill slope
y1 -= 1
# count the number of crossing lines
crossing_lines = 0
for y in graph:
for spot in graph[y]:
if spot > 1:
crossing_lines += 1
return crossing_lines |
def merge_two_dicts(dict1, dict2):
"""
Merge two dicts into one and return.
result = {**dict1, **dict2} only works in py3.5+.
"""
result = dict1.copy()
result.update(dict2)
return result |
def parse_context_name(context_obj):
"""Parses context name from Dialogflow's contextsession prefixed context path"""
return context_obj["name"].split("/contexts/")[1] |
def _NormalizeGitPath(path):
"""Given a |path| in a GIT repository (relative to its root), normalizes it so
it will match only that exact path in a sparse checkout.
"""
path = path.strip()
if not path.startswith('/'):
path = '/' + path
if not path.endswith('/'):
path += '/'
return path |
def strip_each_line(s):
"""Strips each line of a string
Args:
s (str): The string to strip each line of
Returns:
str: The modified string
"""
return "\n".join([line.strip() for line in s]) |
def adjacent(one, two, items):
"""
>>> adjacent(1, 2, [1, 2, 3, 4])
True
>>> adjacent(2, 1, [1, 2, 3, 4])
True
>>> adjacent(1, 3, [1, 2, 3, 4])
False
>>> adjacent(4, 2, [1, 2, 3, 4])
False
>>> adjacent(1, 4, [1, 2, 3, 4])
True
>>> adjacent(4, 1, [1, 2, 3, 4])
True
"""
one_index = items.index(one)
two_index = items.index(two)
end_index = len(items) - 1
if one_index == two_index - 1:
return True
if one_index == two_index + 1:
return True
if one_index == 0 and two_index == end_index:
return True
if one_index == end_index and two_index == 0:
return True
return False |
def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace() |
def mod_family_accession(family_accession):
"""Reduces family accession to everything prior to '.'."""
return family_accession[:family_accession.index('.')] |
def contained_folder(params, folder, component):
"""Return the folder of component within parent folder 'folder' - or None if not present."""
if component == '.':
return folder
if component == '..':
if folder.parent_uid is None:
return params.root_folder
return params.folder_cache[folder.parent_uid]
if component in params.folder_cache:
return params.folder_cache[component]
for subfolder_uid in folder.subfolders:
subfolder = params.folder_cache[subfolder_uid]
if subfolder.name == component:
return subfolder
return None |
def convert_to_ascii(text):
"""Converts text to ascii
"""
text_encoded = text.encode("ascii", "ignore")
return text_encoded.decode() |
def env_to_dictionary(env_list):
"""
Parse the environment variables into a dictionary for easy access.
:param env_list: list of strings in the form "var=value"
:return: a dictionary {"var": "value"}
"""
env_dict = {}
for pair in env_list:
(var, value) = pair.split("=", 1)
env_dict[var] = value
return env_dict |
def find_overlap(true_range, pred_range):
"""Find the overlap between two ranges
Find the overlap between two ranges. Return the overlapping values if
present, else return an empty set().
Examples:
>>> find_overlap((1, 2), (2, 3))
2
>>> find_overlap((1, 2), (3, 4))
set()
"""
true_set = set(true_range)
pred_set = set(pred_range)
overlaps = true_set.intersection(pred_set)
return overlaps |
def _flatten_dotted(input_dict, prefix=''):
"""Convert nested dict into flat dict with dotted key notation.
Given a nested dict, e.g.
>>> input_dict = {'spam': {'eggs': 23}, 'answer': 42}
create a flat dict with dotted keys for the nested items
>>> output_dict = _flatten_dotted(input_dict)
>>> output_dict == {'spam.eggs': 23, 'answer': 42}
True
Args:
dict: Nested dict
string: Key prefix, used for recursion. Should be left at the default
for normal use.
Returns:
dict: Flattened dict with dotted notation.
"""
output_dict = {}
for key, value in input_dict.items():
if prefix:
dotted = prefix + '.' + key
else:
dotted = key
if isinstance(value, dict):
output_dict.update(_flatten_dotted(value, dotted))
else:
output_dict[dotted] = value
return output_dict |
def flatten(l):
"""
Flatten a list of lists by one level.
Args:
l (list of lists): List of lists
Returns:
flattened_list (list): Flattened list
"""
flattened_list = [item for sublist in l for item in sublist]
return flattened_list |
def format_non_date(value):
"""Return non-date value as string."""
return_value = None
if value:
return_value = value
return return_value |
def _GenericRetrieve(root, default, path):
"""Given a list of dictionary keys |path| and a tree of dicts |root|, find
value at path, or return |default| if any of the path doesn't exist."""
if not root:
return default
if not path:
return root
return _GenericRetrieve(root.get(path[0]), default, path[1:]) |
def matrix_op(lsts, func):
"""
IMPORTANT: You should ONLY use one-line list comprehension.
Make a function that applies given function to the given nested-list.
>>> lsts = [[1,2], [3,4]]
>>> matrix_op(lsts, square)
[[1, 4], [9, 16]]
>>> lsts = [[10, 20], [30, 40]]
>>> matrix_op(lsts, lambda x: x / 10)
[[1.0, 2.0], [3.0, 4.0]]
>>> lsts = [[5,15], [25,35]]
>>> matrix_op(lsts, identity)
[[5, 15], [25, 35]]
"""
return [[func(i) for i in lst] for lst in lsts] |
def modular_sqrt(a, p):
""" Find a quadratic residue (mod p) of 'a'. p must be an odd prime.
Solve the congruence of the form:
x^2 = a (mod p)
And returns x. Note that p - x is also a root.
0 is returned is no square root exists for these a and p.
"""
def legendre_symbol(a):
""" Compute the Legendre symbol a|p using Euler's criterion. p is a prime, a is
relatively prime to p (if p divides a, then a|p = 0)
Returns 1 if a has a square root modulo p, -1 otherwise.
"""
ls = pow(a, (p - 1) // 2, p)
return -1 if ls == p - 1 else ls
# Simple cases
if a == 0 or p == 2 or legendre_symbol(a) != 1:
return 0
elif p % 4 == 3:
return pow(a, (p + 1) // 4, p)
# Partition p-1 to s * 2^e for an odd s (i.e.
# reduce all the powers of 2 from p-1)
#
s, e = p - 1, 0
while s % 2 == 0:
s //= 2
e += 1
# Find some 'n' with a legendre symbol n|p = -1.
# Shouldn't take long.
n = 2
while legendre_symbol(n) != -1:
n += 1
# x is a guess of the square root that gets better with each iteration.
# b is the "fudge factor" - by how much we're off with the guess.
# The invariant x^2 = ab (mod p) is maintained throughout the loop.
# g is used for successive powers of n to update both a and b
# r is the exponent - decreases with each update
x, r = pow(a, (s + 1) // 2, p), e
b, g = pow(a, s, p), pow(n, s, p)
while True:
t, m = b, 0
for m in range(r):
if t == 1: break
t = pow(t, 2, p)
if m == 0:
return x
gs = pow(g, 2 ** (r - m - 1), p)
g = (gs * gs) % p
x = (x * gs) % p
b = (b * g) % p
r = m |
def timer(start, end):
"""
Convert the measured time into hours, mins, seconds and print it out.
:param start: start time (from import time, use start = time.time())
:param end: end time (from import time, use end = time.time()
:return: the time spent in hours, mins, seconds
"""
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
return int(hours), int(minutes), seconds |
def norn(x):
""" return the next or None of an iterator """
try:
return next(x)
except StopIteration:
return None |
def rename_keys(d, keys):
"""Rename keys from `d` that are present as a key in `keys` by the
corresponding value in `keys`.
Arguments:
d {dict} -- [a dict whose certain keys need to be updated]
keys {dict} -- [a dict that map old key to new key]
Returns:
[dict] -- [an updated dict]
"""
return dict([(keys.get(k, k), v) for k, v in d.items()]) |
def count_frequency(word_list):
"""
Return a list giving pairs of form: (word,frequency)
"""
L = []
for new_word in word_list:
for entry in L:
if new_word == entry[0]:
entry[1] = entry[1] + 1
break
else:
L.append([new_word,1])
return L |
def slugify(name) -> str:
"""Return a slugified version of the name."""
return f'#{name.lower().replace(" ", "-").replace("(", "").replace(")", "")}' |
def safe_crc(string):
"""64 bit safe crc computation.
See http://docs.python.org/library/zlib.html#zlib.crc32:
To generate the same numeric value across all Python versions
and platforms use crc32(data) & 0xffffffff.
"""
from zlib import crc32
return crc32(string) & 0xffffffff |
def get_slice(string_to_slice, slice_index_list):
"""String slice of a string and slice pair."""
# We're slicing a string,
# so the list should only have the start and stop of the slice.
assert len(slice_index_list) == 2
i1 = slice_index_list[0]
i2 = slice_index_list[1]
return str(string_to_slice)[i1:i2] |
def hard_combine_max(a, b):
"""Takes in 2 lists of integers and returns a new list where each value represents the maxmimum of the input lists at that index. If the lists are not the same length, then the extra values in the longer list should be assumed to be valid maximum values and therefore included in the result."""
# too tricky?
z = [max(x, y) for x, y in zip(a, b)]
if len(a) > len(b):
z += a[len(b):]
elif len(b) > len(a):
z += b[len(a):]
return z |
def get_pagination(current_page_number, total_number_pages):
"""
Generate a pagination dictionary given a page number
:param current_page_number: current page to paginate
:param total_number_pages: total number of pages in the current model
:return: dictionary of pagination
"""
previous_page = current_page_number - 1
next_page = current_page_number + 1
displayed_previous_page = None
displayed_next_page = None
if previous_page > 0:
displayed_previous_page = previous_page
if next_page < total_number_pages:
displayed_next_page = next_page
return {
"first-page": 0,
"previous-page": displayed_previous_page,
"current-page": current_page_number,
"next-page": displayed_next_page,
"last-page": total_number_pages
} |
def MultiplyTwoNumbers(a,b):
"""
multiplying two numbers
input: a,b - two numbers
output: returns multiplication
"""
c = a*b
return c |
def check_version(a: str, b: str) -> bool:
"""
Returns True if a > b, False otherwise
"""
a = a.replace('.', '').replace('-', '')
b = b.replace('.', '').replace('-', '')
return a > b |
def get_basedir(cfg, stream):
""" Return base directory base don stream
"""
if stream in ['cems_fire', 'agera5', 'wfde5']:
return cfg['derivdir']
else:
return cfg['datadir'] |
def argsort(seq):
""" Stable version of argsort """
# http://stackoverflow.com/questions/3382352/equivalent-of-numpy-argsort-in-basic-python/3382369#3382369
return sorted(range(len(seq)), key=seq.__getitem__) |
def is_schema_field(field):
""" Returns whether or not we should expect a schema to be found for the given field.
Currently this only applies to validation_errors and aggregated_items.
:param field: field name to check
:return: False if this field doesn't a schema, True otherwise
"""
# XXX: Consider doing this with regex? - Will 6/11/2020
if field.startswith('validation_errors') or field.startswith('aggregated_items'): # note that trailing '.' is gone
return False
return True |
def skip(app, what, name, obj, would_skip, options):
"""
Define which methods should be skipped in the documentation
"""
if obj.__doc__ is None:
return True
return would_skip |
def impuesto_iva14(monto=0):
""" Calcula el impuesto del IVA de 14 % """
total = ((monto * 14)/100)
return total |
def compact_timeslot(sind_list):
"""
Test method. Compact all snapshots into a single one.
:param sind_list:
:return:
"""
tls = sorted(sind_list)
conversion = {val: idx for idx, val in enumerate(tls)}
return conversion |
def json_to_tone(json_object):
"""
Receives json and returns the tone of the sentence.
"""
tone = json_object['document_tone']['tones'][0]
return tone['tone_id'] |
def IR(spot:list, m=1):
"""
IR(): A function to calculate Single Effective Interest Rate from an array of spot rates.
:param spot: An array/List of Spot rates
:type spot: list
:param m: Frequency of Interest Calculation (eg: 2 for Semi-annually), defaults to 1.
:type m: float
:return: float, None for -ve values of m.
:rtype: float
"""
if(m<=0 or len(spot)==0):
return None
return spot[-1] |
def checkSequenceConstraint(SC):
"""
Checks the Sequence constraint for illegal nucleotide characters
"""
out = ""
for c in SC:
c = c.upper()
if c not in "ACGURYSWKMBDHVN":
# and c!= "R" and c != "Y" and c != "S" and c != "W" and c != "K" and c != "M" and c != "B" and c != "D" and c != "H" and c != "V":
if c == "T":
c = "U"
else:
print("\tIllegal Character in the constraint sequence!")
print(
"\tPlease use the IUPAC nomenclature for defining nucleotides in the constraint sequence!"
)
print("\tA Adenine")
print("\tC Cytosine")
print("\tG Guanine")
print("\tT/U Thymine/Uracil")
print("\tR A or G")
print("\tY C or T/U")
print("\tS G or C")
print("\tW A or T/U")
print("\tK G or T/U")
print("\tM A or C")
print("\tB C or G or T/U")
print("\tD A or G or T/U")
print("\tH A or C or T/U")
print("\tV A or C or G")
print("\tN any base")
exit(0)
out += c
return (1, out) |
def rsplit(s, sep=None, maxsplit=-1):
"""Equivalent to str.split, except splitting from the right."""
return s.rsplit(sep, maxsplit) |
def _prepare_toc(toc):
"""Prepare the TOC for processing."""
# Drop toc items w/o links
toc = [ii for ii in toc if ii.get('url', None) is not None]
# Un-nest the TOC so it's a flat list
new_toc = []
for ii in toc:
sections = ii.pop('sections', None)
new_toc.append(ii)
if sections is None:
continue
for jj in sections:
subsections = jj.pop('subsections', None)
new_toc.append(jj)
if subsections is None:
continue
for kk in subsections:
new_toc.append(kk)
return new_toc |
def get_nodes(dict_or_list):
""" """
if isinstance(dict_or_list, dict) == True:
return [dict_or_list]
else:
return dict_or_list |
def norm_chr(chrom_str, gens_chrom):
"""
Returns the chromosome string that matches the chromosome annotation of the input gens file
"""
chrom_str = str(chrom_str)
if not gens_chrom:
return chrom_str.replace("chr", "")
elif gens_chrom and not chrom_str.startswith("chr"):
return "chr" + chrom_str
else:
return chrom_str |
def camel_case(name):
"""
converts this_is_new to ThisIsNew
and this in This
"""
return "".join([x.capitalize() for x in name.split("_")]) |
def fpath_suffix(src_fpath: str, suffix: str, dst_extension: None) -> str:
"""Add a suffix (before extension) to a remote or local file path.
Also optionally change extension of new file path.
"""
src_extension = src_fpath.split(".")[-1]
dst_fpath = src_fpath.replace(f".{src_extension}", f"_{suffix}.{src_extension}")
if dst_extension:
if src_extension != dst_extension:
dst_fpath = dst_fpath.replace(src_extension, dst_extension)
return dst_fpath |
def flatten_list(list):
"""
| Flattens a list of lists.
| Based on:
| http://stackoverflow.com/questions/457215/comprehension-for-flattening-a-sequence-of-sequences/5330178#5330178
"""
#print 'List: {0}'.format(list)
result = []
extend = result.extend
for l in list:
extend(l)
return result |
def get_message_from_multiformat_message(data, rule):
"""Get a message from multimessage struct"""
if rule is not None and "id" in data:
text = rule["messageStrings"][data["id"]].get("text")
arguments = data.get("arguments", [])
# argument substitution
for i in range(6): # the specification limit to 6
substitution_str = "{" + str(i) + "}"
if substitution_str in text:
text = text.replace(substitution_str, arguments[i])
else:
return text
return data.get("text") |
def transformToRGB(lst):
"""
Change representation from 0-255 to 0-1, for triples value corresponding to RGB.
"""
def normToOne(x): return float(x)/255.
return [(normToOne(x), normToOne(y), normToOne(z)) for x, y, z in lst] |
def value_label(label):
"""Label of a numeric index.
Special value representing a label of a numeric index. Can be used to query
data cubes by character labels rather than numerical indices, which are the
actual pixel values.
Parameters
----------
label : :obj:`str`
The label.
Returns
-------
:obj:`dict`
JSON-serializable object that contains the value label, and can be
understood by the query processor as such.
"""
obj = {"type": "value_label", "label": label}
return obj |
def is_possible_temp(temp: str) -> bool:
"""Returns True if all characters are digits or 'M' (for minus)"""
for char in temp:
if not (char.isdigit() or char == "M"):
return False
return True |
def matrix_multiplication(attrs, inputs, proto_obj):
"""Performs general matrix multiplication"""
return 'linalg_gemm2', attrs, inputs |
def get_expr_for_end_pos_from_info_field(field_prefix="va.", end_field="info.END"):
"""Retrieve the "END" position from the INFO field. This is typically found in VCFs produced by
SV callers."""
return "%(field_prefix)s%(end_field)s" % locals() |
def remove_chars(string, chars):
"""
Return string without given characters
"""
return "".join([c for c in string if c not in set(chars)]) |
def propToCol(propList):
"""Helper function which translates recorder properties to column
names for MySQL. This should replicate how GridLAB-D does this
translation
"""
# replace periods with underscores
cols = [s.replace('.', '_') for s in propList]
return cols |
def istrue(value):
"""
Accepts a string as input.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns
``True``.
If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns
``False``.
``istrue`` is not case sensitive.
Any other input will raise a ``KeyError``.
"""
return {
'yes': True, 'no': False,
'on': True, 'off': False,
'1': True, '0': False,
'true': True, 'false': False,
}[value.lower()] |
def exchange(configuration_filename, time, input_names,
input_values, output_names, save_to_file=False,
memory=None):
"""
"""
memory = None
# Process inputs
inputs = {}
for name, value in zip(input_names, input_values):
inputs[name] = value
# Multiply value by 2
value = float(inputs['x']) + float(inputs['u'])
return [value, memory] |
def TransformDash(n):
"""Transform dashes often found in 3DNA tables to floats"""
if n == '---' or n == '----':
return float(0)
else:
return float(n) |
def is_validhand(cards):
""" Returns True if the cardlist is 5 unique cards. """
return len(set(cards)) == 5 |
def parse_archive_filename(filename):
"""
Read the filename of the requested archive and return
both the chart name and the release version.
"""
chunks = filename[:-4].split('-')
chart_name = '-'.join(chunks[:-1])
version = chunks[-1]
return chart_name, version |
def is_config_parameter(line: str) -> bool:
"""Does the line refer to a configuration parameter"""
return line.startswith("@ConfigurationParameter") and not line.endswith("Changer") |
def binomialCoef(n, k):
"""
Return the binomial coefficient nCk i.e., coefficient of x^k in (1+x)^n
Parameters
----------
n : int
denotes n in nCk
k : int
denotes k in nCk
return : int
return an integer
"""
if(n<k):
raise TypeError(
"Value of first argument cannot be smaller than second"
)
Coef = [[0 for x in range(k+1)] for x in range(n+1)]
for i in range(n+1):
for j in range(min(i, k)+1):
if j == 0 or j == i:
Coef[i][j] = 1
else:
Coef[i][j] = Coef[i-1][j-1] + Coef[i-1][j]
return Coef[n][k] |
def groupby(target, group_key):
"""Groups a list of dictionaries by group_key.
"""
result = {}
for value in target:
key_value = value[group_key]
if not key_value in result:
result[key_value] = []
result[key_value].append(value)
return result |
def _exponential_decay(x: float, t: int, max_t: int, factor: float = 2.0) -> float:
"""
Exponential decay function. Can be used for both the learning_rate or the neighborhood_radius.
:param x: float: Initial x parameter
:param t: int: Current iteration
:param max_t: int: Maximum number of iterations
:param factor: float: Exponential decay factor. Defaults to 2.0.
:return: float: Current state of x after t iterations
"""
return x * (1 - (factor / max_t)) ** t |
def check_for_ticket_name_error(ticket_name):
"""
Returns any error message if the ticket name is not alphanumeric, if there is an
invalid space in the name or the name is too long for a ticket name. If
there is no errors it returns false.
:param ticket_name: a string for the ticket's name
:return: false if no error, else returns the error as a string message
"""
if not ticket_name.replace(' ', '').isalnum():
return "The name of the ticket has to be alphanumeric only"
if (ticket_name[0] == ' ') or (ticket_name[-1] == ' '):
return "The name of the ticket is only allowed spaces if it is not the first or last character"
if len(ticket_name) > 60:
return "The name of the ticket should be no longer than 60 characters"
return False |
def get_task_scouts(jobs):
"""
Get PanDAIDs of selected scouting metrics for a task
:param jobs: list of dicts
:return: dict:
"""
scouts_dict = {}
scout_types = ['cpuTime', 'walltime', 'ramCount', 'ioIntensity', 'outDiskCount']
for jst in scout_types:
scouts_dict[jst] = []
for job in jobs:
for jst in scout_types:
if 'jobmetrics' in job and 'scout=' in job['jobmetrics'] and jst in job['jobmetrics'][job['jobmetrics'].index('scout='):]:
scouts_dict[jst].append(job['pandaid'])
# remove scout type if no scouts
st_to_remove = []
for jst, jstd in scouts_dict.items():
if len(jstd) == 0:
st_to_remove.append(jst)
for st in st_to_remove:
if st in scouts_dict:
del scouts_dict[st]
return scouts_dict |
def clean(filenames_list):
""" removes hidden files (starting with .) from a list of filenames """
result = []
for l in filenames_list:
if l[0] != '.':
result.append(l)
return result |
def check_even_list(num_list):
"""
return all the even numbers in a list
"""
even_numbers = []
for number in num_list:
if number % 2 == 0:
even_numbers.append(number)
else:
pass
return even_numbers |
def XSSEncode(maliciouscode):
"""custom xss containg input escaper"""
html_code = (
('"', '"'), ('%22', '"'),
("'", '''), ('%27', '''),
('/', '/'), ('%2f', '/'), ('%2F', '/'),
('<', '<'), ('%3C', '<'), ('%3c', '<'),
('>', '>'), ('%3E', '>'), ('%3e', '>'),
(';', '&end;'), ('%3B', '&end;'), ('%3b', '&end;'),
('&', '&'), ('%26', '&'),
)
for code in html_code:
maliciouscode = maliciouscode.replace(code[0], code[1])
import re
maliciouscode = re.sub(' +', ' ', maliciouscode)
return maliciouscode |
def _build_alerts(data):
"""
Helper function that extracts all the alerts from data and returns them as a list
"""
alerts = []
for item in data:
events = item['return']
if not isinstance(events, list):
events = [events]
alerts.extend(events)
return alerts |
def squared_error(x0, rho, x_obs):
"""
Proximal operator for the pairwise difference between two matrices (Frobenius norm)
Parameters
----------
x0 : array_like
The starting or initial point used in the proximal update step
rho : float
Momentum parameter for the proximal step (larger value -> stays closer to x0)
x_obs : array_like
The true matrix that we want to approximate. The error between the parameters and this matrix is minimized.
Returns
-------
x0 : array_like
The parameter vector found after running the proximal update step
"""
return (x0 + x_obs / rho) / (1 + 1 / rho) |
def is_leap_year(year):
"""Determine whether the specified year is a leap year"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return 1
else:
return 0
else:
return 1
else:
return 0 |
def split_group(source, pos, maxline):
""" Split a group into two subgroups. The
first will be appended to the current
line, the second will start the new line.
Note that the first group must always
contain at least one item.
The original group may be destroyed.
"""
first = []
source.reverse()
while source:
tok = source.pop()
first.append(tok)
pos += len(tok)
if source:
tok = source[-1]
allowed = (maxline + 1) if tok.endswith(' ') else (maxline - 4)
if pos + len(tok) > allowed:
break
source.reverse()
return first, source |
def isWithin(rect1, rect2):
"""Checks whether rectangle 1 is within rectangle 2
Parameters:
rect1: list of coordinates [minx, maxy, maxx, miny]
rect2: list of coordinates [minx, maxy, maxx, miny]
Returns:
True if rect1 within rect2 else False
"""
minx1, maxy1,maxx1, miny1 = rect1
minx2, maxy2,maxx2, miny2 = rect2
if minx1 < minx2 or maxx1 > maxx2 or miny1 < miny2 or maxy1 > maxy2:
return False
return True |
def cmdline_from_pid(pid):
""" Fetch command line from a process id. """
try:
cmdline= open("/proc/%i/cmdline" %pid).readlines()[0]
return " ".join(cmdline.split("\x00")).rstrip()
except:
return "" |
def sigma_weighted(w,g,delta):
"""Computes standard deviation of the weighted normalization."""
g2 = g.real**2
c2= g2 + g.imag**2
d2 = delta**2
return (0.5 * (w**2 * (c2 + 1 + d2) - 4 * w * g.real + 2*g2 - c2 + 1 - d2))**0.5 |
def generate_layer_name(layer_type, index):
"""
Generates a unique layer name
"""
# Generating a unique name for the layer
return f"{layer_type.lower()}_layer_{index+1}" |
def ms_to_kt(val):
"""
Converts m/s to knots; accepts numeric or string
"""
try:
return float(val) * 1.94384
except (TypeError, ValueError):
return val * 1.94384 |
def colorHash(text):
"""
Stolen from https://github.com/zenozeng/color-hash
"""
SaturationArray = [0.66, 0.83, .95]
LightnessArray = [0.5, 0.66, 0.75]
h = hash(text)
Hue = h % 359 # (Note that 359 is a prime)
Saturation = SaturationArray[h // 360 % len(SaturationArray)]
Lightness = LightnessArray[h // 360 // len(SaturationArray) % len(LightnessArray)]
return Hue, Saturation, Lightness |
def summ_r(listy):
"""
Input: A list of numbers.
Output: The sum of all the numbers in the list, recursive.
"""
if listy == []:
return 0
else:
return (listy[0] + summ_r(listy[1:])) |
def _le_from_gt(self, other):
"""Return a <= b. Computed by @total_ordering from (not a > b)."""
op_result = self.__gt__(other)
if op_result is NotImplemented:
return NotImplemented
return not op_result |
def solve(n, ar):
"""
Given an integer array ar of size n, return the decimal fraction of the
number of positive numbers, negative numbers and zeroes. Test cases are
scaled to 6 decimal places.
"""
num_pos = 0
num_neg = 0
num_zero = 0
for i in ar:
if i > 0:
num_pos += 1
elif i < 0:
num_neg += 1
else:
num_zero += 1
# Return the ratios but cast to float to ensure preservation of precision.
return (float(num_pos) / float(n),
float(num_neg) / float(n),
float(num_zero) / float(n)) |
def remove_verbatim_cr_lf_tab_chars(s):
"""
Return a string replacinf by a space any verbatim but escaped line endings and
tabs (such as a literal \n or \r \t).
"""
if not s:
return s
return s.replace('\\r', ' ').replace('\\n', ' ').replace('\\t', ' ') |
def color_code(color_number):
"""Generate an ANSI escape sequence with the given color number or description string."""
return '\033[' + str(color_number) + 'm' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.