content stringlengths 42 6.51k |
|---|
def construct_url(*components):
"""Concetenate strings to URL."""
separator = '/'
url = separator.join(components)
return url |
def blob_name(i):
"""
Implements legacy schema for blobs naming:
0-th blob is called 'weights'
1-th blob is called 'biases'
then, next blobs are called according to the new default schema
with 'custom_' prefix: custom_2, custom_3 and so on.
"""
predefined_names = ['weights', 'bia... |
def func_exp(x, a, b, c):
"""Fit an exponential function."""
return a * x + b * x ** 2 + c |
def count_words(text):
"""
Counts the number of words in a text
:param text: The text you want to count the words in
:return: The number of words in the text.
"""
text = text.split()
return len(text) |
def lengthOfLongestSubstring(s):
"""
:type s: str
:rtype: int
"""
res = ""
n = 0
for i in s:
if i not in res:
res = res + i
else:
indexofi = res.find(i)
res = res[indexofi+1::] + i
k = len(res)
if k > n:
n = k
... |
def _get_movie_from_list(movies, sapo_title, sapo_description):
"""Get movie from list of movies to add if exists"""
for m in movies:
if m.sapo_title == sapo_title and m.sapo_description == sapo_description:
return m
return None |
def update(event, context):
"""
Place your code to handle Update events here
To return a failure to CloudFormation simply raise an exception, the exception message will be sent to
CloudFormation Events.
"""
physical_resource_id = event["PhysicalResourceId"]
response_data = {}
return phy... |
def hex_to_rgb(hexcode):
"""
Convert Hex code to RGB tuple
"""
return (int(hexcode[-6:-4], 16), int(hexcode[-4:-2], 16), int(hexcode[-2:], 16)) |
def key_parse(keystring):
"""
parse the keystring/keycontent into type,key,comment
:param keystring: the content of a key in string format
"""
# comment section could have a space too
keysegments = keystring.split(" ", 2)
keystype = keysegments[0]
key = None
comment = None
if len... |
def _nint(str):
"""
Nearest integer, internal use.
"""
# return int(float(str)+0.5)
x = float(str)
if x >= 0: return int(x+0.5)
else: return int(x-0.5) |
def get_signed_headers(headers):
"""
Get signed headers.
:param headers: input dictionary to be sorted.
"""
signed_headers = []
for header in headers:
signed_headers.append(header.lower().strip())
return sorted(signed_headers) |
def strConcat(strings : list) -> str:
"""Concatenate a list of string objects
Parameters
----------
strings
list of input strings to concatenate
Returns
-------
concatenated string
"""
return "".join(map(str, strings)) |
def pointer_pack(first, second):
"""Ex. pointer_pack(0xab, 0xcd) == 0xabcd"""
return (first << 8) + second |
def build_empty_list(size):
"""Build empty List.
Args:
size (int): Size.
Returns:
list: List of size with 'None' values.
"""
build = []
for _ in range(size):
build.append(None)
return build |
def trim_txt(txt, limit=10000):
"""Trim a str if it is over n characters.
Args:
txt (:obj:`str`):
String to trim.
limit (:obj:`int`, optional):
Number of characters to trim txt to.
Defaults to: 10000.
Returns:
:obj:`str`
"""
trim_line =... |
def create_filename(file_name: str, extension: str) -> str:
"""
Replaces white spaces of the string with '-' and
adds a '.' and the extension to the end.
:param file_name: File name
:param extension: File extension
:return: str Transformed filename
"""
return file_name.replace(' ', '-') ... |
def linear_warmup_learning_rate(current_step, warmup_steps, base_lr, init_lr):
"""Construct the trainer of SpNas."""
lr_inc = (float(base_lr) - float(init_lr)) / float(warmup_steps)
learning_rate = float(init_lr) + lr_inc * current_step
return learning_rate |
def delete_empty_values(d):
"""
removes empty values from a dictionary
to prevent uneccessary metadata key transmission
"""
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in (delete_empty_values(v) for v in d) if v]
return {k: v for k, v ... |
def k2j(k, E, nu, plane_stress=False):
"""
Convert fracture
Parameters
----------
k: float
E: float
Young's modulus in GPa.
nu: float
Poisson's ratio
plane_stress: bool
True for plane stress (default) or False for plane strain condition.
Returns
... |
def linear_search(alist, key):
""" Return index of key in alist . Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1 |
def kth_ugly_number(k):
"""
Find kth ugly number
:param k: given k
:type k: int
:return: kth ugly number
:rtype: int
"""
# list of ugly numbers
ugly_numbers = [0] * k
# 1 is the first ugly number
ugly_numbers[0] = 1
# indices of multiplier
i_2 = i_3 = i_5 = 0
# v... |
def channel_frequency(channel, frequency):
"""
Takes a WiFi channel and frequency value and if one of them is None,
derives it from the other.
"""
new_channel = channel
new_frequency = frequency
if (frequency is None and channel is not None):
if 0 < channel < 14:
# 2.4 GH... |
def nest(dict_in, delim="__"):
"""Nests the input dict by splitting keys (opposite of flatten above)"""
# We will loop through all keys first, and keep track of any first-level keys
# that will require a recursive nest call. 'renest' stores these keys
output, renest = {}, []
for key in dict_in:
... |
def reform(data):
"""Turn a grid into raw pixels"""
new_data = b""
for all_ in data:
for cols in all_:
new_data += bytes(cols)
return new_data |
def checkForRequiredField(form, *fields):
"""Check if all required fields are available"""
for f in fields:
if(len(form[f].strip()) == 0):
return False
return True |
def all_subarray(flag=True):
"""When `flag` is True, mark this constraint as applying to all SUBARRAY forms,
including full frame, as long as SUBARRAY is defined. Returns "A" or False.
>>> all_subarray(True)
'A'
>>> all_subarray(False)
False
"""
return "A" if flag else False |
def filter_niftis(candidates):
"""
Takes a list and returns all items that contain the extensions '.nii' or '.nii.gz'.
"""
candidates = list(filter(lambda x: 'nii.gz' == '.'.join(x.split('.')[1:]) or
'nii' == '.'.join(x.split('.')[1:]), candidates))
return candi... |
def SetFieldValue(regValue, lsb, fsize, fieldValue):
"""
An internal utility function to assign a field value to a register value.
Perform range check on fieldValue using fsize.
:type regValue: ``int`` or ``long``
:param regValue: The value of the register to parse
:type lsb: ``int``
:par... |
def _get_alias(full_or_partial_id):
"""
Returns the alias from a full or partial id
Parameters
----------
full_or_partial_id: str
Returns
-------
str
"""
# Note that this works for identifiers of all types currently described in the spec, i.e.:
# 1. did:factom:f0e4c2f76c589... |
def is_hexstring(string):
"""
Determines if a string is a hexstring.
:param Union[ByteString, str] string: A string.
:return: Whether the string's length is even and all of its characters
are in [0-9a-fA-f].
"""
if isinstance(string, str):
string = string.encode()
return not ... |
def frame_attrs_from_set(frame_set):
"""
A `dict` of all the attributes of all frame classes in this
`TransformGraph`.
Broken out of the class so this can be called on a temporary frame set to
validate new additions to the transform graph before actually adding them.
"""
result = {}
fo... |
def deep_merge(base, changes):
"""
Create a copy of ``base`` dict and recursively merges the ``changes`` dict.
Returns merged dict.
:type base: dict
:param base: The base dictionary for the merge
:type changes: dict
:param changes: The dictionary to merge into the base one
:return: The... |
def results_list_to_tsv(results):
"""
Format a list of SearchResults into a TSV (Tab Separated Values) string.
:param results: a list of SearchResults
:type results: list[sr_parser.SearchResult]
:return: string in TSV format
:rtype: str
"""
results_tab_separated = [str(res) for res in r... |
def como_mutable(matriz):
"""Obtener una copia mutable de `matriz`."""
return [list(fila) for fila in matriz] |
def merge(arrayA, arrayB, k):
""" As A has enough buffer to store all numbers of B, we need
to use k to indicate the end of A.
i is used to indicate the tail of A's unsorted numbers.
j is used to indicate the tail of B's unsorted numbers.
tail is the tail of the result.
"""
N... |
def bits2positions(bits):
"""Converts an integer in the range 0 <= bits < 2**61 to a list of integers
in the range 0 through 60 inclusive indicating the positions of the nonzero bits.
Args:
bits:
int. An integer in the range 0 <= bits < 2 ** 61
Returns:
A list of integers i... |
def isSorted(lyst):
"""
Return whether the argument lyst is in non-decreasing order.
"""
for i in range(1, len(lyst)):
if lyst[i] < lyst[i-1]:
return False
return True |
def gcd(a, b):
"""Find greatest common divisor."""
while b > 0:
a, b = b, a % b
return a |
def split_args_extra(args):
"""
Separate main args from auxiliary ones.
"""
try:
i = args.index('--')
return args[:i], args[i + 1:]
except ValueError:
return args, [] |
def worker_exploration(worker_index, num_workers):
"""
Computes an exploration value for a worker
Args:
worker_index (int): This worker's integer index.
num_workers (int): Total number of workers.
Returns:
float: Constant epsilon value to use.
"""
exponent = (1.0 + worker... |
def _pad_norm_assert_noshape(outputs):
"""Assert Masked BN/GN w/o spatial shape returns None shape."""
outputs, spatial_shape = outputs
assert spatial_shape is None
return outputs, [] |
def _interpolate_target(bin_edges, y_vals, idx, target):
"""Helper to identify when a function y that has been discretized hits value target.
idx is the first index where y is greater than the target
"""
if idx == 0:
y_1 = 0.
else:
y_1 = y_vals[idx - 1]
y_2 = y_vals[idx]
edg... |
def simple_logged_task(a, b, c): # pylint: disable=invalid-name
"""
This task gets logged
"""
return a + b + c |
def is_same_class_or_subclass(target, main_class):
"""
checks if target is the same class or a subclass of main_class
:param target:
:param main_class:
:return:
"""
return isinstance(target, main_class) or issubclass(target.__class__, main_class) |
def prune_species(components):
"""Remove any duplicates and set stoichiometries"""
unique_names = set(species.name for species in components)
unique_species = []
for name in unique_names:
identical_species = [s for s in components if s.name == name]
# Add this species only once
... |
def debian_package_install(packages, clean_package_cache=True):
"""Jinja utility method for building debian-based package install command.
apt-get is not capable of installing .deb files from a URL and the
template logic to construct a series of steps to install regular packages
from apt repos as well ... |
def _nh(name):
"""
@return: Returns a named hex regex
"""
return '(?P<%s>[0-9a-f]+)' % name |
def unique(seq):
"""use this instead of list(set()) to preserve order of the original list.
Thanks to Stackoverflow: http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
seen = set()
seen_add = seen.add
return [ x for x in seq if not (x in seen or... |
def set(byte: int, index: int) -> int:
"""Set bit at index to 1."""
assert 0 <= byte <= 255
assert 0 <= index <= 7
return byte | (1 << index) |
def check_unexpected(lines, recipes):
"""Check for unexpected output lines from dry run"""
unexpected = []
for line in lines.splitlines():
if 'Running task' in line:
for recipe in recipes:
if recipe in line:
break
else:
line... |
def _plugin_import(plug):
"""
Tests to see if a module is available
"""
import sys
if sys.version_info >= (3, 4):
from importlib import util
plug_spec = util.find_spec(plug)
else:
import pkgutil
plug_spec = pkgutil.find_loader(plug)
if plug_spec is None:
... |
def search(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums :
return -1
left = 0
right = len(nums) - 1
while left <= right :
mid = (left + right) >> 1
if nums[mid] == target :
return mid
if nums[0] <= n... |
def find_all_indexes(text, pattern):
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# ins... |
def has_all_tags(span, tags):
"""
Tests if `tags`'s are all in a certain trace span
"""
return tags.items() <= span.get("tags").items() |
def set_format(data):
"""Set the data in the requested format.
(1) Devide into 8 bits.
(2) Convert to the format 'XXXX XXXX'.
"""
n = len(data)
data_list = []
for i in range(0, n, 8):
data_temp = ''.join(data[i:i+4]) + ' '
data_temp = data_temp + ''.join(data[i+4:i+8])
... |
def IsQACup(cup):
"""
Given inner cup checks if it is QA or a clinical one
Parameters
----------
cup: string
Inner cup series
returns: boolean
True if QA, False otherwise
"""
return cup == "Q" |
def get_rolled_fn(logfile, rotations):
"""Helper to get filename of |logfile| after |rotations| log rotations."""
return '%s.%d' % (logfile, rotations) |
def roundto(val,decimal:int=8,force:bool=False):
"""
Better round function which works with complex numbers and lists
val:Any; value to round
decimal:int>=0; decimal places to round to
force:bool; force value rounding as complex number rounding
"""
if isinstance(val,complex) or force:
... |
def check_ship_direction(head, tile):
"""
Return whether ship is placed horizontally ("H") or vertically ("V")
"""
h_c, h_r = head[0], head[1]
t_c, t_r = tile[0], tile[1]
if h_r == t_r:
return "H"
elif h_c == t_c:
return "V"
else:
raise ValueError(
"Y... |
def MakeDeclarationString(params):
"""Given a list of (name, type, vectorSize) parameters, make a C-style
parameter declaration string.
Ex return: 'GLuint index, GLfloat x, GLfloat y, GLfloat z'.
"""
n = len(params)
if n == 0:
return 'void'
else:
result = ''
i = 1
for (name, type, vecSize) in params:
... |
def weeks_elapsed(day1: int, day2: int) -> int:
"""
def weeks_elapsed(day1, day2): (int, int) -> int
day1 and day2 are days in the same year. Return the number of full weeks
that have elapsed between the two days.
>>> weeks_elapsed(3, 20)
2
>>> weeks_elapsed(20, 3)
2
>>> weeks_elapse... |
def _underline(text):
"""Format a string by overstriking."""
return ''.join('_' + '\b' + ch for ch in text) |
def unicoded(s:str)->str:
"""
Recursively finds the first occurance of \\u and either corrects or
keeps it. Decision is based on amount of backslashes: if the printed
version has even, then they are all escape-character sequences.
On very long lines, recursion limits occur. Reverting to loop-based ... |
def benchmark_select_skl_metric(metric: str) -> str:
"""
Convert `MuyGPyS` metric names to `scikit-learn` equivalents.
Args:
metric:
The `MuyGPyS` name of the metric.
Returns:
The equivalent `scikit-learn` name.
Raises:
ValueError:
Any value other t... |
def fetch_image_url(item, key="images"):
"""Fetch image url."""
try:
return item.get(key, [])[0].get("url")
except IndexError:
return None |
def try_helper(f, arg, exc=AttributeError, default=''):
"""Helper for easy nullable access"""
try:
return f(arg)
except exc:
return default |
def dimensionalize_pressure(p, config_dict):
""" Function to dimensionalize pressure
Function 'dimensionalize_pressure' retrurns the pressures values
dimensionalize accorind to data from the SU2 configuration file
Args:
p (list): Pressure values
config_dict (dict): SU2 cfg file diction... |
def greet2(name:str):
"""Stack example function."""
print("How are you, " + name + "?")
return None |
def _num_extreme_words(words, extreme_words, average=True):
""" Count the number of common words
Inputs:
words (list of string): to be checked
extreme_words (set of string or dict[string] -> float): common words set
Returns:
tuple or list of int: # of extreme words in each extreme ... |
def unshuffle(l, order):
""" unshuffles list given shuffled index """
l_out = [0] * len(l)
for i, j in enumerate(order):
l_out[j] = l[i]
return l_out |
def iso7816_4_unpad(padded):
"""Removes ISO 7816-4 padding"""
msg_end = padded.rfind(b'\x80')
if msg_end == -1 or any(x for x in padded[msg_end+1:]):
raise ValueError(f'Invalid padding')
return padded[:msg_end] |
def parse_db_result(result):
"""Returns a Rate object from the data from the database"""
return {'from':result[1], 'to':result[2], 'date':result[0], 'rate':result[3]} |
def tau_h(R0, vsc):
"""Arnett 1982 expansion timescale, in days
R0: initial radius in cm
vsc: scaling velocity in cm/s
"""
return (R0/vsc) / 86400.0 |
def revoke_role(role, target):
"""Helper method to construct SQL: revoke privilege."""
return f"REVOKE {role} from {target};" |
def bearer_auth(req, authn):
"""
Pick out the access token, either in HTTP_Authorization header or
in request body.
:param req:
:param authn:
:return:
"""
try:
return req["access_token"]
except KeyError:
assert authn.startswith("Bearer ")
return authn[7:] |
def linspace(minimum, maximum, count):
"""a lazy reimplementation of linspace
because I often need linspace but I'm too lazy to import a module that would provide it.
NB this version includes both end-points, which might make the step not what you expect.
"""
if maximum <= minimum:
rais... |
def _min_max(x, xmin, xmax):
"""
Defines a function which enforces a minimum and maximum value.
Input: x, the value to check.
Input: xmin, the minumum value.
Input: xmax, the maximum value.
Output: Either x, xmin or xmax, depending.
"""
# Check if x is less than the minimum. If so, return the minimum.
if x < x... |
def convert_box(box):
"""[x, y, w, h] to x1, y1, x2, y2."""
x, y, w, h = box
return [x, y, x + w, y + h] |
def find_snippet(text, start, end, skip=(0, 0)):
"""Find snippet in text
:param text: Text to search in
:type text: str
:param start: Where to start grabbing text
:type start: str
:param end: Where to stop grabbing text and return
:type end: str
:param skip: Number of character to trim ... |
def launch_piece_letter_to_number(letters):
"""Convert 24 upper case letter 3-letter code to integer, omitting I (eye) and O (oh) from the alphabet.
The TLE standard is 24 upper case letter 3-letter code, omitting I (eye) and O (oh) from the alphabet,
with no representation for zero.
The 1st p... |
def set(d, *item):
"""Set a value in the nested dict `d`.
Any subdictionaries created in this process are of the same type as `d`. Note that this
implies the requirement that `d`s type have a zero-argument constructor.
"""
*intermediate_keys, last_key, value = item
create_intermediate_dicts = F... |
def prepend_list(base_word: str, prepend: list, separator: str='') -> list:
"""Inserts list:prepend at beginning of str:base_word
with default str:separator='', returns a list
"""
return [f'{pre}{separator}{base_word}' for pre in prepend] |
def switch_testing(fuel_switches, service_switches, capacity_switches):
"""Test if swithes defined for same enduse
Arguments
---------
fuel_switches : list
Switches
service_switches : list
Switches
capacity_switches : list
Switches
"""
all_switches_incl_sectors =... |
def min_max(num1, num2) -> tuple:
"""
Gets the min and max of the provided values
:param num1: first number
:param num2: second number
:return: -> (min, max)
"""
return (min(num1, num2), max(num1, num2)) |
def prob6(limit=100):
"""
The sum of the squares of the first ten natural numbers is,
1**2 + 2**2 + ... + 10**2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)**2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten
natural n... |
def manhattan_distance(a, b):
""" Return the Manhattan distance between points A and B (both tuples). """
return abs(a[0] - b[0]) + abs(a[1] - b[1]) |
def _reverse_table(table):
"""Return value: key for dictionary."""
return {value: key for (key, value) in table.items()} |
def check_rows(board):
"""
list -> bool
This function checks if every row has different numbers and returns
True is yes, and False if not.
>>> check_rows(["**** ****", "***1 ****", "** 3****", "* 4 1****", \
" 9 5 ", " 6 83 *", "3 1 **", " 8 2***", " 2 ****"])
True
>>> check_ro... |
def zeemanLande(S, N, J):
"""
Return the Zeeman splitting factor in Hz/microG
"""
if (J == 0):
gJ = 0.0
else:
gJ = (J*(J+1)+S*(S+1)-N*(N+1)) / (J*(J+1))
return gJ |
def index(fks, id):
"""Looks for the id on fks, fks is an array of arrays, each array has on [1]
the id of the class in a dia diagram. When not present returns None, else
it returns the position of the class with id on fks"""
for i, j in fks.items():
if fks[i][1] == id:
return i
... |
def linear_mass(t, ttrunc, m):
"""Integrate (1-m*(a-ttrunc)) da from a=ttrunc to a=t
"""
tt = t - ttrunc
return ((tt + ttrunc * m * tt) - m/2. * (t**2 - ttrunc**2)) |
def join_chunks(chunks):
"""empty all chunks out of their sub-lists to be split apart again by split_chunks(). this is because chunks now
looks like this [[t,t,t],[t,t],[f,f,f,][t]]"""
return [item for sublist in chunks for item in sublist] |
def optimize_highlight(lst):
"""Optimize a highlight list (s1, n1), ... by combining parts that have
the same color.
"""
if len(lst) == 0:
return lst
else:
prev = lst[0]
new_lst = []
for s, n in lst[1:]:
if s.strip() == "" or prev[1] == n:
... |
def getThreshhold(g: int, n: int, alpha: float = 0.06, d=0.1, zeta=1) -> float:
"""
`returns` minimum vector movement threshold
Paremeters
----------
`g`: current generation/iteration
`n`: total number of iterations
`alpha`: fraction of the main space diagonal
`d`: initial value of thre... |
def create_table(order:int) -> str:
"""
create a table to store polynomial root information
"""
query = "CREATE TABLE IF NOT EXISTS polynomials (id text primary key, "
params = ["root{} int, iroot{} int".format(root, root) for root in range(order)]
return query + ', '.join(params) + ");" |
def build_suffix_tree(text):
"""
Build a suffix tree of the string text and return a list
with all of the labels of its edges (the corresponding
substrings of the text) in any order.
"""
result = []
# Implement this function yourself
return result |
def add_versions(nodes, versions):
"""
In Dutch rechtspraak.nl data, an version can have an annotation.
:param nodes: list of node objects
:param versions: list of versions
:return: list of nodes
"""
count_version = {}
count_annotation = {}
for item in versions:
id0 = item['... |
def is_affine_st(A, tol=1e-10):
"""
True if Affine transform has scale and translation components only.
"""
(_, wx, _, wy, _, _, *_) = A
return abs(wx) < tol and abs(wy) < tol |
def RLcoeffs(index_k, index_j, alpha):
"""Calculates coefficients for the RL differintegral operator.
see Baleanu, D., Diethelm, K., Scalas, E., and Trujillo, J.J. (2012). Fractional
Calculus: Models and Numerical Methods. World Scientific.
"""
if index_j == 0:
return ((index_k... |
def update_connections(existing, new):
"""
This will update the connections dictonary
"""
for new_key in new.keys():
if new_key not in existing.keys():
existing[new_key] = new[new_key]
else:
existing[new_key] += new[new_key]
return existing |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.