content stringlengths 42 6.51k |
|---|
def _conv_number(number, typen=float):
"""Convert a number.
Parameters
----------
number
Number represented a float.
typen :
The default is ``float``.
Returns
-------
"""
if typen is float:
try:
return float(number)
except:
... |
def _truncate_with_offset(resource, value_list, offset):
"""Truncate a list of dictionaries with a given offset.
"""
if not offset:
return resource
offset = offset.lower()
for i, j in enumerate(value_list):
# if offset matches one of the values in value_list,
# the truncated... |
def get_device_type_id(name):
"""
Returns the ATCADeviceType value based on the device name
"""
devices = {'ATSHA204A': 0,
'ATECC108A': 1,
'ATECC508A': 2,
'ATECC608A': 3,
'UNKNOWN': 0x20}
return devices.get(name.upper()) |
def merge(l1, l2):
"""
l1, l2: Lists of integers (might be empty). Arrays are assumed to be sorted.
Returns the lists merged.
"""
n = len(l1) + len(l2)
merged = []
i, j, s = 0, 0, 0
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
merged.append(l1[i])
... |
def word(item, lex):
"""This function returns true if item is word in lexicon that has
not been analyzed, i.e. it has no attached syntactic category"""
# If item is a key in lex, return True
if isinstance(item, list):
return False
if item in lex:
return True
return False |
def fill(array, value, start=0, end=None):
"""Fills elements of array with value from `start` up to, but not
including, `end`.
Args:
array (list): List to fill.
value (mixed): Value to fill with.
start (int, optional): Index to start filling. Defaults to ``0``.
end (int, opt... |
def make_s3_raw_record(bucket, key):
"""Helper for creating the s3 raw record"""
# size = len(s3_data)
raw_record = {
's3': {
'configurationId': 'testConfigRule',
'object': {
'eTag': '0123456789abcdef0123456789abcdef',
'sequencer': '0A1B2C3D4E5... |
def lot_status(parkingLot):
"""
return the status of Parking Lot
ARGS:
parkingLot(ParkingLot Object)
"""
returnString = ''
if parkingLot:
print('Slot No.\tRegistration No\tColour')
parkingSlot = parkingLot.get_slots()
for parkedCar in parkingSlot.values():
... |
def get_similarity_score(dict1, dict2, dissimilarity = False):
"""
The keys of dict1 and dict2 are all lowercase,
you will NOT need to worry about case sensitivity.
Args:
dict1: frequency dictionary of words or n-grams for one text
dict2: frequency dictionary of words or n-grams ... |
def normalize_recommend(rec_list, max_len):
"""
If len(rec_list) < max_len, rec_list will be dropped.
Otherwise, rec_list will be truncated.
"""
if len(rec_list) < max_len:
return []
else:
return rec_list[-max_len:] |
def probability_multiply(probability, token_frequency, n):
"""Assigns score to document based on multiplication of probabilities. Probability is token frequency devided by length of document.
In this metric only documents containing all query words have positive probability.
Args:
probabili... |
def InsetLineColourRev(argument):
"""Reverse dictionary for switching colour argurments"""
switcher = {
'k' : 'Black',
'dimgrey' : 'Dark Grey',
'darkgrey' : 'Grey',
'lightgrey' : 'Light Grey',
'white' : 'White'
}
return switcher.get(argument, 'k') |
def energy_au(neff): #energy in atomic units
"""
returns the energy of the state in atomic units.
"""
return -(0.5 * (1.0 / ((neff)**2) )) |
def assign_ids(lang, data):
"""Add ID values for groups and characters"""
group_id = 1
char_id = 1
for purity_group in data.values():
for group in purity_group["groups"].values():
group["ID"] = f"g-{lang}-{group_id}"
group_id += 1
for cluster in group["cluster... |
def required(label, field, data, **kwargs):
"""Validates presence value.
- when bool, return True
- when None, return False,
- when inexistent key, return False
"""
if not field in data:
return False
value = data[field]
if value == None:
return False
elif type(value... |
def wrap(text, width=80):
"""
Wraps a string at a fixed width.
Arguments
---------
text : str
Text to be wrapped
width : int
Line width
Returns
-------
str
Wrapped string
"""
return "\n".join(
[text[i:i + width] for i in range(0, len(text), w... |
def get_min_hit_end_distance(l1, l2):
"""
Given two lists of kmer hit ends on a sequence (from get_kmer_hit_ends()),
return the minimum distance between two hit ends in the two lists.
In other words, the closest positions in both lists.
>>> l1 = [2,10,20]
>>> l2 = [12,15,30]
>>> get_min_hit... |
def str2bin(msg):
"""Convert a binary string into a 16 bit binary message."""
assert isinstance(msg, bytes), 'must give a byte obj'
return ''.join([bin(c)[2:].zfill(16) for c in msg]).encode() |
def name_is_private(name: str) -> bool:
"""Determines whether a given name is private."""
return name.startswith("~") |
def deltatime_format(a, b):
""" Compute and format the time elapsed between two points in time.
Args:
a Earlier point-in-time
b Later point-in-time
Returns:
Elapsed time integer (in s),
Formatted elapsed time string (human-readable way)
"""
# Elapsed time (in seconds)
t = b - a
# Elapsed t... |
def is_numlike(obj):
""" Return True if `obj` looks like a number
"""
try:
obj + 1
except:
return False
return True |
def isqrt(n: int) -> int:
"""Returns the square root of an integer."""
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x |
def NnotNone(*it):
"""
Returns the number of elements of it tha are not None.
Parameters
----------
it : iterable
iterable of elements that are either None, or not None
Returns
-------
int
"""
return sum([i is not None for i in it]) |
def parse_number(input_string, parsing_hex=False):
"""
# hex: ABCDEF
# atoi (int, float), integer/float
@param input_string: input string
@param parsing_hex: ABCDEF
@return:
"""
input_string = str(input_string).strip().strip('+').rstrip('.')
result, multiplier, division = 0, 10, 1
... |
def parse_date(string_value):
""" Used to parse date on which match is played.
"""
dd, mm, yyyy = string_value.split("-")
return int(yyyy), int(mm), int(dd) |
def findimagenumber (filename):
"""find the number for each image file"""
#split the file so that name is a string equal to OBSDATE+number
name=filename.split('/')[-1].split('.')[0]
return int(name[9:]) |
def transform_metadata(record):
"""Format the metadata record we got from the database to adhere to the response schema."""
response = dict(record)
response["id"] = response.pop("datasetId")
response["name"] = None
response["description"] = response.pop("description")
response["assemblyId"] =... |
def hexToStr(hexStr):
"""
Convert a string hex byte values into a byte string
"""
bytes = []
hexStr = ''.join(hexStr.split(" "))
for i in range(0, len(hexStr)-2, 2):
bytes.append(chr(int(hexStr[i:i+2], 16)))
return ''.join( bytes ) |
def as_int_or_float(val):
"""Infers Python int vs. float from string representation."""
if type(val) == str:
ret_val = float(val) if '.' in val else int(val)
return ret_val
return val |
def convert_to_fortran_string(string):
"""
converts some parameter strings to the format for the inpgen
:param string: some string
:returns: string in right format (extra "" if not already present)
"""
if not string.strip().startswith("\"") or \
not string.strip().endswith("\""):
... |
def check_step_motion_from_dissonance(
movement: int,
is_last_element_consonant: bool,
**kwargs
) -> bool:
"""
Check that there is step motion from a dissonating element.
Note that this rule prohibits double neighboring tones.
:param movement:
melodic interval (in scale... |
def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"uid": string,
... |
def memoized_longest_palindromic_subsequence(input_string):
"""
Parameters
----------
input_string : str
String with palindromic subsequence
Returns
-------
int
length of the longest palindromic subsequence
>>> memoized_longest_palindromic_subsequence("abdbca")
5
... |
def mate(generations: int, litter: int) -> int:
""" Calculate population at end"""
fib = [0, 1]
for _ in range(generations - 1):
fib.append((fib[-2] * litter) + fib[-1])
pop = fib[-1]
return pop |
def print_delays_header(v=1):
"""
Print header for summary of delay information.
Parameters
----------
v : int
verbose mode if 1.
Returns
-------
str_out : str
line with header.
"""
str_out=("D "+"st".rjust(3)+ "t0 [s]".rjust(14)+"total delay [us]".r... |
def _horner(x, coeffs):
"""Horner's method to evaluate polynomials."""
res = coeffs[0]
for c in coeffs[1:]:
res = c + x * res
return res |
def boxes_required(qty, box_capacity=6):
"""
Calculate how many egg boxes will be required for a given quatity of eggs.
:param qty: Number of eggs
:param box_capacity: How many eggs will fit in a box
:return: The number of boxes that are required
"""
return int(qty / box_capacity) + 1 |
def scale_model_weights(weight, scalar):
"""Function for scaling a models weights for federated averaging"""
weight_final = []
steps = len(weight)
for i in range(steps):
weight_final.append(scalar * weight[i])
return weight_final |
def local_time_constant(longitude: float) -> float:
"""Local time constant K in minutes - DK: Lokal tids konstant"""
time_median_longitude = int(longitude/15)*15
longitude_deg = longitude / abs(longitude) * (abs(int(longitude)) + abs(longitude) % 1 * 100 / 60)
local_time_constant = 4 * (time_median_long... |
def get_language(path: str):
"""
Get website language in url path.
Args:
path (str): path
"""
# The path are in the following format:
# <optional base_url>/<year>/<lang>/....
# ex: /2021/zh-hant/about/history, /2015apac/en/about/index.html, /2019/en-us/
# Use for loop to find la... |
def extract_update(input):
"""extract the update data, from which we compute new metrics"""
update = input['update']
update['_id'] = input['_id']
return update |
def parse_siteclass_proportions(line_floats):
"""For models which have multiple site classes, find the proportion of the alignment assigned to each class.
"""
site_classes = {}
if len(line_floats) > 0:
for n in range(len(line_floats)):
site_classes[n] = {"proportion" : line_floats[n]... |
def stabilize_steering_angle(curr_steering_angle, new_steering_angle, num_of_lane_lines, max_angle_deviation_two_lines=5, max_angle_deviation_one_lane=1):
"""
Using last steering angle to stabilize the steering angle
This can be improved to use last N angles, etc
if new angle is too different from curre... |
def dict_to_string(d, num_dict_round_floats=6, style='dictionary'):
"""given a dictionary, returns a string
Arguments:
d {dictionary} --
num_dict_round_floats {int} -- num of digits to which the float numbers on the dict should be round
style {string}
"""
separator = ''
desc... |
def compute_precision_recall(correct_chunk_cnt, found_pred_cnt,
found_correct_cnt):
"""Computes and returns the precision and recall.
Args:
correct_chunk_cnt: The count of correctly predicted chunks.
found_pred_cnt: The count of predicted chunks.
found_correct_cnt : Th... |
def _selStrFromList(item_str, lst_str):
"""
Selects a string from a list if it is a substring of the item.
Parameters
----------
item_str: str
string for which the selection is done
list_str: list-str
list from which selection is done
Returns
-------
str
"""
strs = [s for s in lst_... |
def strip_scheme_www_and_query(url):
"""Remove the scheme and query section of a URL."""
if url:
return url.split("//")[-1].split("?")[0].lstrip("www.")
else:
return "" |
def GetSupportPoint(left, right):
"""
Returns supported point.
Args:
left: Left point
right: Right point
Returns:
Point
"""
return (right[0], left[1]) |
def __material_mu(d):
""" Fixed length data fields for music. """
return (d[0:2], d[2], d[3], d[4], d[5], d[6:12], d[12:14], d[14],
d[15], d[16]) |
def cycle(permutation, start):
"""
Compute a cycle of a permutation.
:param permutation: Permutation in one-line notation (length n tuple of the numbers 0, 1, ..., n-1).
:param start: Permutation element to start with.
:return: Tuple of elements we pass until we cycle back to the start element.
... |
def eiffel_confidence_level_modified_event(name="Eiffel Graphql API Tests"):
"""Eiffel confidence level modified event."""
return {
"meta": {
"version": "3.0.0",
"source": {"name": "eiffel-graphql-api-tests"},
"type": "EiffelConfidenceLevelModifiedEvent",
... |
def env_str_to_int(varname, val):
"""Convert environment variable decimal value `val` from `varname` to an int and return it."""
try:
return int(val)
except Exception:
raise ValueError("Invalid value for " + repr(varname) +
" should have a decimal integer value but ... |
def range_out_of_set(list):
"""Filters the single interfaces
Filters the single interface sets, leaves out
the ones with multiple elements and returns them
as a list.
Args:
list (list): list of sets
Returns:
list: list of strings which is interface name
"""
same_co... |
def remove_namespace(inp):
"""Remove namespace from input string.
A namespace in this context is the first substring before the '/' character
Parameters
----------
inp : Input string
Returns
-------
string with namespace removed.
"""
ind = inp.find('/')
if ind != -1:
... |
def supports_float(value: object) -> bool: # noqa: E302
"""Check if a float-like object has been passed (:class:`~typing.SupportsFloat`).
Examples
--------
.. code:: python
>>> from nanoutils import supports_float
>>> supports_float(1.0)
True
>>> supports_float(1)
... |
def counting_stats(response_stat_collection: dict) -> int:
"""
Count a correct total of features in all collections
:param response_stat_collection: the collection field'd in response's statistics
:returns: count of all features
"""
count = 0
for stat_collection in response_stat_collection.... |
def read_labeled_image_forward_list(data_dir, data_list):
"""Reads txt file containing paths to images and ground truths.
Args:
data_dir: path to the directory with images and masks.
data_list: path to the file with lines of the form
'/path/to/image /path/to/image-labels'.
Ret... |
def get_right_child_index(parent_index, heap):
"""
Get the index of the right child given the
parent node's index.
"""
# Remember, this is a 1-based index.
if parent_index * 2 + 1 >= len(heap):
# There is no right child
return 0
return parent_index * 2 + 1 |
def grid_edge_is_closed_from_dict(boundary_conditions):
"""Get a list of closed-boundary status at grid edges.
Get a list that indicates grid edges that are closed boundaries. The
returned list provides a boolean that gives the boundary condition status
for edges order as [*bottom*, *left*, *top*, *rig... |
def _restrict_reject_flat(reject, flat, raw):
"""Restrict a reject and flat dict based on channel presence"""
reject = {} if reject is None else reject
flat = {} if flat is None else flat
assert isinstance(reject, dict)
assert isinstance(flat, dict)
use_reject, use_flat = dict(), dict()
for ... |
def calculate_bucket_count_in_heap_at_level(k, l):
"""
Calculate the number of buckets in a
k-ary heap at level l.
"""
assert l >= 0
return k**l |
def get_boundary_indicators_for_sorted_array(sorted_array):
"""
Parameters
----------
sorted_array: list[int]
Returns
-------
list[bool]
list[bool]
"""
start_indicators = [True]
for i in range(1, len(sorted_array)):
if sorted_array[i] != sorted_array[i - 1]:
... |
def cube_to_axial(c):
"""
Converts a cube coord to an axial coord.
:param c: A cube coord x, z, y.
:return: An axial coord q, r.
"""
x, z, _ = c
return x, z |
def extract_sticker_id(body):
"""
Obtains the sticker ID from the event body
Parameters
----------
body: dic
Body of webhook event
Returns
-------
str
file_id of sticker
"""
file_id = body["message"]["sticker"]["file_id"]
return file_id |
def mock_lookup_queue_length(url, request):
"""
Mocks an API call to check the queue length
"""
return {'status_code': 200,
'content-type': 'application/json',
'server': 'Apache',
'content': {
"supportId": "123456789",
"httpStatus": 200... |
def is_1_2(s, t):
"""
Determine whether s and t are identical except for a single character of
which one of them is '1' and the other is '2'.
"""
differences = 0
one_two = {"1", "2"}
for c1, c2 in zip(s, t):
if c1 != c2:
differences += 1
if differences == 2:
... |
def linear_combinaison(alpha = 1.0, m1 = {},
beta = None, m2 = {}):
"""
Return the linear combinaison m = alpha * m1 + beta * m2.
"""
if m2 == {}:
m2 = m1
beta = 0.0
m = {}
for (name, value) in m1.items():
m[name] = alpha * value + beta * m2.get(na... |
def if_else(n: int) -> str:
"""
>>> if_else(3)
'Weird'
>>> if_else(24)
'Not Weird'
"""
if n % 2 or 6 <= n <= 20:
return 'Weird'
return 'Not Weird' |
def ids2str(ids):
"""Given a list of integers, return a string '(int1,int2,...)'."""
return "(%s)" % ",".join(str(i) for i in ids) |
def int2bin(n, count=24):
"""returns the binary of integer n, using count number of digits"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) |
def _filter_direct_matching(key: dict, all_data: list, *, inverse: bool=False) -> tuple:
"""Filter through all data to return only the documents which match the key.
`inverse` keyword-only argument is for those cases when we want to retrieve all documents which do NOT match the `check`."""
if not inverse:
... |
def new_metric(repo_name: str, metric_name: str, metric_value: float) -> dict:
"""Creates a new metric in the format required for CloudWatch
:param repo_name: the repository name to associate with the metric
:type repo_name: str
:param metric_name: the name of the metric
:type metric_name: str
... |
def mmHg_to_unit(p):
"""
Converts pressure value in mmHg to g cm-1 s-2.
Arguments
---------
p : float
Pressure value in mmHg
Returns
-------
return : float
Pressure value in g cm-1 s-2
"""
return 101325/76*p |
def validate_format(input_format, valid_formats):
"""Check the input format is in list of valid formats
:raise ValueError if not supported
"""
if not input_format in valid_formats:
raise ValueError('{} data format is not in valid formats ({})'.format(input_format, valid_formats))
return inp... |
def swap_row(content, row_index, row_info=[]):
"""
Swap row position into the table
Arguments:
- the table content, a list of list of strings:
- First dimension: the columns
- Second dimensions: the column's content
- cursor index for col
- cursor index for... |
def field_items_text(content):
"""
Creates a comma separated string of values for a particular field
"""
if len(content):
tag = content[0].find_all(class_="field-items")[0]
if len(tag.contents):
return ', '.join([c.text for c in tag.contents])
else:
return... |
def compact_date(date):
"""
Converts an ISO 8601 format date string into a compact date.
Parameters
----------
Date: a string date in iso format.
Returns
----------
A string date without hyphens.
"""
return date.replace('-', '') |
def get_number_of_anchor_boxes_per_anchor_point(scale:list,aspect_ratio:list):
"""Gets the number of bounding boxes per anchor point from the scale and aspect_ratio list"""
return len([ar+s for ar in aspect_ratio for s in scale]) |
def bspline_numba(p, j, x):
"""Return the value at x in [0,1[ of the B-spline with
integer nodes of degree p with support starting at j.
Implemented recursively using the de Boor's recursion formula"""
assert ((x >= 0.0) & (x <= 1.0))
if p == 0:
if j ==... |
def parse_bool(value, additional_true=None, additional_false=None):
"""Parses a value to a boolean value.
If `value` is a string try to interpret it as a bool:
* ['1', 't', 'y', 'true', 'yes', 'on'] ==> True
* ['0', 'f', 'n', 'false', 'no', 'off'] ==> False
Otherwise raise TypeError.
A... |
def _get_defined_keywords(section_string):
""" gets a list of all the keywords defined in a section
"""
defined_keys = []
for line in section_string.splitlines():
tmp = line.strip().split(' ')[0]
defined_keys.append(tmp.strip())
return defined_keys |
def verify(text):
"""Verify that the url is valid in a very simple manners."""
if 'anonfiles.com' in text:
return True
return False |
def set_level(request, level):
"""
Sets the minimum level of messages to be recorded, returning ``True`` if
the level was recorded successfully.
If set to ``None``, the default level will be used (see the ``get_level``
method).
"""
if not hasattr(request, '_messages'):
return False
... |
def get_center(box):
"""
Get bounding box centeroid.
Arguments:
box (list): List of bounding box coordinates returned from Azure Cognitive Services API.
The list would comprise of x-coordinate, y-coordinate from the left-top corner of the image.
Return:
center (Dict... |
def _dict_to_object(dict_):
"""
Convert a dictionary loaded from a JSON file to an object
"""
if '__class__' in dict_:
module = __import__(dict_['__module__'], fromlist=[dict_['__class__']])
klass = getattr(module, dict_['__class__'])
# Check that this is a class that we're expec... |
def is_lego_id(vid, pid):
"""Determine if a LEGO Hub by checking the vendor id and product id."""
# Values obtained from PyBricks project: https://github.com/pybricks/technical-info/blob/master/assigned-numbers.md
# 0x0694 0x0008 LEGO Technic Large Hub in DFU mode (SPIKE Prime)
# 0x0694 0x0009 LEGO Tech... |
def read_file(file_name: str):
"""read file
"""
with open(file_name) as f:
return f.read() |
def jsonapi_id_schema(value=None):
"""Generate a Cerberus schema for validating a JSONAPI id value.
:param value: The required value for the id value [optional]
:type value: ``string``
:return: A Cerberus schema for the JSONAPI id value
"""
if value:
return {'type': 'string',
... |
def cross_entropy_cost_derivative(a, y):
"""The derivative of the cross-entropy cost function. This function is
used in backpropagation to calculate the error between the output of the
network and the label. Where 'a' is the network input and 'y' is the
label."""
return (a - y) |
def _is_subclass(obj, superclass):
"""Safely check if obj is a subclass of superclass."""
try:
return issubclass(obj, superclass)
except Exception:
return False |
def ComputeIntercoPfx(svlan):
""" Generates a 100.64/10 prefix based on the svlan-id
Output if svlan=1001 : 100.67.233
"""
byte1 = 100
byte2 = 64 + int(svlan/256)
byte3 = svlan%256
return str(byte1)+"."+str(byte2)+"."+str(byte3) |
def make_protein_index(proteins):
"""Indexes proteins."""
prot_index = {}
skip = set(['sp', 'tr', 'gi', 'ref'])
for i, p in enumerate(proteins):
accs = p.accession.split('|')
for acc in accs:
if acc in skip:
continue
prot_index[acc] = i
return ... |
def satoshi_str(number):
"""
string prices rounded to satoshi
"""
return "%.8f" % float(number) |
def process_size(size):
"""
Docker SDK provides size in bytes, which is processed here to
provide Docker CLI-like output.
"""
final_size = ''
if size < 1000:
final_size = f'{size}B'
elif size > 1000 and size < 1000000:
size = round(size / 1000, 1)
final_size = f'{size... |
def _select_pattern_problem(prob, patterns):
"""
Selects a benchmark type based on the problem kind.
"""
if '-reg' in prob:
return patterns['regressor']
if '-cl' in prob and '-dec' in prob:
return patterns['classifier_raw_scores']
if '-cl' in prob:
return patterns['classi... |
def find_the_duplicate(nums):
"""Find duplicate number in nums.
Given a list of nums with, at most, one duplicate, return the duplicate.
If there is no duplicate, return None
>>> find_the_duplicate([1, 2, 1, 4, 3, 12])
1
>>> find_the_duplicate([6, 1, 9, 5, 3, 4, 9... |
def eq_of_motion(t, w, p):
""" A simple mass with a force input
Arguments:
w : the states, [x, x_dot]
t : the current timestep
p : the parameters
p = [m, curr_force]
Returns:
sysODE : 1st order differential equations
"""
m, curr_force = p
sysO... |
def xyzw_to_wxyz(arr):
"""
Convert quaternions from pyBullet to numpy.
"""
return [arr[3], arr[0], arr[1], arr[2]] |
def _contains_access_modifier(line):
"""Checks whether the line contains some Java access modifier in it.
Args:
line: the line to check.
Returns:
bool: `True` if the line contains access modifier and `False` otherwise.
"""
return 'public ' in line or 'private ' in line or 'protecte... |
def get_first_text_flag(config):
"""Creates a valid flag with the flag format using the flag format and the first text flag, if it exists.
Args:
config (dict): The normalized challenge config
Returns:
string: A valid flag. May be an empty string, in which case it's probably not a valid fla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.