content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def test_3(df, seed=0):
"""training: unbalanced; test: unbalanced
training: 80k (16k 1, 64k 0)
test: 20k (4k 1, 16k 0)
"""
df_ones = df[df['label'] == 1]
df_zeros = df[df['label'] == 0]
df_ones = df_ones.sample(frac=1, random_state=seed).reset_index(drop=True)
df_zeros = df_zero... | 9211d7b9ca027aaf1ddb8372cafa0a541269b6ac | 3,627,600 |
def getStores(customer):
"""
This function returns the stores linked to the given customer.
This function does not care about token, it is done before.
Returns the Stores in case of success, otherwise will return an error (OBJECT_NOT_FOUND if the store was not found, DB_ERROR otherwise).
"""
try:
stores... | 9265064fddd8099fd39110ee4385bd952e968a5c | 3,627,601 |
def create_header(multiobj_bool, constr_func):
""" Creates header to save data.
Args:
multiobj_bool (:obj:`bool`): True if multiobjective function is used.
constr_func (:obj:`list`) : Constraint functions applied.
Returns:
Header.
"""
if multiobj_bool:
header =... | 519e66c8437f972cd3ad6d604bc01ab858c8abed | 3,627,602 |
import logging
def authenticate_password(dir_cli):
"""
Function to authenticate SSO password
:param dir_cli:
:return:
"""
try:
if password.strip() == '':
logging.info('password should not be empty')
return False
dir_cli.get_services_list()
return... | 1b727944a05d61b3008a8bc3e77d51b5749cac1b | 3,627,603 |
def colour_by_year(year, train_thresh, update1_thresh, update2_thresh, colours=None):
"""
Assign/return a colour depending on the year the data point was published.
Parameters
----------
year :
publication year of data point
train_thresh :
Last year threshold to assign to traini... | 179b4a5d7f8cccaaa398fdffe43c59d02478dff2 | 3,627,604 |
import http.client as http_client
import httplib as http_client
import shutil
import pip
import subprocess
import py_compile
from tzlocal import get_localzone
import subprocess
import dateutil.relativedelta
import dateutil.relativedelta
import py_compile
import shutil
import traceback
def main(argv=None):
"""Comm... | 076cf570126b0da1fa7ac2db42ece4c34d81197e | 3,627,605 |
import os
from datetime import datetime
def last_modification_datetime(path):
"""
Returns last modification datetime for a given path
"""
mtime=os.path.getmtime(path)
return datetime.datetime.fromtimestamp(mtime) | 94a86b973b857403c4cecaea492ebc21f4471ab0 | 3,627,606 |
def create_text_blocks(font: pygame.freetype.Font, padding: int) -> dict:
"""Initializes all the text blocks for later use.
:param font: The font that will be used to generate the texts.
:param padding: The size of the padding that will be created.
:return: A dictionary containing :py:class:`TextBlock`... | d9943b074716f02125d663f86462d8ace2e7a539 | 3,627,607 |
import json
import os
def root_data(path):
"""Root path of data reference. 数据资源引用路径。
1.出于安全原因,该函数不允许客户端直接读取任何*.py代码文件;
2.所有其他类型的文件将被映射到项目的 data 目录中。
"""
state = {
'success' : 0,
'message' : "不允许客户端直接读取任何*.py代码文件"
}
if path.rfind('py') > (len(path)-4):
return js... | c10da33692b27e3e4611edadab3b63df45c27aa4 | 3,627,608 |
def testable_files(files):
"""
Given a list of files, return the files that have an extension listed in TESTABLE_FILE_EXTENSIONS and are
not blacklisted by NON_TESTABLE_FILES (metrics.yaml, auto_conf.yaml)
"""
return [f for f in files if f.endswith(TESTABLE_FILE_EXTENSIONS) and not f.endswith(NON_TE... | 21069e9f7c955d7936bafd0261c2f9210bb2ec1d | 3,627,609 |
def longest_cont_matrix(pool):
"""Takes in a list of sequences (pool) and returns
a matrix with longest stretch of identity"""
# Make sure pool variable is a list
if type(pool) != list:
raise ValueError('Pool is not a list')
# Array dimension
dimLen = len(pool)
# Gen... | 3dc2788df9db23ee55d5c9dcede0a68084c85ac8 | 3,627,610 |
def as_int(val):
"""
Tries to convert a string to an int.
Returns None if string is empty
"""
try:
return(int(val))
except ValueError:
return(None) | 87586fbc47c37354e34d10116b86d013a98d20b9 | 3,627,611 |
def stream(xp,yp):
"""
Calculates the stream function in physical space.
Clockwise rotation. One full rotation corresponds to 1 (second).
"""
streamValue = np.pi*(xp**2 + yp**2)
return streamValue | bc1220a84a1520df70b90c19eb482f3c4feb97ca | 3,627,612 |
def _get_switch_by_ip(switch_ip, session=None, **kwargs):
"""Get switch by switch ip."""
switch_ip_int = long(netaddr.IPAddress(switch_ip))
return utils.get_db_object(
session, models.Switch,
ip_int=switch_ip_int, **kwargs
) | 913e41cf1d9152fc9353601812250a58bc8e50d3 | 3,627,613 |
def decodeFont(name):
"""
Parses a font string into a tkinter <code>Font</code> object.
This method accepts a font in either the <code>Font.decode</code>
used by Java or in the form of a CSS-based style string.
"""
font = parseJSFont(name)
if font is None:
font = parseJavaFont(name)
... | f0f38b3c9cb3f6bef1f83f6ad2eafc2e1e72f7cc | 3,627,614 |
def get_value(obj, key, default=None):
"""
Returns dictionary item value by name for dictionary objects or property value by name for other types.
Also list of lists obj is supported.
:param obj: dict or object
:param key: dict item or property name
:param default: default value
:return:
... | 5885fa5ae944fd6967c21b97cd7955a94ad0dce2 | 3,627,615 |
def validate_edges(g, max_kmph=200):
"""
Make sure all edges can possibly be traversed with reasonable speed
"""
good_edges, bad_edges = [], []
for u, v, data in g.edges(data=True):
dur, dist_km = data.get("duration"), data.get("distance")
# Distances < 1km are not precise enough
... | 3d0b176f1de7fd7e81a72c44b9d3775f6daaa17c | 3,627,616 |
from typing import Union
import pathlib
def uploadFile(localPath:pathlike, remotePath:Union[str, S3Path]) -> Outcome[str, Union[str, S3Path]]:
"""Assumes AWS credentials exist in the environment
Though the types involved are different, the signature for
downloadFile, uploadFile, and uploadData follo... | f36dc2cd6b24b7e9c8d33a8666f325d3123b8862 | 3,627,617 |
def calculate_bayes_probability(df: np.ndarray = 0, clusters_means: np.ndarray = 0, clusters_variances: np.ndarray = 0,
clusters_weights: np.ndarray = 0, k: int = 0):
""" calculate the normalized Bayes probability of each point per all clusters
# Arguments
df: arrays of p... | a6f43e7950f7b1413cbc5bd4e7d680ced7c72980 | 3,627,618 |
from typing import Tuple
import requests
def comanage_check_person_couid(person_id, couid) -> Tuple[int, bool]:
"""
Check if a given person is a member of couid. Return tuple of API status code
and True or False. Strings or integers accepted as parameters
"""
assert person_id is not None
asser... | 9f42a1161c12046ad2ac5e86ed63493b3e49e941 | 3,627,619 |
from operator import concat
def tensor_contract(*tensors, output_inds=None, get=None,
backend=None, **contract_opts):
"""Efficiently contract multiple tensors, combining their tags.
Parameters
----------
tensors : sequence of Tensor
The tensors to contract.
output_inds... | 481ec9cce4551377c8dc6f9aebea7d945dac14fc | 3,627,620 |
def registry(db, term=None):
"""List the organizations available in the registry.
The function will return the list of organizations. If term
parameter is set, it will only return the information about
the organizations which match that term. When the given term does
not match with any organization... | 5f09b2bdf2a44214be32cd4e8dbce6e3516fa66c | 3,627,621 |
def get_column_names(connection,schema_name, table_name):
"""
Returns a list of column names for a given table.
"""
cur = connection.cursor()
try:
cur.execute("SELECT column_name,data_type FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s';" % (schema_name, ... | 70cdcffe27398ecc13c0e5454517050b6a722845 | 3,627,622 |
import pathlib
from typing import List
def _write_dataset_files(
root_path: pathlib.Path, namespace: str, datasets: List[str]
) -> str:
"""Write the repo content containing the datasets."""
repo_path = root_path / namespace
# Create all datasets
for ds_name in datasets:
ds_path = repo_path / ds_name /... | 49baafff58a08802830208382180ce32d8aaf8c0 | 3,627,623 |
def get(params, query, offset, limit):
"""Get the data from BigQuery."""
sql = SQL.format(
table_id='%ss' % params['type'],
where_clause=query.get_where_clause(),
prefix=params['type'],
offset=offset,
limit=limit)
client = big_query.Client()
result = client.query(query=sql, offset=... | 8f41051360d51693547858b06f7603e0ea0bae81 | 3,627,624 |
def get_rose_username():
"""
Get the Rose username from Subversion's config file
"""
try:
config = SafeConfigParser()
config.read(svn_servers)
return config.get('metofficesharedrepos','username')
except Exception:
return None | 87e423d1417d3ce6d6714e7ae6744844c8cc7568 | 3,627,625 |
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
This method is deprecated, use atom.http.HttpClient.request instead.
Usage example, pe... | 0b7b965b7f28b6e4482be4a7e7f07aa34ddfef92 | 3,627,626 |
def findLargestGap(depth_og, min_dist, barrier_h=0, min_gap=0):
"""
Given depth image, find the largest gap that goes from the bottom of
the image to the top. Use min_dist as threshold below which objects are
shown to be too close. Return the position in the middle of the largest
gap.
"""
d... | 191f3f8ab9724d50d06386df399e827a58395464 | 3,627,627 |
import time
def _CalcProjectAlert(project):
"""Return a string to be shown as red text explaning the project state."""
project_alert = None
if project.read_only_reason:
project_alert = 'READ-ONLY: %s.' % project.read_only_reason
if project.moved_to:
project_alert = 'This project has moved to: %s.' %... | 5d2288753654a0275b6d4c4f77123691be941433 | 3,627,628 |
def normalized_8UC3_image(image):
"""
:param image: two-dimensional image
:return: normalized to [0, 255] three-dimensional image
"""
assert len(image.shape) == 2, 'two-dimensional images are only supported'
image = normalized_8U_image(image)
return np.stack((image,) * 3, axis=-1) | 3a6f334a5264b235bbcbcebcc3e39168ff15d878 | 3,627,629 |
import argparse
import sys
def _parse_arguments() -> argparse.Namespace:
"""Plot argument parser.
"""
parser = argparse.ArgumentParser(description="Plot")
parser.add_argument(
"--inputs",
type=str,
required=True,
help=
"comma-separated list of input data filenames (e.g., --input ... | f69c69040d9003e32b27e3195218cad06c807e69 | 3,627,630 |
import sys
import click
def _read_plan_yaml(yaml_path: str) -> PlanSchema:
"""Read YAML, either from a path on disk or from stdin."""
try:
if yaml_path == "-":
data = sys.stdin.read()
result = PlanSchema.parse_raw(data)
else:
with open(yaml_path, "r", encodi... | fd939fa5a93c1c9a150a6dff3015794319245bb0 | 3,627,631 |
def remove_sex(beta, array_type='450k'):
"""Remove non-autosomal cpgs from beta matrix.
Parameters
----------
array_type
450k/850k array?
"""
beta = robjects.r("""function (beta,array.type){
featureset<-array.type
autosomal.sites <- meffil.get.autosomal.sites(featureset)... | 1ec585b2bd589d8cab5e3dc747f91604c4561be0 | 3,627,632 |
from datetime import datetime
def create_netcdf(valid):
"""Create and return the netcdf file"""
ncfn = "/mesonet/data/iemre/cfs_%s.nc" % (valid.strftime("%Y%m%d%H"), )
nc = ncopen(ncfn, 'w')
nc.title = "IEM Regridded CFS Member 1 Forecast %s" % (valid.year,)
nc.platform = "Grided Forecast"
nc.... | 80c1eddb0850d496500a1b9d7b1c512fc459abb7 | 3,627,633 |
def check_fortran_type(typestr, error=False):
"""Return <typestr> if a valid Fortran type, otherwise, None
if <error> is True, raise an Exception if <typestr> is not valid.
>>> check_fortran_type("real")
'real'
>>> check_fortran_type("integer")
'integer'
>>> check_fortran_type("InteGer")
... | 70c63c78c4b33016bc9ee508eea5ddac197aa96d | 3,627,634 |
def pyro_service_process(auto_start=False, *args, **kwargs):
"""Start a pyro service in a separate process."""
# Set up nameserver process.
logger.debug(f'Setting up Pyro service process.')
service_process = Process(target=pyro_service, args=args, kwargs=kwargs)
if auto_start: # noqa
logge... | 8a57201342c2556380fe61cac96121ed3905abb8 | 3,627,635 |
def topk_caculate(predict_p, true_labels, k=1, number_cat=None, epsilon=1e-19):
"""
topk准确率计算
Args:
predict_p: 预测的概率分布shape=(N,number_cat)
true_labels: 真实标签,shape=(N,)
k: top k
number_cat: number categories
eposion: e
Returns:
topk acc [top1,top2,...,topk... | 0882b9b2fbace903f4d6afeda80d50400fc83b3f | 3,627,636 |
def mon_operator(xs):
"""xs = [unary_op, unary] OR primary"""
if not isinstance(xs, list):
return xs
return TokenOperator(xs[0], [xs[1]]) | 182f06edf958cbf4b30ae930097c1736e50fc9e5 | 3,627,637 |
from typing import List
def chunked_phrase_strict(m) -> List[BasePhraseChunk]:
"""A chunked phrase that must start with dictation.
This capture can be used to insert keywords that would otherwise be handled
as symbols or commands. For example, we could put this in a .talon file:
snake <chunked_p... | 8aa6b58b0be5fffae70330f11ac41edf52294822 | 3,627,638 |
def merge_nodes(merge_nodes, player_nodes, edge_index):
"""
merge nodes by redirecting any connected edges, only the edges are changed
"""
m_nodes = merge_nodes.copy()
while m_nodes:
node = m_nodes.pop()
#if node not in merged:
# get edges going out from the node
c1_... | 9613a84df61aac314beec9459013ddf2cb0fd251 | 3,627,639 |
def load_portfolio(portfolio_filepath):
"""
Load Portfolio json file to dataframe
INPUT:
portfolio_filepath: string
OUTPUT:
portfolio: dataframe
"""
portfolio = pd.read_json(portfolio_filepath, orient='records', lines=True)
return portfolio | 07763140800697b91fb07eed33827e66c80e3972 | 3,627,640 |
import json
def transform_group_roles_data(data, okta_org_id):
"""
Transform user role data
:param data: data returned by Okta server
:param okta_org_id: okta organization id
:return: Array of dictionary containing role properties
"""
role_data = json.loads(data)
user_roles = []
... | ea554dfb4e91e3647298a2ef0891452e423ff957 | 3,627,641 |
def price_lineplot(card_id, df):
"""in construction"""
fig, ax = plt.subplots()
df_price =(get_price_list_from_redis(card_id))
sns.lineplot(x=df_price.index, y=df_price['price'], ax=ax)
ax.set_title(df.loc[df['id'] == card_id]['name'].values[0])
ax.set_ylim(ymin=0)
return fig | ed95dbd9d68a6e267c9bd132aeec856d38501a5c | 3,627,642 |
def status_select_block(initial_option: str = None):
"""Builds the incident status select block"""
status_options = [option_from_template(text=x.value, value=x.value) for x in IncidentStatus]
block = {
"block_id": IncidentBlockId.status,
"type": "input",
"label": {"type": "plain_text... | a8ed54917097658462a7953e48c72704ec530920 | 3,627,643 |
def streaming_order_filter(
include_overall_position: bool = None,
customer_strategy_refs: list = None,
partition_matched_by_strategy_ref: bool = None,
) -> dict:
"""
:param bool include_overall_position: Returns overall / net position (OrderRunnerChange.mb / OrderRunnerChange.ml)
:param list cu... | c06bf2149410c64c82d0b8383ad1c195d03bef47 | 3,627,644 |
def fasterrcnn_resnet_fpn_x(*args, **kwargs):
"""Instantiate FRCNN-ResNet-FPN with extra RoI projection"""
return FasterRCNN_(fasterrcnn_resnet_fpn(*args, **kwargs)) | b77995c1ad362485cfd621fadc565a38d8df7fc3 | 3,627,645 |
def circuit_measure_max_once():
"""A fixture of a circuit that measures wire 0 once."""
return qml.expval(qml.PauliX(wires=0)) | 789eb0e2e51f7b8bd452b11460326d0594c8e766 | 3,627,646 |
def regenerate_image_filename_using_dimensions(filename, height, width):
"""Returns the name of the image file with dimensions in it.
Args:
filename: str. The name of the image file to be renamed.
height: int. Height of the image.
width: int. Width of the image.
Returns:
st... | ed5f141c9c027c5a8469350c052ad88d0acbddde | 3,627,647 |
from datetime import datetime
def calculate_time_matrix(name):
"""Calucation and round in closest 15 minutes, delivery stops"""
gmaps = frappe.db.get_value('Google Maps', None,
['client_key', 'enabled', 'home_address'], as_dict=1)
if not gmaps.enabled:
frappe.throw(_("Google Maps integration is not enabled")... | 525621193f17920871be0eddb4660f5189a6815d | 3,627,648 |
import time
def revoke_token():
"""revoke token"""
token_string = get_token_from_headers(request)
try:
token = OARepoAccessToken.get_by_token(token_string)
assert token.is_valid()
except:
time.sleep(INVALID_TOKEN_SLEEP)
json_abort(401, {"message": f"Invalid token. ({tok... | c115905adf42b229467a65f66d3bde5e2acc606b | 3,627,649 |
def command_error_handler(e, cmd_descr, use_logger=False, warn_only=False,
exit_val=exitvals['startup']['num']):
"""
Handle external-command-related exceptions with various options.
If it returns, returns False.
Parameters:
cmd_descr: a string describing the command, us... | a8cded1ca6d4447f5fb6a36607f03766c194efa7 | 3,627,650 |
import os
import numpy
import tqdm
import pickle
def emb_computation_loop(split, set_loader, stat_file):
"""Computes the embeddings and saves the in a stat file"""
# Extract embeddings (skip if already done)
if not os.path.isfile(stat_file):
embeddings = numpy.empty(
shape=[0, params["... | 040bea86b89f489a26e9fceee2821f39a505b801 | 3,627,651 |
def register(*ids):
"""Register termination function class for environments with given ids."""
def librarian(cls):
for id_ in ids:
TERMINATIONS[id_] = cls
_raylab_registry.register(RAYLAB_TERMINATION, id_, cls)
return cls
return librarian | 50e3199011c86c1d740675f2b975dfe84033b009 | 3,627,652 |
import logging
import os
def process_sdk_options(parser, options, app_dir):
"""Handles values of options added by 'add_sdk_options'.
Modifies global process state by configuring logging and path to GAE SDK.
Args:
parser: OptionParser instance to use to report errors.
options: parsed options, as return... | eb0ecb347640bbd59d1b1c01911df3c26985737a | 3,627,653 |
def IsProjectAddressOnToLine(project_addr, to_addrs):
"""Return True if an email was explicitly sent directly to us."""
return project_addr in to_addrs | 7907bbb313b3e6d8439af79539e469b04a62da63 | 3,627,654 |
def FID3_factual(instance, rule_list, threshold=0.01):
"""Returns the factual extracted for the Fuzzy ID3
tree in this package
Parameters
----------
instance : dict, {feature: {set_1: pert_1, set_2: pert_2, ...}, ...}
Fuzzy representation of the instance with all the features and pertenence... | 95160c477f003931b9094b52eb475c8d93cba4c1 | 3,627,655 |
def percent_decode(s, encoding='utf-8', decodable=None, errors='replace'):
"""
[*** Experimental API ***] Reverses the percent-encoding of the given
string.
Similar to urllib.parse.unquote()
By default, all percent-encoded sequences are decoded, but if a byte
string is given via the 'decodable... | d1d57503c2b75d13f962ffc80139a32901d8c3ef | 3,627,656 |
def get_card_key(word_type: WordType, russian: AccentedText,
english: AccentedText) -> tuple:
"""
Get the key that identifies a card.
"""
return (word_type,
AccentedText(russian).text.lower(),
AccentedText(english).text.lower()) | e31915cf523ec64578f62674fa6019629df28dad | 3,627,657 |
def parse_text_content(html: str) -> list:
"""
获取每个查询结果显示的数据量,然后通过每页20条的数据转换成共计多少页。
:return:
"""
html = etree.HTML(html)
need_content = html.xpath('//*[@id="__next"]/div[1]/div/div[1]/section[1]/article/p')
return need_content | 2fb4f1e271253260e53590499f5ef5241a06f5cc | 3,627,658 |
def create_input(config=None, src_data=None, tgt_data=None, src_pos_dict=None):
"""
:return:
"""
assert src_data.shape[0] == tgt_data.shape[0]
n_datapoints = src_data.shape[0]
sequence_length = config['sequence_length']
data = []
close_price_idx = src_pos_dict['close_price']
for i i... | 5b72bd884023eba621667b640f76baf03203a75e | 3,627,659 |
import numpy
def std_histogrammed_function(t, y, **kwargs):
"""Compute standard deviation of data *y* in bins along *t*.
Returns the standard deviation-regularised function *F* and the centers of the bins.
.. SeeAlso:: :func:`regularized_function` with *func* = :func:`numpy.std`
"""
return apply... | d4730530046a4f65f58c7f07bd68c9444b8be8e9 | 3,627,660 |
def _crown_div(out_bound, lhs, rhs):
"""Backward propagation of LinearBounds through an addition.
This is a linear operation only in the case where this is a division by a
constant.
Args:
out_bound: CrownBackwardBound, linear function of network outputs bounds
with regards to the results of the divi... | 13c2fb9f2cea401119d5a19435ae897f643b5520 | 3,627,661 |
def cartesian_to_polar(x, y, vx, vy, THRESH=0.0001):
"""
Converts 2d cartesian position and velocity coordinates to polar coordinates
Args:
x, y, vx, vy : floats - position and velocity components in cartesian respectively
THRESH : float - minimum value of rho to return non-zero values
Ret... | 82655bf23d08198f106dfb1ecd9d3967627e21c1 | 3,627,662 |
import time
import requests
def processing(channel):
"""
获取代理,缓存1小时
:param channel: nn-国内高匿/nt-国内普通/wn-国内https/wt-国内http
:return:
"""
if len(settings.CACHE['proxies']['items']) == 0 or int(time.time()) > settings.CACHE['proxies']['update'] + 60 * 60 * 0.5:
items_http = []
item... | 0d9bc70b16d0b16c39a56a47123483b017407a60 | 3,627,663 |
def _to_voxel_coordinates(streamline, lin_T, offset):
"""Applies a mapping from streamline coordinates to voxel_coordinates,
raises an error for negative voxel values."""
inds = np.dot(streamline, lin_T)
inds += offset
if inds.min().round(decimals=6) < 0:
raise IndexError('streamline has poi... | da8991e7265e994268df99dda038f406073c0cc5 | 3,627,664 |
def check_if_branch_exist(db, root_hash, key_prefix):
"""
Given a key prefix, return whether this prefix is
the prefix of an existing key in the trie.
"""
validate_is_bytes(key_prefix)
return _check_if_branch_exist(db, root_hash, encode_to_bin(key_prefix)) | 960cc3082bcfb8ec2030a56122e1366347dc3daf | 3,627,665 |
def add_trace(rule, mbox_response, request_type, request_detail, tracer):
"""
:param rule: (target_decisioning_engine.types.decisioning_artifact.Rule) rule
:param mbox_response: (delivery_api_client.Model.mbox_response.MboxResponse) mbox response
:param request_type: ( "mbox"|"view"|"pageLoad") request ... | d50e40fac8d1b22cd2243c7f876ab0b27a16a09c | 3,627,666 |
from typing import List
def _get_axis_labels(axes: List["CalibratedAxis"]) -> List[str]:
"""Get the axes labels from a List of 'CalibratedAxis'.
Extract the axis labels from a List of 'CalibratedAxis'.
:param axes: A List of 'CalibratedAxis'.
:return: A list of the axis labels.
"""
return [s... | ed22aeab55d874d6728399c0e4928805ec479c19 | 3,627,667 |
import json
async def show():
"""
Dumps shits table for test
:return:
"""
cur = current_app.db.cursor()
cur.execute('''SELECT * FROM shits''')
return await make_response(json.dumps(cur.fetchall())) | fbf5a21fea1e7a8f1dd6bbcd17ef362192de6be8 | 3,627,668 |
def set_filter(info_dict, norm=False, norm_val=0.95):
"""
Compute the transmittance of the filter with respect to wavelength
Parameters
----------
info_dict: dictionary
wavelength : array
wavelengths in angstrom
norm: boolean
enables to normalise the values to 'norm_val' ... | 314238c37fbbe9803e1da0c0aae91c8f94bf29b8 | 3,627,669 |
from .auth import auth as auth_blueprint
from .main import main as main_blueprint
def create_app(config_name):
"""
application factory function
:param config_name:
:return:
"""
app = Flask(__name__)
app.config.from_object(config_options[config_name])
# initialising bootstrap
bootst... | 15d67ca46dc5ec022831f58ec7ba2a6f332ff0a0 | 3,627,670 |
def convert_to_tensor_v1(value,
dtype=None,
name=None,
preferred_dtype=None,
dtype_hint=None):
"""Converts the given `value` to a `Tensor`.
This function converts Python objects of various types to `Tensor`
object... | 969d6ceb2255a7d7107518e7e36a9ad80e114897 | 3,627,671 |
def simulate(rate, bdepth, policy, dset_mr, rsz_is=(1e5, 1e2)):
"""Simulate policy on a single camera."""
qpm = ut.getqpm(rate, bdepth)
rsz_is = (int(rsz_is[0]), int(rsz_is[1]))
return _simulate(qpm, policy, dset_mr, rsz_is) | f732c25ff9e537c1e27b98dcf4d3ce3859bc4141 | 3,627,672 |
def CreateUser():
"""Route for checking if user exists."""
profile = check_if_user_profile(users.get_current_user().user_id())
return str(profile) | 67841a7ec7c6edd98e43a13d1cff4f8293ac02a9 | 3,627,673 |
from typing import Tuple
import os
import shutil
def process_file(file_url: str) -> Tuple[str, Tuple[str, ...]]:
"""Process file with download, cache and upgrade."""
_, file_ext = os.path.splitext(file_url)
folder_hash = md5(file_url.encode('utf-8')).hexdigest()
path = f"/notebooks/{folder_hash}"
... | 089d9195fb99abc41616bcf484b004c890c9846b | 3,627,674 |
def is_list(string):
"""
Checks to see if a string contains a list in the form [A, B]
:param string: string to evaluate
:return: Boolean
"""
if string:
if '[' == string[0] and ']' == string[-1] and ',' in string:
return True
return False | 77b86e7480a2a591e18ea21989cfefa06282c5f2 | 3,627,675 |
def load(input_file):
"""
Loads a pcap file
"""
header = pcap.read_pcap_header(input_file)
return header | 2a1b75e2547e9d438ab3e074bf989c0e3386c70c | 3,627,676 |
def personal_wiki_pages(request):
"""
List personal wiki pages.
"""
username = request.user.username
if request.cloud_mode and request.user.org is not None:
org_id = request.user.org.org_id
joined_groups = seaserv.get_org_groups_by_user(org_id, username)
else:
joined_gr... | 60ece13b54c0d8af26279df31a7855de8b17e42f | 3,627,677 |
def parse_args():
"""This function parses and return arguments passed in """
descr = 'Plot the Bifurcation Diagram of Logistic, Cubic, and Sine Maps'
examples = '''
%(prog)s -r 1:4
%(prog)s -r 4:6.5 --map=cubic
%(prog)s --map=sine -s 200 -n 200
%(prog)s -r 3.:4. -s 500 -n 600
%... | cb0f1c54b1fb9c07712b206a19057e4dc742f00f | 3,627,678 |
import string
import random
def get_random_mac_address():
"""Generate and return a MAC address in the format of WINDOWS"""
# get the hexdigits uppercased
uppercased_hexdigits = ''.join(set(string.hexdigits.upper()))
# 2nd character must be 2, 4, A, or E
return random.choice(uppercased_hexdigits) +... | 171eaca1df7b35def0d09a2ac1bc2e96163a3ceb | 3,627,679 |
def remove_fragments(mol):
"""Filters out fragments.
A predefined list contains numerous known fragments which can be
filtered out.
Parameters
----------
mol: rdkit.Chem.Mol
A molecule with various fragments.
Returns
-------
mol: rdkit.Chem.Mol
Returns a molecule f... | a04f9d097edadc2e0e53f9ea43e1a41467cb880b | 3,627,680 |
def mooring_horizontal_volume_transport(od):
"""
Compute horizontal volume flux through a mooring array section (in/outflow).
If the array is closed, transport at the first mooring is not computed.
Otherwise, transport at both the first and last mooring is not computed.
Transport can be comput... | ca15da2d094994fc1e6645f3d8f528e890fc66d6 | 3,627,681 |
from typing import cast
def _cast_list(definition: dict, value: list) -> list:
"""
Convert a list botocore type into formatted values recursively casting its items.
:param definition:
Specification definition for the associated value to cast.
:param value:
A loaded value to be cast in... | 875b965c8e841c4963bc95a053aed615d7d55097 | 3,627,682 |
def demo_hello():
"""Example with simple swagger definition
This is the most simple swagger definition example.
---
tags:
- demo
# tags: [demo1, demo3]
parameters:
- name: username
in: query
type: string
required: true
- name: age
in: query
... | 38b6b0073177b6bdb2519e09d4840a81d67f50f9 | 3,627,683 |
def get_signed_node(node, sign, reverse):
"""Given sign and direction, return a node
Assign the correct sign to the source node:
If search is downstream, source is the first node and the search must
always start with + as node sign. The leaf node sign (i.e. the end of
the path) in this case will th... | bdfb0aae5984de6f8ef0adf7919322e814b3263f | 3,627,684 |
def isChinese(word):
"""判断是否为中文"""
for uchar in word:
if not '\u4e00' <= uchar <= '\u9fa5': # 遇到非中文
return False
return True | 464f87a2211f6e3d2f00a9a2bf12d0669cd297ec | 3,627,685 |
from typing import Optional
import ssl
from typing import Sequence
import asyncio
from typing import Mapping
from typing import Iterable
from typing import Type
from typing import Any
from typing import cast
import websockets
async def serve(
ssl_context: Optional[ssl.SSLContext],
keys: Optional[Seque... | 205089ff07067ff9eb0abfc623fdc79bdd696722 | 3,627,686 |
def ll_dist(lon1, lat1, lon2, lat2):
"""
Return distance between a pair of lat, long points.
"""
# functions based on radians
lat1, lat2, dlon, dlat = map(radians, [lat1, lat2, (lon2 - lon1), (lat2 - lat1)])
a = sin(dlat / 2.0) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2.0) ** 2
return R_EA... | 5c47948b84f1770c96448dfe84842903fcbd35d0 | 3,627,687 |
import json
def game(request, *, window_codename):
"""Display problems"""
# Process request
superuser = request.user.is_superuser
team = request.user.competitor.team
try:
window = queries.get_window(window_codename)
except models.Window.DoesNotExist:
raise Http404()
# Ini... | 07b311431e930784f6a7f762845ffafed0351879 | 3,627,688 |
def to_video_labels(label=None, frames=None, warn_unsupported=True):
"""Converts the given labels to ``eta.core.video.VideoLabels`` format.
Args:
label (None): video-level labels provided as a
:class:`fiftyone.core.labels.Label` instance or dict mapping field
names to :class:`fi... | 753a221e5ccbcedcf43165f08aaf7c0231845dd7 | 3,627,689 |
def api_create_user():
"""Creates a new user.
Example Request:
HTTP POST /api/v1/users/create
{
"username": "johndoe",
"password": "Password1",
"email": "johndoe@example.com",
"first_name": "John"
}
Example Response:
{
... | 31fd2c47c06438520e9d5af4f3219e466c40370e | 3,627,690 |
def plot_activity(preds, sort_map_list, label_list, window_size=2, active_length_cutoff=3, disable_inactive=True,
start=None, end=None, step=10, ax=None, fig=None, cbar=False, legend=True):
"""Visualize the progression of an outbreak through time. Apply activity cutoffs based on time and similar
... | 380c741f575499c2521c25704fa58523a94fa131 | 3,627,691 |
import six
def make_events_query_from_filter(event_filter):
"""Return start and stop row for filtering and a query.
Query is based on the selected parameter.
:param event_filter: storage.EventFilter object.
"""
q = {}
ts_range = make_timestamp_range(event_filter.start_time,
... | e71675b07c615d37078e1b7999f94600bb9efc63 | 3,627,692 |
def jpeg_next_marker(fh):
"""Scans to the start of the next valid-looking marker. Return
value is the marker id.
TODO use fh.read instead of read_exactly
"""
# Find 0xff byte. We should already be on it.
try:
byte = read_exactly(fh, 1)
while ord3(byte) != 0xff:
# log... | 92d74d96ad33b4faca181615cfa39d3b34272784 | 3,627,693 |
def data_context_topology_context_topologyuuid_nodenode_uuid_owned_node_edge_pointowned_node_edge_point_uuid_cep_list_connection_end_pointconnection_end_point_uuid_otsi_connection_end_point_spec_otsi_termination_selected_central_frequency_get(uuid, node_uuid, owned_node_edge_point_uuid, connection_end_point_uuid): # n... | f31837559e5dc67c0b23d7dcf659d0b702572ce2 | 3,627,694 |
from typing import Optional
from typing import List
def get_edge_trace(
g: nx.Graph,
edge_colours: Optional[List[str]] = None,
) -> List[go.Scatter]:
"""Gets edge traces from PPI graph. Returns a list of traces enabling edge colours to be set individually.
:param g: _description_
:type g: nx.Grap... | f220b50d6a78f54c5edcb48d4da1988ba32878e5 | 3,627,695 |
def matmul_A_BT(a, b):
"""
Computes A * B.T, dealing automatically with sparsity and data modes.
:param a: Tensor or SparseTensor with rank 2 or 3.
:param b: Tensor or SparseTensor with rank 2 or 3.
:return: Tensor or SparseTensor with rank = max(rank(a), rank(b)).
"""
mode = modes.autodetec... | c04f8e19834a48f3a26682ca6c653f665765aebc | 3,627,696 |
def entries_to_labels_scores(entries):
"""
Convert entries to labels and scores for barplot.
NOTE The labels only exist to discern entries: the actual labels are
set in set_label_legends.
"""
nicknames = [entry['algo-nickname'] for entry in entries]
scores = []
colors = []
for entr... | 31c42ffa820d09bfbfb437904884c354f6fec257 | 3,627,697 |
import sys
def guessarraytype (arr, makeintfloats=False):
"""
guess the underlying datatype (out of 'i8', 'f4', 'a20') of an iterable
of strings. If the iterable contains strings that are guessed to be of
different types, the most 'general' type will be returned, where we mean
('i8', 'f4', 'a20')... | 0ace5e36aa1ef8cadd12b677449b28d86fbd3910 | 3,627,698 |
def get_current_system_datetime(device):
""" Returns current time of system
Args:
device ('obj'): device to use
Returns:
current time ('str')
Raises:
None
"""
log.info("Getting current system time")
try:
out = device.parse("show cloc... | 614d51af0a1be18901533f1920e2c5f8c07149a2 | 3,627,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.