content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import tempfile
def representative_sample(X, num_samples, save=False):
"""Sample vectors in X, prefering edge cases and vectors farthest from other vectors in sample set
"""
X = X.values if hasattr(X, 'values') else np.array(X)
N, M = X.shape
rownums = np.arange(N)
np.random.shuffle(rownums)... | e5352bbc31257eda3b5cfc24dbfba41fdcc84c7a | 26,900 |
import os
import logging
def _heal(batch):
"""Heal whisper files.
This method will backfill data present in files in the
staging dir if not present in the local files for
points between 'start' and 'stop' (unix timestamps).
"""
for metric in batch.metrics_fs:
src = os.path.join(batch.... | 244c1cd8244e6d325c1d9fd099379c88b0cc7619 | 26,901 |
def fix_saving_name(name):
"""Neutralizes backslashes in Arch-Vile frame names"""
return name.rstrip('\0').replace('\\', '`') | ba7063766f3397b955a427b4304605fa2add48fb | 26,902 |
from typing import OrderedDict
def read_dataset_genomes(dataset):
"""Read genomes of the given dataset.
Args:
dataset: instance of datasets.GenomesDataset
Returns:
list of genome.Genome
"""
genomes = []
if dataset.is_multi_chr():
# The genomes in this dataset have mo... | ad7b3d8991084da3152f60c065af508aa2a75bb8 | 26,903 |
import os
import re
def _parse_sum_ouput(exit_code):
"""Parse the SUM output log file.
This method parses through the SUM log file in the
default location to return the SUM update status. Sample return
string:
"Summary: The installation of the component failed. Status of updated
components:... | 5dbaf7489efbb872b221b2c669c91c9e202fb440 | 26,904 |
def compute_metrics(logits, labels, lengths):
"""Computes metrics and returns them."""
loss = cross_entropy_loss(logits, labels, lengths)
# Computes sequence accuracy, which is the same as the accuracy during
# inference, since teacher forcing is irrelevant when all output are correct.
token_accuracy = jnp.ar... | 2fa08ad9c06e5860f4cb57ca891087b7d67e7806 | 26,905 |
def replace_prelu(input_graph_def: util.GraphDef) -> util.GraphDef:
"""
Replace all Prelu-activations in the graph with supported TF-operations.
Args:
input_graph_def: TF graph definition to examine
Returns:
Updated copy of the input graph with Prelu-nodes replaced by supported
... | 694d84f2661261a320a3d9cee360dd5980bb3a9d | 26,906 |
def tf_parse_filename_classes(filename, normalization='None', normalization_factor=1, augmentation=False):
"""Take batch of filenames and create point cloud and label"""
idx_lookup = {'airplane': 0, 'bathtub': 1, 'bed': 2, 'bench': 3, 'bookshelf': 4,
'bottle': 5, 'bowl': 6, 'car': 7, 'chair':... | 75cc87faa46f25485e2c097c5243f0a44bda1554 | 26,907 |
def next_traj_points(dimension: int, last_point):
"""
:param dimension: dimension of our fake latent trajectory
:param last_point: the last point that was sent to the client as a numpy array
:return: here we are sending 3 points at a time from a noisy Lorenz system
"""
#Euler step size
step... | 6e33833b877cc8bc218d8c0a74357c6b4d8d2a9b | 26,908 |
from six.moves import urllib
def has_internet():
"""
Test if Internet is available.
Failure of connecting to the site "http://www.sagemath.org" within a second
is regarded as internet being not available.
EXAMPLES::
sage: from sage.doctest.external import has_internet
sage: has_... | d9cacc17a315abe85022e9a889d4a1da3c9b6a49 | 26,909 |
def read_warfle_text(path: str) -> str:
"""Returns text from *.warfle files"""
try:
with open(path, "r") as text:
return text.read()
except Exception as e:
raise Exception(e) | ba15fe6a62fbefe492054b0899dcdbff35462154 | 26,910 |
from typing import List
from typing import OrderedDict
def from_mido(midi: MidiFile, duplicate_note_mode: str = "fifo") -> Music:
"""Return a mido MidiFile object as a Music object.
Parameters
----------
midi : :class:`mido.MidiFile`
Mido MidiFile object to convert.
duplicate_note_mode : ... | 795b13dcba41a7c10270e6cd799ef439a0ceb426 | 26,911 |
def iterable_validator(iterable_type, member_type):
# type: (ISINSTANCE, ISINSTANCE) -> Callable[[object, Attribute, Iterable[Any]], None]
"""``attrs`` validator to perform deep type checking of iterables."""
def _validate_iterable(instance, attribute, value):
# type: (object, Attribute, Iterable[A... | 708738c7bc55e4bb4c4fa9ae93cf56ddb038ebda | 26,912 |
def sample_filtering(df, metadata, filter_by):
"""Filter samples based on selected features and values."""
# Get the variable a values specified for sample filtering
filter_col = filter_by[0]
filter_values = filter_by[1].split(sep=',')
# Saving a new metadata file containing only the samples remai... | 437391b946ed61817292c160402b1c6e0b81fa94 | 26,913 |
def blog_post_historia(request, slug,template="blog/blog_post_historia.html"):
"""Display a list of contenidos that are filtered by slug,
"""
templates = []
#listamos todos los pacientes..
pacientes = BlogPost.objects.published(for_user=request.user)
paciente = get_object_or_404(pacientes, title... | 125a612afdaefe8dff494655ae5d53df1d125072 | 26,914 |
def user_is_registered_or_more(user_id):
"""Check that user is registered, moderator, or admin."""
user = Users.query.filter_by(UserID=user_id).first()
user_map = UsersAccessMapping.query.filter_by(UserID=user_id).first()
if user is None:
return False
if user_map is None:
return Fals... | a405ee98673ffa87f260519ec8fc9ff88efa2089 | 26,915 |
import os
def avi_common_argument_spec():
"""
Returns common arguments for all Avi modules
:return: dict
"""
return dict(
controller=dict(default=os.environ.get('AVI_CONTROLLER', '')),
username=dict(default=os.environ.get('AVI_USERNAME', '')),
password=dict(default=os.envir... | 5bed3408a2f843053271656d98f5919feaee4b02 | 26,916 |
from typing import Union
from typing import Sequence
from typing import Optional
from typing import Type
def run(
cmds: Union[str, Sequence[Union[str, Sequence[str]]]],
shell: Optional[Union[str, bool]] = None,
mode: Type[Mode] = str,
block: bool = True,
**kwargs
) -> Processes:
"""
Runs s... | 370f4867701fcda0683030749e0a9754bf2b518e | 26,917 |
def _infer_labels(center_e):
"""Create labels based on center extrema."""
# Infer labels
if center_e == 'trough':
labels = ['Trough', 'Peak', 'Inflection']
keys = ['sample_trough', 'sample_next_peak', 'sample_end']
elif center_e == 'peak':
labels = ['Peak', 'Trough', 'Inflection... | 854a6bbe1c45a806d3c6ecd15bee11f3ec9496a4 | 26,918 |
def MXXXtoMYYY(redshift = 0.3,
MXXX = 6E14,
CXXX = 3.0,
wrt = "crit",
new_wrt = "crit",
XXX = 500.0,
YYY = 500.0,
cosmo = cosmo):
"""
It converts the (MXXX,CXXX) in... | f6c7e628ce79785c9d28939e6e3de8fe3ed3878a | 26,919 |
import html
def gldas_to_cycles(
latitude,
longitude,
output_file,
start_date="2000-01-01",
end_date="2017-12-31",
gldas_path="/raw-data/GLDAS",
):
"""Transform GLDAS to Cycles."""
j = Job("gldas_to_cycles")
j.addProfile(Profile(Namespace.CONDOR, key="+SingularityImage", value=html... | 1ce787266d5b232f0b8c76d639328a0dc4384e2f | 26,920 |
def max_pool_2x2(x):
"""max_pool_2x2 downsamples a feature map by 2X."""
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='VALID') | 45141be3715fd821c8712bc81c644498871d7b8c | 26,921 |
import os
def get_largest_files_new(directory: str, num: int) -> list:
"""
Return a sorted list containing up to num of the largest files from the directory.
Preconditions:
- num > 0
"""
# ACCUMULATOR: Priority queue so far
list_so_far = []
for root in os.walk(directory):
p... | a9966a03166d1102cc2567fbb5bc19f336893b35 | 26,922 |
def set_bit_value(val, offs, value):
"""Set bit at offset 'offs' to a specific value in 'val'."""
if value:
return set_bit(val, offs)
else:
return clear_bit(val, offs) | 793165cc53adc140b60521b6fc772efa80b69ebb | 26,923 |
def gradientFunction(theta, X, y):
"""
Compute cost and gradient for logistic regression with regularization
computes the cost of using theta as the parameter for regularized logistic
regression and the gradient of the cost w.r.t. to the parameters.
"""
# Initialize some useful values
# n... | 5ca8c355474c9cab10b2b255b71b943b2b6b0aa1 | 26,924 |
def splice(tree, rep, tag):
"""Splice in a tree into another tree.
Walk ``tree``, replacing the first occurrence of a ``Name(id=tag)`` with
the tree ``rep``.
This is convenient for first building a skeleton with a marker such as
``q[name["_here_"]]``, and then splicing in ``rep`` later. See ``fora... | b42c5300b7ad9d5d04ba0233c94c735686e1300a | 26,925 |
def get_devp2p_cmd_id(msg: bytes) -> int:
"""Return the cmd_id for the given devp2p msg.
The cmd_id, also known as the payload type, is always the first entry of the RLP, interpreted
as an integer.
"""
return rlp.decode(msg[:1], sedes=rlp.sedes.big_endian_int) | bd930be7205871183ac9cb4814ae793f5524964d | 26,926 |
def custom_cached(name, *old_method, **options):
"""
decorator to convert a method or function into a lazy one.
note that this cache type supports expire time and will consider method inputs
in caching. the result will be calculated once and then it will be cached.
each result will be cached using ... | a6732fee6cd484068d3171079bf4989d5367adbc | 26,927 |
def _full_url(url):
"""
Assemble the full url
for a url.
"""
url = url.strip()
for x in ['http', 'https']:
if url.startswith('%s://' % x):
return url
return 'http://%s' % url | cfb56cf98d3c1dd5ee2b58f53a7792e927c1823f | 26,928 |
from rx.core.operators.replay import _replay
from typing import Optional
import typing
from typing import Callable
from typing import Union
def replay(mapper: Optional[Mapper] = None,
buffer_size: Optional[int] = None,
window: Optional[typing.RelativeTime] = None,
scheduler: Optional[... | 8a5ff1cbbc5c12d63e0773f86d02550bf5be65c4 | 26,929 |
import io
import torch
def read_from_mc(path: str, flush=False) -> object:
"""
Overview:
read file from memcache, file must be saved by `torch.save()`
Arguments:
- path (:obj:`str`): file path in local system
Returns:
- (:obj`data`): deserialized data
"""
global mclient... | c606b131ba3d65c6b3dd320ae6a71983a79420c8 | 26,930 |
import wave
import struct
def write_wav(file, samples, nframes=-1, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048):
"""
Writes the samples to a wav file.
:param file: can be a filename, or a file object.
:param samples: the samples
:param nframes: the number of frames
:param nchannels... | ec38069d59dde8dafd5aa98a826ee699ded15b29 | 26,931 |
async def check_login(self) -> dict:
"""Check loging and return user credentials."""
session = await get_session(self.request)
loggedin = UserAdapter().isloggedin(session)
if not loggedin:
informasjon = "Logg inn for å se denne siden"
return web.HTTPSeeOther(location=f"/login?informasjon... | 48dd910c143e4ca8f90d8d3da2be2ce6ed275b1b | 26,932 |
from typing import Callable
def get_knn_func_data_points(
data_points: np.ndarray,
pairwise_distances: np.ndarray = None,
approx_nn: ApproxNN = None,
metric: Callable = fastdist.euclidean,
metric_name: str = "euclidean",
) -> KnnFunc:
"""
Gets a K-nearest neighbour callable for data points... | 897289271aef24610dc949fefd14761a3bea4322 | 26,933 |
from aiida import orm
def get_database_nodecount():
"""Description pending"""
query = orm.QueryBuilder()
query.append(orm.Node)
return query.count() | dcb71a022d36c2602125cbba4dccd1c7ccb16281 | 26,934 |
def shower_profile(xdat, alpha, beta, x0):
"""Function that represents the shower profile.
Takes in the event and predicts total gamma energy using alpha and beta to fit.
Described in source in README.
shower_optimize() fits for alpha and beta.
"""
#measured_energy = event.measured_energy
#... | 99c94604a742ffd44e21b4c5cd2061f6293a4d72 | 26,935 |
def has_prefix(s, sub_index):
"""
This function can make sure that the current string(recorded in index) is in the dictionary.
(or it will return False and stop finding.
:param s: string, the user input word
:param sub_index: list, current list (recorded in the index type)
:return: (bool) If the... | a33ce5d13b473f264636bfb430d0191450103020 | 26,936 |
def get_experiment_tag(name):
"""Interfaces to callables that add a tag to the matplotlib axis.
This is a light-weight approach to a watermarking of a plot in a way
that is common in particle physics experiments and groups.
`name` can be an identifier for one of the styles provided here.
Alternativ... | 9dc11a6caac2010aa99e288897a6f60273d1a372 | 26,937 |
def _add_layer1(query, original_data):
"""Add data from successful layer1 MIB query to original data provided.
Args:
query: MIB query object
original_data: Two keyed dict of data
Returns:
new_data: Aggregated data
"""
# Process query
result = query.layer1()
new_dat... | ab2d3ad95435dd2fcc6b99745f115cab08aa6699 | 26,938 |
def encodeUcs2(text):
""" UCS2 text encoding algorithm
Encodes the specified text string into UCS2-encoded bytes.
@param text: the text string to encode
@return: A bytearray containing the string encoded in UCS2 encoding
@rtype: bytearray
"""
result = bytearray()
for b in ... | da2243ffc959db64a196a312522f967dce1da9d1 | 26,939 |
def w_kvtype(stype: str, ctx: dict) -> dict:
"""
Make definition from ktype or vtype option
"""
stypes = {'Boolean': 'boolean', 'Integer': 'integer', 'Number': 'number', 'String': 'string'}
if stype in stypes:
return {'type': stypes[stype]}
if stype[0] in (OPTION_ID['enum'], OPTION_ID['p... | e09bc0ceaed2edc2927ddbc4b6bc38bcec5a345d | 26,940 |
from typing import Optional
def create_article_number_sequence(
shop_id: ShopID, prefix: str, *, value: Optional[int] = None
) -> ArticleNumberSequence:
"""Create an article number sequence."""
sequence = DbArticleNumberSequence(shop_id, prefix, value=value)
db.session.add(sequence)
try:
... | 3be2f0399fee0c01a117ffef0f790bae80750db0 | 26,941 |
import sys
import bz2
def queryMultifield(queryWords, listOfFields, pathOfFolder, fVocabulary):
"""
Multifield query:
"""
fileList = defaultdict(dict)
df = {}
for i in range(len(queryWords)):
word, key = queryWords[i], listOfFields[i]
returnedList, mid= findFileNumber(0, le... | 4062ce462f6155f86a741db15cf3e63490532f30 | 26,942 |
import scanpy as sc
def csv_to_im(
image_in,
csv_path,
labelkey='label',
key='dapi',
name='',
maxlabel=0,
normalize=False,
scale_uint16=False,
replace_nan=False,
channel=-1,
outpath='',
):
"""Write segment backprojection."""
if isinstance(image_in, Image):
... | c89e3d0c9ffa9b04b23c905148d45790ea782371 | 26,943 |
import vtk
def get_defaults(vtkName, debug=False):
"""Get default values for VTK Set methods
Example:
--------
>>> print(get_defaults("vtkSphere"))
>>> # {'SetCenter': (0.0, 0.0, 0.0), 'SetRadius': 0.5}
"""
t = getattr(vtk, vtkName)()
ignores = [
'SetAbortExecute',
... | 5fbdad8c93138e9c1f03d3bdca40b85a52808e18 | 26,944 |
import math
def transform_side(side,theta):
"""Transform the coordinates of the side onto the perpendicular plane using Euler-Rodrigues formula
Input: side coordinates, plane
Output: new coordinates
"""
new_side = list()
#calculating axis of rotation
axis = side[len(side)-1][0]-side[0][0],0,0
#converting th... | 41e71676ee138cc355ae3990e74aeae6176d4f94 | 26,945 |
def get_approved_listings():
"""
Gets pending listings for a user
:param user_id
:return:
"""
user_id = request.args.get('user_id')
approved_listings = []
if user_id:
approved_listings = Listing.query.filter_by(approved=True, created_by=user_id)
else:
approved_listin... | 1d20094c8b3ca10a23a49aa6c83020ae3cdf65e3 | 26,946 |
def edit_profile(request):
"""
编辑公司信息
:param request:
:return:
"""
user_id = request.session.get("user_id")
email = request.session.get("email")
# username = request.session.get("username")
if request.session.get("is_superuser"):
# 管理员获取全部公司信息
data = models.I... | f106b3f6f35497bf5db0a71b81b520ac023c2b37 | 26,947 |
from typing import Optional
def get_vault(vault_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVaultResult:
"""
This data source provides details about a specific Vault resource in Oracle Cloud Infrastructure Kms service.
Gets the specified vault's con... | 586bc794d066cd3e4040aff04a39a81762016c41 | 26,948 |
import os
def build_docker_build_command(configuration):
"""
Translate a declarative docker `configuration` to a `docker build` command.
Parameters
----------
configuration : dict
configuration
Returns
-------
args : list
sequence of command line arguments to build an... | 89869a37a07694270df5e0eebd0ff80f95e6e949 | 26,949 |
def _make_dist_mat_sa_utils():
"""Generate a sample distance matrix to test spatial_analysis_utils
Returns:
xarray.DataArray:
a sample distance matrix to use for testing spatial_analysis_utils
"""
dist_mat = np.zeros((10, 10))
np.fill_diagonal(dist_mat, 0)
# Create distanc... | 706ce73e1a5e66cdf521df7d0e1bf2c43bd09d02 | 26,950 |
def _workSE(args):
"""Worker function for batch source extraction."""
imageKey, imagePath, weightPath, weightType, psfPath, configs, \
checkImages, catPostfix, workDir, defaultsPath = args
catalogName = "_".join((str(imageKey), catPostfix))
se = SourceExtractor(imagePath, catalogName, weigh... | be98194a91108268bb7873fb275416a394aee3c1 | 26,951 |
def split_match(date,time,station):
"""
Function to find and extract the measuremnt from Jack Walpoles splititng data for the same event.
This matching is done by finding an entry with the same date stamp. Inital testing has shown this to be a unique identifier.
station MUST be a string of a station cod... | b1a7a1b4265719c8d79274169593754a7f683bc2 | 26,952 |
import numpy
def schoolf_eq(temps, B0, E, E_D, T_pk):
"""Schoolfield model, used for calculating trait values at a given temperature"""
function = B0 * exp(-E * ((1/(K*temps)) - (1/(K*283.15)))) / (1 + (E/(E_D - E)) * exp((E_D / K) * (1 / T_pk - 1 / temps)))
return numpy.array(map(log,function), dtype=numpy.float6... | 67969317bee63d759071c86840e4ae9ecfb924b4 | 26,953 |
import argparse
def get_parser():
""" Builds the argument parser for the program. """
parser = argparse.ArgumentParser()
parser.add_argument('-c', type=str, dest='clf_key', default='dt', choices=['dt', 'xts', 'rf'], help='A classifier to use.')
parser.add_argument('-m', type=str, dest='mode', default=... | 6246e9105d1435715b5297afe87de15288b5f7ea | 26,954 |
from typing import Union
from typing import Type
from typing import Any
from typing import Iterable
def heat_type_of(
obj: Union[str, Type[datatype], Any, Iterable[str, Type[datatype], Any]]
) -> Type[datatype]:
"""
Returns the corresponding HeAT data type of given object, i.e. scalar, array or iterable. ... | 2637d7559bb1ff3d6a1b07d9cedd10f1eb57e564 | 26,955 |
from typing import Union
from typing import Tuple
from typing import Dict
from typing import Any
def get_field_from_acc_out_ty(
acc_out_ty_or_dict: Union[Tuple, Dict[str, Any]], field: str
):
"""
After tracing NamedTuple inputs are converted to standard tuples, so we cannot
access them by name directl... | 44b0cac3737823c6ea7aa4b924683d17184711a6 | 26,956 |
import os
import sys
def stop_gracefully(db, no_exit=False):
"""
A mechanism to stop the python process that is reading/writing to brunodb and
shutdown gracefully, i.e. close the database first. Better than a hard stop
which might corrupt the database. Particularly for when running a load
with blo... | 037a61aedfaa066d4e38b8f60991bbcaa916b77e | 26,957 |
def bhc(data,alpha,beta=None):
"""
This function does a bayesian clustering.
Alpha: Hyperparameter
Beta: Hyperparameter
If beta is not given, it uses the Multinomial-Dirichlet.
Otherwise it uses Bernoulli-Beta.
"""
n_cluster = data.shape[0]
nodekey = n_cluster
list_cluster... | a0c6cb588a66dce92a2041a02eb60b66a12422ae | 26,958 |
import logging
def get_sql_value(conn_id, sql):
"""
get_sql_value executes a sql query given proper connection parameters.
The result of the sql query should be one and only one numeric value.
"""
hook = _get_hook(conn_id)
result = hook.get_records(sql)
if len(result) > 1:
logging.... | 24cc8c633f855b5b07c602d247a543268972d615 | 26,959 |
def get_rendered_config(path: str) -> str:
"""Return a config as a string with placeholders replaced by values of the corresponding
environment variables."""
with open(path) as f:
txt = f.read()
matches = pattern.findall(txt)
for match in matches:
txt = txt.replace("[" + match + "]",... | 93445db04960fd66cc88673f397eb959d2e982ec | 26,960 |
def units_to_msec(units, resolution):
"""Convert BLE specific units to milliseconds."""
time_ms = units * float(resolution) / 1000
return time_ms | 49588d7961593b2ba2e57e1481d6e1430b4a3671 | 26,961 |
def IR(numOfLayer, useIntraGCN, useInterGCN, useRandomMatrix, useAllOneMatrix, useCov, useCluster, class_num):
"""Constructs a ir-18/ir-50 model."""
model = Backbone(numOfLayer, useIntraGCN, useInterGCN, useRandomMatrix, useAllOneMatrix, useCov, useCluster, class_num)
return model | dbe638d3cd38c66387c67e0854b07ea7f800909f | 26,962 |
import re
def extractNextPageToken(resultString):
"""
Calling GASearchVariantsResponse.fromJsonString() can be slower
than doing the variant search in the first place; instead we use
a regexp to extract the next page token.
"""
m = re.search('(?<=nextPageToken": )(?:")?([0-9]*?:[0-9]*)|null',
... | 151a5697561b687aeff8af51c4ec2f73d47c441d | 26,963 |
def underscore(msg):
""" return underlined msg """
return __apply_style(__format['underscore'],msg) | ded741e58d1f6e46fc4b9f56d57947903a8a2587 | 26,964 |
def get_slice(dimspins, y):
"""
Get slice of variable `y` inquiring the spinboxes `dimspins`.
Parameters
----------
dimspins : list
List of tk.Spinbox widgets of dimensions
y : ndarray or netCDF4._netCDF4.Variable
Input array or netcdf variable
Returns
-------
ndarr... | 3545391babb06c7cae5dc8fc6f413d34e40da57c | 26,965 |
import requests
import json
def query_real_confs(body=None): # noqa: E501
"""
query the real configuration value in the current hostId node
query the real configuration value in the current hostId node # noqa: E501
:param body:
:type body: dict | bytes
:rtype: List[RealConfInfo]
"""
... | 1313792649942f402694713df0d413fe39b8a77c | 26,966 |
def Run(get_initial_items,
switch_to_good,
switch_to_bad,
test_script,
test_setup_script=None,
iterations=50,
prune=False,
pass_bisect=None,
ir_diff=False,
noincremental=False,
file_args=False,
verify=True,
prune_iterations=... | 65034be624fa8b1ddd6807c4dac0207c92d9710b | 26,967 |
def is_data(data):
""" Check if a packet is a data packet. """
return len(data) > 26 and ord(data[25]) == 0x08 and ord(data[26]) in [0x42, 0x62] | edb2a6b69fde42aef75923a2afbd5736d1aca660 | 26,968 |
def _bool_value(ctx, define_name, default, *, config_vars = None):
"""Looks up a define on ctx for a boolean value.
Will also report an error if the value is not a supported value.
Args:
ctx: A Starlark context. Deprecated.
define_name: The name of the define to look up.
default: The val... | c60799e3019c6acefd74115ca02b76feb9c72237 | 26,969 |
def get_tf_metric(text):
"""
Computes the tf metric
Params:
text (tuple): tuple of words
Returns:
tf_text: format: ((word1, word2, ...), (tf1, tf2, ...))
"""
counts = [text.count(word) for word in text]
max_count = max(counts)
tf = [counts[i]/max_count for i in range(0, len(counts))]
return text, tf | 6397e150fa55a056358f4b28cdf8a74abdc7fdb6 | 26,970 |
import torch
def R_transform_th(R_src, R_delta, rot_coord="CAMERA"):
"""transform R_src use R_delta.
:param R_src: matrix
:param R_delta:
:param rot_coord:
:return:
"""
if rot_coord.lower() == "model":
R_output = torch.matmul(R_src, R_delta)
elif rot_coord.lower() == "camera" ... | 67d4b94bcc9382fae93cc926246fb2436eac7173 | 26,971 |
def calculate_UMI_with_mismatch(UMIs):
"""
Corrected the mismatches in UMIs
input: UMI sequences and their counts;
return: Corrected unique UMI sequences
"""
if len(UMIs.keys()) == 1:
return [x for x in UMIs if UMIs[x]>0]
UMIs = sorted(UMIs.items(), key=lambda k: k[1], reverse=True)... | c0e24bf7043b3041043187ca78c8b8f5cafae7cc | 26,972 |
def create_import_data(properties):
"""
This function collects and creates all the asset data needed for the import process.
:param object properties: The property group that contains variables that maintain the addon's correct state.
:return list: A list of dictionaries containing the both the mesh an... | b8b28ac4a1d753214dbcd1361b1ababf7f366b55 | 26,973 |
def get_data(URL, pl_start, pl_end):
"""Generic function. Should be called only when
it is checked if the URL is a cached playlist.
Returns a tuple containing the songs and name of
the playlist.
"""
logger.debug("Extracting Playlist Contents")
cached_playlist = CachedIE(URL, pl_start, pl_en... | 73de68869e86cb4325c4574cc8ca7aff1f8b737d | 26,974 |
def _parse_vertex_tuple(s):
"""Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k'.
...).
"""
vt = [0, 0, 0]
for i, c in enumerate(s.split("/")):
if c:
vt[i] = int(c)
return tuple(vt) | 37e53236ef7a96f55aed36e929abe4472911b9ea | 26,975 |
def getKeyFromValue(dictionary, value):
"""
dictionary内に指定したvalueを持つKeyを検索して取得
"""
keys = [key for key, val in dictionary.items() if val == value]
if len(keys) > 0:
return keys[0]
return None | d2bb42938a809677f4a96e869e9e03c194a28561 | 26,976 |
def withdraw(dest):
"""
This function defines all the FlowSpec rules to be withdrawn via the iBGP Update.
////***update*** Add port-range feature similar to announce() - ADDED in TBowlby's code.
Args:
dest (str): IP Address of the Victim host.
Calls:
send_requests(messages): Calls ... | 2e0767630c72d69a914175e6bcc808d9b088b247 | 26,977 |
def get_prefix(node):
"""
Strips off the name in the URI to give the prefixlabel...
:param node: The full URI string
:return: (prefix, label) as (string, string)
"""
if '#' in node:
name = node.split("#")[-1]
else:
# there must be no # in the prefix e.g. schema.org/
n... | 5d005548da722751cdd0ae022994de5f39f9ac56 | 26,978 |
def sY(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
"""Return the Pauli sigma_Y operator acting on the given qubit"""
return Pauli.sigma(qubit, 'Y', coefficient) | 8d2444f4e9a4b9e3734a1d7ec1e686f06ded0c89 | 26,979 |
def load_data_and_labels(filename):
"""Load sentences and labels"""
df = pd.read_csv(filename, compression='zip', dtype={'faits': object}, encoding = 'utf8')
selected = [ATTRIBUTE_TO_PREDICT, 'faits']
non_selected = list(set(df.columns) - set(selected))
df = df.drop(non_selected, axis=1) # Drop non selected colum... | 651b156801dcdd5b847ab1eb3330afe569c6b63e | 26,980 |
def ovc_search(request):
"""Method to do ovc search."""
try:
results = search_master(request)
except Exception as e:
print('error with search - %s' % (str(e)))
return JsonResponse(results, content_type='application/json',
safe=False)
else:
retu... | f571627dba30a3f0a1e958e484c528fa3338defa | 26,981 |
import struct
def incdata(data, s):
"""
add 's' to each byte.
This is useful for finding the correct shift from an incorrectly shifted chunk.
"""
return b"".join(struct.pack("<B", (_ + s) & 0xFF) for _ in data) | 89633d232d655183bee7a20bd0e1c5a4a2cc7c05 | 26,982 |
from typing import Tuple
def nonsquare_hungarian_matching(
weights: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]:
"""Hungarian matching with arbitrary shape.
The matchers_ops.hungarian_matching supports only squared weight matrices.
This function generalizes the hungarian matching to nonsquare cases by paddin... | 02968da51da1d65020b544bb2467ecbe3ba4ab96 | 26,983 |
from collections import defaultdict
from json import load
from HUGS.Modules import Datasource, ObsSurface
from HUGS.Util import (get_datetime_now, get_datetime_epoch, create_daterange_str,
timestamp_tzaware, get_datapath)
def search(
locations,
species=None,
inlet=None,
instrument=None,
find_... | 793a467f4705854c6334f25b4ffa05812e9a71e3 | 26,984 |
import string
def strip_non_printable(value):
"""
Removes any non-printable characters and adds an indicator to the string
when binary characters are fonud
:param value: the value that you wish to strip
"""
if value is None:
return None
# Filter all non-printable characters
#... | 279ea769bd7d57ee3e4feb9faf10f2a3af3aa657 | 26,985 |
def flatten(name):
"""Get a flatten layer.
Parameters
----------
name : string
the name of the flatten layer
Returns
-------
flatten : keras.layers.core.Flatten
"""
if LIB_TYPE == "keras":
return Flatten(name=name) | b395162b7551d4292a89a2128b651305df294069 | 26,986 |
import math
def tangent_circle(dist, radius):
"""
return tangent angle to a circle placed at (dist, 0.0) with radius=radius
For non-existing tangent use 100 degrees.
"""
if dist >= radius:
return math.asin(radius/float(dist))
return math.radians(100) | bcde88456a267239566f22bb6ea5cf00f64fa08e | 26,987 |
import re
def find_backup_path(docsents, q, cand, k=40):
"""
If no path is found create a dummy backup path
:param docsents:
:param q:
:param cand:
:param k:
:return:
"""
path_for_cand_dict = {"he_docidx": None,
"he_locs": None,
"... | 10a71c623da6c185a1e1cc1242b2e0402208837c | 26,988 |
def state_transitions():
"""Simplified state transition dictionary"""
return {
"E": {"A": {"(0, 9)": 1}},
"A": {"I": {"(0, 9)": 1}},
"I": {"H": {"(0, 9)": 1}},
"H": {"R": {"(0, 9)": 1}}
} | f8c79f8071f2b61ceacaacf3406a198b2c54c917 | 26,989 |
import json
def send(socket, action, opts=None, request_response=True, return_type='auto'):
"""Send a request to an RPC server.
Parameters
----------
socket : zmq socket
The ZeroMQ socket that is connected to the server.
action : str
Name of action server should perform. See ... | 9a2dcf2fb78c1458c0dead23c4bcc451f1316731 | 26,990 |
def brighter(data, data_mean=None):
"""
Brighter set of parameters for density remap.
Parameters
----------
data : numpy.ndarray
data_mean : None|float|int
Returns
-------
numpy.ndarray
"""
return clip_cast(amplitude_to_density(data, dmin=60, mmult=40, data_mean=data_mean)... | d00688ac99fb509ad0fe0e2f35cc5c03f598bfee | 26,991 |
from typing import List
import os
def get_configuration(args_in: List[str]) -> Configuration:
"""
Retrieves configuration from the command line or environment variables.
Parameters
----------
args_in: List[str]
The system arguments received by the main script
Returns
-------
... | d68e09a23c216b035e4027070ed4cdb5138e793a | 26,992 |
import sys
def main() -> int:
"""Entry point for 'compress'."""
try:
argv = parser.parse_args()
buffersize = int(argv.buffersize * 1024**2)
action = compress if argv.decompress is False else decompress
schemes = {getattr(argv, scheme): scheme for scheme in SCHEMES}
if... | 8d64975c689b8a19a38e85ab1d3ee569ab039ac0 | 26,993 |
import logging
import sqlite3
def get_lensed_host_fluxes(host_truth_db_file, image_dir, bands='ugrizy',
components=('bulge', 'disk'),
host_types=('agn', 'sne'), verbose=False):
"""
Loop over entries in `agn_hosts` and `sne_hosts` tables in
the host_tru... | 1b28c58ed824b988e02d40091ac633bc8187d27a | 26,994 |
from pathlib import Path
def load_challenges() -> list[Challenge]:
"""
Loads all challenges.
Returns
-------
list[Challenge]
All loaded challenges.
"""
__challenges.clear()
modules = []
for lib in (Path(__file__).parent / "saves/challenges").iterdir():
if not lib.n... | d6cd5d65d572ba081d5f2ba0bca67c755bc57d2d | 26,995 |
def get_new_user_data(GET_params):
"""Return the data necessary to create a new OLD user or update an existing one.
:param GET_params: the ``request.GET`` dictionary-like object generated by
Pylons which contains the query string parameters of the request.
:returns: A dictionary whose values ar... | 61ee952088bb37a2f5171f0bdd0ed9a59d66bed7 | 26,996 |
import six
def add_heatmap_summary(feature_query, feature_map, name):
"""Plots dot produce of feature_query on feature_map.
Args:
feature_query: Batch x embedding size tensor of goal embeddings
feature_map: Batch x h x w x embedding size of pregrasp scene embeddings
name: string to name tensorflow su... | d7807942a2e3d92b4653d822b24686b649a6df88 | 26,997 |
def ParseVecFile(filename):
"""Parse a vector art file and return an Art object for it.
Right now, handled file types are: EPS, Adobe Illustrator, PDF
Args:
filename: string - name of the file to read and parse
Returns:
geom.Art: object containing paths drawn in the file.
Retur... | accf0446a4600de77cf41fdc5a586f930156dfd6 | 26,998 |
import torch
def batchnorm_to_float(module):
"""Converts batch norm to FP32"""
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
module.float()
for child in module.children():
batchnorm_to_float(child)
return module | bf9ad7cbda5984465f5dcb5f693ba71c8a0ab583 | 26,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.