content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def record(location):
"""Creates an empty record."""
draft = RDMDraft.create({})
record = RDMRecord.publish(draft)
return record | 77c8069e4fd894f2ed1d760fc983a9a2094c0f6d | 18,717 |
def firfls(x, f_range, fs=1000, w=3, tw=.15):
"""
Filter signal with an FIR filter
*Like firls in MATLAB
x : array-like, 1d
Time series to filter
f_range : (low, high), Hz
Cutoff frequencies of bandpass filter
fs : float, Hz
Sampling rate
w : float
Length of ... | 71c7c3fc229ce8745f5940593a6e5a2f9bf12490 | 18,718 |
def extract_and_coadd(ra, dec, pm_ra, pm_dec, match_radius=4./3600.,
search_radius=25./60, sigma_clip=None, query_timeout=60.,
upper_limits=True, return_exps=False):
"""
The top-level function of this module, extract_and_coadd finds sources in
GALEX archive matchi... | d28d62877ba0c8a99aba1596128dc764bc3e19b7 | 18,719 |
import aiohttp
async def create_payout(
session: ClientSession, data: CreatePayoutRequest
) -> CreatePayoutResponse:
"""
Create a payout.
"""
url = RAZORPAY_BASE_URL + "/payouts"
async with session.post(
url,
json=data.__dict__,
auth=aiohttp.BasicAuth(RAZORPAY_KEY_ID, ... | c4b9dae09111c83efb1d5a9c5fd88050f11b5510 | 18,720 |
def eval_ocr_metric(pred_texts, gt_texts):
"""Evaluate the text recognition performance with metric: word accuracy and
1-N.E.D. See https://rrc.cvc.uab.es/?ch=14&com=tasks for details.
Args:
pred_texts (list[str]): Text strings of prediction.
gt_texts (list[str]): Text strings of ground tru... | 0ec92be231d93abf9db8247369ba5ea546bd1b17 | 18,721 |
def get_all_zones():
"""Return a list of all available zones."""
cf = CloudFlare.CloudFlare(raw=True)
page_number = 0
total_pages = 1
all_zones = []
while page_number < total_pages:
page_number += 1
raw_results = cf.zones.get(params={'per_page':100, 'page':page_number})
z... | 0b9f6bf9b7b8fe274f7c6f856abf1d9397384c3c | 18,722 |
def entry_id(e):
"""entry identifier which is not the bibtex key
"""
authortitle = ''.join([author_id(e),title_id(e)])
return (e.get('doi','').lower(), authortitle) | 7c663d6c2bbdfcef8168c11a78e176e634cf644b | 18,723 |
def AskNumber(text="unknown task"):
"""
Asks the user to interactively input a number (float or int) at any point in the script, and returns the input number.
| __option__ | __description__
| --- | ---
| *text | an optional string to identify for what purpose the chosen number will be used.
"""
def ValidateN... | 41949d0a2e2d87b5cdb26d2db9bff9a64fbeeb1d | 18,724 |
def TokenEmphasis(character="_"):
"""
Italic (`<i>`, `<em>`) text is rendered with one asterisk or underscore
"""
assert character in ("_", "*")
return {
"type": "Characters",
"data": character,
"_md_type": mdTokenTypes["TokenEmphasis"],
} | 2012fdeb9ca4d9483b4cc403010f9900dcc1230f | 18,725 |
import random
def generate_plan(suite, node):
"""Randomly generates a plan, completely ignoring norms. This is mainly for testing the norm driven algorithm"""
plan = [node]
next_actions = next_actions(suite,node)
# print "Next actions ", next_actions
while (next_actions != []):
a = random.... | 30d967986d1c4237b4b312470d47d1ecce06ecbc | 18,727 |
def update_y(pred_coords, ypart_tracker, history=1500):
"""
Update y-tracker and store last 1500 detection
:param pred_coords: y coordinates
:param ypart_tracker: choose keypoints based on input conditions
:return: y-tracker
"""
anks_val = (pred_coords[15] + pred_coords[16]) * 0.5
shdr_v... | ee1880e27b121dae4661a93286bf07117bc7bb34 | 18,728 |
def augmentData(features, labels):
"""
For augmentation of the data
:param features:
:param labels:
:return:
"""
features = np.append(features, features[:, :, ::-1], axis=0)
labels = np.append(labels, -labels, axis=0)
return features, labels | ef684ae2bf9eb4fca9a0636d3b0089020805f4be | 18,729 |
def sigmoid(x):
""" Implement 1 / ( 1 + exp( -x ) ) in terms of tanh."""
return 0.5 * (np.tanh(x / 2.) + 1) | 95d6dd0cd62db2c43df419358ef368609ede42c8 | 18,731 |
def get_unique_output_values(signals):
"""
Based on segment length, determine how many of the possible four
uniquely identifiable digits are in the set of signals.
"""
unique_digit_count = 0
for signal in signals:
for digit in signal["output"]:
if len(digit) in (2, 3, 4, 7):... | 84098d4d294bfdd1b983ea70d51da1453b17245a | 18,732 |
import itertools
def split_and_pad(s, sep, nsplit, pad=None):
""" Splits string s on sep, up to nsplit times.
Returns the results of the split, pottentially padded with
additional items, up to a total of nsplit items.
"""
l = s.split(sep, nsplit)
return itertools.chain(l, itertools.rep... | 6c439301df7109d9b01a06a87bd7d6adafb8ee1e | 18,733 |
def transpose_report(report):
"""Transposes the report. Columns into rows"""
return list(map(list, zip(*report))) | bc59f9106496b0b830fdc9ac0266f3b774a8f759 | 18,734 |
def _shape_from_resolution(resolution):
"""
Calculate the shape of the global Earth relief grid given a resolution.
Parameters
----------
resolution : str
Same as the input for load_earth_relief
Returns
-------
shape : (nlat, nlon)
The calculated shape.
Examples
... | c726d599696cee2259bc450606e63480b0991451 | 18,735 |
def __virtual__():
"""
Load module only if cx_Oracle installed
"""
if HAS_CX_ORACLE:
return __virtualname__
return (
False,
"The oracle execution module not loaded: python oracle library not found.",
) | a64eddc8b78e5d7b3c8e0588a72a0c238b4c12d0 | 18,736 |
def get_fuel_from(mass: int) -> int:
"""Gets fuel from mass.
Args:
mass (int): mass for the fuel
Returns:
int: fuel necessary for the mass
"""
return mass // 3 - 2 | 37390c8cb9ba7e84c7b5c14841528d6c38f1589e | 18,739 |
def test_energy_density_function():
"""
Compute the Zeeman energy density over the entire mesh, integrate it, and
compare it to the expected result.
"""
mesh = df.RectangleMesh(df.Point(-50, -50), df.Point(50, 50), 10, 10)
unit_length = 1e-9
H = 1e6
# Create simulation object.
sim ... | 10a4da043554a93c3d6c90f32c554741b2fe2c7b | 18,740 |
def my_Bayes_model_mse(params):
""" Function fits the Bayesian model from Tutorial 4
Args :
params (list of positive floats): parameters used by the model (params[0] = posterior scaling)
Returns :
(scalar) negative log-likelihood :sum of log probabilities
"""
trial_ll = np.zeros_li... | b4a03e3edd0c9894b518ecd2589949aed8337479 | 18,741 |
def validate_request_tween_factory(handler, registry):
"""
Updates request.environ's REQUEST_METHOD to be X_REQUEST_METHOD if present.
Asserts that if a POST (or similar) request is in application/json format,
with exception for /metadata/* endpoints.
Apache config:
SetEnvIf Request_Method ... | 909e7d67044e31c1b3c0a97774d398f7d64d40bb | 18,742 |
async def get_rank(display_number: int, minimal_msg_number: int,
display_total_number: int, group_id: int) -> str:
""" 获取排行榜 """
repeat_list = recorder_obj.repeat_list(group_id)
msg_number_list = recorder_obj.msg_number_list(group_id)
ranking = Ranking(group_id, display_number, minim... | f1ca183890e33b15b77d7693771b37c33af9535e | 18,743 |
def feedback(request):
"""FeedbackForm"""
if (request.method == 'POST'):
form = forms.FeedbackForm(request.POST)
# pdb.set_trace()
if form.is_valid():
form.save()
type = form.cleaned_data['type']
type = dict(form.fields['type'].choices)[type]
... | 188dfa77d7e72555062e25acc15518f90c252b33 | 18,744 |
def get_convolutional_args(call, include_buffers=False, remove_constants=False):
"""A method to extract the arguments from conv2d or depthwise_conv2d extern call."""
args = call.args
conv_args = []
remove_indices = [0]
if remove_constants:
remove_indices += [41, 42, 44, 45]
for i, arg ... | 01db4d4e025bb9212bcb20a8852a7d4f1250e4b2 | 18,745 |
def view_party(party_id):
"""View dashboard for that party."""
party = party_service.find_party(party_id)
if party is None:
abort(404)
days = party_service.get_party_days(party)
days_until_party = (party.starts_at.date() - date.today()).days
orga_count = orga_team_service.count_member... | de02cf21c9afe35a1dc5ef7a896d99d40a9bd43f | 18,746 |
def subcat_add():
"""
添加小分类
"""
if request.method == 'POST':
cat_name = request.form['cat_name']
super_cat_id = request.form['super_cat_id']
# 检测名称是否存在
subcat = SubCat.query.filter_by(cat_name=cat_name).count()
if subcat :
return "<script>alert('该小分类已经... | 046011d15be00557b28f9300d813ffc6e23d43e0 | 18,748 |
async def async_setup_entry(hass, config_entry, async_add_devices):
"""Set up the Alexa sensor platform by config_entry."""
return await async_setup_platform(
hass,
config_entry.data,
async_add_devices,
discovery_info=None) | b7a4a8a4573ecc008f43a4a9c3e9dcfa21fb0d78 | 18,749 |
def parse_duration(dur: str) -> int:
"""Generates seconds from a human readable duration."""
if not DURATION_REGEX.match(dur):
raise ValueError('Time passed does not match required format: `XX:XX` or `XX:XX:XX`')
parts = dur.split(':')
seconds = 0
if len(parts) == 3:
seconds += int... | ec60b2362d8dc2e898e278b4e1dbf0aca764bc87 | 18,750 |
import random
def shorter_uuid(length=7, starter=None, with_original=False):
"""
Generate an even shorter short UUID generated by the shortuuid library.
:param length: Length of trimmed ID.
:param starter: Whether to begin with an already-created ShortUUID.
Useful when using recur... | 80eca9d14ff3ebeccd77a4b989dde52e4786a042 | 18,751 |
from typing import Iterable
from typing import Callable
from typing import Optional
from typing import List
from typing import Dict
def group_by(s: Iterable[_ElementType],
key: Callable[[_ElementType], _GroupType],
gfunc: Optional[Callable[[List[_ElementType]], _ResultType]] = None) -> Dict[... | b515e0b3a3467b47ad29552bed39b14eca2d2978 | 18,752 |
def init_templateflow_wf(
bids_dir,
output_dir,
participant_label,
mov_template,
ref_template='MNI152NLin2009cAsym',
use_float=True,
omp_nthreads=None,
mem_gb=3.0,
modality='T1w',
normalization_quality='precise',
name='templateflow_wf',
fs_subjects_dir=None,
):
"""
... | 677218b13cbfc48881440523d87667eaed7ea2e8 | 18,753 |
def Qest(ICobj, r=None):
"""
Estimate Toomre Q at r (optional) for ICs, assuming omega=epicyclic
frequency. Ignores disk self-gravity
"""
if not hasattr(ICobj, 'sigma'):
raise ValueError, 'Could not find surface density profile (sigma)'
G = SimArray(1.0, 'G')
kB = ... | f262c0f68683dc069dd983981b2cbd1d9a9e608a | 18,754 |
def get_projector_csr_file(config_name: str) -> str:
"""Returns full path to projector server crt file"""
return join(get_run_configs_dir(), config_name, f'{PROJECTOR_JKS_NAME}.csr') | 159bc798d28bf23ce06d356591d8c41bcea40356 | 18,755 |
def make_epsilon_greedy_policy(Q: defaultdict, epsilon: float, nA: int) -> callable:
"""
Creates an epsilon-greedy policy based on a given Q-function and epsilon.
I.e. create weight vector from which actions get sampled.
:param Q: tabular state-action lookup function
:param epsilon: exploration fac... | f0fe733b18b416939db44acd830ee605bc41e18f | 18,758 |
def write_init(proxy_parameters=None, exception=None):
"""Encodes and returns an MPI ('Metadata Init') response."""
return _write_init(Method.MPI, MetadataProviderError, proxy_parameters,
exception) | 0a73c4949796a93549e208da523e805894170193 | 18,759 |
def pfam_to_pubmed(family):
"""get a list of associated pubmed ids for given pfam access key.
:param family: pfam accession key of family
:type family: str
:return: List of associated Pubmed ids
:rettype:list"""
url='https://pfam.xfam.org/family/'+family
pattern='http://www.ncbi.nlm.nih... | e3d63050d7e2e782ccd9d376fb4cd2d33c177be6 | 18,760 |
def cvConvexHull2(input, hull_storage=None, orientation=CV_CLOCKWISE, return_points=0):
"""CvSeq_or_CvMat cvConvexHull2(list_or_tuple_of_CvPointXYZ input, void* hull_storage=NULL, int orientation=CV_CLOCKWISE, int return_points=0)
Finds convex hull of point set
[ctypes-opencv] OpenCV's note: a vertex of th... | 3def10577e29e6b9bcf2611ad194dca2f6e2feb7 | 18,761 |
from typing import Union
from typing import Optional
from typing import Dict
def init_classifier(config: Union[str, mmcv.Config],
checkpoint: Optional[str] = None,
device: str = 'cuda:0',
options: Optional[Dict] = None) -> nn.Module:
"""Prepare a few sho... | 20f819892295f6bfeb9c01f4e6d558731a2f8e68 | 18,762 |
def Newton_method(f, df, start:float=0.0, max_step:int=32, sign_dig:int=6)->float:
"""
Newton method.
---------------------------
Args:
None.
Returns:
None.
Raises:
None.
"""
fun = lambda x: x - f(x)/df(x)
return fixed_point(fun, start, max_step, sign_dig) | d3a803a1a10b6c6d34831efeccd6fb7bae43689a | 18,764 |
def get_all(isamAppliance, count=None, start=None, filter=None, check_mode=False, force=False):
"""
Retrieve a list of federations
"""
return isamAppliance.invoke_get("Retrieve a list of federations",
"{0}/{1}".format(uri, tools.create_query_string(count=count, start=... | d65529bfc953976247fd44cb50051d5efddf10ea | 18,765 |
def roty(theta):
"""
Rotation about Y-axis
@type theta: number
@param theta: the rotation angle
@rtype: 3x3 orthonormal matrix
@return: rotation about Y-axis
@see: L{rotx}, L{rotz}, L{rotvec}
"""
ct = cos(theta)
st = sin(theta)
return mat([[ct, 0, st],
... | 702051efbd9f0999e04d5d7faca207c53520d712 | 18,766 |
def flush(name, family="ipv4", ignore_absence=False, **kwargs):
"""
.. versionadded:: 2014.7.0
.. versionchanged:: Magnesium
Flush current nftables state
family
Networking family, either ipv4 or ipv6
ignore_absence
If set to True, attempts to flush a non-existent table will n... | 67ab6d2f7e337ff5a68704be14d605298a1447aa | 18,767 |
def solution(s):
"""
Check if a string has properly matching brackets
:param s: String to verify if it is well-formed
:return: 1 if the brackets are properly matching, 0 otherwise
"""
return check_matching_brackets(s, opening="(", closing=")") | 4ba1bb92e0a1db05557980420f2fac3a88b93086 | 18,768 |
def process_to_annotation_data(df, class_names, video_fps, min_len):
"""
This function cleans the output data, so that there are
no jumping frames.
"""
j = 1 # Helper
# Minimum qty of frames of the same task in order to
# consider it a whole task
min_frames = int(float(min_len) * float... | eaa0537b217030664562489a2ceeec63cf7b32c0 | 18,769 |
def reduce_memmap(a):
"""Pickle the descriptors of a memmap instance to reopen on same file."""
m = _get_backing_memmap(a)
if m is not None:
# m is a real mmap backed memmap instance, reduce a preserving striding
# information
return _reduce_memmap_backed(a, m)
else:
# Th... | 4e4caf6bb5f1be1f62537c45671010232665ec0c | 18,770 |
def load_sparse_csr(filename):
"""Load a saved sparse matrix in csr format. Stolen from above source."""
loader = np.load(filename)
return sparse.csr_matrix((loader['data'], loader['indices'],
loader['indptr']), shape=loader['shape']) | 9654e8baedf5ada8b626d86860aef2335a04b565 | 18,771 |
from typing import Optional
def blank(name: Optional[str]) -> Output:
"""Generate a blank `Output` instance."""
return Output(file_suffix=name or _DEFAULT_SUFFIX, variables=dict()) | 0811dd8875983b89a8ae82a204243419effddcb4 | 18,772 |
def estatistica_regras(regras_pt, regras_lgp):
"""
Contagem das regras morfossintáticas no corpus.
:param regras_pt: Lado português das regras (lista)
:param regras_lgp: Lado LGP das regras (lista)
:return: Dicionário com a frequência de cada regra. Ex: {"(0, 'INT')": 1, "(1, 'CAN')": 1, "(2, 'INT')": 1}
"""
est... | 67e1edae2d0418e1a36eefbb16ea4795b04728d6 | 18,773 |
def bq_create_dataset(bq_client):
"""Creates the BigQuery dataset.
If the dataset already exists, the existing dataset will be returned.
Dataset will be create in the location specified by DATASET_LOCATION.
Args:
bq_client: BigQuery client
Returns:
BigQuery dataset that will be used to store data... | ff2c0072210541261aff58ef8c590e94260e046d | 18,775 |
def root_node():
"""
Returns DCC scene root node
:return: str
"""
return scene.get_root_node() | 3a632bc0887a5c3a5696ec10f4387c917d12bfe5 | 18,776 |
def firsts(things):
"""
FIRSTS list
outputs a list containing the FIRST of each member of the input
list. It is an error if any member of the input list is empty.
(The input itself may be empty, in which case the output is also
empty.) This could be written as::
to firsts :list
... | 72141a7409cb17ac6785eabde91b45d5e9e0869f | 18,777 |
def inf_set_mark_code(*args):
"""
inf_set_mark_code(_v=True) -> bool
"""
return _ida_ida.inf_set_mark_code(*args) | 0395ab40bac5f036210802fdf548534c83c78951 | 18,778 |
def get_letter(xml):
"""
:param xml:
:return: everything between <bank> tag
"""
try:
left, right = xml.index('<bank '), xml.index('</bank>') + _BANK_OFFSET
return xml[left:right]
except ValueError:
return None | 3c7a601b2a25969902d530e3e17a48ddcf0819c1 | 18,779 |
def PowercycleNode(opts, args):
"""Remove a node from the cluster.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the name of
the node to be removed
@rtype: int
@return: the desired exit code
"""
node = args[0]
if (not ... | 557b48309bb897da29cc1c1f6f724cd6d3959e23 | 18,781 |
def collect_data(bids_dir, participant_label, queries, filters=None, bids_validate=True):
"""
Uses pybids to retrieve the input data for a given participant
"""
if isinstance(bids_dir, BIDSLayout):
layout = bids_dir
else:
layout = BIDSLayout(str(bids_dir), validate=bids_validate)
... | eaa15a3b3dacbae7c16b03f0c6347d71d939b57d | 18,782 |
def minimaldescriptives(inlist):
"""this function takes a clean list of data and returns the N, sum, mean
and sum of squares. """
N = 0
sum = 0.0
SS = 0.0
for i in range(len(inlist)):
N = N + 1
sum = sum + inlist[i]
SS = SS + (inlist[i] ** 2)
mean = sum / float(N)
... | ca1d821ef64b93218bdb22268bfdde737f2d731c | 18,783 |
def gen_filelist(infiles, tmpd) :
"""Write all audio files to a temporary text document for ffmpeg
Returns the path of that text document."""
filename = tmpd/"files.txt"
with open(filename, "w") as f:
for file in infiles:
# This part ensures that any apostro... | c7d21c62de34fea98725a39fec735836e0cfd3d9 | 18,784 |
def VMMemoryLower() -> tvm.ir.transform.Pass:
"""Perform memory lowering. Lowers the relax.builtin.alloc_tensor intrinsic to VM intrinsics.
Returns
-------
ret: tvm.ir.transform.Pass
"""
return _ffi_api.VMMemoryLower() | f636ea5f854e42413395669d1a0da3c2e439fb1e | 18,786 |
def _is_disk_larger_than_max_size(device, node_uuid):
"""Check if total disk size exceeds 2TB msdos limit
:param device: device path.
:param node_uuid: node's uuid. Used for logging.
:raises: InstanceDeployFailure, if any disk partitioning related
commands fail.
:returns: True if total disk... | ed39e885825cec7c2fba895121741b43e3661a58 | 18,787 |
def getLines(filename):
"""Return list of lines from file"""
with open(filename, 'r', errors='ignore') as ff:
return ff.readlines() | 36e515decaa3876eed3b5db8363fb81a5db89c84 | 18,788 |
import torch
def bbox_next_frame_v3(F_first, F_pre, seg_pre, seg_first, F_tar, bbox_first, bbox_pre, temp, name):
"""
METHOD: combining tracking & direct recognition, calculate bbox in target frame
using both first frame and previous frame.
"""
F_first, F_pre, seg_pre, seg_first, F_tar = s... | 62d782a04b5d7c114fe0096fec50d6cd2d9db7bf | 18,789 |
def hough_lines(img, rho=2, theta=np.pi / 180, threshold=20, min_line_len=5, max_line_gap=25, thickness=3):
"""Perform a Hough transform on img
Args:
img (numpy.ndarray): input image
rho (float, optional): distance resolution in pixels of the Hough grid
theta (float, optional): angular ... | f797e8b24255225d4c2beb41677da3fa6c6e42d6 | 18,790 |
import packaging
def verify_package_version(ctx, config, remote):
"""
Ensures that the version of package installed is what
was asked for in the config.
For most cases this is for ceph, but we also install samba
for example.
"""
# Do not verify the version if the ceph-deploy task is being... | 5ab0177738ccec3879c0383a13038515b2d6b6e9 | 18,791 |
def decrypt(v1: int, v2: int):
"""funcao desencriptadora"""
palavra_encriptada = int(v1) ^ int(v2)
desencriptada = palavra_encriptada.to_bytes((palavra_encriptada.bit_length() + 7) // 8, 'big')
return desencriptada.decode() | 19887e070f0c6ae7e68f677d69c2c5eb24761bdb | 18,793 |
def enforce_mixture_consistency_time_domain(mixture_waveforms,
separated_waveforms,
mix_weights=None,
mix_weights_type=''):
"""Projection implementing mixture consistency in time domain.... | 294b1d927394ef388967de529ac5f24382ceec2c | 18,794 |
def MatchNormsLoss(anchor_tensors, paired_tensors):
"""A norm on the difference between the norms of paired tensors.
Gradients are only applied to the paired_tensor.
Args:
anchor_tensors: batch of embeddings deemed to have a "correct" norm.
paired_tensors: batch of embeddings that will be pushed to the n... | 02f62a90cf51547b4af6063ad13be1bb712dfe5a | 18,795 |
def authenticate_begin(username, **_):
"""
Begin authentication procedure
Variables:
username user name of the user you want to login with
Arguments:
None
Data Block:
None
Result example:
<WEBAUTHN_AUTHENTICATION_DATA>
"""
user = STORAGE.user.get(username, as_obj=... | 6a42bfd2aba2f17f7ee7ec892bf23ef2f0221ee0 | 18,797 |
def tempSHT31():
"""Read temp and humidity from SHT31"""
return sht31sensor.get_temp_humi() | 1e934ad3a467d48019ec91e18ffab4e8d4c473ae | 18,798 |
import requests
def dog(argv, params):
"""Returns a slack attachment with a picture of a dog from thedogapi"""
# Print prints logs to cloudwatch
# Send response to response url
dogurl = 'https://api.thedogapi.com/v1/images/search?mime_types=jpg,png'
dogr = requests.get(dogurl)
url = dogr.json(... | cb80426e6cab0aa2fc58b78baa0ff225d654f04a | 18,799 |
def get_public_suffix (domain):
""" get_public_suffix("www.example.com") -> "example.com"
Calling this function with a DNS name will return the
public suffix for that name.
Note that if the input does not contain a valid TLD,
e.g. "xxx.residential.fw" in which "fw" is not a valid TLD,
the retu... | 8982df4677f1a1853fa328973cfc00c17796e3d8 | 18,800 |
from scipy.interpolate import interp1d
def interpol(data,x):
"""
Resamples data by given factor with interpolation
"""
# Resamples data by given factor by interpolation
x0 = np.linspace(0, len(data)-1, len(data))
x1 = np.linspace(0, len(data)-1, len(data)*x-(x-1))
f = interp1d(x0, data)
... | 85cb9c9d776abc8317edbf1df5935e78ac774c02 | 18,801 |
import torch
def convert_to_torch_tensors(X_train, y_train, X_test, y_test):
""" Function to quickly convert datasets to pytorch tensors """
# convert training data
_X_train = torch.LongTensor(X_train)
_y_train = torch.FloatTensor(y_train)
# convert test data
_X_test = torch.LongTensor(X_test)... | 0d40fe19c977b25e3a2571adc98790d7058a77d9 | 18,802 |
def api_auth(func):
"""
If the user is not logged in, this decorator looks for basic HTTP auth
data in the request header.
"""
@wraps(func)
def _decorator(request, *args, **kwargs):
authentication = APIAuthentication(request)
if authentication.authenticate():
return ... | 624c997dae9da9b698b1dccbd5293027d54d0fc8 | 18,803 |
def object_miou(y_true, y_pred, num_classes=cfg.num_classes):
"""
衡量图中目标的iou
:param y_true: 标签
:param y_pred: 预测
:param num_classes: 分类数量
:return: miou
"""
confusion_matrix = get_confusion_matrix(y_true, y_pred, num_classes)
# Intersection = TP Union = TP + FP + FN
# IoU = TP / ... | 1051fe488fb4b16760bb256265d11b33aa613743 | 18,804 |
import datetime
def post_discussion(title: str, content: str, path: str, top: bool, private: bool = False):
"""
发送讨论
参数:
title:str 讨论题目
content:str 内容
path:str 路径
top:bool 是否置顶
返回
{
"code":-1,//是否成功执行
"discussion_id":"成功执行时的讨论ID",
"message":"错误信息"
}
... | b633da456a8ca05d592efb3e1dd16c8a7a465e23 | 18,805 |
from operator import and_
def _get_fields_usage_data(session):
"""
Obtaining metrics of field usage in lingvodoc,
the metrics are quantity of all/deleted dictionary perspectives using this field
(also with URLs) and quantity of lexical entries in such dictionary perspectives
Result:
dict ... | d57fb6fd0c07e22ac62ba63e5ba5b72189481aed | 18,807 |
def test_merge_batch_grad_transforms_same_key_same_trafo():
"""Test merging multiple ``BatchGradTransforms`` with same key and same trafo."""
def func(t):
return t
bgt1 = BatchGradTransformsHook({"x": func})
bgt2 = BatchGradTransformsHook({"x": func})
merged = Cockpit._merge_batch_grad_tr... | 10aade423092d39e6a7d754c0ceecfdb53226b53 | 18,809 |
import atexit
import time
def main(selected_ssids, sample_interval, no_header, args=None):
"""
Repeatedly check internet connection status (connected or disconnected) for given WiFi SSIDs.
Output is writen as .csv to stdout.
"""
wireless_connections = [
c for c in NetworkManager.Settings.... | f47e13bdb994e450b8bb77e26e0da3d25014032f | 18,810 |
def getNarrowBandULAMIMOChannel(azimuths_tx, azimuths_rx, p_gainsdB, number_Tx_antennas, number_Rx_antennas,
normalizedAntDistance=0.5, angleWithArrayNormal=0, pathPhases=None):
"""This .m file uses ULAs at both TX and RX.
- assumes one beam per antenna element
the first co... | bb201abaca60e2855e86a41d9c581599b9ab0c22 | 18,811 |
def get_pybricks_reset_vector():
"""Gets the boot vector of the pybricks firmware."""
# Extract reset vector from dual boot firmware.
with open("_pybricks/firmware-dual-boot-base.bin", "rb") as pybricks_bin_file:
pybricks_bin_file.seek(4)
return pybricks_bin_file.read(4) | 7d504e7e6e6ca444932fd61abb701a010a259254 | 18,812 |
def nSideCurve(sides=6, radius=1.0):
"""
nSideCurve( sides=6, radius=1.0 )
Create n-sided curve
Parameters:
sides - number of sides
(type=int)
radius - radius
(type=float)
Returns:
a list with lists of x,y,z coordinates fo... | d64668ae2fdbd2dc06b36fb2523e09a8cc380d6f | 18,813 |
def _get_corr_mat(corr_transform, n_dim):
""" Input check for the arguments passed to DirectionalSimulator"""
if corr_transform is None:
return np.eye(n_dim)
if not isinstance(corr_transform, np.ndarray) or corr_transform.ndim < 2:
err_msg = "corr_transform must be a 2-D numpy array"
... | 94909cc43322e8eebf14942cd39817d10bd744fa | 18,814 |
def get_flowline_routing(NHDPlus_paths=None, PlusFlow=None, mask=None,
mask_crs=None, nhdplus_crs=4269):
"""Read a collection of NHDPlus version 2 PlusFlow (routing)
tables from one or more drainage basins and consolidate into a
single pandas DataFrame, returning the `FROMCOMID` an... | c79d943b35f236f9d2bddbc6c9e2f470ac6ba0fc | 18,815 |
from typing import Callable
from typing import Optional
from datetime import datetime
import pytz
def df_wxyz(
time_slot_sensor: Sensor, test_source_a: BeliefSource, test_source_b: BeliefSource
) -> Callable[[int, int, int, int, Optional[datetime]], BeliefsDataFrame]:
"""Convenient BeliefsDataFrame to run tes... | 64928090a7fa58cc1f6a6e4928025c426c17e799 | 18,816 |
def not_posted(child, conn) -> bool:
"""Check if a post has been already tooted."""
child_data = child["data"]
child_id = child_data["id"]
last_posts = fetch_last_posts(conn)
return child_id not in last_posts | 5be321bf838a22cfcd742c0ddf48eb00ec1e35bf | 18,817 |
def parse_img_name(path):
"""parse image by frame name
:param name [str]
:output img_lists
"""
code = path.split('\\')[-1].split('.')[0]
vid_id = path.split('\\')[-2]
rcp_id = path.split('\\')[-3]
seg_id = int(code[:4])
frm_id = int(code[4:])
return rcp_id, vid_id, seg_id, frm_id | 6e0a140934c584400365f12feb8a86cfea3bbb2b | 18,818 |
def get_bspline_kernel(x, channels, transpose=False, dtype=tf.float32, order=4):
"""Creates a 5x5x5 b-spline kernel.
Args:
num_channels: The number of channels of the image to filter.
dtype: The type of an element in the kernel.
Returns:
A tensor of shape `[5, 5, 5, num_channels, num_channels]`.
"""... | 1696e3a9077c672becda474de98750f45d1fe3d4 | 18,819 |
from .protocols import Stock_solution,MonoDispensing_type1,MonoDispensing_type2,MultiBase,SMTransfer,ReactionQC,QCSolubilise,DMATransfer,\
def gen_prot_dict():
"""
:param input_list:
:return:
"""
PostWorkupTransfer,Workup,PostWorkupQCAndTransfer,PostWorkupDMSOAddition,BaseT3PMulti, PoisedReact... | 64c4c88f684297ea7e658015d225481005315527 | 18,820 |
def f(x):
"""
예측해야 하는 함수입니다.
"""
return np.matmul(x * np.absolute(np.sin(x)), np.array([[2], [1]])) | 228e8f431f7c071ad1587b76c73495296e1331f3 | 18,821 |
def create_frame_coords_list(coords_path):
"""
:param coords_path: [int]
:type coords_path: list
:return: int, [int]
:rtype: tuple
"""
id_number = coords_path[0]
fr_coordinates = [None]*int((len(coords_path) - 1) / 3) # excluding the index 0 (which is the id) the number of triples ... | ca835c04b67789903a74e6882434c570f33647ab | 18,822 |
def arcToolReport(function=None, arcToolMessageBool=False, arcProgressorBool=False):
"""This decorator function is designed to be used as a wrapper with other GIS functions to enable basic try and except
reporting (if function fails it will report the name of the function that failed and its arguments. If a re... | 673dd42bd96a0f5aede5ca0593efaa02d630e2e5 | 18,824 |
def check_for_pattern(input_string):
""" Check a string for a recurring pattern. If no pattern,
return False. If pattern present, return smallest integer
length of pattern.
Warning: equal_divisions discards the remainder, so if it doesn't
fit the pattern, you will get a false postive... | 6d6e32c7228ef3cec4107a3354fe53b90ef69e04 | 18,825 |
import logging
def get_xml_namespace(file_name,pkg_type):
"""Get xml's namespace.
Args:
file_name: The path of xml file.
Returns:
xml_namespace: The namespace of xml.
for example:
xml file content:
...
<config xmlns="urn:ietf:params:xml:n... | 401bf5c321b5626d7b7171e2270df04863a01d61 | 18,826 |
def build_successors_table(tokens):
"""Return a dictionary: keys are words; values are lists of
successors.
>>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.']
>>> table = build_successors_table(text)
>>> sorted(table)
[',', '.', 'We', 'an... | 92206bf3dd40518c23c6fb98e22dc818912c5bcc | 18,827 |
import math
def _rolling_nanmin_1d(a, w=None):
"""
Compute the rolling min for 1-D while ignoring NaNs.
This essentially replaces:
`np.nanmin(rolling_window(T[..., start:stop], m), axis=T.ndim)`
Parameters
----------
a : numpy.ndarray
The input array
w : numpy.ndarray, ... | 37229440ba632d1ddadc55a811f9abca1c8e3132 | 18,828 |
def get_model_init_fn(train_logdir,
tf_initial_checkpoint,
initialize_last_layer,
last_layers,
ignore_missing_vars=False):
"""Gets the function initializing model variables from a checkpoint.
Args:
train_logdir: Log direc... | 7fdd1bcff59fc01dff2f1ef49eda4bd29b162ea2 | 18,829 |
import time
def tokenize_protein(text):
"""
Tokenizes from a proteins string into a list of strings
"""
aa = ['A','C','D','E','F','G','H','I','K','L',
'M','N','P','Q','R','S','T','V','W','Y']
N = len(text)
n = len(aa)
i=0
seq = list()
timeout = time.time()+5
for i... | 7dba531023aef97dcbfb37af75a9a1459a1e94d2 | 18,830 |
from typing import Callable
def read_xml_string() -> Callable[[int, int, str], str]:
"""Read an XML file to a string. Subsection string needs to include a prepending '-'."""
def _read_xml_string(number: int, year: int, subsection: str) -> str:
xmlfile = f"tests/data/xmls/session-{number:03}-{year}{su... | 2b4e4c3585e26138e5fecf820699e97e1011a842 | 18,831 |
def compute_mean_std_data(filelist):
"""
Compute mean and standard deviation of a dataset.
:param filelist: list of str
:return: tuple of floats
"""
tensor_list = []
for file in filelist:
img = Image.open(file)
img_np = np.array(img).ravel()
tensor_list.append(img_np.... | 57c8d5e9294e291e9897ac0e865a661319123965 | 18,832 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.