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]
... | 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)
# St... | 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 = t... | 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 ... | 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 ... | 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', '... | 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.
... | 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) =... | 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... | 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 inele... | 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 lett... | 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)
# metr... | 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.radia... | 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='si... | 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... | 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):
# C... | 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_LT... | 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(m... | 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(_... | 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
... | 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 scal... | 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.
... | 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... | 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
... | 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'.
... | 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_l... | 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
... | 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, (hel... | 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, m... | 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 i... | 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 f... | 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... | 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 chun... | 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... | 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])'
'... | 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... | 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:
# ... | 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([])
Trace... | 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... | 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')
t... | 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
r... | 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'] * confi... | 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',
... | 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:
re... | 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, e... | 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 += ... | 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:
- Administr... | 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 se... | 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... | 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... | 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'... | 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 = ... | 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... | 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["subscrip... | 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:
+-------------------------------------------------------+------+----------+-------+
| ... | 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... | 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 t... | 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 com... | 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 = ma... | 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 : tupl... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.