content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import argparse
def create_parser() -> ArgumentParser:
"""
Constructs the MFA argument parser
Returns
-------
ArgumentParser
MFA argument parser
"""
GLOBAL_CONFIG = load_global_config()
def add_global_options(subparser: argparse.ArgumentParser, textgrid_output: bool = False):... | cb91b45e8c958b6e50f7cc31ef9e5e16c8cb4888 | 3,656,500 |
def build_params_comments(python_code, keyword, info):
"""Builds comments for parameters"""
for arg, arg_info in zip(info.get('expected_url_params').keys(), info.get('expected_url_params').values()):
python_code += '\n' + 2*TAB_BASE*SPACE + ':param ' + score_to_underscore(arg) + ': '
python_cod... | ce7446bb49ff25cbb2fb08ed8ca389dea16919bd | 3,656,501 |
async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Netatmo component."""
hass.data[DOMAIN] = {}
hass.data[DOMAIN][DATA_PERSONS] = {}
if DOMAIN not in config:
return True
config_flow.NetatmoFlowHandler.async_register_implementation(
hass,
config_entry_oa... | 7913dd1b7eaa60e7bedfba2a9da199cb4045e7ba | 3,656,502 |
import asyncio
import os
import aiohttp
async def upload_artifact(req):
"""
Upload artifact created during sample creation using the Jobs API.
"""
db = req.app["db"]
pg = req.app["pg"]
sample_id = req.match_info["sample_id"]
artifact_type = req.query.get("type")
if not await db.samp... | 79a9e76fb75ba12b9118e8facbb23d2c007158cf | 3,656,503 |
def hotkey(x: int, y: int) -> bool:
"""Try to copy by dragging over the string, and then use hotkey."""
gui.moveTo(x + 15, y, 0)
gui.mouseDown()
gui.move(70, 0)
gui.hotkey("ctrl", "c")
gui.mouseUp()
return check_copied() | 5cd789fd8e1b3ecf9dd1585a6831f6db92d4b6b0 | 3,656,504 |
import requests
def get_tv_imdbid_by_id( tv_id, verify = True ):
"""
Returns the IMDb_ ID for a TV show.
:param int tv_id: the TMDB_ series ID for the TV show.
:param bool verify: optional argument, whether to verify SSL connections. Default is ``True``.
:returns: the IMDB_ ID for that TV sho... | 363a2284d65fe1cfa2f3d2d07e3205de77bf67ef | 3,656,505 |
def test_reading_cosmos_catalog():
"""Returns the cosmos catalog"""
cosmos_catalog = CosmosCatalog.from_file(COSMOS_CATALOG_PATHS)
return cosmos_catalog | 1fc6f32cfc86ee28e114878d5ce7c13891e79ae1 | 3,656,506 |
def is_terminal(p):
"""
Check if a given packet is a terminal element.
:param p: element to check
:type p: object
:return: If ``p`` is a terminal element
:rtype: bool
"""
return isinstance(p, _TerminalPacket) | 189da8342e61d112a7d56d778de7562f7b609b82 | 3,656,507 |
def vgg11_bn(pretrained=False, **kwargs):
"""VGG 11-layer model (configuration "A") with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['A'], batch_norm=True)... | 3a8a03bd4a337143d56ed99ae89f2bbc3e312e63 | 3,656,508 |
def trf_input_method(config, patient_id="", key_namespace="", **_):
"""Streamlit GUI method to facilitate TRF data provision.
Notes
-----
TRF files themselves have no innate patient alignment. An option
for TRF collection is to use the CLI tool
``pymedphys trf orchestrate``. This connects to th... | 710a3f47e58ea5ed879cba6e51624072340308cf | 3,656,509 |
from datetime import datetime
def plotter(fdict):
""" Go """
ctx = get_autoplot_context(fdict, get_description())
station = ctx['station']
network = ctx['network']
year = ctx['year']
season = ctx['season']
nt = NetworkTable(network)
table = "alldata_%s" % (station[:2],)
pgconn = g... | ff07233d7c716715f1b4a414f0e2066222439925 | 3,656,510 |
from .. import sim
def connectCells(self):
"""
Function for/to <short description of `netpyne.network.conn.connectCells`>
Parameters
----------
self : <type>
<Short description of self>
**Default:** *required*
"""
# Instantiate network connections based on the connect... | 8f037f2ae6dbf8aab68c12fbbedcf71dd3ca6b31 | 3,656,511 |
import sys
def convert_numpy_str_to_uint16(data):
""" Converts a numpy.unicode\_ to UTF-16 in numpy.uint16 form.
Convert a ``numpy.unicode_`` or an array of them (they are UTF-32
strings) to UTF-16 in the equivalent array of ``numpy.uint16``. The
conversion will throw an exception if any characters c... | 7a16934c7c90ab373b88b4945641ea784bd5a144 | 3,656,512 |
import math
def _get_process_num_examples(builder, split, process_batch_size, process_index,
process_count, drop_remainder):
"""Returns the number of examples in a given process's split."""
process_split = _get_process_split(
split,
process_index=process_index,
proc... | a0621a6146e919db78b0ff5e7a5ae6d3c1bb68a6 | 3,656,513 |
def export_python_function(earth_model):
"""
Exports model as a pure python function, with no numpy/scipy/sklearn dependencies.
:param earth_model: Trained pyearth model
:return: A function that accepts an iterator over examples, and returns an iterator over transformed examples
"""
i = 0
ac... | 593d8cf9f1156359f2276f0481e02a2d00d8ffde | 3,656,514 |
def ehi(data, thr_95, axis=0, keepdims=False):
"""
Calculate Excessive Heat Index (EHI).
Parameters
----------
data: list/array
1D/2D array of daily temperature timeseries
thr_95: float
95th percentile daily mean value from climatology
axis: int
The axis along which ... | b56166dc070c9f44ce0d8197526c09ba2f95995c | 3,656,515 |
def make_transpose_tests(options):
"""Make a set of tests to do transpose."""
# TODO(nupurgarg): Add test for uint8.
test_parameters = [{
"dtype": [tf.int32, tf.int64, tf.float32],
"input_shape": [[2, 2, 3]],
"perm": [[0, 1, 2], [0, 2, 1]],
"constant_perm": [True, False],
}, {
"dt... | c6d28307d756b6475258f43893ca7811c69ff12d | 3,656,516 |
def get_disable_migration_module():
""" get disable migration """
class DisableMigration:
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
return DisableMigration() | d44a26c5e597f23dbc2434488baf54ebccc5010c | 3,656,517 |
import requests
def weather():
"""The weather route of My Weather API."""
# Load URL and KEY args of Current Weather API of OpenWeatherMap
api_url = app.config.get("API_URL")
api_key = app.config.get("API_KEY")
validators.check_emptiness('API_URL', api_url)
validators.check_emptiness('API_KEY'... | 927335cb4d2ca41f0fc81a43a4f5dec7ec92b264 | 3,656,518 |
def __sbox_bytes(data, sbox):
"""S-Box substitution of a list of bytes"""
return [__sbox_single_byte(byte, sbox) for byte in data] | db4999ada745c07127d9eff66841877a157839ec | 3,656,519 |
def load_config_with_kwargs(cls, kwargs):
"""Takes a marshmallow class and dict of parameter values and appropriately instantiantes the schema."""
assert_is_a_marshmallow_class(cls)
schema = cls.Schema()
fields = schema.fields.keys()
return load_config(cls, **{k: v for k, v in kwargs.items() if k in... | 9058becb8ae387ad012554ff0afe7ac5fcbf62f7 | 3,656,520 |
def split_rows(sentences, column_names):
"""
Creates a list of sentence where each sentence is a list of lines
Each line is a dictionary of columns
:param sentences:
:param column_names:
:return:
"""
new_sentences = []
root_values = ['0', 'ROOT', 'ROOT', 'ROOT', 'ROOT', 'ROOT', '0', ... | 444733a9c169bedae8dc0045cd696cafed7085e2 | 3,656,521 |
import secrets
import os
import shutil
def compute_pw_sparse_out_of_memory2(tr,
row_size = 500,
pm_processes = 2,
pm_pbar = True,
max_distance = 50,
... | be155db9bb8990a84e8005c5b58903f3e5a600fe | 3,656,522 |
def _rollup_date(dts, interval=None):
"""format date/time string based on interval spec'd for summation
For Daily, it returns just the date. No time or timezeone.
For Hourly, it returns an ISO-8061 datetime range. This provides previously
missing clarity around whether the rainfall amount shown was fo... | 12f74d9becfa52c626d33174cb628dc9e0112c07 | 3,656,523 |
def offset_compensation(time_signal):
""" Offset compensation filter.
"""
return lfilter([1., -1], [1., -0.999], time_signal) | 0fc423646071dc07bf88f88698f3248fa302a41e | 3,656,524 |
import subprocess
import sys
import os
def process_dir(thisdir):
"""Process /thisdir/ recursively"""
res = []
shellparams = {'stdin':subprocess.PIPE,'stdout':sys.stdout,'shell':True}
command = [utils.assimp_bin_path,"testbatchload"]
for f in os.listdir(thisdir):
if os.path.splitext(f)[-1]... | 6442bc6f0e77b56dc7f03ea457b59fd3ce14316b | 3,656,525 |
from typing import Callable
from re import T
from typing import cast
def _alias(default: Callable) -> Callable[[T], T]:
"""
Decorator which re-assigns a function `_f` to point to `default` instead.
Since global function calls in Python are somewhat expensive, this is
mainly done to reduce a bit of ove... | f286472a7f14428ea5243d54a671b9d3d743c9ef | 3,656,526 |
def test_image(filename):
"""
Return the absolute path to image file having *filename* in test_files
directory.
"""
return absjoin(thisdir, 'test_files', filename) | bda20e51a495e56f8ebf373819e60ebdea3da535 | 3,656,527 |
import difflib
def menu(
ticker: str,
start: str,
interval: str,
stock: pd.DataFrame,
):
"""Sector and Industry Analysis Menu"""
sia_controller = SectorIndustryAnalysisController(ticker, start, interval, stock)
sia_controller.call_help(None)
while True:
# Get input command fro... | 5c3d13d292525abdb5c7f98a2467274c2172cf8f | 3,656,528 |
def fname_template(orun, detname, ofname, nevts, tsec=None, tnsec=None):
"""Replaces parts of the file name specified as
#src, #exp, #run, #evts, #type, #date, #time, #fid, #sec, #nsec
with actual values
"""
template = replace(ofname, '#src', detname)
template = replace(template, '#exp',... | 7f38b638d89a7f99ab36b4e08369cfc7f22bb575 | 3,656,529 |
def opt_checked(method):
"""Like `@checked`, but it is legal to not specify the value. In this case,
the special `Unset` value is passed to the validation function. Storing
`Unset` causes the key to not be emitted during serialization."""
return Checked(method.__name__, method.__doc__, method, True) | 5d34db8fcc602dc51d69c128a1855eef44c81453 | 3,656,530 |
from datetime import datetime
def _metadata(case_study):
"""Collect metadata in a dictionnary."""
return {
'creation_date': datetime.strftime(datetime.now(), '%c'),
'imagery': case_study.imagery,
'latitude': case_study.lat,
'longitude': case_study.lon,
'area_of_interest... | eb16892135326662029fe568922f2871f016090e | 3,656,531 |
def CoP_constraints_ds(
m,
foot_angles,
next_support_foot_pos,
stateX,
stateY,
N=16,
dt=0.1,
h=1.0,
g=9.81,
tPf=8,
):
"""
INPUTS
m (int): remaining time steps in current foot step;
foot_angles ([N, 1] vector): containing the orientations in radians
of the foot... | 647e9313b79523ae41ab47a61501c1b356d43785 | 3,656,532 |
import io
def HARRIS(img_path):
"""
extract HARR features
:param img_path:
:return:
:Version:1.0
"""
img = io.imread(img_path)
img = skimage.color.rgb2gray(img)
img = (img - np.mean(img)) / np.std(img)
feature = corner_harris(img, method='k', k=0.05, eps=1e-06, sigma=1)
re... | 5c11c9e5b2947b0ddeb2e1780d11be4020fe53a4 | 3,656,533 |
import os
import pickle
def load_object(f_name, directory=None):
"""Load a custom object, from a pickle file.
Parameters
----------
f_name : str
File name of the object to be loaded.
directory : str or SCDB, optional
Folder or database object specifying the save location.
Ret... | d8809fd6b95bb894ec3aed4a1d0499fbc1ad77ea | 3,656,534 |
def http_req(blink, url='http://example.com', data=None, headers=None,
reqtype='get', stream=False, json_resp=True, is_retry=False):
"""
Perform server requests and check if reauthorization neccessary.
:param blink: Blink instance
:param url: URL to perform request
:param data: Data to... | 0596f82752292216235e9d9f3b14bb01f053d0d7 | 3,656,535 |
def make_dataset(path, seq_length, mem_length, local_rank, lazy=False, xl_style=False,
shuffle=True, split=None, tokenizer=None, tokenizer_type='CharacterLevelTokenizer',
tokenizer_model_path=None, vocab_size=None, model_type='bpe', pad_token=0, character_converage=1.0,
... | 419e50d3dab13d9aa1f096b99a598c52441bb2ae | 3,656,536 |
import re
def fix_reference_name(name, blacklist=None):
"""Return a syntax-valid Python reference name from an arbitrary name"""
name = "".join(re.split(r'[^0-9a-zA-Z_]', name))
while name and not re.match(r'([a-zA-Z]+[0-9a-zA-Z_]*)$', name):
if not re.match(r'[a-zA-Z]', name[0]):
name... | 2f1a291fc7ac9816bc2620fceeeaf90a1bb3fd4a | 3,656,537 |
import sys
def handle_args():
"""Handles arguments both in the command line and in IDLE.
Output:
Tuple, consisting of:
- string (input filename or stdin)
- string (output filename or stdout)
- integer (number of CPUs)
"""
version_num = "0.0.2"
# Tries to execute the script wit... | d93457881e81dde1a11412be418f54181ff15c2b | 3,656,538 |
import time
import traceback
import traceback
import imp
import traceback
import gc
def load_scripts(reload_scripts=False, refresh_scripts=False):
"""
Load scripts and run each modules register function.
:arg reload_scripts: Causes all scripts to have their unregister method
called before loading.... | a6e8186575eb7cb04d64ee650a77035d9adfb16c | 3,656,539 |
from hybridq.gate.gate import _available_gates
def get_available_gates() -> tuple[str, ...]:
"""
Return available gates.
"""
return tuple(_available_gates) | f4d9e8d617675174f97d7d1cc3d6ea8bdadab725 | 3,656,540 |
def main():
"""
Entry point
Collect all reviews from the file system (FS) &
Dump it into JSON representation back to the FS
Returns:
int: The status code
"""
collector = Collector()
return collector.collect() | d6d15227fe37522357a3f1706cf446026e277a32 | 3,656,541 |
def __parse_tokens(sentence: spacy.tokens.Doc) -> ParsedUniversalDependencies:
"""Parses parts of speech from the provided tokens."""
#tokenize
# remove the stopwards, convert to lowercase
#bi/n-grams
adj = __get_word_by_ud_pos(sentence, "ADJ")
adp = __get_word_by_ud_pos(sentence, "ADP")
adv... | 86553239aaac9d89203722f3853989ba0f95b8e3 | 3,656,542 |
from datetime import datetime
def main():
"""
In this main function, we connect to the database, and we create position table and intern table
and after that we create new position and new interns and insert the data into the position/intern
table
"""
database = r"interns.db"
sql_drop_posi... | 89b88d681b4f4eaeada0a8e8de5a3dadad1ddd15 | 3,656,543 |
from typing import Tuple
def parse_date(month: int, day: int) -> Tuple[int, int, int]:
"""Parse a date given month and day only and convert to
a tuple.
Args:
month (int): 1-index month value (e.g. 1 for January)
day (int): a day of the month
Returns:
Tuple[int, int, int]: (ye... | d9ebb40061c14c9a2b1336465921cea0d5c756a8 | 3,656,544 |
def usgs_perlite_parse(*, df_list, source, year, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param source: source
:param year: year
:return: df, parsed and partially formatted to flowbyactivity
specifications
"... | 8b9b1dcf3312cb59f5a27873e791c4bc744599bc | 3,656,545 |
import warnings
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
# token from https://github.com/bioinf-jku/TTUR/blob/master/fid.py
"""Numpy implementation of the Frechet Distance.
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
and X_2 ~ N(mu_2, C_2) is
... | 0f22ce0a99e9b8f2ffca7af4a190c020f376ce8c | 3,656,546 |
def _svdvals_eig(x): # pragma: no cover
"""SVD-decomposition via eigen, but return singular values only.
"""
if x.shape[0] > x.shape[1]:
s2 = np.linalg.eigvalsh(dag(x) @ x)
else:
s2 = np.linalg.eigvalsh(x @ dag(x))
return s2**0.5 | af47405994cf8fa1504fcb898b7621483eb1e346 | 3,656,547 |
def get_3d_object_section(target_object):
"""Returns 3D section includes given object like stl.
"""
target_object = target_object.flatten()
x_min = min(target_object[0::3])
x_max = max(target_object[0::3])
y_min = min(target_object[1::3])
y_max = max(target_object[1::3])
z_min = min(tar... | e11d62ad06ada005d16803b2f440ac700e272599 | 3,656,548 |
import os
def load_spectr_folder(path, result_format="xy"):
"""
Load a folder containing demod scope files.
Return a list of 6 elements (one pere demod), which are either ``None``, if there's not data for this demod, or contain that demod's trace.
"""
data=[]
for demod in range(1,7):
... | 3a84d180d9320ddd2722e2738dd710fb492bbb4d | 3,656,549 |
def make_row(filename, num_cols, col_names):
"""
Given a genome file, create and return a row of kmer counts
to be inerted into the mer matrix.
"""
# Filepath
thefile = str(filename[0])
# Get the genome id from the filepath
genomeid = filename[0].split('/')[-1]
genomeid = genomeid.s... | 59ed16c4a19da95145ed56164bc35ef24bc7f6bc | 3,656,550 |
def analytic_overlap_NM(
DQ: float,
w1: float,
w2: float,
n1: int,
n2: int
) -> float:
"""Compute the overlap between two displaced harmonic oscillators.
This function computes the overlap integral between two harmonic
oscillators with frequencies w1, w2 that are dis... | f0eba159f1bfb3fd05b1a825170e03e02587ef32 | 3,656,551 |
def init_manager(mocker):
"""Fixture to initialize a style constant."""
mocker.patch.object(manager.StyleManager, "__init__", lambda x: None)
def _create():
return manager.StyleManager()
return _create | da7838352c0a8c13acfcd0d345f78e329978409c | 3,656,552 |
def GaussLegendre(f, n):
"""Gauss-Legendre integration on [-1, 1] with n points."""
x, w = numint.GaussLegendre(n)
I = np.dot(f(x), w)
return I | 73fcd257e92852b56fcec7d0f21cbbcf87afdb51 | 3,656,553 |
from typing import List
from typing import Dict
from typing import OrderedDict
def directory_item_groups(
items: List[Item], level: int
) -> Dict[str, List[Item]]:
"""Split items into groups per directory at the given level.
The level is relative to the root directory, which is at level 0.
"""
mod... | 2a8e8138097ad48417f9988059a0ed19d63e4877 | 3,656,554 |
def mergeSort(x):
""" Function to sort an array using merge sort algorithm """
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = mergeSort(x[:middle])
b = mergeSort(x[middle:])
return merge(a,b) | 9187209cd9e679c790d0cddc18d58e6edc3e6d3a | 3,656,555 |
from typing import Union
from typing import Optional
from typing import Dict
from typing import Any
async def join(
db,
query: Union[dict, str],
document: Optional[Dict[str, Any]] = None,
session: Optional[AsyncIOMotorClientSession] = None,
) -> Optional[Dict[str, Any]]:
"""
Join the otu assoc... | d01dc90855692a149a279fbad9b8777d4a850a7d | 3,656,556 |
import time
import networkx
import math
def cp_solve(V, E, lb, ub, col_cov, cuts=[], tl=999999):
"""Solves a partial problem with a CP model.
Args:
V: List of vertices (columns).
E: List of edges (if a transition between two columns is allowed).
col_cov: Matrix of the zone coverages of ... | 6ad8ca02fcf119192e3aad4881a4eb9e0adf30d0 | 3,656,557 |
def file_exists(path: Text):
"""
Returns true if file exists at path.
Args:
path (str): Local path in filesystem.
"""
return file_io.file_exists_v2(path) | 9d9acf36ad0276a4fa440a54ed859b24e6bfee4e | 3,656,558 |
import requests
import json
def _get_page_num_detail():
"""
东方财富网-数据中心-特色数据-机构调研-机构调研详细
http://data.eastmoney.com/jgdy/xx.html
:return: int 获取 机构调研详细 的总页数
"""
url = "http://data.eastmoney.com/DataCenter_V3/jgdy/xx.ashx"
params = {
"pagesize": "5000",
"page": "1",
"j... | 84c32485637cb481f1ebe6fe05609e5b545daece | 3,656,559 |
def freeze_session(
session,
keep_var_names=None,
output_names=None,
clear_devices=True):
"""
Freezes the state of a session into a pruned computation graph.
"""
graph = session.graph
with graph.as_default():
freeze_var_names = list(set(v.op.name for v in tf.g... | ad8335110c139b73fb0c5cebb56dbdeea702a751 | 3,656,560 |
def send_mail(subject, body, recipient_list, bcc_list=None, from_email=None, connection=None, attachments=None,
fail_silently=False, headers=None, cc_list=None, dc1_settings=None, content_subtype=None):
"""
Like https://docs.djangoproject.com/en/dev/topics/email/#send-mail
Attachment is a list... | 36389b7f7e0906aa92ce06c66c4f51faa2643e31 | 3,656,561 |
def distinct_by_t(func):
"""
Transformation for Sequence.distinct_by
:param func: distinct_by function
:return: transformation
"""
def distinct_by(sequence):
distinct_lookup = {}
for element in sequence:
key = func(element)
if key not in distinct_lookup:
... | 3e2811b9f1b69b5c45f65a561b7f67ae477c8825 | 3,656,562 |
import os
def are_datasets_created(path, number_of_datasets, suffix='parts'):
"""Checks existence and reads the dataset ids from the datasets file in
the path directory
"""
dataset_ids = []
try:
with open("%s%sdataset_%s" % (path, os.sep, suffix)) as datasets_file:
for line... | 602d41071e01ade333b52524907d8a30ac8c25ac | 3,656,563 |
def _get_partition_info(freq_unit):
"""
根据平台单位获取tdw的单位和格式
:param freq_unit: 周期单位
:return: tdw周期单位, 格式
"""
if freq_unit == "m":
# 分钟任务
cycle_unit = "I"
partition_value = ""
elif freq_unit == "H":
# 小时任务
cycle_unit = "H"
partition_value = "YYYYMM... | 1f7df3364a21018daa8d3a61507ee59c467c8ffc | 3,656,564 |
from typing import Any
def metadata_property(k: str) -> property:
"""
Make metadata fields available directly on a base class.
"""
def getter(self: MetadataClass) -> Any:
return getattr(self.metadata, k)
def setter(self: MetadataClass, v: Any) -> None:
return setattr(self.metadat... | 22d3ab3c8a7029564083a6ba544acd69f2ee5491 | 3,656,565 |
import torch
def adjust_contrast(img, contrast_factor):
"""Adjust contrast of an RGB image.
Args:
img (Tensor): Image to be adjusted.
contrast_factor (float): How much to adjust the contrast. Can be any
non negative number. 0 gives a solid gray image, 1 gives the
origi... | 740c68fe269229329cd37d25424178a74f5ac7fc | 3,656,566 |
def license_wtfpl():
"""
Create a license object called WTF License.
"""
return mixer.blend(cc.License, license_name="WTF License") | d202d605fe84556c553fdc7cf70c5815eb1dbee4 | 3,656,567 |
import copy
def _add_embedding_column_map_fn(
k_v,
original_example_key,
delete_audio_from_output,
audio_key,
label_key,
speaker_id_key):
"""Combine a dictionary of named embeddings with a tf.train.Example."""
k, v_dict = k_v
if original_example_key not in v_dict:
raise ValueError(
... | 710fd658b0f1d830c8e4e97d473b02f54a0d4414 | 3,656,568 |
def modelf(input_shape):
"""
Function creating the model's graph in Keras.
Argument:
input_shape -- shape of the model's input data (using Keras conventions)
Returns:
model -- Keras model instance
"""
X_input = Input(shape = input_shape)
### START CODE HERE ###
... | d8beaf7335e19c66ea3913ed019647d9e42f92d1 | 3,656,569 |
def get_mbed_official_psa_release(target=None):
"""
Creates a list of PSA targets with default toolchain and
artifact delivery directory.
:param target: Ask for specific target, None for all targets.
:return: List of tuples (target, toolchain, delivery directory).
"""
psa_targets_release_li... | 0f260c1d57b0d21d911fcd6998fadee0791600de | 3,656,570 |
def match_l2(X, Y, match_rows=False, normalize=True):
"""Return the minimum Frobenius distance between X and Y over permutations of columns (or rows)."""
res = _match_factors(X, Y, l2_similarity, match_rows)
res['score'] = np.sqrt(-res['score'])
if normalize:
res['score'] = res['score'] / np.lin... | 181ecde4c0837b69f7a37287bcf9e768fdaa3e58 | 3,656,571 |
import time
import scipy
def doNMFDriedger(V, W, L, r = 7, p = 10, c = 3, plotfn = None, plotfnw = None):
"""
Implement the technique from "Let It Bee-Towards NMF-Inspired
Audio Mosaicing"
:param V: M x N target matrix
:param W: An M x K matrix of template sounds in some time order\
along ... | 3b3b0fe9388992bdd87cfa6b4cb0748f4502adc7 | 3,656,572 |
def extract_red(image):
""" Returns the red channel of the input image. It is highly recommended to make a copy of the
input image in order to avoid modifying the original array. You can do this by calling:
temp_image = np.copy(image)
Args:
image (numpy.array): Input RGB (BGR in OpenCV) image.
... | 0f591099e439a038ef8e75d65e4eb26c200018d0 | 3,656,573 |
def _cleaned_data_to_key(cleaned_data):
"""
Return a tuple representing a unique key for the cleaned data of an InteractionCSVRowForm.
"""
# As an optimisation we could just track the pk for model instances,
# but that is omitted for simplicity
key = tuple(cleaned_data.get(field) for field in DU... | aa08e0cafd0ac4ba3749db65208655dc51671997 | 3,656,574 |
def schedule_for_cleanup(request, syn):
"""Returns a closure that takes an item that should be scheduled for cleanup.
The cleanup will occur after the module tests finish to limit the residue left behind
if a test session should be prematurely aborted for any reason."""
items = []
def _append_clea... | ccbdba1a1f8dea0f13e5717d0743739d599e22e6 | 3,656,575 |
import base64
def unpickle_context(content, pattern=None):
"""
Unpickle the context from the given content string or return None.
"""
pickle = get_pickle()
if pattern is None:
pattern = pickled_context_re
match = pattern.search(content)
if match:
return pickle.loads(base64.... | 87fa831b038329313364d512107129f69db136ad | 3,656,576 |
def ask_openid(request, openid_url, redirect_to, on_failure=None,
sreg_request=None):
""" basic function to ask openid and return response """
on_failure = on_failure or signin_failure
trust_root = getattr(
settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
)
if xri.ide... | bb5deefc32d1c4253d518eeead34b290e028a051 | 3,656,577 |
import torch
def get_accuracy_ANIL(logits, targets):
"""Compute the accuracy (after adaptation) of MAML on the test/query points
Parameters
----------
logits : `torch.FloatTensor` instance
Outputs/logits of the model on the query points. This tensor has shape
`(num_examples, num_classe... | 2ab61284da6d9cd96c066061823570d64567e9f3 | 3,656,578 |
import logging
def stream_logger():
""" sets up the logger for the Simpyl object to log to the output
"""
logger = logging.Logger('stream_handler')
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
logger.addHandler(handler)
return logger | 45f5af00a0006cc8155bb4a134cce531e51e646a | 3,656,579 |
def sql_coordinate_frame_lookup_key(bosslet_config, coordinate_frame):
"""
Get the lookup key that identifies the coordinate fram specified.
Args:
bosslet_config (BossConfiguration): Bosslet configuration object
coordinate_frame: Identifies coordinate frame.
Returns:
coordinate... | 8bf7db01b171e13b0066a806eb097dec4a59c04e | 3,656,580 |
def entry_from_resource(resource, client, loggers):
"""Detect correct entry type from resource and instantiate.
:type resource: dict
:param resource: One entry resource from API response.
:type client: :class:`~google.cloud.logging.client.Client`
:param client: Client that owns the log entry.
... | 0519ad63c11e04ca890288953440272de224b9db | 3,656,581 |
def make_preprocesser(training_data):
"""
Constructs a preprocessing function ready to apply to new dataframes.
Crucially, the interpolating that is done based on the training data set
is remembered so it can be applied to test datasets (e.g the mean age that
is used to fill in missing values for '... | 480ba5b02e5347e768bd5b2cdbc8b19af1ddee8c | 3,656,582 |
def get_breakeven_prob(predicted, threshold = 0):
"""
This function calculated the probability of a stock being above a certain threshhold, which can be defined as a value (final stock price) or return rate (percentage change)
"""
predicted0 = predicted.iloc[0,0]
predicted = predicted.iloc[-1]
p... | a1cededbe7a0fbe7ffe19e9b873f55c8ce369590 | 3,656,583 |
def trim_whitespace(sub_map, df, source_col, op_col):
"""Trims whitespace on all values in the column"""
df[op_col] = df[op_col].transform(
lambda x: x.strip() if not pd.isnull(x) else x)
return df | 649a48cbb9246d4842555b5a21bc4d638a00ca00 | 3,656,584 |
from re import A
from re import T
def beneficiary():
""" RESTful CRUD controller """
# Normally only used in Report
# - make changes as component of Project
s3db.configure("project_beneficiary",
deletable = False,
editable = False,
insertable =... | ec34dd0989154bcfe2ace8506fe1cbe9c1ba9c49 | 3,656,585 |
def setup(args):
"""
Create configs and perform basic setups.
"""
cfg = get_cfg()
#cfg.merge_from_file(args.config_file)
#cfg.merge_from_file(model_zoo.get_config_file("/data/mostertrij/tridentnet/detectron2/configs/COCO-Detection/my_script_faster_rcnn_X_101_32x8d_FPN_3x.yaml"))
cfg.merge_fr... | a3053945cd6680c220fe8ea87189943c44558d8d | 3,656,586 |
def get_distinct_quotation_uid(*args, **kwargs):
"""
获取用户
:param args:
:param kwargs:
:return: List
"""
field = 'uid'
return map(lambda x: getattr(x, field), db_instance.get_distinct_field(Quotation, field, *args, **kwargs)) | 5a8fe7252f6ac233b69e57c0baac0f1f2d3f51ff | 3,656,587 |
import pathlib
def present_from(ref: pathlib.Path, obs: pathlib.Path) -> pathlib.Path:
"""Build a somehow least surprising difference folder from ref and obs."""
ref_code = ref.parts[-1]
if obs.is_file():
return pathlib.Path(*obs.parts[:-1], f'diff-of-{obs.parts[-1]}')
present = pathlib.Path(... | 59ae1eefaeacc9ddfac773c0c88974b98757d4a2 | 3,656,588 |
def dataQ_feeding(filename_queue, feat_dim, seq_len):
""" Reads and parse the examples from alignment dataset
Args:
filename_queue: A queue of strings with the filenames to read from.
Returns:
An object representing a single example, with the following fields:
MFCC sequence: 200 * 39 d... | 23d3e81bdd266f6cebe9bdff2160c4b7294e648c | 3,656,589 |
def dummy_backend(_, **kwargs):
"""
Dummy backend always returning stats with 0
"""
return _default_statement() | 875adb50540029022b28de6388738d1e5ba01e30 | 3,656,590 |
def comp_mass(self):
"""Compute the mass of the Frame
Parameters
----------
self : Frame
A Frame object
Returns
-------
Mfra: float
Mass of the Frame [kg]
"""
Vfra = self.comp_volume()
# Mass computation
return Vfra * self.mat_type.struct.rho | b78ef02f045c1f624b3277ec3e358921b3ea5c02 | 3,656,591 |
def write_DS9reg(x, y, filename=None, coord='IMAGE', ptype='x', size=20,
c='green', tag='all', width=1, text=None):
"""Write a region file for ds9 for a list of coordinates.
Taken from Neil Crighton's barak.io
Parameters
----------
x, y : arrays of floats, shape (N,)
The c... | 9e2c67c8a681ba7abdd55e7f456079b32ed50688 | 3,656,592 |
def checkInputDataValid(lstX:list=None,lstY:list=None,f:object=None)->(int,tuple):
"""
:param lstX:
:param lstY:
:param f:
:return: int, (int,list, int,int)
"""
ret=-1
rettuple=(-1,[],-1,-1)
if lstX is None or lstY is None:
msg = "No input lists of arrays"
msg2log(No... | daacee0ee3803c02c04fe2b7213c6f8d408b39f6 | 3,656,593 |
def parseManualTree(node):
"""Parses a tree of the manual Main_Page and returns it through a list containing tuples:
[(title, href, [(title, href, [...]), ...]), ...]"""
if node.nodeType != Node.ELEMENT_NODE: return []
result = []
lastadded = None
for e in node.childNodes:
if e.nodeType ... | 6b62e9ad3b3ef4f3a0c6c60a931f1f2e940fe0f9 | 3,656,594 |
from typing import Union
from typing import List
from typing import Dict
from typing import Optional
from typing import Tuple
import tqdm
def validation_by_method(mapping_input: Union[List, Dict[str, List]],
graph: nx.Graph,
kernel: Matrix,
k:... | b7ce9e72af55dc6d111948cb393f5e07b7fedd68 | 3,656,595 |
def get_about_agent():
"""
This method returns general information of the agent, like the name and the about.
Args:
@param: token: Authentication token.
"""
data = request.get_json()
if "token" in data:
channel = get_channel_id(data["token"])
if channel is not None:
... | ca4301a9de5d4cb711892a221d4c984489c1e329 | 3,656,596 |
from io import StringIO
def add_namespace(tree, new_ns_name, new_ns_uri):
"""Add a namespace to a Schema.
Args:
tree (etree._ElementTree): The ElementTree to add a namespace to.
new_ns_name (str): The name of the new namespace. Must be valid against https://www.w3.org/TR/REC-xml-names/#NT-NS... | acd187389ef6de08aec2c4760212af40d4083fd1 | 3,656,597 |
def RZ(angle, invert):
"""Return numpy array with rotation gate around Z axis."""
gate = np.zeros(4, dtype=complex).reshape(2, 2)
if not invert:
gate[0, 0] = np.cos(-angle/2) + np.sin(-angle/2) * 1j
gate[1, 1] = np.cos(angle/2) + np.sin(angle/2) * 1j
else:
gate[0, 0] = np.cos(-an... | d99839fa49d92edea8d98653fd7a38861e6f49d8 | 3,656,598 |
def _create_unicode(code: str) -> str:
"""
Добавление экранизирующего юникод кода перед кодом цвета
:param code: Код, приоритетно ascii escape color code
:return:
"""
return u'\u001b[{}m'.format(code) | 523973766d4f18daca8870e641ac77967b715532 | 3,656,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.