content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_spectra_onepixel(data, indx, MakeMock, seed, log, ntarget,
maxiter=1, no_spectra=False, calib_only=False):
"""Wrapper function to generate spectra for all targets on a single healpixel.
Parameters
----------
data : :class:`dict`
Dictionary with all the mock data... | 4d6db87a9ee53b22e3607a364387e1792641740b | 23,300 |
def one_way_mi(df, feature_list, group_column, y_var, bins):
"""
Calculates one-way mutual information group variable and a
target variable (y) given a feature list regarding.
Parameters
----------
df : pandas DataFrame
df with features used to train model, plus a target variable
... | 2b3e8336a5843a2e4bedc4f42699c233bb2118d3 | 23,301 |
import tqdm
def draw_parametric_bs_reps_mle(
mle_fun, gen_fun, data, args=(), size=1, progress_bar=False
):
"""Draw parametric bootstrap replicates of maximum likelihood estimator.
Parameters
----------
mle_fun : function
Function with call signature mle_fun(data, *args) that computes
... | 75569e4be203fe4614f55f077c5d0abff20b468e | 23,302 |
def parse_subpalette(words):
"""Turn palette entry into a list of color-to-index mappings.
For example, #AAA=2 or #AAAAAA=2 means that (170, 170, 170) will be
recognized as color 2 in that subpalette.
If no =number is specified, indices are recognized sequentially from 1.
Return a list of ((r, g, b), index) tuple... | 13d52a4b8092755cac28401356183025dac7dfb3 | 23,303 |
import json
def data_word2vec(input_file, num_labels, word2vec_model):
"""
Create the research data tokenindex based on the word2vec model file.
Return the class _Data() (includes the data tokenindex and data labels).
Args:
input_file: The research data
num_labels: The number of class... | b5330fce3c71a62896fdfdc40a20743df0a313aa | 23,304 |
from os import scandir
from pathlib import Path
def find_version_files(
root_dir: str, dont_search_dir_names: set = {"tests", "test"}
) -> list:
"""You can use this.
This function will recursively find the __init__.py(s) in a nontest directory.
:param str root_dir: Description of parameter `root_dir... | 02db4080b5cad353d58d9c4c0790e7de4e0d4260 | 23,305 |
def object_difference():
"""Compute the difference parts between selected shapes.
- Select two objects.
Original code from HighlightDifference.FCMacro
https://github.com/FreeCAD/FreeCAD-macros/blob/master/Utility/HighlightDifference.FCMacro
Authors = 2015 Gaël Ecorchard (Galou)
"""
global v... | b99fb61e0d85cc66ae395273f785f8f7441fd297 | 23,306 |
def diffusionkernel(sigma, N=4, returnt=False):
""" diffusionkernel(sigma, N=4, returnt=False)
A discrete analog to the continuous Gaussian kernel,
as proposed by Toni Lindeberg.
N is the tail length factor (relative to sigma).
"""
# Make sure sigma is float
sigma = floa... | 3fe620454963eec357072bd0ecd64fd66b392600 | 23,307 |
def CalculateTopologicalTorsionFingerprint(mol):
"""
#################################################################
Calculate Topological Torsion Fingerprints
Usage:
result=CalculateTopologicalTorsionFingerprint(mol)
Input: mol is a molecule object.
... | 0c646ea977ea257c523425a7f8526c16f8531e14 | 23,308 |
from typing import List
from typing import Dict
def prepare_answer_extraction_samples(context: str, answer_list: List[Dict] = None):
"""
Args:
context: str (assumed to be normalized via normalize_text)
answer_list: [
{'text': str, 'answer_start': int},
{'text': str, 'an... | 3cb431fa2ec6472f3e060cb7f85eb0a52cfbfe6c | 23,309 |
from typing import Optional
from typing import Callable
from typing import List
import abc
def mix_in(
source: type,
target: type,
should_copy: Optional[Callable[[str, bool], bool]] = None,
) -> List[str]:
"""
Copy all defined functions from mixin into target. It could be
usefull when you cann... | 702552f01d4a915f11d6d3d618aaf151bf5b8af3 | 23,310 |
def get_img_num_per_cls(cifar_version, imb_factor=None):
"""
Get a list of image numbers for each class, given cifar version
Num of imgs follows emponential distribution
img max: 5000 / 500 * e^(-lambda * 0);
img min: 5000 / 500 * e^(-lambda * int(cifar_version - 1))
exp(-lambda * (int(cifar_ver... | 941be25ed96ef336e11c16bd9b81f2973c25bcf2 | 23,311 |
def xml():
"""
Returns the lti.xml file for the app.
"""
try:
return Response(render_template(
'lti.xml'), mimetype='application/xml'
)
except:
app.logger.error("Error with XML.")
return return_error('''Error with XML. Please refresh and try again. If this... | c40ffb52e4931fd41e6627778331a1c7acf9558b | 23,312 |
def log_get_level(client):
"""Get log level
Returns:
Current log level
"""
return client.call('log_get_level') | 2a3915d8c6576187a0af738d3021d495b4efda21 | 23,313 |
def cal_pivot(n_losses,network_block_num):
"""
Calculate the inserted layer for additional loss
"""
num_segments = n_losses + 1
num_block_per_segment = (network_block_num // num_segments) + 1
pivot_set = []
for i in range(num_segments - 1):
pivot_set.append(min(num_block_per_se... | d23324fc39f2f1aeec807a4d65a51234a2b76cde | 23,314 |
import asyncio
async def scan_host(
host: IPv4Address,
semaphore: asyncio.Semaphore,
timeout: int,
verbose: bool,
):
"""
Locks the "semaphore" and tries to ping "host" with timeout "timeout" s.
Prints out the result of the ping to the standard output.
"""
async with semaphore:
... | 66bd0165dbbb7b717fd6ded19c78cb901f89a588 | 23,315 |
def _emit_post_update_statements(
base_mapper, uowtransaction, cached_connections, mapper, table, update
):
"""Emit UPDATE statements corresponding to value lists collected
by _collect_post_update_commands()."""
needs_version_id = (
mapper.version_id_col is not None
and mapper.version_i... | 13444703b45030a2d0e1dc1f2371a729cd812c11 | 23,316 |
import copy
def build_grid_search_config(params_dict):
"""
传入一个json,按网格搜索的方式构造出符合条件的N个json, 目前网格搜索只作用在optimization范围内
:param params_dict:
:return: param_config_list
"""
model_params_dict = params_dict.get("model")
opt_params = model_params_dict.get("optimization", None)
if not opt_para... | a5f2b8249f9a50cad7da855d6a49a3225715fb00 | 23,317 |
def cutoff_countmin_wscore(y, scores, score_cutoff, n_cm_buckets, n_hashes):
""" Learned Count-Min (use predicted scores to identify heavy hitters)
Args:
y: true counts of each item (sorted, largest first), float - [num_items]
scores: predicted scores of each item - [num_items]
score_cut... | 99ab1b6174d49ccf4f4517fe713f98cecd65d978 | 23,318 |
def test_lcc_like_epi():
"""
Takes about 5 mins with epicyclic
If burnin is too short (say 200 steps) won't actually find true solution
"""
TORB_FUNC = trace_epicyclic_orbit
mean_now = np.array([50., -100., 25., 1.1, -7.76, 2.25])
age = 10.
mean = TORB_FUNC(mean_now, times=-age)
dx... | 43583e06741632aba41400ee1a6562cd6fc226be | 23,319 |
import numpy as np
def uniquePandasIndexMapping(inputColumn):
"""quickly mapps the unique name entries back to input entries
Keyword arguments:
inputDataToAssess -- a SINGLE column from a pandas dataframe, presumably with
duplications. Will create a frequency table and a mapping back to the sou... | c26fce9b8617963737c4b8dd05c0e8429c92daa3 | 23,320 |
def non_max_suppression(boxlist, thresh, max_output_size, scope=None):
"""Non maximum suppression.
This op greedily selects a subset of detection bounding boxes, pruning
away boxes that have high IOU (intersection over union) overlap (> thresh)
with already selected boxes. Note that this only works for a sing... | aa8990ea579ed5d4614561b617717c9e7b73f798 | 23,321 |
import inspect
import os
import json
def client_role_setting(realm, client_id):
"""クライアントロール設定 client role setting
Args:
realm (str): realm
client_id (str): client id
Returns:
[type]: [description]
"""
try:
globals.logger.debug('#' * 50)
globals.logger.deb... | bfade7a4e045b195fd00355a19c38875449d6434 | 23,322 |
def gen_weekly_ccy_df( start,end ):
""" Generate weekly ccy data table
"""
currency_li =[ "USD_Index",
"EURUSD","GBPUSD","AUDUSD","CADUSD",
"JPYUSD",
"CNYUSD","HKDUSD","TWDUSD",
"KRWUSD","THBUSD","SGDUSD","MYRUSD",
... | cf856535d148378826fd99a6d8afef5e1eb77778 | 23,323 |
def demean_and_normalise(points_a: np.ndarray,
points_b: np.ndarray):
"""
Independently centre each point cloud around 0,0,0, then normalise
both to [-1,1].
:param points_a: 1st point cloud
:type points_a: np.ndarray
:param points_b: 2nd point cloud
:type points_b: ... | 249bb8edf5ef423613748f0ce599c98e4f437960 | 23,324 |
import yaml
import six
def ParseCustomLevel(api_version):
"""Wrapper around ParseCustomLevel to accept api version."""
def VersionedParseCustomLevel(path):
"""Parse a YAML representation of custom level conditions.
Args:
path: str, path to file containing custom level expression
Returns:
... | e5e414ea29324233d4fc8291f0ea829176805d99 | 23,325 |
def specMergeMSA(*msa, **kwargs):
"""Returns an :class:`.MSA` obtained from merging parts of the sequences
of proteins present in multiple *msa* instances. Sequences are matched
based on species section of protein identifiers found in the sequence labels.
Order of sequences in the merged MSA will fol... | fdb605347bdc88df4c844fa8765640dc5a91b88d | 23,326 |
def parse(filePath):
"""
Returns a full parsed Maya ASCII file.
:type filePath: str
:rtype: mason.asciiscene.AsciiScene
"""
return asciifileparser.AsciiFileParser(filePath).scene | 2f7d50724fcda1d4ef240e362ae6ee3f18bdfacd | 23,327 |
import os
def getSpectrumFromMlinptFolder(inpFolder, fwhm, hv, angle, polarised=None, multEnergiesByMinusOne=True, database=None):
""" Description of function
Args:
inpFolder: (str) Path to folder containing *MLinpt.txt files
fwhm: (float) Full-Width at half maximum for the broadening function
hv: (float) P... | 10c8f36620cc455eb806adfa4a037cd87601dc4a | 23,328 |
import json
def extract_events_from_stream(stream_df, event_type):
""" Extracts specific event from stream.
"""
events = stream_df.loc[stream_df.EventType == event_type][['EventTime', 'Event']]
events_json = events['Event'].to_json(orient="records")
json_struct = json.loads(events_json)
# TOD... | 4b366a82c042966f01ffb37125655b30ceb67014 | 23,329 |
def d_psi(t):
"""Compute the derivative of the variable transform from Ogata 2005."""
t = np.array(t, dtype=float)
a = np.ones_like(t)
mask = t < 6
t = t[mask]
a[mask] = (np.pi * t * np.cosh(t) + np.sinh(np.pi * np.sinh(t))) / (
1.0 + np.cosh(np.pi * np.sinh(t))
)
return a | 8b0fc652a60d2ba45623bc098b7e9d0fae2c7dbe | 23,330 |
from typing import Dict
from typing import Any
import io
def build_environ(request: HTTPRequest, errors: Errors) -> Dict[str, Any]:
"""
参考 https://www.python.org/dev/peps/pep-3333/ 构建 environ
"""
headers = {
f"HTTP_{k.upper().replace('-','_')}": v for k, v in request.header.items()
}
e... | b2e98d726bf256b06d1c2f82679bd75ada7181cf | 23,331 |
def loadPage(url, filename):
"""
作用:根据url发送请求,获取服务器响应文件
url: 需要爬取的url地址
filename : 处理的文件名
"""
print "正在下载 " + filename
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"}
... | 7250a42d03bc1af7e9f30aa22198f3d4a56605f3 | 23,332 |
def get_exporter_class():
"""Returns exporter class based on preferences and support."""
if _use_xlsx() is True:
return XLSXExporter
else:
return CSVExporter | 3d66e0e0abe8c936e2f86598427ff27180dac6b4 | 23,333 |
def get_twitter_token():
"""This is used by the API to look for the auth token and secret
it should use for API calls. During the authorization handshake
a temporary set of token and secret is used, but afterwards this
function has to return the token and secret. If you don't want
to store this in... | 218f16141473e76c4318870bec9516c77f1dfe1b | 23,334 |
def is_text_serializer(serializer):
"""Checks whether a serializer generates text or binary."""
return isinstance(serializer.dumps({}), str) | f08f40662da7fd34f5984028e601d664cac943df | 23,335 |
def plot_power(ngroups, mesh_shape, directory, mode="show"):
"""Plot the integrated fission rates from OpenMC and OpenMOC, as well as
the relative and absolute error of OpenMOC relative to OpenMC.
Parameters:
-----------
ngroups: int; number of energy groups
mesh_shape: str; name of the mesh shape
di... | e9db852e840d2f3f8013f006acc191276a74e9d7 | 23,336 |
def glDeleteFramebuffersEXT( baseOperation, n, framebuffers=None ):
"""glDeleteFramebuffersEXT( framebuffers ) -> None
"""
if framebuffers is None:
framebuffers = arrays.GLuintArray.asArray( n )
n = arrays.GLuintArray.arraySize( framebuffers )
return baseOperation( n, framebuffers ) | 514fe96d8088210bfe1251a8a9c7c93856f19504 | 23,337 |
import os
import time
def projection_matching(input_model, projs, nside, dir_suffix=None, **kwargs):
"""
Parameters:
-------
input_model: path of input mrc file
projections: numpy array
"""
try:
WD = kwargs['WD']
except KeyError as error:
raise KeyError('lack working di... | 9d4eb2c85587a88970b6e3de19b6a44db7baf6a8 | 23,338 |
def backtostr(dayback=1, format="%Y/%m/%d", thedate=date.today()):
"""Print backto datetime in string format."""
return(backto(dayback=dayback, thedate=thedate).strftime(format)) | c79b10962537d9eef939e7f49697275f31e900e2 | 23,339 |
def no_conflict_require_POST(f):
"""
Catches resource conflicts on save and returns a 409 error.
Also includes require_POST decorator
"""
@require_POST
@wraps(f)
def _no_conflict(*args, **kwargs):
try:
return f(*args, **kwargs)
except ResourceConflict:
... | 98a28b5fbc2824eaa5d5020f8be1d55878974fc4 | 23,340 |
from typing import Tuple
from re import S
def _split_vector(expr, ranges, fill_ranges=True):
"""Extract the components of the given vector or matrix.
Parameters
==========
expr : Vector, DenseMatrix or list/tuple
ranges : list/tuple
Returns
=======
split_expr : tuple
... | 77f243d17b912a2ac4ad2e546e8a5f144b200e3e | 23,341 |
def Transition_rep(source_State_name, target_State_name):
"""Representation of a transition
:param source_State_name: The sequence of "name" values of State objects referred to by attribute "source" in this Transition
:type source_State_name: Array
:param target_State_name: The sequence of "name" value... | 2e5f7048722997e0931fd6ec3a2d9e880a160359 | 23,342 |
def tifread(ifile, metaData):
"""Read raster from file."""
file = gdal.Open(ifile, GA_ReadOnly)
projection = file.GetProjection()
src = osr.SpatialReference()
src.ImportFromWkt(projection)
proj = src.ExportToWkt()
Nx = file.RasterXSize
Ny = file.RasterYSize
trans = file.GetGeoTransfo... | 3f2ce1491cb982b2427108002c02bc9581580b8b | 23,343 |
from typing import List
from typing import Any
def search_model(trial: optuna.trial.Trial) -> List[Any]:
"""Search model structure from user-specified search space."""
model = []
n_stride = 0
MAX_NUM_STRIDE = 5
UPPER_STRIDE = 2 # 5(224 example): 224, 112, 56, 28, 14, 7
n_layers = trial.sugges... | 228180bc1f02c793273a763db271889f4dcd4f26 | 23,344 |
def create_search_forms(name, language_code, script_code):
"""Return a list of names suitable for searching.
Arguments:
name -- string name
language_code -- string code of language
script_code -- string code of script
"""
# QAZ: It would be useful if something could be done here (or
# ... | a417fe9ab37e544c094341fcb7f1249feaed43c6 | 23,345 |
def iv_params(*, N_s, T_degC, I_ph_A, I_rs_1_A, n_1, I_rs_2_A, n_2, R_s_Ohm, G_p_S,
minimize_scalar_bounded_options=minimize_scalar_bounded_options_default,
newton_options=newton_options_default):
"""
Compute I-V curve parameters.
Inputs (any broadcast-compatible combination of ... | 7998b52f02482d79bae6c0732e99ed5e151326fa | 23,346 |
import glob
import os
import ast
def list_class_names(dir_path):
"""
Return the mapping of class names in all files
in dir_path to their file path.
Args:
dir_path (str): absolute path of the folder.
Returns:
dict: mapping from the class names in all python files in the
fo... | 612f386330a494cfffcd4a7d2f296bf8020bae6f | 23,347 |
def update_domain(
uuid, name=None, disabled=None, project_id=None, user_id=None):
"""Update an existing domain."""
res = get_domain(uuid=uuid)
if disabled is not None:
res['disabled'] = disabled
if name is not None:
res['name'] = name
if project_id is not None:
res[... | 7cdc53c96e17d79dd0998165b87dd745b8afd73e | 23,348 |
def ja_of(tree: Tree) -> str:
"""tree string in the Japanese CCGBank's format
Args:
tree (Tree): tree object
Returns:
str: tree string in Japanese CCGBank's format
"""
def rec(node):
if node.is_leaf:
cat = node.cat
word = normalize(node.word)
... | 7722e9de3b31354be4820cc32a8949ffac333e5f | 23,349 |
def cut_flowlines_at_points(flowlines, joins, points, next_lineID):
"""General method for cutting flowlines at points and updating joins.
Only new flowlines are returned; any that are not cut by points are omitted.
Parameters
----------
flowlines : GeoDataFrame
joins : DataFrame
flowli... | e535f6d5e073955b74784f5ce3121a929f9bc200 | 23,350 |
def export(gen, directory, file_prefix='{uid}-', **kwargs):
"""
Export a stream of documents to nxstxm_baseline.
.. note::
This can alternatively be used to write data to generic buffers rather
than creating files on disk. See the documentation for the
``directory`` parameter below... | ec1b1237f63fc29c8e8d1b14283b392523e86426 | 23,351 |
import os
def get_test_dataset(path):
"""
Gets a dataset that only has features
:param string path: The path the the dataset file after /datasets/
:return: features
"""
with open(os.path.abspath(os.path.join(os.getcwd(), "../datasets/", path)), "r") as file:
data = [line.split(',') for... | 4c9c8ed203367a51ae9d915e6318ad78a42372a1 | 23,352 |
def services():
"""
Returns the grader-notebook list used as services in jhub
Response: json
example:
```
{
services: [{"name":"<course-id", "url": "http://grader-<course-id>:8888"...}],
groups: {"formgrade-<course-id>": ["grader-<course-id>"] }
}
```
"""
service... | b1fbc2c90b344f75027538037c5d6786bda810c8 | 23,353 |
def chunks(l, k):
"""
Take a list, l, and create k sublists.
"""
n = len(l)
return [l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)] for i in range(k)] | 7cf0c39941ed8f358c576046154af6b3ee54b70a | 23,354 |
def bfs(adj, src, dst, cache=None):
"""BFS search from source to destination. Check whether a path exists, does
not return the actual path.
Work on directed acyclic graphs where we assume that there is no path to the
node itself.
Args:
adj: Adjacency matrix.
src: Source node index, 0-based.
dst: ... | 5e224ffa575dd0bd471142023e828a8e36d1782e | 23,355 |
import _ast
import ast
def get_source_ast(name: str) -> _ast.Module:
"""
Return ast of source code
"""
with open(name, "r") as f:
data = f.read()
return ast.parse(data) | 8e0826175df538bdd894f05b0c6cf143b0b0f69b | 23,356 |
import os
def fit_grain_FF_reduced(grain_id):
"""
Perform non-linear least-square fit for the specified grain.
Parameters
----------
grain_id : int
The grain id.
Returns
-------
grain_id : int
The grain id.
completeness : float
The ratio of predicted to me... | 941efcd3319c263ac95cfbaeecf07f1a5f12ef0a | 23,357 |
import math
def floor(base):
"""Get the floor of a number"""
return math.floor(float(base)) | 8b00ffccf30765f55ff024b35de364c617b4b20c | 23,358 |
def TranslateSecureTagsForFirewallPolicy(client, secure_tags):
"""Returns a list of firewall policy rule secure tags, translating namespaced tags if needed.
Args:
client: compute client
secure_tags: array of secure tag values
Returns:
List of firewall policy rule secure tags
"""
ret_secure_tags... | 5cbf71885c167d5c9d0dcae3294be017512db73a | 23,359 |
import os
import fnmatch
def _find_files(directory, pattern):
"""Searches a directory finding all files and dirs matching unix pattern.
Args:
directory : (str)
The directory to search in.
patterns : (str)
A unix style pattern to search for. This should be the same sty... | 5f10d14d6c4c68b68c54ef681c8ad5669e7b03d4 | 23,360 |
from typing import Callable
from typing import Dict
from typing import Any
import functools
def memoize(func: Callable):
"""
A decorator that memoizes a function by storing its inputs and outputs.
Calling the function again with the same arguments will return the cached
output.
This function is s... | 7ba9500c57c867abcb43bf5ffe58087270ebef08 | 23,361 |
def mini_batch(positive_rdd, negative_rdd, num_iterations):
"""get the positive and negative classes with index for mini-batch"""
# mini-batch preparation
pos_num = int(batch_size / 46)
neg_num = pos_num * 45
i = num_iterations % int(74 / pos_num)
# get the new mini-batch rdd for this iteration
new_rdd = positi... | e523c170d66cf9bdabf5f12ab78af417c59333a2 | 23,362 |
import math
def draw_polygon(img, max_sides=8, min_len=32, min_label_len=64):
""" Draw a polygon with a random number of corners and return the position
of the junctions + line map.
Parameters:
max_sides: maximal number of sides + 1
"""
num_corners = random_state.randint(3, max_sides)
... | 1dc1cdb18424c8d47ee95777d52713c884eedc5d | 23,363 |
def order_budget_update(request, order_id):
"""
Update budget for order
"""
serializer = OrderBudgetSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
order = get_object_or_404(Order, pk=order_id)
budget = serializer.validated_data['budget']
order.bud... | adc708d7cbc429ea6e5d81c5f9db60d0fa5f298a | 23,364 |
def analyse_readability_metrics(article_text):
"""
Use the textstat library to report multiple readability measures.
The readability metrics analysed are:
* The Flesch Reading Ease Score. A score from 100 (very easy to read) to 0 (very confusing).
* The grade score using the Flesch-Kincaid Grade Fo... | 32a89cf4788d469a164f9cdd606f1675ddf219b8 | 23,365 |
def dx(data):
"""
Derivative by central difference
Edges are takes as difference between nearest points
Parameters
----------
data : ndarray
Array of NMR data.
Returns
-------
ndata : ndarray
Derivate of NMR data.
"""
z = np.empty_like(data)
z[..., 0] ... | 6e88618750ff69662ec7f41ecfc50efbaab717db | 23,366 |
def grad(w):
""" Dao ham """
N = Xbar.shape[0]
return 1/N * Xbar.T.dot(Xbar.dot(w) - y) | 8bcce8c10eeb7ffae6e2af3e2f273f03b6984885 | 23,367 |
import graphsurgeon as gs
import importlib, sys
def from_tensorflow(graphdef, output_nodes=[], preprocessor=None, **kwargs):
"""
Converts a TensorFlow GraphDef to a UFF model.
Args:
graphdef (tensorflow.GraphDef): The TensorFlow graph to convert.
output_nodes (list(str)): The names of the... | 385bf490d2a034dd20856bb05370a90d461e7377 | 23,368 |
import random
def random_binary():
"""
测试 cached 缓存视图的装饰器 设置 key
:return:
"""
return [random.randrange(0, 2) for i in range(500)] | 3c30014d1222c136cb7d3d2fbe6e0d972decc776 | 23,369 |
def remove_from_end(string, text_to_remove):
"""
Remove a String from the end of a string if it exists
Args:
string (str): string to edit
text_to_remove (str): the text to remove
Returns: the string with the text removed
"""
if string is not None and string.endswith(text_to_rem... | 19cebd002fcf5aea5290a6998129427363342319 | 23,370 |
from .compose import ComposeHole
from .directconv import DirectConv
from .matmuls import MatmulHole
from .reducesum import ReduceSum
from typing import Optional
from typing import Iterable
from typing import Any
def spec_to_hole(
spec: specs.Spec, inputs: Optional[Iterable] = None, output: Optional[Any] = None
) ... | 0b23c1e1fff85c42391b11f6785dc16ef1039704 | 23,371 |
def get_node_number(self, node, typ) -> str:
"""Get the number for the directive node for HTML."""
ids = node.attributes.get("ids", [])[0]
if isinstance(self, LaTeXTranslator):
docname = find_parent(self.builder.env, node, "section")
else:
docname = node.attributes.get("docname", "")
... | f88227ef727d45d14cd9343ee26bdbfb15f6a2fc | 23,372 |
import os
import fnmatch
def count_mp3_files_below(adir_path):
"""counts all mp3 files below given dir including subdirs"""
matches = []
for root, dirnames, filenames in os.walk(adir_path):
for filename in fnmatch.filter(filenames, '*.mp3'):
matches.append(os.path.join(root, filename))... | c7be55162a8d1abd45fab1bef7592113494ed173 | 23,373 |
def get_client(client, aws_access_key_id, aws_secret_access_key, region=None):
"""Shortcut for getting an initialized instance of the boto3 client."""
return boto3.client(
client,
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=regio... | 4ebed5da9ca146b79563c0efb5bf04e7bc13f791 | 23,374 |
import logging
import traceback
import json
def main(req: func.HttpRequest) -> func.HttpResponse:
""" main function for status/http """
logging.info('Status processed a request.')
try:
response = get_http_response_by_status(200)
if req.get_body() and len(req.get_body()):
respo... | ac464fd479c0df9f9d462f37d884542bf670dfef | 23,375 |
def _variable_map_by_name(variables):
"""
Returns Dict,representing referenced variable fields mapped by name.
Keyword Parameters:
variables -- list of 'variable_python_type' Warehouse support DTOs
>>> from pprint import pprint
>>> var1 = { 'column':'frob_hz', 'title':'Frobniz Resonance (Hz)'... | 91c27ceb84614313d036ec216ef4c4d567a68255 | 23,376 |
def true_divide(x, y):
"""Divides x / y elementwise (using Python 3 division operator semantics).
NOTE: Prefer using the Tensor operator or tf.divide which obey Python
division operator semantics.
This function forces Python 3 division operator semantics where all integer
arguments are cast to flo... | 3bdcf5052730fd2c3e2e25a395b0e16534d2dcf9 | 23,377 |
def ObjectNotFoundError(NDARError):
"""S3 object not found"""
def __init__(self, object):
self.object = object
return
def __str__(self):
return 'Object not found: %s' % self.object | 3cc552f7074f8117ed18fd975bc5ac0b09f8016a | 23,378 |
def hello():
"""
Say hello using a template file.
"""
return render_template('index.html') | b2b09afd651a69fdc270238dbf3f724fa9f40ae4 | 23,379 |
def pause_sale(ctx):
"""
Pause the token sale
:param ctx:GetContext() used to access contract storage
:return:bool Whether pausing the sale was successful
"""
if CheckWitness(TOKEN_OWNER):
Put(ctx, SALE_STATUS_KEY, SALE_PAUSED)
return True
return False | 63e99802a852146f7a20460a28a7d277c4104954 | 23,380 |
def parse_item_hash(value):
"""
Parses the item-hash datatype, e.g. sha-256:5b8e5ee02caedd0a6f3539b19d6b462dd2d08918764e7f476506996024f7b84a
:param value: a string to parse
:return: parsed value
"""
if isinstance(value, ItemHash):
return value
if not isinstance(value, str):
r... | 6275ab41d437728ea3448bf150f068668c3f1819 | 23,381 |
def __convert_swizzle_scale(scale, export_settings):
"""Convert a scale from Blender coordinate system to glTF coordinate system."""
if export_settings[gltf2_blender_export_keys.YUP]:
return Vector((scale[0], scale[2], scale[1]))
else:
return Vector((scale[0], scale[1], scale[2])) | 19c2f62c9cd3c267a3edc2451c5f0eba3208c34f | 23,382 |
import time
import html
from sys import audit
def launch_plugin_flow(current, client_id, rekall_session, plugin, plugin_arg):
"""Launch the flow on the client."""
db = current.db
flow_id = utils.new_flow_id()
spec = plugins.RekallAPI(current).get(plugin)
if not spec:
raise ValueError("Unkn... | 69cb40da844293eaaa9a43aed2cca8bb476c41c9 | 23,383 |
from pathlib import Path
from typing import Type
from typing import cast
def load_config_from_expt_dir(experiment_dir: Path, loop_config: Type[OptimizerConfig]) -> OptimizerConfig:
"""
Locate a config file in experiment_dir or one of its subdirectories (for a per-seed config).
Config files are now normall... | 5c609b877c6c40f019d234b685caed17b287aca0 | 23,384 |
def glsadf_delay(order, stage):
"""Delay for glsadf
Parameters
----------
order : int
Order of glsadf filter coefficients
stage : int
-1 / gamma
Returns
-------
delay : array
Delay
"""
return np.zeros(_sptk.glsadf_delay_length(order, stage)) | dacf0a754ba2040ba7ae004658f02df3060c6251 | 23,385 |
def find_next(s: str)->[int]:
"""
input:string
output:the next array of string
"""
if len(s) == 1:
return [-1]
result = [0 for i in range(len(s))]
result[0] = -1
result[1] = 0
i = 2
cn = 0
while i < len(result):
if s[i-1] == s[cn]:
cn += 1
... | 455297eee28360f75a4f714172f62a7645ca49e0 | 23,386 |
from datetime import datetime
def _read_date():
""" read date from input; default to today """
# show date
while 1:
dts = prompt("Date", default=str(datetime.date.today()))
try:
datetime.datetime.strptime(dts, "%Y-%m-%d")
break
except ValueError:
... | 45cd0e68cc6ca14552c2e2953edd2cc15809f122 | 23,387 |
def handle_pending_submission(self, request, layout=None):
""" Renders a pending submission, takes it's input and allows the
user to turn the submission into a complete submission, once all data
is valid.
This view has two states, a completable state where the form values
are displayed without a fo... | b591246498c22d6079181654a94b4cd6290732ec | 23,388 |
import functools
def i18n_view(tpl_base_name=None, **defaults):
"""
Renders a template with locale name as suffix. Unlike the normal view
decorator, the template name should not have an extension. The locale names
are appended to the base template name using underscore ('_') as separator,
and lowe... | 46c33f2be90fb9cca8059ba1f13f97c3e5a61807 | 23,389 |
def git_file_list(path_patterns=()):
"""Returns: List of files in current git revision matching `path_patterns`.
This is basically git ls-files.
"""
return exec_output_lines(['git', 'ls-files', '--exclude-standard'] + path_patterns, False) | 0c8cf1a3570d39e6d5c7f1658fd85b6ef2938d8a | 23,390 |
def unreserve_id():
"""
Removes the reservation of a SCSI ID as well as the memo for the reservation
"""
scsi_id = request.form.get("scsi_id")
reserved_ids = get_reserved_ids()["ids"]
reserved_ids.remove(scsi_id)
process = reserve_scsi_ids(reserved_ids)
if process["status"]:
RESE... | 6665297f37420a5ad3498f9aa9a705f5b8f1830f | 23,391 |
def integral_sqrt_a2_minus_x2(x, a):
"""Integral of $\sqrt(a^2 - x^2)$ --- see (30) at
http://integral-table.com.
"""
return 0.5*x*np.sqrt(a**2 - x**2) + 0.5*a**2*np.arctan2(x, np.sqrt(a**2 - x**2)) | 778a5dc745c62727f192616448b6c98da3d93b5c | 23,392 |
def read_length(file_obj): # pragma: no cover
""" Numpy trick to get a 32-bit length from four bytes
Equivalent to struct.unpack('<i'), but suitable for numba-jit
"""
sub = file_obj.read(4)
return sub[0] + sub[1]*256 + sub[2]*256*256 + sub[3]*256*256*256 | 82c311c3a8e2d2e277979c19aaae665b0227f9cd | 23,393 |
import tempfile
import os
def check_and_reorder_reads(input_files, output_folder, temp_output_files):
""" Check if reads are ordered and if not reorder """
# read in the ids from the first pair (only check the first 100)
ids = []
for count, lines in zip(range(100),read_file_n_lines(input_files[0],4))... | c201b16cbc1fe1723c2354e8cad4e480c2d33a03 | 23,394 |
def acquires_lock(expires, should_fail=True, should_wait=False, resource=None, prefix=DEFAULT_PREFIX, create_id=None):
"""
Decorator to ensure function only runs when it is unique holder of the resource.
Any invocations of the functions before the first is done
will raise RuntimeError.
Locks are s... | 24b504a5319f76465e212f98a8bbfeddb0dc7b85 | 23,395 |
import json
def ifttt_comparator_alpha_options():
""" Option values for alphanumeric comparators """
errmsg = check_ifttt_service_key()
if errmsg:
return errmsg, 401
data = {"data": [
{"value": "ignore", "label": "ignore"},
{"value": "equal", "label": "is equal to"},
{... | d04d1f421eeda42324372702b7caf1777dfba964 | 23,396 |
def flat_abs_maximum(data, preserve_sign=True):
"""
Function to return the absolute maximum value in an array. By default,
this function will preserve the sign, meaning that if an array contains [-75, -25, 0, 25, 50]
then the function will return -75 because that value has the highest magnitude but it w... | 6276c874ba9e1dcd047b087f6954a11ee3b680a9 | 23,397 |
def get_image_to_groundplane_homography(P):
"""Given the 3x4 camera projection matrix P, returns the homography
mapping image plane points onto the ground plane."""
return np.linalg.inv(get_groundplane_to_image_homography(P)) | 189bb5b80243c9145065260c591fe00c29a9a947 | 23,398 |
import logging
def create_object_detection_edge_training(
train_object_detection_edge_model_request: TrainImageEdgeModel,
):
"""[Train a Object Detection Model for Edge in AutoML GCP]
Args:
train_object_detection_edge_model_request (TrainImageEdgeModel): [Based on Input Schema]
Raises:
... | afff20623b96195294740056de6e327add72148f | 23,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.