content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pickle
def get_data():
"""Get data in form suitable for episodic training.
Returns:
Train and test data as dictionaries mapping
label to list of examples.
"""
with tf.gfile.GFile(DATA_FILE_FORMAT % 'train', 'rb') as f:
processed_train_data = pickle.load(f)
with tf.gfile.GFile(DATA_FILE_F... | b5c53df37de518401270c59f003ac71efb5eb056 | 3,621,800 |
import os
import logging
def create_cache_directory(
directory_subpath: str,
cache_directory: str = DEFAULT_CACHE_DIRECTORY,
use_cache: bool = True) -> str:
"""Create the cache directory structure for the given directory."""
# Ensure the cache_directory always exists.
os.makedirs(c... | ce076a5448b9bacc5795123e13d144a4b8aeafa8 | 3,621,801 |
def svd(a, full_matrices=True, algo='svd', **kwargs):
""" ctypes wrapper for LAPACK SVD (DGESVD)
Factorizes the matrix a into two unitary matrices U and Vh and
an 1d-array s of singular values (real, non-negative) such that
a == U S Vh if S is an suitably shaped matrix of zeros whose
main diagonal ... | 6b58789fe8ef1a83cc602868aaff8d56606985d3 | 3,621,802 |
def reshape(fd: DahliaFuncDef) -> str:
"""https://tvm.apache.org/docs/api/python/relay/index.html#tvm.relay.reshape"""
data, res = fd.args[0], fd.dest
newshape = fd.attributes.get_int_tuple("newshape")
ddims = get_dims(data.comp)
rdims = get_dims(res.comp)
assert (
# See the TVM Relay A... | bbb3f1a5b9d6da3915295122a3bded891feac9db | 3,621,803 |
def convert(digits, base1, base2):
"""Convert given digits in base1 to digits in base2.
digits: str -- string representation of number (in base1)
base1: int -- base of given number
base2: int -- base to convert to
return: str -- string representation of number (in base2)"""
# Handle up to base 3... | 01638a1a356af60549f7520f1dd4f5deb7fffeca | 3,621,804 |
import requests
def _nanuq_get(url, username="", password="", logprefix=""):
"""returns an open request object to a NANUQ download"""
# nanuq has a non-standard form auth
log.info("%s GET %s (username=%s)", logprefix, url, username or "")
if username:
r = requests.post(url, data={'j_username'... | 96e7351bb452f23e87558a1257eccff99099b09b | 3,621,805 |
def initMap(llCrds,urCrds,figsize=(16,16)):
"""
Function for initializing a figure using a cartopy map projection.
Parameters
----------
llCrds : tuple
Tuple of (lat,lon) at the lower left corner of the desired
domain.
urCrds : tuple
Tuple of (lat,lon) at the up... | 16ea6ca2437ebad1e8277e53a0687ad57bb9cfc7 | 3,621,806 |
def validate(number):
"""Check if the number provided is a valid NCF."""
number = compact(number)
if len(number) != 19:
raise InvalidLength()
if number[0] not in 'AP' or not number[1:].isdigit():
raise InvalidFormat()
if number[9:11] not in (
'01', '02', '03', '04', '11',... | 90622ec2597d25de7e354a637db7bd9e733a3f21 | 3,621,807 |
def pressure_broad_coefs(Te):
"""
Defines the values of the constants :math:`a` and :math:`\\gamma` that go into the collisional broadening formula
of Salgado et al. (2017).
:param Te: Electron temperature.
:type Te: float
:returns: The values of :math:`a` and :math:`\\gamma`.
:rtype: l... | 0e5e18bd444721eab783ad499fcef6d5061129c8 | 3,621,808 |
from typing import Union
def parse_sources(sources: dict) -> Union[SourcesV1, SourcesV2, SourcesV3]:
"""Parse sources.json
Args:
sources: A dict of sources.json
Returns:
Union[SourcesV1, SourcesV2, SourcesV3]
"""
dbt_schema_version = get_dbt_schema_version(artifact_json=sources)
... | a0d7d1b2b5fed6671bea17ddb65c8da27808548c | 3,621,809 |
def _get_indices_from_highest(highest_indices):
"""Return a list of coordinates from a set of highest indices.
Parameters
----------
highest_indices : list, tuple, or numpy.ndarray
Highest indices to consider.
Returns
-------
indices : numpy.ndarray
An array of indices sort... | ecc1acf6c341c148b6edfadf7737dd6d5e3fdb4b | 3,621,810 |
def reports_ovc_rawdata(request):
"""Method to do adhoc pivot reports."""
try:
ext = 'Pivot'
# time_now = int(datetime.now().strftime('%H'))
user_id = request.user.id
report_variables = get_variables(request)
if request.method == 'POST':
ext = request.POST.get... | 2ece9fa8d6adf7136d985194efabf65b3363a516 | 3,621,811 |
def get_buggy_path(error_path):
"""
return list buggy path.
"""
error_path_list = []
f = open(error_path, 'r')
lines = f.readlines()
for line in lines:
if '---' in line:
path = line.split('::')
buggy_path = path[0].split('---')[-1].strip().replace('.', '/')
... | 0a6094297eb1613462b5184d74e865fe8c813c93 | 3,621,812 |
def get_config(arguments=None, events=None):
"""
Retruns a pre-formatted configuration block for supervisor
"""
if arguments is None:
arguments = ''
if events is None:
events = 'PROCESS_STATE'
configuration_string = '''
[eventlistener:logstash-notifier]
command = ./logstash_not... | cf548a31393a05a4f7a474b193e5752c5406233d | 3,621,813 |
def sieve_of_eratosphenes(n: int) -> list[int]:
"""
Finds prime numbers <= n using the sieve of Eratosphenes algorithm.
:param n: the upper limit of sorted list of primes starting with 2
:return: sorted list of primes
Integers greater than 2 are considered good input that gives
meaningful ... | 4dbfdffe0ff6e360361daccdcd39fb7fb3d09a03 | 3,621,814 |
def load_test_set(
filename=DATA_FILE,
add_target=True,
target_species=DEFAULT_TARGET):
"""Load the test set"""
df = load_data(filename, add_target, target_species)
train, test = get_train_test_split(df)
return test | 2eadc2d9f7d7924463db7ae8f5874b4f1e3170a2 | 3,621,815 |
from datetime import datetime
def create_observation(host_since, property_type, room_type, accommodates,
bathrooms, bed_type, cancellation_policy, cleaning_fee,
city, host_identity_verified, instant_bookable,
review_scores_rating, zipcode, bedrooms,... | 2203afcf23fa32f1173c59284e4029ee9453bfd4 | 3,621,816 |
from typing import List
from typing import Tuple
from typing import Callable
import logging
import random
def gibbs_sampling_inference(factor_graph: FactorGraph,
sample_pool: List[Tuple[int]],
num_samples: int, init_temp: float,
an... | b2356193fe71509a1bd079767994f9aa1f42d697 | 3,621,817 |
import argparse
import sys
def __get_arguments():
"""Parse command line arguments"""
argument_parser = argparse.ArgumentParser(
description='Handle YAML and JSON config files')
argument_parser.add_argument(
'-v', '--verbose',
action='store_true',
help='Verbose output')
... | 0b6a50aab249e84264eedbc2283d127efa7e4704 | 3,621,818 |
from typing import Tuple
from typing import Optional
from pathlib import Path
import configparser
def update_ansible_vars(version: Tuple[str, str, str], dry_run: bool = False) -> Optional[str]:
"""
Updates the ansible project variables file with the new release number
:param version: Release number tuple... | f85fff9292d1a4664a673d466d598f4dbd85b933 | 3,621,819 |
import unittest
def net():
"""Run all network tests"""
suite = ServiceTestSuite()
suite.addTest(unittest.makeSuite(AttributeTestCase, 'test_net'))
return suite | 0901faf9cd3d753341cb48a303df30b7fe94eaff | 3,621,820 |
def xor_decipher(text, key):
"""
Decipher a message using XOR.
text -- a list of integers corresponding to the ASCII value of characters.
key -- a list of characters used as keys.
"""
deciphered = []
key_length = len(key)
key_ascii = [ord(_k) for _k in key]
for i, _ascii in enumerate... | 99edcb7a08f9c22772305d70f5d4830828c2bbbf | 3,621,821 |
import os
def itkElastix_MDR_coregistration(target, source, elastix_model_parameters, image_parameters):
"""
This function takes unregistered source image and target image as input
and returns ffd based co-registered image and corresponding deformation field.
"""
shape_source = np.shape(... | 9c86b70a06861dd69d8333f13aab06603597c1cb | 3,621,822 |
from datetime import datetime
import time
def _create_signed_certificate(ca_cert, ca_key, name, valid_days=365, type='client', **kwargs):
"""
Creates signed cert of type provided and signs it with ca_key provided. To create subject for the new certificate
common name is set new value, rest of the attribut... | 2afe13a4223f78755e9556280172e943d2860a28 | 3,621,823 |
def _get_expanded_variable_list(var_list):
"""Given an iterable of variables, expands them if they are partitioned.
Args:
var_list: An iterable of variables.
Returns:
A list of variables where each partitioned variable is expanded to its
components.
"""
returned_list = []
for variable in var_l... | 4baae6fbdb145ecc09c42090fcca26298cddcd61 | 3,621,824 |
import fcntl, termios, struct, os
def get_terminal_size() -> (int, int):
"""
Get size of the terminal in symbols and lines.
:return: height (lines), width (symbols)
"""
def ioctl_GWINSZ(fd):
try:
cr = struct.unpack(
"hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "12... | c06b40c7a19268bfae85d73bbf20f295f468eeba | 3,621,825 |
import string
import random
def name_generator(size=9, chars=string.ascii_uppercase + string.digits):
"""
this method is for generating a randndom name for the downloaded files
@param size: number of random characters
@param chars: type of the random characters
"""
return ''.join(random.choice... | afe91c39ed5d985f93e1aa4ab72bf7ff7c1b75e0 | 3,621,826 |
def recovery_secret_to_ksk(recovery_secret):
"""Turn secret and salt to the URI.
>>> recovery_secret_to_ksk("0123.4567!ABCD")
'KSK@babcom-recovery-0123.4567!ABCD'
"""
if isinstance(recovery_secret, bytes):
recovery_secret = recovery_secret.decode("utf-8")
# fix possible misspellings... | a8832a9e970e4728dcb5f779fd4463abf142e69e | 3,621,827 |
from methylprep import Manifest, ArrayType
def plot_beta_by_type(beta_df, probe_type='all', return_fig=False, silent=False, on_lambda=False):
"""compare betas for type I and II probes -- (inspired by the plotBetasByType() function)
Plot the overall density distribution of beta values and the density distribution... | 340a706faa3704a4465aae05d74da3f80756a142 | 3,621,828 |
import click
from datetime import datetime
def validate_end_date(ctx, param, value):
"""
Validator for the 'click' command line interface, checking whether the entered date as argument 'start_date' is
later than argument 'end_date' and 'end_date' argument is later than current date.
"""
# option w... | b1416fdc614aad53ffab537275b7ae2cb15eddce | 3,621,829 |
def transform_uppercase(val, mode=None):
"""
Convert to uppercase
<dotted>|uppercase string to uppercase
<dotted>|uppercase:force string to uppercase or raises
"""
try:
return val.upper()
except TypeError:
if mode == 'force':
raise
return v... | f043674932bf900c0654b1be64ac80b6f4ec54fa | 3,621,830 |
import glob
def get_installer_packages(installer_dirs):
"""
Returns a list of nipkg files in the provided directories.
:param installer_dirs: List of directories containing nipkgs.
:return The list of nipkg files.
"""
installers = []
for dir in installer_dirs:
packages = glob... | 60b85fdaff214d287d8673df71389159484f943a | 3,621,831 |
def get_H2_surface_density_error(co_error: np.array, inclination: int) -> np.array:
"""Calculate the error on the H2 surface density from the CO emission maps from Heracles, this follows Leroy, et al. 2008/2009
Args:
co_error (np.array): error on the CO emission in [K km/s]
inclination (int): i... | 04f1a14435d1e60ebfcd521723120739a2ee37df | 3,621,832 |
from typing import Mapping
def _copy_object(obj: Mapping):
"""
Performs a deep copy of a Mapping.
Converts to a basic dict to avoid problems with kopf Body mapping type.
Pykube expects json-serializable types, i.e. basic types.
"""
new_obj = deepcopy(dict(obj))
for key in [
"resour... | dcf1e30142469986acc95ed0b1513aeaf077dbd2 | 3,621,833 |
def dmoist_bdz(th, th_ref, p, q_v, q_cl, z, zn, thresh = 1.0e-5):
"""
Vertical Gradient of (buoyancy including cloud condensation).
Derived variable name: dmoist_bdz
MONC approximation.
This is db/dz with b = beta_t theta_l + beta_q q_t.
Note - not to be used for vertical buoyancy flux.
P... | fc369a2a9789a32ce3122f8e3a022e6b49dd895a | 3,621,834 |
def tag_list(page=None):
"""
标签列表
"""
if page is None:
page = 1
page_data = Tag.query.order_by(
Tag.addtime.desc()
).paginate(page=page, per_page=3)
return render_template('admin/tag_list.html', page_data=page_data) | 922128c0e4130e116475b17bd52fdd16fa824e0a | 3,621,835 |
from typing import Union
def _parse_handler(handler: Union[callable, object, Subscriber]):
"""Parse handler name and body.
Function accept functions, callable object and instance of Subscriber.
If Subscriber has been given, parser will extract its name and handler.
:param handler: Function or callab... | f68fc8609058b38790a3a25bc2df9653c18d8a96 | 3,621,836 |
def string_pair_list_to_dictionary_no_json(spl):
"""
Covert a mongodb_store_msgs/StringPairList into a dictionary, ignoring content
:Args:
| spl (StringPairList): The list of (key, value) to pairs convert
:Returns:
| dict: resulting dictionary
"""
return dict((pair.first, pair.s... | fdcaa23eed195d389456a6ceb0fdde2d06d932d6 | 3,621,837 |
import re
def sanitize(inStr):
"""Hide any sensitive info from the alert"""
# Key-value pairs of patterns with what to replace them with
patterns = {
"https\:\/\/oauth2\:[\d\w]{64}@gitlab\.pavlovia\.org\/.*\.git": "[[OAUTH key hidden]]" # Remove any oauth keys
}
# Replace each pattern
... | 62c55f7d0af7c458d66e426fc9366c8ec84379df | 3,621,838 |
def str2dict(s):
"""Convert a "foo=bar, blah=baz" type string into a dictionary"""
if type(s) not in (str, unicode):
s = str(s)
d = {}
for kv in [[x.strip() for x in i.split('=', 1)] for i in s.split(',')]:
if (len(kv[0]) > 0) and (len(kv[1]) > 0):
d[kv[0]] = kv[1]
retur... | 2ce80c4f0da1d0b4487f7806778c5a3e11ef78db | 3,621,839 |
def get_techniques_of_tactic(tactic, techniques):
"""Given a tactic and a full list of techniques, return techniques that
appear inside of tactic
"""
techniques_list = []
for technique in techniques:
for phase in technique['kill_chain_phases']:
if phase['phase_name'] == tact... | 15efe8788bc4e45170f9d02c452482422ec8cf9f | 3,621,840 |
def unabc(msg):
"""
Add dummy methods to a class to satisfy abstract base class constraints.
Usage::
@unabc
class NotAbstract(SomeAbstractClass):
pass
@unabc('Fake {}')
class NotAbstract(SomeAbstractClass):
pass
"""
# Handle the possibility... | 3101fe4284b2695e76a8d4481ebcf12ee1b55055 | 3,621,841 |
def extract_logic_free_variables(expression):
"""Extract variables from expression assuming it's in logic format.
Parameters
----------
expression : Expression
Returns
-------
OrderedSet
set of all free variables in the expression.
"""
efvw = ExtractFreeVariablesWa... | 4a9c846795070a2a7a20e9547a2b6f212925b801 | 3,621,842 |
import sys
def inNativeByteOrder(im):
""" Put image in native byte order."""
if ((im.dtype.byteorder=='<') & (sys.byteorder=='big')) | ((im.dtype.byteorder=='>') & (sys.byteorder=='little')):
return im.byteswap(inplace=True).newbyteorder()
else:
return im | ccb7c05f068c00de429a99ddc98f5876a0c5de5c | 3,621,843 |
import warnings
def train_val_test_split_adjacency(A, p_val=0.10, p_test=0.05, seed=0, neg_mul=1,
every_node=True, connected=False, undirected=False,
use_edge_cover=True, set_ops=False, asserts=False):
"""
Split the edges of the adjacency m... | 78bd771e0e4812e8978b3d736a69b22b6a73c938 | 3,621,844 |
def get_status(invocation_id):
"""check status
:param invocation_id: Id of image-building Invocation
:type invocation_id: str
:rtype: Invocation
"""
logger.debug(f"Checking status for invocation with ID {invocation_id}")
inv = invocation_service.load_invocation(invocation_id)
if not in... | 6f1b381e698c927c89e687cef41cdbf01b8a619a | 3,621,845 |
def odia_to_other_lang(text: str, dest_language_code: str = "en") -> str:
"""Translate from Odia to other language"""
return _hit_google_api(text, "or", dest_language_code) | c4989c6eac300f57f9ad45da53c6bc72fade5cb0 | 3,621,846 |
def _invoke_with_properties(callable_obj, all_props, environ, prop_defs,
arg_names, **additional_args):
"""Internal version of invoke_with_properties.
The main difference is it gets passed the argument names as `arg_names`.
This allows us to reuse this logic elsewhere, without definin... | 44a5dddf460d0a22ec67c2ca7d4ac88c1a4f6679 | 3,621,847 |
def initial_time():
"""
Real Name: b'INITIAL TIME'
Original Eqn: b'1960'
Units: b'Year'
Limits: (None, None)
Type: constant
b'The initial time for the simulation.'
"""
return 1960 | 7e731a15c0fa128c5c3858d98ae2f9ac0bc04ca8 | 3,621,848 |
import pickle
def get_y_eval(dataset_id):
"""
retrieves the y value of the eval set
:param dataset_id: id of the dataset
:return: y values
"""
#
return pickle.load(open(get_dataset_folder(dataset_id) + '/y_eval.pkl', 'rb')) | 15fc4892ade6b5661f4276535f081dc989fc8f0b | 3,621,849 |
import time
from typing import OrderedDict
import inspect
import pickle
def main():
"""Scripty bits"""
t0 = time.time()
kwargs = parse_args()
if "histo_data_dir" in kwargs:
histo_data_dir = expand(kwargs["histo_data_dir"])
if basename(histo_data_dir) != "histo_data":
hist... | 17ee583dceb569e462fbadd64747ea1ab99f679a | 3,621,850 |
def sourcecontrol_repos_repo_id_refs_get(repo_id): # noqa: E501
"""sourcecontrol_repos_repo_id_refs_get
# noqa: E501
:param repo_id: Source control repository identifier
:type repo_id: str
:rtype: None
"""
return 'do some magic!' | 880635586cca99cbd759f33ce5cfa6b8f56ee3eb | 3,621,851 |
from typing import Union
def duration_offpeak(
ts_left: Union[pd.Timestamp, pd.DatetimeIndex], freq: str = None
) -> Union[Q_, pd.Series]:
"""
Total duration of offpeak periods in a timestamp.
See also
--------
.tools.stamps.duration
"""
return duration_base(ts_left, freq) - duration_... | c0dfeb82477597d72c61a5d9073ad4827de749db | 3,621,852 |
def truncate_labels(labels):
"""
(1) replacing row[0] by 10, and move it to the last of row
(2) replace the second 10 by -1 row wise
"""
def do_one_row(row):
erase = False
for i, _ in enumerate(row):
if erase:
row[i] = -1
else:
... | 0cbf05f935ee12e123475ac58cfb47918ac9b4da | 3,621,853 |
import warnings
import math
def sample(problem, N, calc_second_order=True, seed=None, skip_values=1024):
"""Generates model inputs using Saltelli's extension of the Sobol' sequence.
Returns a NumPy matrix containing the model inputs using Saltelli's sampling
scheme. Saltelli's scheme extends the Sobol' s... | af179d538a9ab51a07332199fe37573c5f6a6535 | 3,621,854 |
def create_wall(obj_name, document):
"""Create a wall."""
obj = document.addObject('Part::FeaturePython', obj_name)
origin = document.addObject('App::Origin', 'WallOrigin')
Wall(obj, origin)
WallViewProvider(obj.ViewObject)
return obj | b2352fc4dff59f1854cdce3eec73cef83d1ba557 | 3,621,855 |
def prepare_roi(image5d, roi_size, roi_offset):
"""Extracts a region of interest (ROI).
Calls :meth:`prepare_subimage` but expects size and offset variables to
be in x,y,z order following this software's legacy convention.
Args:
image5d: Image array as a 5D array (t, z, y, x, c), or 4D if
... | 867c33140b9413434e442025599562369a489443 | 3,621,856 |
import torch
import os
def get_model_summary(model, *input_tensors, item_length=26, verbose=False):
"""
:param model:
:param input_tensors:
:param item_length:
:return:
"""
summary = []
ModuleDetails = namedtuple(
"Layer", ["name", "input_size", "output_size", "num_parameters", "multiply_adds"])
hooks = ... | 5843e0596a5573753d61a4ca8791394c1359afcc | 3,621,857 |
from arbiter.async import run_tasks
from arbiter.task import create_task
def test_no_dependencies():
"""
run dependency-less tasks (with threads)
"""
executed_tasks = set()
def make_task(name, dependencies=(), should_succeed=True):
"""
Make a task
"""
function = ... | 66ac6963eaee611dc1613fb4f4308d78f0ef937e | 3,621,858 |
import json
def decode(s):
"""
Deserialize a DMRS object from a DMRS-JSON string.
"""
return from_dict(json.loads(s)) | 340f5a184a565de06f7139158896127a9ddf91b8 | 3,621,859 |
import copy
def cross_multiply_array(array_1, array_2=None, axis=0):
"""Cross multiply the arrays along the given axis.
Cross multiplies along axis and computes array_1.conj() * array_2
if axis has length M then a new axis of size M will be inserted directly succeeding the original.
Parameters
-... | 0c27c8b27dd1d3cc4cc07bba4f9b211e725b2b95 | 3,621,860 |
from typing import Union
def Create(
allow_multiple=True,
) -> Union[ZeroOrMorePhraseItem, OptionalPhraseItem]:
"""\
('@' <name> <<Arguments>>? <newline>?)*
- or -
('@' <name> <<Arguments>>? <newline>?)? # If 'allow_multiple' is False
"""
phrase_item = PhraseItem.Create(
... | 0e783eceaf3f1f206a9ed3d72af82a85800c2b7e | 3,621,861 |
def return_largest_region(image_bin):
"""Returns the largest region in the input image.
Parameters
----------
image_bin : (M, N) ndarray
A binary image.
Returns
-------
image_bin : (M, N) ndarray
The input binary image containing only the largest region.
"""
props =... | 40f6745b0908c7ee08c1563f3991a5e7880c720e | 3,621,862 |
def stretchedAmplitude(TA_file, pol_time, peak_min, peak_max, time_zero=None):
"""Takes in TA data and picks out the peak for the polaron state and returns
the average value so it can be used for fitting function. Must make sure to
pick the right energy range, peak_min and max are in eV."""
TA = np.loa... | 8f734bf778f0a1e768ab35acd1fc7b8a39eb3183 | 3,621,863 |
def _write_rollup_config(
ctx,
root_dir,
filename = "_%s.rollup.conf.js",
downlevel_to_es2015 = False):
"""Generate a rollup config file.
Args:
ctx: Bazel rule execution context
root_dir: root directory for module resolution (defaults to None)
filename: output ... | f9b8cf2621e0cf68f0bad9a02802c2500dda9b53 | 3,621,864 |
def raw_images_to_array(images):
"""
Decode and normalize multiple images from tfrecord data
:param images: list of images encoded as a png in a string
:return: a numpy array of size (N, 56, 56, channels), normalized for training
"""
image_list = []
for image_str in images:
image = d... | adac8756926ba92536ae4fdd0a7b32620d37d028 | 3,621,865 |
from typing import Dict
def create_model(model: str, config: Dict) -> object:
"""
Creates a model with a given configuration
Args:
model (str): name of the model
config (dict): dictionary of parameters
Returns:
(object): created model (HHVAEM, HMCVAEM, ...)
"""
if mod... | 19bdb172fb8890bee08ac63de929c213dc85996d | 3,621,866 |
import torch
def make_positions(tensor, padding_idx, onnx_trace=False):
"""Replace non-padding symbols with their position numbers.
Position numbers begin at padding_idx+1. Padding symbols are ignored.
"""
mask = tensor.ne(padding_idx).long()
return torch.cumsum(mask, dim=1) * mask + padding_idx | f59fad86a23ff76f184c0dd6a21a92722f4817f5 | 3,621,867 |
import requests
def get_song_list(playlist_url):
"""
This function get the song list in the form of "name creator" from the spotify page
"""
# validating the data
if not playlist_url.startswith("https://open.spotify.com"):
print("this is not a spotify url")
return []
elif play... | 10bc3b6f14cd93c9a4f525883c7a2d56f66bf234 | 3,621,868 |
import unittest
def makeTestSuiteV201101():
"""Set up test suite using v201101.
Returns:
TestSuite test suite using v201101.
"""
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(CustomTargetingServiceTestV201101))
return suite | 05b925b4bcdd38ab9a6e4b71374a6ff44fe8eb57 | 3,621,869 |
def add_bond_features(X_df):
"""
Using the information about standard C-H,N-H and O-H bond distances, we compute features
which aims to find a notion of deviation from the expected bond distances.
"""
assert len(set(['atom_1', 'atom_0', 'x_0', 'x_1', 'y_0', 'y_1', 'z_0', 'z_1']) - set(X_df.columns))... | 9798a97d9ebd308552334db64672ee23e8c6a666 | 3,621,870 |
def port_to_ip_mapping(index):
"""
A user defined mapping port_id (kni) to ipv4.
"""
return {"vEth0_{}".format(index): "192.167.10.{}".format(index + 1)} | 81d981bc8742e1295cb279d6b47d0e97f012b679 | 3,621,871 |
def quote():
"""Get stock quote."""
current_userid = session["user_id"]
userbalance = get_userbal(db, current_userid)
userstocks = get_userstock(db, current_userid)
stocklist = get_stocklist(db, stocksid=True, prices=True)
if request.method == "POST":
response = lookup(request.form.get("... | 506b0a2398269f73d6dc2e78f31ac5a9743cf01b | 3,621,872 |
from typing import OrderedDict
def cleanup_dataframe(df, logger=None):
"""Cleans the dataframe
- strips new lines, double, single quotes; None -> nan, etc
- formats the column names for Bigquery input
"""
if logger:
logger.log_text("Cleaning up the dataframe", severity='INFO')
... | 4fd7788bc5c99a220845d93a7c0549acbc67bdf6 | 3,621,873 |
import re
def organize_key(filename):
"""用于sorted的key参数"""
if filename[0:2].upper() == 'AD':
return 0
name = re.findall(r"-([0-9]+[A-Z]*).pdf", filename)[0]
num = get_group_index(filename)
alpha = name.replace(num, '')
if len(alpha) == 1:
return int(num)*100+ord(alpha)-64 # 使用... | eee3c3e9f0f967212e7f38ea8781291b4794ed38 | 3,621,874 |
def launch_svr(X, y, sample_weight=None, kernel='linear', C=1):
"""Fit the classification SVMs according to the given training data.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vectors.
y : array-like, shape (n_samples,)
Target values.
sample_weig... | 02ae4f86a6cac32e0af862cb24f6565f932e6729 | 3,621,875 |
def cancel_candidacy(request, candidacy):
"""Cancel your own, yet-unapproved candidacy."""
user = request.user
cd = get_candidacy(candidacy)
if user != cd.user:
return HttpResponseForbidden(u"Vous ne pouvez annuler que vos propres candidatures.")
m.JournalEntry.log(user, "Cancelled own appli... | 0a8f93934ccf3b530e6d27a5be1bad76798c7607 | 3,621,876 |
import random
def generate_rsa_keys(prime_lenth=4):
"""Return tuple of (open, close, mod)"""
start = 10 ** (prime_lenth-1)
end = (10 ** (prime_lenth)) - 1
p, q = get_generate_prime_pair(start=start, end=end)
n = p * q
print("p: {} q: {}".format(p, q))
print("n: {}".format(n))
eul... | 8c2e5b6b6d4db6d2667ac6e935c8a9ae429b28ef | 3,621,877 |
def cache_by_hashed_args(obj):
""" Decorator for caching a function values
.. deprecated:: v0.9.8.3
:func:`cache_by_hashed_args` will be removed in pyGSTi
v0.9.9. Use :func:`functools.lru_cache` instead.
"""
return lru_cache(maxsize=128)(obj) | 2fc95b7a248febd206703e48bdd0494dd0bca04d | 3,621,878 |
import numpy
def setBadRegions(exposure, badStatistic="MEDIAN"):
"""Set all BAD areas of the chip to the average of the rest of the exposure
Parameters
----------
exposure : `lsst.afw.image.Exposure`
Exposure to mask. The exposure mask is modified.
badStatistic : `str`, optional
... | 90b987039b13264ac205f28a12c90bb341e04a80 | 3,621,879 |
def humanize_list(elements):
""""
splits a list and add punctuations to it elements
"""
humanize_string = ''
if len(elements) > 1:
for element in elements:
if element == elements[len(elements)-2]: # second to last item
humanize_string = humanize_string + element.... | 3172ac89f763d7faca4ce31c41611ca6b6731896 | 3,621,880 |
import typing
def ark(row: typing.Mapping[str, str]) -> str:
"""The item ARK (Archival Resource Key)
Args:
row: An input CSV record.
Returns:
The item ARK.
"""
ark_prefix = "ark:/"
if row["Item ARK"].startswith(ark_prefix, 0):
return row["Item ARK"]
return ark_pre... | ea428fcddf26a5bfdad3ec1c4906e765b72b1f47 | 3,621,881 |
import os
def recon(sino, angles,
weights = None, weight_type = 'unweighted', init_image = 0.0, prox_image = None, init_proj = None,
num_rows = None, num_cols = None, roi_radius = None,
delta_channel = 1.0, delta_pixel = 1.0, center_offset = 0.0,
sigma_y = None, snr_db = 30.0, ... | 64089443aa836168edea1bf646e25359f65ba374 | 3,621,882 |
def common_member(a, b, natural_sort=True):
"""
Checks if two lists (or sets) have a common member, and if so, returns
the common members.
:param a: First list (or set)
:param b: Second list (or set)
:param bool natural_sort: Sort the resulting items naturally
(default: True)
:return: Tr... | 160f1429f412a52513be60d331d7cb15d03e64e7 | 3,621,883 |
import argparse
def parse_args():
"""
parse arguments
"""
parser = argparse.ArgumentParser(
description="PaddlePaddle Youtube Recall Model Example")
parser.add_argument(
'--infer_set_path',
type=str,
required=True,
help="path of the infer set")
parser.ad... | 2400acb7d9f8864eddf5b24d085e462b56de9de2 | 3,621,884 |
import copy
def transforms_description(f):
"""
Decorator which deepcopies the description and extracts ['rnn'][0] from it.
Desperately needs to be obsoleted.
"""
@wraps(f)
def wrapper(description, *args, **kwds):
description = copy.deepcopy(description)
try: desc = description[... | 04343be02ec049d98e548b378a5965adb929c61b | 3,621,885 |
async def close(ctx):
"""issueをcloseします。"""
try:
bot.close_issue(ctx.channel.id)
except ValueError:
return await ctx.send("issueがオープンされていません。", delete_after=5)
await ctx.message.add_reaction("\U0001f44d") | c6f6c9aac62855361d09f066f81344d13012ac3b | 3,621,886 |
import numpy as np
def read_data(fname, filter_params, time_windows, time_units, fps, is_manual_index):
"""
Reads the timeseries_data and the blob_features for a given file within every time window.
return:
timeseries_data_list: list of timeseries_data for each time window (length of lists = numbe... | aad55507d0bec581f072c173fb78f8fd1a470d8d | 3,621,887 |
def forecast(
precip,
velocity,
timesteps,
threshold,
extrap_method="semilagrangian",
extrap_kwargs=None,
slope=5,
):
"""
Generate a probability nowcast by a local lagrangian approach. The ouput is
the probability of exceeding a given intensity threshold, i.e.
P(precip>=thres... | 09bbeebdfe99277bdf8f77903d6d3e2fd812133e | 3,621,888 |
def train_svm(documents, ntesting=500):
"""
:param documents- politeness-annotated training data
:type documents- list of dicts
each document must be preprocessed and
'sentences' and 'parses' and 'score' fields.
:param ntesting- number of docs to reserve for testing
:type ntesting- ... | d756911708fd26116b990131cffaffc069cd6eb7 | 3,621,889 |
from typing import Union
from typing import Optional
from datetime import datetime
from typing import Sequence
def get_logs_for_action(
data: Union[LogData, pd.DataFrame],
log_action: str,
selected_day: Optional[datetime.date] = None,
rows: Optional[Union[str, int, Sequence[int]]] = None,
) -> Union[p... | 07d098ce6af982a1cc50a9d88121b84721bee181 | 3,621,890 |
import math
def is_mc_multiplier(multiplier, modulus):
"""
Checks if multiplier is a MC multiplier w.r.t. modulus.
:param multiplier: an integer in (0, modulus).
:param modulus: a prime number.
:return: True if multiplier is a MC multiplier w.r.t. modulus.
"""
return (modulus % multiplier)... | 6d210f8de081ae0a468692b2f93e5145170917e9 | 3,621,891 |
from typing import List
from typing import Container
async def buckets_get(buckets: Buckets = Depends(Provide[Container.buckets])) -> List[Bucket]:
""" returns all buckets configured """
return buckets.get_all() | 3f8d4a9db3a3648b00f79ba4a9108aef554415c2 | 3,621,892 |
def group_without_decoys(peptides, target_column, proteins):
"""Retrieve the protein group with a target-only FASTA.
Build a dictionary mapping the decoy peptides to a plausible unique
target peptide. Then proceed to map as with the targets.
Parameters
----------
peptides : pandas.DataFrame
... | 57c528aef970855a3cdce029d1c101485d5e401f | 3,621,893 |
from typing import Any
def get_endpoint_stats(netid: str, client: ShrunkClient) -> Any:
"""``GET /api/stats/endpoint``
Returns visit statistics for each Flask endpoint. Response format:
.. code-block:: json
{ "stats": [ { "endpoint": "string", "total_visits": "number", "unique_visits": "number" ... | b4d0d22ad0014da66fd1b99448d6fcf863071eeb | 3,621,894 |
import requests
import jsonschema
def create_project(project, notify_user=True):
"""
Create an OpenLDAP project.
Args:
project (Project): Project instance - required
notify_user (bool): Issue a notification email to the project technical lead? - optional
"""
url = ''.join([setting... | 022ab097e9df0be19def36fc9a418a1bf8d976ac | 3,621,895 |
def readToTuple(f_path):
"""Reads in a two-col file (tab-delim) and returns a list of tuples"""
f = open(f_path)
ls = []
for l in f:
if l.startswith("#"):
continue
ls.append(tuple(l.strip().split("\t")))
return ls | 726d1b4a4682c4e11afbf59e342340e0cf5ccc63 | 3,621,896 |
from typing import List
from typing import Tuple
import tqdm
def _preprocess_file(input_file: str, lang: str) -> List[Tuple[List[str]]]:
"""
Performs initial preprocessing, i.e., urls formatting, removal of "_trans" from Ru set
Args:
input_file: path to a file in google TN format
lang: da... | 8dfdba600ed2efe419983e90f2a7b7e7355bd534 | 3,621,897 |
def pod_status(logger, pod):
"""
Check health of a pod and returns it's status as result
"""
result = {'criteria': 'pass',
'name': pod.metadata.name,
'namespace': pod.metadata.namespace,
'node': pod.spec.node_name}
if pod.status.container_statuses is None:
... | eebb694420ab7ab3d613ddd97bc78087c47887e7 | 3,621,898 |
from .methods import FaceNet
from .methods import GoogleNet
from .methods import AlexNet
from .methods import SqueezeNet
from .methods import VGGFace
from .methods import OpenFace
from .methods import FaceRecognition
def predict(image, method_name, **kwargs):
"""
Get descriptor of image with an specific metho... | ea6de2b4bdfd70a079ea911f78239cf26641e4cd | 3,621,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.