content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def singlepass(fn):
"""
Will take the mean of the iterations if needed.
Args:
fn (Callable): Heuristic function.
Returns:
fn : Array -> Array
"""
@_wraps(fn)
def wrapper(self, probabilities):
if probabilities.ndim >= 3:
# Expected shape : [n_sample, n_... | 81052f3daf498e119cd953144da6ae76ef5bdf7d | 34,000 |
def remove_dihedral(mol, a, b, c, d):
"""
utils.remove_dihedral
Remove a specific dihedral in RDkit Mol object
Args:
mol: RDkit Mol object
a, b, c: Atom index removing a specific dihedral (int)
Returns:
boolean
"""
if not hasattr(mol, 'dihedrals'):
return ... | 7e26e995fec97c5c6d2304e11d06fec03b990942 | 34,001 |
import inspect
def load_mo(elem):
"""
This loads the managed object into the current name space
Args:
elem (str): element
Returns:
MangedObject
"""
mo_class_id = elem.tag
mo_class = load_class(mo_class_id)
mo_class_params = inspect.getargspec(mo_class.__init__)[0][... | 07738ce084cc0c6a51a6445eaa361c5c38daf312 | 34,002 |
import collections
def partialdot(mpa1, mpa2, start_at, axes=(-1, 0)):
"""Partial dot product of two MPAs of inequal length.
The shorter MPA will start on site ``start_at``. Local dot products
will be carried out on all sites of the shorter MPA. Other sites
will remain unmodified.
mpa1 and mpa2 ... | 2051e1e9e5023ee5e9724e62d0a123937ece7fb3 | 34,003 |
import torch
def thresh_ious(gt_dists, pred_dists, thresh):
"""
Computes the contact intersection over union for a given threshold
"""
gt_contacts = gt_dists <= thresh
pred_contacts = pred_dists <= thresh
inter = (gt_contacts * pred_contacts).sum(1).float()
union = union = (gt_contacts | p... | 9bd6244325acae0d3ebb5ffca46e0453a71000d1 | 34,004 |
def encode_sentences(sentences, tokenizer, language, mode):
"""对句子进行编码
@param sentences: 要编码的句子列表
@param tokenizer: 使用的字典
@param language: 语言
@param mode: 模式
@return: 编码好的句子列表,最大句子长度
"""
if language == 'zh':
return _encode_sentences_keras(sentences, tokenizer)
elif language =... | 8bb0d2143b73c02f1fac600ce322012da0bbdb05 | 34,005 |
def calc_scores(line_executions=LINE_EXECUTIONS, prior=PRIOR):
"""Return 'fault' score for each line, given prior and observations."""
return {
line: float(
execution_counts.negative_cases + prior.negative_cases
) / (
execution_counts.positive_cases + prior.positive_cases... | 985fb4ccc193135e5aa8b5637fc8878c9314e74e | 34,006 |
def symmetric_variable_summaries(var, metrics=None):
"""
Set summaries for a symmetric variable, e.g., the output of tanh.
Args:
var: tensorflow variable.
metrics: set a list of metrics for evaluation. Support: mean, stddev, max, min, histogram.
Default: mean, stddev.
Returns:
summaries: a li... | 8ba02b426c73e939aa2797bdc32dc988b07191b0 | 34,007 |
def normalize_parameters(raw_parameters, minvals, maxvals):
"""takes in a list of parameters and does simple min/max normalization according to min/max values
INPUTS
raw_parameters: length n, containing parameters for a star
minvals: length n, minimum parameter values
maxvals: length n, max paramete... | 53249bcecc8c3fd88beae7f377c6d5490693fba9 | 34,008 |
from typing import Any
def read_users(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
current_user: models.User = Depends(deps.get_current_active_superuser)
) -> Any:
"""
Retrieve users.
"""
users = crud.user.get_multi(db, skip=skip, limit=limit)
return users | 0f4f6eed8fc181165b261cb2f325e2dd38d14cf8 | 34,009 |
from numpy import cos, sin, array
def euler(a, b, c):
"""
Calculate a three dimensional rotation matrix from the euler angles.
@param a: alpha, angle between the x-axis and the line of nodes
@param b: beta, angle between the z axis of the different coordinate systems
@param c: gamma, angle betwee... | 406786a62b798b8e7dbbf57bd33f7243b5671e06 | 34,010 |
from pathlib import Path
def guardar_imagen_cv2(img_path, filtro, filtro_name="", output_dir=""):
"""
img_path: directorio de la imagen
filtro: funcion para aplicar filtro
file_path: directorio donde guardaremos las imagen
"""
try:
imagen_preprocesada = aplicar_preproceso(img_path, fil... | ede6ede0080df8b0ab1d99f348c014710f37c254 | 34,011 |
def create_begin_files(params):
"""Create initial files for HADDOCK3 run."""
run_dir = params['run_dir']
data_dir = run_dir / 'data'
begin_dir = run_dir / 'begin'
run_dir.mkdir()
begin_dir.mkdir()
data_dir.mkdir()
copy_files_to_dir(params['molecules'], data_dir)
copy_molecules_to_b... | 8c80a2bc084cb7573948055d2e04c1fb54eb93da | 34,012 |
import torch
from typing import Optional
def dump_sender_receiver_with_noise(agent_1: torch.nn.Module,
agent_2: torch.nn.Module,
dataset: 'torch.utils.data.DataLoader',
noise_prob: float,
... | 0fde105094d2fdf1b15247b80533bd6f2714d9dd | 34,013 |
def split_list(xs, at):
"""Split a list into sublists by a specific item value
E.g split_list(['a', 'b', '.', 'c', '.', 'd') = [['a', 'b'], ['c'], ['d']
Parameters
----------
x
A list
at
The item value to split by
Returns
-------
List[List]
A list of sublists split... | 5fd0d3f0c9417481918c36203fc84db8be33b104 | 34,014 |
def do(the_state_machine, pre_context_sm, BeginOfLinePreContextF, BeginOfStreamPreContextF):
"""Sets up a pre-condition to the given state machine. This process
is entirely different from any concatenation or parallelization
of state machines. Here, the state machine representing the pre-
condi... | bd6bdfa6826b74b036c2b7514e78a34b0b68404e | 34,015 |
def Sexp(x,G,N):
"""
Stochastic exponentiation function
Note: G should be such that G<<N
Parameters
----------
x: Stochastic bit-stream
G: Positive integer
N: Integer specifying the number of states
Returns
-------
A stochastic bit-stream approximating exp(-2Gx)
""... | 7815c2a2310593db651bad3e7922fc289d13597a | 34,016 |
def truncate(s: str, length: int = DEFAULT_CURTAIL) -> str:
"""
Truncate a string and add an ellipsis (three dots) to the end if it was too long
:param s: string to possibly truncate
:param length: length to truncate the string to
"""
if len(s) > length:
s = s[: length - 1] + '…'
re... | 90eb3cb1a26f525f8bc6076421a85d2f86af365c | 34,017 |
def amp_kd_calc(amph_sites_ff, element):
"""
aem_calc calculates the partition coefficient for a specified trace element
that is in equilibrium with a given amphibole composition according to
Humphreys et al., 2019.
supported elements = ['Rb','Sr','Pb','Zr','Nb','La','Ce','Nd','Sm',
'Eu','Gd','Dy','... | 8c1f4f4b82ba24801770fffc1b8a127183a63428 | 34,018 |
def _compute_errors_and_split(p, bezier, u):
"""Compute the maximum and rms error between a set of points and a bezier curve"""
dists = np.linalg.norm(bezier.xy(u)-p,axis=1)
i = np.argmax(dists)
rms = np.sqrt(np.mean(dists**2))
if i==0:
return 0.0, rms, len(p)//2
elif i==len(p)-1:
return 0.0, rms, len(p)//2
... | d97c06a0924e6a0d26a57d4fd0bd4e7322e74206 | 34,019 |
def rebin_flux(target_wavelength, source_wavelength, source_flux):
"""Rebin a flux onto a new wavelength grid."""
targetwl = target_wavelength
originalwl = source_wavelength
originaldata = source_flux[1:-1]
# The following is copy-pasted from the original fluxcal.py
originalbinlimits = ( origina... | 361484666824c7b8f23997812822cadaf57bcf47 | 34,020 |
def rate_match(residue, bead, match):
"""
A helper function which rates how well ``match`` describes the isomorphism
between ``residue`` and ``bead`` based on the number of matching atomnames.
Parameters
----------
residue : networkx.Graph
A graph. Required node attributes:
... | 474c2a4fb8be84935088dd1984445c4d0dccb980 | 34,021 |
def isNotEmptyString(input:str):
"""
this function check a string is not empty.
:param input:str: given string
"""
if isNotNone(input):
tmp = input.lstrip(' ')
return isStr(input) and (len(tmp) > 0)
else:
return False | 53c9fecea08947b500047962f609236ebc9bbb7f | 34,022 |
def show_queue(event_id):
"""
Pokazuje listę osób chętnych do rezerwacji wydarzenia (kolejka). Działa
tylko dla właściciela wydarzenia.
:type event_id: int
:param event_id: id wydarzenia
"""
try:
with conn:
with conn.cursor() as cur:
cur.execute("""select... | d617a4d71a925d6f6f000fb481e7afbf9ee4ff66 | 34,023 |
def _load_contact_template(user_email, email_details):
"""
Loads the email contents and returns the template for contact us
"""
##Email Template Init###
email_template = EmailMessage(
subject=email_details['subject'],
from_email="Questr <hello@questr.co>",
to=["Questr <hello@... | 4534c0ae8ad01c3abff20e8478589c0b7863118f | 34,024 |
def create_index(files, include_metadata=False, multi_run=False):
"""creates the index from list of files, by crawling over each file"""
ecpps = None
ecpps = run_func_on_files(ElChemPathParser, files, multi_run=multi_run)
ecds = None
if include_metadata:
ecds = run_func_on_files(
... | ccba3c031d2b763be19f4148162fc5cb39210625 | 34,025 |
def save_partnership_contact_form(request):
""" Saves the requests coming from the Partnership Contact form on the
home page """
if request.method == 'POST':
form = PartnershipRequestForm(request.POST)
if form.is_valid():
form.save()
send_partnership_request_email(req... | f22958204b3edd587e4d6a3ea6c9f6dee12f1705 | 34,026 |
def check_and_format_value(v):
"""
Formats all Pythonic boolean value into XML ones
"""
booleans = {'True': 'true', 'False': 'false'}
clean = strip(v)
if clean in booleans:
return booleans.get(clean)
return clean | 26beca017621efe425a99d5f7af0645953b83870 | 34,027 |
def name_exists(name, id=-1):
"""Check if category name exists in db.
Arguments: name as String, optional id as Integer
Public categories are not allowed to appear more than once. Private
categories can be duplicates.
"""
try:
c = db_session.query(Category).filter(Category.name==name,\
... | 36d2d8597431b62425d1270c9b82c5940eb6cbf0 | 34,028 |
def perimeter_nd(img_np, largest_only=False):
"""Get perimeter of image subtracting eroded image from given image.
Args:
img_np (:obj:`np.ndarray`): Numpy array of arbitrary dimensions.
largest_only (bool): True to retain only the largest connected
component, typically the outer... | 8957efb818c3d17485c88a0864c06f14b091c169 | 34,029 |
def get_storing_type():
"""Return the storing type of the data file.
One of the following integers:
0 --> ST_ALWAYS_FAST
1 --> ST_ALWAYS_SLOW
2 --> ST_FAST_ON_TRIGGER
3 --> ST_FAST_ON_TRIGGER_SLOW_OTH
A STORING_TYPE dict is provided by this module.
Wraps:
int DWGetStoringType... | aa10f947e55c0731e9fb6446a9c102198954b09a | 34,030 |
from typing import Optional
import requests
def transactions(api_url : str, network_id : NetworkIdentifier, operator : Optional[Operator] = "and",
max_block : Optional[int] = None, offset : Optional[int] = None, limit : Optional[int] = None,
transaction_id : Optional[TransactionIdent... | 76b4a64f24dc54a7e6f1a37761b82ec2222e4fbb | 34,031 |
def _normalize_3dinputs(x, y, z):
"""Allow for a variety of different input types, but convert them all to componentwise
numpy arrays that the functions in this module assume."""
# Handle different forms in input arguments
x = np.atleast_2d(x) # Assure a numpy array for componentwise or array versions... | f6162959cee8c4e5efa6fff5f9d81a63bacb396b | 34,032 |
import phono3py._phono3py as phono3c
def get_grid_point_from_address(address, D_diag):
"""Return GR grid-point indices of grid addresses.
Parameters
----------
address : array_like
Grid address.
shape=(3, ) or (n, 3), dtype='int_'
D_diag : array_like
This corresponds to me... | 86a6bb7385dfeb6553e1784ca656c7fbfebd30e4 | 34,033 |
def _generate_interpreted_layer(diagnostic_layer):
"""Generate interpreted layer from diagnostic test band
Parameters
----------
diagnostic_layer: numpy.ndarray
Diagnostic test band
Returns
-------
interpreted_layer : numpy.ndarray
Interpreted la... | 9810ec9306d967993881d5b94701239dbd862727 | 34,034 |
from textwrap import dedent
import keras.backend as k
import keras
import h5py
from snntoolbox.parsing.utils import get_custom_activations_dict
import matplotlib
import warnings
def update_setup(config_filepath):
"""Update default settings with user settings and check they are valid.
Load settings from confi... | e4237f7ffd153498a861bc69d3689c7489e170af | 34,035 |
from pyparsing import ParseException
from matplotlib.pyparsing import ParseException
def parse_gml(lines, relabel=True):
"""Parse GML graph from a string or iterable.
Parameters
----------
lines : string or iterable
Data in GML format.
relabel : bool, optional
If True use th... | b4438e5bdbc75a4bc0e4905748640ceacffa5b32 | 34,036 |
def get_evaluations(filename):
"""Return a list of all evaluations within an ENDF file.
Parameters
----------
filename : str
Path to ENDF-6 formatted file
Returns
-------
list
A list of :class:`openmc.data.endf.Evaluation` instances.
"""
evaluations = []
with o... | 469153dd3385f8f9ca3008c410d7b039e7167868 | 34,037 |
def svm_ova():
"""Multiclass (One-vs-All) Linear Support Vector Machine."""
return CClassifierMulticlassOVA(CClassifierSVM) | 064338ae0824225ad9fcd1dafc842bd2fee5180a | 34,038 |
import re
def parse(filename):
""" Dict of Data """
to_return = {}
f = open(filename,'r')
for line in f.readlines():
m = re.match(parse_regex, line)
result = m.groups()
if result[0] == '+':
to_return[result[1]] = True
else:
to_return[result[1]] =... | dbf4f25583913e1c99d70f99084a0aad2b6f618e | 34,039 |
def get_Theta_wtr_d(region, Theta_ex_prd_Ave_d):
"""日平均給水温度 (℃) (12)
Args:
region(int): 省エネルギー地域区分
Theta_ex_prd_Ave_d(ndarray): 期間平均外気温度 (℃)
Returns:
ndarray: 日平均給水温度 (℃)
"""
# 日平均給水温度を求める際の会期係数
a_wtr, b_wtr = get_table_7()[region - 1]
# 日平均給水温度 (12)
Theta_wtr_d = ... | d038da7a01f6acc7ac4204e8ef8c0ac99a74027a | 34,040 |
def get_FAAM_flights_df():
"""
Retrieve DataFrame of FAAM BAe146 flights
"""
# Flights to use...
DataRoot = get_local_folder('DataRoot')
folder = '/{}/FAAM/core_faam_NetCDFs/'.format(DataRoot)
filename = 'FAAM_BAe146_Biomass_burning_and_ACISIS_flights_tabulated.csv'
df = pd.read_csv(fold... | 0a60f9cdc61479da29de9ee93102af1abc9354b2 | 34,041 |
def get_facebook_customisations(token, aiid):
"""load customisations for the page"""
return fetch_api(
'/ai/{aiid}/facebook/custom',
token=token,
aiid=aiid,
timeout=config.API_FACEBOOK_TIMEOUT
) | 067e3f30143238053ba796fe3f0bac4fd4f7a751 | 34,042 |
import os
def get_matrices(training_set_path):
"""Return three Keras HDF5Matrix instances for the input, ground-truth
density map and ground-truth segmentation mask in a compact TrainingSet
"""
if os.path.isfile(training_set_path):
X = HDF5Matrix(training_set_path, 'input/input')
y = ... | f2c1c4988f56f3557752a58c6b5492ae7b87cc7f | 34,043 |
def plot_profile_base(
x, y, err, label_x, label_y, annotate, categorical, scale_x, scale_y
):
"""Make a scatter plot of eval metric `y` vs training config param `x`"""
f, ax = plt.subplots()
if scale_y is not None:
ax.set_yscale(scale_y)
if scale_x is not None:
ax.set_xscale(scale... | 6c23989b4eaa380d5955279e1e1ba8b2eb3b85be | 34,044 |
def train_one_step(
train_batch_i,
bvae_model,
genmo_optimizer,
infnet_optimizer,
prior_optimizer,
grad_variable_dict,
grad_sq_variable_dict):
"""Train Discrete VAE for 1 step."""
metrics = {}
input_batch = process_batch_input(train_batch_i)
(genmo_grads, prior_grads, infnet_grads, ... | b1a4dff6dd43f1569908718bef50eacf77fe84a8 | 34,045 |
def make_stepped_schedule(steps):
"""
Helper to generate a schedule function to perform step-wise changes of a given optimizer hyper-parameter.
:param steps: List of tuples (start_epoch, value);
start_epochs should be increasing, starting at 0. E.g.
momentum_sche... | 33fcd823bba6bcbd5fbf9edfbad780d79a1875f5 | 34,046 |
def sepfirnd(input,filters,axes,output=None,mode='reflect',cval=0.0,origin=0):
"""Apply multiple 1d filters to input using scipy.ndimage.filters.convolve1d
input : array_like
filters : sequence of array_like
Sequence of filters to apply along axes. If length 1, will apply the same filter to all axes... | 3b2cc1687343121c3b93805efdadb467c0dd9e34 | 34,047 |
import json
def daily_treasury(request):
"""
Get daily treasury. Data is from https://fiscaldata.treasury.gov/datasets/daily-treasury-statement/operating-cash-balance
"""
pd.options.display.float_format = '{:.2f}'.format
daily_treasury_stats = pd.read_sql_query("SELECT * FROM daily_treasury", conn... | 6b5f14edf68858683727b3c8a640674c4499e4e3 | 34,048 |
def list_representations():
"""list available server-side objects"""
try:
response = get_bus().list_representations()
return JsonResponse({'type': 'list', 'list': response})
except Exception as exception:
message, status = handle_exception(exception)
return JsonResponse({'mes... | 01241939634c3eff088c1d3c6b2caac8847d1f9f | 34,049 |
def format_endpoint_argument_doc(argument):
"""Return documentation about the argument that an endpoint accepts."""
doc = argument.doc_dict()
# Trim the strings a bit
doc['description'] = clean_description(py_doc_trim(doc['description']))
details = doc.get('detailed_description', None)
if detai... | 7acb21e3abafb188e3850ee9c78803e55d33fc8d | 34,050 |
import scipy
def from_edgelist(filename, directed=False, num_vertices=None, **kwargs) -> Graph:
"""
Construct an ``sgtl.Graph`` object from an edgelist file.
The edgelist file represents a graph by specifying each edge in the graph on a separate line in the file.
Each line looks like::
id1 i... | e425169eadb405458ffe3e72629409cb67e563db | 34,051 |
def shn_shelter_rheader(r, tabs=[]):
""" Resource Headers """
if r.representation == "html":
rheader_tabs = shn_rheader_tabs(r, tabs)
record = r.record
rheader = DIV(TABLE(
TR(
TH(Tstr("Name") + ": "), record.name
... | d802f68d89e04ec420e366ef651df278025d9822 | 34,052 |
import os
import numpy as np
from mindboggle.mio.vtks import read_scalars, read_vtk, write_vtk
from mindboggle.guts.mesh import reindex_faces_points, keep_faces
def explode_scalars(input_indices_vtk, input_values_vtk='', output_stem='',
exclude_values=[-1], background_value=-1,
... | 4af0b3382a86915a4ae77720f7ad01355633b577 | 34,053 |
from operator import xor
def usig1(bitarray: UBitArray32) -> UBitArray32:
"""
(uppercase sigma 1)
Computes the XOR of three sets of bits which result from rotating the input
set rightwards by 6, then 11, and then 25.
Args:
bitarray: (UBitArray32) The set of bits to operate on.
R... | 62aa93fa77dde53aecfe5bfd335ec919eedbbdb2 | 34,054 |
def fullRadar(dicSettings, mcTable):
"""
Calculates the radar variables over the entire range
Parameters
----------
dicSettings: a dictionary with all settings output from loadSettings()
mcTable: McSnow data output from getMcSnowTable()
Returns
-------
specXR: xarray dataset with t... | c7de880a159b80c60ec030a926f9d6278103c8cb | 34,055 |
def connect_db(uri, default_db_name=None, factory=pymongo.MongoClient):
"""
Use pymongo to parse a uri (possibly including database name) into
a connected database object.
This serves as a convenience function for the common use case where one
wishes to get the Database object and is less concerned... | 2ccb233aec3f9df9da1e4a9b82c7c4e5dbbfd0d9 | 34,056 |
import os
def send_email(to_email, subject, message):
"""This function is used to send email.
Takes in email_to, subject, message as parameters
:param to_email: person to be sent email
:param subject: subject of the email
:param message: message of the email
:return: a message, success or fail... | d6a64d6d341bf14d84b1a8a3a3e46275c45f96cd | 34,057 |
from pathlib import Path
import re
def parse_path(path: Path):
"""Obtain filename, task, framework and engine from saved path.
"""
if re.match(r'^.*?[!/]*/[A-Za-z]+-[A-Za-z]+/[A-Za-z_]+/\d+$', str(path.with_suffix(''))):
filename = path.name
architecture = path.parent.parent.parent.stem
... | 310d7bccb6f54147cb2214da45f339243be99620 | 34,058 |
import requests
def check_newer_version(command: str):
"""
Query for the latest release of the chaostoolkit to compare it
with the current's version. If the former is higher then issue a warning
inviting the user to upgrade its environment.
"""
try:
command = command.strip()
r ... | 0998818229f2cb0de5abb6bf9c9de0ba765fdbe9 | 34,059 |
def prettyprint(s, toUpper=False):
"""Given a string, replaces underscores with spaces and uppercases the
first letter of each word ONLY if the string is composed of lowercased
letters. If the param, toUpper is given then s.upper is returned.
Examples: "data_quality" -> "Data Quality"
"copy_number... | 18a57e74a2e3df66db4ede337663f9d8993a986b | 34,060 |
def doFilter(rule, dstPath):
"""
过滤
"""
global useStart
global useEnd
global useConatins
global searchInChild
# 文件名后缀(可以包含 点号)
global fileNameSuffix
temp = rule.get("searchInChild", False)
if True == temp:
searchInChild = True
print "searchInChild is " + s... | 9de196537753ffabd288f1aa64d0fe6b63a4225e | 34,061 |
import json
def generate(schema_id: str) -> tuple:
"""Generates sample data from a schema
:param str schema_id: Schema id
:return: A http response
:rtype: tuple
"""
search = [{'schema': schema_id}]
if ObjectId.is_valid(schema_id):
search.append({'_id': ObjectId(schema_id)})
... | 1caaa15753d0e33cb62d0d3c0f7cdf68945bb938 | 34,062 |
def recombine_edges(output_edges):
"""
Recombine a list of edges based on their rules.
Recombines identical Xe isotopes. Remove isotopes.
:param output_edges:
:return:
"""
mol = Chem.MolFromSmiles(".".join(output_edges))
# Dictionary of atom's to bond together and delete if they come in ... | b3ffbb9d3cf15c0f411fb83a8f1013a1988ae7ec | 34,063 |
import os
def initializeHdf5Write(filepath, groupname=None, **kwds):
""" Prepares an hdf5 file for output
Parameters
----------
filepath : `str`
The output file name
groupname : `str` or `None`
The output group name
Returns
-------
group : `h5py.File` or `h5py.Group`
... | 91db98b631aed79eec3cd75c4a63688791ea0751 | 34,064 |
def to_num_groups(word_groups):
"""
This function returns the a list of 24 numbers from a list of 24 words
representing the payload
"""
with open('wordlist.txt', 'rb') as (file):
words = file.readlines()
words = [word.decode('utf8').strip() for word in words]
num_groups = [words.inde... | 4286c584bb2f32d9c5ed0f3bcf2d0ee225b84ce4 | 34,065 |
import math
def _rsqrt(step_number, tail_start, body_value):
"""Computes a tail using a scaled reciprocal square root of step number.
Args:
step_number: Absolute step number from the start of training.
tail_start: Step number at which the tail of the curve starts.
body_value: Value relative to which ... | 99138c88ae8d0fc0d49a5ac55e389cd5a40d5f90 | 34,066 |
def set_formula_in_row(ws, num, row, mr_col=1):
"""
This "loops" through single cells in a column and applies mixing ratio formulas. The format of the formulas is quite
convulted for legacy reasons. Existing procedures made adhering to this format easier, but the gist is below.
Samples come in sets of ... | 2d4d438670e0760ce0158d5930390824634cce52 | 34,067 |
from typing import Union
import pathlib
from typing import List
from typing import Tuple
import json
def prepare_ablation_from_path(
path: Union[str, pathlib.Path],
directory: Union[str, pathlib.Path],
save_artifacts: bool,
) -> List[Tuple[pathlib.Path, pathlib.Path]]:
"""Prepare a set of ablation stu... | 39e043ed3a9cb82a85610c4b6df0d2d718895fb1 | 34,068 |
import re
import os
def read_txt_into_list(file_path):
"""
read the list from the file, each elem in a line compose a list, each line compose to a list,
the elem "None" would be filtered and not considered
:param file_path: the file path to read
:return: list of list
"""
assert os.path.isf... | a3f35831bff2b69aec2de2b652af6a1c6388fbe6 | 34,069 |
def currentTime(*args, **kwargs):
"""
Modifications:
- if no args are provided, the command returns the current time
"""
if not args and not kwargs:
return cmds.currentTime(q=1)
else:
return cmds.currentTime(*args, **kwargs) | 89b6d0c8abbea29b4a1f1f9f0f6458735313b400 | 34,070 |
def get_shapes(gdf: gpd.GeoDataFrame, colname: str) -> list:
"""
Extract and associate and format geometry and data in GeoDataFrame.
"""
assert "geometry" in gdf.columns, f"Expected `geometry` in {gdf.columns=}"
assert colname in gdf.columns, f"Expected {colname!r} in {gdf.columns=}."
return [(... | bf65d6a2caeee7d82b2b84f2b07722445beefb58 | 34,071 |
def _decodeUserData(byteIter, userDataLen, dataCoding, udhPresent):
""" Decodes PDU user data (UDHI (if present) and message text) """
result = {}
if udhPresent:
# User Data Header is present
result['udh'] = []
udhLen = next(byteIter)
ieLenRead = 0
# Parse and store U... | 91a259e2482ee654cc3fc1388138695ed975d778 | 34,072 |
from NexposeAPI import VulnData
from skaldship.exploits import connect_exploits
def import_all_vulndata(overwrite=False, nexpose_server={}):
"""
Uses the NexposeAPI and imports each and every vulnerability to Kvasir. Can take a looooong time.
Args:
overwrite: Whether or not to overwrite an existi... | d87bfc3e1a12de4e4c65bf0961be4b74787c5393 | 34,073 |
import json
def add_category(category_name):
"""
REST-like endpoint to add a category
:returns: Customized output from GIPHY
:rtype: json
"""
user = (
models.database.session.query(models.users.User)
.filter(
models.users.User.token == flask.request.cookies["X-Auth... | e5ff14ef56f628df982c524c27a7a7b61719be2c | 34,074 |
import os
def scale_multipolygon(im_name, mpoly, height, width):
"""scales a multipolgon using the gridsizes provided by kaggle admins"""
grid_sizes = pd.read_csv(os.path.join(global_vars.DATA_DIR,'grid_sizes.csv'), index_col=0)
x_max = grid_sizes.loc[im_name, 'Xmax']
y_min = grid_sizes.loc[im_name, ... | 22440596d3adc1b6870ce012e686124570cf5d32 | 34,075 |
from typing import Optional
from datetime import datetime
from typing import List
from typing import Tuple
import re
async def send_embed(
channel: Messageable,
embed_text: str,
title: str = "",
url: Optional[str] = None,
colour: Colour = Colour(settings.embed_color_normal),
... | f102bb7a5737519d5d6f9cbda48feb1a0337ffba | 34,076 |
from ucscsdk.mometa.comm.CommSyslogMonitor import \
def syslog_local_monitor_disable(handle):
"""
This method disables logs on local monitor.
Args:
handle (UcscHandle)
Returns:
CommSyslogMonitor: Managed Object
Raises:
UcscOperationError: If CommSyslogMonitor is not pres... | 40d48a4932c7e79221aba95ba5f0a4d8b5ba446c | 34,077 |
def git_push_obj(verbose, remote, obj=None):
"""
Push given object to git
:param obj: object wich will be pushed to git
:type obj: any one implements the interface of pushing to git
:rparam boolean: If success return True
"""
try:
LOGGER.info("%s: pushing to remote - %s", verbose, ... | 4139e93ff714baf70e50ff43329b6d3618508ede | 34,078 |
from datetime import datetime
import random
def partial_generator(api_list, seed = datetime.now().microsecond):
"""
Randomly denys access to certain API functions
:param api_list: The list of functions in the api
:param seed: An int, allows for seeding the tests with a certain seed to create predictab... | c32f8e072d35a79028cd9dcbe1edb2b28edf867c | 34,079 |
def get_key_from_event(*, event: dict) -> str:
"""Return S3 Object's Key from Lambda event
Args:
event (dict): Lambda event object
"""
record = event['Records'][0]
obj_key = record['s3']['object'].get('key')
if obj_key:
return obj_key
else:
raise ObjectKeyError('KeyE... | 274eef78eb646fd10d3f5970051de24a0f273e1e | 34,080 |
def country_name_from_code(code:str) -> str:
"""Return the full country name in English"""
# TODO: error handling if code is not found
return country_dict[code.upper()] | 948ac6ee8c9e59374ee659ff8e312562951d3207 | 34,081 |
def import_buffer_to_ast(buf, module_name):
""" Import content from buf and return a Python AST."""
return hy_compile(import_buffer_to_hst(buf), module_name) | b9bf33808e6951f3c6e49223f77c8cd8b1db07b6 | 34,082 |
def svn_wc_delete(*args):
"""
svn_wc_delete(char const * path, svn_wc_adm_access_t * adm_access, svn_cancel_func_t cancel_func,
svn_wc_notify_func_t notify_func, apr_pool_t pool) -> svn_error_t
"""
return _wc.svn_wc_delete(*args) | fb93c2989f65001a5e0ef012801a7c66582c815b | 34,083 |
import functools
import warnings
def deprecated(func):
"""
A decorator used to mark functions that are deprecated with a warning.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
# https://stackoverflow.com/questions/2536307/decorators-in-the-python-standard-lib-deprecated-specific... | b79556e9ef0c7b8fb877788ab53b198807f782ee | 34,084 |
def queryAnnotations(
paths, # type: List[String]
startTime=None, # type: Optional[Date]
endTime=None, # type: Optional[Date]
types=None, # type: Optional[List[String]]
):
# type: (...) -> List[Annotation]
"""Queries user stored annotations from the Tag history system for a
set of paths,... | e68b2a94ae54f7cfba854cf295dfbaf9e148e391 | 34,085 |
def has_other_useful_output(content_text):
"""Returns whether |content_text| has other useful output.
Namely, console errors/warnings & alerts/confirms/prompts.
"""
prefixes = ('CONSOLE ERROR:', 'CONSOLE WARNING:', 'ALERT:', 'CONFIRM:',
'PROMPT:')
def is_useful(line):
retu... | c1abfdaf681816314134ae33b5fd0fc48757dcc5 | 34,086 |
import re
def scrape(pagelim, endpoint, term=''):
"""
Retrieves all pages of the specified URL format up to the page limit.
Most of this code is spent on the loop structure to make sure we can
automatically get all the pages needed without storing empty data.
The latter half of thi... | 16c0d026e7f320549d77b1a6655aa8db35f6521e | 34,087 |
def TransformContainerAnalysisData(image_name, occurrence_filter=None):
"""Transforms the occurrence data from Container Analysis API."""
occurrences = FetchOccurrencesForResource(image_name, occurrence_filter)
analysis_obj = container_analysis_data_util.ContainerAnalysisData(image_name)
for occurrence in occur... | 99edfe655884a2932b4e84d6ce370df7dde7412e | 34,088 |
from .model_store import download_model
import os
def get_lednet(model_name=None,
pretrained=False,
root=os.path.join("~", ".torch", "models"),
**kwargs):
"""
Create LEDNet model with specific parameters.
Parameters:
----------
model_name : str or None... | c4fa6ca8b6e72fa223d23ca450611a3e791b83ba | 34,089 |
def sb_related_posts(post, num=5):
"""
cursor.execute("select object_id, count(distinct term_taxonomy_id) as weight from wp_2_term_relationships t inner join wp_2_posts p on p.ID=t.object_id where term_taxonomy_id in (%s) and post_type='post' and post_status='publish' and object_id != %s group by object_id orde... | 902c63dbc14bc64d56e3a42c090d90fb99983196 | 34,090 |
import random
def cluster_randomly_weigthed(document, prob_coref=0.03):
"""
Randomly creates a coreferring link between a mention, m2, and any preceding
mention, m1.
Probability of selecting a closer antecedent is higher, according to a
geometric distribution
Probability of selecting an ante... | d7223c9594ba5689e69f47048cf53f10b04bb85a | 34,091 |
def getOffset(self,name):
""" get the offset """
return [self.xoffset,self.yoffset] | b7b8d9c5da6bb38751e579583a8a5bd118cb1f67 | 34,092 |
def to_nbsphinx(s):
"""Use the sphinx naming style for anchors of headings"""
s = s.replace(" ", "-").lower()
return "".join(filter(lambda c : c not in "()", s)) | 87b266c84f9b32c1d7357c5ed23ba4058ba33673 | 34,093 |
import os
def get_training_data(file_name):
"""
Read the given training data file or default training data file and return the training data
params: training_data_file - string - Training data file path
returns: training_data - Datafrmae
"""
logger.debug("<<<< 'Current Executing Function' >>>>... | 8599129587f0b0dbc886cb838a444a86377ca906 | 34,094 |
import re
def isrest(peak):
"""Determine whether the first 512 bytes are written in reST."""
try:
a, b = re.match('^(.+?)\n((?:-|=|#)+)', peak).groups()
except (ValueError, AttributeError):
return False
return len(b) >= len(a) | 2ba2f65611118e8de19542f10a8a9668cd1b03a3 | 34,095 |
def load_raw(stream):
""" Load a schism YAML
"""
# First round to get environmental variables
loader = RawLoader(stream)
try:
data = loader.get_single_data()
finally:
loader.dispose()
stream.seek(0)
# Second round with substitution
env = {}
for key in substitute_... | ab150dfac1d557b96f5e8e1b4ad6e186d786a6a9 | 34,096 |
def compare_time_stats(grouped, ref_grouped):
"""Given two nested dictionaries generated by get_dict_from_json, after running
calculate_time_stats on both, compare the performance of the given run to a reference
run.
A string will be returned with instances where there is a significant performance
difference... | cb6512533ca64c1f59af4a02a4f53f3996e95b0c | 34,097 |
from typing import Tuple
from typing import Type
from typing import Dict
from typing import Any
def task_name_to_model_class(name: str) -> Tuple[Type[GraphTaskModel], Dict[str, Any]]:
"""
Map task name to a model class and default hyperparameters for that class.
"""
task_info = TASK_NAME_TO_DATASET_AN... | ba7e391de5510c06fbb72abb2d0891931dce1ffd | 34,098 |
def compute_pairwise_similarities(string_series_1: pd.Series,
string_series_2: pd.Series,
**kwargs) -> pd.Series:
"""
Computes the similarity scores between two Series of strings row-wise.
:param string_series_1: pandas.Series. The input S... | 79a12c261f4b687689ab4747fcb04500a6b7258d | 34,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.