content stringlengths 42 6.51k |
|---|
def prime_factors(n):
""" Return the prime factors of the given number. """
# < 1 is a special case
if n <= 1:
return [1]
factors = []
lastresult = n
while True:
if lastresult == 1:
break
c = 2
while True:
if lastresult % c == 0:
break
c += 1
factors.append(c)
lastresult /= c
return fact... |
def make_header(in_files,args):
"""Make sam header given input file species and"""
#parse input barcode file and make list of individuals
in_files['header'] = 'location of header'
return in_files |
def _validate_print_table(tuple_list: list, col_headers: tuple) -> int:
"""Validate arguments on behalf of _print_table() and returns number of columns."""
# LOCAL VARIABLES
num_columns = 0 # Number of columns detected
# INPUT VALIDATION
# tuple_list
if not isinstance(tuple_list, list):
... |
def make_dices(tup):
"""Make a string with comma separated dice values from tuple.
From a given tuple, dice values are written in a string separated by
','
Arguments:
tup: (tuple) Tuple with dice values
Returns:
string: (str) string with dice values separated by comma
... |
def value_approximation(value_a: float, value_b: float, value_threshold: float) -> bool:
"""Compare two numbers to check if they are roughly the same.
Args:
value_a (float): First number.
value_b (float): Second number.
value_threshold (float): Approximation threshold.
Returns:
... |
def ring_level(num):
"""Return the side lenth, level, and max value of a spiral ring of consecutive ints"""
max_value = 1
level = 0
side_len = 1
while max_value < num:
level = level + 1
side_len = (level * 2) + 1
max_value = side_len + side_len * (side_len - 1)
return sid... |
def count_restricted_partitions(n, m, l):
"""
Returns the number of partitions of n into m or less parts
"""
if n == 0:
return 1
elif l == 0:
return 0
elif m == 0:
return 0
return sum(count_restricted_partitions(n - i, m - 1, i)
for i in range(1, min(n... |
def _get_column_property_display_data(row, col_str, data):
"""
This function is used to get the columns data.
:param row:
:param col_str:
:param data:
:return:
"""
if row['collnspname']:
col_str += ' COLLATE ' + row['collnspname']
if row['opcname']:
col_str += ' ' + r... |
def split_string(x, separator=' '):
"""
Quick function to tidy up lines in an ASCII file (split on spaces and strip consecutive spaces).
Parameters
----------
x : str
String to split.
separator : str, optional
Give a separator to split on. Defaults to space.
Returns
---... |
def prior(theta, parameter_intervals):
""" Very simple prior estimator only for MH as it checks if the parametrisation is inside of respective domain or not.
This simulates uniform distribution.
Args:
theta: (tuple): parameter point
parameter_intervals (list of pairs): parameter domains,... |
def get_channel_for_utt(flist, ch, utt):
""" Returns a specific channel for one utterance.
Raises a KeyError if the channel does not exist
:param flist: A dict representing a file list, i.e. the keys are the utt ids
:param ch: The channel to fetch (i.e. X/CH1). Separator must be `/`
:param utt: Th... |
def jwt_response_payload_handler(token, user=None, request=None):
""" Custom response payload handler.
This function controlls the custom payload after login or token refresh. This data is returned through the web API.
"""
return {
'token': token,
} |
def turn_list_to_int(list_):
"""converts elements of a list to integer"""
list_ = [int(i) for i in list_]
return list_ |
def list_to_dict(items, value):
"""
Converts a list into a dict.
"""
key = items.pop()
result = {}
bracket_index = key.find('[')
if bracket_index > 0:
value = [value]
result[key] = value
if items:
result = list_to_dict(items, result)
return result |
def get_user_parameters_string(data):
"""Returns the UserParameters string in a given data object.
:type data: dict
:param data: data object in a CodePipeline event.
:rtype: dict
:return: UserParameters string in ``data``.
:raises KeyError: if ``data`` does not have a necessary property.
... |
def check_constraints(param_constraints):
"""Checks whether user provided list specifying which parameters
are to be free versus fixed is in proper format, and assigns
default values where necessary.
Keyword arguments:
param_constraints -- specifies which parameters to estimate (list)
"""
... |
def objective(s, s_min=100):
"""
minimum is reached at s=s_min
"""
return -0.5 * ((s - s_min) ** 2) |
def random_morphing_points(n_thetas, priors):
"""
Utility function to be used as input to various SampleAugmenter functions, specifying random parameter points
sampled from a prior in a morphing setup.
Parameters
----------
n_thetas : int
Number of parameter points to be sampled
pr... |
def _field_index(header, field_names, index):
"""Determine a field index.
If the index passed is already a valid index, that index is returned.
Otherwise, the header is searched for a field name matching any of
the passed field names, and the index of the first one found is
returned.
If no mat... |
def _get_deconv_pad_outpad(deconv_kernel):
"""Get padding and out padding for deconv layers."""
if deconv_kernel == 4:
padding = 1
output_padding = 0
elif deconv_kernel == 3:
padding = 1
output_padding = 1
elif deconv_kernel == 2:
padding = 0
output_paddin... |
def to_readable_dept_name(dept_name):
"""Converts a department acronym into the full name
Arguments:
dept_name {String} -- The department acronym
Returns:
String -- The department's full name
"""
depts = ['TWS', 'BIOL', 'RSM', 'MUS', 'COMM', 'ECON', 'CHIN', 'NENG', 'CGS', '... |
def np_bitwise_maj (x, y, z):
""" Bitwise MAJ function """
return (x & y) | (x & z) | (y & z) |
def is_prime(n):
"""
Return True if the given integer is prime, False
otherwise.
>>> is_prime(1)
False
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(9)
False
>>> is_prime(10)
False
"""
if n < 2:
return False
... |
def _extract_conflict_packages(license_service_output):
"""Extract conflict licenses.
This helper function extracts conflict licenses from the given output
of license analysis REST service.
It returns a list of pairs of packages whose licenses are in conflict.
Note that this information is only av... |
def job_ids(log_stream):
"""Grep out all lines with scancel example."""
id_rows = [line for line in log_stream if 'scancel' in line]
jobs = [id_row.strip()[-7:-1] for id_row in id_rows]
return jobs |
def _fix_name(name):
"""Clean up descriptive names"""
return name.strip('_ ') |
def to_locale(language, to_lower=False):
"""
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
True, the last component is lower-cased (en_us).
"""
p = language.find('-')
if p >= 0:
if to_lower:
return language[:p].lower() + '_' + language[p + 1:].low... |
def comma_list_to_hex(cpus):
"""
Converts a list of cpu cores in corresponding hex value
of cpu-mask
"""
cpu_arr = cpus.split(",")
binary_mask = 0
for cpu in cpu_arr:
binary_mask = binary_mask | (1 << int(cpu))
return format(binary_mask, '02x') |
def _format_stages_summary(stage_results):
"""
stage_results (list of (tuples of
(success:boolean, stage_name:string, status_msg:string)))
returns a string of a report, one line per stage.
Something like:
Stage: <stage x> :: SUCCESS
Stage: <stage y> :: FAILED
Stage: <s... |
def str2tuple(string, sep=","):
"""
Map "1.0,2,0" => (1.0, 2.0)
"""
tokens = string.split(sep)
# if len(tokens) == 1:
# raise ValueError("Get only one token by " +
# f"sep={sep}, string={string}")
floats = map(float, tokens)
return tuple(floats) |
def is_sane_slack_webhook(url):
"""Really basic sanity checking."""
if url is None:
return False
return "https://hooks.slack.com/" in url.strip() |
def is_cybox(entity):
"""Returns true if `entity` is a Cybox object"""
try:
return entity.__module__.startswith("cybox.")
except AttributeError:
return False |
def is_pal(test):
"""
Returns bool of whether test is a palindrome.
Does so iteratively
"""
# Reverse the test
reverse_test = test[::-1]
# Loop through to test test against reverse
for i in range(len(test)):
if test[i] != reverse_test[i]:
return False
return Tru... |
def solution(n):
"""Returns the largest palindrome made from the product of two 3-digit
numbers which is less than n.
>>> solution(20000)
19591
>>> solution(30000)
29992
>>> solution(40000)
39893
"""
answer = 0
for i in range(999, 99, -1): # 3 digit nimbers range from 999 d... |
def processObjectListWildcards(objectList, suffixList, myId):
"""Replaces all * wildcards with n copies that each have appended one element from the provided suffixList and replaces %id wildcards with myId
ex: objectList = [a, b, c_3, d_*, e_%id], suffixList=['0', '1', '2'], myId=5 => objectList = [a, b, c_3, e... |
def _validate_manifest_upload(expected_objs, upload_results):
"""
Given a list of expected object names and a list of dictionaries of
`SwiftPath.upload` results, verify that all expected objects are in
the upload results.
"""
uploaded_objs = {
r['object']
for r in upload_results
... |
def int_convert_to_minute(value):
"""Convert value into min & sec
>>> int_convert_to_minute(123)
'02:03'
"""
min = int(int(value) / 60)
sec = int(int(value) % 60)
return "%02d" % min + ":" + "%02d" % sec |
def empty_1d_array(size, fill_default=None):
"""
Create and return 1-D array
:param size:
:param fill_default: Default value to be filled in cells.
:return:
"""
return [fill_default] * size |
def get_color(score: float) -> str:
"""Return a colour reference from a pylint score"""
colors = {
"brightgreen": "#4c1",
"green": "#97CA00",
"yellow": "#dfb317",
"yellowgreen": "#a4a61d",
"orange": "#fe7d37",
"red": "#e05d44",
"bloodred": "#ff0000",
... |
def create_dict(entities):
"""Create the html5 dict from the decoded json object."""
new_html5 = {}
for name, value in entities.items():
new_html5[name.lstrip('&')] = value['characters']
return new_html5 |
def only_alpha(tokens):
"""
Exclude non-alphanumeric tokens from a list of tokens
"""
tokens = [token for token in tokens if token.isalpha()]
return tokens |
def map_quads(coord):
"""
Map a quadrant number to Moran's I designation
HH=1, LH=2, LL=3, HL=4
Input:
@param coord (int): quadrant of a specific measurement
Output:
classification (one of 'HH', 'LH', 'LL', or 'HL')
"""
if coord == 1:
return 'HH'
... |
def try_parse_int(candidate):
"""
Convert the given candidate to int. If it fails None is returned.
Example:
>>> type(try_parse_int(1)) # int will still be int
<class 'int'>
>>> type(try_parse_int("15"))
<class 'int'>
>>> print(try_parse_int("a"))
None
... |
def generate_label_asm(label, address):
"""
Return label definition text at a given address.
Format: '{label}: ; {address}'
"""
label_text = '%s: ; %x' % (label, address)
return (address, label_text, address) |
def suffix_replace(original, old, new):
"""
Replaces the old suffix of the original string by a new suffix
"""
return original[:-len(old)] + new |
def cleanup_code(content: str) -> str:
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith("```") and content.endswith("```"):
return "\n".join(content.split("\n")[1:-1])
# remove `foo`
return content.strip("` \n") |
def quote_string(prop):
"""Wrap given prop with quotes in case prop is a string.
RedisGraph strings must be quoted.
"""
if not isinstance(prop, str):
return prop
if prop[0] != '"':
prop = '"' + prop
if prop[-1] != '"':
prop = prop + '"'
return prop |
def _iszero(x):
"""Returns True if x is zero."""
return getattr(x, 'is_zero', None) |
def int_to_bytes(x):
"""Changes an unsigned integer into bytes."""
return x.to_bytes((x.bit_length() + 7) // 8, 'big') |
def process_entries(entries):
"""
Ignore empty lines, comments and editable requirements
:param list entries: List of entries
:returns: mapping from a project to its version specifier
:rtype: dict
"""
data = {}
for e in entries:
e = e.strip()
if e and not e.startswith('... |
def create_result(flags):
"""
Create the correct return value for YCM.
:param flags: The flags for the requested file.
:type flags: list[str]
:rtype: dict[str,object]
:return: A dictionary in the format wanted by YCM.
"""
return {"flags": flags} |
def is_parans_exp(istr):
"""
Determines if an expression is a valid function "call"
"""
fxn = istr.split('(')[0]
if (not fxn.isalnum() and fxn != '(') or istr[-1] != ')':
return False
plevel = 1
for c in '('.join(istr[:-1].split('(')[1:]):
if c == '(':
plevel += 1... |
def parsed_length(line: str) -> int:
"""The length of the string after evaluating."""
return len(eval(line)) |
def findMinWidth(list):
"""
Finds and returns the length of the longest string in list
Parameter: (list) containing strings
Return: (int) length of longest string in list
"""
longest = ""
for item in list:
item = str(item) # Can't use len() on int
if len(longest) < len(item):... |
def _bytearray_comparator(a, b):
"""Implements a comparator using the lexicographical ordering of octets as unsigned integers."""
a_len = len(a)
b_len = len(b)
i = 0
while i < a_len and i < b_len:
a_byte = a[i]
b_byte = b[i]
if a_byte != b_byte:
if a_byte - b_byte... |
def split_data(line):
"""
Split each line into columns
"""
data = str.split(line, ',')
return [data[0], data[1]] |
def count_possibilities(dic):
"""
Counts how many unique names can be created from the
combinations of each lists contained in the passed dictionary.
"""
total = 1
for key, value in dic.items():
total *= len(value)
return total |
def parse_addr(addrstr):
"""
parse 64 or 32-bit address from string into int
"""
if addrstr.startswith('??'):
return 0
return int(addrstr.replace('`', ''), 16) |
def nacacode4(tau, maxthickpt, camb):
"""Converts airfoil parameters to 4-digit naca code
:param tau: maximum thickness as percent of chord
:type tau: float
:param maxthickpt: Location of maximum thickness as percent of chord
:type maxthickpt: float
:param camb: max camber as a percentage of ch... |
def _levenshtein_compute(source, target, rd_flag):
"""Computes the Levenshtein
(https://en.wikipedia.org/wiki/Levenshtein_distance)
and restricted Damerau-Levenshtein
(https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance)
distances between two Unicode strings with given lengths using t... |
def img_pred(path):
"""Sends a path to an image to the classifier, should return a
JSON object."""
if path == "https://michelangelostestbucket.s3.us-west-2.amazonaws.com/8bf0322348cc11e7e3cc98325fbfcaa1":
result = "{'frogs' : '3'}"
else:
result = {'sharks': '17'}
return result |
def _generate_mark_code(rule_name):
"""Generates a two digit string based on a provided string
Args:
rule_name (str): A configured rule name 'pytest_mark3'.
Returns:
str: A two digit code based on the provided string '03'
"""
code = ''.join([i for i in str(rule_name) if i.isdigit()... |
def getObjName(objID, objList):
"""
Returns an object's name (str) given its 'objID' (int) and a reference 'objList' (list)
Format of 'objList' is [['name_1', id_1], ['name_2', id_2], ...]
"""
for i in range(0, len(objList)):
if objList[i][1] == objID:
return objList[i][0] |
def get_tile_prefix(rasterFileName):
"""
Returns 'rump' of raster file name, to be used as prefix for tile files.
rasterFileName is <date>_<time>_<sat. ID>_<product type>_<asset type>.tif(f)
where asset type can be any of ["AnalyticMS","AnalyticMS_SR","Visual","newVisual"]
The rump is defined as <da... |
def stream_name_to_dict(stream_name, separator='-'):
"""Transform stream name string to dictionary"""
catalog_name = None
schema_name = None
table_name = stream_name
# Schema and table name can be derived from stream if it's in <schema_nama>-<table_name> format
s_parts = stream_name.split(separ... |
def get_audio_samplerate(samplerate):
"""
Get audio sample rate into a human easy readable format.
Arguments:
:param samplerate: integer
:return: string
"""
return "%s kHz" %(samplerate) |
def overlap(start1: float, end1: float, start2: float, end2: float) -> float:
"""how much does the range (start1, end1) overlap with (start2, end2)
Looks strange, but algorithm is tight and tested.
Args:
start1: start of interval 1, in any unit
end1: end of interval 1
start2: start ... |
def convert_bytes(num, suffix='B'):
"""Convert bytes int to int in aggregate units"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix) |
def configure(args):
"""Use default hyperparameters.
Parameters
----------
args : dict
Old configuration
Returns
-------
args : dict
Updated configuration
"""
configure = {
'node_hidden_size': 128,
'num_propagation_rounds': 2,
'lr': 1e-4,
... |
def _get_main_is_module(main_is):
"""Parses the module name from a "main_is" attribute.
The attribute may be either Foo.Bar or Foo.Bar.baz.
Args:
main_is: A string, the main_is attribute
Returns:
A string, a valid Haskell module name.
"""
components = main_is.split(".")
if com... |
def digital_method(coefficients, val, add, mul, act, power, zero, one):
"""
Evaluate a univariate polynomial at val.
The polynomial is given as an iterator 'coefficients' which yields
(degree, coefficient) pair in descending order of degree.
If the polynomial is of R-coefficients, then val should ... |
def check_anagrams(first_str: str, second_str: str) -> bool:
"""
Two strings are anagrams if they are made of the same letters
arranged differently (ignoring the case).
>>> check_anagrams('Silent', 'Listen')
True
>>> check_anagrams('This is a string', 'Is this a string')
True
>>> check_a... |
def _noaa_names(i):
"""Return set of possible NOAA names for sat number
- lower or UPPER case
- zero-padded number or not (noaa7, noaa07)
- with or without dash (noaa-14, noaa14)
- long (noaa) or short (n)
Does not include pre-launch names.
Arguments:
i [int]: Number of NOAA sate... |
def post_details(post):
"""
Displays info about a post: title, date, feed and tags.
"""
return {"post": post} |
def cleanup_social_account(backend, uid, user=None, *args, **kwargs):
"""
3rd party: python-social-auth.
Social auth pipeline to cleanup the user's data. Must be placed after 'social_core.pipeline.user.create_user'.
"""
if user and kwargs.get('is_new', False):
user.first_name = kwargs['deta... |
def data_process(input_string):
"""
This is where all the processing happens.
Let's just read the string backwards
"""
output = input_string
return output
# Test
# return input_string |
def extract_scalar_reward(value, scalar_key='default'):
"""
Extract scalar reward from trial result.
Raises
------
RuntimeError
Incorrect final result: the final result should be float/int,
or a dict which has a key named "default" whose value is float/int.
"""
if isinstance... |
def fraction_str(numerator, denominator) -> str:
"""
Formats a fraction to the format %.5f [numerator/deniminator]
:param numerator:
:param denominator:
:return: Formatted string
"""
if denominator > 0:
return "%.5f [%.5f/%d]" % (float(numerator)/denominator, numerator, denominator)
... |
def datesuffix(n):
"""Given day of month return English Ordinal Suffix"""
if (n == 1 or n == 21 or n == 31):
suffix = "st"
elif (n == 2 or n == 22):
suffix = "nd"
elif (n == 3 or n == 23):
suffix = "rd"
else:
suffix = "th"
return suffix |
def get_key_from_value(haystack: dict, needle: str):
"""
Returns a dict key by it's value, ie get_key_from_value({key: value}, value) returns key
"""
return next((k for k, v in haystack.items() if v == needle), None) |
def build_aggregation(facet_name, facet_options, min_doc_count=0):
"""Specify an elasticsearch aggregation from schema facet configuration.
"""
exclude = []
if facet_name == 'type':
field = 'embedded.@type.raw'
exclude = ['Item']
elif facet_name.startswith('audit'):
field = f... |
def clean_paths(url):
"""Translate urls into human-readable filenames."""
to_remove = ['http://', 'https://', 'www.', '.com', '.json', '.']
for item in to_remove:
url = url.replace(item, '')
return url.replace('/', '_') |
def unique(L1, L2):
"""Return a list containing all items in 'L1' that are not in 'L2'"""
L2 = dict([(k, None) for k in L2])
return [item for item in L1 if item not in L2] |
def transform_file_output(result):
""" Transform to convert SDK file/dir list output to something that
more clearly distinguishes between files and directories. """
from collections import OrderedDict
new_result = []
iterable = result if isinstance(result, list) else result.get('items', result)
... |
def _split_up_multiple_entries(entry):
"""Split up lists of entries that have been recorded as a single string."""
split_types = ['<br>', '<br/>', '<br />']
for split_type in split_types:
if split_type in entry:
return entry.split(split_type)
return [entry] |
def YDbDrtoYUV(Y, Db, Dr):
""" convert RGB to YUV color
:param Y: Y value (0;1)
:param Db: Db value (-1.333-1.333)
:param Dr: Dr value (-1.333-1.333)
:return: YUV (PAL) tuple (Y0;1 U-0.436-0.436 V-0.615-0.615) """
U = Db / 3.059
V = Dr / -2.169
return Y, U, V |
def triwhite(x, y):
""" Convert x,y chromaticity coordinates to XYZ tristimulus values.
"""
X = x / y
Y = 1.0
Z = (1-x-y)/y
return [X, Y, Z] |
def hypot(a):
# type: (tuple) -> float
"""Returns the hypotenuse of point."""
return (a[0] ** 2) + (a[1] ** 2) |
def did_commands_succeed(report):
""" Returns true if all the commands succeed"""
for com in report['command_set']:
if com['result']['status'] != 0:
return False
return True |
def adjustEdges(height, width, point):
"""
This handles the edge cases if the box's bounds are outside the image range based on current pixel.
:param height: Height of the image.
:param width: Width of the image.
:param point: The current point.
:return:
"""
newPoint = [point[0], point[1... |
def get_query_params(query):
"""
Extract (key, value) pairs from the given GET / POST query. Pairs
can be split by '&' or ';'.
"""
params = {}
if query:
delim = "&"
if "&" not in query and ";" in query:
delim = ";"
for k_v in query.split(delim):
k,... |
def piece_size(file_size):
"""
Based on the size of the file, we decide the size of the pieces.
:param file_size: represents size of the file in MB.
"""
# print 'Size {0} MB'.format(file_size)
if file_size >= 1000: # more than 1 gb
return 2 ** 19
elif file_size >= 500 and file_size ... |
def remove_digits(name: str) -> str:
""" "O1" -> "O" """
return ''.join([i for i in name if not i.isdigit()]) |
def fname_to_code(fname: str):
"""file name to stock code
Parameters
----------
fname: str
"""
prefix = "_qlib_"
if fname.startswith(prefix):
fname = fname.lstrip(prefix)
return fname |
def unencrypted_ami_volume(rec):
"""
author: airbnb_csirt
description: Identifies creation of an AMI with a non encrypted volume
reference: https://amzn.to/2rQilUn
playbook: (a) Reach out to the user who created the volume
(b) Re-create the AMI with encryption enabled... |
def verify_policy_map_row_added(table, parameter_name, parameter_value):
"""Add row to Table
Args:
table (`obj`): Table object
parameter_name (`str`): Parameter name
parameter_value (`str`): Parameter value
Returns:
True
False
"""
... |
def unsigned_leb128_decode(data) -> int:
"""Read variable length encoded 128 bits unsigned integer
.. doctest::
>>> from ppci.utils.leb128 import unsigned_leb128_decode
>>> signed_leb128_decode(iter(bytes([0xe5, 0x8e, 0x26])))
624485
"""
result = 0
shift = 0
while True:... |
def get_unique_user_lexeme(data_dict):
"""Get all unique (user, lexeme) pairs."""
pairs = set()
for u_id in data_dict.keys():
pairs.update([(u_id, x) for x in data_dict[u_id].keys()])
return sorted(pairs) |
def get_screen_name_to_player(players_dict):
"""Based on player-account assigments this function returns 'screen_name' -> schedule player name mapping."""
screen_name_to_player = {}
for player in players_dict:
for screen_name in players_dict[player]:
if screen_name in screen_name_to_play... |
def PreProcessScore(s):
""" Remove all the | and the || """
s = s.replace("|", " ")
s = s.replace(" ", " ")
return s |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.