content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
import math
def sieve(n):
"""
Returns a list with all prime numbers up to n.
>>> sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> sieve(10)
[2, 3, 5, 7]
>>> sieve(9)
[2, 3, 5, 7]
>>> sieve(2)
[2]
>>> sieve(1)
[]
"""
l = [True] * (n + 1) # noqa: E741
prime = []
start = 2
end = int(math.sqrt(n))
while start <= end:
# If start is a prime
if l[start] is True:
prime.append(start)
# Set multiples of start be False
for i in range(start * start, n + 1, start):
if l[i] is True:
l[i] = False
start += 1
for j in range(end + 1, n + 1):
if l[j] is True:
prime.append(j)
return prime | f6c930c604839ba1872bd3168c76b353606ee8ee | 708,558 |
def is_trueish(expression: str) -> bool:
"""True if string and "True", "Yes", "On" (ignorecase), False otherwise"""
expression = str(expression).strip().lower()
return expression in {'true', 'yes', 'on'} | 7d958c068281deb68de7665dc1eeb07acf5e941f | 708,559 |
import re
def contains_order_by(query):
"""Returns true of the query contains an 'order by' clause"""
return re.search( r'order\s+by\b', query, re.M|re.I) is not None | 4f4eebadfd5dc4cb1121378db4ef5f68d27bf787 | 708,560 |
import re
def __shorten_floats(source):
""" Use short float notation whenever possible
:param source: The source GLSL string
:return: The GLSL string with short float notation applied
"""
# Strip redundant leading digits
source = re.sub(re.compile(r'(?<=[^\d.])0(?=\.)'), '', source)
# Strip redundant trailing digits
return re.sub(re.compile(r'(?<=\d\.)0(?=\D)'), '', source) | 538645cde50e6c9a4ed3960cf6bbd177c5583381 | 708,561 |
from typing import OrderedDict
def elem_props_template_init(templates, template_type):
"""
Init a writing template of given type, for *one* element's properties.
"""
ret = OrderedDict()
tmpl = templates.get(template_type)
if tmpl is not None:
written = tmpl.written[0]
props = tmpl.properties
ret = OrderedDict((name, [val, ptype, anim, written]) for name, (val, ptype, anim) in props.items())
return ret | c31d5ca8224763701f44471f23f00454c4365240 | 708,562 |
def mean(l):
"""
Returns the mean value of the given list
"""
sum = 0
for x in l:
sum = sum + x
return sum / float(len(l)) | 74926c9aaafd2362ce8821d7040afcba1f569400 | 708,564 |
import re
def clean_hotel_maxpersons(string):
"""
"""
if string is not None:
r = int(re.findall('\d+', string)[0])
else:
r = 0
return r | d20d9db1da49eea1a4057e43b9f43f2960dbd27a | 708,565 |
from typing import OrderedDict
def merge_nodes(nodes):
"""
Merge nodes to deduplicate same-name nodes and add a "parents"
attribute to each node, which is a list of Node objects.
"""
def add_parent(unique_node, parent):
if getattr(unique_node, 'parents', None):
if parent.name not in unique_node.parents:
unique_node.parents[parent.name] = parent
else:
unique_node.parents = {parent.name: parent}
names = OrderedDict()
for node in nodes:
if node.name not in names:
names[node.name] = node
add_parent(names[node.name], node.parent)
else:
add_parent(names[node.name], node.parent)
return names.values() | 1f5a2a7188071d9d6f8b6ab1f25ceff1a0ba8484 | 708,566 |
def find_records(dataset, search_string):
"""Retrieve records filtered on search string.
Parameters:
dataset (list): dataset to be searched
search_string (str): query string
Returns:
list: filtered list of records
"""
records = [] # empty list (accumulator pattern)
for record in dataset:
if search_string.lower() in record.lower(): # case insensitive
records.append(record) # add to new list
return records | c6cbd5c239f410a8658e62c1bbacc877eded5105 | 708,567 |
from functools import reduce
def flatten(l):
"""Flatten 2 list
"""
return reduce(lambda x, y: list(x) + list(y), l, []) | 85b4fad4ef0326304c1ee44714d8132841d13b16 | 708,569 |
def get_mapping():
"""
Returns a dictionary with the mapping of Spacy dependency labels to a numeric value, spacy dependency annotations
can be found here https://spacy.io/api/annotation
:return: dictionary
"""
keys = ['acl', 'acomp', 'advcl', 'advmod', 'agent', 'amod', 'appos', 'attr', 'aux', 'auxpass', 'case', 'cc', 'ccomp',
'clf', 'compound', 'conj', 'cop', 'csubj', 'csubjpass', 'dative', 'dep', 'det', 'discourse', 'dislocated',
'dobj', 'expl', 'fixed', 'flat', 'goeswith', 'iobj', 'intj', 'list', 'mark',
'meta', 'neg', 'nn', 'nmod', 'nounmod', 'npadvmod', 'npmod', 'nsubj', 'nsubjpass', 'nummod', 'oprd', 'obj', 'obl',
'orphan', 'parataxis', 'pcomp', 'pobj', 'poss', 'preconj', 'predet', 'prep', 'prt', 'punct', 'quantmod', 'relcl',
'reparandum', 'root', 'vocative', 'xcomp', '']
values = list(range(2, len(keys) + 2))
assert len(keys) == len(values)
return dict(zip(keys, values)) | 164d2292bdd573a5805f9a66f685d21aac92061e | 708,570 |
def filter_spans(spans):
"""Filter a sequence of spans and remove duplicates or overlaps. Useful for
creating named entities (where one token can only be part of one entity) or
when merging spans with `Retokenizer.merge`. When spans overlap, the (first)
longest span is preferred over shorter spans.
spans (iterable): The spans to filter.
RETURNS (list): The filtered spans.
"""
get_sort_key = lambda span: (span.end - span.start, -span.start)
sorted_spans = sorted(spans, key=get_sort_key, reverse=True)
result = []
seen_tokens = set()
for span in sorted_spans:
# Check for end - 1 here because boundaries are inclusive
if span.start not in seen_tokens and span.end - 1 not in seen_tokens:
result.append(span)
seen_tokens.update(range(span.start, span.end))
result = sorted(result, key=lambda span: span.start)
return result | 3b15a79b14f02ffa870b94eb9b61261c4befc0eb | 708,571 |
import itertools
def generate_combinations (n, rlist):
""" from n choose r elements """
combs = [list(itertools.combinations(n, r)) for r in rlist]
combs = [item for sublist in combs for item in sublist]
return combs | 7339b61a7ea76813c8356cf4a87b1e81b67ce10e | 708,572 |
def get_description_value(name_of_file):
"""
:param name_of_file: Source file for function.
:return: Description value for particular CVE.
"""
line = name_of_file.readline()
while 'value" :' not in line:
line = name_of_file.readline()
tmp_list = line.split(':')
if len(tmp_list) == 2:
value = tmp_list[1][:]
return value
else:
# When description value contains ":" too.
concatenation = ""
for i in range(1, len(tmp_list)-1):
concatenation = concatenation + tmp_list[i] + ":"
concatenation = concatenation + tmp_list[-1]
return concatenation | a7b0915feff7fcd2a175bdb8fe9af48d0d9f14d7 | 708,573 |
from typing import Optional
from typing import List
def to_lines(text: str, k: int) -> Optional[List[str]]:
"""
Given a block of text and a maximum line length k, split the text into lines of length at most k.
If this cannot be done, i.e. a word is longer than k, return None.
:param text: the block of text to process
:param k: the maximum length of each line
:return: the list of lines
>>> text = 'the quick brown fox jumps over the lazy dog'
>>> to_lines(text, 4) is None
True
>>> to_lines(text, 5)
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
>>> to_lines(text, 9)
['the quick', 'brown fox', 'jumps', 'over the', 'lazy dog']
>>> to_lines(text, 10)
['the quick', 'brown fox', 'jumps over', 'the lazy', 'dog']
>>> to_lines(text, 12)
['the quick', 'brown fox', 'jumps over', 'the lazy dog']
>>> to_lines('AAAAA', 5)
['AAAAA']
"""
def line_to_str(l: List[str]) -> str:
return ' '.join(l)
# If there is no text or the line length is 0, we can't do anything.
if not text or not k:
return None
# If any word is longer then k, we can't do anything.
words = text.split()
if max(len(word) for word in words) > k:
return None
# Now split the word into lines.
lines = []
line = []
len_so_far = 0
for word in words:
len_word = len(word)
if len_word + len_so_far <= k:
# We add the word to the line plus a blank space afterwards.
# If this is the last word in the line, the blank space will not occur; hence why we check the
# condition <= k rather than < k.
line.append(word)
len_so_far += len_word + 1
else:
# Make the line into a string, add it to lines, and reset everything.
lines.append(line_to_str(line))
line = [word]
len_so_far = len_word + 1
# Last case: if we have a partial line, add it.
if line:
lines.append(line_to_str(line))
# Assert that none of the lines went over the length.
for line in lines:
assert(len(line) <= k)
return lines | 1797f45ce4999a29a9cc74def3f868e473c2775a | 708,575 |
def product_except_self(nums: list[int]) -> list[int]:
"""Computes the product of all the elements of given array at each index excluding the value at that index.
Note: could also take math.prod(nums) and divide out the num at each index,
but corner cases of num_zeros > 1 and num_zeros == 1 make code inelegant.
Args:
nums:
Returns:
Examples:
>>> product_except_self([])
[]
>>> product_except_self([1,2,3,4])
[24, 12, 8, 6]
>>> product_except_self([-1,1,0,-3,3])
[0, 0, 9, 0, 0]
"""
"""ALGORITHM"""
## INITIALIZE VARS ##
nums_sz = len(nums)
# DS's/res
nums_products_except_i = [1] * nums_sz
## Multiply against product of all elements PRECEDING i
total_product = 1
for i in range(nums_sz):
nums_products_except_i[i] *= total_product
total_product *= nums[i]
## Multiply against product of all elements FOLLOWING i
total_product = 1
for i in reversed(range(nums_sz)):
nums_products_except_i[i] *= total_product
total_product *= nums[i]
return nums_products_except_i | 15090d4873b0dec9ea6119e7c097ccda781e51fa | 708,576 |
def find_missing_letter(chars):
"""
chars: string of characters
return: missing letter between chars or after
"""
letters = [char for char in chars][0]
chars = [char.lower() for char in chars]
alphabet = [char for char in "abcdefghijklmnopqrstuvwxyz"]
starting_index = alphabet.index(chars[0])
for letter in alphabet[starting_index:]:
if letter not in chars and chars[0].lower() == letters[0]:
return letter
if letter not in chars and chars[0].upper() == letters[0]:
return letter.upper() | bc663b68ac49095285a24b06554337c1582c8199 | 708,577 |
def tally_cache_file(results_dir):
"""Return a fake tally cache file for testing."""
file = results_dir / 'tally.npz'
file.touch()
return file | 271c58cc263cf0bfba80f00b0831303326d4d1a8 | 708,578 |
import torch
def get_soft_label(cls_label, num_classes):
"""
compute soft label replace one-hot label
:param cls_label:ground truth class label
:param num_classes:mount of classes
:return:
"""
# def metrix_fun(a, b):
# torch.IntTensor(a)
# torch.IntTensor(b)
# metrix_dis = (a - b) ** 2
# return metrix_dis
def metrix_fun(a, b):
a = a.type_as(torch.FloatTensor())
b = b.type_as(torch.FloatTensor())
metrix_dis = (torch.log(a) - torch.log(b)) ** 2
return metrix_dis
def exp(x):
x = x.type_as(torch.FloatTensor())
return torch.exp(x)
rt = torch.IntTensor([cls_label]) # must be torch.IntTensor or torch.LongTensor
rk = torch.IntTensor([idx for idx in range(1, num_classes + 1, 1)])
metrix_vector = exp(-metrix_fun(rt, rk))
return metrix_vector / torch.sum(metrix_vector) | e08e6fc86252bf76dd8a852c63e92776b4fdcfc3 | 708,579 |
def get_option(args, config, key, default=None):
"""Gets key option from args if it is provided, otherwise tries to get it from config"""
if hasattr(args, key) and getattr(args, key) is not None:
return getattr(args, key)
return config.get(key, default) | 54d77c6ae3e40b2739156b07747facc4a952c237 | 708,580 |
import re
def parse_extension(uri):
""" Parse the extension of URI. """
patt = re.compile(r'(\.\w+)')
return re.findall(patt, uri)[-1] | 5ed4eee77b92f04e62390128939113168d715342 | 708,581 |
import math
def rotz(ang):
"""
Calculate the transform for rotation around the Z-axis.
Arguments:
angle: Rotation angle in degrees.
Returns:
A 4x4 numpy array of float32 representing a homogeneous coordinates
matrix for rotation around the Z axis.
"""
rad = math.radians(ang)
c = math.cos(rad)
s = math.sin(rad)
return [
[c, -s, 0.0, 0.0],
[s, c, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
] | 4332242c5818ccc00d64cbebf7a861727e080964 | 708,582 |
def getBits(data, offset, bits=1):
"""
Get specified bits from integer
>>> bin(getBits(0b0011100,2))
'0b1'
>>> bin(getBits(0b0011100,0,4))
'0b1100'
"""
mask = ((1 << bits) - 1) << offset
return (data & mask) >> offset | 0bdae35f5afa076d0e5a73b91d2743d9cf156f7d | 708,583 |
import argparse
def get_args():
"""
gets cli args via the argparse module
"""
msg = "This script records cpu statistics"
# create an instance of parser from the argparse module
parser = argparse.ArgumentParser(description=msg)
# add expected arguments
parser.add_argument('-s', dest='silent', required=False,
action="store_true",
help="dont display statistics to screen")
parser.add_argument('-a', dest='append', required=False,
action="store_true",
help="dont overwrite previous files")
parser.add_argument('-c', dest='convert', required=False,
action="store_true",
help="converts data to human readable")
parser.add_argument('-n', dest='noheader', required=False,
action="store_true", help="dont write header")
parser.add_argument('-R', dest='refresh', required=False)
parser.add_argument('-r', dest='runtime', required=False)
parser.add_argument('-o', dest='outfile', required=False)
args = parser.parse_args()
if args.silent:
silent = True
else:
silent = False
if args.noheader:
noheader = True
else:
noheader = False
if args.append:
append = True
else:
append = False
if args.refresh:
refresh = float(args.refresh)
else:
# default refresh i s 5 seconds
refresh = 5
if args.runtime:
runtime = float(args.runtime)
else:
# default runtime is eight hours
runtime = 28800
if args.outfile:
outfile = args.outfile
else:
outfile = 'memutil.csv'
if args.convert:
convert = True
else:
convert = False
return silent, noheader, refresh, runtime, append, outfile, convert | a97cdbf33710bac17d78581548970e85c2397e15 | 708,585 |
import copy
import json
def compress_r_params(r_params_dict):
"""
Convert a dictionary of r_paramsters to a compressed string format
Parameters
----------
r_params_dict: Dictionary
dictionary with parameters for weighting matrix. Proper fields
and formats depend on the mode of data_weighting.
data_weighting == 'dayenu':
dictionary with fields
'filter_centers', list of floats (or float) specifying the (delay) channel numbers
at which to center filtering windows. Can specify fractional channel number.
'filter_half_widths', list of floats (or float) specifying the width of each
filter window in (delay) channel numbers. Can specify fractional channel number.
'filter_factors', list of floats (or float) specifying how much power within each filter window
is to be suppressed.
Returns
-------
string containing r_params dictionary in json format and only containing one
copy of each unique dictionary with a list of associated baselines.
"""
if r_params_dict == {} or r_params_dict is None:
return ''
else:
r_params_unique = {}
r_params_unique_bls = {}
r_params_index = -1
for rp in r_params_dict:
#do not include data set in tuple key
already_in = False
for rpu in r_params_unique:
if r_params_unique[rpu] == r_params_dict[rp]:
r_params_unique_bls[rpu] += [rp,]
already_in = True
if not already_in:
r_params_index += 1
r_params_unique[r_params_index] = copy.copy(r_params_dict[rp])
r_params_unique_bls[r_params_index] = [rp,]
for rpi in r_params_unique:
r_params_unique[rpi]['baselines'] = r_params_unique_bls[rpi]
r_params_str = json.dumps(r_params_unique)
return r_params_str | 4e56badfb7ea773d9d1104b134aa61b83d8d2f2f | 708,586 |
def replace_ext(filename, oldext, newext):
"""Safely replaces a file extension new a new one"""
if filename.endswith(oldext):
return filename[:-len(oldext)] + newext
else:
raise Exception("file '%s' does not have extension '%s'" %
(filename, oldext)) | 33ab99860cfe90b72388635d5d958abe431fa45e | 708,587 |
import functools
import time
def debounce(timeout, **kwargs):
"""Use:
@debounce(text=lambda t: t.id, ...)
def on_message(self, foo=..., bar=..., text=None, ...)"""
keys = sorted(kwargs.items())
def wrapper(f):
@functools.wraps(f)
def handler(self, *args, **kwargs):
# Construct a tuple of keys from the input args
key = tuple(fn(kwargs.get(k)) for k, fn in keys)
curr = set()
if hasattr(self, '__debounce_curr'):
curr = self.__debounce_curr
prev = set()
if hasattr(self, '__debounce_prev'):
prev = self.__debounce_prev
now = time.time()
tick = time.time()
if hasattr(self, '__debounce_tick'):
tick = self.__debounce_tick
# Check the current and previous sets, if present
if key in curr or key in prev:
return
# Rotate and update
if now > tick:
prev = curr
curr = set()
tick = now + timeout
curr.add(key)
self.__debounce_curr = curr
self.__debounce_prev = prev
self.__debounce_tick = tick
# Call the wrapped function
return f(self, *args, **kwargs)
return handler
return wrapper | ac457a68834f1a6305ff4be8f7f19607f17e95fb | 708,589 |
import curses
def acs_map():
"""call after curses.initscr"""
# can this mapping be obtained from curses?
return {
ord(b'l'): curses.ACS_ULCORNER,
ord(b'm'): curses.ACS_LLCORNER,
ord(b'k'): curses.ACS_URCORNER,
ord(b'j'): curses.ACS_LRCORNER,
ord(b't'): curses.ACS_LTEE,
ord(b'u'): curses.ACS_RTEE,
ord(b'v'): curses.ACS_BTEE,
ord(b'w'): curses.ACS_TTEE,
ord(b'q'): curses.ACS_HLINE,
ord(b'x'): curses.ACS_VLINE,
ord(b'n'): curses.ACS_PLUS,
ord(b'o'): curses.ACS_S1,
ord(b's'): curses.ACS_S9,
ord(b'`'): curses.ACS_DIAMOND,
ord(b'a'): curses.ACS_CKBOARD,
ord(b'f'): curses.ACS_DEGREE,
ord(b'g'): curses.ACS_PLMINUS,
ord(b'~'): curses.ACS_BULLET,
ord(b','): curses.ACS_LARROW,
ord(b'+'): curses.ACS_RARROW,
ord(b'.'): curses.ACS_DARROW,
ord(b'-'): curses.ACS_UARROW,
ord(b'h'): curses.ACS_BOARD,
ord(b'i'): curses.ACS_LANTERN,
ord(b'p'): curses.ACS_S3,
ord(b'r'): curses.ACS_S7,
ord(b'y'): curses.ACS_LEQUAL,
ord(b'z'): curses.ACS_GEQUAL,
ord(b'{'): curses.ACS_PI,
ord(b'|'): curses.ACS_NEQUAL,
ord(b'}'): curses.ACS_STERLING,
} | 2121ab5dd650019ae7462d2ab34cf436966cffe9 | 708,590 |
import os
import sqlite3
import csv
def map2sqldb(map_path, column_names, sep='\t'):
"""Determine the mean and 2std of the length distribution of a group
"""
table_name = os.path.basename(map_path).rsplit('.', 1)[0]
sqldb_name = table_name + '.sqlite3db'
sqldb_path = os.path.join(os.path.dirname(map_path), sqldb_name)
conn = sqlite3.connect(sqldb_path) # @UndefinedVariable
c = conn.cursor()
# If table already exist, return the connector and the table_name
SQL = '''
SELECT count(*) FROM sqlite_master WHERE name == \"{}\"
'''.format(table_name)
c.execute(SQL)
exists_flag = False
if c.fetchone()[0] == 1:
c.fetchall() #get rid of the remainder
exists_flag=True
if exists_flag:
return c, table_name
# Create table
SQL = '''
create table if not exists {0} ({1});
'''.format(table_name, '\"' + '\" text,\"'.join([str(n).lower() for n in column_names]) + '\" text')
c.execute(SQL)
c.close()
# Fill table
SQL = '''
insert into {0} values ({1})
'''.format(table_name, ' ,'.join(['?']*len(column_names)))
with open(map_path, 'r') as map_file:
csv.field_size_limit(2147483647)
csv_reader = csv.reader(map_file, delimiter=sep, quoting=csv.QUOTE_NONE)
with sqlite3.connect(sqldb_path) as conn: # @UndefinedVariable
c = conn.cursor()
c.executemany(SQL, csv_reader)
return c, table_name | 656db3aa8797231ba09f6ddd08d00c0308be9285 | 708,591 |
def next_method():
"""next, for: Get one item of an iterators."""
class _Iterator:
def __init__(self):
self._stop = False
def __next__(self):
if self._stop:
raise StopIteration()
self._stop = True
return "drums"
return next(_Iterator()) | 85cdd08a65ae66c2869ba2067db81ff37f40d0b8 | 708,592 |
def u1_series_summation(xarg, a, kmax):
"""
5.3.2 ROUTINE - U1 Series Summation
PLATE 5-10 (p32)
:param xarg:
:param a:
:param kmax:
:return: u1
"""
du1 = 0.25*xarg
u1 = du1
f7 = -a*du1**2
k = 3
while k < kmax:
du1 = f7*du1 / (k*(k-1))
u1old = u1
u1 = u1+du1
if u1 == u1old:
break
k = k+2
return u1 | e54cb5f68dd5ecba5dd7f540ac645ff8d70ae0e3 | 708,593 |
import torch
def normalized_grid_coords(height, width, aspect=True, device="cuda"):
"""Return the normalized [-1, 1] grid coordinates given height and width.
Args:
height (int) : height of the grid.
width (int) : width of the grid.
aspect (bool) : if True, use the aspect ratio to scale the coordinates, in which case the
coords will not be normalzied to [-1, 1]. (Default: True)
device : the device the tensors will be created on.
"""
aspect_ratio = width/height if aspect else 1.0
window_x = torch.linspace(-1, 1, steps=width, device=device) * aspect_ratio
window_y = torch.linspace(1, -1, steps=height, device=device)
coord = torch.stack(torch.meshgrid(window_x, window_y, indexing='ij')).permute(2,1,0)
return coord | 7ddd1c5eda2e28116e40fa99f6cd794d9dfd48cc | 708,594 |
import struct
def pack4(v):
"""
Takes a 32 bit integer and returns a 4 byte string representing the
number in little endian.
"""
assert 0 <= v <= 0xffffffff
# The < is for little endian, the I is for a 4 byte unsigned int.
# See https://docs.python.org/2/library/struct.html for more info.
return struct.pack('<I', v) | bbaeb0026624a7ec30ec379466ef11398f93d573 | 708,595 |
def maximum_sum_increasing_subsequence(numbers, size):
"""
Given an array of n positive integers. Write a program to find the sum of
maximum sum subsequence of the given array such that the integers in the
subsequence are sorted in increasing order.
"""
results = [numbers[i] for i in range(size)]
for i in range(1, size):
for j in range(i):
if numbers[i] > numbers[j] and results[i] < results[j] + numbers[i]:
results[i] = results[j] + numbers[i]
return max(results) | a684ead4dcd9acbf8c796f5d24a3bf826fb5ad9d | 708,596 |
import json
def getResourceDefUsingSession(url, session, resourceName, sensitiveOptions=False):
"""
get the resource definition - given a resource name (and catalog url)
catalog url should stop at port (e.g. not have ldmadmin, ldmcatalog etc...
or have v2 anywhere
since we are using v1 api's
returns rc=200 (valid) & other rc's from the get
resourceDef (json)
"""
print(
"getting resource for catalog:-"
+ url
+ " resource="
+ resourceName
)
apiURL = url + "/access/1/catalog/resources/" + resourceName
if sensitiveOptions:
apiURL += "?sensitiveOptions=true"
# print("\turl=" + apiURL)
header = {"Accept": "application/json"}
tResp = session.get(apiURL, params={}, headers=header, )
print("\tresponse=" + str(tResp.status_code))
if tResp.status_code == 200:
# valid - return the jsom
return tResp.status_code, json.loads(tResp.text)
else:
# not valid
return tResp.status_code, None | 883a393018b068b8f15a8c0ea5ac6969c1a386b6 | 708,597 |
def _merge_sse(sum1, sum2):
"""Merge the partial SSE."""
sum_count = sum1 + sum2
return sum_count | 0aae96262cfb56c6052fdbe5bbd92437d37b1f76 | 708,598 |
def print_param_list(param_list, result, decimal_place=2, unit=''):
"""
Return a result string with parameter data appended. The input `param_list` is a list of a tuple
(param_value, param_name), where `param_value` is a float and `param_name` is a string. If `param_value`
is None, it writes 'N/A'.
"""
for param_value, param_name in param_list:
result += '<tr>'
result += r' <td class = "key"><span>{0}</span></td>'.format(param_name)
result += r' <td class="equals">=</td>'
if param_value is None:
result += r' <td class="value">N/A</td>'
else:
param_value = '%.*f' % (decimal_place, param_value)
result += r' <td class="value"><script type="math/tex">{0} \ \mathrm{{ {1!s} }}</script></td>'.format(
param_value, unit)
result += '</tr>\n'
return result | f92fd926eaf312e625058c394c42e9909cac7a43 | 708,600 |
def has_soa_perm(user_level, obj, ctnr, action):
"""
Permissions for SOAs
SOAs are global, related to domains and reverse domains
"""
return {
'cyder_admin': True, #?
'ctnr_admin': action == 'view',
'user': action == 'view',
'guest': action == 'view',
}.get(user_level, False) | 6b32c9f3411d9341d9692c46e84a7506d649f36d | 708,601 |
def fix_units(dims):
"""Fill in missing units."""
default = [d.get("units") for d in dims][-1]
for dim in dims:
dim["units"] = dim.get("units", default)
return dims | d3a47ad84e1b4e44bedebb1e5739778df975a6fe | 708,602 |
def _uno_struct__setattr__(self, name, value):
"""Sets attribute on UNO struct.
Referenced from the pyuno shared library.
"""
return setattr(self.__dict__["value"], name, value) | 6b66213e33bb8b882407ff33bcca177701fb98cd | 708,604 |
def partCmp(verA: str, verB: str) -> int:
"""Compare parts of a semver.
Args:
verA (str): lhs part to compare
verB (str): rhs part to compare
Returns:
int: 0 if equal, 1 if verA > verB and -1 if verA < verB
"""
if verA == verB or verA == "*" or verB == "*":
return 0
if int(verA) > int(verB):
return 1
return -1 | d9417ce482bf0c2332175412ba3125435f884336 | 708,607 |
import argparse
def get_args(**kwargs):
"""Generate cli args
Arguments:
kwargs[dict]: Pair value in which key is the arg and value a tuple with the help message and default value
Returns:
Namespace: Args namespace object
"""
parser = argparse.ArgumentParser()
for key, (help, default) in kwargs.items():
parser.add_argument("--{}".format(key), help=help, default=default)
return parser.parse_args() | f2cade1e0ec3b5a1fccd7ea94090c719de2849b6 | 708,608 |
import copy
def stretch(alignment, factor):
"""Time-stretch the alignment by a constant factor"""
# Get phoneme durations
durations = [factor * p.duration() for p in alignment.phonemes()]
alignment = copy.deepcopy(alignment)
alignment.update(durations=durations)
return alignment | 1ea58c32509365d503379df616edd00718cfca19 | 708,609 |
def _read_node( data, pos, md_total ):
"""
2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2
The quantity of child nodes.
The quantity of metadata entries.
Zero or more child nodes (as specified in the header).
"""
child_count = data[ pos ]
pos += 1
md_count = data[ pos ]
pos += 1
for i in range( child_count ):
pos, md_total = _read_node( data, pos, md_total )
for m in range( md_count ):
md_total += data[ pos ]
pos += 1
return ( pos, md_total ) | 768036031ab75b532d667769477f8d3144129ac8 | 708,610 |
def sequence_equals(sequence1, sequence2):
"""
Inspired by django's self.assertSequenceEquals
Useful for comparing lists with querysets and similar situations where
simple == fails because of different type.
"""
assert len(sequence1) == len(sequence2), (len(sequence1), len(sequence2))
for item_from_s1, item_from_s2 in zip(sequence1, sequence2):
assert item_from_s1 == item_from_s2, (item_from_s1, item_from_s2)
return True | 38016a347caf79458bb2a872d0fd80d6b813ba33 | 708,611 |
def second_order_difference(t, y):
""" Calculate the second order difference.
Args:
t: ndarray, the list of the three independent variables
y: ndarray, three values of the function at every t
Returns:
double: the second order difference of given points
"""
# claculate the first order difference
first_order_difference = (y[1:] - y[:-1]) / (t[1:] - t[:-1])
return (first_order_difference[1] - first_order_difference[0]) / (t[2] - t[0]) | 40e37d2b34104772966afc34e41c1ebc742c9adf | 708,612 |
def _load_method_arguments(name, argtypes, args):
"""Preload argument values to avoid freeing any intermediate data."""
if not argtypes:
return args
if len(args) != len(argtypes):
raise ValueError(f"{name}: Arguments length does not match argtypes length")
return [
arg if hasattr(argtype, "_type_") else argtype.from_param(arg)
for (arg, argtype) in zip(args, argtypes)
] | 0eb6a16c2e4c1cd46a114923f81e93af331c3d6e | 708,613 |
import requests
def download(url, local_filename, chunk_size=1024 * 10):
"""Download `url` into `local_filename'.
:param url: The URL to download from.
:type url: str
:param local_filename: The local filename to save into.
:type local_filename: str
:param chunk_size: The size to download chunks in bytes (10Kb by default).
:type chunk_size: int
:rtype: str
:returns: The path saved to.
"""
response = requests.get(url)
with open(local_filename, 'wb') as fp:
for chunk in response.iter_content(chunk_size=chunk_size):
if chunk:
fp.write(chunk)
return fp.name | 0a86b8600e72e349a4e1344d2ce1ad2bb00b889d | 708,614 |
def sum_2_level_dict(two_level_dict):
"""Sum all entries in a two level dict
Parameters
----------
two_level_dict : dict
Nested dict
Returns
-------
tot_sum : float
Number of all entries in nested dict
"""
'''tot_sum = 0
for i in two_level_dict:
for j in two_level_dict[i]:
tot_sum += two_level_dict[i][j]
'''
tot_sum = 0
for _, j in two_level_dict.items():
tot_sum += sum(j.values())
return tot_sum | 6b5be015fb84fa20006c11e9a3e0f094a6761e74 | 708,615 |
import re
def check_ip(ip):
"""
Check whether the IP is valid or not.
Args:
IP (str): IP to check
Raises:
None
Returns:
bool: True if valid, else False
"""
ip = ip.strip()
if re.match(r'^(?:(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])'
'(\.(?!$)|$)){4}$', ip):
return True
else:
return False | 2ff9a9262e46546fcb8854edee4b3b18ae1e2cc4 | 708,617 |
from typing import Iterator
from typing import Optional
def _stream_lines(blob: bytes) -> Iterator[bytes]:
"""
Split bytes into lines (newline (\\n) character) on demand.
>>> iter = _stream_lines(b"foo\\nbar\\n")
>>> next(iter)
b'foo'
>>> next(iter)
b'bar'
>>> next(iter)
Traceback (most recent call last):
...
StopIteration
>>> iter = _stream_lines(b"\\x00")
>>> next(iter)
b'\\x00'
:param blob: the bytes to split.
:return: a generated list of lines.
"""
start = 0
def _index(needle: bytes) -> Optional[int]:
try:
return blob.index(needle, start)
except ValueError:
return None
line_index = _index(b"\n")
while line_index is not None:
yield blob[start:line_index]
start = line_index + 1
line_index = _index(b"\n")
# Deal with blobs that do not end in a newline.
if start < len(blob):
yield blob[start:] | 8a166af1f765ca9eb70728d4c4bb21c00d7ddbf8 | 708,618 |
def chao1_var_no_doubletons(singles, chao1):
"""Calculates chao1 variance in absence of doubletons.
From EstimateS manual, equation 7.
chao1 is the estimate of the mean of Chao1 from the same dataset.
"""
s = float(singles)
return s*(s-1)/2 + s*(2*s-1)**2/4 - s**4/(4*chao1) | 6b93743a35c70c9ed5b9f3fc9bece1e9363c5802 | 708,619 |
def inBarrel(chain, index):
"""
Establish if the outer hit of a muon is in the barrel region.
"""
if abs(chain.muon_outerPositionz[index]) < 108:
return True | 9cbc5dad868d6e0ca221524ef8fc5ed5501adaa4 | 708,620 |
def to_string(class_name):
"""
Magic method that is used by the Metaclass created for Itop object.
"""
string = "%s : { " % type(class_name)
for attribute, value in class_name.__dict__.iteritems():
string += "%s : %s, " % (attribute, value)
string += "}"
return string | a7e155c92c4e62c1f070a474905a7e0c654f45ff | 708,621 |
def molefraction_2_pptv(n):
"""Convert mixing ratio units from mole fraction to parts per
thousand by volume (pptv)
INPUTS
n: mole fraction (moles per mole air)
OUTPUTS
q: mixing ratio in parts per trillion by volume (pptv)
"""
# - start with COS mixing ratio n as mole fraction:
# (n mol COS) / (mol air)
# convert to mixing ratio as volumetric fraction
# = (n * 6.023 * 10^23 molecules COS) / (6.023 * 10^23 molecules air)
# = (q molecules COS) / (1000 molecules air)
# q is mixing ratio in pptv, n is mole fraction
# solve for q --> 1000n = q
# therefore pptv = 1000 * mole fraction
q = 1e3 * n
return(q) | a6a26267f45fb70c346e86421c427bd155bfa65a | 708,622 |
def find_shortest_path(node):
"""Finds shortest path from node to it's neighbors"""
next_node,next_min_cost=node.get_min_cost_neighbor()
if str(next_node)!=str(node):
return find_shortest_path(next_node)
else:
return node | 4fa3979ff665b5cf8df423ff9b3fbaa880d62a73 | 708,623 |
def str_is_float(value):
"""Test if a string can be parsed into a float.
:returns: True or False
"""
try:
_ = float(value)
return True
except ValueError:
return False | 08f2e30f134479137052fd821e53e050375cd11e | 708,624 |
def activate_model(cfg):
"""Activate the dynamic parts."""
cfg["fake"] = cfg["fake"]()
return cfg | df8b0a23dc683435c1379e57bc9fd98149876d9d | 708,625 |
def convert_to_number(string):
"""
Tries to cast input into an integer number, returning the
number if successful and returning False otherwise.
"""
try:
number = int(string)
return number
except:
return False | 30110377077357d3e7d45cac4c106f5dc9349edd | 708,626 |
from typing import List
def mean(nums: List) -> float:
"""
Find mean of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Mean
>>> mean([3, 6, 9, 12, 15, 18, 21])
12.0
>>> mean([5, 10, 15, 20, 25, 30, 35])
20.0
>>> mean([1, 2, 3, 4, 5, 6, 7, 8])
4.5
>>> mean([])
Traceback (most recent call last):
...
ValueError: List is empty
"""
if not nums:
raise ValueError("List is empty")
return sum(nums) / len(nums) | 3c802b4967f646b6338e52b4ce12977274054c15 | 708,627 |
def is_gzip(name):
"""Return True if the name indicates that the file is compressed with
gzip."""
return name.endswith(".gz") | a6ea06f04808a07c4b26338f87273986eda86ef1 | 708,629 |
def possible_sums_of(numbers: list) -> list:
"""Compute all possible sums of numbers excluding self."""
possible_sums = []
for idx, nr_0 in enumerate(numbers[:-1]):
for nr_1 in numbers[idx + 1:]:
possible_sums.append(nr_0 + nr_1)
return possible_sums | 39ebe3e48c45a9c30f16b43e6c34778c5e813940 | 708,631 |
def fibonacci(n):
"""
object: fibonacci(n) returns the first n Fibonacci numbers in a list
input: n- the number used to calculate the fibonacci list
return: retList- the fibonacci list
"""
if type(n) != int:
print(n)
print(":input not an integer")
return False
if n <= 0:
print(str(n)+"not a postive integer")
return False
f1=1
f2=1
retList=[]
for i in range (0,n):
retList.append(f1)
fn=f1+f2
f1=f2
f2=fn
return retList | ac37d952eecae57b33fb3768f1c8097d76769534 | 708,632 |
def upcoming_movie_name(soup):
"""
Extracts the list of movies from BeautifulSoup object.
:param soup: BeautifulSoup object containing the html content.
:return: list of movie names
"""
movie_names = []
movie_name_tag = soup.find_all('h4')
for _movie in movie_name_tag:
_movie_result = _movie.find_all('a')
try:
_movie_name = _movie_result[0]['title']
movie_names.append(_movie_name)
except KeyError as e:
continue
return movie_names | 6bac06375109ec103492a079746e2c0364bfac17 | 708,633 |
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
"""learning_rate_decay: updates the learning rate using
inverse time decay in numpy
Args:
alpha : is the original learning rate
decay_rate : is the weight used to determine the
rate at which alpha will decay
global_step : is the number of passes of gradient
descent that have elapsed
decay_step : is the number of passes of gradient descent
that should occur before alpha is decayed further
Returns:
the updated value for alpha
"""
alpha = alpha / (1 + decay_rate * int(global_step / decay_step))
return alpha | a98f893acc7f14dafcf2dea551df4eb44da07bc4 | 708,634 |
def predict(model, img_base64):
"""
Returns the prediction for a given image.
Params:
model: the neural network (classifier).
"""
return model.predict_disease(img_base64) | 545a98dd682b81a1662878f91091615871562226 | 708,635 |
import hashlib
def get_hash(x: str):
"""Generate a hash from a string."""
h = hashlib.md5(x.encode())
return h.hexdigest() | 538c936c29867bb934776333fb2dcc73c06e23d0 | 708,636 |
def is_anagram(s,t):
"""True if strings s and t are anagrams.
"""
# We can use sorted() on a string, which will give a list of characters
# == will then compare two lists of characters, now sorted.
return sorted(s)==sorted(t) | 2b615f8180bcaa598e24c0772893c9a528bc5153 | 708,637 |
def lif_r_psc_aibs_converter(config, syn_tau=[5.5, 8.5, 2.8, 5.8]):
"""Creates a nest glif_lif_r_psc object"""
coeffs = config['coeffs']
threshold_params = config['threshold_dynamics_method']['params']
reset_params = config['voltage_reset_method']['params']
params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,
'g': coeffs['G'] / config['R_input'] * 1.0e09,
'E_L': config['El'] * 1.0e03 + config['El_reference'] * 1.0e03,
'C_m': coeffs['C'] * config['C'] * 1.0e12,
't_ref': config['spike_cut_length'] * config['dt'] * 1.0e03,
'a_spike': threshold_params['a_spike'] * 1.0e03,
'b_spike': threshold_params['b_spike'] * 1.0e-03,
'a_reset': reset_params['a'],
'b_reset': reset_params['b'] * 1.0e03,
'tau_syn': syn_tau, # in ms
'V_dynamics_method': 'linear_exact'}
return params | 091e45f44f9c777dac6c2b35fd51459a7947e301 | 708,638 |
def _organize_parameter(parameter):
"""
Convert operation parameter message to its dict format.
Args:
parameter (OperationParameter): Operation parameter message.
Returns:
dict, operation parameter.
"""
parameter_result = dict()
parameter_keys = [
'mapStr',
'mapBool',
'mapInt',
'mapDouble',
]
for parameter_key in parameter_keys:
base_attr = getattr(parameter, parameter_key)
parameter_value = dict(base_attr)
# convert str 'None' to None
for key, value in parameter_value.items():
if value == 'None':
parameter_value[key] = None
parameter_result.update(parameter_value)
# drop `mapStrList` and `strValue` keys in result parameter
str_list_para = dict(getattr(parameter, 'mapStrList'))
result_str_list_para = dict()
for key, value in str_list_para.items():
str_list_para_list = list()
for str_ele in getattr(value, 'strValue'):
str_list_para_list.append(str_ele)
str_list_para_list = list(map(lambda x: None if x == '' else x, str_list_para_list))
result_str_list_para[key] = str_list_para_list
parameter_result.update(result_str_list_para)
return parameter_result | 8cbd7c863bb244e71266a573ba756647d0ba13ea | 708,639 |
import json
def open_json(filepath):
"""
Returns open .json file in python as a list.
:param: .json file path
:returns: list
:rvalue: str
"""
with open(filepath) as f:
notes = json.load(f)
return notes | a7cae15880ee1caaaf7bfa8c1aec98f5f83debe7 | 708,640 |
import json
def load_credentials():
"""
load_credentials
:return: dict
"""
with open("credentials.json", "r", encoding="UTF-8") as stream:
content = json.loads(stream.read())
return content | 2f08fc4e897a7c7eb91de804158ee67cd91635d0 | 708,641 |
def get_utm_string_from_sr(spatialreference):
"""
return utm zone string from spatial reference instance
"""
zone_number = spatialreference.GetUTMZone()
if zone_number > 0:
return str(zone_number) + 'N'
elif zone_number < 0:
return str(abs(zone_number)) + 'S'
else:
return str(zone_number) | 50f01758f7ee29f1b994d36cda34b6b36157fd9e | 708,642 |
def return_intersect(cameraList):
"""
Calculates the intersection of the Camera objects in the *cameraList*.
Function returns an empty Camera if there exists no intersection.
Parameters:
cameraList : *list* of *camera.Camera* objects
A list of cameras from the camera.Camera class, each containing
a *poly* and a *coordsList*.
Returns:
intersectCam : *camera.Camera* object
An object from the camera.Camera class that is the
intersection between all cameras in the cameraList. If there
exists no intersection between any cameras in the camerList,
an empty Camera will be returned.
"""
intersectCam = None
for camera in cameraList:
if intersectCam is None: # Initiates the intersectCam variable
intersectCam = camera
else:
intersectCam = intersectCam.intersect(camera)
return intersectCam | a47613b8d79c4a4535cd5e7e07aa3b26dea019a5 | 708,643 |
import struct
def readShort(f):
"""Read 2 bytes as BE integer in file f"""
read_bytes = f.read(2)
return struct.unpack(">h", read_bytes)[0] | 1b31c2285d055df3c128e8158dcc67eb6c0a2b18 | 708,644 |
def build_table(infos):
""" Builds markdown table. """
table_str = '| '
for key in infos[0].keys():
table_str += key + ' | '
table_str += '\n'
table_str += '| '
for key in infos[0].keys():
table_str += '--- | '
table_str += '\n'
for info in infos:
table_str += '| '
for value in info.values():
table_str += str(value) + ' | '
table_str += '\n'
return table_str | 8d31e6abc9edd0014acbac3570e4a2bc711baa4a | 708,645 |
import csv
def load_data(filename):
"""
Load shopping data from a CSV file `filename` and convert into a list of
evidence lists and a list of labels. Return a tuple (evidence, labels).
evidence should be a list of lists, where each list contains the
following values, in order:
- Administrative, an integer
- Administrative_Duration, a floating point number
- Informational, an integer
- Informational_Duration, a floating point number
- ProductRelated, an integer
- ProductRelated_Duration, a floating point number
- BounceRates, a floating point number
- ExitRates, a floating point number
- PageValues, a floating point number
- SpecialDay, a floating point number
- Month, an index from 0 (January) to 11 (December)
- OperatingSystems, an integer
- Browser, an integer
- Region, an integer
- TrafficType, an integer
- VisitorType, an integer 0 (not returning) or 1 (returning)
- Weekend, an integer 0 (if false) or 1 (if true)
labels should be the corresponding list of labels, where each label
is 1 if Revenue is true, and 0 otherwise.
"""
with open("shopping.csv") as f:
reader = csv.reader(f)
next(reader)
months = ["Jan", "Feb", "Mar", "Apr", "May", "June",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
data = []
for row in reader:
data.append({
"evidence": [int(row[0]), float(row[1]), int(row[2]), float(row[3]), int(row[4]), float(row[5]), float(row[6]), float(row[7]), float(row[8]), float(row[9]),
months.index(row[10]), int(row[11]), int(row[12]), int(row[13]), int(row[14]), 0 if row[15] == "New_Visitor" else 1, 0 if row[16] == "FALSE" else 1],
"label": 0 if row[17] == "FALSE" else 1
})
evidence = [row["evidence"] for row in data]
labels = [row["label"] for row in data]
return (evidence, labels) | eb2465d0ebfb7398a3742d8fb79463d3d7b076f0 | 708,647 |
def get_loci_score(state, loci_w, data_w, species_w, better_loci,
species_counts, total_individuals, total_species,
individuals):
"""
Scoring function with user-specified weights.
:param state:
:param loci_w: the included proportion of loci from the original data set (higher is better).
:param data_w: 1 - the proportion of missing data for the selected loci (higher is better).
:param species_w: the average proportion of species represented per locus (higher is better).
:param better_loci:
:param species_counts:
:param total_individuals:
:param total_species:
:param individuals:
:return:
"""
num_loci = sum(state)
species_loci_counts = {species: 0 for species in species_counts}
individual_count = 0
missing_counts = {individual: 0 for individual in individuals}
total_loci = len(better_loci)
for i in range(total_loci):
if state[i] == 0:
continue
found_species = set()
found_individuals = set()
lines = better_loci[i].split("\n")
for line in lines:
if line == "":
continue
(individual, sequence) = line[1:].split()
found_individuals.add(individual)
individual_count += 1
species = individual.split("_")[-1]
found_species.add(species)
for species in found_species:
species_loci_counts[species] += 1
# Keep track of the amount of missing data for each individual.
for individual in individuals:
if individual not in found_individuals:
missing_counts[individual] += 1
num_missing = num_loci * total_individuals - individual_count
score_comps = [loci_w * float(num_loci) / float(total_loci),
data_w * (1 - float(num_missing) / float(num_loci * total_individuals)),
species_w * float(sum([species_loci_counts[species] for species in species_loci_counts])) / (float(num_loci) * float(total_species))]
return score_comps, missing_counts | e5e12bf2f9f76e994289a33b52d4cdc3d641ec8e | 708,648 |
def _find_full_periods(events, quantity, capacity):
"""Find the full periods."""
full_periods = []
used = 0
full_start = None
for event_date in sorted(events):
used += events[event_date]['quantity']
if not full_start and used + quantity > capacity:
full_start = event_date
elif full_start and used + quantity <= capacity:
full_periods.append((full_start, event_date))
full_start = None
return full_periods | 16c36ce8cc5a91031117534e66c67605e13e3bd4 | 708,649 |
import random
def crop_image(img, target_size, center):
""" crop_image """
height, width = img.shape[:2]
size = target_size
if center == True:
w_start = (width - size) / 2
h_start = (height - size) / 2
else:
w_start = random.randint(0, width - size)
h_start = random.randint(0, height - size)
w_end = w_start + size
h_end = h_start + size
img = img[h_start:h_end, w_start:w_end, :]
return img | c61d4410155501e3869f2e243af22d7fc13c10ee | 708,650 |
def create_dist_list(dist: str, param1: str, param2: str) -> list:
""" Creates a list with a special syntax describing a distribution
Syntax: [identifier, param1, param2 (if necessary)]
"""
dist_list: list = []
if dist == 'fix':
dist_list = ["f", float(param1)]
elif dist == 'binary':
dist_list = ["b", float(param1)]
elif dist == 'binomial':
dist_list = ["i", float(param1), float(param2)]
elif dist == 'normal':
dist_list = ["n", float(param1), float(param2)]
elif dist == 'uniform':
dist_list = ["u", float(param1), float(param2)]
elif dist == 'poisson':
dist_list = ["p", float(param1)]
elif dist == 'exponential':
dist_list = ["e", float(param1)]
elif dist == 'lognormal':
dist_list = ["l", float(param1), float(param2)]
elif dist == 'chisquare':
dist_list = ["c", float(param1)]
elif dist == 'standard-t':
dist_list = ["t", float(param1)]
return dist_list | 19cb93867639bcb4ae8152e4a28bb5d068a9c756 | 708,653 |
import time
def timeit(func):
"""
Decorator that returns the total runtime of a function
@param func: function to be timed
@return: (func, time_taken). Time is in seconds
"""
def wrapper(*args, **kwargs) -> float:
start = time.time()
func(*args, **kwargs)
total_time = time.time() - start
return total_time
return wrapper | 68723a74c96c2d004eed9533f9023d77833c509b | 708,654 |
def merge_count(data1, data2):
"""Auxiliary method to merge the lengths."""
return data1 + data2 | 8c0280b043b7d21a411ac14d3571acc50327fdbc | 708,655 |
def B(s):
"""string to byte-string in
Python 2 (including old versions that don't support b"")
and Python 3"""
if type(s)==type(u""): return s.encode('utf-8') # Python 3
return s | b741bf4a64bd866283ca789745f373db360f4016 | 708,656 |
def density_speed_conversion(N, frac_per_car=0.025, min_val=0.2):
"""
Fraction to multiply speed by if there are N nearby vehicles
"""
z = 1.0 - (frac_per_car * N)
# z = 1.0 - 0.04 * N
return max(z, min_val) | 95285a11be84df5ec1b6c16c5f24b3831b1c0348 | 708,657 |
def get_receiver_type(rinex_fname):
"""
Return the receiver type (header line REC # / TYPE / VERS) found
in *rinex_fname*.
"""
with open(rinex_fname) as fid:
for line in fid:
if line.rstrip().endswith('END OF HEADER'):
break
elif line.rstrip().endswith('REC # / TYPE / VERS'):
return line[20:40].strip()
raise ValueError('receiver type not found in header of RINEX file '
'{}'.format(rinex_fname)) | 7391f7a100455b8ff5ab01790f62518a3c4a079b | 708,658 |
def buildHeaderString(keys):
"""
Use authentication keys to build a literal header string that will be
passed to the API with every call.
"""
headers = {
# Request headers
'participant-key': keys["participantKey"],
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': keys["subscriptionKey"]
}
return headers | 4505fb679dec9727a62dd328f92f832ab45c417b | 708,659 |
def classname(obj):
"""Returns the name of an objects class"""
return obj.__class__.__name__ | 15b03c9ce341bd151187f03e8e95e6299e4756c3 | 708,660 |
def getbias(x, bias):
"""Bias in Ken Perlin’s bias and gain functions."""
return x / ((1.0 / bias - 2.0) * (1.0 - x) + 1.0 + 1e-6) | 0bc551e660e133e0416f5e426e5c7c302ac3fbbe | 708,661 |
from typing import Dict
from typing import Optional
def get_exif_flash_fired(exif_data: Dict) -> Optional[bool]:
"""
Parses the "flash" value from exif do determine if it was fired.
Possible values:
+-------------------------------------------------------+------+----------+-------+
| Status | Hex | Binary | Fired |
+-------------------------------------------------------+------+----------+-------+
| No Flash | 0x0 | 00000000 | No |
| Fired | 0x1 | 00000001 | Yes |
| "Fired, Return not detected" | 0x5 | 00000101 | Yes |
| "Fired, Return detected" | 0x7 | 00000111 | Yes |
| "On, Did not fire" | 0x8 | 00001000 | No |
| "On, Fired" | 0x9 | 00001001 | Yes |
| "On, Return not detected" | 0xd | 00001011 | Yes |
| "On, Return detected" | 0xf | 00001111 | Yes |
| "Off, Did not fire" | 0x10 | 00010000 | No |
| "Off, Did not fire, Return not detected" | 0x14 | 00010100 | No |
| "Auto, Did not fire" | 0x18 | 00011000 | No |
| "Auto, Fired" | 0x19 | 00011001 | Yes |
| "Auto, Fired, Return not detected" | 0x1d | 00011101 | Yes |
| "Auto, Fired, Return detected" | 0x1f | 00011111 | Yes |
| No flash function | 0x20 | 00100000 | No |
| "Off, No flash function" | 0x30 | 00110000 | No |
| "Fired, Red-eye reduction" | 0x41 | 01000001 | Yes |
| "Fired, Red-eye reduction, Return not detected" | 0x45 | 01000101 | Yes |
| "Fired, Red-eye reduction, Return detected" | 0x47 | 01000111 | Yes |
| "On, Red-eye reduction" | 0x49 | 01001001 | Yes |
| "On, Red-eye reduction, Return not detected" | 0x4d | 01001101 | Yes |
| "On, Red-eye reduction, Return detected" | 0x4f | 01001111 | Yes |
| "Off, Red-eye reduction" | 0x50 | 01010000 | No |
| "Auto, Did not fire, Red-eye reduction" | 0x58 | 01011000 | No |
| "Auto, Fired, Red-eye reduction" | 0x59 | 01011001 | Yes |
| "Auto, Fired, Red-eye reduction, Return not detected" | 0x5d | 01011101 | Yes |
| "Auto, Fired, Red-eye reduction, Return detected" | 0x5f | 01011111 | Yes |
+-------------------------------------------------------+------+----------+-------+
:param exif_data:
:return: If the flash was fired, or None if the exif information is not present
"""
if 'Flash' not in exif_data:
return None
return bool((int(exif_data['Flash']) & 1) > 0) | 82b4fc095d60426622202243f141614b9632340f | 708,662 |
import shlex
import os
def gyp_generator_flags():
"""Parses and returns GYP_GENERATOR_FLAGS env var as a dictionary."""
return dict(arg.split('=', 1)
for arg in shlex.split(os.environ.get('GYP_GENERATOR_FLAGS', ''))) | 51777f7b9ad87291dc176ce4673cb8a9cd5864f9 | 708,663 |
def array_pair_sum_iterative(arr, k):
"""
returns the array of pairs using an iterative method.
complexity: O(n^2)
"""
result = []
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] + arr[j] == k:
result.append([arr[i], arr[j]])
return result | c4f0eb5e290c784a8132472d85023662be291a71 | 708,664 |
def merge_named_payload(name_to_merge_op):
"""Merging dictionary payload by key.
name_to_merge_op is a dict mapping from field names to merge_ops.
Example:
If name_to_merge_op is
{
'f1': mergeop1,
'f2': mergeop2,
'f3': mergeop3
},
Then two payloads { 'f1': a1, 'f2': b1, 'f3': c1 } and
{ 'f1': a2, 'f2': b2, 'f3': c2 } will be merged into
{
'f1': mergeop1(a1, a2),
'f2': mergeop2(b1, b2),
'f3': mergeop3(c1, c2)
}.
"""
def merge(p1,p2):
p = {}
for name, op in name_to_merge_op.items():
p[name] = op(p1[name], p2[name])
return p
return merge | ee20147b7937dff208da6ea0d025fe466d8e92ed | 708,665 |
def euclidean_distance(this_set, other_set, bsf_dist):
"""Calculate the Euclidean distance between 2 1-D arrays.
If the distance is larger than bsf_dist, then we end the calculation and return the bsf_dist.
Args:
this_set: ndarray
The array
other_set: ndarray
The comparative array.
bsf_dist:
The best so far distance.
Returns:
output: float
The accumulation of Euclidean distance.
"""
sum_dist = 0
for index in range(0, len(this_set)):
sum_dist += (this_set[index] - other_set[index]) ** 2
if sum_dist > bsf_dist:
return bsf_dist
return sum_dist | 7055c0de77cad987738c9b3ec89b0381002fbfd4 | 708,666 |
import math
def FibanocciSphere(samples=1):
""" Return a Fibanocci sphere with N number of points on the surface.
This will act as the template for the nanoparticle core.
Args:
Placeholder
Returns:
Placeholder
Raises:
Placeholder
"""
points = []
phi = math.pi * (3. - math.sqrt(5.)) # golden angle in radians
for i in range(samples):
y = 1 - (i / float(samples - 1)) * 2 # y goes from 1 to -1
radius = math.sqrt(1 - y * y) # radius at y
theta = phi * i # golden angle increment
x = math.cos(theta) * radius
z = math.sin(theta) * radius
points.append((x, y, z))
return points | ea47b7c2eed34bd826ddff1619adac887439f5e0 | 708,667 |
def model(p, x):
""" Evaluate the model given an X array """
return p[0] + p[1]*x + p[2]*x**2. + p[3]*x**3. | fe923f6f6aea907d3dc07756813ed848fbcc2ac6 | 708,668 |
import time
def perf_counter_ms():
"""Returns a millisecond performance counter"""
return time.perf_counter() * 1_000 | 55f1bbbd8d58593d85f2c6bb4ca4f79ad22f233a | 708,669 |
from typing import List
import os
def find_files(
path: str,
skip_folders: tuple,
skip_files: tuple,
extensions: tuple = (".py",),
) -> List[str]:
"""Find recursively all files in path.
Parameters
----------
path : str
Path to a folder to find files in.
skip_folders : tuple
Skip folders containing folder to skip
skip_files : tuple
Skip files.
extensions : tuple, optional
Extensions to filter by. Default is (".py", )
Returns
-------
list
Sorted list of found files.
"""
found_files = []
for root, _dirs, files in os.walk(path, topdown=False):
for filename in files:
fpath = os.path.join(root, filename)
if any(folder in fpath for folder in skip_folders):
continue
if fpath in skip_files:
continue
if filename.endswith(extensions):
found_files.append(fpath)
return list(sorted(found_files)) | c3513c68cb246052f4ad677d1dc0116d253eae1a | 708,670 |
def TourType_LB_rule(M, t):
"""
Lower bound on tour type
:param M: Model
:param t: tour type
:return: Constraint rule
"""
return sum(M.TourType[i, t] for (i, s) in M.okTourType if s == t) >= M.tt_lb[t] | 0495e2d01c7d5d02e8bc85374ec1d05a8fdcbd91 | 708,673 |
def pick_ind(x, minmax):
""" Return indices between minmax[0] and minmax[1].
Args:
x : Input vector
minmax : Minimum and maximum values
Returns:
indices
"""
return (x >= minmax[0]) & (x <= minmax[1]) | 915a1003589b880d4edf5771a23518d2d4224094 | 708,674 |