content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def survey_getQuestionFromCode(code, series_id=None):
"""
Function to return the question for the given series
with the code that matches the one passed in
"""
s3db = current.s3db
sertable = s3db.survey_series
q_ltable = s3db.survey_question_list
qsntable = s3db.survey_question
... | bd2483be4e1c4e2fa33806c2d4c80215c6414975 | 3,618,500 |
import argparse
def init_args():
"""
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument('--imgs_pth', type=str, help='The images path',
default='../m2nist/combined.npy')
parser.add_argument('--weights_pth', type=str, help='The model weights path',
... | 71bcda4b062c907d2ce06358161103b38264f115 | 3,618,501 |
import glob
def get_cityscapes_file_pairs(split='train', city='*', sequence='*',
frame='*', ext='.*', gt_type='labelTrainIds', type='leftImg8bit',
root_folder=CITYSCAPES_FOLDER, file_template=CITYSCAPES_FILE_TEMPLATE):
"""
Fetch pairs of filenames f... | dc4915dacf0862bde76938c96322e0895f84ccb2 | 3,618,502 |
def OT_retrieve_optfile(filename, mode='rsync-ssh', keyfile='', args='', sshargs=''):
"""
retrieve_optfile(...) is identical to retrieve_file(...), except
that it returns a tuple that can be passed to optfile(...) that
contains both the temporary file and ``filename``, thus indicating
``filename`` ... | 3409d1f428e69b54b3e95fdbf03ce18d511129ad | 3,618,503 |
def test_bounds_optional():
"""Test that each object template can have passthrough bounds for any of its attributes."""
def link():
return LinkByUID(id=str(uuid4()), scope=str(uuid4()))
for template_type, attribute_args in [
(MaterialTemplate, [
('properties', PropertyTemplate),
... | 85a852d303b47c7ef75f8b9e2e88726ffabc32ed | 3,618,504 |
import json
def is_session_active_api(request):
"""
API endpoint that tells if user has active session.
"""
user_id = request.user.id if request.user.is_authenticated else None
return HttpResponse(json.dumps({'success': request.user.is_authenticated,
'user_id': ... | b05bc9c8ad45590ff123ff999f6688cfdb4a2aa6 | 3,618,505 |
def high_precision_keyword_read(hdr, keyword):
"""Read FITS header keywords, also if split in two.
In the case where the keyword is split in two, like
MJDREF = MJDREFI + MJDREFF
in some missions, this function returns the summed value. Otherwise, the
content of the single keyword
Paramet... | c30ee16781b32cdc0a371413021df90d6dbf83ac | 3,618,506 |
def build_assign_term_to_entities_request(
term_guid, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Assign the given term to the provided list of related objects.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code f... | eabf9d843980186bf8f5ef8f3b952b9675098488 | 3,618,507 |
def calc_skier_position(skierposition,userinput):
"""
"""
if userinput == "j":
skierposition = skierposition - 1
if userinput == "k":
skierposition = skierposition + 1
return skierposition | 66f638f9d9b5311efed10bbfe28274a9e80b9dd7 | 3,618,508 |
def intersect_plane_with_box(tshape, plane_def):
"""For each 'unknown' dimension, let the knowns be the other dimensions.
The known ones define the edges of the box.
Then find the unknown by the plane-equation.
But this gives also out-of-box points, so filter them out.
"""
normal,d = plane_def[:... | eb28d1ceed90a53a009e17c32a87200325b079b9 | 3,618,509 |
def _get_command_powershell_script(command):
"""Return a valid CMD command that runs a powershell script."""
return "powershell -NonInteractive -NoLogo -File {}".format(command) | fdd67ac942e7869417c57f8021f26480228bc0a7 | 3,618,510 |
def _getProductPath(product_name):
""" Return the absolute path of the product's directory.
"""
try:
# BBB: for GenericSetup 1.1 style product names
product = __import__('Products.%s' % product_name, globals(), {},
['initialize'])
except ImportError:
... | e269c1d261bb60c92f3c83fce66e6168be486e84 | 3,618,511 |
from typing import Optional
from typing import Dict
from typing import Any
def get_commit_sheet(
access_key: str,
url: str,
owner: str,
dataset: str,
*,
commit_id: str,
sheet: str,
with_record_count: Optional[bool] = None,
schema_format: Optional[str] = None,
) -> Dict[str, Any]:
... | cdf448dd1be367afc8f97b739619cc58ee175ad3 | 3,618,512 |
def get_transport_and_path_from_url(url, config=None, **kwargs):
"""Obtain a git client from a URL.
:param url: URL to open (a unicode string)
:param config: Optional config object
:param thin_packs: Whether or not thin packs should be retrieved
:param report_activity: Optional callback for reporti... | 368fb58aafbc9895bd7f5a7bcde2481dcdafa7e6 | 3,618,513 |
def getModelSupportTypes(data):
"""
获取模型支持的分类
:return:
"""
temp = ''
for i in data:
temp = temp + ' ' + i
return temp | b44a362ca231c65eff5aff8d17da9a46236106b6 | 3,618,514 |
from typing import List
def get_function_argument_names_from_source_code(source_code: str) -> List[str]:
"""
Gets the names of the function arguments found in a particular line of source code.
Specifically, it retrieves the names of the arguments in the first function call found in the source code string... | 3eb7bf9dccf34112777ce35464a3f1b62821e914 | 3,618,515 |
def load_image(addr, resizeSize=None, imgType=np.float32):
"""Read an image and make sure it is of the correct type. Optionally resize it"""
try:
img = imread(addr, mode='F')
except:
img = 0.5*np.ones((512,512))
print("Image read failed")
if resizeSize:
img = cv2.re... | becd97a8004398d3b7278401564bd2bdb9a49847 | 3,618,516 |
def queue_count(queue_name: str = QUEUE_NAME) -> int:
""" Display the number of messages in SQS queue """
logger.info("Getting queue messages count...")
try:
sqs = boto3.client("sqs")
queues = sqs.list_queues(QueueNamePrefix=queue_name)
queue_url = queues["QueueUrls"][0]
re... | d08fbe04bbc60b90c5dbc115d77b3caaeed71dc7 | 3,618,517 |
import time
def check_monit(dut):
"""
@summary: Check whether the Monit is running and whether the services which were monitored by Monit are
in the correct status or not.
@return: A dictionary contains the testing result (failed or not failed) and the status of each service.
"""
lo... | 31b43b83636cdf27f836f7027a0271784ef0b75c | 3,618,518 |
import inspect
def generator(T):
"""Mark a class as a generator"""
class generator_interposer(T):
def __init__(self, *args, **kwargs):
gen_i = self._get_int()
# Capture the instantiation location
frame = inspect.stack()[1]
gen_... | 80b570950268ecc43ca3ad0f7fbef73cb03dd92a | 3,618,519 |
import numpy as _np
def hausdorff_distance(polyline1,polyline2):
"""
Compute the hausdorff distance from `polyline1` to `polyline2`
:Inputs:
`polyline1`:
a (k,n1) array for the n1 points of the 1st polyline in k-dimension
`polyline2`:
a (k,n2) array for the n2 points of... | 7f19bedf1c6d17ff0535f9f6c0b7860532491c7d | 3,618,520 |
def combine_two_nets(N_1,N_2):
""" combines two networks and returns the new network and its POs
For the moment each net can have only a single PO """
if N_1 == []:
return N_2
if N_2 == 0:
return N_1
N, (xlat_1, xlat_2) = pyzz.combine_cones(N_1, N_2)
POs_N1 = list(N_1.get_POs())
... | e668ae5546c05b8058ff084bab8fa47a95212d68 | 3,618,521 |
def merge_collected_sets(a: Column, b: Column):
"""Merge 2 collected sets keeping only unique items"""
def merge_col(list_a, list_b):
set_a = set()
set_b = set()
if isinstance(list_a, list):
set_a = set(list_a)
if isinstance(list_b, list):
set_b = set(li... | fc039d112e483c2262b5a45457dd3053ab4e1702 | 3,618,522 |
def rank(accessing_obj, accessed_obj, *args, **kwargs):
"""
Use rank in an organization to see if we pass. If orgname
is not specified, the org is assumed to be the accessed
object. If rank is called incorrectly, we'll try to call the
organization permission instead as a fallback.
Usage:
... | d129f14696488e8cd5bff2967446289cc3d2871e | 3,618,523 |
from npt.utils import debug
import torch
def replacement_test_batch(
model, batch_dict, c, verbose=False, sweep_vals=None):
"""Replacem inputs of single target element, see if pred changes accord."""
col = batch_dict['target_cols']
if len(col) > 1:
raise ValueError('Multi-col tests not im... | 77cef22e1f3223aa4cd17dfe4a9603547c14fe51 | 3,618,524 |
def _transform_retexpr(tree, known_ecs, call_cb=None, data_cb=None):
"""Analyze and TCO a return-value expression or a lambda body.
This performs a tail-position analysis on the given ``tree``, recursively
handling the builtins ``a if p else b``, ``and``, ``or``; and from
``unpythonic.syntax``, ``do[]`... | ef44e91eaa9187f8a9e01c9188350b16403051c5 | 3,618,525 |
def cloud2cloud(source_msh, source_val, target_msh, unroll_axis=None, verbose=False, **kwargs):
"""
Interpolate source_val between source_msh and target_msh.
:param source: ndarray(\*shape_sce, dim_msh)
:param target: ndarray(\*shape_tgt, dim_msh)
:param values: ndarray(\*shape_sce, \*shape_val)
:param verbose: ... | 0d568877ef1b83cc9de3e8bc271bbbca8c844887 | 3,618,526 |
def dVhatdYTrans(dcdVhat, U, s, VT):
"""
Apply action of [d(Vhat^{T})/d(Y)]^{T} to the array of derivatives
[d(c)/d(Vhat^{T})]^{T} to obtain the derivatives d(c)/d(Y)
Parameters
----------
dcdVhat : numpy.ndarray
array of derivatives d(c)/d(Vhat)
U : numpy.ndarray
left singu... | 2e79ff9fd841feb3b5c789ba4210e18b40f0f3fc | 3,618,527 |
from pathlib import Path
import json
def latest_checkpoint(model_dir, model_name):
"""return path of latest checkpoint in a model_dir
Args:
model_dir: string, indicate your model dir(save ckpts, summarys,
logs, etc).
model_name: name of your model. we find ckpts by name
Returns... | 29acafdb72bbb549cda7d72cc15a5a93f5535dca | 3,618,528 |
def user_key(username):
"""
Returns user auth key, used to access feed and user settings
Args:
username (str): registered user
Returns:
key (str): user key
"""
config = db.user_config(username)
return config['CONFIG']['key'] | be06c220cddd205679d48337bce45fdaaa33910b | 3,618,529 |
def write_multiple_files( extmodule, dir_path, files_sum_repository=None, encoding='ascii' ):
"""writes extmodule to multiple files"""
mfs = multiple_files_t( extmodule, dir_path, files_sum_repository=files_sum_repository, encoding=encoding )
mfs.write()
return mfs.written_files | 9cf6dcc134347c9468bb751a320d79cbaeb5f850 | 3,618,530 |
async def upload_zarr(sas_url=None, src_folder=None, dst_blob_name=None, timeout=30*60):
"""
Asyn upload a folder to Azure blob
:param sas_url: str, the SAS url
:param src_folder: str, full abs path to the folder
:param dst_blob_name: str, relative (to container) timeout of the
:param timeout:
... | 38c136d1e470a3370a00d60827be5f1ae702d379 | 3,618,531 |
def line_coordinates(image_data, centroid_x, centroid_y, angle_vector_rad, \
step_division = 1, radius_approx = None, radius_approx_interval = 20):
"""Get the coordinates along each radial line of each specified angle
For all angles specified in angle_vector_rad, the coordinates (x,y) ... | 3b93a9fd28c970014b6c17fcca91491b23831b3d | 3,618,532 |
def as_batch(img, shape, as_list=False):
"""Convert an image block group to a list
After chop_to_blocks, the data has a structure like
(jx, ix, 1, 400, 400, 3)
convert this to:
obj_detection : (ix*jx, 400, 400, 3)
patch_identification : (ix*jx, 200, 200, 3)
Args
----
img ( np.... | 77c2c5d83d88d2e4307f6f26a3d49a2e1f852a50 | 3,618,533 |
def dtw_sakoechiba(x=None, y=None, dist='square', window_size=0.1,
precomputed_cost=None, return_cost=False,
return_accumulated=False, return_path=False):
"""Dynamic Time Warping (DTW) distance with Sakoe-Chiba band constraint.
.. deprecated:: 0.11
This function is... | fb27288ce62409af9aba1b270a4b91770c163500 | 3,618,534 |
import yaml
def node_from_manifest(manifest):
"""Create V1Node object from a YAML manifest."""
manifest = yaml.safe_load(manifest)
manifest['api_version'] = manifest.pop('apiVersion')
return k8s.client.V1Node(**manifest) | d043418022bfe4973457dd48e4d7ec8cf2581eab | 3,618,535 |
def _OverrideBinaryOperatorHelper(func, op_name, clazz_object=ops.Tensor):
"""Register operators with different tensor and scalar versions.
If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices,
sp_values, sp_shape, dense)` and outputs `(new_sp_values)`.
Args:
func: the operator
op_na... | 15164bc3428e0d5789bf6654e1513eeadf59475b | 3,618,536 |
def generate_freenas_snapshot_name(name, iqn_prefix):
"""Create FREENAS snapshot / iscsitarget name from Cinder name."""
backend_snap = 'snap-' + name.split('-')[1]
backend_target = 'target-' + name.split('-')[1]
backend_iqn = iqn_prefix + backend_target
return {'name': backend_snap,
'ta... | 90594d19e0e04c92937e1f976d3e0c480b802dac | 3,618,537 |
def GetTestPoint(name):
"""
Factory method to return a TestPoint object.
@params name: Desired name of the object.
"""
global GLOBAL_TOGGLE
# Only return a real object if
# TestPoints are enabled
if(GLOBAL_TOGGLE is True):
return TestPoint(name)
else:
return DummyPo... | 9ac51d71ca55387f5285baef9366c3a75af2882f | 3,618,538 |
import copy
import time
import torch
def train_classifier(model, optimizer, scheduler,dataloaders,device,kwargs):
"""This funcion performs training of classifier HEAD. It can be wrapped into the DNN
module as a class function
"""
num_epochs=kwargs['ep']
writer=kwargs['writer']
best_l... | 56228b761291cf0c0c7fc47fab7a3ecfb602af27 | 3,618,539 |
def get_token_list(text):
"""Returns a list of tokens.
This function expects that the tokens in the text are separated by space
character(s). Example: "ca n't , touch". This is the case at least for the
public DiscoFuse and WikiSplit datasets.
Args:
text: String to be split into tokens.
"""
return t... | 01a917fae5923cdfd693548bb688695a917fab70 | 3,618,540 |
import logging
def _search_children(statespace, node, expression, taint_result=None, constraint=[], index=0, depth=0, max_depth=64):
"""
Checks the statespace for children states, with JUMPI or SSTORE instuctions,
for dependency on expression
:param statespace: The statespace to explore
:param nod... | 479d5a08155c13c542f1dd4567706218837c474b | 3,618,541 |
def cut_string(string, limit=30):
"""Shorten the length of longer strings."""
if len(string) <= limit:
return string
else:
return string[:limit-3] + '...' | 842cfefcff84c4f146cc85a4e86dff1486e9a434 | 3,618,542 |
def dxp(u):
"""Backward finite differences in x direction.
Args:
u (ndarray): 2D input array.
Returns:
ndarray: Finite difference.
"""
u = np.mat(u)
dx = np.hstack((u[:, 1:], u[:, -1])) - u
return np.array(dx) | 6ef92c85a29ef43ed6f227fcd81e6400ce1ff8f4 | 3,618,543 |
def is_unique_dist_mat_energy(geo, ene, geo_list, ene_list):
""" compare given geo with list of geos all to see if any have the same
distance matrix and energy
"""
unique = True
for idx, geoi in enumerate(geo_list):
enei = ene_list[idx]
etol = 2.e-5
if abs(ene-enei) < etol:
... | 606c8f2c9ab4767ee8538a18ab1feddddf52165e | 3,618,544 |
def SeismogramEnsemble2Stream(sge):
"""
Convert a seismogram ensemble to stream
:param sge: seismogram ensemble input
:return: stream
"""
# This uses the same approach as TimeSeriesEnsemblet2Stream to handle
# ensemble metadata. See comments there for potential maintenanc issues
md = sg... | 890e5906fd0342f56cdc2c2a485b30a136126cf9 | 3,618,545 |
def hrm_training_job_title(row):
"""
Which Job Titles(s) the person is active with
"""
try:
person_id = row.hrm_training.person_id
except AttributeError:
# not available
person_id = None
if person_id:
s3db = current.s3db
table = s3db.hrm_human_resour... | dd91ac1a7d860e94f66a8aa72fb687f8bdafb396 | 3,618,546 |
import datasets
import os
def get_dataset(dataset, data_path, size, download=False):
"""
Loads a dataset
:param dataset: String. Name of dataset. Currently supports ['test', 'cifar10', 'cifar100', 'imagenet'].
Note that 'test' loads the 'cifar10'
:param data_path: String. Path to directory where ... | e4f6592a18929f3c9c8f8854080499d839df9fb5 | 3,618,547 |
import torch
def dct_N(x, perm=None, expk=None):
""" Batch Discrete Cosine Transformation without normalization to coefficients.
Compute y_u = \sum_i x_i cos(pi*(2i+1)*u/(2N)),
Impelements the N permuting trick to solve DCT with FFT in the following link,
https://dsp.stackexchange.com/questions/2807/... | 753148dec5c300001ad10b74d0f06de4f6aaa065 | 3,618,548 |
def portal(driver):
"""Return the 'portal' function, and the hint-annotator policy.
The portal is the function that gets patched with a call to the JIT
compiler.
"""
return tiny2.interpret, MyHintAnnotatorPolicy() | b9eb07439cabf0248ef7e6912c6432e7ea719f08 | 3,618,549 |
def format_results_for_suggestion(search_res: dict) -> list:
"""Format search movie results for `show_movie_suggestions()`
Parameters
----------
search_res : dict
result of `search_movie_from_query()`
Returns
-------
list
List of formated tuple for displays.
1st ele... | 165925bd65e09239c8c4c9ed7a62289ab09e962f | 3,618,550 |
def recommended_from_views(request):
""" get product recommendations based on products that the customer has viewed;
gets list of tracking IDs of other customers who have viewed the products in the current customer's
viewed products, and gets products that these other customers also viewed.
"""
t_i... | a53229f79baad8006640f7d3bd3ae46a1dd008ba | 3,618,551 |
def heading(heading_string, underline='='):
"""
Takes a raw string and underlines it with the given underline char
"""
return '%s\n%s' % (heading_string, underline * len(heading_string)) | 369385ffef60b88ba7e3a5c376236f6d4043ac72 | 3,618,552 |
from typing import Union
def cvx_kron(
expr_1: Union[np.ndarray, Expression], expr_2: Union[np.ndarray, Expression]
) -> Expression:
"""
Compute Kronecker product between CVXPY objects.
By default, CVXPY does not support taking the Kronecker product when the argument on the left is
equal to a CVX... | 0098816249de5cbabdee32cf88a652ab602899f3 | 3,618,553 |
def run_batch():
"""[Runs batch of 2D parameter scans]
Returns:
None
"""
for gr_Sfission in gr_Sfission_Vec:
for par0 in par0Vec:
if gr_Sfission == 0:
K_tot = K_tot_def * 6
else:
K_tot = K_tot_def
s... | 7fbe312b46f32515e869c759dcc1fb8ff293c50d | 3,618,554 |
from typing import Tuple
def optionally_resample(key: RandomKey, log_weights: Array, samples: Array,
resample_threshold: Array) -> Tuple[Array, Array]:
"""Call simple_resampling on log_weights/samples if ESS is below threshold.
The resample_threshold is interpretted as a fraction of the t... | 839607b0f57c7c8c7669426f65032190f7bc2a71 | 3,618,555 |
def composed_measurement(ec_measurement):
"""Fixture that returns a composed measurement"""
measurement1 = ec_measurement.select(cycle=1)
measurement2 = ec_measurement.select(cycle=3)
return measurement1 + measurement2 | f7aa5891b7a9f88e2d18723cd526ff48044d0fd8 | 3,618,556 |
def construct_trace_net(trace, trace_name_key=xes_util.DEFAULT_NAME_KEY, activity_key=xes_util.DEFAULT_NAME_KEY):
"""
Creates a trace net, i.e. a trace in Petri net form.
Parameters
----------
trace: :class:`list` input trace, assumed to be a list of events
trace_name_key: :class:`str` key of t... | d59a02c50ab7241af2bbd70bed927943b2690c4b | 3,618,557 |
def MurtyPartition(N, a, type):
"""
MurtyPartition partitioin node N with its minimum assignment a
input:
N - in Murty's original paper, N is a "node", i.e. a non empty
subset of A, which contains all assignment schemes.
a - a nMeas*1 vector containing one assignment scheme.
type -... | 6a256d41081f3f2a501469435560c95ece32ef62 | 3,618,558 |
def create_dataset(param):
"""
Create a dataset given the parameters.
"""
dataset_class = find_dataset_using_name(param.dataset_mode)
# Get an instance of this dataset class
dataset = dataset_class(param)
print("Dataset [%s] was created" % type(dataset).__name__)
return dataset | 845ae2c70cca3a373c88e6dd7d98d7daedb9115f | 3,618,559 |
from typing import Optional
import ray
import uuid
import time
def run(entry_workflow: Workflow,
workflow_id: Optional[str] = None,
overwrite: bool = True) -> ray.ObjectRef:
"""Run a workflow asynchronously.
# TODO(suquark): The current "run" always overwrite existing workflow.
# We need ... | ed1aa327ba567f69adbfc41409bd6d057df2f66a | 3,618,560 |
import six
def fully_connected(inputs,
num_outputs,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None... | ad5c8b569308e3e816b87e53c1fe2103270b851e | 3,618,561 |
async def get_snapshot(request):
""" get list of available snapshots
:Example:
curl -X GET http://localhost:8081/foglamp/snapshot/category
curl -X GET http://localhost:8081/foglamp/snapshot/schedule
When auth is mandatory:
curl -X GET http://localhost:8081/foglamp/snaps... | ca7fc806cc4c0e5ec1133a61c6ee4d5ed2e9a31b | 3,618,562 |
def score_sig_1A(sim, est_distrib):
"""
euclidian norm between normalized trinucleotide context counts (empirical),
and the reconstituted profile
"""
raw_data_distrib = np.zeros(96)
val, c = np.unique(sim.T, return_counts=True)
raw_data_distrib[val.astype(int)] = c
raw_data_distrib = raw... | 45e5cff15f545766652af11a75b81208206009cb | 3,618,563 |
import os
def problem_default_script(request, script_name: str):
"""
Function to provide the facility to download the
default compilation or test script.
:param request: the request object used
:type request: HttpRequest
:param script_name: name of the script - one of `compilation_script` or ... | 5fb78a635fea287cd28cfa7918c7583193a312ff | 3,618,564 |
def permission_to_edit_page(request, page, context={}):
"""Calls user.permission_to_edit_page() on the user in the request, or
returns False if no user in the request."""
if hasattr(request, 'user') and request.user.is_authenticated():
profile = get_profile(request.user)
if profile:
... | 3df73351c1a73d454b8c5bfcc495f4c3ba9b06b4 | 3,618,565 |
def is_admin_user():
"""判断是否是管理员用户分配不同的逻辑"""
# 访问管理员登录页面,不需要拦截处理
if request.url.endswith('/admin/login'):
pass
else:
# 每一次请求之前都进行拦截判断处理
# 1.用户id
user_id = session.get("user_id")
# 2.管理员标志位
is_admin = session.get("is_admin", False)
# 如果用户没有登录,或者登录... | 2a1c7d5f8955d7a28ea3b572e2b7a44ffcc07bdc | 3,618,566 |
def ecdf_formal(x, data):
"""
Compute the values of the formal ECDF generated from `data` at x.
I.e., if F is the ECDF, return F(x).
Parameters
----------
x : int, float, or array_like
Positions at which the formal ECDF is to be evaluated.
data : array_like
One-dimensional a... | 61fd43be4cbd762718ca3a51dac131ddaaf7c373 | 3,618,567 |
def AverageOverlap(l1, l2, depth = 10):
"""Calculates Average Overlap score.
l1 -- Ranked List 1
l2 -- Ranked List 2
depth -- depth
@author: Ritesh Agrawal
@Date: 13 Feb 2013
@Description: This is an implementation of average overlap measure for
comparing two score
(R... | 9cec7fcf500ae6e59eb44e6bad4a9b5c376f87c3 | 3,618,568 |
def _view_connections_cmd(options):
"""
Return the post_setup hook function for 'openmdao view_connections'.
Parameters
----------
options : argparse Namespace
Command line options.
Returns
-------
function
The post-setup hook function.
"""
def _viewconns(prob):... | 5bdfb53e8bd1053ae7f78fe4ca211f25d01ba479 | 3,618,569 |
def three_shouts(word1, word2, word3):
"""Returns a tuple of strings
concatenated with '!!!'."""
# Define inner
def inner(word):
"""Returns a string concatenated with '!!!'."""
return word + '!!!'
# Return a tuple of strings
return (inner(word1), inner(word2),inner(word3)) | d7986646a48fcdd3448d834d59ce497c292a984d | 3,618,570 |
import functools
def accepts(*accepted_arg_types):
"""
A decorator to validate the parameter types of a given function.
It is passed a tuple of types. eg. (<type 'tuple'>, <type 'int'>)
Note
-----
It doesn't do a deep check, for example checking through a
tuple of types. The argument pass... | 47173f7933714da5661c0841fe2479a6da147cbd | 3,618,571 |
from typing import Union
from typing import Dict
from typing import OrderedDict
def trigger_to_dict(trigger: Union[DateTrigger, IntervalTrigger, CronTrigger]) -> Dict:
"""Converts a trigger to an OrderedDict."""
data = OrderedDict()
if isinstance(trigger, DateTrigger):
data['trigger'] = 'date'
... | 6f25cf80218957519f36dae2bef25d9408a00f6a | 3,618,572 |
from datetime import datetime
import re
def run_sentiment(model, tokenizer, device):
"""
SECTION : sentiment
DESCRIPTION 1: Running sentiment analysis using comments from 'video_comment.pkl'
DESCRIPTION 2: Calling 'run_model' function to run BERT model
"""
# ====================== Setup ======... | 743cafb3b42a5c80d222d4f40c99c85a18316b09 | 3,618,573 |
from qmt.tasks import Task
import numpy as np
def fix_task_env():
"""
Set up a testing environment for tasks.
"""
class InputTaskExample(Task):
"""Simple example task. This is the first task in the chain.
:param dict options: Dictionary specifying the input parts. It should be of the... | 01edc228466f2ea6cdc52876a24b98cea3aef2d0 | 3,618,574 |
import os
import yaml
from datetime import datetime
def participants(root_dir):
"""
Render the participants page,
which shows a directory of all
the students with their forge
links, blog posts, assignment
links, and etc.
"""
yaml_dir = app_path('people', root_dir)
student_data =... | d34504c3b390e856a202a308694311f8800ca5e1 | 3,618,575 |
def adjacency_list_from_adjacency_list_bipartite(old_adj_list):
"""
Creates the adjacency list from another adjacency list, converting the data type to integers.
Method for bipartite networks.
Returns two dictionaries, each representing an adjacency list with the rows or columns as keys, respectively.
... | e21dd0eeaa2a4255605a79a3d6076d9c13b1c1c0 | 3,618,576 |
def is_integer(db_type):
"""Return True if the database type is an integer supported type, False otherwise.
"""
return db_type in ACCEPTED_INTEGER_DB_TYPES | ae499501da19dd01e10fc334911254446a01cbee | 3,618,577 |
def add_custom_header(res):
"""レスポンスにカスタムヘッダーを追加する。"""
res.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
res.headers["Expires"] = "0"
res.headers["Server"] = "Roppo-JSON"
return res | 7ed261a4aa9d4aa532bd2c07544a4ffe4ec1cafb | 3,618,578 |
import html
def render_form():
"""Render form for selecting genes and samples."""
genes_options = [
{"label": gene_symbol, "value": gene_symbol}
for gene_symbol in natsorted(
set((tx.gene_symbol for tx in genes.load_transcripts().values()))
)
]
samples_options = [
... | 5aa744916c98b4748b22e1bd502cbf4e2a03dd12 | 3,618,579 |
from typing import List
def _get_table_ids(
api: ThoughtSpot,
*,
db: str,
schema: str='falcon_default_schema',
table: str=None
) -> List[str]:
"""
Returns a list of table GUIDs.
"""
r = api._metadata.list(type='LOGICAL_TABLE', subtype=['ONE_TO_ONE_LOGICAL'])
table_details = r.j... | 0d0f82f4439a239750b00753664ae8af00d992cc | 3,618,580 |
def get_entity_heading(geopoint):
"""
Acquires heading based on spawn position in map.
Prompts user to select lane if multiple lanes exist at spawn position.
Throws error if spawn position is not on lane.
Args:
geopoint: [AD Map GEOPoint] point of click event
Returns:
lane_head... | 7e39f9b27355c6d4feed27e3b7f574103db77942 | 3,618,581 |
import warnings
def plot_face(
model=None,
au=None,
vectorfield=None,
muscles=None,
ax=None,
feature_range=False,
color="k",
linewidth=1,
linestyle="-",
gaze=None,
*args,
**kwargs
):
"""Function to plot facesself
Args:
model: sklearn PLSRegression insta... | e136bec9ae0a3e9a7dc3dc7da8dfef0d4b3fab77 | 3,618,582 |
def find_cell_with_tag(nb, tag):
"""
Find a cell with a given tag, returns a cell, index tuple. Otherwise
(None, None)
"""
out = find_cell_with_tags(nb, [tag])
if out:
located = out[tag]
return located['cell'], located['index']
else:
return None, None | bcfdbefbb9e0dd052a6da5ab8bda6ba48749bb9e | 3,618,583 |
def profile_to_node(src_profile):
"""convert source profile to graph node."""
return (src_profile['uid'], src_profile) | 970d349c2884dd57d10bef8f7e2649509e480a62 | 3,618,584 |
def instruction_interval_seconds():
""" returns every how many seconds there should be a check for new instructions """
if instruction_interval_overwrite is None:
return float(_get_option_with_default('instruction_check_interval_time_seconds', DEFAULT_INSTRUCTION_CHECK_INTERVAL_SECONDS))
else:
... | 98d417e0cbc8eecd995df0dc9c1294ee06fd3f10 | 3,618,585 |
from typing import Union
from typing import Callable
from typing import Optional
from typing import Tuple
def sample(
sampler: Sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
*,
state: Optional[SamplerState] = None,
chain_length: int = 1,
) -> Tuple[jnp.ndarray, SamplerState]... | d0addc00b2759e35f19ddbbcd591225b60ab968e | 3,618,586 |
import psutil
def get_dist_usage():
"""得到硬盘使用"""
return psutil.disk_usage('/') | 72144a5e493d630a96a2ba92f35a836f9c76edb3 | 3,618,587 |
def set_center(data, origin, crop='maintain_size', axes=(0, 1), verbose=False,
center=_deprecated):
"""
Move image origin to mid-point of image.
Parameters
----------
data : 2D np.array
the image data
origin : tuple
(row, column) coordinates of the image origin
... | 86dca72f9de8927315efaa185c0a636f341354d8 | 3,618,588 |
def index():
"""Global index for the whole application."""
golab = app.config.get('GOLAB', False)
return render_template("index.html", golab = golab) | eb93523c02074cea28fe1594251cde255e2a4423 | 3,618,589 |
import base64
def compile_program(client, code):
"""This Functon helps to compile
our source code
Args:
client: [description]
code: source code
Returns:
Encoded compiled code
"""
compiler_response =client.compile(code)
return base64.b64decode(compiler_response["... | e666a420b0c2b96d46d6b096e1fb3f2e570dee87 | 3,618,590 |
import aiohttp
import json
async def make_request(model_id, message):
"""Make asynchronous call to model service
:param model_id: str
:param message: dict
:return: response for the service as dict
"""
async with aiohttp.ClientSession(headers={'Content-Type': 'application/json'}) as session:
... | d1567628853a29eff984ec33797e9484b2f3f3fb | 3,618,591 |
import argparse
def parse_args():
"""parse custom arguments and set default value"""
parser = argparse.ArgumentParser(
description="Trim spaces at the end of every lines."
)
parser.add_argument("-R", "-r", action="store_true", help="Whether to recursive")
parser.add_argument("-y", "--yes",... | 8aff3fba3f9c5af0e98d938c544d1dde08977086 | 3,618,592 |
def load_image(img_path, df_info, reduce_factor=1):
"""
Load image and make sure sizes matches df_info
"""
image_fname = img_path.rsplit("/", -1)[-1]
W = int(df_info[df_info.image_file == image_fname]["width_pixels"])
H = int(df_info[df_info.image_file == image_fname]["height_pixels"])... | fde1cb2031a3614f082559040058e952bf80b624 | 3,618,593 |
def mult(v1, m):
"""multiplies a vector"""
return (v1[0]*m,v1[1]*m) | 5055a89c9e3175d103071c09a4553cc6b1528bae | 3,618,594 |
def linear_function_fa(A, W, B, b=None):
"""An alias for using class :class:`LinearFunctionFA`.
Args:
(....): See docstring of method :meth:`LinearFunctionFA.forward`.
"""
# Note, `apply()` doesn't allow keyword arguments, which is why we build
# this wrapper.
if b is None:
retu... | 77d34d876f9e49e16161ef4a5cfeb8f8ef06caf0 | 3,618,595 |
def dis_ten(fea):
"""fea: Series"""
fea_range = [fea.quantile(x) for x in np.arange(11)/10.]
fea_range[0] = fea_range[0] - 0.1
fea_range = set(fea_range)
fea_range = np.sort(list(fea_range))
return pd.cut(fea,fea_range,labels=np.arange(len(fea_range)-1)) | 336bc56c8bae0ade6ea72603785f90f553ab8305 | 3,618,596 |
def default_seed():
"""Default numpy.random.Generator seed.
Returns
-------
int
"""
return 7 | fb1b29d333ce36ca359002db761d50524438b671 | 3,618,597 |
def get_height_variable_name(obj, variable=None):
"""
Determines the height variable name in the Dataset using variable
coordinate information.
Parameters
----------
obj : Xarray.Dataset
Xarray Dataset containing data
variable : string
Varible name to correct
Returns
... | a302c2c0473eee6912eab95056836c30f153c889 | 3,618,598 |
def mass_metric(sat_size, sat_mass):
"""
This function calculates the metric for the mass of the satellite based upon the maximum allowed for its size.
:param sat_size: Either 1, 1.5, 2 or 3, to correlate to CubeSat sizes of 1U, 1.5U, 2U and 3U
:param sat_mass: the total mass of the satellite including ... | bc8a47aa3f1419eba8ce3dd5050e14e271d9a3f0 | 3,618,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.