content stringlengths 42 6.51k |
|---|
def _endian_char(big) -> str:
"""
Returns the character that represents either big endian or small endian in struct unpack.
Args:
big: True if big endian.
Returns:
Character representing either big or small endian.
"""
return '>' if big else '<' |
def get_class_name(o, lower=False):
"""
Returns the class name of an object o.
"""
if not isinstance(o, type):
o = o.__class__
if lower:
return o.__name__.lower()
else:
return o.__name__ |
def _buf_split(b):
""" take an integer or iterable and break it into a -x, +x, -y, +y
value representing a ghost cell buffer
"""
try: bxlo, bxhi, bylo, byhi = b
except:
try: blo, bhi = b
except:
blo = b
bhi = b
bxlo = bylo = blo
bxhi = byhi = b... |
def saving_file(filename):
"""
:param filename: name of the file we will save after calling this function
:type filename: str
"""
return f'\nSaving {filename}\n' |
def check_prime(number):
"""
it's not the best solution
"""
special_non_primes = [0, 1, 2]
if number in special_non_primes[:2]:
return 2
elif number == special_non_primes[-1]:
return 3
return all([number % i for i in range(2, number)]) |
def _station_code(station):
"""returns station code from a station dict"""
return "-".join([station["USAF"], station["WBAN"]]) |
def tonum(value):
"""Convert a value to a numerical one if possible"""
for converter in (int, float):
try:
return converter(value)
except (ValueError, TypeError):
pass
return value |
def colour_name(colour):
"""Return the (lower-case) full name of a colour.
colour -- 'b' or 'w'
"""
try:
return {'b': 'black', 'w': 'white'}[colour]
except KeyError:
raise ValueError |
def acceptable_variance(probability, window_size):
"""Get the acceptable variance.
:param probability: The probability to use.
:param window_size: A window size.
:return: The acceptable variance.
"""
return float(probability * (1 - probability)) / window_size |
def get_injected_value(field_metadata, source):
""" First try for attr, then key, then call, else source """
# We can have different flavors of the injected() field type:
# injected(Breadcrumbs, attr='title')
# injected(Breadcrumbs, key='title')
# injected(Breadcrumbs) where Breadcrumbs.__call__ ex... |
def hide_empty(value, prefix=', '):
"""Return a string with optional prefix if value is non-empty"""
value = str(value)
return prefix + value if value else '' |
def _filter_comparison_fields(song):
"""Filter missing artist, album, title, or track fields to improve match accuracy."""
# Need both tracknumber (mutagen) and track_number (Google Music) here.
return [field for field in ['artist', 'album', 'title', 'tracknumber', 'track_number'] if field in song and song[field]] |
def unique(sequence):
"""Get unique elements from a list maintaining the order.
Parameters
----------
input_list: list
Returns
-------
unique_list: list
List with unique elements maintaining the order
"""
visited = set()
return [x for x in sequence if not (x in... |
def parse_coord(coord_string):
"""Convert string to number, and exclude brackets such as 0.342(3)."""
coord = coord_string.split("(")[0]
return float(coord) |
def voltage_extremes(x):
"""
find the minimum and the maximum of a list of voltage and return a tuple
:param x: the input should be a list
:raises ImportError: if the module not found
:raises TypeError: if the input is not a list or the input includes string
:raises ValueError: if the input i... |
def calc_rank(someset, n):
"""
Calculates the rank of a subset `someset` of {1, 2, ..., `n`}
in the ordering given by grey sequenccce of characteristic vectors.
"""
assoc_seq = [k + 1 in someset for k in range(n)]
bit = False
rank = 0
for k, x in enumerate(assoc_seq):
bit ^= x
rank +=... |
def linspace(a, b, num_points):
""" return a list of linearly spaced values
between a and b having num_points points
"""
inc = (float(b) - float(a))/(num_points-1)
ret_ar = []
for i in range(num_points):
ret_ar.append(a + i*inc)
return ret_ar |
def group_anagrams(strs):
"""
Group anagrams in given list of strings
:param strs: a list of input strings
:type strs: list[str]
:return: grouped anagrams
:rtype: list[str]
"""
str_dict = {}
for string in strs:
str_sorted = ''.join(sorted(string))
if str_sorted not i... |
def _dict_mixed_conll_formatter(v, v_delimiter):
"""
Format a mixed value into a string representation.
Args:
v: The value to convert to a mixed CoNLL string format.
v_delimiter: The delimiter between values in the string.
Returns:
A CoNLL representation of the mixed value.
... |
def parse_uri(uri):
"""Parse the doozerd URI scheme to get node addresses"""
if uri.startswith("doozer:?"):
before, params = uri.split("?", 1)
addrs = []
for param in params.split("&"):
key, value = param.split("=", 1)
if key == "ca":
addrs.append(... |
def get_by_string(source_dict, search_string, default_if_not_found=None):
"""
Search a dictionary using keys provided by the search string.
The search string is made up of keywords separated by a '.'
Example: 'fee.fie.foe.fum'
:param source_dict: the dictionary to search
:param search_string: se... |
def splitWords(aList):
"""
Takes a list of strings, splits those strings on the whitespace and combines
the newly split words into a list, also removes double quotes
"""
returnList = list()
for item in aList:
stringList = item.split(" ")
returnList += stringList
# Cl... |
def align_address_to_size(address, align):
"""Align the address to the given size."""
return address + ((align - (address % align)) % align) |
def pathcombine(path1, path2):
"""Joins two paths together.
This is faster than `pathjoin`, but only works when the second path is relative,
and there are no backreferences in either path.
>>> pathcombine("foo/bar", "baz")
'foo/bar/baz'
"""
if not path1:
return path2.lstrip()
... |
def _format_public_key(public_key):
"""PEM-format the public key."""
public_key = public_key.strip()
if not public_key.startswith("-----BEGIN PUBLIC KEY-----"):
public_key = "-----BEGIN PUBLIC KEY-----\n" + \
public_key + \
"\n-----END PUBLIC KEY-----"
... |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*',\
'*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check... |
def _aligned_i(i, olen, alignment):
"""
A function that checks if a given foreign word is aligned
to any 'english' word in a given 'english' sentence
"""
# print "i:%s" % (i)
# print "olen:%s" % (olen)
# print "len(alignment):%s" % (len(alignment))
for o in range(olen):
if (i, o)... |
def median(lst):
""" Calculates median value of the given lst """
lst=sorted(lst)
n=len(lst)
if n&1==0:
res=(lst[(n>>1)-1]+lst[n>>1])*.5
else:
res=lst[n>>1]
return res |
def format_time(seconds):
"""Defines how to format time in FunctionEvent"""
US_IN_SECOND = 1000.0 * 1000.0
US_IN_MS = 1000.0
time_us = seconds * 1e6
if time_us >= US_IN_SECOND:
return "{:.3f} s".format(time_us / US_IN_SECOND)
if time_us >= US_IN_MS:
return "{:.3f} ms".format(tim... |
def rle_kyc(seq: str) -> str:
""" Run-length encoding """
counts = []
count = 0
prev = ''
for char in seq:
# We are at the start
if prev == '':
prev = char
count = 1
# This letter is the same as before
elif char == prev:
count += 1... |
def rol(a, b):
"""Rotate left
Returns (result, carry)
"""
b &= 31
if b:
return ( (a >> (32 - b)) | ((a << b) & 0xffffffff), 1 & (a >> (31 - b)) )
else:
return (a, 0) |
def feature_size(
enable_abs,
enable_linear_speed,
enable_angular_speed,
enable_steering,
):
""" The length of the environment features """
total_length = 0
if enable_linear_speed:
total_length += 1
if enable_angular_speed:
total_length += 1
if enable_abs:
... |
def dict_to_list(input_obj):
"""Convert resource dict into list."""
# return sorted(input.values(), key=lambda x: locale.strxfrm(x.get("name_sv")))
return list(input_obj.values()) |
def SymbolTypeToHuman(type):
"""Convert a symbol type as printed by nm into a human-readable name."""
return {'b': 'bss',
'd': 'data',
'r': 'read-only data',
't': 'code',
'w': 'weak symbol',
'v': 'weak symbol'}[type] |
def format_exception(type, value, tb):
"""Single string return wrapper for traceback.format_exception
used by nrnpyerr_str
"""
import traceback
slist = (
traceback.format_exception_only(type, value)
if tb is None
else traceback.format_exception(type, value, tb)
)
s =... |
def roundup_16(x: int) -> int:
"""Rounds up the given value to the next multiple of 16."""
remainder = x % 16
if remainder != 0:
x += 16 - remainder
return x |
def check_options(cart_option, baseprice_option):
"""
Checks if the options of a product in the cart matches with the options of the given
product in the base-price file.
:param cart_option: The dict containing options provided with the product in the cart
:type cart_option: dict
:param basepric... |
def check_length(min_length: int,
max_length: int,
mode: str = 'and',
*args) -> bool:
"""
check items length is between min_length and max_length
:param min_length: minimum length
:param max_length: maximum length
:param mode: check mode, 'and': all... |
def starts_with(line, starts_list):
"""Returns True when the line starts with any of the string in
starts_list"""
return any([line.startswith(s) for s in starts_list]) |
def sqDig(n):
"""
n: an int or a str of int
output: the square of the digits in n
"""
retVal = 0
aStr = str(n)
for digit in aStr:
retVal += int(digit) ** 2
return retVal |
def get_price_range(category, value):
"""
Function to generate the price query. Code is from https://docs.mongodb.com
/manual/reference/operator/aggregation/gte/ and https://docs.mongodb.com/
manual/reference/operator/aggregation/lte/
"""
price_file = {'Phones': {
1: {'$gte': 0, '$lte': ... |
def stripNameSpace(objName):
"""
Check to see if there is a namespace on the incoming name, if yes, strip and return name with no namespace
:param name: str
:return: str, name with no namespace
"""
name = objName
if ":" in name:
name = name.split(":")[-1]
return name |
def fastExpMod(b, e, m):
"""
e = e0*(2^0) + e1*(2^1) + e2*(2^2) + ... + en * (2^n)
b^e = b^(e0*(2^0) + e1*(2^1) + e2*(2^2) + ... + en * (2^n))
= b^(e0*(2^0)) * b^(e1*(2^1)) * b^(e2*(2^2)) * ... * b^(en*(2^n))
b^e mod m = ((b^(e0*(2^0)) mod m) * (b^(e1*(2^1)) mod m) * (b^(e2*(2^2)) mod m) * ...... |
def parse_version(version, sep="."):
"""Convert string version into a tuple of ints for easy comparisons."""
return tuple(int(x) for x in version.split(sep)) |
def hk_modes(hier_num):
"""
Generate modes in the HK hierarchy.
Parameters
----------
hier_num : int
Number in the HK hierarchy (hier_num = n means the nth model).
Returns
-------
p_modes : list
List of psi modes, represented as tuples.
Each tuple contains the h... |
def get_binary_tree_diameter_and_height(tree):
"""
Given a binary tree, returns the longest path of connected nodes & height
O(n) time
O(n) space for recursion
"""
# leaf node has 0 diameter & height (base case)
if not tree:
return 0, 0
# calculate the left and right sub tree ... |
def remove_list_duplicates(list: list, amount: int = 1) -> list:
"""
Info:
Removes any duplicates from the list given with the amount, then retursn that list
Paramaters:
list: list - The list to remove duplicates from.
[Optional]amount: int -> 1 - Amount of duplicates wanted
... |
def enumerate_items(items):
"""
list items in a string
ex. ["dog", "cat", "mouse"] returns "dog, cat, and mouse"
"""
items_str = ""
# multiple items in container
if len(items) > 1:
for item in items[:-2]:
items_str += "{}, ".format(item)
items_str += "{} ".format... |
def horner(a, x):
"""
T(n) = Theta(n^2) since we have to traverse a nested loop for each term
:param a: list of "n" coefficients
:x float: the value for which to compute the polynomial value
"""
y = 0
for i in range(len(a)):
temp = 1
print("temp= 1")
for j in ran... |
def translate_to_id(value, fields):
"""Tries to translate to the corresponding id a field name maybe
prefixed by "-"
"""
try:
prefix = ""
if isinstance(value, str):
if value.startswith("-"):
value = value[1:]
prefix = "-"
return... |
def merge_bam2xml_cmd(in_bams, out_xml):
"""Merge bam files to xml command """
cmd = 'dataset merge {out_xml} {in_bams}'.format(out_xml=out_xml, in_bams=' '.join(in_bams))
return cmd |
def time_translation(time_string):
"""
This function translates values of 'cookTime' and 'prepTime' ,which are in the string format, into integers
so then we can calculate the difficulty. The function outputs the sum of hours and minutes in the string.
Parameter:
time_string (str): cookTime or... |
def convert_time(old_str):
"""
Function:
convert_time
Description:
Converts a time string from the YYYY-MM-DD HH:MM:SS format to the mm/dd/yy hh:mm am/pm format
Input:
old_str - The string to be converted
Output:
- the converted string
"""
new_str = old_str[5... |
def get_list(item):
"""
Return instance as a list.
"""
return item if isinstance(item, list) else [item] |
def lift_calc(PPV, PRE):
"""
Calculate Lift score.
:param PPV: Positive predictive value (PPV)
:type PPV: float
:param PRE: Prevalence
:type PRE: float
:return: lift score as float
"""
try:
return PPV / PRE
except (ZeroDivisionError, TypeError):
return "None" |
def clean_string(text: str):
"""Replace MS Office Special Characters from a String as well as double whitespace
Args:
text (str):
Returns:
str: Cleaned string
"""
result = ' '.join(text.split())
result = result.replace('\r', '').replace('.', '').replace(
'\n', ' ').repl... |
def svars(Dictionary):
"""Return an exec string to use dvars. That is, the user of this
function should do this:
import functions # This module
d = dict(a=1, b=2, c=3)
exec(functions.svars(d) + 'functions.dvars(d)')
Note there must not be a key in your dictionary called Dictionary.
... |
def find_faces_at_index(layer_qs, coord_val, index):
"""Find all the faces that intersect `coord_val` along `index`
Example
Slice a list of faces along the x-axis so that you can tell
where to fill the shape in, by drawing lines across the polygon.
"""
return [face for face_q in layer_qs for fa... |
def get_otu_lists(data):
"""Returns list of lists of OTUs given data.
- data: list of OTUs in following format:
['seq_1,seq_2,seq_3','seq_4,seq_5','seq_6','seq_7,seq_8']
"""
return [i.split(',') for i in data] |
def list_workers(input_data, workerlimit):
"""
Count number of threads, either length of iterable or provided limit.
:param input_data: Input data, some iterable.
:type input_data: list
:param workerlimit: Maximum number of workers.
:type workerlimit: int
"""
runners = len(input_data) ... |
def guess_interval(nums, accuracy=0):
"""Given a seq of number, return the median, only calculate interval >= accuracy.
Basic Usage::
from torequests.utils import guess_interval
import random
seq = [random.randint(1, 100) for i in range(20)]
print(guess_interval(seq, 5))
... |
def _get_disposable_app_filename(clientInfo):
"""
Get name of file used to store creds.
"""
return clientInfo.get('file', clientInfo['name'] + '.client_data.json') |
def _winpath_to_uri(path):
"""Converts a window absolute path to a file: URL."""
return "///" + path.replace("\\", "/") |
def search_matrix(matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return False
if matrix[0][0] > target or matrix[-1][-1] < target:
return False
row = len(matrix) - 1
col = 0
while... |
def fulfillsHairpinRule(s):
"""
CHECKING FOR THE 3 nt LOOP INTERSPACE
for all kind of basepairs, even wihtin the pdeudoknots
"""
# fulfillsRules = 1
for bracket in ["()", "[]", "{}", "<>"]:
last_opening_char = 0
check = 0
for a in range(len(s)):
if s[a] == br... |
def romanToInt(s):
"""
:type s: str
:rtype: int
"""
c2num_normal = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
c2num_sp = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
def sub_roman2int(s_index, num):
if s_index == len(s):
return num
... |
def replace(line, a, b):
"""
if line starts with string a, then
replace string a with string b in line
"""
mline = line
if line.startswith(a):
mline = line.replace(a,b)
return(mline) |
def _is_bn_diff_doctypes(dyad):
"""Check if a dyad is between two different doctypes.
Args:
dyad (tuple): two-item tuple where each item is a dict which represents a document
Returns:
ind (bool): True if the dyad is between two different doctypes
"""
if dyad[0]["doctype"] != dyad[... |
def construct_address_dict(street: str,
city: str,
state: str,
zipcode: str) -> dict:
"""
Construct an address dict for Seatte, WA specific addresses with provided
*street* and *zipcode*
"""
return ({
'street': ... |
def map_value(x: float, a: float, b: float, c: float, d: float) -> float:
"""Map linearly :math:`x` from math:`[a, b]` to math:`[c, d]`.
The function used is:
.. math::
f : [a, b] & \\to [c, d] \\\\
x & \\mapsto \\frac{x - a}{b - a} * (d - c) + c
Args:
x: Valu... |
def multfloat(a:float,b:float) -> float:
"""
Returns the product of two numbers i.e
a * b without using the '*' multiplication operator
>>> multfloat(5,3)
15.0
"""
return a / (1 / b) |
def remap(degreeinput,degreemin,degreemax,dmxmin=0,dmxmax=65536):
"""
Convert the degree value to a 16 bit dmx number.
"""
DMXvalue = ((degreeinput - degreemin) * (dmxmax-dmxmin) / (degreemax - degreemin) + dmxmin)
return DMXvalue |
def uncommon_cities(my_cities, other_cities):
"""Compare my_cities and other_cities and return the number of different
cities between the two"""
return len(list(set(my_cities) ^ set(other_cities))) |
def sieve(iterable, indicator):
"""Split an iterable into two lists by a boolean indicator function. Unlike
`partition()` in iters.py, this does not clone the iterable twice. Instead,
it run the iterable once and return two lists.
Args:
iterable: iterable of finite items. This function will sca... |
def content_decode(content: bytes) -> str:
"""
decode the target bytes to str \n
:param content: the target bytes
:return: the decode text
:rtype str
"""
return content.decode() |
def count_even(obj):
"""
Return the number of even numbers in obj or sublists of obj
if obj is a list. Otherwise, if obj is a number, return 1
if it is an even number and 0 if it is an odd number.
@param int|list obj: object to count even numbers from
@rtype: int
>>> count_even(3)
0
... |
def _wcut(l, windowsize, stepsize):
"""
Parameters
l - The length of the input array
windowsize - the size of each window of samples
stepsize - the number of samples to move the window each step
Returns
The length the input array should be so that leftover samples are ignore... |
def _rel_approx_equal(x, y, rel=1e-7):
"""Relative test for equality.
Example
>>> _rel_approx_equal(1.23456, 1.23457)
False
>>> _rel_approx_equal(1.2345678, 1.2345679)
True
>>> _rel_approx_equal(0.0, 0.0)
True
>>> _rel_approx_equal(0.0, 0.1)
False
>>> _rel_approx_equal(... |
def incorrectly_encoded_metadata(text):
"""Encode a text that Jupytext cannot parse as a cell metadata"""
return {"incorrectly_encoded_metadata": text} |
def uncgi_headers(environ):
"""A helper to transform a WSGI environment into a list of headers.
:param environ: the WSGI environment
:type environ: dict
:return: headers
:rtype: list(tuple(str, str))
"""
return [
("-".join(p.capitalize() for p in k[5:].split("_")), v)
for ... |
def calc_num_beats(peaks):
"""Calculate the number of beats in ECG recording
Args:
peaks (list[int]): list with indexes of peaks of QRS complexes
Returns:
int: the number of peaks
"""
num_beats = len(peaks)
return num_beats |
def _validate_animation(animation: str) -> bool:
"""Validates that the requested animation is a known, registered Phuey animation. """
if animation in ['vapor', 'cycle-color', 'marquee', 'christmas-wave']:
return True
return False |
def dunder_partition(key):
"""Splits a dunderkey into 2 parts
The first part is everything before the final double underscore
The second part is after the final double underscore
>>> dunder_partition('a__b__c')
>>> ('a__b', 'c')
:param neskey : String
:rtype : 2 Tuple
... |
def get_language(languages, language_id):
"""Retrieve a language from the given language list with the given ID"""
for language in languages:
if language['id'] == language_id:
return language
return None |
def vytvor_pole(pocet_radku, pocet_sloupcu):
"""
vytvori dvojrozmerne pole (matice, seznam v seznamu)
dle zadane sirky a delky a vyplni se kazde mi sto "."
"""
seznam_radku = []
for y in range(pocet_radku):
radek = []
for x in range(pocet_sloupcu):
radek.append(".")
... |
def cover_website(website):
"""
>>> cover_website('https://unilexicon.com/vocabularies/')
'unilexicon…'
"""
www = website.replace('http://', '').replace('https://', '')
return f'{www[:10]}…' |
def filter(dictionary: dict, key) -> dict:
"""
Filter values from a certain dictionary of dictionary.
:param dictionary: The dictionary.
:param key: The key to filter.
:return: The list of filtered values.
"""
result_dict = dict()
for k, v in dictionary.items():
if isinstance(v,... |
def is_complex(x):
"""
If **x** is of type ``complex``, it returns ``True``.
"""
try:
y = complex(x)
except:
return False
return True |
def count_homologies(matches, min_size):
"""Return a dict {(start, end): number_of_homologies_count}.
"""
homologies_counts = {}
if len(matches) == 1:
segment = list(matches.keys())[0]
homologies_counts[segment] = 1
matches_list = sorted(matches.keys())
for i, match1 in enumerate... |
def factor_3d(x):
"""Find 3 factors of a number for splitting volumes for threading.
args:
x: number to be factorised
returns:
tuple of factors
"""
fac = list()
fac.append((1, x))
for i in range(2, x):
if i >= (x / fac[-1][0]):
break
elif x % i ==... |
def get_types(field):
"""
Returns a field's "type" as a list.
:param dict field: the field
:returns: a field's "type"
:rtype: list
"""
if 'type' not in field:
return []
if isinstance(field['type'], str):
return [field['type']]
return field['type'] |
def strip(mydict):
"""{ DocumentFeature('1-GRAM', ('X', 'Y',)) : int} -> {'X Y' : int}"""
return {str(feature): count for feature, count in mydict.items()} |
def is_instance(list_or_dict):
"""Converts dictionary object to list"""
if isinstance(list_or_dict, list):
make_list = list_or_dict
else:
make_list = [list_or_dict]
return make_list |
def parse_cp_counter_output(data):
"""Parse file print_counter data must be a single string, as returned by file.read() (notice the difference
with parse_text_output!) On output, a dictionary with parsed values."""
parsed_data = {}
cardname = 'LAST_SUCCESSFUL_PRINTOUT'
tagname = 'STEP'
numbers =... |
def _fixstring(s):
"""
Fix the string by adding a zero in front if single digit number.
"""
if len(s) == 1:
s = '0' + s
return s |
def set_config(cnf):
"""Singleton access point for global config.
Synchronize this in the future."""
global __config
__config = cnf
return __config |
def box_overlap(row, window):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
window : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bo... |
def error_msg(s):
""" Just making clearer error messages """
return "test_observatory.py: " + s |
def add_sparql_line_nums(sparql):
"""
Returns a sparql query with line numbers prepended
"""
lines = sparql.split("\n")
return "\n".join(["%s %s" % (i + 1, line) for i, line in enumerate(lines)]) |
def format_output(tosave, formatter):
"""
Applies the formatting function, formatter, on tosave.
If the resulting string does not have a newline adds it.
Otherwise returns the formatted string
:param tosave: The item to be string serialized
:param formatter: The formatter function applied to ite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.