content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def get_list():
"""Supports starling/peafowl-style queue_<name>_items introspection via stats."""
conn = Client(CONN.split(';'))
queue_list = []
queue_re = re.compile(r'queue\_(.*?)\_total_items')
try:
for server in conn.get_stats():
for key in server[1].keys():
... | cfd19a24f9e49836eda87fa25c6e52ccaf6a7155 | 37,800 |
import os
import csv
def compute_correlations_of_each_k(data, predictions, model_name, year):
"""
Computes the correlations between the BERT or GPT2 Language Model with Q1
:param data: The actual data of the year stored on dictionary
:param predictions: A dict where the predictions from our experiment... | 349189e8505091b409342cd666857c91fac38207 | 37,801 |
def net(n_ID):
"""
simple sample net to be used to train larger representations of given representations
while retaining the identity information
return: keras model
"""
model = Sequential()
model.add(Dense(256, input_shape=(128,), activation="relu", kernel_ini... | ec2be4984347532206804be2bf8fdbd40f8689d1 | 37,802 |
from re import L
def fullrank(X, r=None):
"""
Return a matrix whose column span is the same as X.
If the rank of X is known it can be specified as r -- no check
is made to ensure that this really is the rank of X.
"""
if r is None:
r = rank(X)
V, D, U = L.svd(X, full_matrices=0... | 6375359a8fd6a4d7671b3bfc6aa972079ec8ed62 | 37,803 |
import random
def update_solution_set(thresholds, threshold_h, asked_no_solutions, campus_id, current_sol):
"""Updates the set of solutions stored when one of the thresholds changes."""
print("Running 'update_solution_set'.")
# Check that all thresholds are integers, otherwise do nothing.
if not all(m... | 62db52e7408ddde1c999a66780297a8be081c33c | 37,804 |
def gwloss(constC, hC1, hC2, T):
""" Return the Loss for Gromov-Wasserstein
The loss is computed as described in Proposition 1 Eq. (6) in [12].
Parameters
----------
constC : ndarray, shape (ns, nt)
Constant C matrix in Eq. (6)
hC1 : ndarray, shape (ns, ns)
h1(C1) matrix ... | 465b389a17489ee6ed707748f751a7d057518496 | 37,805 |
def get_tag_by_storage_id(storage_id):
"""
根据storage_id查询地域tag
:param storage_id:
:return: None if not found
"""
return get_tag_by_target_id(STORAGE_CLUSTER, storage_id) | b36a91bd7ebbd951a347a346ba84b954d13869e6 | 37,806 |
def load_merged_with_style(dataset, style):
"""Load the merged dataframe for all the splits and then filter them
based on style."""
assert dataset in ['duke_ct','openi_cxr']
if dataset == 'duke_ct':
train_merged, test_merged, predict_merged = load_data_duke_ct()
elif dataset == 'openi_cxr':
... | caf9f3328f4ddf52901a464a15da2d25b78754cd | 37,807 |
import copy
def with_inverse(points, noise, debug = False):
""" Smooths a set of points
It smooths them twice, once in given order, another one in the reverse order.
The the first half of the results will be taken from the reverse order and
the second half from the normal order.
Args:
... | 702ed14e640a5a972667884dfdd63dd2a0df78af | 37,808 |
import html
def update_stats(preds, names, *args):
"""
Get the prediction of the best model and calculate
price per square meter and difference in price from
the previous parameters.
Notes
-----
Difference shows up after the user
changes the settings.
"""
area = args[2]
... | 059e6213a8c8056d977fc0041b6bcaecad0c34f1 | 37,809 |
def tflops_per_second(flops, dt):
""" Computes an effective processing rate in TFLOPS per second.
TFLOP/S = flops * / (dt * 1E12)
Args:
flops: Estimated FLOPS in the computation.
dt: Elapsed time in seconds.
Returns:
The estimate.
"""
return flops / (1E12 * dt) | f244632e1378a69ea55d4a994a9711bd3a2dca2a | 37,810 |
def format_img(img, C):
""" formats an image for model prediction based on config """
img, ratio = format_img_size(img, C)
img = format_img_channels(img, C)
return img, ratio | 84426f043c4ea8de5acb7b195aaabc1ecf082582 | 37,811 |
import json
def register():
#构造要返回的字符串# 初始化返回的数据 [arg1, arg2, arg3, arg4] arg1=状态码(num)arg2=msg(str) arg3= count(num) arg4=tuple
"""
:return:
{
"code": 0,
"msg": "",
"count": 29,
"data": []
}
"""
code = 500
print('??????????????code type=', type(code))
msg = '注册失败,请重新尝... | ace5184b847d9ce4fa7f5600ef0b8fa2646c9e1d | 37,812 |
from typing import Mapping
from typing import Dict
def get_instance_groups(context: models.Context) -> Mapping[str, InstanceGroup]:
"""Get a list of InstanceGroups matching the given context, indexed by name."""
groups: Dict[str, InstanceGroup] = {}
if not apis.is_enabled(context.project_id, 'compute'):
ret... | 08e1a09230856920aa4a25b6770b9ec8429b91dd | 37,813 |
from almahelpers_localcopy import tsysspwmap
from recipes.almahelpers import tsysspwmap
from casarecipes.almahelpers import tsysspwmap
from recipes.almahelpers import tsysspwmap
from casarecipes.almahelpers import tsysspwmap
def generateReducScript(msNames='', step='calib', corrAntPos=True, timeBinForFinalData=0.,
... | 9723a3a6e361a63b799a28ba6f9e47801581ba89 | 37,814 |
import os
import json
def get_hosts(host_file):
""" Fetches host data from a specified host_file
Args:
host_file: Device host file in JSON format
Returns:
A dict mapping keys to the corresponding host data, as follows:
{u'Group-1':
{u'example-device-2':
... | 1d0e58c5cd7d0e9fbe4ea3db6c4e91690afffbd0 | 37,815 |
def get_criteria_description(criterias, milestone_name):
"""Get implementation of the criteria, based on config.
This function checks for config criteria_name in config['criterias'],
gets class - realization of this criteria - and returns an instance
of this class.
"""
description = ""
for... | 0ba8b02206588c5fa978ed4c76d69a9be05b6e94 | 37,816 |
import pyslalib
def geo_to_bary(ra,dec,jd,epoch):
"""
For a given ra/dec, return the conversion from geocentric velocity to heliocentric
:ra: Decimal right ascension (degrees)
:dec: Decimal declination (degrees)
:jd: Modified (2000 = 51544) julian date
:epoch: Epoch of observations (e.g., 200... | b42c8d494c08c3c6f4da5c8d64712c3909225922 | 37,817 |
def plot_precinct_scatterplot(ei_runs, run_names, candidate, demographic_group="all", ax=None):
"""
Given two RxC EI runs, plot precinct-by-precinct comparison of preferences
for a given candidate from a given demographic group.
Parameters
----------
ei_runs: array
Length = 2
El... | 12432f06d643beb642883cf8924b87c18401d2a4 | 37,818 |
def linear_cubic_interpolation(driver_array=(), divisions=20, interpolation='quadratic'):
"""
interpolate the cubic line between points.
:return: <tuple> the array of point dictionary.
"""
point_final = ()
if interpolation == 'quadratic':
for t in xrange(divisions):
v1 = Vect... | d7820ba2a3bfc4f0dcb202b85bfdafb14b231a08 | 37,819 |
def gf_edf_shoup(f, n, p, K):
"""
Gathen-Shoup: Probabilistic Equal Degree Factorization
Given a monic square-free polynomial ``f`` in ``GF(p)[x]`` and integer
``n`` such that ``n`` divides ``deg(f)``, returns all irreducible factors
``f_1,...,f_d`` of ``f``, each of degree ``n``. This is a complet... | 46b2a478d6d3486d459337866c8f7fe427a7f5ef | 37,820 |
import inspect
def create_wrappers_for_class_methods(klass):
"""Wraps all the functions and class methods of a class."""
for name, func in inspect.getmembers(klass, predicate=inspect.isfunction):
setattr(klass, name, strong(func))
return klass | 559f10f9bc8449920fdbe093d942537fe9b21a8e | 37,821 |
def eci2geodetic(eci, t):
"""
convert ECI to geodetic coordinates
inputs:
eci/ecef: Nx3 vector of x,y,z triplets in the eci or ecef system [meters]
t : length N vector of datetime OR greenwich sidereal time angle [radians].
output
------
lat,lon (degrees/radians)
alt (meters)
... | ae3b974ba9ec1a8a143e33a912515e3f6832b4c7 | 37,822 |
def convert_to_circuit(image):
"""Encode truncated classical image into quantum datapoint."""
values = np.ndarray.flatten(image)
qubits = cirq.GridQubit.rect(4, 4)
circuit = cirq.Circuit()
for i, value in enumerate(values):
if value:
circuit.append(cirq.X(qubits[i]))
return c... | 0514aa99b30fe7b76e45b66bdd1d2c64560680c7 | 37,823 |
def verify_email_change(userid, token):
"""
Verify a user's email change request, updating the `login` record if it validates.
Compare a supplied token against the record within the `emailverify` table, and provided
a match exists, copy the email within into the user's account record.
Parameters:
... | e18e0481cd574027fd28cde7086b2198b1d8b940 | 37,824 |
import torch
def huber_fn_gradient(x, mu):
""" Huber function gradient """
y = torch.zeros_like(x)
with torch.no_grad():
mask = torch.abs(x) <= mu
y[mask] = x[mask]/mu
y[~mask] = x[~mask] / torch.abs(x[~mask])
return y | 1bcbe697a76c06afd49e7bbf106a3c1be0a47481 | 37,825 |
import sys
def video_read(filename_full):
"""Reads a video from the specified file in ~/Physics Pics. Converts to grayscale to reduce filesize.
Parameters
----------
filename_full : string
The file name within /Physics Pics, include the file extension, i.e. '.mp4'.
Returns
-------
... | 7914d1a832cc1e1ceb58c80341787deebc6eec7f | 37,826 |
def vectorsToRotMatrix(v1,v2):
"""
Given two points v1 and v2 in 3D space. Suppose furthermore that v2 is generated by v1
multiplied by a rotation matrix over the origin. We will determine this rotation matrix using this method
:rtype: float list
:return: Rotation matrix (unhomegenized) i... | 13a7348f84e69bc3337c0047e38443e839f74e33 | 37,827 |
def missing_impact(df: dd.DataFrame, bins: int) -> Intermediate:
"""
Calculate the data for visualizing the plot_missing(df).
This contains the missing spectrum, missing bar chart and missing heatmap.
"""
cols = df.columns.values
(nulldf,) = dask.persist(df.isnull())
nullity = nulldf.to_dask... | 44869403f21416f16341671e7d870cf4d2d01815 | 37,828 |
def svn_stream_write(stream, data):
"""svn_stream_write(svn_stream_t * stream, char const * data) -> svn_error_t"""
return _core.svn_stream_write(stream, data) | f35015ec517e77699db794ecedc93165bb5a0154 | 37,829 |
def build_word_dict(args, examples):
"""Return a dictionary from sentence words in
provided examples.
"""
word_dict = Dictionary()
for w in load_words(args, examples):
word_dict.add(w)
return word_dict | 1fa9d3906f16f00f89363acb487bb8c22eb5c0b1 | 37,830 |
def train_test_split(df, index,
split_by=None,
stratify_by=None,
test_split=0.1,
seed=None):
"""Split pandas dataframe into train and test splits. Options to split by
group (i.e. keep groups together) and stratify by label.
... | fe56f9897da4df4708b2b439ea8d2b027d01668e | 37,831 |
def get_data_ce_duals_active_all():
"""() -> list
Returns a list of all of the active ce cards in the database, sorted in ascending order by start date."""
query = (
f'''
SELECT active_product_nick, active_product_titles, CAST (CAST (active_product_prices AS text) AS money), active_product_... | 0d9af4d17059ae53c2d0a4fa40f5e007253f07c6 | 37,832 |
from typing import Optional
def _import_project_sections(nt_client, monday_client, nt_project_id, project, limits: dict):
"""Import monday lists as project sections"""
nt_api_sections = apis.ProjectSectionsApi(nt_client)
def _parse_timestamp(monday_timestamp: Optional[str]) -> Optional[models.TimestampNu... | a57a8a6a41b7ef333d45001859e9b199b3d7339a | 37,833 |
def evaluate_wos_layer(epoch_predicts, epoch_labels, vocab, threshold=0.5, top_k=None):
"""
:param epoch_labels: List[List[int]], ground truth, label id
:param epoch_predicts: List[List[Float]], predicted probability list
:param vocab: data_modules.Vocab object
:param threshold: Float, filter probab... | c3b3a47caab6d396e1c3531d7f5e4442e7e4dd33 | 37,834 |
def convert_weighted(array : np.array) :
"""
3D-array to 2D-array
(R^2 + G^2 + B^2) / (R+G+B)
"""
sqrd = array**2
sqrd = sqrd.sum(axis = -1)
norm = array.sum(axis = -1)
return np.nan_to_num(sqrd/norm, nan=0) | 794d2fae798aec538cc6d502d86c0cd524fdf889 | 37,835 |
def empty_init():
"""Returns True if trying to initialize an Interactionobseng
without any arguments fails."""
try:
BaseObservationEngine()
return True
except TypeError:
return False | 0d3a3f4b5e6addd818037b73edd5dc6ea37edd79 | 37,836 |
import signal
def smooth_column(args):
"""Low-level helper function for smoothing single column
Parameters
----------
args : tuple
Tuple containing data to smooth in 1d array,
smoothing kernel in 1d array, whether to
ignore nans, and data dtype
Returns
-------
... | ce3f62c01c2a6e14cf921c83b670dc08e94e2936 | 37,837 |
def check_all_H(structure):
"""
Parameters
----------
structure : Biopython protein structure object made with PDBParser().
Returns
-------
all_ligands : dataframe of all distances between each amino acid residue
and ligand from the protein structure.
"""
heteros = get_hetero... | db70d4d891c50ef97a3dc642e1f6d81068d8ef8e | 37,838 |
import os
def get_file_join_name(input_path=None, file_name=None):
"""Function for getting join name from input path."""
name_list = []
file_join_name = ''
if os.path.exists(input_path):
files = os.listdir(input_path)
for f in files:
if file_name in f and not f.endswith('.d... | 174a84f344a203dfc9aae2970a77a2ba18fe7367 | 37,839 |
def get_example_jwt_auth_signer(**kwargs):
""" returns an example jwt_auth_signer instance. """
issuer = kwargs.get('issuer', 'egissuer')
key_id = kwargs.get('key_id', '%s/a' % issuer)
key = kwargs.get(
'private_key_pem', get_new_rsa_private_key_in_pem_format())
algorithm = kwargs.get('algor... | 33a40801a7492c23b08570f6204cedf4d8c02eb8 | 37,840 |
import os
import binascii
def generate_id(hksess):
"""
Generates a unique session id based on the start_time, process_id,
and hksess description.
Args:
hksess (so3g.HKSessionHelper)
"""
# Maybe this should go directly into HKSessionHelper
elements = [
(int(hksess.start_tim... | 2bf52c38b26e9a65071b0db0a7bb0d3edaba17ca | 37,841 |
async def close_trades(ctx):
"""Ends free agency in the identified league."""
if ctx.author.id not in admin_ids:
return await ctx.send("This is an admin-only command.")
for l in leagues:
if l.get_channel() == ctx.channel.id:
league = l
break
else:
return a... | 3219057ba9e05da4e7fa66af963c4991a55b6e3e | 37,842 |
def generate_set_None(gen_dict, class_dict):
"""Generate the code for the _set_None method of the class
Parameters
----------
gen_dict : dict
Dict with key = class name and value = class dict (name, package, properties, methods...)
class_dict : dict
Dictionnary of the class to gene... | 457f6588e71b9ae66b1b23a768d13a0a38be0ed0 | 37,843 |
from sumpy import P2P
def drive_volume_fmm(traversal, expansion_wrangler, src_weights, src_func,
direct_evaluation=False, timing_data=None,
reorder_sources=True, reorder_potentials=True,
**kwargs):
"""
Top-level driver routine for volume potential... | 1a2ca1c47f05d7f8f3a973c58a71dc3ee9ec604a | 37,844 |
def k_from_m1m2(m1,m2, P, i, e=0):
"""
Parameters
----------
i: float
inclination with units
FIXME: Add in non-zero eccentricity
"""
f1 = m2**3*np.sin(np.radians(i))**3/(m1+m2)**2
f2 = m1**3*np.sin(np.radians(i))**3/(m1+m2)**2
K1 = ((f1*2*np.pi*const.G/P)**(1/3.)).si... | 1f717587d4736e3748015371f0c1d2c7ed5db2bb | 37,845 |
import xml
def unescape_ssml(text: str) -> str:
"""Unescapes XML control characters in SSML.
See:
https://console.bluemix.net/docs/services/text-to-speech/http.html#escape
We first unescape the text in case it already contains escaped control
characters.
"""
return xml.sax.s... | 4f58510cad608fc7e18ac4ab19cf5895206adfaa | 37,846 |
def descSetupInEipMode():
"""
Setting up an EIP/ELB enabled zone with netscaler provider
"""
zs = cloudstackConfiguration()
for l in range(1):
z = zone()
z.dns1 = "8.8.8.8"
z.dns2 = "8.8.4.4"
z.internaldns1 = "192.168.110.254"
z.internaldns2 = "192.168.110.25... | a77b650532b3187085df9a19f70879addb6629b5 | 37,847 |
async def send_expr(bot: NoneBot, ctx: Context_T,
expr: Expression_T, **kwargs):
"""Sending a expression message ignoring failure by default."""
return await send(bot, ctx, expression.render(expr, **kwargs)) | 0999f5d9c914c27029b0427f84089b5419432fbb | 37,848 |
import os
import json
import logging
def read_settings(path=os.getenv('MOASTROCONFIG',
os.path.expandvars('$HOME/.moastro.json'))):
"""Read the Mo'Astro JSON configurations file.
Parameters
----------
path : str
Path to the ``.moastro.json`` file.
Returns
-------
se... | ef0d8f0dcb176bcca98be9b604c382e3111ec7e7 | 37,849 |
def ssd_model_build():
"""create network"""
ssd = ssd_inception_v2(configs=config)
if config.feature_extractor_base_param != "":
ssd.init_parameters_data()
param_dict = load_checkpoint(config.feature_extractor_base_param)
load_param_into_net(ssd, param_dict)
return ssd | 1a4e412d7dafcb43333cda6d0966b2fc920f6b07 | 37,850 |
def last_update_import_id():
"""
For better filtering.
@return:
"""
last_run = app.session.query(func.max(ImportLog.import_id)).filter(ImportLog.status == STATUS_FINISHED).first()[0]
if last_run is None:
max_import_id = -1
else:
max_import_id = last_run
return max_import... | e4e402a6d82e4b98d63363530c4775f50a7ee9b2 | 37,851 |
def is_valid(value, cast_fn, expected_data_type, allow_none=False):
"""
Checks whether a value can be converted using the cast_fn function.
Args:
value: Value to be considered
cast_fn: Function used to determine the validity, should throw an
exception if it cannot
e... | ee1a2aca4ba7d437692f5025901f9bf94031434a | 37,852 |
import re
def get_kanji(seg_content: str) -> dict:
"""Split raw lesson content into individual character entries and process each one."""
ret = {}
entries = [entry for entry in re.split(KANJI, seg_content) if entry]
for kanji, desc in zip(entries[::2], entries[1::2]):
ret[kanji] = parse_kanji(... | 96fa6d48d3c0ac8b0e64f110987522f9656486aa | 37,853 |
def range_transformation(value: float, input_range: list, output_range: list = [-1, 1]):
"""Range transformation from [input_range[0], input_range[1]] to [output_range[0], output_range[1]]
Args:
value (float): variable
input_range (list): desired input variable range
output_range (list,... | 31fbddf575a896fa1ffba7c85857557c3df0337a | 37,854 |
def get_authen_roles():
"""
Get the authentication roles
Returns:
arr[str]: Array of associated roles
"""
return g.get(AUTHEN_ROLES, []) | a3ba9caa050491203626f60a273d0fa3f8f58a07 | 37,855 |
def _mkanchors(ws, hs, x_ctr, y_ctr):
"""
Given a vector of widths (ws) and heights (hs) around a center
(x_ctr, y_ctr), output a set of anchors (windows).
"""
ws = ws[:, np.newaxis]
hs = hs[:, np.newaxis]
anchors = np.hstack((x_ctr - 0.5 * (ws - 1),
y_ctr - 0.5 * (h... | 54e5cc05c34f970f9e725f8ecfd27043c700378c | 37,856 |
def explode(dataframe: DataFrame, col: str, new_col: str = None) -> DataFrame:
"""Explode a list in a cell to many rows in the dataframe
:param str col: name of the column to explode
:param str new_col: name of the new column to explode to, could be exploded column
"""
tmp_new_col = new_col if new_... | 54133354eddf42dad973c2e19a9bfc80f3763f08 | 37,857 |
def median_buffer_range(mag, magerr):
"""This function returns the ratio of points that are between plus or minus 10% of the
amplitude value over the mean
:param mag: the time-varying intensity of the lightcurve. Must be an array.
:param magerr: photometric error for the intensity. Must be an array... | 83b1eed561399916da58be96c2e8437a8669d2d8 | 37,858 |
def multiply(a, b):
"""Multiply simple numbers, vectors, and 2D matrices."""
is_a_num = is_number(a)
is_b_num = is_number(b)
is_a_vec = not is_a_num and is_number(a[0])
is_b_vec = not is_b_num and is_number(b[0])
is_a_mat = not is_a_num and not is_a_vec
is_b_mat = not is_b_num and not is_b_... | f4c9a6e29a24bfbd9dab940510f3b6c35d09c4a7 | 37,859 |
from typing import Tuple
from typing import List
def two_qubit_matrix_to_diagonal_and_operations(
q0: 'cirq.Qid',
q1: 'cirq.Qid',
mat: np.ndarray,
allow_partial_czs: bool = False,
atol: float = 1e-8,
clean_operations: bool = True,
) -> Tuple[np.ndarray, List['cirq.Operation']]:
"""Decompos... | 36bb1d8a31eeebf78619427e681c4c9784783d45 | 37,860 |
def log_f(theta):
"""log of unnormalized target probability density function"""
log_var = theta[0]
var = np.exp(log_var)
xx = theta[1:]
return -0.5*log_var**2 - (0.5/var)*np.dot(xx, xx) - 0.5*xx.size*log_var | a04ed631ae035101a04bb429c8e254f5fed0a59c | 37,861 |
from operator import or_
def search(database, search_params=None, limit=0, order_by='last_updated desc'):
"""
Searches for one or more resources in the database using the specified parameters.
Args:
database: The current database context.
limit: The maximum number of results to return.
... | d2ff639263310186e2362ce290fdeeb33d58242b | 37,862 |
def pd_series_to_instapost(timeseries:pd.core.series.Series, pathname:str, units:str, timezone:str)->dict:
"""
Args:
series: a pd.core.Series time series with a time stamp index
pathname: pathname the data is to be stored at
units: the units the data is in
... | 527d20d5cfe2e6bd02199ab2713c41fd291179ea | 37,863 |
def iou_batch(bb_test, bb_gt):
"""
From SORT: Computes IUO between two bboxes in the form [l,t,w,h]... | 75a3eaea8aeac8c57553cc961ffcd11f25d21ac3 | 37,864 |
from typing import Callable
from typing import Optional
def action_interaction_additive_reward_function(
context: np.ndarray,
action_context: np.ndarray,
action: np.ndarray,
base_reward_function: Callable[[np.ndarray, np.ndarray], np.ndarray],
action_interaction_weight_matrix: np.ndarray,
is_c... | 720b23fb2dd539dba29acf46f498ce46d7a0a77e | 37,865 |
def butter2d_lp(shape, f, n):
"""
Designs a lowpass 2D Butterworth filter.
Modified from Peirce JW (2009) Generating stimuli for neuroscience using
PsychoPy. Front. Neuroinform. 2:10.
doi:10.3389/neuro.11.010.2008.
Parameters
----------
shape : tuple
Size of the filter.
f :... | 6c4b7ccc14290b4be2e06e7c752eb2146f3023cf | 37,866 |
def run_model(network, nodes, demand_per_person_kw_peak, mg_gen_cost_per_kw, mg_cost_per_m2, cost_wire_per_m, grid_cost_per_m2):
"""
"""
# First calcaulte the off-grid cost for each unconnected settlement
for node in nodes:
if node[5] == 0:
node[7] = node[4]*demand_per_person_kw_pe... | 02b386363ac2b18bde7e5773da91109fd234353b | 37,867 |
def read_circuit(file):
"""
Read a Revlib circuit file and create a Qiskit circuit objetc
:param file: Revlib circuit file
:returns a Qiskit circuit object
"""
with open(file, mode="r") as file:
lines = []
begin = end = 0
variables = ''
for index, line in enum... | b8d5c126c867a7a63843c3baf6fb321dcba9aa3a | 37,868 |
def global_reconstruction_error(
X,
Y,
test_idx=None,
train_idx=None,
scaler=None,
estimator=None,
):
"""Computes the global reconstruction error using the source X
to reconstruct the features or samples of target Y based on a minimization
by linear regression:
.. math:: GRE... | cebeb31aea82a5258955523bd5eeb95e492d2eea | 37,869 |
def api_mobsfy(request):
"""POST - MobSFy API."""
if 'identifier' not in request.POST:
return make_api_response(
{'error': 'Missing Parameters'}, 422)
resp = operations.mobsfy(request, True)
if resp['status'] == 'ok':
return make_api_response(resp, 200)
return make_api_re... | 306319f12e43cf57c3ab0757e964fae30cf17ed9 | 37,870 |
def numero_lista(df):
"""
Función destinada a obtener el número de lista de clases
:parameter: dataframe
:return:
numero de lista de clases
"""
# Selecciono la columna clase del dataframe y realizo unas modificaciones
df['clase'] = df['clase'].str.replace(
'[', '').str.replace(']... | 86523b6f9eae835de6dfc960e8930cf7659cb2a7 | 37,871 |
def Fingerprint(path, params):
"""Check for a Python app.
Args:
path: (str) Application path.
params: (ext_runtime.Params) Parameters passed through to the
fingerprinters.
Returns:
(PythonConfigurator or None) Returns a module if the path contains a
python app.
"""
log.info('Checking f... | 9fde55896fc98984ab90c6274f0f51b14d77e2a0 | 37,872 |
import os
def generate_tray_hash(xlist, ylist, floor, wall, depth, round):
"""
This method generates a unique identifier for a given tray for the given version of this script
(based on the version.txt file). This allows us to generate a given tray one time, and then it
can be saved to a central locat... | 9d139059d1a58bd05b242c14b6128e6ab226245b | 37,873 |
import numpy as np
def calc_spatialCorrHeightLev(varx,vary,levs,lons,weight,levelq):
"""
Calculates spatial correlation from pearson correlation coefficient for
grids over vertical height (17 pressure coordinate levels). Change the
weighting for different level correlations
Parameters
--... | 9645f5d92598250d75a484b0c5bf848073c3f5e8 | 37,874 |
def v_relative(v, met):
"""Estimates the relative air speed which combines the average air speed of
the space plus the relative air speed caused by the body movement. Vag is assumed to
be 0 for metabolic rates equal and lower than 1 met and otherwise equal to
Vag = 0.3 (M – 1) (m/s)
Parameters
... | 6dceae6ec076dc800d2aa3e80d7d491d94830580 | 37,875 |
def fully_qualified_name(entry):
"""
Calculates the fully qualified name for an entry by walking the path
to the root node.
Args:
entry: a BeautifulSoup Tag corresponding to an <entry ...> XML node,
or a <clone ...> XML node.
Raises:
ValueError: if entry does not correspond to one of the ... | 68119b640509cd972770f810b80ba1a2ad54f688 | 37,876 |
from pathlib import Path
def lab(
jupyter_lab: t.Tuple[BrowserContext, Path, int],
) -> t.Callable:
"""Provide function-scoped fixture leveraging longer lived fixtures."""
context, tmp, port = jupyter_lab
path = tmp / f"notebook-{uuid4()}.ipynb"
return lambda json_in: _lab(
json_in,
... | de906a24e494ac7dd056099ca925b82ac7eeb136 | 37,877 |
def load(env_name):
"""Loads the train and eval environments, as well as the obs_dim."""
# pylint: disable=invalid-name
kwargs = {}
if env_name == 'sawyer_push':
CLASS = SawyerPush
max_episode_steps = 150
elif env_name == 'sawyer_drawer':
CLASS = SawyerDrawer
max_episode_steps = 150
elif env... | 47f03f29d69f643ebd64040fa1d98607217fbb82 | 37,878 |
from typing import Iterable
from typing import Dict
def get_pkg_info(
package_name: str,
additional: Iterable[str] = ("pip", "flit", "pbr", "poetry", "setuptools", "wheel"),
) -> Dict[str, str]:
"""Return build and package dependencies as a dict."""
dist = distribution(package_name)
dependencies =... | 439b5058df1e421506ef6f23976cb64e48d555bc | 37,879 |
def sort_tasks_by_exec_time(tasks):
"""
Sort tasks in descending order by the execution time
Args:
tasks (list(Node)
Returns:
list(Node)
"""
n = len(tasks)
for i in range(n):
for j in range(0, n - i - 1):
if tasks[j].get_exec_time() < tasks[j+1].get_exe... | 44f24408803c851ae7f1dd021ec19f99efc3feda | 37,880 |
def csr_sort_indices(*args):
"""
csr_sort_indices(int n_row, int Ap, int Aj, signed char Ax)
csr_sort_indices(int n_row, int Ap, int Aj, unsigned char Ax)
csr_sort_indices(int n_row, int Ap, int Aj, short Ax)
csr_sort_indices(int n_row, int Ap, int Aj, unsigned short Ax)
csr_sort_indices(int n_r... | 06bf9c3c66e30d432e43e682e87da33665439b96 | 37,881 |
def rdkit_functional_group_label_features_generator(mol: Molecule) -> np.ndarray:
"""
Generates functional group label for a molecule in RDKit.
:param mol: A molecule (i.e. either a SMILES string or an RDKit molecule).
:return: A 1D numpy array containing the RDKit 2D features.
"""
smiles = Che... | 15ea9e0255e18674f8aeb6dc20834f1c7aee1d7f | 37,882 |
def append(log: immutables.Map, after: model.Index, *entries: model.Entry) -> immutables.Map:
"""Append entries to `log` *after* the given index.
:param log: Log object to append entries to.
:param after: Log index after which entries will be appended.
:raises AppendError: If the operation is unsucces... | c9947284f8333910e2f00703ab0da43b7c9eb2a8 | 37,883 |
def get_ids(conn, sql_class, columns, data):
"""
Get row ids based on data and column_names.
This function returns only the first id per data point.
Be careful if the columns do not ensure uniqueness.
"""
return [
_get_data(
conn=conn,
sql_class=sql_class,
... | b36be7ef815b6d2b82e340ed44881f8117490d29 | 37,884 |
import requests
import re
def get_special_search_qnodes(search_term):
"""
Searches for the search_term and returns a list of candidates from the wikidata search api
"""
if search_term == '':
return []
url = "https://www.wikidata.org/w/api.php"
params = {
"action": "query",
... | fce3f0c7ebc34613e4e92162169a766e538897cf | 37,885 |
def custom(colors, bins=None, bin_method=BinMethod.quantiles):
"""Create a custom scheme.
Args:
colors (list of str): List of hex values for styling data
bins (int, optional): Number of bins to style by. If not given, the
number of colors will be used.
bin_method (str, optiona... | eb6f0726d3523e4937cb7615e74eb073025c144c | 37,886 |
import re
import sys
def unhandledExceptionMessage():
"""
Returns detailed message about occurred unhandled exception
"""
errMsg = "unhandled exception occurred in %s. It is recommended to retry your " % VERSION_STRING
errMsg += "run with the latest development version from official Gitlab "
... | 70dbc78b8d65f1d2dd3e548fc43d59b93e623b05 | 37,887 |
def convert_vdot_to_time(vdot, distance):
"""Given a VDOT score, returns an approx time for a given distance."""
# Get equation parameters
c = VDOT_TO_TIME[VDOT_TO_TIME.Distance==distance].iloc[0].Intercept
m1 = VDOT_TO_TIME[VDOT_TO_TIME.Distance==distance].iloc[0].Coef1
m2 = VDOT_TO_TIME[VDOT_TO_TI... | bb4a3071b7a94e2e1486b37baf3aeff82fcb8a2f | 37,888 |
def exception_response(status_code, **kw):
"""Creates an HTTP exception based on a status code. Example::
raise exception_response(404) # raises an HTTPNotFound exception.
The values passed as ``kw`` are provided to the exception's constructor.
"""
exc = status_map[status_code](**kw)
retur... | 0efc1bdd3c6febd4976210bb2759fd50c8fce9db | 37,889 |
import os
import packaging
def get_latest_installed(dataset_path):
"""Return the latest version number installed in a dataset directory.
Parameters:
dataset_path (str): The path to the dataset of interest.
Returns:
str: The latest version installed locally. Returns None if no versions are instal... | 372d5fbb5a222dc22d3d87941e50da448a324395 | 37,890 |
def _mask_iou(mask1: np.ndarray, mask2: np.ndarray) -> ScalarMetricValue:
"""Computes iou between two binary segmentation masks."""
return np.sum(mask1 & mask2) / np.sum(mask1 | mask2) | 6f781f3f9f0702613093432de67ea91179a5cd23 | 37,891 |
import re
def shorten_int_name(interface_name):
"""
Returns the Cisco shortened interface name from a full one.
If the full interface name is invalid, this will return None
"""
short = None
regex = "(\w{2}).*?(\d+(?:/\d+)?(?:/\d+)?)"
match = re.match(regex, interface_name)
... | 48a6f730c8d3d2f0abaec299385b5d558cf06a00 | 37,892 |
import re
def read_version():
"""Read version from the first line starting with digit
"""
regex = re.compile('^(?P<number>\d.*?) .*$')
with open('../CHANGELOG.rst') as f:
for line in f:
match = regex.match(line)
if match:
return match.group('number') | 7188470ab1a794b6e72a1fe8bcd804f7290be4a4 | 37,893 |
def version_to_semver(version):
""" Convert an SDK version string to an npm compatible semver
:param version: should be major[.minor]
:return: "major.minor.0"
"""
return "{}.{}.0".format(*parse_sdk_version(version)) | b1006b7dca79e6c19d3849dfef298cf08b7c7f29 | 37,894 |
def RefDefaults():
"""
Returns dictionary of default values for all properties. These are used
to provide defaults to fields that we do not want to automatically
calculate dimensions for
"""
return {
'phi': {
'min':-180,
'max':180... | e6e87fd7c3b3a05f83808bebb410a6d5c687d3d3 | 37,895 |
import json
def load_json(path: str):
"""
Load the contents of a json file into a python dictionary
"""
with open(path) as f:
content = json.load(f)
return content | b35ae26ca303347a98ea3dd3ca42370279d19a2a | 37,896 |
import sys
def get_taxa_to_create(
es,
opts,
*,
taxonomy_name="ncbi",
taxon_ids=None,
asm_by_taxon_id=None,
):
"""Create a dict of taxa to create."""
taxa_to_create = {}
if not taxon_ids:
return {}
if asm_by_taxon_id is None:
asm_by_taxon_id = {}
taxonomy_te... | d640de236f1dab2e19f0b9539a4414163d651946 | 37,897 |
def repopulate(opt: Optimizer, selected_data: pd.DataFrame, target_size: int) -> Population:
"""
Create new generation.
"""
fittest_pop = Population(selected_data, opt.population.blueprint)
offspring_pop = make_new_generation(n=target_size,
parent_fitness_data... | 1ab2bbcee1f6f4b69aa2eba0fd4f1d48da770ba2 | 37,898 |
def DataframetolaTexTable(DF, alignment=None, fname=None,shade=False):
"""
Args:
df: pandas dataframe
alignment: python list of allignment of columns; default is ['c',..]; use ['c', 'p{4in}', 'c', 'c'] for wrapping
fname: path to save latex table
Returns:
object:
Returns... | 62be7748dbdce035b70468388d314c585696e275 | 37,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.