content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def GateBranches(x, **unused_kwargs):
"""Implements a gating function on a (memory, gate, candidate) tuple.
Final update is memory * gate + (1-gate) * candidate
This gating equation may also be referred to as Highway Network.
Highway Networks: https://arxiv.org/abs/1505.00387
Args:
x: A tuple of (memor... | bb72b6de2af808929e7bb24cb31bfa34d5791c41 | 638,792 |
def text(meta):
"""
Returns the meta message's text as a string.
"""
return meta[3].decode('ascii') | 47dee2ab4606a18f9418dc45b26b9d28269a4abb | 638,793 |
def get_r12_squared(r1, r2):
"""Get the distance between two centers in Cartesian space."""
return (r1[0] - r2[0])**2.0 + (r1[1] - r2[1])**2.0 + (r1[2] - r2[2])**2.0 | 63e792e25e5be209b8a5c783307f067f387c260a | 638,794 |
import torch
def compute_distances(model, prototypes, batch):
""" Computes the distances between all vectors to all prototypes """
inputs, targets = batch
outputs = model(inputs)
# Calculate euclidean distance in a vectorized way
diffs = outputs.unsqueeze(1) - prototypes.unsqueeze(0)
distanc... | 353a811af2876237d9be36fd25239327a5aa22a5 | 638,795 |
def hierarchical_label(*names):
"""
Returns the XNAT label for the given hierarchical name, qualified
by a prefix if necessary.
Example:
>>> from qixnat.helpers import hierarchical_label
>>> hierarchical_label('Breast003', 'Session01')
'Breast003_Session01'
>>> hierarchical_lab... | 91124a21ef117c2aa0b3ae45c078cd1e8f4a3314 | 638,797 |
def train_test(df):
"""
split into train and test set
train contains Jan 1, 2018 through July 31, 2018
test contains August 1, 2018 through September 28, 2018
:param df:
:return:
"""
df = df[df['Date'] >= '2018-01-01']
train = df[df['Date'] < '2018-08-01']
test = df[df[... | 665657b8daa804762297063bc4b2fd14c2a5155f | 638,798 |
import re
def is_regex(tentative_regex: str):
""" Returns true if the argument is a valid python regex, and false otherwise. """
if len(tentative_regex) == 0:
return False
try:
re.compile(tentative_regex)
return True
except re.error:
return False | adcf2693bbbdd3e83344dfd4ac393dc8342a1372 | 638,799 |
def _team_sizes(rating_groups):
"""Makes a size map of each teams."""
team_sizes = [0]
for group in rating_groups:
team_sizes.append(len(group) + team_sizes[-1])
del team_sizes[0]
return team_sizes | 9c2fa2ab1928054074afba77ecfd5291654b64bb | 638,800 |
import codecs
def load_vocab(vocab_path):
""" Loading a vocabulary file
:param vocab_path: Path to vocabulary file
:return: Array contains words
"""
with codecs.open(vocab_path, encoding="utf-8") as fobj:
vocab = fobj.readlines()
return vocab | 2e71a6693c2b174413ccc4447d7387a8cfb43dc1 | 638,801 |
import os
def os_path(import_path: str, ext: str) -> str:
"""
Build the path to a module from it's import path.
"""
return os.path.join(*import_path.split(".")) + ext | 6d8283220ded036f71936091264d769d846ffff5 | 638,802 |
import math
def ceil(number):
"""
Return the ceiling of a number as an int.
This is the smallest integral value >= number.
Example:
>>> ceil(1.5)
2
Arguments:
number (float): A numeric value.
Returns:
int: Smallest integer >= number.
Raises:
TypeError: If argument ... | c0e6e8a4c25d1e9b94b51ee9da6c436c6e9d0cc4 | 638,804 |
def mangle_patch(self, url, x):
"""
Mangle the name by hashing the I{name} and appending I{x}.
@return: the mangled name.
"""
version, filename = url.rsplit('/')[-2:]
return '%s-%s-%s' % (version, filename, x) | 9aa25dbef2fcd33d4ca9525f51226670e59cea96 | 638,805 |
def calculate_betweenness(root, tree, reversed_tree, edges, path_count):
"""Recursively compute betweenness of edges for a specific tree
:param root: root node
:param tree: tree being figured out from root node
:param reversed_tree: tree from children to parent
:param edges: keep track of edges and ... | 705790c57f66a9ac15b609572a3600c8780b4b6a | 638,807 |
def _combine_field_specs(field_specs, exclude_fields):
"""
take a list of FieldSpec objects and return a sorted list where field is unique
and fields in exclude_fields are removed, and where the first mention of a
field in field_specs will win out over any repeats.
"""
combined_field_specs = {... | fa9a8f92dbe31755cecfeecad2c2813b9c6be0a7 | 638,808 |
def _get_user_project_membership(user, project, cache="user"):
"""
cache param determines how memberships are calculated trying to reuse the existing data
in cache
"""
if user.is_anonymous():
return None
if cache == "user":
return user.cached_membership_for_project(project)
... | eac2d4142d3098b5eb607160783df423a4624176 | 638,809 |
def _allowed_uri_format(rv: str) -> bool:
"""Check that a URI format doesn't have another resolver in it."""
return (
not rv.startswith("https://identifiers.org")
and not rv.startswith("http://identifiers.org")
and "n2t.net" not in rv
and "purl.bioontology.org" not in rv
) | f0ba3a167c22b44946f9e6c152987a117de8ca60 | 638,810 |
import collections
def simple_multipliers(n, simple_numbers):
"""
Каноническое разложение числа на простые множители
:param n: int
:param simple_numbers: list
:return: str
"""
if n in simple_numbers:
return n
# убираем единицу из списка
simple_numbers.pop(0)
d = simple... | f1966b8ffcb494f2550cf3d8d5fe493196fd08f5 | 638,811 |
def manage_degrees(info):
"""
Manages and interprets string values relating to degrees. Removes
degrees symbols and interprets key word flat for slope.
Args:
info: Dictionary containing potential degrees entries to be converted
to numbers
Returns:
info: Modificed dicti... | 768911a785f809e806788d0c69d8a7057a9090ef | 638,812 |
def halflife_to_phi(rho, dt=1):
"""Convert half-life to the AR(1) propagation parameter phi"""
phi = 0.5 ** (dt / rho)
# st_dev = st_dev * np.sqrt(1 - phi**2)
return phi | 9805166539ce2ca9c3f4f0ede163ab7797573497 | 638,813 |
from typing import List
from pathlib import Path
import tempfile
import subprocess
def get_system_from_user(
users: List[str],
corpus_path:Path,
spell_errors_path: Path,
smooth_type: str
) -> List[str]:
"""
Runs the spelling error correction program.
"""
with tempfile.NamedTemporaryFile(mode="w+", encodin... | b2cd5041cbaced0ee3ccb99e4b83f7b6461b3d19 | 638,814 |
from typing import Tuple
from typing import Dict
from typing import Any
import json
def parse_event(event_data: Tuple[str, Dict[str, Any]]) -> Dict[str, Any]:
"""
解析事件。
:param event_data: 事件数据。
:return:
"""
event_id = event_data[0]
event_payload = event_data[1]["data"]
return {"id": e... | bbbe97e67cef1216d93076b1a8e8b55307358811 | 638,815 |
import logging
def trace(wrapped, instance, args, kwargs):
""" work on this """
logging.getLogger('trace').info(
"%s" % (wrapped.__qualname__ if hasattr(wrapped, '__qualname__') else wrapped.__name__))
return wrapped(*args, **kwargs) | 8767fa1fdfd25ab13821e0c8513a834e87313281 | 638,816 |
import os
import glob
def get_master_project_files(directory):
"""Returns list of relative file names from the master project that should be copied to the new WP projects"""
mergin_internal_dir = os.path.join(directory, ".mergin")
config_file = os.path.join(directory, "mergin-work-packages.yml")
wp_di... | d0085eb639c9465bb77209fbd48f30c9b3081acd | 638,817 |
import inspect
def function_to_mousai(sdfunc):
"""Convert scipy.integrate functions to Mousai form.
The form of the function returning state derivatives is
`sdfunc(x, t, params)` where `x` are the current states as an `n` by `1`
array, `t` is a scalar, and `params` is a dictionary of parameters, one ... | 8c713b8be71faf460319c302b60403e0ef76372d | 638,818 |
import zipfile
import os
def unzip(file_to_unzip = None, unzip_location = None):
"""function to unzip zip file to specified location"""
if file_to_unzip is None or file_to_unzip == '':
print('[RPA][ERROR] - filename missing for unzip()')
return False
elif not os.path.isfile(file_to_unzip)... | a9f727c5a6f97b19799cd8ad8d51404a6c86bedb | 638,819 |
import os
def check_if_dir_exists(path):
"""
A bit more robust than os.path.isdir
"""
if not os.path.exists(path):
return False
if os.path.isfile(path):
print(f'{path} exists as a file')
return False
if os.path.isdir(path):
if len(os.listdir(path)) > 0:
... | 39149f45b2ec2b6961643f10700a1db6616ca138 | 638,820 |
from typing import Dict
def _parametrized_name(name: str, parameters: Dict[str, str]) -> str:
"""Generate a unique entity name that includes the parameters value.
:param name: original name
:type name: str
:param parameters: parameters applied to apply
:type parameters: dict
:return: parametr... | 72de2d71c10ef6994e261459d45517c2a050a39e | 638,821 |
import requests
import json
def product_list():
"""Request Product data from API"""
try:
print('Please see complete list of products below')
api = "https://reqres.in/api/products/"
response = requests.get(api)
parsed = json.loads(response.text)
data = json.dumps(parsed[... | 39a782ada14026c428b84607ecead57765364b7e | 638,822 |
def remove_unreadable_characters_at_start(string):
"""
Removes non ASCII characters from the string start as eggPlant files often begin with some strange symbols.
The string gets also stripped (blank characters at start and end will be removed)
:param string:
:return: the processed string
"""
... | c8b4ebc8d9c39d57937a460a8bdd38123555d2f2 | 638,823 |
import os
def join(receptor, ligands, residue, output_folder=".", output="input{}.pdb"):
"""
Join receptor and ligand PDB files into one, conserving old formatting
and not repeating atom numbers.
"""
with open(receptor, "r") as f:
lines = f.readlines()
receptor_content = [line for... | f718df7fff527a7bf30d271934477b98434be4d5 | 638,824 |
import os
def get_shapefiles_in_dir(path):
"""Finds any shapefiles in path."""
all_files = []
for dirpath, subdirs, files in os.walk(path):
for name in files:
all_files.append(os.path.join(dirpath, name))
shapefiles = [f for f in all_files if f.endswith('.shp')]
return shapefil... | a5b84bb8f183c7bfe41301bfcf454f0fc5823c23 | 638,825 |
def f_major(interesting_version, versions):
"""Filter based on the major version
Filtering on version 4 means 4.7.5 is returned while 5.2.1 is not
"""
return filter(lambda ver: ver.tup[0] == interesting_version, versions) | 97bea1df26c9a258a17ed7dbe4b18e3f4105b67f | 638,826 |
def _getLastRevision(lines):
"""Returns last revision of the PDB entry, if applicable."""
if lines['REVDAT']:
for i, line in lines['REVDAT']:
return line[13:22]
break
else:
return "No revision yet" | fc07e1500e18b8a90ed8be7e7e9884236eec5fdb | 638,827 |
def coin_total_usd(coin: str, amount: float, tickers: dict) -> float:
"""
Get value of coin in USD
:param coin: coin symbol from balance
:param amount: total amount of coin from balance
:param tickers: raw tickers fetched from binance
:return: value of coin in USD as float
"""
price_in_b... | 31ed3c6d4f5d143e294f66f9d2da3e820c0c5e47 | 638,828 |
import torch
def cross_entropy(pred, target):
"""
"Proper" cross entropy between distributions.
:param pred: predicted logits
:type pred: torch.autograd.Variable
:param target: target distributions
:type target: torch.autograd.Variable
:return: loss
:rtype: torch.autograd.Variable
... | eb566bfb94b428bceafa18c9ff5eb50177d23667 | 638,829 |
def decrypt_key(e1, modulus):
"""Works out the decryption key
Inputs - e and the modulus both integers
Outputs - The decryption key"""
d = 1 #Setting d to 1
finished = False #To check if we found a value for d
while finished != True: #We check to see if we have a v... | 34c675b22703d998a7545ef1093eee74f34689d2 | 638,830 |
def find_default_vpc(session, region_name):
"""
Looks for every default VPC in a region
:param session: Boto3 Session
:param region_name: The region name to look in
:return: list of vpc id's
"""
result = []
client = session.client("ec2", region_name)
response = client.describe_vpcs(
... | af77133ab64ec5f3f59335e085c83927c56093c2 | 638,831 |
import re
def validate(data, regex):
"""Custom Validator"""
return True if re.match(regex, data) else False | 9af429ea54b889aa308b21e5d7dcd975e097760e | 638,832 |
import math
def to_polar_coordinates(x, y):
"""Convert the 2D pixel coordinates to polar coordinates
:param x: x coordinate of the point
:param y: y coordinate of the point
:returns: tuple -- (r,phi) of the point as polar coordinates
"""
theta = math.atan2(y, x)
if theta < 0:
thet... | 7ca0596c6db352b42566db2d88580478435204b1 | 638,833 |
def run_replace(block: str, replace_dict: dict) -> str:
"""Replace routine for dealing with n-grams.
:param block: Contains the text block replacement is done on
:param replace_dict: {token: replacement_token}
:return: Occurrences of token replaced with replacement_token
"""
for k in replace_d... | cc47686d37df9dbdfcc73b2118a1305700f3c9a2 | 638,834 |
import os
import subprocess
def run_cmd(command: str):
"""run_cmd Run given shell command
Args:
command (str): Shell command to run
Returns:
(int, str): Status code, stdout of shell command
Examples:
>>> run_cmd("ls /")
(0, 'bin\nboot\ndev\netc\nhome\ninit\nlib\nlib32\n... | 44ec2b0e25d6faf0daf584d46e0dfe31a2aaad72 | 638,835 |
import requests
def get_vlans(url, headers):
"""
Get dictionary of existing VRFs
"""
vlans = []
api_url = f"{url}/api/ipam/vlans/"
response = requests.request("GET", api_url, headers=headers)
all_vlans = response.json()["results"]
for vlan in all_vlans:
vlan_info = dict()
... | c31b51b21686163188d366ce48595e6ae15a95f8 | 638,836 |
import time
def mathyTime():
"""Get time is list format, in the order of Hours, Minutes, Seconds."""
return [time.strftime('%H'), time.strftime('%M'), time.strftime('%S')] | 2d9acbca5c42e4bc0ca11c8f07d1fdd4e7add964 | 638,837 |
import argparse
def parse_params():
""" Parses parameters
"""
parser = argparse.ArgumentParser(description='SOF Binary Info Utility')
parser.add_argument('-v', '--verbose', help='increase output verbosity',
action='store_true')
parser.add_argument('--headers', help='display... | c79c31c7050f626e98ef34a83209eed6dc9e2aa2 | 638,838 |
import math
def exponential(T, prop):
""" Returns a point on an exponential function. """
return math.exp(-T) | d5c8b59a50dd20af21aab6d1d61287ccd1bc36a9 | 638,839 |
def get_class_by_name(classes_dict, class_name, default):
""" Get a class given its name.
Parameters
----------
classes_dict : dict
Dict with the form {class_name: class}
class_name : str
Class name.
default: class
Class to be used if class_name is not in classes_dict.
... | 93b985cc53b15c9b68a207831eee4caf931681c9 | 638,840 |
def parse_configuration(cfg):
"""
Parse the JSON configuration file by default in the root directory.
For simplicity, define your configuration file as the default one.
Customized file paths will require the edit of the UltraFastLaneDetection/model/model.py file
"""
# with open(conf_file, 'r') as cfg_file:
... | 502c20430881ea9470555e299095cffc8a2f3caa | 638,841 |
def _dedupe_deps(deps):
""" Deduplicate a set of string labels in a deps argument. """
if deps == None:
return deps
depindex = []
for i in deps:
if i not in depindex:
depindex.append(i)
return depindex | 01799bfee0d4a30131b1d4d5c6001b7f1087c38a | 638,842 |
def mse(df, y:str, yhats:list):
"""
Calculates Mean Squared Error.
Args:
df: pandas dataframe
y: name of column with actual data
yhats: list of column names with estimated data
Returns:
df: containing the MPE for each column
"""
columns_to_keep = yhats + [y]
... | e79bf058e5f7351f8fc7dd370e1672e1d7c002b4 | 638,844 |
import requests
import json
def get_schema():
""" This function loads the given schema available"""
url = 'https://raw.githubusercontent.com/microbiomedata/nmdc-schema/main/jsonschema/nmdc.schema.json'
resp = requests.get(url)
schema = json.loads(resp.text)
return schema | 94964bf76399855c70c1ca9435f67b39a1804bdf | 638,845 |
def to_numpy(tensor):
"""Convert Torch tensor to NumPy array.
Args:
tensor (torch.Tensor): Torch tensor.
Returns:
numpy.ndarray: Converted NumPy array.
"""
return tensor.to('cpu').detach().numpy() | 500fe33a19d771cbecd1abcc9ae1a373a8774afd | 638,846 |
import os
def IsFileNewerThanFile(file_a, file_b):
"""Returns True if file_a's mtime is newer than file_b's."""
def getmtime(f):
try:
return os.path.getmtime(f)
except os.error:
return 0
return getmtime(file_a) >= getmtime(file_b) | 369f5167a12c25f5346890ce0a524c80a3e92f1d | 638,847 |
def degree_to_order(degree):
"""Compute the order given the degree of a B-spline."""
return int(degree) + 1 | c5e7229e350e810fe75c7697ebbb2ac2f90fd765 | 638,848 |
import os
def load_songs(dir_path):
"""Loads a list of songs and their lyrics from text files into a dictionary given folder path.
Returns list of dictionaries.
"""
song_file = os.path.join(dir_path, 'songs.csv')
first_line = True
keys = []
songs = []
with open(song_file) as f:
... | 90808868aa5dda9b9a6abb274c2f9c58b0be2149 | 638,849 |
def potential_fields(rules_dict: dict, number: int) -> set:
"""Check number against each field and return set of valid ones."""
valid_fields = set()
for field, range_tuples in rules_dict.items():
for num_range in range_tuples:
lower, upper = num_range
if number >= lower and n... | f38d671c7725fda1108047454a3d3b441e1e625a | 638,850 |
import types
def copy_function(function, module=None, name=None):
"""
Copy a function and optionally change its name and module definition
"""
name = name if name else function.__name__
module = module if module else function.__module__
new_function = types.FunctionType(
function.__co... | 5cb87aa9fbb08915c4565d4b68c9cbb77cd25b99 | 638,851 |
import requests
import imghdr
def is_image(url) -> bool:
"""
Determine if it is an image of png or jpeg.
Parameters
----------
url : str
Target url.
Returns
-------
True or False: Return True if this url content is an image of png or jpeg else returns False.
"""
img = r... | 4ad67187d09ac1d79d8d030d0120f3f06cd492b3 | 638,852 |
def slope_intercept_form(m, x, b):
"""
Handles the formula used for y=mx+b format to find slope
"""
m = float(m)
x = float(x)
b = float(b)
return m * x + b | 2f91902fb2eecf01e83e8c3c3331de01b776f2d3 | 638,853 |
def tail(_b, _x):
"""Determine the number of trailing b's in vector x.
Parameters
----------
b: int
Integer for counting at tail of vector.
x: array
Vector of integers.
Returns
-------
tail: int
Number of trailing b's in x.
"""
# Initialize counter
... | 0832caec0ace94c85d965ce9a2b6817cb77ad851 | 638,854 |
def run_experiment(n, m, start=1, testing=False):
"""
Run the "Mortal_Fibonacci_rabbits" algorithm,
taking as inputs a value for:
n (int; number of months to run for)
m (int; maximum life span of rabbits)
start (int; number of rabbit pairs to start with;
optional, default = 1)
te... | af637462da5e30f51c34b606ef2f8ce54406a568 | 638,855 |
from io import StringIO
def remove_updater_creator_from_manifest(manifest: str) -> str:
"""删除manifest中的添加的平台注入的updater和creator
:param manifest: 资源的yaml内容
:return: 返回移除updater和creator后的内容
"""
stream = StringIO(manifest)
refine_stream = StringIO()
for l in stream.readlines():
if ("i... | 3909d3bd28c98246e32634ae38ff62ce0c55cfab | 638,856 |
def release_save(lock):
"""Release a lock and return its state."""
if hasattr(lock, '_release_save'):
return lock._release_save()
elif hasattr(lock, 'release'):
lock.release()
else:
raise TypeError('expecting Lock/RLock') | 82fe63d7ebef695e9df91168a2e8191cd753e3bf | 638,857 |
def _api_result_to_frame(api_result):
"""Convert API result into dataframe"""
ordered_columns = [c['key'] for c in api_result['metadata']]
# Create the dataframe
return api_result['data']
df = pd.DataFrame(api_result['data'])
existence_filtered_columns = [c for c in ordered_columns if c in ... | d67d1d915818e391829dceeb03b37af81226e27f | 638,858 |
def bubble_sort(list_object):
"""as the name implies list_object: is a list object"""
swap = False
while not swap:
swap = True
for index in range(1, len(list_object)):
if list_object[index-1] > list_object[index]:
swap = False
list_object[index], l... | 6275e163064b8d90936d17453338599b590ebd53 | 638,859 |
def getSim(w1, w2):
"""
:param w1: winner cell which should be a list
:param w2:
:return: simularity score
"""
w1 = set(w1)
w2 = set(w2)
return len(w1 & w2) / len(w1 | w2) | 8772e616caeb4d817060cd756770f6db52cb6b1b | 638,860 |
from typing import Any
from typing import Union
def to_number(s: Any) -> Union[int, float]:
"""Cast the string representation of the given object to a number (int or float), or raise ValueError."""
try:
return int(str(s))
except ValueError:
return float(str(s)) | de5261dbcd05f214f4f8fae40842f8a378d07d4e | 638,861 |
def longest_range(index_list):
"""
select longest index range
eg. [1, 0, 1, 1, 1] ==> (2, 5)
@param index_list: list, element is 0 or 1
@return: a tuple (a, b). a is the range begin, and b is the range off end.
"""
range_list = []
begin = 0
for i in range(len(index_list) - 1):
... | 6d9847a3fe8dfcc73b13dc1460cf4fe699c8ed5a | 638,862 |
def openreadlines(filename, xform=None):
"""Open a file and return a list of all its lines.
xform -- a function to run on all lines"""
with open(filename, "r", encoding="utf-8") as infp:
return [xform(x) if xform else x for x in infp] | 2042d190d1c0606e310ec5f602c90f8e095a0d44 | 638,863 |
import numpy as np
def remove_silent_frames(xl, xr, yl, yr, dyn_range, framelen, hop):
"""
Remove silent frames of x and y based on x
A frame is excluded if its energy is lower than max(energy) - dyn_range
The frame exclusion is based solely on x, the clean speech signal
Based on mpariente/pystoi... | d047eae002e4062b87fa122523675d3d320d1eae | 638,864 |
import os
def option(path, default=None, vtype=str):
"""Fetch a configurable value in the environment"""
path = path.replace(".", "_").upper()
full = f"SEEDPROJECT_{path}"
value = vtype(os.environ.get(full, default))
return value | bda8e2e9f1a4834c1eeb9c23e7c323726a8ca42a | 638,865 |
import numpy
def get_grid_spacing(cube):
"""Return an array of grid spacings."""
if not cube.coord('latitude').has_bounds():
cube.coord('latitude').guess_bounds()
spacing = [numpy.diff(bounds)[0] for bounds in cube.coord('latitude').bounds]
return numpy.array(spacing) | ce9d4c9fe6049afb9990e7155e21f4ad881e1e1c | 638,866 |
def set_dict_values(d, value):
"""
Return dict with same keys as `d` and all values equal to `value'.
"""
return dict.fromkeys(d, value) | 6b52c95759ffd5b9286d96bbc3410b4df5534313 | 638,867 |
def check_http_code_in_output(http_code, error_message=None):
"""Create a callable to ensure that the given HTTP error code is present in the
output of the response.
Args:
http_code (int): the HTTP error code to check.
error_message (str, optional): the message that will be displayed if the... | cca1800b025d069096152cd494bcdd6cf6e92c5a | 638,868 |
import os
import tempfile
def create_temporary_file(in_file, ext):
"""Creates a temporary file of type 'ext' in the same
directory as the input argument."""
dir_name = os.path.dirname(in_file)
suf = ".{}".format(ext)
file_desc, tmp_file = tempfile.mkstemp(suffix=suf, dir=dir_name)
os.close(fil... | b3250c1ecc76310ac19b1691b187bfce044d3470 | 638,870 |
import torch
def apply_tform(tform, verts):
"""
Applies a 4x4 rigid transform to a list of points
:param tform: tensor (batch, 4, 4)
:param verts: tensor (batch, N, 3)
:return:
"""
verts_homo = torch.cat((verts, torch.ones(verts.shape[0], verts.shape[1], 1, device=verts.device)), 2)
ne... | 7a75d44e9a19165acbb370eea49a22e5d00bf42d | 638,872 |
def get_the_key(t):
"""
get the key by calculte how many number it shift from letter e possiton
"""
number = int(t[0])
key = number - 5
return key | f05ac5337af70067135aad378818afc07109da05 | 638,873 |
def query_url(namespace, cls_version,
extension=''):
"""
"""
url = 'https://kg.humanbrainproject.org/query/%s/%s/fg' %\
(namespace.lower(), cls_version)
return url+extension | fe749543bec16d1582f0e39f16407d60e80b0fa6 | 638,874 |
def _should_ignore(class_reference, property_name):
"""Check if a property should be ignored."""
if not hasattr(class_reference, "__deserialize_ignore_map__"):
return False
return class_reference.__deserialize_ignore_map__.get(property_name, False) | 91868a403427779da1f803ae08e273f04e30f8e4 | 638,875 |
def checkstyle_source_to_error_type(source):
"""Convert a checkstyle error source to an error type
"""
class_name = source.split('.')[-1]
if class_name.endswith('Check'):
type = class_name[:-len('Check')]
else:
type = class_name
return type | 8a9e5502613a665efa3cefa84c7fc5fd3342cb46 | 638,876 |
def calculate_nfmap(train_toks, encoding):
"""
Construct a map that can be used to compress ``nf`` (which is
typically sparse).
*nf(feature_vector)* is the sum of the feature values for
*feature_vector*.
This represents the number of features that are active for a
given labeled text. This... | 7429c1c2150943a451e9008c98fd9409f1f77c4a | 638,877 |
def sum2(a,b):
"""
:param a: (float) Primer variable a sumar
:param b: (float) Segunda varaible a sumar
:return c: (float) c=a+b
"""
c = a + b
return c | 1e307125527ee04e8af06295171c60cf82d2a7d0 | 638,878 |
import logging
def transform_description(description, path_prefix):
"""
This function replaces the script paths with script contents.
:param description:
:return:
"""
logging.getLogger("root").info("Transforming application description")
groups = description['groups']
for g in groups:... | f68c7e4d568ff04ef45bd912a27f9bb4b8f6d4f0 | 638,879 |
def IoU(str1,str2):
"""
交并比,将字符串转化为字符集合进行计算
"""
set1=set(str1)
set2=set(str2)
ul=len(set1.union(set2))
if ul==0:
return 0.0
return len(set1.intersection(set2))/ul | f2e23dd4c4cc32fedbc06c93ce9ef20bec1e6a1c | 638,880 |
from typing import List
import os
import logging
def read_seed(seed_dir: str, seed_file_name: str) -> List[str]:
"""读取种子
Args:
seed_dir: 种子文件所在文件夹
seed_file_name: 种子文件名
Returns:
种子 url 列表。
Raise: FileNotFoundError
"""
# 拼接种子文件实际完整路径
seed_file_path = os.path.join... | 5434f5a7eacc33985841a0f2e3001adda065dc83 | 638,881 |
def set_config_defaults(config):
"""Add defaults so the site works"""
new_config = config.copy()
new_config.setdefault("window_title", "Materials Cloud Tool")
new_config.setdefault(
"page_title",
"<PLEASE SPECIFY A PAGE_TITLE AND A WINDOW_TITLE IN THE CONFIG FILE>",
)
new_confi... | 222b079c6fbb5e53541570a924d739351a822ddc | 638,882 |
import argparse
def cli_parser():
"""
Parse command line arguments
:return: argparse
"""
parser = argparse.ArgumentParser(
description="Distributed Fast Fourier Transform",
fromfile_prefix_chars="@",
)
parser.add_argument(
"--swift_config",
type=str,
... | 3f4de8935b11cf1f054418dbe7b1d86267e1b97b | 638,883 |
def mpad(msg, size):
"""Pad a byte string to multiple of size bytes. """
amount = size - len(msg) % size
return msg + b'\0' * amount | 48f01ceccf7132fa8f8fbf5c52b0ddc8f3fec61d | 638,884 |
def convertir_a_grises(imagen: list) -> list:
""" Escala de Grises (Matriz de Tuplas)
Parámetros:
imagen (list): Matriz que representa la imagen
Retorno:
list: Matriz que representa la imagen convertida a grises
"""
alto = len(imagen)
ancho = len(imagen[0])
for i in range(alto):
... | a2113b1b6c41ef37d80817d77d204f586381fd39 | 638,885 |
import requests
def getJsons(game_number,
codes,
api_version = "0.1",
url = "https://np.ironhelmet.com/api"):
"""
Returns a list of values collected via the API
:param str game_number: Number of the game you wish to visualize data from
:param list co... | 142a789b7578ef9ede98b70ea8dddec67afc0b66 | 638,886 |
def add_gender(file_info,speaker_gender_df):
"""
Adds a gender entry to the dictionary of file information
"""
gender = speaker_gender_df[speaker_gender_df['Speaker']==file_info['speaker']]['Gender'].values[0]
new_info = dict(file_info)
new_info['gender']=gender
return new_info | 886bbc43ceace327cbc395dd70a73bc86dbd9370 | 638,887 |
def move_color_add(style):
"""
Makes color lighter or darker
based on a style.
"""
return {'o': 0, 'x': 80, '*': -80, '^': 120}[style] | 959e64a86b92d97a5d23e960dc917000967af073 | 638,888 |
def get_end_linenumber(text):
"""Utility to get the last line's number in a Tk text widget."""
return int(float(text.index('end-1c'))) | 8768a6ce777087ee1730b41efd9a41180672c33b | 638,889 |
import re
def _strip_time(desc):
"""Strips time from play description."""
return re.sub('^\([^)]+\)', '', desc).strip() | 2c7ca2d8c2ddffe2f741123946fc7cc659e1447b | 638,890 |
def find_digit_sum(num):
"""Return the sum of digits in num."""
num = str(num)
digit_sum = 0
for char in num:
digit_sum += int(char)
return digit_sum | aeaaae9beec3f25c5fc697583dfe9575602a7574 | 638,891 |
def rgb2gray(rgb,biases = [1/3,1/3,1/3]):
"""
Calculate gray image value from RGB value. May include bias values to correct for luminance differences in layers.
Parameters
----------
rgb : TYPE
DESCRIPTION.
biases : TYPE, optional
DESCRIPTION. The default is [1/3,1/3,1/3].
... | f182d48a45a154c3220877edb9342ca9142eaaae | 638,892 |
import math
def zoom_number(minimum_tile_size, border_size):
"""Return the number of zooms"""
num = math.log(border_size / minimum_tile_size) / math.log(2)
return num | 1f75e4fc0f1539d94fd96f6e055e0dbb0021d2a9 | 638,893 |
import csv
def get_metabolites(input_file):
"""
Get the metabolite contained in the input file in CSV format
Input file must be in the same folder as the script.
The file name must be a string including .csv extension.
--------------------------------------------------------
Argument:
in... | 6a8b6d12130f00529cdb07b09c95392cd8c71a29 | 638,894 |
import _operator
def _basic_math_operation(df, new_column, column_1, column_2, op):
"""
Basic mathematical operation to apply operator on `column_1` and `column_2`
Both can be either a number or the name of a column of `df`
Will create a new column named `new_column`
"""
if not isinstance(colu... | de20b508a39fd18bf5cf1b8d37eefe3814c1ef18 | 638,895 |
def _makeFunctionStatement(function_name, inputs):
"""
:param function_name: string name of the function to be created
:param inputs: list of column names that are input to the function
:return: statements
"""
statement = "def %s(" % function_name
statement += ", ".join(inputs)
statement += "):"
retur... | ca3e184ad1ba0fee499e3afea68e88900fe58e96 | 638,896 |
import re
def load_help(txtfile):
"""
Returns a list of strings split with ': '
"""
with open(txtfile, 'r') as f:
s = f.read()
s = re.sub('\n',': ', s)
li = s.split(': ')
return li | 4451d07e685eb95e51ff4be9197b6e0a1fc38527 | 638,897 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.