content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Sequence
def build_action_observations(
observations: Sequence[data.Observation]
) -> Sequence[data.ActionObservation]:
"""Given observations, creates the actions associated with them.
Args:
observations: a sequence of Observation objects capturing a PanoContext, a
heading, and t... | cec2c5007c7192e778ecf3c6edd5ef2aef781850 | 36,600 |
def handle_write_config_request(config_request):
"""Set piaware-config setting
Expected config_request format:
{
"request": piaware_config_write
"request_payload" : {"rtlsdr-gain": 20, "wireless-network": "no"}
}
request_payload must be a dictionary of key/v... | 8e91fdafac073813e4365eb1f535375bfdb4bf8a | 36,601 |
import numpy
def nanallclose(x, y, rtol=1.0e-5, atol=1.0e-8):
"""Numpy allclose function which allows NaN
Args:
* x, y: Either scalars or numpy arrays
Returns:
* True or False
Note:
Returns True if all non-nan elements pass.
"""
xn = numpy.isnan(x)
yn = numpy.is... | 053fdc260d215304f0e913a468775dd4ce86dba9 | 36,602 |
import re
def get_current_data(cfg):
"""Reads the output file to see what are the contents of the arrays and the version control string
Returns a dictionary with:
'etag' -- Etag of the source file used to render the file. As stored in the version control string
'date' -- Date of the source file used to render t... | 7b17b6410b2f38c9fc21cd4904b43673dc227014 | 36,603 |
def vgg13_bn(pretrained=False, requires_grad=False, **kwargs):
"""VGG 13-layer model (configuration "B") with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['... | 38f4e2ca715b310c914c7753ac90b66c5c305916 | 36,604 |
def get_shape_label():
"""Get shape of the labels in Thyroid dataset"""
return (None,) | cc7bd48de40de185f39450e360846adc81383aca | 36,605 |
import random
def pick_random_question(df_questions, topic_id):
"""Randomly pick a question for a given topic
Random choice uses 1/box as weight
Parameters
----------
df_questions: DataFrame
DataFrame containing questions
columns = ['ID_question', 'ID_topic', 'label', 'link', 'bo... | 036997a7b80dda05fcb4f1d7a029567b257e35c1 | 36,606 |
def CTDensityPixel_getGray():
"""CTDensityPixel_getGray() -> vpl::img::tDensityPixel"""
return _Core.CTDensityPixel_getGray() | 9b61f68a6231ef2c2685c5755653eeb8b37e65ab | 36,607 |
import math
def bfm2Mesh(bfm_info, image_shape=default_init_image_shape):
"""
generate mesh data from 3DMM (bfm2009) parameters
:param bfm_info:
:param image_shape:
:return: mesh data
"""
[image_h, image_w, channel] = image_shape
pose_para = bfm_info['Pose_Para'].T.astype(np.float32)
... | 2683ec2f532ca8e837797bd09a586e84716b953e | 36,608 |
import requests
import time
import logging
import re
def query_rest_server(ts1, ts2, data_url, idstr, nbins):
"""get xml from restful interface for the requested channels
with a single request
inputs:
t1, t2 are start/stop time in ms
data_url is url w/out args
idstr ... | c0b6078bf756149dcc71c4362186331c9f943203 | 36,609 |
def _merge_css_item(item):
"""Transform argument into a list with a single string value."""
if isinstance(item, (list, tuple)):
return _merge_css_list(*item)
item = f"{item}" if item else ""
return [item] | dd844fa6ede8b4515e02ab3498242b7a03443af2 | 36,610 |
def get_iscsi_auth_groups(client):
"""Display current authentication group configuration.
Returns:
List of current authentication group configuration.
"""
return client.call('get_iscsi_auth_groups') | 4a31f6c1f1ea4fa543ee731d54e699cdd108e512 | 36,611 |
import os
def list():
""" Return list of all available books. """
return jsonify({'books': [x for x in os.listdir(BOOK_PATH)
if not x.startswith('.')]}) | 6360dcf81cd71bd108ee16ed764f4806db1800a7 | 36,612 |
import argparse
def arguments():
"""
parsing command line arguments
"""
parser = argparse.ArgumentParser(description="Summarize columns in given file.")
parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Print debug info.")
parser.add_argument("-f", "--file", action... | 246f47e09d6f8aebb8ece3be896b457c25a31c51 | 36,613 |
def _filter_returned_ops(fn):
"""Filtering out any ops returned by function.
Args:
fn: a function
Returns:
A tuple of (
Wrapped function that returns `None` in place of any ops,
dict that maps the index in the flat output structure to the returned op
)
"""
returned_ops = {}
def wr... | b4e3cdb09746dad6ffccd547c3c94ce5b779dbcb | 36,614 |
def subclass_of(*args):
"""
This type validation function can be used in two modes:
* providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType
error if not. If ref_type is a set of types, any match with one of the included types will do
* provid... | 7f9e8d224756d5da0eb775cb6861788d6c558fc5 | 36,615 |
from typing import Tuple
from typing import List
from typing import Dict
from typing import Any
def info() -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""
Get input and output schemas
:return: OpenAPI specifications. Each specification is assigned as (input / output)
"""
input_sample = ... | 282f60cacac69865736c58712c4bfbdb2f5e2c24 | 36,616 |
def region_growing_lab_hsv(I, max_dist, min_pixels=1, smoothing=0):
"""Performs region growing on an color image in HSV space.
Parameters
----------
I : ndarray of float32
3D array representing the image
max_dist : float
maximum hsv distance to add a neighbou... | f595b92a71ac1f15c0bf5683ed0c49ae3b9b8035 | 36,617 |
def wolf_mass(sigma, Re):
"""
Wolf mass estimator from Wolf+ 2010
Args:
sigma :
1D line of sight velocity dispersion in km/s
Re :
2D radius enclosing half the stellar mass in pc
Returns: estimate of the dynamical mass within the half light radius in Msun
... | 7b5258858e932c0b15eaf45a32d08dcf655f1c24 | 36,618 |
async def delete_pokemon(id: int):
"""
## Deletes a Pokemon by ID.
Path Parameters
---------------
Pokemon ID.
Body Parameters
---------------
None
Returns
-------
None
"""
if not await PokemonRepository.exists(id=id):
# Non-existent Pokemon, ... | 5d0917fbae0bcfeb4c567dd0d15979c02637fb38 | 36,619 |
import requests
import itertools
def anagrams_in_list(word, list_of_words):
"""Given a word (str) and list of words (list or tuple, a list is returned
with the valid anagrams of the word in the list of words
Args:
- word (str): The word that you want to test
- list_of_words (list or tuple... | 3b8621c81bae1fb274cd740113c844ecfeaa83ce | 36,620 |
import os
import fileinput
import re
import sys
def use_pebble(func):
"""Creates an config with pebble as the CA, and returns the pebble process"""
def pebble_wrapper(tmpdir, pebble, opt_username, opt_password, opt_lb):
os.environ["REQUESTS_CA_BUNDLE"] = os.path.abspath(
"tests/functional... | 1845cb042a245afbb51e0655cd62d52e95b7530c | 36,621 |
def oavol(x, y, z, v, xx, yy, zz, pmap=None, weight=10, nx=2, ny=2,
verbose=False):
"""
Objective analysis interpolation for 3D fields
Parameters
----------
x: array [2-D]
x-values of source data
y: array [2-D]
y-values of source data
z: array [3-D]
z-value... | a1a8d1e0e474fea0a99bd4173c0ba2aa892a4773 | 36,622 |
from typing import List
from typing import Optional
def create_study(
name: str,
description: str,
run_ids: List[int],
alias: Optional[str],
benchmark_suite: Optional[int],
) -> OpenMLStudy:
"""
Creates an OpenML study (collection of data, tasks, flows, setups and run),
where the runs ... | bfb3f8ca2650b59754dba8f72077543d91167050 | 36,623 |
def nats_to_params(nat1, nat2, nat3, nat4):
"""
natural parameters to distribution parameters
"""
alpha = nat1 + (1./2)
nu = -2 * nat4
mu = nat3 / nu
beta = - nat2 - (nu * (mu**2) / 2)
return alpha, beta, mu, nu | 56fba0a886d35948edf570c6eb379f6e0175b589 | 36,624 |
def depth_type_order(order):
"""Create a function which constrains paragraphs depths to a particular
type sequence. For example, we know a priori what regtext and
interpretation markers' order should be. Adding this constrain speeds up
solution finding."""
order = list(order) # defensive copy
... | ed22f589f05df52c736c29ccbaef22c14eb24b6b | 36,625 |
from typing import Dict
def euclidean(a: Dict, b: Dict)->float:
"""Return the euclidean distance beetween the given dictionaries.
Parameters
----------------------------
a: Dict,
First dictionary to consider.
b: Dict,
Second dictionary to consider.
Returns
---------------... | 88311a84606ede224437b87a128b76d0da458474 | 36,626 |
def get_system_category():
"""获取文档分类"""
systems = ComponentSystem.objects.all()
doc_category = {}
for system in systems:
if not system.has_display_doc:
continue
system_doc_category = system.doc_category
doc_category.setdefault(system_doc_category.id, {
'na... | 712669eaa4b044f9fd62e2589a1462678aabbc2f | 36,627 |
from typing import Iterable
def _serialize_graph(ops):
"""
Serializes a graph and returns the actual protobuf python object (rather than serialized
byte string as done by `serialize_graph`).
"""
assert isinstance(ops, Iterable), "Ops passed into `serialize_graph` must be an iterable"
ops = Op.... | 65458fe18fff382c90aa9a1bb97f3d654ccac766 | 36,628 |
def single_cell_variables(model_name, dat, let):
"""
Single cell variable of model_name.
1: head, 2:temp, 3:conc, 4:kz, 5:lz, 6:por (inside mem)
11: head, 12:temp, 13:conc, 14:kz, 15:lz, 16:por (not inside mem)
"""
output_path = rm.make_output_dirs(model_name, dat, let)[0]
enkf_inpu... | 711389851f58dcce652d1bb891ca8cd48b805a15 | 36,629 |
import sqlite3
def add_signature(db, df):
"""Adds `signature` from database `db` to dataframe `df`."""
events = df["event_no"]
with sqlite3.connect(db) as con:
query = (
"select event_no, pid, interaction_type from truth where event_no in %s"
% str(tuple(events))
)
... | 5ff85591bf03393cbc428abde40242e6ca3c39f0 | 36,630 |
import re
def getLLVMVersion(llvmProgram):
"""executes the program with --version and extracts the LLVM version string"""
versionString = getVersion(llvmProgram)
printLLVMVersion = re.search(r'(clang |LLVM )?(version )?((\d)\.\d)(\.\d)?', versionString, re.IGNORECASE)
if printLLVMVersion is None:
... | 2facaaf70824febdfb6a79956138963d0f61b6ce | 36,631 |
import os
from re import T
import torch
def box2patch(image_dir, detection_result):
"""
Clip and get bbox patch, also normalize
"""
img = Image.open(os.path.join(image_dir, detection_result['name']))
# for normalization
mean=(0.485, 0.456, 0.406)
std=(0.229, 0.224, 0.225)
transform = T... | 5fb7f3631c26d9cce32569f0cb77954b9b4d963b | 36,632 |
def lambert(disk):
"""Converts coordinates on the disk to spherical coordinates, using
the Lambert azimuthal equal-area projection.
Args:
disk: Array of shape [..., 2] representing points on the disk.
Returns:
phi, theta: Spherical coordinates
>>> phi, theta = lambert(_TEST_DISK_R... | 6e6461e06fe0092ea9806fba1874a5153d3115cb | 36,633 |
def mandel_geom(params, x, etc = []):
"""
This function computes a transit shape using equations provided by Mandel & Agol (2002).
Parameters
----------
midpt: Center of eclipse
width: Eclipse duration from contacts 1 to 4
rp_rs: Planet-star radius ratio
b: Impact parameter
flux... | 62c2b41435600381200af66b9465b054c1a1d0f9 | 36,634 |
import os
import sys
def parse_args():
"""
Parse out testing arguments.
"""
_, fname = os.path.split(__file__)
usage = "cat data | python %s" % fname
parser = ArgumentParser(usage=usage)
parser.add_argument("-m", "--center", dest="m", required=True,
type=float, hel... | 75482fb97f3ffc84180b557b1b582c5de9edffb8 | 36,635 |
def from_columns(mapping, fp):
"""
Write columns to the open file opbject ``fp`` in XPT-format.
The mapping should be of column names to equal-length sequences.
Column labels are restricted to 40 characters. The XPT format also
requires a separate column "name" that is restricted to 8
characte... | 55b5436bfbb99ddaa90b413171111748d1a799b6 | 36,636 |
from typing import Optional
def find_unused_relay_number(event_number, organizer_number) -> Optional[str]:
"""Find a relay number that isn't currently used by an existing chatroom
connection."""
# TODO: Should probably be a join, but its unlikely this list will
# get big enough in the near future to b... | 0953c0a194df8f042c56c7da64ae956e9e1d94ae | 36,637 |
def list_random_circuits_onelen(opLabels, length, count, seed=None):
"""
Create a list of random operation sequences of a given length.
Parameters
----------
opLabels : tuple
tuple of operation labels to include in operation sequences.
length : int
the operation sequence length... | 6f3a849a54d201dcd39c743b997c9409b5c834da | 36,638 |
from datetime import datetime
def simulate_lambda(drlambda, date, zone):
"""
TODO: do we assume that the lambda is for the peak period only: 4-7pm
how do we do this on the backend?
assume date is in YYYY-MM-DD
"""
print(xsg.get_zones(sites[0]))
start = pendulum.parse(date, tz='US/Paci... | 73226b51d40b9a156caaedf2f28dcc5ab1619205 | 36,639 |
def get_number_of_pictures(directions,cutOff,referenceAtom):
"""
Finding the amount of copies
of the original SuperCell
.---------------------------.
/ \ \
/ \ \
/ \ ... | e175e12329707312cd3aa78cb027e70b728756fc | 36,640 |
def _create_extension_feed_items(client, customer_id, campaign_resource_name):
"""Helper method that creates extension feed items.
Args:
client: a GoogleAdsClient instance.
customer_id: a str Google Ads customer ID, that the extension feed items
will be created for.
campaign... | 54eb2ff33e8bea07c8dad0a91201d63484bd9924 | 36,641 |
def rgb2hsv(img):
""" Use matplotlib to convert rgb to hsv (TA allowed) """
return (rgb_to_hsv(img.astype(np.float32) / 255.) * 255).astype(np.uint8) | 2afaefd68fbc68c1c36e8a0000fca999d7f30e83 | 36,642 |
def get_territory_options_formatted():
"""
Formats list of territory options per Dash dropdown standards.
Example of returned data structure:
{'country': [{'label': 'Algeria', 'value': 'Algeria'}, {'label': 'Angola', 'value': 'Angola'}], 'state': [{'label': 'Alberta, Canada', 'value': 'Alberta, Canada'}... | 5359d6bb6581772244a66c7a7568275589145f48 | 36,643 |
def _get_resources(rtype='resources'):
""" resource types from state summary include: resources, used_resources
offered_resources, reserved_resources, unreserved_resources
The default is resources.
:param rtype: the type of resources to return
:type rtype: str
:param role: the name of the role... | 04746e33685d503adb9f0a3527a7bc203ab639b3 | 36,644 |
def feature_name_to_placeholder(feature_name, params):
"""
Get a placeholder for the given feature.
Args:
- feature_name: name of the feature (<string>).
Returns:
Return as a tensor tf.placeholder.
"""
feature_type, shape = (
DATASETS_METADATA[feature_name].dtype,
... | b5785a985517b318e919f03e1f11eaef10fa5827 | 36,645 |
from typing import List
import re
def split_words(value: str) -> List[str]:
"""Split a string on words and known delimiters"""
# We can't guess words if there is no capital letter
if any(c.isupper() for c in value):
value = " ".join(re.split("([A-Z]?[a-z]+)", value))
return re.findall(rf"[^{DE... | 690dfb75c5e22c5d2bbd33797aabe2af41b09518 | 36,646 |
from typing import Dict
from typing import Any
def setup(app: sphinx.application.Sphinx) -> Dict[str, Any]:
"""Entry point for sphinx theming."""
app.require_sphinx("3.0")
app.add_config_value(
"pygments_dark_style", default="native", rebuild="env", types=[str]
)
app.add_html_theme("furo... | 2c196ef86fba7e81f540f4feff3f6c5b924d1940 | 36,647 |
def ldns_key_set_pubkey_owner(*args):
"""LDNS buffer."""
return _ldns.ldns_key_set_pubkey_owner(*args) | f13a90fb29b158254f053523aa387ccf68b41128 | 36,648 |
def graph(ich, no_stereo=False):
""" inchi => graph
"""
return automol.convert.inchi.graph(ich, no_stereo=no_stereo) | 6925a830838ced5714155b3274517574e5dcdb88 | 36,649 |
def get_rancher_services_list():
"""
:return: array of all system services
"""
service_list = []
stacks = get_request(
RANCHER_API_URL + RANCHER_API_STACKS_LIST_ENDPOINTS + '?system=false',
True
)
for stack in stacks['data']:
services = get_request(
RANCH... | 4a9d8076539702fdb754c2a75d9684a712e714b5 | 36,650 |
from typing import List
def check_peak(data: List[DataPoint]) -> bool:
"""
This is a function to check the condition of a simple peak of signal y in index i
:param data:
:return:
"""
if len(data) < 3:
return False
midpoint = int(len(data) / 2)
test_value = data[0]
for i ... | 59811943a68136978a4018f50895431ccb028834 | 36,651 |
def load_subtensor(g, labels, seeds, input_nodes, device):
"""
Copys features and labels of a set of nodes onto GPU.
"""
batch_inputs = g.ndata['feat'][input_nodes].to(device)
batch_labels = labels[seeds].to(device)
return batch_inputs, batch_labels | 34da3bb7f0d17b4a37f4f0abc990ff24116a0e58 | 36,652 |
def node_index_at_link_ends(shape):
"""Array of nodes at each end of links."""
node_ids = np.arange(np.prod(shape))
node_ids.shape = shape
return (node_at_link_tail(node_ids), node_at_link_head(node_ids)) | 62f5f6d6cecd2de6b45a2cce39a34239c9a35e9f | 36,653 |
import sympy
def get_symbol_list(number_of_symbols):
""" Returns a list of sympy expression, each being an identity of a variable. To be used for input layer."""
return sympy.symbols(['x_{}'.format(i + 1) for i in range(number_of_symbols)], real=True) | 2d81bfc1a162e52b42bf69d4cf68786717ba6f3c | 36,654 |
def get_viewer_frame(frame, viewer_size):
"""Get viewer frame.
Parameters
----------
frame : numpy.ndarray
viewer_size : tuple
Returns
-------
viewer_frame : numpy.ndarray
"""
return cv2.resize(frame, (viewer_size[1], viewer_size[0]),
interpolation=cv2.IN... | 2883fb1130b66bbbff2b35c3831bb91e7308a6ad | 36,655 |
def preprocess_waveform(y, sample_rate,
target_sample_rate,
preemphasis_coeff=0.95,
stft_args={}):
"""Resample, preemphasize, and compute the magnitude spectrogram.
Inputs:
y: 1D numpy array containing signal to featurize (np.ndarra... | a3f731e163fec00865391e811d5ec696d7920b07 | 36,656 |
from typing import List
def patients_from_tissue(df: pd.DataFrame, tissue: str) -> List[str]:
"""Given a tissue, return all patients within that tissue"""
return df[df.tissue == tissue].id.tolist() | 61d33879f2ddeb1f84d76ce168df723ed8237e88 | 36,657 |
def asst70_gene_descriptors(moa_abl1):
"""Create assertion70 gene_descriptors test fixture."""
return [moa_abl1] | a68a349aaebf107cdd645e213fb56f268046a619 | 36,658 |
from typing import List
from typing import Dict
from typing import Any
import logging
import requests
def get_all_pokemon_info() -> List[Dict[str, Any]]:
"""
Retrieves all pokemon information from PokeAPI.
"""
logger.info("Retrieving all pokemon data.")
api_query = urljoin(POKEAPI_URL_PREFIX, POKE... | cc2b8911fe75a87c966982f51213c728e1258766 | 36,659 |
import functools
import os
def basic_auth(function):
"""Require HTTP Basic Auth."""
@functools.wraps(function)
def wrapper(*args, **kwargs):
auth = flask.request.authorization
if auth is not None:
if auth.username == os.environ.get('AUTELION_USERNAME'):
if auth.... | 7efdff89100d6919e9ca353337f813fa883a75a2 | 36,660 |
def medoid(collection, bands=None, discard_zeros=False):
""" Medoid Composite
:param collection: the collection to composite
:type collection: ee.ImageCollection
:param bands: the bands to use for computation. The composite will include
all bands
:type bands: list
:param discard_zeros: ... | c0876ddb3cf9940f665eee7e833082d80e304ae6 | 36,661 |
import urllib3
import certifi
import tqdm
import os
def download_zip(url: str) -> BytesIO:
"""Download data from url."""
logger.warning(
"start patched secure https chromium download.\n"
"Download may take a few minutes."
)
with urllib3.PoolManager(
cert_reqs="CERT_REQUIRED", ... | 84e9645a7fc107b5158dfc84f9a1595d30384b78 | 36,662 |
def match_bool(value: bool) -> models.Match:
"""_summary_
Args:
value (bool): _description_
Returns:
models.Match: _description_
"""
# Check
if value:
# Return
return models.Match(
accuracy=models.Accuracy.RIGHT,
direction=models.Directio... | 3631b03ad5b3f1f17ca0de9661bf711b2ed464ca | 36,663 |
def p_ibd_1(f):
"""Compute Joint-PMF for sibling pair genotypes given IBD1.
Args:
f : :class:`float`
allele frequency
Returns:
P : :class:`~numpy:numpy.array`
matrix of probabilities
"""
fmatrix = np.array([[0.0,1.0,0.0],[1.0,1.0,2.0],[0.0,2.0,3.0]])
mi... | 870a307b287556d5d5db032bf47213a5aa2e818a | 36,664 |
from typing import Any
from typing import Callable
import click
def argument(*args: Any, **kwargs: Any) -> Callable[[Any], Any]:
"""Create command-line argument.
SeeAlso:
:func:`click.argument`
"""
return click.argument(*args, **kwargs) | cebe48c946f48ab90368779052302e650a29679a | 36,665 |
def nvctl(*args, **kwargs):
"""
Run the nvctl command with the specified args returning the output as
a parsed json object by default. The kwargs support 'json=false' and
'no_login=true'.
Exception is raised for errors.
"""
cmd_list = list(args)
json_out = True
if 'json' in kwargs an... | b2b904d40477ff78c882b572afddfd7899e0435b | 36,666 |
import ctypes
def load_libgmt(env=None):
"""
Find and load ``libgmt`` as a :py:class:`ctypes.CDLL`.
By default, will look for the shared library in the directory specified by
the environment variable ``GMT_LIBRARY_PATH``. If it's not set, will let
ctypes try to find the library.
Parameters
... | 656c8d9297a26ff27ab7b45af6531b80e1d68e9a | 36,667 |
def validate(board: list) -> bool:
"""
Main functrion of the module.
Recieves board and checks if it is a valid one or not
with the help of other functions.
>>> board = board = [\
"**** ****",\
"***1 ****",\
"** 3****",\
"* 4 1****",\
" 9 5 ",\
"... | 499128dbd1817be880b7a17e0fcb7fdefa7002e0 | 36,668 |
def build_table_separator(outer_left='╠', inner='╬', outer_right='╣'):
"""
Builds formatted unicode header for the stopwatch table.
:return: formatted unicode header
"""
return f"{outer_left}{'═' * 14}{inner}{'═' * 18}{inner}{'═' * 20}{outer_right}" | 22d9aef799e2245a072e9032b9d8dcc2f138386e | 36,669 |
import hashlib
def _hash_feature(feature):
"""Calculate SHA256 hash of feature geometry as WKT"""
geom = shape(feature["geometry"])
return hashlib.sha256(geom.wkt.encode("utf-8")).hexdigest() | 59013e7fb643b5261e1ca9557e4c875a1fda72f3 | 36,670 |
def review_pull_request_event(event):
"""Determine whether this is a valid pull request review event."""
try:
source = event["source"]
detail_type = event["detail-type"]
event_type = event["detail"]["event"]
return (
source == "aws.codecommit"
and detail_... | 2182ec385f2521e016ebee8995611df73944d569 | 36,671 |
import argparse
import os
def copy(args):
"""Perform the copy on required instances.
args list of arg values
"""
# parse the command args
parser = argparse.ArgumentParser(prog='swarm copy',
description='This plugin is used to copy a file to many instances.... | c6e0e92a2fde5a6a78beb7afa7a6c42fa55a513b | 36,672 |
import ast
from typing import Optional
from typing import Any
def safe_eval(expr: ast.expr, culprit: ast.AST) -> Optional[Any]:
"""Return the given expression as evaluated at compile-time.
NOTE
Use this instead of Python's `eval` to avoid potential arbitrary code
execution.
"""
_erro... | cd93df7a1c4c59806327165a2bf10307a6720e45 | 36,673 |
import tqdm
import torch
def bert_cos_score_idf(model, refs, hyps, tokenizer, idf_dict,
verbose=False, batch_size=64, device='cuda:0'):
"""
Compute BERTScore.
Args:
- :param: `model` : a BERT model in `pytorch_pretrained_bert`
- :param: `refs` (list of str): referenc... | bf5be0252066caf2ab143d06fe9f1b8d03fc26f9 | 36,674 |
from datetime import datetime
def search_tickets(request, **kwargs):
"""Return the tickets search page."""
template = 'tickets/search_tickets.html'
check_groups(request.user, [GROUP_SUPERVISOR, GROUP_SUPPORT])
# If the REFERER is a page other than the tickets
# search page, don't do any extra wo... | 6aa91d6b69c7ce51185ba87606070fc4473d1de5 | 36,675 |
def add_port_filter_by_host_interface(query, hostid, interfaceid):
"""Adds a port-specific host and interface filter to a query.
Filters results by host id and interface id if supplied hostid and
interfaceid are integers, otherwise attempts to filter results by
host uuid and interface uuid.
:param... | 883b3cb0df8c0bc3662c29f148fcefcf78fcf71c | 36,676 |
def lidar_classify_phase(instrument, model, beta_p_phase_thresh=None,
convert_zeros_to_nan=False, remove_sub_detect=True):
"""
Phase classification based on fixed thresholds of a lidar's LDR and
tot beta_p variables.
Parameters
----------
instrument: Instrument
... | 34f37919d10102eb41ed485b905bc83e0f304c4d | 36,677 |
def compute_cog(d):
"""
Args:
d: dict
Returns:
percentage
"""
accuracy=(d['22']+d['25']+d['23']+d['24'])/27
return round(accuracy*100, 3) | a83cb11f4d5fdec3bb63533352eb4fd0b62782ea | 36,678 |
from pathlib import Path
def get_builddir() -> PathLike:
"""Obtain Sphinx base build directory for a given docset.
Returns:
Base build path.
"""
parser = get_parser()
args = parser.parse_args()
return (Path(args.outputdir) / ".." / "..").resolve() | 7bd5d5e498a679c64fbf10b7461a19c6f5b4c0b2 | 36,679 |
from typing import Union
from typing import List
from typing import TextIO
from pathlib import Path
from typing import BinaryIO
from typing import Any
from typing import ContextManager
from typing import Iterator
from io import StringIO
import fsspec
def _prepare_file_arg(
file: Union[str, List[str], TextIO, Path... | d266a50d2832018031b2d1dd7660bde35cd11345 | 36,680 |
import json
def read_file(file):
"""Reads in a data file and generates insert statements for the sql dump."""
rs = "\n"
with open(file, "r", encoding='utf-8') as f:
data = json.load(f)
# Insert conf
rs += '''INSERT INTO Conference (conf_name, time, location) VALUES ("{}", "{}", "{}... | bf5db1e737278182bbddae836bbfc2f3fe8dc013 | 36,681 |
from typing import Optional
def retrieve_price(user: Optional[UserProtocol], price_id: str) -> PriceSubscription:
"""
Retrieve a single price with subscription info
"""
price_future = executor.submit(stripe.Price.retrieve, price_id)
subscription_info = is_subscribed_and_cancelled_time(user, price_... | e149c02d2bc6e55ae673970a8b4a02eef02120c5 | 36,682 |
def transform(claims):
"""label encode value of claims
Parameters
----------
claims: panda.DataFrame
a data frame [source_id, object_id, value] where source_id, and object_id is already label encoded.
Returns
-------
claims_value_enc: pandas.DataFrame
a data frame [... | 9e24656726834df10de6e8136558abb6bb01da9a | 36,683 |
def set_callback(ar, cb):
"""
Runs when confimation is requred, checks if answer is present in request data, if so, runs corisponding function
Otherwise returns with data that will pop up a dialog.
"""
cb_id = cb.uid
answer = ar.xcallback_answers.get("xcallback__" + cb_id, None)
if answer is... | 90acf651ad324b6e4958ed90f4bf8d76f37a6073 | 36,684 |
import os
def get_map_crs(dem, longitude, latitude):
""" Get map coordinate system.
Notes:
If `dem` is a file, the map coordinate system should be
the same as that of the dem file; otherwise define a UTM coordinate system
based on the longitude and latitude.
Arguments:
dem:... | 1b58eddac2768c77fb045fde53bd60e2fe7c6cfc | 36,685 |
import re
def parse_args():
"""
Parses the command line arguments.
"""
# Override epilog formatting
OptionParser.format_epilog = lambda self, formatter: self.epilog
parser = OptionParser(usage="usage: %prog -i INPUT_STRING | --input INPUT_STRING "
"| --load FILE",
epilog=EXAMPLES)
parser.add_... | 14f67abde64178cf6dae8ae5548ceac56db7aab9 | 36,686 |
def clicked_watchtime_reward(responses):
"""Calculates the total clicked watchtime from a list of responses.
Args:
responses: A list of IEvResponse objects
Returns:
reward: A float representing the total watch time from the responses
"""
reward = 0.0
for response in responses:
if response.clicke... | a931fd235a0e70add98c3b8cb70adbfbf74b4fb9 | 36,687 |
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib
import seaborn as sns
import numpy as np
def plot_counts(counts, gene_type):
"""Plot expression counts. Return a Figure object"""
sns.set_style('white')
sns.set_style({'patch.... | 1e9654bc2d0895bb642ba5dcc95750324c7f5a43 | 36,688 |
def watersheds_gdb_reader():
"""reader watersheds gdb into geopandas"""
#watersheds_gdb = 'WRIWatersheds.gdb'
# watersheds_gdb = 'AQID_Watwershed_Jan2020/AQID_Watwershed_Jan2020.shp'
# watersheds = geopandas.read_file(watersheds_gdb)
# watersheds.set_index("aqid",inplace=True)
#pfaf_id, ar... | 13b64789e1f7e246d520cf757948d089c3948ef2 | 36,689 |
def cast_to_list(emoticons_list):
"""
Fix list of emoticons with a single name
to a list for easier future iterations,
and cast iterables to list.
"""
emoticons_tuple = []
for emoticons, image in emoticons_list:
if isinstance(emoticons, basestring):
emoticons = [emoticons... | 5d955e493924a7ce1b206a30e4e8b9ea25068ba0 | 36,690 |
def merge_sorted(arr1: t.List[float], arr2: t.List[float]) -> t.List[float]:
"""
Merge two sorted arrays into a third sorted array.
Using two pointers, this algorithm is in O(n1 + n2), where n1 and n2 are
respectively the lengths of ``arr1`` and ``arr2``.
Args:
arr1: The first array to mer... | 4bb2a42d378ffc17f7b2d0231dab5a8e22545a6d | 36,691 |
def history(locs: ArrayLike, name: int) -> np.void:
"""Creates a named and sorted location history.
Args:
locs: An iterable of location numpy structured arrays.
name: A 64-bit int that labels the history.
Returns:
A structured array with attributes "name" and "locs".
"""
lo... | e2903ab4d29ddb233af541e6625dd7267ba415ed | 36,692 |
def conv1x1(in_planes, out_planes, stride=1, bias=False):
"""1x1 convolution"""
return nn.Conv2d(
in_planes,
out_planes,
kernel_size=1,
stride=stride,
bias=bias
) | c491d90c74e798fa798a946e38fb0a04563bfb4b | 36,693 |
def argv_obj(input):
"""argv_obj(PyObject * input) -> char **"""
return _strumpack.argv_obj(input) | ba0d3cd61f93d2414d598e7a6cff95eeef9cbcd9 | 36,694 |
import sys
def palettise_image(img, palette):
"""Map image to nearest colours in a given palette"""
img_palette = img.getcolors()
if img_palette is None:
sys.exit("error: source image has too many colours!")
col_map = {x[1] : closest_palette_index(x[1], palette) for x in img_palette}
img_... | cfb2a9701942eab8e34505437fa6b5b672936792 | 36,695 |
import types
def atom(token: str) -> types.Atom:
"""Convert token to proper types
When parsing, we get all tokens represented as strings.
Here we convert all integers and floats to their proper
types, and keep all other types as `types.Symbol` objects.
"""
try:
return int(token)
e... | 5122747a0d3b25c10a47d405949184aa987ae754 | 36,696 |
def _descend_namespace(caller_globals, name):
"""
Given a globals dictionary, and a name of the form "a.b.c.d", recursively
walk the globals expanding caller_globals['a']['b']['c']['d'] returning
the result. Raises an exception (IndexError) on failure.
"""
names = name.split('.')
cur = call... | 111a5277907b60d3f27f037868ac8c84e390e159 | 36,697 |
def str_to_int(string):
"""Converts a DNA sequence to a list of integers.
Parameters
----------
string : str
The string of nucleobases.
Returns
-------
list of int
A list with the integer value for each nucleobase in the string.
"""
return [ut.nucleotide[nb] for nb... | c8f4431a79d77f5e92b592a44a824ff3c060bda4 | 36,698 |
def _get_extension_point_url_from_name(domain, category, pluggable_name):
"""Get the extension point URL based on a pluggable method name"""
return '{}/{}/{}'.format(domain, category, pluggable_name).replace('//', '/') | a4a34409dac26e42d123c4fda66ddc0947134e00 | 36,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.