content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def sharpe_ratio(r, rf_rate, periods_per_year):
"""
Computes annualized sharpe ratio of a set of returns
"""
rf_per_period = (1 + rf_rate) ** (1 / periods_per_year) - 1
excess_return = r - rf_per_period
ann_excess_return = annualize_ret(excess_return, periods_per_year)
ann_vol = annualize_vo... | 59fd6f6ca1b76fcd35380ec2005272777f5b85a9 | 69,100 |
def NetInvIncTax(e00300, e00600, e02000, e26270, c01000,
c00100, NIIT_thd, MARS, NIIT_PT_taxed, NIIT_rt, niit):
"""
Computes Net Investment Income Tax (NIIT) amount assuming that
all annuity income is excluded from net investment income.
"""
modAGI = c00100 # no foreign earned inco... | 992946090d5894042f2e0909a325ea3225c8a49f | 69,101 |
def merge_dicts(*dict_args):
""" Efficiently merges arbitrary number of dicts, giving precedence to latter dicts. """
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result | 9170784049bc1b70e07672301bed020f584a4a4b | 69,102 |
def make_pi_dict(**kwargs):
"""
Make a dict of pi components suitable for passing to Surface.
"""
return {
i: np.array([kwargs.get(i, 0.)])
for i in ['xx', 'yy', 'xy', 'xz', 'yz']
} | c6c2df7c758f14eb415d8fefe38ebaca6847aac8 | 69,103 |
import os
def find_card_in_img(im, debug):
"""Find position of card in the image, crop, rotate and isolate that card
:param im: (npa) image being processed
:param debug: (bool) toggles saving intermediary images for debug purposes
:return img_card_isol: (npa) image of card isolated from rest of the ... | 69befad0d2e94d5107c394bcb5cfb1ebb928e8ae | 69,104 |
import numpy
def get_COMs_celllist(cell, M):
""" Calculate Center of Mass (COM) for celllist """
Mx = M[0]
My = M[1]
Mz = M[2]
Lx = numpy.linalg.norm(cell[0, :])
Ly = numpy.linalg.norm(cell[1, :])
Lz = numpy.linalg.norm(cell[2, :])
NEW_P = []
vec_x = cell[:][0, :].copy()
n_x = ... | 329a4ef25951aea6b38fee9dc0dafb19200621a4 | 69,105 |
def lowest_cost_search(start, successors, is_goal, action_cost):
"""Return the lowest cost path, starting from start state,
and considering successors(state) => {state:action,...},
that ends in a state for which is_goal(state) is true,
where the cost of a path is the sum of action costs,
which are g... | 13ca96b3563660b7645023a0bf3be601ddd575a8 | 69,106 |
def provider_amazon_de(section):
"""Provider for Amazon
"""
try:
amazon = AmazonAPI(section['amazon_access_key'], section['amazon_secret_key'], section['amazon_assoc_tag'], region="DE")
product = amazon.lookup(ItemId=section['asin'])
return product.price_and_currency[0]
except:
return None | d9a0201f17cf925ce717038cb060f3859e7ab9ea | 69,107 |
def get_dynamic_projection_info_delay():
"""Get information about the current dynamic projection data. """
descriptor = [ {'name':'N_time_bins', 'type':'uint', 'value':None },
{'name':'N_counts', 'type':'long', 'value':None },
... | c072fe29671ddd7333735965fd2c23c7b4cc09fa | 69,108 |
def get_supported_technologies():
"""Runs 'kallisto bus --list' to fetch a list of supported technologies.
:return: list of technologies
:rtype: list
"""
p = run_executable([get_kallisto_binary_path(), 'bus', '--list'],
quiet=True,
returncode=1)
ret... | e35427a14f3b1d509bc6abf9a55848c1fbfbfb4b | 69,109 |
def get_bprop_assign_add(self):
"""Grad definition for `AssignAdd` operation."""
def bprop(x, y, out, dout):
return zeros_like(x), zeros_like(y)
return bprop | 7d1878e9d0a72883316a1bb51c57775977a90fad | 69,110 |
def break_up_sink_info(sink_info:str) -> dict:
"""Break up the info into a dictionary.
Parameters
----------
sink_info: str
The sink info from pulsemixer.
Returns
-------
dict
A dictionary of sink information.
"""
pieces = sink_info.split(",")
if "\t" in pieces[... | 790c757500528af28a6a01bc0cea2b7772d2ea55 | 69,111 |
import subprocess
def convert_mp3_to_wav_ffmpeg_bytes2bytes(input_data: bytes) -> bytes:
"""
It converts mp3 to wav using ffmpeg
:param input_data: bytes object of a mp3 file
:return: A bytes object of a wav file.
"""
# print('convert_mp3_to_wav_ffmpeg_bytes2bytes')
args = (ffmpeg
... | 0ac836d9cd30ef2322590fcdeb3a700801da321b | 69,112 |
def project_content_url(project, **kwargs):
"""
Get the URL for a file path within a project.
This can significantly reduce the number of queries instead
of fetching the project and account for every file in a list
which happens when using `{{ file.download_url }}`.
"""
return project.conte... | 91a6a927b3fa88f4b9e976093965a1176657532e | 69,113 |
def mavlink_latlon(degrees):
"""Converts a MAVLink packet lat/lon degree format to decimal degrees."""
return float(degrees) / 1e7 | 20d883e45f99cca3c99eeb9d7c5fae96db03fd5a | 69,114 |
from typing import Union
import os
from typing import Any
def read_saved_model(path: Union[str, os.PathLike]) -> Any:
"""Reads a SavedModel from `path`."""
py_typecheck.check_type(path, (str, os.PathLike))
if isinstance(path, os.PathLike):
path = os.fspath(path)
module = tf.saved_model.load(path)
retur... | 37baa2d5fdce11ff8238709762cd96b87db9c1ba | 69,115 |
def get_pym_string_single(source):
"""get_pym_string_single(source) -> python_code_string
Translate MATLAB single statement string into a functionally equivalent
Python compatible statement that relies on features of OMPClib's mobject.
This string can be further passed to Python's built-in compile... | 4670fac6f0b58f833c559c9b25965297dc59cba0 | 69,116 |
def getQLClothInMesh(target):
"""
Get the input mesh of a Qualoth cloth object.
:param target: `PyNode` qualoth cloth object (inmesh, qlClothShape, outmesh)
:return: `PyNode`
"""
clothNode = getQLClothNode(target)
if not clothNode: return None
qlConverter = clothNode.inputGeometry.conne... | 76dfb9a5d6eadcda5d53b31709997d02241998dd | 69,117 |
def decode_token(token):
"""
Top-level method to decode a JWT.
Takes either a compact-encoded JWT with a single signature,
or a multi-sig JWT in the JSON-serialized format.
Returns the deserialized token, as a dict.
The signatures will still be base64-encoded
"""
if isinstance(token, (u... | 1100dbfc970cf394a34ee127b362f3e994d60ba7 | 69,118 |
def load_smart_meters(cursor=None, schema: str = "public", name: str = "smart_meters"):
"""
---------------------------------------------------------------------------
Ingests the smart meters dataset into the Vertica database. This dataset is ideal
for time series and regression models. If a table with the same na... | 3cdb7f82bd6100cb2c5803bde27ba091c5935e05 | 69,119 |
import os
def isValidVideoFolder(path):
"""A valid video folder must have \\groundtruth, \\input, ROI.bmp, temporalROI.txt"""
# Second check for folders with RGB / thermal
isValid = os.path.exists(os.path.join(path, 'groundtruth')) and os.path.exists(os.path.join(path, 'input')) and os.path.exists(os... | 012840715cfadbd0f9e48a0ea494b9507335fbd7 | 69,120 |
def is_whitespace(c):
"""
static boolean isWhitespace(int codepoint)
"""
# try to hit the most common ASCII ones first, then the nonbreaking
# spaces that Java brokenly leaves out of isWhitespace.
# u202F is the BOM, see
# http://www.unicode.org/faq/utf_bom.html#BOM
# we just accept it... | f2160386120da49cb42eb0cefd80a65a2345832b | 69,121 |
def vertical(samples, classes):
"""
Return vertcial array of shape (samples, classes).
"""
X = np.zeros((samples*classes, 2))
y = np.zeros(samples*classes, dtype='uint8')
for class_number in range(classes):
ix = range(samples*class_number, samples*(class_number+1))
X[ix] = np.c_[... | be70fecd50b3b866902373040107f3c020d0b4a6 | 69,122 |
import itertools
def _merge_dicts(first, second):
"""Merge two dicts into a new one
Args:
first (dict): Primary dict; if a key is present in both, the value from this
dict is used.
second (dict): Other dict to merge.
Returns:
dict: Union of provided dicts, with value fr... | 85b3377d25d730b32c9bf925bfde375db5c49450 | 69,123 |
def bbox2result(bboxes, labels, num_classes):
"""Convert detection results to a list of numpy arrays.
Args:
bboxes (Tensor): shape (n, 5)
labels (Tensor): shape (n, )
num_classes (int): class number, including background class
Returns:
list(ndarray): bbox results of each cl... | cdee80469e8af546e105d7cfb9e1b70267dbe560 | 69,124 |
def compare_inputs(in1, in2, shape, hist_len):
"""
Return a matplotlib image with the inputs as 2 rows
of `hist_len` images side-by-side
"""
images1, images2 = [], []
img_size = np.prod(shape)
for i in range(hist_len):
images1.append(in1[img_size*i:img_size*(i+1)].reshape(shape))
... | 90dbf8ab603eb26abce8b936ade9d85781876fce | 69,125 |
def create_clidriver():
""" CLIDriver Builder.
:rtype: CLIDriver
:return: CLIDriver instance.
"""
return CLIDriver() | d1b51f284be7e4a0617dbdbb592cfbf708124bfc | 69,126 |
def loadFoil(file_profile="/home/paul/CAD/foil/H105Coord.dat",
file_LeadTrail="/home/paul/CAD/foil/test.sweepPath"):
"""
Load a foil profile (section) from file_profile and leading and trailing edges
from file_LeadTrail. The leading edge defines the sweep path (trajectory).
The leading and trai... | 56a538bf3c59111ac746e622c670663f193e520f | 69,127 |
def create_covg_table(fname, table_data):
"""Add average CpG depth table to document."""
samps = sorted(
list(constants.SAMPLE_NAMES.keys()),
key=lambda d: constants.INTERLEAVE_ORDER[d],
reverse=False
)
data = format_covg_data(table_data)
with open(fname, 'a') as f:
... | 489559cd80fa8b2c731e9d49a26d693f345b92d9 | 69,128 |
def perform_plot(strain1, strain2, txtome):
"""
Plot the STP between two strains.
Params:
-------
strain1, strain2: str
Strains to plot
txtome: txtome
A transcriptome object that contains the data to plot.
Output:
-------
... | 90278169196d3ffadfa8aa2b837587c243612626 | 69,129 |
def _cosine_similarity(x, y, eps):
"""cosine similarity between two tensors"""
dotxy = jnp.sum(x * y, axis=1)
normx = jnp.linalg.norm(x, axis=1)
normy = jnp.linalg.norm(y, axis=1)
return jnp.abs(dotxy) / jnp.maximum(eps, normx * normy) | 12b93561df009c8320daaed42aff409ca646acd5 | 69,130 |
import os
def mol_validate_file_object(path_file):
"""
Validate a MDStudio path_file object
- Check if 'content' is a InChI or SMILES string and set extension
(mol_format)
- If no 'content' check if path exists
:param path_file: path_file object
:type path_file: :py:dict
:return:... | 2249376d14e52981801edd0390b4e5ee0d5314be | 69,131 |
def oidc_auth(account, issuer, ui_vo=None):
"""
# TODO: Validate for Flask
Open ID Connect Login
:param account: Rucio account string
:param issuer: issuer key (e.g. xdc, wlcg) as in the idpsecrets.json file
:param ui_vo: 3 character string to identify the VO, if None will attempt to deduce it f... | a67a5a669c36ee6fb9b7d131e5ff1763d17ed173 | 69,132 |
def build_df_per_id(trajectories):
"""Build one dataframe per id
Arguments:
trajectories: Dict mapping each id to a list of tuple (x,y,frame)
Returns:
df_per_id: dict mapping each id to a dataframe with its trajectory
Raises:
"""
df_per_id = {}
full_trajectories = add_nan_tra... | c27534b6a8b6b8e7a81015bc42cbc0279346f820 | 69,133 |
def int64_feature(values):
"""Returns a TF-Feature of int64s.
Args:
values: A scalar or list of values.
Returns:
A TF-Feature.
"""
if not isinstance(values, (tuple, list)):
values = [values]
return tf.train.Feature(int64_list=tf.train.Int64List(value=values)) | 01378bf614f3d289f2511c755f505bbaa8a99f1c | 69,134 |
def mul(mean1, var1, mean2, var2):
"""
Multiply Gaussian (mean1, var1) with (mean2, var2) and return the
results as a tuple (mean, var).
Strictly speaking the product of two Gaussian PDFs is a Gaussian
function, not Gaussian PDF. It is, however, proportional to a Gaussian
PDF, so it is safe to ... | 71844426a2b9f1d7466d85d8c6c1d2037626c7f5 | 69,135 |
def load_item(item_id: int):
"""
Load an item from item_template, convert it to a object of Class Item and return it
"""
if item_id <= 0 or not isinstance(item_id, int):
raise Exception("There is no such item with an ID that's 0 or negative!")
item_template_info: ItemTemplateSchema = sessio... | 0d31e007cf3bfed7f98c480bdef778350e461087 | 69,136 |
def revokeCloseBankAccount(request):
"""
정액제 해지신청을 취소합니다.
"""
try:
# 팝빌회원 사업자번호
CorpNum = settings.testCorpNum
# 팝빌회원 아이디
UserID = settings.testUserID
# [필수] 기관코드
# 산업은행-0002 / 기업은행-0003 / 국민은행-0004 /수협은행-0007 / 농협은행-0011 / 우리은행-0020
# SC은행-0023 ... | fb7cbdf564a3705776a9d81dc4b39a5ff2a8619e | 69,137 |
def download_post(client: Instaloader, post: Post) -> bool:
""" Downloads content and returns True """
client.download_post(post, post.owner_username)
return True | a3bfc7dd6344e2d31266ee2f113f245984c0dd5d | 69,138 |
def json_dumper(obj):
"""
Dumps generic objects to JSON. Useful to serialize ENV_CONFIG.
"""
# extra hacky, but works
try:
return obj.toJSON()
except:
try:
return obj.__dict__
except:
return str(obj) | 31d7ddcebb16bf437a18aa5584383f7ca5c83aed | 69,139 |
from typing import Counter
def apply_rules(
candidates: "list[Commit]",
advisory_record: AdvisoryRecord,
active_rules=["ALL"],
) -> "list[Commit]":
"""
This applies a set of hand-crafted rules and returns a dict in the following form:
commits_ruled[candidate] = ["explanation"]
where 'exp... | 2b11cbda939bfeab4b904b20c7d830f0e0f0d949 | 69,140 |
def get_paired_bams(align_bams, items):
"""Split aligned bams into tumor / normal pairs if this is a paired analysis.
Allows cases with only tumor BAMs to handle callers that can work without
normal BAMs or with normal VCF panels.
"""
tumor_bam, tumor_name, normal_bam, normal_name, normal_panel, tum... | 434d6c951d3e29d02d1bb1b0b594f7002e465775 | 69,141 |
def macroexpand(tree, module_name):
"""Expand the toplevel macros for the `tree`.
Load the macros from the given `module_name`, then expand the (top-level)
macros in `tree` until it stops changing.
"""
load_macros(module_name)
old = None
while old != tree:
old = tree
tree =... | e9954ddb5df6298532bdfd2861d20d43e24a4bbc | 69,142 |
import argparse
def arg_processor():
"""
Generate an argument parser for command line argument processing.
The help menu is generated automatically.
"""
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(
title='subcommands',
description='valid subcommands... | 46d98fec6c66b8016786b131adfec8b3db4ffab7 | 69,143 |
def create_dimensions():
"""
This Function that will create all the dimensions for stroopwafel, a dimension is basically one of the variables you want to sample
Invoke the Dimension class to create objects for each variable. Look at the Dimension class definition in classes.py for more.
It takes the nam... | b7ad49793b1251489c8c066f8bc1b316343411b5 | 69,144 |
from typing import Tuple
from typing import Optional
def parse_trailing_comment(line: str) -> Tuple[str, Optional[str]]:
"""Split the line and return the extracted trailing comment."""
chunks = REGEX_QUOTE.split(line)
result = ""
while chunks:
text, *comment = REGEX_COMMENT.split(chunks.pop(0... | 339cc320d9242bcc2e0a0d929d51083059570716 | 69,145 |
from typing import List
import re
def get_dic(data)->List[float]:
""" """
new_data = [0,0,0,0]
for key, item in data.items():
if re.match(r"\b(elevation)\b", str(key), re.IGNORECASE):
new_data[0] = item.value
elif re.match(r"\b(thickness)\b", str(key), re.IGNORECASE):
... | 8d8adab78e739e364b7726f78a49403f5c9ae34a | 69,146 |
def make_header(in_files,args):
"""Make sam header given input file species and"""
#parse input barcode file and make list of individuals
in_files['header'] = 'location of header'
return in_files | 8a4a222391a462d0d6187080ed2eccc631526513 | 69,147 |
def accuracy(actual_y: list, predicted_y: list) -> float:
"""
Calculate the value of accuracy based-on predictions
:param actual_y:a list containing initial Y values generated by 'y_generator'
function
:param predicted_y: a list containing predicted Y values generated by
'predict_y_value... | 7082d0e5505fc58e9ba80883b63bec98f4632676 | 69,148 |
def send_messages(queue, messages):
"""
Send a batch of messages in a single request to an SQS queue.
This request may return overall success even when some messages were not sent.
The caller must inspect the Successful and Failed lists in the response and
resend any failed messages.
Usage is s... | 806bd30fb5efc9fef226ddb6c2d46ffe33402cbb | 69,149 |
def get_graph(network_data, vocab):
""" Build graph, treat all nodes as the same type
Parameters
----------
network_data: a dict
keys describing the edge types, values representing edges
vocab: a dict
mapping node IDs to node indices
Output
------
DGLHeteroGraph
... | b3bb88a8d7d3b3d102a38fec41bb57d3e9d45e73 | 69,150 |
def dict2columns(data, id_col=None):
"""Convert a dict-based object to two-column output.
Also make sure the id field is at top.
"""
if not data:
return ({}, {})
else:
if id_col is not None and id_col in data:
keys = [id_col]
[keys.append(key) for key in sort... | 24917339d53febc4239e21ebb8b39e487f45a370 | 69,151 |
def insertTimer (signal, type):
"""
- param signal a plugged input signal.
- return an Timer entity.
"""
assert signal.isPlugged()
Timer = getTimerType (type)
timer = Timer ("timer_of_" + signal.name)
other = signal.getPlugged()
plug(other, timer.sin)
plug(timer.sout, signal)
... | 3f1671647ac7842fd32e0b1b107069371f4e4cdd | 69,152 |
def resolve_int_list_arg(arg):
"""Resolve a CLI argument as a list of integers"""
if arg is None:
return None
if isinstance(arg, int):
return [arg]
if isinstance(arg, str):
return [int(arg)]
if isinstance(arg, tuple):
# Interpret as range (ignore any other items in tu... | 5201d191946c69e10253e476341ab70c76b3a67d | 69,153 |
from pathlib import Path
def create_planar_paths_cgal(mesh, planes):
"""Creates planar contours using CGAL
Considers all resulting paths as CLOSED paths.
This is a very fast method.
Parameters
----------
mesh: :class: 'compas.datastructures.Mesh'
A compas mesh.
planes: list, :clas... | c318afd46e1edb7b5da10f26190fe66f27220e04 | 69,154 |
def divide_by_two(a):
"""Return a / 2.
"""
return a / 2.0 | f7c71a468f91892d327d7e9745934f6f4760deeb | 69,155 |
import csv
def read_ensembl_genes(fpath, source, name):
"""
:param fpath:
:param source: content of ensemblSource file; contains transcript type info, e.g., protein coding
:param name: content of ensemblToGeneName file; contains gene symbol/name info
:return:
"""
fieldnames = ['bin', 'name... | 820bbb02dec86da382137ad7eddb52ee596a02a6 | 69,156 |
def SystemYChanged():
"""(read-only) Flag that indicates if elements of the System Y have been changed by recent activity."""
return lib.Solution_Get_SystemYChanged() != 0 | 04195262f03ef6df39caf4f56c95fb117f0e279f | 69,157 |
def groupwise_normalise(gs):
"""
Normalises each group of GeoSeries
:param gs: GeoSeries
:return: normalised GeoSeries
"""
return gs.groupby(level=0).apply(lambda x: x / x.sum()) | e0c87701658481ccea01828c75244b7a1043ee29 | 69,158 |
def dnn_batch_normalization_train(inputs, gamma, beta, mode='per-activation',
epsilon=1e-4, running_average_factor=0.1,
running_mean=None, running_var=None):
"""
Performs batch normalization of the given inputs, using the mean and
variance ... | 853f5a2c130ff4aa6b319b40a456817d982a2332 | 69,159 |
import os
def is_enabled():
"""Check if infiniband is loaded on the system"""
return os.path.exists(ABI_VERSION_FILE) | f5c9ba12f4eb9c43ff33ca272525958fc92e3b23 | 69,160 |
from typing import Dict
def component_io_to_rest_obj(io_dict: Dict):
"""Component inputs/outputs entity to rest object."""
rest_component_io = {}
for name, port in io_dict.items():
rest_component_io[name] = port._to_rest_object()
return rest_component_io | 03c3b5fc0033c3488a1190db89e8361483fc765d | 69,161 |
def delta(net: ann.NeuralNetwork,
sample: Sample,
error_function_deriv: List[Mapping[Tuple(Sample,
ann.NeuralNetwork
),
float]
... | 3f8b411750f7b3266eaaef814e21eaba36cf68ec | 69,162 |
def PolynomialJac(mu, *u):
"""The derivative matrix of the polynomial model."""
jac = -np.array([(1 - mu) ** (l + 1) for l in range(len(u))]).transpose()
return jac | 495dd55004b8014ef7ee2499ba79188eaee48707 | 69,163 |
import struct
def b58decode(v, length=None):
""" decode v into a string of len bytes."""
if isinstance(v, bytes):
v = v.decode()
for c in v:
if c not in __b58chars:
raise ValueError("invalid Base58 string")
long_value = 0
for (i, c) in enumerate(v[::-1]):
long... | 496b70440346b4545371b9293ff50e7c1e05300d | 69,164 |
def transformRemoveXmlTagsC14NId():
"""
The 'remove xml tags' transform id (used before base64 transforms)
(http://www.w3.org/TR/xmldsig-core/sec-Base-64).
Returns : 'remove xml tags' transform id.
"""
return TransformId(_obj=xmlsecmod.transformRemoveXmlTagsC14NId()) | 856dd18d4e04e3b9e94d911a02f564b3561dccf1 | 69,165 |
def correlation(season, metric, n, connection, generalize=False, traditional=False,
mixed=False, playoffs=False, multiple=False, partitioned=False,
evaluation_start=None, evaluation_end=None):
"""
Calculate the correlation coefficients (Pearson/Spearman) for a specific
numbe... | ca31974b6ec8e78b300afe0bf58931b358b01f18 | 69,166 |
import matplotlib.pyplot as plt
from .network import Network
from matplotlib.ticker import ScalarFormatter
def plot_cell_connectivity(net, conn_idx, src_gid=None, axes=None,
colorbar=True, colormap='viridis', show=True):
"""Plot synaptic weight of connections.
This is an interactiv... | 798d824095fd8008d0bf178c0800bfa41ac9cb61 | 69,167 |
def generate_wrapper(config):
"""
Generates a wrapper script for the format.
:param config: The configuration for the format
"""
return "#!/bin/sh\n%s" % config['interpreter'] | 694ecb3369de8ab4af4c57418c732d39ed57aceb | 69,168 |
import itertools
def string_between(left, right, subject, *args, **kwargs):
"""
string_between(left, right, subject, [,start [,end]] [,greedy=False] [,inclusive=False] [,repl=None] [,retn_all_on_fail=False] [,retn_class=False] [,rightmost=False]) -> str
Return the substring sub delineated by being betwe... | 8f80f15b27fe8dfde0afcbb6aa85d55250fd13ae | 69,169 |
def logout(request):
"""
Return logout page
"""
django_logout(request)
print("Logging out")
return redirect('/') | 923ded3599a435d9a782afdbf43d66f4b4b44a02 | 69,170 |
def tgram_to_bundles(tgram, bundle_dict, reference):
"""
Convert a StatefulTractogram object to a dict with StatefulTractogram
objects for each bundle.
Parameters
----------
tgram : StatefulTractogram class instance.
Requires a data_per_streamline['bundle'][bundle_name]['uid'] attribute... | 9d9595a90a6103641e2acfe551c8d95f001bf5d6 | 69,171 |
def params_to_dict(params):
"""
Converts the parameters of a mwparserfromhell template to a dictionary
"""
dct = {}
for param in params:
dct[param.name.strip()] = param.value.strip()
return dct | 0799a22627b1f09e684d2b506f69eabcc942ec2f | 69,172 |
import fastapi
async def delete_feed(
*,
db: sa.orm.Session = params.Depends(deps.get_db),
id: int,
):
"""
Delete RSS feed.
"""
obj = crud.rss_feed.get(db, id=id)
if obj is None:
raise fastapi.HTTPException(404, detail="RSS Feed not found")
return crud.rss_feed.remove(db, i... | b893b3d48db0476e1ac2f8c0c04a7705027cf2e2 | 69,173 |
def filter_definition_names(names, origin, position=None):
"""
Filter names that are actual definitions in a scope. Names that are just
used will be ignored.
"""
# Just calculate the scope from the first
stmt = names[0].get_definition()
scope = stmt.get_parent_scope()
if not (isinstance... | 14ef64d3df898e1b64890c54252d64079e2b478e | 69,174 |
def new_deconstruct(self):
"""Patches makemigration's logic to ignore fields that are not of relevance to our database.
This avoids unnecessary, annoying migrations whenever a frontend facing string is changed."""
name, path, args, kwargs = original_deconstruct(self)
for attr in IGNORED_ATTRS:
... | 71965fe02b032f31574f42787c8a5f6398540945 | 69,175 |
def render_network_key(ssid, address):
"""ssid:address"""
return ssid + ':' + address | daf47616c455c3b542688293195f45607fb8b7ea | 69,176 |
from typing import Callable
def percentage_income_contributions(
income: float,
contribution_rate: float,
income_growth: float = 0.0,
tax_function: Callable[[float], float] = (lambda x: 0),
) -> Callable[[int], float]:
"""
Creates a function that returns a contribution based on a percentage of... | a122d7d4afa95f3be799e0913ddd127e761fe6ca | 69,177 |
import math
def scattering_filter_factory(N, J_support, J_scattering, Q, T,
r_psi=math.sqrt(0.5), criterion_amplitude=1e-3,
normalize='l1', max_subsampling=None, sigma0=0.1,
alpha=4., P_max=5, eps=1e-7, **kwargs):
"""
Bu... | cbf0c3533037822f24a42c2e27f31263e94dfe72 | 69,178 |
import os
import requests
def requests_get(*args, **kwargs):
"""Wrap request get method.
Disabling SSL certificate validation if ``DONT_VERIFY_SSL`` environment
variable is found. This is useful when Deadline or Muster server are
running with self-signed certificates and their certificate is not
... | 7b266d77c08c161ba609a6d398d2f675718ccc00 | 69,179 |
def get_response(zone_key, url, session=None):
"""Get response"""
ses = session or Session()
response = ses.get(url)
if response.status_code != 200:
raise ParserException(zone_key, 'Response code: {0}'.format(response.status_code))
return response | d44b2f9e78e37acd0ed17b0864e8f989e57d0171 | 69,180 |
def make_one_shot_iterator(dataset):
"""Returns a dataset's one-shot iterator."""
try:
return v1.data.make_one_shot_iterator(dataset)
except AttributeError:
return dataset.make_one_shot_iterator() | b1d55a21af7f031a2f4f09b4fcdca38167dd0add | 69,181 |
def checkPossibility(nums):
"""
:param nums:
:return:
"""
modified = False
size = len(nums)
for i in range(len(nums)-1):
if nums[i] > nums[i + 1]:
if modified:
return False
"""
i-1 i i+1
1 2 3 ... | 83b5205ad3009b09d6f90a69c1e4a702cc17b6d0 | 69,182 |
from typing import Iterable
from typing import Any
from typing import List
def serialize_list(items: Iterable[Any]) -> List[Any]:
"""Serializes UFP data list"""
new_items: List[Any] = []
for item in items:
new_items.append(serialize_unifi_obj(item))
return new_items | ea24ffca17d7475938cf0400e68a890b4e6bcf4b | 69,183 |
def generic_scalar_product(b1, b2=None, scalar_product=None):
"""
Calculates the pairwise scalar product between the elements
of the :py:class:`.ApproximationBase` *b1* and *b2*.
Args:
b1 (:py:class:`.ApproximationBase`): first basis
b2 (:py:class:`.ApproximationBase`): second basis, if... | 40b9ba0cd785959090f1d70fca489afcfcd6dcde | 69,184 |
from typing import Dict
import random
def create_a_negative_example(assignment_and_columns) -> Dict:
"""
Given an extracted variable, create a negative example from it
:param assignment:
:return:
"""
assignment, columns_to_keep = assignment_and_columns
negative_example = dict(assignment) ... | 6382ee8d8fb79f8d256b08bd277ddfd910239bc2 | 69,185 |
def rename(src, dst):
""" Calls gfs_rename."""
p0 = abst_path(src)
s0 = str(p0).encode(name_coding)
p1 = abst_path(dst)
s1 = str(p1).encode(name_coding)
cc = _gfs_rename(s0, s1)
return cc | dd9f04573dbffb17cf8cbf952d2c85b54145b7ea | 69,186 |
def feature_extraction(df, df1, n):
"""The function performs feature extraction on the information from xyz files
Requirements:
numpy
Args:
df (pandas dataframe): Data table with spatial distribution and atom info
df1 (pandas dataframe): Data table with lattice vectors (o... | ef13a079ca454d65603b3544500638e3063b67ab | 69,187 |
def locality_sensitive_hashing(min_hash, b):
"""Locality sensitive hash to find identical pair
:param min_hash: signature matrix
:param b: number of bands to split signature matrix
:return: candidate pairs for each band
"""
all_rdd = [] # Empty list to store all rd... | cacee5c2023fd3d663c69ac0efa7546f13f355b1 | 69,188 |
def false_negative_rate(pred, target):
"""
正样本中被误判为负样本的比例,1 - recall/true_positive_rate
"""
try:
return false_negative(pred, target) / (target == 1).sum().item()
except: # divide by zero
return -1 | f02e77423a9448163fd5e12500a2a651e0084ce5 | 69,189 |
def fateman_poly_F_1(n):
"""Fateman's GCD benchmark: trivial GCD """
Y = [Symbol("y_" + str(i)) for i in range(n + 1)]
y_0, y_1 = Y[0], Y[1]
u = y_0 + Add(*[y for y in Y[1:]])
v = y_0 ** 2 + Add(*[y ** 2 for y in Y[1:]])
F = ((u + 1) * (u + 2)).as_poly(*Y)
G = ((v + 1) * (-3 * y_1 * y_0 *... | aacb38639704e7e64b8f120db662fe5789c566f4 | 69,190 |
import cgi
def safe_enter2p(s):
"""正文 换行替换"""
return '<p>' + cgi.escape(s).replace("\n", "</p><p>") + '</p>' if s else '' | 7ca789f9b12bc6cb685975f37548d43504c4d3f8 | 69,191 |
import torch
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
corre... | 76571ef880404138a16f814415a987c8ecbbe750 | 69,192 |
import json
import PIL
import io
import base64
def input_fn(request_body):
"""Pre-processes the input data from JSON to PyTorch Tensor.
Parameters
----------
request_body: dict, required
The request body submitted by the client. Expect an entry 'url' containing a URL of an image to classify.
... | 363e9a064f7f82576cab77bb40974b39ba0440be | 69,193 |
def _auto_backward(loss,
startup_program=None,
parameter_list=None,
no_grad_set=None,
callbacks=None):
"""
modification is inplaced
"""
act_no_grad_set = _get_no_grad_set(loss, no_grad_set)
assert isinstance(loss, Variable),... | 08977b52e1229eac110f9c3fa37a897bdab6c536 | 69,194 |
import typing
import uuid
import subprocess
import os
def get_png_photo(png_factor: int = 9) -> typing.Tuple[
typing.Optional[Image], typing.List[str]
]:
"""Get image from web camera.
apt-get install fswebcam
"""
img_path = f"/tmp/{uuid.uuid4().hex}.png"
result = subprocess.run(
[
... | b2281d9002e32402119df271472547b11c1685dd | 69,195 |
from typing import Optional
from typing import Callable
def count_hint(
dsid: str,
etype: ir_datasets.EntityType = ir_datasets.EntityType.docs,
metadata_provier: Optional[MetadataProvider] = None) -> Callable[[], Optional[int]]:
"""
Returns a lambda expression that provides the count from metadata... | c9d6e0f76fb302393f5ad4a6c52ab7fd1d3b76ba | 69,196 |
def lambda_handler(event, context):
""" Main Lambda function """
try:
response = PINPOINT.phone_number_validate(
NumberValidateRequest={
'PhoneNumber': MOBILE_ENDPOINT
}
)
except PINPOINT.exceptions.BadRequestException:
response_body = f"Not a ... | 0e35a1d2c319136298d9836fa83ae05756bca0ef | 69,197 |
def calc_gradient_from_gate(
c_sys: CompositeSystem,
hs: np.ndarray,
var_index: int,
is_estimation_object: bool = True,
on_para_eq_constraint: bool = True,
on_algo_eq_constraint: bool = True,
on_algo_ineq_constraint: bool = True,
mode_proj_order: str = "eq_ineq",
eps_proj_physical: f... | e5da4b971a8b8dc318b51adfc813987209a007f9 | 69,198 |
import io
def part1(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int:
"""
As a sanity check, look through your list of boarding passes. What is the
highest seat ID on a boarding pass?
"""
tickets = parse(stdin)
stderr.write(f"{tickets}\n")
max_ticket = max(seat_ids(tickets))
... | 2460a3785264ac9d9f6987a88a851f80a1b5a047 | 69,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.