content stringlengths 42 6.51k |
|---|
def year2Century(year):
"""
year to century
"""
str_year = str(year)
if(len(str_year)<3):
return 1
elif(len(str_year) == 3):
if(str_year[1:3] == "00"): # 100 ,200 300, 400 ... 900
return int(str_year[0])
else: # 190, 250, 450
... |
def join_opening_bracket(lines):
"""When opening curly bracket is in it's own line (K&R convention), it's joined with precluding line (Java)."""
modified_lines = []
for i in range(len(lines)):
if i > 0 and lines[i] == "{":
modified_lines[-1] += " {"
else:
modified_lin... |
def parse_attribute(attribute):
"""
Convert GTF entry attribute to dictionary
"""
data = attribute.strip(';').split(';')
data = [d.strip() for d in data]
pairs = [d.split() for d in data]
attribute_dict = {k: v.strip('"') for k, v in pairs}
return attribute_dict |
def write_trapezoid(base1, base2, height, length, loc, mat, orPhi=0.0, orTheta=90.0, uvecs=[], pols=[], eps=1.0, mu=1.0, tellegen=0.0):
"""
@brief Writes a trapezoid.
@param base1 bottom base of the trapezoid
@param base2 top base of the trapezoid
@param height height... |
def separate_strings_from_dicts(elements):
"""
Receive a list of strings and dicts an returns 2 lists, one solely with string and the other
with dicts.
:param List[Union[str, Dict[str, str]]] elements:
:rtype: Tuple[List[str], List[Dict[str, str]]]
"""
all_strs = []
all_dicts = []
f... |
def first_index(lst, predicate):
"""Return the index of the first element that matches a predicate.
:param lst: list to find the matching element in.
:param predicate: predicate object.
:returns: the index of the first matching element or None if no element
matches the predicate.
"""
... |
def calc_install(runs, cost_index, system_index, tax_rate):
"""
Calculate total install cost for a manufacturing job.
:param runs: Number of runs in the job.
:param cost_index: Cost Index for the item.
:param system_index: Cost Index for the star system where construction
would occur.
... |
def get_test_submission_case(case_obj):
"""Returns a test casedata submission object"""
casedata_subm_obj = {
'_id' : "{}_a99ab86f2cb3bc18b993d740303ba27f_subj1".format(case_obj['_id']),
'csv_type': "casedata",
'case_id' : case_obj['_id'],
'linking_id' : "a99ab86f2cb3bc18b993d74... |
def lcore_core_ids(lcore_mask_host):
""" Convert CPU ID mask from argument 'lcore_mask' to a list of CPU IDs """
lcore_cores = []
binary_mask = bin(int(lcore_mask_host, 16))[2:]
for i, val in enumerate(binary_mask[::-1]):
if val == "1":
lcore_cores.append(i)
return lcore_cores |
def filter_string(filtr):
"""
Filter function to remove invalid characters
:param filtr:
:return:
"""
return "".join(x for x in filtr if x.isalpha()) |
def concat(L):
"""
tools for concat new dataframe
"""
result = None
for l in L:
if l is None:
continue
if result is None:
result = l
else:
try:
result[l.columns.tolist()] = l
except Exception as err:... |
def print_error(p, i):
"""
Returns the error message for package installation issues.
:param str p: The name of the package to install.
:param str i: The name of the package when imported.
"""
error_message = f"""
{i} not present. Please do the installation using either:
- pip install ... |
def is_image(ext):
"""
Checks if the file_format is a supported image to read.
:param ext: the extension of a file.
:return: whether or not the file is a image
"""
return ext == '.jpeg' or ext == '.png' or ext == '.jpg' or ext == '.bmp' |
def simplified_value_difference(attribute, category0, category1, categorical_class_probability_dict, exponent=1):
"""Return the simplified value difference between the two passed categories, checking the passed dictionary of class-given-category probabilities"""
# equal categories have no distance
if cate... |
def separate_elements(list1, list2):
"""Check of different values of two lists"""
print(f"Liste 1: {len(list1)}")
print(f"Liste 2: {len(list2)}")
print("\n")
print(f"Separate elements: ")
return list(set(list1) ^ set(list2)) |
def _is_int(string):
"""Returns true or false depending on whether or not the passed in string can be converted to an int"""
result = False
try:
value = int(string)
result = True
except ValueError:
result = False
return result |
def pop_highest(l):
"""doc"""
# warning, pass-by-ref so WILL modify input arg
return l.pop() if l[-1] >= l[0] else l.pop(0) |
def enforce_excel_cell_string_limit(long_string, limit):
"""
Trims a long string. This function aims to address a limitation of CSV
files, where very long strings which exceed the char cell limit of Excel
cause weird artifacts to happen when saving to CSV.
"""
trimmed_string = ... |
def sig_refine(sig):
""" To correct deformed signture patterns. e.g., signatures contains
spaces.
"""
sig = sig.replace(' ', '')
return sig |
def much_greater_than(lhs, rhs, r=0.2):
"""
Determine if lhs >> rhs
:param lhs: Left side of the comparison
:param rhs: Right side of the comparison
:param r: Ratio to use for comparison
:returns True: If the ratio of lhs-to-rhs < r
:returns False: Otherwise
:rtype: bool
"""
if ... |
def get_bearing_difference(bearing1, bearing2):
"""
Given two bearings, returns the angle between them
"""
return (((bearing1 - bearing2) + 180) % 360) - 180 |
def encode_color(color, n_bits):
"""
If color is given as boolean, interpret it as maximally on or totally off.
Otherwise check whether it fits within the number of bits.
"""
if isinstance(color, bool):
return (2 ** n_bits - 1) * color
elif 0 <= color < 2 ** n_bits:
return color
... |
def replace_all(text, dic):
""" replaces multiple strings based on a dictionary
replace_all(string,dictionary) -> string
"""
for i, j in dic.items():
text = text.replace(i, str(j))
return text |
def format_device(region=None, zone=None, ip=None, device=None, **kwargs):
"""
Convert device dict or tier attributes to a representative string.
:returns: a string, the normalized format of a device tier
"""
return "r%sz%s-%s/%s" % (region, zone, ip, device) |
def imc(peso: float, estatura: float) -> float:
"""Devuele el IMC
:param peso: Peso en kg
:peso type: float
:param estatura: Estatura en cm
:estatura type: float
:return: IMC
:rtype: float
>>> imc(78, 1.83)
23.29
"""
return round(peso/(estatura**2), 2) |
def get_data(method_name, file_metadata):
"""
Return the method data containing in the file metadata.
"""
for data in file_metadata:
if (method_name == data[1]):
return data |
def _parse_single_arg(function_name, additional_parameter, args, kwargs):
"""
Verifies that a single additional argument has been given (or no
additional argument, if additional_parameter is None). Also
verifies its name.
:param function_name: the name of the caller function, used for
the o... |
def _fix_page(page: dict) -> dict:
"""
Fix a page dict as returned by the API.
:param page:
:return:
"""
# Some (all?) pages with a number as their title have an int in this field.
# E.g. https://fr.wikipedia.org/wiki/2040.
if "page_title" in page:
page["page_title"] = str(page["... |
def _days_before_year(year):
"""year -> number of days before January 1st of year."""
y = year - 1
return y * 365 + y // 4 - y // 100 + y // 400 |
def get_illust_url(illust_id: int) -> str:
"""Get illust URL from ``illust_id``.
:param illust_id: Pixiv illust_id
:type illust_id: :class:`int`
:return: Pixiv Illust URL
:rtype: :class:`str`
"""
return (
'https://www.pixiv.net/member_illust.php'
'?mode=medium&illust_id={}'... |
def pull_top(piles, pos):
"""
Pulls the top card of pile number `pos`,
and returns the new set of piles.
Example:
> pull_top([[1,2,3], [], [4,5,6], [7,8,9]], 2)
[[1,2,3], [], [4,5], [7,8,9]]
"""
rest = piles[:]
rest[pos] = piles[pos][:-1]
return rest |
def shootoutkey(row, col1=None, coldiff=None):
"""Calculate key for sorting a shootout.
row - a tuple (testname, results) where results is [(passing, ...), ...]
and passing is a truthy or falsy value.
col1 and col2 - indices into results
Return a tuple (col12same, col1fail, failcount) where
- col1fail is 0 if res... |
def get_provenance_record(project, ancestor_files):
"""Create a provenance record describing the diagnostic data and plot."""
record = {
'caption':
(f'Transient climate response (TCR) against equilibrium climate '
f'sensitivity (ECS) for {project} models.'),
'statistics': ['mean... |
def get_access_set(access, set):
"""Get access set."""
try:
return access[set]
except KeyError:
return [] |
def dms_deg(degree_tuple):
"""
Convert degree minute' second'' to decimal angle
:param degree_tuple: (degree, minute, second) tuple
:return: Decimal angle in degrees
Example:
>>> import units as u
>>>
>>> u.dms_deg((45, 23, 34))
45.39277777777778
... |
def _pack_into_dict(value_or_dict, expected_keys, allow_subset = False):
"""
Used for when you want to either
a) Distribute some value to all predictors
b) Distribute different values to different predictors and check that the names match up.
:param value_or_dict: Either
a) A value
... |
def subst_variables_in_str(line: str, values: dict, start_char: str = "%") -> object:
"""
Replace variables inside the specified string
:param line: String to replace the variables in.
:param values: Dictionary, holding variables and their values.
:param start_char: Character used to i... |
def legacy_convert_time(float_time):
"""take a float unix timestamp and convert it into something legacy Session likes"""
return int(float_time * 1000) |
def map_colnames(row, name_map):
"""Return table row with renamed column names according to `name_map`."""
return {
name_map.get(k, k): v
for k, v in row.items()} |
def create_bm_dictionary(name, federate_count, core_type, real_time, cpu_time, threads):
"""This function creates a dictionary for a single benchmark
run.
Args:
name (str) - The name of the benchmark, e.g. BMecho_singleCore
federate_count (int) - The number of federates.
core_type ... |
def order_by_leaves(list_graph):
"""
list_graph: A list of list of graphs.
Creates a new list of lists of graphs by dividing the previous lists depending on the number of leaves in each graph.
Returns the new list.
"""
C_l = []
for graph in list_graph:
k = len(graph.leaves())
if len(C_l) < k:
for i in ran... |
def addNamespaceToName(name, namespace):
"""
Args:
name:
namespace:
Returns:
"""
return namespace + "::" + name |
def split_url(url):
"""Splits the given URL into a tuple of (protocol, host, uri)"""
proto, rest = url.split(':', 1)
rest = rest[2:].split('/', 1)
host, uri = (rest[0], rest[1]) if len(rest) == 2 else (rest[0], "")
return (proto, host, uri) |
def enlarge_name(name):
"""Enlarges a parkour room name."""
if name[0] == "*":
return "*#parkour" + name[1:]
else:
return name[:2] + "-#parkour" + name[2:] |
def to_xml_name(name):
"""Convert field name to tag-like name as used in QuickBase XML.
>>> to_xml_name('This is a Field')
'this_is_a_field'
>>> to_xml_name('800 Number')
'_800_number'
>>> to_xml_name('A & B')
'a___b'
>>> to_xml_name('# of Whatevers')
'___of_whatevers'
"""
xm... |
def _aprime(pHI,pFA):
"""recursive private function for calculating A'"""
pCR = 1 - pFA
# use recursion to handle
# cases below the diagonal defined by pHI == pFA
if pFA > pHI:
return 1 - _aprime(1-pHI ,1-pFA)
# Pollack and Norman's (1964) A' measure
# formula from Grier 1971
i... |
def compute_fixed_points(m, n, L):
"""
Find the fixed points of the BCN.
A state is called a fixed point if it can transit to itself by a certain input.
"""
M = 2 ** m
N = 2 ** n
fps = []
for i in range(1, N + 1):
for k in range(1, M + 1):
blk = L[(k - 1) * N: k * N]
... |
def unique_characters(input_str: str) -> bool:
"""Returns true if a string has all unique characters using a dict.
Args:
input_str: Input string
Returns:
Returns True if a string has all unique characters.
"""
seen_chars = {}
for char in input_str:
if char in seen_chars... |
def delta_temperature(wavelength, length, dn=1.87e-4):
"""Return the delta temperature for a pi phase shift on a MZI interferometer."""
return wavelength / 2 / length / dn |
def shuffle_first_axis(arrays):
"""
Shuffle a (possible) multi-dimensional list by first axis
"""
import random
random.shuffle(arrays)
return arrays |
def validate_coin_choice(selection, unique_cans):
"""Translates user menu selection into the name of can that was chosen. No errors."""
if 0 < selection <= len(unique_cans):
return True, unique_cans[selection - 1].name
else:
print("Not a valid selection\n")
return False, None |
def find_nearest_multiple(num, n):
"""Find the nearest multiple of n to num
1. num: a number, num must be larger than n to have a meaningful result.
2. n : a number to be multipled
"""
return int(round(num / n)) * n |
def sqnorm(v):
"""Compute the square euclidean norm of the vector v."""
res = 0
for elt in v:
for coef in elt:
res += coef ** 2
return res |
def bytes_to_hex(bs):
"""
Convert a byte string to an hex string.
Parameters
----------
bs: bytes
byte string
Returns
-------
str: hex string
"""
return ''.join('%02x' % i for i in bs) |
def ignore_escape(path: str) -> str:
"""
Escape a path appropriately for a docker ignore file.
"""
special_chars = "\\*?[]"
return "".join("\\" + ch if ch in special_chars else ch for ch in path) |
def get_odd_numbers(num_list: list) -> list:
"""Returns a list of odd numbers from a list."""
return [num for num in num_list if num % 2 != 0] |
def choices(x):
"""
Takes a list of lists x and returns all possible choices of one element from each sublist.
>>> choices([range(2), range(3), ["foo"]])
[ [0, 0, "foo"], [0, 1, "foo"], [0, 2, "foo"], [1, 0, "foo"], [1, 1, "foo"], [1, 2, "foo"] ]
"""
if len(x) == 0:
return [[]]
else:
res = [... |
def recall(ground_truth_permutated, **kwargs):
"""
Calculate the recall at k
@param ground_truth_permutated: Ranked results with its judgements.
"""
rank = ground_truth_permutated
limit = kwargs.get('limit', len(ground_truth_permutated))
nrel = float(kwargs.get('nrel', len(ground_truth_permu... |
def parse_similar_words(similar_words_file):
"""
as produced by similar_words_batch.py
"""
similar_words = {}
word = ""
for line in open(similar_words_file, "r"):
if line == "----------------------------------------------------\n":
word = ""
elif word == "":
... |
def prepare_dict(hermes_dict):
"""
Prepare a rhasspy type like dict from a hermes intent dict
"""
intent = hermes_dict["intent"]["intentName"]
out_dict = {}
out_dict.update({"slots": {s["slotName"]:s["rawValue"] for s in hermes_dict["slots"]}})
out_dict["intent"] = {"name": intent}
retur... |
def _DiskSize(value):
"""Returns a human readable string representation of the disk size.
Args:
value: str, Disk size represented as number of bytes.
Returns:
A human readable string representation of the disk size.
"""
size = float(value)
the_unit = 'TB'
for unit in ['bytes', 'KB', 'MB', 'GB']:... |
def norm_angle_diff(angle_in_degrees):
"""Normalize the difference of 2 angles in degree.
This function is used to normalize the "delta psi" angle.
"""
return abs(((angle_in_degrees + 90) % 180) - 90.) |
def _process_iss_arg(arg_key, arg_val):
"""Creates a list with argument and its value.
Argument values represented by a list will be converted to a single
string joined by spaces, e.g.: [1, 2, 3] -> '1 2 3'.
Argument names will be converted to command line parameters by
appending a '--' prefix, e.g... |
def _romberg_diff(b, c, k):
"""
Compute the differences for the Romberg quadrature corrections.
See Forman Acton's "Real Computing Made Real," p 143.
"""
tmp = 4.0**k
return (tmp * c - b)/(tmp - 1.0) |
def problem_1_4(s: str) -> str:
"""
replace all spaces in a string with %20
>>> problem_1_4("foo bar ")
'foo%20bar'
>>> problem_1_4("a s")
Traceback (most recent call last):
...
ValueError: Size of provided string is incorrect
"""
from collections import deque
response = ... |
def get_identifiers_given_scope_of_selection(available_idfs_in_scopes: dict, scope_of_selection: str,
target_function_range: str) -> set:
"""
Given identifiers in different scopes and the scope of selection,
get the list of possible Identifiers that may be used a... |
def splitList(inputList, bins = None, preserveOrder = False):
"""Split a list into sublists and return the list of sublists.
Args:
inputList: The list to be split
bins: The number of bins. Overrides cpu_count()
preserveOrder: if true, append to each sublist in list order, otherwise round rob... |
def fresnel_criterion(W, z, wav):
"""
determine the frensel number of a wavefield propagated over some distance z
:param W: approx. beam/aperture size [m]
:param z: propagation distance [m]
:param wav: source wavelength [m]
:returns F: Fresnel number
"""
F = W**2/(z*wav)
return F |
def process(data, template_name_key, **kwargs):
"""
Function to process multitemplate data items.
:param data: (list), data to process - list of dictionaries
:param template_name_key: string, name of the template key
"""
ret = []
headers = tuple()
previous_headers = tuple()
head... |
def create_article_institute_links(article_id, institute_ids, score):
"""Creates data for the article/institutes association table.
There will be multiple links if the institute is multinational, one for each country
entity.
Args:
article_id (str): arxiv id of the article
institute_ids ... |
def _byteshr(bytes):
"""Human-readable version of bytes count"""
for x in ['bytes','KB','MB','GB','TB']:
if bytes < 1024.0:
return "%3.1f%s" % (bytes, x)
bytes /= 1024.0
raise ValueError('cannot find human-readable version') |
def __span_overlap__(span1, span2):
"""
"""
if (span1[0] <= span2[1]) & (span2[0] <= span1[1]):
return True
else:
return False |
def get_colnames(main_colnames=None, error_colnames=None, corr_colnames=None,
cartesian=True):
"""
Utility function for generating standard column names
Parameters
----------
main_colnames: [6] str array_like {None}
The column names of the measurements. If left as None then... |
def find_dist(mol_1_x, mol_1_y, mol_1_z, mol_2_x, mol_2_y, mol_2_z):
"""Function to find the square distance between two points in 3D
Takes two len=3 tuples
Returns a float"""
return (
pow((mol_1_x - mol_2_x), 2)
+ pow((mol_1_y - mol_2_y), 2)
+ pow((mol_1_z - mol_2_z), 2)
) |
def connected_components(edges):
"""
Computes the connected components.
@param edges edges
@return dictionary { vertex : id of connected components }
"""
res = {}
for k in edges:
for _ in k[:2]:
if _ not in res:
res[_] = _
m... |
def hard_dedupe(s):
"""Takes in a string, and returns a string where only the first occurrence of each letter is retained. So the string 'abccba' goes to 'abc'. The empty string returns the empty string."""
seen = set()
ans = ''
for char in s:
if char in seen:
continue
seen.a... |
def is_blank_line(line, allow_spaces=0):
"""is_blank_line(line, allow_spaces=0) -> boolean
Return whether a line is blank. allow_spaces specifies whether to
allow whitespaces in a blank line. A true value signifies that a
line containing whitespaces as well as end-of-line characters
should be con... |
def get_ids(patients):
"""the ids may be different for different trees, fix it"""
ids = []
for name in patients:
try:
ids.append(name.split('|')[1])
except:
ids.append(name)
return ids |
def error_porcentual(experimental: float, aceptado: float) -> str:
"""
Calcular error porcentual de un resultado experimental obtenido con
respecto al aceptado
"""
porcentaje = abs(((aceptado - experimental) / aceptado) * 100)
return "{:.8f}%".format(porcentaje) |
def histogramm(values):
"""Compute the histogramm of all values: a dictionnary dict[v]=count"""
hist = {}
for v in values:
if v in hist:
hist[v]+=1
else:
hist[v]=1
return hist |
def is_in_container(device, container="undefined_container"):
"""
Check if device is attached to given container.
Parameters
----------
device : dict
Device information from cv_facts
container : str, optional
Container name to check if device is attached to, by default 'undefine... |
def _get_haddock_path(package_id):
"""Get path to Haddock file of a package given its id.
Args:
package_id: string, package id.
Returns:
string: relative path to haddock file.
"""
return package_id + ".haddock" |
def compute_best_test_losses(data, k, total_queries):
"""
Given full data from a completed nas algorithm,
output the test error of the arch with the best val error
after every multiple of k
"""
results = []
for query in range(k, total_queries + k, k):
best_arch = sorted(data[:query]... |
def rgb2hex(r,g,b):
"""
Convert a RGB vector to hexadecimal values
"""
hexfmt = "#%02x%02x%02x"%(r,g,b)
return hexfmt |
def func_name(func):
"""
Return func's fully-qualified name
"""
if hasattr(func, "__module__"):
return "{}.{}".format(func.__module__, func.__name__)
return func.__name__ |
def scale(val, src, dst):
"""
Scale the given value from the scale of src to the scale of dst.
val: float or int
src: tuple
dst: tuple
example: print(scale(99, (0.0, 99.0), (-1.0, +1.0)))
"""
return (float(val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0] |
def _text2int(text_num, num_words=None):
"""
Function that takes an input string of a written number (in English) to translate it to
the respective integer.
:param text_num: string of a written number (in English)
:param num_words: optional dictionary to add containing text number (keys) and respect... |
def get_index(string, list):
"""
Return index of string in list.
"""
return [i for i, s in enumerate(list) if string in s][0] |
def to_localstack_url(api_id: str, url: str):
"""
Converts a API GW url to localstack
"""
return url.replace("4566", f"4566/restapis/{api_id}").replace(
"dev", "dev/_user_request_"
) |
def double_times_3(w):
"""
Check if two three consecutive double characters are present.
Return False if otherwise.
"""
l = 0
if len(w) < 6:
return False
while l < len(w) - 5:
if w[l] == w[l+1]:
if w[l+2] == w[l+3]:
if w[l+4] == w[l+5]:
... |
def _set_block_title(reaction):
""" Update the string for the figure title
"""
side_lst = []
for side in reaction:
side_lst.append('+'.join(side))
title = '{0:^60s}'.format(
side_lst[0]+'='+side_lst[1])
return title |
def validate1(recipe):
"""
@param recipe is a list from the list of lists (PBJSammies, GCSammies)
@return whether this recipe is a SuperSammie
"""
# we don't want plain sandwiches!
if len(recipe) <= 2:
return False
else:
return True |
def rotate(table, mod):
"""Rotate a list."""
return table[mod:] + table[:mod] |
def is_sequence(argument):
"""Check if argument is a sequence."""
return (
not hasattr(argument, "strip") and
not hasattr(argument, "shape") and
(hasattr(argument, "__getitem__") or hasattr(argument, "__iter__"))
) |
def autoname(cls):
"""Decorator that automatically names class items with autoname properties
An autoname property is made with the :func:`autoname_property` decorator,
like this::
>>> @autoname_property('name')
... class MyDescriptor:
... def __get__(self, instance, owner=None)... |
def _hamming_distance(x_param: int) -> int:
"""
Calculate the bit-wise Hamming distance of :code:`x_param` from 0.
The Hamming distance is the number 1s in the integer :code:`x_param`.
:param x_param: A non-negative integer.
:return: The hamming distance of :code:`x_param` from 0.
"""
tot ... |
def _tag_string_to_list(tag_string):
"""This is used to change tags from a sting to a list of dicts.
"""
out = []
for tag in tag_string.split(u','):
tag = tag.strip()
if tag:
out.append({u'name': tag, u'state': u'active'})
return out |
def format_entities(entities):
"""
formats entities to key value pairs
"""
## Should be formatted to handle multiple entity values
# e = {"day":None,"time":None,"place":None}
e = {}
for entity in entities:
e[entity["entity"]] = entity["value"]
return e |
def _add_padding(data: str, width: int, padding_char: str = ' ') -> str:
"""Return data with added padding for tabulation using given width."""
return data + padding_char*(width - len(data)) |
def list_of_lines(s):
"""
A post-processor function that splits a string *s* (the stdout output of a)
command in a list of lines (newlines are removed).
:rtype: a list of lines (str)
"""
return s.split('\n') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.