content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def connect_registry_client():
"""
connect the module client for the Registry implementation we're using return the client object
"""
client = adapters.RegistryClient()
client.connect(environment.service_connection_string)
return client | f2e2bccb4cfacd86af36e3924463541d9e3dcdcd | 3,654,159 |
def get_group_average_score(gid=None, name=None):
"""
Get the average score of teams in a group.
Args:
gid: The group id
name: The group name
Returns:
The total score of the group
"""
group_scores = get_group_scores(gid=gid, name=name)
total_score = sum([entry['scor... | cdea61e388b47f399fbc8e228e313d6199164b2f | 3,654,160 |
def solve_with_cdd_for_II(A, verbose=False):
"""This method finds II's minmax strategy for zero-sum game A"""
m = A.shape[0] # number of rows
n = A.shape[1] # number of columns
A = np.column_stack([[0]*m,-A,[1]*m])
I = np.eye(n)
nn = np.column_stack([[0]*n,I,[0]*n])
# non-negativity cons... | 87ac90691fcbbe2f89bf9090c31f86c165c007ed | 3,654,161 |
def build_none() -> KeySetNone:
"""Returns NONE."""
return KeySetNone() | 8ba38204cd763597c66d51466f5d2ffa5c9a19bf | 3,654,162 |
import csv
import numpy
def load_csv(file, shape=None, normalize=False):
"""
Load CSV file.
:param file: CSV file.
:type file: file like object
:param shape : data array is reshape to this shape.
:type shape: tuple of int
:return: numpy array
"""
value_list = []
for row in cs... | 07f3b61bbdb6c9937f3cc4b0ae98fdfb7d8de48a | 3,654,163 |
from typing import Tuple
def flip_around_axis(
coords: np.ndarray,
axis: Tuple[float, float, float] = (0.2, 0.2, 0.2)
) -> np.ndarray:
"""Flips coordinates randomly w.r.t. each axis with its associated probability."""
for col in range(3):
if np.random.binomial(1, axis[col]):
... | 914834a8492998b4e1e0b93e5e9677ec9af2d736 | 3,654,164 |
import math
def get_tc(name):
"""Determine the amount of tile columns to use."""
args = ["ffprobe", "-hide_banner", "-select_streams", "v", "-show_streams", name]
proc = sp.run(args, text=True, stdout=sp.PIPE, stderr=sp.DEVNULL)
lines = proc.stdout.splitlines()
d = {}
for ln in lines[1:-1]:
... | ee917cd8cebfe7dc4ae718d883c657cf23bff1cf | 3,654,165 |
def cmap_hex_color(cmap, i):
"""
Convert a Colormap to hex color.
Parameters
----------
cmap : matplotlib.colors.ListedColormap
Represents the Colormap.
i : int
List color index.
Returns
-------
String
Represents corresponding hex string.
"""
return ... | 9ac7753cde9470e3dd9fbd4a66373b25126635ca | 3,654,167 |
def train_folds(X, y, fold_count, batch_size, get_model_func):
""" K-Fold Cross-Validation for Keras Models
Inspired by PavelOstyakov
https://github.com/PavelOstyakov/toxic/blob/master/toxic/train_utils.py
"""
fold_size = len(X[0]) // fold_count
models = []
for fold_id in range(0, fold_co... | 51a38243925c76ac6179a90be46be31fcb685054 | 3,654,168 |
async def cancel(command: HALCommandType, script: str):
"""Cancels the execution of a script."""
try:
await command.actor.helpers.scripts.cancel(script)
except Exception as err:
command.warning(text=f"Error found while trying to cancel {script}.")
return command.fail(error=err)
... | 438297845f5ba4ffc49b95a798adf61294371694 | 3,654,170 |
def get_nodes_by_betweenness_centrality(query_id, node_number):
"""Get a list of nodes with the top betweenness-centrality.
---
tags:
- query
parameters:
- name: query_id
in: path
description: The database query identifier
required: true
type: integer
... | 44d97e443c6bef4d7048496674a2382a6c4f2ade | 3,654,171 |
import sympy
def preprocess(function):
"""
Converts a given function from type str to a Sympy object.
Keyword arguments:
function -- a string type representation of the user's math function
"""
expr = function
while True:
if '^' in expr:
expr = expr[:expr.index('... | 001bd04d27db2afa4debbe776e5fe3cf1af1476d | 3,654,172 |
import re
def tot_changes(changes: str) -> int:
"""Add deletions and insertions."""
insertions_pat = re.compile(r"(\d+) insertion")
deletions_pat = re.compile(r"(\d+) deletion")
insertions = insertions_pat.search(changes)
insertions = int(insertions.group(1)) if insertions else 0
deletions =... | 74742baf63db51b5c59b332f0104008500f330b9 | 3,654,173 |
def update_from_mcd(full_table, update_table):
# type: (pd.DataFrame, pd.DataFrame) -> pd.DataFrame
"""
Update the full table (aka the PDG extended-style table) with the
up-to-date information from the PDG .mcd file.
Example
-------
>>> new_table = update_from_mcd('mass_width_2008.fwf', 'ma... | c60daea5719445fb696ef21bbc0f233fea4e48cd | 3,654,174 |
import socket
def resolve_hostname(host):
"""Get IP address of hostname or URL."""
try:
parsed = urlparse.urlparse(host)
except AttributeError as err:
error = "Hostname `%s`is unparseable. Error: %s" % (host, err)
LOG.exception(error)
raise errors.SatoriInvalidNetloc(error)... | 1792d943e490661b4dd42608f2b025096810688f | 3,654,175 |
import pandas as pd
import numpy as np
from .data_utils import keep_common_genes
from .data_utils import df_normalization
def DeconRNASeq_main(rna_df, sig_df, patient_IDs='ALL', args={}):
"""
This function does the following:
- parses the dictionary 'args' for the arguments to pass on to the DeconRNAS... | 44bf01b0d53110610d3219e3002cca0ab35720b5 | 3,654,176 |
import re
from typing import OrderedDict
def parse_c_interface(c_interface_file):
"""
@brief Parses a c-interface file and generates a dictionary of function names to parameter lists.
Exported functions are expected to be preceded by 'DLL_EXPORT'. Python keywords should not be used as variable
names f... | 06a4edb40e12343cda688da82c9042d1342e6429 | 3,654,177 |
def con_minimize(fun, bounds, constr=(), x0=None, args=(),
callback=None, options={}, workers=None):
"""Constrained minimization of `fun` using Genetic Algorithm.
This function is a wrapper over modetga.minimize().
The constraints are defined as a tuple of functions
(`fcon1(x, *args)`, `... | 46a7400953e54dfb9b2364832e6029a508acc9de | 3,654,178 |
def unique_v2(lst):
"""
Returns a list of all unique elements in the input list "lst."
This algorithm runs in o(n), as it only passes through the list "lst" twice
"""
dd = defaultdict(int) # avoids blank dictionary problem (KeyError when accessing nonexistent entries)
unique_list = []
for va... | d7c5706908d569b3ee93ba1bebbd09bc6f335ad2 | 3,654,179 |
import ipaddress
def is_ip_network(network, strict=False):
"""Returns True/False if a string is a valid network."""
network = str(network)
try:
ipaddress.ip_network(network, strict)
return True
except ValueError:
return False | 84206586412b76816fa845a75fc6c121bfdf0989 | 3,654,180 |
def assign_point_of_contact(point_of_contact):
"""
Assign a user to be the point of contact in emails/letters
:param point_of_contact: A string containing the user_guid if point of contact has been set for a request
:return: A User object to be designated as the point of contact for a request
"""
... | 99f2e7d036c4f7cf71be2bd6b82a313f26b3af41 | 3,654,181 |
def response_with_pagination(guests, previous, nex, count):
"""
Make a http response for GuestList get requests.
:param count: Pagination Total
:param nex: Next page Url if it exists
:param previous: Previous page Url if it exists
:param guests: Guest
:return: Http Json response
"""
... | 00373c866b6cc8384a88e62b63fcaa5950ccc1c1 | 3,654,182 |
def put_object(request, old_pid):
"""MNStorage.update(session, pid, object, newPid, sysmeta) → Identifier."""
if django.conf.settings.REQUIRE_WHITELIST_FOR_UPDATE:
d1_gmn.app.auth.assert_create_update_delete_permission(request)
d1_gmn.app.util.coerce_put_post(request)
d1_gmn.app.views.assert_db.... | 192ed2a7efc35baf28605de9db594319370f294d | 3,654,183 |
def _match_gelu_pattern(gf, entry_node):
""" Return the nodes that form the subgraph of a GELU layer
"""
try:
if not len(entry_node.outputs) == 3:
return None
pow_1, add_2, mul_3 = [gf[x] for x in entry_node.outputs]
if not (pow_1.op == 'Pow' and add_2.op == 'Add' and mul... | 6e08578a9cb9bea96c939a4fbee31003d6c575d4 | 3,654,184 |
def assign_obs_error(param, truth_mag, band, run):
"""
Assign errors to Object catalog quantities
Returns
-------
obs_err : float or np.array
The error values in units defined in get_astrometric_error(), get_photometric_error
err_type : str
Type of observational error
... | 9a90b80755941ac19cbf023f7ee63f4650518242 | 3,654,185 |
from typing import List
from typing import Tuple
import tokenize
def dir_frequency(dirname: str, amount=50) -> List[Tuple[str, int]]:
"""Pipeline of word_frequency from a directory of raw input file."""
md_list = md.collect_md_text(dirname)
return compute_frequency(tokenize(normalize(" ".join(md_list))), ... | 3daddb1930e80235887b51ed5918e9d7cb1fff71 | 3,654,186 |
def test_solver1(N, version='scalar'):
"""
Very simple test case.
Store the solution at every N time level.
"""
def I(x): return sin(2*x*pi/L)
def f(x,t): return 0
solutions = []
# Need time_level_counter as global variable since
# it is assigned in the action function (that makes
... | 7c74b3f731c0aa613c7a9f8da82533c1239a574f | 3,654,187 |
import requests
def get_auth_data():
"""
Create auth data.
Returns:
return: access token and token expiring time.
"""
payload = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'client_credentials',
}
api_url = '{0}/oauth/access_toke... | ecd921c1ef3639c388111ec5952c887867076d99 | 3,654,188 |
def datatable(module, tag):
"""Mapping for DataTable."""
if tag == "DataTable":
return module, tag | 1eaa06771ecdd99dfa102ec249b23db3999b6fd7 | 3,654,189 |
def remove_prepending(seq):
"""
Method to remove prepending ASs from AS path.
"""
last_add = None
new_seq = []
for x in seq:
if last_add != x:
last_add = x
new_seq.append(x)
is_loopy = False
if len(set(seq)) != len(new_seq):
is_loopy = True
... | 78bb1554678af0998e15ecf9ed8f4e379ac2e2ad | 3,654,190 |
def github_handle_error(e):
"""
Handles an error from the Github API
an error example: Error in API call [401] - Unauthorized
{"message": "Bad credentials", "documentation_url": "https://docs.github.com/rest"}
The error might contain error_code, error_reason and error_message
The error_reason an... | 1b3d7ef6756c02d7bf1b8db506dbf926dd3e6abd | 3,654,191 |
def netmask_to_bits(net_mask):
""" Convert netmask to bits
Args:
net_mask ('str'): Net mask IP address
ex.) net_mask = '255.255.255.255'
Raise:
None
Returns:
Net mask bits
"""
return IPAddress(net_mask).netmask_bits() | 7ecc069e14242ebffd840b989331a431f6c2ecbc | 3,654,192 |
def register_corrector(cls=None, *, name=None):
"""A decorator for registering corrector classes."""
def _register(cls):
if name is None:
local_name = cls.__name__
else:
local_name = name
if local_name in _CORRECTORS:
raise ValueError(f'Already registered model with name: {local_name}... | 90795496caff7958af52bbe1518582a2a2ceea73 | 3,654,193 |
import numpy
def _sample_perc_from_list(lst, perc=100, algorithm="cum_rand", random_state=None):
"""
Sample randomly a certain percentage of items from the given
list. The original order of the items is kept.
:param lst: list, shape = (n,), input items
:param perc: scalar, percentage to sample
... | 4ec000e9bd8f5e10550040e49018e2a045659397 | 3,654,194 |
def irods_setacls(path, acl_list, verbose=False):
"""
This function will add the ACLs listed in 'acl_list'
to the collection or data object at 'path'.
'acl_list' is a list where each element itself is
a list consisting of the username in name#zone format,
and the access level ('read', 'write', ... | 5727d6ff96e2d693323d5d88ed81eafbd4de0435 | 3,654,195 |
from datetime import datetime
def add_years(date_to_change, years):
"""
Return a date that's `years` years after the date (or datetime)
object `date_to_change`. Return the same calendar date (month and day) in the
destination year, if it exists, otherwise use the following day
(thus changing Febru... | e9b71d190f7629a3edc0902d0582005a26a33956 | 3,654,196 |
def concurrency_update_done(client, function_name, qualifier):
"""wait fn for ProvisionedConcurrencyConfig 'Status'"""
def _concurrency_update_done():
status = client.get_provisioned_concurrency_config(
FunctionName=function_name, Qualifier=qualifier
)["Status"]
if status ==... | 4d168e4e9648c3a3d8cb149aad1e835362bd271a | 3,654,197 |
def googleapis_email(url, params):
"""Loads user data from googleapis service, only email so far as it's
described in http://sites.google.com/site/oauthgoog/Home/emaildisplayscope
Parameters must be passed in queryset and Authorization header as described
on Google OAuth documentation at:
http://gr... | c6123e367f093a512ac17797da487e733503dc11 | 3,654,198 |
def max_pool_2x2(input_):
""" Perform max pool with 2x2 kelner"""
return tf.nn.max_pool(input_, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') | b85ccfaafbdcf5d703dffab65e188ffab52ebce9 | 3,654,201 |
import tqdm
def remove_numerals(df, remove_mixed_strings=True):
"""Removes rows from an ngram table with words that are numerals. This
does not include 4-digit numbers which are interpreted as years.
Arguments:
df {Pandas dataframe} -- A dataframe of with columns 'word', 'count'.
Keyword ... | 4c3d0468456e08b1a0579a8b73a21221cae17676 | 3,654,202 |
def b32_ntop(*args):
"""LDNS buffer."""
return _ldns.b32_ntop(*args) | b43bc9b1b112f7815ec3c280d055676e7255adcc | 3,654,204 |
from typing import Callable
from typing import Dict
import torch
def infer_feature_extraction_pytorch(
model: PreTrainedModel, run_on_cuda: bool
) -> Callable[[Dict[str, torch.Tensor]], torch.Tensor]:
"""
Perform Pytorch inference for feature extraction task
:param model: Pytorch model (sentence-trans... | 18f935607c824c2122f68ea1ec9a7bcb50604ac8 | 3,654,206 |
def editRole(userSource, oldName, newName):
"""Renames a role in the specified user source.
When altering the Gateway System User Source, the Allow User Admin
setting must be enabled.
Args:
userSource (str): The user source in which the role is found.
Blank will use the default use... | f72796de14ff5f8c4314a5d31fe4fcf42cb883ec | 3,654,207 |
def beam_hardening_correction(mat, q, n, opt=True):
"""
Correct the grayscale values of a normalized image using a non-linear
function.
Parameters
----------
mat : array_like
Normalized projection image or sinogram image.
q : float
Positive number. Recommended range [0.005, ... | d113ff33c2d688f460cf2bac62cdd8a26b890ce5 | 3,654,210 |
def cargar_recursos_vectores_transpuestos():
"""
Se carga la informacion para poder calcular los vectores transpuestos
"""
# Se crea el df
filename = 'csv/' + conf.data['env']['path'] + '/vectores_transpuestos.csv'
recursos_v_transpuestos = pd.read_csv(filename)
# Se cambia el nombre de los ... | f982fd22bbdfd2d7d389787bf7f923feb9abf66f | 3,654,211 |
def read_pdb(file_name, exclude=('SOL',), ignh=False, modelidx=1):
"""
Parse a PDB file to create a molecule.
Parameters
----------
filename: str
The file to read.
exclude: collections.abc.Container[str]
Atoms that have one of these residue names will not be included.
ignh: ... | d7412b96adef5505676a80e5cdf3fe5e63a3b096 | 3,654,212 |
def sao_isomorficas(texto1: str, texto2: str) -> bool:
"""
>>> sao_isomorficas('egg', 'add')
True
>>> sao_isomorficas('foo', 'bar')
False
>>> sao_isomorficas('eggs', 'add')
False
"""
# Algoritmo O(n) em tempo e memória
letras_encontradas = {}
if len(texto1) != len(texto2):
... | a1f2c00a50b69cb18c32a299d50cbd3a35dcbe5e | 3,654,213 |
def _is_no_args(fn):
"""Check if function has no arguments.
"""
return getargspec(fn).args == [] | 29cb096323c69dd067bf4759a557734443a82ed5 | 3,654,214 |
def failure(parsed_args):
"""
:param :py:class:`argparse.Namespace` parsed_args:
:return: Nowcast system message type
:rtype: str
"""
logger.critical(
f"{parsed_args.model_config} {parsed_args.run_type} FVCOM VH-FR run for "
f'{parsed_args.run_date.format("YYYY-MM-DD")} '
... | e6744bfd61458497b5a70d7d28712385a8488a98 | 3,654,215 |
def good_AP_finder(time,voltage):
"""
This function takes the following input:
time - vector where each element is a time in seconds
voltage - vector where each element is a voltage at a different time
We are assuming that the two vectors are in correspondance (meaning
t... | c13897b7bf5335cae20f65db853e7a214ec570c5 | 3,654,216 |
from typing import Dict
from typing import Any
import tqdm
def parse(excel_sheets: Dict[Any, pd.DataFrame],
dictionary: Dict[str, Any],
verbose: bool = False) -> pd.DataFrame:
"""Parse sheets of an excel file according to instructions in `dictionary`.
"""
redux_dict = recursive_traver... | 88028fef19eda993680e89c58954c04a215a2fdd | 3,654,217 |
def build_LAMP(prob,T,shrink,untied):
"""
Builds a LAMP network to infer x from prob.y_ = matmul(prob.A,x) + AWGN
return a list of layer info (name,xhat_,newvars)
name : description, e.g. 'LISTA T=1'
xhat_ : that which approximates x_ at some point in the algorithm
newvars : a tuple of layer-... | 392050992846aeb1a16e70fe6e43c386e11915e5 | 3,654,218 |
def coeffVar(X, precision=3):
"""
Coefficient of variation of the given data (population)
Argument:
X: data points, a list of int, do not mix negative and positive numbers
precision (optional): digits precision after the comma, default=3
Returns:
float, the cv (measure of dispers... | e92505e79c4d10a5d56ec35cd2b543872f6be59c | 3,654,219 |
def tostring(node):
"""
Generates a string representation of the tree, in a format determined by the user.
@ In, node, InputNode or InputTree, item to turn into a string
@ Out, tostring, string, full tree in string form
"""
if isinstance(node,InputNode) or isinstance(node,InputTree):
return node.p... | 8e6cab92b898bd99b5c738b26fc9f8d79aef0750 | 3,654,220 |
from typing import Dict
import random
def pick_char_from_dict(char: str, dictionary: Dict[str, str]) -> str:
"""
Picks a random format for the givin letter in the dictionary
"""
return random.choice(dictionary[char]) | c593166ef7cb8c960b8c4be8fa0f8a20ec616f00 | 3,654,221 |
from typing import List
def bmeow_to_bilou(tags: List[str]) -> List[str]:
"""Convert BMEOW tags to the BILOU format.
Args:
tags: The BMEOW tags we are converting
Raises:
ValueError: If there were errors in the BMEOW formatting of the input.
Returns:
Tags that produce the sam... | 0081b7691a743fe3e28118cbb571708809fbd485 | 3,654,222 |
def site_sold_per_category(items):
"""For every category, a (site, count) pair with the number of items sold by the
site in that category.
"""
return [(site,
[(cat, total_sold(cat_items)) for cat, cat_items in
categories])
for site, categories in
categ... | 7b224f3e0a786aef497fad99359e525896eb8441 | 3,654,223 |
from typing import List
import ctypes
def swig_py_object_2_list_int(object, size : int) -> List[int]:
"""
Converts SwigPyObject to List[float]
"""
y = (ctypes.c_float * size).from_address(int(object))
new_object = []
for i in range(size):
new_object += [int(y[i])]
return new_ob... | 064a9a1e43884a9f989bec0b31d6d19705764b64 | 3,654,224 |
from typing import Tuple
from typing import Union
async def reactionFromRaw(payload: RawReactionActionEvent) -> Tuple[Message, Union[User, Member], emojis.BasedEmoji]:
"""Retrieve complete Reaction and user info from a RawReactionActionEvent payload.
:param RawReactionActionEvent payload: Payload describing ... | 36ae16e2b1ffb3df1d5c68ae903b95556446138f | 3,654,226 |
import array
def poisson2d(N,dtype='d',format=None):
"""
Return a sparse matrix for the 2d poisson problem
with standard 5-point finite difference stencil on a
square N-by-N grid.
"""
if N == 1:
diags = asarray( [[4]],dtype=dtype)
return dia_matrix((diags,[0]), shape=(1,1)).a... | 089088f468e84dce865bbb26707714617e16f3f6 | 3,654,227 |
import random
def get_factory():
"""随机获取一个工厂类"""
return random.choice([BasicCourseFactory, ProjectCourseFactory])() | c71401a2092618701966e5214f85c67a6520b1c9 | 3,654,228 |
def delay_class_factory(motor_class):
"""
Create a subclass of DelayBase that controls a motor of class motor_class.
Used in delay_instace_factory (DelayMotor), may be useful for one-line
declarations inside ophyd Devices.
"""
try:
cls = delay_classes[motor_class]
except KeyError:
... | 264d68f7d3db164c5c133e68f943b789db52fc8b | 3,654,229 |
def lonlat2px_gt(img, lon, lat, lon_min, lat_min, lon_max, lat_max):
"""
Converts a pair of lon and lat to its corresponding pixel value in an
geotiff image file.
Parameters
----------
img : Image File, e.g. PNG, TIFF
Input image file
lon : float
Longitude
lat : float
... | 39c1aeb63d38fdac383c510913f50f177d274a04 | 3,654,232 |
import scipy
def array_wishart_rvs(df, scale, **kwargs):
""" Wrapper around scipy.stats.wishart to always return a np.array """
if np.size(scale) == 1:
return np.array([[
scipy.stats.wishart(df=df, scale=scale, **kwargs).rvs()
]])
else:
return scipy.stats.wishart(df... | d14b26d8f1b05de1ac961499d96c604028fca379 | 3,654,234 |
async def async_setup_entry(hass, entry):
"""Set up Jenkins from a config entry."""
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, "sensor")
)
return True | c46912d11630c36effc07eed3273e42325c9b2b8 | 3,654,236 |
import math
def signal_to_dataset(raw, fsamp, intvs, labels):
"""Segmentize raw data into list of epochs.
returns dataset and label_array : a list of data, each block is 1
second, with fixed size. width is number of channels in certain standard
order.
Args:
raw: EEG signals. Shap... | 340bbb91bd6a36d1d3a20d0689e25c29e5b879c5 | 3,654,237 |
def project_dynamic_property_graph(graph, v_prop, e_prop, v_prop_type, e_prop_type):
"""Create project graph operation for nx graph.
Args:
graph (:class:`nx.Graph`): A nx graph.
v_prop (str): The node attribute key to project.
e_prop (str): The edge attribute key to project.
v_p... | 6e54180a4ef257c50a02104cc3a4cbbae107d233 | 3,654,238 |
def eqfm_(a, b):
"""Helper for comparing floats AND style names."""
n1, v1 = a
n2, v2 = b
if type(v1) is not float:
return eq_(a, b)
eqf_(v1, v2)
eq_(n1, n2) | 1ee53203baa6c8772a4baf240f68bb5898a5d516 | 3,654,239 |
def flatten_comment(seq):
"""Flatten a sequence of comment tokens to a human-readable string."""
# "[CommentToken(value='# Extra settings placed in ``[app:main]`` section in generated production.ini.\\n'), CommentToken(value='# Example:\\n'), CommentToken(value='#\\n'), CommentToken(value='# extra_ini_settings... | 56104eb6e0109b6c677964cd1873244ff05f27fc | 3,654,240 |
def get_community(community_id):
"""
Verify that a community with a given id exists.
:param community_id: id of test community
:return: Community instance
:return: 404 error if doesn't exist
"""
try:
return Community.objects.get(pk=community_id)
except Community.DoesNotExist:
... | 33d16db86c53b7dd68dec8fe80639b560e41f457 | 3,654,241 |
import csv
import pprint
def load_labeled_info(csv4megan_excell, audio_dataset, ignore_files=None):
"""Read labeled info from spreat sheet
and remove samples with no audio file, also files given in ignore_files
"""
if ignore_files is None:
ignore_files = set()
with open(csv4megan_excel... | f196b02c8667ebe5e8d2d89a79be78c6eb838afe | 3,654,242 |
def de_dupe_list(input):
"""de-dupe a list, preserving order.
"""
sam_fh = []
for x in input:
if x not in sam_fh:
sam_fh.append(x)
return sam_fh | bbf1936f21c19195369e41b635bf0f99704b3210 | 3,654,243 |
def donwload_l10ns():
"""Download all l10ns in zip archive."""
url = API_PREFIX + 'download/' + FILENAME + KEY_SUFFIX
l10ns_file = urllib2.urlopen(url)
with open('all.zip','wb') as f:
f.write(l10ns_file.read())
return True | 26770dfc8f32947c1a32a287f811e95ffe314822 | 3,654,244 |
def _constant_velocity_heading_from_kinematics(kinematics_data: KinematicsData,
sec_from_now: float,
sampled_at: int) -> np.ndarray:
"""
Computes a constant velocity baseline for given kinematics data, time window
... | 2b6781ceb9e012486d3063b8f3cff29164ff8743 | 3,654,245 |
def arg_int(name, default=None):
""" Fetch a query argument, as an integer. """
try:
v = request.args.get(name)
return int(v)
except (ValueError, TypeError):
return default | 110088655bc81363e552f31d9bbd8f4fa45abd1b | 3,654,246 |
def adapter_rest(request, api_module_rest, api_client_rest):
"""Pass."""
return {
"adapter": request.param,
"api_module": api_module_rest,
"api_client": api_client_rest,
} | 8b96313cb190f6f8a97a853e24a5fcfade291d76 | 3,654,248 |
def remove_quotes(string):
"""Function to remove quotation marks surrounding a string"""
string = string.strip()
while len(string) >= 3 and string.startswith('\'') and string.endswith('\''):
string = string[1:-1]
string = quick_clean(string)
string = quick_clean(string)
return string | c6585c054abaef7248d30c1814fb13b6b9d01852 | 3,654,250 |
def compute_list_featuretypes(
data,
list_featuretypes,
fourier_n_largest_frequencies,
wavelet_depth,
mother_wavelet,
):
"""
This function lets the user choose which combination of features they
want to have computed.
list_featuretypes:
"Basic" - min, max, mean, kurt ,skew, ... | f1c8fea04a01f6b7a3932434e27aba7ea2e17948 | 3,654,251 |
def select(locator):
"""
Returns an :class:`Expression` for finding selects matching the given locator.
The query will match selects that meet at least one of the following criteria:
* the element ``id`` exactly matches the locator
* the element ``name`` exactly matches the locator
* the elemen... | a3cd093a62d6c926fd9f782cdec35eadc34eba67 | 3,654,252 |
def send_image(filename):
"""Route to uploaded-by-client images
Returns
-------
file
Image file on the server (see Flask documentation)
"""
return send_from_directory(app.config['UPLOAD_FOLDER'], filename) | 68b99ca59d6d4b443a77560d3eb1913422407764 | 3,654,253 |
def swissPairings():
"""Returns a list of pairs of players for the next round of a match.
Assuming that there are an even number of players registered, each player
appears exactly once in the pairings. Each player is paired with another
player with an equal or nearly-equal win record, that is, a playe... | f83a8a108f2d926c948999014f0dbb79a3b1c428 | 3,654,254 |
import torch
def split(data, batch):
"""
PyG util code to create graph batches
"""
node_slice = torch.cumsum(torch.from_numpy(np.bincount(batch)), 0)
node_slice = torch.cat([torch.tensor([0]), node_slice])
row, _ = data.edge_index
edge_slice = torch.cumsum(torch.from_numpy(np.bincount(batch[row])), 0)
edge_... | 69af8b969d7f0da28a1f7fda951f64974c238da0 | 3,654,255 |
def _get_shadowprice_data(scenario_id):
"""Gets data necessary for plotting shadow price
:param str/int scenario_id: scenario id
:return: (*tuple*) -- interconnect as a str, bus data as a data frame, lmp data
as a data frame, branch data as a data frame and congestion data as a data
frame
... | 57488b7ff6984cc292dce3bf76d18d0b2585b7ff | 3,654,256 |
import json
def get_city_reviews(city):
"""
Given a city name, return the data for all reviews.
Returns a pandas DataFrame.
"""
with open(f"{DATA_DIR}/{city}/review.json", "r") as f:
review_list = []
for line in f:
review = json.loads(line)
review_list.appen... | e0723ab90dafc53059677928fb553cf197abecc1 | 3,654,257 |
def extract_rows_from_table(dataset, col_names, fill_null=False):
""" Extract rows from DB table.
:param dataset:
:param col_names:
:return:
"""
trans_dataset = transpose_list(dataset)
rows = []
if type(col_names).__name__ == 'str':
col_names = [col_names]
for col_name in col... | 91371215f38a88b93d08c467303ccbd45f57b369 | 3,654,258 |
def CalculateHydrogenNumber(mol):
"""
#################################################################
Calculation of Number of Hydrogen in a molecule
---->nhyd
Usage:
result=CalculateHydrogenNumber(mol)
Input: mol is a molecule object.
... | 0b9fbad14c8e9f46beab5208ab0f929fef1ab263 | 3,654,259 |
def check_update ():
"""Return the following values:
(False, errmsg) - online version could not be determined
(True, None) - user has newest version
(True, (version, url string)) - update available
(True, (version, None)) - current version is newer than online version
"""
version... | 8bba3e7fbe11ce6c242f965450628dc94b6c2c0b | 3,654,260 |
import torch
def count_regularization_baos_for_both(z, count_tokens, count_pieces, mask=None):
"""
Compute regularization loss, based on a given rationale sequence
Use Yujia's formulation
Inputs:
z -- torch variable, "binary" rationale, (batch_size, sequence_length)
percentage -- the ... | 7925c8621866a20f0c6130cd925afffe144e1c7c | 3,654,261 |
def unsqueeze_samples(x, n):
"""
"""
bn, d = x.shape
x = x.reshape(bn//n, n, d)
return x | 0c7b95e97df07aea72e9c87996782081763664cf | 3,654,262 |
def f_snr(seq):
"""compute signal to noise rate of a seq
Args:
seq: input array_like sequence
paras: paras array, in this case should be "axis"
"""
seq = np.array(seq, dtype=np.float64)
result = np.mean(seq)/float(np.std(seq))
if np.isinf(result):
print "marker"
result = 0
return result | b018b5e4c249cfafcc3ce8b485c917bfcdd19ce2 | 3,654,263 |
def _lorentzian_pink_beam(p, x):
"""
@author Saransh Singh, Lawrence Livermore National Lab
@date 03/22/2021 SS 1.0 original
@details the lorentzian component of the pink beam peak profile
obtained by convolution of gaussian with normalized back to back
exponentials. more details can be found in... | 7de93743da63ab816133e771075a8e8f0386ad35 | 3,654,264 |
def get_q_HPU_ave(Q_HPU):
"""1時間平均のヒートポンプユニットの平均暖房出力 (7)
Args:
Q_HPU(ndarray): 1時間当たりのヒートポンプユニットの暖房出力 (MJ/h)
Returns:
ndarray: 1時間平均のヒートポンプユニットの平均暖房出力 (7)
"""
return Q_HPU * 10 ** 6 / 3600 | fdf339d7f8524f69409711d4daefd1e2aaccbc76 | 3,654,265 |
def particles(t1cat):
"""Return a list of the particles in a T1 catalog DataFrame.
Use it to find the individual particles involved in a group of events."""
return particles_fromlist(t1cat.particles.tolist()) | 38f9a077b7bab55b76a19f467f596ddb28e40c60 | 3,654,266 |
def prime_list(num):
"""
This function returns a list of prime numbers less than natural number entered.
:param num: natural number
:return result: List of primes less than natural number entered
"""
prime_table = [True for _ in range(num+1)]
i = 2
while i ** 2 <= num:
if prime_... | c8e05aae2a59c229cfafb997469dd8ccacdda0fc | 3,654,268 |
import time
def check_deadline_exceeded_and_store_partial_minimized_testcase(
deadline, testcase_id, job_type, input_directory, file_list,
file_to_run_data, main_file_path):
"""Store the partially minimized test and check the deadline."""
testcase = data_handler.get_testcase_by_id(testcase_id)
store_min... | 443c09a8b5bcd8141f721b8ea90348879bc3b8c5 | 3,654,269 |
import ipaddress
def _item_to_python_repr(item, definitions):
"""Converts the given Capirca item into a typed Python object."""
# Capirca comments are just appended to item strings
s = item.split("#")[0].strip()
# A reference to another network
if s in definitions.networks:
return s
... | 9881e304e923eb2cea8223224273f4c9ef81696b | 3,654,270 |
import numpy
def floor_divide(x1, x2, out=None, where=True, **kwargs):
"""
Return the largest integer smaller or equal to the division of the inputs.
It is equivalent to the Python ``//`` operator and pairs with the
Python ``%`` (`remainder`), function so that ``a = a % b + b * (a // b)``
up to r... | 9269d088c0893b9b6b4c3b27e8dc83c4493ac2c9 | 3,654,271 |
from typing import Callable
import click
def node_args_argument(command: Callable[..., None]) -> Callable[..., None]:
"""
Decorate a function to allow choosing arguments to run on a node.
"""
function = click.argument(
'node_args',
type=str,
nargs=-1,
required=True,
... | 89365a41b7665cf291f5c15852db81e89aeef9a7 | 3,654,272 |
import functools
import unittest
def _tag_error(func):
"""Decorates a unittest test function to add failure information to the TestCase."""
@functools.wraps(func)
def decorator(self, *args, **kwargs):
"""Add failure information to `self` when `func` raises an exception."""
self.test_faile... | a2818c63647410abea3fde0b7f4fdae667b558bf | 3,654,273 |
from datetime import datetime
def get_submission_praw(n, sub, n_num):
"""
Returns a list of results for submission in past:
1st list: current result from n hours ago until now
2nd list: prev result from 2n hours ago until n hours ago
"""
mid_interval = datetime.today() - timedelta(hours=n)
... | 692af49736fac07a2de51d1cd0c4abcfe7bb8ee3 | 3,654,275 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.