content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_data(filename: str) -> pd.DataFrame:
"""
Load city daily temperature dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (Temp)
"""
df = pd.read_csv(filename, parse_dates... | 8be985b6ea729a94db4e90ae6696f00a4a0061c5 | 3,626,700 |
def document_entity_generator(*ehrpreper_files):
"""Generator of DocumentEntity"""
return (
document
for ehrpreper_file in ehrpreper_files
for model in load(ehrpreper_file)
for document in model.documents
) | 823c78590507b05f87e6c0fade73d949e67519e9 | 3,626,701 |
import csv
def readCSV(filepath):
"""
Method that reads a list of values from a CSV file
Parameters:
filepath (str): The path of the CSV file
Returns:
values (list): The list of values
"""
values = []
with open(IP_LIST, "rt", encoding="ascii") as f:
... | 590993fff105b414beedee0aa92279c1bd237f39 | 3,626,702 |
import tqdm
import scipy
def smooth_voxels(voxels, padding_vox=10, sigma=2):
"""
TODO: smoothing params and padding should be in um
padding_vox: zero padding to apply to kernals to ensure that smoothing doesn't go over edges
voxels: binary voxel mask
sigma: std dev for gaussian
"""
# pad ... | 34123b139d89dfd0e8456afbff3c661ee55b3d84 | 3,626,703 |
from typing import Tuple
def calc_gamma(data: np.ndarray) -> Tuple[str, int]:
"""Return a tuple consisting of binary form/string and decimal of gamma value."""
n = np.array([len(data)] * len(data[0]), dtype=int)
ones = np.count_nonzero(data, axis=0)
zeros = n - ones
gamma_bin = ''.join(map(str, (o... | 62ece1fdc89eb3da81d94bedfc846638ed2f6161 | 3,626,704 |
def read_messages(message_file):
""" (file open for reading) -> list of str
Read and return the contents of the file as a list of messages, in the
order in which they appear in the file. Strip the newline from each line.
"""
# Store the message_file into the lst as a list of messages... | 0e4b1a6995a6dd25ab3783b53e730d0dd446747c | 3,626,705 |
def find_outliers(data, threshold=3.5):
"""
Function to remove outlier data, based on
the median absolute deviation from the median.
Note that the function supports asymmetric
distributions and is based on code from the
included reference
Parameters
----------
data: Pandas Series-li... | da0b401c8e7d868e236d9493217ee0526b1ef7d4 | 3,626,706 |
def result_message(iden, result=None):
"""Return a success result message."""
return {
'id': iden,
'type': TYPE_RESULT,
'success': True,
'result': result,
} | a0d704b39d69f355b2d6e5c772c02be65d13d9db | 3,626,707 |
import scipy
def _smesolve_single_trajectory(data, L, dt, tlist, N_store, N_substeps, rho_t,
A_ops, e_ops, m_ops, rhs, d1, d2, d2_len, dW_factors,
homogeneous, distribution, args,
store_measurement=False,
... | c688520f6b116b6338594687770ecc9b237c47c8 | 3,626,708 |
def reconstruction_error(S1, S2):
"""Do Procrustes alignment and compute reconstruction error."""
S1_hat = compute_similarity_transform_batch(S1, S2)
return S1_hat | ce84df6c1406a9b4e417fa379a49fdffa2ab534b | 3,626,709 |
def encode_bboxes(boxes):
"""[This function processes rectangles from Azure API and converts it to cv2.polylines format]
Args:
boxes ([list]): [list of x, y coordinates of rectangles]
Returns:
[list]: [np.array of formatted for use with cv2.polylines function call]
"""
polygon... | 855cd3bbf206d2adf1f046073a78e45b876b7973 | 3,626,710 |
def createTokenFromCredentials(body):
"""
Given a request body with a username and a password, generates a JWT access token or
returns an error response.
"""
valid = False
try:
user: User = User.objects(username=body["username"]).get()
valid = user.validatePassword(body["password... | c960ae9f3cc4417192ef6b8a80a01cec957c29ad | 3,626,711 |
def upload_forecast_batch(conn, json_io_dict_batch, forecast_filename_batch, project_name,
model_abbr, timezero_date_batch, overwrite=False):
"""
Uploads a batch (list) of JSON dictionaries to the model corresponding
to the args. This only iterates through timezeros, not models or ... | 6ae4c6d108266aa142217298ff530cfd0bbe3817 | 3,626,712 |
def count_team_forecasts_draw(team_id):
"""
count the number of draw forecasts for a team
"""
request = """
SELECT COUNT(*)
FROM season_forecast, season_fixture
WHERE season_forecast.fixture_id = season_fixture.id
AND (
(season_fixture.team_a_id = '%(team_id)s' AND season_forecast.s... | 8c0831fe07a66107178e32ce930e15395e921d5b | 3,626,713 |
def get_args():
"""Add custom knn arguments."""
parser = extraction_argument_parser()
parser.add_argument("-k", "--knearest", type=int, default=5,
help="When using a knn classifier, this is the number "
"of neighbors to check. "
"Defaul... | c8191ea8de39179aa3637041d2059a4bf1222491 | 3,626,714 |
from typing import Union
def start_xql_query_polling_command(client: Client, args: dict) -> Union[CommandResults, list]:
"""Execute an XQL query as a scheduled command.
Args:
client (Client): The XDR Client.
args (dict): The arguments to pass to the API call.
Returns:
CommandResu... | 648d9e5e0433cfc13a4f4d0d80ed5117520e2044 | 3,626,715 |
import os
import pickle
def preprocess(path):
"""Transform the 3D image to 2D slices, do normalization and save."""
all_folders = os.listdir(path)
flair = []
dwi = []
seg = []
cnt = 0
for folder in all_folders:
folder_individual = path + '/' + folder + '/'
all_data_individu... | b9e6f50ceb29b7b5ec07b5874452fda374fa8d2e | 3,626,716 |
import logging
def change_main_address_column(df: gpd.geodataframe.GeoDataFrame) -> gpd.geodataframe.GeoDataFrame:
""" Changing the main address column for building gdf
:param df: modified gdf (address column changed)
"""
# Dropping cadaste address from df
df.drop(c.adr_main, inplace=True, axis=1... | a775d569b6c4d8a87a4526a920f82d6c028e44f0 | 3,626,717 |
import os
def _ToGypPath(path):
"""Converts a path to the format used by gyp."""
if os.sep == '\\' and os.altsep == '/':
return path.replace('\\', '/')
return path | a2f4864c7a2cc844716ef17fffcd088843f23b3a | 3,626,718 |
def hello_world1():
"""
Flask endpoint
:return: TXT
"""
return "Hello World From App 1!" | fed4dcf04234ca8c47885d0702f284c13136f52f | 3,626,719 |
def vpt2(prog, output_str):
""" Reads VPT2 information from the output string.
:param prog: electronic structure program to use as a backend
:type prog: str
:param output_str: string of the program's output file
:type output_str: str
"""
return pm.call_module_function(
... | 0ec6c3a4e31d2188718430b62c4943ecbfdf2920 | 3,626,720 |
def learning_rate_schedule(current_epoch,
base_learning_rate,
lr_boundaries,
lr_multiplier):
"""Handles linear scaling rule, gradual warmup, and LR decay.
The learning rate starts at 0, then it increases linearly per epoch.
After 5 e... | 78a284261a4a6040a620556d1d5177ea73335942 | 3,626,721 |
def cradmin_titletext_for_role(context, role):
"""
Template tag implementation of
:meth:`django_cradmin.crinstance.BaseCrAdminInstance.get_titletext_for_role`.
"""
request = context['request']
cradmin_instance = request.cradmin_instance
return cradmin_instance.get_titletext_for_role(role) | 8e6a29c369c5ae407701c12dc541e82dda31f193 | 3,626,722 |
def to_unicode_for_identify(hash):
"""convert hash to unicode for identify method"""
if isinstance(hash, unicode):
return hash
elif isinstance(hash, bytes):
# try as utf-8, but if it fails, use foolproof latin-1,
# since we don't really care about non-ascii chars
# when runni... | 5071bf71e220389c87913e90a0fef509bded40bf | 3,626,723 |
from pathlib import Path
def url_to_path(url: URL) -> Path:
"""Convert a file:// URL into a UNIX path."""
return Path(url.path) | 42d7bdab2a539c3c2e65f3b36e45e2a32f5fdb39 | 3,626,724 |
def ver_notas(request):
"""Ver notas de investigaciones o documentos"""
form_elegir = BuscadorInvestigacionesForm(request.user)
form_crear = NotaForm()
context = {
'form_elegir':form_elegir,
'form_crear': form_crear,
"title":'Notas de investigaciones',
... | 4693ac1907943c1642c4430c8e5f1d502cacc495 | 3,626,725 |
def training_config(estimator, inputs=None, job_name=None, mini_batch_size=None):
"""Export Airflow training config from an estimator
Args:
estimator (sagemaker.estimator.EstimatorBase):
The estimator to export training config from. Can be a BYO estimator,
Framework estimator or... | cebeb96eb478332ed48d6896ecc989951a13a325 | 3,626,726 |
def stft(sig, fs=16000, win_type="hann", win_len=0.025, win_hop=0.01):
"""
Compute the short time Fourrier transform of an audio signal x.
Args:
x (array) : audio signal in the time domain
win (int) : window to be used for the STFT
hop (int) : hop-size
Returns:
X ... | 925626e7d131edfbd226ac1373ab6d5bdfe7c1ea | 3,626,727 |
from bs4 import BeautifulSoup
import re
def parse_problem_statement(problem_code: str):
"""
This function takes a Leet Code problem code as input and
scrapes the problem statement from the site and returns
the parsed problem statement as a text file.
PARAMETERS:
-----------
problem_co... | cc20a7193f51ae6fb4627d546c0bb9e0d76b5e83 | 3,626,728 |
import sys
import traceback
def get_raising_file_and_line(tb=None):
"""Return the file and line number of the statement that raised the tb
Returns: (filename, lineno) tuple
"""
if not tb:
tb = sys.exc_info()[2]
filename, lineno, _context, _line = traceback.extract_tb(tb)[-1]
return f... | f6b0b7878f0a4a322eb4d1ea3f6bdbf1b6ee7530 | 3,626,729 |
def get_name():
""" should return the name of the tool as listed on http://qcomp.org/competition/2020/"""
return "PET" | b26b13117711c7943392cde96244afe496cc9cc4 | 3,626,730 |
def gabby_gums_dark_green() -> Colour:
"""A convenience function that returns a :class:`Colour` with a value of 0x508787 (R80, G135, B135)."""
# discord.Color.from_rgb(80, 135, 135))
return Colour(0x508787) | fcf5f7b3669ee2bb92fb433238cbe6257497df23 | 3,626,731 |
def compute_average_oxidation_state(site):
"""
Calculates the average oxidation state of a site
Args:
site:
Site to compute average oxidation state
Returns:
Average oxidation state of site.
"""
try:
avg_oxi = sum([sp.oxi_state * occu
f... | 8ea8611984f171a84a2bac17c0b49b70c85bfba4 | 3,626,732 |
import os
def est_dans_collection(collection, numero):
"""
Teste si le puzzle dont le :numero: est fourni en paramètre fait partie de la collection
dont le nom est donné dans le paramètre :collection:
:param collection: Nom de la collection considérée
:param numero: Numéro du puzzle recherché dan... | 9a0f6a988fdb4206c210fa2591f28b2f85ab2456 | 3,626,733 |
def lookup_zones(output_file=None,opts=None):
"""
This data source provides a list of available zones in the current region.
> This content is derived from https://github.com/terraform-providers/terraform-provider-ucloud/blob/master/website/docs/d/zones.html.markdown.
"""
__args__ = dict()
... | de507b4d8b02281975b7cd8da003a556d41ed62f | 3,626,734 |
from pypy.objspace.std.listobject import W_ListObject
def PyDict_Next(space, w_dict, ppos, pkey, pvalue):
"""Iterate over all key-value pairs in the dictionary p. The
Py_ssize_t referred to by ppos must be initialized to 0
prior to the first call to this function to start the iteration; the
function ... | f3e9591f6c0b21b9e64327d838da7086f08e1a10 | 3,626,735 |
import torch
def load_point_cloud(filename, min_norm_normal=1e-5, dtype=torch.float64):
"""
Load a point cloud with normals, filtering out points whose normal has a magnitude below the given threshold.
:param filename: Path to a PLY file
:param min_norm_normal: The minimum norm of a normal below which... | c3bbd81aec581f6fcd9cd23a62beb4523cb2d783 | 3,626,736 |
import math
def cos(x, offset=0, period=1, minn=0, maxx=1):
"""A cosine curve scaled to fit in a 0-1 range and 0-1 domain by default.
offset: how much to slide the curve across the domain (should be 0-1)
period: the length of one wave
minn, maxx: the output range
"""
value = math.cos((x/peri... | e3119dc71c1b6c6160a29dca37b51b0550479a83 | 3,626,737 |
def get_terms(num_distinct_documents=500,
remove_stopwords=False,
stopwords=[',', '.', '-', '\xa0', '“', '”', '"', '\n', '—', ':', '?', 'I', '(', ')']):
"""
Creates TermGenerator, and parses the documents for a specific set of documents.
:param num_distinct_documents: (int) Passe... | 0e57798596560eb00593e40217af8a43ba409d6e | 3,626,738 |
from os import access,W_OK
def iswritable(pathname):
"""Is file or folder writable?"""
return access(pathname,W_OK) | 705c8ecb9c5d2d3b7aeef6e6e99838ff72ed27f1 | 3,626,739 |
import argparse
def get_args():
"""Get arguments from CLI"""
parser = argparse.ArgumentParser(
description="""Given a LASTZ input directory, find matches, add flank, and return a FASTA file of sequences""")
parser.add_argument(
"conf",
action=FullPaths,
type... | 5264b1c9d97d0785e326201ed12d5518171755e0 | 3,626,740 |
from typing import List
from typing import Dict
def cli(argv: List[str], renderer: Renderer, commands: Dict[str, Command]):
"""
Command Line Interface
Handles the incoming console input.
:param argv: Raw list of arguments.
:param renderer: The renderer service to print messages.
:param comma... | 474506d5f85ba999e3ce925c42b3960cce74950f | 3,626,741 |
def calc_crossproduct_flow(vU,vV,btU_in,btV_in,elev,bt_depth,mtime):
"""
Calculates the discharge(flow) by finding the cross product of the water
and bottom track velocities. **elev and bt_depth are positive**
Inputs:
vU = U velocity, 2D numpy array, shape [ne,nb] {m/s}
vV = V ve... | e63ec733987d41a4a6c31f7c8d4f72c677d08a93 | 3,626,742 |
def reverse_mutation(perm, *args):
"""
Performs a reverse mutation on a permutation
"""
n = len(perm) - 1
i = np.random.choice(n, 1)[0]
perm[i:i+2] = perm[i:i+2][::-1]
return perm | bdcb517ef247a9c7effd2ae3955a0ff1831bf943 | 3,626,743 |
import csv
import logging
import re
def extraire_reunions(fichier, afficher):
""" Retourne des structures contenant la liste des réunions/organisateurs et des participants
Vérifie au passage la présence de valeurs inhabituelles dans les champs """
organisateurs = {}
participants = {}
lecteur ... | c5e7e76dc18098f76dddf2fb5643d041ccef2083 | 3,626,744 |
def MTL_loss(device, batch_size, ndata=0, contrastive_loss=False):
"""Returns the learned uncertainty loss function."""
# task_rot = LearnedLoss('CrossEntropy')
task_contrastive = LearnedLoss('Contrastive', batch_size=batch_size)
task_recons = LearnedLoss('L1')
task_NCE = LearnedLoss('NCE', nda... | af673c91956d36e600482d35d7245cf9cd65a9f3 | 3,626,745 |
def non_commutative_sympify(string: str):
"""Evaluates sympy string in non-commutative fashion.
This function was taken from stack overflow answer by @ely
https://stackoverflow.com/a/32169940
"""
parsed_expr = parse_expr(string, evaluate=False)
new_locals = {
sym.name: Symbol(sym.name,... | c7efba92223543a4e322fc3f9b72d1d2cd6e3f58 | 3,626,746 |
def parse_last_name(name_string):
"""
isolates last name in a name string extracted from a record
args:
name_string: str, entire name
returns:
last_name: str, with removed diactritics and in uppper case;
may include value of subfield $b
"""
try:
last_na... | dfc833329b0c44f8b027a3fdc7d02a56433adf71 | 3,626,747 |
def generate_neighbours(pattern: str, mismatches: int) -> set:
"""
Generate neighbours for the given pattern (genome string)
:param pattern: genome pattern
:param mismatches: number of mismatches to generate neighbours
:return: a set of patterns in the neighbourhood, including the 'pattern' itself
... | f919b8e09463a1096ca1aadaabe4284db674c0d7 | 3,626,748 |
def head_pose_preprocess(imgs):
"""
Preprocesses the image(s) and face detections for the head pose estimator.
Parameters
----------
imgs: NumPy array
The image(s) to format with values in the range [-1, 1].
Returns
-------
input_hp: NumPy array
Formatted image(s).
... | 9f2bac85daefae6dcd4fac53c7a498f8f74360fc | 3,626,749 |
import os
import json
def dataset_input_put(id, dataset): # noqa: E501
"""Submits data to the framework
# noqa: E501
:param id: ID of the data source
:type id: str
:param dataset: Dataset submitted to the framework
:type dataset: dict | bytes
:rtype: None
"""
if connexion.requ... | 24b7e1f3a14469bdc2f4588682f1a4a7c207ca84 | 3,626,750 |
def two_sum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
mid = target - nums[i]
for j in range(i + 1, len(nums)):
if nums[j] == mid:
return [i, j] | 465ddfa8fd02add40426f803276b0c3fdf193599 | 3,626,751 |
import pandas
def filter_useful_paths_into_a_dataframe(path_list):
"""
Classifies the file types of the paths we actually care about then finegles them into a DataFrame.
"""
print("Gathering metadata.")
paths_we_actually_care_about = [path for path in path_list if filetype_of(path) != "unsorted"... | 0834fe3d665610e566ea7c8bc018664b5d167f88 | 3,626,752 |
def pivottab(d, rowkey, columnkey, reducefn, duplicates=False):
""" A simple pivot table generator based on 2 key indexes and a reduce function
Parameters
----------
d: dict like structure
data container (SimpleTable or DictDataFrame)
rowkey : str
Values to group by in the rows
... | ba2b651674e77b2b2bc945bc3910e79e060ca1a2 | 3,626,753 |
def paseto_required():
""" """
def wrapper(func):
@wraps(func)
def decorated_view(*args, **kwargs):
if not hasattr(current_app, "paseto_verifier"):
raise ConfigError("paseto_verifier is not set in the current_app.")
if not current_paseto.is_verified:
... | 27cef6babb07b442760e1a977b5ab1661db7f973 | 3,626,754 |
def mean_of_list(list_in):
"""Returns the mean of a list
Parameters
----------
list_in : list
data for analysis
Returns
-------
mean : float
result of calculation
"""
mean = sum(list_in) / len(list_in)
return(mean) | fac8f40b86e7fa37f96a46b56de722c282ffc79c | 3,626,755 |
def delazi(lat1, lon1, lat2, lon2):
"""delazi(double lat1, double lon1, double lat2, double lon2)"""
return _Math.delazi(lat1, lon1, lat2, lon2) | 8c71700387d742147cf7f98a6cd2f5532b88ab6e | 3,626,756 |
import os
def create_datastore_client():
"""Creates a Client, to connect to the Datastore DB."""
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = config.GCP_CREDENTIALS
client = datastore.Client(project=config.GCP_PROJECT)
print("Connected to cloud Datastore database, GCP project", config.GCP_PROJECT)
... | f461b95063e6cdcb141f673668d274d1170a0073 | 3,626,757 |
def preliminary_register_user():
"""Администратор может добавить предопределенного пользователя (студента или преподавателя)
"""
answer = blank_resp()
try:
if current_user.status != 'admin':
raise Exception('Only admins can do preliminary registration')
form = PreliminaryRe... | d3237ad9040f7c6cc2ddab49687f05278fb2c1b1 | 3,626,758 |
from collections import OrderedDict
def read_markers_gmt(filepath):
"""
Read a marker file from a gmt.
"""
ct_dict = OrderedDict()
with open(filepath) as file_gmt:
for line in file_gmt:
values = line.strip().split('\t')
ct_dict[values[0]] = values[2:]
return ct_... | a45ed9da13c9ba4110bb4e392338036a32a58e60 | 3,626,759 |
def num_decimal_part(value: float) -> float:
"""Return the decimal part of a floating point number.
Parameters
----------
>>> num_decimal_part(-2.1)
-0.1
>>> num_decimal_part(2.1)
0.1
"""
return value - num_truncate(value) | 2054c5818ba488e8987b40f6310c073cff638d7a | 3,626,760 |
import requests
import json
import os
import tqdm
def main():
"""Main execution."""
def download_ratings_for_project_id(project_id):
if project_id in all_ratings.keys():
return None # already downloaded this project's ratings
for _ in range(MAX_TRIES_PER_URL):
try:
... | b39633a1f2b16b9878b3d92a9f965980c91eff6d | 3,626,761 |
def partition_sort(arr):
"""
An idyllic variant of quicksort, powered by numpy.partition.
"""
if arr.shape[0] < 2:
return arr
mid = arr.shape[0] // 2
partitioned = np.partition(arr, mid)
sm = partition_sort(partitioned[:mid])
lg = partition_sort(partitioned[(mid+1):])
... | ca35ebcbafbdf50a5e98172bfcf85e3bfe1c5678 | 3,626,762 |
def _phase_from_label(label):
"""Return the phase from a label"""
# Returns None if label is invalid
label = label.replace("+", "", 1).replace("1", "", 1).replace("j", "i", 1)
phases = {"": 0, "-i": 1, "-": 2, "i": 3}
if label not in phases:
raise QiskitError("Invalid Pauli phase label '{}'"... | 7d23540148b0951123dc0db19daec10108b0b09b | 3,626,763 |
import os
def test_lightningd_still_loading(node_factory, bitcoind, executor):
"""Test that we recognize we haven't got all blocks from bitcoind"""
mock_release = Event()
# This is slow enough that we're going to notice.
def mock_getblock(r):
conf_file = os.path.join(bitcoind.bitcoin_dir, 'b... | 750426f18ce8c1f198049e5624bb2814c93b2656 | 3,626,764 |
def inverse_metric_tensor(basis):
"""
Compute the inverse metric tensor for a basis.
:param basis: Basis (square matrix with basis vectors as columns).
:return: Inverse metric tensor.
"""
g = metric_tensor(basis)
if not isinstance(g, np.ndarray):
# Assume scalar
return 1 / g... | 461f2a0894611e032b82a3f83f84be4f0e16334e | 3,626,765 |
def save_data(filename, value1, operation, value2, result,log_1_counter):
"""Save data function"""
log_1_counter=log_1_counter+1
"""Save data function"""
logger.debug(f'saving details of {filename}..')
with open('demo.log','a') as append_file:
append_file.write(f'Filename:{filename} -Record ... | 6b63e4131badcb1447fd47ae2f7b35a4e5d72335 | 3,626,766 |
import logging
def get_all_annots(annotations):
"""
All annotations
"""
all_annots = set()
for genome in annotations.keys():
for annot_name in annotations[genome].keys():
all_annots.add(annot_name)
logging.info(' No. of annotation columns: {}'.format(len(all_annots)))
... | 98270d18fbc8ded648a16178087037b1319263d4 | 3,626,767 |
def get(guild):
"""
Gets a single GuildSettings Object representing the settings of that guild
:param guild:
:return Single GuildSettings Object: :type GuildSettings:
"""
return GuildSettings(guild) | c5d3fa1fae0a6347b498a89ec26eb2bd47baee7b | 3,626,768 |
from pathlib import Path
def process_attachments(path_to_content_file: Path, set_of_links: set[str], note_paths: set[Path],
source_absolute_root):
"""
Generate sets of attachment links from content.
The sets of links based on the status of that links.
all - all links found... | 0ba8f4ba2643cdc9d43998db33d09a36a9375ec3 | 3,626,769 |
def delete_instance_template(template_name: str):
"""Returns a ProcessResult from running the command to delete the
measure_worker template for this |experiment|."""
command = [
'gcloud', 'compute', 'instance-templates', 'delete', template_name
]
return new_process.execute(command) | ebf0936b8a17abcb9615941efc8dad1c367537c3 | 3,626,770 |
def create(body):
"""
Create a new grid.
:param (dict) body: A mapping of body param names to values.
:returns: (requests.Response) Returns response directly from requests.
"""
url = build_url(RESOURCE)
return request('post', url, json=body) | ab6e0c50e9c7fa4a76eed0fc2e657d01af479499 | 3,626,771 |
def arr(shape=None, element_type=float,
interval=None,
data=None, copy=True,
file_=None,
order='C'):
"""
Compact and flexible interface for creating numpy arrays,
including several consistency and error checks.
- *shape*: length of each dimension, tuple or int
- *d... | fa9cc6ceb6761cf00236406e5c23bb4ab38e6b6c | 3,626,772 |
def evaluate_template(template: str, prefix="$", sufix="$"):
"""Evaluate a string template; replace all queries by their values
Queries in the template are delimited by prefix and sufix.
Queries should evaluate to strings and should not cause errors.
"""
return Context().evaluate_template(template, ... | 03fc5bab0e4a76911743595f156aac26356b7390 | 3,626,773 |
def rsp_fixpeaks(peaks, troughs=None):
"""Correct RSP peaks.
Low-level function used by `rsp_peaks()` to correct the peaks found by `rsp_findpeaks()`.
Doesn't do anything for now for RSP. See `rsp_peaks()` for details.
Parameters
----------
peaks : list or array or DataFrame or Series or dict
... | 214efc68a59646508cddd0471a45b8b6dcfa1b55 | 3,626,774 |
def get_dfu_devices(*args, **kwargs):
"""Returns a list of USB device which are currently in DFU mode.
Additional filters (like idProduct and idVendor) can be passed in to
refine the search.
"""
# convert to list for compatibility with newer pyusb
return list(usb.core.find(*args, find_all=True,
... | 15b7d6fd53547c19ebfca115f2b8e85acc106b90 | 3,626,775 |
from datetime import datetime
def emailWeeklyOrders():
"""
Emails all the current admins an email containing every users current order.
Returns total emails sent and the email for every admin.
"""
all_orders = get_all_users_orders()
user_login_url = get_login_url()
current_date = date... | 231041367363fe7d9d78763f2a08fb51f66f7bc0 | 3,626,776 |
def content_type(suffix: str) -> str:
"""
Gets the Content-Type header for a type of file.
Arguments:
suffix: Filename suffix.
"""
suffix = normalize_suffix(suffix)
return _content_types.get(suffix, _default_content_type) | 863289460a3e1d6e21c19bb91e391eb21ab9dc36 | 3,626,777 |
import os
def get_ghcn_stid(config, stid):
"""
After code by Luke Madaus.
Gets the GHCN station ID from the 4-letter station ID.
"""
main_addr = 'ftp://ftp.ncdc.noaa.gov/pub/data/noaa'
site_directory = '%s/site_data' % config['THETAE_ROOT']
# Check to see that isd-history.txt exists
... | dcab896f30b66970b4ff3e15ef9faf3f3b06b282 | 3,626,778 |
def compare_pair(p1, p2, cp1, cp2):
"""Given comparison functions for the first and second part of
the pair, compare the two pairs using the two functions under
lexicographic order.
"""
res1 = cp1(p1[0], p2[0])
if res1 != EQUAL:
return res1
else:
return cp2(p1[1], p2[1]) | efac0863ab8728fb8f2e4dc531bbfd9dfc9b56b1 | 3,626,779 |
from typing import Optional
import importlib
import os
def scan(
cli_call_name: str, module: str, package: Optional[str], verbose: bool, help: Optional[str]
) -> CommandTrie:
"""
This crawls all of the modules below us and imports them recursively
:return:
"""
root_module = importlib.import_mo... | 8e6bdff9de2a8281d2154c11be3644555822674b | 3,626,780 |
import torch
import math
def train_epoch(net, train_iter, loss, updater, device, use_random_iter):
"""Train a net within one epoch (defined in Chapter 8)."""
state, timer = None, d2l.Timer()
metric = d2l.Accumulator(2) # Sum of training loss, no. of tokens
for X, Y in train_iter:
if state is ... | 1d7c9269bbeed0da057891e5347d20c10d6150a8 | 3,626,781 |
import struct
def read_tcp_pac(link_packet, byteorder, link_layer_parser, seconds, suseconds):
"""read tcp data.http only build on tcp, so we do not need to support other protocols."""
state, source, dest, tcp_packet = read_ip_pac(link_packet, byteorder, link_layer_parser)
if state == 0:
return 0,... | 98a263f0a203ec9f9b1c5909278069a3f4cd039c | 3,626,782 |
def basic_metrics(predict, label):
"""
Methods that returns:
true positive
true negative
false positive
false negative
Args:
predict: prediction
label: labels
Returns:
true_pos, true_neg, false_pos, false_neg, sum
"""
true_pos = int(sum(n... | 9d83c98f82b755197f269c889063f60233a76d76 | 3,626,783 |
import json
def hail_metadata(t_path):
"""Create a metadata plot for a Hail Table or MatrixTable.
Parameters
----------
t_path : str
Path to the Hail Table or MatrixTable files.
Returns
-------
:class:`bokeh.plotting.figure.Figure` or :class:`bokeh.models.widgets.panels.Tabs` or ... | 83409fcc121e3c1eaebb64b6a338cfad90018b73 | 3,626,784 |
import uuid
def persist_state(request):
"""Persist arbitrary string in cache.
It will be matched when the user returns from the OAuth server login
page.
"""
state = uuid.uuid4().hex
redirect_url = request.validated['querystring']['redirect']
expiration = float(facebook_conf(request, 'cache... | 3c2e8c0dd0c3e91544861097249e61d9bf55185c | 3,626,785 |
def refactor_lambda(astref, srcpos, argsig, body, cntrl, ecntrl):
"""Update lambda so it captures free variables"""
clist = [] # Definition argument signature
newlist = [] # New list is new item list
_find_refs(argsig, srcpos, body, cntrl, ecntrl, clist, newlist)
if clist:
# Get the ... | 2b1b96ead4fd5e87dc8eaa14eb0bfae9a2d54023 | 3,626,786 |
from typing import Callable
from typing import Type
def register_model_wrapper(name: str) -> Callable[[Type], Type]:
"""
Register a model wrapper so that it is available via the CLI.
>>> @register_model_wrapper("my_model_name")
... class MyModelWrapper:
... pass
"""
def _inner(cls_):... | 966187f08c93324a11b8f6fefffe5cdfb2e921ed | 3,626,787 |
def check_non_empty(object_name: str, engine: sqlalchemy.engine.base.Engine):
"""Check if a Snowflake object has a COUNT() > 0."""
with engine.connect() as con:
count = con.execute(f"SELECT COUNT(*) FROM {object_name}").fetchone()[0]
return count > 0 | 8bb73247f54a117b48f976bec5a89064d3707ba1 | 3,626,788 |
def importManeshFiles():
""" import data from Manesh text files, convert to dataframe, concatenate and filter """
# the raw BP data from Manesh came in 2 files, one for my data and one for Adam Guss's data
rawBPdan = pd.read_table(r"October2016\DanOlson_SFRE_V5_Test3\Strain_Sample_BrkPnts.Test3.txt.Tabbed")... | f4cfa757945388440d9de206dfcee29c78fcfb21 | 3,626,789 |
def construct_select_bijlagen_query(bericht_uri):
"""
Construct a SPARQL query for retrieving all bijlages for a given bericht.
:param bericht_uri: URI of the bericht for which we want to retrieve bijlagen.
:returns: string containing SPARQL query
"""
q = """
PREFIX schema: <http://sche... | 56e9868ddc38c703ac383508cce4e446f0f566a4 | 3,626,790 |
def tologodds(df, y):
"""
Converts column `y` of dataframe `df` to its trimmed logodds.
Name is preserved.
"""
return df.assign(**{y: df[y].pipe(lambda x: trimmed(logodds, x))}) | 294e81a147b0023fedf8e79a741723bc88b02f51 | 3,626,791 |
from typing import List
from typing import Dict
def user_demand_tmp(user_demand: UserDemand) -> List[Dict]:
"""
Log global user demand.
:param scheduler: the scheduler
:return: list of records for logging
"""
result = [{"value": user_demand.value}]
return result | e1be835f330f0744351fa4a9afcdba1c013285b8 | 3,626,792 |
def process_css(css_source, tabid, base_uri):
"""
Wraps urls in css source.
>>> url = 'http://blue360media.com/style.css'
>>> process_css('@import "{}"'.format(url), 0, url) # doctest: +ELLIPSIS
'@import "/proxy?..."'
"""
def _absolutize_css_import(match):
return '@import "{}"'.form... | 2b8e173f36c26c4cba908fa39f71b9407c5006ba | 3,626,793 |
import requests
def get_Meraki_Organization(MERAKI_API_KEY):
"""
Get the Meraki Organizations that the API KEY has access to.
:param MERAKI_API_KEY:
:return:
"""
url = '{}/organizations'.format(BASE_URL)
hdrs = {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Cisco-Meraki-API-Key... | d66905852ba6b355686588477eb13fe13401a4a3 | 3,626,794 |
def check_convergence(x):
""" Check for convergence of the sampler
"""
return False | 989d94991eeecd414c3f6ff85b2d2bc2801d5cbc | 3,626,795 |
from typing import List
import requests
def get_repo_names(url: str = "users/dyvenia/repos") -> List[str]:
"""
Get public repositories names from Dyvenia.
Args:
url (str, optional): API url. Defaults to "users/dyvenia/repos".
Returns:
List[str]: List of repository names
"""
r... | 40c5d1dde34c26553493f15445e5a5a7e8021838 | 3,626,796 |
from typing import Iterable
from re import T
from re import U
from typing import Optional
from typing import Callable
from typing import Iterator
from typing import List
def split(
iterable: Iterable[T],
edges: Iterable[U],
cmp: Optional[Callable[[T, U], bool]] = None,
) -> Iterator[List[T]]:
"""Yield... | 6fe30a650bf4167e21021953490429b77533979a | 3,626,797 |
import os
def get_pixar_usd_binaries_path():
"""
Returns binaries directory of Pixar USD library
:return: str
"""
pixar_usd_path = get_usd_path()
if not pixar_usd_path:
return
pixar_usd_bin_path = os.path.join(pixar_usd_path, 'bin')
if not os.path.isdir(pixar_usd_bin_path):
... | 774de03fb5724c1576acf53691e40f26e5b241de | 3,626,798 |
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear',
preview=False):
"""
Make a thumbnail of image in *infile* with output filename *thumbfile*.
See :doc:`/gallery/misc/image_thumbnail_sgskip`.
Parame... | 54133e92baf669280a3cd5fb989d2d5d84c29bb3 | 3,626,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.