content stringlengths 42 6.51k |
|---|
def get_forecast_pct(lprice, fprice):
"""
Return the forecasted percentage price change
Args:
Double: Last price
Double: Forecast price
Returns:
Double: Forecasted percentage change
"""
if lprice != 0 and lprice is not None:
lpf = float(lprice)
fpf = float... |
def recognize_genshin_server(uid: int) -> str:
"""Recognize which server a Genshin UID is from."""
server = {
"1": "cn_gf01",
"2": "cn_gf01",
"5": "cn_qd01",
"6": "os_usa",
"7": "os_euro",
"8": "os_asia",
"9": "os_cht",
}.get(str(uid)[0])
if serve... |
def nernst(temperature):
"""
Description:
Calculates the value of the temperature dependent term of the Nernst
equation to provide the link between measured electrode potentials and
concentration. For use with the THSPH L2 data products (THSPHHC, THSPHHS,
THSPHPH), all of which ... |
def _key_is_valid(dictionary, key):
"""Test that a dictionary key exists and that it's value is not blank."""
if key in dictionary:
if dictionary[key]:
return True
return False |
def _get_file_prefix_and_postfix(filepath):
"""
Get file prefix and postfix from the filepath
If the file name in the filepath has not file extension the file is supposed to be a binary file
:param filepath: File name and full path
:return: prefix, postfix
"""
prefix = filepath.split('.')[0... |
def insertion_sort(arr):
"""
Insertion sort algoritm
"""
# Comparisons
comp = 0
# Move through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move els of [0, i-1] that are greater than key 1 pos ahead
# Move the key to the pos where it is bigger than the pr... |
def constructor_method_name_is_false_positive(constructor: str, line: str) -> bool:
"""Decides whether given constructor method is false positive.
if method does not contain "." in it (for example `getS()`) then it must be before it (`.getS()`)
if method contains "." then before it should not be alpha ... |
def addDicts(dict1, dict2):
"""Add dicts together by value. i.e. addDicts({"a":1,"b":0}, {"a":2}) == {"a":3,"b":0}."""
result = {k:v for k,v in dict1.items()}
for k,v in dict2.items():
if k in result:
result[k] += v
else:
result[k] = v
return result |
def to_usd(my_price):
"""
Converts a numeric value to usd-formatted string, for printing and display purposes.
Param: my_price (int or float) like 4000.444444
Example: to_usd(4000.444444)
Returns: $4,000.44
"""
return f"${my_price:,.2f}" |
def escape_xml_characters(data):
"""Return copy of string with XML special characters escaped.
This replaces the characters <, > and & with the XML escape
sequences <, > and &. It also replaces double
quotes with ".
This could be replaced in future by the
'xml.sax.saxutils.escape' function.... |
def construct_server_name(params, server_name_prefix):
"""
Construct and return a server name for the given prefix
:param params: The params dict containing the server base name
:param server_name_prefix: A string prefix to apply to the server base name
:return: Server name string
"""
return... |
def pbits(num: int, pad: int = 32) -> str:
"""Return the bits of `num` in binary with the given padding."""
return bin(num)[2:].zfill(pad) |
def reverse_bytes(hex_string):
"""
This function reverses the order of bytes in the provided string.
Each byte is represented by two characters which are reversed as well.
"""
#print 'reverse_bytes(' + hex_string + ')'
chars = len(hex_string)
if chars > 2:
return reverse_bytes(hex_st... |
def divisor_extract(row):
"""returns the quotient of the only evenly
divisible numbers in the list. This assumes
that they exist"""
for num in row:
for divisor in row:
if num % divisor == 0 and num != divisor:
return num / divisor
raise ValueError("Row does not ... |
def hide_highlight() -> dict:
"""Hides any highlight."""
return {"method": "DOM.hideHighlight", "params": {}} |
def make_params(vars):
"""quick hacky way to build body params
vars is locals() passed from each api endpoint, eg query_database().
This function copies every var if
- it's not 'self' or 'kw'
- not start with '_':
in case any api endpoint code need local var, it should start with... |
def merge_cluster(cluster_list, cluster_temp):
"""Code to merge a cluster into a cluster list
"""
cluster_list.append(cluster_temp)
merged_index = []
for i, cluster in reversed(list(enumerate(cluster_list))):
if bool(cluster.intersection(cluster_temp)):
cluster_temp = cluster_te... |
def daisy_replicator(alpha, alphag, beta, gamma):
"""Calculate the rate of change of a replicator (daisies). The formula is:
a*[ag*b-g]
which describes a logistic growth and constant death within a limited
resource system over time t.
Arguments
---------
alpha : float
alpha -- the ... |
def nice_string(ugly_string, limit=100):
"""Format and trims strings"""
return (ugly_string[:limit] + '..') if len(ugly_string) > limit else ugly_string |
def read_file( file_path ):
"""
Read data from file_path
Return non-None on success
Return None on error.
"""
try:
fd = open( file_path, "r" )
except:
return None
buf = None
try:
buf = fd.read()
except:
fd.close()
return None
try:
fd.close()
... |
def _format_list(param_name, list1, datadict, **kwargs):
"""Concatenate and format list items.
This is used to prepare substitutions in user-supplied args to the
various test invocations (ie: the location of flash).
Args:
@param param_name: The name of the item in `datadict`.
@param lis... |
def append_list(n):
"""
>>> append_list(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
s = []
for i in range(n):
s.append(i)
return s |
def Drop(x, **unused_kwargs):
"""Drops one element."""
del x # Just for the compiler.
return () |
def is_instance(list_or_dict) -> list:
"""Converts dictionary to list"""
# I use this because it make a data structures the same, no isinstance(), cuts down on code
if isinstance(list_or_dict, list):
make_list = list_or_dict
else:
make_list = [list_or_dict]
return make_list |
def moduleNeedsTests(modulename):
"""
Determine whether a module is a is a special module.
like __init__
"""
return not modulename.split(".")[-1].startswith("_") |
def rgb2hex(rgb):
"""Convert RGB to Hex color."""
h = '#%02x%02x%02x' % (int(rgb[0]*255),int(rgb[1]*255),int(rgb[2]*255))
return h |
def v3_uniques_only(iterable):
"""Return iterable in the same order but with duplicates removed.
We can make this faster by using a set...
Sets rely on hashes for lookups so containment checks won't slow down as
our hash grows in size. Notice we're building up both a list and a set
but we're check... |
def calc_distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""Calculate the distance between two points"""
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 |
def compare_json(json1,json2):
"""Compare Two JSON data structs to check if they're identical.
Args:
json1 (dict): json data
json2 (dict): json data
Returns:
(boolean): True if identical, False if not
"""
# Iterate Through First
for key, value in json1.items():
... |
def p_selection(p_init, it, num_iter):
""" Piece-wise constant schedule for p (the fraction of pixels changed on every iteration). """
it = int(it / num_iter * 10000)
if 10 < it <= 50: return p_init / 2
elif 50 < it <= 200: return p_init / 4
elif 200 < it <= 500: return p_init ... |
def external_question_xml(question_url):
"""Return AMT-formatted XML for external question.
See: https://docs.aws.amazon.com/AWSMechTurk/latest/AWSMturkAPI/
ApiReference_ExternalQuestionArticle.html
"""
question_xml = (
'<?xml version="1.0" encoding="UTF-8"?>'
'<ExternalQuestion xml... |
def ee_bands(collection):
"""
Earth Engine band names
"""
dic = {
'Sentinel2_TOA': ['B1','B2','B3','B4','B5','B6','B7','B8A','B8','B11','B12'],
'Landsat7_SR': ['B1','B2','B3','B4','B5','B6','B7'],
'Landsat8_SR': ['B1','B2','B3','B4','B5','B6','B7','B10','B11'],
'Crop... |
def normalize_whitespace(text):
"""
Remove redundant whitespace from a string.
"""
text = text.replace('"', '').replace("'", '')
return ' '.join(text.split()) |
def extractHash(val, typ="crc32c"):
"""
extract the crc32 from the string returned by an ls -L command
Args:
----
type: flag ['crc32c','md5']
"""
if ' Hash (crc32c):' in val and typ=="crc32c":
return val.split(' Hash (crc32c): ')[-1].split('\\\\n')[0].split('\\n')[0]
elif ' Ha... |
def reverse(text):
"""<string> -- Reverses <string>."""
return text[::-1] |
def p2f(x):
"""Convert percent string to float.
"""
return float(x.strip('%')) / 100. |
def clean_line(line):
""" Cleans a single line
"""
ret = line.replace('-', ' ').replace('.', '. ').strip()
return ret |
def format_name(movie_name):
"""Format movie name to use in file name
Input
-------
movie_name: the name of a movie
Output
-------
formatted file name
"""
return "_".join([x.lower() for x in movie_name
.replace(".", "")
.replace(":", "")
... |
def ParseSize(s):
"""
The reverse of SmartSize, this returns an integer based
on a value.
"""
scaler = {
'k' : 1024,
'm' : 1024 * 1024,
'g' : 1024 * 1024 * 1024,
't' : 1024 * 1024 * 1024 * 1024
}
try:
if s[-1] in list("kKmMgGtT"):
suffix = ... |
def dec2hex(d):
"""return a two character hexadecimal string representation of integer d"""
return "%02X" % d |
def currency_to_float(value):
"""Converte de R$ 69.848,70 (str) para 69848.70 (float)."""
try:
cleaned_value = value.replace("R$", "").replace(".", "").replace(",", ".")
return float(cleaned_value)
except ValueError:
pass
return |
def times_until_out_of_gp(gp: float) -> int:
"""Returns how often you can buy from the enchanted_armoire given some budget.
\f
:param gp:
:return:
"""
enchanted_armoire_price = 100
times: float = gp / enchanted_armoire_price
return int(times) |
def uniq(objectSequence):
""" returns a list with no duplicates"""
d = {}
for o in objectSequence:
d[id(o)] = o
return list(d.values()) |
def maybe_quote(value):
"""
Quote a value for InfluxDB if necessary.
"""
if value[0] == "'" and value[-1] == "'":
return value
return "'{}'".format(value) |
def _make_it_list(args: list) -> list:
"""
Make it list return all args element as list in a list.
:param list args: list of the argument to return as list
:return list: list of the args that are now list
"""
r = []
for x in args:
if x is None:
r.append([])
elif... |
def generate_unused_secgroup_entry(security_group: dict) -> dict:
"""
Generates a dictionary from an unused security group to the analysis
response
"""
unused_group = {
'GroupName': security_group['GroupName'],
'GroupId': security_group['GroupId'],
'Description': security_gro... |
def get_host_batchid_map(workspec_list):
"""
Get a dictionary of submissionHost: list of batchIDs from workspec_list
return {submissionHost_1: {batchID_1_1, ...}, submissionHost_2: {...}, ...}
"""
host_batchid_map = {}
for workspec in workspec_list:
host = workspec.submissionHost
... |
def getPreviousMatchlen(cigarOps, currOffset):
"""
This takes in a vector of cigar operations (reduced instruction set; MID only)
and returns the length of the match needed to consume bases 0..currOffset in the string
"""
if not cigarOps:
return currOffset
off = 0
# recompute the current substring p... |
def list2str(list_obj):
"""
Args:
list_obj(list):
Returns:
str: List converted to a prettier string than the default str(list).
"""
out = "[ "
for item in list_obj:
out += "{}, ".format(item)
out = out[:-1][:-1]
out += " ]"
return out |
def scale(data, min_screen, max_screen, min_data, max_data):
"""
get the scaled data with proportions min_data, max_data
relative to min and max screen dimentions
"""
return ((data - min_data) / (max_data - min_data)) * (max_screen - min_screen) + min_screen |
def do_center(value, width=80):
"""
Centers the value in a field of a given width.
"""
return value.center(width) |
def usefulness_minus_target(k, num_attributes, num_tuples, target_usefulness=5, epsilon=0.1):
"""Usefulness function in PrivBayes.
Parameters
----------
k : int
Max number of degree in Bayesian networks construction
num_attributes : int
Number of attributes in dataset.
num_tuple... |
def generate_notes_file_name(year, month, day):
"""Generate note's file name for a particular date
Args:
year (int): Year
month (int): Month
day (int): Day
Returns:
Note name
"""
return "{}-{}-{}".format(year, month, day) |
def __is_const_str(data: str) -> bool:
""" Returns true if predicate is a constant string.
Note: supports constant strings starting with a lowercase letter
or a number
"""
# common case: string starts with a lowercase letter
test_str = data[0].islower()
# special case: string starts with a... |
def param_first(key, params):
"""Search 'params' for 'key' and return the first value that
occurs. If 'key' was not found, return None."""
for k, v in params:
if key == k:
return v
return None |
def get_doc_info(result):
"""Get the index, doc_type, and id associated with a document.
Parameters
----------
result : dict
A document from an Elasticsearch search result.
Returns
-------
dict
A dictionary with keys 'index', 'doc_type', and 'id',
containing the nam... |
def matchWallTime(walltime, resource_ad):
"""True if `walltime` <= MaxWallTime in `resource_ad`, or if
MaxWallTime is undefined or 0
"""
max_wall_time = resource_ad.get('MaxWallTime', 0)
if not max_wall_time:
return True
else:
return (int(max_wall_time) >= walltime) |
def get_positions(start_idx, end_idx, length):
""" Get subj/obj position sequence. """
return list(range(-start_idx, 0)) + [0]*(end_idx - start_idx) + \
list(range(1, length-end_idx+1)) |
def bytes2MiB(bytes):
"""
Convert bytes to MiB.
:param bytes: number of bytes
:type bytes: int
:return: MiB
:rtype: float
"""
return bytes/(1024*1024) |
def is_valid_id(id_: str) -> bool:
"""If it is not nullptr.
Parameters
----------
id_ : str
Notes
-----
Not actually does anything else than id is not 0x00000
Returns
-------
bool
"""
return not id_.endswith("0x0000000000000000") |
def agent_grounding_matches(agent):
"""Return an Agent matches key just based on grounding, not state."""
if agent is None:
return None
return str(agent.entity_matches_key()) |
def _basename(p):
"""Returns the basename (i.e., the file portion) of a path.
Note that if `p` ends with a slash, this function returns an empty string.
This matches the behavior of Python's `os.path.basename`, but differs from
the Unix `basename` command (which would return the path segment preceding
... |
def bubble_sort_across_lists(dictionary):
"""
>>> d = {'he': [0, 2.5, 0, 1.3846153846153846, 0, 1.0, 5.3478260869565215],
... 'she': [10.25, 0, 28.75, 0, 14.266666666666667, 0, 0],
... 'book': ['a', 'b', 'd', 'f', 'g', 'h', 'i']}
>>> bubble_sort_across_lists(d)
{'he': [5.3478260869565215... |
def single_number3(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# isolate a^b from pairs using XOR
ab = 0
for n in nums:
ab ^= n
# isolate right most bit from a^b
right_most = ab & (-ab)
# isolate a and b from a^b
a, b = 0, 0
for n in nums:
if ... |
def construct_traceview_url(args):
"""
Construct url using artifacts
"""
url = "{host}:{port}/{app}/traceviewer.html?trace={trc}&alignmentset={aln}&subreads={sset}&holen={zmw}"
url = url.format(host=args['--server_host'],
port=args['--server_port'],
app=args... |
def _SplitOption(text):
"""Split simple option list.
@type text: string
@param text: Options, e.g. "foo, bar, baz"
"""
return [i.strip(",").strip() for i in text.split()] |
def find_indices(text, expr):
"""Identify indices where search expression (expr)
occurs in base expression (text)"""
places = []
i = text.find(expr)
while i>=0:
places.append(i)
i = text.find(expr, i + 1)
return places |
def dict_string_to_nums(dictionary):
"""
turns all strings that are numbers into numbers inside a dict
:param dictionary: dict
:return: dict
"""
for i, j in dictionary.items():
if isinstance(j, str) and j.replace(".", "", 1).isnumeric():
num = float(j)
if num.is_... |
def arraylike(thing):
"""Is thing like an array?"""
return isinstance(thing, (list, tuple)) |
def encode_attribute(att, desc, targ):
"""
Encode the 'role' of an attribute in a model.
This is an important function, since here resides the precise encoding.
If this is changed, a whole lot of other things will change too. Since everything
that relies on the encoding should refer here, everythin... |
def filter_octects(ip_address):
"""functional approach filters the list"""
terms = ip_address.split(".")
if not len([*filter(lambda octet: octet.isdecimal(), terms)])==4:
return False
elif not len([*filter(lambda octet: 0<=int(octet)<=255, terms)])==4:
return False
else:
return True |
def clean_boxes_metadata(boxes_metadata):
"""
Get unique boxes metadata
:param boxes_metadata:
:return:
"""
boxes_names = {b['name']: 0 for b in boxes_metadata}
new_boxes_metadata = []
for bb in boxes_metadata:
if bb['name'] in boxes_names and boxes_names[bb['name']] == 0:
... |
def correlate_service(method, service_objects):
""" Returns the service containing the appropriate service path
for the provided method, if a match is found """
service_segment = method["rmtSvcIntName"].lower().split(".")[-1]
for service in service_objects:
service_path = service["servicePat... |
def is_illegal_char(char: int) -> bool:
"""True if char is the base-26 representation of one of i, o, l."""
if char in [8, 11, 14]: # i, l, o
return True
return False |
def empty_when_none(_string=None):
"""If _string if None, return an empty string, otherwise return string.
"""
if _string is None:
return ""
else:
return str(_string) |
def dim(shape):
"""Given shape, return the number of dimension"""
d = 1
for size in shape: d *= size
return d |
def pusher(lst):
"""
A Helper Function that takes all non zero numbers and
pushes them to the front of the list.
"""
sorted_list = []
for dummy_num in range(len(lst)):
if lst[dummy_num] != 0:
sorted_list.append(lst[dummy_num])
for dummy_... |
def make_constructed_utts(utt_tokens):
"""
Converts utterances into correct form for composition
Args:
utt_tokens: List of utterances (utterance = list of tokens)
Returns:
utts:
List of utterances for individual tokens and compositions
compose_idx:
List ... |
def average(lst):
"""
calculate average of a list (of numbers)
"""
return sum(lst) / len(lst) |
def create_output_path(output_template, datacombination, parameter, algorithm_name):
"""
Where does he want his results?
"""
output = output_template
output = output.replace("@@name@@", algorithm_name)
output = output.replace("@@trainOn@@", datacombination["trainOn"])
output = output.rep... |
def convolve(X, Y):
"""
Convolves two series.
"""
N = len(X)
ss = []
for n in range(0, len(Y)):
s = 0
for l in range(0, len(X)):
s += X[l].conjugate()*Y[(n+l)%len(Y)]
ss.append(s)
return ss |
def blank_to_NA(it):
""" Converts blank fields to NAs in some list it
it: list
Return value: list with blank fields represented as NAs
"""
return [(el if el else 'NA') for el in it] |
def _fix_endpoint(endpoint: str) -> str:
"""
Remove all text before "http".
Workaround because the endpoint is automatically prefixed with the data folder. However this does not make sense for
a sparql endpoint.
:param endpoint:
:return:
"""
idx = endpoint.find('http')
return endpoi... |
def dottedQuadToNum(ip):
"""
Convert decimal dotted quad string to long integer
>>> int(dottedQuadToNum('1 '))
1
>>> int(dottedQuadToNum(' 1.2'))
16777218
>>> int(dottedQuadToNum(' 1.2.3 '))
16908291
>>> int(dottedQuadToNum('1.2.3.4'))
16909060
>>> dottedQuadToNum('1.2.3... |
def iterate_mandelbrot(iterate_max, c, z = 0):
"""Calculate the mandelbrot sequence for the point c with start value z"""
for n in range(iterate_max + 1):
z = z * z + c
if abs(z) > 2:
return n
return None |
def is_iterable(x):
"""Checks if an object x is iterable.
It checks only for the presence of __iter__, which must exist for
container objects.
Note: we do not consider non-containers such as string and unicode as
`iterable'; this behavior is intended.
"""
return hasattr(x, "__iter__") |
def transcribe(dna):
"""
return the dna string as rna string
"""
return dna.replace('T', 'U') |
def string_to_tuple(version):
"""Convert version as string to tuple
Example:
>>> string_to_tuple("1.0.0")
(1, 0, 0)
>>> string_to_tuple("2.5")
(2, 5)
"""
return tuple(map(int, version.split("."))) |
def get_num_bytes(i):
"""Get the minimum number of bytes needed to represent a given int
value.
@param i (int) The integer to check.
@return (int) The number of bytes needed to represent the given
int.
"""
# 1 byte?
if ((i & 0x00000000FF) == i):
return 1
# 2 bytes?
... |
def EditDistance(string1, string2):
"""
Edit Distance for given string1 and string2
"""
if len(string1) > len(string2):
string1, string2 = string2, string1
distances = range(len(string1) + 1)
for index2, char2 in enumerate(string2):
newDistances = [index2 + 1]
for ind... |
def dfdz_ReLU(z):
"""Derivative of the rectified linear unit function...
Args:
z (np.array)
Returns:
df(z)/dz = 1 if x > 0 else 0 (np.array)
"""
return (z > 0) |
def get_with_prefix(d, k, default=None, delimiter=":"):
"""\
Retrieve a value from the dictionary, falling back to using its
prefix, denoted by a delimiter (default ':'). Useful for cases
such as looking up `raven-java:logback` in a dict like
{"raven-java": "7.0.0"}.
"""
if k is None:
... |
def normalize(item):
"""
lowercase and remove quote signifiers from items that are about to be compared
"""
item = item.lower().rstrip('_')
return item |
def index_1d(row, col):
"""For a given row and column in a grid world, return the row that cell would appear on in the transition matrix.
Parameters
----------
row : int
The row number. Indexing starts at 0.
col : int
The column number. Indexing starts at 0.
Returns
-------... |
def get_manhattan_distance(x, y):
"""Calculate Manhattan distance of x, y to the 0, 0 point."""
return abs(x) + abs(y) |
def filter_stopwords(str):
"""
Stop word filter
returns list
"""
STOPWORDS = ['a', 'able', 'about', 'across', 'after', 'all', 'almost',
'also', 'am', 'among', 'an', 'and', 'any', 'are', 'as', 'at',
'be', 'because', 'been', 'but', 'by', 'can', 'cannot',
... |
def GetAtxCertificateSubject(cert):
"""Parses and returns the subject field from the given AvbAtxCertificate struct."""
CERT_SUBJECT_OFFSET = 4 + 1032 # Format version and public key come before subject
CERT_SUBJECT_LENGTH = 32
return cert[CERT_SUBJECT_OFFSET:CERT_SUBJECT_OFFSET + CERT_SUBJECT_LENGTH] |
def ms2mph(ms: float) -> float:
"""
Convert meters per second to miles per hour.
:param float ms: m/s
:return: speed in mph
:rtype: float
"""
if not isinstance(ms, (float, int)):
return 0
return ms * 2.23693674 |
def str_to_c_string(string):
"""Converts a Python str (ASCII) to a C string literal.
>>> str_to_c_string('abc\x8c')
'"abc\\\\x8c"'
"""
return repr(string).replace("'", '"') |
def currency_to_int(s: str) -> int:
"""
Just remove a colon.
"""
return int(s[:len(s)-3] + s[len(s)-2:]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.