content stringlengths 42 6.51k |
|---|
def buffer_to_bytes(buf):
"""Cast a buffer object to bytes"""
if not isinstance(buf, bytes):
buf = bytes(buf)
return buf |
def s2n_motorola(str):
"""Extract multibyte integer in Motorola format (little endian)."""
x = 0
for c in str:
x = (x << 8) | ord(c)
return x |
def split_multiple(value):
"""Used to split multiple terms separated by comma (e.g. keywords)."""
result = list()
for item in value.split(','):
item = item.strip()
if item:
result.append(item)
return result |
def is_object_ref(d):
"""
Checks if a dictionary is a reference object. The dictionary is considered to be a
reference object when it contains non-empty 'id' and 'type' fields.
:type d: dict
:return: True if passed dictionary is a reference object, otherwise False
"""
has_id = 'id' in d.key... |
def validate_value(arg):
"""Function: validate_value
Description: Test function.
Arguments:
(input) arg
"""
return arg == "value" |
def _get_matching_stream(smap, itag):
""" Return the url and signature for a stream matching itag in smap. """
for x in smap:
if x['itag'] == itag and x.get("s"):
return x['url'], x['s']
raise IOError("Sorry this video is not currently supported by pafy") |
def readable_timedelta(days):
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
return "{} week(s) and {} day(s).".format(w... |
def find_first_different_block(cipher_bytes1, cipher_bytes2, block_size):
"""
If there are differences in cipher_bytes (in a block), return index of 1st byte in that block.
If they are the same, return -1.
If they have different length, and everything is the same (except those longer blocks)... |
def deltafmt(delta, decimals=None):
"""
Returns a human readable representation of a time with the format:
[[[Ih]Jm]K[.L]s
For example: 6h5m23s
If "decimals" is specified, the seconds will be output with that many decimal places.
If not, there will be two places for ti... |
def interp2(x, xdata, ydata): # --DC
"""LINEAR INTERPOLATION/EXTRAPOLATION GIVEN TWO DATA POINTS"""
m = (ydata[1] - ydata[0]) / (xdata[1] - xdata[0])
b = ydata[1] - m * xdata[1]
y = m * x + b
return y |
def flatten(obj, path=""):
"""Flatten nested dicts into hierarchical keys."""
result = {}
if isinstance(obj, dict):
for key, item in obj.items():
result.update(flatten(item, path=(path + "." if path else "") + key.lower()))
elif isinstance(obj, (str, int, float, bool)):
resul... |
def shortest_path_from_list(file_name, name_list):
""" Determines the shortest path to a file in a list of candidates.
Args:
file_name: A string specifying the name of the matching candidates.
name_list: A list of strings specifying paths.
Returns:
A string specifying the candidate with the shortest ... |
def cucdiv(real1, imag1, real2, imag2):
"""
Compute the quotient of the given complex numbers.
Assuming that `x` is the complex number composed of
the real part `real1` and imaginary part `imag1`,
while `y` consists of `real2` and `imag2`,
the result is computed by the equation `x / y`.
"""
... |
def is_valid_unknown_header(header):
"""Check whether characters of a header are all valid.
:type header: str
:rtype : bool
:param header: The header.
:return: True if so.
"""
# Construct valid characters.
valid_char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# Che... |
def pad_string(string: str, length: int) -> str:
"""Pads a string to specified length.
Args:
string: the text string to be padded with spaces
length: the length of the returned string
Returns:
A string exactly length characters long.
This is a helper function to hide the messy... |
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
"""
total = 0
for i in range(len(prices) - 1):
total += max(prices[i + 1] - prices[i], 0)
return total |
def link_parse(link, page_type):
"""Returns the owner and album ids for an album or the screen
name of either user or group page.
Parameters:
-----------
:link: str, e.g. https://vk.com/album11111_111111111
or https://vk.com/club1;
:page_type: str, one of {'album', 'user', ... |
def list_dim(lst):
""" Function to return the dimension of a list (e.g. nested list).
"""
if not type(lst) == list:
return 0
return len(lst) + list_dim(lst[0]) |
def fix_thread_string(tstr):
"""
Takes a string with numbers separated by period and possibly with /
at end, and outputs a string with 3 digit numbers separated by periods.
"""
remove_slash = lambda s: s[:-1] if s[-1] == '/' else s
three_digits = lambda s: "%03d" % int(s)
return '.'.join( ma... |
def filter_today_probs(done, today_probs):
"""Filter today's problems from done."""
today_prob_id = set(x[0] for x in today_probs)
done = list(filter(lambda x: x[0] not in today_prob_id,
done))
return done |
def sim_avg(terms1, terms2, sem_sim):
"""Similarity between two term sets based on average
"""
sims = []
for t1 in terms1:
for t2 in terms2:
sim = sem_sim(t1, t2)
if sim is not None:
sims.append(sim)
if not sims:
return
return round(sum(sim... |
def dir_filter(item):
"""
Accept each item which doesn't start with _
:type item: str
:param item: a string item to filter
:return: true if item doesn't start with _
"""
return not item.startswith("_") |
def HasCombine(r):
"""Whether structure involves Combine predicate."""
if isinstance(r, dict):
member_index = sorted(r.keys())
elif isinstance(r, list):
member_index = range(len(r))
else:
assert False, (
'HasCombine should be called on list or dict. Got: %s' % str(r))
if isinstance(r, dic... |
def relative_index(list_, value):
"""
Returns on which the given `value` would be inserted into the given list.
Parameters
----------
list_ : `list` of `Any`
The list o which value would be inserted.
value : `Any`
The value what would be inserted.
Returns
------... |
def inverse(a, n, strict = True):
"""
Compute the inverse of a modulo n using the Extended Euclidean algorithm.
If strict is True (default), raises an error if a is not invertible.
Otherwise, a number b is output such that a*b % n == gcd(a, b).
"""
b, x, y = n, 0, 1
while a != 0:
k ... |
def compute_border_indices(J, i0, i1):
"""
Computes border indices at all scales which correspond to the original
signal boundaries after padding.
At the finest resolution,
original_signal = padded_signal[..., i0:i1].
This function finds the integers i0, i1 for all temporal subsamplings
by ... |
def ping_parser(line):
"""When Twitch pings, the server ,ust pong back or be dropped."""
if line == 'PING :tmi.twitch.tv':
return 'PONG :tmi.twitch.tv'
return None |
def create_unique(dic):
"""
create unique identifier from the dict
"""
return dict(zip(range(1, len(dic.keys()) + 1), dic.keys())) |
def type_name(cls):
"""Get the name of a class."""
if not cls:
return '(none)'
return '{}.{}'.format(cls.__module__, cls.__name__) |
def linear_range_transform(tensor, from_range, to_range):
"""
Linearly interpolate from the from_range into to_range.
For example, if from_range = (0,1), and to_range=(-2, 5), then 0 is mapped
to -2 and 1 is mapped to 5, and all the values in-between are linearly
interpolated.
* tensor: a numpy... |
def parse_rule(l, cats):
"""Parses a sound change rule or category.
Given a line l with the format 'a > b / c_d ! e_f', produces a dict of
the form
{
'from': 'a',
'to': 'b',
'before': 'c',
'after': 'd',
'unbefore': 'e',
'unafter': 'f'
}.
If l is o... |
def format_size(size_bytes):
"""
Format size in bytes approximately as B/kB/MB/GB/...
>>> format_size(2094521)
2.1 MB
"""
if size_bytes < 1e3:
return "{}B".format(size_bytes)
elif size_bytes < 1e6:
return "{:.1}kB".format(size_bytes / 1e3)
elif size_bytes < 1e9:
... |
def FunList(List):
"""[Takes list and prints it vertically assigning each item its index number on CLI]
Args:
List ([string]): [The items to be displayed]
Returns:
[string]: [a string displaying entries vertically with its indexes]
"""
rtnList = "\n"
for i in range(len(List)):
... |
def method_2(lst):
""" Using sum() function """
lst_sum = sum(lst)
print(f'method 2: {lst_sum}')
return lst_sum |
def serialize(expr):
"""
Return code to write expression to buffer.
:param expr str: string python expression that is evaluated for serialization
:returns str: python call to write value returned by expr to serialization buffer
"""
return 'buff.write(%s)' % expr |
def count_char(char, word):
"""Counts the characters in word"""
return word.count(char)
# If you want to do it manually try a for loop |
def full_term_match(text, full_term, case_sensitive):
"""Counts the match for full terms according to the case_sensitive option
"""
if not case_sensitive:
text = text.lower()
full_term = full_term.lower()
return 1 if text == full_term else 0 |
def dependency_mapping(dep):
"""
+-----------+-----------------------------------+
| EGrid Tag | Dependency Tag |
+===========+===================================+
| S | nsub, csubj, csubjpass, dsubjpass |
+-----------+-----------------------------------+
| O ... |
def indexMultiple(x,value):
"""
Return indexes in x with multiple values.
"""
return [ i[0] for i in enumerate(x) if i[1] == value ] |
def dec_to_bin(number):
"""
Returns the string representation of a binary
number.
:param number: int, base 10
:return: str, string representation base 2
>>> assert(dec_to_bin(10) == '1010')
"""
return '{0:b}'.format(number) |
def opts_dd(lbl, value):
"""Format an individual item in a Dash dcc dropdown list.
Args:
lbl: Dropdown label
value: Dropdown value
Returns:
dict: keys `label` and `value` for dcc.dropdown()
"""
return {'label': str(lbl), 'value': value} |
def _merge_observation(accum_observation, observation):
"""
Old visual observation is discarded, because it is outdated frame.
Text observations are merged, because they are messages sent from the rewarder.
"""
if observation is None:
# We're currently masking. So accum_observation probably
... |
def get_role_permission(role):
"""Common function for getting the permission froms arg
This format is 'openstack.roles.xxx' and 'xxx' is a real role name.
:returns:
String like "openstack.roles.admin"
If role is None, this will return None.
"""
return "openstack.roles.%s" % role.l... |
def parseMemory(memAttribute):
"""
Returns EC2 'memory' string as a float.
Format should always be '#' GiB (example: '244 GiB' or '1,952 GiB').
Amazon loves to put commas in their numbers, so we have to accommodate that.
If the syntax ever changes, this will raise.
:param memAttribute: EC2 JSO... |
def decode_lookup(key, dataset, description):
"""Convert a reference to a description to be used in data files"""
if key in dataset:
return dataset[key]
else:
decoded = input("Please enter {desc} for {key}: ".format(desc=description, key=key))
dataset[key] = decoded
return de... |
def join_str_list(str_list):
"""Join a list of strings, handling spaces appropriately"""
return "".join(s[2:] if s.startswith("##") else " " + s for s in str_list) |
def imo_checksum(n):
"""
This function for IMO numbers that are designed as 7-digit integer number
:param n: String or Integer, Number to be subject to a IMO-checksum test
:return: Boolean, True for valid IMO number checksum, False for otherwise
"""
#
# Cross check type of input, and the r... |
def underline(text):
"""Format a string in underline by overstriking."""
return ''.join(map(lambda ch: ch + "\b_", text)) |
def has_duplicates2(t):
"""Checks whether any element appears more than once in a sequence.
Faster version using a set.
t: sequence
"""
return len(set(t)) < len(t) |
def strip_zip_suffix(filename):
"""
Helper function to strip suffix from filename.
:param filename: This field is the name of file.
"""
if filename.endswith('.gz'):
return filename[:-3]
elif filename.endswith('.bz2'):
return filename[:-4]
else:
return filename |
def _calculate_checksum(bytestring):
"""Calculate the checksum used by OneTouch Ultra and Ultra2 devices
Args:
bytestring: the string of which the checksum has to be calculated.
Returns:
A string with the hexdecimal representation of the checksum for the input.
The checksum is a very stupid one: it j... |
def fmt_time(val, missing, _trace, tzinfo):
"""Format timestamp."""
if val is None:
return missing
return (val.astimezone(tzinfo)).strftime("%Y-%m-%d %H:%M") |
def basic_ttr(n_terms, n_words):
""" Type-token ratio (TTR) computed as t/w, where t is the number of unique
terms/vocab, and w is the total number of words.
(Chotlos 1944, Templin 1957)
"""
if n_words == 0:
return 0
return n_terms / n_words |
def linecount(doc: str, end: int, start: int = 0):
"""Returns the number of lines (by counting the
number of newline characters \\n, with the first line
being line number one) in the string *doc* between the
positions *start* and *end*.
"""
return doc.count("\n", start, end) + 1 |
def find_innermost_brackets(formula):
"""Return the indices of (one of) the innermost bracketed term.
Args:
formula (list of str): The formula split at whitespace.
Returns:
int: The first index of the first innermost bracketed term.
int: The last index +1 of the first innermost bracketed term.
"""
d = 0... |
def get_user_credentials(username, env_config):
""" Return email and pswd of specified user, as a tuple. """
user_email = env_config.get(username).get('email')
user_pswd = env_config.get(username).get('pswd')
return (user_email, user_pswd) |
def update_schema_types(schema: dict, column_names: list, new_type: dict):
"""
Update entries within schema dictionary to reflect a common change across all rows in list (column_names)
Parameters
----------
schema
column_names
list of names of keys within schema to assign new type to
... |
def _get_hdr_values(extns, key):
"""
Helper function to get the all header values from a list of extensions.
The return value is a dict keyed on the EXPID value.
Parameters
----------
extns : iterable of :any:`astrodata.Astrodata`
AstroData extensions to be examined
key : str
... |
def build_production_array(arr: list) -> list:
"""
Parameters
-----------
Returns
---------
Notes
------
"""
if not arr:
return arr
lenth = len(arr)
out = [1] * lenth
for i in range(1, lenth):
out[i] = out[i-1] * arr[i-1]
tmp = 1
for i in... |
def parse_args(args):
"""
Takes the given args, parses them and return the arguments object
:param args:
:return:
"""
arguments = {}
if args is not None:
for argument in args:
if '=' in argument:
tmp = [a for a in argument.split('=', 1)]
tr... |
def bead_sort(sequence: list) -> list:
"""
>>> bead_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> bead_sort([6, 11, 12, 4, 1, 5])
[1, 4, 5, 6, 11, 12]
>>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> bead_sort([5, 0, 4, 3])
[0, 3, 4, 5]
"""
if any(not is... |
def normalize_api_params(params):
"""Normalize GitHub Issues API params to Search API.
conventions:
Issues API params | Search API converted values
-------------------------|---------------------------------------
state | into q as "state:open", "state:closed"
creator... |
def recurse_fact(n):
# n! can also be defined as n * (n-1)!
""" calculates n! recursively """
if n <= 1:
return 1
else:
return n * recurse_fact(n - 1) |
def get_label_buttons(label_buttons, endpoint, labels, collection, eid):
"""
Creates endpoints with the prefix 'endpoint' to assign qualitative
analysis codes to a given document 'eid' in a given 'collection'.
The codes are taken from 'labels' (typically part of the app config).
Appends the new en... |
def hsla_to_rgba(h, s, l, a):
""" 0 <= H < 360, 0 <= s,l,a < 1
"""
h = h % 360
s = max(0, min(1, s))
l = max(0, min(1, l))
a = max(0, min(1, a))
c = (1 - abs(2*l - 1)) * s
x = c * (1 - abs(h/60%2 - 1))
m = l - c/2
if h<60:
r, g, b = c, x, 0
elif h<120:
r, g,... |
def moeda_brasileira(numero, with_marker=True):
"""
Retorna uma string no formato de moeda brasileira
"""
if numero == None or numero == '': return ''
try:
contador = 0
preco_str = ''
num = numero.__str__()
if '.' in num:
preco, centavos = num.... |
def to_array(string):
"""Converts a string to an array relative to its spaces.
Args:
string (str): The string to convert into array
Returns:
str: New array
"""
try:
new_array = string.split(" ") # Convert the string into array
while "" in new_array: # Check if th... |
def split_numerical_value(numeric_value, splitVal):
"""
split numeric value on splitVal
return sub ranges
"""
split_num = numeric_value.split(',')
if len(split_num) <= 1:
return split_num[0], split_num[0]
else:
low = split_num[0]
high = split_num[1]
# Fix 2,2 ... |
def euclid_algorithm(area):
"""Return the largest square to subdivide area by."""
height = area[0]
width = area[1]
maxdim = max(height, width)
mindim = min(height, width)
remainder = maxdim % mindim
if remainder == 0:
return mindim
else:
return euclid_algorithm((mindim... |
def gridify(n, f):
"""
e.g., (1.1243, 0.005) -> 1.120
"""
return round(n / f) * f |
def neuron_params(device_params, scale=1 << 6, p_scale=1 << 12):
"""Translates device parameters to neuron parameters.
Parameters
----------
device_params : dictionary
dictionary of device parameter specification.
scale : int
neuron scale value. Default value = 1 << 6.
p_scale ... |
def create_zero_matrix(rows: int, columns: int) -> list:
"""
Creates a matrix rows * columns where each element is zero
:param rows: a number of rows
:param columns: a number of columns
:return: a matrix with 0s
e.g. rows = 2, columns = 2
--> [[0, 0], [0, 0]]
"""
if not isinstance(r... |
def configGet(cmap, tup):
"""
Answers the question, should we do this test, given this config file?
Following the values of the tuple through the map,
returning the first non-null value. If all values are null,
return True (handles tests that may have been added after the
config was generated).... |
def gen_marker(marker_id, marker_type, Point, Color, scale, text):
"""Place a marker of a given type and color at a given location"""
marker = """ -
header:
seq: 1482
stamp:
secs: 1556650754
nsecs: 179000000
frame_id: "world"
ns: "thick_traj"
id: %d
type: %... |
def get_array_info(subs, dictofsubs):
"""
Returns information needed to create and access members of the numpy array
based upon the string names given to them in the model file.
Parameters
----------
subs : Array of strings of subscripts
These should be all of the subscript names that a... |
def convert_f_to_k(temperature_f):
"""Convert Fahrenheit to Kelvin"""
temperature_k = (temperature_f - 32) * (5/9) + 273.15
return temperature_k |
def to_numbers(li_dig1, li_dig2, li_result):
"""
This function gets 3 lists of numbers which represent the operands' digits
It returns the operands as integers
"""
dig1 = li_dig1[0]
dig2 = li_dig2[0]
result = li_result[0]
for i in range(0, len(li_dig1) - 1):
dig1 = dig1 ... |
def cz_u(cL, U, cL_u = 0):
""" This calculates the coefficient of force in the z direction
with respect to the change in the forward velocity
Assumptions:
None
Source:
J.H. Blakelock, "Automatic Control of Aircraft and Missiles"
Wiley & Sons, Inc. New York, 1991, (pg 23)
Inpu... |
def next_available_id(v):
"""
Return smallest nonnegative integer not in v.
"""
i = 0
while i in v:
i += 1
return i |
def parse_schedule_json(schedules_json):
"""
The original design of metronome had an array of schedules defined but
limited it to 1. This limits to 1 and takes the array format or just
1 schedule format.
:param schedules_json: schedule or array of schedules in json
:type schedules_json: json []... |
def epoch_time(start_time: float, end_time: float):
"""
Calculate the time spent during one epoch
Args:
start_time (float): training start time
end_time (float): training end time
Returns:
(int, int) elapsed_mins and elapsed_sec spent during one epoch
"""
ela... |
def gray_code(N):
""" Generate a Gray code for traversing the N qubit states. """
if N <= 0 or type(N) is not int:
raise ValueError("Input for gray code construction must be a positive integer.")
if N == 1: # Base case
return ["0", "1"]
else:
sub_code = gray_code(N-1)
ret... |
def get_matching_items_from_dict(value, dict_name):
"""
Return all items in a dict for which the label matches the provided value.
@param value: the value to match
@param dict_name: the dict to look in
"""
matches = [dict_name[x]["items"]
for x in dict_name if x.lower() == value]... |
def bern_choice(probabilities, random_function) -> int:
"""Draws a random value with random_function and returns
the index of a probability which the random value undercuts.
The list is theoretically expanded to include 1-p
"""
assert type(probabilities) is list
random_value = random_function()
... |
def xor(a: bytes, b: bytes) -> bytes:
""" Xor byte a byte entre a e b """
return bytes(x^y for x, y in zip(a, b)) |
def generate_query_string(query_params):
"""Generate a query string given kwargs dictionary."""
query_frags = [
str(key) + "=" + str(value) for key, value in query_params.items()
]
query_str = "&".join(query_frags)
return query_str |
def fpi_bandpass_lims(d, n):
"""Bandpass filter limits for a single order of an FPI at given gap.
Parameters
----------
d : float
Gap length of the Fabry-Perot etalon.
n : int
The order of the FPI peak included in the limits
Returns
-------
(lmin, lmax) : tuple of floa... |
def joiner(list_of_strings):
"""Join all the stings in the list, excepting the first"""
if len(list_of_strings) > 1:
return ' '.join(list_of_strings[1:])
return '' |
def unpad_pkcs7(data):
"""
Strips PKCS#7 padding from data.
Raises ValueError if padding is invalid.
"""
if len(data) == 0:
raise ValueError("Error: Empty input.")
pad_value = data[-1]
if pad_value == 0 or pad_value > 16:
raise ValueError("Error: Invalid padding.")
for i ... |
def _parse_input(obj, arg):
"""
Returns obj[arg] if arg is string, otherwise returns arg.
"""
return obj[arg] if isinstance(arg, str) else arg |
def DNA_to_mRNA_List(DNA_string):
"""Takes in DNA sequence string and converts it to an mRNA list.
Parameters
----------
DNA_string : string
String that contains letters/characters of a DNA string, e.g., 'a,' t,' 'c,' and 'g.'
Returns
-------
mRNA_List : l... |
def l1_norm(lst):
"""
Calculates the l1 norm of a list of numbers
"""
return sum([abs(x) for x in lst]) |
def bisection_solve(x, eval_ans, epsilon, low, high):
"""x, epsilon, low, high are floats
epsilon > 0
eval_ans a function mapping a float to a float
low <= high and there is an ans below low and high s.t.
eval(ans) is within epsilon of x
returns ans s.t. eval(ans) within epsilon of x"""
... |
def choose(n: int, k: int) -> int:
"""Return binomial coefficient of n choose k."""
ans = 1
for i in range(min(k, n-k)):
ans *= n-i
ans //= i+1
return ans |
def check_if_only_decoys(sequences):
"""
Check if the sequences to consolidate are composed only of decoys
"""
only_decoys = True
for sequence in sequences:
if 'decoy' not in sequence.split()[2]:
only_decoys = False
break
return only_decoys |
def read_int_item(item_id: int) -> dict:
""" Example function """
return {
'foo': item_id
} |
def decode(what):
"""Decode a EDIComm string into its component parts (splitting lists as needed)"""
parts = what.split(' ')
new_parts = []
# First expansion: each separate parameter, keeping lists together.
this_part = ''
for part in parts:
this_part += part
merge = part.endswith('\\')
if merge:
thi... |
def add_lists(*lists):
"""Add two lists together without numpy
For example, given lists:
[1, 2] [3, 4]
The result is:
[4, 6]
Lists are sliced to prevent mutation.
"""
lists = (l[:] for l in lists)
return list(map(sum, zip(*lists))) |
def maybe_add_ellipses(s, maxlen=72, instead_of_ellipses_add_this_text=None):
"""
If string s is longer than maxlen, truncate it and add on ... to
the end.
If you want something else, use the instead_of_ellipses_add_this_text
>>> maybe_add_ellipses('abcdef')
'abcdef'
>>> maybe_add_ellipses... |
def best_score(a_dictionary):
"""Returns a key with the biggest integer value.
Checks if a thing is a dicrionary with the is instance method"""
if not isinstance(a_dictionary, dict) or len(a_dictionary) == 0:
return None
ret = list(a_dictionary.keys())[0]
big = a_dictionary[ret]
for k, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.