content stringlengths 42 6.51k |
|---|
def hook_get_load_data_query(table: str, current_date: str) -> str:
"""Returns the query to load the customer transactions.
Here it is possible to filter just new customers or other customer
groups.
Args:
table: A string representing the full path of the BQ table where the
transactions are located. ... |
def binary_search_iterative(arr: list, key) -> int:
"""Returns index of key in sorted arr if key is in arr, else -1.
Implements:
https://en.wikipedia.org/wiki/Binary_search_algorithm#Algorithm
"""
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == key:
... |
def CheckToDelete(MasterStationList,data_files):
"""
Extract file names on server, and check if any which are not in
master station list
These already may not exist on the local system
"""
RemoteStations=[]
for dfile in data_files:
RemoteStations+=[dfile.filen.split('.')[0][:-5]]
... |
def invert_dict(d):
"""Return a dictionary whose keys are the values of d, and whose
values are lists of the corresponding keys of d
"""
inverse = dict()
for key in d:
val = d[key]
inverse.setdefault(val,[]).append(key)
return inverse |
def parse_response(browse_nodes_response_list):
"""
The function parses Browse Nodes Response and creates a dict of BrowseNodeID to BrowseNode object
:param browse_nodes_response_list: List of BrowseNodes in GetBrowseNodes response
:return: Dict of BrowseNodeID to BrowseNode object
"""
mapped_re... |
def canvas_rect(dw, dh):
"""Resizes a canvas dimensions so that it better fits on client browser."""
ar = dw / dh
h = 400 if ar > 3 else 500
w_min = 300
w_max = 1000
w = int(ar * h)
if w > w_max: w = w_max
if w < w_min: w = w_min
return ... |
def latest(scores):
"""Get last added score.
Args:
scores: list of positive integers
Returns:
An integer representing the latest score
"""
return scores[-1] |
def toGoatLatin(S):
"""
:type S: str
:rtype: str
"""
count=1
sentences=S.split()
for i in range(len(sentences)):
if sentences[i][0].lower() in "aeiou":
sentences[i]+="ma"+count*"a"
else:
sentences[i]=sentences[i][1:]+sentences[i][0]+'ma'+count*"a"
count+=1
return " ".join(sentences) |
def superset(alldicts):
""" Returns dict containing all keys from the dicts contained in `alldicts`
:param dict alldicts: a dictionary containing dictionaries"""
superdict = {}
for dict_ in alldicts.values():
superdict.update(dict_)
return superdict |
def truncate_text(text: str, limit: int = 256) -> str:
"""Truncate a given `text` if the `limit` is reached"""
if limit <= 0:
raise ValueError("limit must be greater than 0")
return text[:limit] + "..." if len(text) > limit else text |
def default_url_filter(url_list: list) -> list:
"""Filters out URLs that are to be queried.
Args:
url_list: List of URL with metadata dict object.
Returns:
List of URL with metadata dict object that need to be queried.
"""
ret_list = []
for cur_url in ur... |
def calculate_percentages(counts):
"""
Given a list of (token, count) tuples, create a new list (token,
count, percentage) where percentage is the percentage number of
occurrences of this token compared to the total number of tokens.
Arguments:
counts (list of (str or unicode, int)): tuples... |
def parse_weights(weights):
"""Parse loss weights from configuration setting.
Args:
weights: weights in configuration
Return:
a list where each element is the weight as float
"""
weights = weights.split(",")
weights = [float(w) for w in weights]
return weights |
def format_session_uri(reana_server_url, path, access_token):
"""Format interactive session URI."""
return "{reana_server_url}{path}?token={access_token}".format(
reana_server_url=reana_server_url,
path=path, access_token=access_token) |
def get_shapes(tensor5s):
"""Return shapes of a list of tensors"""
return [t['shape'] for t in tensor5s] |
def list_files_in_directory(path):
"""
Get a list of files within a given directory
"""
import glob
return glob.glob(path + "/*") |
def crc32_tab_rev(prev, crctab, byte):
"""
return next = crc32(prev, byte)
crc32(p0,b0) ^ crc32(p1,b1) = crc32(p0^p1, b0^b1)
"""
return crctab[(prev^byte)&0xff] ^ (prev>>8) |
def parse_colon_delimited_options(option_args):
"""Parses a key value from a string.
Args:
option_args: Key value string delimited by a color, ex: ("key:value")
Returns:
Return an array with the key as the first element and value as the second
Raises:
ValueError: If the key value option is ... |
def verifica_punct(punct, linii, coloane):
"""Verifica daca un anumit punct se afla in interiorul imaginii
"""
return 0 <= punct[0] < linii and 0 <= punct[1] < coloane |
def _humanize_time(amount, units):
"""Chopped and changed from http://stackoverflow.com/a/6574789/205832"""
intervals = (1, 60, 60 * 60, 60 * 60 * 24, 604800, 2419200, 29030400)
names = (
("second", "seconds"),
("minute", "minutes"),
("hour", "hours"),
("day", "days"),
... |
def _nearesthr(t=0):
"""Top of the hour nearest within 30 minutes"""
hr=3600
d=t%hr
if d<1800:
hr=0
return t+hr-d |
def normalize_alef_maksura_safebw(s):
"""Normalize all occurences of Alef Maksura characters to a Yeh character
in a Safe Buckwalter encoded string.
Args:
s (:obj:`str`): The string to be normalized.
Returns:
:obj:`str`: The normalized string.
"""
return s.replace(u'Y', u'y') |
def distance_steps(wire_coords, point):
"""Calculate the distance in steps for a wire to reach a point"""
dist = 0
for coord in wire_coords:
dist += 1
if coord == point:
break
return dist |
def generate_id(list):
""" Creates a unique ID for a new item to be added to the list"""
return len(list) + 1 |
def group_by(resources, key):
"""Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup
"""
resource_map = {}
parts = key.split('.')
for r in resources:
v = r
for k in parts:
v = v.get... |
def forwardCost(item, problem, heuristic):
"""Find forward cost which is heuristic"""
# heuristic None means null so return Zero
if heuristic is None:
return 0
return heuristic(item[0], problem) |
def main(textlines, messagefunc, config):
"""
KlipChop func to to join lines together using the joiner character
"""
result = list(textlines())
count = len(result)
result = config['joiner'].join(result)
messagefunc(f'Joined {count} lines')
return result |
def _is_pair(obj):
"""Helper to test if something is a pair (2-tuple)."""
return isinstance(obj, tuple) and len(obj) == 2 |
def find_missing_number(nums):
"""Returns the missing number from a sequence of unique integers
in range [0..n] in O(n) time and space. The difference between
consecutive integers cannot be more than 1. If the sequence is
already complete, the next integer in the sequence will be returned.
>>> find... |
def _filter_unique(tuple_list):
"""For a list of tuples [(distance, value), ...] - filter out duplicate
values.
Args:
tuple_list: List of tuples. (distance, value)
"""
added = set()
ret = []
for distance, value in tuple_list:
if not value in added:
ret.append((di... |
def int_parser(int_str: str) -> str:
"""Convert a numeric string to hex."""
return hex(int(int_str)) |
def unicode_unescape(value):
"""Convert escaped unicode and Python backslash values in str
Args:
value (str): contains escaped characters
Returns:
str: unescaped string
"""
if hasattr(value, 'decode'):
# py2
return value.decode('string_escape')
# py3
return v... |
def indent_string(string: str, amount: int) -> str:
"""
Indent a string by a given number of spaces.
Parameters
----------
string : str
The string to indent.
amount : int
The number of spaces to indent by.
Returns
-------
str
The indented string.
"""
... |
def _get_keyword(query):
"""
Calculate word len, used internally by is_begin_required
:param query: query
:return: keyword len, keyword
"""
query_len = len(query)
word_len = 0
while (word_len < query_len) and query[word_len].isalpha():
word_len += 1
keyword = query[0:word_le... |
def make_polynomial(coefficients: list) -> str:
"""Make a string polynomial from coefficients."""
polynomial = []
power = len(coefficients) - 1
# Create the polynomial
for i, a in enumerate(coefficients):
# If a is negative, add a minus sign between terms.
if i != 0:
if a... |
def remove_translation_suffix(value, arg):
""" Removes the '/de' component from page titles
Args:
value:
arg:
Returns:
str: The title without a translation suffix
"""
if arg in value:
return value.replace("/" + arg, "")
return value |
def build_metadata_from_setuptools_dict(metadata):
"""Build and return metadata from a setuptools dict.
This is typically from package metadata.
"""
# based on warehouse and virtualenv examples
# https://github.com/pypa/warehouse/blob/master/warehouse/templates/packaging/detail.html
# https://g... |
def xywh_to_xyxy(a):
""" Converts a single box from XYWH to XYXY format
a: box in XYWH coordinates
"""
return [a[0], a[1], a[0]+a[2]-1, a[1]+a[3]-1] |
def extract_lists(source_data):
"""Extract each item from a nested list into one list.
Takes a list which holds one list with a number of items. Extracts
each item so that it is one item in one list. Returns a list with
multiple items, from a list of one list.
Args:
source_data (list):... |
def reduced_digest(digest_peaks):
"""
Create a reduced version of the digest with only the M-xx ions, to be used in the step of normalization of
intensities
"""
output_dic = {}
for key in digest_peaks:
a = [x for x in digest_peaks[key][-1] if 'M-' in x.split("(")[0] or len(x.split("(")[0... |
def rev(s):
"""concatenates inside out"""
return len(s) != 0 and rev(s[1:]) + s[0] or s |
def status_from_tag(tag: str = "info") -> str:
"""
Determine Bootstrap theme status/level from Django's Message.level_tag.
"""
status_map = {
'warning': 'warning',
'success': 'success',
'error': 'danger',
'debug': 'info',
'info': 'info',
}
return status_ma... |
def get_trasnformed_dict(old_dict, transformation_dict):
"""
Returns a dictionary with the same values as old_dict, with the correlating key:value in transformation_dict
:type old_dict: ``dict``
:param old_dict: Old dictionary to pull values from
:type transformation_dict: ``dict``... |
def calc_compression(word_size, time_series_len=24):
"""
Calculated according to 'Application of time series discretization using evolutionary programming for classification
of precancerous cervical lesions' by H. Acosta-Mesa et al., 2014
:param word_size: wordsize chosen for the SAX algorithm. integer.... |
def clean_value(value):
""" This gets run on every value """
value = value.lstrip(" ") # Remove leading whitespace
if value=='NA': # Throw out NA's
return ''
return value |
def on_off(image, w, h, threshold=128):
"""
Black and white (no greyscale) with a simple threshold.
If the color is dark enough, the laser is on!
"""
result = []
for row in image:
result_row = []
for pixel in row:
# We draw black, so 255 is for dark pixels
... |
def _find_slice_interval(f, x, u, D, r, w=1.0):
"""Return approximated interval under f at height u."""
a = x - r*w
b = x + (1-r)*w
a_out = [a]
b_out = [b]
if a < D[0]:
a = D[0]
a_out[-1]= a
else:
while f(a) > u:
a -= w
a_out.append(a)
... |
def service_item(service, status, openapi, endpoints):
"""Function that sets the correct structure for service item
If status=='OK' and openapi is empty then:
* it is REST X-Road service that does not have a description;
* endpoints array is empty.
If status=='OK' and openapi is not empty then:
... |
def urlnoencode(query):
"""Convert a sequence of two-element tuples or dictionary into a URL query string
without url-encoding.
"""
output = []
arg = "%s=%s"
if hasattr(query, "items"):
# mapping objects
query = list(query.items())
for k, val in query:
output.append... |
def DUMMY(_workflow, view):
"""Never takes any action."""
return {v: None for v in view} |
def excel_column_label(n):
"""
Excel's column counting convention, counting from A at n=1
"""
def inner(n):
if n <= 0:
return []
if not n:
return [0]
div, mod = divmod(n - 1, 26)
return inner(div) + [mod]
return "".join(chr(ord("A") + i) for i... |
def hund_case_b_landau_g_factor(n, j, s, l, gs, gl):
""" Hund case B Landau g-factor
.. math::
g = g_s \\frac{J(J+1) + S(S+1) - N(N+1)}{2J(J+1)} +
g_l \\Lambda \\frac{J(J+1) - S(S+1) + N(N+1)}{2JN(J+1)(N+1)}
Parameters:
n (float): N of level
j (float): J of level
... |
def removesuffix(self: str, suffix: str) -> str:
"""[util] remove suffix from a string
XXX: use build-in method instead for Python 3.9:
s.removesuffix(suffix)
From https://www.python.org/dev/peps/pep-0616/
"""
if suffix and self.endswith(suffix):
return self[:-len(suffix)]
els... |
def has_flag(value: int, flag: int) -> bool:
"""
Checks if *flag* (or mask) is set in *value*
:param value: The value to check in
:param flag: The flag
:returns: True if *flag* is set in *value*, false otherwise
"""
return value & flag == flag |
def split(a, n):
"""
Splits an array into n arrays with an as-equal-as-possible distribution
ex. an array with 42 elements split into 4 groups will
"""
k, m = divmod(len(a), n)
return [x for x in (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n))] |
def remove_unused_Y(ar_iteration, dict_Y_predicted, dict_Y_to_remove):
"""Remove unused Y predictions of past AR iterations."""
list_idx_Y_to_remove = dict_Y_to_remove[ar_iteration]
if list_idx_Y_to_remove is not None:
for ldt in list_idx_Y_to_remove:
del dict_Y_predicted[ldt]
retur... |
def square_area(side):
"""Returns the area of a square"""
area = side ** 2
return area |
def js_quote(string):
"""Prepare a string for use in a 'single quoted' JS literal."""
string = string.replace('\\', r'\\')
string = string.replace('\'', r'\'')
return string |
def nand(bool1, bool2):
"""
Take two Boolean values bool1 and bool2
and return the specified Boolean values
"""
if bool1:
if bool2:
return False
else:
return True
else:
return True |
def _get_two_lowest(matching_terms, counts):
"""Gets two lowest frequency matching terms
Assumes that len(matching_terms) >= 2
Parameters
----------
matching_terms : {str}
The set of matching words
counts : {str: int}
A dictionary of word counts for the text from which the chun... |
def normalize_range(original_array, original_min, original_max, new_min, new_max):
""" Normalizing data to a new range (e.g. to [-1, 1] or [1, 1])
:param original_array: input array
:param original_min: current minimum (array, can be derived from a larger sample)
:param original_max: current max (arra... |
def quadratic_limb_darkening(mu, a_ld=0., b_ld=0.):
""" Define quadratic limb darkening model with two params. """
return 1. - a_ld * (1. - mu) - b_ld * (1. - mu)**2 |
def flatten_value_in_nested_dict(nested_dict, key_path):
"""Flatten a value within a nested dict.
eg.
If nested_dict = {'outer-key': {'inner-key': 'inner-value'}}
And key_path = 'outer-key.inner-value'
Then result = {'outer-key: 'inner-value'}
"""
val = nested_dict
for key i... |
def sort(_list):
"""
Bubble Sorting algorithm
:param _list: list of values to sort
:return: sorted values
"""
for i in range(len(_list)):
for j in range(len(_list) - 1, i, -1):
if _list[j] < _list[j - 1]:
_list[j], _list[j - 1] = _list[j - 1], _list[j]
re... |
def AND(bools):
"""Logical And."""
if False in bools:
return False
return True |
def out_of_bounds(pt, shape):
"""
Returns True if point is in the bounds given by shape, False if not.
Parameters
----------
pt : 2-tuple of ints
Point to check if out of bounds.
shape : 2-tuple of ints
Bounds (assuming from 0 to the values given in this tuple).
Returns :
... |
def diamond(n):
"""Display a diamond made of *.
Args:
n: (int) Amount of *s in the middle row.
Returns:
Diamond shaped text. None if input n is invalid.
"""
if n <= 0 or n % 2 == 0:
return None
offset = int((n - 1)/2)
# for i in range(offset + 1):
# shap... |
def getCallingCodes(phoneNumber):
"""
Returns the calling code for a phone number. () will be removed from calling codes for fixed lines
Assuming that fixed lines do not have a calling code that is (140)
"""
if phoneNumber.startswith("140"):
return "140"
if (
phoneNumber.... |
def is_iterable(x): # https://stackoverflow.com/a/1952481/6605826
"""Test if x is iterable"""
try:
iter(x)
except TypeError:
return False
else:
return True |
def binary_search(array, element):
"""
Perform Binary Search by Iterative Method.
:param array: Iterable of elements
:param element: element to search
:return: returns value of index of element (if found) else return None
"""
left = 0
right = len(array) - 1
while left <= right:
... |
def split_host(srv):
""" Split host:port notation, allowing for IPV6 """
if not srv:
return None, None
# IPV6 literal (with no port)
if srv[-1] == "]":
return srv, None
out = srv.rsplit(":", 1)
if len(out) == 1:
# No port
port = None
else:
try:
... |
def refoldidx(SEPlib=True, swapXY=False):
"""
Theses are indexing corrections to set the spacings and origin witht the correct axes after refolding.
"""
if SEPlib:
idx = (2,1,0)
if swapXY:
idx = (1,2,0)
else:
idx = (0,1,2)
if swapXY:
idx = (1,0... |
def get_approving_reviewers(props):
"""Retrieves the reviewers that approved a CL from the issue properties with
messages.
Note that the list may contain reviewers that are not committer, thus are not
considered by the CQ.
"""
return sorted(
set(
message['sender']
for message in props... |
def filter_nc_files(path_list):
"""Given a list of paths, return only those that end in '.nc'"""
return [p for p in path_list if p.suffix == '.nc'] |
def param_to_secopt(param):
"""Convert a parameter name to INI section and option.
Split on the first dot. If not dot exists, return name
as option, and None for section."""
sep = '.'
sep_loc = param.find(sep)
if sep_loc == -1:
# no dot in name, skip it
section = None
opt... |
def tokenize(chars):
"""
Convert a string of characters into a list of tokens.
"""
return chars.replace('(', ' ( ').replace(')', ' ) ').split() |
def tile_coords_to_quadkey(x, y, zoom):
"""Create a quadkey from xyzoom coordinates for Bing-style tileservers."""
quadKey = ''
for i in range(zoom, 0, -1):
digit = 0
mask = 1 << (i - 1)
if(x & mask) != 0:
digit += 1
if(y & mask) != 0:
digit += 2
... |
def get_ptype(proxy):
"""
:param proxy: https://124.0.0.1
:return: https
"""
return proxy.split(':')[0] |
def convert_milliseconds(milliseconds):
"""
Takes in time in milliseconds and returns time in human readable format.
"""
hours = milliseconds // 3600000
leftover = milliseconds % 3600000
minutes = leftover // 60000
if minutes < 10:
minutes = "0" + str(minutes)
seconds = (lefto... |
def xml_boolean(line, tag, namespace, default=False):
""" Get bool value from etree element """
try:
val = (line.find(namespace + tag).text)
except:
val = default
if val=='false' or val=='0' or val=='False' or val==False or val==None:
val=False
else:
val=True... |
def sensor_number(status: int):
"""
>>> sensor_number(0b011)
'sensor #3'
"""
sensornum = status & 0b111
if sensornum == 0:
return 'no sensor has error'
elif sensornum <= 4:
return f'sensor #{sensornum}'
else:
return 'reserved' |
def bytes_to_human(size):
"""
Convert Bytes to more readable units
"""
units = [ 'B', 'kB', 'MB', 'GB', 'TB' ]
unit_idx = 0 # Start with Bytes
while unit_idx < len(units)-1:
if size < 2048:
break
size /= 1024.0
unit_idx += 1
return size, units[unit_idx] |
def events_bridge_region(previous, current, types, getter):
"""Used in trace.process_chunk to check for certain enter-leave event sequences"""
return (getter(previous, 'region_type') in types
and getter(previous, 'endpoint') == 'enter'
and getter(current, 'region_type') in types
... |
def read_numbers(line):
"""
This function reads the pp (purchase price) and ch (cash) float numbers from the input line.
@param line -- Input line with the numbers
@return -- (pp, ch) tuple with the read float numbers
"""
args = line.split(';')
pp = float(args[0])
ch = float(args[1])
... |
def as_actor(input, actor) :
"""Takes input and actor, and returns [as
<$actor>]$input[endas]."""
if " " in actor :
repla = "<%s>"%actor
else :
repla = actor
return "[as %s]%s[endas]" % (repla, input) |
def calc_starting_row(page_num, rows_per_page=10):
"""
Calculate a starting row for the Solr search results. We only retrieve one page at a time
:param page_num: Current page number
:param rows_per_page: number of rows per page
:return: starting row
"""
page = 1
try:
page = int(p... |
def validate_src_dest(src, dest):
"""Check that at least one argument is a Dropbox URI."""
return src.startswith("dbx://") or dest.startswith("dbx://") |
def get_set_bits_count(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer
>>> get_set_bits_count(25)
3
>>> get_set_bits_count(37)
3
>>> get_set_bits_count(21)
3
>>> get_set_bits_count(58)
4
>>> get_set_bits_count(0)
0
>>> get_set_bits_count(256)... |
def square(x):
""" square numpy array
Args:
x (ndarray): input array
Returns:
y (ndarray): output array
"""
y = x**2
return y |
def replicaset_members(replicaset_document):
"""
Returns the members section of the MongoDB replicaset document
"""
return replicaset_document["members"] |
def bubble_sort(L):
"""Implementation of bubble sort."""
n = len(L)
if n < 2:
return L
for i in range(n - 1):
is_sorted = True
for j in range(n - i - 1):
if L[j] > L[j + 1]:
L[j], L[j + 1] = L[j + 1], L[j]
is_sorted = False
if i... |
def round_up(address, align):
"""round_up(address, align) -> int
Round up ``address`` to the nearest increment of ``align``.
"""
return (address+(align-1))&(~(align-1)) |
def class_fullname(cls):
"""Return the fullname of a class"""
return cls.__module__ + "." + cls.__name__ |
def AnyList(list_cls): # noqa
"""
Use during testing to assert call value types as list.
The function will return an instantiated class that is equal to any
version of `list(cls)`, for example using string.
>>> mock = MagicMock()
>>> mock.func(["str"])
>>> mock.func.assert_cal... |
def instance_tenancy(value):
"""
Property: VPC.InstanceTenancy
"""
valid = ["default", "dedicated"]
if value not in valid:
raise ValueError("InstanceTenancy needs to be one of %r" % valid)
return value |
def is_config_exist(cmp_cfg, test_cfg):
"""is configuration exist"""
if not cmp_cfg or not test_cfg:
return False
return bool(test_cfg in cmp_cfg) |
def hash_distance(left_hash, right_hash):
"""Compute the hamming distance between two hashes"""
if len(left_hash) != len(right_hash):
raise ValueError('Hamming distance requires two strings of equal length')
return sum(map(lambda x: 0 if x[0] == x[1] else 1, zip(left_hash, right_hash))) |
def parse_version_code(version_str, default_version_code=1.5):
"""
parser paddle fluid version code to float type
:param version_str:
:param default_version_code:
:return:
"""
if version_str:
v1 = version_str.split(".")[0:2]
v_code_str = ".".join(v1)
v_code = float(v_... |
def mCVTC(molFrac, vTC, vV, fW, eps=1.0):
"""
mCVTC(molFrac, vTC, vV, fW, eps=1.0)
multi-Component Vapor Thermal Conductivity in W/m/K
Parameters:
molFrac, list of mol fractions
vTC, list of pure component vapor thermal conductivities (components
ordered as in molFrac... |
def count_displayed_calendars(calendars):
"""
@brief counts the number of displayed calendars
@param calendars: A list of calendars (Google Calendars)
@return Number of displayed calendars.
For example, the user may have 7 separate calendars linked
to the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.