content stringlengths 42 6.51k |
|---|
def binarySearch(array, key, left, right):
"""
Inputs -
array - A sorted array in which we're going to search for the key
key - The number to be searched for
left - The leftmost index at which we need to look
right - The rightmost index at which we need to look
=============================... |
def unique_file_name(file_name: str, cnt: int) -> str:
"""creates a random temporary file name, returns a str"""
return f'{file_name}_wordlist({cnt}).temp' |
def determine_data_type(raw_resource_type_id):
"""Determine resource type ID.
:param raw_resource_type_id: raw resource type ID from manifest file
:return: short resource type ID
"""
return raw_resource_type_id.split("/")[-1].replace(":", "") \
if raw_resource_type_id is not None else None |
def womp_womp(docp):
"""need this to work around xpdan putting diffpy objects in some events"""
import pickle
try:
doc = pickle.loads(docp)
except Exception as e:
print(e)
return {"time": 0, "data": {}, "timestamps": {}, "uid": "", "seq_num": 0}
return doc |
def if_blank_return(input, default) -> object:
"""
:param default:
:return: object
if input value is none or blank element return default value
[] "" are blank element
"""
if not input:
return default
return input |
def parse_sections(lines):
"""Parse the input document into sections, separated by blank lines.
A list of lists is returned. Each item is the list of lines for a section.
"""
secid = 0
section = []
for line in lines:
if not line.strip():
secid += 1
continue
... |
def safe_decode(s, coding='utf-8', errors='surrogateescape'):
"""decode bytes to str, with round-tripping "invalid" bytes"""
if s is None:
return None
return s.decode(coding, errors) |
def f(s, o=0):
"""Diamonds extractor."""
if len(s) == 0:
return 0
elif s[0] == '<':
return f(s[1:], o + 1)
elif s[0] == '>' and o > 0:
return 1 + f(s[1:], o - 1)
else:
return 0 |
def leading_zeros(val, n):
""" Return string with "n" leading zeros to integer. """
return (n - len(str(val))) * '0' + str(val) |
def is_palindrome(x: int) -> bool:
"""
O(1) time and space.
"""
x_str = str(x)
return x_str == x_str[::-1] |
def findFirst(L, pred):
"""
Returns the first element in L that satisfies a given predicate with binary search.
L must be a list of elements that DO NOT satisfy the predicate followed by a list of ones that DO satisfy pred.
Returns 0 if there is no element satisfying pred.
"""
left, right ... |
def sample_n_unique(sampling_f, n):
"""Helper function. Given a function `sampling_f` that returns
comparable objects, sample n such unique objects.
"""
res = []
while len(res) < n:
candidate = sampling_f()
if candidate not in res:
res.append(candidate)
return res |
def _get_value(value):
"""Interpret null values and return ``None``. Return a list if the value
contains a comma.
"""
if not value or value in ['', '.', 'NA']:
return None
if ',' in value:
return value.split(',')
return value |
def simplify(value):
"""Return an int if value is an integer, or value otherwise.
>>> simplify(8.0)
8
>>> simplify(2.3)
2.3
>>> simplify('+')
'+'
"""
if isinstance(value, float) and int(value) == value:
return int(value)
return value |
def _find_pattern(pattern, buf, iterator, start=0):
"""Find pattern in buf, appending new data from iterator to buf if
necessary
"""
while len(buf) <= start + len(pattern):
buf.extend(next(iterator))
while True:
pos = buf.find(pattern, start)
if pos >= 0:
assert ... |
def tolist(listlike):
"""
Turns a list-like object into a list,
if it not already is one.
"""
if type(listlike) == type(None):
return listlike
if type(listlike) is list:
return listlike
else:
return listlike.tolist() |
def _build_error_message(html: str, message: str) -> str:
""" Constructs the HTML for an error text with message `message` over the original html. """
return f"""<p style="text-align: center; color: red; font-size: large;">
Maobi encountered an error: <br />
{message}
</p>
{html}
""" |
def spot_centroid(regions):
"""Returns centroids for a list of regionprops.
Args:
regions (regionprops): List of region proposals (skimage.measure).
Returns:
list: Centroids of regionprops.
"""
return [r.centroid for r in regions] |
def _create_typedef_classes(typedefs):
""" Creates an anonymous class for each typedef in the C function
"""
classes = {}
for k, v in typedefs.items():
class Wrapper:
"""Wrapper class for a C typedef
The attributes are dynamically from the C definition using
... |
def round_fracs(amts):
"""
Rounds array, ensuring that sum(result) == sum(amts)
Using even-rounding (rounds to the nearest even for 0.5)
All fractions are closed (accumulated) to last element.
"""
if len(amts) == 0:
return []
if len(amts) == 1:
return [round(amts[0])... |
def enforce_list(var):
""" Enforces a list of elements
If a single, non-list element is given, a list with one element is returned
args:
var: list or single element
returns:
given list or single element list holding the given var parameter
"""
if type(var) is not list:
... |
def dict_to_yaml_list(pdict):
"""Converts a python dict into a yaml list (volumes, configs etc)
:pdict: python dict
:return: list of a yaml containing colon separated entries
"""
return [f'{k}:{v}' for (k, v) in pdict.items()] |
def class_counts(rows, label):
"""
find the frequency of items for each class in a dataset.
PARAMETERS
==========
rows: list
A list of lists to store the rows whose
predictions is to be determined.
label: integer
The index of the last column
RETURNS
=======
... |
def getMax2(operations):
"""This method tries to use only one stack, but uses external-to-the-stack
variables to keep track of the maximum element present in the stack."""
q = []
output = list()
for op in operations:
if len(op.split(" ")) == 2:
_, x = op.split(" ")
q... |
def patternize(lst):
"""helper function for vecToMatrix"""
lst = sorted(lst)
n = [lst[0]]
for i in range(len(lst)-1):
if lst[i] != lst[i+1]:
n.append(lst[i+1])
return n |
def M_TO_N_ONLY(m, n, e):
"""
:param:
- `m`: the minimum required number of matches
- `n`: the maximum number of matches
- `e`: the expression t match
"""
return r"\b{e}{{{m},{n}}}\b".format(m=m, n=n, e=e) |
def durationtoseconds(period):
"""
@author Jayapraveen
"""
# Duration format in PTxDxHxMxS
if (period[:2] == "PT"):
period = period[2:]
day = int(period.split("D")[0] if 'D' in period else 0)
hour = int(period.split("H")[0].split("D")[-1] if 'H' in period else 0)
min... |
def partition(iterable, pred, first=0, last=None):
"""
Parition the iterable from first to last such that all elements
that satisfy pred are before all elements where pred is false.
Returns one past the index of the last element where pred is true.
Relative order of the elements is not preserved.
... |
def extract_qa_bits(qa_band, start_bit, end_bit):
"""Extracts the QA bitmask values for a specified bitmask (starting
and ending bit).
Parameters
----------
qa_band : numpy array
Array containing the raw QA values (base-2) for all bitmasks.
start_bit : int
First bit in the bit... |
def build_metric_link(region, alarm_name):
"""Generate URL link to the metric
Arguments:
region {string} -- aws region name
alarm_name {string} -- name of the alarm in aws
Returns:
[type] -- [description]
"""
url = 'https://{}.console.aws.amazon.com/cloudwatch/home?... |
def param_enabled(param_obj):
"""Return True if param is enabled, False otherwise"""
enabled=True
if "enabled" in param_obj:
if param_obj['enabled'].lower() == "no":
enabled=False
del param_obj["enabled"]
return enabled |
def margin_range(base, val):
"""Create a range of margins around a base value.
Parameters
----------
base : int
The value around which a margin should be created.
val : int or float
The margin size. If float, val will be interpreted as percentage.
Returns
-------
r : ... |
def main(argv=()):
"""
Args:
argv (list): List of arguments
Returns:
int: A return code
Does stuff.
"""
print(argv)
return 0 |
def link2dict(l):
"""
Converts the GitHub Link header to a dict:
Example::
>>> link2dict('<https://api.github.com/repos/sympy/sympy/pulls?page=2&state=closed>; rel="next", <https://api.github.com/repos/sympy/sympy/pulls?page=21&state=closed>; rel="last"')
{'last': 'https://api.github.com/repos/sym... |
def as_learning_rate_by_sample(learning_rate_per_minibatch, minibatch_size, momentum=0, momentum_as_unit_gain=False):
"""
Compute the scale parameter for the learning rate to match the learning rate
definition used in other deep learning frameworks.
In CNTK, gradients are calculated as follows:
... |
def coordsToString(top, left):
"""Creates a string of coordinates to use to track places the computer has shot"""
return str(top) + str(left) |
def insert_stream_parameters(streams, stream_params):
"""Helper function for inserting the stream parameters back to the streams.
Args:
streams (list):
list of StationStream objects.
stream_params (dict):
Dictionary of stream parameters.
Returns:
list of Sta... |
def automata_line(state, line):
"""
Automata parsing knowledges.
0: waiting for knowledge block
1: seen the heading of a knowledge block
2: we are in a knowledge block
"""
if state == 0 and "Undefined knowledges" in line:
return 1, None
elif state == 1 and "**********************... |
def dashrange(s):
"""Parses individual groups of ranges inside an already
(comma)-separated list, e.g, ["0-4","12"]. It returns a flat
list with all numbers between the range
Args:
s (str): string containing dashes
Returns:
list: list of integers between the range
"""
if "-... |
def lowercase_subset(A, B):
"""Check that A is a subset of B when case is ignored."""
set_a = set([a.lower() for a in A])
set_b = set([b.lower() for b in B])
return set_a.issubset(set_b) |
def naive_log_ctz(x: int) -> int:
"""Count trailing zeros, in a O(log(zeros)) steps.
Args:
x: An int.
Returns:
The number of trailing zeros in x, as an int.
This implementation is much faster than the naive linear implementation,
as it performs a logarithmic number of steps relati... |
def get_ndata(ofile):
"""Read the whole file to get number of data attributes."""
data = [next(ofile)]
loc = 1
if data[0].strip()[0] == '{':
raise ValueError("This looks like a sparse ARFF: not supported yet")
for i in ofile:
loc += 1
return loc |
def f(x, r):
"""
Implement the right-hand-side of the differential equation
x' = r * x - x / (1 + x)
"""
return r * x - x / (1 + x**2) |
def _generate_data(jcr_primary_type, base_name, path_name, asccidoc_type):
"""
Generate the data object for the API call.
"""
data = {}
if jcr_primary_type:
data["jcr:primaryType"] = jcr_primary_type
if base_name:
data["jcr:title"] = base_name
data["jcr:description"] = ba... |
def is_at_end(word1, word2):
"""checks if word1 is at the end of word2"""
return word1 != word2 and word1 == word2[-len(word1):] |
def validate_etextno(etextno):
"""Raises a ValueError if the argument does not represent a valid Project
Gutenberg text idenfifier.
"""
if not isinstance(etextno, int) or etextno <= 0:
msg = 'e-text identifiers should be strictly positive integers'
raise ValueError(msg)
return etext... |
def _CheckListType(settings, allowed_type, name, allow_none=True):
"""Verify that settings in list are of the allowed type or raise TypeError.
Args:
settings: The list of settings to check.
allowed_type: The allowed type of items in 'settings'.
name: Name of the setting, added to the exception.
all... |
def _get_file_type(fname):
"""Return the type of a file."""
if fname.endswith('.nii.gz') or fname.endswith('.nii'):
return 'NIfTI-1'
if fname.endswith('.png'):
return 'PNG'
if fname.endswith('.jpg'):
return 'JPEG'
if fname.endswith('.mnc'):
return 'MINC'
if fname.... |
def round_to_nearest(number, nearest=5):
"""@see https://stackoverflow.com/questions/2272149/round-to-5-or-other-number-in-python"""
return int(nearest * round(float(number) / nearest)) |
def F2K(T_F):
"""
Convert temperature in Fahrenheit to Kelvin
"""
return 5/9*(T_F+459.67) |
def avi(b4, b8a):
"""
Ashburn Vegetation Index (Ashburn, 1978).
.. math:: AVI = 2 * b8a - b4
:param b4: Red.
:type b4: numpy.ndarray or float
:param b8a: NIR narrow.
:type b8a: numpy.ndarray or float
:returns AVI: Index value
.. Tip::
Ashburn, P. 1978. The vegetative ind... |
def recovery_clifford(state):
"""
Returns the recovery clifford operation matching the final state (after the RB circuit)
:param state:
:return:
"""
operations = {
"z": ["I"],
"-x": ["-Y/2"],
"y": ["X/2"],
"-y": ["-X/2"],
"x": ["Y/2"],
"-z": ["X"]... |
def transform(data):
"""Multiply the input by 10"""
if not data:
data = [1, 2, 3]
return [i * 10 for i in data] |
def to_one_dimensional_array(iterator):
"""convert a reader to one dimensional array"""
array = []
for i in iterator:
if type(i) == list:
array += i
else:
array.append(i)
return array |
def get_group_value_nb(from_col, to_col, cash_now, last_shares, last_val_price):
"""Get group value."""
group_value = cash_now
group_len = to_col - from_col
for k in range(group_len):
col = from_col + k
if last_shares[col] != 0:
group_value += last_shares[col] * last_val_pric... |
def timefrac_helper(t1,t2,frac):
"""
Shorthand for t1 + (t2-t1)*frac, returns the number
t whose fractional progress along t1->t2 is frac.
"""
return t1 + (t2-t1)*frac; |
def unpop(state):
"""Given the before, stack, and after tuples, returns the (one-step) preimage.
"""
after,stack,before = state
if after and after[-1] and (not stack or after[-1] < stack[-1]):
return (after[:-1], stack+(after[-1],), before)
else:
return |
def flatten_list(input):
"""
Given a list or list of lists, this method will flatten any list structure into a single list
:param input: Artibtrary list to flatten. If not a list, then the input will be returned as a list of that single item
:return: Flattened list
"""
if isinstance(input,lis... |
def sanitize (tuple_numbers):
"""
Clean up a tuple of strings passed for irregular formatting of phone numbers
Whether it's spaces, dashes, or parenthesis
Return: A clean string with only numbers
"""
clean_string = ()
for st in tuple_numbers:
# Remove junk characters
st = st... |
def parse_literal(x):
"""
return the smallest possible data type for a string
Parameters
----------
x: str
a string to be parsed
Returns
-------
int, float or str
the parsing result
"""
if isinstance(x, list):
return [parse_literal(y) for y in x]
eli... |
def FormCATSLabel(PathLength = 10):
"""
#################################################################
Construct the CATS label such as AA0, AA1,....AP3,.......
The result is a list format.
A acceptor;
P positive;
N negative;
L lipophilic;
D donor;
###... |
def coerce_tag(tag):
"""
Coerce a BeautifulSoup tag to its string contents (stripped from leading and trailing whitespace).
Used by :func:`parse_status_table()` to get the text values of HTML tags.
"""
try:
return u''.join(tag.findAll(text=True)).strip()
except Exception:
return... |
def parse_boolean(value: str, default=False, invert=False):
"""
Parses a boolean value from a string.
String must contain "yes" to be considered True.
Parameters
----------
value: :class:`str`
The string containing an integer.
default: :class:`bool`, optional
The value to re... |
def chocolate_maker(small, big, x):
""" calculate if small or big pieces can create the relevant size of chocolate
:param:small:big:x
:type:int
:return if can be created of small or big pieces
:rtype:bool
"""
if (x/big == 5) or (x/small == 1):
return True
elif x - small*1 - big*5... |
def int_to_bytes(number, length):
"""
Returns a list of bytes that repersent `number`. The list is little endian.
`length` represents the number of bytes.
`number` is cast to an int before using. If number is larger then `length`
the higher order bytes are ignored.
"""
number = int(number... |
def resolve_frompath(pkgpath, relpath, level=0):
"""Resolves the path of the module referred to by 'from ..x import y'."""
if level == 0:
return relpath
parts = pkgpath.split('.') + ['_']
parts = parts[:-level] + (relpath.split('.') if relpath else [])
return '.'.join(parts) |
def _format_command_stdout(stdout):
"""
Formats the output from stdout returned from subprocess
"""
lines, list_of_strs = stdout.splitlines(), list()
for line in lines:
list_of_strs.append(line.decode())
return list_of_strs |
def anneal(c_max, step, iteration_threshold):
"""Anneal function for anneal_vae (https://arxiv.org/abs/1804.03599).
Args:
c_max: Maximum capacity.
step: Current step.
iteration_threshold: How many iterations to reach c_max.
Returns:
Capacity annealed linearly until c_max.
"""
... |
def sort_objects_top_to_bottom(objs):
"""
Put the objects in order from top to bottom.
"""
return sorted(objs, key=lambda k: k['bbox'][1] + k['bbox'][3]) |
def find_border_crossing(subset, path, final_state):
"""
Find the transition that steps outside the safe L{subset}.
@param subset: Set of states that are safe.
@type subset: C{set} of L{State}
@param path: Path from starting state to L{final_state}, sequence of state
and its outg... |
def is_paired(text, open="(", close=")"): # type: (str, str, str) -> bool
"""Check if the text only contains:
1. blackslash escaped parentheses, or
2. parentheses paired.
"""
count = 0
escape = False
for c in text:
if escape:
escape = False
elif c == "\\":
... |
def get_post_message(text, identity):
"""
Generate json of the post request.
Parameters
----------
text
String to send as message
"""
return { "sender": 'bot', "message": f'{identity}: {text}' } |
def strip_query(url):
"""Remove query string from a url"""
return url.split('?', 1)[0] |
def getAccountId(rid):
"""
:param rid:
:return:
"""
try:
list=rid.split(":")
return list[4]
except Exception as e:
return None |
def trim(chips, dates):
"""Eliminates chips that are not from the specified dates
Args:
chips: Sequence of chips
dates: Sequence of dates that should be included in result
Returns:
tuple: filtered chips
"""
return tuple(filter(lambda c: c['acquired'] in dates, chips)) |
def plural(x):
""" Returns an 's' if plural.
Useful in print statements to avoid something like 'point(s)'. """
if x > 1:
return 's'
return '' |
def merge_dicts(*dict_args):
"""
Given any number of dictionaries, shallow copy and merge into a new dict,
precedence goes to key-value pairs in latter dictionaries.
Parameters
----------
**dict_args : dict
Dictionary to merge
Returns
-------
merged_dict : str
Merge... |
def dop2str(dop: float) -> str:
"""
Convert Dilution of Precision float to descriptive string.
:param float dop: dilution of precision as float
:return: dilution of precision as string
:rtype: str
"""
if dop == 1:
dops = "Ideal"
elif dop <= 2:
dops = "Exce... |
def section_start(lines, section=' IMPRESSION'):
"""Finds line index that is the start of the section."""
for idx, line in enumerate(lines):
if line.startswith(section):
return idx
return -1 |
def getColor(k) :
"""Homemade legend, returns a nice color for 0 < k < 10
:param k : indice
"""
colors = ["#862B59","#A10000","#0A6308","#123677","#ff8100","#F28686","#6adf4f","#58ccdd","#3a3536","#00ab7c"]
return colors[k] |
def main( argv ):
"""
"""
# Return success.
return 0 |
def get_provenance_record(ancestor_files):
"""Create a provenance record describing the diagnostic data and plot."""
record = {
'caption':
('(a) Zonally averaged sea surface temperature (SST) error in CMIP5 '
'models. (b) Equatorial SST error in CMIP5 models. (c) Zonally '
'ave... |
def decode(s):
"""
Return a decoded unicode string from s or None if the string cannot be decoded.
"""
if b'\x00' in s:
try:
return s.decode('utf-16-le')
except UnicodeDecodeError:
pass
else:
return s.decode('ascii') |
def prop_convert(prop):
"""Take property urls and converts them into more human readable names.
Args:
prop (str): a url for a property, e.g. http://purl.org/dc/terms/title
or http://sbols.org/v2#type
Raises:
ValueError: raised if the prop is not a string
Returns:
... |
def find_pure_symbol(symbols, unknown_clauses):
"""
Find a symbol and its value if it appears only as a positive literal
(or only as a negative) in clauses.
Arguments are expected to be in integer representation.
>>> find_pure_symbol({1, 2, 3}, [{1, -2}, {-2, -3}, {3, 1}])
(1, True)
"""
... |
def decode_fourcc(cc):
"""
Turns the float into a four letter codec string.
Taken from here:
https://stackoverflow.com/a/49138893/4698227
:param cc: the codec as float
:type cc: float
:return: the codec string
:rtype: str
"""
return "".join([chr((int(cc) >> 8 * i) & 0xFF) for i i... |
def even_or_odd(number):
"""
Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for
even numbers or "Odd" for odd numbers.
:param number: a positive integer value.
:return: return 'Even' when the input value is even, otherwise return 'Odd'.
"""... |
def rgb_mix_colors2(c1, c2):
""" color mix
:param c1: color 1 (tuple of rgb values)
:param c2: color 2 (tuple of rgb values)
:return: relative mix of c1 & c2 """
r1 = c1[0]
g1 = c1[1]
b1 = c1[2]
r2 = c2[0]
g2 = c2[1]
b2 = c2[2]
# remove white before mixing
w1 = min(r1, ... |
def potential_lrc ( density, r_cut ):
"""Calculates long-range correction for Lennard-Jones potential per atom."""
import math
# density, r_cut, and the results, are in LJ units where sigma = 1, epsilon = 1
sr3 = 1.0 / r_cut**3
return math.pi * ( (8.0/9.0) * sr3**3 - (8.0/3.0) * sr3 ) * de... |
def protein_properties_filename(filestem):
"""Return the name of the protein properties file."""
if filestem is None:
return "proteins.tsv"
return f"{filestem}-proteins.tsv" |
def blendPath(path):
"""
Converts a relitive path to an asset in a blender libary
to an absolute path to the blend,
the location of the asset in the blend
and the name of the asset.
path, location, name
"""
blendPath, dirName, assetName = ( part.strip() for part in path.rsplit('/', 2) )
return blen... |
def _total_dataset_eval(name_task):
"""
:param name_task: name task, this can be : ro, md
:return: total size of dataset fo dev, train for the other dataset
"""
if name_task == 'ro':
return 2716, 2719
if name_task == 'md':
return 3205, 3205
return None, None |
def raw_tag(name, value):
"""Create a DMAP tag with raw data."""
return name.encode('utf-8') + \
len(value).to_bytes(4, byteorder='big') + \
value |
def update_schema_names(schema: dict, column_name_map: dict):
"""
Update schema dictionary column names using a column name map, of old to new names.
"""
return {column_name_map[key]: value for key, value in schema.items()} |
def merge(list1, list2):
"""this function takes two lists and returns a list of tuples paired itemwise list1[i]:list2[i]"""
merged_list = tuple(zip(list1, list2))
return merged_list |
def db_to_host(_hostvars):
"""
Return db_to_host mapping.
"""
_db_to_host_var = {}
if _hostvars:
for _hostname, _entry in _hostvars.items():
_dbs = _entry.get('dbs')
if _dbs:
for _db_entry in _entry.get('dbs'):
_db_to_host_var[_db_e... |
def lin_parallaxE_lon_lat(delta_ups, ups, lon, lat):
"""
Eq. 4.14
Linear approximation of the parallax error as a function of the elevated
target's longitude and latitude
Parameters
------------
delta_ups : float
Parallax error, in km
ups : float
SSP distance angle, in ... |
def translate_sequence(rna_sequence, genetic_code):
"""Translates a sequence of RNA into a sequence of amino acids.
Translates `rna_sequence` into string of amino acids, according to the
`genetic_code` given as a dict. Translation begins at the first position of
the `rna_sequence` and continues until th... |
def keypress_to_dispatch_key(key, scancode, codepoint, modifiers):
"""Converts the key_down event data into a single string for more convenient
keyboard shortcut dispatch.
:returns: The dispatch key in format ``109+alt,shift`` -- key number, ``+``,
and the modifiers joined by commas.
"""
if... |
def isValidSymbol(sym):
"""
Determine whether a character is a valid unit symbol
@param sym: the string to check
@return True if the character is a valid unit symbol, False otherwise
"""
for char in sym:
if (not char.isalpha()) and (char != '_'): return False
return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.