content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _depends_sort_helper(names, data, _stack, _results):
""" Sort all names by dependency. """
for name in names:
if name in _results:
continue
# Add dependencies first, prevent recusrive dependencies
depends = data.get(name)
if depends:
if name in _stac... | 25fc995cd8bd836fd762ba671152c47a016a960a | 656,347 |
import hashlib
def hash256(string):
"""
Create a hash from a string
"""
grinder = hashlib.sha256()
grinder.update(string.encode())
return grinder.hexdigest() | 7409e5053a3ee61f534ec05edfffaf63bd6ca3e6 | 656,348 |
def moving_average(window, df):
"""
data frame should has two series: time, and value
:return: a time serires data frame of the moving average
"""
ma_df = df.rolling(window).mean()
ma_df.columns = ['mavg_{}'.format(window)]
return ma_df | ae2bdf416c8798802ff1797e1ccf4db5351f50dd | 656,349 |
import re
def config_attrs(config):
"""Returns config attributes from a Config object"""
p = re.compile('^[A-Z_]+$')
return filter(lambda attr: bool(p.match(attr)), dir(config)) | 21fc542909b16a587db04e990af8e5bc3177c93f | 656,350 |
def get_identifier(numbers, i):
"""Get identifier for list of numbers and starting kid i."""
min_ = min(numbers)
return min_
# if min_ != i:
# return min_
# else:
# return min_ | 3f526bc2370a34f5ed91932a7b8ccb69bdc8ed66 | 656,352 |
import logging
def _get_sac_origin(tr):
"""
Get the origin time of an event trace in sac format.
:param tr: A event trace
:return origin: origin time of an event
.. Note::
The trace should be sac formatted.
"""
try:
origin = tr.stats.starttime - tr.stats.sac.b + tr.stats... | 5a3709cc00e909bb5b9e088e9b46dc6ea00c0001 | 656,353 |
import numpy
def calc_confusion_matrix(label, predict):
"""Calculate confusion matrix.
Args:
label (numpy.ndarray): 1-d array of true label
(0 is normal, positive value is anormaly)
predict (numpy.ndarray): 1-d array of model's predict of category.
Returns: tp is true positi... | 854881050a94882caa4528564f4faf3b953a5938 | 656,354 |
def padding_alphabet(block_size):
"""
This is faster for the padding.
"""
return list(range(0, block_size))[::-1] + list(range(block_size, 256)) + [0] | daca049773f46d5d4a59e9d2456a13586063fe5a | 656,355 |
import os
def PathHasFile(path_spec, fname):
"""Check if a given filename is in the PATH
Args:
path_spec: Value of PATH variable to check
fname: Filename to check
Returns:
True if found, False if not
"""
for dir in path_spec.split(':'):
if os.path.exists(os.path.j... | d39729214f8484587b911de8f3e042d732a70e61 | 656,356 |
def seam_end(energy_totals):
"""
Parameters
==========
energy_totals: 2-D numpy.array(int64)
Cumulative energy of each pixel in the image
Returns
=======
numpy.int64
the x-coordinate of the bottom of the seam for the image with these
cumulative energies
"""
... | 6b029ffd3d466c5d006e0ce504ebe373a4c9ca0a | 656,357 |
def get_update_str(isupdate):
"""Gets correct tag for update and list
This is used to tag the status of a whole manifest
"""
return 'update' if isupdate else 'list' | 9b8718ab8cbb4d52854adfc0ea55691985656976 | 656,359 |
import re
def aliasSub(requestContext, seriesList, search, replace):
"""
Runs series names through a regex search/replace.
.. code-block:: none
&target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1")
"""
try:
seriesList.name = re.sub(search, replace, seriesList.name)
except AttributeError:
for series... | 8dae0feeff0e4a90742a2cb09b0a38d777b14849 | 656,360 |
def word_count(phrase):
""" Count occurrences of each word in a phrase excluding punctuations"""
punctuations = '''!()-[]{};:"\<>./?@#$%^&*~'''
counts = dict()
no_punct = ""
for char in phrase:
if char not in punctuations:
no_punct = no_punct + char
no_punct = no_punct.repla... | b2ba2751b793da2b5eacb22eae49899bec6479d6 | 656,362 |
def renew_order(order, icon):
"""Returns the new order with the contracted indices removed from it."""
return [i for i in order if i not in icon] | b29b23ea6b1664639586376ba83efc08ba8465a1 | 656,363 |
def gcd(x, y):
"""Calculate greatest common divisor of x and y."""
if not y:
return x
if x % y == 0:
return y
return gcd(y, x % y) | 7346ba80d4fa19b1c46a66b413d1fd08e10fc2dd | 656,364 |
def resource_wrapper(data):
"""Wrap the data with the resource wrapper used by CAI.
Args:
data (dict): The resource data.
Returns:
dict: Resource data wrapped by a resource wrapper.
"""
return {
'version': 'v1',
'discovery_document_uri': None,
'discovery_nam... | e3606fd7d66fa1a54ba02a3ee0b6c1c3ba8a9ae0 | 656,365 |
def exists(item, playlist):
"""Return a boolean
True if playlist contains item. False otherwise.
"""
for i in playlist: #for each item in playlist
if i.song_id == item.song_id: #check if the primary key is equal
return True
return False | 36fcff366499aff7532e5d3bd16826b9e91f28f6 | 656,366 |
def mask_val(val, width):
"""mask a value to width bits"""
return val & ((1 << width) - 1) | 87f70dd97d50f767604022c50223350db88966fb | 656,367 |
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna) | bb4c724d1c8793fd2ce9699c5540c49db0cd226d | 656,368 |
import re
def get_function_name(line):
"""Get name of a function."""
func_name = re.split(r"\(", line)[0]
func_name = re.split(r" ", func_name)[-1]
func_name = re.sub(r"(\*|\+|\-)", r"", func_name)
return func_name | f5b7048755000929822a6d97577dc872a4d4e966 | 656,369 |
import requests
import json
def get_swagger_dict(api_url: str) -> dict:
"""
Gets the lusid.json swagger file
Parameters
----------
api_url : str
The base api url for the LUSID instance
Returns
-------
dict
The swagger file as a dictionary
"""
swagger_path = "... | c6b29a68f1fc35ed870187d81efff8a22df76f9b | 656,370 |
def calculate_error(source, target, base, alpha):
"""
Calculates error for a given source/target/base colors and alpha
"""
alpha /= 255.0
alpha_inverse = 1.0 - alpha
return abs(target - alpha * source - alpha_inverse * base) | 1c8286b2634cfcb0381ed146a6e15780f2e33386 | 656,371 |
def cal_num_procs(world_size: int, gnx: int, gny: int):
"""Calculate the number of MPI ranks in x and y directions based on the number of cells.
Arguments
---------
world_size : int
Total number of MPI ranks.
gnx, gny : int
Number of cells globally.
Retunrs
-------
pnx,... | 24e8451b3aca642167a761737989e63baeb2bb19 | 656,372 |
def _rshift_nearest(x, shift):
"""Given an integer x and a nonnegative integer shift, return closest
integer to x / 2**shift; use round-to-even in case of a tie.
"""
b, q = 1 << shift, x >> shift
return q + (2 * (x & b - 1) + (q & 1) > b) | cb6fa2a2d65367766adab37e05534990dfe3b2a6 | 656,373 |
from typing import Tuple
def parse_path(path: str) -> Tuple[str, str]:
"""Split a full S3 path in bucket and key strings.
's3://bucket/key' -> ('bucket', 'key')
Parameters
----------
path : str
S3 path (e.g. s3://bucket/key).
Returns
-------
Tuple[str, str]
Tuple of ... | a62ae1bd30eaa74deb97e4ea4fe91aca41ebe730 | 656,374 |
def sqlite_table_indexes(c=None, table=None):
"""
"""
db_index = {}
if c is not None and table is not None:
c.execute('PRAGMA index_list({0})'.format(table))
rows = c.fetchall()
for r in rows:
db_index[r['name']] = {}
db_index[r['name']]['infos'] = r
... | 72ef91f577e8520e5308ac12a029577ff23b2675 | 656,375 |
def reciprocal_rank(truth, recommend):
"""Reciprocal Rank (RR).
Args:
truth (numpy 1d array): Set of truth samples.
recommend (numpy 1d array): Ordered set of recommended samples.
Returns:
float: RR.
"""
for n in range(recommend.size):
if recommend[n] in truth:
... | 55af4855d33db74b34163f5f6b7995213fb0960e | 656,376 |
import os
import pkgutil
def find_commands(management_dir):
"""
获取命令目录的路径, 返回所有可用命令的名称列表
"""
command_dir = os.path.join(management_dir, "commands")
return [
name
for _, name, is_pkg in pkgutil.iter_modules([command_dir])
if not is_pkg and not name.startswith("_")
] | f6343679e21976874827660164d3c6705935deb1 | 656,377 |
def is_cli_tool(req):
"""
Returns true if the user-agent looks like curl or wget
"""
user_agent = req.headers.get_first("User-Agent", "")
if user_agent.startswith('curl'):
return True
if user_agent.startswith('Wget'):
return True
return False | 22aa21ff5c2a2f05bdc01bcf6652364fb7faba12 | 656,378 |
def valid_odd_size(size):
"""
Validates that a kernel shape is of odd ints and of with 2 dimensions
:param size: the shape (size) to be checked
:return: False if size is invalid
"""
if type(size) not in (list, tuple):
return False
if len(size) != 2:
return False
if size[... | 5e1b1e6f6655f9732a80b97a01cd588b93e6e5f2 | 656,380 |
def findmin(L):
"""
>>> L3 = [ 1, 4, 5, 10 ]
>>> findmin(L3)
1
>>> L4 = [ 9, 10, 22, 44, 55 ]
>>> findmin(L4)
9
"""
return min(L) | cd9304753140084c6dbaf268fd1ad306104dd9ff | 656,383 |
def get_duplicates(index):
"""Returns a list of duplicates in the index .
Args:
index (list): All lines in the ffindex
Returns:
list: All the duplicated line
"""
duplicates = set()
entries = set()
for entry in index:
if(entry[0] in entries):
duplica... | 4512ef98dab9a95d94add3c4b4aa7ec14a847b41 | 656,384 |
import os
def get_api_endpoint():
"""Get Ion Channel endpoint from envvars."""
if os.environ.get('IONCHANNEL_ENDPOINT_URL') is not None:
return os.environ['IONCHANNEL_ENDPOINT_URL']
else:
return 'https://api.ionchannel.io' | 708ac97ea1ee6d7d5c556c70f5ec9b2f19bd7f69 | 656,385 |
def relative_camera_motion(R1, t1, R2, t2):
"""
Computes the relative camera motion between two cameras.
Given the motion parameters of two cameras, computes the motion parameters of the second
one assuming the first one to be at the origin. If `T1` and `T2` are the camera motions,
t... | 291868c6a90eac9823b4094eb07a91676d52d215 | 656,386 |
def _generate_pairs(geo, pairs='offdiag'):
""" Generate a list of pairs to calculate potentials
"""
assert pairs == 'offdiag', (
'Can only generate list of off-diagonal pairs'
)
# OFF-DIAG PAIRS
pairs = tuple()
for i in range(len(geo)):
for j in range(len(geo)):
... | 2ad248050bdab991b535a9810107304a91af1f56 | 656,387 |
def make_url(photo: dict):
"""
Get download URL for photo
:param photo: photo data as returned from API
"""
return photo["baseUrl"] + "=d" | 532444d58af34d8911e7a303341f7f02d29c27a2 | 656,388 |
def adjacent_vectors(vector_field, neighbors):
"""
Query the vectors neighboring a vector field entry.
"""
return [vector_field.vector(key) for key in neighbors] | b43e95bfd05493b8a36c65b80461a671c6aef1ab | 656,389 |
def dictfetchall(cursor) -> list:
"""
從 cursor 獲取的資料行轉換成元素為字典的列表
[
{
'column1': '...',
'column2': '...',
...': '...',
},
{
'column1': '...',
'column2': '...',
'...': '...',
},
]
"""
columns = ... | 1e0a2f7fa7a0ff7242906ec62ac738ba92b52257 | 656,390 |
def recommend_random(movies, k=10):
"""
Recommends a list of k random movie ids
"""
return movies['title'].sample(k).to_list() | 56cbd013b60a26e84e20ce69c8376935586b95d5 | 656,391 |
def split_and_strip(sep, s):
"""
Split input `s` by separator `sep`, strip each output segment with empty
segment dropped.
"""
return [y for y in (x.strip() for x in s.split(sep)) if len(y) > 0] | 366dcd401ca6e3d953a75e321388d2b97465bfb5 | 656,392 |
def plus_petite(noeud):
"""Renvoie le noeud avec la plus petite valeur."""
if noeud == None:
return None
n = noeud
while n.gauche != None:
n = n.gauche
return n | ffa9e4293fd78ef186c4a0af356c9a132bad975f | 656,393 |
def get_feature_multitask_dim(X, y, sample_dim):
"""return feature dim and multitask dim if exists, otherwise return empty
lists"""
# check if y has a multitask dim, i.e., y(sample, multitask)
mt_dim = [x for x in y.dims if x != sample_dim]
# check if X has a feature dim, i.e., X(sample, regressors)... | fac318735c63a34b61946c2eefc736a7f1730fdf | 656,394 |
def build_post_data_from_object(model, obj, ignore=["id"]):
"""
Build a payload suitable to a POST request from given object data.
Arguments:
model (django.db.models.Model): A model object used to find object
attributes to extract values.
obj (object): A instance of given model ... | 77bf514a831502b930b073f2e71c1fe39e128a42 | 656,395 |
def full_name(user):
"""
returns users full name.
Args:
user (User): user object.
Returns:
str: full name from profile.
"""
if not user or not user.profile:
return None
profile = user.profile
first = profile.first_name or profile.user.username
last = " {}".... | 96533a87b5bbb99f73db104f72e2b99d707f7e81 | 656,396 |
def piecewise_compare(a, b):
""" Check if the two sequences are identical regardless of ordering """
return sorted(a) == sorted(b) | 40316e161846e29063b0db2076ef74c3be4c72d6 | 656,397 |
def sw_naming_to_latlon(tile_name):
"""
Get latitude and longitude corresponding to southwestern corner of tile naming (originally SRTMGL1 convention)
parsing is robust to lower/upper letters to formats with 2 or 3 digits for latitude (NXXWYYY for most existing products,
but for example it is NXXXWYYY ... | f9076ce78b983c18acef7b4cfaec420ed5efc58d | 656,398 |
def patch_many(mocker):
"""
Makes patching many attributes of the same object simpler
"""
def patch_many(item, attributes, autospec=True, **kwargs):
for attribute in attributes:
mocker.patch.object(item, attribute, autospec=autospec, **kwargs)
return patch_many | f955c5b1c95993c035ae143e78f780ed43a8c439 | 656,399 |
def maze_gen():
"""takes in put from the user and returns a map
Returns:
dict: the json file containing all the maps
"""
res = {}
for i in range(1): # for each of the mazes (9)
print("this is maze ", i+1)
Green_1 = []
Green_2 = []
Green_1.append([int((inp ... | 561c0563c829870f7ef1bbef63248c79bda81c23 | 656,401 |
def ShutDown():
""" This function will close the AndorMCD system down."""
return None | 9bcba1273942db2e3f9823997247750c0753e45a | 656,402 |
def make_readable_pythonic(value: int) -> str:
"""Make readable time (pythonic).
Examples:
>>> assert make_readable(359999) == "99:59:59"
"""
return f"{value / 3600:02d}:{value / 60 % 60:02d}:{value % 60:02d}" | a091ef99b94cb2b4c3e0d657805a9e7b6418dd3a | 656,404 |
def _get_index(x, x_levels):
"""Finds element in list and returns index.
Parameters
----------
x: float
Element to be searched.
x_levels: list
List for searching.
Returns
-------
i: int
Index for the value.
"""
for i, value in enumerate(x_levels):
... | 6f4e7c590ab41357faa1125485cc74c9409dd0c6 | 656,405 |
def _ve_gauss_ ( self , val ) :
"""Generate the gaussian according to Ostap.Math.ValueWithError
>>> ve = VE ( 1 , 2 )
>>> value = ve_gauss ( ve )
"""
mean = val.value ()
sigma = val.error ()
return self.gauss ( mean , sigma ) | 6dfe5e7be6599ece34dbb379db0c378911e91072 | 656,406 |
def unconsolidated_sand_line(Vs):
"""
Vp from Vs using the unconsolidated sand line. Very similar to Greenberg-
Castagna sandstone line but returns a smaller Vs to account for lack of
consolidation. Not the same as friable sand model (from RokDoc Help
documents; coefficients from Rob Simm).
""... | 1761aa9e34c05a8a58201280868c4f3a87fddb8a | 656,407 |
import torch
def custom_collate_fn(batch):
"""
Since all images might have different number of BBoxes, to use batch_size > 1,
custom collate_fn has to be created that creates a batch
Args:
batch: list of N=`batch_size` tuples. Example [(img_1, bboxes_1, ci_1, labels_1), ..., (img_N, bboxe... | 885e729aeb3a5fb55866cdde73e3e5f2025340b0 | 656,408 |
def ferc1_etl_parameters(etl_settings):
"""Read ferc1_to_sqlite parameters out of test settings dictionary."""
return etl_settings.ferc1_to_sqlite_settings | 8c1593c9b504efda99759e6fff14528876162c47 | 656,409 |
def _partial_rotation_values(k=3):
""" These ammounts along with mults can be used to quickly count
rotations until a given point. For a given number, i.e 8372, we
use the ammounts along with mults to quickly calculate the rotations
until 7999.
This is possible because there's a pattern that emerge... | aacea343f7de0380e6bb0b30ee1cc3ef03a9b486 | 656,410 |
def files_handler(ctx, param, value):
"""Process and validate input file names"""
return value | 99b2a69fdae6363a1beddc9ead44aa23ff6cd52d | 656,411 |
def get_all_links(pipes, root_node="0"):
"""given a dict of links, walk the tree to find all possible endpoints from a given startpoint"""
new_nodes = links = {root_node}
while True:
new_links = set()
for node in new_nodes:
new_links |= set(pipes[node])
if new_links.issu... | f8d261fd9252beb601be9c697aa180be4ab921e0 | 656,412 |
def create_lists(emotions_list):
"""
(EmotionsList) -> list, list, list
Creates lists with emotions, probabilities and colors
to create charts
"""
emotions = []
probability = []
max_probability = 0
counter = 0
max_el = 0
for element in emotions_list:
emotions.append(... | 88477c110e36ecc26196484e1e944c03b11549ed | 656,413 |
def table2tsv(table):
"""Represent a list of lists of strings (a "table") as a "tsv"
(tab separated value) string.
"""
return '\n'.join(['\t'.join(row) for row in table]) | 77367210fd1fbdbab1bc18b3eb776f24de4430ae | 656,414 |
def norm2(g, a):
"""
calculates the norm squared of vector "a" with metric "g"
INPUT:
g, a - dictionaries
OUTPUT:
|a|^2 - float, the dot norm squared of "a"
Written: Jan 9, 2014, Dmitry Malyshev (SLAC), MIT licence
"""
res = 0.
for key, value in a.iteri... | ebd5a3407f1c9c88d55f30815cf0c4a719c75c85 | 656,416 |
import logging
def find_mu(s, y, eta=1, tol=1e-8, max_iter=1000):
"""
:param s: singular values
:param y: data whitened by left eigen matrix of svd of L
y |-> u.T @ y
:param eta: SNR
if prewhitened use 1.
:param tol:
:param max_iter:
:return: mu, float
"""
logg... | 8070fab02955df5ac4a2e19abd46723569e978eb | 656,417 |
import pickle
def load_feed(file_path):
"""Loads feed as a binary file"""
with open(file_path, "rb") as file:
return pickle.load(file) | 6526e467eca4a6a2dc448645b471874b778ca4f7 | 656,418 |
def calculate_N50(list_of_lengths):
"""Calculate N50 for a sequence of numbers.
Args:
list_of_lengths (list): List of numbers.
Returns:
float: N50 value.
"""
tmp = []
for tmp_number in set(list_of_lengths):
tmp += [tmp_number] * list_of_lengths.count(tm... | 654b423e2ce38ad2d9adaef60882f8b5eef48438 | 656,419 |
def ashift(num1, num2):
"""
ASHIFT num1 num2
outputs ``num1`` arithmetic-shifted to the left by ``num2`` bits.
If num2 is negative, the shift is to the right with sign
extension. The inputs must be integers.
"""
return num1 >> num2 | 7d4f2c03b6d124770739fc49b4fef951d0d6d795 | 656,420 |
import os
def root_dirpath():
"""
:return: Root directory path (str)
"""
return os.path.abspath(os.sep) | d0a7fc60f4855367504b0d84af1521d104b30e64 | 656,422 |
def tuples_sorted_by_keys(adict):
"""Return list of (key, value) pairs of @adict sorted by keys."""
return [(key, adict[key]) for key in sorted(adict.keys())] | 66b1aa62e5e09fa7c269ae3463c583683d230b22 | 656,423 |
def index_of(seq, value, from_index=0):
"""
Description
----------
Return the index of a value in a sequence.\n
Returns -1 if the value was not found.
Parameters
----------
seq : (list or tuple or string) - sequence to iterate\n
value: any - value to search for\n
from_index : in... | b5af32b3dafe51663de372836d4fbd4e582b2e32 | 656,424 |
def coverage(pileup):
"""Returns the sum of nucleotide reads (no gap or N) per position"""
return pileup.sum(axis=0)[:4, :].sum(axis=0) | 1092bb1324f6df471a76eb44354f71d58d99137a | 656,426 |
import random
def randomint(max, min=0, step=1):
"""Defaults some values for the inbuilt function."""
return random.randrange(min, max, step) | 116afda6650a8e79c26c562984459490d73e88ec | 656,427 |
def renumber_locals(instructions, num_args):
"""Renumbers locals in the order of creation without any gaps."""
locals_map = {i: i for i in range(num_args)}
for ins in instructions:
for i, arg in enumerate(ins.args):
ins.args[i] = locals_map[arg]
if hasattr(ins, 'dest'):
... | aab3279548a8369990f90720629437d1b18cf56e | 656,428 |
import collections
import os
def prepare_data_set_from_directory(path, test_ratio, fixed_order):
"""Parses data set from given directory, split them into train/test sets.
Args:
path: string, path of the data set. Images are stored in sub-directory named
by category.
test_ratio: float in (0,1), rati... | 293c07a712f18ca0c5f618b3fc612b5d5c1c7849 | 656,429 |
def split_phases(df):
"""
Separates DataFrame into groups by unique values of a column 'Phase', and returns a tuple of DataFrames.
"""
return(
tuple([df.groupby('Phase').get_group(p) for p in df.Phase.unique()])
) | 1774db1d8708e8d17a88ed9586234018ba701b7f | 656,430 |
import re
def FindMethods(section):
"""Spin through the 'method code index' section and extract all
method signatures. When found, they are added to a result list."""
# Match lines like:
# |[abcd] com/example/app/Class.method:(args)return
# capturing the method signature
methodPa... | f98c4afe63267a478330675fc7aa58bd68381ed8 | 656,432 |
def get_event_delete_role(bot, guild):
"""Return the event delete role, if it exists"""
result = bot.db.get_event_delete_role_id(guild.id)
if result:
for role in guild.roles:
if role.id == result.get('event_delete_role_id'):
return role | ec3e8fde7cf93037004633e1558307c482b53ac8 | 656,433 |
def calc_relativistic_correction(stoichiometry):
"""Calculate the relativistic correction to the Kramers-Kronig transform.
Parameters:
-----------
stoichiometry : array of integer/float pairs
Each pair in the list consists of an atomic number and the relative proportion of that element.
Returns
-------
This ... | 2ea0314e9f70e2496585f45e8486f279a8cfbf89 | 656,434 |
def pyext_coms(platform):
"""Return PYEXTCCCOM, PYEXTCXXCOM and PYEXTLINKCOM for the given
platform."""
if platform == 'win32':
pyext_cccom = "$PYEXTCC /Fo$TARGET /c $PYEXTCCSHARED "\
"$PYEXTCFLAGS $PYEXTCCFLAGS $_CCCOMCOM "\
"$_PYEXTCPPINCFLAGS $SOURCES"
... | 5225e580d4187e928043f0c96b9b534734a998ca | 656,435 |
def wh2xy_c(bboxes):
"""
:param bboxes: (x_ctr, y_ctr, w, h) (n, 4 * #C)
:return: out_bboxes: (xmin, ymin, xmax, ymax) (n, 4)
"""
num_boxes = bboxes.size(0)
out_bboxes = bboxes.clone()
xmins = bboxes[..., 0::4] - (bboxes[..., 2::4] - 1) / 2.0
ymins = bboxes[..., 1::4] - (bboxes[..., 3::4... | 23b8f8ddea51baf43ee67eafb2a9c9deeb883e6b | 656,436 |
def replace_in_list(counter_list, replacements):
"""Replaces the <name> in the list recursively until there is nothing to replace."""
new_list = []
is_replaced = False
# Not very efficient, but does the job
for name in counter_list:
is_replaced_local = False
for replacement, replace... | adbcfbc6a7cf68a779042ee0620ec0ed7ab82728 | 656,437 |
def digitalSum(n):
"""Calculates the sum of the digits of `n`."""
if n < 10:
return n
else:
return n % 10 + digitalSum(n // 10) | c7cc4ed54c61c786782669fce4f8cac943866713 | 656,438 |
import itertools
def get_bases(parameter) -> set:
"""Function to get set of all base classes of parameter"""
def __get_bases(parameter_type):
return [parameter_type.__name__] + list(
itertools.chain.from_iterable(
__get_bases(t1) for t1 in parameter_type.__bases__
... | d9b83d544e542de33f50e959ebf49307c1d1663c | 656,439 |
def get_graph_last_edge(g, filter_out_types=set()):
"""
Get the last edge of the graph or an empty edge if there is non
:param g: a graph as a dictionary
:param filter_out_types: a set fo edge types to filter out, if not empty the last edge of the specified type is returned
:return: an edge as a di... | c2ad797e806ec3542708b916057968755de50d2b | 656,440 |
def to_number(s):
"""
Convert a string to a number. If unsuccessful, return the de-blanked string.
"""
ret = s
# remove single quotes
if "'" in ret:
ret = ret.strip("'").strip()
# try converting to booleans / None
if ret == 'True':
return True
elif ret == 'False':
... | deb9c134965c06f0c16ec522996b507e8c7370b8 | 656,441 |
import json
def get_cat_to_name_mapping(file):
"""
Read the json file provided and return a dictionary containing the mapping between categories and label names
:param file: path to JSON file containing mapping between categories and label names
:return cat_to_name: dictionary containing mapping betw... | 0801f4b4ade24ed897007747c98493ad97538f8b | 656,442 |
def plucker(key, default=None):
"""
return a function that extracts an attribute or a default value
"""
return lambda d: d.get(key, default) | 3f6705592b7827accaee18892f183f5010067d69 | 656,443 |
def _format_time(total_seconds):
"""Format a time interval in seconds as a colon-delimited string [h:]m:s"""
total_mins, seconds = divmod(int(total_seconds), 60)
hours, mins = divmod(total_mins, 60)
if hours != 0:
return f"{hours:d}:{mins:02d}:{seconds:02d}"
else:
return f"{mins:02d}... | 5d36548e7dc0ec5bb3481d21131a8e0611b6c1cb | 656,444 |
def pile_sub(pile1, pile2):
"""
对类进行求减法运算
:param pile1:
:param pile2:
:return:
"""
return list(set(pile1) - set(pile2)) | b9dc4850dd62813d0075a6c92b90308b46e98591 | 656,445 |
def split_into_quadrants(m):
"""
Split a nxn matrix into quadrants.
Given A, returns A11, A12, A21, and A22.
"""
mid = m.shape[0] // 2
return m[:mid:, :mid:], m[:mid:, mid:], m[mid:, :mid], m[mid:, mid:] | 982416f7584440a2b8bb73b40b1c7fed5ca138f3 | 656,446 |
def compreso(num, low, high):
"""
checks whether or not a number is between low and high
"""
return num>=low and num<=high | 2b63cf812ce6b1222693013cadf1e382e7359313 | 656,447 |
def print_gains(odrv, axis):
"""
Prints gains. Also returns them.
"""
axis_config = axis.controller.config # shorten that
print("Position:", axis_config.pos_gain )
print("Velocity:", axis_config.vel_gain)
print("Velocity Integrator:", axis_config.vel_integrator_gain)
return axis_config.... | 09ede6acd6133c9b43c13395b7d213eaeb7ae879 | 656,448 |
def categorize_local_files(manifest):
"""Categorize the files in the lambda function's directory into two bins: python files and other files"""
python = []
other = []
for filename in manifest.basedir.iterdir():
path = filename.relative_to(manifest.basedir)
if path.suffix == '.py':
... | 1de437a42500ba99515eb265438c41914326258d | 656,449 |
from typing import Iterable
def input_handling(
request_msg: str, input_option: Iterable, error_msg: str = "Invalid input."
) -> str:
"""
Returns (str) user choice from the option and handles invalid input
NOTE: For str input, one string options only
otherwise input a list of options.
"... | a6d6deaf1b9ff4a7fba8e7100a3d7c85be7fef66 | 656,450 |
def is_current_system_raspberry_pi():
"""Determine whether the current system is a Raspberry Pi.
Use the same method that is used by the setup script of
the picamera package. Namely search for the entry 'Hardware'
in /proc/cpuinfo.
"""
is_raspberry_pi = False
with open('/proc/cpuinfo', 'r')... | 4412322edd901812e1f73f4d779b5919d80e7039 | 656,451 |
def read_paralogs(paralogs_file):
"""Read list of paralogs."""
if paralogs_file is None:
# then nothing to return
return set()
f = open(paralogs_file, "r")
paralogs = set(x.rstrip() for x in f.readlines())
f.close()
return paralogs | c74d8f77fe59c411dc38c3cb31c32caf5f04e726 | 656,452 |
def make_map(elems):
"""
Create dictionary of elements for faster searching
@param elems: Elements, separated by comma
@type elems: str
"""
obj = {}
for elem in elems.split(','):
obj[elem] = True
return obj | 69419772fb283a46209bb01b6b29d796e500332f | 656,453 |
def seconds_into_day(time):
"""Takes a time in fractional days and returns number of seconds since
the start of the current day.
Parameters
----------
time: float
The time as a float.
Returns
-------
int
The day's duration in seconds.
"""
return(int(round(86400.... | 38927724e4a27a854bfda5aa6ef91498dcc5d35c | 656,454 |
import ast
import json
def get_roommate_json(roommate_data, type):
"""This method returns the JSON of the roommate object"""
roommate_list = []
for roomate in roommate_data:
if type == 'student':
roommate_json = {
'userid': roomate[0],
'username': rooma... | fdc476fab396dd86e39b8eb079001d2aa1e5ab2f | 656,456 |
def get_lam1(membrane_geometry):
""" dimensionless geometry coefficient lambda1
The corresponding definition (of different separability factor) is provided in Table 1 in [2].
Note that the definition in [2] is slightly different due to the use of hydraulic radius of channel.
This means that the lam1 in ... | 8db9170541a9b42e5cf7584d7321f08c79d9e6bb | 656,457 |
def getattrs(attrs, getclasses):
"""return all attributes in the attribute list attrs, which are
instances of one of the classes in getclasses"""
return [attr for attr in attrs if isinstance(attr, tuple(getclasses))] | c687931ba953d6c238ebd0a47b18e72c3a6fefe4 | 656,458 |
from typing import List
import unicodedata
import re
def preprocess_without_tokens(sentence: str) -> List[str]:
"""
preprocess the given sentence, do not add tokens
"""
# convert to ascii
sentence = ''.join(c for c in unicodedata.normalize('NFD', sentence.lower().strip())
if... | 3a7d6bb9df1ebfda8aa852c603973305a90027cb | 656,459 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.