content
stringlengths 42
6.51k
|
---|
def function_lexer(string):
"""A brute force lexer for funcions of the SensorThings API.
Returns a list of the function and parameters"""
parsedlist = []
parsedstring = ''
leftbcounter = 0
rightbcounter = 0
for i, a in enumerate(string):
if a == '(':
leftbcounter += 1
if a == ')':
rightbcounter += 1
if a == '(' and leftbcounter != 1:
parsedstring += a
elif a == '(' and leftbcounter == 1:
parsedlist.append(parsedstring)
parsedstring = ''
elif a == ')' and i+1 == len(string):
parsedlist.append(parsedstring)
else:
parsedstring += a
return parsedlist
|
def make_mongo_url(user, pwd, url, db):
"""
makes the mongo url string
:param user: user
:param pwd: password
:param url: url
:param db: db
:return: mongo url string
"""
return "mongodb://" + user + ":" + pwd + "@" + url + "/" + db
|
def all_nums(table):
"""
Returns True if table contains only numbers (False otherwise)
Example: all_nums([[1,2],[3,4]]) is True
all_nums([[1,2],[3,'a']]) is False
Parameter table: The candidate table to modify
Preconditions: table is a rectangular 2d List
"""
result = True # Accumulator
# Check each row
# Check each item in each row
return result
|
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to underscores.
"""
value = value.strip().lower()
value = value.replace(',', '')
value = value.replace(' ', '_')
return value
|
def google_api_query(query_dict: dict) -> str:
"""Join given query args into one string.
Return query string in format required by googlapis:
https://developers.google.com/books/docs/v1/using#WorkingVolumes
"""
if not query_dict:
return ""
def allowed_google_item():
if item[1] and item[0] in ["intitle", "inauthor"]:
return True
return False
query_string = f"q={query_dict.get('search', '')}"
for i, item in enumerate(query_dict.items()):
if allowed_google_item():
query_string = f"{query_string}+{item[0]}:{item[1]}"
return query_string
|
def format32BitHexStr(hexStr):
"""
format the given string which represents a valid 32-bit hexadecimal number.
prefix "0x" will be added and will replace any valid prefix.
alphabetic letter will be formatted into upper case.
"0" will be used to fill the hexadecimal number if this number is represented as less than 8-letter.
Exmaple usage:
input: 0Xff -> output:0x000000FF
input: Ab -> output: 0x000000AB
input 0xAf -> output: 0x000000AF
:param hexStr: a valid string representing a 32-bit hexadecimal number
:return: a formatted string representing 32-bit hexadecimal number as described
"""
# remove "0x" or "OX" prefix if it had any
hexStr = hexStr.replace("0x", "").replace("0X", "")
hexStr = hexStr[0:8].zfill(8)
hexStr = hexStr.upper()
hexStr = "0x" + hexStr
return hexStr
|
def get_url_at_page_number(url: str, counter: int) -> str:
"""Retrieves the link to the next result page of a query."""
# All result pages will start out like this
root_url = "https://www.hearthstonetopdecks.com/cards/"
# Fhe first page of the query is followed by a string
# describing your query options, like this
query_url = url.split(root_url)[1]
# But subsequent pages have text describing the page number
# in between the rool url and the query text, as such:
next_url = f"page/{counter}/"
# Finally, reconstruct the next URL
return root_url + next_url + query_url
|
def makevar(name):
"""Make a variable name"""
return "var" + str(name)
|
def maprange(x, input: complex, output: complex):
"""Scales bound of `x` as of `input` and converts to another
bound as of `output`. `input` and `output` are complex numbers
whose `real` denotes minimum and `imag` denotes maximum value."""
a = input.real; b = input.imag
c = output.real; d = output.imag
return (x-a) * (d-c)/(b-a) + c
|
def price_text(price):
"""Give price text to be rendered in HTML"""
if price == 0:
return "Gratis"
return price
|
def Segments(n):
"""
n has to be greater than 3
"""
# divide Segment into 2 sub Segments
if n % 2 == 0:
n_1 = n / 2
n_2 = n / 2
else:
n_1 = (n + 1) / 2
n_2 = n - n_1
# determine the checking point index of the two sub Segments
if n_1 % 2 == 0:
n_1_checking_point = n_1 / 2
else:
n_1_checking_point = (n_1 + 1) / 2
if n_2 % 2 == 0:
n_2_checking_point = n_2 / 2 + n_1
else:
n_2_checking_point = (n_2 + 1) / 2 + n_1
return n_1, n_2, n_1_checking_point, n_2_checking_point
|
def sample_data_path(name):
"""return the static path to a CatEyes sample dataset.
Parameters
----------
name : str
The example file to load. Possible names are: 'example_data',
'example_events' and 'test_data_full'.
Returns
-------
data_path : str
The absolute path leading to the respective .csv file on your
machine.
"""
import os.path as op
data_dir = op.join(op.dirname(__file__), "data")
data_path = op.join(data_dir, name + ".csv")
return op.abspath(data_path)
|
def _classify(srna_type, attr, samples):
"""
Parse the line and return one
line for each category and sample.
"""
# iso_5p, iso_3p, iso_add ...
# FILTER :: exact/isomiR_type
lines = []
counts = dict(zip(samples, attr['Expression'].split(",")))
for s in counts:
if int(counts[s]) > 0:
lines.append([srna_type, s, counts[s]])
if attr['Variant'].find("iso") == -1:
continue
for v in attr['Variant'].split(","):
if int(counts[s]) > 0:
lines.append([v.split(":")[0], s, counts[s]])
return lines
|
def champZ(commande):
"""
Commande CC pour ajouter un Scalar Field pour la composante Z
"""
commande+=" -coord_to_SF Z"
#subprocess.call(commande)
return commande
|
def date_to_int(d):
"""
Represents a date object as an integer, or 0 if None.
"""
if d is None:
return 0
return int(d.strftime('%Y%m%d'))
|
def Clamp(val, min, max):
"""
Clamps a given value to be between max and min parameters.
Converts value to float.
:param val: (float, int) Value to clamp
:param min: (float, int) Minimal value
:param max: (float, int) Maximal value
:returns: float
"""
val = float(val)
min = float(min)
max = float(max)
if val < min:
return min
elif val > max:
return max
else:
return val
|
def get_radii(coords):
""" Radii of x,y,z arrays in array. Distance from (0,0,0). """
return [(x**2+y**2+z**2)**.5 for x,y,z in coords]
|
def calculate_real_len(args):
"""
Calculate the real length of supplied arguments
:param args: args
:return: real length
"""
i = 0
for arg in args:
if arg is not None:
i += 1
return i
|
def indices_containing_substring(list_str, substring):
"""For a given list of strings finds the indices containing the substring.
Parameters
----------
list_str: list of strings
substring: substring
Returns
-------
index: containing the substring or -1
"""
indices = []
for i, s in enumerate(list_str):
if substring in s:
indices.append(i)
return indices
|
def normalize(hex_code):
"""Convert hex code to six digit lowercase notation.
"""
hex_digits = hex_code.lstrip('#')
if len(hex_digits) == 3:
hex_digits = ''.join(2 * c for c in hex_digits)
return '#{}'.format(hex_digits.lower())
|
def count_chars(s: str) -> dict:
"""Checking the chars number in a str example
:param s: {str}
:return: {dict}
"""
count_dict = {}
for c in s:
if c in count_dict:
count_dict[c] += 1
else:
count_dict[c] = 1
return count_dict
|
def match_pattern(
resource: bytes,
pattern: bytes,
mask: bytes,
ignored: bytes):
"""
Implementation of algorithm in:
https://mimesniff.spec.whatwg.org/#matching-a-mime-type-pattern
True if pattern matches the resource. False otherwise.
"""
if len(pattern) != len(mask):
return False
if len(resource) < len(pattern):
return False
start = 0
for byte in resource:
if byte in ignored:
start += 1
else:
break
iteration_tuples = zip(resource[start:], pattern, mask)
for resource_byte, pattern_byte, mask_byte in iteration_tuples:
masked_byte = resource_byte & mask_byte
if masked_byte != pattern_byte:
return False
return True
|
def format_bit(b):
"""
Converts a bit to a string.
>>> format_bit(0)
'0'
>>> format_bit(one)
'1'
"""
return '0' if b == 0 else '1'
|
def get_argument_score(user1, user2):
"""
Considers two twitter users and calculates some proxy of
'probability of argument' between them.
Score is either in [0, 1] or {0, 1} (undecided)
"""
# this is likely going to be a binary classifier
# or logistic regression model
#
# required:
# features (notably, numerical representation of such)
# pretrained model
#
# pretrained model requires:
# features
# training data!
score = 0.5
return score
|
def is_false(str_value):
"""
:param str_value: String to evaluate.
:returns: True if string represents TGN attribute False value else return True.
"""
return str_value.lower() in ('false', 'no', '0', 'null', 'none', '::ixnet::obj-null')
|
def get_key(val, search_dict):
"""
Gets dict key from supplied value.
val: Value to search
search_dict : Dictionary to search value for
"""
for key, value in search_dict.items():
if val in value:
return key
|
def interpolate_num(a, b, fraction):
"""Linear interpolation for numeric types.
Parameters
----------
a : numeric type
initial value
b : numeric type
final value
fraction : float
fraction to interpolate to between a and b.
Returns
----------
: numeric type
Interpolated value between a and b at fraction.
"""
return type(a)(a + (b - a) * fraction)
|
def insertion_sort(arr):
"""
insertion sort using swap
Time: O(n^2)
Space: O(1)
"""
for i in range(1, len(arr)):
j = i
while j > 0 and arr[j - 1] > arr[j]:
arr[j - 1], arr[j] = arr[j], arr[j - 1]
j -= 1
return arr
|
def get_number(s):
""" Check that s is number
In this plugin, heatmaps are created only for columns that contain numbers. This
function checks to make sure an input value is able to be converted into a number.
This function originally appeared in the image asembler plugin:
https://github.com/Nicholas-Schaub/polus-plugins/blob/imageassembler/polus-image-assembler-plugin/src/main.py
Inputs:
s - An input string or number
Outputs:
value - Either float(s) or False if s cannot be cast to float
"""
try:
return int(s)
except ValueError:
return s
|
def recursive_get(d, attr, default=None, sep='.'):
"""
Recursive getter with default dot separation
:param d:
:param attr:
:param default:
:param sep:
:return:
"""
if not isinstance(attr, str):
return default
if not isinstance(d, dict) or not dict:
return default
if sep:
items = attr.split(sep)
else:
items = [attr]
root = d
for p in items:
if p in root:
root = root[p]
else:
return default
return root
|
def overlap(_x: list, _y: list) -> float:
"""overlap coefficient (Unuse)
Szymkiewicz-Simpson coefficient)
https://en.wikipedia.org/wiki/Overlap_coefficient
"""
set_x = frozenset(_x)
set_y = frozenset(_y)
return len(set_x & set_y) / float(min(map(len, (set_x, set_y))))
|
def count_bitmap(b, n):
""" Counts the number of bitmaps occupied """
return 0 if n==0 else (1 if b&1==1 else 0) + count_bitmap(b>>1, n-1)
|
def preprocess_DFun_args(dfun):
"""Preprocess function arguments in function declaration `dfun`"""
assert "DFun_args" in dfun
dfun["DFun_args"] = [
{"tag": "DFun_arg", "DFun_arg_name": name, "DFun_arg_type": t}
for name, t in dfun["DFun_args"]
]
return dfun
|
def generate_access(metadata):
"""Generates access metadata section.
https://oarepo.github.io/publications-api/schemas/publication-dataset-v1.0.0.html#allOf_i0_allOf_i1_access
"""
return {
'record': 'restricted',
'files': 'restricted',
'owned_by': []
}
|
def convert_label_for_pixellink(old_class):
"""Convert input class name to new for PixelLink
Args: old_class: label to be converted
Return converted label name
"""
# IMAGE_TYPE_TEXT_DETECTION = ['TopTitleText','TopTitleWord', 'LeftTitleText','LeftTitleWord', 'Text', 'Word']
IMAGE_TYPE_TEXT_DETECTION = ['TopTitleText','TopTitleWord', 'Text', 'Word']
top_title_set = ['TopTitleText','TopTitleWord']
# left_title_set = ['LeftTitleText','LeftTitleWord']
text_word_set = ['Text', 'Word']
top_title = 'TopTitle'
# left_title = 'LeftTitle'
text_word = 'Text'
if old_class in top_title_set:
return top_title
# elif old_class in left_title_set:
# return left_title
elif old_class in text_word_set:
return text_word
else:
print('\nInvalid label or not used: {}, please refer to labels in: {}'.format(old_class, IMAGE_TYPE_TEXT_DETECTION))
return None
|
def calcInputUnits(c):
"""gets input units for a response, checking InstrumentSensitivity,
InstrumentPolynomial and the first Stage"""
units = None
if hasattr(c, 'Response'):
resp = c.Response
if hasattr(resp, 'InstrumentPolynomial'):
units = resp.InstrumentPolynomial.InputUnits
elif hasattr(resp, 'InstrumentSensitivity'):
units = resp.InstrumentSensitivity.InputUnits
elif hasattr(resp, 'Stage') and len(resp.Stage) > 0:
stage = resp.Stage[0]
if hasattr(stage, 'PolesZeros'):
units = stage.PolesZeros.InputUnits
elif hasattr(stage, 'Coefficients'):
units = stage.Coefficients.InputUnits
elif hasattr(stage, 'ResponseList'):
units = stage.ResponseList.InputUnits
elif hasattr(stage, 'FIR'):
units = stage.FIR.InputUnits
elif hasattr(stage, 'Polynomial'):
units = stage.Polynomial.InputUnits
return units
|
def _batch_updates(updates):
"""Takes a list of updates of form [(token, row)] and sets the token to
None for all rows where the next row has the same token. This is used to
implement batching.
For example:
[(1, _), (1, _), (2, _), (3, _), (3, _)]
becomes:
[(None, _), (1, _), (2, _), (None, _), (3, _)]
"""
if not updates:
return []
new_updates = []
for i, update in enumerate(updates[:-1]):
if update[0] == updates[i + 1][0]:
new_updates.append((None, update[1]))
else:
new_updates.append(update)
new_updates.append(updates[-1])
return new_updates
|
def get_version(version_info):
"""Return a PEP-386 compliant version number from version_info."""
assert len(version_info) == 5
assert version_info[3] in ('alpha', 'beta', 'rc', 'final')
parts = 2 if version_info[2] == 0 else 3
main = '.'.join([str(part) for part in version_info[:parts]])
sub = ''
if version_info[3] == 'alpha' and version_info[4] == 0:
sub = '.dev'
elif version_info[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version_info[3]] + str(version_info[4])
return str(main + sub)
|
def term_A(P0, e0):
"""Term A in the main equation.
P0 is the atmospheric pressure at the site (in hPa).
e0 is the water vapor pressure at the site (in hPa)"""
return 0.002357 * P0 + 0.000141 * e0
|
def get_projects_by_4(p):
""" The frontend displays a list of projects in 4 columns. This function
splits the list of the projects visible by the user in chunks of size 4
and returns it."""
# Split the list of visible projects by chunks of size 4
projects = sorted([e['id'] for e in p['projects']])
n = 4 # split projects in chunks of size 4
projects_by_4 = [projects[i * n:(i + 1) * n]
for i in range((len(projects) + n - 1) // n)]
return projects_by_4
|
def is_pull_request(issue):
"""Return True if the given issue is a pull request."""
return 'pull_request_url' in issue
|
def extract_label_signature(autodoc_line):
"""Extract the object name and signature of the object being document.
For example::
>>> extract_label_signature(':: foo(a, b)')
'foo', 'foo(a, b)'
>>> extract_label_signature(':: foo')
'foo', None
"""
_, what = autodoc_line.split("::")
if "(" in what:
signature = what.strip()
what, *_ = what.partition("(")
else:
signature = None
# NOTE: if given, the signature is already stripped
return what.strip(), signature
|
def validate_probability(p: float, p_str: str) -> float:
"""Validates that a probability is between 0 and 1 inclusively.
Args:
p: The value to validate.
p_str: What to call the probability in error messages.
Returns:
The probability p if the probability if valid.
Raises:
ValueError if the probability is invalid.
"""
if p < 0:
raise ValueError(f'{p_str} was less than 0.')
elif p > 1:
raise ValueError(f'{p_str} was greater than 1.')
return p
|
def check_bounds_overlap(bounds_1, bounds_2):
"""
Calculate the ratio of overlap
"""
left_1, top_1, right_1, bottom_1 = bounds_1[0], bounds_1[1], bounds_1[2], bounds_1[3]
left_2, top_2, right_2, bottom_2 = bounds_2[0], bounds_2[1], bounds_2[2], bounds_2[3]
width_1 = right_1 - left_1
height_1 = bottom_1 - top_1
width_2 = right_2 - left_2
height_2 = bottom_2 - top_2
overlap_width = width_1 + width_2 - (max(left_1 + width_1, left_2 + width_2) - min(left_1, left_2))
overlap_height = height_1 + height_2 - (max(top_1 + height_1, top_2 + height_2) - min(top_1, top_2))
if overlap_height <= 0 or overlap_width <= 0:
return False
overlap_area = overlap_height * overlap_width
bounds_1_area = width_1 * height_1
bounds_2_area = width_2 * height_2
ratio = overlap_area / (bounds_1_area + bounds_2_area - overlap_area)
return ratio
|
def intseq(words, w2i, unk='.unk'):
"""
Convert a word sequence to an integer sequence based on the given codebook.
:param words:
:param w2i:
:param unk:
:return:
"""
res = [None] * len(words)
for j, word in enumerate(words):
if word in w2i:
res[j] = w2i[word]
else:
res[j] = w2i[unk]
return res
|
def extract_github_owner_and_repo(github_page):
"""
Extract only owner and repo name from GitHub page
https://www.github.com/psf/requests -> psf/requests
Args:
github_page - a reference, e.g. a URL, to a GitHub repo
Returns:
str: owner and repo joined by a '/'
"""
if github_page == "":
return ""
# split on github.com
split_github_page = github_page.split("github.com")
# take portion of URL after github.com and split on slashes
github_url_elements = split_github_page[1].split("/")
# rejoin by slash owner and repo name
github_owner_and_repo = ("/").join(github_url_elements[1:3])
return github_owner_and_repo
|
def strip_list(xs, e):
"""Get rid of all rightmost 'e' in
the given list."""
p = len(xs) - 1
while p >= 0 and xs[p] == e:
p -= 1
return xs[:p+1]
|
def hex_to_byte(hex_str):
"""
Convert a string hex byte values into a byte string. The Hex Byte values may
or may not be space separated.
:param hex_str: hex string msg with UUID.
:return: byte string msg with UUID.
"""
# The list comprehension implementation is fractionally slower in this case
#
# hexStr = ''.join( hexStr.split(" ") )
# return ''.join( ["%c" % chr( int ( hexStr[i:i+2],16 ) ) \
# for i in range(0, len( hexStr ), 2) ] )
bytes_str = []
hex_str = ''.join(hex_str.split(" "))
for i in range(0, len(hex_str), 2):
bytes_str.append(chr(int(hex_str[i:i + 2], 16)))
return ''.join(bytes_str)
|
def mySqrt(x):
"""
:type x: int
:rtype: int
"""
if x <= 0:
return x
x0=x
hk=0
while 1:
hk=(pow(x0,2)-x)/(2*x0)
x0 -= hk
if hk < 0.1:
break
return int(x0)
|
def _strip_quote(value):
"""
Removing the quotes around the edges
"""
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
return value
|
def has_three_or_more_vowels(string):
"""Check if string has three or more vowels."""
return sum(string.count(vowel) for vowel in 'aeiou') >= 3
|
def from_letter_base(letters):
"""Tranforms a letter base number into an integer."""
n = 0
for i, letter in enumerate(letters):
n += (ord(letter) - 64) * pow(26, len(letters) - (i + 1))
return n - 1
|
def ordset(xs):
"""
a generator for elements of xs
with duplicates removed
"""
return tuple(dict(zip(xs, xs)))
|
def time_delta(t1: int, t2: int) -> float:
"""
:param t1: first timestamp
:param t2: second timestamp
:return: time delta
"""
return (t2 - t1) / 3600000
|
def filter_jump_paths(simple_paths):
""" Filter jump simple path or simple cycle(as a special case of simple path).
Args:
simple_paths (list): a list of simple paths, where each path is a list.
Return:
List: a list of filtered simple paths.
"""
filter_scs = []
for sc in simple_paths:
valid_sc = True
for i in range(0, len(sc) - 2):
node1 = sc[i][:-1]
node2 = sc[i + 1][:-1]
node3 = sc[i + 2][:-1]
# Filter jump in the middle of a simple cycle
# There should not be 3 consecutive different nodes
if node1 != node2 and node2 != node3:
valid_sc = False
break
# Filter jump at the end of a sc
first = sc[0][:-1]
second = sc[1][:-1]
last = sc[-1][:-1]
second_last = sc[-2][:-1]
if last == second_last:
if first != second:
valid_sc = False
else:
if first != last:
valid_sc = False
if first == second:
if last != second_last:
valid_sc = False
if valid_sc:
filter_scs.append(sc)
return filter_scs
|
def intersector(x, y):
"""
Intersection between two tuples of counters [c_1, c_3, ..., c_d] [c'_1, c'_3, ..., c'_d].
Corresponds to the minimum between each c_i, c'_i.
:param x:
:type x:
:param y:
:type y:
:return:
:rtype:
"""
size = len(x)
res = []
for i in range(0, size):
res.append(min(x[i], y[i]))
return res
|
def applyF_filterG(L, f, g):
"""
Assumes L is a list of integers
Assume functions f and g are defined for you.
f takes in an integer, applies a function, returns another integer
g takes in an integer, applies a Boolean function,
returns either True or False
Mutates L such that, for each element i originally in L, L contains
i if g(f(i)) returns True, and no other elements
Returns the largest element in the mutated L or -1 if the list is empty
"""
# Your code here
mList = []
tmp = 0
#Calc New List
for i in L:
if g(f(i)):
mList.append(i)
#Apply Mutation
L.clear()
for i in mList:
L.append(i)
#Calc Retun Value
if len(mList) == 0:
return -1
else:
for i in mList:
tmp = max(tmp, i)
return tmp
|
def col_to_num(col_str):
""" Convert base26 column string to number. """
expn = 0
col_num = 0
for char in reversed(col_str):
col_num += (ord(char) - ord('A') + 1) * (26 ** expn)
expn += 1
return col_num
|
def store_by_slc_id(obj_list):
"""returns a dict where acquisitions are stored by their slc id"""
result_dict = {}
for obj in obj_list:
slc_id = obj.get('_source', {}).get('metadata', {}).get('title', False)
if slc_id:
result_dict[slc_id] = obj
return result_dict
|
def minmax(s):
"""Return the minimum and maximum elements of a sequence. Hint: start
with defining two variables at the beginning.
>>> minmax([1, 2, -3])
(-3, 2)
>>> minmax([2])
(2, 2)
>>> minmax([])
(None, None)
"""
if s:
max = s[0]
min = s[0]
for x in s:
if x > max:
max = x
if x < min:
min = x
return (min, max)
else:
return (None, None)
|
def replace_if_none(to_be_checked, replacement_string):
"""Return a replacement is to be checked is empty (None or empty string)"""
if to_be_checked:
return to_be_checked
return replacement_string
|
def check_horizontal_winner(board) -> bool:
"""checks for horizontal winner"""
for row in board:
if row[0] == row[1] == row[2] and row[0] is not None:
return True
return False
|
def get_most_freq_cui(cui_list, cui_freq):
"""
from a list of strings get the cui string that appears the most frequently.
Note: if there is no frequency stored then this will crash.
"""
cui_highest_freq = None
for cui in cui_list:
if cui in cui_freq:
# sets an initial cui
if cui_highest_freq is None:
cui_highest_freq = cui
# assign new highest
elif cui_freq[cui] > cui_freq[cui_highest_freq]:
cui_highest_freq = cui
# at this point we have not found any concept ids with a frequency greater than 0.
# good chance it is CUI-less
if cui_highest_freq is None:
cui_highest_freq = "CUI-less"
return cui_highest_freq
|
def add_extras(cosmo):
"""Sets neutrino number N_nu = 0, neutrino density
omega_n_0 = 0.0, Helium mass fraction Y_He = 0.24.
Also sets w = -1.
"""
extras = {'omega_n_0' : 0.0,
'N_nu': 0,
'Y_He': 0.24,
'w' : -1.0,
'baryonic_effects' : False
}
cosmo.update(extras)
return cosmo
|
def compression_ratio(obs_hamiltonian, final_solution):
"""Function that calculates the compression ratio of the procedure.
Args:
- obs_hamiltonian (list(list(str))): Groups of Pauli operators making up the Hamiltonian.
- final_solution (list(list(str))): Your final selection of observables.
Returns:
- (float): Compression ratio your solution.
"""
# QHACK
initial=len(obs_hamiltonian)
final=len(final_solution)
r=1-(final/initial)
return r
# QHACK
|
def joinPathSplit(pathSplit):
"""
Join the pathSplit with '/'
"""
return "/".join(pathSplit)
|
def format_span_id(span_id):
"""Format the span id according to b3 specification."""
return format(span_id, '016x')
|
def instance_or_id_to_snowflake(obj, type_, name):
"""
Validates the given `obj` whether it is instance of the given `type_`, or is a valid snowflake representation.
Parameters
----------
obj : `int`, `str` or`type_` instance
The object to validate.
type_ : `type` of (`tuple` of `type`)
Expected type.
name : `str`
The respective name of the object.
Returns
-------
snowflake : `int`
Raises
------
TypeError
If `obj` was not given neither as `type_`, `str` or `int` instance.
ValueError
If `obj` was given as `str` or as `int` instance, but not as a valid snowflake.
Notes
-----
The given `type_`'s instances must have a `.id` attribute.
"""
obj_type = obj.__class__
if issubclass(obj_type, type_):
snowflake = obj.id
else:
if obj_type is int:
snowflake = obj
elif issubclass(obj_type, str):
if 6 < len(obj) < 18 and obj.isdigit():
snowflake = int(obj)
else:
raise ValueError(f'`{name}` was given as `str` instance, but not as a valid snowflake, got {obj!r}.')
elif issubclass(obj_type, int):
snowflake = int(obj)
else:
if type(type_) is tuple:
type_name = ', '.join(t.__name__ for t in type_)
else:
type_name = type_.__name__
raise TypeError(f'`{name}` can be given either as {type_name} instance, or as `int` or `str` representing '
f'a snowflake, got {obj_type.__name__}.')
if snowflake < 0 or snowflake>((1<<64)-1):
raise ValueError(f'`{name}` was given either as `int` or as `str` instance, but not as representing a '
f'`uint64`, got {obj!r}.')
return snowflake
|
def remove_prefix(text, prefix):
""" remove prefix from text
"""
if text.startswith(prefix):
return text[len(prefix):]
return text
|
def get_tag_name(number):
"""Convert a pinColor to a tag string"""
if number == 0:
return "Food"
elif number == 1:
return "Drink"
elif number == 2:
return "Coffee"
elif number == 3:
return r"Coffee\ Supplies" #dayone2 cli needs the space escaped
elif number == 4:
return "Tea"
|
def calc_line(p1, p2):
"""
Calculates line from two points p1 and p2 by
returning a, b, c from line formula ax + by = c
:param p1: point 1, represented as x, y coordinates
:param p2: point 2, represented as x, y coordinates
:return: a, b, -c from line formula ax + by = c
"""
a = (p1[1] - p2[1])
b = (p2[0] - p1[0])
c = (p1[0] * p2[1] - p2[0] * p1[1])
return a, b, -c
|
def find_stats(_id, stats):
"""Find the latest activity stats for the SSG with `_id`.
"""
for ssg in stats:
if ssg["id"] == _id:
return ssg
return None
|
def _transform_data(data, data_mapper=None):
"""Use mapper or transformer to convert raw data to engineered before explanation.
:param data: The raw data to transform.
:type data: numpy, pandas, dense, sparse data matrix
:param data_mapper: A list of lists of generated feature indices for each raw feature.
:type data_mapper: list[list[]]
:return: The transformed data.
:rtype: numpy, pandas, dense, sparse data matrix
"""
if data_mapper is not None:
return data_mapper.transform(data)
return data
|
def find_nth(str1, mystr, n):
""" Finds a pattern in an input string and returns the starting index. """
start = str1.find(mystr)
while start >= 0 and n > 1:
start = str1.find(mystr, start+len(mystr))
n -=1
return start
|
def _config_split(value, delim, cast=None):
"""Splits the specified value using `delim` and optionally casting the
resulting items.
Args:
value (str): config option to split.
delim (str): string to split the option value on.
cast (function): to apply to each item after the split operation.
"""
if value is None:
return
if delim is None: # pragma: no cover
vals = value.split()
else:
vals = value.split(delim)
if cast is not None:
return list(map(cast, vals))
else:
return vals
|
def is_zero_len(value):
""" is value of zero length (or has no len at all)"""
return getattr(value ,'__len__', lambda : 0)() == 0
|
def mocked_search_execute(search_query: str, search_part: str, search_type: str, max_results: int):
"""
Currently only returns a response of video ID's based on max_results.
Otherwise returns none.
"""
if search_type == 'video' and search_part == 'id':
items = [{'id': {'videoId': str(i).zfill(11)}} for i in range(max_results)]
return {'items': items}
return None
|
def parse_material(inp):
"""
Parse each material and create a map with it's name and the amount.
"""
material_map = {}
for x in inp.split(", "):
amount, name = x.split(" ")
material_map[name] = int(amount)
return material_map
|
def index(it, ind):
""" Fancy indexing into an indexable iterable (tuple, list).
Examples
========
>>> from sympy.unify.core import index
>>> index([10, 20, 30], (1, 2, 0))
[20, 30, 10]
"""
return type(it)([it[i] for i in ind])
|
def gs_to_accel(data):
""" Convert to m/s^2
:param data:
:return: data in m/s^2
"""
import numpy as np
return np.array(data) * 9.8
|
def is_integer(value):
"""
check if value is an interger
"""
try:
v = int(value)
return True
except ValueError:
return False
|
def b2i(byte_string):
""" big endian byte array to integer value """
return int.from_bytes(byte_string, byteorder="big", signed=False)
|
def infinite(smaj, smin, bpa):
"""
If the beam is not correctly fitted by AWimager, one or more parameters
will be recorded as infinite.
:param smaj: Semi-major axis (arbitrary units)
:param smin: Semi-minor axis
:param bpa: Postion angle
"""
return smaj == float('inf') or smin == float('inf') or bpa == float('inf')
|
def is_file(line: str) -> bool:
"""Check if a return line is a song file."""
return line.startswith('file:')
|
def giniIndex(p_m1):
"""
G = sum_k { p_mk(1-p_mk }
"""
G = p_m1*(1-p_m1)*2
return G
|
def not_list_tuple(obj):
"""return False if obj is a list or a tuple"""
return not isinstance(obj, (list, tuple))
|
def genome_2_cortical_list(flat_genome):
"""
Generates a list of cortical areas inside genome
"""
cortical_list = list()
for key in flat_genome:
cortical_id = key[9:15]
if cortical_id not in cortical_list and key[7] == "c":
cortical_list.append(cortical_id)
return cortical_list
|
def _clean_listofcomponents_tuples(listofcomponents_tuples):
"""force 3 items in the tuple"""
def to3tuple(item):
"""return a 3 item tuple"""
if len(item) == 3:
return item
else:
return (item[0], item[1], None)
return [to3tuple(item) for item in listofcomponents_tuples]
|
def _wordwrap(text, chars_per_line=80):
"""Split the lines of a text between whitespaces when a line length exceeds
the specified number of characters. Newlines already present in text are
kept.
"""
text_ = text.split('\n')
text = []
for l in text_:
if len(l) > chars_per_line:
l = l.split()
c = 0
i = 0
_prev_i = 0
while i < len(l):
while c <= chars_per_line and i < len(l):
c += len(l[i])
if i < (len(l) - 1):
c += 1 # whitespace char
i += 1
if c > chars_per_line:
i -= 1
text.append(' '.join(l[_prev_i:i]))
_prev_i = i
c = 0
else:
text.append(l)
# drop any trailing empty lines
while not text[-1].strip():
text.pop()
return '\n'.join(text)
|
def normalize(y_eval, mean_y, std_y):
""" normalize outputs for GP
"""
return (y_eval - mean_y) / std_y
|
def sizes_by_key(sections, key):
""" Takes a dict of sections (from load_sections) and returns
a dict keyed by 'key' with aggregate output size information.
Key can be either "archive" (for per-archive data) or "file" (for per-file data) in the result.
"""
result = {}
for section in sections.values():
for s in section["sources"]:
if not s[key] in result:
result[s[key]] = {}
archive = result[s[key]]
if not section["name"] in archive:
archive[section["name"]] = 0
archive[section["name"]] += s["size"]
return result
|
def get_sample_name(sample, delimiter='_', index=0):
"""
Return the sample name
"""
return sample.split(delimiter)[index]
|
def find_high_index1(arr, key):
"""Find the high index of the key in the array arr.
Time: O(log n)
Space: O(1)
"""
lo, hi = 0, len(arr)
while lo < hi:
mi = (lo + hi) // 2
if arr[mi] <= key:
lo = mi + 1
elif arr[mi] > key:
hi = mi
if lo > 0 and arr[lo - 1] == key:
return lo - 1
return -1
|
def method_item(method, status, wsdl):
"""Function that sets the correct structure for method item"""
return {
'serviceCode': method[4],
'serviceVersion': method[5],
'methodStatus': status,
'wsdl': wsdl
}
|
def nearest_square(num):
"""Return the nearest perfect square that is
less than or equal to num"""
root =0
while (root +1) **2 <= num:
root +=1
return root**2
|
def csv_append(csv_string, item):
"""
Appends an item to a comma-separated string.
If the comma-separated string is empty/None, just returns item.
"""
if csv_string:
return ",".join((csv_string, item))
else:
return item
|
def deep_exclude(state: dict, exclude: list) -> dict:
"""[summary]
Args:
state (dict): A dict that represents the state of an instance.
exclude (list): Attributes that will be marked as 'removed'
Returns:
dict: [description]
"""
tuples = [key for key in exclude if isinstance(key, tuple)]
s = state
for loc in tuples:
for key in loc:
try:
s[key]
except Exception:
pass
else:
if key == loc[-1]:
s[key] = "*removed*"
else:
s = s[key]
return state
|
def parse_string_format(time_string):
""" Fixes some difficulties with different time formats """
format = "%Y-%m-%d %H:%M:%S"
if '.' in time_string:
format = "%Y-%m-%d %H:%M:%S.%f"
if time_string[-6] == '+':
format = format + "%z"
return format
|
def spin_words(sentence):
"""Take a string and reverse all words 5+ characters."""
answer_array = []
split = sentence.split(" ")
for word in split:
if len(word) < 5:
answer_array.append(word)
else:
answer_array.append(word[::-1])
return " ".join(answer_array)
|
def FindNearestElectrode(x, y, z, electrodes={}):
"""
finds the nearest electrode in the dictionary electrodes
(x,y,z) is the coordinates of a proposed electrode
:param x: x coordinate of electrode
:param y: y coordinate of electrode
:param z: x coordinate of electrode
:param electrodes: dictionary of defined electrodes: electrodes[ide]=X=(xe, ye, ze)
:return: id of nearest electrode and distance and distance to
"""
distmin=1e88
idemin=None
for ide in electrodes:
X=electrodes[ide]
dist=((X[0]-x)**2 + (X[1]-y)**2 + (X[2]-z)**2)**0.5
if dist < distmin :
distmin=dist
idemin=ide
if not idemin is None:
return int(idemin), distmin
else:
return idemin, distmin
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.