content stringlengths 42 6.51k |
|---|
def linmag(vali, magstart, magend, dur):
"""
Generates a ramp of values that is linear in magnification.
**Parameters**
vali: *float*
The initial y value at the start of the ramp.
magstart: *float*
The magnification at the start of the ramp.
magend: *float*
The magnif... |
def evaluate_compound(demand, price):
"""
Evaluate compound.
Parameters
----------
demand : number
Compound demand.
price : number
Compound price.
Returns
-------
number
Value of the compound.
Raises
------
TypeError
If demand or price a... |
def norma_vector(vector:list):
"""
Funcion que realiza la norma de un vector complejo.
:param vector: Lista que representa el vector complejo.
:return: Lista que representa la norma del vector complejo.
"""
fila = len(vector)
columna = len(vector[0])
magnitud = 0
for i in ra... |
def difference_count(a,b):
""" Return the number of differences between A and B. """
diffs = 0
z = zip(a,b)
for x, y in z:
if x != y:
diffs += 1
return diffs |
def find_binary_of_command(candidates):
"""
Calls `find_executable` from distuils for
provided candidates and returns first hit.
If no candidate mathces, a RuntimeError is raised
"""
from distutils.spawn import find_executable
for c in candidates:
binary_path = find_executable(c)
... |
def calc_errors_from_vd(errors: dict, data_on_validate: dict = {}) -> list:
""" calc errors from validate-data (errors) by UnmarshalResult """
result_errors = []
# errors = {field_name: [errors-msgs]}
for field_name in errors:
if isinstance(errors[field_name], list):
for msg in error... |
def map_feature_to_field(feature):
"""Takes a feature string and returns a list of the corresponding
database fieldname(s) (usually just one but can handle more)"""
#self.logger.debug('Feature to map: ' + feature)
f = feature.lower()
# NB: this structure assumes all features will be mapped by at ... |
def encode_state(substate_node_set, state):
"""
Injectively encode state and its substate (with respect to given
subset of nodes) by (big) numbers.
:param state: state to encode
:param substate_node_set: nodes of the substate
:return: (state code, substate code)
"""
state_code = 0
s... |
def read_ld_score(b, ancestries, anc_to_ldscore, expect_bgz, prefix):
""" Read LD score files. Expects that there is one file per ancestry, *not* split per chromosome.
Parameters
----------
b : :obj:`Batch`
ancestries : `list`
Ancestry abbreviations compatible with `anc_to_ldscore`
anc... |
def iter_points(x):
"""Iterates over a list representing a feature, and returns a list of points,
whatever the shape of the array (Point, MultiPolyline, etc).
"""
if isinstance(x, (list, tuple)):
if len(x):
if isinstance(x[0], (list, tuple)):
out = []
... |
def get_postgres_curie_prefix(curie):
"""The representation in postgres moves things to lowercase, and replaces . with _"""
if ':' not in curie:
raise ValueError(f'Curies ought to contain a colon: {curie}')
prefix = curie.lower().split(':')
prefix = '_'.join(prefix[0].split('.'))
return pref... |
def create_new_products(user_data, prod_data, range):
"""
Special pre-processing for the YelpNYC since there is no new products (#reviews<5)
:param range: the range of products to be processed
"""
product_list = [(product, len(user)) for (product, user) in prod_data.items()]
sorted_product_list = sorted(product_... |
def getBaladiyatsFromWilayaObject(dairats, daira):
"""
this fucntion take an array of wilaya 'dairats' objects and a daira name
and return the daira baladiyats and if the daira exist in this wilaya
"""
for daira_element in dairats:
if daira == daira_element["code"] :
try :
... |
def filter_doc_list_through_topics_train_test(topics, types, docs):
"""
Reads all of the documents and creates a new list of two-tuples
that contain a single feature entry and the body text, instead of
a list of topics. It removes all geographic features and only
retains those documents which have ... |
def verify_goals(boolean=None):
"""
If boolean is True, then whenever the planner uses a method m to refine
a goal or multigoal, it will insert a "verification" task into the
current partial plan. If boolean is False, the planner won't insert
any verification tasks into the plan. If verify_goals is ... |
def hex_to_rgb(hex_code):
"""
Converts hex to rgb colours
===========================
Parameters:
-----------
hex: 6 characters representing a hex colour (str)
Returns:
--------
rgb: RGB values (list of 3 floats)
"""
hex_code = hex_code.strip("#") # removes hash symbol if ... |
def pSEDCC( sedtype ):
""" returns the likelihood of observing
a host galaxy with the given SED type,
assuming the SN is a CC.
The SED type is from the GOODZ SED template
set (Dahlen et al 2010).
1=E, 2=Sbc, 3=Scd, 4=Irr, 5,6=Starburst
plus 4 interpolations between each.
RETURNS :... |
def get_health(token_info=None, user=None):
"""Get a health report
:rtype: Health
"""
return {"status": "OK", "message": "Service is running"} |
def rootname(name):
"""Remove all extensions from name
Arguments:
name: name of a file
Returns:
Leading part of name up to first dot, i.e. name without any
trailing extensions.
"""
try:
i = name.index('.')
return name[0:i]
except ValueError:
# No dot
... |
def getid(obj):
"""Get object's ID or object.
Abstracts the common pattern of allowing both an object or an object's ID
as a parameter when dealing with relationships.
"""
return getattr(obj, 'id', obj) |
def _filter_lines_for_docker(docker_content):
"""Depending on the context, only some Docker statements can be compared,
among "RUN", "FROM", "MAINTAINER", "WORKDIR", "CMD", "EXPOSE" etc ... """
def is_machine_independent(input_line):
"""This tells if a line in a dockerfile is dependent on the machi... |
def uncompress_compressed_vector(compressed_vec):
"""
@compressed_vec: [[index, non_zero_value], ..., [lastindex, value]]
Returns list containing elements
"""
# length is the last index of the vector
length = compressed_vec[-1][0] + 1
v = [0.] * length
for i, val in compressed_vec:
... |
def _preprocess(doc, accent_function=None, lower=False):
"""
Chain together an optional series of text preprocessing steps to
apply to a document.
"""
if lower:
doc = doc.lower()
if accent_function is not None:
doc = accent_function(doc)
return doc |
def assemble_prediction(C4_prediction, mult_prediction):
"""
Assemble prediction from C4 and multi models
- C4_prediction is an array of prediction generated by the C4 model
- mult_prediction is an array of prediction generated by the C1C2C3 model
=> return an array of all preidction gener... |
def convert_to_int(s: str):
"""
Convert string to integer
:param s: str Input string
:return: Interpreted value if successful, 0 otherwise
"""
try:
nr = int(s)
except (ValueError, TypeError):
nr = 0
return nr |
def removeScopes(line):
"""Return a VB line with the scopes removed
This helps in the structure explorer, where the scopes get in the way
and make the line appear very long.
"""
potentials = [
"Sub ", "Function ", "Property ",
]
for item in potentials:
if item in line:
... |
def ignorant_next(iterable):
"""
Will try to iterate to the next value, or return None if none is available.
:param iterable:
:return:
"""
try:
return next(iterable)
except StopIteration:
return None |
def opt_tqdm(iterable):
"""
Optional tqdm progress bars
"""
try:
import tqdm
except:
return iterable
else:
return tqdm.tqdm(iterable) |
def cap(val, min, max):
""" Cap the value between the minimum and maximum values, inclusive.
Parameters:
val - value to cap
min - minimum allowed value
max - maximum allowed value
Return Value:
Returns capped value.
"""
if val < min: return min
if val > max: ret... |
def format_gravity_message(message):
""" Add a gravity to a message if not present."""
if not isinstance(message, tuple):
# gravity is not set by Supervisor so let's deduce it
if 'ERROR' in message:
message = message.replace('ERROR: ', '')
gravity = Error
elif 'un... |
def get_pages(sample_url, nb):
"""
Args :
sample_url (str): base of the url that will be copied to create the list.
nb(int) = number of loop executions.
Returns :
list: list containing your created urls from the base."""
pages = []
for i in range(1,nb+1):
j ... |
def represent_2d_char_list(l: list) -> str:
"""Output a 2d character list as aligned multiline string. Can be used for printing."""
row_num = 0
repres = ""
for rowlist in l:
if row_num > 0:
repres += "\n"
for c in rowlist:
repres += str(c)
row_num += 1
return repres |
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new han... |
def tab_file_url(expression_accession, filetype):
"""Generate a url for access of a tab file of the EBI's filetypes"""
url = "https://www.ebi.ac.uk/gxa/sc/experiment/%s/download?fileType=%s&accessKey=" \
% (expression_accession, filetype)
return url |
def not_zero(x):
"""Return None if value is zero"""
if x == 0:
return
return x |
def __get_file_data(file_path):
"""Extract data from file
Used to get all data included in the file at the specified path.
Args:
file_path (str): Path to specified file
max_files (int): number of files which may be included in the hash tuple
Returns:
binary: data stored in spe... |
def transposeM(matrix):
"""
"""
# rt = list( map( list, zip( *r_matrix ) ) )
return list(zip(*matrix)) |
def compareLists(c1,c2):
"""
Compare a pair of lists, returning None if the lists are identical,
or a pair of lists containing:
(1) elements of first list not in second, and
(2) elements of second list not in first list.
"""
c1 = c1 or []
c2 = c2 or []
c1d = []
c2d = []
for ... |
def icml2022_tex(*, family="serif"):
"""Fonts for ICML 2022. LaTeX version."""
preamble = r"\usepackage{times} "
if family == "serif":
return {
"text.usetex": True,
"font.family": "serif",
"text.latex.preamble": preamble,
}
preamble += (
r"\re... |
def energy_consumption(cpu_active_time, cpu_lpm_time, listen_time):
"""
Calculates the power consumption during a synchronization attempt.
Note that, in our experiments, we use Zolertia RE-Mote B devices (https://github.com/Zolertia/Resources/raw/master/RE-Mote/Hardware/Revision%20B/Datasheets/ZOL-RM0x-B%20... |
def add_integer(a, b=98):
"""
ADD Two integer a and b
Args:
a (int/float): first int
b (int/float): Second int
Raises:
TypeError: in case the arguments are not int or float
Return:
(int) : Sum of the int a and b
"""
if type(a) not in [int, float]:
rais... |
def Exact(caseAttrib, queryValue, weight):
"""
Exact matches for fields defined as equal. Attributes that use this are indexed using 'keyword'.
"""
# build query string
query = {
"term": {
caseAttrib: {
"value": queryValue,
"boost": weight,
"_name": "exact"
}
}
}
return query |
def format_price(raw_price):
"""Formats the price to account for bestbuy's raw price format
Args:
raw_price(string): Bestbuy's price format (ex: $5999 is $59.99)
Returns:
string: The formatted price
"""
formatted_price = raw_price[:len(raw_price) - 2] + "." + raw_price[len(raw_pric... |
def get_node_value(data, path):
"""
Gets node value
:param data: The dictionary to search
:param path: The path to search
Example - root.node1.node2.0.node3
:return: The value of the node specified in the path
"""
node = data
path_list = path.split('.')
for element in path... |
def version_str(version):
"""Convert a version tuple or string to a string.
Should be returned in the form: major.minor.release
"""
if isinstance(version, str):
return version
elif isinstance(version, tuple):
return '.'.join([str(int(x)) for x in version])
else:
raise Va... |
def count_values(tokens):
"""Identify the number of values ahead of the current token."""
ntoks = 0
for tok in tokens:
if tok.isspace() or tok == ',':
continue
elif tok in ('=', '/', '$', '&'):
if ntoks > 0 and tok == '=':
ntoks -= 1
break
... |
def is_quarter(string):
"""Determine if measurement label is quarterly."""
return string.startswith('Q') |
def build_test_gui_item(modes, buf_size, max_freq):
"""Create a dictionary object with all required key-pair values, to be used
for testing the GUI method.
"""
return {"allowedModeList": modes,
"allowedBufferSize": buf_size,
"allowedMaxFrequency": max_freq} |
def quote(text):
"""Quotes each line in text"""
return ['"{0}"'.format(line) for line in text] |
def _fuzzy_index(dct, full_key):
"""Return d[key] where ((key in k) == true) or return d[None]."""
for key in dct:
if key and (key in full_key):
return dct[key]
return dct[None] |
def dist_point(point,line):
"""
Computes the distance square between a point and a line
inputs:
- point : (x,y)
- line : (slope, intercept)
"""
return (point[1] - line[0]*point[0]-line[1])**2 |
def format_cwt(x):
"""
format cwts as 63-03-99
"""
x = str(x)
cwt = "-".join([x[:2], x[2:4], x[4:6]])
return cwt |
def getScenarioPercent(scenario_score, scenario_criteria):
"""
Get success rate of the scenario (in %)
"""
try:
score = float(scenario_score) / float(scenario_criteria) * 100
except ZeroDivisionError:
score = 0
return score |
def contains_item(L, s):
""" (list, object) -> bool
Return True if and only if s is an item of L.
"""
for item in L:
if item == s:
return True
else:
return False |
def yesno(boolean):
"""Boost-based C++ programs can accept 'yes' and 'no' on command line
arguments mapped to bools."""
if boolean is True:
return 'yes'
return 'no' |
def which(program):
"""
Emulates the behaviour of the \*nix 'which' command - if the given program exists in the path,
the full executable path is returned.
Credit for this function go to an answer on Stack Overflow:
http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
... |
def text_begins(text, pattern, case_sensitive=True):
"""
Checks whether the text (also known as `text`) contains the text specified for `pattern` at the beginning.
The no-data value None is passed through and therefore gets propagated.
Parameters
----------
text : str
Text in which to f... |
def create_hue_success_response(entity_id, attr, value):
"""Create a success response for an attribute set on a light."""
success_key = '/lights/{}/state/{}'.format(entity_id, attr)
return {'success': {success_key: value}} |
def repl_to_reprex_code(input: str, comment: str = "#>") -> str:
"""Reformat a code block copied from a Python REPL to a reprex-style code block.
Args:
input (str): code block
comment (str): Line prefix to use when rendering the evaluated results. Defaults to "#>".
Returns:
Reforma... |
def get_model_input(batch, input_id=None):
"""
Get model input from batch
batch: batch of model input samples
"""
if isinstance(batch, dict) or isinstance(batch, list):
assert input_id is not None
return batch[input_id]
else:
return batch |
def get_configurations(configs):
"""
Builds a list of all possible configuration dictionary
from one configuration dictionary that contains all values for a key
"""
if type(configs) == list:
return configs
all_configs = []
config_keys = list(configs.keys())
def recursive_config_... |
def pad_before(s, n, c):
"""Pad s by prepending n bytes of c."""
return (c * n)[:n - len(s)] + s if len(s) < n else s |
def fix_hyphen_commands(raw_cli_arguments):
"""Update options to match their module names with underscores."""
for i in ['gen-sample', 'run-python', 'run-stacker']:
raw_cli_arguments[i.replace('-', '_')] = raw_cli_arguments[i]
raw_cli_arguments.pop(i)
return raw_cli_arguments |
def get_job_url(config, hub=None, group=None, project=None):
"""
Util method to get job url
"""
hub = config.get('hub', hub)
group = config.get('group', group)
project = config.get('project', project)
if hub and group and project:
return '/Network/{}/Groups/{}/Projects/{}/jobs'.form... |
def splitanswertolists(answer):
"""Split 'answer' into tuple (items, values) of lists.
@param answer : String "item1 item2 ... = val1 val2 ...<LF>" or single "value".
@return : Tuple ([[item1], [item2], ...], [[val1, val2, ...]]) or (None, [[values]]).
"""
answer = answer.split('\n')
if '=' in a... |
def DatabaseFlags(sql_messages,
settings=None,
database_flags=None,
clear_database_flags=False):
"""Generates the database flags for the instance.
Args:
sql_messages: module, The messages module that should be used.
settings: sql_messages.Settings, the ... |
def make_compose(obj, hook_cls, hooks: list):
"""method that produces the compose of the hook_cls for all hooks in the list"""
def _get_loop_fn(fn_name):
def loop(*args, **kwargs):
for hook in hooks:
fn = getattr(hook, fn_name)
fn(*args, **kwargs)
retu... |
def decorator(f, log):
"""
Decorates f to include passing the plugin's log
Decorator taking any imported callable and wrapping it to include passing the plugin's log.
:param callable f: function to decorate
:param AigisLog.log log: log of the plugin
:returns: the wrapped callable
:rtype: c... |
def short_bubble(l, debug=True):
"""
what if the whole list is already in ascending order, the bubble would then still go through the entire outer loops
actually, if there is no swap happens in a certain iteration ( the inner loop), the next loop should stop
:param l:
:param debug:
:return:
... |
def match_orphan(first, second, third):
"""Matches on potential for orphan."""
if first['t'] == 'Str' and second['t'] == 'Space' and third['t'] == 'Math':
if third['c']:
return third['c'][0]['t'] == 'InlineMath'
return False |
def __get_tags_gtf(tagline):
"""Extract tags from given tagline in a gtf file"""
tags = dict()
for t in tagline.strip(';').split(';'):
tt = t.strip(' ').split(' ')
tags[tt[0]] = tt[1].strip('"')
return tags |
def _collision_transformed(corners, ref_L, ref_W):
"""safe bool for trasformed corners"""
for c in corners:
if -ref_L/2<=c[0]<=ref_L/2 and -ref_W/2<=c[1]<=ref_W/2:
return True
return False |
def is_dubious(corrected, isdiffpos, corr_magstats):
"""Get if object is dubious
:param corrected:
:type corrected: bool
:param isdiffpos:
:type isdiffpos: bool
:param corr_magstats:
:type corr_magstats: bool
:return: if the object is dubious
:rtype: bool
"""
return (~cor... |
def filter_image_gallery(image_gallery_list, result_names, widths, show_list):
"""return a list of strings for inclusion into gallery.rst"""
result = []
for ig, result_name, width, show in zip(
image_gallery_list, result_names, widths, show_list
):
if not show:
continue
... |
def is_close(a, b, rel_tol=1e-09, abs_tol=0.0):
"""Determines whether two floats are within a tolerance.
Returns:
bool: Returns True if the two floats are within a tolerance,
False otherwise.
"""
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) |
def matr_transp(_A):
"""
Returns transposed matrix
"""
lenA = len(_A)
lenA0 = len(_A[0])
return [[_A[i][j] for i in range(lenA)] for j in range(lenA0)] |
def piece_wise_add(list_a, list_b):
"""Add each element of list a to list b.
After trying to get numpy to work with decimals for about 10 minuts
it was raising cryptic errors. Enough of that nonsense.
"""
return [x+y for x, y in zip(list_a, list_b)] |
def insert(value: int, in_list: list) -> list:
"""
Insert a value in an ordered list
:param value: value to insert
:param in_list: list where we add the value
:return: the new list
"""
for idx in range(len(in_list)):
if in_list[idx] >= value:
return in_list[:idx] + [value... |
def truncate(text, length=30, truncate_string='...'):
"""
Truncates ``text`` with replacement characters
``length``
The maximum length of ``text`` before replacement
``truncate_string``
If ``text`` exceeds the ``length``, this string will replace
the end of the string
""... |
def _is_yearbook_transaction(transaction_detail):
"""Returns True iff the paypal `transaction_detail` object contains an `item_name` of Yearbook.
"""
cart_info = transaction_detail.get('cart_info')
if cart_info:
item_details = cart_info.get('item_details')
if item_details and len(item_de... |
def myint(number,default=0):
""" return a int from a object
@param number object to convert into a integer
@param default default value if error (0)
@return integer
"""
try:
return int(number)
except:
return default |
def dropannotation(annotation_list):
"""
Drop out the annotation contained in annotation_list
"""
target = ""
for c in annotation_list:
if not c == "#":
target += c
else:
return target
return target |
def get_case_inputs(case_id):
"""Get case file data"""
data = {
'case_id': case_id,
'options': {
'solution_format': 'validation',
}
}
return data |
def filter_functions_to_include_in_client(functions: dict) -> dict:
"""Include only those functions which dont have 'include_in_client' tag in metadata."""
filtered_functions = {}
for func_name in functions.keys():
if functions[func_name].get("include_in_client", True) is True:
filtered_... |
def ndk(name):
"""
Return the NDK version of given name, which replace
the leading "android" to "acamera"
Args:
name: name string of an entry
Returns:
A NDK version name string of the input name
"""
name_list = name.split(".")
if name_list[0] == "android":
name_list[0] = "acamera"
return... |
def check_list_of_type(lst, cls, msg=''):
""" Check that the given list contains only instances of cls.
Raise TypeError if an element is not of the given type.
If the list is None, an empty list is returned.
:param lst: list of items or None
:param cls: the class of which the elements should be ins... |
def wikipedia_id_to_url(wiki_id: str):
"""Convert a wikipedia title as outputted by BLINK to a wikipedia URL"""
return f"https://en.wikipedia.org/wiki/{'_'.join(wiki_id.split(' '))}" |
def get_url_path_valid_parts(url_path, rp_name):
"""valid parts of url path is a section of url without subscription, resource group and providers"""
url_path = url_path.split('?')[0]
parts = url_path.split("/")
provider_idx = None
for idx, part in enumerate(parts):
if part.lower() == rp_na... |
def strtobool(val: str) -> bool:
"""Convert a string representation of truth to true or false.
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.
Taken from distutils.util and modified to re... |
def hideExtension(path_):
"""Returns given path without it's extension"""
spPath = path_.split('/')
spPath[-1] = spPath[-1].split('.')[0]
return '/'.join(spPath) |
def int_to_binarray(x, d):
"""
Finds the pathway for the X'th item in row D using zero based indexing.
root to leaf
"""
m = [int(s) for s in bin(x)[2:]]
x = [0] * (d - len(m)) + m
x.reverse()
return x |
def get_url_path(value):
"""Takes a gitlab repository url and returns its path component
Example:
>>> get_url_path("https://gitlab.com/thorgate-public/django-project-template")
>>> "thorgate-public/django-project-template"
"""
if not value or not value.strip():
return value
res = v... |
def normalize_url(url: str) -> str:
"""Add explicit HTTPS schema to schema-less links"""
if not url.startswith("https://"):
return f"https://{url}"
return url |
def len_recursive(node):
"""
This function should calculate the length of a linked list recursively
:param node: the head of the list
:return: the length of the list
"""
if node == None:
return 0
return 1 + len_recursive(node._next) |
def truncatechars(value, arg):
"""
Truncates a string after a certain number of chars.
Argument: Number of chars to truncate after.
"""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
if len(value) > length:
retu... |
def occurrences(word, document, documents):
"""
count the number of times a word appears in a document
"""
count = 0
for string in documents[document]:
if(word == string):
count += 1
return count |
def split_into_blocks(data, size=16):
"""
Splits data into equally-sized blocks of size bytes
E.g. "ABCD" -> ["AB","CD"] for size=2.
"""
return [data[i : i + size] for i in range(0, len(data), size)] |
def audit_get_counts(data, is_print=True):
""" Gets counts for each unique value in a data list """
from collections import defaultdict
cnts = defaultdict(int)
for s in data:
cnts[s] += 1
if is_print:
keys = cnts.keys()
keys = sorted(keys, key=lambda s: s.lower())
for... |
def verse(bottle):
"""Sing a verse"""
next_bottle = bottle - 1
s1 = '' if bottle == 1 else 's'
s2 = '' if next_bottle == 1 else 's'
num_next = 'No more' if next_bottle == 0 else next_bottle
return '\n'.join([
f'{bottle} bottle{s1} of beer on the wall,',
f'{bottle} bottl... |
def _sanitize(string, zerotrim=False):
"""
Sanitize tick label strings.
"""
if zerotrim and '.' in string:
string = string.rstrip('0').rstrip('.')
string = string.replace('-', '\N{MINUS SIGN}')
if string == '\N{MINUS SIGN}0':
string = '0'
return string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.