content stringlengths 42 6.51k |
|---|
def recipStep(y, x):
"""Perform one step of reciprocal algorithm."""
return 2*x - y*(x**2); |
def _get_text( row, attr ):
"""
Get the row from a dataframe
"""
return "" if type( row[ attr ] ) is float else str( row[ attr ] ) |
def mask_val(val, width):
"""mask a value to width bits"""
return val & ((1 << width) - 1) |
def dictRemove(dict, keys):
""" Remove dict values who has a key in keys"""
for key in keys:
dict.pop(key)
return dict |
def replace_forward_slash(file_name):
"""
This method takes a string representing a file name and replaces forward slashes with ":"
This approach is consistent with how other clients deal with attempts to upload files with forward slashes
in the name.
"""
return file_name.replace("/", ":") |
def champion_dictionary(obj):
"""Converts champion.json to a dictionary that is useful to us."""
champions = {}
for champion in obj["data"]:
name = champion.lower()
champions[int(obj["data"][champion]["key"])] = name
return champions |
def compact_address_range(r):
""" Compact address ranges
Input: list of pairs of address ranges
Output: (nothing)
Returns: compacted list of pairs of address ranges
"""
x = list(r[:])
x.sort()
j = 0
y = []
y.append(list(x[0]))
for i in range(len(x) - 1):
if (x[i][-1] ... |
def get_pi0(pv, lambdas):
"""
Compute Storey's C{pi0} from p-values C{pv} and C{lambda}.
this function is equivalent to::
m = len(pv)
return [sum(p >= l for p in pv)/((1.0-l) * m) for l in lambdas]
but the above is C{O(m*n)}, while it needs only be C{O(m+n)
(... |
def get_min_temp(results):
"""Returns the minimum temp for the given hourly weather objects."""
min_temp = 100000
for forecast in results:
min_temp = min(forecast['temp'], min_temp)
return min_temp |
def get_split_ind(seq, N):
"""seq is a list of words. Return the index into seq such that
len(' '.join(seq[:ind])<=N
"""
sLen = 0
# todo: use Alex's xrange pattern from the cbook for efficiency
for (word, ind) in zip(seq, list(range(len(seq)))):
sLen += len(word) + 1 # +1 to account for... |
def readable_list(elements, liaison='and'):
""" Creates a readable sentence by joining elements of a list
Args:
elements (:obj:`list` of :obj:`str`): elements to join together
liaison (`str`, optional, 'and'): liaison to use to join elements
Returns:
`str` A human readable sentence... |
def s_(xT): # pragma: no cover
""" derivative of saturation vapor pressure: kPa / C
Paw U and Gao (1987) Ag For Met 43:121-145
Applicaitons of solutions to non-linear energy budget equations
:param xT - temperature (C):
:return:
"""
return (42.22 + 2 * 1.675 * xT + 3 * 0.01408 * xT... |
def name_test(item):
""" used for pytest verbose output """
p = item['params']
return f"{p['peer_device']} role={p['role']} via={p['peer_ip']}" |
def team_distance(str):
"""
function to weight teams distance from tournament for use
in sorting teams prior to scheduling; higher weighted numbers give a team's
request priority.
team = a str with city and state (ex. 'Charleston, SC')
current weights are setup with Charleston, SC as t... |
def compute_sum(n, total):
"""
Compute the total sum range 0 to n
"""
# print(n)
# base case, if you reach n is 0 then you want to return it
print(total[0])
if n == 0:
return 0
total[0] = total[0] + compute_sum(n-1, total)
# else the previous value + (n - 1)
# return ... |
def pos_to_index(mouse_col, mouse_row, labels_positions):
"""
convert label's position to it's index
"""
if 550 <= mouse_row <= 600 and 0 <= mouse_col <= 200:
return 'mode_changed'
if 580 <= mouse_row <= 600 and 430 <= mouse_col <= 440:
return 'back_changed-'
if 580 <= ... |
def drop_hash_comment(line):
""" Getting a line with '#' comment it drops the comment.
Note that JSON does not support comments, but gyp
with its JSON-like syntax (really just a Python dict)
does support comments.
Should this func be aware of hashes in double quotes?
Atm it's... |
def night_to_month(night):
"""
Trivial function that returns the month portion of a night. Can be given a string or int.
Args:
night, int or str. The night you want the month of.
Returns:
str. The zero-padded (length two) string representation of the month corresponding to the input mo... |
def create_graphics(graphics: list) -> str:
"""Function to transform a list of graphics dicts (with lines and fill
rectangles) into a PDF stream, ready to be added to a PDF page stream.
Args:
graphics (list): list of graphics dicts.
Returns:
str: a PDF stream containing the passed grap... |
def TransformEventData(event_data):
"""Takes Event object to new specification."""
new_event_data = {}
new_event_data['summary'] = event_data['summary']
new_event_data['description'] = event_data['description']
# Where
new_event_data['location'] = event_data['location']
# When
start = event_data['whe... |
def parse_vertex(text):
"""Parse text chunk specifying single vertex.
Possible formats:
vertex index
vertex index / texture index
vertex index / texture index / normal index
vertex index / / normal index
"""
v = 0
t = 0
n = 0
chunks = text.split("/")
v... |
def tokenize_line(line):
"""
Tokenize a line:
* split tokens on whitespace
* treat quoted strings as a single token
* drop comments
* handle escaped spaces and comment delimiters
"""
ret = []
escape = False
quote = False
tokbuf = ""
ll = list(line)
while len(ll) > 0:
... |
def _tuples_native(S, k):
"""
Return a list of all `k`-tuples of elements of a given set ``S``.
This is a helper method used in :meth:`tuples`. It returns the
same as ``tuples(S, k, algorithm="native")``.
EXAMPLES::
sage: S = [1,2,2]
sage: from sage.combinat.combinat import _tuple... |
def remove_whitespace(s):
"""Remove excess whitespace including newlines from string
"""
words = s.split() # Split on whitespace
return ' '.join(words) |
def colorCalculator(hex):
"""
Converts an RGB hex string into a tuple of (R, G, B) values from 0 to 1.
Args:
hex (str): hex value of color.
Returns:
tuple: tuple (R, G, B) of values from 0 to 1.
"""
# check for pound-sign
if hex[0] == "#":
hex = hex[1:]
# first,... |
def get_taxonomies_by_meta(data):
"""
Reads from the dict via
meta -> taxonomies
"""
return data["meta"]["taxonomies"] |
def convert_gdml_unit(unit):
"""Convert a GDML unit to MCNP system"""
units = {"m": 1E+02, "cm": 1., "mm": 1E-01, "g/cm3": 1.}
return units[unit] |
def add_text_col(example: dict) -> dict:
"""constructs text column to news article"""
example["text"] = ""
if example["Heading"].strip(" "):
example["text"] = example["Heading"]
if example["SubHeading"].strip(" "):
example["text"] += f'\n {example["SubHeading"]}'
# if example["Publis... |
def is_sorted(arr):
""" assert array is sorted """
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) |
def is_none_or_empty(arg):
"""
purpose:
check if the arg is either None or an empty string
arguments:
arg: varies
return value: Boolean
"""
try:
return arg is None or arg == ""
except Exception:
return False |
def NDD_eval(xi, dd, xd):
"""Evaluar el polinomio interpolante.
Args:
dd : array
Diferencias divididas
xi : list or array
Valores donde quiero evaluar al polinomio
xd : list or array
Valores X interpolados
Returns:
y : list or array
Valores del polinomio en x... |
def count_padding_bases(seq1, seq2):
"""Count the number of bases padded to
report indels in .vcf
Args:
seq1 (str): REF in .vcf
seq2 (str): ALT in .vcf
Returns:
n (int):
Examples:
REF ALT
GCG GCGCG
By 'left-alignment', REF ... |
def check_redirect_uris(uris, client_type=None):
"""
This function checks all return uris provided and tries to deduce
as what type of client we should register.
:param uris: The redirect URIs to check.
:type uris: list
:param client_type: An indicator of which client type you are expecting
... |
def string_to_env(string: str):
"""
Overview:
Turn string ``KEY=VALUE`` to key-value tuple.
Arguments:
- string (:obj:`str`): Original key-value string.
Returns:
- (key, value): key and value
Examples::
>>> from pyspj.utils import string_to_env
>>> string_t... |
def recursive_merge(source, destination):
"""
Recursively merge dictionary in source with dictionary in
desination. Return the merged dictionaries.
Stolen from:
https://stackoverflow.com/questions/20656135/python-deep-merge-dictionary-data
"""
for key, value in source.items():
if isi... |
def RemoveBadCarac(mot):
"""
remove a list of bad carac in a word
"""
bad_carac = [",", "*", "'", "]", "[", "-", "!", "?", " ", '', "(", ")", "//", ".", '-']
mot_propre = list()
for carac in mot:
if carac not in bad_carac and not carac.isnumeric():
mot_propre.append(carac)
... |
def render_build_args(options, ns):
"""Get docker build args dict, rendering any templated args.
Args:
options (dict):
The dictionary for a given image from chartpress.yaml.
Fields in `options['buildArgs']` will be rendered and returned,
if defined.
ns (dict): the namespace used... |
def store(value=None, addr=None, heap=None):
"""Symbolic accessor for the store command"""
return '!', value, addr, heap |
def split_docker_domain(name):
"""Split Docker image name to domain and remainder part.
Ported from https://github.com/distribution/distribution/blob/v2.7.1/reference/normalize.go#L62-L76.
Args:
name (str): Docker image name.
Returns:
str: Docker registry domain.
str: Remainde... |
def cpp_escape_name(name):
"""Escape package name to be CPP macro safe."""
return name.replace("-", "_") |
def is_local(path: str) -> str:
"""Return valid URL path for file
Args:
path (str): normal path or URL
Returns:
str: Modified file path if local file
Returns path as it is if URL
"""
import os
URL = path
if os.path.exists(path) or path.startswith("file"):
... |
def get_iterable(x):
"""Helper function to ensure iterability."""
if isinstance(x, str):
return (x,)
else:
try:
iter(x)
except TypeError:
return (x,)
return x |
def is_fragment(href):
"""Return True if href is a fragment else False"""
is_fragment = False
try:
if href[0] == '#':
is_fragment = True
except IndexError:
is_fragment = False
return is_fragment |
def merge_sorted_lists( l1, l2):
"""
:param l1: ListNode 1 head
:param l2: ListNode 2 head
:return: merged L head
"""
if not l1 or not l2:
return l1 or l2
if l1.val <= l2.val:
main = l1
sub = l2
else:
main = l2
sub = l1
last = main
while su... |
def _quick_sort_in(input_data):
"""
Intern method for quicksort
"""
if input_data == []:
return []
else:
pivot = input_data[0]
first = _quick_sort_in([x for x in input_data[1:] if x < pivot])
second = _quick_sort_in([x for x in input_data[1:] if x > pivot])
re... |
def table_log_format(name, timestamp, data):
""" Return a formatted string for use in the log"""
return str(str(name) + '&' + str(timestamp) + '->[' + str(data) + ']') |
def _str_date(time):
"""
Transfer date to str.
Args:
time(datetime.datetime): time input.
"""
return str(time.date()) if time else None |
def md(pArray1, pArray2, pFunc, axis=0):
"""
Map _by dot product_
"""
if bool(axis):
pArray1, pArray2 = pArray1.T, pArray2.T
iRow1 = len(pArray1)
iRow2 = len(pArray2)
assert(iRow1 == iRow2)
aOut = []
for i, item in enumerate(pArray1):
aOut.append(pFunc(item, pArray2[i]))
return aOut |
def _get_quote_state(token, quote_char):
"""
the goal of this block is to determine if the quoted string
is unterminated in which case it needs to be put back together
"""
# the char before the current one, used to see if
# the current character is escaped
prev_char = None
for idx, cur_c... |
def sum_2_cpdicts(cpdict_a,cpdict_b):
"""
Sum 2 dicts of cpdict and store the result in the second parameter
"""
for item in cpdict_a.keys():
if item not in cpdict_b.keys():
cpdict_b[item] = dict(cpdict_a[item])
else:
for chords in cpdict_a[item].keys():
... |
def solution(S): # O(N)
"""
Given a string S of upper case characters, from which you have to retrieve
the 7 letters:
"B", "A", "L", "L" "O", "O", "N"
Return how many times you can retrieve these characters from string S.
>>> solution('AGEASEB... |
def toansi(text):
""" Encode special characters """
trans = {'{': r'\{',
'}': r'\}',
'\\': r'\\',
'|': r'\|',
}
out = ''
for char in text:
if char in trans:
out += trans[char]
elif ord(char) < 127:
out += char
... |
def start_new_game(player1, player2):
"""
Creates and returns a new game configuration.
"""
board = [['-']*3 for _ in range(3)]
game = {
'player1': player1,
'player2': player2,
'board': board,
'next_turn': player1,
'winner': None
}
return game |
def name_score(name: str) -> int:
"""Get the score of the input name."""
return sum(ord(char) - 64 for char in name) |
def _PortValue(value):
"""Returns True if port value is an int within range or 'default'."""
try:
return value == 'default' or (1 <= int(value) <= 65535)
except ValueError:
return False |
def get_alias_from_index(index_name):
""" The indexes are named as `alias_suffix` """
return index_name.split("_",1)[0] |
def pick_all(keys, dict):
"""Similar to pick except that this one includes a key: undefined pair for
properties that don't exist"""
picked_dict = {}
for k in keys:
picked_dict[k] = None
if k in dict:
picked_dict[k] = dict[k]
return picked_dict |
def update_dictionary(dictionary, key, value):
"""
Add the key-value pair to the dictionary and return the dictionary.
:dictionary: dict object
:key: String (e.g. module name)
:value: Integer (e.g. line number)
:returns: dict object
"""
if key not in dictionary:
dictionary[key] ... |
def split_virtual_offset(virtual_offset):
"""Divides a 64-bit BGZF virtual offset into block start & within block offsets.
>>> (100000, 0) == split_virtual_offset(6553600000)
True
>>> (100000, 10) == split_virtual_offset(6553600010)
True
"""
start = virtual_offset >> 16
return start, v... |
def calculateAccuracy(tn, fp, fn, tp):
"""
return the accuracy based on the confusion matrix values
:param tn: Quantity of True negative
:param fp: Quantity of False positive
:param fn: Quantity of False negative
:param tp: Quantity of True positive
:type tn: int - required
:type fp: i... |
def basic_open(file):
"""Open and read a file."""
with open(file, 'r', encoding="utf=8") as f:
f = f.readlines()
return f |
def from_sql(row):
"""Translates an SQLAlchemy model instance into a dictionary."""
if not row:
return None
data = row.__dict__.copy()
data['id'] = row.id
data.pop('_sa_instance_state')
return data |
def escapeDoubleQuoteInSQLString(string, forceDoubleQuote=True):
"""
Accept true database name, schema name, table name, escape the double quote
inside the name, add enclosing double quote by default.
"""
string = string.replace('"', '""')
if forceDoubleQuote:
string = '"' + string + '"... |
def _get_edges(value, last_value, mask):
"""
Given two integer values representing a current and a past value,
and a bit mask, this function will return two
integer values representing the bits with rising (re) and falling (fe)
edges.
"""
changed = value ^ last_value
re = changed & value... |
def decode_punycode(thebytes: bytes):
"""Decodes the bytes string using Punycode.
Example:
>>> encode_punycode('hello')\n
b'hello-'
>>> decode_punycode(b'hello-')\n
'hello'
"""
import codecs
if isinstance(thebytes, bytes):
temp_obj = thebytes
return co... |
def check_input(s):
"""
This function checks the input is in correct format or not
:param s: The input string of each row
:return: (bool) If the input format is correct
"""
for i in range(len(s)):
if i % 2 == 1 and s[i] != ' ':
return True
elif len(s) != 7:
return True
elif i % 2 == 0 and s[i].isalpha... |
def hard_threshold(x):
"""
Returns an hard threshold which returns 0 if sign = -1 and 1 otherwise.
This let the combination of multiple perceptron with uniform input
:param x: + or - 1
:return: 1 for positive, 0 for negative
"""
return 0 if x <= 0.5 else 1 |
def is_criticality_balanced(temperature: int, neutrons_emitted: int) -> bool:
"""
:param temperature: int - Temperatur of the reactor core
:param neutrons_emitted: int - Neutrons emitted per second
:return: boolean True if conditions met, False if not
A reactor is said to be critical if it satisfi... |
def get_headers(token):
"""Return HTTP Token Auth header."""
return {"x-rh-identity": token} |
def get_simulation_length_info(
units,
prop_freq,
coord_freq,
run_length,
steps_per_sweep=None,
block_avg_freq=None,
):
"""Get the Simulation_Length_Info section of the input file
Parameters
----------
units : string
'minutes', 'steps', or 'sweeps'
prop_freq : int
... |
def to_currency(cents: int) -> str:
"""Convert a given number of cent into a string formated dollar format
Parameters
----------
cents : int
Number of cents that needs to be converted
Returns
-------
str
Formated dollar amount
"""
return f"${cents / 100:.2f}" |
def contrasting_hex_color(hex_str):
""" Pass string with hash sign of RGB hex digits.
Returns white or black hex code contrasting color passed.
"""
(r, g, b) = (hex_str[1:3], hex_str[3:5], hex_str[5:])
return '#000000' if 1 - (int(r, 16) * 0.299 + int(g, 16) * 0.587 +
... |
def create_rules(lines):
"""
Given the list of line rules, create the rules dictionary.
"""
rules = dict()
for line in lines:
sline = line.split()
rules[sline[0]] = sline[-1]
return rules |
def convertFloat(s):
"""Tells if a string can be converted to float and converts it
Args:
s : str
Returns:
s : str
Standardized token 'FLOAT' if s can be turned to an float, s
otherwise"""
try:
float(s)
return "FLOAT"
except:
return s |
def format_sizeof(num, suffix='bytes'):
"""
Readable size format, courtesy of Sridhar Ratnakumar
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1000.0:
return '{0:3.1f}{1}{2}'.format(num, unit, suffix)
num /= 1000.0
return '{0:.1f}Y{1}'.format(num,... |
def count_val_size_in_dict(result):
"""
expects a dict with keys which map to lists
sums the size of all lists in the dict
@param result: a dict where each key maps to a list
@return: the summed size of all lists
"""
amount = 0
for k, values in result.items():
amount += len(value... |
def check_placement(ship_placement, ship_number):
"""Returns true if ship placed inside the board"""
ships_position_check = [0,10,20,30,40,50,60,70,80,90]
if ship_placement > 99 or ship_placement < 0:
return False
if ship_number in [2,3,4]:
if ship_placement in ships_position_check:
... |
def shorten_str(text: str, width: int = 30, suffix: str = "[...]") -> str:
"""Custom string shortening (`textwrap.shorten` collapses whitespace)."""
if len(text) <= width:
return text
else:
return text[: width - len(suffix)] + suffix |
def validate_http_request(request):
""" Check if request is a valid HTTP request and returns TRUE / FALSE and the requested URL """
request = request.decode()
if request[0:3] == "GET":
if request[0:14] == "GET / HTTP/1.1":
return "GET", True, " "
else:
return "GET", T... |
def ID2ccc(ID, device_number=0):
"""
Turns a control ID into a combination of channel + cc.
>>> ID2ccc(0)
1, 0
>>> ID2ccc(1)
1, 1
>>> ID2ccc(127)
1, 127
>>> ID2ccc(128)
2, 0
>>> ID2ccc(2047)
16, 127
"""
ID -= device_number * 128 * 16
ID %= 128 * 16
return ... |
def addNums(a, b):
""" Adds two numbers and returns the result. """
c = a + b
return c |
def process_line(line):
""" Split a Line in key, value pairs """
key, value = line.partition("=")[::2]
return key, value.rstrip() |
def divide(x: float, y: float) -> float:
"""Divide :math:`x` by :math:`y`
Arguments
---------
x : float
First number
y : float
Second number.
Raises
------
ZeroDivisionError:
If the denominator is zero
Returns
-------
float
x / y
"""
... |
def markdown_image(url):
"""Markdown image markup for `url`."""
return ''.format(url) |
def k_to_c(tempk):
"""
Parameters
Temp (K)
Returns
Temp(C)
"""
tempc = tempk - 273.15
return tempc |
def divide_range(total_size: int, chunk_size: int = 1000):
"""
Break down the range into chunks of specific size.
Args:
total_size: The total size of the range
chunk_size: The size of each chunk
return:
list_ranges: A list of chunked range objects
"""
num_thousand, remain... |
def split_16bit(_16bit):
"""
Split a 16-bit value into a list of 8-bit values
in little endian format.
"""
return [_16bit & 0xFF, (_16bit >> 7) & 0xFF] |
def sliding_windows(periods):
""" Split into training and test sets, augment the data. """
x = []
y = []
for period in periods[:-3]:
p_index = periods.index(period)
x.append([])
x[-1].append([period[-2], period[-1]])
x[-1].append([periods[p_index + 1][-2], periods[p_inde... |
def minimum(a, b, *others):
"""The minimum value of all arguments"""
return min(a, b, *others) |
def eat_blank(Q):
"""Discards a sequence of blank chars at the top of Q"""
n = len(Q)
while Q:
if Q[0] in ' \t\n':
Q.popleft()
else:
break
return n - len(Q) |
def get_parents_iterative(child, child_2_parent_dict):
"""
par = {"C22":{"C1"}, "C21":{"C1"}, "C1":{"P1"}}
get_parents_iterative("C22", par)
"""
if child not in child_2_parent_dict:
return []
# important to set() otherwise parent is updated in orig object
all_parents = set(child_2_pa... |
def mm(mm):
"""Convert from millimeter values to rounded points
>>> mm(210)
595
>>> mm(297)
842
"""
return int(round(mm * 72 * 0.039370)) |
def _tester(func, *args):
"""
Tests function ``func`` on arguments and returns first positive.
>>> _tester(lambda x: x%3 == 0, 1, 2, 3, 4, 5, 6)
3
>>> _tester(lambda x: x%3 == 0, 1, 2)
None
:param func: function(arg)->boolean
:param args: other arguments
:return: something or none
... |
def updated_dict(dic1, dic2):
"""Return dic1 updated with dic2 if dic2 is not None.
Example
-------
>>> my_dict = updated_dict({"size": 7, "color": "r"}, some_defaults_dict)
"""
if dic2 is not None:
dic1.update(dic2)
return dic1 |
def perm_to_pattern(P,index=0):
"""
Convert the permutation P into a permutation
"""
if index not in (0,1):
raise Exception("index must be 0 or 1")
S = sorted(set(P))
D = {v:rank for rank,v in enumerate(S,index)}
return tuple([D[p] for p in P]) |
def convert_time_format(date_format):
"""
helper function to convert the data format that is used by the Cisco EoX API
:param date_format:
:return:
"""
if date_format == "YYYY-MM-DD":
return "%Y-%m-%d"
return "%Y-%m-%d" |
def UC_V(V_mm, A_catch, outUnits):
""" Convert volume from mm to m^3 or litres
Args:
V_mm: Float. Depth in mm
outUnits: Str. 'm3' or 'l'
A_catch: Float. Catchment area in km2
Returns:
Float. Volume in specified units.
"""
factorDict = {'m3':10**3, 'l':10**6}
... |
def find_payment(loan: float, rate: float, m: int):
"""
Returns the monthly payment for a mortgage of size
loan at a monthly rate of r for m months"""
return loan * ((rate * (1 + rate) ** m) / ((1 + rate) ** m - 1)) |
def _build_message(input_table, output_table, current_date):
"""Returns a JSON object containing the values of the input parameters.
Args:
input_table: A string containing the BQ table to read from
output_table: A string containing the BQ table to write to
current_date: The processing date to suffix th... |
def LoadPins(mapping,inp):
"""Organizes an input into a pin mapping dict
mapping <list>, ['IA','IB']
inp <dict>, <list>, <int> {'IA':1,'IB':2}, [1,2]
"""
if type(inp) is int and len(mapping) == 1:
return {mapping[0]:inp}
elif type(inp) is list and len(mapping) == len(inp):
o = {}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.