content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pickle
import asyncio
async def main(client):
"""
Main function of the graph processing. \n
- Gets client and tries to connect \n
- Manage last channel database and saves the last after each iteration to `db.pkl` \n
- Manage total graph and saves the composed graph after each iteration to `... | 62edae0f44f2436ff2b09e634986162c68961683 | 69,300 |
import requests
def get_user_info():
"""
Gets name, credits, etc.
"""
head = {"request": "users/info/", "api_key": API_KEY}
ret = requests.get(url,params=head)
if ret.status_code != 200:
raise ValueError
else:
return ret.json()['data'] | 794df7bc1c97bcf45df04ae59e4555f81183688f | 69,301 |
import math
def spd_pgs_make_theta_spec(data_in, resolution=None, colatitude=False):
"""
Builds theta (latitudinal) spectrogram from simplified particle data structure.
Input:
data_in: dict
Particle data structure
Parameters:
resolution: int
Number of theta po... | d3f751d6040f3263b049b42b3cab8a906b17d0f2 | 69,302 |
def check_interval(child_span, parent_span):
"""
Given a child span and a parent span, check if the child is inside the parent
"""
child_start, child_end = child_span
parent_start, parent_end = parent_span
if (
(child_start >= parent_start)
&(child_end <= parent_end)
):
... | 6c6a8e636ad181af821d185ba35f18db41d0ce77 | 69,303 |
from typing import Tuple
from typing import Union
from typing import List
def pseudo_event_list(
x_lim: Tuple[int, Union[int, None]],
y_lim: Tuple[int, Union[int, None]],
exp_time: float,
) -> Tuple[List, List]:
"""
Generate a pseudo-events list with positions and timestamps.
Args:
x_... | b0b67091d751f879354fd3c2afab536d8f663be5 | 69,304 |
def filter_entities_by_noise(
true: list, pred: list, noise_lower: float, noise_upper: float
) -> tuple:
"""
Filter to keep any tokens with a LEVENSHTEIN distance within particular range.
If not given, the tokens are kept as well.
"""
filtered_true = []
filtered_pred = []
for tok_true,... | 8add64fe828e17d1c532a1c67cc1f7da232ae5f2 | 69,305 |
def loss_numba(
alpha: np.ndarray,
X: np.ndarray,
Y: np.ndarray,
epsilon: float,
lambda2: float,
beta: float,
) -> (float, np.ndarray):
"""
Smoothed (with sigmoid) version of the loss, that also calculates the gradient.
This function is sped up with numba.
"""
epsilon... | b8dfdd750d6a823887d7aebafc5d4307c502a73b | 69,306 |
def update_posterior_states(A, obs, prior=None, **kwargs):
"""
Update marginal posterior over hidden states using mean-field fixed point iteration
FPI or Fixed point iteration.
See the following links for details:
http://www.cs.cmu.edu/~guestrin/Class/10708/recitations/r9/VI-view.pdf, slides 13- ... | 3eddf4484789e63f349fe2962fa88cacfa78945a | 69,307 |
import os
import urllib
def download_mnist(data_folder, dataset):
"""
Download and extract database
:param database_name: Database name
"""
image_files = ['train-images-idx3-ubyte.gz', 't10k-images-idx3-ubyte.gz']
label_files = ['train-labels-idx1-ubyte.gz', 't10k-labels-idx1-ubyte.gz']
u... | a63cc47b7d8b7b1f2a33d74b9d1b29383f95a624 | 69,308 |
def fftn(data, axes=None, **kwargs):
"""Fourier transform wrapper
Args:
data: microstructure
axes: the axes over which to perform the transform
Returns:
the transformation
"""
return FFTMODULE.fftn(data, axes=axes, **kwargs) | 573e33d593cca83ce09d8324d76522a1f3b140be | 69,309 |
def merge_to_length(a, b, length):
"""Merge 2 lists into a specific length.
This method will merge 2 lists into a short list, replacing the last few
items of the first list if necessary.
For example, a = [1,2,3], b = [4,5,6,7], and length = 6. The result will
be [1,2,4,5,6,7]. If length = 5, the r... | bdadb57c04567bae2a6890d7e5be981f1ba18fc9 | 69,310 |
def run_model(
V,
initial_aerosols,
T,
P,
dt,
S0=-0.0,
max_steps=1000,
t_end=500.0,
solver="lsoda",
output_fmt="smax",
terminate=False,
solver_kws=None,
model_kws=None,
):
""" Setup and run the parcel model with given solver configuration.
Parameters
----... | 089eb1ffec516d2ecf7a06e9a094da7f6f416775 | 69,311 |
import pathlib
import torch
import logging
import json
def train(
checkpoint_dir: str = None,
load_checkpoint_dir: str = None,
# Dataset Parameters
mask_prob: float = 0.15,
random_replace_prob: float = 0.1,
unmask_replace_prob: float = 0.1,
max_seq_length: int =... | 15c33e612597a7d5311594b45b0c2fe349d9a940 | 69,312 |
def calc_bpe_bulk_electrolyte_resistance(characteristic_length, sigma):
"""
The area specific charge transfer resistance through the bulk electrolyte
units: Ohm*m2
Notes:
Adjari, 2006 - "(area specific) bulk electrolyte resistance"
Squires, 2010 - does not explicitly define this... | f6a08cd5997de8954faa41d69e7abca1541e3fa0 | 69,313 |
import random
def generate_verification_code():
"""
随机生成6位数
:return:
"""
code_list = []
for i in range(10): # 0-9数字
code_list.append(str(i))
myslice = random.sample(code_list, 6) # 从list中随机获取6个元素,作为一个片断返回
verification_code = ''.join(myslice) # list to string
return verif... | a319391d782e2ce34b9d95a36a823df05267dcb8 | 69,314 |
def lin_a98rgb_to_xyz(rgb):
"""
Convert an array of linear-light a98-rgb values to CIE XYZ using D50.D65.
(so no chromatic adaptation needed afterwards)
http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
which has greater numerical precision than section 4.3.5.3 of
https://www.ado... | 385d5557536dc92e3ca3c0679ce9d7e0d6ba2722 | 69,315 |
import time
def record_time_interval(section, start_time, line_break=False):
"""Record a time interval since the last timestamp"""
end_time = time.time()
delta = end_time - start_time
if delta < 1:
delta *= 1000
units = "ms"
else:
units = "s"
if line_break:
logg... | 60255615dd2d80e4cdd480ab8090a93665521ceb | 69,316 |
def getConfigurations(identifier: str):
"""Gets the configuration information for the project.
Args:
identifier (str): The directory or sln file or csproj file to parse the output names from.
Returns:
Any: The configurations.
"""
return _dynamicallyDetermine(identifier, 'getConfigurations') | 97807df7e9e229cb828d31d66767b6c9cba02ed6 | 69,317 |
from typing import Dict
from typing import Set
def _get_cone_size_helper(self,
as_obj: AS,
cone_dict: Dict[int, Set[int]]) -> Set[int]:
"""Recursively determines the cone size of an as"""
if as_obj.asn in cone_dict:
return cone_dict[as_obj.asn]
... | be7084bb46759be2955d7d951da8adace99ae5fe | 69,318 |
def build_resnet_fpn_gnbn_lowlevel_gala_cbp10_backbone(cfg, input_shape: ShapeSpec):
"""
Args:
cfg: a detectron2 CfgNode
Returns:
backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
"""
bottom_up = build_resnet_gnbn_lowlevel_model_backbone(cfg, input_shape... | 958e2d28ffad1e51b26363632838724dfce52b8b | 69,319 |
def concat_tas_dict_vectorized(frame: pd.DataFrame):
""" Given a DataFrame containing columns for all TAS components, build a Series of the TAS string.
Arguments:
frame: the DataFrame from whose columns to build the TAS display string
Returns:
A series containing TAS displa... | 61644a2ba245c6501a5f175936d777b680503922 | 69,320 |
import torch
def sample_point_labels(instances, point_coords):
"""
Sample point ori_annotation_file_list from ground truth mask given point_coords.
Args:
instances (list[Instances]): A list of N Instances, where N is the number of images
in the batch. So, i_th elememt of the list cont... | ff1d4a02e178e377eb501129d804625f22b434ba | 69,321 |
def get_abstract(pubmed_id, prepend_title=True):
"""Get the abstract of an article in the Pubmed database."""
article = get_article_xml(pubmed_id)
if article is None:
return None
return _abstract_from_article_element(article, prepend_title) | e497c93f0afbb66eed567e741ae44207e7f47c15 | 69,322 |
def get_square_dark_gray_dataset():
"""Create the dark gray square set from the images in the directory.
This test set is not meant for training, just for prediction, thus it doesn't have a split nor
labels.
"""
return _get_images(SQUARE_GRAY_DARK) | 574814aee8271327975d42d765fa0d59732653a8 | 69,323 |
import numpy
def load_spectra_data(json_path, group_label, group_ref):
"""load results from log-linear mutation spectrum analysis
Parameters
----------
json_path : str
path to file produced by spectra command
group_label : str
Factor name, e.g. "group", from which counts are extra... | bc617f4ab101e37b2484994314a4f363b0613321 | 69,324 |
def part_of_speech(input_text):
"""Part of speech tagging of sentence."""
doc = PARSER(input_text)
pos_lst = []
for word in doc:
pos_lst.append((word.text, word.pos_))
return pos_lst | 09a8d31963982322ba7006b743ceb914b27371e7 | 69,325 |
import random
def random_order(ugraph, num_nodes):
"""
return a list of nodes in ugraph in random order
:param ugraph:
:param num_nodes:
:return:
"""
if len(ugraph) is 0 or num_nodes is 0:
return []
random.seed()
return random.sample(ugraph.keys(), num_nodes) | 4bad993f22f6435648e3e0ff30992f1930961dc9 | 69,326 |
import csv
def get_students(csv_file):
"""
:param csv_file: csv file with list of students.\
Each row contains: first_name, last_name, email
:type csv_file: str
:rtype: 2 lists existing_students and new_students [[username, email], ..]
"""
with open(csv_file) as ff:
reader = c... | 01f9a3022d49856604d78129ca943c0defe6307f | 69,327 |
import requests
import re
def get_filenames(url):
"""
The location where the hydat database has the sqlite database
file itself, as well as supporting documentation.
This function returns the filenames of the documentation pdfs
in both languages, as well as the database filename.
Input the url... | 0ccfc46c74d5b89be904dd093a40b82cd4abed5d | 69,328 |
from typing import List
from typing import Tuple
def mock_ORBIT(
params: List[Quantity],
) -> Tuple[float, List[float], List[float], List[List[str]], List[int]]:
"""A function to mock ORBIT behaviour but return fixed non-changing values for
the goal and results
Parameters
----------
params : ... | 3e92eb99b413cfa10cf55eee3265d8ca486f902e | 69,329 |
def count_correl_above(correl_mat,limit):
"""
count numbers of correlation matrix elements above a certain threshold
Args:
correl_mat (array): Matrix correlation values
limit: Threshold for counting
Returns:
(float): Percentage of correlations above the limit
"""
... | 00fb1f0aea268a9333c3741255a2fd7cafcb43ee | 69,330 |
import click
import os
import getpass
def _account(keystore_name, password=None):
"""
utility function to get the keypair from the click context
:return: (account, keypath)
"""
ctx = click.get_current_context()
kf = ctx.obj.get(CTX_KEY_PATH) if keystore_name is None else keystore_name
if n... | efd6e8160f36a8510683504ae9afc599e87ac495 | 69,331 |
def threshold_gaussian(inputs, params):
"""Given importance scores, calculates stdev cutoff
and thresholds at that pval
Args:
signal: input tensor
pval: the pval threshold
Returns:
out_tensor: output thresholded tensor
"""
# get features and pass rest through
features = i... | f8934c028b9d0f68fc62703e881296e2a5042d36 | 69,332 |
def prepare_mhe(
biorbd_model: biorbd.Model, final_time: float, n_shooting: int, x_ref: np.ndarray, rt_ratio: int, use_noise: bool
):
"""
Prepare to build a blank ocp witch will be update several times
Parameters
----------
biorbd_model: biorbd.Model
biorbd model build with the bioMod
... | 47f5793de2888f4d4f96f4e23e764e38173eed18 | 69,333 |
def map_gazette_to_nodes(df, gazette_data, gazette_column):
"""[summary]maps the given gazette reference data and column to the naptan
nodes data.
Arguments:
df {[geodataframe]} -- [the naptan dataframe]
gazette_data {[gazette reference data]} -- []
gazette_column {[pandas series c... | 41fa9a4286f696d424aa7e7c2b201f1970137339 | 69,334 |
def eval_objectives(objectives, database):
"""Evaluate fitness/cost"""
fitness = np.array([objv(database) for objv in objectives])
return fitness | f73d61079121a84c112040890e1fdc01bd5980ce | 69,335 |
from pathlib import Path
def subtract_dark(
frames : ccdp.ImageFileCollection,
master_dark : CCDData,
output_path: Path
) -> ccdp.ImageFileCollection:
"""
Subtract dark from one of more frames
Parameters
----------
frames : ccdproc.ImageFileCollection
Frames fr... | a035cf28da49dbda1d62b56cf6efdd47c610180d | 69,336 |
import re
def derive_ip_address( cidr_block, delegate, final8 ):
"""
Given a CIDR block string, a delegate number, and an integer
representing the final 8 bits of the IP address, construct and return
the IP address derived from this values. For example, if cidr_block is
10.0.0.0/1... | 8c80d39fd1a86eee4ac61250bebe58760a2170ea | 69,337 |
def make_gaussian_mask_same(roi_point, boxes, sigma, shape):
"""Generates mask targets for each proposal.
Inputs:
roi_point: [NUM_INSTANCES, num_keypoint, 2] of float32. normalized point
boxes: [NUM_INSTANCES, 4] normalized location
Returns: Target masks.
masks: [NUM_INSTANC... | 254b290105fd8e7afe1935a2221ce4282e23f0d7 | 69,338 |
def fix_bad_indent(data_in: tuple) -> tuple:
"""Remove empty lines, bad indentation,...
Args:
data_in: list of lines
Returns:
tuple: cleaned text lines
"""
temp = []
# filter the '' out of data_in and store to temp
for x in data_in:
if x != "":
temp.append... | 1901b7e0aad73ade4ab59f7ab56f81a67fc0ab1f | 69,339 |
import click
from typing import Optional
import pathlib
import os
import sys
import yaml
from typing import Tuple
import json
def notion(
input_file: click.Path,
database_id_opt: str,
config_file: Optional[click.Path],
dry_run: bool,
) -> None:
"""
Create or update one or more rows in a Notion... | 931b2828d8afe280f8b4ae59450e7e12f286cad1 | 69,340 |
def get_cmo():
"""
update the Current Management Object (cmo) to current mbean in wlst.
:return: updated cmo
:raises: PyWLSTException: if a WLST error occurs
"""
_method_name = 'get_cmo'
_logger.entering(class_name=_class_name, method_name=_method_name)
try:
wlst.updateCmo()
... | 29345aeff4a9aebaed22e03edef7c48fa0e33c4f | 69,341 |
import itertools
def expand(elements):
"""Expand Transition Operations."""
transitions = []
# If string
if isinstance(elements, str):
trans_x = TransOperation(elements)
# Expand if there is list argument
if trans_x.has_list_arg:
expanded_trans_list =... | a6b82fe175a571f3778e2f3ec497d5d762ba94bf | 69,342 |
import time
def scanForDevices(scantime=5):
"""
@param scantime: The time (in seconds) to scan for BLE devices in range
@type scantime: float
@return: A DeviceList of any devices found during the scanning process
@rtype: DeviceList
"""
if args.verbose:
print("Starting BLE device sc... | d3e1abce48393bab911cfc49dcd0c45f71be7d10 | 69,343 |
def get_notify():
"""Get the notification."""
return Options.notify | 37777270c41a4735d5b0e9a8189610718252a152 | 69,344 |
def compress_indices(indices: utt.Vector) -> utt.NumpyVector:
"""
Given a vector of group ``indices`` per element, return a vector where the group indices are
consecutive.
If the group indices contain ``-1`` ("outliers"), then it is preserved as ``-1`` in the result.
"""
unique, consecutive = n... | a54566c519d426f80332c3b687bb13d4ef3669b9 | 69,345 |
def input_fn_builder(input_files,
is_training,
drop_remainder,
max_seq_length=32,
max_predictions_per_seq=5,
num_cpu_threads=4,
batch_size=16,
is_prediction=False):
"""Cre... | cb8efce5a64504789692fd52e7a4e2a3f9c9f4e1 | 69,346 |
from typing import Optional
from typing import Dict
def __get_source_file_for_analyzer_result_file(
analyzer_result_file_path: str,
metadata: Optional[Dict]
) -> Optional[str]:
""" Get source file for the given analyzer result file. """
if not metadata:
return None
result_source_files = {... | c40dec03234954bdb6cb43d43e0988d98c6f0bbd | 69,347 |
from typing import Tuple
from typing import List
from pathlib import Path
def synchronize_directories(directory_names: Tuple[str, ...],
dry_run: bool, verbose: bool) -> Tuple[str, ...]:
"""Synchronize some directories.
* Arguments:
* *directory_names* (Tuple[str, ...):
... | 58eb46ec717259c8935407668fe789c708d4df4c | 69,348 |
def _maybe_wrap_runtime_deps_as_build_time_deps(
name,
target,
visibility,
path_in_output = None,
dynamic_path_in_output = False):
"""
If necessary (see "When..."), wraps `target` with a new target named
`name`, in the current project.
Returns `(False, target)` i... | e9b620306e4439d2ed35995a2c2b9f6926d414f2 | 69,349 |
from typing import List
def fitness_proportionate_selection(evaluated_population: List[Eval], random_seed: int = 12345,
num_elites: int = 5) -> List[Parents]:
"""Uses the fitness proportionate selection to select parents from the population.
This selects chromosomes from t... | 0fd80ceff85f3abf4542d36b5279b922171a37b4 | 69,350 |
import uuid
import json
import logging
def schedule(issue, patchset_id, builds):
"""Schedules builds on buildbucket.
|builds| is a list of dicts with keys:
bucket: required, target buildbucket bucket name. May have "master." prefix.
builder: required.
revision
properties
"""
account = models.... | 63a8e0ffa85bcd81faa71e6b057c426949ea340a | 69,351 |
def make_trans_order_data(busi_type):
"""
交易订单号,仅需网络支付填写
:param busi_type:
:return:
"""
if busi_type == "01":
trans_order = make_random_num(20)
else:
trans_order = ""
return trans_order | 3b47fa672e3b600ed010ef4d62b4cad7a132074c | 69,352 |
import functools
import torch
def get_pc_inpainter(sde, predictor, corrector, inverse_scaler, snr,
n_steps=1, probability_flow=False, continuous=False,
denoise=True, eps=1e-5):
"""Create an image inpainting function that uses PC samplers.
Args:
sde: An `sde_lib.SDE` ... | 3f04f8e38f92026d023547a3aad4ce3a6a2e9a82 | 69,353 |
def _CreateUniqueJobKeyForYamlJob(job):
"""Creates a key from the YAML job instance's attributes passed as input.
Args:
job: An instance of a parsed YAML job object.
Returns:
A tuple of attributes used as a key to identify this job.
"""
retry_params = job.retry_parameters
return (
job.schedul... | 035ef1dff1033e49a3f521dfaf7567bfdd5d92ae | 69,354 |
def THALIANA():
"""Boolean network model of the control of flower morphogenesis in Arabidopsis thaliana
The network is defined in :cite:`Chaos:2006`.
Returns:
(BooleanNetwork)
"""
return BooleanNetwork.from_file(_path + '/thaliana.txt', name="Arabidopsis thaliana", keep_constants=True) | 1eb8f7018035cc5df6eec4124a3a3c76249e2549 | 69,355 |
import scipy
def discount_cumsum(x, discount):
"""
magic from rllab for computing discounted cumulative sums of vectors.
input:
vector x,
[x0,
x1,
x2]
output:
[x0 + discount * x1 + discount^2 * x2,
x1 + discount * x2,
x2]
"""
re... | 1d90659cbb0fa1e98f012e5a21cc8fd74db59be0 | 69,356 |
import ast
def unpool_theory_atom(x):
"""
Removes all pools from the conditions of theory atoms.
See note in unpool_term.
"""
x.elements = list(chain.from_iterable(
(ast.TheoryAtomElement(element.tuple, condition)
for condition in unpool_list_with(unpool_literal, element.conditio... | 390b482ef12f1c0679e0f351671197415020b957 | 69,357 |
def fixture_response_get_docs(
base_url: str, repo_owner: str, repo_name: str
) -> ResponseLabel:
"""Return a dict respresenting the GitHub API response body for the docs
label.
"""
return {
"id": 2222,
"node_id": "4444",
"url": f"{base_url}/repos/{repo_owner}/{repo_name}/lab... | 05bfcef0927f6202ff0ae3445dd2d128187de751 | 69,358 |
def box(parser, token):
"""
{% box label [args] [kwargs] %}
All args/kwargs are passed directly to callable defined in the setting
BOXES_CAN_EDIT_CALLABLE which returns True or False to determine if the
box can be edited.
"""
return BoxNode.handle(parser, token) | 77aafb61e49dec8b040046838d22060fbe79b2ee | 69,359 |
from typing import Optional
def _create_projector_config(
path_metadata: str, path_sprite: Optional[str]
) -> projector.ProjectorConfig:
"""Creates a projector-config as needed to show the embedding in Tensorboard."""
config = projector.ProjectorConfig()
embedding = config.embeddings.add()
embeddi... | 4742c89c47630be9a8f7527fa3b1480df9cadb88 | 69,360 |
import select
from datetime import datetime
def edit_project(project_id):
"""
Takes "name" and/or "published" as JSON data
Returns "msg" and "project_id" on success, otherwise 40x
"""
request_data = request.get_json()
if not request_data:
return jsonify({"msg": "No data provided."}), 4... | e4cdee50b4d7e40b950b62f8d0f388588075895e | 69,361 |
import http
import socket
import ssl
import errno
def _is_conn_error(exception):
"""
Checks if the given exception resembles an error in the network connection, e.g. a timeout or connection
abort.
"""
conn_exceptions = (
BrokenPipeError, # Raised on SIGPIPE
ConnectionAbortedErr... | 3c5b23060e60a4a763ada5812ec008ea6dcf87a9 | 69,362 |
def log_posterior_helper(ip: np.ndarray, dof: float, n: int) -> float:
"""Computes the log-density of the Student-t distribution given the inner
product, the degrees of freedom, and the dimensionality of the space.
Args:
ip: The Mahalanobis inner product regularized by the degrees of freedom.
... | aedee887eaacd65786a4dbdea321aeb2857604bd | 69,363 |
def get_notification(
request, annotation, action
): # pylint: disable=too-many-return-statements,too-complex
"""
Check if the passed annotation and action pair should send a notification.
Checks to see if the annotation event represented by the passed annotation
and action should trigger a notifi... | 6f85f99c1fe030b68a4cb187c28ae3066ad8c05b | 69,364 |
import base64
def arr_to_b64(numpy_arr, ensure_RGB=True):
"""Convert a numpy array into a b64 string"""
# Generate image in bytes format; will convert using `tobytes` if not contiguous
image_pil = PIL_Image.fromarray(numpy_arr)
if ensure_RGB:
image_pil = image_pil.convert('RGB')
byte_io ... | 87ab965ecb8f11bc59209ff6de85b14ae123b43a | 69,365 |
import os
import grp
def is_effective_group(group_id_or_name):
"""Returns True if group_id_or_name is effective group (id/name)."""
egid = os.getegid()
if str(group_id_or_name) == str(egid):
return True
effective_group_name = grp.getgrgid(egid).gr_name
return group_id_or_name == effective_... | de279d789d85b216f5da59762571dda5bfa9d2ab | 69,366 |
def testdat(testdir):
"""Path to the testdat directory"""
return testdir / "testdat" | d7c278fba718164d50863e3fb353155a1ff00eee | 69,367 |
import pandas as pd
import os
def stars_cyg(path):
"""Hertzsprung-Russell Diagram Data of Star Cluster CYG OB1
Data for the Hertzsprung-Russell Diagram of the Star Cluster CYG OB1,
which contains 47 stars in the direction of Cygnus, from C.Doom. The
first variable is the logarithm of the effective temperatur... | 0acf64eaaf9fbefbf71941174647cbd4e96428ed | 69,368 |
def quartznet15x5(**kwargs):
"""
QuartzNet 15x5 model from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable
Convolutions,' https://arxiv.org/abs/1910.10261.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for mod... | 2140ea59b65368ef9357733c7c942d1671911bcd | 69,369 |
from typing import Callable
import re
import inspect
from typing import Sequence
from typing import Union
def make_parser(
func: Callable, add_short_args: bool = True, validate_dict_types: bool = False
) -> ArgumentParser:
"""
Automatically configure an argparse parser for `func`.
To get automatic
... | 57e92d38e46369e83e8cdcf74e5994b5407bf1b8 | 69,370 |
def hub_modules():
"""Return list of hub modules"""
global modules
modules = import_modules()
context = {
"modules": modules,
}
result = render_template(
"powershell/modules.ps1",
**context,
).encode()
result = b64encode(encrypt_aes((result... | 72bfec7c5d6a2b44314c64bcb2f3d973972a7773 | 69,371 |
import os
def get_image_file(client, tile: LookerPresentationTile, width=960, height=540):
"""By calling the Looker API, convert a tile object/definition into an actual .png image"""
query_api = looker.QueryApi(client)
element_request = {
"body": tile.body,
"result_format": 'png',
... | 6d4af011153390095f31ecd34463edc2cb102465 | 69,372 |
from typing import Tuple
def gcb_build_base_images() -> Tuple[int, str]:
"""Build base images on GCB."""
return gcb_build(get_build_config_file('base-images.yaml'), 'base-images') | 2534ee05655567f2fe7f6e51ba1a50d75e1b2547 | 69,373 |
import logging
import os
import re
def GetFastqGzFiles(dirn,pattern=None,file_list=None):
"""Return list of fastq.gz files in target directory
Optionally also specify a regular expression pattern that file
names must also match in order to be included.
Arguments:
dirn: name/path of directory t... | 779ea20edbbd71fed9fe8132467e9d8ae1ca6135 | 69,374 |
def load_data(source=None):
"""Load original data, and key lists"""
if 'parquet' in source:
df = pd.read_parquet(source)
else:
df = pd.read_csv(source)
df['TotalCharges'] = df['TotalCharges'].str.replace(r' ','0').astype(float)
df['Churn'] = df['Churn'].apply(lambda x: 0 if x... | 62ae7305d32affabeebc5cb7bd781bda919b73f5 | 69,375 |
from typing import Optional
from typing import Dict
from typing import Any
from typing import Tuple
from typing import Union
from typing import List
import warnings
import time
from typing import OrderedDict
import torch
import types
def fit_gpytorch_manifold(
mll: MarginalLogLikelihood,
bounds: Optional[Para... | 78aebdf3140d20137599cb5e5f8175b3f70b1506 | 69,376 |
def sigmoid(x):
"""
Simple sigmoid function. Warning: when overflow problems are encountered use sigmoid2 instead.
:param x: numerical value or numpy.ndarray
:return: sigmoid(x)
"""
return 1 / (1 + np.exp(-x)) | 09f8809a3bdc494f744aa12e5e9e6dff782fe28b | 69,377 |
def send_receipt(payload: receipt_schemas.atrributes, background_tasks: BackgroundTasks, db: orm.Session = Depends(get_db)):
"""
An endpoint to send receipts.
Note: The message field in the payload should be HTML formatted.
"""
pdf_name = (payload.subject)+str(uuid4().hex)+".pdf"
... | 34124b1168f17edd41e26d4af01e2158b07fa32a | 69,378 |
def _sample_haar_mtx(size):
"""Samples Haar-distributed matrices.
Samples Haar-distributed matrices that are useful to generate
random matrices for COE, CUE and CSE ensembles.
Args:
n (int): matrix size.
Returns:
numpy array containing Haar-distributed random matrix.
"""
#... | 3adfb047fb87deb1612ed059380d4b907743deba | 69,379 |
import math
def crop_helper(image_stack, crop_size):
""""Helper function to take an image, and return crops of size crop_size
Inputs:
image_stack (np.array): A 4D numpy array of shape(points, rows, columns, channels)
crop_size (int): Size of the crop to take from the image. Assumes square cro... | b99c257dd268ec48624161e1ad18b7d2537f88f5 | 69,380 |
import tqdm
def set_progeny_size(G, root):
"""
Store as a node attribute the number of leaves below a given node. Traverses from the root provided.
:param G:
input tree
:param root:
Root of tree
:return:
Graph with progeny size stored as a node attribute (for some nod... | 98de04cd2e7221f464ac52136e050968828e0491 | 69,381 |
def bbox_info_from_point_list(point_list):
""" Generate bounding box info from a point list. """
if len(point_list) == 0:
return BoundaryInfo()
x = [c[0] for c in point_list]
y = [c[1] for c in point_list]
return BoundaryInfo(min(x), max(x), max(y), min(y)) | a1b44edf26c1e187057d9756c21a83ddce8fb6ad | 69,382 |
def upgrade_available():
"""Check for upgrade for ceph
:returns: whether an upgrade is available
:rtype: boolean
"""
c = config()
old_version = ceph_utils.resolve_ceph_version(c.previous('source') or
'distro')
new_version = ceph_utils.resolv... | 33d501182176e76e911272b3d83a425044b88ca6 | 69,383 |
import pytz
from datetime import datetime
def get_current_timezone(location="Europe/Bucharest"):
""" @location: Continent/City"""
if location not in pytz.all_timezones:
raise TimezoneNotFoundError
current_datetime = datetime.now(pytz.timezone(location)).strftime("%d.%m.%Y-%H:%M:%S")
_location... | ea0e59160c188d2ba985c806a2fa8ad6a59f2a34 | 69,384 |
def CARAutility(c, alpha):
"""
Evaluates constant absolute risk aversion (CARA) utility of consumption c
given risk aversion parameter alpha.
Parameters
----------
c: float
Consumption value
alpha: float
Risk aversion
Returns
-------
(unnamed): float
Uti... | 51cff418899872c201a5cf3a4989320e3381b2f4 | 69,385 |
def solve_part1(data: list[str]) -> int:
"""
Finds the solution to part 1 (the power consumption of the submarine)
"""
gamma = ""
epsilon = ""
for bits in zip(*data):
gamma += more_common_bit(bits)
epsilon += less_common_bit(bits)
return multiply_binary(gamma, epsilon) | 46a7af1329d335271d2278de4a87e0a6c3df7983 | 69,386 |
def allowed_anions():
"""
Args:
Returns:
list of elements (str) that tau should be able to classify
NOTE: only trained on ['O', 'F', 'Cl', 'Br', 'I']
"""
return ['O', 'S', 'Se', 'Te', 'F', 'Cl', 'Br', 'I', 'N', 'P', 'As', 'Sb'] | 337c25b4d2097e920885630fe52c322ac23480b0 | 69,387 |
def sigmoid_prime(z):
"""Derivative of the sigmoid function.
sigmoid函数的导数"""
return sigmoid(z) * (1 - sigmoid(z)) | 15b3512d81ae0562e527bddefb20c25aee9e7ea1 | 69,388 |
def _RequireOpenQueue(fn):
"""Decorator for "public" functions.
This function should be used for all 'public' functions. That is,
functions usually called from other classes. Note that this should
be applied only to methods (not plain functions), since it expects
that the decorated function is called with a ... | fe1b79b33e092bc5f1e5a4afe78f3ec23b2f7102 | 69,389 |
def get_human_annotation(config: Config) -> str:
"""Get the best human genome annotation available in config."""
if config.use_hg38:
return "hg38"
elif config.use_hg19:
return "hg19"
else:
raise AnnotationError("no available human annotation in config") | 5e52b9f668a17894767b85ce566b211d79c64652 | 69,390 |
def query_yes_no(question,default="yes"):
"""
Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is... | f6c767d14b425716ee72ab6b8fbc5e596cb52474 | 69,391 |
def get_mse_sorted(series1, series2):
"""
sorted but not normalized values
the series will be sorted
"""
assert len(series1) == len(series2)
mse = 0.0
series2_s = sorted(series2)
for index, data1 in enumerate(sorted(series1)):
diff = (data1 - series2_s[index])
mse += dif... | 9debccd97dd146468e28c01f9db5e8a80f55e4db | 69,392 |
def AutoGooey(fn): # pragma: no cover
"""Automatically show a Gooey GUI if --gui is passed as the first argument, else it will just run the function as normal"""
if check_gui_arg():
return gooey.Gooey(fn)
else:
return fn | 96abab8921fd9db18ce8b401cc66cd210f96f82c | 69,393 |
def parity(self, allow_rescaling_flag=True):
"""
Returns the parity ("even" or "odd") of an integer-valued quadratic
form over `ZZ`, defined up to similitude/rescaling of the form so that
its Jordan component of smallest scale is unimodular. After this
rescaling, we say a form is even if it only re... | 12c68f6dfb447cd88d59367ad1fed9c2ba9aedde | 69,394 |
def add_cc_month(path):
"""
Adds complete common crawl month
"""
programms = []
for file in path.iterdir():
print(file.suffix)
if file.suffix == '.gz' and 'head' in file.name:
print(f'Adding lines from {file}')
p = Process(target=add2mongo, args=(file,))
... | be39951a1478204b3ded474d875314a75d45842a | 69,395 |
def pitches_leveinsthein_diff(original, compare_to, noteNode1, noteNode2, ids):
"""Compute the leveinsthein distance between two sequences of pitches
Arguments:
original {list} -- list of pitches
compare_to {list} -- list of pitches
noteNode1 {annotatedNote} --for referencing
not... | 74cb07c5b4a3c6d8d5ec1135371f30a1011a805f | 69,396 |
def edit_extensions(request):
"""
Edit known file extensions
:param request:
:return:
"""
form_set = modelformset_factory(FileExtension, form=FileExtensionForm, can_delete=True, extra=3)
qu = FileExtension.objects.all()
formset = form_set(queryset=qu)
if request.method == 'POST':
... | 8fede9fa4a7734bb2bc4806eba674b66bf473515 | 69,397 |
def get_sentiment(news: NewsObject) -> float:
"""
Given a news object, return the probability that its underlying sentiment is liberal
"""
return sentiment_model(news.title + news.content) | e2fe4cf89f7bd6377e7ccc333e70c31ef992123e | 69,398 |
from pathlib import Path
import tempfile
import shutil
import yaml
def fork():
"""Generate a local fork of the current state of naucse for testing.
1) Copies the entire local state of naucse
2) Adds one working course and one working run
3) Commits everything on branch ``test_branch``
4) Adds one... | 605f98d2b77d7133aeb5da4b03816eac0814f083 | 69,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.