content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import json
def trigger_mutation_test(limit):
""" Test data for IFTTT trigger bunq_mutation """
result = [{
"created_at": "2018-01-05T11:25:15+00:00",
"date": "2018-01-05",
"type": "MANUAL",
"amount": "1.01",
"balance": "15.15",
"account": "NL42BUNQ0123456789",
... | dc749cb7aaa3f65e29181ada2a07a727915fd90b | 666,328 |
def all_are_none(*args) -> bool:
"""
Return True if all args are None.
"""
return all([arg is None for arg in args]) | f23b00b5f0d7ae50e08cc25b48f524cb13fa2753 | 666,330 |
def default_join(row, join, *elements):
"""
Joins a set of objects as strings
:param row: The row being transformed (not used)
:param join: The string used to join the elements
:param elements: The elements to join
:return: The joined string
"""
return str(join).join(map(str, elements)... | 2663c2d0869330eb370ac2befdd4fca9f46ea8f0 | 666,331 |
def led():
"""Calls the LED function.
GET: LED flashes.
Returns HTTP 200 on success; body is payload as-is.
Returns HTTP 404 when data does not exist.
"""
return 'blink' | ba761730d41516688b0062c92ba7d3708fe8f23d | 666,333 |
def freeze(model):
"""
Freezes all the parameters in the model
Returns
-------
Model
the model itself
"""
for param in model.parameters():
param.requires_grad = False
model.training = False
return model | 70afe94a83eaf1203e099d47ecc53209d70ba658 | 666,334 |
def tirar_bijecao(line):
"""
Retira o número de correspondência das regras.
:param line: lista com a regra
:return: lista com a regra sem número de correspondência.
"""
regra_sem_bij = []
for e in line:
regra_sem_bij.append(e[:-1])
return regra_sem_bij | e02917190c9960ae571c2ddaf97dfd92ead18581 | 666,335 |
def identity(x):
"""Return the argument as is."""
return x | b46c085f18d367db1d307bad26d28e8d55096756 | 666,336 |
import re
def split_s(pattern, string, maxsplit=0, flags=0):
"""Split function in perl is similar to re.split but not quite
the same - this is the version used in scalar context"""
result = re.split(pattern, string, max(0, maxsplit), flags)
if len(result) >= 1 and result[0] == '' and (m:=re.match(p... | c9271e44e3b918f247aa915c42772646adc7d785 | 666,338 |
def dec_str_to_int(ch):
"""function to process a decimal string into an integer."""
return int(ch) | 5c1eb00f8b4704c18ede4d75666d097816568420 | 666,339 |
def partition_all(n):
"""Partition a collection into sub-collections (lists) of size n."""
def generator(coll):
temp = []
for i, item in enumerate(coll, 1):
temp.append(item)
if not i % n:
yield temp
temp = []
if temp:
y... | 54bea1f22b2b0a494461a3737111b5e8e25ca8b0 | 666,341 |
import subprocess
def install():
"""Installs an npm package in the current directory"""
return subprocess.Popen('npm install', shell=True) | 23663c4f260264fbbe77384b5b2efaf0ee5421ed | 666,342 |
def split_batch_size(batch_size, num_workers):
"""Returns a list of batch_size
Args:
batch_size (int): total batch size
num_workers (int): number of workers
"""
num_workers = min(num_workers, batch_size)
split_size = batch_size // num_workers
total_size = 0
split_sizes = [sp... | 45918b63c011dd849d6b1115f06bbdd764c445db | 666,343 |
def retrieve_id(seqheader,extrainfo=False):
"""Extracts sequence IDs from a standard .fasta header.
:param seqheader: Standard .fasta header, starting with ">".
:type seqheader: str
:param extrainfo: If True, extra information string is returned instead of sequence IDs, defaults to False.
:type ext... | 16a840cd8f6fb4968ddae09a25dd6ab968cd0120 | 666,344 |
def private_key():
"""Server side private key."""
return "Toholampi summer festival 2017 has the most harcore rock bands" | d9e6889a66c677ca09fb85ea963d4b44103170ce | 666,346 |
def CONCAT_ARRAYS(*arrays):
"""
Concatenates arrays to return the concatenated array.
See https://docs.mongodb.com/manual/reference/operator/aggregation/concatArrays/
for more details
:param arrays: A set of arrays(expressions).
:return: Aggregation operator
"""
return {'$concatArrays': ... | 0b77fb6b9c687ef9217c1f6e6504ed3a70d25db9 | 666,347 |
from itertools import groupby
def process_join(interface, state, label, inp, task, full_join, label_fn,
ffuncs, ghfuncs, deffuncs, agg_fn, wide=False, need_agg=False):
"""
Processor function for the join stage.
Note that each key in the 'inp' is orgnized as:
key = (where_index, j... | 584d08476de8a4b3dddf356580ac9ab98e4c85ad | 666,348 |
def get_total_time_in_sec(last_user_stats):
"""Calculates the total time you listen to music"""
return last_user_stats.total_time | 74e9f4db656a8ea181d65c0b3cc5742455eda696 | 666,350 |
def get_emotion(detected_faces):
"""
Looks into the response of Azure and compiles an easy-to-read dictionary of emotion values for
the first detected face.
:param detected_faces: A dictionary containing the detected faces and their associated attributes.
:return: A dictionary containing the emotion... | dbc04c44802a9e9dafd1f9e76c2a842476d9536f | 666,351 |
def filters(tag, val):
"""Helper method for parsing filters."""
return {
'Name': 'tag:%s' % tag,
'Values': ['%s' % val]
} | 87314f2531529128a88413ded71ff9886055af7e | 666,352 |
def isnan(z): # real signature unknown; restored from __doc__
"""
isnan(z) -> bool
Checks if the real or imaginary part of z not a number (NaN)
"""
return False | 6bcafccc5f4746a2b21c7b35214e08b078b60677 | 666,353 |
import re
def crush_invalid_field_name(name):
"""Given a proposed field name, replace banned characters with underscores, and convert any run of underscores with a single."""
if name[0].isdigit():
name = "_%s" % name
name = re.sub(r'[^a-z0-9_]', "_", name.lower())
return re.sub(r'__*', "_", na... | dbc672b4a725169ca1c335f3ae2f335279460f9c | 666,354 |
def basis_function(degree, knot_vector, span, t):
"""Computes the non-vanishing basis functions for a single parameter t.
Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller.
Uses recurrence to compute the basis functions, also known as Cox - de
Boor recursion formula.
"""
le... | b23549dfa81a87acf2478120eaf9c9e1e84005d5 | 666,355 |
import configparser
import os
def _get_config_parser(path):
"""Given a path, gets a config parser"""
ret = configparser.ConfigParser()
ret.read(os.path.expanduser(path))
return ret | 106f6ee4fc53950df511b2436706ed8edd98aaf6 | 666,356 |
def gen_user_list_id(user_list_obj):
"""
Generates the Elasticsearch document id for a UserList
Args:
user_list_obj (UserList): The UserList object
Returns:
str: The Elasticsearch document id for this object
"""
return "user_list_{}".format(user_list_obj.id) | 80aa70a0ad6c3a13822968b1f111cbc669fa7d62 | 666,357 |
import pickle
def pickle_load(pickled_file):
"""
This function...
:param pickled_file:
:return:
"""
_file = open(pickled_file, "rb")
output = pickle.load(_file)
_file.close()
return output | 1d9d6b228187cf70b4183517894e77257490c150 | 666,359 |
import os
def isfolder(*args, make_if_absent=False):
"""Returns true if input path is the name of a valid, existing, file. Joins multiple inputs.
tf = isfolder(str) Returns true is str is a full (or relative from the current working directory) folder path,
false otherwise.
tf = isfolder(str1, str2, ... | 5c0b4253a3926619609d3da198e3972192ff0cef | 666,360 |
def get_gamma_distribution_params(mean, std):
"""Turn mean and std of Gamma distribution into parameters k and theta."""
# mean = k * theta
# var = std**2 = k * theta**2
theta = std**2 / mean
k = mean / theta
return k, theta | 49b5ccdf7b83c949b81ad05e6d351cfb0b1f4d26 | 666,361 |
def admins_from_iam_policy(iam_policy):
"""Get a list of admins from the IAM policy."""
# Per
# https://cloud.google.com/appengine/docs/standard/python/users/adminusers, An
# administrator is a user who has the Viewer, Editor, or Owner primitive role,
# or the App Engine App Admin predefined role
roles = [
... | a2bf60ead9ba27de7013b87a70baeb2fb5d17dab | 666,362 |
import torch
def to_tensor(data):
"""
Convert numpy array to PyTorch tensor.
"""
return torch.view_as_real(torch.from_numpy(data)) | dec478a853e2e71d8578c59648db484b208685a8 | 666,363 |
import os
def _make_tmp_dir(cfg):
"""Make the tmp and ancil dirs."""
tmp_dir = os.path.join(cfg['work_dir'], 'tmp')
ancil_dir = os.path.join(cfg['work_dir'], 'ancil')
if not os.path.exists(tmp_dir):
os.makedirs(tmp_dir)
if not os.path.exists(ancil_dir):
os.makedirs(ancil_dir)
r... | e4a17ffd36960b6154fd10da56e97a1d4b862b57 | 666,365 |
import re
def parse_host_ids(text):
"""Parses the host list input string. If preceded by a "!", generate a host list
using the input as a range.
Parameters
----------
test : str
Returns
-------
list
"""
match = re.search(r'^\!\[\s*(\d+)\s*\,\s*(\d+)\s*\,?\s*(\d+)?\s*\,?\]$',... | 93bfa5922906008181f66905cf0b7d97ec4548f7 | 666,366 |
def pretty_str(label, arr):
"""
Generates a pretty printed NumPy array with an assignment. Optionally
transposes column vectors so they are drawn on one line. Strictly speaking
arr can be any time convertible by `str(arr)`, but the output may not
be what you want if the type of the variable is not a... | 4e48a9e68a1fa764c4af5827dd2b015868829986 | 666,367 |
def merge_duplicate_concepts(concepts):
"""
NHP has many duplicate ingredients in the raw data. During
data preprocessing each unique ingredient string is assigned a unique
ID, so duplicate ingredient entries will have the same ID. This
function merges those entries into a single concept.
:para... | 9138e97c82ed15c44fd59f2e46d1465fa2f41cfa | 666,368 |
def remove_stopwords(record):
"""
Remove stopwords from a string
"""
words = record.split()
# Core stopwords
stopwords_core = [u'a', u'about', u'above',
u'after', u'again', u'against', u'all',
u'am', u'an', u'and', u'any', u'are',
... | 0af7ca497c07df58c65c4e2b5a6858deb4503fb6 | 666,369 |
import argparse
import os
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Evaluate the given model on the given data')
def check_extension(extensions, filename):
ext = os.path.splitext(filename)[1]
if ext not in extensions:
parser.e... | 5a1827931eab13e15271907d9fb2c47142cb32f5 | 666,370 |
import os
import sys
def getAppDataDirDir():
""" getAppDataDirDir()
Get the directory where visvis can store user-specific data.
"""
# Define user dir and appDataDir
userDir = os.path.expanduser('~')
appDataDir = os.path.join(userDir, '.visvis')
if sys.platform.startswith('wi... | 9353895432ce175ad276d21ba872a50d296a5434 | 666,371 |
def dict_factory(cursor, row) -> dict:
"""Transform tuple rows into a dictionary with column names and values
Args:
cursor: database cursor
row: row
Returns:
dict: a dictionary containing the column names as keys and the respective values
"""
output = {}
for idx, col in... | fbc8d1e1157f0d6d3f70236ad36b6002ba34b45e | 666,372 |
def hello(friend_name: str):
"""
@args
friend_name: str, a name of a friend
@return
"""
return f"Hello, {friend_name}!" | 68c0a2e93c31c53f6c449ce482539f4f7d83c9dc | 666,373 |
def regionalGlobalMoments(ds1, ds2):
"""
moments - regional /averaged
"""
return ds1.regionalAndGlobalInvariantMomentsCorr(ds2), 'moments_regional+global' | c300c8c8896164a956c7cc2ba11bc9df76771b76 | 666,374 |
import torch
def onehot(y, num_classes):
"""
Generate one-hot vector
:param y: ground truth labels
:type y: torch.Tensor
:param num_classes: number os classes
:type num_classes: int
:return: one-hot vector generated from labels
:rtype: torch.Tensor
"""
assert len(y.shape) in [... | b112afc1d3ae7b2182a2304fddac1d473b896576 | 666,375 |
def bitstring_to_bytes(bitstring):
"""Converts one of those ASN.1 bitstrings to bytes.
Args:
bitstring: ASN.1 bitstring encoded as a sequence of bits.
Returns:
Binary representation of the bitstring as bytes.
"""
bits = list(bitstring) + [0] * ((8 - len(bitstring) % 8) % 8)
bytes = []
... | 415fdb268b50ca9b41e721edf2861e6e29b08dfe | 666,376 |
def CubicInOut(start=0.1, finish=1.0):
"""
Cubically increasing, starts and ends very slowly but very fast in the
middle.
"""
def cubic_in_out_easing(sprite, delta):
delta *= 2.0
if delta < 1.0:
return start + 0.5 * delta * delta * delta * (finish - start)
delta ... | 92da45c2877aa2ca87565dbd2d2beece612fe8fa | 666,377 |
def filter_parsed_question(tree):
"""
Filters and flattens a given NLP tree
and keeps only most important parts of it
:type tree tree
:rtype: list[str, str]
"""
def get_item_type_and_value(_item: str):
"""
:type _item str
:rtype: (str, str)
"""
# (NNP... | d6658126d8b78b7cb54f8a89e6dfab6ea1ec461d | 666,378 |
import os
def env(*_vars, **kwargs):
"""Search for the first defined of possibly many env vars.
Returns the first environment variable defined in vars, or
returns the default defined in kwargs.
"""
for v in _vars:
value = os.environ.get(v, None)
if value:
return value... | 172705b3970ceb4e1d0720bca4367e28f287b674 | 666,379 |
import math
def __MtoE(M,e):
"""Calculates the eccentric anomaly from the mean anomaly.
Args:
M(float): the mean anomaly (in radians)
e(float): the eccentricity
Returns:
float: The eccentric anomaly (in radians)
"""
E = M
dy = 1
while(abs(dy) > 0.0... | 06697e5582e72c570a48b66978f215c215df9fc8 | 666,380 |
import os
def assert_address(opt):
"""
Checks is a address exists or not.
:param opt: parser
:return: return 0 on success else raise exception.
"""
try:
assert os.path.exists(opt.dir)
assert os.path.exists(opt.blue_score_script)
assert os.path.exists(opt.moses_tok_scrip... | 690b2f6226eb732bef6cd1dbf7001452ef25f006 | 666,381 |
def get_f1(candidate, refs):
"""Compute F1 score for candidate and list of references."""
# split into tokens & remove dublicates
token_c = candidate.strip().split()
token_c = set(token_c)
score = 0.0
if not token_c:
return score
for ref in refs:
token_r = ref.strip().split()
token_r = se... | d0025d55af4ff72e0741e289c6e47b24230afafa | 666,384 |
def identity_grid(grid):
"""Do nothing to the grid"""
# return np.array([[7,5,5,5],[5,0,0,0],[5,0,1,0],[5,0,0,0]])
return grid | 04115496775baa3a002331c16aaf89ef851e501b | 666,385 |
def sitewide_election_metrics_sync_out_doc_template_values(url_root):
"""
Show documentation about sitewideElectionMetricsSyncOut
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # bo... | 429c988cc3519931b290ebc69ade17af58f17cb9 | 666,386 |
def is_valid_param(param):
"""Given a parameter string, this method checks whether that parameter
is a modifiable parameter in header.f90."""
return param == "NS" or param == "NRTOT" or param == "NX" or param == "NTIME" or param == "NELEM" | 869eef43da6f189881a991837cd619ec67cc8715 | 666,387 |
import sys
def tryDivide(a: int, b: int) -> float:
"""divides numbers"""
div = 0
try:
div = a / b
return div
except TypeError:
print('one of arguments is not a number:', a, type(a), b, type(b))
# типа как process.exit() в Node.js
print(sys.exc_info()[1])
... | 02351075632a9900319fb72329ba889924005b4f | 666,388 |
import pandas
def get_user_lookup_table():
""" returns series mapping user id to user name """
return pandas.read_table('/etc/passwd', sep=':', names=['user','code','id','group','home','shell'], index_col=2)['user'] | db2784e9401dd248d3dffe6600a62686444636a1 | 666,389 |
def mark_fill(image, fills):
"""Mark filled areas with 0.
# Arguments
image: an image.
fills: an array of fills' points.
# Returns
an image.
"""
result = image.copy()
for fill in fills:
result[fill] = 0
return result | 3fa9981ea285a2e36b313da0cb11d181a335acf2 | 666,390 |
import os
def getenv_check(e):
"""
Check environment variable is defined, and return the result
"""
res = os.getenv(e)
if res == None:
print(e, 'environment variable not set - stopping.')
exit(1)
else:
return res | c8abd05d6655f1753f287e6e28b6f7c649fa307c | 666,392 |
def squad_EM(preds, labels):
"""
Count how often the pair of predicted start and end index exactly matches one of the labels
"""
n_docs = len(preds)
n_correct = 0
for (pred, label) in zip(preds, labels):
qa_candidate = pred[0][0]
pred_start = qa_candidate.offset_answer_start
... | 0191dca287a397991f25519862cde08be831d48c | 666,393 |
def ObtainWaitingtimes(data_stochsim,reactions):
"""
This function extracts the waiting times for each reaction of the model from the used SSA output.
Input:
- *data_stochsim* (python data object) that stores all simulation data
- *reactions* (list)
output:
- *D_waiting_times* (dict)
... | 39c8d1312e16b01c8556611b87de0eb782e62d1f | 666,394 |
def supply(request, page_name):
"""Supply the view_objects content."""
_ = request
_ = page_name
return {} | f3998c82b5a5110dab6966fedbe92b9d4b28bd2e | 666,395 |
from typing import List
def intcode_computer(program: List[int],
sum_code: int = 1,
multiply_code: int = 2,
finish_code: int = 99
) -> List[int]:
"""
An Intcode program is a list of integers separated by commas (like 1,0,0,3,9... | 0110d2803923e92ac024b108b9bd05704d215d8d | 666,397 |
def stem(word):
""" Stem word to primitive form
This example taken from toolz: https://github.com/pytoolz/toolz
There are several different ways to split a string, stem the words,
and calculate their frequency.
"""
return word.lower().rstrip(",.!:;'-\"").lstrip("'\"") | 65711314daed542fa8de64796b1c8688d67cebba | 666,398 |
def _get_meal_cost():
"""Private function to get meal cost from user, check that the cost is valid float."""
try:
return float(input('Cost of meal: '))
except ValueError: # Using built-in ValueError raised by float conversion
print('Must be a valid decimal number. Please try again.')
... | b51509800a0f22ef4e5a07d3b6de5f893d94ef90 | 666,399 |
def routepack(value):
"""Pack a route into a string"""
return str(value).replace("/","!") | f243f61924f316554c8f07949f8d759e2bd42940 | 666,401 |
import argparse
def get_args():
""" Get command-line arguments. """
des = "Optimal Interpolation of spatial data"
parser = argparse.ArgumentParser(description=des)
parser.add_argument(
"ifile",
metavar="ifile",
type=str,
nargs="+",
help="name of input file (in H... | 6979f5212e3aeab51b312321c0df32df730eec9b | 666,402 |
def order_pythonic(sentence: str) -> str:
"""Returns ordered sentence (pythonic).
Examples:
>>> assert order_pythonic("") == ""
>>> assert order_pythonic("is2 Thi1s T4est 3a") == "Thi1s is2 3a T4est"
"""
return " ".join(
sorted(sentence.split(), key=lambda x: "".join(filter(str.... | b6d47419afe86137471412937f31d17bbc5934d0 | 666,403 |
def RSet(var, value):
"""Do a VB RSet
Right aligns a string within a string variable.
RSet stringvar = string
If stringvar is longer than string, RSet replaces any leftover characters
in stringvar with spaces, back to its beginning.
"""
return " " * (len(var) - len(value)) + value[:len(... | f74324c6ce30d743e21efa31c9a0c712b2d8d025 | 666,404 |
import pdb
def lower_bound_caen(gr):
"""
See the article "A lower bound on the probability of a union" by Caen
:param gr: Graph where each node correspond to an embedding
:return: lower bound on the prob of union of embeddings
"""
lb = 0.0
for ev1, attr1 in gr.nodes(data=True):
non... | bc512cb16d7da401dd96b76d6f227d5f7ce0c063 | 666,405 |
def create_2d_box(box_2d):
""" create 2d box """
corner1_2d = box_2d[0]
corner2_2d = box_2d[1]
val_pt1 = corner1_2d
val_pt2 = (corner1_2d[0], corner2_2d[1])
val_pt3 = corner2_2d
val_pt4 = (corner2_2d[0], corner1_2d[1])
return val_pt1, val_pt2, val_pt3, val_pt4 | 14f3422828d477c17bf19b3b751c3dac51258195 | 666,406 |
from typing import Union
from typing import List
from typing import Set
from typing import Counter
def list_equal(
left: Union[List[Union[str, int]], Set[Union[str, int]]],
right: Union[List[Union[str, int]], Set[Union[str, int]]],
use_sort=True,
) -> bool:
"""
判断列表是否相等,支持具有重复值列表的比较
参考:https:/... | 081072a0bba9b33904e330cd4268e5b1fbd14fbe | 666,407 |
def check_callbacks(bot, url):
"""Check if ``url`` is excluded or matches any URL callback patterns.
:param bot: Sopel instance
:param str url: URL to check
:return: True if ``url`` is excluded or matches any URL callback pattern
This function looks at the ``bot.memory`` for ``url_exclude`` patter... | 060e031caab1efcc43e4a0e606001075bc23395f | 666,408 |
def make_biplot_scores_output(taxa):
"""Create convenient output format of taxon biplot coordinates
taxa is a dict containing 'lineages' and a coord matrix 'coord'
output is a list of lines, each containing coords for one taxon
"""
output = []
ndims = len(taxa['coord'][1])
header = '... | 4c461fb160544333109a126806cea48047103db1 | 666,409 |
def set_add__Set_ANY(space, w_left, w_other):
"""Add an element to a set.
This has no effect if the element is already present.
"""
w_left.setdata[w_other] = None
return space.w_None | 1fc735a10cffd463f9184ad6fb2226f788cd738f | 666,410 |
import re
def derive_ip_address(cidr_block, delegate, final8):
"""
Given a CIDR block string, a delegate number, and an integer
representing the final 8 bits of the IP address, construct and return
the IP address derived from this values. For example, if cidr_block is
10.0.0.0/16,... | 402008bfcac8b4682b1edf01798d931a2a3930ec | 666,411 |
def expect_formatted_streams():
"""
Expected streams for the best matching video for "track" in
search results.
The `download_url` is expected as `None` since it's impossible
to predict its value before-hand.
"""
return [
{"bitrate": 160, "content": None, "download_url": None, "enco... | fc52a677847893f24fdb59647edf938cb8c05815 | 666,413 |
def get_struct_member_vardecl(struct_type, member_name, declvisitor=None):
"""Return the type for the member @member_name, of the struct type defined by
@struct_type."""
for vardecllist in struct_type.children:
assert vardecllist.type == "VarDeclList"
for vardecl in vardecllist.children:
... | b880c40dcc4f9a983e948b4cb98dc28963030c2c | 666,414 |
import re
def indent_xml(message):
"""
Indents the XML in a nice way.
"""
INDENT_SIZE = 2
lines = [line.strip() for line in message.split("\n") if line.strip() != ""]
indent = 0
for i, line in enumerate(lines):
if i == 0:
continue
if re.search(r'^</[^>]+>$', lin... | 2d39c0da47dff867412693f66dcce8a95d1372b1 | 666,416 |
def nc_define_var(ncid, metadata):
"""
Define a new variable in an open netCDF file and add some default
attributes.
Parameters
----------
ncid: netCDF4.Dataset
Handle to an open netCDF file.
metadata: dict
Bundle containing the information needed to define the variable.
... | be2f30a469f0e36ae24bb1fa4722f41b0833e690 | 666,417 |
import os
def get_file_name(pathname: str) -> str:
"""
Return the last child of the tree represented by the given pathname.
:param str pathname:
:return str:
"""
pathname = pathname.rstrip("/")
return os.path.basename(pathname) | 0771121056e52a526cfff5f107c8ff216b0bcdf5 | 666,419 |
def create_one_hot(vector, one_hot_size):
"""Creates one-hot matrix from 1D vector"""
batch_size = vector.size()[0]
depths_one_hot = vector.new(batch_size, one_hot_size)
return depths_one_hot.zero_().scatter_(1, vector.unsqueeze(1), 1).float() | 8e7f734a3d922b26f36c9c069bf0ee25aee1c8a3 | 666,421 |
def get_outer_corners(corners):
"""gets the outer box of corners
Args:
corners: list of corners to iterate
Returns:
4 of the outer corners
"""
top_left = corners[0]
top_right = corners[0]
bottom_left = corners[0]
bottom_right = corners[0]
for corner in corners:
... | dec6bbd75dba27823a5a89d84c0d6a58145e9f55 | 666,422 |
import re
def clean_date_time(text, replace_with="time"):
"""Remove date and time expressions from a text and replace them
with the value of the parameter replace_with"""
# Remove all time expressions formatted with 'am' and 'pm'
new_text = re.sub(r"\d{1,2}:\d{1,2}:\d{1,2}\s*[a|A|p|P][m|M]", replace_... | a2adf66fe3dfec32084d5232e821eae0df8a8497 | 666,423 |
import numpy
import math
def scalarField(x,y):
""" this is the analytical function, it can be padded, doenst matter,
there results are in function of spacing"""
phi = 0.1*numpy.cos(2.0*math.pi*y)*numpy.cos(2.0*math.pi*x)
return phi | 8691c0105000bb5cdb6b6ffe8067c9184dee6eab | 666,424 |
def eval_vehicle_offset(pixel_offset, mx=3.7/780):
"""
Calculates offset of the vehicle from middle of the lane
based on the value of the pixel offset of center of the
detected lane from middle of the camera image.
The vehicle offset is calculated in meters using the scale
factor mx (in meter... | a06566505f3cd207674b6bb3e652defe1660eef2 | 666,425 |
def __deserialize_file(response):
"""Deserializes body to file
More specifically it just returns a pointer to the binary content
of the response, so the user can decide what do do with the data.
"""
return response.content | e942343b7dc0f0ed282770316138a523da01a439 | 666,426 |
import os
def join_path(path1, path2):
"""Join and normalize two paths.
"""
return os.path.normpath(os.path.join(
path1, os.path.expanduser(path2))) | c8b1a0f56241ffbbb0ef59ea8fa1da911fc351c6 | 666,427 |
def dict_from_hash(hashstring):
"""
From a hashstring (like one created from hash_from_dict),
creates and returns a dictionary mapping variables to their
assignments.
Ex:
hashstring="A=0,B=1"
=> {"A": 0, "B": 1}
"""
if hashstring is None:
return None
if len(hashstring) == 0:
return {}
re... | 966b33f0fd919506b99cd4e154033c952a002a99 | 666,428 |
def users_in_group(conn,groupname):
"""
Gets all users in a group in the Openstack OU. Takes
* connection object
* Group name
Returns a array of hashes with keys: mail, username, firstname, lastname and DN
"""
users = []
conn.search(attributes=['givenName','sn','mail','distinguishedName'... | 8d336194a5d0dbe28d87dd1d337730c01d5babc5 | 666,430 |
def is_compose_project(group_id, artifact_id):
"""Returns true if project can be inferred to be a compose / Kotlin project
"""
return "compose" in group_id or "compose" in artifact_id | 7b659c459c2f39485ee59fc43b70ee81c5e5bb95 | 666,431 |
def domain_name(url):
"""
url: url of a website to split from "/" and "."
return: domain name from the url
"""
domain_list = ([elt.split(".") for elt in url.split("/")])
for elt in domain_list:
name = ([elt[i] for i in range(len(elt)) if elt[i] != "www" and elt[i] != "http:" and elt[i] != "https:" and e... | 6e55b6e89c301264eab634bb230bd5e577e65f37 | 666,432 |
def checkIfTableNeedExist(database, cursor, tableNameList):
"""
Input: the connected database
this function will check if the tables that is needed for this program exists or not
if yes:
return 1
if no:
return -1
"""
for tableName in tableNameList:
cursor.execute("SELECT name FROM sqlite_master WHERE typ... | a36178ac38d934ec5fbb2bbf2f53fa7b8cd09759 | 666,433 |
import json
def use_json(insert_function):
"""
DECORATOR
:param insert_function: this is the function that will be called using the jsonObejct (as dictionary) as second
parameter by this decorator
:return: the inner function ==> execution of the following procedure:
1. loading the json as... | 9621a8b2fc3b788788cec54b9fac563a734a2491 | 666,435 |
def __x_product_aux (property_sets, seen_features):
"""Returns non-conflicting combinations of property sets.
property_sets is a list of PropertySet instances. seen_features is a set of Property
instances.
Returns a tuple of:
- list of lists of Property instances, such that within each list, no tw... | 4c8556d8e83e8cc88f7dbfc0aeffc678eda17a12 | 666,436 |
def steering2(course, power):
"""
Computes how fast each motor in a pair should turn to achieve the
specified steering.
Input:
course [-100, 100]:
* -100 means turn left as fast as possible,
* 0 means drive in a straight line, and
* 100 means turn right as fast as po... | 3e6c8919042fa167d1c98fcb26f05d2aa4955a41 | 666,437 |
def minmax(dates):
"""Returns an iso8601 daterange string that represents the
min and max datemap.values().
Args:
datestrings: [d1, d2, d3,]
Returns:
['min_date/max_date',]
Example:
>>> minmax(['2008-01-01', '2010-01-01', '2009-01-01'])
"2008-01-01/2010-01-01"
... | 012a081fadb633384c7369e9d637bb9761667489 | 666,438 |
import os
def get_optimal_bucket_boundaries(n=100):
"""Function to get the optimal bucket boundaries
Args:
n (int): Number of buckets
Returns:
bucket_boundaries (list): Optimal bucket boundaries for n
"""
train_list_file = os.path.join('data', 'train_list.txt')
val_list_f... | 00b65fedaf6e076cc8aa186e83d27d6c675e3c7c | 666,439 |
import os
import gzip
def read_info_from_man():
"""Read information on commands from the vimivrc.5 man page.
Return:
A dictionary containing command-names and information on them.
"""
infodict = {}
# Man page might have been installed as .5.gz by a package manager
if os.path.isfile("/... | d9a0e2bbd17159029aeee3e62cc4531d9872d502 | 666,440 |
import argparse
def get_cli_parser(): # pragma: no cover
"""Get the CLI parser."""
parser = argparse.ArgumentParser(description='Create beautiful releases on GitHub.')
parser.add_argument('infile', type=argparse.FileType('r+t'))
parser.add_argument('-i', '--in-place', action='store_true', help="Updat... | ef5292f41a0f8ba1547c3c80103fd6bf36761b17 | 666,441 |
def horiz_div(col_widths, horiz, vert, padding):
"""
Create the column dividers for a table with given column widths.
col_widths: list of column widths
horiz: the character to use for a horizontal divider
vert: the character to use for a vertical divider
padding: amount of padding to add to eac... | b83399e401d655fcaa6ad3ff66fb936c8737a8da | 666,442 |
from bs4 import BeautifulSoup
def cleanHTML(raw_html):
"""
Remove HTML tags
"""
return BeautifulSoup(raw_html,"lxml").text | b52f8acdc77d57dea6f5874c6ea94f61eed11756 | 666,443 |
def _get_message(fh, msglen):
"""Returns the message
The message is given in the line (or maybe multiple lines)
following the current line. If the length of the line(s) read match
the length of the expected message the message is wrapped in double
quotes and returned. Otherwise an exception is raised.
"""
... | f5e59b1071a816bdf933e67d8591ad2910cb7ea6 | 666,444 |
def get_filter_in(filters):
"""Recuperar filtros de una lista"""
filter_in = {}
for filter_index, value in list(filters.items()):
if isinstance(value, list):
filter_in.update({filter_index: value})
del filters[filter_index]
return filter_in | d39b9399199d6572ed668207adca4e0a0429bee3 | 666,445 |
def appendDtectArgs( cmd, args=None ):
"""Append OpendTect arguments
Parameters:
* cmd (list): List to which the returned elements will be added
* arg (dict, optional):
Dictionary with the members 'dtectdata' and 'survey' as
single element lists, and/or 'dtectexec' (see odpy.getODSoftwareDir)
... | e3af9ee1bb9cf73b7e836ada985d342e53012f2e | 666,446 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.