content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def hot(df, hot_maps, drop_cold=True, ret_hots_only=False, verbose=False):
"""
df: pd.DataFrame
hot_maps: list(dict)
hot_map: dict
key: str column in df
value: one_hot vector for unique row value
---
returns dataframe
"""
if verbose:
print(f"hot_df c... | b0912ae22aa3ee34acde76e89c5f926c9d309492 | 4,418 |
def menu(function_text):
"""
Decorator for plain-text handler
:param function_text: function which set as handle in bot class
:return:
"""
def wrapper(self, bot, update):
self.text_menu(bot, update)
function_text(self, bot, update)
return wrapper | dc68a46aaf402cd5ce3bd832a0f2a661b5cbc71b | 4,419 |
def create_delete_classes(system_id_or_identifier, **kwargs):
"""Create classes for a classification system.
:param system_id_or_identifier: The id or identifier of a classification system
"""
if request.method == "DELETE":
data.delete_classes(system_id_or_identifier)
return {'message'... | 4f48ebb7fe80854d255f47fb795e83b54f9f60b3 | 4,420 |
def add_latents_to_dataset_using_tensors(args, sess, tensors, data):
""" Get latent representations from model.
Args:
args: Arguments from parser in train_grocerystore.py.
sess: Tensorflow session.
tensors: Tensors used for extracting latent representations.
data: Data used... | 550c7c878b43737b5fcabbb007062774f404b0b3 | 4,422 |
def normal_distribution_parameter_estimation(data):
"""
Notice: Unbiased Estimation Adopted. Line 115.
:param data: a list, each element is a real number, the value of some attribute
eg: [0.46, 0.376, 0.264, 0.318, 0.215, 0.237, 0.149, 0.211]
:return miu: the estimation of miu of the normal distri... | ce8ca8010f98fdd2067285fea4779507fe7e958b | 4,423 |
def compose(chosung, joongsung, jongsung=u''):
"""This function returns a Hangul letter by composing the specified chosung, joongsung, and jongsung.
@param chosung
@param joongsung
@param jongsung the terminal Hangul letter. This is optional if you do not need a jongsung."""
if jongsung is None... | 047d0cf68a558d795a5bf71b0ebe686a41208af7 | 4,425 |
from typing import Dict
from typing import List
def generate_markdown_metadata(metadata_obj: Dict[str, str]) -> List[str]:
"""generate_markdown_metadata
Add some basic metadata to the top of the file
in HTML tags.
"""
metadata: List[str] = ["<!---"]
passed_metadata: List[str] = [
f"... | 02ef3952c265276f4e666f060be6cb1d4a150cca | 4,426 |
def fftshift(x:np.ndarray):
"""平移FFT频谱
FFT默认频谱不是关于零频率对称的,使用fftshift可以对调左右频谱。
:Parameters:
- x: 频谱序列
:Returns: 平移后的频谱
"""
N = x.size
return np.append(x[N//2:], x[:N//2]) | beaf2dcd0d5c9ff0b9bd83d326b3d3a9f6471968 | 4,427 |
from typing import List
from typing import Tuple
def get_20newsgroups_data(
train_test,
categories=None,
max_text_len: int = None,
min_num_tokens=0,
random_state=42,
) -> List[Tuple[str, str]]:
"""
'alt.atheism',
'comp.graphics',
'comp.os.ms-windows.misc',
'comp.sys.ibm.pc.... | 6053f967ac1fb782cab28fe401e384940703e384 | 4,428 |
def crossdomain(allowed_origins=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True, credentials=False):
"""
http://flask.pocoo.org/snippets/56/
"""
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in metho... | 9d352718406f62eaeb184a081b4223b67f6200f3 | 4,429 |
from typing import Callable
def make_vector_gradient(bcs: Boundaries) -> Callable:
""" make a discretized vector gradient operator for a cylindrical grid
|Description_cylindrical|
Args:
bcs (:class:`~pde.grids.boundaries.axes.Boundaries`):
|Arg_boundary_conditions|
R... | 61d4f1a29d4a81e57ad37a6b963e201e5deabc06 | 4,430 |
def exec_in_terminal(command):
"""Run a command in the terminal and get the
output stripping the last newline.
Args:
command: a string or list of strings
"""
return check_output(command).strip().decode("utf8") | 1186649cebbd20559f7de0ba8aa743d70f35c924 | 4,431 |
def replace_string(original, start, end, replacement):
"""Replaces the specified range of |original| with |replacement|"""
return original[0:start] + replacement + original[end:] | c71badb26287d340170cecdbae8d913f4bdc14c6 | 4,432 |
def edit_mod():
""" Admin endpoint used for sub transfers. """
if not current_user.is_admin():
abort(403)
form = EditModForm()
try:
sub = Sub.get(fn.Lower(Sub.name) == form.sub.data.lower())
except Sub.DoesNotExist:
return jsonify(status='error', error=[_("Sub does not exist... | debab16603e2cfe412eb0f819753fb7571a9c803 | 4,433 |
def get_current_info(symbol_list, columns='*'):
"""Retrieves the latest data (15 minute delay) for the
provided symbols."""
columns = ','.join(columns)
symbols = __format_symbol_list(symbol_list)
yql = ('select %s from %s where symbol in (%s)'
% (columns, FINANCE_TABLES['quotes'], symbo... | a13df0f44b31ac091a5283958cdb1aa675fe9bdc | 4,434 |
def dictionarify_recpat_data(recpat_data):
"""
Covert a list of flat dictionaries (single-record dicts) into a dictionary.
If the given data structure is already a dictionary, it is left unchanged.
"""
return {track_id[0]: patterns[0] for track_id, patterns in \
[zip(*item.items()) for ... | d1cdab68ab7445aebe1bbcce2f220c73d6db308f | 4,435 |
def _get_qualified_name(workflow_name, job_name):
"""Construct a qualified name from workflow name and job name."""
return workflow_name + _NAME_DELIMITER + job_name | 29881480a9db33f18ff4b01abcdd1aaf39781f36 | 4,436 |
def normalize_each_time_frame(input_array):
"""
Normalize each time frame
- Input: 3D numpy array
- Output: 3D numpy array
"""
for i in range(input_array.shape[0]):
max_value = np.amax(input_array[i, :, :])
if max_value != 0:
input_array[i, :, :] = input_arr... | bee7f41f17e4e24a654426f65c6a73c518abafca | 4,437 |
def pre_process_data(full_data):
"""
pre process data- dump invalid values
"""
clean_data = full_data[(full_data["Temp"] > -10)]
return clean_data | 6172d4a77f5805c60ae9e4f146da2bd8283beef0 | 4,438 |
def invalid_grant(_):
"""Handles the Invalid Grant error when doing Oauth
"""
del current_app.blueprints['google'].token
flash(("InvalidGrant Error"), category="danger")
return redirect(url_for('index')) | 95b8b20d3d96b46387c6dd23ede9b54c6b056da1 | 4,439 |
import difflib
def diff_text(a, b):
"""
Performs a diffing algorithm on two pieces of text. Returns
a string of HTML containing the content of both texts with
<span> tags inserted indicating where the differences are.
"""
def tokenise(text):
"""
Tokenises a string by spliting i... | e15348e942ac3e6936872ec61f123a9241f49eba | 4,440 |
from common.aes import encrypt
from common.datatypes import PasswordResetToken
from config import AUTH_TOKEN, RESET_PASSWORD_EXPIRE_SECONDS
from time import time
from urllib.parse import quote_plus
from utils import send_mail
import traceback
from operator import or_
def require_reset_password():
"""
请求重设密码
... | aa1c14755485fe3ac5fc294e43fa1d4e610e0a83 | 4,441 |
def coerce_affine(affine, *, ndim, name=None):
"""Coerce a user input into an affine transform object.
If the input is already an affine transform object, that same object is returned
with a name change if the given name is not None. If the input is None, an identity
affine transform object of the give... | 66900e32b83100004d2ea62a742fc0afe8a26cbb | 4,442 |
def known_peaks():
"""Return a list of Peak instances with data (identified)."""
peak1 = Peak(
name="Test1Known",
r_time=5.00,
mz=867.1391,
charge="+",
inchi_key="IRPOHFRNKHKIQA-UHFFFAOYSA-N",
)
peak2 = Peak(
name="Test2Known",
r_time=8.00,
... | 3f7d5eb5b16d61f09c0c10f32e9d8d40324e2d5d | 4,444 |
def explode_sheet_music(sheet_music):
"""
Splits unformatted sheet music into formated lines of LINE_LEN_LIM
and such and returns a list of such lines
"""
split_music = sheet_music.split(',')
split_music = list(map(lambda note: note+',', split_music))
split_list = []
counter = 0
line... | f89ae58a0deb315c61419bd381cd0bf84f079c3e | 4,445 |
def norm_coefficient(m, n):
"""
Calculate the normalization coefficient for the (m, n) Zernike mode.
Parameters
----------
m : int
m-th azimuthal Zernike index
n : int
n-th radial Zernike index
Returns
-------
norm_coeff : float
Noll normalization coefficien... | 1632ffac5e771e4ab16b3f7918d9543ffd67171e | 4,446 |
def get_waveglow(ckpt_url):
"""
Init WaveGlow vocoder model with weights.
Used to generate realistic audio from mel-spectrogram.
"""
wn_config = {
'n_layers': hp.wg_n_layers,
'n_channels': hp.wg_n_channels,
'kernel_size': hp.wg_kernel_size
}
audio_config = {
... | a5b494299fae98be2bb5f764ed7a53fc42d36eff | 4,447 |
def user_exists(keystone, user):
"""" Return True if user already exists"""
return user in [x.name for x in keystone.users.list()] | 17d99e12c0fc128607a815f0b4ab9897c5d45578 | 4,448 |
from typing import List
from typing import Dict
import itertools
def gen_cartesian_product(*args: List[Dict]) -> List[Dict]:
""" generate cartesian product for lists
生成笛卡尔积,估计是参数化用的
Args:
args (list of list): lists to be generated with cartesian product
Returns:
list: cartesian p... | cbe85f440f399b523aa70bc10733ea175dc93f7a | 4,449 |
def get_234_df(x):
"""
This function get the dataframe for model2.1,2.2,2.3
input: x, the col we want
output: the dataframe only for x
"""
styles = pd.read_csv("styles.csv", error_bad_lines=False)
styles = styles.drop(["productDisplayName"],axis = 1)
styles = styles.drop(["year"],axis = 1)
sty... | c9d456ae058492e5e242bbde2288885158681f98 | 4,450 |
def appropriate_bond_orders(params, smrts_mol, smrts):
"""Checks if a SMARTS substring specification has appropriate bond orders
given the user-specified mode.
:param params: A dictionary of the user parameters and filters.
:type params: dict
:param smrts_mol: RDKit mol object of the SMARTS string.... | 045abda277716812694cc1093256742e1d67a016 | 4,451 |
def train(model, train_path, val_path, steps_per_epoch, batch_size,
records_path):
"""
Train the Keras graph model
Parameters:
model (keras Model): The Model defined in build_model
train_path (str): Path to training data
val_path (str): Path to validation data
steps... | 24a8080a8b4738f7eb32846729b006ca2237a576 | 4,452 |
def Mcnu_to_m1m2(Mc, nu):
"""Convert chirp mass, symmetric mass ratio pair to m1, m2"""
q = nu_to_q(nu)
M = Mcq_to_M(Mc, q)
return Mq_to_m1m2(M, q) | 8b4eb6e49549607bda0ea9a17baec8c4d0b38cb6 | 4,453 |
import functools
def _AccumulateActions(args):
"""Given program arguments, determines what actions we want to run.
Returns [(ResultsReportCtor, str)], where ResultsReportCtor can construct a
ResultsReport, and the str is the file extension for the given report.
"""
results = []
# The order of these is ar... | 73925fe55e6986e1222a5e88f804caaa9793044a | 4,454 |
def build_predictions_dictionary(data, class_label_map):
"""Builds a predictions dictionary from predictions data in CSV file.
Args:
data: Pandas DataFrame with the predictions data for a single image.
class_label_map: Class labelmap from string label name to an integer.
Returns:
Dictionary with key... | 738e1c9c4568bc689ecda9765c3412d36f2d73ec | 4,455 |
def create_file_link(link_id, file_id, parent_share_id, parent_datastore_id):
"""
DB wrapper to create a link between a file and a datastore or a share
Takes care of "degenerated" tree structures (e.g a child has two parents)
In addition checks if the link already exists, as this is a crucial part of ... | 0c4abe1d5aa4bce8bd489f8bec1ae900a9194631 | 4,456 |
def deptree(lines):
"""Build a tree of what step depends on what other step(s).
Test input becomes
{'A': set(['C']), 'C': set([]), 'B': set(['A']),
'E': set(['B', 'D', 'F']), 'D': set(['A']),
'F': set(['C'])}
A depends on C
B depends on A
C depends on nothing (starting point)
D ... | 9a435a0e78dd3a68c97df4bcd2e03583841de216 | 4,457 |
from datetime import datetime
def get_datetime(time_str, model="0"):
"""
时间格式化 '20200120.110227'转为'2020-01-20 11:02:27'
返回一个datetime格式
"""
if model == "0":
time_str = get_time(time_str)
time = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
return time | 568c46efab9366f64fc0e286cf9876cd48e7a9bb | 4,458 |
def gather_parent_cnvs(vcf, fa, mo):
"""
Create BEDTools corresponding to parent CNVs for converage-based inheritance
"""
cnv_format = '{0}\t{1}\t{2}\t{3}\t{4}\n'
fa_cnvs = ''
mo_cnvs = ''
for record in vcf:
# Do not include variants from sex chromosomes
if record.chrom i... | 2d685586a917bbd94f87758221b4d06c2d6ad7c1 | 4,459 |
import json
def create_images():
""" Create new images
Internal Parameters:
image (FileStorage): Image
Returns:
success (boolean)
image (list)
"""
# vars
image_file = request.files.get('image')
validate_image_data({"image": image_file})
i... | 682bb2f6044265fbd6c29c4ff6581d6bc2469edb | 4,460 |
from typing import Union
from pathlib import Path
from typing import Optional
def docx2python(
docx_filename: Union[str, Path],
image_folder: Optional[str] = None,
html: bool = False,
paragraph_styles: bool = False,
extract_image: bool = None,
) -> DocxContent:
"""
Unzip a docx file and ex... | 557ba8502b62ffc771a7d3b6f88a8b769dd55d68 | 4,461 |
def parcel_analysis(con_imgs, parcel_img,
msk_img=None, vcon_imgs=None,
design_matrix=None, cvect=None,
fwhm=8, smooth_method='default',
res_path=None):
"""
Helper function for Bayesian parcel-based analysis.
Given a sequence o... | 8abface7ad72f5ca2679dc9a8ea6cedd93f681a5 | 4,462 |
def memoize(fn):
"""Simple memoization decorator for functions and methods,
assumes that all arguments to the function can be hashed and
compared.
"""
memoized_values = {}
@wraps(fn)
def wrapped_fn(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
try:
... | 2a48fad065e04a7eed9b9865adc0640f2a7cff9f | 4,463 |
from pydantic import BaseModel # noqa: E0611
import torch
def validate(
args: Namespace,
model: BaseModel
) -> pd.DataFrame:
"""Perform the validation.
Parameters
----------
args : Namespace
Arguments to configure the model and the validation.
model : BaseModel
The model ... | 456ec24e1639970db285e260028e9ba3bd4d2e31 | 4,464 |
def stats(last_day=None, timeframe=None, dates_sources=None):
"""See :class:`bgpranking.api.get_stats`"""
query = {'method': 'stats'}
query.update({'last_day': last_day, 'timeframe': timeframe,
'dates_sources': dates_sources})
return __prepare_request(query) | 5da42848926372fa5fe90338529ab47396203fd8 | 4,465 |
def restore_purchases() -> None:
"""restore_purchases() -> None
(internal)
"""
return None | 7f047cdfe892bd724c2203d846762c3b3786d7c2 | 4,466 |
import time
def sim_mat(fc7_feats):
"""
Given a matrix of features, generate the similarity matrix S and sparsify it.
:param fc7_feats: the fc7 features
:return: matrix_S - the sparsified matrix S
"""
print("Something")
t = time.time()
pdist_ = spatial.distance.pdist(fc7_feats)
pri... | 6b896a4912f4a9a8fc765674ad47e17aea73bfa0 | 4,467 |
def text_split(in_text, insert_points, char_set):
""" Returns: Input Text Split into Text and Nonce Strings. """
nonce_key = []
encrypted_nonce = ""
in_list = list(in_text)
for pos in range(3967):
if insert_points[pos] >= len(in_list) - 1: point = len(in_list) - 2
else: point = inser... | 15f496513e63236b0df7e2d8a8949a8b2e632af4 | 4,468 |
import decimal
def f_approximation(g_matrix, coeficients_array):
"""
Retorna um vetor para o valor aproximado de f, dados os coeficientes ak.
"""
decimal.getcontext().prec = PRECSION
decimal.getcontext().rounding = ROUNDING_MODE
num_of_xs = len(g_matrix[0])
num_of_coeficients = len(g_mat... | f5f8ce78b07e877c521a6374548e21273c61dcee | 4,469 |
def _module_exists(module_name):
"""
Checks if a module exists.
:param str module_name: module to check existance of
:returns: **True** if module exists and **False** otherwise
"""
try:
__import__(module_name)
return True
except ImportError:
return False | 8f3ed2e97ee6dbb41d6e84e9e5595ec8b6f9b339 | 4,470 |
def users(request):
"""Show a list of users and their puzzles."""
context = {'user_list': []}
for user in User.objects.all().order_by('username'):
objs = Puzzle.objects.filter(user=user, pub_date__lte=timezone.now()).order_by('-number')
if objs:
puzzle_list = []
for p... | abf953394af6baff08bedf252796eb0d89cba3f4 | 4,471 |
from xidplus.stan_fit import get_stancode
def MIPS_SPIRE_gen(phot_priors,sed_prior_model,chains=4,seed=5363,iter=1000,max_treedepth=10,adapt_delta=0.8):
"""
Fit the three SPIRE bands
:param priors: list of xidplus.prior class objects. Order (MIPS,PACS100,PACS160,SPIRE250,SPIRE350,SPIRE500)
:param se... | be3d168e6a7a5a8159e83371059cfcbd1f0c187e | 4,472 |
def check_cstr(solver, indiv):
"""Check the number of constraints violations of the individual
Parameters
----------
solver : Solver
Global optimization problem solver
indiv : individual
Individual of the population
Returns
-------
... | 2aa52d2badfb45d8e289f8314700648ddc621252 | 4,473 |
def _FixFsSelectionBit(key, expected):
"""Write a repair script to fix a bad fsSelection bit.
Args:
key: The name of an fsSelection flag, eg 'ITALIC' or 'BOLD'.
expected: Expected value, true/false, of the flag.
Returns:
A python script to fix the problem.
"""
if not _ShouldFix('fsSelection'):
... | 6dda9ccbb565857c4187afc4dada6dd84653b427 | 4,474 |
def dilation_dist(path_dilation, n_dilate=None):
"""
Compute surface of distances with dilation
:param path_dilation: binary array with zeros everywhere except for paths
:param dilate: How often to do dilation --> defines radious of corridor
:returns: 2dim array of same shape as path_dilation, with ... | 0d35ec5a0a14b026f0df228ae752f104502b82ba | 4,475 |
def plot_rgb_phases(absolute, phase):
"""
Calculates a visualization of an inverse Fourier transform, where the absolute value is plotted as brightness
and the phase is plotted as color.
:param absolute: 2D numpy array containing the absolute value
:param phase: 2D numpy array containing phase info... | d2f12df2af25925ae9607ef102f4b0fc1cb01373 | 4,476 |
def normal_shock_pressure_ratio(M, gamma):
"""Gives the normal shock static pressure ratio as a function of upstream Mach number."""
return 1.0+2.0*gamma/(gamma+1.0)*(M**2.0-1.0) | 30d0a339b17bab2b662fecd5b19073ec6478a1ec | 4,479 |
from typing import Tuple
import numpy
def _lorentz_berthelot(
epsilon_1: float, epsilon_2: float, sigma_1: float, sigma_2: float
) -> Tuple[float, float]:
"""Apply Lorentz-Berthelot mixing rules to a pair of LJ parameters."""
return numpy.sqrt(epsilon_1 * epsilon_2), 0.5 * (sigma_1 + sigma_2) | b27c282cec9f880442be4e83f4965c0ad79dfb1e | 4,480 |
def verify_password_str(password, password_db_str):
"""Verify password matches database string."""
split_password_db = password_db_str.split('$')
algorithm = split_password_db[0]
salt = split_password_db[1]
return password_db_str == generate_password_str(algorithm, salt, password) | 467dcbfa1dbf1af0d7cd343f00149fc8322053e5 | 4,481 |
def get_ical_file_name(zip_file):
"""Gets the name of the ical file within the zip file."""
ical_file_names = zip_file.namelist()
if len(ical_file_names) != 1:
raise Exception(
"ZIP archive had %i files; expected 1."
% len(ical_file_names)
)
return ical_file_names... | 7013840891844358f0b4a16c7cefd31a602d9eae | 4,482 |
def unquoted_str(draw):
"""Generate strings compatible with our definition of an unquoted string."""
start = draw(st.text(alphabet=(ascii_letters + "_"), min_size=1))
body = draw(st.text(alphabet=(ascii_letters + digits + "_")))
return start + body | 7927e828a82786f45749e25e25376f48479c0662 | 4,483 |
from typing import List
from typing import Optional
from typing import Any
from typing import Callable
def _reduce_attribute(states: List[State],
key: str,
default: Optional[Any] = None,
reduce: Callable[..., Any] = _mean) -> Any:
"""Find the first... | bfc4ca6826e05b04ae9e1af6d3c167935bceda6f | 4,484 |
def sync_garmin(fit_file):
"""Sync generated fit file to Garmin Connect"""
garmin = GarminConnect()
session = garmin.login(ARGS.garmin_username, ARGS.garmin_password)
return garmin.upload_file(fit_file.getvalue(), session) | 8e604a0461f503d83b5a304081020d54acd7577c | 4,485 |
from typing import Callable
from typing import List
def get_paths(graph: Graph, filter: Callable) -> List:
""" Collect all the paths consist of valid vertices.
Return one path every time because the vertex index may be modified.
"""
result = []
if filter == None:
return result
vis... | f7e1679bae48781010257b4fe8e980964dee80ce | 4,486 |
def create_app(app_name=PKG_NAME):
"""Initialize the core application."""
app = Flask(app_name)
CORS(app)
with app.app_context():
# Register Restx Api
api.init_app(app)
return app | 1773b0a84253aa6a1bca5c6f6aec6cd6d59b74fa | 4,487 |
from typing import Dict
from typing import Callable
import sympy
import warnings
def smtlib_to_sympy_constraint(
smtlib_input: str,
interpreted_constants: Dict[str, Callable] = default_interpreted_constants,
interpreted_unary_functions: Dict[str,
Callable] = default_i... | d04782272cd13fcb7eafdb4b8f9cb7b1fd857dcc | 4,488 |
async def revert(app, change_id: str) -> dict:
"""
Revert a history change given by the passed ``change_id``.
:param app: the application object
:param change_id: a unique id for the change
:return: the updated OTU
"""
db = app["db"]
change = await db.history.find_one({"_id": change_i... | ad5484639f0a70913b17799534fa52b8531b3356 | 4,489 |
def days_away(date):
"""Takes in the string form of a date and returns the number of days until date."""
mod_date = string_to_date(date)
return abs((current_date() - mod_date).days) | f76b10d9e72d8db9e42d7aba7481e63cf1382502 | 4,490 |
def node_constraints_transmission(model):
"""
Constrains e_cap symmetrically for transmission nodes.
"""
m = model.m
# Constraint rules
def c_trans_rule(m, y, x):
y_remote, x_remote = transmission.get_remotes(y, x)
if y_remote in m.y_trans:
return m.e_cap[y, x] == m... | 0fc51f39b63324c73503b349cfd38da4c9816c50 | 4,491 |
def plot_mtf(faxis, MTF, labels=None):
"""Plot the MTF. Return the figure reference."""
fig_lineplot = plt.figure()
plt.rc('axes', prop_cycle=PLOT_STYLES)
for i in range(0, MTF.shape[0]):
plt.plot(faxis, MTF[i, :])
plt.xlabel('spatial frequency [cycles/length]')
plt.ylabel('Radial MTF'... | dac09628a72666a4f4e3e8aae4263cb9f2688fa2 | 4,492 |
import enum
def forward_ref_structure_hook(context, converter, data, forward_ref):
"""Applied to ForwardRef model and enum annotations
- Map reserved words in json keys to approriate (safe) names in model.
- handle ForwardRef types until github.com/Tinche/cattrs/pull/42/ is fixed
Note: this is the... | acbbf365c7a80c7a9f5230bcd038c2c286ae58c5 | 4,493 |
def cross(x: VariableLike, y: VariableLike) -> VariableLike:
"""Element-wise cross product.
Parameters
----------
x:
Left hand side operand.
y:
Right hand side operand.
Raises
------
scipp.DTypeError
If the dtype of the input is not vector3.
Returns
---... | 372156ba869e3dabb2421e1ea947fdc710c316eb | 4,494 |
def delete(service, name, parent_id=None,
appProperties=defaults.GDRIVE_USE_APPPROPERTIES):
""" Delete a file/folder on Google Drive
Parameters
----------
service : googleapiclient.discovery.Resource
Google API resource for GDrive v3
name : str
Name of file/folder
par... | e2653005d8d0e53df80119869586542b08405c55 | 4,495 |
def _is_LoginForm_in_this_frame(driver, frame):
""" 判断指定的 frame 中是否有 登录表单 """
driver.switch_to.frame(frame) # 切换进这个 frame
if _is_LoginForm_in_this_page(driver):
return True
else:
driver.switch_to.parent_frame() # 如果没有找到就切换回去
return False | 16a4b3af1d5cf9abe2efee6856a37b520fc2a1fc | 4,496 |
def parse_range_header(specifier, len_content):
"""Parses a range header into a list of pairs (start, stop)"""
if not specifier or '=' not in specifier:
return []
ranges = []
unit, byte_set = specifier.split('=', 1)
unit = unit.strip().lower()
if unit != "bytes":
return []
... | 2a408abe816684bf42b2253495088338bf4cac2b | 4,497 |
def acf(x, lags=None):
""" Computes the empirical autocorralation function.
:param x: array (n,), sequence of data points
:param lags: int, maximum lag to compute the ACF for. If None, this is set to n-1. Default is None.
:return gamma: array (lags,), values of the ACF at lags 0 to lags
"""
ga... | 9d47df88255ec8c9ae373c501f8b70af8f3c4ebc | 4,498 |
def _login(client, user, users):
"""Login user and return url."""
login_user_via_session(client, user=User.query.get(user.id))
return user | 079136eb777957caf09c51c75ae5148ab2eea836 | 4,500 |
def search(request):
"""renders search page"""
queryset_list = Listing.objects.order_by('-list_date')
if 'keywords' in request.GET:
keywords = request.GET['keywords']
# Checking if its none
if keywords:
queryset_list = queryset_list.filter(
description__... | a25d6e112d4054dfaf505aff5c4c36f07a95d989 | 4,501 |
def generate_cutout(butler, skymap, ra, dec, band='N708', data_type='deepCoadd',
half_size=10.0 * u.arcsec, psf=True, verbose=False):
"""Generate a single cutout image.
"""
if not isinstance(half_size, u.Quantity):
# Assume that this is in pixel
half_size_pix = int(half_s... | fdc42ad0dd0f357d53804a1f6fa43c93e86d2c0e | 4,502 |
def get_arraytypes ():
"""pygame.sndarray.get_arraytypes (): return tuple
Gets the array system types currently supported.
Checks, which array system types are available and returns them as a
tuple of strings. The values of the tuple can be used directly in
the use_arraytype () method.
If no ... | 192cb215fdc651543ac6ed4ce2f9cac2b0d3b4f4 | 4,503 |
def is_request_authentic(request, secret_token: bytes = conf.WEBHOOK_SECRET_TOKEN):
"""
Examine the given request object to determine if it was sent by an authorized source.
:param request: Request object to examine for authenticity
:type request: :class:`~chalice.app.Request`
:param secret_token: ... | 1ffceea3aebc0c038384c003edc93358e6faa9ed | 4,504 |
def circular_mask_string(centre_ra_dec_posns, aperture_radius="1arcmin"):
"""Get a mask string representing circular apertures about (x,y) tuples"""
mask = ''
if centre_ra_dec_posns is None:
return mask
for coords in centre_ra_dec_posns:
mask += 'circle [ [ {x} , {y}] , {r} ]\n'.format(
... | 04e66d160eb908f543990adf896e494226674c71 | 4,505 |
def dataset_hdf5(dataset, tmp_path):
"""Make an HDF5 dataset and write it to disk."""
path = str(tmp_path / 'test.h5')
dataset.write_hdf5(path, object_id_itemsize=10)
return path | 4a7920adf7715797561513fbb87593abf95f0bca | 4,506 |
def _make_indexable(iterable):
"""Ensure iterable supports indexing or convert to an indexable variant.
Convert sparse matrices to csr and other non-indexable iterable to arrays.
Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.
Parameters
----------
iterable : {list, d... | 94be904009adfd3bf15de0f258b94a196a9612df | 4,507 |
def fib_for(n):
"""
Compute Fibonnaci sequence using a for loop
Parameters
----------
n : integer
the nth Fibonnaci number in the sequence
Returns
-------
the nth Fibonnaci number in the sequence
"""
res = [0, 1]
for i in range(n-1):
res.append(res[i] + res... | 1609a2d52f5308a6a9d496f13c1de3f7eee6332d | 4,509 |
import pickle
def command_factory(command):
"""A factory which returns functions for direct daemon communication.
This factory will create a function which sends a payload to the daemon
and returns the unpickled object which is returned by the daemon.
Args:
command (string): The type of payl... | ec84d6ab611d4edaf55ba0c365ed8526250c7ce1 | 4,510 |
def load_prepare_saif_data(threshold=0.25):
"""
Loads and prepares saif's data.
Parameters
----------
threshold : float
Only data with intensities equal to or
above this threshold will be kept (range 0-1).
Returns
-------
DataFrame : pd.DataFrame
Concatenated t... | b2087d0558473069cf5985bd7e2b063162157df5 | 4,511 |
def nonmax_suppression(harris_resp, halfwidth=2):
"""
Takes a Harris response from an image, performs nonmax suppression, and outputs the x,y values
of the corners in the image.
:param harris_resp: Harris response for an image which is an array of the same shape as the original image.
:param half... | b980ac9045728c8231749e7a43aa2f06d958d80c | 4,512 |
import uuid
from datetime import datetime
import pytz
def create_credit_request(course_key, provider_id, username):
"""
Initiate a request for credit from a credit provider.
This will return the parameters that the user's browser will need to POST
to the credit provider. It does NOT calculate the si... | 8c9e763d1f10f9187c102746911dc242385100e8 | 4,513 |
import pathlib
def is_valid_project_root(project_root: pathlib.Path) -> bool:
"""Check if the project root is a valid trestle project root."""
if project_root is None or project_root == '' or len(project_root.parts) <= 0:
return False
trestle_dir = pathlib.Path.joinpath(project_root, const.TRESTL... | f35d63373d96ee34592e84f21296eadb3ebc6c98 | 4,514 |
def make_2D_predictions_into_one_hot_4D(prediction_2D, dim):
"""
This method gets 2D prediction of shape (#batch, #kpts)
and then returns 4D one_hot maps of shape
(#batch, #kpts, #dim, #dim)
"""
# getting one_hot maps of predicted locations
# one_hot_maps is of shape (#batch, #kpts, #dim * ... | 507d2fa9c52d5f8a1674e695f55928783a179082 | 4,515 |
def distance(a, b):
"""
"""
dimensions = len(a)
_sum = 0
for dimension in range(dimensions):
difference_sq = (a[dimension] - b[dimension]) ** 2
_sum += difference_sq
return sqrt(_sum) | 20acd50d7e3ab7f512f3e9ab9920f76b805043a9 | 4,517 |
def is_block(modules):
"""Check if is ResNet building block."""
if isinstance(modules, (BasicBlock, Bottleneck)):
return True
return False | 8c6b5f59797646b27301a25a40d753b6c404b418 | 4,518 |
def playlist_500_fixture():
"""Load payload for playlist 500 and return it."""
return load_fixture("plex/playlist_500.xml") | 834efe057419f56b626c40430b68860fd5e0db1e | 4,519 |
def strip_output(nb):
"""strip the outputs from a notebook object"""
nb.metadata.pop('signature', None)
for cell in nb.cells:
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
return nb | 6339100f6897951bad4f91f8b8d86d1e5a68f459 | 4,520 |
def get_neighbors_general(status: CachingDataStructure, key: tuple) -> list:
"""
Returns a list of tuples of all coordinates that are direct neighbors,
meaning the index is valid and they are not KNOWN
"""
coords = []
for key in get_direct_neighbour_coords_general(key):
if status.valid_i... | 46a2b3aa91e424122982011ccaa684c2d9cf83f2 | 4,521 |
def transit_params(time):
"""
Dummy transit parameters for time series simulations
Parameters
----------
time: sequence
The time axis of the transit observation
Returns
-------
batman.transitmodel.TransitModel
The transit model
"""
params = batman.TransitParams(... | 5e74a32ef4077a990d44edb15d66e56e00925666 | 4,522 |
def actions(__INPUT):
"""
Regresamos una lista de los posibles movimientos de la matriz
"""
MOVIMIENTOS = []
m = eval(__INPUT)
i = 0
while 0 not in m[i]:
i += 1
# Espacio en blanco (#0)
j = m[i].index(0);
if i > 0:
#ACCION MOVER ARRIBA
m[i][j], m[i-1][j] = m[i-... | 46875f83d7f50bbd107be8ad5d926397960ca513 | 4,523 |
def get_massif_geom(massif: str) -> WKBElement:
"""process to get the massifs geometries:
* go on the meteofrance bra website
* then get the html "area" element
* then convert it to fake GeoJSON (wrong coordinates)
* then open it in qgis.
* Select *all* the geom of the layer.
* rotate -90°... | 194ef4274dfd240af65b61781f39464e0cde4b3d | 4,524 |
def _to_arrow(x):
"""Move data to arrow format"""
if isinstance(x, cudf.DataFrame):
return x.to_arrow()
else:
return pa.Table.from_pandas(x, preserve_index=False) | c88c40d2d35f681ff268347c36e2cae4a52576d0 | 4,525 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.