content stringlengths 42 6.51k |
|---|
def split_kwargs(original, anothers):
"""split a dict to 2 dicts.
Args:
original: original data.
antohers: the elments will be put the other dict if its key in
this tuple.
Returns: (original, new)
"""
new = {}
for key in anothers:
try:
new[... |
def get_tags_gff3(tagline):
"""Extract tags from given tagline"""
tags = dict()
for t in tagline.strip(';').split(';'):
tt = t.split('=')
tags[tt[0]] = tt[1]
return tags |
def patternToIndex(pattern):
"""
the index of the pattern in lexicographically ordered k-mers
"""
if len(pattern) == 1:
if pattern == 'A': return 0
elif pattern =='C': return 1
elif pattern =='G': return 2
elif pattern =='T': return 3
lastChar = pattern[-1:]
pref... |
def addrstr(astr):
"""Parse string astr as a socket address.
Return (addr, af) where af is a socket.AddressFamily and the type
of addr depends on af (see documentation of the socket module).
If astr contains a slash it is interpreted as the file name of a
AF_UNIX socket. Otherwise the syntax is ho... |
def modify_eve_dict(eve_dict):
"""
Modify nested event dictionary to make it follow a more flattened
approach so as to use full functionality of the run.py function
`find_value(name, obj)`. The dictionaries of the format
{
"event_type":"http",
"http":{
"hostname":"support... |
def bit_invert(value, width=32):
"""! @brief Return the bitwise inverted value of the argument given a specified width.
@param value Integer value to be inverted.
@param width Bit width of both the input and output. If not supplied, this defaults to 32.
@return Integer of the bitwise inversion of @... |
def get_ellipse_equation_coefficient_by_simplest_focus_add(x1, y1, x2, y2, add):
"""
[1/a^2, 0, 1/b^2, 0, 0, -1]
"""
if y1 == 0:
a = add / 2
aa = a * a
c = abs(x1)
bb = aa - c ** 2
return [1 / aa, 0, 1 / bb, 0, 0, -1]
b = add / 2
bb = b * b
c = abs(y1)... |
def palindrome_anagram(S):
"""Find an anagram of the string that is palindrome
"""
visited = set()
for s in S:
if s in visited:
visited.remove(s)
else:
visited.add(s)
return len(visited) <= 1 |
def filter_requirements(requirements: str) -> list:
"""Filter the requirements, exclude comments, empty strings
Parameters:
-----------
requirements: str,
string of requirements
Returns:
--------
list
list of filtered requirements
"""
list_requirements = requirement... |
def __get_gnome_url(pkg_info):
"""
Get gnome repo url of package
"""
src_repos = pkg_info["src_repo"].split("/")
if len(src_repos) == 1:
url = "https://gitlab.gnome.org/GNOME/" + pkg_info["src_repo"] + ".git"
else:
url = "https://gitlab.gnome.org/" + pkg_info["src_repo"] + ".git"... |
def calculate_m_metric(flux_a: float, flux_b: float) -> float:
"""Calculate the m variability metric which is the modulation index between two fluxes.
This is proportional to the fractional variability.
See Section 5 of Mooley et al. (2016) for details, DOI: 10.3847/0004-637X/818/2/105.
Args:
f... |
def is_same_sequence_sublist(child_list: list, parent_list: list) -> bool:
"""
Check if the parent list has a sublist which is identical to the child list including the sequence.
Examples:
- child_list = [1,2,3], parent_list=[5,1,2,3,9] -> ``True``
- child_list = [1,2,3], parent_list=[5,6,1,... |
def entity_list(raw_entities_dict):
"""
Returns a list of tuples that preserves the qbbo_types and Id keys.
(The input is what you get when you run quickbooks.transactions()
or quickbooks.names())
Each item in list is a three-item tuple:
(qbbo_type,Id,raw_entity_dict)
"""
e_list =... |
def username(email):
"""Keeps the username of an email address."""
return email and email.split('@', 1)[0] |
def valid_cluster_header(ds, file):
"""
checks if colnames are comaptible with provided list
:param ds: ds header name
:param file: lsit of allowed header names
:return: bool showing whether given colname is compatible with list
"""
return str(ds) in list(file) |
def sgn(val):
"""Sign function. Returns -1 if val negative, 0 if zero, and 1 if
positive.
"""
try:
return val._sgn_()
except AttributeError:
if val == 0:
return 0
if val > 0:
return 1
else:
return -1 |
def estimate_fee(estimated_size: int, fee_kb: int) -> int:
"""
Calculate fee based in the transaction size and the price per KiB.
:param estimated_size: Estimated size for the transaction.
:param fee_kb: Price of the transaction by KiB.
:return: The estimated fee.
"""
return int(estimated_size * fee_kb / 1024.0 ... |
def get_tool_name(header):
"""Gets the name of the tool that was used and that delivered the log."""
header = header.split(":")
return header[1].strip(), ":".join(header[2:]) |
def none_of(pred, iterable):
"""
Returns ``True`` if ``pred`` returns ``False`` for all the elements in
the ``iterable`` range or if the range is empty, and ``False`` otherwise.
>>> none_of(lambda x: x % 2 == 0, [1, 3, 5, 7])
True
:param pred: a predicate function to check a value from... |
def get_last_index(dictionary: dict) -> int:
"""
Obtaining of the last index from the `dictionary`, functions returns `-1` if the `dict` is empty.
"""
indexes = list(dictionary)
return indexes[-1] if indexes else -1 |
def is_google_registry_image(path: str) -> bool:
"""Returns true if the given Docker image path points to either the Google
Container Registry or the Artifact Registry."""
host = path.partition('/')[0]
return host == 'gcr.io' or host.endswith('docker.pkg.dev') |
def make_diff_header(path, old_tag, new_tag, src_label=None, dst_label=None):
"""Generate the expected diff header for file PATH, with its old and new
versions described in parentheses by OLD_TAG and NEW_TAG. SRC_LABEL and
DST_LABEL are paths or urls that are added to the diff labels if we're
diffing against th... |
def genSubparts(string):
"""
Partition a string into all possible two parts, e.g.
given "abcd", generate [("a", "bcd"), ("ab", "cd"), ("abc", "d")]
For string of length 1, return empty list
"""
length = len(string)
res = []
for i in range(1, length):
res.append((string[0:i], stri... |
def _PerModeMini(x):
"""Takes Numeric Code and returns String API code
Input Values: 1:"Totals", 2:"PerGame"
Used in:
"""
measure = {1:"Totals",2:"PerGame"}
try:
return measure[x]
except:
raise ValueError("Please enter a number between 1 and "+str(len(measure))) |
def binary_eval(op, left, right):
"""token_lst has length 3 and format: [left_arg, operator, right_arg]
operator(left_arg, right_arg) is returned"""
return op(left, right) |
def get_custom_params_value(custom_params_list, key):
"""
:param List custom_params_list:
:param str key:
:rtype: str
"""
param = next(iter(
filter(lambda x: x['name'] == key,
custom_params_list)), None)
if param:
return param['value']
else:
return ... |
def path_to_directions(l):
"""
as seen here: https://github.com/multinormal/ddsm/blob/master/ddsm-software/get_ddsm_groundtruth.m
original documentation: http://marathon.csee.usf.edu/Mammography/DDSM/case_description.html#OVERLAYFILE
rows and columns are swapped
"""
chain_code = {0: [-1, 0],
... |
def soundex(name, len=4):
"""
Code referenced from http://code.activestate.com/recipes/52213-soundex-algorithm/
@author: Pradnya Kulkarni
"""
# digits holds the soundex values for the alphabet
digits = "01230120022455012623010202"
sndx = ""
fc = ""
# Translate alpha chars in name... |
def to_internal_instsp(instsp):
"""Convert instantiation pair to assignments of internal variables."""
tyinst, inst = instsp
tyinst2 = {"_" + nm: T for nm, T in tyinst.items()}
inst2 = {"_" + nm: t for nm, t in inst.items()}
return tyinst2, inst2 |
def dict2str(dictionary):
"""Helper function to easily compare lists of dicts whose values are strings."""
s = ''
for k, v in dictionary.items():
s += str(v)
return s |
def is_valid_manifest(manifest_json, required_keys):
"""
Returns True if the manifest.json is a list of the form [{'k' : v}, ...],
where each member dictionary contains an object_id key.
Otherwise, returns False
"""
for record in manifest_json:
record_keys = record.keys()
if not ... |
def convert_classes(raw_data, local_label_dict):
"""Convert the MC Land use classes to the specific things I'm interested in
Args
----
raw_data (dict) : dictionary of raw data, returned from load_raw_data()
local_label_dict (dict) : a dictionary that maps the datasets labels into
the labels... |
def multi_tmplt_1(x, y, z):
"""Tests Interfaces"""
return x + y + z |
def DeepSupervision(criterion, xs, y):
"""
Args:
criterion: loss function
xs: tuple of inputs
y: ground truth
"""
loss = 0.
for x in xs:
loss += criterion(x, y)
# loss /= len(xs)
return loss |
def max_nth_percent(n, data):
""" A function that returns the nth percent top value, planned use is for plotting
:param n: the percentile value desired for return
:param data: the iterable object searched through
:return: nth percent largest value
"""
import heapq
data=list(data)
n=floa... |
def lennard_jones_potential(x):
"""
calculates the lennard-jones-potential of a given value x
"""
return 4 * ((x ** -12) - (x ** -6)) |
def find_migration_file_version(config, migrations, version, prior=False):
"""
Returns int (or None on failure)
Finds the target migration version by its version string (not sortable version) in the list of migrations
"""
# find target
ix = None
for ix, m in enumerate(migrations):
... |
def add_params(value, arg):
""" Used in connection with Django's add_preserved_filters
Usage:
- url|add_params:'foo=bar&yolo=no'
- url|add_params:'foo=bar'|add_params:'motto=yolo'
use only for admin view
"""
first = '?'
if '?' in value:
first = '&'
return v... |
def have_mp3_extension(l):
"""Check if .mp3 extension is present"""
if ".mp3" in str(l):
return 1
else:
return 0 |
def font_stretch(keyword):
"""Validation for the ``font-stretch`` property."""
return keyword in (
'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed',
'normal',
'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded') |
def any_above(prices, threshold):
"""Determines if there are any prices above a threshold."""
for x in prices:
if x > threshold:
return True
return False |
def dice_counts(dice):
"""Make a dictionary of how many of each value are in the dice """
return {x: dice.count(x) for x in range(1, 7)} |
def _getParameterRange(key):
"""
Returns fur's default parameter range as 2-tuple (min, max).
key: fur attribute (string)
"""
if "Density" ==key: return (10000.0, 30000.0)
## geometry attributes (1) for single strand
if "Length" ==key: return (1.00, 5.00)
if "BaseWidth"==key: return ... |
def get_content_values_by_name(content, name):
"""
:type content: dict
:param content: A dictionary as returned by KairosDB with timestamps converted to seconds since the epoch
:type name: str
:param name: The name of the entry in the results whose values will be returned
:rtype: list
:ret... |
def sort_spec(spec):
"""Helper to provide a key function for `sorted`
Provide key to sort by type first and by whatever identifies a particular
type of spec dict
Parameters
----------
spec: dict
study specification dictionary
Returns
-------
string
"""
if spec['type... |
def recall_at(targets, scores, k):
"""Calculation for recall at k."""
for target in targets:
if target in scores[:k]:
return 1.0
return 0.0 |
def generate_predefined_split(n=87, n_sessions=3):
"""Create a test_fold array for the PredefinedSplit function."""
test_fold = []
for s in range(n_sessions):
test_fold.extend([s] * n)
return test_fold |
def assert_not_equal(other, obj, msg=None):
"""Fail if the two objects are equal as determined by the '=='
operator.
"""
if obj == other:
raise AssertionError(msg or '%r == %r' % (obj, other))
return obj |
def decode_dict(source):
"""
docstring for
"""
if type(source) in [str, int, float, bool]:
return source
if type(source) == bytes:
return source.decode()
if type(source) in [list, set]:
decode_list = []
for item in source:
decode_list.append(decode_dic... |
def reverse(graph):
"""Reverse the direction of edges in a graph."""
reverse_graph = [[] for _ in range(len(graph))]
for node, children in enumerate(graph):
for child in children:
reverse_graph[child].append(node)
return reverse_graph |
def is_std_logic(value):
"""Returns whether the given value is the Python equivalent of an
std_logic."""
return value is True or value is False |
def has_at_least_one_models_key(lc_keys):
"""Check if there is at least one optional Models dict key in lowercase keys
"""
model_keys = {"paper",
"code",
"weights",
"config",
"readme",
"metadata",
"r... |
def erb_bandwidth(fc):
"""Bandwidth of an Equivalent Rectangular Bandwidth (ERB).
Parameters
----------
fc : ndarray
Center frequency, or center frequencies, of the filter.
Returns
-------
ndarray or float
Equivalent rectangular bandwidth of the filter(s).
"""
# In... |
def _swap_endian(val, length):
"""
Swap the endianness of a number
"""
if length <= 8:
return val
if length <= 16:
return (val & 0xFF00) >> 8 | (val & 0xFF) << 8
if length <= 32:
return ((val & 0xFF000000) >> 24 |
(val & 0x00FF0000) >> 8 |
... |
def check_dht_value_type(value):
"""
Checks to see if the type of the value is a valid type for
placing in the dht.
"""
typeset = [int, float, bool, str, bytes]
return type(value) in typeset |
def mVPD( vpd, vpdclose, vpdopen ):
"""VPD dependent reduction function of the biome dependent potential conductance"""
if vpd <= vpdopen:
return 1.0
elif vpd >= vpdclose:
return 1.0
else:
return ( ( vpdclose - vpd ) / ( vpdclose - vpdopen ) ) |
def pseudo_quoteattr(value):
"""Quote attributes for pseudo-xml"""
return '"%s"' % value |
def is_valid_section_format(referenced_section):
""" referenced_section - a list containing referenced chapter
and paragraph.
"""
return referenced_section is not None and len(referenced_section) == 2 |
def row_to_dict(row):
"""
This takes a row from a resultset and returns a dict with the same structure
:param row:
:return: dict
"""
return {key: value for (key, value) in row.items()} |
def _zero_forward_closed(x, y, c, l):
"""convert coordinates to zero-based, both strand, open/closed coordinates.
Parameters are from, to, is_positive_strand, length of contig.
"""
y += 1
if not c:
x, y = l - y, l - x
return x, y |
def get_backgroundcolor(window, defalut=0xeeeeee):
""" Get background color through accesibility api. """
import sys
try:
acc = window.getAccessibleContext()
if sys.platform.startswith("win"):
return acc.getAccessibleChild(0).getBackground()
else:
return acc.g... |
def parse_user(line, sep=','):
"""
Parses a user line
Returns: tuple of (user_id, gender)
"""
fields = line.strip().split(sep)
user_id = int(fields[0]) # convert user_id to int
gender = fields[1]
return user_id, gender |
def create_one_hot_v(selected_set, reference):
"""
:param selected_set:
:param reference: list/dict, is full set list or a item2id dict
:return:
"""
v = [0 for i in range(len(reference))]
# print('************** debug *************** create one hot v', selected_set, reference, )
if type... |
def parse_line(line, file_type, verboseprint):
"""Parse a scan file line, returns state, proto, port, host, banner."""
result = []
if line[0] == "#":
return result
if file_type == "masscan":
state, proto, port, host, _ = line.split()
result = ["open", proto, port, host, ""]
... |
def encode_bool(value):
"""Encode booleans to produce valid XML"""
if value:
return "true"
return "false" |
def _modify_instance_state_response(response_type, previous_state, new_state):
"""
Generates a response for a Start, Stop, Terminate requests.
@param response_type: Cloudstack response.
@param previous_state: The previous state of the instance.
@param new_state: The new state of the instance.
@... |
def minutes_readable(minutes):
"""
convert the duration in minutes to a more readable form
Args:
minutes (float | int): duration in minutes
Returns:
str: duration as a string
"""
if minutes <= 60:
return '{:0.0f} min'.format(minutes)
elif 60 < minutes < 60 * 24:
... |
def find_first_list_element_above(a_list, value):
"""
Simple method to return the index of the first element of a list that is greater than a specified value.
Args:
a_list: List of floats
value: The value that the element must be greater than
"""
if max(a_list) <= value:
Val... |
def get_id(state):
"""
Assigns a unique natural number to each board state.
:param state: Two dimensional array containing the state of the game board
:return: Id number of the state
"""
cell_id = 0
exponent = 8
for row in state:
for column in row:
if column == 1:
... |
def remove_text_inside_brackets(text, brackets="()[]{}"):
"""Removes all content inside brackets"""
count = [0] * (len(brackets) // 2) # count open/close brackets
saved_chars = []
for character in text:
for idx, brack in enumerate(brackets):
if character == brack: # found bracket
... |
def multAll(lst):
"""Multiplies a list of variables together"""
if len(lst) == 0:
return 0
out = lst[0]
for i in range(1,len(lst)):
out *= lst[i]
return out |
def _shell_quote(word):
"""Use single quotes to make the word usable as a single commandline
argument on bash, so that debug output can be easily runnable.
"""
return "'" + word.replace("'", "'\"'\"'") + "'" |
def base_expansion(num: int, base: int = 2):
"""
return a base expansion
"""
q = int(num)
b = int(base)
count = 0
expansion = []
while q != 0:
expansion.append(q % b)
q = q//b
count += 1
expansion.reverse()
res = "".join(map(str, expansion))
return int... |
def commandLine(Argv):
"""
Method converting a list of arguments/parameter in a command line format (to include in the execution of a program for exemple).
list --> str
"""
assert type(Argv) is list, "The argument of this method are the arguments to convert in the command line format. (type Lis... |
def _get_job_string(ii, jj, ii_zfill, jj_zfill, protocol):
"""Returns the job string used in `generate_job_indexes`."""
_s_ii = str(ii).zfill(ii_zfill)
_s_jj = str(jj).zfill(jj_zfill)
return "p%s-%s-%s" % (str(protocol), _s_ii, _s_jj) |
def truncate(base, length, ellipsis="..."):
"""Truncate a string"""
lenbase = len(base)
if length >= lenbase:
return base
return base[:length - len(ellipsis)] + ellipsis |
def _tokenize_string(formula):
"""
Converts a string formula into a series of tokens for evaluation
Takes a string and divides it into a list of individual string tokens.
Special tokens include ``"(", ")", "+", "^", "[", "]", "=", "~"``,
where these have the expected Python behavior, with ``"="`` a... |
def zip_object(keys, values=None):
"""Creates a dict composed from lists of keys and values. Pass either a
single two dimensional list, i.e. ``[[key1, value1], [key2, value2]]``, or
two lists, one of keys and one of corresponding values.
Args:
keys (list): either a list of keys or a list of ``[... |
def assignment_no_params_with_context(context):
"""Expected assignment_no_params_with_context __doc__"""
return "assignment_no_params_with_context - Expected result (context value: %s)" % context['value'] |
def unhappy_point(list, index):
"""
Checks if a point is unhappy. Returns False if happy.
"""
if list[index] == list[index - 1] or list[index] == list[(index + 1) % len(list)]:
return False
return True |
def process_coordinate_string(str):
"""
Take the coordinate string from the KML file, and break it up into [[Lat,Lon,Alt],[Lat,Lon,Alt],...]
"""
long_lat_alt_arr = []
for point in str.split('\n'):
if len(point) > 0:
long_lat_alt_arr.append(
[float(point.split(',')... |
def find_ngrams(token_dict, text, n):
""" See: https://github.com/facebookresearch/ParlAI/blob/master/parlai/core/dict.py#L31
token_dict: {'hello world', 'ol boy'}
text: ['hello', 'world', 'buddy', 'ol', 'boy']
n: max n of n-gram
ret: ['hello world', 'buddy', 'ol boy']
"""
#... |
def badhash(x):
"""
Just a quick and dirty hash function for doing a deterministic shuffle based on image_id.
Source:
https://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key
"""
x = (((x >> 16) ^ x) * 0x045d9f3b) & 0xFFFFFFFF
x = (((x ... |
def find_between(string, first, last):
"""Return substring between 'first' and 'last'."""
try:
start = string.index(first) + len(first)
end = string.index(last, start)
return string[start:end]
except ValueError:
return "" |
def getsize(data):
"""Return the smallest possible integer size for the given array."""
maxdata = max(data)
if maxdata < (1 << 8):
return 1
if maxdata < (1 << 16):
return 2
return 4 |
def l2_loss(x: float, y: float) -> float:
"""
Compute the L2 loss function.
Return the square difference between the inputs.
https://www.bitlog.com/knowledge-base/machine-learning/loss-function/#l2-error
Parameters
----------
x : float
The estimate
y : float
The actual... |
def action_get_into_bash(image_name, image_tag, user_name):
"""The function action_get_into_bash takes into the bash shell running in the container.
Arguments:
image_name: Name of the image to be used to build the container.
image_tag: The tag of the image which is used to build the container.
... |
def escape_html_chars(str_val):
"""
Escape special HTML characters (& <>)
@type str_val: string
@return: formatted string
@rtype: string
"""
if str_val is None:
return None
output = str_val
output = output.replace('&', '&')
output = output.replace(' ', ' ')
o... |
def convert_to_int(str_byte: str) -> int:
"""Take string representation of byte and convert to int"""
return int(str_byte, 2) |
def count_ballots(ballots):
"""
Counts the "for" and "against" ballots
:param ballots: Vote ballots
:return: A tuple of dictionaries: for and against votes
"""
# Count the number of votes for each candidate
results_for = {}
results_against = {}
blanks = []
for name, ballot in b... |
def pkcs7_unpad(bytes_, len_):
"""Unpad a byte sequence with PKCS #7."""
remainder = bytes_[-1]
pad_len = remainder if remainder != 0 else len_
msg = bytes_[:-pad_len]
pad = bytes_[-pad_len:]
if remainder >= len_ or any(p != remainder for p in pad):
raise ValueError("Invalid padding")
... |
def permutation(s):
"""
@s: list of elements, eg: [1,2,3]
return: list of permutations, eg: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
"""
ret = []
length = len(s)
if length == 0:
return ret
if length == 1:
return [s]
curr = s[0]
for prev in permutat... |
def global2local(gobal_coord, start, end, strand):
"""Returns local coordinate in a global region"""
# swap if strands disagree
if strand == 1:
return gobal_coord - start
else:
return end - gobal_coord |
def split_line(line):
"""Split a line read from file into a name/sequence tuple
Arguments:
line: line of text with name and sequence separated by tab.
Returns:
(name,sequence) tuple.
"""
name = line.strip('\n').split('\t')[0]
seq = line.strip('\n').split('\t')[-1]
return (name... |
def get_keys(dictionary):
"""
:param dictionary: python dict obj
:return: sorted list of keys of dictionary
"""
keys = sorted(list(dictionary.keys()))
print("length of keys: ", len(keys))
return keys |
def rgbu8_size(width, height):
"""Calculate rgb 24bit image size
Args:
width: image width
height: image height
Returns:
rgb 24bit image data size
"""
return int(width * height * 3) |
def parse_author_and_permlink(url):
"""
Parses a typical steem URL and returns a tuple
including the author and permlink.
Ex: http://steemit.com/@author/permlink
"""
try:
author = url.split("@")[1].split("/")[0]
permlink = url.split("@")[1].split("/")[1]
except IndexError as ... |
def get_smiles(res):
"""
Get a list of SMILES from function results
"""
smiles = set()
for smi in res:
try:
smiles.add(
"{}\t{}".format(
smi["molecule_structures"]["canonical_smiles"],
smi["molecule_chembl_id"],
... |
def _is_private(name: str) -> bool:
"""Return true if the name is private.
:param name: name of an attribute
"""
return name.startswith('_') |
def barxor(a, b): # xor two strings of different lengths
"""XOR the given byte strings. If they are not of equal lengths, right pad the shorter
one with zeroes.
"""
if len(a) > len(b):
return [ord(x) ^ ord(y) for (x, y) in zip(a[:len(b)], b)]
else:
return [ord(x) ^ ord(y) for (x, y) in zip(a, b[:l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.