content stringlengths 42 6.51k |
|---|
def combine_by_function(iterable, start_val, combine_func):
"""
An approximation of the reduce method.
:param iterable: input list etc.
:param start_val: a starting value
:param combine_func: a function taking two arguments and returning a value.
:return: combined value
"""
count = len(i... |
def get_web2_slack_url(host, service=None, web2_url=""):
"""
Return a Slack formatted hyperlink
Parameters
----------
host: str
host name to use for url. If service is None a hyperlink
to a Icingaweb2 host page will be returned
service : str, optional
service name to use... |
def rotate_2d_list(squares_list):
"""
http://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python
"""
return [x for x in zip(*squares_list[::-1])] |
def validate_periodicity(periodic):
"""Validate method params: periodic.
Periodicity has a differnt validator format
because it can be changed in set_periodicity,
so we only validate it there
"""
# Chek if dict
if not isinstance(periodic, dict):
raise TypeError(
"Periodi... |
def coalesce(*args):
"""Returns the first not None item.
:param args: list of items for checking
:return the first not None item, or None
"""
try:
return next((arg for arg in args if arg is not None))
except StopIteration:
return None |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
next_pos_0 = 0
next_pos_2 = len(input_list) - 1
front_index = 0
while front_index <= next_pos_2:
if inp... |
def parse_torrent_id(arg):
"""Parse an torrent id or torrent hashString."""
torrent_id = None
if isinstance(arg, int):
# handle index
torrent_id = int(arg)
elif isinstance(arg, float):
torrent_id = int(arg)
if torrent_id != arg:
torrent_id = None
elif isin... |
def _compose_args(bloom_fn: str, gfa_fn: str) -> dict:
"""Compose a dict of args with two variables"""
return {
"kmer": 30,
"bloom": bloom_fn,
"bloom_size": "500M",
"levels": 1,
"fasta": "tests/correct/transcript.fa",
"max_fp_bases": 5,
"max_overlap": 10,
... |
def operatingexpenses(taxes, insurance, pmi, managementfee, hoafee):
"""Annual expenses occured through normal cost of business.
:param taxes: Annual taxes.
:type taxes: double
:param insurance: Annual insurance.
:type insurance: double
:param pmi: Annual pmi payment.
:type pmi: double
... |
def intersection(lst1, lst2):
"""
Python program to illustrate the intersection
of two lists using set() method
"""
return list(set(lst1).intersection(lst2)) |
def _fibonacci(n):
"""Fibonacci base function (naive recursive algorithm)
Exponential Time
Args:
n: The nth number of the fibonacci sequence
Returns:
An integer of the nth number in the fibonacci sequence
"""
if n <= 2:
# Base case
f = 1
else:
# Rec... |
def _check_values(in_values):
""" Check if values need to be converted before they get mogrify'd
"""
out_values = []
for value in in_values:
# if isinstance(value, (dict, list)):
# out_values.append(json.dumps(value))
# else:
out_values.append(value)
return tuple... |
def split_on_attribute(index, value, dataset):
"""Separate a given dataset into two lists of rows.
Args:
index: the attribute index
value: the split point of this attribute
dataset: the list of instances the represent the dataset
Returns: A tuple with the lists of instances accordi... |
def get_number_of_reviews(num_review: str) -> int:
"""
>>> get_number_of_reviews('172 reviews')
172
>>> get_number_of_reviews('1,822 reviews')
1822
"""
num_str = num_review.split(' ')[0]
num_str = ''.join([n for n in num_str if n != ','])
return int(num_str) |
def fix_sanitizer_crash_type(crash_type):
"""Ensure that Sanitizer crashes use generic formats."""
# General normalization.
crash_type = crash_type.lower().replace('_', '-').capitalize()
# Use more generic types for certain Sanitizer ones.
crash_type = crash_type.replace('Int-divide-by-zero', 'Divide-by-zero... |
def get_attr_from_base_classes(bases, attrs, attr, default=None):
"""
The attribute is retrieved from the base classes if they are not already
present on the object.
Args:
bases (tuple, list): The base classes for a class.
attrs (dict): The attributes of the class.
attr (str): S... |
def get_tri_category(score):
"""Get a 3 class integer classification label from a score between 0 and 1."""
if score >= 0 and score < 0.3333333333:
return 0
elif score >= 0.3333333333 and score < 0.6666666666:
return 1
else:
return 2 |
def create_headers_for_request(token):
"""Create a header dict to be passed to the api.
:param token: token string coming from the api
:return: a dict containing all the headers for a request
"""
return {
'X-Auth-Token': token,
'Content-Type': 'application/json',
'Accept': '... |
def is_valid_number(val):
""" Validates if the value passed is a number(int/float) or not.
Args:
val (any type): value to be tested
Returns:
bool: True if number else False
"""
return type(val) == int |
def _tuple_or_list(this_identifier, typ):
"""
Turn all lists to tuple/list so this becomes hashable/dcc.storable
"""
opposite = tuple if typ == list else list
out = []
for i in this_identifier:
if isinstance(i, opposite):
i = _tuple_or_list(i, typ)
out.append(typ(... |
def _remove(item, command, replace=""):
""" Remove key, pre, and post words from command string. """
command = " " + command + " "
if replace != "":
replace = " " + replace + " "
for keyword in item["keywords"]:
if item["pre"]:
for pre in item["pre"]:
command ... |
def rank_delta(bcp_47, ot):
"""Return a delta to apply to a BCP 47 tag's rank.
Most OpenType tags have a constant rank, but a few have ranks that
depend on the BCP 47 tag.
Args:
bcp_47(str): A BCP 47 tag.
ot(str): An OpenType tag to.
Returns:
A number to add to ``ot``'s ra... |
def sum_of_factorial_circle_plus_recursion(number: int) -> int:
"""
>>> sum_of_factorial_circle_plus_recursion(0)
0
>>> sum_of_factorial_circle_plus_recursion(1)
1
>>> sum_of_factorial_circle_plus_recursion(2)
3
>>> sum_of_factorial_circle_plus_recursion(5)
153
"""
sum_factor... |
def is_editor(permission):
"""
based on settings.CMS_CONTEXT_PERMISSIONS
given a permission code (int)
returns a dict{} with editor permission info
"""
if not permission > 2: return {}
allow_descendant = True if permission > 4 else False
only_created_by = True if permission == 3 else Fal... |
def count_the_letters(count_words):
"""Find the number of distinct letters."""
letters = {}
for word in count_words.keys():
for letter in word:
letters.setdefault(letter, 0)
letters[letter] += count_words[word]
return len(letters.keys()) |
def _to_numeric(value):
"""Try to convert a string to an integer or a float.
If not possible, returns the initial string.
"""
try:
value = int(value)
except:
try:
value = float(value)
except:
pass
return value |
def _raw_bus_voltage_cnvr(bus_voltage_register):
"""The CNVR bit is set after all conversions, averaging, and multiplications are complete"""
return (bus_voltage_register >> 1) & 0x1 |
def truncate_line(line, max_len):
"""Truncate a string to a given length
@param line String to truncate
@param max_len Length to which to truncate the line
"""
if line.count("\n") > 0:
return "\n".join(map(
lambda x: truncate_line(x, max_len),
line.split("\n")))
... |
def _formatted_hour_min(seconds):
"""Turns |seconds| seconds into %H:%m format.
We don't use to_datetime() or to_timedelta(), because we want to
show hours larger than 23, e.g.: 24h:00m.
"""
time_string = ''
hours = int(seconds / 60 / 60)
minutes = int(seconds / 60) % 60
if hours:
... |
def remove_surrogates(s, errors='replace'):
"""Replace surrogates generated by fsdecode with '?'
"""
return s.encode('utf-8', errors).decode('utf-8') |
def all_factors(num):
""" Return the set of factors of n (including 1 and n).
You may assume n is a positive integer. Do this in one line for extra credit.
Example:
>>> all_factors(24)
{1, 2, 3, 4, 6, 8, 12, 24}
>>> all_factors(5)
{1, 5}
"""
factors = set()
for i in range(1, i... |
def update_parameters_with_gd(parameters, grads, learning_rate):
"""
Update parameters using one step of gradient descent
Arguments:
parameters -- python dictionary containing your parameters to be updated:
parameters['W' + str(l)] = Wl
parameters['b' + str(l)] =... |
def onlywhite(line):
"""Return true if the line does only consist of whitespace characters."""
for c in line:
if c is not ' ' and c is not ' ':
return c is ' '
return line |
def verhoeff_digit(arg):
"""
Implemention of Verhoeff's Dihedral Check Digit based on code from Nick Galbreath
"""
# dihedral addition matrix A + B = a[A][B]
_amatrix = ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(1, 2, 3, 4, 0, 6, 7, 8, 9, 5),
(2, 3, 4, 0, 1, 7, 8, 9, 5, 6),
... |
def get_repeated_elements_in_list(input_list):
"""
Finds repeated elements in a list. Returns a list with the repeated elements.
"""
elem_count = {}
for elem in input_list:
if elem in elem_count:
elem_count[elem] += 1
else:
elem_count[elem] = 1
repeated_... |
def mass_from_radius(r_p):
"""
From Weiss et al. for 1 R_earth < R < 4 R_earth
r_p = radius of planet in earth radii
"""
return 2.69*(r_p)**(0.93) |
def guess_xyz_columns(colnames):
"""
Given column names in a table, return the columns to use for x/y/z, or
None/None/None if no high confidence possibilities.
"""
# Do all the checks in lowercase
colnames_lower = [colname.lower() for colname in colnames]
for x, y, z in [('x', 'y', 'z')]:
... |
def max_of_three_good(x, y, z):
""" (int, int, int) -> int
Computes and returns the maximum of three numeric values
"""
result = x
if y > result:
result = y
if z > result:
result = z
return result |
def parse_cards_from_board(raw):
"""
Returns a list of tuples (word, team, flipped).
"""
out = []
for line in raw.lower().strip().split("\n"):
data = line.strip().split(", ")
out.append((data[0], data[1], "revealed" in data[2]))
return out |
def darpaNodeNet(node_id):
"""Return IP subnet of radio node on DARPA's network."""
return '192.168.{:d}.0'.format(node_id+100) |
def rst_header(text, style=None):
"""Format RST header.
"""
style = style or "-"
return f"{text}\n{style * len(text)}\n\n" |
def regex_match(word, regex, repeat=None):
"""
Given that '.' corresponds to any character, and '*'
corresponds to 0 or more matches of the previous character,
write a function that checks if the pattern matches the input.
"""
if not word and not regex:
return True
if not word:
... |
def anagrams(w):
"""group a list of words into anagrams
:param w: list of strings
:returns: list of lists
:complexity:
:math:`O(n k log k)` in average, for n words of length at most k.
:math:`O(n^2 k log k)` in worst case due to the usage of a dictionary.
"""
w = list(set(w)) ... |
def find_all_indexes(text, pattern, flag = False):
"""Return a list of starting indexes of all occurrences of pattern in text,
or an empty list if not found."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(tex... |
def join_app_version(appname,version,platform):
"""Join an app name, version and platform into a version directory name.
For example, ("app-name","0.1.2","win32") => appname-0.1.2.win32
"""
return "%s-%s.%s" % (appname,version,platform,) |
def map_range(value, in_min, in_max, out_min, out_max):
"""Map Value from one range to another."""
return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min |
def filter_start_bids_by_bidder_id(bids, bidder):
"""
"""
return [bid for bid in bids
if bid['bidders'][0]['id']['name'] == bidder] |
def isBetween(x, a, b):
"""
Check if x is between a and b.
:param x: x.
:param a: a.
:param b: b.
:return: True or False.
"""
if x > min(a,b) and x < max(a,b):
return True
return False |
def point_distance_l1(hook_pos: tuple, fish_pos: tuple) -> float:
"""
Distance between two 2-d points using the Manhattan distance.
:param tuple hook_pos: (x,y) coordinates of first point
:param tuple fish_pos: (x,y) coordinates of first point
:return: distance as a float object
"""
return m... |
def apply_opcode3(code_list, opcode_loc, programme_input=1):
"""When you've determined that the opcode is 3 - which means to take an
input value and store it in the location of its only parameter then you can
use this function to
adjust code_list.
Parameters
----------
code_list : list
... |
def temp_or_none(t):
"""Return the supplied temperature as a string in the format
"%5.1f" or a hyphen, if unavailable (None).
"""
if t is None:
return " -"
return "%5.1f" % t |
def mean(data):
"""Return the mean of a sequence of numbers."""
return sum(data) / len(data) |
def bbox_filter ( wkt_string, lonmin, latmin, lonmax, latmax ):
"""
Return a string that will select records from the geographic range
given in WKT. If four bounding coordinates are given instead, a
POLYGON() is constructed from them.
"""
if wkt_string:
return {'loc': wkt_string}
... |
def uncap_it(x):
"""Match capitalization format"""
if "-" in str(x):
temp = str(x).split("-")
tt = ""
for t in temp:
tt = tt + "-" + t.capitalize()
return tt[1:]
else:
temp = str(x).split()
tt = ""
for t in temp:
tt = tt + " "... |
def _get_rate_limit_wait(log, resp, opts):
"""
Returns the number of seconds we should wait given a 429 HTTP response and
HTTP options.
"""
max_wait = 3600
wait = opts['wait']
header_name = opts['rate_limit_reset_header_name']
if header_name and header_name in resp.headers:
hea... |
def get_lagrange(atom, lagrange=None):
"""
Return appropriate `lagrange` parameter.
"""
if lagrange is None:
lagrange = atom.lagrange
if lagrange is None:
raise ValueError('either atom must be in Lagrange '
+ 'mode or a keyword "lagrange" '
... |
def get_layer_spdxref_snapshot(timestamp):
"""Given the layer object created at container build time, return an
SPDX reference ID. For this case, a layer's diff_id and filesystem hash
is not known so we will provide a generic ID"""
return 'SPDXRef-snapshot-{}'.format(timestamp) |
def GetMSBIndex(n):
"""
Getting most significiant bit
"""
ndx = 0
while 1 < n:
n = (n >> 1)
ndx += 1
return ndx |
def process(document, rtype=None, api=None):
""" Detects subjectivity in given batch of texts. """
""" Extracts subjectivity value from given texterra-annotated text. """
return bool(document['annotations']) |
def fix_keys(fix_func, conf):
"""Apply fix_func on every key of key value iterable"""
return [(fix_func(field), value) for field, value in conf] |
def get_job_url(config, hub, group, project):
"""
Util method to get job url
"""
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if ((config is not None) and ('group' in config) and (group is None)):
group = config["group"]
if ((config is no... |
def kataSlugToKataClass(kataSlug):
"""Tranform a kata slug to a camel case kata class"""
pascalCase = ''.join(x for x in kataSlug.title() if not x == '-')
# Java don't accept digits as the first char of a class name
return f"Kata{pascalCase}" if pascalCase[0].isdigit() else pascalCase |
def charset_to_encoding(name):
"""Convert MySQL's charset name to Python's codec name"""
if name in ('utf8mb4', 'utf8mb3'):
return 'utf8'
return name |
def rotate_string(string, offset):
"""
Rotate string in place
:param string: given array of characters
:type string: list[str]
:param offset: offset for rotation
:type offset: int
:return: list[str]
:rtype: rotated string
"""
if len(string) == 0 or offset == 0:
return st... |
def inconsistent_typical_range_stations(stations):
""" This returns a list of stations that are not consistent from an input list of stations"""
# iterates through stations, and returns a list of those which are inconsistent
return [ i for i in stations if i.typical_range_consistent() == False ] |
def parse_argv(argv):
"""A very simple argv parser. Returns a list of (opts, args) for options
and arguments in the passed argv. It won't try to validate anything.
"""
opts = []
args = []
for arg in argv:
if arg.startswith('-'):
parts = arg.split('=', 1)
if len(pa... |
def merge_dicts(list_of_dicts):
"""
Merge multipe dictionaries together.
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
Args:
dict_args (list): a list of dictionaries.
Returns:
dictionary
"""
merge_d... |
def rpm_to_hz(rpm):
"""
RPM to Hertz Converter.
Given the angular velocity in RPM (Revolutions-Per-Minute), this function
will evaluate the velocity in Hertz.
Parameters
----------
rpm: float
The angular velocity in revolutions-per-minute (RPM)
Returns
-----... |
def lcfirst(s):
"""Return a copy of string s with its first letter converted to lower case.
>>> lcfirst("Mother said there'd be days like these")
"mother said there'd be days like these"
>>> lcfirst("Come on, Eileen")
'come on, Eileen'
"""
return s[0].lower()+s[1:] |
def get_total_slice_size(op_slice_sizes, index, slice_count):
"""Returns total size of a sublist of slices.
Args:
op_slice_sizes: List of integer slice sizes.
index: Integer index specifying the start of the sublist.
slice_count: Integer number of slices to include in the total size.
Returns:
In... |
def check_block_name(block_name):
"""
Check whether a block_name has been rename
"""
if block_name.endswith('_2'):
block_name = block_name[:-2]
return block_name |
def jet_finding(R: float = 0.2) -> str:
""" The jet finding label.
Args:
R: The jet finding radius. Default: 0.2
Returns:
A properly latex formatted jet finding label.
"""
return r"$\mathrm{anti \textendash} k_{\mathrm{T}}\;R=%(R)s$" % {"R": R} |
def get_window_indexes(data_length, window_size, step_size):
"""
This function returns the indexes from which the training samples will start (it doesn't return the sequences
themselves yet, because we want to save some memory)requested cell's configuration.
Input:
data_leng... |
def _client_ip(client):
"""Compatibility layer for Flask<0.12."""
return getattr(client, 'environ_base', {}).get('REMOTE_ADDR') |
def query_sort(resources, arguments):
"""Return the resources sorted
Args:
resources(list): List to sort
arguments(FormsDict): query arguments
Returns:
list: Sorted resource (asc or desc)
"""
if '_sort' not in arguments:
return resources
sort = arguments['_sor... |
def reverse(x):
"""
:type x: int
:rtype: int
"""
sum = 0
negative = False
if x < 0:
x = -x
negative = True
while x:
sum = sum * 10 + x%10
x /= 10
if sum > ((1<<31) - 1): return 0
return -sum if negative else sum |
def eq_up_to_order(A, B):
"""
If A and B are lists of four-tuples ``[a0,a1,a2,a3]`` and ``[b0,b1,b2,b3]``,
checks that there is some reordering so that either ``ai=bi`` for all ``i`` or
``a0==b1``, ``a1==b0``, ``a2==b3``, ``a3==b2``.
The entries must be hashable.
EXAMPLES::
sage: from... |
def gen_caption_from_classes(class_names, templates):
"""
Given a list of class names, return a list of template augmented captions,
and the class_idx of these captions.
captions: A list of strings describing each class
labels_list: A list of ints representing the class index
"""
captions = ... |
def get_entities_lookup(entities):
"""From a list of entities gives back a dictionary that maps the value to the index in the original list"""
entities_lookup = {}
for index, value in enumerate(entities):
entities_lookup[value] = index
return entities_lookup |
def readFile(file: str) -> str:
"""
read a file
"""
f = open(file, "r")
content = f.read()
f.close()
return content |
def export_users(ucm_axl):
"""
retrieve users from ucm
"""
try:
user_list = ucm_axl.get_users(
tagfilter={
"userid": "",
"firstName": "",
"lastName": "",
"directoryUri": "",
"telephoneNumber": "",
... |
def add_newlines(string):
"""
:param string:
:return:
"""
return f'\n{string}\n\n' |
def OK_No(value, collection):
""" True -> "OK", green background ; False->"No",red, None to "-",no color """
if value:
return ("OK", "black; background-color:green;")
if value == None:
return ("-", "black")
return ("No", "black; background-color:red;") |
def eval_string(input_string, locals):
"""Dynamically evaluates the input_string expression.
This provides dynamic python eval of an input expression. The return is
whatever the result of the expression is.
Use with caution: since input_string executes any arbitrary code object,
the potential for ... |
def lat_lon_region(lower_left_corner_latitude,
lower_left_corner_longitude,
upper_right_corner_latitude,
upper_right_corner_longitude):
"""
Converts a geographical region with lower left corner
and upper right corner into a Basemap compatible structure.
:param lower_lef... |
def get_fresh_col(used_columns, n=1):
"""get a fresh column name used in pandas evaluation"""
names = []
for i in range(0, 1000):
if "COL_{}".format(i) not in used_columns:
names.append("COL_{}".format(i))
if len(names) >= n:
break
return names |
def isvalid(gridstr, x, y, test_value):
""" Check if it would be legal to place a in pos x,y """
sq_indexes = ((0, 1, 2), (3, 4, 5), (6, 7, 8))
group_indexes = [(x_ind, y_ind)
for x_ind in sq_indexes[x // 3]
for y_ind in sq_indexes[y // 3]]
for index in range(9... |
def decorate_string_for_latex(string):
"""
decorate strings for latex
"""
if string is None:
decorated_string = ''
elif string == 'GAMMA':
decorated_string = "$" + string.replace("GAMMA", r"\Gamma") + "$"
elif string == 'SIGMA':
decorated_string = "$" + string.replace("SI... |
def _clear_dash(s):
"""Returns s if it is not '-', otherwise returns ''."""
return s if s != '-' else '' |
def mult_option(a, b):
""" Multiply even if any arg is None """
return a * b if a is not None and b is not None else a if a is not None else b |
def is_friends_with(user1, user2):
"""
Returns whether user1 and user2 are friends or not.
:param user1: An User instance.
:param user2: An User instance.
"""
if not user1 or not user2 or user1.is_anonymous() or user2.is_anonymous():
return False
return user1.friend_of(user2) |
def getstoreprice(item, storeprices):
"""Get store price of item"""
index = item['defindex']
return ('{:.2f}'.format(storeprices[index]['prices']['USD'] / 100.00)
if index in storeprices else '') |
def is_palindrome(s: str) -> bool:
"""Return True if input string is palindrome."""
return s == s[::-1] |
def dlog(num, base=2):
"""Returns the discrete logarithm of num.
For the standard base 2, this is the number of bits required to store the range 0..num."""
return [n for n in range(32) if num < base**n][0] |
def audio_len(audio):
"""
>>> audio_len([1, 4, 2, 5, 3, 6])
3
"""
assert len(audio) % 2 == 0
return len(audio) // 2 |
def cast_to_bool(string):
"""
Cast string value to boolean or return None if the string is not convertible to int.
:param string: string
:return: boolean or None if string is None
"""
if string is None:
return None
values = {"true": True,
"false": False,
... |
def integer(number, *args):
"""In Python 3 int() is broken.
>>> int(bytearray(b'1_0'))
Traceback (most recent call last):
...
ValueError:
"""
num = int(number, *args)
if isinstance(number, str) and '_' in number or isinstance(number, (bytes, bytearray)) and b' ' in number:
raise ValueError()
return num |
def yaml_diagnostic(name='${diag_name}',
message='${message}',
file_path='/tidy/file.c',
file_offset=1,
replacements=(),
notes=()):
"""Creates a diagnostic serializable as YAML with reasonable defaults."""
result = {... |
def get_list(key, row):
"""Reads a comma-separated list from a row (interpreted as strings)."""
if key in row and row[key]:
return [i.strip() for i in row[key].split(',') if i.strip()]
else:
return None |
def nb(i: int, length=False) -> bytes:
"""converts integer to bytes"""
b = b""
if length == False:
length = (i.bit_length() + 7) // 8
for _ in range(length):
b = bytes([i & 0xFF]) + b
i >>= 8
return b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.