content
stringlengths 42
6.51k
|
|---|
def rotcon2pmi(rotational_constant):
""" Convert rotational constants in units of MHz to
Inertia, in units of amu A^2.
The conversion factor is adapted from:
Oka & Morino, JMS (1962) 8, 9-21
This factor comprises h / pi^2 c.
:param rotational_constant: rotational constant in MHz
:return:
"""
return 1 / (rotational_constant / 134.901)
|
def subtract_year(any_date):
"""Subtracts one year from any date and returns the result"""
date = any_date.split("-")
date = str(int(date[0])-1) + "-" + date[1] + "-" + date[2]
return date
|
def KK_RC24(w, Rs, R_values, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
return (
Rs
+ (R_values[0] / (1 + w * 1j * t_values[0]))
+ (R_values[1] / (1 + w * 1j * t_values[1]))
+ (R_values[2] / (1 + w * 1j * t_values[2]))
+ (R_values[3] / (1 + w * 1j * t_values[3]))
+ (R_values[4] / (1 + w * 1j * t_values[4]))
+ (R_values[5] / (1 + w * 1j * t_values[5]))
+ (R_values[6] / (1 + w * 1j * t_values[6]))
+ (R_values[7] / (1 + w * 1j * t_values[7]))
+ (R_values[8] / (1 + w * 1j * t_values[8]))
+ (R_values[9] / (1 + w * 1j * t_values[9]))
+ (R_values[10] / (1 + w * 1j * t_values[10]))
+ (R_values[11] / (1 + w * 1j * t_values[11]))
+ (R_values[12] / (1 + w * 1j * t_values[12]))
+ (R_values[13] / (1 + w * 1j * t_values[13]))
+ (R_values[14] / (1 + w * 1j * t_values[14]))
+ (R_values[15] / (1 + w * 1j * t_values[15]))
+ (R_values[16] / (1 + w * 1j * t_values[16]))
+ (R_values[17] / (1 + w * 1j * t_values[17]))
+ (R_values[18] / (1 + w * 1j * t_values[18]))
+ (R_values[19] / (1 + w * 1j * t_values[19]))
+ (R_values[20] / (1 + w * 1j * t_values[20]))
+ (R_values[21] / (1 + w * 1j * t_values[21]))
+ (R_values[22] / (1 + w * 1j * t_values[22]))
+ (R_values[23] / (1 + w * 1j * t_values[23]))
)
|
def _double_quotes(unquoted):
"""
Display String like redis-cli.
escape inner double quotes.
add outter double quotes.
:param unquoted: list, or str
"""
if isinstance(unquoted, str):
# escape double quote
escaped = unquoted.replace('"', '\\"')
return f'"{escaped}"' # add outter double quotes
elif isinstance(unquoted, list):
return [_double_quotes(item) for item in unquoted]
|
def parse_as_unsigned_int(value, size_in_bits):
"""This is necessary because some fields in spans are decribed as a 64 bits unsigned integers, but
java, and other languages only supports signed integer. As such, they might send trace ids as negative
number if >2**63 -1. The agent parses it signed and interpret the bytes as unsigned. See
https://github.com/DataDog/datadog-agent/blob/778855c6c31b13f9235a42b758a1f7c8ab7039e5/pkg/trace/pb/decoder_bytes.go#L181-L196"""
if not isinstance(value, int):
return value
# Asserts that the unsigned is either a no bigger than the size in bits
assert -(2 ** size_in_bits - 1) <= value <= 2 ** size_in_bits - 1
# Take two's complement of the number if negative
return value if value >= 0 else (-value ^ (2 ** size_in_bits - 1)) + 1
|
def get_span_labels(sentence_tags, inv_label_mapping=None):
"""Go from token-level labels to list of entities (start, end, class)."""
if inv_label_mapping:
sentence_tags = [inv_label_mapping[i] for i in sentence_tags]
span_labels = []
last = 'O'
start = -1
for i, tag in enumerate(sentence_tags):
pos, _ = (None, 'O') if tag in ['O','<s>','</s>'] else tag.split('-')
if (pos == 'S' or pos == 'B' or tag == 'O') and last != 'O':
span_labels.append((start, i - 1, last.split('-')[-1]))
if pos == 'B' or pos == 'S' or last == 'O':
start = i
last = tag
if sentence_tags[-1] != 'O':
span_labels.append((start, len(sentence_tags) - 1,
sentence_tags[-1].split('-')[-1]))
return span_labels
|
def mogrify(cursor, query, queryArgs = None):
""" Logs the query statement and execute it"""
query = query.upper()
if queryArgs == None:
return query
else:
cursor.prepare(query)
bindnames = cursor.bindnames()
if len(queryArgs) != len(bindnames):
raise Exception('Error: len(queryArgs) != len(bindnames) \n ' + str(queryArgs) + '\n' + str(bindnames))
if (type(queryArgs) == list) or (type(queryArgs) == tuple):
for i in range(len(queryArgs)):
query = query.replace(':'+bindnames[i],str(queryArgs[i]))
return query
elif type(queryArgs) == dict:
upQA = {}
for k in queryArgs:
upQA[k.upper()] = queryArgs[k]
for bindname in bindnames:
query = query.replace(':'+bindname, str(upQA[bindname]))
return query
else:
raise Exception('Error: queryArgs must be dict, list or tuple')
|
def correct_names_ERA5(x,y, options):
"""
"""
z = x
if x in ['tp', 'sd', 'e']:
y = 'mm'
z = options[x]
elif x in ['t2m']:
y = 'C'
z = options[x]
elif x in ['u10', 'v10']:
y = 'm/s'
z = options[x]
return z, y
|
def _create_folds_list(data, count):
"""
Creates folds from the given data.
:param data: the data to fold
:param count: the number of folds to create
:return: a list of folds
"""
fold_count = len(data) / count
folds = list()
for fold_index in range(count):
low = int(fold_index * fold_count)
high = int((fold_index + 1) * fold_count)
fold = data[low:high]
folds.append(fold)
return folds
|
def read_file(path):
"""
Read a file and return the contents as string
:param f: (str) The file to read
:return: (str) The file contents
"""
with open(path, 'r') as file:
return file.read()
|
def no_trailing_comma(l):
"""
By-lines wikidata dumps have trailing commas (on all but the last line). Remove them.
"""
if l[-1] == ',':
return l[:-1]
else:
return l
|
def bisect(a, x, lo=0, hi=None):
"""Find the index where to insert item x in list a, assuming a is sorted."""
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)/2
if x < a[mid]: hi = mid
else: lo = mid+1
return lo
|
def _set_bit(current, epaddr, v):
"""
>>> bin(_set_bit(0, 0, 1))
'0b1'
>>> bin(_set_bit(0, 2, 1))
'0b100'
>>> bin(_set_bit(0b1000, 2, 1))
'0b1100'
>>> bin(_set_bit(0b1100, 2, 0))
'0b1000'
>>> bin(_set_bit(0b1101, 2, 0))
'0b1001'
"""
if v:
return current | 1 << epaddr
else:
return current & ~(1 << epaddr)
|
def d2h(d):
"""Convert degrees into hours."""
return d * (24.0 / 360.0)
|
def approximately_equal(x, y, tol=0.00000000000001):
"""
Determines if floats x and y are equal within a degree of uncertainty
Inputs:
x --- a float
y --- a float
tol --- an error tolerance
"""
return abs(x - y) <= tol
|
def merge(line):
"""
Merge Function for the 2048 Game
"""
new_line = [0]*len(line)
ind = 0
for ele in line:
if ele == 0:
continue
elif new_line[ind] == 0:
new_line[ind] = ele
elif new_line[ind] == ele:
new_line[ind] += ele
ind += 1
else:
ind += 1
new_line[ind] = ele
return new_line
|
def is_grpc_service_dir(files):
"""Returns true iff the directory hosts a gRPC service."""
return ".grpc_service" in files
|
def fizz_buzz(num: int) -> str:
"""This is my great and neat function to solve the famous
Fizz Buzz problem.
:param num: That's the number which we want the answer for
:return: fizz, buzz, fizzbuzz or the number itself
"""
if num % 15 == 0:
return "fizzbuzz"
if num % 5 == 0:
return "buzz"
if num % 3 == 0:
return "fizz"
return str(num)
|
def match_name(s, l):
""" Return if s matches l, where s can include wildcards '*'."""
assert(isinstance(s,str))
assert(isinstance(l,str))
spl = s.split('*')
if not l.find(spl[0])==0:
return False
start = len(spl[0])
for si in spl[1:]:
idx = l.find(si,start)
if idx<0:
return False
else:
start = idx + len(si)
return start==len(l) or spl[-1]==''
|
def _exclude(term: str) -> str:
"""
Returns a query term excluding messages that match the given query term.
Args:
term: The query term to be excluded.
Returns:
The query string.
"""
return f'-{term}'
|
def IRAF_image_type(image_type):
"""
Convert MaximDL default image type names to IRAF
Parameters
----------
image_type : str
Value of the FITS header keyword IMAGETYP; acceptable values are
below in Notes.
Returns
-------
str
IRAF image type (one of 'BIAS', 'DARK', 'FLAT' or 'LIGHT')
Notes
-----
The MaximDL default is, e.g. 'Bias Frame', which IRAF calls
'BIAS'. Can safely be called with an IRAF-style image_type.
"""
return image_type.split()[0].upper()
|
def choices_on_ballots(L, printing_wanted=False):
"""
Return a dict of the choices shown on ballot list L, with counts.
Args:
L (list): list of ballots
Returns:
C (dict): dict of distinct strings appearing in ballots in L,
each with count of number of occurrences.
Example:
"""
C = dict()
ballot_no = 0
for ballot in L:
ballot_no += 1
for choice in ballot:
if False and choice not in C:
print("Choice {} first seen in ballot {}"
.format(choice, ballot_no))
C[choice] = 1 + C.get(choice, 0)
return C
|
def clip(number,start,end):
"""Returns `number`, but makes sure it's in the range of [start..end]"""
return max(start, min(number, end))
|
def _PathFromRoot(module_tree, module):
"""Computes path from root to a module.
Parameters:
module_tree: Dictionary mapping each module to its parent.
module: Module to which to compute the path.
Returns:
Path from root the the module.
"""
path = [module]
while module_tree.get(module):
module = module_tree[module]
path = [module] + path
return path
|
def format_error(error_code, message):
"""
Converts an error_code and message into a response body
"""
return {"errors": [{"code": error_code, "message": message}]}
|
def to_list(val):
""" Do whatever it takes to coerce val into a list, usually for blind concatenation """
if isinstance(val, list):
return val
if not val:
return []
return [val]
|
def Summation(xs, mu, cache={}):
"""Computes the sum of (x-mu)**2 for x in t.
Caches previous results.
xs: tuple of values
mu: hypothetical mean
cache: cache of previous results
"""
try:
return cache[xs, mu]
except KeyError:
ds = [(x-mu)**2 for x in xs]
total = sum(ds)
cache[xs, mu] = total
return total
|
def do_datetime(dt, format=None):
"""Jinja template filter to format a datetime object with date & time."""
if dt is None:
# By default, render an empty string.
return ''
if format is None:
# No format is given in the template call. Use a default format.
#
# Format time in its own strftime call in order to:
# 1. Left-strip leading 0 in hour display.
# 2. Use 'am' and 'pm' (lower case) instead of 'AM' and 'PM'.
formatted_date = dt.strftime('%Y-%m-%d - %A')
formatted_time = dt.strftime('%I:%M%p').lstrip('0').lower()
formatted = f'{formatted_date} at {formatted_time}'
else:
formatted = dt.strftime(format)
return formatted
|
def get_mode(input_list: list):
"""
Get's the mode of a certain list. If there are few modes, the function returns False.
This is a very slow way to accomplish this, but it gets a mode, which can only be 4 things, so it should be OK
"""
if len(input_list) == 0:
return False
distinguished_elements = {}
for element in input_list:
if element not in distinguished_elements:
distinguished_elements[element] = 0
# Count all of the elements and save them in a dictionary
for key, value in distinguished_elements.items():
distinguished_elements[key] = input_list.count(key)
# Get the mode
max_key = None
max_value = 0
for key, value in distinguished_elements.items():
if value > max_value:
max_key = key
max_value = value
# If there's a second mode, return False
for key, value in distinguished_elements.items():
if value == max_value and key != max_key:
return False
return max_key
|
def quick_sort(items):
""" the quick sort algorithm takes in an unsorted list of numbers.
returns a list in ascending order.
Parameters
----------
items : list
list of unordered numbers
Returns
-------
list
list of elements in items in ascending order
Examples
-------
>>> bubble_sort([1])
1
>>> bubble_sort([54,26,93,17,77,31,44,55,20])
[17, 20, 26, 31, 44, 54, 55, 77, 93]
"""
if len(items) == 0: # base case
return items
# divide array in half and quick sort recursively
p = len(items) // 2
s = [i for i in items if i < items[p]] # small list
d = [i for i in items if i == items[p]] # duplicate list
l = [i for i in items if i > items[p]] # large list
return quick_sort(s) + d + quick_sort(l)
|
def letter_tuple_to_string(letter_tuple):
""" Ronseal. """
string = ""
for letter in letter_tuple:
string = string+letter
return string
|
def check_certificate_data(certificates):
"""
Checks the correctness of the certificates provided by the CS.
:param certificates: the provided certificates.
:type certificates: DER str list
:return: True if the certificates are correct, False otherwise.
:rtype: bool
"""
# ToDo: Decide witch fields of the certificate have to be checked and how
return True
|
def remove_duplicates_and_nones(items):
"""Removes all duplicates and None values from a list."""
new_list = [item for item in items if item is not None]
return list(set(new_list))
|
def sanitize_host(host):
"""Return the hostname or ip address out of a URL"""
for prefix in ['https://', 'http://']:
host = host.replace(prefix, '')
host = host.split('/')[0]
host = host.split(':')[0]
return host
|
def read_metadatablockpicture( data ):
"""Extract picture from a METADATA_BLOCK_PICTURE"""
off = 8 + int.from_bytes( data[4:8], 'big' )
off += 4 + int.from_bytes( data[off:off+4], 'big' ) + 16
size = int.from_bytes( data[off:off+4], 'big' )
return data[4+off:4+off+size]
|
def bytes_to_str(bytes_arr):
"""
This function print all bytes in the same
way as C/C++. When we have 2 in python we get 10,
but I want to see it as like 00000010
"""
res_str = ""
for byte in bytes_arr:
byte_str = "{0:b}".format(byte)
res_str += "0" * (8 - len(byte_str))
res_str += byte_str
return res_str
|
def get_trained_policies_name(policies, num_trained_agent):
"""
Get index of the max reward of the trained policies in most recent episode.
"""
train_policies_name = []
i = 0
for k,v in policies.items():
if i < num_trained_agent:
train_policies_name.append(k)
i = i + 1
return train_policies_name
|
def nodetype(anode):
"""return the type of node"""
try:
return anode[1]
except IndexError as e:
return None
|
def make_subsets(data, size: int) -> list:
""" Creates subsets out of ``data``, each subset having ``size``
elements. Used in ``graphs/multiple_results.html`` and
``graphs/single_result.html``. """
subset_list = list()
if type(data) is list:
subset = list()
while True:
subset.append(data.pop())
if len(subset) == size:
subset_list.append(subset)
subset = list()
if not data:
subset_list.append(subset)
break
elif type(data) is dict:
subset = dict()
while True:
key, value = data.popitem()
subset.update({key: value})
if len(subset) == size:
subset_list.append(subset)
subset = dict()
if not data:
subset_list.append(subset)
break
return subset_list
|
def read_cube_name_from_mdx(mdx):
""" Read the cubename from a valid MDX Query
:param mdx: The MDX Query as String
:return: String, name of a cube
"""
mdx_trimed = ''.join(mdx.split()).upper()
post_start = mdx_trimed.rfind("FROM[") + len("FROM[")
pos_end = mdx_trimed.find("]WHERE", post_start)
# if pos_end is -1 it works too
cube_name = mdx_trimed[post_start:pos_end]
return cube_name
|
def fizz_buzz(num):
"""
return 'Fizz', 'Buzz', 'FizzBuzz', or the argument it receives,
all depending on the argument of the function,
a number that is divisible by, 3, 5, or both 3 and 5, respectively.
"""
if not isinstance(num, int):
raise TypeError("Expected integer as input")
if num % 3 == 0 and num % 5 == 0:
return "FizzBuzz"
elif num % 3 == 0:
return "Fizz"
elif num % 5 == 0:
return "Buzz"
return num
|
def parser_add_help_from_doc(doc):
"""Find the conventional H/ Help Option and return True, else False or None"""
if doc is None:
return None
lines = doc.splitlines()
for (index, line) in enumerate(lines):
next_line = lines[index + 1] if lines[(index + 1) :] else ""
stripped = line.strip()
if stripped.startswith("-h, --help"):
help_tail = "show this help message and exit"
if stripped.endswith(help_tail) or (next_line.strip() == help_tail):
return True
return False
|
def create_metadata(metadata, data, **kwargs):
"""Function: create_metadata2
Description: Merge a list of data sets into an existing dictionary based
on the keys in the dictionary or create new keys in the dictionary
based on the data set in the list.
Arguments:
(input) metadata -> Dictionary of meta-data.
(input) data -> List of data sets.
(output) metadata -> Dictionary of meta-data.
"""
data = list(data)
for item in data:
# Create new key.
if item[1] not in metadata.keys():
metadata[item[1]] = [item[0]]
# Check for duplicate entry in dictionary's list.
elif item[0] not in metadata[item[1]]:
metadata[item[1]].append(item[0])
return metadata
|
def atoi(s : str):
"""
Converts integer jobId as string to integer
Args:
s (string): Microsoft jobId
Returns:
integer form
"""
if not s:
print("Cannot convert empty string to integer")
n = 0
for i in s:
n = n * 10 + ord(i) - ord("0")
return n
|
def partition_around_index(list_to_partition, index):
"""
Partitions a list around the given index, returning 2 lists. The first contains elements
before the index, and the second contains elements after the index (the given index is excluded).
Examples:
partition_around_index([1,2,3,4,5], 2) == ([1,2], [4,5])
partition_around_index([1,2,3,4,5], 0) == ([], [2,3,4,5])
Args:
list_to_partition (list): The list to partition
index (int): The index that the list should be partitioned around
Returns:
Tuple(list, list): The partitions of the given list
"""
list_len = len(list_to_partition)
if list_len <= index:
raise ValueError(
"Index out of range: {} ({} item list)".format(index, list_len)
)
l1, l2 = [], []
if index > 0:
l1 = list_to_partition[0:index]
if index < (list_len - 1):
l2 = list_to_partition[(index + 1) :]
return l1, l2
|
def contiguous_seq_eff2(A, maxx=0, max_seq=set()):
"""
No need for any recursion and only one for loop
"""
# Stop if
if len(A) < 1:
return False
sum_ = 0
seq = set()
for n in A:
sum_ += n
seq.add(n)
if sum_ > maxx:
maxx = sum_
max_seq = seq.copy()
elif sum_ < 0:
sum_ = 0
seq = set()
print("Max: {} with Sequence: {}".format(maxx, max_seq))
return True
|
def _to_gj_point(obj):
"""
Dump a Esri JSON Point to GeoJSON Point.
:param dict obj:
A EsriJSON-like `dict` representing a Point.
:returns:
GeoJSON representation of the Esri JSON Point
"""
if obj.get("x", None) is None or \
obj.get("y", None) is None:
return {'type': 'Point', 'coordinates': ()}
return {'type': 'Point', 'coordinates': (obj.get("x"),
obj.get("y"))}
|
def SizeToReadableString(filesize):
"""Turn a filesize int into a human readable filesize.
From http://stackoverflow.com/questions/1094841/
Args:
filesize: int
Returns:
string: human readable size representation.
"""
for x in ["bytes", "KiB", "MiB", "GiB", "TiB"]:
if filesize < 1000.0:
return "%3.1f %s" % (filesize, x)
filesize /= 1000.0
|
def _range_is_valid (list, range):
"""checks if each element of the range is a valid element of the list and returns True if this is the case."""
return (0 <= min(range) and max(range) < len(list))
|
def is_sibling_of(page1, page2):
"""
Determines whether a given page is a sibling of another page
{% if page|is_sibling_of:feincms_page %} ... {% endif %}
"""
if page1 is None or page2 is None:
return False
return (page1.parent_id == page2.parent_id)
|
def _find_prime_factors(n):
"""
Find all the prime factors of `n`, sorted from largest to smallest
Parameters
----------
n : int
Number to factorize
Returns
-------
factors : list[int]
Notes
-----
From http://stackoverflow.com/questions/15347174/python-finding-prime-factors
Examples
--------
>>> _find_prime_factors(8)
[2, 2, 2]
>>> _find_prime_factors(25)
[5, 5]
>>> _find_prime_factors(26)
[13, 2]
>>> _find_prime_factors(29)
[29]
>>> _find_prime_factors(14)
[7, 2]
>>> _find_prime_factors(12)
[3, 2, 2]
"""
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
factors = sorted(factors, reverse=True)
return factors
|
def suba(a, b, c, d=0, e=0):
"""Subtract numbers b and c from number a. Optionally also subtract
either or both of numbers d and e from the result.
"""
print(f"Function `suba` called with arguments a={a} b={b} c={c}", end="")
if d: print(f" d={d}", end="")
if e: print(f" e={e}", end="")
print()
return a - b - c - d - e
|
def bayes_factor(model_1, model_2):
"""
Use the `Bayes factor`_ to compare two models. Using Table from `Kass and Raftery`_ to compare.
Args:
model_1 (:py:class:`uncertainties.core.Variable` or :py:attr:`float`): ln evidence for model 1.
model_2 (:py:class:`uncertainties.core.Variable` or :py:attr:`float`): ln evidence for model 2.
Return:
:py:class:`uncertainties.core.Variable` or :py:attr:`float`: 2ln(B), where B is the Bayes Factor between the two models.
.. _Bayes factor: https://en.wikipedia.org/wiki/Bayes_factor
.. _Kass and Raftery: https://www.colorado.edu/amath/sites/default/files/attached-files/kassraftery95.pdf
"""
return 2 * (model_1 - model_2)
|
def format_markdown(content, params):
"""Format content with config parameters.
Arguments:
content {str} -- Unformatted content
Returns:
{str} -- Formatted content
"""
try:
fmt = content.format(**params)
except KeyError:
fmt = content
return fmt
|
def mandel_numba(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
i = 0
c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z * z + c
if (z.real * z.real + z.imag * z.imag) >= 4:
return i
return 255
|
def max_no_repeat(s):
"""
Returns the first longest substring of s containing no repeated characters.
"""
max_start = -1
max_end = -1
max_len = -1
char_set = set() # {} initializes an empty dict instead of an empty set.
curr_start = 0
for curr_end in range(len(s)):
char = s[curr_end]
if char in char_set:
curr_len = curr_end - curr_start
if curr_len > max_len:
max_start, max_end, max_len = curr_start, curr_end, curr_len
# Throw out the characters that came before the match.
while s[curr_start] != char:
char_set.remove(s[curr_start])
curr_start += 1
curr_start += 1
else:
char_set.add(char)
curr_len = len(s) - curr_start
if curr_len > max_len:
max_start, max_end, max_len = curr_start, len(s), curr_len
return s[max_start:max_end]
|
def nocomment(st,com):
"""
just like the comment in python.
removes any text after the phrase 'com'
"""
ls=st.splitlines()
for i in range(len(ls)):
el=ls[i]
pt=el.find(com)
if pt!=-1:
ls[i]=el[:pt]
return '\n'.join(ls)
|
def griddef(gridname):
"""
Returns a tuple of grid parameters for an EASE grid
gridname - standard name of grid
"""
gdef = {
'Nh': {'c': 12.5, 'nx': 1441, 'ny': 1441, 'r0': 720, 's0': 720}
}
try:
result = gdef[gridname]
return result
except:
print ('griddef: unknown grid name')
|
def round_coordinates(coord_x, coord_y):
""" Round coordinates to 1 decimal """
x = round(coord_x, 1)
y = round(coord_y, 1)
return x, y
|
def cast_int(value):
"""
Cast value to 32bit integer
Usage:
cast_int(1 << 31) == -1
(where as: 1 << 31 == 2147483648)
"""
value = value & 0xFFFFFFFF
if value & 0x80000000:
value = ~value + 1 & 0xFFFFFFFF
return -value
else:
return value
|
def convert_ddmmss_to_float(astring):
"""Convert sexigesimal to decimal degrees
Parameters
----------
astring: str
The sexigesimal coordinate.
Returns
-------
hour_or_deg : float
The converted coordinate.
"""
aline = astring.split(':')
d = float(aline[0])
m = float(aline[1])
s = float(aline[2])
hour_or_deg = (s/60.+m)/60.+d
return hour_or_deg
|
def _parse_tshape(tshape):
"""Parse tshape in string."""
return [int(x.strip()) for x in tshape.strip('()').split(',')]
|
def is_float(string):
"""Checks if the string is a float
Args:
string (str): The string to check
Returns:
Boolean: Whether the string could be converted to a float or not
"""
try:
float(string)
return True
except ValueError:
return False
|
def conf_full():
"""complete config used for tests.
"""
return {
"jwt_secret": "SECRET",
"user_claim": "jid",
"jwt_secret_old": "OLDSECRET",
"jwt_algorithm": "HS256",
"issuer": "https://www.myapplication.com",
"audience": "https://www.myapplication.com",
"jwt_expiration": 86400,
"leeway": 10,
}
|
def average_nonmissing(row, cols, missing=-999, adjustfactor=1, countmissings=False):
"""Average the non-missing columns in cols, adjusting denominator"""
nonmissingcols = [row[col] for col in cols if row[col] != missing]
return missing if len(nonmissingcols) == 0 \
else sum(nonmissingcols)/((len(cols) if countmissings else len(nonmissingcols)) * adjustfactor)
|
def is_supported_english_translation(translation):
"""
A helper function to determine if the provided string is a supported English translation.
:param translation: Translation code
:type translation: str
:return: True = the translation is not supported, False = the translation is supported
:rtype: bool
>>> is_supported_english_translation('NIV')
True
>>> is_supported_english_translation('RVA')
False
"""
return translation.upper() in ['ASV', 'AKJV', 'BRG', 'CJB', 'EHV', 'ESV', 'ESVUK', 'GNV', 'GW', 'ISV',
'JUB', 'KJV', 'KJ21', 'LEB', 'MEV', 'NASB', 'NASB1995', 'NET',
'NIV', 'NKJV', 'NLT', 'NLV', 'NOG', 'NRSV', 'WEB', 'YLT']
|
def compute_sv_offset(frequency, pulse_length):
"""
A correction must be made to compensate for the effects of the finite response
times of both the receiving and transmitting parts of the instrument. The magnitude
of the correction will depend on the length of the transmitted pulse, and the response
time (on both transmission and reception) of the instrument.
:param frequency: Frequency in KHz
:param pulse_length: Pulse length in uSecs
:return:
"""
sv_offset = 0
if frequency > 38: # 125,200,455,769 kHz
if pulse_length == 300:
sv_offset = 1.1
elif pulse_length == 500:
sv_offset = 0.8
elif pulse_length == 700:
sv_offset = 0.5
elif pulse_length == 900:
sv_offset = 0.3
elif pulse_length == 1000:
sv_offset = 0.3
else: # 38 kHz
if pulse_length == 500:
sv_offset = 1.1
elif pulse_length == 1000:
sv_offset = 0.7
return sv_offset
|
def unzip_pairs(tups):
""" turn a list of pairs into a pair of lists """
return zip(*tups) if tups else ([],[])
|
def reversebits6(max_bits, num):
""" Like reversebits5, plus avoidance of an unnecessary shift. """
rev_num = 0
rev_left_shifts_to_do = max_bits - 1
while True:
rev_num |= num & 1
num >>= 1
if num == 0 or rev_left_shifts_to_do == 0:
break
rev_num <<= 1
rev_left_shifts_to_do -= 1
rev_num <<= rev_left_shifts_to_do
return rev_num
|
def comparing_tuple(A,B, tol=0.01):
"""
comparing two same sized tuple
"""
assert len(A) == len(B)
for i in range(0,len(A)):
if abs(A[i] - B[i]) <= tol:
continue
else:
return False
return True
|
def encode(text: str) -> str:
"""
Reverse order of given text characters.
:param text: Text to reverse.
:return: Reversed text.
"""
reversed_text = "".join(char for char in text[-1::-1])
return reversed_text
|
def flaghandler_note(mastodon, rest):
"""Parse input for flagsr. """
# initialize kwargs to default values
kwargs = {'mention': True,
'favourite': True,
'reblog': True,
'follow': True}
flags = {'m': False,
'f': False,
'b': False,
'F': False}
# token-grabbing loop
# recognize `note -m -f -b -F` as well as `note -mfbF`
while rest.startswith('-'):
# get the next token
(args, _, rest) = rest.partition(' ')
# traditional unix "ignore flags after this" syntax
if args == '--':
break
if 'm' in args:
kwargs['mention'] = False
if 'f' in args:
kwargs['favourite'] = False
if 'b' in args:
kwargs['reblog'] = False
if 'F' in args:
kwargs['follow'] = False
return (rest, kwargs)
|
def strings_match_at_indices(string_a, index_a, string_b, index_b):
"""Check if both strings match at given indices and indices aren't 0.
Args:
string_a (str): First string.
index_a (int): Index of character in first string.
string_b (str): Second string.
index_b (int): Index of character in second string.
Returns:
boolean: If both strings match at given indices and indices aren't 0.
"""
if index_a == 0:
return False
if index_b == 0:
return False
return string_a[index_a - 1] == string_b[index_b - 1]
|
def wrap_html_source(text):
"""
wrap the text with html tags to force the browser show the code as was created without corrupting it
"""
if text is None:
text = "ERROR: got None value!"
return "<html><pre><code> " + text + "</code></pre></html>"
|
def pawssible_patches(start, goal, limit):
"""A diff function that computes the edit distance from START to GOAL.
>>> pawssible_patches('place', 'wreat', 100)
5
"""
# assert False, 'Remove this line'
# print(start, goal, limit)
if start == goal:
return 0
elif limit == 0:
return 1
if len(goal) == 0 or len(start) ==0: # Fill in the condition
# BEGIN
"*** YOUR CODE HERE ***"
return max(len(goal), len(start))
# END
elif start[0] == goal[0]: # Feel free to remove or add additional cases
# BEGIN substitute
"*** YOUR CODE HERE ***"
return pawssible_patches(start[1:], goal[1:], limit)
# END
else:
"*** YOUR CODE HERE ***"
add_diff = pawssible_patches(start, goal[1:], limit - 1) + 1# Fill in these lines
remove_diff = pawssible_patches(start[1:], goal, limit - 1) + 1
substitute_diff = pawssible_patches(start[1:], goal[1:], limit - 1) + 1
return min(add_diff, remove_diff, substitute_diff)
|
def get_meta_name_and_modifiers(name):
""" Strips a meta name from any leading modifiers like `__` or `+`
and returns both as a tuple. If no modifier was found, the
second tuple value is `None`.
"""
clean_name = name
modifiers = None
if name[:2] == '__':
modifiers = '__'
clean_name = name[3:]
elif name[0] == '+':
modifiers = '+'
clean_name = name[1:]
return (clean_name, modifiers)
|
def tag_seq(words, seq, tag):
"""Sub in a tag for a subsequence of a list"""
words_out = words[:seq[0]] + ['{{%s}}' % tag]
words_out += words[seq[-1] + 1:] if seq[-1] < len(words) - 1 else []
return words_out
|
def clean_regex(regex):
"""
Escape any regex special characters other than alternation.
:param regex: regex from datatables interface
:type regex: str
:rtype: str with regex to use with database
"""
# copy for return
ret_regex = regex
# these characters are escaped (all except alternation | and escape \)
# see http://www.regular-expressions.info/refquick.html
escape_chars = '[^$.?*+(){}'
# remove any escape chars
ret_regex = ret_regex.replace('\\', '')
# escape any characters which are used by regex
# could probably concoct something incomprehensible using re.sub() but
# prefer to write clear code with this loop
# note expectation that no characters have already been escaped
for c in escape_chars:
ret_regex = ret_regex.replace(c, '\\' + c)
# remove any double alternations until these don't exist any more
while True:
old_regex = ret_regex
ret_regex = ret_regex.replace('||', '|')
if old_regex == ret_regex:
break
# if last char is alternation | remove it because this
# will cause operational error
# this can happen as user is typing in global search box
while len(ret_regex) >= 1 and ret_regex[-1] == '|':
ret_regex = ret_regex[:-1]
# and back to the caller
return ret_regex
|
def get_step_limit(lines):
"""Computes the maximum number of IPA-GNN steps allowed for a program."""
step_limit = 1 # Start with one step for reaching exit.
indents = []
for line in lines:
indent = len(line) - len(line.lstrip())
while indents and indent <= indents[-1]:
indents.pop()
step_limit += 2 ** len(indents)
if (line.lstrip().startswith('for') or line.lstrip().startswith('while')):
indents.append(indent)
# We add steps at both levels of indentation for loops.
# Before for the initial condition check, after for subsequent condition
# checks.
step_limit += 2 ** len(indents)
return step_limit
|
def sequence_delta(previous_sequence, next_sequence):
""" Check the number of items between two sequence numbers. """
if previous_sequence is None:
return 0
delta = next_sequence - (previous_sequence + 1)
return delta & 0xFFFFFFFF
|
def _count_set_bits(i):
"""
Counts the number of set bits in a uint (or a numpy array of uints).
"""
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
|
def get_group_key(group_name):
"""Build group key"""
return 'cephx.groups.{}'.format(group_name)
|
def flatten_doc(doc, return_fields, exceptions=None):
"""
Parameters
----------
doc : dict
The document in the Solr response.
return_fields : string
A string of comma-separated field names.
exceptions : list, optional
A list of names of fields that should not be flattened.
Flattens single-item list fields returned by Solr.
"""
if type(doc) is not dict:
raise ValueError('Document must be a dictionary.')
for field in return_fields.split(","):
if exceptions is not None and field in exceptions:
continue
elif field not in doc:
continue
else:
doc[field] = doc[field][0] if len(doc[field]) == 1 else doc[field]
return doc
|
def sorted_with_prefix(prefix, it, drop_exact=True, drop_special=True):
"""
>>> sorted_with_prefix("foo", ["fooZ", "fooAA", "fox"])
['fooAA', 'fooZ']
>>> sorted_with_prefix("", ["fooZ", "fooAA", "_f", "__f", "fox"])
['fooAA', 'fooZ', 'fox', '_f']
>>> sorted_with_prefix("", ["fooZ", "fooAA", "_f", "__f", "fox"], drop_special=False)
['fooAA', 'fooZ', 'fox', '_f', '__f']
"""
key = lambda name: (name.startswith("__"), name.startswith("_"), name)
return sorted([
el for el in it
if el.startswith(prefix) and (not drop_exact or el != prefix)
and (not drop_special or not el.startswith("__"))
], key=key)
|
def compute_in_degrees(digraph):
""" dict -> dict
Takes a digraph represented as a dictionary, and returns a dictionary in
which the keys are the nodes and the values is the node's indegree value.
"""
indegrees = {}
for node in digraph:
indegrees[node] = 0
for node in digraph:
for edge in digraph[node]:
indegrees[edge] += 1
return indegrees
|
def nset(dic, keys, val):
""" Set a nested key-value pair - in-place.
No-op when a value already exists.
Example:
x = {}
nset(x, ['a', 'b', 'c'], 0)
print(x)
> {'a': {'b': {'c': 0}}}
"""
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = dic.setdefault(keys[-1], val)
return dic
|
def loadConfigFromValuesNoCase(conf, key, values):
"""NOTE: The values must all be lowercase (e.x. \"highest\")"""
value = conf.get('all', key).lower()
if value in values:
return value
else:
raise Exception("ERROR: Configuration \'" + key + "\' was an invalid value, unable to run!")
|
def check_if_present(a,b):
"""
to check if b contains only letters from a, only once
a='abcdei'
b='is'
"""
_len=0
for i in a:
if b.count(i) > a.count(i):
return -1
if b.count(i)== a.count(i):
_len+=1
#print i,b.count(i)
if _len == len(b):
return 1
else:
return 0
|
def interleave_lists(*args):
"""Interleaves N lists of equal length."""
for l in args:
assert len(l) == len(args[0]) # all lists need to have equal length
return [val for tup in zip(*args) for val in tup]
|
def sort_module(module_reqs):
"""Sort modules based on dependency relations.
"""
module_sorted = []
module_depth = {}
def dfs(module_name):
max_depth = 0
if module_name in module_reqs.keys():
for req in module_reqs[module_name]:
max_depth = max(max_depth, dfs(req)+1)
module_depth[module_name] = max_depth
return max_depth
for req in module_reqs:
dfs(req)
for depth in range(len(module_reqs.keys())):
for module, mdepth in module_depth.items():
if mdepth == depth:
module_sorted.append(module)
return module_sorted
|
def munge_level(lvl):
"""
Turn obnoxious data like 'level': 'wizard/sorceror 2, bard 3' into
'level': {'wizard': 2, 'sorceror': 2, 'bard': 3}
"""
lvls = {}
for spec in lvl.split(','):
if len(spec) < 0:
continue
cls, lvl = spec.split()
if '/' in cls:
cls = cls.split('/')
else:
cls = [cls]
for c in cls:
lvls[c] = int(lvl)
return lvls
|
def update_hand(hand, word):
"""
Does NOT assume that hand contains every letter in word at least as
many times as the letter appears in word. Letters in word that don't
appear in hand should be ignored. Letters that appear in word more times
than in hand should never result in a negative count; instead, set the
count in the returned hand to 0 (or remove the letter from the
dictionary, depending on how your code is structured).
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
word = word.lower()
new_hand = hand.copy()
for i in word:
if hand.get(i, 0):
if new_hand.get(i, 0) <= 1:
del(new_hand[i])
else:
new_hand[i] = new_hand.get(i, 0) - 1
return new_hand
|
def schedule(epoch, lr):
"""
The learning rate schedule
Parameters:
epoch and current learning rate
Returns:
lr: updated learning rate
"""
if epoch==15:
lr=lr/4
return lr
|
def _is_currency(shape):
""" Check if this shape represents a Currency question; a 'ROUND_RECTANGLE' """
return shape.get('shapeType') == 'ROUND_RECTANGLE'
|
def s3_str(s, encoding="utf-8"):
"""
Convert an object into a str
Args:
s: the object
encoding: the character encoding
"""
if type(s) is str:
return s
elif type(s) is bytes:
return s.decode(encoding, "strict")
else:
return str(s)
|
def list_minus(l, minus):
"""Returns l without what is in minus
>>> list_minus([1, 2, 3], [2])
[1, 3]
"""
return [o for o in l if o not in minus]
|
def _get_node_url(node_type: str, node_name: str) -> str:
"""Constructs the URL to documentation of the specified node.
Args:
node_type (str): One of input, model, dabble, draw or output.
node_name (str): Name of the node.
Returns:
(str): Full URL to the documentation of the specified node.
"""
node_path = f"{node_type}.{node_name}"
url_prefix = "https://peekingduck.readthedocs.io/en/stable/nodes/"
url_postfix = ".html#module-"
return f"{url_prefix}{node_path}{url_postfix}{node_path}"
|
def layer_is_in_mark(layer, mark):
"""
Whether the given layer is in the given mark.
"""
return layer["mark"] == mark or ("type" in layer["mark"]
and layer["mark"]["type"] == mark)
|
def join(*args):
"""Concatenation of paths. Just for compatibility with normal python3."""
return "/".join(args)
|
def hexstr_to_dbytes(h,swap=True):
""" converts and swaps hex string represenation of hash to bytes for generating digest """
if h[:2] == "0x":
h = h[2:]
if len(h)%2 != 0:
h = h.zfill(len(h)+1)
num_bytes = len(h)//2
if swap:
return int(h,16).to_bytes(num_bytes,"little")
else:
return int(h,16).to_bytes(num_bytes,"big")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.