content stringlengths 42 6.51k |
|---|
def build_filename_data(_bibcode:str) -> str:
"""
Builds the name for the data output file
"""
return '{}.json'.format(_bibcode) |
def get_item(dictionary, key):
"""Returns value corresponding to a certain key in a dictionary.
Useful if standard 'dot-syntax' lookup in templates does not work.
"""
return dictionary.get(key) |
def eformat(f, prec, exp_digits):
"""
Formats to Scientific Notation, including precise exponent digits
"""
s = "%.*e" % (prec, f)
mantissa, exp = s.split("e")
# add 1 to digits as 1 is taken by sign +/-
return "%sE%+0*d" % (mantissa, exp_digits + 1, int(exp)) |
def landeg(gL,gS,J,S,L):
""" Calculating the Lande factor g,
For fine structure: landeg(gL,gS,J,S,L)
For hyperfine structure: landeg(gJ,gI,F,I,J)
"""
return gL * (J * (J + 1) - S * (S + 1) + L * (L + 1)) / (2 * J * (J + 1)) + \
gS * (J * (J + 1) + S * (S + 1) - L * (L + 1)) / (2 * J * (J + 1)) |
def recalculateEnergies(d, grid_number, min_energy, delta):
"""
For each density sample, we want the same exponential energy grid
:param d:
:param grid_number:
:param min_energy:
:param delta:
:return:
"""
densities = d.keys()
new_energies = []
for i in range(0, grid_number):
new_energy = min_energy * (delta**i)
new_energies.append(new_energy)
for i in densities:
d[i].update({'Energy (J/kg)': new_energies})
return d |
def stress_score(norm_power, threshold_power, duration):
"""Stress Score
Parameters
----------
norm_power : number
NP or xPower
threshold_power : number
FTP or CP
duration : int
Duration in seconds
Returns
-------
ss:
TSS or BikeScore
"""
ss = (duration/3600) * (norm_power/threshold_power)**2 * 100
return ss |
def urljoin(*args):
"""
Joins given arguments into a url. Trailing but not leading slashes are
stripped for each argument.
https://stackoverflow.com/a/11326230
"""
return "/".join(map(lambda x: str(x).strip('/').rstrip('/'), args)) |
def get_curated_date(date):
"""
remove the seconds etc, e.g., 2018-07-15T16:20:55 => 2018-07-15
"""
return date.strip().split('T')[0] |
def merge_dicts(dicts):
"""
Keep updating one dict with the values of the next
"""
result = {}
for item in dicts:
result.update(item)
return result |
def get_package_repo_name(package_info):
"""
The source repo name is stored with the package.
The "From repo" line indicates where the package came from.
Return the repo name or None if not found
"""
# should check that there is EXACTLY one line
repo_lines = \
[line for line in package_info if line.startswith("From repo ")]
# "From repo : <repo name>"
# Get the value and remove white space.
if len(repo_lines) > 0:
repo_name = repo_lines[0].split(':')[1].strip()
else:
repo_name = None
return repo_name |
def distance(strand_a, strand_b):
"""Determine the hamming distance between two RNA strings
param: str strand_a
param: str strand_b
return: int calculation of the hamming distance between strand_a and strand_b
"""
if len(strand_a) != len(strand_b):
raise ValueError("Strands must be of equal length.")
distance = 0
for i, _ in enumerate(strand_a):
if strand_a[i] != strand_b[i]:
distance += 1
return distance |
def xor(msg: bytes, key: bytes, strict: bool = False) -> bytes:
"""
XOR encrypts/decrypts a message
:param msg: Message to encrypt/decrypt
:type msg: bytes
:param key: Key to use
:type key: bytes
:param strict: If encrypting and this is set to True, the key MUST be at least as long as the message to enforce OTP rules, defaults to False
:type strict: bool, optional
:return: Encrypted/Decrypted message
:rtype: bytes
"""
if len(msg) > len(key) and strict:
raise ValueError("Key must be at least as long as the Message when Strict is set to True")
elif len(msg) > len(key): # Extend the key be the length of the message
key = (key * (int(len(msg)/len(key))+1))[:len(msg)]
return bytearray([c1 ^ c2 for c1, c2 in zip(msg, key)]) |
def validate_input(input_string):
"""
:param str input_string: A string input to the program for validation
that it will work wiht the diamond_challenge program.
:return: *True* if the string can be used to create a diamond.
*False* if cannot be used.
"""
if not isinstance(input_string, str) or len(input_string) != 1 \
or ord(input_string) < ord('A') or ord(input_string) > ord('Z'):
print("\nInvalid input! Please input a single capital letter (A-Z).\n")
return False
return True |
def stripiter(target: list):
"""Striping all of texts in list."""
out = []
for txt in target:
out.append(
str(txt)
.rstrip()
.lstrip()
)
return out |
def sort_font(fontlist):
"""
Returns a new list that is first sorted by the font's compatibleFamilyName3
(Windows compatible name), and secondly by the font's macStyle (style name).
"""
return sorted(fontlist, key=lambda font: (font.compatibleFamilyName3, font.macStyle)) |
def fix_single_tuple(x):
"""For scalar x, return x. For 1 element tuple, return x[0].
For multi-element tuple, return x.
"""
if isinstance(x, tuple):
if len(x) == 1:
return x[0]
return x |
def sum_digits(y):
"""Sum all the digits of y.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
>>> a = sum_digits(123) # make sure that you are using return rather than print
>>> a
6
"""
result = 0
cur = 0 # Current digit number
while y > 0:
cur = y % 10
y = y // 10
result += cur
return result |
def _BuildOutputFilename(filename_suffix):
"""Builds the filename for the exported file.
Args:
filename_suffix: suffix for the output file name.
Returns:
A string.
"""
if filename_suffix is None:
return 'results.html'
return 'results-{}.html'.format(filename_suffix) |
def compare_strings(first, second):
"""Compare two strings, returning the point of divergence and the equality"""
big = max(len(first), len(second))
small = min(len(first), len(second))
if big == small:
pairs = [(x,y) for x, y in zip(first, second)]
else:
pairs = [(x,y) for i, (x, y) in enumerate(zip(first, second))
if i < small - 1]
pairs.append((first[small - 1:], second[small - 1:]))
resemblance = sum(x == y for x, y in pairs) / big
differences = [(x,y) for x,y in pairs if x != y]
return resemblance, differences |
def argument(*name_or_flags, **kwargs):
"""Convenience function to properly format arguments to pass to the
subcommand decorator."""
return (list(name_or_flags), kwargs) |
def _filter_none_values(d: dict):
"""
Filters out the key-value pairs with None as value.
Arguments:
d
dictionary
Returns:
filtered dictionary.
"""
return {key: value for (key, value) in d.items() if value is not None} |
def oddNumbers(l, r):
"""
List odd numbers within a closed interval.
:param l: left interval endpoint (inclusive)
:param r: right interval endpoint (inclusive)
:return: odd numbers within [l, r].
"""
l = l if l % 2 == 1 else l + 1
r = r if r % 2 == 0 else r + 1
return list(range(l, r, 2)) |
def filter_none(d) :
"""
Remove items of a dictionary with None values.
Args:
d (:obj:`dict`): Dictionary object.
Returns:
:obj:`dict`: Dictionary without None items.
"""
if isinstance(d, dict) :
return {k: filter_none(v) for k,v in d.items() if v is not None}
elif isinstance(d, list) :
return [filter_none(v) for v in d]
else :
return d |
def filesize(file):
""" Returns the size of file sans any ID3 tag
"""
f=open(file)
f.seek(0,2)
size=f.tell()
try:
f.seek(-128,2)
except:
f.close()
return 0
buf=f.read(3)
f.close()
if buf=="TAG":
size=size-128
if size<0:
return 0
else:
return size |
def order_domain(var, assignment, board):
"""order domain"""
if (len(assignment) <= 1):
return assignment
cons_lev = {}
for i in assignment:
cons_lev[i] = 0
for v in board.values():
if v in assignment:
cons_lev[v] =+ 1
cons_lev = {k: v for k, v in sorted(cons_lev.items(), key=lambda item: item[1])}#, reverse = True)}
#get keys in sorted order
res = [k for k in cons_lev.keys()]
return res |
def add_vectors(vector_1, vector_2):
"""Example function. Sums the same index elements of two list of numbers.
Parameters
----------
v1 : list
List of ints or floats
v2 : list
List of ints or floats
Returns
-------
list
Sum of lists
Notes
-----
This is NOT good Python, just an example function for tests.
"""
sum_vec = []
for a, b in zip(vector_1, vector_2):
sum_vec.append(a + b)
return sum_vec |
def get_next_level_groups(groups):
"""
Find all groups of k+1 elements such that all of their subgroups with k elements are given.
Parameters
----------
groups: array of sorted touples - all valid groups of (indicies f) k detections identifies so far
Returns
-------
array of sorted touples
all potentially valid groups of k+1 detections to be chekced
"""
if len(groups) == 0:
return []
lengths = list(map(len, groups))
l = max(lengths)
assert(l == min(lengths)) #all groups must be the same length
max_i = max(map(max, groups)) #maximum element across all groups
#extend all groups by adding one element
#the added elements are larger then the largest element already in each group
#this endures uniquness of all results groups with l+1 elements/indices
potential_groups = [g + (j,) for g in groups for j in range(g[-1]+1,max_i+1)]
#a function for cheking that all sub-groups of the new groups are given
all_sub_exist = lambda g: all(g[:j] + g[j+1:] in groups for j in range(l+1))
#return only new groups withh all sub-groups given
return list(filter(all_sub_exist, potential_groups)) |
def _split_path(loc):
""" Split S3 path into bucket and prefix strings """
bucket = loc.split("s3://")[1].split("/")[0]
prefix = "/".join(loc.split("s3://")[1].split("/")[1:])
return bucket, prefix |
def doubled_label_fix(lbls, num, previous):
"""
Fix ground truth mix up where a sentence belogns to two sections in a
report.
:param lbls: The two labels that are confusing.
:param num: The sentence number in the report
:param previous: previous sentence label
:return: The correct label to use
"""
if (lbls == ['Title', 'Findings'] or lbls == ['Title', 'Impression']) and \
num <= 2:
lbls = ['Title']
if (lbls == ['Title', 'Findings'] or lbls == ['Title', 'Impression']) and \
num >= 2:
lbls = ['Findings']
if lbls == ['Findings', 'Impression']:
lbls = [previous]
if 'HX' in lbls and num<5:
lbls= ['HX']
if 'HX' in lbls and num > 5:
lbls = ['Dx']
if lbls == ['PrIM', 'Findings'] and previous==['HX']:
lbls = ['PrIM']
return lbls |
def abstract_injection_type(assignment):
"""
return an abstract type name for the type we have in the given assignment.
"""
if "[" in assignment["type"]:
return "array"
if not any(c in assignment["type"] for c in "[](){}"):
return "scalar"
return None |
def is_product_id(identifier):
"""Check if a given identifier is a product identifier
as opposed to a legacy scene identifier.
"""
return len(identifier) == 40 |
def inclusion_two_params_from_template(one, two):
"""Expected inclusion_two_params_from_template __doc__"""
return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)} |
def ifnone(*xs):
"""Return the first item in 'x' that is not None"""
for x in xs:
if x is not None: return x
return None |
def path_from_query(query):
"""
>>> path_from_query('/service?foo=bar')
'/service'
>>> path_from_query('/1/2/3.png')
'/1/2/3.png'
>>> path_from_query('foo=bar')
''
"""
if not ('&' in query or '=' in query):
return query
if '?' in query:
return query.split('?', 1)[0]
return '' |
def get_8_bit_fg_color(r, g, b):
"""Returns the color value in the 6x6x6 color space. The other color values are reserved for backwards compatibility"""
return '38;5;%d' % (16 + 36 * r + 16 * g + b) |
def can_run_for_president(age):
"""Can someone of the given age run for president in the US?"""
# The US Constitution says you must be at least 35 years old
return age >= 35 |
def accuracy_score(y_true, y_pred):
"""Accuracy classification score.
In multilabel classification, this function computes subset accuracy:
the set of labels predicted for a sample must *exactly* match the
corresponding set of labels in y_true.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
score : float.
Example:
>>> from seqeval.metrics import accuracy_score
>>> y_true = [['O', 'O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> y_pred = [['O', 'O', 'B-MISC', 'I-MISC', 'I-MISC', 'I-MISC', 'O'], ['B-PER', 'I-PER', 'O']]
>>> accuracy_score(y_true, y_pred)
0.80
"""
if any(isinstance(s, list) for s in y_true):
y_true = [item for sublist in y_true for item in sublist]
y_pred = [item for sublist in y_pred for item in sublist]
nb_correct = sum(y_t == y_p for y_t, y_p in zip(y_true, y_pred))
nb_true = len(y_true)
score = nb_correct / nb_true
return score |
def get_device(config):
""" Return the device portion of the part
Device portion of an example:
xc6slx9-tqg144-3: xc6slx9
Args:
config (dictionary): configuration dictionary
Return:
(string) device
Raises:
Nothing
"""
part_string = config["device"]
device = part_string.split("-")[0]
return device.strip() |
def square_sorted(A):
"""Given a sorted array, return a new array sorted by the squares of the
the elements.
[LC-977]
Example:
>>> square_sorted([-4, -1, 0, 3, 10])
[0, 1, 9, 16, 100]
>>> square_sorted([-7, -3, 2, 3, 11])
[4, 9, 9, 49, 121]
>>> square_sorted([-2, -1, 0, 2, 3])
[0, 1, 4, 4, 9]
>>> square_sorted([-3, -1, 0, 1, 2])
[0, 1, 1, 4, 9]
"""
left, right = 0, len(A) - 1
results = [0 for _ in A]
write_head = len(A) - 1
while left <= right:
left_squared = A[left] ** 2
right_squared = A[right] ** 2
if left_squared > right_squared:
results[write_head] = left_squared
left += 1
else:
results[write_head] = right_squared
right -= 1
write_head -= 1
return results |
def split_lists(original_list, max_slices):
""" Split a list into a list of small lists given the desired number of sub lists """
slices = max_slices - 1
original_list_size = len(original_list)
split_index = int(original_list_size / slices)
return [original_list[x:x + split_index] for x in range(0, len(original_list), split_index)] |
def in_range(value, minimum, maximum):
"""Check if value is in range."""
okay = True
if minimum >= 0 and value < minimum:
okay = False
elif maximum >= 0 and value > maximum:
okay = False
return okay |
def jump(orig):
"""encipher the plain text num"""
encoding = {'0': '5', '5': '0', '1': '9', '2': '8', '3': '7',
'4': '6', '6': '4', '7': '3', '8': '2', '9': '1'}
cipher = encoding[orig]
return cipher |
def _tile2lng(tile_x, zoom):
"""Returns tile longitude
Parameters
----------
tile_x: int
x coordinate
zoom: int
zoom level
Returns
-------
longitude
"""
return ((tile_x / 2 ** zoom) * 360.0) - 180.0 |
def parse_csv_header(line):
"""Parse the CSV header returned by TDS."""
units = {}
names = []
for var in line.split(','):
start = var.find('[')
if start < 0:
names.append(str(var))
continue
else:
names.append(str(var[:start]))
end = var.find(']', start)
unitstr = var[start + 1:end]
eq = unitstr.find('=')
if eq >= 0:
# go past = and ", skip final "
units[names[-1]] = unitstr[eq + 2:-1]
return names, units |
def _near_words(
first: str,
second: str,
distance: int,
exact: bool = False
) -> str:
"""
Returns a query term matching messages that two words within a certain
distance of each other.
Args:
first: The first word to search for.
second: The second word to search for.
distance: How many words apart first and second can be.
exact: Whether first must come before second [default False].
Returns:
The query string.
"""
query = f'{first} AROUND {distance} {second}'
if exact:
query = '"' + query + '"'
return query |
def sp(number, singular, plural):
""" Return either a singular or plural form of a noun based on a number. """
return singular if number == 1 else plural |
def resolve_checks(names, all_checks):
"""Returns a set of resolved check names.
Resolving a check name involves expanding tag references (e.g., '@tag') with
all the checks that contain the given tag.
names should be a sequence of strings.
all_checks should be a sequence of check classes/instances.
"""
resolved = set()
for name in names:
if name.startswith("@"):
for check in all_checks:
if name[1:] in check.tags:
resolved.add(check.name)
else:
resolved.add(name)
return resolved |
def testfn(arg):
"""
Test function for L{deferred} decorator.
Raises L{ValueError} if 42 is passed, otherwise returns whatever was
passed.
"""
if arg == 42:
raise ValueError('Oh noes')
return arg |
def check_keys_contain(result_keys, target_keys):
"""Check if all elements in target_keys is in result_keys."""
return set(target_keys).issubset(set(result_keys)) |
def valid_type(data):
"""
>>> valid_type(0.1)
True
>>> valid_type(1)
True
>>> valid_type("hola")
False
>>> valid_type([1, 2])
False
"""
return type(data) in [int, float] |
def breadcrumbs_li(links):
"""Returns HTML: an unordered list of URLs (no surrounding <ul> tags).
``links`` should be a iterable of tuples (URL, text).
"""
crumbs = ''
li_str = '<li><a href="{}">{}</a></li>'
li_str_last = '<li class="active"><span>{}</span></li>'
# Iterate over the list, except for the last item.
if len(links) > 1:
for i in links[:-1]:
crumbs += li_str.format(i[0], i[1])
# Add the last item.
crumbs += li_str_last.format(links[-1][1])
return crumbs |
def sat_proportional_filter(
input: float, abs_min=0.0, abs_max=10.0, factor=1) -> float:
"""
Simple saturated proportional filter
:param input : input value
:param abs_min and abs_max : upper and lower bound, abs value
:param factor : multiplier factor for the input value
:return : output filtered value, within boundary
"""
output = 0.0
input *= factor
if abs(input) < abs_min:
if (input < 0):
output = -abs_min
else:
output = abs_min
elif abs(input) > abs_max:
if (input > 0):
output = abs_max
else:
output = -abs_max
else:
output = input
return output |
def n_to_data(n):
"""Convert an integer to one-, four- or eight-unit graph6 sequence.
This function is undefined if `n` is not in ``range(2 ** 36)``.
"""
if n <= 62:
return [n]
elif n <= 258047:
return [63, (n >> 12) & 0x3F, (n >> 6) & 0x3F, n & 0x3F]
else: # if n <= 68719476735:
return [
63,
63,
(n >> 30) & 0x3F,
(n >> 24) & 0x3F,
(n >> 18) & 0x3F,
(n >> 12) & 0x3F,
(n >> 6) & 0x3F,
n & 0x3F,
] |
def _rotate_byte(byte, rotations):
"""Rotate byte to the left by the specified number of rotations."""
return (byte << rotations | byte >> (8-rotations)) & 0xFF |
def list_videos(plugin, item_id, category_url, **kwargs):
"""Build videos listing"""
return False
# videos_json = urlquick.get(URL_PLAYLIST % category_playlist).text
# videos_jsonparser = json.loads(videos_json)
# for video_data in videos_jsonparser["videos"]:
# item = Listitem()
# item.label = video_data["headline"]
# video_id = str(video_data["id"])
# for image in video_data["images"]:
# item.art['thumb'] = item.art['landscape'] = URL_ROOT + '/' + image["url"]
# item.info['plot'] = video_data["summary"]
# item.set_callback(get_video_url,
# item_id=item_id,
# video_id=video_id)
# item_post_treatment(item, is_playable=True, is_downloadable=True)
# yield item |
def handle_result(api_dict):
"""Extract relevant info from API result"""
result = {}
for key in {"title", "id", "body_safe", "locale", "section"}:
result[key] = api_dict[key]
return result |
def n_choose_k(n: int, k: int) -> int:
"""
Calulate the number of combinations in N choose K
When K is 0 or 1, the answer is returned directly. When K > 1, iterate to compute factoral to compute
nCk formula = n! / (k! (n-k)! by using m as an accumulator
:return: number of ways to choose k from n
"""
m = 0
if k == 0:
m = 1
if k == 1:
m = n
if k >= 2:
num, dem, op1, op2 = 1, 1, k, n
while(op1 >= 1):
num *= op2
dem *= op1
op1 -= 1
op2 -= 1
m = num//dem
return m |
def lookupDict(item_list, keyprop="key_string", valueTransform=None):
"""
keyprop can be 'key_string', 'key_id', or a property name
if valueProp is None, value at each key is full item from list
otherwise, run specified function to get value to store in dict
"""
lookup = {}
for item in item_list:
if not item:
continue
keyval = None
if keyprop == 'key_string':
keyval = str(item.key.urlsafe())
elif keyprop == 'key_id':
keyval = item.key.id()
if keyval:
if valueTransform:
val = valueTransform(item)
else:
val = item
lookup[keyval] = val
return lookup |
def evenify(num, oddify=False):
"""
Make sure an int is even... or false
returns: type int
"""
if oddify:
remainder = 1
else:
remainder = 0
if num % 2 == remainder:
return num
else:
return num + 1 |
def get_file_or_default(metric_file):
""" Returns the module name from which to extract metrics. Defaults to cohorts.metrics
:param str metric_file: The name of the module to extract metrics from
:return: The name of the module where metric functions reside
"""
return metric_file if metric_file is not None else 'cohorts.metrics' |
def find_choice_index(choice, choices):
"""
Finds the index of an item in a choice list.
"""
for choice_tuple in choices:
if choice == choice_tuple[1]:
return choice_tuple[0] - 1 |
def validateSyntax(func):
"""
Check if the function is valid.
Arguments: function
Warning: This function only checks if the function stays in the syntax limit. Further validation will be conducted later when an error is thrown.
"""
validSyntax = 'abcdefghijklmnopqrstuvwxz1234567890()+-*/^%!'
for a in func.lower():
if a not in validSyntax:
return False
return True |
def to_arcmin(crosshair, origin, pixels_per_arcmin):
"""Convert the crosshair location from pixels to arcmin.
Parameters
----------
crosshair : :class:`dict`
The location of the crosshair.
origin : :class:`dict`
The location of the origin.
pixels_per_arcmin : :class:`float`
The pixels/arcmin conversion factor.
Returns
-------
:class:`dict`
The coordinates of the crosshair, in arcmin units.
"""
try:
return {
'x': (crosshair['x'] - origin['x']) / pixels_per_arcmin,
'y': (origin['y'] - crosshair['y']) / pixels_per_arcmin,
}
except TypeError:
return {'x': None, 'y': None} |
def floating_point(v):
""" Is arg a floating point number ? """
return isinstance(v, float) |
def merge(b, c):
"""
Arguments:
Array1, Array2: Two sorted arrays b and c.
Return:
array_d: The merged version of b and c
"""
i = 0
j = 0
k = 0
n1 = len(b)
n2 = len(c)
array_d = [None]*(n1+n2)
# traverse both arrays
while i<n1 and j<n2:
if b[i] <= c[j]:
array_d[k] = b[i]
i+=1
k+=1
else:
array_d[k] = c[j]
j+=1
k+=1
while i < n1:
array_d[k] = b[i]
i+=1
k+=1
while j < n2:
array_d[k] = c[j]
j+=1
k+=1
return array_d |
def _count_relative_level(module_symbol: str) -> int:
"""Given a relative package name return the nested levels based on the number of leading '.' chars
Args:
module_symbol (str): relative module symbol
Returns:
int: relative import level
"""
module_symbol_cp = str(module_symbol)
levels = 0
# loop to compute how many layers up this relative import is by popping off the '.' char
# until it reaches a different char
while module_symbol_cp[0] == ".":
module_symbol_cp, next_char = module_symbol_cp[1:], module_symbol_cp[0]
if next_char == ".":
levels = levels + 1
else:
break
return levels |
def concat_and_filters(filters):
"""Task for an AND filter list
For more information see the API documentation
:param filters: the filter list to be concat
:type filters: List
:return: A Json filter formated
:rtype: Dict
"""
return {"operator": "And", "filters": filters} |
def _normalize_padding(padding):
"""Ensure that padding has format (left, right, top, bottom, ...)"""
if all(isinstance(p, int) for p in padding):
return padding
else:
npadding = []
for p in padding:
if isinstance(p, (list, tuple)):
npadding.extend(p)
else:
npadding.append(p)
npadding.append(p)
return npadding |
def includes_subpaths(path) :
"""Checks if a given path includes subpaths or not. It includes them if it
ends in a '+' symbol.
"""
return path[-1] == '+' |
def miller_rabin(n):
""" primality Test
if n < 3,825,123,056,546,413,051, it is enough to test
a = 2, 3, 5, 7, 11, 13, 17, 19, and 23.
Complexity: O(log^3 n)
"""
if n == 2:
return True
if n <= 1 or not n & 1:
return False
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
d = n - 1
s = 0
while not d & 1:
d >>= 1
s += 1
for prime in primes:
if prime >= n:
continue
x = pow(prime, d, n)
if x == 1:
continue
for r in range(s):
if x == n - 1:
break
if r + 1 == s:
return False
x = x * x % n
return True |
def strtobool(val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ("y", "yes", "t", "true", "on", "1"):
return 1
elif val in ("n", "no", "f", "false", "off", "0"):
return 0
else:
raise ValueError("invalid truth value %r" % (val,)) |
def isAbsolute(uri : str) -> bool:
""" Check whether a URI is Absolute. """
return uri is not None and uri.startswith('//') |
def floatformat(number, mind=2, maxd=4):
""" Format a floating point number into a string """
rounded = int(number * (10**mind)) / float(10**mind)
if number == rounded:
return ('%%.0%df' % mind) % number
else:
return ('%%.0%dg' % maxd) % number |
def query_decode(query):
# type: (str) -> str
"""Replaces "+" for " " in query"""
return query.replace("+", " ") |
def is_internal_mode(alignment_set, is_legacy):
"""See if alignmentset was collected in internal-mode."""
if is_legacy:
is_internal = True
else:
is_internal = 'PulseCall' in alignment_set.pulseFeaturesAvailable()
return is_internal |
def unique(iterable):
"""Uniquify elements to construct a new list.
Parameters
----------
iterable : collections.Iterable[any]
The collection to be uniquified.
Returns
-------
list[any]
Unique elements as a list, whose orders are preserved.
"""
def small():
ret = []
for e in iterable:
if e not in ret:
ret.append(e)
return ret
def large():
ret = []
memo = set()
for e in iterable:
if e not in memo:
memo.add(e)
ret.append(e)
return ret
if hasattr(iterable, '__len__'):
if len(iterable) < 16:
return small()
return large() |
def flat(l):
"""
Parameters
----------
l : list of list
Returns
-------
Flattened list
"""
return [item for sublist in l for item in sublist] |
def filter_uniq(item):
"""Web app, feed template, creates unique item id"""
detail = item['item']
args = (item['code'], item['path'], str(detail['from']), str(detail['to']))
return ':'.join(args) |
def validate_main_menu(user_input):
"""Validation function that checks if 'user_input' argument is an int 1-4. No errors."""
switcher = {
1: (True, 1),
2: (True, 2),
3: (True, 3),
4: (True, 4),
5: (True, 5),
6: (True, 6)
}
return switcher.get(user_input, (False, None)) |
def least_distance_only(annotation, new_annotations):
"""Condition function to keep only smallest distance annotation per image
Args:
annotation: Current annotation being examined
new_annotations: Dict of new annotations kept by image_name
Returns: True if annotation image is not yet in new_annotations or distance
is less than previous value. False otherwise.
"""
image_name = annotation["image_name"]
if image_name in new_annotations:
return annotation["distance"] < new_annotations[image_name]["distance"]
else:
return True |
def normalize_dict(dictionary: dict, dict_sum: float) -> dict:
""" Constrain dictionary values to continous range 0-1 based on the dictionary sum given.
Args:
- dictionary: the dictionary to be normalized.
- dict_sum: the sum value to normalize with.
"""
return {key: value/dict_sum if dict_sum > 0 else 0 for key, value in dictionary.items()} |
def pick_from_greatests(dictionary, wobble):
"""
Picks the left- or rightmost positions of the greatests list in a window
determined by the wobble size. Whether the left or the rightmost positions
are desired can be set by the user, and the list is ordered accordingly.
"""
previous = -100
is_picked_list = []
for pos, is_greatest in dictionary.items():
is_picked = False
if is_greatest:
if previous not in range(pos - wobble, pos + wobble + 1):
is_picked = True
previous = pos
is_picked_list.append(is_picked)
return is_picked_list |
def conv_bright_ha_to_lib(brightness) -> int:
"""Convert HA brightness scale 0-255 to library scale 0-16."""
if brightness == 255: # this will end up as 16 which is max
brightness = 256
return int(brightness / 16) |
def get_sorted_data(data: list, sort_by: str, reverse=True) -> list:
"""Get sorted data by column and order
Parameters
----------
data : list
Data stored in list of dicts
sort_by : str
Sort data by specific column
reverse : bool, optional
Flag to determinate order of sorting (False - asc, True - desc), by default True
Returns
-------
list
Sorted data stored in list of dicts
"""
return sorted(data, key=lambda k: (k[sort_by] is not None, k[sort_by]), reverse=reverse) |
def dimensions(rotor_lst):
""" Get the dimensions of each of the rotors
"""
return tuple(len(rotor) for rotor in rotor_lst) |
def find_smallest(arr):
"""Find Smallest value in an array."""
smallest = arr[0]
smallest_i = 0
for i, val in enumerate(arr):
if val < smallest:
smallest = val
smallest_i = i
return smallest_i |
def stage_check(x):
"""A simple function to chack if a string contains keyword '2'"""
import re
if re.compile('2',re.IGNORECASE).search(x):
return True
else:
return False |
def join_slices(*slices):
"""Join together contiguous slices by extending their start and/or end points.
All slices must be increasing, i.e. start < stop.
Identical slices will be removed.
Args:
*slices (iterable of slice): Slices to concatenate.
Examples:
>>> join_slices(slice(0, 2), slice(2, 4))
slice(0, 4, None)
>>> join_slices(slice(0, 2), slice(2, 4), slice(-2, 0))
slice(-2, 4, None)
Raises:
ValueError: If any of the given slices defines a step other than 1 or None.
ValueError: If the slices are not contiguous.
ValueError: If any of the slices are not increasing.
"""
if not slices:
raise ValueError("No slices were given.")
for s in slices:
if s.step not in (None, 1):
raise ValueError("Slices may not define a step other than 1 or None.")
if s.stop < s.start:
raise ValueError("Slices must be increasing.")
if len(slices) == 1:
return slices[0]
# Sort unique slices by their start.
slices = sorted(
(
slice(*elements)
for elements in set((s.start, s.stop, s.step) for s in slices)
),
key=lambda s: s.start,
)
# Ensure they are contiguous.
for s1, s2 in zip(slices[:-1], slices[1:]):
if s1.stop != s2.start:
raise ValueError("All slices must be contiguous.")
return slice(slices[0].start, slices[-1].stop) |
def add_article ( name ):
""" Returns a string containing the correct indefinite article ('a' or 'an')
prefixed to the specified string.
"""
if name[:1].lower() in 'aeiou':
return 'an ' + name
return 'a ' + name |
def is_chinese(name):
"""
Check if a symbol is a Chinese character.
Note
----
Taken from http://stackoverflow.com/questions/16441633/python-2-7-test-if-characters-in-a-string-are-all-chinese-characters
"""
if not name:
return False
for ch in name:
ordch = ord(ch)
if not (0x3400 <= ordch <= 0x9fff) and not (0x20000 <= ordch <= 0x2ceaf) \
and not (0xf900 <= ordch <= ordch) and not (0x2f800 <= ordch <= 0x2fa1f):
return False
return True |
def deg2HMS(ra=None, dec=None, round=False):
""" quick and dirty coord conversion. googled to find bdnyc.org.
"""
RA, DEC, rs, ds = '', '', '', ''
if dec is not None:
if str(dec)[0] == '-':
ds, dec = '-', abs(dec)
deg = int(dec)
decM = abs(int((dec-deg)*60))
if round:
decS = int((abs((dec-deg)*60)-decM)*60)
else:
decS = (abs((dec-deg)*60)-decM)*60
DEC = '{0}{1} {2} {3}'.format(ds, deg, decM, decS)
if ra is not None:
if str(ra)[0] == '-':
rs, ra = '-', abs(ra)
raH = int(ra/15)
raM = int(((ra/15)-raH)*60)
if round:
raS = int(((((ra/15)-raH)*60)-raM)*60)
else:
raS = ((((ra/15)-raH)*60)-raM)*60
RA = '{0}{1} {2} {3}'.format(rs, raH, raM, raS)
if ra is not None and dec is not None:
return (RA, DEC)
else:
return RA or DEC |
def codify(in_str: str) -> str:
"""
Cushions a string with four "`" character, used to indicated code in a Sphinx rst file.
:param in_str: The string to cushion
:return: The cushioned string
"""
return "``{}``".format(in_str) |
def levenshtein_distance(w1, w2):
"""
Parameters:
----------
w1: str
w2: str
Returns:
--------
int:
Returns Levenshtein edit distance between the two strings
"""
n1 = len(w1) + 1
n2 = len(w2) + 1
dist = [[0]*n2 for _ in range(n1)]
for i in range(n1):
dist[i][0] = i
for j in range(n2):
dist[0][j] = j
for x in range(1, n1):
for y in range(1, n2):
if w1[x-1] == w2[y-1]:
dist[x][y] = min(dist[x-1][y-1],
dist[x-1][y] + 1,
dist[x][y-1] + 1)
else:
dist[x][y] = min(dist[x-1][y-1] + 1,
dist[x-1][y] + 1,
dist[x][y-1] + 1)
return dist[n1-1][n2-1] |
def contain_any(iterable, elements):
"""
Return `True` if any of the `elements` are contained in the `iterable`,
`False` otherwise.
"""
for e in elements:
if e in iterable:
return True
return False |
def lowercase(string):
"""Convert string into lower case.
Args:
string: String to convert.
Returns:
string: Lowercase case string.
"""
return str(string).lower() |
def _query_builder(parameters):
"""Converts dictionary with queries to http-able query."""
queries = dict()
for key in parameters:
queries.setdefault(key, set())
if type(parameters[key]) in [list, set]:
# Union is Set.extend() in this context.
queries[key] = queries[key].union(set(parameters[key]))
else:
queries[key].add(parameters[key])
final_query = ""
for key, group in queries.items():
group = sorted(list(group))
for value in group:
single_query = f"&{key}={value}"
if single_query not in final_query:
final_query += single_query
final_query = final_query.lstrip('&')
return f"?{final_query}" |
def link(url, linkText='{url}'):
"""Returns a link HTML string.
The string is an <a> tag that links to the given url.
If linkText is not provided, the link text will be the url.
"""
template = '<a href={url}>' + linkText + '</a>'
return template.format(url=url) |
def check_proxy(host, port):
""" Is there even an appearance of something resembling a proxy on the set
up port?
"""
if host is None or port is None:
print("No proxy set up at options.yaml")
return False
import socket
with socket.socket() as proxy:
try:
proxy.connect((host, port))
return True
except ConnectionRefusedError:
print("No proxy on {}:{}?".format(host, str(port)))
return False |
def removeDuplicateEntries(outputList):
"""
Take a list of entries (dictionaries), and create a new list where duplicate
entries have been omitted. The basis for detecting duplication is the esaId key.
"""
newOutputList = []
esaIdSet = set()
for entry in outputList:
esaId = entry['esaId']
if esaId not in esaIdSet:
esaIdSet.add(esaId)
newOutputList.append(entry)
return newOutputList |
def get_pos_colors(image, x, y):
"""Get the color at a position or 0-vector, if the position is invalid."""
if x > 0 and y > 0 and len(image) > y and len(image[0]) > x:
return (image[y][x][0], image[y][x][1], image[y][x][2])
else:
return (0, 0, 0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.