content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import importlib
def load_attr(str_full_module):
"""
Args:
- str_full_module: (str) correspond to {module_name}.{attr}
Return: the loaded attribute from a module.
"""
if type(str_full_module) == str:
split_full = str_full_module.split(".")
str_module = ".".join(split_full[:... | f96dd56c73745e76ccc9c48dda4ba8a6592ab54b | 31,785 |
from typing import Dict
from typing import List
import math
def conv(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]) -> List[XLayer]:
"""ONNX Conv to XLayer Conv conversion function"""
logger.info("ONNX Conv -> XLayer Conv (+ BiasAdd)")
assert len(node.get_out... | 7b004f41d103796ed01bc46e7dcff156171b35bd | 31,786 |
def yices_bvconst_int32(n, x):
"""Conversion of an integer to a bitvector constant, returns NULL_TERM (-1) if there's an error.
bvconst_int32(n, x):
- n = number of bits
- x = value
The low-order bit of x is bit 0 of the constant.
- if n is less than 32, then the value of x is truncated to
... | b676ea0ea5b25f90b60f2efd67af553d835daa9b | 31,787 |
from scipy.special import comb
def combination(n, k):
"""
组合数 n!/k!(n-k)!
:param n:
:param k:
:return:
"""
return comb(n, k, exact=True) | b87f9037decd765680e0e2d5b5dfea336e014b61 | 31,788 |
def create_carray(h5file_uri, type, shape):
"""Creates an empty chunked array given a file type and size.
h5file_uri - a uri to store the carray
type - an h5file type
shape - a tuple indicating rows/columns"""
h5file = tables.openFile(h5file_uri, mode='w')
root = h5file... | ca4c9605905a44b5f3027024f78cc855136472b0 | 31,790 |
def sort_dictionary_by_keys(input_dict):
"""
Sort the dictionary by keys in alphabetical order
"""
sorted_dict = {}
for key in sorted(input_dict.keys()):
sorted_dict[key] = input_dict[key]
return sorted_dict | 225df2c16d2b21740603c224319ad4b0eaa0899d | 31,791 |
def sorted_instructions(binview):
"""
Return a sorted list of the instructions in the current viewport.
"""
addrs = []
instructions = []
for ii in binview.instructions:
if ii[1] not in addrs:
instructions.append(instr(ii))
addrs.append(ii[1])
del addrs
in... | 5f8602b80a73fc4b66bbb6d2e70070f2e9e35397 | 31,792 |
def quick_sort(seq):
"""
Реализация быстрой сортировки. Рекурсивный вариант.
:param seq: любая изменяемая коллекция с гетерогенными элементами,
которые можно сравнивать.
:return: коллекция с элементами, расположенными по возрастанию.
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3,... | 46b56b5d29ca31a872e1805b66f4529a8bf48c6b | 31,793 |
def _geocode(address):
"""
Like :func:`geocode` except returns the raw data instead.
:param str address: A location (e.g., "Newark, DE") somewhere in the United States
:returns: str
"""
key = _geocode_request(address)
result = _get(key) if _CONNECTED else _lookup(key)
if _CONNECTED ... | f6cee8c606c5fe014c6c67787e0a9bcee70a0281 | 31,794 |
def easeOutBack(n, s=1.70158):
"""A tween function that overshoots the destination a little and then backs into the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to... | bc5a0e34c2f7a16492c0456d8c28725888c6822c | 31,795 |
def normalize_query_result(result, sort=True):
"""
Post-process query result to generate a simple, nested list.
:param result: A QueryResult object.
:param sort: if True (default) rows will be sorted.
:return: A list of lists of RDF values.
"""
normalized = [[row[i] for i in range(len(row))... | 1df57ef889be041c41593766e1ce3cdd4ada7f66 | 31,796 |
from typing import List
def count_jobpairs(buildpairs: List) -> int:
"""
:param buildpairs: A list of build pairs.
:return: The number of job pairs in `buildpairs`.
"""
counts = [len(bp['jobpairs']) for bp in buildpairs]
return sum(counts) | 30c345698400fd134456abcf7331ca2ebbfec10f | 31,797 |
def unravel_params(nn_params, input_layer_size, hidden_layer_size,
num_labels, n_hidden_layers=1):
"""Unravels flattened array into list of weight matrices
:param nn_params: Row vector of model's parameters.
:type nn_params: numpy.array
:param input_layer_size: Number of units in th... | 40703668ad74e4f6dbaf5c9c291da0c1c9528f60 | 31,798 |
def is_op_stack_var(ea, index):
""" check if operand is a stack variable """
return idaapi.is_stkvar(idaapi.get_flags(ea), index) | b041cc56d8a0f772223b96cf5fa8bd6e338c777f | 31,799 |
def get_circles():
"""
Create 3 images each containing a circle at a different position.
Returns:
List([numpy array,]) of 3 circle images
"""
circles = []
x, y = np.meshgrid(range(256), range(256))
for d in range(30, 390, 120):
img = np.zeros((256, 256), dtype=np.uint8... | 4068c5eb028fd728596a1eddb7aa657993cc140b | 31,800 |
def load_sequences( fasta_file ):
"""! @brief load candidate gene IDs from file """
sequences = {}
assembly_seq_order = []
with open( fasta_file ) as f:
header = f.readline()[1:].strip()
if " " in header:
header = header.split(' ')[0]
seq = []
line = f.readline()
while line:
if line[0] == '>':
... | 7dd6cb97f457fee371556ab49a95ad12d52ca8dd | 31,801 |
def compute_distance_fields(params, canvas_size, df=distance_to_cuboids):
"""Compute distance fields of size (canvas_size+2)^3 to specified primitives.
params -- [b, *]
canvas_size
df -- distance_to_*
"""
grid_pts = th.stack(th.meshgrid([th.linspace(-1/(canvas_size-1),
... | 4d6ab66f0d540e20b7f4b8782b9cce24e989be10 | 31,802 |
def view_user_posts(request, pk=None):
"""View your own posts or others posts"""
if pk is None:
pk = request.user.pk
user = get_object_or_404(User, pk=pk)
return render(request, 'home/view_user_posts.html',
{"pk": user.username, "user": user}) | 20be478cc98c99afeace4188549ec3728fa4221a | 31,803 |
def find_all_strobogrammatic_numbers(n: int):
""" Returns all strobogrammatic numbers for a given number of digits.
Args:
int: number of digits
Returns:
A list of string with strobogrammatic numbers.
"""
result = numdef(n, n)
return result | 9923386d85de5110044488cf3e491d6602755d37 | 31,804 |
def get_deploy_size_bytes(deploy: Deploy) -> int:
"""Returns size of a deploy in bytes.
:deploy: Deploy to be written in JSON format.
:returns: Size of deploy in bytes.
"""
size: int = len(deploy.hash)
for approval in deploy.approvals:
size += len(approval.signature)
size += le... | 791c6ea249a9cdec39f4f02b9d88215868df6ebf | 31,805 |
from typing import Any
from typing import get_args
def make_hetero_tuple_unstructure_fn(cl: Any, converter, unstructure_to=None):
"""Generate a specialized unstructure function for a heterogenous tuple."""
fn_name = "unstructure_tuple"
type_args = get_args(cl)
# We can do the dispatch here and now.
... | a1ffa13bcf6488a79c6aacafd6f1e12112f99bb2 | 31,807 |
from typing import Optional
from typing import Mapping
def get_dps(name: Optional[str] = None,
resource_group_name: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDpsResult:
"""
Use this data sourc... | cd258d299319c794fcb97a123b1f6265d8405d1c | 31,808 |
from cacao_accounting.database import Modulos
from typing import Union
def obtener_id_modulo_por_nombre(modulo: Union[str, None]) -> Union[str, None]:
"""Devuelve el UUID de un modulo por su nombre."""
if modulo:
MODULO = Modulos.query.filter_by(modulo=modulo).first()
return MODULO.id
els... | 2b66b7dafbf45c251717b673bc75db1bf2b99683 | 31,809 |
def qg8_graph_get_chunk(graph: qg8_graph, idx: int):
"""
Get a chunk from the graph according to its index provided the second argument `idx`
"""
if not isinstance(graph, qg8_graph):
raise TypeError("Argument is not a qg8_graph")
if idx > len(graph.chunks) - 1:
raise ValueError("Inde... | 8000d04a0e657842b1c3a5e0510ed81e26cffbde | 31,810 |
def InterruptStartForwardForVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartForwardForVector(builder, numElems) | 84cb4ffafc876554dfaded6c20bc08a00edc41ba | 31,811 |
from .planning import Network # Imported here not to affect locals() at the top.
return Network(*merge_set)
def build_network(
operations,
cwd=None,
rescheduled=None,
endured=None,
parallel=None,
marshalled=None,
node_props=None,
renamer=None,
excludes=None,
):
"""
Th... | f44ae5b68c7f2feb35b95b7e97d3ac5947e42933 | 31,812 |
def docker_volume_exist(volume):
"""Check if the docker-volume exists."""
cmd = "docker volume inspect {0}".format(volume)
status = execute_subprocess(cmd)
return status == 0 | d96269dad83d594ae1c2eb5b04db1813699369e7 | 31,814 |
def get_embed_similarity(embed1, embed2, sim_measure="euclidean", num_top=None):
"""
Score alignments based on embeddings of two graphs
"""
if embed2 is None:
embed2 = embed1
if num_top is not None and num_top != 0: # KD tree with only top similarities computed
kd_sim = kd_align(em... | 3f33f64f4dab3da42076956e083e7bd29e2909b1 | 31,815 |
from typing import get_args
def preprocess_meta_data():
""" preprocess the config for specific run:
1. reads command line arguments
2. updates the config file and set gpu config
3. configure gpu settings
4. define logger.
"""
args = get_args()
config =... | c7f4202fe3ccece2934999376af428ff5a72a164 | 31,818 |
def calc_water(scenario, years, days_in_year):
"""Calculate Water costs Function
Args:
scenario (object): The farm scenario
years (int): The no. of years the simulation will analyse
days_in_year (float): The number of days in a year
Returns:
cogs_water (list): Cost of Goods So... | ed23060e64c928a545897edef008b8b020d84d3c | 31,819 |
def vit_large_patch32_224_in21k(pretrained=False, **kwargs):
""" ViT-Large model (ViT-L/32) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-21k weights @ 224x224, source https://github.com/google-research/vision_transformer.
"""
model_kwargs = dict(
patch_size=32,
embed_... | 51205d4fd518a1274f6ebc84916c0df968dc1eb2 | 31,820 |
def _check_template(hass, value_template):
""" Checks if result of template is true """
try:
value = template.render(hass, value_template, {})
except TemplateError:
_LOGGER.exception('Error parsing template')
return False
return value.lower() == 'true' | 9de8bc9207a17cdb9902cd0d804a3e33531a93fb | 31,821 |
def _snr_single_region(spectrum, region=None):
"""
Calculate the mean S/N of the spectrum based on the flux and uncertainty
in the spectrum.
Parameters
----------
spectrum : `~specutils.spectra.spectrum1d.Spectrum1D`
The spectrum object overwhich the equivalent width will be calculated.... | 1a87cad818c17aad3f098731d8a37d809176b92b | 31,822 |
def squared_error(
prediction: chex.Array,
targets: chex.Array,
weight: float = 1.0,
# register_loss: bool = True,
) -> chex.Array:
"""Squared error loss."""
if prediction.shape != targets.shape:
raise ValueError("prediction and targets should have the same shape.")
# if register_loss:
kfac_... | bf078eab1fd0578b8f28a2cdcef4a325ed3ef18a | 31,824 |
def add_vqe_exact(params):
"""Add the ground states to the dict"""
ex = run_exact(params["operator"])
vq = run_vqe(params["operator"])
return {**params, **vq, **ex} | 548f347af1aff46b087d7abb6936a0fdf5556ca1 | 31,825 |
def post_demo(module_id):
"""
validation为数据验证装饰器,类似于wtf,这里做成yaml文件方便配置,易于阅读
返回值在tflask中有定制,这里使用字典也是为了更直观(不为了少些几个单词而牺牲可读性)
:param module_id:
:type module_id:
:return:
:rtype:
"""
post_form = parse_json_formdict('module_update')
code = update_module(module_id, post_form)
retur... | 03c644cb4ea31a1e9c7bb0efea6a8e7194d12932 | 31,826 |
import logging
def local_angle_2D(points, times=None):
"""
Calculates 2-dimensional absolute step angles in radians where step angle
is deviation from a straight path when going from one time point to the next
Parameters
----------
points: np.ndarray
Array of track points in matrix co... | d774061bf164bb3b835094fff5d4a0d20d449829 | 31,828 |
def calculate_geometry_stats(df):
"""Calculate total network miles, free-flowing miles (not in waterbodies),
free-flowing unaltered miles (not in waterbodies, not altered), total
perennial miles, total free-flowing unaltered perennial miles, and count of
segments.
Parameters
----------
df :... | 0e5a32aab297d23fcf77eec7649c662e03ee9bb5 | 31,829 |
def unshelve(ui, repo, *shelved, **opts):
"""restore a shelved change to the working directory
This command accepts an optional name of a shelved change to
restore. If none is given, the most recent shelved change is used.
If a shelved change is applied successfully, the bundle that
contains the s... | 6656db08227788f216620651727213ad9eab9800 | 31,830 |
def SyntaxSpec(lang_id=0):
"""Syntax Specifications
@param lang_id: used for selecting a specific subset of syntax specs
"""
if lang_id == synglob.ID_LANG_JAVA:
return SYNTAX_ITEMS
else:
return list() | 0de3ec2386efedc1472a977c1338759c61d70e8f | 31,831 |
from bids import BIDSLayout
from ..utils import collect_participants
from nipype import logging as nlogging, config as ncfg
from ..__about__ import __version__
from ..workflow.base import init_xcpabcd_wf
from niworkflows.utils.misc import clean_directory
from yaml import load as loadyml
import uuid
from pathlib import... | 0158606b916b35607480637275a2abda5eb53774 | 31,832 |
def handler404(request):
"""
Utility handler for people wanting EXCEPTIONAL_INVASION, since we can't trap the Http404 raised when the
URLconf fails to recognise a URL completely. Just drop this in as handler404 in your urls.py. (Note that
if you subclass ExceptionalMiddleware to override its render() me... | 65c952f8c6f25b2e625fb27ebdcd054ea3ea76c8 | 31,833 |
def get_pipeline(name, outfolder):
"""
Build and return pipeline instance associated with given name.
:param str name: Name of the pipeline to build.
:param str outfolder: Path to output folder for use by pipeline instance.
:return SafeTestPipeline: A test-session-safe instance of a Pipeline.
"... | 539d0485e8bdfa679bc7901f2e2174a2fab0d161 | 31,834 |
def get_idw_interpolant(distances, p=2):
"""IDW interpolant for 2d array of distances
https://pro.arcgis.com/en/pro-app/help/analysis/geostatistical-analyst/how-inverse-distance-weighted-interpolation-works.htm
Parameters
----------
distances : array-like
distances between interpolati... | fefc53b590ee083c176bb339ad309b285dfe1a1a | 31,835 |
from typing import Iterable
def _render_html_attributes(attributes):
"""
Safely renders attribute-value pairs of an HTML element.
"""
if attributes and isinstance(attributes, dict):
def map_key(key):
# Map and case converts keys
return _kebab(ALIASES.get(key, key))
... | c86d03c4fb316b1a3d74f377867d8a8609d55ff8 | 31,836 |
def interpolate_force_line2(form, x, tol=1E-6):
"""Interpolates a new point in a form polyline
Used by the `add_force_line` function
(I think it is assumed that the )
"""
if len(form) < 1:
raise ValueError('interpolate_force_line2 : form must not be an empty list')
form_out1 = [form[0]]
... | 82a0eac9132b7e631fd395bddf87595385cae574 | 31,837 |
def load_hdf5(infile):
"""
Load a numpy array stored in HDF5 format into a numpy array.
"""
with h5py.File(infile, "r", libver='latest') as hf:
return hf["image"][:] | 3a9a83f03a32a029a0dda5e86ac9432c96ff62c6 | 31,838 |
import json
def enqueue_crawling_job(delegate_or_broadcast_svc, job_id, urls, depth):
"""
Used to enqueue a crawling job (or delegate a sub-url on a current job)
to the worker pool.
:type delegate_or_broadcast_svc: ZeroMQDelegatorService or
ZeroMQBroadcastService.
:param delegate_or_broad... | 6a211346edd6f921bf26ed08adcee98cff066764 | 31,839 |
def show_control_sidebar_tabs():
"""Show the control sidebar tabs"""
# Default the show recent activity tab to true
default_dict = {
'SHOW_RECENT_ACTIVITY_TAB': True,
}
# Pull the settings for the control sidebar from settings.
# It is possible that the show recent activity will be
... | f30147c39c507effa92e2cd6c5bc8f9dd84438b6 | 31,840 |
def unsubscribe(login, rec):
"""Unsubscribe from user
"""
try:
if login == env.user.login:
raise SubscribeError
if rec:
if users.check_subscribe_to_user_rec(login):
fn = users.unsubscribe_rec
else:
return xmpp_template('sub_... | c0d79eb011734de3a06c5d50e187e4ecaa7a6319 | 31,841 |
def build_script(configurators):
"""
Loops over configurators, calling gather_input on them and then renders the script sections
in a template.
"""
def gather_input(configurator):
cfg = configurator.Config()
dialog.set_background_title(cfg.description)
return {"config": cfg,... | 4a332c3c0ebb55074babb1872a586dd43276f63a | 31,842 |
def fix_source_eol( path, is_dry_run = True, verbose = True, eol = '\n' ):
"""Makes sure that all sources have the specified eol sequence (default: unix)."""
if not os.path.isfile( path ):
raise ValueError( 'Path "%s" is not a file' % path )
try:
f = open(path, 'rb')
except IOError, msg:... | e435e9856d14fdcaf1d833be4e8df7414d4c92eb | 31,843 |
import logging
def truew(crse=None,
cspd=None,
hd=None,
wdir=None,
wspd=None,
zlr=DEFAULT_ZRL,
wmis=DEFAULT_MISSING_VALUES,
):
"""
FUNCTION truew() - calculates true winds from vessel speed, course and
relative wind
INPUTS
crs... | b3a97b126ba9bc32bd1452c3278ec72512dc6dd8 | 31,844 |
def ascii_encode(string):
"""Return the 8-bit ascii representation of `string` as a string.
:string: String.
:returns: String.
"""
def pad(num):
binary = baseN(num, 2)
padding = 8 - len(binary)
return "0"*padding + binary
return "".join(pad(ord(c)) for c in string) | 1a06c49514e5c320d299a93aa683f249470b26f7 | 31,845 |
import chunk
def print_statement(processor, composer, searcher):
# type: (Parser, Compiler, scanner.Scanner) -> Tuple[Parser, Compiler]
"""Evaluates expression and prints result."""
processor, composer = expression(processor, composer, searcher)
processor = consume(
processor,
searche... | ecb930fb90c7cb88e874d85df42ba3d28225031d | 31,846 |
def gmm_sky(values, **extras):
"""Use a gaussian mixture model, via expectation maximization.
of course, there's only one gaussian. could add another for
faint sources, bad pixels, but..."""
gmm = sklearn.mixture.GMM()
r = gmm.fit(values)
return r.means_[0, 0], np.sqrt(r.covars_[0, 0]) | a41a386b931c2eaa71dd5927f5060548dac5dc33 | 31,847 |
import pytz
def getLocalTime(utc_dt, tz):
"""Return local timezone time
"""
local_tz = pytz.timezone(tz)
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
return local_dt | 70789f61a90d991714fafe3c15917d1f1113fe8f | 31,848 |
def SyncSleep(delay, name=None):
"""Pause for `delay` seconds (which need not be an integer).
This is a synchronous (blocking) version of a sleep op. It's purpose is
to be contrasted with Examples>AsyncSleep.
Args:
delay: tf.Tensor which is a scalar of type float.
name: An optional name for the op.
... | 7015a756cc670efcafce9952269e3a7f2465e3fb | 31,849 |
def admin():
"""
Adminページ
"""
return redirect(url_for('rooms')) | 090d00f84204f58b22e83c468d368d928ea92e03 | 31,850 |
def timer(interval):
"""
Decorator for registering a function as a callback for a timer thread. Timer object deals with delegating event
to callback function.
"""
def decorator(f):
timers = timer.__dict__.setdefault('*timers', [])
timers.append(Timer(f, interval))
return f
... | 773fd5d072d7cc83eaf7512a6b6722b9df9ca1b1 | 31,851 |
def common_start(stra, strb):
""" returns the longest common substring from the beginning of stra and strb """
def _iter():
for a, b in zip(stra, strb):
if a == b:
yield a
else:
return ""
return ''.join(_iter()) | 365daf9e43a01e8a1871fbe88775880adba940a9 | 31,852 |
def auto_weight(X, Y, model, resolution=0.01, limits=0.05, **kwargs):
"""Automatically determine the weight to use in the CPD algorithm.
Parameters
----------
X : ndarray (N, D)
Fixed point cloud, an N by D array of N original observations in an n-dimensional space
Y : ndarray (M, D)
... | 3eb18c38725f434d2a2756acfe4ade01e5964b93 | 31,853 |
def max(self, parameter_max):
"""
It returns the maximum value of a parameter and the value's indexes.
Parameters
----------
parameter_max: str
Name of the parameter.
Returns
-------
max_dict: dict
Dictionary with the following format:
{
... | 8acf9c645a7c427d543c9087d66318ddf4765330 | 31,854 |
import json
def search(query):
"""
Searches your bucket. query can contain plaintext, and can also contain clauses
like $key:"$value" that search for exact matches on specific keys.
Returns either the request object (in case of an error) or a list of objects with the following keys:
key: key ... | 7844e503eb65a97d5729498fad4119d7b78606cd | 31,855 |
import re
def camel_to_snake(text: str) -> str:
"""
A helper function to convert `camelCase` to `snake_case`.
- e.g. `bestBigBrawlerTime` -> `best_big_brawler_time`
### Parameters
text: `str`
The text to restructure from `camelCase` to `snake_case`.
### Returns
`str`
The ... | b9ac748bf0cc345c7cfb0bade1e4b1e9cbdf712c | 31,857 |
def get_stats(distance_results):
"""
list order: median, mean, min, max
:param distance_results:
:return: dictionary of stats
"""
if len(distance_results) == 0:
return {'median': 0, 'mean': 0, 'min': 0, 'max': 0}
else:
return {'median': median(distance_results), 'mean': mean(... | 429a6b984f080fa351888177dd3d3f26e30d4a6e | 31,858 |
from typing import Mapping
def create(collection_id):
"""Create a mapping.
---
post:
summary: Create a mapping
parameters:
- description: The collection id.
in: path
name: collection_id
required: true
schema:
minimum: 1
type: integer
... | b0283e174ccc0ba2f50cad2d7f416d0f6b570025 | 31,861 |
def get_arc_proxy_lifetime(proxy_file=None):
"""
Returns the remaining lifetime of the arc proxy in seconds. When *proxy_file* is *None*, it
defaults to the result of :py:func:`get_arc_proxy_file`. Otherwise, when it evaluates to
*False*, ``arcproxy`` is queried without a custom proxy file.
"""
... | 08c46e3f25db792ae4553a4670487f04d27e9898 | 31,863 |
def LLR_alt2(pdf, s0, s1):
"""
This function computes the approximate generalized log likelihood ratio (divided by N)
for s=s1 versus s=s0 where pdf is an empirical distribution and
s is the expectation value of the true distribution.
pdf is a list of pairs (value,probability). See
http://hardy.uhasselt.be/Fishtes... | cb56260a390d1e9233e96e430835f851c222e30a | 31,864 |
def load_configs(ex_dir):
""" Loads all configuration files into a list from the given experiment directory. """
configs = []
run_nums = get_run_nums(ex_dir)
for run_num in run_nums:
loc = ex_dir + '/' + run_num
try:
configs.append(extract_config(loc))
except:
... | 7413f3a310684c47b87bfc912fae39ab0e6067eb | 31,865 |
from typing import Type
def create_app(item_model: Type[Item], db_session: Session) -> StacApi:
"""Create application with a custom sqlalchemy item"""
api = StacApi(
settings=ApiSettings(indexed_fields={"datetime", "foo"}),
extensions=[
TransactionExtension(
client=... | 80407ff030569bc4df23296e1e156b3d116f0cdc | 31,866 |
from typing import Dict
def reducemin(node: NodeWrapper,
params: Dict[str, np.ndarray],
xmap: Dict[str, XLayer]):
""" ONNX ReduceMin to XLayer AnyOp conversion function """
return generic_reduce("ReduceMin", node, params, xmap) | f8f6c84d9aa0a1f5f3f53a21e65938f939806f57 | 31,867 |
def mass(query,ts):
"""Calculates Mueen's ultra-fast Algorithm for Similarity Search (MASS) between a query and timeseries. MASS is a Euclidian distance similarity search algorithm."""
#query_normalized = zNormalize(np.copy(query))
m = len(query)
q_mean = np.mean(query)
q_std = np.std(query)
me... | 89dc6b5da2e2197f3e96606d17912868a112b5f7 | 31,868 |
def concept_categories():
"""概念类别映射{代码:名称}"""
db = get_db()
collection = db['同花顺概念']
pipeline = [
{
'$project': {
'_id': 0,
'概念编码': 1,
'概念名称': 1,
}
}
]
ds = collection.aggregate(pipeline)
df = pd.DataFram... | 0fd38a54ccfec50fbfeab438496a80b63bdf8a7f | 31,869 |
def schema_validate(stack, schema_json):
"""Check that the schema is valid.
.. warning: TidyWidget index is hardcoded!
Parameters
----------
stack: pd.DataFrame
The stacked data.
schema_json: json
Full description
Returns
-------
"""
# Import library
# Che... | 5ad66d87c6ff09fecbc99338bd8e1fd1dc8a1ff9 | 31,870 |
def dict_to_config_str(config_dict):
"""Produces a version of a dict with keys (and some values) replaced with
shorter string version to avoid problems with over long file names in
tensorboard"""
key_abrv = {
"embedding_dimension": "ed",
"loss_type": "lt",
"initialize_uniform": ... | da7d4ae8a58c2dab2d07616ae25438c8c0e0252d | 31,871 |
import time
import json
def wait_erased(fout,
prog,
erased_threshold=20.,
interval=3.0,
prog_time=None,
passn=0,
need_passes=0,
timeout=None,
test=False,
verbose=False):
... | 8ce4e6739d1d911353039c59ac8177f0733ea64d | 31,872 |
def settle(people, rates, bills, decimal_places=2):
"""Calculate the smallest set of transactions needed to settle debts.
For each person we sum the money spent for her and subtract the money she
paid. We get the amount she should pay (it does not matter to whom from her
point of view). After she does,... | 25890a647a492999fe44e668d2270f359fbc3863 | 31,874 |
import ast
def extract_ast_class_def_by_name(ast_tree, class_name):
"""
Extracts class definition by name
:param ast_tree: AST tree
:param class_name: name of the class.
:return: class node found
"""
class ClassVisitor(ast.NodeVisitor):
"""
Visitor.
"""
de... | 011f1cb8d965db8e30e6f4281704a6140103946b | 31,875 |
def getAttribute(v, key):
"""
This function is mainly for retrive @@transducer/xxx property, and fantasy-land/xxx property.
We assume dict/object in Python may own such properties.
dict case:
d = {'@@transducer/init': lambda: True}
init_fn = getAttribute(d, '@@transducer/init')
obj case:
class T... | d44d31bb6734637c56554e040d93620bb2d617e0 | 31,876 |
def getdata(mca):
""" Extract the data contained in spectrum files
INPUT:
mca; path
OUTPUT:
Data; 1D-array """
name = str(mca)
name = name.split("\\")[-1]
name = name.replace('_',' ')
# custom MC generated files
if 'test' in name or 'obj' in name or 'newtest' ... | 4b89f6a6d93cf174c6791fb908482958d7651220 | 31,877 |
def merge_dicts(dict_a, dict_b):
"""Recursively merge dictionary b into dictionary a.
If override_nones is True, then
"""
def _merge_dicts_(a, b):
for key in set(a.keys()).union(b.keys()):
if key in a and key in b:
if isinstance(a[key], dict) and isinstance(b[key], ... | 1ce3d253ceb467ead2bee8efb2652b81191147d0 | 31,878 |
import torch
def adjust_contrast(inp, contrast_factor):
"""
Adjust Contrast of an image.
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The inp image is expected to be in the range of [0, 1].
"""
if not isinstance(inp, torch.Tensor):
... | 9e98f1b0cf11efd6c9aa14b4ff35701605690134 | 31,879 |
def default_tiling():
"""Return default tiling options for GeoTIFF driver.
Returns
-------
dict
GeoTIFF driver tiling options.
"""
return {"tiled": True, "blockxsize": 256, "blockysize": 256} | c2d78f2d87478121cc52124d0b33edde5850a10a | 31,880 |
import importlib
def read_template():
"""Loads a html template for jinja.
Returns:
str: The loaded template.
"""
html = 'image_template.html'
package = '.'.join([__name__, 'templates'])
return importlib.resources.read_text(package, html) | f6288076ed32c2ed6db86e91595c4a635c9ce5b0 | 31,881 |
def parse_training_labels(train_box_df, train_image_dirpath):
"""
Reads and parses CSV file into a pandas dataframe.
Example:
{
'patientId-00': {
'dicom': path/to/dicom/file,
'label': either 0 or 1 for normal or pnuemonia,
'boxes': list of box(es)
},
... | 1b6765c6c3ffe261cd6d796fd1f97154008a5126 | 31,882 |
from typing import Optional
from typing import Union
def retryable_request(retries: Optional[Union[int, Retry]] = 1, *,
session: Session = None,
backoff_factor: float = None) -> Session:
"""Возвращает объект Session, который способен повторять запрос указанное число раз... | eb2396d9284eb9693643339477ab2dbb5aadcb8c | 31,883 |
def get_timeouts(timeout=None):
"""Ensures that both read and connect timeout are passed in
final patched requests call. In case any of it is missing in initial
call by the caller, default values are added"""
if timeout:
return timeout
return (Config.connect_timeout(), Config.read_timeout()) | f2545334efdf0e1c740cffa5554a8ee8c91eda0c | 31,884 |
import math
def populateDayOverview(excelDataConsolidated:ExcelDataConsolidation, overviewSheetData) -> DayOverview:
"""Populates the Day Overview Object
Arguments:
excelDataConsolidated {ExcelDataConsolidation} -- [description]
overviewSheetData {[type]} -- [description]
Returns... | 6969e9c047d1206df059c687f4d9b2e13ab6cc61 | 31,885 |
async def get_loading_images(mobi_app: str = "android", platform: str = "android",
height: int = 1920, width: int = 1080,
build: int = 999999999, birth: str = "",
credential: Credential = None):
"""
获取开屏启动画面
Args:
buil... | 032f7ab911dc48dfbec2b09b33863230c4295c67 | 31,886 |
def cross_energy(sig, eps, mesh):
"""
Calcul de l'energie croisée des champs de contrainte sig et de deformation eps.
"""
return fe.assemble(fe.inner(sig, eps) * fe.dx(mesh)) | b6bcf3a9c2885e1d3bf6b8c0f3e30454854ed474 | 31,887 |
import requests
def login():
"""
登录API
:return: True: 登录成功; False: 登录失败
"""
ctrl.BEING_LOG = True
if check_login_status():
ctrl.BEING_LOG = False
return True
error_times = 0
while True:
try:
update_proxy()
update_cookies()
us... | a34ed7b8f44680b826d648193150c0387af18e7a | 31,888 |
def logout():
"""Logout"""
next_url = request.args.get('next') if 'next' in request.args else None
# status = request.args.get('status') if 'status' in request.args else None
# client_id = request.args.get('client_id') if 'client_id' in request.args else None
logout_user()
return redirect(next_u... | 0cb55a1845386e655f313ee519a84b1ab548b971 | 31,889 |
from operator import and_
def find_all(query, model, kwargs):
"""
Returns a query object that ensures that all kwargs
are present.
:param query:
:param model:
:param kwargs:
:return:
"""
conditions = []
kwargs = filter_none(kwargs)
for attr, value in kwargs.items():
... | 84e24214d21cb70a590af395451f250002de21bf | 31,890 |
def ot1dkl(x, y, M, epsilon, log=True, **kwargs):
"""General OT 2d function."""
if log:
ot = ot1dkl_log
else:
ot = ot1dkl_
output = ot(x, y, M, epsilon, **kwargs)
return output | 6c56ca504b5cfffdc45f0a1931ae33cfe8b5fe8c | 31,891 |
def normalize_element_without_regex(filter, field):
"""
mongomock does not support regex...
"""
if len(filter) > 0:
filters = {field: { "$in": filter}}
else:
filters = {}
print filters
return filters | 55fa5d108891819d9e8ee208b6475aed95b49b2a | 31,892 |
def _pad_random(m, new_rows, rand):
"""Pad a matrix with additional rows filled with random values."""
rows, columns = m.shape
low, high = -1.0 / columns, 1.0 / columns
suffix = rand.uniform(low, high, (new_rows, columns)).astype(REAL)
return vstack([m, suffix]) | 9ac694ae0f8451f2b18f75acfa414f07c5a1fbf9 | 31,893 |
def quantize_sequences(sequences, alphabet):
"""Giving prescribing alphabet, quantize each caracter using index in alphabet
in each sequence.
input:
sequences: [str]
return:
[[int]]
"""
print("quantizing sequences...")
new_sequences = []
for sequence in sequences:
... | 7b8a870d72d6b0a9568fba8d96a1d3c2e422ff59 | 31,894 |
def search(context, mpd_query):
"""
*musicpd.org, music database section:*
``search {TYPE} {WHAT} [...]``
Searches for any song that contains ``WHAT``. Parameters have the same
meaning as for ``find``, except that search is not case sensitive.
*GMPC:*
- does not add quotes ar... | c24881b3298c444f6f80fe690f71ed8f504d78f1 | 31,896 |
def get_camera_pose(camera_info):
"""
:param camera_info:
:return:
"""
camera_pose = list()
for sbj in camera_info.keys():
for i, cam in enumerate(camera_info[sbj]):
camera_pose.append(cam.cam_orig_world.reshape(3))
return np.array(camera_pose) | a371ce035b51b8c01775152bd5bb7355040f1cb6 | 31,897 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.