content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import math
def schedule_exp(initial_value):
"""
Exponential decay learning rate schedule.
:param initial_value: (float or str)
:return: (function)
"""
def func(progress):
"""
Progress will decrease from 1 (beginning) to 0
:param progress: (float)
:return: (fl... | 5d13bbd63c2a3e78ce921cb5e6fb6a38f4f729bb | 3,628,200 |
def home(request):
"""
main view that handles rendering home page
"""
all_images = UserPost.objects.all()
all_users = User.objects.exclude(id=request.user.id)
if request.method == 'POST':
form = UserPostForm(request.POST, request.FILES)
if form.is_valid():
post = form... | cf8fb596b1ba40dcb37d2bfc49cdcc4ad3f757f4 | 3,628,201 |
def get_table_id(table):
"""
Returns id column of the cdm table
:param table: cdm table name
:return: id column name for the table
"""
return table + '_id' | 33fd8f445f15fb7e7c22535a31249abf6f0c819b | 3,628,202 |
from typing import Sequence
from typing import Hashable
def all_items_present(sequence: Sequence[Hashable], values: Sequence[Hashable]) -> bool:
"""
Check whether all provided `values` are present at any index
in the provided `sequence`.
Arguments:
sequence: An iterable of Hashable values to ... | f43a881159ccf147d3bc22cfeb261620fff67d7a | 3,628,203 |
import shutil
def lnpost_hr4796aH2spf(var_values = None, var_names = None, path_obs = None, path_model = None, calcSED = False, hash_address = True, calcImage = False, calcSPF = True, Fe_composition = False, pit = False, pit_input = None):
"""Returns the log-posterior probability (post = prior * likelihood, thus ... | 8f554959b042392afbcf5bcfc08bbc63eb1da867 | 3,628,204 |
def reorder(rules):
""" Set in ascending order a list of rules, based on their score.
"""
return(sorted(rules, key = lambda x : x.score)) | cf4ff3b8d8aacd5e868ee468b37071fed2c1d67e | 3,628,205 |
def expand_np_candidates(np, stemming):
"""
Create all case-combination of the noun-phrase (nyc to NYC, israel to Israel etc.)
Args:
np (str): a noun-phrase
stemming (bool): True if to add case-combinations of noun-phrases's stem
Returns:
list(str): All case-combination of the ... | 3afe020bdec4d159a3ba5e186cb1a74492935c94 | 3,628,206 |
def gantt_chart(username, root_wf_id, wf_id):
"""
Get information required to generate a Gantt chart.
"""
dashboard = Dashboard(g.master_db_url, root_wf_id, wf_id)
gantt_chart = dashboard.plots_gantt_chart()
d = []
for i in range(len(gantt_chart)):
d.append(
{
... | 2640ffe378c08fed01f6fe6f23939eece9c89b4a | 3,628,207 |
def read_sharepoint_excel(file_path, host, site, library, credentials,
token_filepath=None, **kwargs):
""" Returns a panda DataFrame with the contents of a Sharepoint list
:param str file_path: a file path to an excel file in sharepoint
within a site's library (i.e. /General/file.xlsx)
:... | 66e745913e3c3161e733e35d2b79f4235d4b4df5 | 3,628,208 |
def XDoG(img, sigma=0.5, k=1.6, tau=0.98, epsilon=0.1, phi=10):
"""
Improve thresholding with a tanh
"""
# Get a DoG
aux = DoG(img, sigma=sigma, k=k, tau=tau)/255
# Thresholding
for i in range(aux.shape[0]):
for j in range(aux.shape[1]):
if aux[i, j] >= epsilon:
aux[i, j] = 1 # white!
else:
aux[... | 2679505db9c8272f0e6abcf1cf793c096a8d0f8e | 3,628,209 |
def calc_gcc_weights(ks_calib, num_virtual_channels, correction=True):
"""Calculate coil compression weights.
Input
ks_calib -- raw k-space data of dimensions (num_kx, num_readout, num_channels)
num_virtual_channels -- number of virtual channels to compress to
correction -- apply rotation cor... | d3754859c4e36d03d0e32431d91c0307df692592 | 3,628,210 |
def _ontology_info_url(curie):
"""Get the to make a GET to to get information about an ontology term."""
# If the curie is empty, just return an empty string. This happens when there is no
# valid ontology value.
if not curie:
return ""
else:
return f"{OLS_API_ROOT}/ontologies/{_ont... | 95a56a97e100387306bccb50d523fc7e41c4f8b2 | 3,628,211 |
def _is_LoginForm_in_this_page(driver):
""" 用于判断一个页面是否有账号密码框 """
try:
get_username_input(driver)
get_password_input(driver)
except Errors.LoginFormIsNotFound:
return False
else:
return True | e5ffb5cf512ff35821ebb0f723528102957c3ba2 | 3,628,212 |
def get_native_instance() -> native.new_word_finder.NewWordFinder:
"""
返回原生NLPIR接口,使用更多函数
:return: The singleton instance
"""
return __instance__ | 7b9604fcab328149ad185b3883f8a287e5a45873 | 3,628,213 |
def reconstruct(analysis):
"""Main reconstruct method"""
reconstruction = Reconstruction(analysis)
reconstruction.reconstruct()
return reconstruction.data | 253ac1bd62bb683823e39d9fda4493466f9b4226 | 3,628,214 |
import six
def validate_str(value=None, min_length=None, max_length=None, required=True, name=None):
""" validate string """
name_str = __name(name)
# no input / no required
if not value and not required:
return True
if not value and required:
raise TypeError(('{name_str} expected str, string must be inpu... | 15ccf4e4b4cd4143c513ee7fc26cf3b5fdbb8a5c | 3,628,215 |
from typing import Dict
def ore_required_for(target: Reactant, reactions: Dict[str, Reaction]) -> int:
"""Return the units of ORE needed to produce the target."""
ore = 0
excess: Dict[str, int] = defaultdict(int)
needed = [target]
while needed:
cur = needed.pop()
if cur.ID == "OR... | 8670a9903c8777f88db4566833096a04174ca76f | 3,628,216 |
from typing import Union
from typing import List
def list_available_dbms(connection: "Connection", to_dictionary: bool = False, limit: int = None,
**filters) -> Union[List["Dbms"], List[dict]]:
"""List all available database management systems (DBMSs) objects or dicts.
Optionally filte... | ca45a956890186d721a40cc623c00ea33d148fea | 3,628,217 |
def loop():
""" Main loop running the bot """
# Initialize the light sensor. Note that the Gpio library
# returns strings...
sensorpin = CFG.get("cfg", "light_sensor_pin")
sensor = onionGpio.OnionGpio(int(sensorpin))
status = int(sensor.setInputDirection())
# Check sensor status
if statu... | a142a46a5f2cc22fa37068891b5fd8f6c6c1a848 | 3,628,218 |
import io
def csv_encode(data: np.ndarray) -> bytes:
"""Encodes a NumPy array in CSV.
:param: data: NumPy array to encode
"""
with io.BytesIO() as buffer:
np.savetxt(buffer, data, delimiter=",")
return buffer.getvalue() | 334ee81d47cb3b8a5c459856c82839e4e7b3da79 | 3,628,219 |
def _calculate_global_step(current_step: int) -> int:
"""Calculate the current global step given the current iteration step."""
global_step = 0
for step in range(current_step):
global_step += n_optimize_fn(step)
return global_step | f78cb5553cfd1134f75bd65805e0e490882b5ca2 | 3,628,220 |
def _format_optvalue(value, script=False):
"""Internal function."""
if script:
# if caller passes a Tcl script to tk.call, all the values need to
# be grouped into words (arguments to a command in Tcl dialect)
value = _stringify(value)
elif isinstance(value, (list, tuple)):
v... | 6f8123050e3249e2e038684d4324aff5181b6dc4 | 3,628,221 |
def scheme_to_str(exp):
"""Convert a Python object back into a Scheme-readable string."""
if isinstance(exp, ltypes.List):
return "(" + " ".join(map(scheme_to_str, exp)) + ")"
return str(exp) | 1fe7f4e557c2ba2b5a0c3876c3b8e6787c45bfa2 | 3,628,222 |
from datetime import datetime
def utcTimeFromUTCTimestamp(utcTimestamp: int):
"""
Args:
utcTimestamp: number of seconds since 1970-01-01 00:00:00 UTC
Returns: a (non-timezone aware) datetime object representing the same time as utcTimestamp, in UTC time
"""
return datetime.datetime.utcf... | 57c9e7351bb87a3e5ac6770076539c7164e3c6dc | 3,628,223 |
import re
def extract_floats(string):
"""Extract all real numbers from the string into a list (used to parse the CMI gateway's cgi output)."""
return [float(t) for t in re.findall(r'[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?', string)] | 0dc26261d45bd0974e925df5ed660a6e31adf30c | 3,628,224 |
import random
def ProbToSequence_Nitem2_Order1(Prob):
"""
Return a random sequence of observations generated based on Prob, a
sequence of first-order transition probability. In other words, the sequence
follows a first-order Markov chain.
Prob is a np array.
"""
length = Prob.shape[1]
... | 7e73cbf6249d21fb5980614079bb16acead4fdfd | 3,628,225 |
def binary(n, digits):
"""Returns a tuple of (digits) integers representing the
integer (n) in binary. For example, binary(3,3) returns (0, 1, 1)"""
t = []
for i in range(digits):
n, r = divmod(n, 2)
t.append(r)
return tuple(reversed(t)) | bc52a985b86954b1d23bb80a14c56b3e3dfb7c59 | 3,628,226 |
def build_results(interactions: pd.DataFrame,
mean_analysis: pd.DataFrame,
percent_analysis: pd.DataFrame,
clusters_means: dict,
complex_compositions: pd.DataFrame,
counts: pd.DataFrame,
genes: pd.DataFrame,
... | 5d8d5dea8adf0e4fa6798ddf295555895241f653 | 3,628,227 |
from typing import Tuple
def load_mnist(data_node_name, label_node_name, *args, normalize=True, folder='', **kwargs) -> Tuple[Dataset, Dataset]:
""" Returns the training and testing Dataset objects for MNIST.
@param data_node_name The graph node name for the data inputs.
@param label_node_name The... | 4d84d7c17528bc391cafa97f3da7caf3ad6181d6 | 3,628,228 |
def test_api_group_in_role_template(admin_mc, admin_pc, user_mc,
remove_resource):
"""Test that a role moved into a cluster namespace is translated as
intended and respects apiGroups
"""
# If the admin can't see any nodes this test will fail
if len(admin_mc.client... | d2bb334bd7fa27f19347a03e58f95341d0db3156 | 3,628,229 |
def voc_ap(rec, prec):
"""
Compute VOC AP given precision and recall.
Taken from https://github.com/marvis/pytorch-yolo2/blob/master/scripts/voc_eval.py
Different from scikit's average_precision_score (https://github.com/scikit-learn/scikit-learn/issues/4577)
"""
# first append sentinel values a... | 428bbdb9883d2b38a7bcdafa1a678305989c3904 | 3,628,230 |
import sympy
def GetShapeFunctionDefinitionLine3D3N(x,xg):
""" This computes the shape functions on 3D line
Keyword arguments:
x -- Definition of line
xg -- Gauss point
"""
N = sympy.zeros(3)
N[1] = -(((x[1,2]-x[2,2])*(x[2,0]+x[2,1]-xg[0]-xg[1])-(x[1,0]+x[1,1]-x[2,0]-x[2,1])*(x[2,2]-xg[2]... | aaa2f5b7afac4afc60d2b79ef3f22fba3553aabb | 3,628,231 |
def get_next_version(release_type):
"""Increment a version for a particular release type."""
if not isinstance(release_type, ReleaseType):
raise TypeError()
version = Version(get_current_version())
if release_type is ReleaseType.major:
return str(version.next_major())
if release_t... | f8a3be4195ed971a5bfadb86163ff6bdcfab1ab8 | 3,628,232 |
from crits.core.user import CRITsUser
def get_user_subscriptions(user=None):
"""
Get user subscriptions.
:param user: The user to query for.
:type user: str or CRITsUser
:returns: str
"""
if user is None:
return None
if not hasattr(user, 'username'):
user = str(user)... | b6b3eb0bc03646939394ce8c495ea543c5d566d9 | 3,628,233 |
import os
def picasso() -> dict:
"""Handler for service discovery
:returns: picasso service descriptor
:rtype: dict
"""
return {"app": "demo-man", "svc": "picasso", "version": os.environ["VERSION"]} | d8e8fe0ca6287536143149edd47c2e42f932a515 | 3,628,234 |
def calc_zvals(opt: Optimizer, std_errors=None,
information='expected'):
"""Calculates z-scores.
Keyword arguments:
opt -- Optimizer containing proper parameters' values.
std_errors -- Standard errors in case they were already calculated.
... | c344791c7632ae75270a22320b604e0bdad81f50 | 3,628,235 |
from rx.core.operators.observeon import _observe_on
import typing
from typing import Callable
def observe_on(scheduler: typing.Scheduler) -> Callable[[Observable], Observable]:
"""Wraps the source sequence in order to run its observer callbacks
on the specified scheduler.
Args:
scheduler: Schedul... | d803cfb77cca5550d6b9a46b4d40816125a123f0 | 3,628,236 |
def generate_grande_signature_regex(signataire_titre):
"""
Create a regex for a grande signature using the appropriate titres (main signatory, or secretary)
signataire_titre : the list of usable titres (president, conseiller national, secretaire...) for the signature
Return : (grande_signature_regex, ti... | 52a0221fdbd3fc33f41162c59acad71b315511ca | 3,628,237 |
def list_product_images():
"""Retrieve a paginated list of product images with optional filters."""
shelf_image_id = request.args.get('shelfImageId')
print(shelf_image_id)
upc = request.args.get('upc')
review_status = request.args.get('reviewStatus')
skip = int(request.args.get('skip', 0))
l... | 29d2b0ad73a374e28d69618217258eaf617f0636 | 3,628,238 |
from typing import Dict
from typing import Any
import yaml
def variables() -> Dict[str, Any]:
"""Contents of ruinway.variables.yml."""
return yaml.safe_load((CURRENT_DIR / "runway.variables.yml").read_bytes()) | c17834814f5a91103760bc2f6a5a1beb0e3ab63f | 3,628,239 |
def csi_fsmn(
frame,
l_filter,
r_filter,
frame_sequence,
frame_counter,
l_order,
r_order,
l_stride,
r_stride,
unavailable_frames,
out_dtype,
q_params,
layer_name="",
):
"""Quantized fsmn operator.
Parameters
----------
Input : tvm.te.Tensor
2-... | 1b2d99eaf38e007a52fc4788c2e8c03238b59c0b | 3,628,240 |
def get_line_context(line: str) -> tuple[str, None] | tuple[str, str]:
"""Get context of ending position in line (for completion)
Parameters
----------
line : str
file line
Returns
-------
tuple[str, None]
Possible string values:
`var_key`, `pro_line`, `var_only`, `... | 5f2bd8fafd71c69ae78dbe4cfeb790537a72753d | 3,628,241 |
def list_accounts_for_identity(identity_key, id_type):
"""
Returns a list of all accounts for an identity.
:param identity: The identity key name. For example x509 DN, or a username.
:param id_type: The type of the authentication (x509, gss, userpass, ssh, saml).
returns: A list of all accounts fo... | d6dd84ec6a2ea4b5604501c84f537b75f5a6718e | 3,628,242 |
def test_champion_itemsets(champion_name, champion_data, all_items):
"""Test the item sets recommended for a champion are consistent.
Return a list of errors that were encountered."""
itemset_data = champion_data["data"][champion_name]["recommended"]
all_items_data = all_items['data']
errors = list... | 37f1d23a223d3f1d6331f31e7b16fc52cf542a13 | 3,628,243 |
from typing import Any
from typing import Tuple
def to_tuple(
value: Any,
length: int = 1,
) -> Tuple[TypeNumber, ...]:
"""
to_tuple(1, length=1) -> (1,)
to_tuple(1, length=3) -> (1, 1, 1)
If value is an iterable, n is ignored and tuple(value) is returned
to_tuple((1,), le... | 6fa9b38fe040b1e16f016a12b288436a50a35ee2 | 3,628,244 |
import sys
def main():
"""Console script for copyright_automation."""
parse_args(sys.argv[1:])
return 0 | fd6b126e6ecc4126aea7c67631f6998c9e59f33f | 3,628,245 |
def makenodelogin():
"""make a node login
"""
if request.method == 'POST':
ipaddr=request.form['ip']
iqn=request.form['iqn']
cmdres="iscsiadm -m node "+ iqn + "-p " +ipaddr + "-o update -n node.startup -v automatic"
res=cmdline(cmdres)
return Response(response=res,sta... | 1a05d92ed6e699969254d0753e3ea213ad998af2 | 3,628,246 |
def _sorted_photon_data_tables(h5file):
"""Return a sorted list of keys "photon_dataN", sorted by N.
If there is only one "photon_data" (with no N) it returns the list
['photon_data'].
"""
prefix = 'photon_data'
ph_datas = [n for n in h5file.root._f_iter_nodes()
if n._v_name.sta... | a8df6edb5cfa9b328d7648e0c9ab9f883812ee5a | 3,628,247 |
from typing import Any
def apatch(mocker: MockerFixture):
"""Return a function that let you patch an async function."""
def patch(target: str, return_value: Any):
return mocker.patch(target, side_effect=mocker.AsyncMock(return_value=return_value))
yield patch | 159a5087754a9b4befaae61b68244c76277e3cf3 | 3,628,248 |
def test():
"""
定义一个reader来获取测试数据集及其标签
Args:
Return:
read_data: 用于获取测试数据集及其标签的reader
"""
global TEST_SET
return read_data(TEST_SET) | 195eaeb2f1a54cf3419a807c5a180498034449f9 | 3,628,249 |
def structure_sample_ks_convergence_diagnostics(fit, max_nonzero=None,
indicator_var='k',
batch=True, **kwargs):
"""Calculate chi squared convergence diagnostics."""
if batch and hasattr(fit, 'warmup_posterior'):
... | 96933c359c31bf0f4db5da1c5415034ca5192f2c | 3,628,250 |
def prepare_wld(bbox, mwidth, mheight):
"""Create georeferencing world file"""
pixel_x_size = (bbox.maxx - bbox.minx) / mwidth
pixel_y_size = (bbox.maxy - bbox.miny) / mheight
left_pixel_center_x = bbox.minx + pixel_x_size * 0.5
top_pixel_center_y = bbox.maxy - pixel_y_size * 0.5
return ''.join(... | 668c348d74780a79a39ebc53f3f119ea37855e8e | 3,628,251 |
def graphql_refresh_token_mutation(client, variables):
"""
Refreshes an auth token
:param client:
:param variables: contains a token key that is the token to update
:return:
"""
return client.execute('''
mutation refreshTokenMutation($token: String!) {
refreshToken(token: $to... | c217217b289a188de8709dbe875853329d2c3fbc | 3,628,252 |
def sintef_d50(u0, d0, rho_p, mu_p, sigma, rho):
"""
Compute d_50 from the SINTEF equations
Returns
-------
d50 : float
Volume median diameter of the fluid phase of interest (m)
Notes
-----
This function is called by the `sintef()` function after several
intermedia... | c6cad2e32ddaf0b254ad118a80ed29e0ac49e88a | 3,628,253 |
import os
import glob
def get_jinja2_function_names():
"""Gets functions dynamically from python files.
Returns:
list: List of function names form python files.
"""
function_names = []
python_files = [y[9:-3] for x in os.walk("netutils/") for y in glob(os.path.join(x[0], "*.py"))]
fil... | 26ec50ff666a2c7d1e4d8345f1287ab089f7be0e | 3,628,254 |
def check_duplicate_stats(stats1, stats2, threshold=0.01):
"""
Check two lists of paired statistics for duplicates.
Returns a list of the pairs that agree within to <1%.
INPUTS:
STATS1 : List of first statistical metric, e.g. Standard Deviations
STATS2 : List of second statistical metric, e.g.... | eb75d9d02a92cdb337dcbc100b282773543ac894 | 3,628,255 |
def get_width(panel: Panel) -> int:
"""Return the width of the panel"""
if isinstance(panel, RowPanel):
return GRID_WIDTH
if panel.gridPos is None:
return 0 # unknown width
return panel.gridPos.w | 2e2542a51d517062fdd82f9c80932167d8da855b | 3,628,256 |
def tensor_abs(inputs):
"""Apply abs function."""
return P.Abs()(inputs) | 5635018e4186601ff2579a7aaf9329b73d3ba601 | 3,628,257 |
import re
def _parse_uci_regression_dataset(name_str):
"""Parse name and seed for uci regression data.
E.g. yacht_2 is the yacht dataset with seed 2.
"""
pattern_string = "(?P<name>[a-z]+)_(?P<seed>[0-9]+)"
pattern = re.compile(pattern_string)
matched = pattern.match(name_str)
if matched:
name = ma... | dd2158e1a5ceeba25a088b07ff8064e8016ae551 | 3,628,258 |
import requests
import json
def http_request(method, path, other_params=None):
"""
HTTP request helper function
Args:
method: HTTP Method
path: part of the url
other_params: Anything else that needs to be in the request
Returns: request result
"""
params = {'app_partn... | 281ddd467d0d8854495d7235ae06e381ef0790bf | 3,628,259 |
def preprocess(text, remove_punct=False, remove_num=True):
"""
preprocess text into clean text for tokenization
"""
# 1. normalize
text = normalize_unicode(text)
# 2. remove new line
text = remove_newline(text)
# 3. to lower
text = text.lower()
# 4. de-contract
text = decontr... | 8debaa593904219620e43ffe5f4805219f57fd3b | 3,628,260 |
def get_world_trans(m_obj):
"""
Extracts the translation from the worldMatrix of the MObject.
Args:
m_obj
Return:
trans
"""
plug = get_world_matrix_plug(m_obj, 0)
matrix_obj = plug.asMObject()
matrix_data = oMa.MFnMatrixData(matrix_obj)
matrix = matrix_data.matrix()
... | 72d1459b32ba2d27f60e9445fa9513ab6cfbf3e4 | 3,628,261 |
import time
import subprocess
import sys
import signal
import logging
import os
def cmd_exe(cmd, timeout=-1, cap_stderr=True, pipefail=False):
"""
Executes a command through the shell.
timeout in minutes! so 1440 mean is 24 hours.
-1 means never
returns namedtuple(ret_code, stdout, stderr, run_tim... | 706fd40fd4db2799a89bc56ce46a8d9c8c697c3b | 3,628,262 |
def isip46(value):
"""Assert value is a valid IPv4 or IPv6 address.
On Python < 3.3 requires ipaddress module to be installed.
"""
import ipaddress # requires "pip install ipaddress" on python < 3.3
if not isinstance(value, basestring):
raise ValidationError("expected a string, got %r" % va... | a511048469ec231667735e7c3028807c0faf90a9 | 3,628,263 |
def wrap_with_arctan_tan(angle):
""" Normalize angle to be in the range of [-np.pi, np.pi[.
Beware! Every possible method treats the corner case -pi differently.
>>> wrap_with_arctan_tan(-np.pi)
-3.141592653589793
>>> wrap_with_arctan_tan(np.pi)
3.141592653589793
:param angle: Angle as nu... | 351e230eac5b5650ddefb22075709f0b4c185761 | 3,628,264 |
import re
def get_params(proto):
""" get the list of parameters from a function prototype
example: proto = "int main (int argc, char ** argv)"
returns: ['int argc', 'char ** argv']
"""
paramregex = re.compile('.*\((.*)\);')
a = paramregex.findall(proto)[0].split(', ')
#a = [i.replace('cons... | 37841b2503f53353fcbb881993e8b486c199ea58 | 3,628,265 |
def _preprocess(state, mode='min-max-1'):
"""
Implements preprocessing of `state`.
Parameters
----------
state : np.array
2D array of features. rows are variables and columns are features.
Return
------
(np.array) : same shape as state but with transformed variables
"""
... | 90d6f0efd4c9de6b6b8639680d8a1809d6ef7962 | 3,628,266 |
def _parse_basic_txt_scorefile(file, epoch_len=pysleep_defaults.epoch_len):
"""
Parse the super basic sleep files from Dinklmann
No starttime is available.
:param file:
:return:
"""
dict_obj = {"epochstages": [], "epochoffset": 0}
for line in file:
temp = line.split(' ')
... | 6ad11f2258fac4951d81152788318e33f1b204e9 | 3,628,267 |
import math
def DominantModeStructured(amps, dt, N = 250):
"""
Compute the period and amplitude of the dominant mode in an even data series.
"""
def Omegas(ts):
return [2.0 * math.pi / t for t in ts]
nScans = len(amps)
times = [i * dt for i in range(nScans)]
tMin = 2.0 * dt
tMax = nScan... | 9df963b51117a579df63dcdf76120c58b5bc5cdc | 3,628,268 |
def decode_record(record, name_to_features=name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.io.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):... | 559950a440d2f86e3ae3a4def5c431912b9b37a3 | 3,628,269 |
import argparse
import difflib
def parse_arguments(description):
"""Parse the arguments for the scripts."""
parser = argparse.ArgumentParser(description=description)
task = "lab"
parser.add_argument(
"-n", "--name", type=str, help=f"name of {task}", default="all", dest="name"
)
args ... | b530d41b2fd49018bf9246b0440dde1eac8b4b52 | 3,628,270 |
def have_color(parent, is_levels=False):
"""Checks that the color directories have images.
Args:
parent: class instance
is_levels (bool, optional): Whether or not to use full-size (False) or
level_0 images (True).
Returns:
dict[str, bool]: Map of color directories and w... | cb8d1ad7a8d9927fa48bfecc37e21015910415d2 | 3,628,271 |
from typing import Match
import re
def _IsType(clean_lines, nesting_state, expr):
"""Check if expression looks like a type name, returns true if so.
Args:
clean_lines: A CleansedLines instance containing the file.
nesting_state: A NestingState instance which maintains information about
... | eb7be397e2d4e583ac3a63293c467a78cb8dbba7 | 3,628,272 |
import requests
def return_figures(countries=country_default, start_year=1990, end_year=2014):
"""Creates four plotly visualizations using the World Bank API
# Example of the World Bank API endpoint:
# arable land for the United States and Brazil from 1990 to 2015
# http://api.worldbank.org/v2/countries/usa;... | a739a5ed2a5bd2033fc0f5b6e818773a9ac972c2 | 3,628,273 |
def generate_info(kd: KnossosDataset) -> dict:
"""Generate Neuroglancer precomputed volume info for a Knossos
dataset
Args:
kd (KnossosDataset):
Returns:
dict: volume info
"""
info = {}
info["@type"] = "neuroglancer_multiscale_volume"
info["type"] = None
info["... | a0f6c23cb99f77eff7fff61dfc67a56dbd6fb8a5 | 3,628,274 |
from typing import Callable
from typing import Concatenate
from typing import Awaitable
from typing import Coroutine
from typing import Any
def plugwise_command(
func: Callable[Concatenate[_T, _P], Awaitable[_R]] # type: ignore[misc]
) -> Callable[Concatenate[_T, _P], Coroutine[Any, Any, _R]]: # type: ignore[mi... | 564dfeff805ecc89a8e69b5c5c605f5a0e3c790e | 3,628,275 |
def order_parsed_fields(parsed, types, names=None):
"""Order parsed fields using a template file."""
columns = {}
fields = {}
ctr = 0
types = add_names_to_types(names, types)
for group, entries in types.items():
for field, attrs in entries.items():
header = False
... | 3752f8cbd13e410f3c548243df31149c9a0c3e86 | 3,628,276 |
def cvSeqSort(*args):
"""cvSeqSort(CvSeq seq, CvCmpFunc func, void userdata=None)"""
return _cv.cvSeqSort(*args) | d3c6d6b4f0840a02614396e3b0fff43694a2ffd1 | 3,628,277 |
def dice_coef_fn(y_true, y_pred, axis=1, eps=1e-6):
"""Calculate the Dice score."""
intersection = tf.reduce_sum(input_tensor=y_pred * y_true, axis=axis)
union = tf.reduce_sum(input_tensor=y_pred * y_pred +
y_true * y_true, axis=axis)
dice = (2. * intersection + eps) / (union +... | ece185fd9464172db51c9fcd2ea434593a9576e9 | 3,628,278 |
def bootstrap_flask_app(app):
"""
Create a new, fully initialized Flask app.
:param obj app: A Stormpath Application resource.
:rtype: obj
:returns: A new Flask app.
"""
a = Flask(__name__)
a.config['DEBUG'] = True
a.config['SECRET_KEY'] = uuid4().hex
a.config['STORMPATH_API_KEY... | 3f966830d8879b97cc4bdfdb632e98b4eaba9a18 | 3,628,279 |
import collections
def gram_counter(value: str, gram_size: int = 2) -> dict:
"""Counts the ngrams and their frequency from the given value
Parameters
----------
value: str
The string to compute the n-grams from
gram_size: int, default= 2
The n in the n-gram
Returns
------... | 21a55bf89ddad13f40af9f25ac5aeb759089dc82 | 3,628,280 |
import os
def get_nucl_data_from_fasta(wd, all_projections):
"""Extract nucleotide data."""
meta_data = os.path.join(wd, "temp", "exons_meta_data.tsv")
nucl_fasta = os.path.join(wd, "nucleotide.fasta")
exon_to_meta_data = extract_exons_meta_data(meta_data)
projection_to_ref, projection_to_q = extr... | d4fd9a2a205f8378872b6e01436cf0ed89651ad5 | 3,628,281 |
import json
def check(request):
"""SQL检测按钮, 此处没有产生工单"""
sql_content = request.POST.get('sql_content')
instance_name = request.POST.get('instance_name')
instance = Instance.objects.get(instance_name=instance_name)
db_name = request.POST.get('db_name')
result = {'status': 0, 'msg': 'ok', 'data'... | 28181f1d22c905beb292d37029c21f05a2ae5c14 | 3,628,282 |
def div_ext(
ticker: str,
viewer: viewers.Viewer = bootstrap.VIEWER,
) -> pd.DataFrame:
"""Сводная информация из внешних источников по дивидендам."""
df = viewer.get_df(ports.DIV_EXT, ticker)
return df.loc[bootstrap.START_DATE :] | 53b8931cd6e2a11022c56fe8e6649042dcd17cf9 | 3,628,283 |
def is_pyside():
"""
Returns True if the current Qt binding is PySide
:return: bool
"""
return __binding__ == 'PySide' | 9d69660ac223f124e49e86b19c44b4bc52fa2964 | 3,628,284 |
from pm4py.algo.filtering.ocel import activity_type_matching
from typing import Dict
from typing import Collection
def filter_ocel_object_types_allowed_activities(ocel: OCEL, correspondence_dict: Dict[str, Collection[str]]) -> OCEL:
"""
Filters an object-centric event log keeping only the specified object typ... | 9c25a9262827885547c8096de0ca511f1ca6cfa5 | 3,628,285 |
from sys import path
def upload():
"""
Accepts a file upload and stores it on disk.
"""
f = request.files['file']
filename = secure_filename(f.filename)
f.save(path.join(app.config['UPLOAD_FOLDER'], filename))
return "%s uploaded successfully" % f.filename | 11c84b2fee9a0e997cb9eb01fab79ea014b7745a | 3,628,286 |
def parse_sources_data(data, origin='<string>', model=None):
"""
Parse sources file format (tags optional)::
# comments and empty lines allowed
<type> <uri> [tags]
e.g.::
yaml http://foo/rosdep.yaml fuerte lucid ubuntu
If tags are specified, *all* tags must match the current
co... | c278d19fc96d847ef5d8e17dfd6b5dc98633613a | 3,628,287 |
import inspect
def list_module_public_functions(mod, excepted=()):
""" Build the list of all public functions of a module.
Args:
mod: Module to parse
excepted: List of function names to not include. Default is none.
Returns:
List of public functions declared in this module
"... | d27dc869cf12701bcb7d2406d60a51a8539a9e1b | 3,628,288 |
from typing import Iterable
import ctypes
def twovec(
axdef: Iterable[float], indexa: int, plndef: Iterable[float], indexp: int
) -> ndarray:
"""
Find the transformation to the right-handed frame having a
given vector as a specified axis and having a second given
vector lying in a specified coordi... | cdb18fc69bd29eb64191adbd1dd01c8201e4c0eb | 3,628,289 |
def translate_marker_and_linestyle_to_Plotly_mode(marker, linestyle):
"""<marker> and <linestyle> are each one and only one of the valid
options for each object."""
if marker is None and linestyle != 'none':
mode = 'lines'
elif marker is not None and linestyle != 'none':
mode = 'lines+markers'
elif marker is n... | 53de94176afe47f5a9b69e7ad676853b4b19a8db | 3,628,290 |
import json
def handle_exception(err):
"""for better error handling"""
# start with the correct headers and status code from the error
response = err.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": err.code,
"name": err.name,
"description":... | d6990ef6295206618d50faaaa2c8aea9cdb076e9 | 3,628,291 |
def strRT(R, T):
"""Returns a string for a rotation/translation pair in a readable form.
"""
x = "[%6.3f %6.3f %6.3f %6.3f]\n" % (
R[0,0], R[0,1], R[0,2], T[0])
x += "[%6.3f %6.3f %6.3f %6.3f]\n" % (
R[1,0], R[1,1], R[1,2], T[1])
x += "[%6.3f %6.3f %6.3f %6.3f]\n" % (
R[2,0]... | 2d7ec1bf2ebd5a03472b7b6155ed43fdcc71f76a | 3,628,292 |
def _scale_log_and_divide(train, val, scaler="log_and_divide_20"):
"""First apply a log transform, then divide by the value specified in
scaler to sequences train and val.
Parameters
----------
train : np.ndarray
Training dataset
val : np.ndarray
Validation dataset
scaler: s... | ba3ccdae25e50cf6855f56fe56f366daf4b37212 | 3,628,293 |
def extract_classes(document):
""" document = "545,32 8:1 18:2"
extract_classes(document) => returns "545,32"
"""
return document.split()[0] | b7e8fed3a60e3e1d51a067bef91367f960e34e6b | 3,628,294 |
def general_value(value):
"""Checks if value is generally valid
Returns:
200 if ok,
700 if ',' in value,
701 if '\n' in value"""
if ',' in value:
return 700
elif '\n' in value:
return 701
else:
return 200 | 5cf8388294cae31ca70ce528b38ca78cdfd85c2c | 3,628,295 |
def _cast_to(matrix, dtype):
""" Make a copy of the array as double precision floats or return the reference if it already is"""
return matrix.astype(dtype) if matrix.dtype != dtype else matrix | 9625311c0918ca71c679b1ac43abe67f2a4b0f2d | 3,628,296 |
def wire_mask(arr: np.ndarray, invert: bool = False) -> np.ndarray:
"""
Function
----------
Given an 2D boolean array, returns those pixels on the surface
Parameters
----------
arr : numpy.ndarray
A 2D array corresponding to the segmentation mask
invert : boolean (Default = Fals... | f3a49ad458c17f021c8bcb30c78464fccbde8b71 | 3,628,297 |
def reverse_str(string):
"""
Base case: length of string
Modification: str slice
"""
if len(string) == 1:
return string
return reverse_str(string[1:]) + string[0] | eb0d27816e8fe54f1136f4a507478f40a3354d72 | 3,628,298 |
def check_drf_token(request, format=None):
"""
Return `{"status": true}` if the Django Rest Framework API Token is valid.
<!--
:param request:
:type request:
:param format:
:type format:
:return:
:rtype:
-->
"""
token_exists = Token.objects.filter(key=request.data["token... | 38e62e8d3ac11bfba5fffb73bf727164ed63133d | 3,628,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.