content stringlengths 42 6.51k |
|---|
def is_delayed_tuple(obj) -> bool:
"""is_delayed_tuple.
Parameters
----------
obj : object
Returns
-------
bool
is `obj` joblib.delayed tuple
"""
return isinstance(obj, tuple) and len(obj) == 3 and callable(obj[0]) |
def crypto_price_in_usd(crypto_prices, amount, base):
# print(amount, base, dest)
""" Return price of any "dest" currency normalized to USD """
# if parsed_tickers['base']
return crypto_prices[base] * amount |
def format_dir_nospace(dirpath):
"""ESCAPE SPACES IN DIRECTORY PATH
Args:
dirpath: Str, directory path to be corrected
Returns:
dirpath: Str, directory path with escaped spaces and appended backslash
"""
dirpath = dirpath.replace(" ", "\ ")
if dirpath[-1] != '/':
... |
def sanitize(s) -> str:
"""
Returns string decoded from utf-8 with leading/trailing whitespace
character removed
"""
return s.decode('utf-8').strip() |
def get_option(dhcp_options, key):
"""return single DHCP option"""
must_decode = ['hostname', 'domain', 'vendor_class_id']
try:
for i in dhcp_options:
if i[0] == key:
# If DHCP Server Returned multiple name servers
# return all as comma seperated string.
... |
def title(title:str)->str:
"""wrap a title string in div and <H1></H1>"""
return f"<div><H1>{title}</H1></div>" |
def pretty_time_delta(seconds: float) -> str:
"""Return a human-readable string of a duration in seconds.
modified from: https://gist.github.com/thatalextaylor/7408395
:param seconds:
:return:
"""
ms = float(seconds * 1000)
seconds = int(seconds)
days, seconds = divmod(seconds, 86400)
... |
def _bitget(byteval, idx):
"""
A binary code for getting index of Z2(Z1)
"""
return ((byteval & (1 << idx)) != 0) |
def fastaEncodeHeader(attributes):
"""Decodes the fasta header
"""
for i in attributes:
assert len(str(i).split()) == 1
return "|".join([ str(i) for i in attributes ]) |
def _parse_bool(el):
"""parse a boolean value from a xml element"""
value = str(el)
return not value.strip() in ('', '0') |
def get_unique_name(name, elems):
"""
Return a unique version of the name indicated by incrementing a numeral
at the end. Stop when the name no longer appears in the indicated list of
elements.
"""
digits = []
for c in reversed(name):
if c.isdigit():
digits.append(c)
... |
def htmlEsc(val):
"""Escape certain HTML characters by HTML entities.
To prevent them to be interpreted as HTML
in cases where you need them literally.
"""
return (
""
if val is None
else (
str(val)
.replace("&", "&")
.replace("<", "&... |
def _count_str(string):
"""count rows and columns of a string"""
lines = string.split('\n')
cols = len(lines)
rows = 0
for line in lines:
rows = max(rows, len(line))
return rows, cols |
def unique_list(seq):
""" Removes duplicate elements from given @seq
@seq: a #list or sequence-like object
-> #list
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] |
def evaluate_mrr(preds):
"""evaluate_mrr"""
last_qid = None
total_mrr = 0.0
qnum = 0.0
rank = 0.0
correct = False
for qid, score, label in preds:
if qid != last_qid:
rank = 0.0
qnum += 1
correct = False
last_qid = qid
rank += 1... |
def count_characters_one( string ):
""" Counts with a for loop and a dict. """
d = {}
for s in string:
d[s] = d.get(s,0)+1
return d |
def calc_series_range_well(wellnumber, imgperwell):
"""
this function can be used when the number of positions or scenes per well is equal for every well.
The well numbers start with Zero and have nothing to do with the actual wellID, e.g. C2
"""
seriesseq = range(wellnumber * imgperwell, wellnumb... |
def ekman_layer_height(friction_velocity, coriolis_parameter):
"""
returns the height of the atmospheric boundary layer - Geostrophic height
For neutral conditions this is the height of the ABL
"""
return friction_velocity / (6.0 * coriolis_parameter) |
def get_viz_node_names(node_set):
"""
:param node_set:
:return:
:meta private:
"""
base_names = set()
nonunique_names = set()
for node in node_set:
name = node.name
if name in base_names:
nonunique_names.add(node.name)
base_names.add(node.name)
u... |
def largest_continous(l):
"""
Runtime: O(n)
"""
max_sum = 0
start = 0
end = 1
while (end < len(l)+1):
if l[start] + l[start+1] > 0:
curr_sum = sum(l[start:end])
max_sum = max(curr_sum, max_sum)
end += 1
else:
# Start new sequenc... |
def noamwd_decay(step, warmup_steps, model_size,
rate, decay_steps, start_step=0):
"""
Learning rate schedule optimized for huge batches
"""
return (
model_size ** (-0.5) *
min(step ** (-0.5), step * warmup_steps**(-1.5)) *
rate ** (max(step - start_step + decay... |
def validate(config):
"""
Validate the beacon configuration
"""
# Configuration for swapusage beacon should be a list of dicts
if not isinstance(config, list):
return False, "Configuration for swapusage beacon must be a list."
else:
_config = {}
list(map(_config.update, c... |
def clean_b64(b64_str):
"""Cleans a base64 encoding to be more amenable as an ID in a URL
:param b64_str:
:returns:
:rtype:
"""
assert type(b64_str) == str
result = b64_str.replace("=", "") # remove padding
return result |
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new han... |
def acl_bucket_access_analyzer(acl_actions):
"""parameters:
acl_actions : list
description:
This function analyzes the bucket acl grants, and determines the access scope (read, write, etc).
It return a string of the access scope."""
access_actions = []
bucket_access = None
... |
def _format_value(value):
"""
Formats values to a format accepted by database
:param value: a value to parse
:return: parsed value
"""
if isinstance(value, str):
return f"'{value}'"
elif value is None:
return 'NULL'
else:
return str(value) |
def format_time(seconds):
"""Formats seconds as an ISO time string `hh:mm:ss`."""
minutes, seconds_rem = divmod(seconds, 60)
if minutes >= 60:
hours, minutes_rem = divmod(minutes, 60)
return "%02d:%02d:%02d" % (hours, minutes_rem, seconds_rem)
return "00:%02d:%02d" % (minutes, seconds_re... |
def sqla_uri_from_config_section(config_section) -> str:
"""
>>> from jasmine.etl.app_base import sqla_uri_from_config_section
>>> sqla_uri_from_config_section({
... "uri": "mysq://blah:blah@blah/{username}={user}, {password}={pass}, {database}={db}",
... "username": "username",
... ... |
def extent_from_bbox(bbox):
"""
Args:
bbox (ndarray): tl_x, tl_y, w, h
Returns:
extent (ndarray): tl_x, br_x, tl_y, br_y
CommandLine:
xdoctest -m ~/code/vtool_ibeis/vtool_ibeis/geometry.py extent_from_bbox
Example:
>>> # ENABLE_DOCTEST
>>> from vtool_ibeis.... |
def fasta_wrap(text):
"""Line wrap FASTA output at 80 characters."""
new = []
lines = text.split("\n")
while lines:
line = lines.pop(0)
if line.startswith(">"):
while len(line) > 80 and " " in line:
cut = line
while len(cut) > 80 and " " in cut... |
def rotate_address(level, address, rotate_num):
"""Rotates the address with respect to rotational symmetries of SG
Args:
level: A nonnegative integer representing the level of SG we're
working with.
address: np.array of size (level+1) representing the address
vector of... |
def is_palindrome(input):
"""
Return True if input is palindrome, False otherwise.
Args:
input(str): input to be checked if it is palindrome
"""
if len(input) < 2:
return True
first_char = input[0]
last_char = input[-1]
return first_char == last_char and is_palindrome(inp... |
def bitcount(num, length, value=1):
"""Counts the bits in num that are set to value (1 or 0, default 1)."""
one_count = 0
curr_length = length
while num and curr_length:
one_count += 1 & num
num >>= 1
curr_length -= 1
if value:
return one_count
else:
retur... |
def _check_same_layout(tensor_layout1, tensor_layout2):
"""check if two tensor layouts are same"""
return tensor_layout1[0] == tensor_layout2[0] and tensor_layout1[1] == tensor_layout2[1] |
def underline(text):
""" Return the text in underline (Linux console only).
@param text: The text to underline
"""
return "\033[4m" + str(text) + "\033[0m" |
def wipe_resource_id(rsrc_id):
"""Basic cleaning of resource-id string."""
rsrc_id = "".join([c for c in str(rsrc_id) if c.isalnum()]).strip()
assert len(rsrc_id) == 32, "{} is not a valid Resource-ID".format(rsrc_id)
return rsrc_id |
def Branch(node):
"""
Root of if/then/else branch
Args:
node (Branch): Current position in node-tree
Return:
str : Translation of current node.
Children:
If Elif* Else?
If:
If block
Elif:
Elseif block
Else:
Else block
Examples:
>>> print(matlab2cpp.qscript("i... |
def safe_decode(s, coding='utf-8', errors='surrogateescape'):
"""decode bytes to str, with round-tripping "invalid" bytes"""
return s.decode(coding, errors) |
def create_rec_lvl_range(rec_lvl):
"""
gui values:
'Level 1 - blank, I, 4',
'Level 2 & up - M, K, 7, 1, 2',
'Level 3 & up - 3, 8'
"""
default = [" ", "I", "4"]
try:
lvl = rec_lvl[6]
if lvl == "1":
return default
elif lvl == "2":
... |
def rescale(inlist, newrange=(0, 1)):
"""
rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum)
"""
OldMax = max(inlist)
OldMin = min(inlist)
if OldMin == OldMax:
raise RuntimeError('list contains of only one unique value')
OldRange ... |
def rwrap(some_string):
"""
Returns red text
"""
return "\033[91m%s\033[0m" % some_string |
def doc_errors(errors):
"""format errors for doc-string"""
return " :raises: {0}".format(', '.join(errors)) |
def get_after_slash(string):
"""
Get the part of a string after the first slash
:param str string: String to return the part after the first
slash of
:return str part_after_first_slash: Part of the string after
the first slash
"""
return '/'.join(string.split('/')[1:]) |
def match(v1, v2, nomatch=-1, incomparables=None, start=0):
"""
Return a vector of the positions of (first)
matches of its first argument in its second.
Parameters
----------
v1: array-like
the values to be matched
v2: array-like
the values to be matched against
nomatc... |
def _pf1a2(val1, val2):
"""
Some function description.
Parameters
----------
val1 : float
Description of the parameter Value 1.
val2 : list(str)
Description of the parameter Value 2.
Returns
-------
v : int
... |
def get_nested_key(_dict, keys=[]):
"""Gets a nested key from a dictionary."""
key = keys.pop(0)
if len(keys) == 0:
return _dict[key]
return get_nested_key(_dict[key], keys) |
def validate_required_kwargs_are_not_empty(args_list, kwargs):
"""
This function checks whether all passed keyword arguments are present and that they have truthy values.
::args::
args_list - This is a list or tuple that contains all the arguments you want to query for. The arguments are strings seperat... |
def solution(n: int = 1000) -> int:
"""Returns the number of letters used to write all numbers from 1 to n.
where n is lower or equals to 1000.
>>> solution(1000)
21124
>>> solution(5)
19
"""
# number of letters in zero, one, two, ..., nineteen (0 for zero since it's
# never said alo... |
def is_palindrome(string):
"""
Checks the string for palindrome
:param string: string to check
:return: true if string is a palindrome false if not
"""
if string == string[::-1]:
return True
return False |
def iou(bbox1, bbox2):
"""
Calculates the intersection-over-union of two bounding boxes.
Source: https://github.com/bochinski/iou-tracker/blob/master/util.py
Parameters
----------
bbox1 : numpy.array, list of floats
bounding box in format (x-top-left, y-top-left, x-bottom-right, y-b... |
def classify_code_type(raw_string):
"""
A very simple function to detect HTML/XML.
"""
search_for_words = [
'</div>',
'</p>',
]
for word in search_for_words:
if word not in raw_string:
return 'XML'
return 'HTML' |
def emulator_type(emulator):
"""Identifies the type of emulator."""
return emulator["emulator_type"] |
def frac(x1,x2):
"""FRAC(A,B)=A/B
Compared to the matlab version, this function has little interest...
_________________________________________________________________
This is part of JLAB
(C) 2004 J.M. Lilly
Rewritten in python 2.X by G. Lenoir, October 2016"""
y=x1/x2
return y |
def is_list_or_tuple(obj):
"""
Return True if object is list or tuple.
:param obj: object to check
:returns: True or False
"""
return isinstance(obj, (list, tuple)) |
def parseGithubUrl(fullUrl, stripDotGit=False):
""" Get user/organisation and repository name from github remote name (optionally removing the trailing ".git") """
remote, repo = fullUrl.split(":")[-1].split("/")[-2:]
if stripDotGit:
repo = repo.strip(".git")
return remote, repo |
def build_ignorables_mapping(copyrights, holders, authors, urls, emails):
"""
Return a sorted mapping of ignorables built from lists of ignorable clues.
"""
ignorables = dict(
ignorable_copyrights=sorted(copyrights or []),
ignorable_holders=sorted(holders or []),
ignorable_author... |
def clear_data_for_origin(origin: str, storageTypes: str) -> dict:
"""Clears storage for origin.
Parameters
----------
origin: str
Security origin.
storageTypes: str
Comma separated list of StorageType to clear.
"""
return {
"method": "Storage.clearDataForOri... |
def resources_of_config(config):
""" Returns all resources and models from config.
"""
return set( # unique values
sum([ # join lists to flat list
list(value) # if value is iter (ex: list of resources)
if hasattr(value, '__iter__')
el... |
def stringify_list(list_orig: list) -> str:
"""Stringify the given list for sql query - used when inserting lists for reset query's."""
list_str = ''
for item in list_orig:
# remove any spaces or end brackets to avoid sql injection that could end the list and execute another command
list_str... |
def id_to_port(id: str):
"""Turn unique ONNX output and input value names into valid MDF input and outport names"""
new_name = str(id).replace(".", "_")
# If the first character is a digit, precede with an underscore so this can never be interpreted
# as number down the line.
if new_name[0].isdigi... |
def _coerce_types(vals):
"""Makes sure all of the values in a list are floats."""
return [1.0 * val for val in vals] |
def getSeqMotifDict(fimoDict):
"""
Make a dict between the seq names and list of motifs that occur in it
Args:
fimoDict: dict between motif names and the seqs it hits
Returns:
a dict between seq names and a list of motif IDs that hit it
"""
seqMotifDict = {}
tmpCount = 0
for motifId, seqList in fimoDict.ite... |
def sort_submissions_by_score(dict_of_data):
# print submissions with highest score first
"""make a list of submussion.ids, highest first (reversed)
x is the submussion.ids iterated in dict_of_data to use ['score'] key
taken from:
https://stackoverflow.com/questions/4110665/
sort-nested-dictiona... |
def casing_count(word):
"""
:param word: any word to be counted
Determines if input is a word or number
then takes length of the word and times it by the power of 2
:return: the count
"""
if word.isdigit(): # if a digit, only has one possibility
r = 1
else: ... |
def has_bash_info(filename):
"""Check if a file can be executed with bash.
This basically checks if the first line contains #!/bin/bash or #!/bin/sh.
"""
with open(filename, 'r') as infile:
first_line = infile.readline()
return first_line.strip() in ["#!/bin/bash", "#!/bin/sh"] |
def convert_markdown(text: str) -> str:
"""Removes the markdown tags"""
return text.replace("`", "") |
def sort(li):
"""
Performs a mini radix sort on the top ten documents by first sorting
on document ids, then sorting on document ranking. As sorted() is stable,
this ensures that any documents with identical rankings will be sorted on
their document ids in increasing order
... |
def solve(lim = 4 * 1000 * 1000):
"""
Naive solution with a function.
:param lim: Max number to sum up to.
:returns: The sum of the even Fibo-numbers.
"""
a, b = 0, 1
sum = 0
while b < lim:
if not b % 2:
sum += b
a, b = b, a +... |
def compute_precision_recall(results, partial_or_type=False):
"""
Takes a result dict that has been output by compute metrics.
Returns the results dict with precison and recall populated.
When the results dicts is from partial or ent_type metrics, then
partial_or_type=True to ensure the right calcu... |
def ns(v):
"""Return empty str if bool false"""
return str(v) if bool(v) else '' |
def convert_to_list(items):
"""Converts items to list items:
- if items are already list items then skip;
- if are not list items then convert to list items."""
list_items = items if isinstance(items, list) else [items, ]
return list_items |
def factorial(num):
"""
The factorial of a number.
On average barely quickar than product(range(1, num))
"""
# Factorial of 0 equals 1
if num == 0:
return 1
#if not, it is the product from 1...num
product = 1
for integer in range(1, num + 1):
product *= integer
return product |
def complement(sequence):
"""
Params:
* *sequence(str) *: DNA sequence, non ATGC nucleotide will be returned unaltered
Returns:
* *sequence.translate(_rc_trans)(str) *: complement of input sequence
"""
_rc_trans = str.maketrans('ACGTNacgtn', 'TGCANtgcan')
return sequence.translate(_rc... |
def check_list(entity):
"""Check if a number is repeated in a list of length 9."""
for key in range(0, 9):
for compare in range(key+1, 9):
if (entity[key] == entity[compare]) & (entity[key] != 0):
return False
return True |
def merge(left, right):
"""Merge two sorted lists.
left: list
right: list
"""
left = left[::-1]
right = right[::-1]
res = []
while len(left) != 0 and len(right) != 0:
if left[-1] < right[-1]:
res.append(left.pop())
else:
res.append(right... |
def find_loss(prediction, target):
"""
Calculating the squared loss on the normalized GED.
"""
prediction = prediction
target = target
score = (prediction-target)**2
return score |
def mention_role_by_id(role_id):
"""
Mentions the role by it's identifier.
Parameters
----------
role_id : `int`
The role's identifier.
Returns
-------
role_mention : `str`
"""
return f'<@&{role_id}>' |
def vcross(vect1, vect2):
"""
This function returns the cross product of two vectors.
:rtype: double list
:return: cross product M{vect1 S{times} vect2}
:type vect1: double list
:param vect1: The vector - in the format [x,y,z]
(or [x,y,z,0] for affine transformations in an homo... |
def get_illust_url(illust_id: int) -> str:
"""Get illust URL from ``illust_id``.
:param illust_id: Pixiv illust_id
:type illust_id: :class:`int`
:return: Pixiv Illust URL
:rtype: :class:`str`
"""
return (
'http://www.pixiv.net/member_illust.php'
'?mode=medium&illust_id={}'.... |
def friendly_number(number):
"""
Produce a human-readable value for file size.
:param number: bytes.
:return: human-readable string.
"""
template = '%.1f%sB'
powers = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
base = 1000
number = float(number)
for power in powers[:-1]:
... |
def _get_gem_path(incpaths):
"""
incpaths is a list of `<bundle_name>/lib/ruby/<version>/gems/<gemname>-<gemversion>/lib`
The gem_path is `<bundle_name>/lib/ruby/<version>` so we can go from an incpath to the
gem_path pretty easily without much additional work.
"""
if len(incpaths) == 0:
... |
def translate_severity_level(level):
""" return severity level
"""
if level is None or level == 'LOW':
return '-l'
if level == 'MEDIUM':
return '-ll'
if level == 'HIGH':
return '-lll'
raise ValueError(f'{level} is not a valid severity level') |
def row_format_resource(*fields):
"""Transform a variable number of fields to a `table-row` format.
```
>>> row_format_resource(a,b,c,d)
'| a | b | c | d |'
```
:param fields: fields to be converted to row.
"""
return ('| {} ' * len(fields)).format(*fields... |
def dot_product(a, b):
"""Computes dot product between two vectors writen as tuples or lists"""
return sum(ai * bj for ai, bj in zip(a, b)) |
def raw_face_coordinates(face, x, y, z):
"""
Finds u,v coordinates (image coordinates) for a given
3D vector
:param face: face where the vector points to
:param x, y, z: vector cartesian coordinates
:return: uv image coordinates
"""
if face == 'left':
u = z
v ... |
def get_desc(funct_string) -> str:
"""
Get the description of the function
:param funct_string: The documentation to pull the description from
:return: A string of the description
"""
desc = ''
for line in funct_string.split('\n'):
if 'param' in line or 'return' in line:
... |
def is_list(data):
"""
function to check if data is a list
Parameters.
----------
data:any
it's suppose to be a list
Returns:
---------
True if data is a list otherwise False.
"""
return isinstance(data, list) |
def remove_prefix(text: str, prefix: str) -> str:
"""Remove prefix and strip underscores"""
if text.startswith(prefix):
text = text[len(prefix) :]
return text.strip('_') |
def create_foreign_key_not_null(foreign_key,foreign_key_not_null,maps):
"""
Args:
foreign_key(list):
tmp_foreign_key_not_null(list):
Returns:
highestStudent_id integer NOT NULL REFERENCES students(student_id)
"""
if foreign_key_not_null:
ret = []
for i in for... |
def calculateSquareRoot(n):
"""
Given an input n, returns the closest integer above square root of n.
"""
root = 1 # Only considering positive roots
while(root*root <= n):
root += 1
return root |
def parse_join(join_str):
"""Parsing joing string in form of 'X=X,Y=Y'
"""
join_on = {}
for x in join_str.split(','):
y = x.split('=')
if len(y) != 2:
msg = '--join should be in format "X=X,Y=Y"'
try:
join_on['left'].append(y[0])
except KeyError:
... |
def alternate_join(list1, list2):
""" Combine two lists in with consecutive elements from alternate lists """
result = [None]*(len(list1)+len(list2))
result[::2] = list1
result[1::2] = list2
return result |
def index_of(val, in_list):
"""
:param val: String variable to test
:param in_list: list of Strings
:return: index of the value if it's in the list
"""
try:
return in_list.index(val)
except ValueError:
return -1 |
def Mean(l):
"""Computes the mean (average) for a list of numbers."""
if l:
return float(sum(l)) / len(l)
else:
return None |
def _norm(s: str) -> str:
"""Normalize a string for dictionary key usage."""
rv = s.casefold().lower()
for x in " .-_./":
rv = rv.replace(x, "")
return rv |
def f_to_c(tempe):
"""Receives a temperature in Fahrenheit and returns in Celsius"""
return (tempe - 32) / 1.8 |
def mapVal(x, in_min, in_max, out_min, out_max):
"""
Maps a value that is between in_min and in_max to
a value between out_min and out_max
@param in_min The minimum value that the input value could be
@param in_max The maximum value that the input value could be
@param out_min The minimum value ... |
def time_lr_scheduler(optimizer, epoch, lr_decay=0.5, lr_decay_epoch=10):
"""Decay learning rate by a factor of lr_decay every lr_decay_epoch epochs"""
if epoch % lr_decay_epoch:
return optimizer
print("Optimizer learning rate has been decreased.")
for param_group in optimizer.param_groups... |
def _auth_mysql_cmd(cmd, username, password):
"""takes a command string and adds auth tokens if necessary"""
if username != "":
cmd.append("--user")
cmd.append(username)
if password != "":
cmd.append("--password="+password)
return cmd |
def form2_list_comprehension(items):
"""
Remove duplicates using list comprehension.
:return: list with unique items.
"""
return [i for n, i in enumerate(items) if i not in items[n + 1:]] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.