content stringlengths 42 6.51k |
|---|
def oddify(n):
"""Ensure number is odd by incrementing if even
"""
return n if n % 2 else n + 1 |
def fn_SortByKey(d_Dict: dict) -> list:
"""
:
: Returns a list of values in a dictionary in order of their keys.
:
:
: Args:
: dict d_Dict : An unsigned integer!
:
: Returns:
: List of values sorted by key
:
:
"""
return [y[1] for y in sorted([(k, v) for k, v in d_Dict.items()], key=lambda x: x[0])] |
def key_int_to_str(key: int) -> str:
"""
Convert spotify's 'pitch class notation' to
and actual key value
"""
switcher = {
"0": "C",
"1": "C#",
"2": "D",
"3": "D#",
"4": "E",
"5": "F",
"6": "F#",
"7": "G",
"8": "G#",
"9": "A",
"10": "A#",
"11": "B"
}
return switcher.get(str(key), "No key") |
def hauteur(arbre):
"""Renvoie la hauteur de l'arbre"""
if arbre is None:
return 0
return 1 + max(hauteur(arbre.get_gauche()), hauteur(arbre.get_droite())) |
def _n_onset_midi(patterns):
"""Computes the number of onset_midi objects in a pattern
Parameters
----------
patterns :
A list of patterns using the format returned by
:func:`mir_eval.io.load_patterns()`
Returns
-------
n_onsets : int
Number of onsets within the pattern.
"""
return len([o_m for pat in patterns for occ in pat for o_m in occ]) |
def bytes_to_size_string(b: int) -> str:
"""Convert a number in bytes to a sensible unit."""
kb = 1024
mb = kb * 1024
gb = mb * 1024
tb = gb * 1024
if b > tb:
return "%0.2fTiB" % (b / float(tb))
if b > gb:
return "%0.2fGiB" % (b / float(gb))
if b > mb:
return "%0.2fMiB" % (b / float(mb))
if b > kb:
return "%0.2fKiB" % (b / float(kb))
return str(b) |
def select_and_combine(i, obj, others, combine_func, *args, **kwargs):
"""Combine `obj` and an element from `others` at `i` using `combine_func`."""
return combine_func(obj, others[i], *args, **kwargs) |
def calculate_average_price_sl_percentage_long(sl_price, average_price):
"""Calculate the SL percentage based on the average price for a long deal"""
return round(
((sl_price / average_price) * 100.0) - 100.0,
2
) |
def bits2int(bits):
"""
convert bit list to int
"""
num = 0
for b in bits:
num <<= 1
num += int(b)
return num |
def to_string(obj):
"""Process Sigma-style dict into string JSON representation"""
import json
return json.dumps(obj) |
def rk4(x, v, a, dt,accell):
"""Returns final (position, velocity) tuple after
time dt has passed.
x: initial position (number-like object)
v: initial velocity (number-like object)
a: acceleration function a(x,v,dt) (must be callable)
dt: timestep (number)"""
x1 = x
v1 = v
a1 = a(x1, v1, 0,accell)
x2 = x + 0.5*v1*dt
v2 = v + 0.5*a1*dt
a2 = a(x2, v2, dt/2.0,accell)
x3 = x + 0.5*v2*dt
v3 = v + 0.5*a2*dt
a3 = a(x3, v3, dt/2.0,accell)
x4 = x + v3*dt
v4 = v + a3*dt
a4 = a(x4, v4, dt,accell)
xf = x + (dt/6.0)*(v1 + 2*v2 + 2*v3 + v4)
vf = v + (dt/6.0)*(a1 + 2*a2 + 2*a3 + a4)
return xf, vf |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*', '423145*', '*5?3215', '*35214*', '*41532*', '*2*1***'])
False
"""
lst = list(" ".join(board))
if "?" in lst:
return False
return True |
def get_frame_name_and_description(header, i, always_call_first_primary=True):
"""
This function ...
:param header:
:param i:
:param always_call_first_primary:
:return:
"""
planeX = "PLANE" + str(i)
# Return the description
if planeX in header: description = header[planeX]
else: description = None
plane_type = "frame"
# FITS file created by AstroMagic
if description is not None and "[" in description and "]" in description:
name = description.split(" [")[0]
plane_type = description.split("[")[1].split("]")[0]
elif i == 0 and always_call_first_primary:
# Get the name of this frame, but the first frame always gets the name 'primary' unless the
# 'always_call_first_primary' flag is disabled
description = "the primary signal map"
name = "primary"
elif description is not None:
# Convert spaces to underscores and ignore things between parentheses
name = description.split("(")[0].rstrip(" ").replace(" ", "_")
# If the frame name contains 'error', use the standard name "errors" for this frame
if 'error' in name: name = "errors"
else: ## description is None
description = ""
name = "frame"+str(i)
# Return the name and description
return name, description, plane_type |
def increment_pair(pair):
"""
Increments pair by traversing through all
k for a given j until 1 is reached, then starting
back up with the next highest value for j
E.G. [1,2]-->[2,3]-->[1,3]-->[3,4]-->[2,4]-->...
"""
k, j = pair
k -= 1
if k > 0:
return [k, j]
else:
return [j, j + 1] |
def r2h(rgb):
"""
Convert an RGB-tuple to a hex string.
"""
return '#%02x%02x%02x' % tuple([ int(a*255) for a in rgb ]) |
def pulse_train(time, start, duration, repeat_time, end):
""" Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
"""
t = time()
if start <= t < end:
return 1 if (t - start) % repeat_time < duration else 0
else:
return 0 |
def getSmallerAndBiggerElement(element1, element2):
"""Returning a tuple of smaller and bigger element, if the same length the first is listed first.
>>> getSmallerAndBiggerElement([1,2], [3,4])
([1, 2], [3, 4])
>>> getSmallerAndBiggerElement([1,2,3], [3,4])
([3, 4], [1, 2, 3])
>>> getSmallerAndBiggerElement([1,2], [3,4,5])
([1, 2], [3, 4, 5])
"""
smallerList = None
biggerList = None
if len(element1) == len(element2):
smallerList = element1
biggerList = element2
elif len(element1) > len(element2):
smallerList = element2
biggerList = element1
else:
smallerList = element1
biggerList = element2
return (smallerList, biggerList) |
def to_set(value):
"""Convert a value to set."""
if type(value) == set or type(value) == list:
return set(value)
else:
return set([value]) |
def _variable_status(value, declarations):
"""Check that an environment variable exists."""
required = False
for decl in declarations:
if decl.required:
required = True
break
if value is not None:
return "PRESENT"
if required and value is None:
return "MISSING"
return "NOT PRESENT" |
def ChromeOSTelemetryRemote(test_config):
"""Substitutes the correct CrOS remote Telemetry arguments.
VMs use a hard-coded remote address and port, while physical hardware use
a magic hostname.
Args:
test_config: A dict containing a configuration for a specific test on a
specific builder.
"""
def StringContainsSubstring(s, sub_strs):
for sub_str in sub_strs:
if sub_str in s:
return True
return False
VM_POOLS = [
'chromium.tests.cros.vm',
'chrome.tests.cros-vm',
]
HW_POOLS = [
'chrome-cros-dut',
'chrome.cros-dut',
]
dimensions = test_config.get('swarming', {}).get('dimension_sets', [])
assert len(dimensions)
pool = dimensions[0].get('pool')
if not pool:
raise RuntimeError(
'No pool set for CrOS test, unable to determine whether running on '
'a VM or physical hardware.')
if StringContainsSubstring(pool, VM_POOLS):
return [
'--remote=127.0.0.1',
# By default, CrOS VMs' ssh servers listen on local port 9222.
'--remote-ssh-port=9222',
]
if StringContainsSubstring(pool, HW_POOLS):
return [
# Magic hostname that resolves to a CrOS device in the test lab.
'--remote=variable_chromeos_device_hostname',
]
raise RuntimeError('Unknown CrOS pool %s' % pool) |
def pair(k1, k2):
"""
Cantor pairing function
"""
z = int(0.5 * (k1 + k2) * (k1 + k2 + 1) + k2)
return z |
def remove_unused_fields(d):
"""
Remove from the dictionary fields that should not be in the final output.
"""
copy = dict(d)
copy.pop("title", None)
return copy |
def fibonacci(n: int) -> list:
"""
Returns a list of the Fibonacci Sequence
up to the n'th number (input)
"""
lst = []
for i in range(n + 1):
if i == 0:
lst.append(0)
elif i == 1:
lst.append(1)
elif i > 1:
x = lst[-1] + lst[-2]
lst.append(x)
return lst |
def is_triangle(side_a, side_b, side_c):
"""Returns True if the input satisifes the sides of a triangle"""
return side_a + side_b > side_c and side_a + side_c > side_b and side_b + side_c > side_a |
def _noise_free_model_of_recovery(sulphur):
"""This method returns a metal recovery for a given sulphur %."""
return 74.81 - 6.81/sulphur |
def fix_url(url: str) -> str:
"""Prefix a schema-less URL with http://."""
if '://' not in url:
url = 'http://' + url
return url |
def str_if_not_none(value):
"""Return the string value of the argument, unless
it is None, in which case return None"""
if value is None:
return None
else:
return str(value) |
def lyrics_processing(lyrics):
"""Preprocess the lyrics"""
lyrics_a = lyrics.replace(r"\n", " ")
lyrics_b = lyrics_a.replace(r"\r", " ")
text_list = list(lyrics_b.rsplit())
words_count = len(text_list)
return words_count |
def parse_dict_json(dict):
"""
Helper function that convers Python dictionary keys/values into strings
to be dumped into a JSON file.
"""
return {
outer_k: {str(inner_k): inner_v for inner_k, inner_v in outer_v.items()}
for outer_k, outer_v in dict.items()
} |
def row_to_dict(row, field_names):
"""Convert a row from bigquery into a dictionary, and convert NaN to
None
"""
dict_row = {}
for value, field_name in zip(row, field_names):
if value and str(value).lower() == "nan":
value = None
dict_row[field_name] = value
return dict_row |
def sum_series(n, x=0, y=1):
"""Function that uses a required parameter and two optional parameters."""
for i in range(n - 1):
x, y = y, x + y
return x |
def word_split(phrase, list_of_words, result=None):
"""word_split(str,list) -> list
If a phrase can be split into a list of words it returns the list.
>>> word_split('themanran',['the','ran','man'])
['the', 'man', 'ran']
>>> word_split('ilovedogsJohn',['i','am','a','dogs','lover','love','John'])
['i', 'love', 'dogs', 'John']
"""
if result is None:
result = []
for word in list_of_words:
if phrase.startswith(word):
result.append(word)
return word_split(phrase[len(word):], list_of_words, result)
return result |
def ringIsClockwise(ringToTest):
"""
determine if polygon ring coordinates are clockwise. clockwise signifies
outer ring, counter-clockwise an inner ring or hole.
"""
total = 0
i = 0
rLength = len(ringToTest)
pt1 = ringToTest[i]
pt2 = None
for i in range(0, rLength - 1):
pt2 = ringToTest[i + 1]
total += (pt2[0] - pt1[0]) * (pt2[1] + pt1[1])
pt1 = pt2
return (total >= 0) |
def email_parser(raw_email):
"""parse email and return dict
@raw_email str
"""
import email
msg = email.message_from_string(raw_email)
# print msg.keys()
return {
'subject': msg.get("subject"),
'from': msg.get('from'),
'to': msg.get('to'),
'date': msg.get('Date')
} |
def get_uris_for_oxo(zooma_result_list: list) -> set:
"""
For a list of Zooma mappings return a list of uris for the mappings in that list with a high
confidence.
:param zooma_result_list: List with elements of class ZoomaResult
:return: set of uris from high confidence Zooma mappings, for which to query OxO
"""
uri_set = set()
for mapping in zooma_result_list:
# Only use high confidence Zooma mappings for querying OxO
if mapping.confidence.lower() == "high":
uri_set.update([entry.uri for entry in mapping.mapping_list])
return uri_set |
def set_md_table_font_size(row, size):
"""Wrap each row element with HTML tags and specify font size"""
for k, elem in enumerate(row):
row[k] = '<p style="font-size:' + str(size) + '">' + elem + '</p>'
return row |
def is_health_monitor_alarm(alarm):
""" Check that the alarm target is the cloudwatch forwarder """
is_health_alarm = False
if len(alarm["OKActions"]) > 0:
action = alarm["OKActions"][0]
is_health_alarm = "cloudwatch_forwarder" in action
return is_health_alarm |
def matched_requisition(ref, requisitions):
"""Get the requisition for current ref."""
for requisition in requisitions:
if requisition["reference"] == ref:
return requisition
return {} |
def merge_dicts(dict1, dict2):
""" Merge two dictionaries.
Parameters
----------
dict1, dict2 : dict
Returns
-------
dict_merged : dict
Merged dictionaries.
"""
dict_merged = dict1.copy()
dict_merged.update(dict2)
return dict_merged |
def if_elif_else(value, condition_function_pair):
"""
Apply logic if condition is True.
Parameters
----------
value : anything
The initial value
condition_function_pair : tuple
First element is the assertion function, second element is the
logic function to execute if assertion is true.
Returns
-------
The result of the first function for which assertion is true.
"""
for condition, func in condition_function_pair:
if condition(value):
return func(value) |
def arquivo_existe(nome):
"""
-> verifica se existe um arquivo para salvar os dados dos participantes do jogo. dando assim o return
para o programa principal seguir.
"""
try:
a = open(nome, 'rt')
a.close()
except FileNotFoundError:
return False
else:
return True |
def isBin(s):
"""
Does this string have any non-ASCII characters?
"""
for i in s:
i = ord(i)
if i < 9 or 13 < i < 32 or 126 < i:
return True
return False |
def _path_in_ignore_dirs(source_path: str, ignore_dirs: list) -> bool:
"""Checks if the source path is to be ignored using a case sensitive match
Arguments:
source_path: the path to check
ignore_dirs: the list of directories to ignore
Return:
Returns True if the path is to be ignored, and False if not
"""
# Break apart the source path for later checking
if '/' in source_path:
source_parts = source_path.split('/')
test_join_char = '/'
elif '\\' in source_path:
source_parts = source_path.split('\\')
test_join_char = '\\'
else:
source_parts = [source_path]
test_join_char = '/'
for one_dir in ignore_dirs:
# Check for multiple folders
if '/' in one_dir:
dir_parts = one_dir.split('/')
elif '\\' in one_dir:
dir_parts = one_dir.split('\\')
else:
dir_parts = [one_dir]
# See if the entire path to check is to be found
if test_join_char.join(dir_parts) not in source_path:
continue
# Check path particles to ensure the entire path names match and not just parts of path names
# 'test' vs. 'testing' for example
parts_matched = 0
for one_part in dir_parts:
if one_part not in source_parts:
break
parts_matched += 1
if parts_matched == len(dir_parts):
return True
return False |
def listsdelete(x, xs):
"""Return a new list with x removed from xs"""
i = xs.index(x)
return xs[:i] + xs[(i+1):] |
def calculate_hamming_distance(input_bytes_1, input_bytes_2):
"""Finds and returns the Hamming distance (number of differing
bits) between two byte-strings
"""
hamming_distance = 0
for b1, b2 in zip(input_bytes_1, input_bytes_2):
difference = b1 ^ b2
# Count the number of differences ('1's) and add to the hamming distance
hamming_distance += sum([1 for bit in bin(difference) if bit == '1'])
return hamming_distance |
def describe_call(name, args):
""" Return a human-friendly description of this call. """
description = '%s()' % name
if args:
if isinstance(args, dict):
description = '%s(**%s)' % (name, args)
elif isinstance(args, list):
description = '%s(*%s)' % (name, args)
return description |
def add_zeros(element):
"""This changes the format of postcodes to string with the needed zeros
Args:
element: individual row from apply codes
Returns:
parameter postcode value with zeros
"""
#postinumeroihin etunollat jos on ollut integer
element=str(element)
if len(element) == 3:
element = "00" + element
if len(element) == 4:
element = "0" + element
return(element) |
def ris_itemType_get(ris_text_line_dict_list):
"""
params: ris_text_line_list_dict, [{},[],[],[], ...]
return: itemType_value, str.
"""
#
itemType_list = []
for ris_element in ris_text_line_dict_list:
if isinstance(ris_element, dict):
if "itemType" in ris_element.keys():
itemType_list.append(ris_element["itemType"])
else:
pass
else:
pass
#
itemType_value = itemType_list[0]
#
return itemType_value |
def convert_type(string):
""" return an integer, float, or string from the input string """
if string is None:
return None
try: int(string)
except: pass
else: return int(string)
try: float(string)
except: pass
else: return float(string)
return string.strip() |
def make_lr_schedule(lr_base, lr_sched_epochs, lr_sched_factors):
"""Creates a learning rate schedule in the form of a dictionary.
After ``lr_sched_epochs[i]`` epochs of training, the learning rate will be set
to ``lr_sched_factors[i] * lr_base``. The schedule is given as a dictionary
mapping epoch number to learning rate. The learning rate for epoch 0 (that is
``lr_base``) will automatically be added to the schedule.
Examples:
- ``make_schedule(0.3, [50, 100], [0.1, 0.01])`` yields
``{0: 0.3, 50: 0.03, 100: 0.003}``.
- ``make_schedule(0.3)`` yields ``{0: 0.3}``.
- ``make_schedule(0.3, [], [])`` yields ``{0: 0.3}``.
Args:
lr_base: A base learning rate (float).
lr_sched_epochs: A (possibly empty) list of integers, specifying epochs at
which to decrease the learning rate.
lr_sched_factors: A (possibly empty) list of floats, specifying factors by
which to decrease the learning rate.
Returns:
sched: A dictionary mapping epoch numbers to learning rates.
"""
if lr_sched_epochs is None and lr_sched_factors is None:
return {0: lr_base}
# Make sure learning rate schedule has been properly specified
if lr_sched_epochs is None or lr_sched_factors is None:
raise TypeError(
"""Specifiy *both* lr_sched_epochs and lr_sched_factors.""")
if ((not isinstance(lr_sched_epochs, list))
or (not isinstance(lr_sched_factors, list))
or (len(lr_sched_epochs) != len(lr_sched_factors))):
raise ValueError(
"""lr_sched_epochs and lr_sched_factors must be lists of
the same length.""")
# Create schedule as dictionary epoch->factor; add value for epoch 0.
sched = {n: f * lr_base for n, f in zip(lr_sched_epochs, lr_sched_factors)}
sched[0] = lr_base
return sched |
def _is_valid_input_row(row, conf):
"""
Filters blank rows and applies the optional configuration filter
argument if necessary.
:param row: the input row
:param config: the configuration
:return: whether the row should be converted
"""
# Filter blank rows.
if all(value == None for value in row):
return False
# Apply the config filter, if any.
return conf.in_filter(row, conf.in_col_ndx_map) if conf.in_filter else True |
def from_path_get_project(path):
"""
To maintain an organization of webposts beyond a top-level
grouping, we keep track of a "project" for each post
:param: path of the post
:type path: string
"""
folder_list = path.split("/")
# All posts are under the "projects/" folder
# We assume the next folder is the project
if len(folder_list) >= 2:
return folder_list[1]
return "" |
def hex8_to_u32le(data):
"""! @brief Build 32-bit register value from little-endian 8-digit hexadecimal string
@note Endianness in this function name is backwards.
"""
return int(data[0:8], 16) |
def color_command_validator(language, inputs, options, attrs, md):
"""Color validator."""
valid_inputs = set()
for k, v in inputs.items():
if k in valid_inputs:
options[k] = True
continue
attrs[k] = v
return True |
def bubble_sort(ls):
"""
Bubble sort the simplest sorting algorith.
Time:O(n^2); Auxiliary space: O(1)
"""
size = len(ls)
while size > 1:
i = 0
while i < size - 1:
if ls[i] > ls[i+1]:
temp = ls[i+1]
ls[i+1] = ls[i]
ls[i] = temp
i += 1
size -= 1
return ls |
def extract_dtype(descriptor, key):
"""
Work around the fact that we currently report jsonschema data types.
"""
reported = descriptor["data_keys"][key]["dtype"]
if reported == "array":
return float # guess!
else:
return reported |
def get_factors(x):
"""Returns a list of factors of given number x."""
factors = []
#iterate over range from 1 to number x
for i in range(1, x + 1):
#check if i divides number x evenly
if (x % i == 0):
factors.append(i)
return factors |
def format_subrank(parent_rank, number):
"""Formats the name for ambiguous subranks based on their parent and
number."""
return '{}_Subrank_{}'.format(parent_rank, number) |
def sum_proper_divisors(x):
"""
Calculate the sum of x's proper divisors.
"""
s = 1
for i in range(2, x // 2 + 1):
if x % i == 0:
s += i
return s |
def pig_latinify(word):
"""
Describe your function
:param :
:return:
:raises:
"""
result = ""
return result |
def gerling(rho, C0=6.0, C1=4.6):
"""
Compute Young's modulus from density according to Gerling et al. 2017.
Arguments
---------
rho : float or ndarray
Density (kg/m^3).
C0 : float, optional
Multiplicative constant of Young modulus parametrization
according to Gerling et al. (2017). Default is 6.0.
C1 : float, optional
Exponent of Young modulus parameterization according to
Gerling et al. (2017). Default is 4.6.
Returns
-------
E : float or ndarray
Young's modulus (MPa).
"""
return C0*1e-10*rho**C1 |
def numeric_range(numbers):
"""Calculates the difference between the min and max of a given list
Args:
numbers: A list of numbers
Returns:
The distance of the minimax
"""
numbers = sorted(list(numbers))
return (numbers[len(numbers) - 1] - numbers[0]) if numbers else 0 |
def format_user_input(user_input):
"""re-formats user input for API queries"""
lower_user_input = user_input.lower()
search_query = lower_user_input.replace(" ", "%20")
return search_query |
def dqn_params(buffer_size=int(1e6),
gamma=0.99,
epsilon=0.9,
epsilon_decay=1e-6,
epsilon_min=0.1,
batch_size=64,
lr=0.01,
update_freq=5,
tau=0.01):
"""
Parameters
----------
buffer_size : number, optional
Capacity of experience buffer. The default is int(1e6).
gamma : number optional
Discount factor. The default is 0.99.
epsilon : number, optional
Exploration parameter. The default is 0.05.
epsilon_decay : number, optional
Decay rate for epsilon. The default is 1e6.
epsilon_min : number, optional
Minimum value of epsilon. The default is 0.1.
batch_size : number, optional
Batch size for training. The default is 128.
lr : number, optional
Learn rate for Q-Network. The default is 0.01.
update_freq : number, optional
Update frequency for target Q-Network. The default is 0.01.
tau : number, optional
Smoothing factor for target Q-Network update. The default is 0.01.
Returns
-------
params
"""
params = {
'buffer_size': buffer_size,
'gamma': gamma,
'epsilon': epsilon,
'epsilon_decay': epsilon_decay,
'epsilon_min': epsilon_min,
'batch_size': batch_size,
'lr': lr,
'update_freq': update_freq,
'tau': tau,
'device': 'cpu'
}
return params |
def test_if_duplicated_first_value_in_line_items_contents(lst):
"""Takes components and amounts as a list of strings and floats, and returns true if there is at least one repeated component name."""
first_value = lst[0::2]
duplicated_first_value = [x for x in first_value if first_value.count(x) > 1]
return bool(len(duplicated_first_value) > 0) |
def _icd10cm_code_fixer(code):
"""Fixes ICD10CM codes"""
new_code = code[0:3]
if len(code) > 3:
new_code += '.' + code[3:]
return new_code |
def normalize_string(string):
"""
Standardize input strings by making
non-ascii spaces be ascii, and by converting
treebank-style brackets/parenthesis be characters
once more.
Arguments:
----------
string : str, characters to be standardized.
Returns:
--------
str : standardized
"""
return string.replace("\xa0", " ")\
.replace("\\", "")\
.replace("-LRB-", "(")\
.replace("-RRB-", ")")\
.replace("-LCB-", "{")\
.replace("-RCB-", "}")\
.replace("-LSB-", "[")\
.replace("-RSB-", "]") |
def bitstr(n, width=None):
"""return the binary representation of n as a string and
optionally zero-fill (pad) it to a given length
"""
result = list()
while n:
result.append(str(n%2))
n = int(n/2)
if (width is not None) and len(result) < width:
result.extend(['0'] * (width - len(result)))
result.reverse()
return ''.join(result) |
def size2str(num, suffix='B'):
"""Convert size from bytes to human readable string."""
for unit in ('', 'K', 'M', 'G', 'T'):
if abs(num) < 1024.0:
return '{:3.1f} {}{}'.format(num, unit, suffix)
num /= 1024.0
return '>1000 TB' |
def dict(*args, **kwargs):
"""
Takes arguments and builds a dictionary from them. The actual arguments
can vary widely. A single list of (key, value) pairs, or an unlimited
number of (key, value) pairs may be passed. In addition, any number of
keyword arguments may be passed, which will be added to the dictionary
as well.
"""
dict = {}
if len(args) == 1:
listOfPairs = args[0]
else:
listOfPairs = args
for key, value in listOfPairs:
dict[key] = value
dict.update(kwargs)
return dict |
def match_dim_specs(specs1, specs2):
"""Matches dimension specs used to link axes.
Axis dimension specs consists of a list of tuples corresponding
to each dimension, each tuple spec has the form (name, label, unit).
The name and label must match exactly while the unit only has to
match if both specs define one.
"""
if (specs1 is None or specs2 is None) or (len(specs1) != len(specs2)):
return False
for spec1, spec2 in zip(specs1, specs2):
for s1, s2 in zip(spec1, spec2):
if s1 is None or s2 is None:
continue
if s1 != s2:
return False
return True |
def find_unbalanced_program(program_tree, aggregated_weights):
"""Find the node in the tree that is unbalanced."""
# Find all the nodes that are candidates to be unbalanced.
# I.e. all nodes that have child nodes
parent_nodes = set(parent_node for parent_node in program_tree.values() if parent_node)
unbalanced_nodes = {}
# For all candidate nodes, look at the aggregated weights of all its
# direct children
for parent_node in parent_nodes:
weights = sorted([aggregated_weights[child_node] \
for child_node in program_tree.keys() \
if program_tree[child_node] == parent_node], reverse=True)
if weights[0] != weights[-1]:
# Store off the unbalanced node and its parent node
unbalanced_nodes[parent_node] = program_tree[parent_node]
# As there is only one unbalanced node, the list of unbalanced nodes
# must form a subtree. The actual unbalanced node is lowest node -
# i.e the node that no other nodes in the subtree are pointing to
unbalanced_node = [unbalanced_node for unbalanced_node in unbalanced_nodes \
if unbalanced_node not in unbalanced_nodes.values()][0]
return unbalanced_node |
def MPInt(value):
"""Encode a multiple precision integer value"""
l = value.bit_length()
l += (l % 8 == 0 and value != 0 and value != -1 << (l - 1))
l = (l + 7) // 8
return l.to_bytes(4, 'big') + value.to_bytes(l, 'big', signed=True) |
def _interp_fit(y0, y1, y_mid, f0, f1, dt):
"""Fit coefficients for 4th order polynomial interpolation.
Args:
y0: function value at the start of the interval.
y1: function value at the end of the interval.
y_mid: function value at the mid-point of the interval.
f0: derivative value at the start of the interval.
f1: derivative value at the end of the interval.
dt: width of the interval.
Returns:
List of coefficients `[a, b, c, d, e]` for interpolating with the polynomial
`p = a * x ** 4 + b * x ** 3 + c * x ** 2 + d * x + e` for values of `x`
between 0 (start of interval) and 1 (end of interval).
"""
a = 2 * dt * (f1 - f0) - 8 * (y1 + y0) + 16 * y_mid
b = dt * (5 * f0 - 3 * f1) + 18 * y0 + 14 * y1 - 32 * y_mid
c = dt * (f1 - 4 * f0) - 11 * y0 - 5 * y1 + 16 * y_mid
d = dt * f0
e = y0
return [e, d, c, b, a] |
def to_16_bit(letters):
"""Convert the internal (little endian) number format to an int"""
a = ord(letters[0])
b = ord(letters[1])
return (b << 8) + a |
def num_to_str(num):
"""Convert an int or float to a nice string.
E.g.,
21 -> '21'
2.500 -> '2.5'
3. -> '3'
"""
return "{0:0.02f}".format(num).rstrip("0").rstrip(".") |
def evaluate_part_one(expression: str) -> int:
"""Solve the expression from left to right regardless of operators"""
answer = 0
operator = None
for elem in expression.split():
if elem.isdigit():
if operator is None:
answer = int(elem)
elif operator == "+":
answer += int(elem)
elif operator == "*":
answer *= int(elem)
else:
operator = elem
return answer |
def _index_digit(s):
"""Find the index of the first digit in `s`.
:param s: a string to scan
Raises a ValueError if no digit is found.
"""
for i, c in enumerate(s):
if c.isdigit():
return i
raise ValueError('digit not found') |
def get_inline_function(binary2source_entity_mapping_simple_dict):
"""find inline functions by its mapping"""
function_number = 0
source_function_number = 0
inline_source_function_number = 0
inline_function_number = 0
binary_number = 0
for binary in binary2source_entity_mapping_simple_dict:
binary_number += 1
binary_function_mapping = binary2source_entity_mapping_simple_dict[binary]
for func_name in binary_function_mapping:
mapping_source_functions = binary_function_mapping[func_name]
if len(mapping_source_functions) > 1:
inline_function_number += 1
inline_source_function_number += len(mapping_source_functions)
source_function_number += len(mapping_source_functions)
function_number += 1
return [binary_number, function_number, inline_function_number, source_function_number,
inline_source_function_number] |
def lambda_handler(event, context):
"""
Lambda function that verifies a Cognito user creation automatically.
"""
event['response']['autoConfirmUser'] = True
if 'email' in event['request']['userAttributes']:
event['response']['autoVerifyEmail'] = True
if 'phone_number' in event['request']['userAttributes']:
event['response']['autoVerifyPhone'] = True
return event |
def get_value(obj, name):
"""Get value from object by name."""
if isinstance(obj, dict):
return obj.get(name)
return getattr(obj, name, obj) |
def not_none(passed, default):
"""Returns `passed` if not None, else `default` is returned"""
return passed if passed is not None else default |
def is_overlapped(peaks, chrom, start, end):
"""
check if the promoter of a gene is overlapped with a called peak
:param peaks:
:param chrom:
:param start:
:param end:
:return:
"""
for temp_list in peaks[chrom]:
if (temp_list[0] <= start and start <= temp_list[1] ) or (temp_list[0] <= end and end <= temp_list[1]) or \
(start <= temp_list[0] and temp_list[1] <= end):
return True
return False |
def heat_flux_to_temperature(heat_flux: float, exposed_temperature: float = 293.15):
"""Function returns surface temperature of an emitter for a given heat flux.
:param heat_flux: [W/m2] heat flux of emitter.
:param exposed_temperature: [K] ambient/receiver temperature, 20 deg.C by default.
:return temperature: [K] calculated emitter temperature based on black body radiation model.
"""
epsilon = 1.0 # radiation view factor
sigma = 5.67e-8 # [W/m2/K4] stefan-boltzmann constant
# E_dash_dash_dot = epsilon * sigma * (T_1 ** 4 - T_0 ** 4) # [W/m2]
return ((heat_flux / sigma / epsilon) + exposed_temperature ** 4) ** 0.25 |
def calculate_stations_adjoint(py, stations_path, misfit_windows_directory, output_directory):
"""
get the files STATIONS_ADJOINT.
"""
script = f"ibrun -n 1 {py} -m seisflow.scripts.shared.get_stations_adjoint --stations_path {stations_path} --misfit_windows_directory {misfit_windows_directory} --output_directory {output_directory}; \n"
return script |
def pad(data, blocksize=16):
"""
Pads data to blocksize according to RFC 4303. Pad length field is included in output.
"""
padlen = blocksize - len(data) % blocksize
return bytes(data + bytearray(range(1, padlen)) + bytearray((padlen - 1,))) |
def hash_string(value, length=16, force_lower=False):
""" Generate a deterministic hashed string."""
import hashlib
m = hashlib.sha256()
try:
m.update(value)
except TypeError:
m.update(value.encode())
digest = m.hexdigest()
digest = digest.lower() if force_lower else digest
while len(digest) < length:
digest = digest + digest
return digest[:length] |
def numberFormat(value: float, round: int = 2) -> str:
"""Formats numbers with commas and decimals
Args:
value (float): Number to format
round (int, optional): Number of decimals to round. Defaults to 2.
Returns:
str: String representation of formatted number
"""
num_format = "{:,." + str(round) + "f}"
return num_format.format(float(value)) |
def transform(subject_number, loop_size):
"""
>>> transform(17807724, 8)
14897079
>>> transform(5764801, 11)
14897079
"""
value = 1
loop = 0
while loop < loop_size:
value *= subject_number
value %= 20201227
loop += 1
return value |
def format_class_name(value):
"""
Example:
octree::OctreePointCloudVoxelCentroidContainer<pcl::PointXYZ> -> OctreePointCloudVoxelCentroidContainer_PointXYZ
"""
if "<" in value:
before = format_class_name(value[:value.find("<")])
inside = format_class_name(value[value.find("<") + 1:value.rfind(">")])
after = format_class_name(value[value.rfind(">")+1:])
return "_".join([v for v in (before, inside, after) if v])
elif "::" in value:
return value[value.rfind("::") + 2:]
else:
return value |
def sorted_distances(distances):
"""
This function sorted the distances between same relationship of two shapes Author: @Gautier
======================================= Parameter: @distances: dictionnary of distances between all two shapes,
like this {"smallTriangle-middleTriangle_11":[0.5], "smallTriangle-middleTriangle_21":[0.4]}
Output: a dictionary of distances between all two shapes but ordered by distance and rename keys by the number of
the same relation, example: {"smallTriangle-middleTriangle1":[0.4], "smallTriangle-middleTriangle2":[0.5]}
"""
data_distances = {"smallTriangle-smallTriangle": [], "smallTriangle-middleTriangle": [],
"smallTriangle-bigTriangle": [], "smallTriangle-square": [], "smallTriangle-parallel": [],
"middleTriangle-bigTriangle": [], "middleTriangle-square": [], "middleTriangle-parallel": [],
"bigTriangle-bigTriangle": [], "bigTriangle-square": [], "bigTriangle-parallel": [],
"square-parallel": []
}
keys = ["smallTriangle", "middleTriangle",
"bigTriangle", "square", "parallel"]
shape_list = []
for i in range(len(keys)):
for j in range(i):
shape_list.append(keys[j] + "-" + keys[i])
shape_list.append("smallTriangle-smallTriangle")
shape_list.append("bigTriangle-bigTriangle")
for key, value in distances.items():
for title in shape_list:
if title in key:
data_distances[title].append(value)
for title in shape_list:
data_distances[title] = sorted(data_distances[title])
if len(data_distances['smallTriangle-smallTriangle']) > 1:
del data_distances['smallTriangle-smallTriangle'][1]
if len(data_distances['bigTriangle-bigTriangle']) > 1:
del data_distances['bigTriangle-bigTriangle'][1]
sorted_data = {}
for key, value in data_distances.items():
if len(value) > 1:
for i in range(len(value)):
sorted_data[key + str(i + 1)] = value[i]
elif len(value) == 1:
sorted_data[key + str(1)] = value[0]
return sorted_data |
def create_story(story_list):
"""Create string of text from story_list."""
story = ' '.join(story_list)
print(story)
return(story) |
def string_to_list(string_list):
"""
string_list -> is a string in a list shape
e.g. '[1,2,False,String]'
returns list of parameters
"""
parameters = []
string_parameters = string_list.strip('[]').split(',')
for param in string_parameters:
try:
parameters.append(int(param))
except ValueError:
# If object is not integer try to convert it to boolean.
if param == 'True' or param == 'False':
parameters.append(param == 'True')
else:
# If object is not boolean then append string.
parameters.append(param)
return parameters |
def non_decreasing(values):
"""True if values are not decreasing."""
return all(x <= y for x, y in zip(values, values[1:])) |
def format_keyword(name):
"""
Get line alignment by 8 chars length
Parameters
----------
name : str
String for alignment
Returns
-------
out : str
8 chars length string
"""
return "{name: <8}".format(name=name.upper()) |
def _agg_scores_by_key(scores, key, agg_mode='mean'):
"""
Parameters
----------
scores: list or dict
list or dict of {'precision': ..., 'recall': ..., 'f1': ...}
"""
if len(scores) == 0:
return 0
if isinstance(scores, list):
sum_value = sum(sub_scores[key] for sub_scores in scores)
else:
sum_value = sum(sub_scores[key] for _, sub_scores in scores.items())
if agg_mode == 'sum':
return sum_value
elif agg_mode == 'mean':
return sum_value / len(scores) |
def infer_plot_type(model, **kwargs):
"""Infer the plot type. """
try:
model.h([0, 0])
return "binary_ones"
except:
# Error with 2d input vector.
pass
try:
model.h([0])
return "line"
except:
# Error with 1d input vector.
pass
return "unknown" |
def _get_ordered_motifs_from_tabular(data, index=1):
"""backend motif extraction function for motif_counts, motif_freqs and pssm
assumed index 1 are motif strings; motif returned in order of occurrence"""
chars = []
for entry in data:
if not entry[index] in chars:
chars.append(entry[index])
return chars |
def consistent_shapes(objects):
"""Determines whether the shapes of the objects are consistent."""
try:
shapes = [i.shape for i in objects]
return shapes.count(shapes[0]) == len(shapes)
except:
try:
lens = [len(i) for i in objects]
return lens.count(lens[0]) == len(lens)
except:
if isinstance(objects[0], (int, float)):
return True
return False |
def tofloat(v):
"""Check and convert a value to a floating point number"""
return float(v) if v != '.' else None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.