content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Callable
def rescue(
function: Callable[
[_SecondType],
KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType],
],
) -> Kinded[Callable[
[KindN[_RescuableKind, _FirstType, _SecondType, _ThirdType]],
KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType],
]]... | c5474129e260729c61f5ecc80e3c1bb714195b25 | 3,635,634 |
def try_get_resource(_xmlroot, parent_node: str, child_node: str, _lang: str):
""" Получить ресурс (решение / условия) """
for tutorial in _xmlroot.find(parent_node).iter(child_node):
lang = tutorial.attrib['language']
_type = tutorial.attrib['type']
if lang == _lang and _type == 'applic... | 7cb362ec0c1e8fb7926b67b3790b8c5bc9539a67 | 3,635,635 |
def get_sample_media():
"""Gets the sample media.
Returns:
bytes
"""
path = request.args.get("path")
# `conditional`: support partial content
return send_file(path, conditional=True) | 9e3d98928096b4261bf3451564791384423524ef | 3,635,638 |
def _is_swiftmodule(path):
"""Predicate to identify Swift modules/interfaces."""
return path.endswith((".swiftmodule", ".swiftinterface")) | 085fa4f8735ce371927f606239d51c44bcca5acb | 3,635,639 |
import itertools
def _unpack_array(fmt, buff, offset, count):
"""Unpack an array of items.
:param fmt: The struct format string
:type fmt: str
:param buff: The buffer into which to unpack
:type buff: buffer
:param offset: The offset at which to start unpacking
:type offset: int
:param... | 4aad2b38a332a9c57e4bb412990b4ba8ffd282dd | 3,635,640 |
def _add_column_and_sort_table(sources, pointing_position):
"""Sort the table and add the column separation (offset from the source) and phi (position angle from the source)
Parameters
----------
sources : `~astropy.table.Table`
Table of excluded sources.
pointing_position : `~astropy.c... | 780fa4cd5ebed99b556cb283f41a52594921db39 | 3,635,641 |
import torch
def smooth_l1_loss_detectron2(input, target, beta: float, reduction: str = "none"):
"""
Smooth L1 loss defined in the Fast R-CNN paper as:
| 0.5 * x ** 2 / beta if abs(x) < beta
smoothl1(x) = |
| abs(x) - 0.5 * beta otherwise,
where x = input - targ... | d6e9264e8de9acf3fec59cb70207c1aa4075ece6 | 3,635,644 |
def png_to_jpg(png_path, jpg_path):
""" convert image format: png -> jpg, then save picture with jpg
Args:
png_path (str)
jpg_path (str)
Return:
True or False (bool)
"""
img = Image.open(png_path)
try:
if len(img.split()) == 4:
# prevent IOError: ... | 255f5ed67d8929c05cbf573fcc64c45ff019ece1 | 3,635,645 |
import warnings
import io
def split_lines_to_df(in_lines_trunc_df):
"""
For a column of strings that each represent the line of a CSV
(and each line may have a different number of separators),
read them into a DataFrame.
in_lines_trunc_df: Assumes that the relevant column is `0`
Returns: The ... | eec9624a88f0758d4db2ecafc6df3eaa9e3a3eb2 | 3,635,646 |
def generate_full_vast_beleg_ids_request_xml(form_data, th_fields=None, use_testmerker=False):
""" Generates the full xml for the Verfahren "ElsterDatenabholung" and the Datenart "ElsterVaStDaten",
including "Anfrage" field.
An example xml can be found in the Eric documentation under
common/... | 88dd6e5e374deec62ce1229525bc936e2fb2ac79 | 3,635,647 |
def get_q_vocab(ques, count_thr=0, insert_unk=False):
"""
Args:
ques: ques[qid] = {tokenized_question, ...}
count_thr: int (not included)
insert_unk: bool, insert_unk or not
Return:
vocab: list of vocab
"""
counts = {}
for qid, content in ques.iteritems():
... | 4926a595d2d4bff50db986ad012a21357fb9b8ec | 3,635,648 |
def get_desc_dist(descriptors1, descriptors2):
""" Given two lists of descriptors compute the descriptor distance
between each pair of feature. """
#desc_dists = 2 - 2 * (descriptors1 @ descriptors2.transpose())
desc_sims = - descriptors1 @ descriptors2.transpose()
# desc_sims = d... | 2baea3bfa01b77765ec3ce95fd9a6be742783420 | 3,635,649 |
def _parse_cells_icdar(xml_table):
"""
Gets the table cells from a table in ICDAR-XML format.
"""
cells = list()
xml_cells = xml_table.findall(".//cell")
cell_id = 0
for xml_cell in xml_cells:
text = get_text(xml_cell)
start_row = get_attribute(xml_cell, "start-row"... | fdfca5c77f1122ae14bc8b72a676ab5cafab6c63 | 3,635,650 |
def gist_ncar(range, **traits):
""" Generator for the 'gist_ncar' colormap from GIST.
"""
_data = dict(
red = [(0.0, 0.0, 0.0),
(0.0050505050458014011, 0.0, 0.0),
(0.010101010091602802, 0.0, 0.0),
(0.015151515603065491, 0.0, 0.0),
(0.020202020183205605... | f4ade6627bdaba25ae873c76b5b0970f7a650a70 | 3,635,654 |
def main(request, username):
"""
User > Main
"""
namespace = CacheHelper.ns('user:views:main', username=username)
response_data = CacheHelper.io.get(namespace)
if response_data is None:
response_data, user = MainUserHelper.build_response(request, username)
if response_data['sta... | b605987f395b227a481012257c0c04add787cee5 | 3,635,655 |
import copy
def checksum2(path):
"""Calculate the checksum of a TSV.
The checksum of a TSV is calculated as the sum of the division between the
only two numbers in each row that evenly divide each other.
Arguments
---------
path : str
Path to a TSV file.
Returns
-------
... | 01ccbfbd1a2c4258105d5bf9dd46395ebd50b080 | 3,635,656 |
import configparser
def load_config(config_file_path):
"""
Load the config ini, parse settings to WORC
Args:
config_file_path (String): path of the .ini config file
Returns:
settings_dict (dict): dict with the loaded settings
"""
settings = configparser.ConfigParser()
se... | 3f85f3ccd9e635cb9ce021d424ed97e98cbfb75c | 3,635,657 |
import pathlib
def find_toplevel() -> pathlib.Path:
"""Get the toplevel git directory."""
return pathlib.Path(cmd_output(["rev-parse", "--show-toplevel"]).strip()) | 3d2cc723aadcec69b0d86b879e5d720f15d2c5da | 3,635,658 |
def db20(value):
"""Convert voltage-like value to dB."""
return 20 * log10(np.abs(value)) | ef261696d5fd4b3a0f841411e03fc9897a9a9a93 | 3,635,659 |
from typing import Any
def construct_class_by_name(*args, class_name: str = None, **kwargs) -> Any:
"""Finds the python class with the given name and constructs it with the given arguments."""
return call_func_by_name(*args, func_name=class_name, **kwargs) | a666bf509513a8098b0c4deca58141a2957741fb | 3,635,660 |
import csv
def simple_file_scan(reader, bucket_name, region_name, file_name):
""" Does an initial scan of the file, figuring out the file row count and which rows are too long/short
Args:
reader: the csv reader
bucket_name: the bucket to pull from
region_name: the regi... | ccd1aad870124a9b48f05bbe0d7fe510ae36bc33 | 3,635,661 |
import typing
import torch
import copy
def random_plane(model: typing.Union[torch.nn.Module, ModelWrapper], metric: Metric, distance=1, steps=20,
normalization='filter', deepcopy_model=False) -> np.ndarray:
"""
Returns the computed value of the evaluation function applied to the model or agen... | 8c431268a56a1ac929e9b5f272b476cbda64ab70 | 3,635,662 |
def _solarize_impl(pil_img, level):
"""Applies PIL Solarize to `pil_img`.
Translate the image in the vertical direction by `level`
number of pixels.
Args:
pil_img: Image in PIL object.
level: Strength of the operation specified as an Integer from
[0, `PARAMETER_MAX`].
Returns:
A PIL Ima... | d07952a043f61e401cc2c6fc858d43947c68019d | 3,635,663 |
def payment_callback():
"""通用支付页面回调"""
data = request.params
sn = data['sn']
result = data['result']
is_success = result == 'SUCCESS'
handle = get_pay_notify_handle(TransactionType.PAYMENT, NotifyType.Pay.SYNC)
if handle:
# 是否成功,订单号,_数据
return handle(is_success, sn)
if ... | dc7c2dfaadf47c00fe355f1c82465c38e8bf7c7c | 3,635,665 |
def get_rest_parameter_state(parameter_parsing_states):
"""
Gets the rest parameter from the given content if there is any.
Parameters
----------
parameter_parsing_states `list` of ``ParameterParsingStateBase``
The created parameter parser state instances.
Returns
-------
p... | e90d1ee848af7666a72d9d0d4fb74e3fedf496fa | 3,635,667 |
def random_user_id() -> str:
"""Return random user id as string."""
return generate_random_id() | ee6a8299a81458bc20d4c0879a9ca4ab0741b790 | 3,635,668 |
from typing import List
def batch_answer_same_question(question: str, contexts: List[str]) -> List[str]:
"""Answers the question with the given contexts (local mode).
:param question: The question to answer.
:type question: str
:param contexts: The contexts to answer the question with.
:type cont... | 3e013b793cebbb172c90d054e90bb830fbb7009f | 3,635,670 |
def calculate_log_probs(conditioners, joint_dists):
"""
Calculates the marginal log probabilities of each feature's values and also the conditional
log probabilities for the predecessors given in the predecessor map.
"""
log_marginals = [
N.log(joint_dists[f,f])
for f in xrange(len(condi... | dd84cf8b76177aeeb90ca6205402e95b3686b421 | 3,635,671 |
import json
def validate_response_code(response, expected_res):
""" Function to validate work order response.
Input Parameters : response, check_result
Returns : err_cd"""
# check expected key of test case
check_result = {"error": {"code": 5}}
check_result_key = list(check_result.keys(... | caf687ecffbe5deb9d8b458efede71f4c2c0b3be | 3,635,672 |
from scipy.stats import gaussian_kde
def _calc_density(x: np.ndarray, y: np.ndarray):
"""\
Function to calculate the density of cells in an embedding.
"""
# Calculate the point density
xy = np.vstack([x, y])
z = gaussian_kde(xy)(xy)
min_z = np.min(z)
max_z = np.max(z)
# Scale be... | 64ea42d14c933137ffb0efaf3a74d3ca1b4927b0 | 3,635,673 |
from x2paddle.op_mapper.pytorch2paddle import prim2code
def gen_layer_code(graph, sub_layers, sub_layers_name, different_attrs=dict()):
""" 根据sub_layers生成对应的Module代码。
Args:
graph (x2paddle.core.program.PaddleGraph): 整个Paddle图。
sub_layers (dict): 子图的id和其对应layer组成的字典。
sub_layers_name (s... | b4aac353a525405a8eecb82c3b719c419f1e938b | 3,635,674 |
import torch
def test_CreativeProject_integration_ask_tell_one_loop_kwarg_response_works(covars, model_type, train_X, train_Y,
covars_proposed_iter, covars_sampled_iter,
response_sampled... | aba248b5102013ea91f81c380faa922c18449cd9 | 3,635,675 |
import io
def read_all_files(filenames):
"""Read all files into a StringIO buffer."""
return io.StringIO('\n'.join(open(f).read() for f in filenames)) | efb2e3e8f35b2def5f1861ecf06d6e4135797ccf | 3,635,676 |
from typing import Optional
def calculate_distance(geojson, unit: Unit = Unit.meters) -> Optional[float]:
"""
Calculate distance of LineString or MultiLineString GeoJSON.
Raises geojson_length.exc.GeojsonLengthException if input GeoJSON is invalid.
:param geojson: GeoJSON feature of type LineString or... | 5f019f6acf7ff49189ceab7531ffddeef5a15d03 | 3,635,677 |
def weighted_mse_loss(y_true, y_pred):
"""
apply weights on heatmap mse loss to only pick valid keypoint heatmap
since y_true would be gt_heatmap with shape
(batch_size, heatmap_size[0], heatmap_size[1], num_keypoints)
we sum up the heatmap for each keypoints and check. Sum for invalid
keypoint... | 2ad89db78ec78d571a727002d6e62fc6de624965 | 3,635,678 |
def p_marketprices(
i: pd.DatetimeIndex,
avg: float = 100,
year_amp: float = 0.30,
week_amp: float = 0.05,
peak_amp: float = 0.30,
has_unit: bool = True,
) -> pd.Series:
"""Create a more or less realistic-looking forward price curve timeseries.
Parameters
----------
i : pd.Datet... | db51ba10f6dda4f1df77833d29310a97411f0979 | 3,635,679 |
def read_flow(fn):
""" Read .flo file in Middlebury format"""
# Code adapted from:
# http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy
# WARNING: this will work on little-endian architectures (eg Intel x86) only!
with open(fn, 'rb') as f:
... | e8b1d39a40b6650bdeb1ae8cf8b8ecd00b45c787 | 3,635,680 |
from typing import List
def sma(grp_df: pd.DataFrame, cols: List[str], windows: List[int]) -> pd.DataFrame:
"""
Calculate the simple moving average.
Parameters:
-------
grp_df: pd.DataFrame
The grouped dataframe.
col: str
window: list
List of windows to take simple moving ... | 12c80365255893330d1ced017019c318f3683587 | 3,635,681 |
def add_anchor_tag(anchor_id, header):
"""
Add anchor tag to header.
Input and output will look like below.
Input:
## Task 02 - Do something
Output:
## <a id="task02"></a> Task 02 - Do something [^](#toc)
"""
anchor = ANCHOR.format(anchor_id)
# Replace the first space w... | 1f58f985cc90d7cb8243a1d593eb89e329e7ccef | 3,635,682 |
from typing import Callable
def create_async_executor(query: Query) -> Callable:
"""Create async executor for query.
Arguments:
query: query for which executor should be created.
Returns:
Created async executor.
"""
executor = _OPERATION_TO_EXECUTOR[query.operation_type]
retu... | 0e13ae11e8096b807615c3cc8812dcd3e5acaed9 | 3,635,683 |
def batch_write_coverage(bed_fname, bam_fname, out_fname, by_count, processes):
"""Run coverage on one sample, write to file."""
cnarr = coverage.do_coverage(bed_fname, bam_fname, by_count, 0, processes)
tabio.write(cnarr, out_fname)
return out_fname | 7b29ed2422181f8a42574368a22da8814693f7f9 | 3,635,684 |
def splitTargets(targetStr):
""" break cmdargs into parts consisting of:
1) cmdargs are already stripped of their first arg
2) list of targets, including their number. Target examples:
* staff
* staff 2
* staff #2
* player
* player #3
"""
... | 4b53a7db8d8b871b21b2d5b9044f1889be462ace | 3,635,685 |
def get_model():
"""
Epoch 50/50
3530/3530 [==============================] - 10s - loss: 8.5420e-04 - acc: 1.0000 - val_loss: 0.3877 - val_acc: 0.9083
1471/1471 [==============================] - 1s
Train score: 0.00226768349974
Train accuracy: 1.0
"""
model=Sequential()... | d2a6baf0071c6d6e37cb9cf43e64e4ec2703b725 | 3,635,686 |
def path_inside_dir(path, directory):
"""
Returns True if the specified @path is inside @directory,
performing component-wide comparison. Otherwise returns False.
"""
return ((directory == "" and path != "")
or path.rstrip("/").startswith(directory.rstrip("/") + "/")) | 30ad431f9115addd2041e4b6c9c1c8c563b93fe9 | 3,635,687 |
def generate_sd_grid_mapping_traj(ipath_sd, n_top_grid, ipath_top_grid, ipath_grid_block_gps_range,
odir_sd, mapping_rate=1, mapping_bais=None):
"""generate the gird-mapping traj for SD
"""
def random_sampling(grid_range):
"""generate a sample point within a grid ra... | dbc70465e6a66cb967b697559f598d0e8c2ece90 | 3,635,689 |
def butterworth_type_filter(frequency, highcut_frequency, order=2):
"""
Butterworth low pass filter
Parameters
----------
highcut_frequency: float
high-cut frequency for the low pass filter
fs: float
sampling rate, 1./ dt, (default = 1MHz)
period:
period of the sign... | f8ff570d209560d65b4ccc9fdfd2d26ec8a12d35 | 3,635,691 |
def mypad(x, pad, mode='constant', value=0):
""" Function to do numpy like padding on tensors. Only works for 2-D
padding.
Inputs:
x (tensor): tensor to pad
pad (tuple): tuple of (left, right, top, bottom) pad sizes
mode (str): 'symmetric', 'wrap', 'constant, 'reflect', 'replicate', ... | 48e435e1622a1d74bff0b44e159dc0562e12bb5e | 3,635,693 |
import operator
def molarity(compound, setting = None, moles = None, volume = None):
"""
Calculations involving the molarity of a compound. Returns a value based on the setting.
The compound must be the Compound class. The moles/volume setting will be gathered from the compound itself if defined.
**Volume... | 4fb477115f2c41c5729702b4037aa63abcfaf6f1 | 3,635,694 |
def set_initial_det(noa, nob):
""" Function
Set the initial wave function to RHF/ROHF determinant.
Author(s): Takashi Tsuchimochi
"""
# Note: r'~~' means that it is a regular expression.
# a: Number of Alpha spin electrons
# b: Number of Beta spin electrons
if noa >= nob:
# Here... | 53b34999014d0926f02308122ad32f88ea08a802 | 3,635,695 |
def face_detection(frame):
""" detect face using cv2
:param frame:
:return: (x,y), w, h: face position x,y coordinates, face width, face height
"""
if frame is None :
return 0,0,0,0
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gr... | 8a75ca46fd78d481fa2ec6d93d7d8123d7bf4463 | 3,635,696 |
def coro1():
"""定义一个简单的基于生成器的协程作为子生成器"""
word = yield 'hello'
yield word
return word # 注意这里协程可以返回值了,返回的值会被塞到 StopIteration value 属性 作为 yield from 表达式的返回值 | 1bfcfb150748c002638d2c6536299025864ac1f6 | 3,635,697 |
import itertools
import scipy
def plot_combinations_9array3x3_v2(coli_to_test, sorted_combinations, sorted_vals, comb_ind, renaming_fun):
"""Plot the nine best decompositions of a given set with variables
outside the matrix for a decomposition of 3 variables
Parameters
----------
coli_to_test... | d34684e12b2ffb8157dff33a461ae9ee4f45c818 | 3,635,698 |
from typing import Union
from typing import Tuple
def random_split(df: Union[DataFrame, Series], split_size: float,
shuffle: bool = True, random_state: int = None) -> Tuple[DataFrame]:
"""Shuffles a DataFrame and splits it into 2 partitions according to split_size.
Returns a tuple with the sp... | 2b69d97d69bebd3257201bf5629bb4e033134f82 | 3,635,699 |
def create_discriminator_inputs(images, conditional_vectors):
"""
識別器用入力画像(画像+条件画像)を生成する。
Args:
images: 画像
conditional_vectors: 条件ベクトル
index: image_seqから取得するデータのインデックス
Returns
画像+条件画像を統合したテンソル (B, H, W, A + C)
B: バッチサイズ。images.shape[0]
H: 画像の高さ。images... | 75a14931106c05dd4007a0963c4152f0b54b04d5 | 3,635,700 |
def add_to_master_list(single_list, master_list):
"""This function appends items in a list to the master list.
:param single_list: List of dictionaries from the paginated query
:type single_list: list
:param master_list: Master list of dictionaries containing group information
:type master_list: li... | 4b4e122e334624626c7db4f09278b44b8b141504 | 3,635,701 |
from typing import Optional
def weight_by_attr(
attr: str, prev_edge: Optional[models.Edge], edge: models.Edge
) -> float:
"""
Generic weight function to retrieve a value from an edge.
"""
return getattr(edge, attr) | 292ab3d8cd551122eb57663bdc20f0aed288dd43 | 3,635,702 |
from typing import Union
import warnings
def check_if_porous(structure: Structure, threshold: float = 2.4) -> Union[bool, None]:
"""Runs zeo++ to check if structure is porous according to the CoRE-MOF
definition (PLD > 2.4, https://pubs.acs.org/doi/10.1021/acs.jced.9b00835)
Args:
structure (Struc... | a6af20bcb3273b4d516309fbe156b997db7e30dd | 3,635,703 |
def order_node_list(tree):
"""
Sorts a list of node dict from a LightGBM instance. Key `tree_structure` is
specific for LightGBM.
Parameters
----------
tree : list,
Unsorted list of node dicts
Returns
-------
ordered_node_list : list,
Ordered list of node dicts com... | 812dcaeb96e4c0a55dece5e678fd86d27f42ddf0 | 3,635,705 |
import logging
def sanitize_parameters(func):
"""Sets any queryparams in the kwargs"""
@wraps(func)
def wrapper(*args, **kwargs):
try:
logging.info(f'[middleware] [sanitizer] args: {args}')
myargs = dict(request.args)
# Exclude params like loggedUser here
... | b76d4361e73671130b03463ac74144a3a2111bef | 3,635,707 |
def build_render_setup(cfg):
"""Build information struct about the rendering backup from a configuration.
This performs type conversion to the expected types. Paths contained in
cfg are expected to be alread expanded. That is, it should not contain
global variables or other system dependent abbreviatio... | e7631ccbda98a99d1db961b3bbcbcf36d1b7b3ad | 3,635,708 |
def generate_coupled_image_from_self(img, out_img, noise_amp=10):
"""
Generates an input image for siam by concatenating an image with a transformed version of itself
"""
def __synthesize_prev_img(in_img, noise_amp=10):
"""Synthesizes previous frame by transforming the input image
... | 778de50045b2b8932453c61863923bb9d2127ad6 | 3,635,709 |
def pca_preprocess(df, pca_components):
"""Preprocess the given dataframe using PCA"""
# Drop rows
df.dropna(axis=0, inplace=True)
# Separate features and targets
X = df.drop('ASPFWR5', axis=1)
y = df['ASPFWR5']
# Dimensionality reduction with principal component analysis
... | b09506efb52502aacbb66a9b80a6d2abe55f84d9 | 3,635,710 |
from datetime import datetime
def add_nonce(func):
"""Helper function which adds a nonce to the kwargs dict"""
@wraps(func)
def inner(*args, **kwargs):
if "nonce" not in kwargs:
kwargs["nonce"] = int(datetime.datetime.utcnow().timestamp() * 1000)
return func(*args, **kwargs)
... | 9138066e65416dab677c42ac8a6106f4dc421832 | 3,635,711 |
def morse_encode(string):
"""Converts a string to morse code"""
words = [morse_encode_word(word) for word in string.split(' ')]
return ' '.join(words) | aea0ffc0172096f8507c16ee5f7fc9e75f36c596 | 3,635,713 |
def TIMES_cleanup (file, Model_Module):
"""Cleans data genrated by Oasis TIMES and returns a dataframe witht he DTXSID of the parent compound and InChI key of each metabolite"""
"""The Model_Module argument should be a string to designate the model used for metabolism (e.g., TIMES_RatLiver S9, TIMES_RatInVivo""... | ae5d566ad606ea74d7209b8304693238c71981e0 | 3,635,715 |
import random
def generate_key():
"""Generate an key for our cipher"""
shuffled = sorted(chars, key=lambda k: random.random())
return dict(zip(chars, shuffled)) | dc0cc2c5ac063f0b0e5f7b53445a43680d34be8f | 3,635,716 |
def unmatched(match):
"""Return unmatched part of re.Match object."""
start, end = match.span(0)
return match.string[:start] + match.string[end:] | 6d34396c2d3c957d55dbef16c2673bb7f571205c | 3,635,718 |
def cubicgw(ipparams, width, etc = []):
"""
This function fits the variation in Gaussian-measured PRF half-widths using a 2D cubic.
Parameters
----------
x1: linear coefficient in x
x2: quadratic coefficient in x
x3: cubic coefficient in x
y1: linear coefficient in y
y2: quadratic coeffici... | 334be9d8dc8baaddf122243e4f19d681efc707cf | 3,635,719 |
def get_columns_by_type(df, req_type):
"""
get columns by type of data frame
Parameters:
df : data frame
req_type : type of column like categorical, integer,
Returns:
df: Pandas data frame
"""
g = df.columns.to_series().groupby(df.dtypes).groups
type_dict = {k.name: v for k, v ... | aeedea92fbfb720ca6e7a9cd9920827a6ad8c6b0 | 3,635,722 |
def get_total(lines):
"""
This function takes in a list of lines and returns
a single float value that is the total of a particular
variable for a given year and tech.
Parameters:
-----------
lines : list
This is a list of datalines that we want to total.
Returns:
--------
... | 284f8061f3659999ae7e4df104c86d0077b384da | 3,635,723 |
def get_ipv6_by_ids(ip_ids):
"""Get Many Ipv6."""
networks = list()
for ip_id in ip_ids:
networks.append(get_ipv6_by_id(ip_id))
return networks | 29511fca93063921ace5019225c03ede518b4c0d | 3,635,724 |
def box(t, t_start, t_stop):
"""Box-shape (Theta-function)
The shape is 0 before `t_start` and after `t_stop` and 1 elsewhere.
Args:
t (float): Time point or time grid
t_start (float): First value of `t` for which the box has value 1
t_stop (float): Last value of `t` for which the ... | 8f4f0e57323f38c9cfa57b1661c597b756e8c4e7 | 3,635,725 |
import numpy
def newton_cotes(order, domain=(0, 1), growth=False, segments=1):
"""
Generate the abscissas and weights in Newton-Cotes quadrature.
Newton-Cotes quadrature, are a group of formulas for numerical integration
based on evaluating the integrand at equally spaced points.
Args:
o... | 72c4afcd7dce50752f349556356db000addba649 | 3,635,728 |
def transpose(a, axes=None):
"""transpose(a, axes=None) returns array with dimensions permuted
according to axes. If axes is None (default) returns array with
dimensions reversed.
"""
# if axes is None: # this test has been moved into multiarray.transpose
# axes = arange(len(array(a).shape))[... | 80fd37c9ab9e48d9bddc95eb8ae32f6d48250b6a | 3,635,729 |
def find_next_prime(N: int) -> int:
"""Find next prime >= N
Parameters
----------
N : int
Starting point to find the next prime >= N.
Returns
-------
int
the next prime found after the number N
"""
def is_prime(n):
if n % 2 == 0:
return False
... | 8648b3583e84a520eca0435cf6ebeb5a939af2fd | 3,635,730 |
def in_16(library, session, space, offset, extended=False):
"""Reads in an 16-bit value from the specified memory space and offset.
Corresponds to viIn16* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:para... | af7f28001faed46e52af0645462cd429e5ca7eb8 | 3,635,731 |
from typing import Pattern
def match_head(subject, pattern):
"""Checks if the head of subject matches the pattern's head."""
if isinstance(pattern, Pattern):
pattern = pattern.expression
pattern_head = get_head(pattern)
if pattern_head is None:
return True
if issubclass(pattern_hea... | cd1b418635dd9a974a0ca4643641ad97add0ed7d | 3,635,732 |
import json
import time
def sfn_result(session, arn, wait=10):
"""Get the results of a StepFunction execution
Args:
session (Session): Boto3 session
arn (string): ARN of the execution to get the results of
wait (int): Seconds to wait between polling
Returns:
dict|None: Di... | ba8a80e81aa5929360d5c9f63fb7dff5ebaf91f3 | 3,635,734 |
def forum_latest_user_posts(parser, token):
"""
{% forum_latest_user_posts user [number] as [context_var] %}
"""
bits = token.contents.split()
if len(bits) not in (2, 3, 5):
raise TemplateSyntaxError('%s tag requires one, two or four arguments' % bits[0])
if bits[3] != 'as':
rais... | 3138f7f43a7cc2b45d7d05ba82cc74bb512dcc29 | 3,635,735 |
def PureMultiHeadedAttention(x, params, num_heads=8, dropout=0.0,
mode='train', **kwargs):
"""Pure transformer-style multi-headed attention.
Args:
x: inputs ((q, k, v), mask)
params: parameters (none)
num_heads: int: number of attention heads
dropout: float: dropout rat... | 32fb6aee5c82b6eaa5aae4cab3b98fb0b5cc423b | 3,635,737 |
def validate_options(options):
"""
Validate the options and return bool.
:param options: options to validate
:type options: dict
:rtype: bool
"""
pywikibot.log('Options:')
notice_keys = [
'email_subject',
'email_subject2',
'email_text',
'email_text2',
... | dade1084873dc9eec95a3be364560d115bbb670c | 3,635,738 |
from typing import List
from typing import Dict
from typing import Any
import logging
def main(
domain: InnerEnv,
planner: planning_types.Planner,
belief: belief_types.Belief,
runs: int,
logging_level: str,
) -> List[Dict[str, Any]]:
"""plan online function of online planning
Handles call... | e45d8aa43933bd85779d48572e4db327003887ec | 3,635,740 |
from typing import Union
from typing import Any
def format_color(
color: Union[ColorInputType, Any],
warn_if_invalid: bool = True
) -> Union[ColorType, Any]:
"""
Format color from string, int, or tuple to tuple type.
Available formats:
- Color name str: name of the color to use, e.g. ... | e4b5413ce96824e7e4990d9e78ec36ad1690a400 | 3,635,742 |
from typing import Optional
def is_yaml_requested(
content_type: str = None,
proto: ExtendedProto = None,
path_suffix: Optional[str] = None,
) -> bool:
"""Checks whether YAML is requested by the user, depending on params."""
is_yaml = False
if content_type is not None:
is_yaml = ("yaml... | 93ace7639b00430d7f3731a0a54792037edff4cc | 3,635,743 |
def _pqs_in_range(dehn_pq_limit, num_cusps):
"""
Return an iterator. This iterator, at each step, returns a
tuple. The contents of this tuple are num_cusps other tuples, and
each of these is of the form (p,q), where 0 <= p <= dehn_pq_limit,
-dehn_pq_limit <= q <= dehn_pq_limit, and gcd(p,q) <= 1.
... | fe28e43823c6b2510ed80294d4b7ed4bed02ed54 | 3,635,744 |
def _units_defaults(calendar, has_year_zero=None):
"""
Set calendar specific default units as 'days since reference_date'
Day 0 of *excel* and *excel1900* starts at 1899-12-31 00:00:00.
Day 0 of *excel1904* starts at 1903-12-31 00:00:00.
Decimal calendars *decimal*, *decimal360*, *decimal365*, an... | 06b7cbc78ad49bdfc24324249c89c49cc7a63723 | 3,635,745 |
def submit_a_feed(request):
"""
用户添加一个自定义的订阅源
"""
feed_url = request.POST.get('url', '').strip()[:1024]
user = get_login_user(request)
if feed_url:
host = get_host_name(feed_url)
if host in settings.ALLOWED_HOSTS:
rsp = add_self_feed(feed_url)
elif settings.... | bf9d4abc850c8012e7c5f56a18df6880b0ea5b04 | 3,635,746 |
def check_existing_credendtials(account_Name):
"""
Function that check if a Credentials exists with that account name and return a Boolean
"""
return Credentials.credential_exist(account_Name) | 31a0edad670b15c9e6e45175c24a55705e9eac4c | 3,635,747 |
def scmplx(p,a,b):
"""
p is a string designating a type, either scalar_f or scalar_d.
"""
if p == 'scalar_f':
return vsip_cmplx_f(a,b)
elif p == 'scalar_d':
return vsip_cmplx_d(a,b)
else:
assert False,'Type %s not defined for cmplx.'%p | 56773eaded2b676c09cdd3b93ef320d9e8a615b3 | 3,635,749 |
import json
def ips_description(request):
"""See :class:`bgpranking.api.get_ips_descs`"""
asn = request.get('asn')
block = request.get('block')
if asn is None or block is None:
return json.dumps({})
return json.dumps(bgpranking.get_ips_descs(asn, block,
request.get('d... | 47318917517cd519e646e477cd933bd639aa4ceb | 3,635,750 |
def handle_msg(msg: dict) ->list:
""" Handler for message request object. Logs message and returns list of responses."""
msg_alert(msg['From'], msg['Body'])
msg, lol = parse_msg(msg)
if lol is not None:
resp = lol
elif lol is None:
resp = get_response(msg)
log_msg = [
{... | d3f751dacf2594ae1aa691c4d4f9e58ee41b4f44 | 3,635,751 |
def create_app(register_blueprints=True):
"""Function to instantiate, configure, and return a flask app"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('app.default_config') # default config
# app.config.from_pyfile('application.cfg.py') # server config file, do not inc... | 459c776e713f6e4c4157d9599a625235565c50c8 | 3,635,752 |
def RoleAdmin():
"""超级管理员"""
return 1 | 78a4fce55fa0fb331c0274c23213ae72afe7184f | 3,635,753 |
import pyproj
from pyproj.exceptions import DataDirError
def _get_proj_info():
"""Information on system PROJ
Returns
-------
proj_info: dict
system PROJ information
"""
try:
data_dir = pyproj.datadir.get_data_dir()
except DataDirError:
data_dir = None
blob = ... | 4e6d7b3f1375f32a5fe4dd106b8e9ac79f29912f | 3,635,754 |
def run_program(intcodes):
"""run intcodes, which are stored as a dict of step: intcode pairs"""
pc = 0
last = len(intcodes) - 1
while pc <= last:
if intcodes[pc] == 1:
# add
if pc + 3 > last:
raise Exception("out of opcodes")
arg1 = intcodes[... | e87343483abddffd9508be6da7814abcbcd59a79 | 3,635,755 |
from re import T
def concat(lst, cat_symb=None, append_to_end=False):
"""Concatenates `lst` of Tensors, optionally with a join symbol.
Args:
lst: list of Tensors to concatenate.
cat_symb: concatenation symbol.
append_to_end: if set to ``True``, it will add the `cat_symb` to the end
... | c8a17b7c44abd3f41ca57097782a2707ba9aaa63 | 3,635,756 |
def find_mcs(mols):
"""Function to count the number of molecules making ito the end of the test"""
out_mols = ROMol_Vect()
while mols.hasNext():
molobj = mols.next()
rdmol, molobj = get_or_create_rdmol(molobj)
# Add this mol to that vector
out_mols.add(rdmol)
# Now find t... | b1ca9cba06187918559bd5ce6b13319b793c4fc6 | 3,635,757 |
def to_numpy(tensor):
"""Convert 3-D torch tensor to a 3-D numpy array.
Args:
tensor: Tensor to be converted.
"""
return tensor.transpose(0, 1).transpose(1, 2).clone().numpy() | 034e016caccdf18e8e33e476673884e2354e21c7 | 3,635,758 |
import time
def is_cluster_healthy(admin, zk, retries=10, retry_wait=30):
"""Return true if cluster is healthy."""
retries_left = retries
while retries_left:
md = _request_meta(admin)
if md is not None and not _unhealthy(md, zk):
logger.info("Cluster is healthy!")
r... | 2995067e30664a616cc48409b6597bf1a80f0067 | 3,635,760 |
def load_data(loc):
""" Load in the csv file """
df = pd.read_csv(loc, engine = "python", encoding = "utf-8")
df.fillna("")
df = np.asarray(df)
return df | b59cc344cdc2ad2805f7d237e22c65c8b2f7300c | 3,635,761 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.