content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def image_count(list_bboxes, list_classes):
"""
统计全图各个类别的数量。
:param list_bboxes: BoundingBoxs list
:param list_classes: Classes list
:return: 各个类别的数量.
"""
class_num = [0]*len(list_classes)
for i in range(0, len(list_bboxes)):
x1 = list_bboxes[i].xmin
y1 = list_bboxes[i... | a038228ae5e74b1e2e73d7245dbd76d63fe6243c | 649,245 |
import argparse
def parse_arguments():
""" Parse command line arguments with which the script was called. Returns
an object containing them all.
"""
### IMPORTANT NOTE: The 'config' argument specifies the path to the main
### YAML configuration file. All the other arguments override keys
### a... | b0f4e728a76a91c9481fc38c4858bcf3dd9d5c62 | 649,246 |
def bdev_ocf_create(client, name, mode, cache_line_size, cache_bdev_name, core_bdev_name):
"""Add an OCF block device
Args:
name: name of constructed OCF bdev
mode: OCF cache mode: {'wb', 'wt', 'pt', 'wa', 'wi', 'wo'}
cache_line_size: OCF cache line size. The unit is KiB: {4, 8, 16, 32,... | cb632d906f8d5ef3192388886aa11f01db9f0e6b | 649,247 |
def binary_search(search_list, search_key):
"""Find the index of a value of a key in a sorted list using
a binary search algorithm. Returns the index of the value if
found. Otherwise, returns -1.
"""
left_idx, right_idx = 0, len(search_list) - 1
# while True:
while left_idx <= right_idx:
... | 17738b9cc392f18d1f51f86a3c8d1b3fd3e14e47 | 649,248 |
def GetSeriesColumnName(series):
"""
Prints useful information for a given series object.
"""
return '{} & {} & QC {}'.format(series.site_code, series.variable_code, series.quality_control_level_code) | 762266560966b65f32504841ae6e1e5991237701 | 649,249 |
from functools import reduce
def extract_post_context(request):
"""Extract and return context from a standard POST request."""
data = {}
for key in request.POST.iterkeys():
key_split = key.split('.')
current_data = reduce(lambda x, y: x.setdefault(y, {}),
[da... | 12a2cc6724a92cfb4020ac2ed4ad32df7596597c | 649,250 |
from typing import List
def beam_options_to_args(options: dict) -> List[str]:
"""
Returns a formatted pipeline options from a dictionary of arguments
The logic of this method should be compatible with Apache Beam:
https://github.com/apache/beam/blob/b56740f0e8cd80c2873412847d0b336837429fb9/sdks/pytho... | 3c370e2949dd21fd9840d6e7cddb051866d4157b | 649,251 |
import json
def structured_solver_data(id_, cat='qpu', incomplete=False):
"""Return string describing a single solver."""
obj = {
"properties": {
"supported_problem_types": ["qubo", "ising"],
"qubits": [1, 2, 3],
"couplers": [[1, 2], [1, 3], [2, 3]],
"nu... | 4a165a4b6e9d034d987b12a53d45fbab53f1adc8 | 649,252 |
def _list_values(values, sep):
"""Returns list of values as '[values[0], values[1], ..., sep values[-1]]':
$ _list_values([1, 2, 3], "and")
"[1, 2, and 3]"
"""
values = list(map(repr, values))
if len(values) > 2:
values = (", ".join(values[:-1]) + ",", values[-1])
if len(values) == ... | ea28c2e44ae7897b7787d2b1143deae8808b9859 | 649,253 |
def cycle_crossover(num_of_cities, parent1, parent2):
"""
Implements cycle crossover operator
"""
child1 = [-1] * num_of_cities
child2 = child1.copy()
i = 0
while child1[i] == -1:
child1[i] = parent1[i]
i = parent1.index(parent2[i])
i = 0
while child2[i] == -1:
... | 0371ca2a0a4e470df128404544e2e43914a425db | 649,255 |
def tasks_get_filtered(taskid_list, module):
"""
Get tasks information from a list of tasks.
Parameters
----------
taskid_list : list
List of task IDs to get.
module : AnsibleModule
Ansible module.
Returns
-------
list
List of tasks from CVP.
"""
tas... | 3aa195792a42e17d91c637cb76382b82967e01dc | 649,256 |
import urllib3
def get_external_ip():
"""A dummy function that takes some time."""
http = urllib3.PoolManager()
#r = http.request('GET', 'http://ifconfig.co/json')
#result = json.loads(r.data.decode('utf-8'))
#return result['ip']
r = http.request('GET', 'http://ifconfig.me')
return r.dat... | c1c328674f69541344d80bdf43dba724ea52e4ae | 649,257 |
import math
def cos_sin_deg(deg):
"""Return the cosine and sin for the given angle
in degrees, with special-case handling of multiples
of 90 for perfect right angles
"""
deg = deg % 360.0
if deg == 90.0:
return 0.0, 1.0
elif deg == 180.0:
return -1.0, 0
elif deg == 270.... | 1f3672e8447285b6ce4ac4d35b4c68fda41c85c3 | 649,258 |
def get_name_history(stripped_uuid): # noqa: E501
"""Gets the full player's name history
# noqa: E501
:param stripped_uuid: The player UUID without hyphens
:type stripped_uuid: str
:rtype: List[NameChange]
"""
return 'do some magic!' | 33c7f053fdaba9a65ebb2286278dfc60f73355bf | 649,259 |
def resv_key_2():
"""NVMe reservation key for 2nd nexus."""
resv_key = 0x1234567890ABCDEF
return resv_key | 307295e2b42659a85e80cf98f75374ffb97841c6 | 649,260 |
def get_header_idx(fname):
"""
Opens the file from fname and returns the row index corresponding to the
header row (with all the column name field information)
"""
blanks = []
with open(fname,'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if li... | c0bd6021ea021f1d372572f2b42e866be1533c9f | 649,261 |
def get_dotfield_value(dotfield, d):
"""
Explore dictionary d using dotfield notation and return value.
Ex: d = {"a":{"b":1}}.
get_dotfield_value("a.b",d) => 1
"""
fields = dotfield.split(".")
if len(fields) == 1:
return d[fields[0]]
else:
first = fields[0]
re... | 914cd8e0fd65e8c641c6166b0dbe9ab9b6cb4e30 | 649,262 |
def permutations(numbers, descents):
"""Compute number of permutations with specified number of descents"""
if descents in (0, numbers - 1):
return 1
add0 = (descents + 1) * permutations(numbers - 1, descents)
add1 = (numbers - descents) * permutations(numbers - 1, descents - 1)
return (ad... | 9cb97e6075746539e99f30b59ebeafcc812edc1d | 649,263 |
import re
def slugify(txt):
"""Slugify function."""
output = txt.lower()
output = re.sub(r'\([^)]*\)', '', output) # remove the content of parenthesis
output = re.sub(r'<[^>]+>', '', output)
output = output.replace('+', 'p')
output = re.sub(r"[\(\):`']", '', output)
output = re.sub(r'\\_'... | a7d2806244abddfa154898cc621e279389064dc9 | 649,264 |
def fahr_to_celsius(temp_fahr):
"""Convert temperature from Fahrenheit to Celsius"""
temp_celsius = (temp_fahr - 32) * 5 / 9.0
return temp_celsius | 2889d002d3a72765035de2a4ccd642206ff4b8ca | 649,266 |
import sys
import platform
def get_headers(key):
"""Return a set of headers for use with requests made to the StatusReporter API."""
version = str(sys.version_info.major) + '.' + str(sys.version_info.minor) + '.' + str(sys.version_info.micro)
return {
'User-Agent': f'PU-Status-Reporter/2.0 Python/... | 70eddb7e6d96331f5b92b821d051f467bbeb2eea | 649,267 |
from typing import OrderedDict
def parse_info(soup):
"""Parse rent and detail descriptions from soup
Arguments:
soup: the soup object to parse from
Returns:
information (dict): parsed information
"""
info = OrderedDict()
infoSection = soup.select("div.detailInfo.clearfix")[... | cc72820d263d2bfc1a80b8b274d437f4139e48cd | 649,268 |
def get_test_command(cmd_list, process_name):
""" Return the first process corresponding to process_name. """
return next(command for command in cmd_list if command.process.process_name == process_name) | 5324044642595d3799b908909ad8591883cb6bfc | 649,269 |
def fix_line_breaks(s):
"""
Convert \r\n and \r to \n chars. Strip any leading or trailing whitespace
on each line. Remove blank lines.
"""
l = s.splitlines()
x = [i.strip() for i in l]
x = [i for i in x if i] # remove blank lines
return "\n".join(x) | 8ac0a9cd1bb14e0817746e5f9c70623ee3667a97 | 649,271 |
import math
def gcf(a, x, itmax=200, eps=3.0e-7):
"""Continued fraction approximation of the incomplete gamma function."""
gln = math.lgamma(a)
gold = 0.0
a0 = 1.0
a1 = x
b0 = 0.0
b1 = 1.0
fac = 1.0
n = 1
while n <= itmax:
an = n
ana = an - a
a0 = (a1 + ... | b1dcfa30dce76b085044c42f25f79b8aae382247 | 649,272 |
import hashlib
def shasha(msg):
"""SHA256(SHA256(msg)) -> HASH object"""
res = hashlib.sha256(hashlib.sha256(msg).digest())
return res | 30803e76020efe6557faf280b8599535ccd002e5 | 649,273 |
def _lcs(x, y):
"""
Computes the length of the longest common subsequence (lcs) between two
strings. The implementation below uses a DP programming algorithm and runs
in O(nm) time where n = len(x) and m = len(y).
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
... | 1bce7a7b193981e8a68737bf0404506a94bc3c6d | 649,274 |
def get_data_types_query() -> str:
"""
Define custom data types inside a database.
"""
# Define data types.
query = """
CREATE TYPE AssetClass AS ENUM ('futures', 'etfs', 'forex', 'stocks', 'sp_500');
CREATE TYPE Frequency AS ENUM ('minute', 'daily', 'tick');
CREATE TYPE ContractType AS ... | 736a30b7d59c664392cb2427d69c20ae26955ece | 649,275 |
def utrue(x,y):
"""
Return true solution for a test case where this is known.
This function should satisfy u_{xx} + u_{yy} = 0.
"""
utrue = x**2 - y**2
return utrue | b68913ee0aa9b72da40f21b4db19334540fd21f5 | 649,276 |
import torch
def evaluate_rho_mean(x, gp_var, gamma, repeat_eval=1):
"""
:param x: torch.Tensor nmb_ponts x dim, input
:param gp_var: botorch.model, e.g., SingleTaskGP, used for modeling variance rho^2
:param gamma: int, d coefficient of absolute risk tolerance in Mean-Variance objective
:param r... | ce4545fe5f4313ee59f9cdc8da11adfa441f2dc9 | 649,277 |
def check_reserved(string):
"""
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters.
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
"$" | ","
Hence for certain inputs, e.g. service name, configuration key etc whic... | 2f36ca93292a33470c832d021645b85277d7e6a5 | 649,278 |
def register_command(*parse_args, **options):
"""Register a method as a commandline command.
options:
help=
"""
def wrapper(function):
function._is_command = True
return function
return wrapper | ca0d78129386b7a70a4a481d73b3aec23328853d | 649,279 |
def consists_of(seq, types):
"""
Check that the all elements from the "seq" argument (sequence) are among the types passed as the "types" argument.
@param seq: The sequence which elements are to be typed.
@param types: A tuple of types to check.
@type types: tuple
@return: Whether the check ... | b422f89a7c22505fc75bcaa9e3d28a787ed1dff6 | 649,280 |
def get_unique_value(query_set, field_name, value):
"""Gets a unique name for an object corresponding to a particular
django query. Useful if you've defined your field as unique
but are system-generating the values. Starts by checking
<value> and then goes to <value>_2, <value>_3, ... until
... | 8463da63f71afd8721326888df0c9ec0c3566bc7 | 649,282 |
def _file_name_2_check_mask(file_name):
"""
Starting from a netcdf output file of RegCM (like ATM or SRF), produce the
name of the txt file that is produced when the other files are closed and
ready to be processed
"""
file_name_split = file_name.split('.')
file_date = file_name_split[-2]
... | ec4e74c41aa7d3287ce9baeb09b7c963b470adc5 | 649,284 |
import argparse
def get_args():
"""" collects command line arguments """
argparser = argparse.ArgumentParser(description=__doc__)
argparser.add_argument('--config', default=None, type=str, help='configuration file')
argparser.add_argument('--exp_name', default=None, ... | 4bf6e77c0c489e714ccd38833478690425fd179e | 649,286 |
def _flp2(number):
""" .. funktion:: _flp2(number)
Rounds x to the largest z | z=2**n.
:type number: int
:rtype: int
"""
number |= (number >> 1)
number |= (number >> 2)
number |= (number >> 4)
number |= (number >> 8)
number |= (number >> 16)
return number - (number >> 1) | 11f0625ef498ec5b5e08431a40094791595e92a1 | 649,287 |
def fib(position):
""" Fibonacci sequence function using for loop"""
if position == 0:
return 0
elif position == 1:
return 1
else:
first, second = 0, 1
next = first + second
for index in range(2, position):
first = second
second = next
... | 331477dab9549c39df4b93c95ee0b5c697208cb5 | 649,288 |
import io
import os
def _open(fname):
"""Read a file relatively to this setup.py."""
return io.open(os.path.join(os.path.dirname(__file__), fname), "rt",
encoding="utf-8") | 9d5bc1a0d03eb0b1b30428809547977001a6e6c9 | 649,289 |
def f(P):
"""list[list[int]] -> int"""
#K: list[list[int]]
K = P[:]
K[0].append(1)
return 0 | 6744c11b68b49accc0a5ec9b96dc607abf402064 | 649,291 |
def bias_term(ci, ref, meta_dict, n_range):
"""
Compute the bias term to be subtracted off the cross spectrum to compute
the covariance spectrum. Equation in Equation in footnote 4 (section 2.1.3,
page 12) of Uttley et al. 2014.
Assumes power spectra are raw (not at all normalized, and not Poisson-... | 181393530b8998e06e1a34196b2e2061dad0b677 | 649,292 |
import argparse
def parse_arg_path():
"""
Obtain path to json file passed as a command line argument.
"""
parser = argparse.ArgumentParser(description='Arguments.')
parser.add_argument('--env_param_json_file', type=str,
help='Path to json file with environment parameters.')... | 151ede41c4ce7b1f64f139f9a83d135c8c2ed44d | 649,293 |
import csv
def read_file(master_csv, meta_keys):
"""Read in metadata from csv file and determine if format is tidy or wide."""
merge_keys = []
merge_data = []
is_tidy = False
with open(master_csv, 'r') as metadata_csv:
meta_reader = csv.reader(metadata_csv)
rows = [row for row in... | 2525061e0efe7ee7f027ff78e9ebded05bb5279c | 649,294 |
import os
import errno
def make_sure_path_exists(path):
""" Check to see if a path exists """
try:
# print("\t-I- Creating: ", path)
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
return True | f816dbcaf15e4a8f889f982df9370991de73e5be | 649,295 |
import itertools
def contains_peroxide(structure, relative_cutoff=1.2):
"""
Determines if a structure contains peroxide anions.
Args:
structure:
Input structure.
relative_cutoff:
The peroxide bond distance is 1.49 Angstrom. Relative_cutoff * 1.49
stipul... | 5db51989f823b3a6cc113267371459e8cf37d920 | 649,296 |
def _convert_to_lower_case_bytes(item):
"""
bot filter is always lower case string.
this function will convert to all string to lower case.
Note: Unicode strings are converted to bytes.
"""
if isinstance(item, (tuple, list)):
output = [_convert_to_lower_case_bytes(v) for v in item]
e... | 285517ef9c2d319c2bdb7a3392feb35cc34c2f80 | 649,297 |
def calculate_param_b(
operating_frequency: float,
atmosphere_height_of_max: float,
atmosphere_semi_width: float,
atmosphere_max_plasma_frequency_squared: float) -> float:
"""
Calculates the B parameter following Hill 1979
"""
atmosphere_base_height = atmosphere_height_of... | b5bbbd7e12d72e05cf5342ca8baa6fc76c393c40 | 649,298 |
def get_snapshot_run_correlation_id(test_run_name, snapshot_type):
"""Returns the qualified string to use as correlation id.
Keyword arguments:
test_run_name -- the test run name for this run
snapshot_type -- either 'full' or 'incremental'
"""
return f"{test_run_name}_{snapshot_type}" | bccc40d43bc39c74f655557dc975b22083476513 | 649,299 |
def prune_cells(grid):
"""Given a grid, scan each row for solved cells, and remove those
numbers from every other cell in the row.
Note that 'grid' can be an iterable of rows, columns, or 3x3 squares.
Since the component cells (sets) are modified in-place it still works
if you rearrange things.... | ad7231f12e44eacef2ec83e69d493e7a5ce54dd1 | 649,300 |
def _copy_cursor(cursor):
"""Returns a new cursor with the same properites that won't affect the original
@cursor: any cursor that hasn't already been iterated over
@return: new cursor with same attributes
"""
new_cursor = cursor.collection.find()
new_cursor.__dict__.update(cursor.__dict__)
... | 992dc2f2ee085f335b3e046d51a0d4c443c2b4b8 | 649,301 |
def _convert_counters(counters, conversion_factor, label):
"""
Convert a single flat dictionary of counters of bytes into another unit
"""
results = {}
# convert each relevant key
for counter, value in counters.items():
if counter.endswith('_bytes'):
new_key = counter.replac... | 69eccada454847175d7be67ada302c74b4d71fa2 | 649,302 |
from typing import OrderedDict
def _get_moment_tensor_info(tensor, get_angles=False,
get_moment_supplement=False):
"""Internal - gather up tensor components and focal mechanism angles.
"""
msource = tensor['eventsource']
if tensor.hasProperty('derived-magnitude-type'):
... | f5d9765bf18d1b644c3aee595c4157fbcad5cabb | 649,303 |
def _build_link_header(links):
"""
Builds a Link header according to RFC 5988.
The format is a dict where the keys are the URI with the value being
a dict of link parameters:
{
'/page=3': {
'rel': 'next',
},
'/page=1': {
'rel': ... | 47b6fb8b69693400a60af8b6b75fd079c4884f14 | 649,304 |
def after_request(response):
"""Define acceptable response headers."""
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,POST')
return response | 709061cd1bae2dad04cc34170d745261d0223f1e | 649,305 |
def is_gerrit_issue(issue):
"""Returns true, if the issue is likely legacy Gerrit issue.
Doesn't do database requests and guesses based purely on issue.
"""
# Gerrit CQ used to post urls for Gerrit users usign same code as Rietveld.
# The only easy way to distinguish Rietveld from Gerrit issue, is that
# a... | 6d29f71ce4d887273be8875ae6bf7cb3efd1b7b3 | 649,306 |
import torch
def scale_model(model, scale):
"""Scale the parameters of a model.
Args:
model (torch.nn.Module): the models whose parameters will be scaled.
scale (float): the scaling factor.
Returns:
torch.nn.Module: the module with scaled parameters.
"""
params = model.na... | e28508ac7375c47183a02e4a12334eedbcd15c01 | 649,307 |
def printXYZ(self):
"""Print X, Y, and Z components."""
return ("[%f, %f, %f]" % (self.x, self.y, self.z)) | 79c585f7314fae60f641ae891f28114b2b353dd5 | 649,308 |
def verse(num_bottles, step=1, reverse=False):
"""Return one verse of the song."""
text_num = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six',
7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten'}
if reverse:
left_bottles = text_num.get(num_bottles + step, 'Ten or more')
... | ae66456c11af8cc39b685e80b3dfbbde1a867cf1 | 649,309 |
def single_tree_into_list(indata):
"""
Turn the fibrous tree based on dict into tree based on list.
:param indata:
:return:
"""
scale = 1e-3
scale = 1
outdata = []
for key in indata:
ii = indata[key]
outdata.append(ii)
return outdata | 025e1fc5e6dbcf3694e5d4df5856bd9ed79c21c6 | 649,310 |
def _check_columns(df_to_check, cols) -> None:
"""Check that a list of required column names is in a data frame
Args:
df_to_check: A DataFrame to check columns on.
cols (Iterable[str]): Required columns.
Returns:
None
Raises:
ValueError: if required cols are not a subset... | e0efe284662e65cbcbce6e13184bf71554600088 | 649,311 |
def makeCDSdict(dataCDS):
"""Takes the dataframe of the CDS information and puts that information on the ranges of the locus in lists
and dictionaries to be used later."""
print("Start makeCDSdict")
# Top strand lists:
dictrangesT = {} #initialize the dicitonary of key = locus, values = [start,stop... | 23db32155bf47ecf9a65e327a0ede14f7fe62a07 | 649,312 |
def cyclic_sort_vertices_2d(Vlist):
"""
Return the vertices/rays in cyclic order if possible.
.. NOTE::
This works if and only if each vertex/ray is adjacent to exactly
two others. For example, any 2-dimensional polyhedron satisfies
this.
See
:meth:`~sage.geometry.polyhedr... | 08853fa05512a7a49c4df60202640486ff1dc034 | 649,313 |
def is_classdef(leaf):
"""
Returns true if the leaf is the beginning of a class definition
"""
return leaf.type == 'keyword' and leaf.value == 'class' | af9fa0b81549bd451d0a10e8f291dada7cca7bc8 | 649,314 |
def parse_class_namespace_string(class_string):
"""
Parses the dotted namespace out of an object's __mro__. Returns a string
"""
class_string = str(class_string)
class_string = class_string.replace("'>", "")
class_string = class_string.replace("<class '", "")
return str(class_string) | d5849ecb4bf5effb3c5b1c97c200c0a727516ec4 | 649,315 |
def responseBinSim(input):
"""
:param input: user input
:return: score as yes or no. still need to work on gensim comparisons
"""
yeslist = ['yes', 'yep', 'yup', 'ok', 'okay', 'yea', 'yeah', 'sure', 'ya']
nolist = ['no', 'nope', 'no way', 'not at all', 'nay', 'negative']
input = input.lower(... | 4c10f443eab0b6cb668564e676bcb3885d797b4e | 649,316 |
import numpy
def normalize_labels(labels):
"""
Normalize labels.
Parameters
----------
labels : list
A list of labels.
Returns
-------
numpy array
A numpy array with normalized labels,
where normalization means converting the
container from a list to a numpy array.
"""
return ... | 4cdec24608c3a12309c9213d665a1e0fe0a99049 | 649,317 |
def get_play_speed(ctx):
"""获取机器人运行速度
Args:
ctx (context.Context): 登陆上下文
Retures:
Success (int): 机器人运行速度
Failure (None): None
"""
return ctx.tran.request("GET", "/v2/paramservice/robot/playspeed")["data"] | 659960220f64cc953143e319e82782703236e39e | 649,318 |
def classify(inputTree, featLabels, testVec):
""" 使用决策树执行分类
INPUT:
inputTree:决策树模型
featLabels:feature标签对应的名称
testVec:测试的输入数据
OUPUT:
classLabel: 分类的结果值,需要映射label才能知道名称
"""
# 获取tree的根节点对应的key值
firstStr = inputTree.keys()[0]
# 通过key得到根节点对应的value
secondDic... | 57076b1742dd4d1dc8c2e74a75cc3170c8048a0c | 649,319 |
import os
def parse_first_line_header(file_name):
"""Parse the first line of the header and extract station code
eg: surface_9958303_2019-05.csv
surface_9958303.csv
"""
# get the file name, path may contain _
file = os.path.basename(file_name)
code = file.split("_")[1]
if "... | f525d4a4ac1edbfe107197f4e2989f6f647b5369 | 649,320 |
import torch
def boxes3d2corners(boxes_3d):
""" b, 7 (cx, cy, cz, l, w, h, r)"""
N = boxes_3d.shape[0]
centers = boxes_3d[:, :3]
l = boxes_3d[:, 3] # (N)
w = boxes_3d[:, 4] # (N)
h = boxes_3d[:, 5] # (N)
headings = boxes_3d[:, 6]
# print l,w,h
x_corners = torch.stack([l / 2, l ... | f79c883e8af317a61cf00aabbce2264597675299 | 649,321 |
def target_function(s):
"""Generate a training data point."""
return s[:-2] + s[:-2] | ba7cc71e46ecc0e916dfa16eb6020f5073f07f32 | 649,322 |
from typing import List
def sieve_of_eratosthenes(n: int) -> List[int]:
"""
Simple Sieve of Eratosthenes algorithm to return all primes up to n.
:param n: the upper bound on the primes
:return: the list of primes in order
>>> sieve_of_eratosthenes(0)
[]
>>> sieve_of_eratosthenes(1)
[]... | 64a3282033b6c1957268957c51f081ce377f0089 | 649,323 |
from typing import Optional
def get_menu_input() -> Optional[int]:
"""Main menu prompt with the available configuration options"""
options = [
'1: List directories being monitored',
'2: Add directory to be monitored',
]
print()
print(*options, sep='\n')
try:
choice = i... | 066e2f3482965e7286d5cc81353649292e92d93a | 649,324 |
import errno
def _recv(sock, size):
"""sock.recv() with retry on EINTR"""
while True:
try:
return sock.recv(size)
except IOError as e:
if e.errno != errno.EINTR:
raise | dd4518e7914c39307bfb84e4cfa542367d90bb81 | 649,325 |
import os
def fn_check(fn):
"""Wrapper to check for file existence
Parameters
----------
fn : str
Input filename string.
Returns
-------
bool
True if file exists, False otherwise.
"""
return os.path.exists(fn) | 89d8fe0ef7e0fadf110ef5e9453baa64e98af57d | 649,327 |
def oncePerStep(sprite, game, name):
""" Utility for guaranteeing that an event gets triggered only once per time-step on each sprite. """
name = "_"+name
if hasattr(sprite, name):
# bounce only once per timestep, even if there are multiple collisions
if sprite.__dict__[name] == game.time:
... | 503871c04c4ca983828ecd8c2872220ee5200b11 | 649,328 |
def get_notebook_selection():
"""prompts user for notebook selection"""
return input("") | 29506e8cdf56d39d0d9100ea34bf5d29c2cb6bc9 | 649,330 |
import requests
import json
def post_json(url, data):
"""Helper method send HTTP POST requests to Elasticsearch."""
return requests.post(
url,
data=json.dumps(data),
headers={'Content-Type': 'application/json'},
) | 80b778c8ec620037c92f02f460309a309acdd70c | 649,331 |
def build_site_url(site,url,secure=False):
"""
Build an absolute URL for a given site
"""
protocol='http'
if secure:
protocol='https'
return u'%s://%s%s' % (protocol,site.domain,url) | 3ed73ba22a0ed82c781a968f9c549903867b516f | 649,332 |
def _CodepointString(unicode_text):
"""Converts unicode string to string of integers in uppercase hex.
Integers correspond to the codepoints within the string. Each integer is
followed by a space.
Args:
unicode_text: unicode string
Returns:
string
"""
return " ".join("%04X" % ord(c) for c in un... | 579e3bdb41d3091c07ca80c7219ee58b7539340e | 649,333 |
def as_system_dict(element):
"""
Autonomous System representation.
"""
return {'autonomous_system': {
'name': element.name,
'as_number': element.as_number,
'comment': element.comment
}
} | 896a371447e3cf3bd780067b63b4591398d8097b | 649,334 |
def get_tables(client, dataset):
"""
Get the names of all tables in a bigquery dataset.
client: bigquery connection
dataset: a connected bigquery dataset
Returns a list of all tables in the dataset
"""
return [table.table_id for table in client.list_tables(dataset)] | bc4baca1a5f2609996b6458348fcf19746c13db4 | 649,335 |
def make_django_user_details(user_name, django_user):
"""
Assemble details of the indicated Django user and return a user_details structure.
"""
user_details = (
{ 'name': user_name
, 'email': django_user.email
, 'uri': "mailto:%s"%django_user.email
, 'f... | 836545d309abf56fd619e0c17507f143a4bcdb1b | 649,336 |
def _select_algs(alg_type, algs, possible_algs, none_value=None):
"""Select a set of allowed algorithms"""
if algs == ():
return possible_algs
elif algs:
result = []
for alg_str in algs:
alg = alg_str.encode('ascii')
if alg not in possible_algs:
... | 602a3f00e7afaa335cd73b5b0016e3c8e7550110 | 649,337 |
def conv_general_permutations(dimension_numbers):
"""Utility for convolution dimension permutations relative to Conv HLO."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
lhs_char, rhs_char, out_char = charpairs = ("N", "C"), ("O", "I"), ("N", "C")
for i, (a, b) in enumerate(charpairs):
if not dimension_... | fc8dfef845e6527691bd41eaef895310cac7ff91 | 649,338 |
def store_true(arg, _, args, acc):
"""
lambda that store a True boolean value on the parser result
"""
acc[arg] = True
return args, acc | 84f6cb94905a03b1952ce62fc8e6bea354866016 | 649,339 |
def left_join(h1, h2):
"""
Functions that takes in two hashmaps, and return one hashmap with appended value if both hashmaps have both keys present
In: Two instances of a hashmap
Out: Hashmap with with appended value
"""
for bucket in h1.map:
if bucket:
for pair in bucket:
... | 18c69d46e213c13e4ef80c44f11037f78ac5819b | 649,340 |
def hour_decimal(dt):
""" For example, the time 12:45 becomes 12.75 """
return dt.hour + dt.minute/60 | 7ad56d4e8d38a9c2e108fca64dbc1d1409beceeb | 649,341 |
import json
import base64
def get_token_claim(jwt, claim):
"""Extract a claim from a JWT token without validating it."""
# Directly decode the base64 claims part without pulling in any JWT libraries
# (since we're not validating any signatures).
claims = jwt.split(".")[1]
# Pad the JWT claims bec... | 7fa9f3db03e9fea9e2bda5bd5cd888b232f82e3f | 649,342 |
from pathlib import Path
def _path_datafile(filename):
"""
Get absolute path to toolbox datafile
:param filename: relative pathname of datafile
:type filename: str
:raises ValueError: File does not exist
:return: Absolute path relative to *roboticstoolbox* folder
:rtype: str
Get the ... | f41d76ddafa624786a8ec0c13f2ca09f69391d8e | 649,343 |
from urllib.parse import quote, urlsplit, urlunsplit
def idna2ascii(url):
"""Converts unicode url to ascii"""
parts = urlsplit(url)
return urlunsplit((
parts.scheme,
parts.netloc.encode('idna').decode('ascii'),
quote(parts.path),
quote(parts.query, '='),
quote(parts... | 01670623f4e19ac2e56d7ebdc65e1135ccaa0b64 | 649,344 |
def genre_to_rating(movie_map):
"""Given a dictionary, returns new dictionary that maps genre to release
year to a list of IMBD ratings for each of those years.
Parameter:
movie_map: a dictionary that maps movieIDs to genre(s), release year,
IMBD rating, female character count and male char... | 37ef8dc012a7f7697f1c4e4ead71265e9c07e90b | 649,345 |
def e_cashback(subj, _text):
"""
cashback
"""
return [
u'Напоминание о кэшбэк', '', subj,
] | 2a82b0b4f752570c9c2bd059f21ac285ca72c6e9 | 649,346 |
from typing import Any
from typing import Callable
def apply_to_all(dictionary: dict[Any, Any], func: Callable[[Any], Any]) -> Any:
"""Recursively apply a callable to all elements (keys + values) of a dictionary."""
if type(dictionary) != dict:
return func(dictionary)
return {func(k): apply_to_all... | ba50df69abf4d0c12bcc9e5e343e4281721c9fec | 649,347 |
import json
import requests
def get_metadata():
""" Read metadata from local instance
Args:
None
Returns:
Dict of instance metadata
"""
metadata_server = "http://metadata/computeMetadata/v1/instance"
headers = {"Metadata-Flavor": "Google"}
return json.load... | efa123e83711128fe15fcae60e6fede1ca13d798 | 649,348 |
def squared_error(ys_orig,ys_line):
"""regresa la sumatoria de las distancias entre los puntos de la grafica y
la linea de regresion, esto es e**2"""
return sum((ys_line-ys_orig)**2) | 597dc822f75c99bf96e4ff75ae8f49674be87fb0 | 649,349 |
def _fmt( text, args = None, kwargs = None ):
""" Utility function. See fmt() """
if text.find('%') == -1:
return text
if not args is None and len(args) > 0:
assert kwargs is None or len(kwargs) == 0, "Cannot specify both 'args' and 'kwargs'"
return text % tuple(args)
if not kwar... | 94e88477d41e52f90dfb0a729e5b7fd347411320 | 649,350 |
def xrsplit(array):
"""
Split an array to a list of all the components.
Parameters
----------
array: xarray.DataArray
Array to split.
Returns
-------
sp_list: list of xarray.DataArrays
List of shape 0 xarray.DataArrays with coordinates.
"""
sp_list = [sa for sa... | b8b1ec8e1db3bc487fde02f3547ada1598a15963 | 649,351 |
from datetime import datetime
def now() -> int:
"""
Get UNIX-style time since epoch in seconds.
Returns
-------
int
Time since epoch in seconds.
"""
return int(datetime.now().timestamp() * 1000) | 3c3bc17cc366c0fad3c07405cfa42ad695ef25ec | 649,352 |
from pathlib import Path
import subprocess
def run_mininet(extra):
"""
Method to run Mininet in the background so the user can run commands through it
:param extra: The holder for the results to be stored to
:return: None
"""
path = str(Path.home()) + "/Desktop/"
sudo_pw = "Mininet"
... | 11cfdabefef091accb04ae9c4be13d9cc7d20918 | 649,353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.