content stringlengths 42 6.51k |
|---|
def _compute_scores(distances, i, n, f):
"""Compute scores for node i.
Arguments:
distances {dict} -- A dict of dict of distance. distances[i][j] = dist. i, j starts with 0.
i {int} -- index of worker, starting from 0.
n {int} -- total number of workers
f {int} -- Total number o... |
def int_half(angle: float) -> int:
"""Assume angle is approximately an even integer, and return the half
:param angle: Float angle
:type angle: float
:return: Integer half of angle
:rtype: int
"""
#
two_x = round(angle)
assert not two_x % 2
return two_x // 2 |
def parse_entry(entry):
"""
Separates an entry into a numeric value and a tied/fixed flag,
if present.
Parameters
----------
entry : str
An f26 parameter entry.
Returns
-------
value : float
The entry value.
flag : str
The fitting flag associated with t... |
def __getILPResults(anchor2bin2var):
"""
interpret the ILP solving results. Map anchor to locations
"""
# get the mapping from anchor to bin
anchor_to_selected_bin = {}
for anchor, bin2var in anchor2bin2var.items():
for bin, var in bin2var.items():
var_value = round(var.x)
assert abs(var.x ... |
def parse_tags_to_string(tags):
"""Create string representation of a dictionary of tags.
:param tags: dictionary containing "tag" meta data of a variant.
:returns: the string representation of the tags.
"""
str_tags = []
for key, value in sorted(tags.items()):
# If key is of type 'Flag... |
def convertToCamelCase(input):
"""
Converts a string into camel case
:param input: string to be converted
:return: camelCase version of string
"""
# split input
splitWords = input.split(' ')
# check if only one word, and if so, just return the input as is
if len(splitWords) == 1:
... |
def _justify(texts, max_len, mode='right'):
"""
Perform ljust, center, rjust against string or list-like
"""
if mode == 'left':
return [x.ljust(max_len) for x in texts]
elif mode == 'center':
return [x.center(max_len) for x in texts]
else:
return [x.rjust(max_len) for x i... |
def get_dot_product(first_vector, second_vector):
""" (dict, dict) -> dict
The function takes two dictionaries representing vectors as input.
It returns the dot product between the two vectors.
>>> v1 = {'a' : 3, 'b': 2}
>>> v2 = {'a': 2, 'c': 1, 'b': 2}
>>> get_dot_product(v1, v2)
... |
def hcp_coord_test(x, y, z):
"""Test for coordinate in HCP grid"""
m = x+y+z
return m % 6 == 0 and (x-m//12) % 3 == 0 and (y-m//12) % 3 == 0 |
def level_to_xp(level: int):
"""
:type level: int
:param level: Level
:return: XP
"""
if level == 0:
return 0
xp = (5 * (level ** 2)) + (60 * level) + 100
return xp |
def add_index_to_pairs(ordered_pairs):
"""
Creates a dictionary where each KEY is a integer index and
the VALUE is a dictionary of the x,y pairs
Parameters
----------
ordered_pairs: dict
dictionary that has been ordered
Returns
-------
dict
this dictionary has
... |
def deenrich_list_with_image_json(enriched_image_list):
"""
De-enrich the image list
:param enriched_image_list: List of enriched images
:return: De-enriched image list
"""
# For each image delete image json
for image in enriched_image_list:
if "image_json" in image:
del... |
def sgn(value):
"""
Signum function
"""
if value < 0:
return -1
if value > 0:
return 1
return 0 |
def find_mmsi_in_message_type_5(transbordement_couple, messages_type5):
"""Add the ship types to a possible transhipment by using AIS message of
type 5
"""
for x in messages_type5: # message_types5 is a list of messages
if x['mmsi'] == transbordement_couple[0][0]:
transbordement_couple[0][0].append(x['shiptyp... |
def humanbytes(size):
"""Convert Bytes To Bytes So That Human Can Read It"""
if not size:
return ""
power = 2 ** 10
raised_to_pow = 0
dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"}
while size > power:
size /= power
raised_to_pow += 1
return str(round(size,... |
def plain_to_ssml(text):
"""
Incomplete. Returns inputted text.
"""
ssml_text = text
return ssml_text |
def retrieve_usernames(list_of_ids, dict_of_ids_to_names):
"""
For retrieving usernames when we've already gotten them from twitter.
For saving on API requests
"""
usernames = []
for user_id in list_of_ids:
usernames.append(dict_of_ids_to_names[user_id])
return usernames |
def clear_mod_zeroes(modsdict):
"""Clear zeroes from dictionary of attributes and modifiers."""
for item in modsdict.keys():
if modsdict[item] == "0":
modsdict[item] = ""
return modsdict |
def ArgumentStringToInt(arg_string):
""" convert '1234' or '0x123' to int
params:
arg_string: str - typically string passed from commandline. ex '1234' or '0xA12CD'
returns:
int - integer representation of the string
"""
arg_string = arg_string.strip()
if arg_string.f... |
def _process_config(config):
"""
Make sure config object has required values
"""
required_fields = [
"api_key",
"from_email",
"to_email",
]
for field in required_fields:
if field not in config:
raise ValueError("required field {} not found in con... |
def elide_sequence(s, flank=5, elision="..."):
"""Trims the middle of the sequence, leaving the right and left flanks.
Args:
s (str): A sequence.
flank (int, optional): The length of each flank. Defaults to five.
elision (str, optional): The symbol used to represent the part trimmed. De... |
def cipher(text, shift, encrypt=True):
"""
Shifts alphabetic characters in a string by a given amount such
as with a Caesar cipher.
Parameters
----------
text : str
A string to be shifted. Non-alphabetic letters are unchanged.
shift : int
The number of positions to shift letters... |
def unreserve(item):
"""Removes trailing underscore from item if it has one.
Useful for fixing mutations of Python reserved words, e.g. class.
"""
if hasattr(item, 'endswith') and item.endswith('_'):
return item[:-1]
else:
return item |
def derivativeSignsToExpressionTerms(valueLabels, signs, scaleFactorIdx=None):
"""
Return remap expression terms for summing derivative[i] * sign[i] * scaleFactor
:param valueLabels: List of node value labels to possibly include.
:param signs: List of 1 (no scaling), -1 (scale by scale factor 1) or 0 (n... |
def clamp(mini, maxi, val):
"""Clamp the value between min and max"""
return min(maxi, max(mini, val)) |
def code(text: str) -> str:
"""Make text to code."""
return f'`{text}`' |
def make_obj_list(obj_or_objs):
"""This method will take an object or list of objects and ensure a list is
returned.
Example:
>>> make_obj_list('hello')
['hello']
>>> make_obj_list(['hello', 'world'])
['hello', 'world']
>>> make_obj_list(None)
[]
"""
if not obj_or_objs:
... |
def output_as_percentage(num, fractional_digits=1):
"""Output a percentage neatly.
Parameters
----------
num: float
The number to make into a percentage.
fractional_digits: int
Number of digits to output as fractions of a percent.
If not supplied, there is no reduct... |
def count_non_zeros(*iterables):
"""Returns total number of non 0 elements in given iterables.
Args:
*iterables: Any number of the value None or iterables of numeric values.
"""
result = 0
for iterable in iterables:
if iterable is not None:
result += sum(1 for element in iterable if element != ... |
def assert_false(test, obj, msg=None):
"""
Raise an error if the test expression is true. The test can be a function that takes the context object.
"""
if (callable(test) and test(obj)) or test:
raise AssertionError(msg)
return obj |
def deep_dictionary_check(dict1: dict, dict2: dict) -> bool:
"""Used to check if all keys and values between two dicts are equal, and recurses if it encounters a nested dict."""
if dict1.keys() != dict2.keys():
return False
for key in dict1:
if isinstance(dict1[key], dict) and not deep_dicti... |
def copy_list(l):
"""generates a copy of a list
"""
if not isinstance(l, list):
return None
return l[:] |
def amdahls(x, p):
"""
Computes Amdal's Law speed-up
:param x: is the speedup of the part of the task that benefits from improved system resources
:param p: is the proportion of execution time that the part benefiting from improved resources originally occupied
:return: the computed speed-up
"""... |
def convert(x):
"""
>>> convert('0x10')
(16, 'x')
>>> convert('0b10')
(2, 'b')
>>> convert('0o7')
(7, 'o')
>>> convert('10')
(10, 'd')
>>> convert('0b11 & 0b10'), convert('0b11 | 0b10'), convert('0b11 ^ 0b10')
((2, 'b'), (3, 'b'), (1, 'b'))
>>> convert('11 & 10'), convert... |
def interval_intersection(min1, max1, min2, max2):
"""
Given two intervals, (min1, max1) and (min2, max2) return their intersecting interval,
or None if they do not overlap.
"""
left, right = max(min1, min2), min(max1, max2)
if left < right:
return left, right
return None |
def lin_model_single_ele(m, x, b):
""" Returns a single y for a given x using a line """
return (m*x) + b |
def get_class_name(obj):
"""
Get class name attribute.
:param Any obj: Object for get class name.
:return: Class name
:rtype: str
"""
if isinstance(obj, type):
return obj.__name__
return obj.__class__.__name__ |
def tabularize(rows, col_spacing=2):
"""*rows* should be a list of lists of strings: [[r1c1, r1c2], [r2c1, r2c2], ..].
Returns a list of formatted lines of text, with column values left justified."""
# Find the column widths:
max_column_widths = []
for row in rows:
while len(row) > len(... |
def get_resource_by_format(resources, format_type):
"""Searches an array of resources to find the resource that
matches the file format type passed in. Returns the resource
if found.
Parameters:
resources - An array of CKAN dataset resources
For more information on the st... |
def check_subtree(t1, t2):
""" 4.1 O Check Subtree: T1 and T2 are two very large binary trees, with
T1 much bigger than T2. Create an algorithm to determine if T2 is a subtree
of T1.
A tree T2 is a subtree of T1 if there exists a node n in T1 such that the
subtree of n is identical to T2. That is, ... |
def is_number(str_value):
"""
Checks if it is a valid float number
"""
try:
float(str_value)
return True
except ValueError:
return False |
def simple_pos(arg):
"""
>>> result = jitii(simple_pos)
"""
if arg > 0:
a = 1
else:
a = 0
return a |
def _remove_rewrite_frames(tb):
"""Remove stack frames containing the error rewriting logic."""
cleaned_tb = []
for f in tb:
if 'ag__.rewrite_graph_construction_error' not in f[3]:
cleaned_tb.append(f)
return cleaned_tb |
def conf_to_env_codename(cd):
"""
Args:
cd: Config dict with the env.
Returns:
"""
return f"{cd['env']['num_customers']}C{cd['env']['num_dcs']}W{cd['env']['num_commodities']}K{cd['env']['orders_per_day']}F{cd['env']['dcs_per_customer']}V" |
def is_n_pandigital(n):
"""Tests if n is 1-len(n) pandigital."""
if len(str(n)) > 9:
return False
if len(str(n)) != len(set(str(n))):
return False
m = len(str(n))
digits = list(range(1, m+1))
filtered = [d for d in str(n) if int(d) in digits]
return len(str(n)) == len(filtere... |
def get_in(coll, path, default=None):
"""Returns a value at path in the given nested collection."""
for key in path:
try:
coll = coll[key]
except (KeyError, IndexError):
return default
return coll |
def dotProduct(vector1, vector2):
"""Returns the dot product of two vectors."""
if len(vector1) == len(vector2):
return sum((vector1[i] * vector2[i] for i in range(len(vector1))))
return None |
def score_alignment(identity, coverage, alpha=0.95):
"""T-score from the interactome3d paper."""
return alpha * (identity) * (coverage) + (1.0 - alpha) * (coverage) |
def __to_float(val, digits):
"""Convert val into float with digits decimal."""
try:
return round(float(val), digits)
except (ValueError, TypeError):
return float(0) |
def fontawesomize(val):
"""Convert boolean to font awesome icon."""
if val:
return '<i class="fa fa-check" style="color: green"></i>'
return '<i class="fa fa-times" style="color: red"></i>' |
def xor_hex_strings(str1, str2):
"""
Return xor of two hex strings.
An XOR of two pieces of data will be as random as the input with the most randomness.
We can thus combine two entropy sources in this way as a safeguard against one source being
compromised in some way.
For details, see http://c... |
def process_input(values, puzzle_input, u_input):
"""Takes input from the user and records them in the location specified
by the "value", and returns the resulting puzzle input
"""
puzzle_input[values[0]] = u_input
return puzzle_input |
def unnormalize_coefficients(n, D):
"""
Functional inverse of normalize_coefficients(n, D)
:param n: integer dimension of the original space
:param D: output from normalize_coefficients(n, D)
:return: equivalent input D to normalize_coefficients(n, D)
>>> D = forward_no_normalization([1,2,3,4])
... |
def three_pad(s):
"""Pads a string, s, to length 3 with trailing X's"""
if len(s) < 3:
return three_pad(s + "X")
return s |
def biSearch(lista, el):
"""Necesita ser una lista ordenada"""
ub = len(lista) -1
lb = 0
while(lb < ub+1):
mid = (ub + lb) // 2
if lista[mid] == el:
return True
elif lista[mid] > el:
ub = mid -1
elif lista[mid] < el:
l... |
def get_image_registry(image_name):
"""Extract registry host from Docker image name.
Returns None if registry hostname is not found in the name, meaning
that default Docker registry should be used.
Docker image name is defined according to the following rules:
- name := [hostname '/'] co... |
def sphere_volume(r):
"""Return the volume of the sphere of radius 'r'.
Use 3.14159 for pi in your computation.
"""
return (4 * 3.14159 / 3)*r**3 |
def isNumber(s: str) -> bool:
"""
Determines if a unicode string (that may include commas) is a number.
:param s: Any unicode string.
:return: True if s represents a number, False otherwise.
"""
s = s.replace(',', '')
try:
float(s)
return True
except ValueError:
... |
def main(stdin):
"""
Read in line. Parse line into list of words.
Print word as a single count.
"""
for line in stdin:
words = line.split()
for word in words:
print(("{word}\t{count}").format(word=word, count=1))
return None |
def translate_aws_action_groups(groups):
"""
Problem - AWS provides the following five groups:
- Permissions
- ReadWrite
- ListOnly
- ReadOnly
- Tagging
The meaning of these groups was not immediately obvious to me.
Permissions: ability to modify (create... |
def is_prime(n):
"""returns True if n is prime, False otherwise"""
for i in range(2, n):
if n % i == 0: # not a prime number
return False
# if we reached so far, the number should be a prime number
return True |
def allocate_site_power_type(settlement, strategy):
"""
Shifts the site power type based onthe strategy.
"""
if strategy == 'baseline':
return settlement
elif strategy == 'smart_diesel_generators':
return settlement
elif strategy == 'smart_solar':
return settlement
... |
def get_last_n_letters(text, n):
"""
The below line is for unit tests
>>> get_last_n_letters('This is for unit testing',4)
'ting'
"""
return text[-n:] |
def _get_resource_type(attribute, root, type_, method):
"""Returns ``attribute`` defined in the resource type, or ``None``."""
if type_ and root.resource_types:
types = root.resource_types
r_type = [r for r in types if r.name == type_]
r_type = [r for r in r_type if r.method == method]
... |
def split_attribute(input):
"""
properly split apart attribute strings, even when they have sub-attributes declated between [].
:param input:the attribute string to split
:return: dict containing the elements of the top level attribute string.
Sub-attribute strings between '[]'s are appended to their parent, withou... |
def any_action_failed(results):
""" Return `True` if some parallelized invocations threw exceptions """
return any(isinstance(res, Exception) for res in results) |
def ind(x, a, b):
"""
Indicator function for a <= x <= b.
Parameters
----------
x: int
desired value
a: int
lower bound of interval
b:
upper bound of interval
Returns
-------
1 if a <= x <= b and 0 otherwise.
"""
return (x >= a)*(x <= b) |
def ksplit(key, mod_key=True):
"""ksplit takes a redis key of the form
"label1:value1:label2:value2"
and converts it into a dictionary for easy access"""
item_list = key.split(':')
items = iter(item_list)
if mod_key:
return {x.replace('-','_'):next(items) for x in items}
else:... |
def get_submission_variants(form_fields):
"""Extracts a list of variant ids from the clinvar submission form in blueprints/variants/clinvar.html (creation of a new clinvar submission).
Args:
form_fields(dict): it's the submission form dictionary. Keys have the same names as CLINVAR_HEADER and ... |
def parse_vec_files(vec_files_str: str):
"""
Examples
--------
>>> parse_vec_files("w:123,c:456")
{'w': '123', 'c': '456'}
"""
_ret = dict()
vec_key_value = vec_files_str.split(",")
for key_value in vec_key_value:
key, value = key_value.split(":")
_ret[key] = value
... |
def unique_values_from_query(query_result):
"""Simplify Athena query results into a set of values.
Useful for listing tables, partitions, databases, enable_metrics
Args:
query_result (dict): The result of run_athena_query
Returns:
set: Unique values from the query result
"""
r... |
def circulo(raio):
"""calcula a area de um circulo"""
area=3.14*(raio**2)
return area |
def Focal_length_eff(info_dict):
"""
Computes the effective focal length give the plate scale and
the pixel size.
Parameters
----------
info_dict: dictionary
Returns
---------
F_eff: float
effective focal length in m
"""
# F_eff = 1./ (info_dict['pixelScale'] *
#... |
def get_cell_connection(cell, pin):
"""
Returns the name of the net connected to the given cell pin. Returns None
if unconnected
"""
# Only for subckt
assert cell["type"] == "subckt"
# Find the connection and return it
for i in range(1, len(cell["args"])):
p, net = cell["args"]... |
def _collapse_results(parameters):
"""
When using cdp_run, parameters is a list of lists: [[Parameters], ...].
Make this just a list: [Parameters, ...].
"""
output_parameters = []
for p1 in parameters:
if isinstance(p1, list):
for p2 in p1:
output_parameters.... |
def _make_expr_time(param_name, param_val):
"""Generate query expression for a time-valued flight parameter."""
if param_val is None:
return None, None
# Summary attributes for each parameter...
smmry_attr = {'time': ('time_coverage_start', 'time_coverage_end')}
attr_min, attr_max = smmry_a... |
def location(text, index):
"""
Location of `index` in the `text`. Report row and column numbers when
appropriate.
"""
if isinstance(text, str):
line, start = text.count('\n', 0, index), text.rfind('\n', 0, index)
column = index - (start + 1)
return "{}:{}".format(line + 1, c... |
def calc_g(r, aa):
"""
DESCRIPTION TBD (FUNCTION USED IN GENERAL CONSTANTS).
Parameters:
r (float): radius
aa (float): spin parameter (0, 1)
Returns:
g (float)
"""
return 2 * aa * r |
def is_integer_like(val):
"""Returns validation of a value as an integer."""
try:
value = int(val)
return True
except (TypeError, ValueError, AttributeError):
return False |
def normalize_wpsm_cost(raw_cost, highest, lowest):
"""
converts a raw_cost into the range (0,1), given the highest and lowest wpsm costs
See: https://stackoverflow.com/questions/5294955/how-to-scale-down-a-range-of-numbers-with-a-known-min-and-max-value
"""
# print(raw_cost)
# print("TURNED INT... |
def get_input_addrs(tx):
""" Takes tx object and returns the input addresses associated. """
addrs = []
# print("tx['inputs']: ", tx['inputs'])
for x in tx['inputs']:
try:
addrs.append(x['prev_out']['addr'])
except KeyError:
continue
return addrs
#try:
... |
def intify(values: bytes, unsigned=False) -> int:
"""Convert bytes to int."""
return int.from_bytes(values, byteorder="little", signed=(not unsigned)) |
def formatCode(arg, type=""):
"""Converts formatting to one suited for discord
"diff" = red;
"css" = red-orange;
"fix" = yellow;
"ini" with [] = blue;
"json" with "" = green;
" " = none
"""
toSend = f"```{type}\n{arg}\n```"
return toSend |
def jet_power(F, m_dot):
"""Jet power of a rocket propulsion device.
Compute the kinetic power of the jet for a given thrust level and mass flow.
Reference: Goebel and Katz, equation 2.3-4.
Arguments:
F (scalar): Thrust force [units: newton].
m_dot (scalar): Jet mass flow rate [units:... |
def translate_subset_type(subset_type):
"""Maps subset shortcut to full name.
Args:
subset_type (str): Subset shortcut.
Returns:
str: Subset full name.
"""
if subset_type == 'max':
model = 'best'
elif subset_type == 'random':
model = 'random'
elif subset_typ... |
def normRect(rect):
"""Normalize a bounding box rectangle.
This function "turns the rectangle the right way up", so that the following
holds::
xMin <= xMax and yMin <= yMax
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
... |
def parse_cluster_pubsub_numpat(res, **options):
"""
Result callback, handles different return types
switchable by the `aggregate` flag.
"""
aggregate = options.get('aggregate', True)
if not aggregate:
return res
numpat = 0
for node_numpat in res.values():
numpat += node... |
def factorial_n(num):
""" (int) -> float
Computes num!
Returns the factorial of <num>
"""
if isinstance(num, int) and num >= 0:
product = 1 # Init
while num: # As long as num is positive
product *= num
num -= 1
return product
else:
... |
def is_odd(n: int) -> bool:
"""
Checks whether n is an odd number.
:param int n: number to check
:returns bool: True if <n> is an odd number"""
return bool(n & 1) |
def loc_to_block_num(y, x):
"""
:param y: The y location of the cell. Precondition: 0 <= y < 9
:param x: The x location of the cell Precondition: 0 <= x < 9
:return: The number of the block the cell is located in
"""
return int(x/3)+int(y/3)*3 |
def inverted_list_index(l):
"""Given a list, return a list enumerating the indexes that gives the original list in order.
Example:
[3, 1, 2, 4]
-> [1, 2, 0, 3]
"""
return [ i[0] for i in sorted(enumerate(l), key=lambda i: i[1]) ] |
def sort_cards(cards):
"""Sort shuffled list of cards, sorted by rank.
reference:
http://pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/
"""
card_order = {'A': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6,
'7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, ... |
def freeze(d):
"""Convert the value sets of a multi-valued mapping into frozensets.
The use case is to make the value sets hashable once they no longer need to be edited.
"""
return {k: frozenset(v) for k, v in d.items()} |
def insert_colon_break(words_list):
"""Doc."""
keys = ('case', 'default', 'private', 'public', 'protect')
new_words_list = []
for words in words_list:
if ':' in words and words[-1][:2] != '//' and words[0] in keys:
index = words.index(':') + 1
new_words_list.append(words[... |
def _get_pymeos_path(package_name):
"""Takes a path starting with _pymeos.something and converts it into pymeos.something"""
if package_name.startswith("_pymeos"):
return package_name[1:]
raise ValueError("Unsupported package name passed: " + package_name) |
def find_nth_digit(n):
"""find the nth digit of given number.
1. find the length of the number where the nth digit is from.
2. find the actual number where the nth digit is from
3. find the nth digit and return
##-------------------------------------------------------------------
"""
length = 1
... |
def parse_purl(purl):
"""
Finds the purl in the body of the Eiffel event message and parses it
:param purl: the purl from the Eiffel ArtC event
:return: tuple: the artifact filename and the substring from the build path
"""
# pkg:<build_path>/<intermediate_directories>/
# <artifact_filename>... |
def GetNumberField(d: dict, item: str):
""" Handles items not being present (lazy get) """
try:
r = d[item]
return r
except:
return 0.0 |
def check_alarm_input(alarm_time):
"""Checks to see if the user has entered in a valid alarm time"""
if len(alarm_time) == 1: # [Hour] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0:
return True
if len(alarm_time) == 2: # [Hour:Minute] Format
if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
... |
def get_batch_size(batch):
"""
Returns the batch size in samples
:param batch: List of input batches, if there is one input a batch can be either
a numpy array or a list, for multiple inputs it can be tuple of lists or
numpy arrays.
"""
if isinstance(batch, tuple... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.