content stringlengths 42 6.51k |
|---|
def f_s(parameter):
"""
format string to make valid filename
"""
if '/' in parameter:
return parameter.replace("/", "-")
else:
return parameter |
def _flatten(ds):
"""Helper to flatten a list of dictionaries"""
res = {}
[res.update(d) for d in ds]
return res |
def content_disposition_value(file_name):
"""Return the value of a Content-Disposition HTTP header."""
return 'attachment;filename="{}"'.format(file_name.replace('"', '_')) |
def parse_range(s, maximum=0):
"""
:param s:
:param maximum:
:return:
"""
maximum -= 1
splits = s.replace(' ', '').replace(';', ',').split(',')
ranges = []
remove = []
not_values = False
for frag in splits:
if frag[0] == '~':
not_values = not not_value... |
def GetObjectByPath(obj, key_path):
"""Given an object, return its nth child based on a key path.
"""
return GetObjectByPath(obj[key_path[0]], key_path[1:]) if key_path else obj |
def _filename(filename):
# type: (str) -> str
"""
Prepends some magic data to a filename in order to have long filenames.
.. warning:: This might be Windows specific.
"""
if len(filename) > 255:
return '\\\\?\\' + filename
return filename |
def covers(str1, str2):
"""
Return if str1 covers str2.
"""
n = len(str1)
m = len(str2)
if n < m:
return 0
i = 0
for j in range(m):
if i >= n:
return 0
while str1[i] != str2[j]:
#print(str1[i], i, str2[j], j)
i += 1
... |
def is_valid_zip(zip_code):
"""Returns whether the input string is a valid (5 digit) zip code
"""
return (len(zip_code) == 5) and zip_code.isdigit() |
def SplitTime(value):
"""Splits time as floating point number into a tuple.
@param value: Time in seconds
@type value: int or float
@return: Tuple containing (seconds, microseconds)
"""
(seconds, microseconds) = divmod(int(value * 1000000), 1000000)
assert 0 <= seconds, \
"Seconds must be larger th... |
def strtobool(val: str) -> int:
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val ... |
def _get_fwxm_boundary(data, max_val):
"""
Returns sample position and height for the last sample which
amplitude is below the specified value.
If no sample can be found returns position and value of last sample
seen.
Note:
For FWHM we assume that we start at the maximum.
"""
i... |
def flatten(listOfLists):
"""
Flatten one level of nesting given a list of lists. That is, convert
[[1, 2, 3], [4, 5, 6]] to [1, 2, 3, 4, 5, 6].
:param listOfLists: a list of lists, obviously
:return: the flattened list
"""
from itertools import chain
return list(chain.from_iterable(li... |
def float_to_int(float_num, default=None):
"""float to int"""
if float_num is None:
return default
else:
try:
return int(float_num)
except ValueError:
return default |
def recite(start_verse, end_verse):
"""
input: start_verse, end_verse num as int
return: list of lyrics
"""
song = []
first_line = "On the X day of Christmas my true love gave to me: "
day_number = {1: "first", 2: "second", 3: "third", 4: "fourth",
5: "fifth",6: "sixth", 7: "seventh", 8... |
def split_model_kwargs(kw):
"""
django_any birds language parser
"""
from collections import defaultdict
model_fields = {}
fields_agrs = defaultdict(lambda : {})
for key in kw.keys():
if '__' in key:
field, _, subfield = key.partition('__')
fields_ag... |
def sdss2decam(g_sdss, r_sdss, i_sdss, z_sdss):
"""
Converts SDSS magnitudes to DECam magnitudes
Args:
[griz]_sdss: SDSS magnitudes (float or arrays of floats)
Returns:
g_decam, r_decam, z_decam
Note: SDSS griz are inputs, but only grz (no i) are output
"""
gr = g_sdss - r... |
def begin0(*vals): # eager, bodys already evaluated when this is called
"""Racket-like begin0: return the first value.
Eager; bodys already evaluated by Python when this is called.
g = lambda x: begin0(23*x,
print("hi"))
print(g(1)) # 23
**CAUTION**: For reg... |
def uncompleted_nets(nets):
""" Check if there are uncompleted nets, return True if there are, otherwise False.
"""
for net in nets:
if net.completed == False:
return True
return False |
def cwc(caBeg,caEnd,clBeg,clEnd):
"""Returns change in working capital."""
wcBeg = caBeg - clBeg
wcEnd = caEnd - clEnd
return wcEnd - wcBeg |
def _filter(lst, func=None):
"""Filter a list according to a predicate.
Takes a sequence [o1,o2,..] and returns a list contains those which
are not `None` and satisfy the predicate `func(o)`
:param lst: Input iterable (not a dictionary)
:param func: Predicate function. If ``none``, this function a... |
def focal_point(distance_image,distance_object):
"""Usage: Find focal point with distance of image and distance of object"""
numerator = distance_image * distance_object
denominator = distance_image + distance_object
return numerator / denominator |
def populate_list(my_list, dir_list):
"""converts a listing of dir into list containing html selection option tags"""
for f in dir_list:
my_list.append((f,f))
return my_list |
def untrack_indexed_db_for_origin(origin: str) -> dict:
"""Unregisters origin from receiving notifications for IndexedDB.
Parameters
----------
origin: str
Security origin.
"""
return {"method": "Storage.untrackIndexedDBForOrigin", "params": {"origin": origin}} |
def find_codon_new(codon, seq):
""" Find a specified codon within a given sequence. """
i = 0
# Scan sequenece until we hit a start codon or the end of sequence
while seq[i:i+3] != codon and i < len(seq):
i += 3
if i == len(seq):
return -1
return i |
def is_even(n: int) -> bool:
"""Return True if n is even, False otherwise. """
return bin(n).endswith("0") |
def reformat_large_tick_values(tick_val, pos):
"""
Turns large tick values (in the billions, millions and thousands) such as 4500 into 4.5K and also appropriately turns 4000 into 4K (no zero after the decimal).
"""
if tick_val >= 1000000000:
val = round(tick_val/1000000000, 1)
new_tick_f... |
def _set_options_selected(options, value):
"""set `selected` attribute for `options`"""
if not isinstance(value, (list, tuple)):
value = [value]
for opt in options:
if opt['value'] in value:
opt['selected'] = True
return options |
def round2bin(number, binsize, direction):
"""Round number to nearest histogram bin edge (either 'up' or 'down')."""
if direction == 'down':
return number - (number % binsize)
elif direction == 'up':
return number - (number % binsize) + binsize |
def split_args(all_args):
"""Split incoming args
All args need to be separted by a space. Kwargs need to have ':=' between key and val
i.e:
``arg1 arg2 kwarg1:=val kwarg2:='ex'``
Args:
all_args (list of str): List of input args
Returns:
list: args, kwargs
"""
args... |
def GetProdTag( s ) :
"""
Get the tag of the production campaign
"""
prod = 'h015'
if 'h014' in s : prod = 'h014'
elif 'h015d' in s : prod = 'h015d'
elif 'h015f' in s : prod = 'h015f'
if 'catMerge' in s : prod += 'catMerge'
return prod |
def _find_no_grad_vars(block, op_path, targets, no_grad_set):
"""
Find the vars which is not used in the program, and
those var belong to no_grad_var.
"""
output_names = set([out.name for out in targets])
no_grad_var = []
for i, op in reversed(list(enumerate(op_path))):
# If the op h... |
def get_key_value_of_nested_dict(nested_dict):
"""
Access a nested dictionary and return a list of tuples (rv) and values. Used to return the list of intensities
given a prox_comm dictionary containing multiple senders.
:param nested_dict: nested dictionary, usually containing prox_comm_events
:ret... |
def make_suffixes(sequences):
"""
Compute the suffixes for each sequence
"""
ret = []
for seq in sequences:
for pos in range(len(seq)):
ret.append(seq[pos:])
return ret |
def bytesToStr(rawBytes):
""" convert bytes to str such that strToBytes can
convert it back to bytes properly """
return rawBytes.hex() |
def find_all(s, ch):
"""Returns all occurrences of character ch in string s"""
return [i for i, ltr in enumerate(s) if ltr == ch] |
def value_search(mydict, search_value):
"""Find the key for a given value in a dictionary"""
return list(mydict.keys())[list(mydict.values()).index(search_value)] |
def max_depth(root):
"""Figure out what is maximum depth of a given binary tree is."""
if root is None:
return 0
return max(max_depth(root.left), max_depth(root.right)) + 1 |
def get_time(hrs: int, mins: int, secs: int):
"""
Gives the time in seconds for hr:min:sec
:param hrs:
:param mins:
:param secs:
:return: time in seconds
"""
return (hrs*60 + mins)*60 + secs |
def is_valid_key(key):
"""Return if a key can be used in the SHA-256 signature."""
return key not in ['merchantSig', 'sig'] and not key.startswith('ignore.') |
def get_new_placeholder_name(node_id: str, is_out_port: bool = False, port: int = 0):
"""
Forms a name of new placeholder created by cutting a graph
:param node_id: a node name that is cut
:param is_out_port: it is True iff output port is cut
:param port: a port number
:return: a name of new pla... |
def normalize_whitespace(text, to_space=u'\u00a0', remove=u'\u200b'):
"""Normalize whitespace in a string, by replacing special spaces by normal
spaces and removing zero-width spaces."""
if not text:
return text
for each in to_space:
text = text.replace(each, ' ')
for each in ... |
def _get_start_end(parts, index=7):
"""Retrieve start and end for a VCF record, skips BNDs without END coords
"""
start = parts[1]
end = [x.split("=")[-1] for x in parts[index].split(";") if x.startswith("END=")]
if end:
end = end[0]
return start, end
return None, None |
def lists(data):
""" organize lists
example:
from qaviton.utils import organize
organize_list = [(1,),(1,2,3),(1,2),(1,2,3,4)]
print(organize.lists(organize_list))
will return:
[[1, 1, 1, 1],[1, 1, 1, 2],[1, 1, 1, 3],[1, 1, 1, 4],[1, 1, 2, 1],[1, 1, 2, 2],
... |
def ones_complement_addition(x, y, bitsize=16):
"""
Add two numbers of any bitsize and carry the carry around.
11 + 10 = 101 => 10:
>>> ones_complement_addition(3, 2, 2)
2
11 + 11 = 110 => 11:
>>> ones_complement_addition(3, 3, 2)
3
00 + 10 = 10 => 10:
>>> ones_complement_addi... |
def _superset(input, values):
"""Checks if the given input is a superset of the given value
:param input: The input to check
:type input: dict
:param values: The values to check
:type values: :func:`list`
:returns: True if the condition check passes, False otherwise
:rtype: bool
"""
... |
def build_key2idx(map):
"""build a key to index mapping for array indexing.
"""
m = {}
for i, key in enumerate(map):
m[key] = i
return m |
def findMaxChildren(env_names, graphs):
"""return the maximum number of children given a list of env names and their corresponding graph structures"""
max_children = 0
for name in env_names:
most_frequent = max(graphs[name], key=graphs[name].count)
max_children = max(max_children, graphs[nam... |
def get_string(time_msec, show_msec = True):
""" Formats a time, in ms, into a timecode of the form HH:MM:SS.nnnn.
This is the default timecode format used by mkvmerge for splitting a video.
Args:
time_msec: Integer representing milliseconds from start of video.
show_msec: If False, omit... |
def format_suffix(altradio=None, radioversion=None, core=False):
"""
Formulate suffix for hybrid autoloaders.
:param altradio: If a hybrid autoloader is being made.
:type altradio: bool
:param radioversion: The hybrid radio version, if applicable.
:type radioversion: str
:param core: If w... |
def get_times(dt):
"""
Converts seconds into hours, minutes and seconds
:param dt: The time in seconds
:type dt: float
:return: hours, minutes and seconds
:rtype: int, int, float
"""
mins = (dt - dt % 60) / 60
dt = dt - 60 * mins
hours = (mins - mins % 60) / 60
mins = mins - ... |
def hasmethod(obj, methodname):
"""Does ``obj`` have a method named ``methodname``?"""
if not hasattr(obj, methodname):
return False
method = getattr(obj, methodname)
return callable(method) |
def compute_accuracy_with_preds(preds, labels):
"""Compute accuracy with predictions and labels"""
correct = 0
for i in range(len(preds)):
if preds[i] == labels[i]:
correct += 1
return float(correct) / len(preds) |
def mag(v):
"""
Returns the euclidean length or magnitude of vector v
"""
return (pow(sum(e*e for e in v), 0.5)) |
def is_new_style(cls):
"""
Python 2.7 has both new-style and old-style classes. Old-style classes can
be pesky in some circumstances, such as when using inheritance. Use this
function to test for whether a class is new-style. (Python 3 only has
new-style classes.)
"""
return hasattr(cls, '_... |
def greatest_common_divisor(num1: int, num2: int) -> int:
"""Greatest common factor of two numbers.
>>> greatest_common_divisor(8, 12)
4
"""
if not num2:
return num1
return greatest_common_divisor(num2, num1 % num2) |
def get_option_name(flags):
"""
Function to get option names from the user defined arguments.
Parameters
----------
flags : list
List of user defined arguments
Returns
-------
flags : list
List of option names
"""
for individualFla... |
def check_search_account_options(val, home):
"""Check if current account option is valid."""
try:
# Change option to integer.
val = int(val)
# Check if option is in range.
if val <= 0 or val > 5:
print('*********************************')
print('Not an op... |
def stitch_values(values_and_indices_list):
"""Stitch values together according to their indices.
Args:
values_and_indices_list: a list of tuples of values and indices indicating
the values and positions in the returned list.
Returns:
a stitched list of values.
"""
length = 0
for values_and_... |
def linkFilter_google(url):
"""
Filters out the links of social media websites from the returned google search results using `filterList` defined implicitly.
Parameters
----------
url : str
URL to be tested against `filterList`
Returns
-------
int
returns 0 (is a social... |
def create_route_map(obj):
"""
Iterates of all attributes of the class looking for attributes which
have been decorated by the @on() decorator It returns a dictionary where
the action name are the keys and the decorated functions are the values.
To illustrate this with an example, consider the foll... |
def search_in_toc(toc, key, totalpg):
"""Searches a particular lesson name provided as a parameter in toc and returns its starting and ending page numbers.
Args:
toc (nested list): toc[1] - Topic name
toc[2] - Page number
key (str): the key to be found
totalpg... |
def select_features(feature_list, candidate_dict):
"""Returns a new dictionary created by selecting keys in a given candidate dictionary with respect to a given feature list
Keyword arguments:
feature_list -- list of desired features
candidate_dict - base dictionary
"""
featu... |
def swift_library_output_map(name, alwayslink):
"""Returns the dictionary of implicit outputs for a `swift_library`.
This function is used to specify the `outputs` of the `swift_library` rule;
as such, its arguments must be named exactly the same as the attributes to
which they refer.
Args:
... |
def _get_docstring(name):
"""Return the docstring of an object with name"""
try:
obj = globals()[name]
except KeyError:
raise ValueError("Invalid object name")
return obj.__doc__ or "" |
def validation_handler_strict(errors):
"""A validation handler that does not allow any errors.
Args:
errors (list[yourdfpy.URDFError]): List of errors.
Returns:
bool: Whether any errors were found.
"""
return len(errors) == 0 |
def parse_colon_delimited_angles(*args):
"""
Parses angle strings delimited with colons
Input data like ('1:38:48.0','41:24:23')
and it will return [1.64666666667 41.4063888889]
@param args : list of hexadecimal strings
@type args : list of str
@return: list of float
... |
def build_addon_button(text, action, title=''):
"""Builds am action button to be rendered in HGrid
:param str text: A string or html to appear on the button itself
:param str action: The name of the HGrid action for the button to call.
The callback for the HGrid action must be defined as a member o... |
def truncated_linear(
min_x: float, max_x: float, min_y: float, max_y: float, x: float
) -> float:
"""Truncated linear function.
Implements the following function:
f1(x) = min_y + (x - min_x) / (max_x - min_x) * (max_y - min_y)
f(x) = min(max_y, max(min_y, f1(x)))
If max_x - min_x < 1e... |
def index_to_numbers(idx):
"""Input: line.col, output: (line, col)
"""
return tuple(map(lambda x: int(x), idx.split('.'))) |
def mask(n):
""" create an n-bit mask """
return 2**n - 1 |
def note_css_class(note_type):
"""
Django Lesson Note Type
text = blocks.TextBlock()
note_type = blocks.ChoiceBlock(
choices=(
('info', 'Info'),
('warning', 'Warning'),
('danger', 'Danger'),
('note', 'Note'),
),
required=False,
... |
def note_to_num(note_str: str) -> int:
"""Convert a musical pitch from string representation to an integer.
Args:
note_str: The string representation of a musical pitch, e.g. 'C4'.
Returns:
The corresponding integer of the pitch.
Raises:
ValueError: if note is invalid.
"... |
def _MachineTypeMemoryToCell(machine_type):
"""Returns the memory of the given machine type in GB."""
memory = machine_type.get('memoryMb')
if memory:
return '{0:5.2f}'.format(float(memory) / 2**10)
else:
return '' |
def split_train_test(pairs, ratio=.7):
"""Given a list of (input, label) pairs, return two separate lists, keeping
`ratio` of the original data in the first returned list."""
i = int(len(pairs) * ratio)
return pairs[:i], pairs[i:] |
def process_variation(variation_name, price, sku, product_id, quantity):
"""
returns a dict for a specific variant
quantity is not actually a square support property. Square will ignore this.
This field is used to record the quantity for the variant so inventory
can be updated
"""
... |
def _volume_admin_metadata_get(context, volume_id):
"""Return dummy admin metadata."""
return {'fake_key': 'fake_value'} |
def lower(word: str) -> str:
"""
Will convert the entire string to lowecase letters
>>> lower("wow")
'wow'
>>> lower("HellZo")
'hellzo'
>>> lower("WHAT")
'what'
>>> lower("wh[]32")
'wh[]32'
>>> lower("whAT")
'what'
"""
# converting to ascii value int value and c... |
def apk(actual, predicted, k=3):
"""
Source: https://github.com/benhamner/Metrics/blob/master/Python/ml_metrics/average_precision.py
"""
if len(predicted) > k:
predicted = predicted[:k]
score = 0.0
num_hits = 0.0
for i, p in enumerate(predicted):
if p in actual and p not in... |
def clean_claim(claim_text_lis):
"""
Returns a list of claims with metadata removed.
Don't call multiple times, on same lis.
"""
clean_claims = []
for claim_text in claim_text_lis:
if claim_text is not None:
clean_claim = ' '.join(claim_text.split()[1:]).strip(' ') ... |
def ceiling_cpm(cpm, ceiling = 1000):
"""Sets CPM to have ceiling
Args:
cpm (float): CPM of isoform
ceiling (int, optional): Maximum. Defaults to 1000.
Returns:
float: new cpm constrained to ceiling
"""
# gtf top score is 1000
if cpm > ceiling:
return ceiling
... |
def ipv4_to_str(ipv4):
""" convert ipv4 integer to string """
return "%s.%s.%s.%s" % (
(ipv4 & 0xff000000) >> 24,
(ipv4 & 0x00ff0000) >> 16,
(ipv4 & 0x0000ff00) >> 8,
(ipv4 & 0x000000ff)
) |
def ping(host):
"""
Returns True if host responds to a ping request
Taken from: http://stackoverflow.com/questions/2953462/pinging-servers-in-python
(just in case I need this to be portable)
"""
import subprocess, platform
# Ping parameters as function of OS
ping_str = "-n 1" if platfo... |
def geoSum(suku_pertama, rasio, jumlah_deret):
"""
Menghitung deret geometri berhingga dari n buah suku
dengan suku pertama a dan rasio r. Rumus umum berlaku
jika r tidak sama dengan 1 dan a tidak sama dengan 0
Rumus : a * ((1 - pow(r, n)) / (1 - r))
Mengembalikan nilai perhitungan rumus
... |
def arrival_filter(row):
""" Copy arrival time from arrival if missing """
if not row["arrival_time"] and row["departure_time"]:
row["arrival_time"] = row["departure_time"]
return row |
def parseContentRange(header):
"""Parse a content-range header into (kind, start, end, realLength).
realLength might be None if real length is not known ('*').
start and end might be None if start,end unspecified (for response code 416)
"""
kind, other = header.strip().split()
if kind.lower() !... |
def get_sleepiest_guard(sleep_record):
"""Finds guard in sleep_record who spent the most total minutes asleep.
returns: ('guard', total_minutes_slept)
"""
sleepiest = '', 0
for guard in sleep_record:
sleep_mins = 0
for minute in sleep_record[guard]:
sleep_mins += sleep_r... |
def convert_items(items, type_, default=""):
"""converts items to type or replaces with default"""
for i in range(len(items)):
try:
items[i] = type_(items[i])
except ValueError:
items[i] = default
return items |
def _as_range(iterable):
"""
Return a tuple representing the bounds of the range.
"""
l = list(iterable)
return (l[0], l[-1]) |
def solution(numerator: int = 1, digit: int = 1000) -> int:
"""
Considering any range can be provided,
because as per the problem, the digit d < 1000
>>> solution(1, 10)
7
>>> solution(10, 100)
97
>>> solution(10, 1000)
983
"""
the_digit = 1
longest_list_length = 0
f... |
def fs_write(obj, file_path):
"""
Convenience function to write an Object to a FilePath
Args:
obj (varies): The Object to write out
file_path (str): The Full path including filename to write to
Returns: The object that was written
"""
try:
with open(str(file_path), 'w')... |
def is_integer(arg):
"""
purpose:
check if the arg is an integer
arguments:
arg: varies
return value: Boolean
"""
try:
return float(arg).is_integer()
except Exception:
return False |
def mystery_3b(c1: int, c2: int, c3: int) -> int:
"""Function for question 3b."""
if c1 >= c2:
if c2 >= c3:
return 1
else:
return 2
else:
if c2 <= c3:
return 3
else:
return 4 |
def expand_unit(value):
"""
Expand units of bytes (K, Ki, M, Mi, G, Gi)
:param value:
:return:
"""
if ":" in value:
return ":".join(str(expand_unit(val)) for val in value.split(':'))
if value.endswith('K'):
value = int(value[:-1]) * 1000
elif value.endswith('Ki'):
... |
def map_title_from_list(number, title_list):
"""Used during the iterative inserts in fn:write_to_db - if number matches
the number within title_list, write title to db.
:arg number: string containing RFC number
:arg title_list: list of all rfc titles from fn:get_title_list
:returns result: string ... |
def AptGetPathToConfig(vm):
"""Returns the path to the mysql config file."""
del vm
return '/etc/mysql/mysql.conf.d/mysqld.cnf' |
def parse_date(date):
""" 29-Nov-20 """
dm = {
"Jun": "06",
"Jul": "07",
"Aug": "08",
"Sep": "09",
"Oct": "10",
"Nov": "11"
}
date = date.split("-")
try:
month = dm[date[1]]
except:
return "2020-12-31"
date = f"2020-{month}-{dat... |
def extract_components(field_data, doc, source, field):
"""Return an array that contains simple elements in the
form (text,lang) from a complex data field."""
array = []
for unit in field_data:
if unit:
# the field element has @lang and #value as nested elements
if isi... |
def check_past(curr_x, curr_y, c_targ_x, c_targ_y, base_dir, targ_dir):
"""
Returns True if we have overshot our targe
"""
if base_dir == 0:
if targ_dir != 0 and curr_x > c_targ_x:
return True
elif base_dir == 90:
if targ_dir != 90 and curr_y > c_targ_y:
retur... |
def intcode(x):
"""Function that computes the intcode for the list x."""
# Traverse x with a stride of 4
for i in range(0, len(x), 4):
# Kill the program
if x[i] == 99:
return x[0]
# Addition
elif x[i] == 1:
x[x[i + 3]] = x[x[i + 1]] + x[x[i + 2]]
... |
def construct_auth_bearer(token):
"""
Helper function to construct authorization bearer header data
:param token: Token string
:type token: str
:return: Authorization header dictionary object with Bearer data
:rtype: dict
"""
return {"Authorization": f"Bearer {token}"} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.