content stringlengths 42 6.51k |
|---|
def detect_date(token: str):
"""
Attempts to convert string to date if found
mask_test = r'(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+(\d{1,2})\s+(\d{4})'
"""
from re import search
from da... |
def compute_total_ue_for_bs(_cell_associate, _bs_count):
"""Computes the number of UEs associated with a BS object for UE.
Args:
_cell_associate: (list) that contains tuple (ue_object, bs_associated)!
_bs_count: (list) that contains tuple of BS objects and the number of UEs t... |
def longest_common_prefix(str1, str2):
""" Returns the length of the longest common prefix of two provided strings """
i = 0
while i < min(len(str1), len(str2)):
if str1[i] != str2[i]:
break
i += 1
return i |
def getFilename(f):
"""Get the filename from an open file handle or filename string."""
if isinstance(f, str):
return f
return f.name |
def load_vocab(vocab):
"""
Transforms a vocabulary to the dictionary format required for the candidate generation.
:param vocab: a list containing the vocabulary
:return: vocab_dict
"""
# TRANSFORM VOCABULARY TO DICTIONARY
# initialize vocab word length keys and character set length keys
... |
def build(scoreGraph, orig_sentences):
"""
Builds the content summary based on the graph
:param orig_sentences: (list) list of original sentences
:param scoreGraph: (list) 2 dimensional list-graph of scores
:returns: Aggregate score(dictionary) of each sentence in `sentences`
"""
aggregateSc... |
def _format_media_type(endpoint, version, suffix):
"""
Formats a value for a cosmos Content-Type or Accept header key.
:param endpoint: a cosmos endpoint, of the form 'x/y',
for example 'package/repo/add', 'service/start', or 'package/error'
:type endpoint: str
:param version: The version of th... |
def sign2w(x):
""" Decode signed 2-byte integer from unsigned int """
if x >= 32768:
x ^= 65535
x += 1
x *=-1
return x |
def get_best_model(errors_list, model_list):
"""
Based on list of errors and list of models, return the model with
the minimum error
Returns:
model object
"""
# Find the index of the smallest ROEM
import numpy as np
idx = np.argmin(errors_list)
print("Index of smallest erro... |
def trimhttp(url):
""" Strip 'http://' or 'https://' prefix to url """
if url[:7] == 'http://':
return url[7:]
elif url[:8] == 'https://':
return url[8:]
return url |
def func_xy_ab_args_pq_kwargs(x, y, a=2, b=3, *args, p="p", q="q", **kwargs):
"""func.
Parameters
----------
x, y: float
a, b: int
args: tuple
p, q: str, optional
kwargs: dict
Returns
-------
x, y: float
a, b: int
args: tuple
p, q: str
kwargs: dict
"""
... |
def get_opcode(instruction_bytes):
"""
Returns the 6-bit MIPS opcode from a 4 byte instruction.
"""
op = (instruction_bytes & 0xFC000000) >> (3 * 8 + 2)
return op |
def summarize_consensus(consensus):
"""
Return 'high', 'medium' or 'low' as a rough indicator of consensus.
"""
cons = int(100 * consensus)
if cons >= 70:
return "high"
elif cons >= 30:
return "medium"
else:
return "low" |
def check_guess(guess, answer):
"""
:param guess: an alphabet, the guess made by player
:param answer: a word, the correct answer
:return: bool, if the guess is in the answer or not
"""
for i in range(len(answer)):
ch = answer[i]
if ch == guess:
return True |
def parse_2hc(segment):
""" Parser for 2hc periodic output"""
second_hit = {}
data = segment.split()
second_hit["fill_perc"] = float(data[1])
return second_hit |
def get_reduction_level(indsize, optlevel, slicesize, chunksize):
"""Compute the reduction level based on indsize and optlevel."""
rlevels = [
[8, 8, 8, 8, 4, 4, 4, 2, 2, 1], # 8-bit indices (ultralight)
[4, 4, 4, 4, 2, 2, 2, 1, 1, 1], # 16-bit indices (light)
[2, 2, 2, 2, 1, 1, 1, 1, ... |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'xlr_test' and password == 'admin' |
def merge_as_sets(*args):
"""Create an order set (represented as a list) of the objects in
the sequences passed as arguments."""
s = {}
for x in args:
for y in x:
s[y] = True
return sorted(s) |
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens |
def get_average(data):
"""Returns the average value
from given data points."""
return sum(data) / len(data) |
def no_response_error(api, response):
"""format error message for empty response"""
return "calling: %s: no response %s" % (api, repr(response)) |
def is_valid_boolstr(val):
"""Check if the provided string is a valid bool string or not."""
val = str(val).lower()
return val in ('true', 'false', 'yes', 'no', 'y', 'n', '1', '0') |
def himmelblau(individual):
"""The Himmelblau's function is multimodal with 4 defined minimums in
:math:`[-6, 6]^2`.
.. list-table::
:widths: 10 50
:stub-columns: 1
* - Type
- minimization
* - Range
- :math:`x_i \in [-6, 6]`
* - Global optima
... |
def _extend_pads(pads, rank):
"""Extends a padding list to match the necessary rank.
Args:
pads ([int] or None): The explicitly-provided padding list.
rank (int): The rank of the operation.
Returns:
None: If pads is None
[int]: The extended padding list.
"""
if ... |
def calc(region, metric, ms):
"""
"""
if metric in region:
value = region[metric]
return round((value / ms) * 100)
else:
return 0 |
def _list_f2s(float_list):
"""Converts a list of floats to strings."""
return ["{:0.2f}".format(x) for x in float_list] |
def title(text):
"""Turns text into a title"""
return str(text).replace("_", " ").title() |
def recursive_longest_palindromic_subsequence(input_string):
"""
Parameters
----------
input_string : str
String with palindromic subsequence
Returns
-------
int
length of the longest palindromic subsequence
>>> recursive_longest_palindromic_subsequence("abdbca")
5... |
def lossless_compression(text: str, token_separator=" ") -> str:
"""Here we count how many times the same token was repeated and write it and it's count
e.g text ABC ABC ABC EE A S X X SD will be compressed to:
ABC 3 EE 1 A 1 S 1 XX 2 SD 1. For small resolutions this compression doesn't give us much... |
def _appendListElement(list_data, data) -> list:
"""
Function Description :
_appendListElement : append new squence element and return into sequence
accept list_data as list that would be append with new data. And the data
is arg to hold the new data
EXAMPLE ARGS : (list_data ... |
def unsigned_int(value):
"""Convert from signed to unsigned int
(Channel Access does not support unsigend int)"""
if type(value) == int and value < 0: value = value+0x100000000
return value |
def dec2hex(x):
"""
Convert decimal number to hexadecimal string.
For instance: 26 -> '1a'
"""
return hex(x)[2:] |
def differentiate(coefficients):
"""
Calculates the derivative of a polynomial and returns
the corresponding coefficients.
"""
new_cos = []
for deg, prev_co in enumerate(coefficients[1:]):
new_cos.append((deg+1) * prev_co)
return new_cos |
def to_multipart_form(data, boundary):
"""Create a multipart form like produced by HTML forms from a dict."""
form_lines = []
for k, v in data.items():
form_lines.append('--' + boundary)
# Handle special case for imageFile.
if k == 'imageFile':
form_lines.append('Content-... |
def get_output_detections_json_file_path(input_file_path, suffix="--detections"):
"""Get the appropriate detections JSON output path for a given image input.
Effectively appends "--detections" to the original image file and
places it within the same directory.
Parameters
-----------
input_fil... |
def _stripItalic(s):
"""Returns the string s, with italics removed."""
return s.replace('\x1d', '') |
def stringify_time(time) -> str:
"""
returns time in appropriate way for agenda
"""
hours = str(int(time))
if len(hours) == 1:
hours = '0' + hours
minutes = '30' if time % 1 != 0 else '00'
return hours + minutes + '00' |
def voltage_to_direction(voltage: float) -> str:
"""
Converts an anolog voltage to a direction
Arguments:
- voltage: Voltage float value form the MCP3008. values are between 0 and 3.3V
Returns:
- Direction coresponding to an input voltage
"""
if voltage < 0.20625 or voltage > 3... |
def oxe_set_headers(token, method=None):
"""Builder for requests headers depending on request method
Args:
token (STR): Authentication token
method (None, optional): GET (not mandatory), PUT, POST, DELETE
Returns:
JSON: headers
"""
# basic method GET
headers = ... |
def _common_dir(dirs):
"""
dirs: List[String]
"""
if not dirs:
return ""
if len(dirs) == 1:
return dirs[0]
split_dirs = [dir.split("/") for dir in dirs]
shortest = min(split_dirs)
longest = max(split_dirs)
for i, piece in enumerate(shortest):
# if the next... |
def build_txt_strand_from_chains(model):
"""
Concatenates chains in given model and builds a single strand from them
:param model: Model aggregate of chains
:return: RNA strand text string
"""
txt = ''
for _, chain in model.items():
txt += ''.join(chain)
return txt |
def justify_right(css: str) -> str:
"""Justify to the Right all CSS properties on the argument css string."""
max_indent, right_justified_css = 1, ""
for css_line in css.splitlines():
c_1 = len(css_line.split(":")) == 2 and css_line.strip().endswith(";")
c_2 = "{" not in css_line and "}" not... |
def search(state, path):
"""Get value in `state` at the specified path, returning {} if the key is absent"""
if path.strip("/") == '':
return state
for p in path.strip("/").split("/"):
if p not in state:
return {}
state = state[p]
return state |
def _plugin_replace_role(name, contents, plugins):
""" The first plugin that handles this role is used.
"""
for p in plugins:
role_hook = p.get_role_hook(name)
if role_hook:
return role_hook(contents)
# If no plugin handling this role is found, return its original form
re... |
def __is_variable(data: str) -> bool:
""" Returns true if predicate is a variable.
Note: requires to start all variables with a capital letter.
"""
return data[0].isupper() |
def isiterable(obj):
"""
Returns True if obj is Iterable (list, str, tuple, set, dict, etc'), and False otherwise. \
This function does not consume iterators/generators.
:param obj: the object to be tested for iterability
:type obj: Any
:return: True if obj is Iterable, False otherwise.
:rt... |
def morris_traversal(root):
"""
Morris(InOrder) travaersal is a tree traversal algorithm that does not employ
the use of recursion or a stack. In this traversal, links are created as
successors and nodes are printed using these links.
Finally, the changes are reverted back to restore the original t... |
def settings_index(val: float, settings: list) -> int:
"""Return index into settings that has nearest value to val.
Args:
val:
settings:
Returns:
"""
idx = 0
for idx, setting in enumerate(settings):
if val <= setting:
if idx > 0:
# Not first... |
def folders_to_path(folders):
"""
Convert list of folders to a path.
:param folders: List of folders, None denotes a root folder e.g. [None, 'NAS', 'Music', 'By Folder', 'folder1']
:returns: path string e.g. /NAS/Music/By Folder/folder1
"""
if not folders:
return '/'
if folders[0] ... |
def vol_format(x):
"""
Formats stock volume number to millions of shares.
Params:
x (numeric, like int or float)): the number to be formatted
Example:
vol_format(10000000)
vol_format(3390000)
"""
return "{:.1f}M".format(x/1000000) |
def convert_variable_name(oldname: str) -> str:
"""Convert Variable Name.
Converts a variable name to be a valid C macro name.
"""
return oldname.strip().upper().replace(" ", "_") |
def readFileLines(fname):
"""Read the lines of 'fname', returning them as a list."""
with open(fname, "r") as fp:
return fp.readlines() |
def task_wrapper(task):
"""Task wrapper for multithread_func
Args:
task[0]: function to be wrapped.
task[1]: function args.
Returns:
Return value of wrapped function call.
"""
func = task[0]
params = task[1]
return func(*params) |
def make_link(text: str, link: str) -> str:
"""
Creates a markdown link
:param text: the text to display
:param link: the link target
:return: the formatted link
"""
return '[%s](%s)' % (text, link) |
def make_extension_name(extension_basename: str, package_name: str) -> str:
"""Make a full Arrowbic extension name.
Args:
extension_basename: Extension basename.
package_name: Package name.
Returns:
Extension fullname.
"""
extension_name = f"arrowbic.{package_name}.{extensio... |
def version_int_to_string(version_integer: int) -> str:
"""Convert a version integer to a readable string.
Args:
version_integer (int): The version integer, as retrieved from the device.
Returns:
str: The version translated to a readable string.
"""
if not version_integer:
... |
def get_scientific_name_from_row(r):
"""
r: a dataframe that's really a row in one of our taxonomy tables
"""
if 'canonicalName' in r and len(r['canonicalName']) > 0:
scientific_name = r['canonicalName']
else:
scientific_name = r['scientificName']
return scientific_name |
def parity(x,N,sign_ptr,args):
""" works for all system sizes N. """
out = 0
sps = args[0]
for i in range(N):
j = (N-1) - i
out += ( x%sps ) * (sps**j)
x //= sps
#
return out |
def cmp_dicts(d1, d2):
"""Recursively compares two dictionaries"""
# First test the keys
for k1 in d1.keys():
if k1 not in d2:
return False
for k2 in d2.keys():
if k2 not in d1:
return False
# Now we need to test the contents recursively. We store the results... |
def _interpolation_max_weighted_deg(n, tau, s):
"""Return the maximal weighted degree allowed for an interpolation
polynomial over `n` points, correcting `tau` errors and with multiplicity
`s`
EXAMPLES::
sage: from sage.coding.guruswami_sudan.interpolation import _interpolation_max_weighted_de... |
def n_eff(dlnsdlnm):
"""
Return the power spectral slope at the scale of the halo radius,
Parameters
----------
dlnsdlnm : array
The derivative of log sigma with log M
Returns
-------
n_eff : float
Notes
-----
Uses eq. 42 in Lukic et. al 2007.
"""
... |
def get_attributes(label_data):
"""Reads all attributes of label.
Args:
label_data (dict): List of label attributes
Returns:
list: List of all attributes
"""
attributes = []
if label_data['attributes'] is not None:
for attribute_name in label_data['attributes']:
... |
def _import_object(source):
"""helper to import object from module; accept format `path.to.object`"""
modname, modattr = source.rsplit(".",1)
mod = __import__(modname, fromlist=[modattr], level=0)
return getattr(mod, modattr) |
def sum_pows(a: int, b: int, c: int, d: int) -> int:
"""
>>> sum_pows(9, 29, 7, 27)
4710194409608608369201743232
"""
return a**b + c**d |
def hist_dict(array):
"""
Return a histogram of any items as a dict.
The keys of the returned dict are elements of 'array' and the values
are the counts of each element in 'array'.
"""
hist = {}
for i in array:
if i in hist:
hist[i] += 1
else:
hist[i... |
def map_tcp_flags(bitmap):
"""
Maps text names of tcp flags to values in bitmap
:param bitmap: array[8]
:return: dictionary with keynames as names of the flags
"""
result = {}
result["FIN"] = bitmap[7]
result["SYN"] = bitmap[6]
result["RST"] = bitmap[5]
result["PSH"] = bitmap[4... |
def _is_substitution(content, start, end):
"""This is to support non-ARM-style direct parameter string substitution as a
simplification of the concat function. We may wish to remove this
if we want to adhere more strictly to ARM.
:param str content: The contents of an expression from the template.
:... |
def createMyWords(language, validletters='abcdefghijklmnopqrstuvwxyz',
additionals=''):
"""Return a list of guessable words.
Ideally, these words originate from an included dictionary file
called de-en.dict.
"""
mywords = set() # guessable words
if language == 'en':
language... |
def get_delete_query(table_name: str) -> str:
"""Build a SQL query to delete a RDF triple from a PostgreSQL table.
Argument: Name of the SQL table from which the triple will be deleted.
Returns: A prepared SQL query that can be executed with a tuple (subject, predicate, object).
"""
return f"DELET... |
def month_converter(month):
"""Convert month name string to number."""
months = ['January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October',
'November', 'December']
return str(months.index(month) + 1).rjust(2, '0') |
def split_string(phrase: str, split_param: str):
"""
Split the 'phrase' string in different strings taking 'split_param' as split's parameter
:param phrase: string to be splitted
:param split_param: split's parameter
:return: a list of strings
"""
return phrase.split(split_param) |
def isinslice(index, Slice):
"""
Determine whether index is part of a slice.
"""
start, stop, stride = Slice.indices(index + 1)
if (index - start) % stride != 0:
return False
if stride < 0:
return (start >= index > stop)
else:
return (start <= index < stop) |
def gamma_PML(x, gamma, PML_start, PML_thk):
"""
Polynomial stretching profile for a perfectly matched layer.
Parameters:
x : physical coordinate
gamma : average value of the profile
PML_start : where the PML starts
PML_thk : thickness of the PML
Returns:
the va... |
def parseIntList(string):
"""Parses a comma-separated string of ints into a list"""
splitarray = string.split(",")
int_list = []
for elem in splitarray:
int_list.append(int(elem))
return int_list |
def get_target_metrics(dataset: str, tolerance: float = 0.0):
"""Get performance of pretrained model as gold standard."""
if dataset == 'eth':
# target_ade, target_fde = 0.64, 1.11 # paper
target_ade, target_fde = 0.732, 1.223 # pretrained
target_col = 1.33
elif dataset == 'hotel':... |
def docker_compose_files(pytestconfig):
"""Get the docker-compose.yml absolute path.
Override this fixture in your tests if you need a custom location.
"""
return ["docker-compose.yml"] |
def cloudtrail_event_parser(event):
"""Extract list of new S3 bucket attributes.
These attributes are extracted from the
AWS CloudTrail resource creation event.
Args:
event: a CloudTrail event
Returns:
s3_bucket_name: name of the created S3 bucket
resource_date: date+time ... |
def filter_out_agg_logs(logs):
"""Remove aggregate interactions from the list in computing data point metrics"""
filtered = []
for log in logs:
if "agg" not in log:
filtered.append(log)
return filtered |
def filter_dict_by_key_set(dict_to_filter, key_set):
"""Takes a dictionary and returns a copy with only the keys that exist in the given set"""
return {key: dict_to_filter[key] for key in dict_to_filter.keys() if key in key_set} |
def flax_while_loop(cond_fun, body_fun, init_val): # pragma: no cover
"""
for debugging purposes, use this instead of jax.lax.while_loop
"""
val = init_val
while cond_fun(val):
val = body_fun(val)
return val |
def _dict_extends(d1, d2):
"""
Helper function to create a new dictionary with the contents of the two
given dictionaries. Does not modify either dictionary, and the values are
copied shallowly. If there are repeates, the second dictionary wins ties.
The function is written to ensure Skulpt compati... |
def file_name(path: str) -> str:
"""From path of a file, find the name of that file"""
# Scroll back path string until he find / or \
for i in range(len(path)-1, 0, -1):
if path[i] == "/" or path[i] == "\\":
return path[i+1:]
else:
return path |
def get_direction_time(direction, travelling_mode):
"""Get the duration of the journey
Arguments:
- direction : (list) information about the journey
- travelling_mode: (str) conveyance
Returns:
- time : (str) duration of the journey
"""
time = None
if travelling_mo... |
def count_total_parameters(variables):
"""
Args:
variables (list): tf.trainable_variables()
Returns:
parameters_dict (dict):
key => variable name
value => the number of parameters
total_parameters (float): total parameters of the model
"""
total_parame... |
def utterance_from_line(line):
"""Converts a line of text, read from an input file, into a list of words.
Start-of-sentence and end-of-sentece tokens (``<s>`` and ``</s>``) will be
inserted at the beginning and the end of the list, if they're missing. If
the line is empty, returns an empty list (instea... |
def _expand_xyfp(x, y):
"""
Undo _redux_xyfp() transform
"""
a = 420.0
return -x*a, y*a |
def grab_file_extension(file_name):
""" grabs the chunk of text after the final period. """
return file_name.rsplit('.', 1)[1] |
def apply_set_and_clear(val: int, set_flag: int, clear_flag: int):
"""
:param val: an input value of the flag(s)
:param set_flag: a mask of bits to set to 1
:param clear_flag: a mask of bits to set to 0
:note: set has higher priority
:return: new value of the flag
"""
return (val & ~cle... |
def _strip_comments(definition_lines):
"""Not as straightforward as usual, because comments can be escaped
by backslash, and backslash can escape space."""
out_lines = []
for line in definition_lines:
pos = 0
while True:
x = line.find("#", pos)
if x <= 0:
... |
def f(x, a, r):
"""
The equation ax^(a-1) - (a-1)x^a - r = 0
To be used as argument in solver
"""
return a*x**(a-1) - (a-1)*x**a - r |
def adjust_parameter_threshold(param, stab, targ_stab = 0.5, rate = 0.03):
"""
"""
param_update = param + (stab - targ_stab)*rate
param_diff= param - param_update
return param_update, param_diff |
def decode(parsed_string):
"""
INPUT: A List of List parsed from encoded string
OUTPUT: A String of Decoded line
"""
decoded = ""
for item in parsed_string:
try:
decoded += item[0] * item[1]
except IndexError:
pass
return decoded |
def prettyElapsed(seconds):
""" Return a pretty string representing the elapsed time in hours, minutes, seconds """
def shiftTo(seconds, shiftToSeconds, shiftToLabel):
""" Return a pretty string, shifting seconds to the specified unit of measure """
prettyStr = '%i%s' % ((seconds / shiftToSecond... |
def file_type_matches(file_types):
"""wildcard file name matches for the file types to include"""
return ["/*.%s" % file_type for file_type in file_types] |
def checkExistence_file(database_filename):
"""Function that check if the db file can be opened"""
try:
with open(database_filename) as file:
read_data = file.read()
except Exception as e:
raise Exception("Could not opened the file '" + database_filename + "'")
return True |
def top_accepted(answers, top=5):
"""Top accepted answers by score"""
return list(
filter(
lambda x: x["is_accepted"],
sorted(answers, key=lambda x: x["score"], reverse=True),
)
)[:top] |
def modelfor(model, table):
"""
Returns True if the given `model` object is for the
expected `table`.
>>> from pyfarm.master.config import config
>>> from pyfarm.models.agent import Agent
>>> modelfor(Agent("foo", "10.56.0.0", "255.0.0.0"), config.get("table_agent"))
True
"""
try:
... |
def build_bmv2_config(bmv2_json_path):
"""
Builds the device config for BMv2
"""
with open(bmv2_json_path) as f:
return f.read() |
def normalize_newlines(text: str) -> str:
"""Normalize text to follow Unix newline pattern"""
return text.replace("\r\n", "\n").replace("\r", "\n") |
def get_midpoint(origin, destination):
""" Return the midpoint between two points on cartesian plane.
:param origin: (x, y)
:param destination: (x, y)
:return: (x, y)
"""
x_dist = destination[0] + origin[0]
y_dist = destination[1] + origin[1]
return x_dist / 2.0, y_dist / 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.