content stringlengths 42 6.51k |
|---|
def check_month_validation(month):
"""check if month is validate
:param month: input month
:return: if month is validate
"""
return int(month) in range(1, 13) |
def mel2hz(mel):
"""
Convert a value in Mels to Hertz
Args:
mel: a value in Mels. This can also be a numpy array, conversion
proceeds element-wise.
Returns:
a value in Hertz. If an array was passed in, an identical sized array is
returned.
"""
return 700*(10... |
def coordinate_length_ok(latitude, longitude):
"""
A valid coordinate should be a float of certain length (i.e. usually 8-9 characters including the dot).
E.g. ['60.388098', '25.621308']
Explicitly check the length of a float and discard clearly invalid coordinates. There seems to be an issue
with some of the... |
def has_keys(needles, haystack):
"""
Searches for the existence of a set of needles in a haystack
"""
return all(item in haystack for item in needles) |
def _is_array(value):
""" Is the provided value an array of some sorts (list, tuple, set)? """
return isinstance(value, (list, tuple, set, frozenset)) |
def base_repr(number, base=2, padding=0):
"""
Return a string representation of a number in the given base system.
Parameters
----------
number : int
The value to convert. Positive and negative values are handled.
base : int, optional
Convert `number` to the `base` number system... |
def parse_email(ldap_entry):
"""
Returns the user's email address from an ldapentry
"""
if "mail" in ldap_entry:
email = ldap_entry['mail'][0]
else:
email = ldap_entry['uid'][0] + "@pdx.edu"
return email |
def compute_closest_coordinate(value, range_min, range_max):
"""
Function for computing closest coordinate for the neighboring hyperplane.
Parameters
----------
value : float
COORDINATE VALUE (x or y) OF THE TARGET POINT.
range_min : float
MINIMAL COORDINATE (x or y) OF... |
def makeSystemCall(args, shell=False):
"""
make a system call
@param args must be an array, the first entry being the called program
@shell turns on or off shell based features. Warning: using shell=True
might be a potential security hazard.
@return returns a tuple with communication from the called system pr... |
def get_attr(item, name, default=None):
"""
similar to getattr and get but will test for class or dict
:param item:
:param name:
:param default:
:return:
"""
try:
val = item[name]
except (KeyError, TypeError):
try:
val = getattr(item, name)
except... |
def GetVSSNumber(event_object):
"""Return the vss_store_number of the event."""
if not hasattr(event_object, 'pathspec'):
return -1
return getattr(event_object.pathspec, 'vss_store_number', -1) |
def _get_states(rev, act):
"""Determines the initial state and the final state based on boolean inputs
Parameters
----------
rev : bool
True if the reaction is in the reverse direction.
act : bool
True if the transition state is the final state.
Returns
-----... |
def int_to_str(num, max_num=0):
"""
Converts a number to a string. Will add left padding based on the max value to ensure numbers
align well.
"""
if num is None:
num_str = 'n/a'
else:
num_str = '{:,}'.format(num)
max_str = '{:,}'.format(int(max_num))
return num_str.rjust(... |
def make_category_query(category):
"""Creates a search query for the target audio category"""
# mediatype:(audio) subject:"radio"
return f"mediatype:(audio) subject:{category}" |
def _convert_results_to_dict(r):
"""Takes a results from ElasticSearch and returns fields."""
if 'fields' in r:
return r['fields']
if '_source' in r:
return r['_source']
return {'id': r['_id']} |
def prune_small_terms(hpo_counts, min_samples):
"""
Drop HPO terms with too few samples
"""
filtered_counts = {}
for term, count in hpo_counts.items():
if count >= min_samples:
filtered_counts[term] = count
return filtered_counts |
def array_equals(a, b):
""" Checks to see that two arrays
are completely equal, regardless of order
Complexity: O(n^2)
"""
i = 0
# Check all values in A
while i < len(a): # This loop runs N times
flag = False
j = 0
# Search for that va... |
def sizeof_fmt(mem_usage, suffix='B'):
"""
Returns the memory usage calculation of the last function.
Parameters
----------
mem_usage : int
memory usage in bytes
suffix: string, optional, default 'B'
suffix of the unit
Returns
-------
str
A string of the me... |
def t_weighted_mean_temp(T_pelagic, T_bottom, t_frac_pelagic):
"""Compute the time-weighted mean temperature.
Parameters
----------
T_pelagic : numeric
Pelagic temperature.
T_bottom : numeric
Bottom temperature.
t_frac_pelagic : numeric
Fraction of time spent in the pelagic... |
def sortData(data):
"""sort data into a specific index"""
sortedData = []
for i in data:
for j in i:
temp = []
i2c = j["i2c"]
temp.append(j["time"])
temp.append(i2c[0])
temp.append(i2c[1][0]["x"])
temp.append(i2c[1][0]["y"])
... |
def template_validation(template_dest, template_reference):
"""Validates a stream template against the current version.
@param template_dest The new stream template
@param template_reference The old stream template
@return True if the templates match, False otherwise
"""
if len(template_dest) !... |
def utf8(astring):
"""Ensure string is utf8"""
return astring.strip().encode("utf-8").decode("utf-8","ignore") |
def is_palindrome_string(string):
"""Return whether `string` is a palindrome, ignoring the case.
Parameters
----------
string : str
The string to check.
Returns
-------
bool
A boolean representing whether `string` is a palindrome or not.
"""
# begin solution
re... |
def insertionSort(ll=[]):
"""The in-place insertionSort algorithm
"""
for i in range(1, len(ll)):
for j in range(0, i):
if ll[i] < ll[j]:
t = ll[i]
for k in range(i, j, -1):
ll[k] = ll[k-1]
ll[j] = t
bre... |
def format_time(elapsed):
"""Formats elapsed seconds into a human readable format."""
hours = int(elapsed / (60 * 60))
minutes = int((elapsed % (60 * 60)) / 60)
seconds = int(elapsed % 60)
rval = ""
if hours:
rval += "{0}h".format(hours)
if elapsed > 60:
rval += "{0}m".form... |
def _get_length_length(_bytes):
"""Returns a count of bytes in an Ion value's `length` field."""
if (_bytes[0] & 0x0F) == 0x0E:
# read subsequent byte(s) as the "length" field
for i in range(1, len(_bytes)):
if (_bytes[i] & 0x80) != 0:
return i
raise Exception... |
def get_filters(content):
"""
Get filter names from the token's content.
WARNING: Multiple filters can be used simultaneously, e.g.:
{{ some_list|safeseq|join:", " }}
:content: String; the token's content
:returns: a list of filter names
"""
filters = []
split_content = content... |
def transform_none(val, *none_vals):
"""
Transform to None
<dotted>|none None if not val else val
<dotted>|none::hello None if val in ('', 'hello') else val
"""
if not none_vals:
return None if not val else val
return None if val in none_vals else val |
def _DocToArgs(doc):
"""Converts a docstring documenting arguments into a dict.
.. image:: _static/adb.common_cli._DocToArgs.CALLER_GRAPH.svg
Parameters
----------
doc : str
The docstring for a method; see `MakeSubparser`.
Returns
-------
out : dict
A dictionary of arg... |
def fib(n):
""" F(n) = F(n - 1) + F(n - 2) """
if n < 2:
return n
else:
return fib(n-1) + fib(n-2) |
def part_device(part_number):
"""Given partition number (but string type), return the device for that
partition."""
return "/dev/mmcblk0p" + part_number |
def freq_to_maf(freq):
""" Convert allele frequency to minor allele freq
"""
return min(freq, 1-freq) |
def split_spec(spec, sep):
"""Split a spec by separator and return stripped start and end parts."""
parts = spec.rsplit(sep, 1)
spec_start = parts[0].strip()
spec_end = ''
if len(parts) == 2:
spec_end = parts[-1].strip()
return spec_start, spec_end |
def negative_accounts(row):
"""
After joining accounts payable and receivable, check for negative values.
Convert negative values to positive to move to the opposite cashflow type.
Example: Accounts payable on June 2021 is -100 while accounts receivable is 50.
Then set accounts payable that month t... |
def split_and_sum(expression) -> float:
"""Avoid using literal_eval for simple addition expressions."""
split_vals = expression.split('+')
float_vals = [float(v) for v in split_vals]
total = sum([v for v in float_vals if v > 0.0])
return total |
def empty(obj):
""" * is the object empty?
* returns true if the json object is empty
"""
if not obj:
# Assume if it has a length property with a non-zero value
# that that property is correct.
return True
if len(obj) > 0:
return False
if len(obj) == 0:
... |
def flatten(v):
"""
Flatten a list of lists/tuples
"""
return [x for y in v for x in y] |
def retrieve_all_parameters(parameter_info_dict):
"""Retrieve all parameters from parameter dictionary."""
return sorted({x for v in parameter_info_dict.values() for x in v}) |
def serialise_colour(colour, context=None):
"""Serialise a Colour value.
colour -- 'b' or 'w'
"""
if colour not in ('b', 'w'):
raise ValueError
return colour.upper().encode('ascii') |
def GetProQ3Option(query_para):#{{{
"""Return the proq3opt in list
"""
yes_or_no_opt = {}
for item in ['isDeepLearning', 'isRepack', 'isKeepFiles']:
if item in query_para and query_para[item]:
yes_or_no_opt[item] = "yes"
else:
yes_or_no_opt[item] = "no"
proq3... |
def pythonize_options(options):
"""
convert string based options into python objects/types
Args:
options: flat dict
Returns:
dict with python types
"""
def parse_string(item):
"""
check what kind of variable string represents and convert accordingly
Args... |
def selectflagpage(place, results):
"""Given a list of wikipedia page names, selects one with 'flag' or 'coat of arms' in the
title and returns it
:param place: The place who's flag is being searched for
:type plae: String
:param results: A list of search results
:type results: [String]
:... |
def remove_duplicates(li):
"""Removes duplicates of a list but preserves list order
Parameters
----------
li: list
Returns
-------
res: list
"""
res = []
for e in li:
if e not in res:
res.append(e)
return res |
def ctestReportCPUTime(cpuTime, oss=None):
"""write ctest tag for timing"""
tag = '<DartMeasurement name="CPUTime" type="numeric/double"> %f </DartMeasurement>'%(cpuTime)
if oss is not None:
oss.write(tag)
return tag |
def lays_in(a, b):
""" Lays cube a completely in cube b? """
axf, axt, ayf, ayt, azf, azt = a
bxf, bxt, byf, byt, bzf, bzt = b
return(
bxf <= axf <= axt <= bxt and
byf <= ayf <= ayt <= byt and
bzf <= azf <= azt <= bzt) |
def GetRegionFromZone(zone):
"""Returns the GCP region that the input zone is in."""
return '-'.join(zone.split('-')[:-1]) |
def _convert_to_float_if_possible(s):
"""
A small helper function to convert a string to a numeric value
if appropriate
:param s: the string to be converted
:type s: str
"""
try:
ret = float(s)
except (ValueError, TypeError):
ret = s
return ret |
def normalize_response(response):
"""Normalize the given response, by always returning a 3-element tuple
(status, headers, body). The body is not "resolved"; it is safe
to call this function multiple times on the same response.
"""
# Get status, headers and body from the response
if isinstance(r... |
def get_destination_from_obj(destination):
"""Helper to get a destination from a destination, event, or tour.
For events and tours, return the first related destination, if any."""
if hasattr(destination, 'first_destination'):
# tour with related destination(s); use the ordered first
retur... |
def pil_coord_to_tesseract(pil_x, pil_y, tif_h):
""" Convert PIL coordinates into Tesseract boxfile coordinates:
in PIL, (0,0) is at the top left corner and
in tesseract boxfile format, (0,0) is at the bottom left corner.
"""
return pil_x, tif_h - pil_y |
def index_first_char_not_equal_to(value: str, char: str, start_index: int = 0) -> int:
"""Returns the index of the first character in string 'value' not containing the character provided by 'char' starting at index start_index."""
for i in range(start_index, len(value)):
if value[i] != char:
return i
re... |
def rstrip_line(line):
"""Removes trailing whitespace from a string (preserving any newline)"""
if line[-1] == '\n':
return line[:-1].rstrip() + '\n'
return line.rstrip() |
def next_nuc(seq, pos, n):
""" Returns the nucleotide that is n places from pos in seq. Skips gap symbols.
"""
i = pos + 1
while i < len(seq):
if seq[i] != '-':
n -= 1
if n == 0: break
i += 1
if i < len(seq) :
return seq[i]
else :
return 'N... |
def AlignMatches(matches):
"""
Tallys up each dif's song id frequency and returns the song id with highest count diff
Args:
matches: list of tuples containing (song id, relative offset) matched from known song
Returns:
songId (int)
"""
diffMap = {}
largestCount = 0
song... |
def remove_dot_segments(path):
"""Remove '.' and '..' segments from a URI path.
Follows the rules specified in Section 5.2.4 of RFC 3986.
"""
output = []
while path:
if path.startswith('../'):
path = path[3:]
elif path.startswith('./'):
path = path[2:]
... |
def list_strip_all_newline(list_item: list) -> list:
"""
Strips all newline characters '\n' from all list_items in list object.
:param list_item: A list object to be cleaned from newline characters.
:return list: A list object which has been cleaned.
"""
return list(map(lambda x: x.strip('\n'),... |
def set_accuracy_95(num: float) -> float:
"""Reduce floating point accuracy to 9.5 (xxxx.xxxxx).
Used by Hedron and Dihedron classes writing PIC and SCAD files.
:param float num: input number
:returns: float with specified accuracy
"""
# return round(num, 5) # much slower
return float(f"{n... |
def inteiro_para_peca(n):
"""
Funcao de alto nivel.
Recebe um inteiro e devolve um jogador 'X', 'O', ou ' ' (livre), dependendo se o inteiro e
1, -1 ou 0 (livre), respetivamente.
:param n:
:return:
"""
int_peca = {1: 'X', -1: 'O', 0: ' '}
return int_peca[n] |
def is_iterable(x):
"""Check if variable is iterable
"""
try:
iter(x)
except TypeError:
return False
else:
return True |
def min_conv(time):
""" converts time into minutes, used for sort and format
"""
hh, mm = time.split(":")
minutes = (int(hh)*60 + int(mm))
return minutes |
def load_cands(path, lines_have_ids=False, cands_are_replies=False):
"""Load global fixed set of candidate labels that the teacher provides
every example (the true labels for a specific example are also added to
this set, so that it's possible to get the right answer).
"""
if path is None:
r... |
def set_bit(value: int, bit: int) -> int:
"""Set n-th bit of value.
Args:
value: Number to set bit.
bit: Bit number.
Returns:
Value with set n-th bit.
Example:
>>> bin(set_bit(0b11011, 2))
'0b11111'
"""
return value | (1 << bit) |
def word_idx(sentences):
"""
sentences should be a 2-d array like [['a', 'b'], ['c', 'd']]
"""
word_2_idx = {}
for sentence in sentences:
for word in sentence:
if word not in word_2_idx:
word_2_idx[word] = len(word_2_idx)
idx_2_word = dict(zip(word_2_idx.... |
def get_taskid_atmptn(key_name):
"""
get jediTaskID and attemptNr from task attempt key name
"""
tmp_list = key_name.split('#')
jediTaskID = int(tmp_list[0])
attemptNr = int(tmp_list[1])
return jediTaskID, attemptNr |
def block_distance(p1, p2):
"""
Returns the Block Distance of a particular point from rest of the points in dataset.
"""
distance = 0
for i in range(len(p1)-1):
distance += abs(p1[i]-p2[i])
return distance |
def build_subprotocol_list(protocols):
"""
Unparse a ``Sec-WebSocket-Protocol`` header.
This is the reverse of :func:`parse_subprotocol_list`.
"""
return ', '.join(protocols) |
def gauss(x, sig):
"""
Samples the value at a single point from the Gaussian Curve, parameterized
using the sig value as its sigma.
x - Relative positioning along the curve, which is centered at x = 0.
sig - Sigma parameter.
"""
from math import pi as PI;
from math import exp;
return exp(-(x ** 2 / 2 * sig... |
def digits_to_int(D,B=10,bigendian=False):
"""
Convert a list of digits in base B to an integer
"""
n = 0
p = 1
if bigendian:
for d in D:
n += d*p
p *= B
return n
else:
for d in reversed(D):
n += d*p
... |
def get_wonderful_numbers(given_str):
"""
Return all of the wonderful numbers for the given numeric string
"""
wonderfuls = []
# get permutations
# add permutation to wonderfuls if greater than given_str
return wonderfuls |
def extract_first_authors_name(author_list):
"""
Extract first name from a string including list of authors in form Author1; Author2; ...; AuthorN
"""
return author_list.split(';')[0].split(' ')[0] |
def int_sqrt(n: int) -> int:
"""
Returns the integer square root of n.
:param n: an int value
:return: the integer square root
"""
try:
from math import isqrt
return isqrt(n)
except ImportError:
# For Python <=3.7
if n < 0:
raise ValueError("Squa... |
def replace_list(text_string: str):
"""Quick formatting of Gamma point"""
substitutions = {'GAMMA': u'$\\Gamma$'}
for item in substitutions.items():
text_string = text_string.replace(item[0], item[1])
return text_string |
def extrap_total_training_time(time_unit, percent_complete):
"""
10 * (1/0.01) => 100
#
10 seconds in 1% 0.01
->
1000 seconds in 100% 1.0
:param time_unit:
:param percent_complete:
:return:
"""
assert 0. <= percent_complete <= 1.
total_time_unit = time_unit * (1./percen... |
def m12_to_mc(m1, m2):
"""convert m1 and m2 to chirp mass"""
return (m1 * m2) ** (3.0 / 5.0) / (m1 + m2) ** (1.0 / 5.0) |
def fp_field_name(name):
"""Translates literal field name to the sanitized one feedparser will use."""
return name.replace(':', '_').lower() |
def worker_should_exit(message):
"""Should the worker receiving 'message' be terminated?"""
return message['should_exit'] |
def format_size(bytes_):
"""
Format a size in bytes with binary SI prefixes.
:param bytes_:
:return:
"""
suffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
index = 0
start = 1
while bytes_ >= start * 1024:
start *= 1024
index += 1
return "%.2f %s" % (by... |
def _select_index_code(code):
"""
1 - sh
0 - sz
"""
code = str(code)
if code[0] == '3':
return 0
return 1 |
def sleeping_func(arg, secs=10, result_queue=None):
"""This methods illustrates how the workers can be used."""
import time
time.sleep(secs)
if result_queue is not None:
result_queue.put(arg)
else:
return arg |
def decimal_to_ip(ip_decimal):
"""
Submit a decimal ip value between 0 and 2*32 - 1.
Returns the ip_address as a zeros padded string: nnn.nnn.nnn.nnn
If ip_decimal is invalid returns -1
"""
# Test it is decimal and in range, else return -1
try:
ip_decimal = int(ip_decimal)
e... |
def unzip(lll):
"""Does the opposite of zip"""
return list(zip(*lll)) |
def _to_datauri(
mimetype, data, charset: str = 'utf-8', base64: bool = False, binary: bool = True
) -> str:
"""
Convert data to data URI.
:param mimetype: MIME types (e.g. 'text/plain','image/png' etc.)
:param data: Data representations.
:param charset: Charset may be any character set registe... |
def match_outside(x, y, i, j):
"""
Match whether the token is outside the entity
:param x: The start of the entity
:param y: The end of the entity
:param i: The start of the token
:param j: The end of the token
"""
return i <= x and j >= y |
def normalize_url(url):
"""Return url after stripping trailing .json and trailing slashes."""
if url.endswith('.json'):
url = url[:-5]
if url.endswith('/'):
url = url[:-1]
return url |
def try_except(success, failure):
"""A try except block as a function.
Note:
This is very similar to toolz.functoolz.excepts, but this version is
simpler if you're not actually passing in any arguments. So, I can't
bring myself to change existing uses of this to use
toolz.iterto... |
def _TaskPathToId(path):
"""Transforms the pathname in YAML to an id for a task.
Args:
path: Path name.
Returns:
id of the task.
"""
return '<joiner>'.join(path) |
def _expSum(x, iterations=1000):
"""Calculate e^x using power series.
exp x := Sum_{k = 0}^{inf} x^k/k! = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...
Which can be rewritten as:
= 1 + ((x/1)(1 + (x/2)(1 + (x/4)(...) ) ) )
This second way of writting it is easier to calc... |
def func_b(y):
"""
This function takes one param y
:param y: Takes any input
:return: Returns the same input
"""
print("Inside func_b")
return y |
def create_inventory(items):
"""
:param items: list - list of items to create an inventory from.
:return: dict - the inventory dictionary.
"""
return {item: items.count(item) for item in list(dict.fromkeys(items))} |
def _deep_merge_dictionaries(a, b, path=None):
"""merges b into a. Adapted from
https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries/7205107#7205107"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isi... |
def get_parent_language_code(parent_object):
"""
.. versionadded:: 1.0
Return the parent object language code.
Tries to access ``get_current_language()`` and ``language_code`` attributes on the parent object.
"""
if parent_object is None:
return None
try:
# django-parler u... |
def list_contains(lst: list, items_to_be_matched: list) -> bool:
"""Helper function for checking if a list contains any elements of another list"""
for item in items_to_be_matched:
if item in lst:
return True
return False |
def _replace_third_person(narrative: str, given_name: str, narr_metadata: dict) -> str:
"""
Update the text to change 3rd person instances of full name, given name + maiden name and
given name + surname to "Narrator", and the possessive form to "Narrator's".
@param narrative: String holding the narrati... |
def not_equal(a,b):
""" return 1 if True, else 0 """
if(a != b):
return 1
else:
return 0 |
def even_modulo(value: int) -> int:
"""
Returns a value if it is even
:param value: the value to check
:return: the even value or -1 if not even
"""
if not value % 2:
return value
return -1 |
def get_xpath_parent(xpath, level=1):
""" Get the parent xpath at any level, 1 is parent just above the input xpath.
Args:
xpath (str): Input xpath
level (int, optional): Parent level. Defaults to 1.
Returns:
str: Parent xpath
"""
if not xpath.startswith("/"):
rais... |
def convertToRavenComment(msg):
"""
Converts existing comments temporarily into nodes.
@ In, msg, string contents of a file
@ Out, string, converted file contents as a string (with line seperators)
"""
msg=msg.replace('<!--','<ravenTEMPcomment>')
msg=msg.replace('-->' ,'</ravenTEMPcomment>')
retur... |
def _parent(node):
"""
Args:
node: index of a binary tree node
Returns:
index of node's parent
"""
return (node - 1) // 2 |
def mock_dag_literal_module_complex():
"""Creates a mock DAG."""
dag_ldict = [
{
"frame": {"name": "A", "type": "function"},
"metrics": {"time (inc)": 130.0, "time": 1.0, "module": "main"},
"children": [
{
"frame": {"name": "B", "ty... |
def find_duplicate_num_array(l1):
""" an array contains n numbers ranging from 0 to n-1. there are some numbers duplicated, but it is
not clear how many. this code find a duplicate number in the array. """
""" A naive solution is to sort the input array, costing O(nlogn). Another solution is the utili... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.