content stringlengths 42 6.51k |
|---|
def _filter_delays(alerts):
"""Select the subset of alerts which refer to delays."""
def is_not_low_impact(alert):
"""Returns true if the alert impact isn't from the minor categories."""
minors = ['Planned Reroute', 'Special Note', 'Bus Stop Relocation',
'Added Service', 'Pla... |
def check_relative_path(path: str):
"""Check if a path is valid as a web address. Returns True if valid, else raises different kinds of errors"""
value_error = ValueError(f"'{path}' (as a path) doesn't start with '/'.")
try:
if type(path) == str:
if path[0] == "/" or (path[0] == "^" and ... |
def non_none_values(*args):
"""Return True if all of the (non-None) elements are equal"""
return set(filter(lambda x: x is not None, args)) |
def fib_recursive(num):
"""
Finds the N-th fibonacci number recursively.
:param int num: The N-th fibonacci number (index).
:return: Computed number.
"""
if num < 2:
return num
return fib_recursive(num - 1) + fib_recursive(num - 2) |
def quickdict(json_map):
"""Quickly convert a mapping list to a dictionary."""
D = {}
for j in json_map:
D.update(j)
return D |
def int_to_mask(mask_int):
""" Convert int to mask
Args:
mask_int ('int'): prefix length is convert to mask
Returns:
mask value
"""
bin_arr = ["0" for i in range(32)]
for i in range(int(mask_int)):
bin_arr[i] = "1"
tmpmask = ["".join(bin_arr[i * 8: i *... |
def int_to_charset(val, charset):
""" Turn a non-negative integer into a string.
"""
if not val >= 0:
raise ValueError('"val" must be a non-negative integer.')
if val == 0: return charset[0]
output = ""
while val > 0:
val, digit = divmod(val, len(charset))
output += chars... |
def allocate(a_list:list, item):
"""
Append an item to a list, and return the new item's index in that list.
Too frequent an idiom not to abbreviate.
"""
idx = len(a_list)
a_list.append(item)
return idx |
def get_results_parameters(config: dict) -> tuple:
"""Returns recipe parameters after sanity check
:param dict config: parameters defined in the recipe settings
:raises: :class:`ValueError`: Missing parameters
:returns: Parameters
:rtype: tuple
"""
reference_column = config.get("user_refer... |
def clean_filename(filename):
"""Remove the .csv part of filename
Args:
filename (string): filepath/filename string
Returns:
string: filepath/filename with removed .csv
"""
temp = filename.split('.')
out = temp[0]
return out |
def format_math(expr):
"""Replace math symbols with HTML conterparts
:param expr: expression to format
:type expr: str
:returns: replaced string
"""
expr2 = expr.replace(".gt.", ">")
expr2 = expr2.replace(".geq.", ">=")
expr2 = expr2.replace(".lt.", "<")
expr2 = expr2.repl... |
def init(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return':0} |
def getIdFromOriginator(originator: str, idOnly: bool = False) -> str:
""" Get AE-ID-Stem or CSE-ID from the originator (in case SP-relative or Absolute was used)
"""
if idOnly:
return originator.split("/")[-1] if originator is not None else originator
else:
return originator.split("/")[-1] if originator is no... |
def get_vars(arg):
"""
Doc String
"""
if isinstance(arg, tuple):
lis = []
for elem in arg:
for val in get_vars(elem):
if val not in lis:
lis.append(val)
return lis
# return [v for e in arg for v in self.get_vars(e)]
elif... |
def parse_intent(dia_act):
""" parse intent """
intent_word = dia_act['intent']
intent = intent_word
if intent_word == 'inform':
if 'taskcomplete' in dia_act['slot_vals'].keys():
intent += '+taskcomplete'
elif 'request' in intent_word: # request intent
for slot ... |
def determine_color(number):
"""
In number ranges from 1 to 10 and 19 to 28, odd numbers are red and even are black.
In ranges from 11 to 18 and 29 to 36, odd numbers are black and even are red.
"""
if number >= 1 and number <= 10:
return "black" if number % 2 == 0 else "red"
elif number... |
def cumulative_sum(h):
"""find cumulative sum of a numpy array or a list"""
return [sum(h[:i + 1]) for i in range(len(h))] |
def in_orbit_idx_to_sat_idx(
sat_idx_in_orbit: int, orbit_idx: int, num_sat_per_orbit: int
) -> int:
"""Compute the satellite index in the constellation.
Starting from from the satellite index in the orbit and orbit index.
Args:
sat_idx_in_orbit: Index of the satellite inside its orbit.
... |
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
If the result is small enough to fit in an int, return an int.
Else return a long.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> facto... |
def clean_known_hosts(dns_name):
"""Command to remove the entry in known_hosts"""
return "sed -i.bak '/"+dns_name.lower()+"/d' ~/.ssh/known_hosts && rm ~/.ssh/known_hosts.bak\n" |
def detectGraphicsTwgoCancelled(frame):
"""Return an empty string if there is no cancelled message in this
graphical TWGO frame. Otherwise return string with cancellation details.
Args:
frame (dict): Contains a graphics TWGO frame.
Returns:
(str): '' if there is no cancellation associ... |
def backtrack(end, start, visited):
""" Return a tuple of nodes from `start` to `end` by recursively looking up
the current node in `visited`. `visited` is a dictionary of one-way edges
between nodes.
"""
path = [end]
node = end
while node != start:
node = visited[node]
path.... |
def file_urls_mutation(dataset_id, snapshot_tag, file_urls):
"""
Return the OpenNeuro mutation to update the file urls of a snapshot filetree
"""
file_update = {
'datasetId': dataset_id,
'tag': snapshot_tag,
'files': file_urls
}
return {
'query': 'mutation ($files... |
def describe_humidity(humidity):
"""Convert relative humidity into wet/good/dry description."""
if 30 < humidity <= 75:
description = "good"
elif humidity > 75:
description = "wet"
else:
description = "dry"
return description |
def human_format(num, pos=None):
""" Format large number using a human interpretable unit (kilo, mega, ...)
INPUT : num (int) -> the number to reformat
OUTPUT : num (str) -> the reformated number
"""
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
... |
def rotate_left(password: str, steps: int) -> str:
"""
Rotate the string, so each character moves the given number of steps to the left.
"""
for _ in range(steps):
password = password[1:] + password[0]
return password |
def substring(s, start, end):
"""
Return a slice of s based on start and end indexes (that can be None).
"""
startless = start is None
endless = end is None
if startless and endless:
return s
if endless:
return s[start:]
if startless:
return s[:end]
return s[s... |
def full_class_name(cls):
"""Get the fully qualified class name of an object class.
Reference: https://stackoverflow.com/a/2020083
"""
module = cls.__class__.__module__
if module is None or module == str.__class__.__module__:
return cls.__class__.__module__ # Avoid reporting __builtin__
... |
def substract_from(list1, list2, index):
"""list1 is longer than list2"""
new_list = list1
i = 0
for item in list2:
new_list[index + i] -= item
i += 1
return new_list |
def get_conv_outsize(size, k, s, p, cover_all=False, d=1):
"""Calculates output size of convolution.
This function takes the size of input feature map, kernel, stride, and
pooling of one particular dimension, then calculates the output feature
map size of that dimension.
.. seealso:: :func:`~chain... |
def count_occurrences(text: str) -> dict:
""" Counts the number of time that each different character appears in the
text.
:param text: the text to be coded
:return: a dictionary with each character of the text as a key and the
number of appearance of this character in the text in value
"""
... |
def add_default_value(arg_name, value, **kwargs):
""" Add argument if it is not in the kwargs already """
if arg_name not in kwargs.keys():
kwargs[arg_name] = value
return kwargs |
def round_down_to_nearest_power_of_2(input_num):
"""
Round up to nearest power of 2
Args:
input_num: input num
Returns: nearest power of 2
"""
if input_num > 1:
last_power = 1
for i in range(1, int(input_num)):
if 2 ** i > input_num:
return i... |
def api(uri):
"""
Given a URI that uses the ConceptNet API, such as "/c/en/test", get its
fully-qualified URL.
"""
return "http://api.conceptnet.io" + uri |
def vector_subtract(v, w):
"""subtracts two vectors componentwise"""
return [v_i - w_i for v_i, w_i in zip(v,w)] |
def SEARCH(find_text, within_text, start_num=1):
"""
Returns the position at which a string is first found within text, ignoring case.
Find is case-sensitive. The returned position is 1 if within_text starts with find_text.
Start_num specifies the character at which to start the search, defaulting to 1 (the fi... |
def _algo_fill_zi_if_missing(ro_rw_zi):
"""Create an empty zi section if it is missing"""
s_ro, s_rw, s_zi = ro_rw_zi
if s_rw is None:
return ro_rw_zi
if s_zi is not None:
return ro_rw_zi
s_zi = {
"sh_addr": s_rw["sh_addr"] + s_rw["sh_size"],
"sh_size": 0
}
re... |
def escape_like(value):
"""Escapes a string to be used as a plain string in LIKE"""
escape_char = '\\'
return (value
.replace(escape_char, escape_char * 2) # literal escape char needs to be escaped
.replace('%', escape_char + '%') # we don't want % wildcards inside the value
... |
def parse_metadata(section):
"""Given the first part of a slide, returns metadata associated with it."""
metadata = {}
metadata_lines = section.split('\n')
for line in metadata_lines:
colon_index = line.find(':')
if colon_index != -1:
key = line[:colon_index].strip()
val = line[colon_index +... |
def safe_delete_key(dictionary, key):
"""
Safely delete a key from a dictionary only if it exists
:param dictionary: the dictionary
:param key: the key to delete
:return: the dictionary
"""
try:
del dictionary[key]
except:
pass
return dictionary |
def check_amt(amt):
"""check if amount contains only integers.
"""
if not amt.isdigit():
return False
return True |
def get_request_link(name, service):
"""
Return a link to a request in a given service
"""
if service == 'mc':
return 'https://cms-pdmv.cern.ch/mcm/requests?prepid=%s' % (name)
if service == 'rereco_machine':
return 'https://cms-pdmv.cern.ch/rereco/requests?prepid=%s' % (name)
if... |
def is_path_removed(patch, path):
"""Returns whether the patch includes removal of the path (or subpath of).
:param patch: HTTP PATCH request body.
:param path: the path to check.
:returns: True if path or subpath being removed, False otherwise.
"""
path = path.rstrip('/')
for p in patch:
... |
def pull_choice_value(original_field_value, field_name, apps, model_name=None):
"""
Map display name to value for storing in db
"""
if original_field_value is None:
return ''
fetched_model = apps.get_model("accounts", model_name if model_name else "DemographicData")
choices = fetched_mod... |
def select_test_based_on_attributes( attrs1, attrs2, result ):
"""
Given the result attributes from two different executions of the same
test, this returns -1 if the first execution wins, 1 if the second
execution wins, or zero if the tie could not be broken. The 'result'
argument is None or a resu... |
def process_mutations(mutations):
"""Pack mutations into a dict
"""
processed_mutations = []
for mutation in mutations:
(_, (orientation, pos, (ref, alt))) = mutation
processed_mutations.append({
"orientation": orientation,
"pos": pos,
"ref": ref,
... |
def timeElapsed(seconds):
"""Time Elapsed
Returns seconds in a human readable format
Arguments:
seconds (uint): The seconds to convert to ((HH:)mm:)ss
Returns:
str
"""
# Get the hours and remaining seconds
h, r = divmod(seconds, 3600)
# Get the minutes and seconds
m, s = divmod(r, 60)
# Init the lis... |
def strtobool(val):
"""Convert a booleany str to a bool.
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
... |
def has_more_than_two_occurence(x):
"""creating a function for finding words with more than 2 occurences"""
if(x[1]>2):
return(x) |
def merge_conf(conf1, conf2):
"""
Merge two config dictionaries, with truthy values overriding falsy values.
`conf1` takes priority over `conf2`.
"""
return dict((str(key), conf1.get(key) or conf2.get(key))
for key in set(conf2) | set(conf1)) |
def get_spec_var(depth):
"""Returns the name of variable for spec with given depth."""
return "s" if depth == 0 else "s{}".format(depth) |
def hash_str(string: str) -> int:
"""
Create the hash for a string (poorly).
"""
hashed = 0
results = map(ord, string)
for result in results:
hashed += result
return hashed |
def file_by_type(file_list, ext):
"""
files_list -- list of files (e.g. from Ruffus)
ext -- file type to match (e.g. '.txt')
"""
filtered = [fname for fname in file_list if fname.endswith(ext)]
assert len(filtered) == 1, "Expect unique match"
return filtered[0] |
def GetRegionFromZone(zone):
"""Returns the GCP region that the input zone is in."""
return '-'.join(zone.split('-')[:-1]).lower() |
def get_typed_attr(obj, attr, _type, default=None):
"""
Typecasts an object's named attribute. If the attribute cannot be
converted, the default value is returned instead.
Parameters
----------
obj: Object
attr: Attribute
_type: Type
default: value, optional
"""
try:
... |
def markdownimage(img, width=1000):
"""Format the image embedding using the markdown notation.
:param str img: Relative path to the image.
:param int width: Width of the image.
:return: Markdown string.
"""
return '{:width="' + str(width) + '"}\n' |
def is_blackjack(card_one, card_two):
"""Determine if the hand is a 'natural' or 'blackjack'.
:param card_one, card_two: str - cards dealt. 'J', 'Q', 'K' = 10; 'A' = 11; numerical value otherwise.
:return: bool - if the hand is a blackjack (two cards worth 21).
"""
# sum = 0
# if card_... |
def munge_av_status(av_statuses):
"""Truncate and lowercase availability_status"""
return [a[20:].lower() for a in av_statuses] |
def value_or(value, default):
"""Returns default if value is exactly None."""
return value if value is not None else default |
def simplify(formula):
"""Simplify a formula
Replace half-turns [F2] with two quarter turns [F F], repeatedly remove
noops [F F']; replace triple rotations [F F F] with their corresponding
inverse single rotation [F']; and find non-interacting sandwiches [F B F']
and rearrange them [F F' B] for fut... |
def fill_value(keys, value):
"""
Return a dict with the given value assigned to each given key.
>>> fill_value([1, 2, 3], 'a')
{1: 'a', 2: 'a', 3: 'a'}
:param keys: keys, which returned dict should contains
:param value: value, which should be assigned to each key
:return: dict wit... |
def query_attr_where(params, table_ref=True):
"""
Construct where conditions when building neighbors query
Create portion of WHERE clauses for weeding out NULL-valued geometries
Input: dict of params:
{'subquery': ...,
'numerator': 'data1',
'denominator': ... |
def verify_headers(headers):
"""
Verify if headers dict includes 'Content-Type' key.
:param headers:
:return: True or False
"""
if headers is None:
return False
for key in headers:
if key.lower() == "content-type":
return True
return False |
def discrete_not_complementary(mgamma, p1, p2, p3, p4): #, alpha, beta
"""Define a discrete not complementary distribtuion.
mgamma: float which describes the mean value of this gamma distribution.
p1, p2, p3, p4: are the breakpoints of a discrete distribution
five bins, (the discrete DFE) with breaks at s = [0, 1... |
def GenerateAndroidResourceStringsXml(names_to_utf8_text, namespaces=None):
"""Generate an XML text corresponding to an Android resource strings map.
Args:
names_to_text: A dictionary mapping resource names to localized
text (encoded as UTF-8).
namespaces: A map of namespace prefix to URL.
Returns:... |
def _clean_line(wn, sec, line):
"""
Parameters
----------
wn: wntr.network.WaterNetworkModel
sec: str
line: list of str
Returns
-------
new_list: list of str
"""
if sec == '[JUNCTIONS]':
if len(line) == 4:
other = wn.options.hydraulic.pattern
... |
def IPToInteger(ip):
"""Convert a string dotted quad IP address to an integer
Args:
ipStr: the IP address to convert
Returns:
The IP address as an integer
"""
pieces = ip.split(".")
return (int(pieces[0]) << 24) + (int(pieces[1]) << 16) + (int(pieces[2]) << 8) + int(pieces[3]) |
def group_patients(patients):
"""Group patients by their label."""
n_labels = len({p.label for p in patients})
groups = [[p for p in patients if p.label == i] for i in range(n_labels)]
return groups |
def get_street(yishuv_symbol, street_sign, streets):
"""
extracts the street name using the settlement id and street id
"""
if yishuv_symbol not in streets:
# Changed to return blank string instead of None for correct presentation (Omer)
return ""
street_name = [
x["SHEM_RECH... |
def sort(item, boolean=False):
"""Arranges the secret word letters in alphabetical order"""
char_list = []
for x in item:
if x in char_list:
continue
elif x in [' ', '-']:
continue
elif x == item[0] or x == item[len(item) - 1]:
if boolean is True:
... |
def prepend(txt: str, prefix: str) -> str:
"""
Add `prefix` before each line of the string `txt`.
"""
lines = [prefix + curr_line for curr_line in txt.split("\n")]
res = "\n".join(lines)
return res |
def merge_dicts(a, b, allow_key_overlap=True):
"""
Returns a dict that merges a and b. Entries of b take priority over entries of a.
"""
if not allow_key_overlap:
k = set(a.keys()).intersection(b.keys())
assert len(k) == 0
out = {k: v for (k, v) in a.items()}
out.update(b)
r... |
def clean_value(value):
"""
To ensure the computed dataframe is consistently typed all values are
co-erced to float or we die trying...
"""
if isinstance(value, (int, float)):
return float(value)
if value is None:
return None
# else str...
value = value.rstrip('%')
va... |
def path_relativa(_arquivo: str) -> str:
"""
extrai a path relativa de um arquivo
:param _arquivo: str
:return: str
"""
return _arquivo.split('/')[-2] + '/' + _arquivo.split('/')[-1] |
def is_iter(obj):
"""
Checks if an object behaves iterably.
Args:
obj (any): Entity to check for iterability.
Returns:
is_iterable (bool): If `obj` is iterable or not.
Notes:
Strings are *not* accepted as iterable (although they are
actually iterable), since string... |
def get_auc(labels, preds, n_bins=10000):
"""ROC_AUC"""
postive_len = sum(labels)
negative_len = len(labels) - postive_len
total_case = postive_len * negative_len
if total_case == 0:
return 0
pos_histogram = [0 for _ in range(n_bins+1)]
neg_histogram = [0 for _ in range(n_bins+1)]
... |
def remove_non_ascii(text: str) -> str:
""" Removes non ascii characters
:param text: Text to be cleaned
:return: Clean text
"""
return ''.join(char for char in text if ord(char) < 128) |
def app_config(app_config):
"""Customize application configuration."""
app_config[
'FILES_REST_STORAGE_FACTORY'] = 'invenio_s3.s3fs_storage_factory'
app_config['S3_ENDPOINT_URL'] = None
app_config['S3_ACCESS_KEY_ID'] = 'test'
app_config['S3_SECRECT_ACCESS_KEY'] = 'test'
return app_config |
def emplace_kv(dictionary: dict, k, v) -> dict:
"""
Returns input dict with added k:v pair, overwriting if k already exists
"""
return {**dictionary, k: v} |
def assign_unit_weights(edge_list):
"""
@param edge_list a list with entries of the form (s, t, w),
where s and t are the two endpoints of an edge and w is the weight
@return a modified list with all weights equal to 1
"""
return [(e[0], e[1], 1) for e in edge_list] |
def _align_indices(data, order, axis=1):
"""Align the indices/ columns in a collection of pandas objects to order"""
for i in range(len(data)):
if data[i] is not None:
data[i] = data[i].reindex(order, axis=axis)
return data |
def random(previous_result):
"""A pseudo-random number generator used (B.B.S) since random can't be imported"""
m = 11 * 23
return previous_result ** 2 % m |
def read_hex_digit(char: str) -> int:
"""Read a hexadecimal character and returns its positive integer value (0-15).
'0' becomes 0, '9' becomes 9
'A' becomes 10, 'F' becomes 15
'a' becomes 10, 'f' becomes 15
Returns -1 if the provided character code was not a valid hexadecimal digit.
"""
i... |
def AndroidSdkFindPackage(packages, key):
"""
Args:
packages: list of (id-num, id-key, type, description).
key: (id-key, type, description-prefix).
"""
(key_id, key_type, key_description_prefix) = key
for package in packages:
(package_num, package_id, package_type, package_description) =... |
def int_to_bool(value):
"""Convert integer string {"0","1"} to its corresponding bool"""
try:
return bool(int(value))
except ValueError:
raise TypeError('must supply integer string') |
def get_provenance_record(project, ancestor_files):
"""Create a provenance record describing the diagnostic data and plot."""
record = {
'caption':
('Equilibrium climate sensitivity (ECS) against the global '
'mean surface temperature of {} models, both for the '
'period 1961-1... |
def ComputeSemiMinorAxis( efit, smarange=None ):
"""For Bender-style ellipse-fits only!
Re-computes semi-minor axis b, based on ellipticity and semi-major axis.
Optionally, the range of semi-major axes for which b is recomputed can be
specified via smarange (only semi-major axis values >= smarange[0] an... |
def always_defect(p, p_other_lag, p_own_lag, rounder_number):
"""
Return 1 if price corresponds to defection at
the stage game Nash equilibrium and 0 else.
"""
return 1 if p == 1 else 0 |
def _is_probably_elf(filename):
"""Heuristically decides whether |filename| is ELF via magic signature."""
with open(filename, 'rb') as fh:
return fh.read(4) == '\x7FELF' |
def reverse(s):
""" (str) -> str
Return s reversed.
>>> reverse('hello')
'olleh'
"""
s_reversed = ''
for ch in s:
s_reversed = ch + s_reversed
return s_reversed |
def abbreviate_list_as_str(ls):
"""
Abbreviates a list when it's too long to show everything
Used mostly in logging.DEBUG
"""
n = len(ls)
if n > 4:
return f"{str(ls[:2])[:-1]},\n...\n{str(ls[-2:])[1:]}"
else:
return f"{str(ls)}" |
def _adjust_component(component: int) -> int:
""" Developed by Trong Nguyen, 100848232
Reviewed by Ahmed Abdellah, 101163588
Return the midpoint value of the quadrant in which an input component
lies as defined by the range of 0 to 255, inclusive in four equal-size
quadrants.
... |
def compare_list(x, y):
"""
Compare lists by content. Ordering does not matter.
Returns True if both lists contain the same items (and are of identical
length)
"""
cmpx = [set(cluster) for cluster in x]
cmpy = [set(cluster) for cluster in y]
all_ok = True
for cset in c... |
def leap_year_finder(year: int) -> bool:
"""Return True if input integer year is leap year."""
if year % 4 == 0 and (year % 100 != 0 or year % 400) == 0:
return True
else:
return False |
def _ws_defaults(data):
"""Set some defaults for the required workspace fields."""
defaults = {
"owner": "owner",
"max_obj_id": 1,
"lock_status": "n",
"name": "wsname",
"mod_epoch": 1,
"is_public": True,
"is_deleted": False,
"metadata": {"narrative... |
def to_binary(int_digit, length=4):
"""Convert a digit into binary string.
Arguments:
int_digit {str} -- the digit needed to be convert
Keyword Arguments:
length {int} -- length of converted string (default: {4})
Returns:
str -- a string with specific length converted from int... |
def centroid(vertsList):
"""
This function returns the baricenter of a set of Blender vertices,
returning a coordinate vector formatted as a float list
[float X,float Y, float Z].
This is the sum of all of the vectors divided by the number of vectors.
Parameters
----------
vertsList:
... |
def string_in_list(str, substr_list):
"""Returns True if the string appears in the list."""
return any([str.find(x) >= 0 for x in substr_list]) |
def count_transcriptome_length(results):
"""
:param results: list of peak_dicts
:return: total transcriptome_length
:rtype: int
"""
transcriptome_length = 0
for gene_result in results:
if gene_result is not None:
transcriptome_length += int(gene_result['loc'].attrs['effe... |
def level_states_full_space(level, dimension):
"""
Creates a list of all states in ``level``.
Parameters
----------
level : int
Level of the state space.
dimension : int
Number of clonotypes.
Returns
-------
state_list : list
List of all states in level.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.