content stringlengths 42 6.51k |
|---|
def binary_search(numbers, look):
"""Binary Search algorithm"""
# Split at the start
start = 0 # Start is beginning
mid = len(numbers) // 2 # the middle
end = len(numbers) - 1 # end
found = -2 # temp not found
# is it empty?
if not numbers:
return -1
def check_val(_sta... |
def is_valid_uni(uni):
""" Validate the syntax of a uni string """
# UNIs are (2 or 3 letters) followed by (1 to 4 numbers)
# total length 3~7
if not isinstance(uni,str):
return False
if len(uni) < 3 or len(uni) > 7:
return False
if uni[:3].isalpha():
# 3 letters
return uni[3:].isnumeric()
elif uni[:2].... |
def format_dir_space(dirpath):
"""REMOVE ESCAPED SPACES FROM DIRECTORY PATH
Args:
dirpath: Str, directory path to be corrected
Returns:
dirpath: Str, directory path with plain spaces and appended backslash
"""
dirpath = dirpath.replace("\ ", " ")
if dirpath[-1] != ... |
def tetrahedral(number):
""" Returns True if number is tetrahedral """
# n-th tetrahedral number is n * (n + 1) * (n + 2) / 6
n = 1
while True:
p = n * (n + 1) * (n + 2) / 6
if p == number:
return True
elif p > number:
return False
n = n + 1 |
def api_repo_url(org_name):
"""
With the supplied organization name, constructs a GitHub API URL
:param org_name: GitHub organization name
:return: URL to GitHub API to query org's repos
"""
return 'https://api.github.com/orgs/{}/repos'.format(org_name) |
def as_twos_comp(value: int) -> int:
"""Interpret number as 32-bit twos comp value."""
if value & 0x8000_0000 != 0:
# negative
flipped_value = (~value) & 0xFFFF_FFFF
return -(flipped_value + 1)
else:
# positive
return value |
def isString( obj ):
"""
Returns a boolean whether or not 'obj' is of type 'str'.
"""
return isinstance( obj, str ) |
def build_config(column):
"""Return router configuration with values from row.
:param column: mapping of values from csv columns for router_id
:type column: dict
:return: router configuration (list)
"""
# > > > Paste configuration *BELOW* the next line ("return \") < < <
return \
[
... |
def slashescape(err):
""" codecs error handler. err is UnicodeDecode instance. return
a tuple with a replacement for the unencodable part of the input
and a position where encoding should continue"""
#print(err, dir(err), err.start, err.end)
thebyte = err.object[err.start:err.end]
repl=u''... |
def part2(allergens):
"""Part 2 wants the list of unsafe ingredients, sorted by their
allergen alphabetically, joined together into one string by commas.
"""
return ",".join(
ingredient for (allergen, ingredient) in sorted(allergens.items())
) |
def list_format(lst):
""" Unpack a list of values and write them to a string
"""
return '\n'.join(lst) |
def _init_well_info(well_info, wname):
"""Initialize well info dictionary for well
"""
if wname not in well_info.keys():
winfo = dict()
winfo['welltype'] = 'Producer'
winfo['phase'] = 'Oil'
well_info[wname] = winfo
return well_info |
def get_num_tablets_per_dose(dose, strength, divisions=1):
"""Calculates the number of tablets to give based on the dose given and the strength of the tablets.
Tablets can be divided in quarters.
:params:
dose (Float) - The dose in mg of what the patient should be receiving
strength (Float) - The ... |
def from_camelcase(s):
"""
convert camel case to underscore
:param s: ThisIsCamelCase
:return: this_is_camel_case
"""
return ''.join(['_' + c.lower() if c.isupper() else c for c in s]).lstrip('_') |
def hex_to_rgb(color):
"""Convert a hex color code to an 8 bit rgb tuple.
Parameters
----------
color : string, must be in #112233 syntax
Returns
-------
tuple : (red, green, blue) as 8 bit numbers
"""
if not len(color) == 7 and color[0] == "#":
raise ValueErr... |
def horizontal_plate_natual_convection_1(Gr, Pr):
"""hot side upward, or cold side downward """
""" 1e4 < Ra < 1e11 """
Ra = Gr * Pr
if Ra < 1.0e7:
return 0.54 * Ra**0.25
else:
return 0.15 * Ra**0.25 |
def dnfcode_key(code):
"""Return a rank/dnf code sorting key."""
# rank [rel] '' dsq hd|otl dnf dns
dnfordmap = {
u'rel':8000,
u'':8500,
u'hd':8800,u'otl':8800,
u'dnf':9000,
u'dns':9500,
u'dsq':10000,}
... |
def to_name_key_dict(data, name_key):
"""
Iterates a list of dictionaries where each dictionary has a `name_key`
value that is used to return a single dictionary indexed by those
values.
Returns:
dict: Dictionary keyed by `name_key` values having the information
contained in the... |
def unify_walk(l1, l2, U):
"""
Tries to unify each corresponding pair of elements from l1 and l2.
"""
if len(l1) != len(l2):
return False
for x1, x2 in zip(l1, l2):
U = unify_walk(x1, x2, U)
if U is False:
return False
return U |
def trash_file(drive_service, file_id):
"""
Move file to bin on google drive
"""
body = {"trashed": True}
try:
updated_file = drive_service.files().update(fileId=file_id, body=body).execute()
print(f"Moved old backup file to bin.")
return updated_file
except Exception:
... |
def cross(a, b):
"""The cross product between vectors a and b. This code was copied off of StackOverflow, but it's better than
making you download numpy."""
c = (a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0])
return c |
def extract_stat_names(dict_of_stats):
""" Extracts all the names of the statistics
Args:
dict_of_stats (dict): Dictionary containing key-alue pair of stats
"""
stat_names = []
for key, val in dict_of_stats.items():
stat_names += [key]
return stat_names |
def weighted_uniform_strings(s, queries):
"""Given a string s, and a list of weight queries return a list indicating if query is possible."""
weights = []
last_char, repetitions = None, 1
for c in s:
val = ord(c) - 96
if last_char == val:
repetitions += 1
else:
... |
def short_method_name(method_name: str) -> str:
"""
This function takes a long method name like "class_name::method_name" and return the short method
name without the class prefix and the "::" separator.
"""
if "::" not in method_name:
return method_name
return method_name.spli... |
def check_path(dirs):
"""Check if directory path has '/' at the end.
Return value is either '/' or empty string ''.
"""
if dirs[-1] != "/":
return "/"
else:
return "" |
def get_water_info(data: dict, hostname: str, path: str):
"""
Use in ows_cfg.py as below:
"feature_info": {
"include_custom": {
"function" : "datacube_ows.feature_info_utils.get_water_info",
"kwargs" : {
"hostname" : "https://data.dea.ga.gov.au",
"path" : "proje... |
def bubble_sort_rc(array):
"""perform bubble search recursively"""
# Check whether all values in list are numbers
if all(isinstance(x, (int,float)) for x in array):
for ind, val in enumerate(array):
try:
if array[ind+1] < val:
array[ind] = array[ind+1]... |
def preproc_space(text):
"""line preprocessing - removes first space"""
return text.replace(" ", "", 1) if text.startswith(" ") else text |
def expandCall(kargs):
"""SNIPPET 20.10 PASSING THE JOB (MOLECULE) TO THE CALLBACK FUNCTION
Expand the arguments of a callback function, kargs['func']
"""
func=kargs['func']
del kargs['func']
out=func(**kargs)
return out |
def wrap_angle(x):
"""Wraps an angle between 0 and 360 degrees
Args:
x: the angle to wrap
Returns:
a new angle on the interval [0, 360]
"""
if x < 0:
x = 360 - x
elif x > 360:
x = x - 360
return x |
def get_suitable_astropy_format(outputFormat):
"""
Reason for change
-----------------
Translate the right file extension to one astropy
would recognize
"""
if "csv" == outputFormat:
return "ascii.csv"
if "tsv" == outputFormat:
return "ascii.fast_tab"
return outputFor... |
def get_total(alist, digits=1):
"""
get total sum
param alist: list
param digits: integer [how many digits to round off result)
return: float
"""
return round(sum(alist), digits) |
def parser_data_broadcast_id_Descriptor(data,i,length,end):
"""\
parser_data_broadcast_id_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
Parses a descriptor containing a list of alternative frequences on which
the multiplex may be carried.
The dict returned is:
{... |
def splitCentersByBeats(centers, splitter_dict):
"""
Split list of note centers by beats
"""
# Sort by columns
column_sorted_centers = sorted(centers, key=lambda x: x[0])
beats = {}
current_offset = 0
total_counter = 0
counter = 0
for key in sorted(splitter_dict.keys(... |
def normalize_string(str_input: str):
"""
Given a string, remove all non alphanumerics, and replace spaces with underscores
"""
str_list = []
for c in str_input.split(" "):
san = [lo.lower() for lo in c if lo.isalnum()]
str_list.append("".join(san))
return "_".join(str_list) |
def replace_all(text, dic):
"""
https://stackoverflow.com/a/6117042
"""
for i, j in dic.items():
text = text.replace(i, j)
return text |
def messageSend(num, text):
"""
:param num : Notification number (1: 'danger', 2: 'info', 3: 'success')
:param text: Message text
:return: Message
"""
alert = {1: 'danger', 2: 'info', 3: 'success'}
if num != 1 and num != 2 and num != 3:
num = 1
text = "Error. Wrong number of... |
def ksi_of_t_discrete(x_func, T, y0, g):
"""
Local regressor.
Discrete system
"""
return x_func(T) * (g - y0) |
def prudent(lst):
"""
:param lst: list
:return: int
"""
mins = dict()
for j in range(len(lst)):
mins[j] = min(lst[j])
for j in mins:
if mins[j] == max([mins[key] for key in mins]):
return j |
def transparency2float(value: int) -> float:
"""
Returns transparency value as float from 0 to 1, 0 for no transparency
(opaque) and 1 for 100% transparency.
Args:
value: DXF integer transparency value, 0 for 100% transparency and 255
for opaque
"""
# Transparency value 0x0... |
def subtract_dict(whole_dict, sub_dict):
"""
Creates a dictionary with a set of keys, that only present in the 'greater' dictionary.
:param whole_dict: dict, the dictionary to be reduced.
:param sub_dict: dict, the dictionary with the required keys.
:return: dict, the reduced dict.
"""
reduc... |
def _format(link):
"""
Give nice format to dict with alleles and reads supporting
"""
cell = ''
for allele in link:
cell += "%s=%s;" % (allele, link[allele])
return cell |
def calculate(digits):
"""Returns the index of the first term in the Fibonacci
sequence to contain the specified number of digits."""
answer = 0
prev = 1
cur = 1
while len(str(prev)) < digits:
answer += 1
next_term = prev + cur
prev = cur
cur = next_term
answe... |
def bullet_list(inp):
"""Convienience function that joins elements of a list into a bullet
formatted list."""
return '\n' + '\n'.join(['- ' + z for z in inp]) |
def round_up_to_power_of_two(n):
"""
From http://stackoverflow.com/a/14267825/1958900
"""
if n < 0:
raise TypeError("Nonzero positive integers only")
elif n == 0:
return 1
else:
return 1 << (n-1).bit_length() |
def active_mode_english(raw_table, base_index):
""" Convert mode to English """
value = raw_table[base_index]
if value == 0:
return "Vacation"
if value == 2:
return "Night"
if value == 4:
return "Day"
return "Unknown" |
def sep(*args):
"""join strings or list of strings ignoring None values"""
return ' '.join(a for a in args if a) |
def create_required(variable, window, in_options=False, var_type='numeric', var_length='11'):
"""
Returns the required `dict` to be used by lottus
:param variable `str`: the variable of that will be stored in the session
:param window `str`: the name of the window that this required object p... |
def items_key(params):
"""Return a hashable object (a tuple) suitable for a cache key
A dict is not hashable, so we need something hashable for caching the
items() function.
"""
def hashable(thing):
if isinstance(thing, list):
return ','.join(sorted(thing))
else:
... |
def parse_command_line_name_and_range(name_and_range_arg):
"""
Parse command line argument that looks like "phage:0:80000,prok:0:70000" into
{
phage_dset_name: "phage",
phage_range: (0,80000),
prok_dset_name: "prok",
prok_range: (0,70000)
}
:param name_and_range: (str) "phag... |
def word_at(match, word_index):
"""A utility function that gets the word with index word_index"""
assert 0 <= word_index < len(match["words"]), "word_index out of range of words"
return match["words"][word_index] |
def get_post_context(resp):
"""
Prepare context data for forum post
:param resp: forum post api response
:return: dict object
"""
post_ec = {
'PostId': resp['id'],
'PublishedAt': resp.get('published_at', ''),
'Url': resp.get('url', ''),
'PlatformUrl': resp.get('p... |
def xor(a, b):
"""xor bits together.
>>> assert xor(0, 0) == 0
>>> assert xor(0, 1) == 1
>>> assert xor(1, 0) == 1
>>> assert xor(1, 1) == 0
"""
assert a in (0, 1)
assert b in (0, 1)
if a == b:
return 0
else:
return 1 |
def _string_or_float_to_integer_python(s):
"""
conda-build 2.0.4 expects CONDA_PY values to be integers (e.g., 27, 35) but
older versions were OK with strings or even floats.
To avoid editing existing config files, we support those values here.
"""
try:
s = float(s)
if s < 10: ... |
def deploy_dashboard(db_json_url, wf_url, api_token):
"""Deploy a dashboard in wavefront."""
print("Deploying Dashboard with %s, %s, %s"
% (db_json_url, wf_url, api_token))
return True |
def get_piece(gameBoard: tuple, x: int, y: int) -> int:
""" Returns the state of the given location """
max_x = len(gameBoard[0]) - 1
max_y = len(gameBoard) - 1
# Check for wraps
if x > max_x:
x = x - max_x - 1
if x < 0:
x = max_x + x + 1
if y > max_y:
y =... |
def unique(ngb):
"""Return unique values from vector."""
uni = list()
for n in ngb:
if n not in uni:
uni.append(n)
return uni |
def group_words(words):
"""Takes a list of words, and groups them, returning a list-of-lists.
The idea is that each word starting with '*' is a synonym for the previous word,
and we group these synonyms together with their base word.
The word '.' is padding, and we discard it if found.
"""
gr... |
def get_2comp(val_int, val_size=16):
"""Get the 2's complement of Python int val_int
:param val_int: int value to apply 2's complement
:type val_int: int
:param val_size: bit size of int value (word = 16, long = 32) (optional)
:type val_size: int
:returns: 2's complement res... |
def approx_Q_linear(B: float, T: float):
"""
Approximate rotational partition function for a linear molecule.
Parameters
----------
B - float
Rotational constant in MHz.
T - float
Temperature in Kelvin.
Returns
-------
Q - float
Rotational partition function... |
def remove_comments(input_string):
""" Helper function for import_test.
Removes all parts of string that would be commented out by # in python
paramters
---------
input_string: string
returns
-------
string where all parts commented out by a '#' are removed from input_string
"""
split_lines = input_string.s... |
def name_mosaic_info(mosaic_info):
"""
Generate the name for a mosaic metadata file in Azure Blob Storage.
This follows the pattern `metadata/mosaic/{mosaic-id}.json`.
"""
return f"metadata/mosaic/{mosaic_info['id']}.json" |
def extract_data(drug, statuses):
"""Extracts the desired data from a list of twitter responses.
Arguments:
drug {str} -- the drug name that corresponds to the statuses.
statuses {list} -- twitter statuses that were the result of searching for 'drug'.
Returns:
[list] -- a list of d... |
def dpq(states, actions, initial_value=0):
"""dynamic programming definition for Q-learning
This implementation returns a table like, nested
dict of states and actions -- where the inner values
q[s][a] reflect the best current estimates of expected
rewards for taking action a on state s.
See [... |
def _singularize(string):
"""Hacky singularization function."""
if string.endswith("ies"):
return string[:-3] + "y"
if string.endswith("s"):
return string[:-1]
return string |
def get_pf_input(spc, spc_str, global_pf_str, zpe_str):
""" prepare the full pf input string for running messpf
"""
# create a messpf input file
spc_head_str = 'Species ' + spc
print('pf string test:', global_pf_str, spc_head_str, spc_str, zpe_str)
pf_inp_str = '\n'.join(
[global_pf_str... |
def base_url(host, port):
"""build scrapyd host url
:param host: scrapyd host ip
:param port: scrapyd host port
:return scrapyd host url
"""
return 'http://{host}:{port}'.format(host=host, port=port) |
def solve(puzzle_input):
"""Solve a puzzle input"""
# print("solve(%s)" % puzzle_input)
direction = 0 # 0 up, 1 left, 2 down, 3 right
# initialise a starting grid with the first ring aka square 1
# The size is known to be big enough to solve my input
grid_size = 13
grid = [[0 for x in... |
def precip_to_energy(prec):
"""Convert precip to W/m2
Parameters
---------
prec : (mm/day)
"""
density_water = 1000
Lv = 2.51e6
coef = density_water / 1000 / 86400 * Lv
return coef * prec |
def sortByLabels(arr, labels):
"""
intended use case: sorting by cluster labels for
plotting a heatmap
"""
return [x[1] for x in sorted(enumerate(arr), key=lambda x: labels[x[0]])] |
def is_float(value):
""" Reports whether the value represents a float. """
try:
float(value)
return True
except ValueError:
return False |
def _align32b(i):
"""Return int `i` aligned to the 32-bit boundary"""
r = i % 4
return i if not r else i + 4 - r |
def NONS(s):
""" strip NS """
return s[32:] |
def unchurch(c) -> int:
"""
Convert church number to integer
:param c:
:return:
"""
return c(lambda x: x + 1)(0) |
def decode_to_string(toDecode):
"""
This function is needed for Python 3,
because a subprocess can return bytes instead of a string.
"""
try:
return toDecode.decode("utf-8")
except AttributeError: # bytesToDecode was of type string before
return toDecode |
def maybeint(x):
"""Convert x to int if it has no trailing decimals."""
if x % 1 == 0:
x = int(x)
return x |
def _codeStatusSplit(line):
"""
Parse the first line of a multi-line server response.
@type line: L{bytes}
@param line: The first line of a multi-line server response.
@rtype: 2-tuple of (0) L{bytes}, (1) L{bytes}
@return: The status indicator and the rest of the server response.
"""
p... |
def to_string(data):
"""Convert data to string.
Works for both Python2 & Python3. """
return '%s' % data |
def test_shadowing(x, y, z):
"""Test an expression where variables are shadowed."""
x = x * y
y = y * z
z = x * z
return x + y + z |
def expand_abbreviations(template, abbreviations) -> str:
"""Expand abbreviations in a template name.
:param template: The project template name.
:param abbreviations: Abbreviation definitions.
"""
if template in abbreviations:
return abbreviations[template]
# Split on colon. If there ... |
def replace_items(lst, old, new):
"""
:param lst: []
List of items
:param old: obj
Object to substitute
:param new: obj
New object to put in place
:return: []
List of items
"""
for i, val in enumerate(lst):
if val == old:
lst[i] = new
... |
def acl_represent(acl, options):
"""
Represent ACLs in tables
for testing purposes, not for production use!
"""
values = []
for o in options.keys():
if o == 0 and acl == 0:
values.append("%s" % options[o][0])
elif acl and acl & o == o:
values.app... |
def kgtk_date(x):
"""Return True if 'x' is a KGTK date literal.
"""
return isinstance(x, str) and x.startswith('^') |
def compression_ratio(width, height, terms):
"""
Parameters
----------
width : int
Width of the image in pixels.
height : int
Width of the image in pixels.
terms : int
The number of terms in the singular value expansion.
Returns
-------
float
The of... |
def aic_measure(log_likelihood, params_num):
"""
Returns the Akaike information criterion value, that is
AIC = -2ln(L) + 2m,
where L is the likelihood in the optimum and m is the number of parameters in the
model.
:param log_likelihood: optimized log-likelihood.
:param params_num: number of... |
def parse_entry_helper(node, item):
"""
Create a numpy list from value extrated from the node
:param node: node from each the value is stored
:param item: list name of three strings.the two first are name of data
attribute and the third one is the type of the value of that
attribute. ty... |
def get_multi_machine_types(machinetype):
"""
Converts machine type string to list based on common deliminators
"""
machinetypes = []
machine_type_deliminator = [',', ' ', '\t']
for deliminator in machine_type_deliminator:
if deliminator in machinetype:
machinetypes = machine... |
def unique_items(seq):
"""Return the unique items from iterable *seq* (in order)."""
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))] |
def int_min(int_a, int_b):
"""
min(a, b)
"""
if int_a < int_b:
return int_a
else:
return int_b |
def evaluate_subcategories(list1, list2, max_score):
"""returns a numerical representation of the similarity of two lists of strings
Args:
list1(list): a list of strings (this is a list of items from the query patient)
list2(list): another list of strings (list of items from the patients in dat... |
def next_run_iso_format(next_run):
"""
Convert next run timestamp object to the ISO format
"""
if isinstance(next_run, bool):
next_run = None
else:
next_run = next_run.isoformat()
return next_run |
def generate_one_test_data_set_1D(
random_generator,
pixels_per_clock: int,
image_size: int,
):
"""Generate a 2D-list of test data suitable for testing a 1D line
buffer with the given pixels/clock and image size parameters. Populate
the test data using values from the random_generator function passed.
... |
def _is_dunder(name):
"""Returns True if a __dunder__ name, False otherwise."""
return (
len(name) > 4
and name[:2] == name[-2:] == "__"
and name[2] != "_"
and name[-3] != "_"
) |
def parse_escaped_hierarchical_category_name(category_name):
"""Parse a category name."""
result = []
current = None
index = 0
next_backslash = category_name.find('\\', index)
next_slash = category_name.find('/', index)
while index < len(category_name):
if next_backslash == -1 and ne... |
def gcd(a, b):
"""Computes the greatest common divisor of integers a and b using
Euclid's Algorithm.
"""
while b != 0:
a, b = b, a % b
return a |
def construct_backwards_adjacency_list(adjacency_list):
"""
Create an adjacency list for traversing a graph
backwards
The resulting adjacency dictionary maps
vertices to each vertex with an edge
pointing to them
"""
backwards_adjacency_list = {}
for u in adjacency_list:
for v in adjacency_list[u... |
def modelVariance(fn,xs,ys,yerrs=None):
"""takes a function and returns the variance compared to some data"""
if yerrs is None:
yerrs=[1]*len(xs)
return sum([(fn(x)-ys[i])**2./yerrs[i]**2. for i,x in enumerate(xs)]) |
def save_params(net, best_metric, current_metric, epoch, save_interval, prefix):
"""Logic for if/when to save/checkpoint model parameters"""
if current_metric > best_metric:
best_metric = current_metric
net.save_parameters('{:s}_best.params'.format(prefix, epoch, current_metric))
with op... |
def count_values(in_list):
"""
Return the count of the number of elements in an arbitrarily nested list
"""
# Deep copy of in_list
if type(in_list) is dict:
mod_list = list(in_list.values())
else:
mod_list = list(in_list)
count = 0
while mod_list:
entry = mod_li... |
def make_xml_name(attr_name):
""" Convert an attribute name to its XML equivalent by replacing
all '_' with '-'. CamelCase names are retained as such.
:param str attr_name: Name of the attribute
:returns: Attribute name in XML format.
"""
return attr_name.replace('_', '-') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.