content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def to_local_js_timestamp(utc_datetime):
"""Convert a UTC datetime into a local time timestamp suitable for the JavaScript date object"""
return int(datetime.timestamp(utc_datetime.replace(tzinfo=timezone.utc).astimezone(tz=None)) * 1000) | 5,291,500 |
def userfcn_dcline_formulation(om, args):
"""This is the 'formulation' stage userfcn callback that defines the
user constraints for the dummy generators representing DC lines.
It expects to find a 'dcline' field in the ppc stored in om, as
described above. By the time it is passed to this callback,
... | 5,291,501 |
def read_raw(path):
"""Return the contents of `path`.
Parameters
==========
path : string
Input data file (may be compressed)
Returns
=======
data : pandas DataFrame
Contents of `path`
"""
# Set compression type
if path.endswith('.gz'):
compression = 'g... | 5,291,502 |
def get_module_version_list(module_list, tainted):
"""Returns a list of pairs (module name, version name) to fetch logs for.
Arguments:
module_list: list of modules to list, defaults to all modules.
tainted: if False, excludes versions with '-tainted' in their name.
"""
result = []
if not module_list... | 5,291,503 |
def get_distrib_param_vars(
distrib_id,
init_params,
const_params=None,
num_class=None,
random_seed=None,
alt_distrib=False
):
"""Creates tfp.distribution and tf.Variables for the distribution's
parameters.
Parameters
----------
distrib_id : str
Name of the distribut... | 5,291,504 |
def mfuncC(f, x):
"""
Deprecated
"""
raise NotImplementedError('Deprecated - needs clean room implementation') | 5,291,505 |
def _assign_interval_base(x, boundaries):
"""Assign each value in x an interval from boundaries.
Parameters
----------
x: numpy.array, shape (number of examples,)
The column of data that need to be discretized.
boundaries: numpy.array, shape (number of interval boundaries,)
... | 5,291,506 |
def angle_between_vectors(v1, v2, v3):
"""
Compute the angle between the vector (v2, v3) and (v1, v2)
The angle is constrained to lie in [-np.pi, np.pi]
No turn will result in an angle of 0.
A left turn will produce a positive angle.
A right turn will produce a negative angle.
The function... | 5,291,507 |
def get_config_parameter_path(param_name):
"""Finds path where Config parameter is stored.
Paramters
---------
param_name: str
Name of parameter
Returns
-------
If parameter is overridden in Model Instance, then path of
parameter from Model Instance is returned else platfor... | 5,291,508 |
def ts(nodes, topo_order): # topo must be a list of names
"""
Orders nodes by their topological order
:param nodes: Nodes to be ordered
:param topo_order: Order to arrange nodes
:return: Ordered nodes (indices)
"""
node_set = set(nodes)
return [n for n in topo_order if n in node_set] | 5,291,509 |
def test_setext_headings_extra_a2():
"""
Test case extra A2: SetExt heading with full image with label newline in url link
"""
# Arrange
source_markdown = """aa
---"""
expected_tokens = [
"[setext(3,1):-:3::(1,1)]",
"[text(1,1):a:]",
"[image(1,2):inlin... | 5,291,510 |
def energy_loss(ef_energy='x', gv_energy='x', n='x'):
"""
Calculate and return the value of energy loss using given values of the params
How to Use:
Give arguments for ef_energy and gv_energy parameters
or,give arguments for efficiency and gv_energy parameters
*USE KEYWORD ARGUME... | 5,291,511 |
def normalize_min_max(x, axis=None):
"""
Parameters:
----------
x: np.array()
target array
axis: int
target axis
Returns:
----------
np.array()
normalized array so that the maximum value is 1 and the minimum value is 0
"""
min = x.min(axis=axis, keepdims... | 5,291,512 |
def save_file(file_name, data, fmt='%.8e', sort_keys=True, indent=4):
"""
Save data file of given path, use numpy.load if it is in .npy format,
otherwise use pickle or imageio
:param file_name: absolute path to the file
:param data: data to save
:return: file data, or IOError if it cannot be sav... | 5,291,513 |
def extractDate(line):
"""
extracts time from an event file input line
and returns a datetime object.
""" | 5,291,514 |
def get_2nd_or_3rd():
"""
Returns all 2nd or 3rd degree connections for a user
http://127.0.0.1:5000/2nd3rd/?ourid=3
"""
args = request.args
ourid = args['ourid']
return jsonify({'result' : n4jinstance.get_2nd_or_3rd(ourid) }) | 5,291,515 |
def get_features_route(model_name: str, file_hash: str) -> str:
"""Gets the features of a file from the dataset.
Args:
model_name (str): Name of the model
file_hash (str): Hash of the file
Raises:
PredictionNotCalledFirstError: The prediction route was not called
before... | 5,291,516 |
def fitted_predicted_OK3(X, y, Tree):
"""Function running OK3 and returning Y_train, Y_test, and Y_preds, for readability purposes
Parameters
----------
X : np.ndarray
features of the dataset
y : np.ndarray
labels of the dataset
Tree : estimator
estimator to fit and pred... | 5,291,517 |
def About(parent):
"""Display the about SPPAS dialog.
:author: Brigitte Bigi
:organization: Laboratoire Parole et Langage, Aix-en-Provence, France
:contact: develop@sppas.org
:license: GPL, v3
:copyright: Copyright (C) 2011-2018 Brigitte Bigi
:param parent: (wx.Window)
... | 5,291,518 |
def load_fold_indices(path):
"""Load the stard and end indices of the test set for every fold."""
filename = os.path.join(path, 'dataset_fold_indices.json')
with open(filename, 'r') as handle:
parsed = json.load(handle)
return json.dumps(parsed['short'], indent=4) | 5,291,519 |
def _map_remote_share(share_system_name: str = None, share_user: str = None,
share_pass: str = None, share_location_format_str: str = None,
share_ignores: List[str] = None,
is_remote_system_drive: bool = True) \
-> Tuple[str, Optional[Dict[str, A... | 5,291,520 |
async def test_echo(server):
"""
Test basic RPC with a simple echo
"""
async with WebSocketRpcClient(uri, RpcUtilityMethods(), default_response_timeout=4, serializing_socket_cls=BinarySerializingWebSocket) as client:
text = "Hello World!"
response = await client.other.echo(text=text)
... | 5,291,521 |
def print_allergies(tables: dict) -> None:
"""Print a list of all the people with their allergies."""
people = []
for name, table in tables.items():
for pair in table:
people.extend(pair)
people.sort(key=lambda x: x.name.split(" ")[-1])
print(f"\n\n\nPERSON -- TABLE -- ALLERGIES... | 5,291,522 |
def default_formatter(route_docs):
"""
解析所有路由中方法的doc成为字典
in: {url_pattern:{ method:method_doc, method:method_doc }}
Return:{url_pattern:{ method:method_dict, method:method_dict }}
"""
paths_dict = dict( (up, dict()) for up in route_docs.iterkeys())
for up, method_dict in route_docs.iter... | 5,291,523 |
def values_reducer(values_fn: Callable) -> Reducer:
"""Return a reducer that just applies values_fn to its values"""
def reduce(key, values: Iterable) -> KV:
return (key, values_fn(values))
return reduce | 5,291,524 |
def background_subtraction_quant_function(im, spool, t, frames, quant_radius=3, quant_z_radius=1, quant_voxels=20, background_radius=30, other_pos_radius=None, threads_to_quantify=None, quantified_voxels=None):
"""
Takes the mean of the 20 brightest pixels in a 3x7x7 square around the specified position minus t... | 5,291,525 |
def _get_topics_by_token(push_token):
"""
:param push_token: required
:return: topics, to which this token is subscribed (tags)
"""
firebase_server_key = "SERVER_KEY"
firebase_info_url = "FIREBASE_INFO_URL" # "https://iid.googleapis.com/iid/info/"
auth_key = "key=%s" % firebase_server_key
... | 5,291,526 |
def setconfig_dict(ui, section, items):
"""
Set's many configuration items with one call. Defined mostly
to make some code (including doctests below) a bit more readable.
>>> import mercurial.ui; ui = mercurial.ui.ui()
>>> setconfig_dict(ui, "sect1", {'a': 7, 'bbb': 'xxx', 'c': '-'})
>>> setcon... | 5,291,527 |
def main():
"""
Entry point
"""
circ_primes = [i for i in range(2, 1000000) if is_circular_prime(i)]
print(f"Number of circular primes: {len(circ_primes)}") | 5,291,528 |
def test():
"""
Stub script entry point. Authenticates CloudGenix SDK, and gathers options from command line to run do_site()
:return: No return
"""
global TOOLKIT_TEST_TIMEOUT
# Parse arguments
parser = argparse.ArgumentParser(description="{0} Run Plan ({1})".format(GLOBAL_MY_SCRIPT_NAME,
... | 5,291,529 |
def set_product_options(name, version):
"""Set the options needed by the product template"""
data = request.get_data().decode('utf-8')
product = registry.get_product(name, version)
product.options = data
return '', 204 | 5,291,530 |
def compute_and_update_frame_translations_dt(imp, channel, dt, process, shifts = None):
""" imp contains a hyper virtual stack, and we want to compute
the X,Y,Z translation between every t and t+dt time points in it
using the given preferred channel.
if shifts were already determined at other (lower) dt
the... | 5,291,531 |
def prepare_target_corpus_parallel(_lang_pair, _target):
"""
immigrant
fr-en:
29077
732
1651
1472
total: 32932
"""
print(_lang_pair)
print(_target)
_lang_s, _lang_t = _lang_pair.split('-')
_query_src = r'{}'.format('|'.join... | 5,291,532 |
def query_data_for_timespan(pdb, start, end):
"""
Retrieve all desired data for one day, from PuppetDB
:param pdb: object representing a connected pypuppetdb instance
:type pdb: one of the pypuppetdb.API classes
:param start: beginning of time period to get data for
:type start: Datetime
:p... | 5,291,533 |
def sigmoid_activation(aggregate: numpy.ndarray) -> float:
"""
:param aggregate: an array whose elements are the aggregate of all the inputs from the previous layer.
For instance, the first element of the array is the aggregate of all input coming into the first node,
the second element of the array is... | 5,291,534 |
def get_intrinsic_matrix(field_of_view_deg, image_width, image_height):
"""
Returns intrinsic matrix K.
"""
# For our Carla camera alpha_u = alpha_v = alpha
# alpha can be computed given the cameras field of view via
field_of_view_rad = field_of_view_deg * np.pi/180
alpha = (image_wid... | 5,291,535 |
def remove_dev(id):
"""Apagar parametro filtrando pela id"""
index = id
del devs[index]
return jsonify({'message': 'Dev is no longer alive'}), 200 | 5,291,536 |
def _get_configuration(resource_root, cluster_name, type, tag="version1"):
"""
Get configuration of a cluster
@param resource_root: The root Resource .
@param cluster_name: cluster_name
@param type: type of config
@return: A ConfigModel object
"""
dic = resource_root.get(
paths.C... | 5,291,537 |
def test_admin_view_access_and_render(init_app):
"""Make sure route '/cabinet' works and template with cabinet form is rendered"""
app = init_app
with captured_templates(app) as templates:
with app.test_client() as client:
# User is not authenticated
response_admin_view = cl... | 5,291,538 |
def create_job():
"""Create a job."""
blob = request.get_json(force=True)
payload = blob["payload"]
state = blob.get("state", None)
job = request.q.create(payload, state)
return jsonify(job_as_json(job)), 200 | 5,291,539 |
def test_update_organization_mutation(db, permission_client):
"""
Only users with the change_organization permission may update an
organization entity.
"""
user, client = permission_client(["change_organization"])
organization = OrganizationFactory(members=[user])
variables = {
"id"... | 5,291,540 |
def import_model(sklearn_model):
"""
Load a tree ensemble model from a scikit-learn model object
Parameters
----------
sklearn_model : object of type \
:py:class:`~sklearn.ensemble.RandomForestRegressor` / \
:py:class:`~sklearn.ensemble.RandomForestClassifier... | 5,291,541 |
async def test_dynalite_shutdown_with_server_down(mock_gateway):
"""Test when shutting down while the server is down. Different flow in async_reset."""
[device] = mock_gateway.configure_dyn_dev(
{
dyn_const.CONF_ACTIVE: False,
dyn_const.CONF_AREA: {"1": {dyn_const.CONF_CHANNEL: {... | 5,291,542 |
def cir_Randles_simplified_Fit(params, w):
"""
Fit Function: Randles simplified -Rs-(Q-(RW)-)-
Return the impedance of a Randles circuit. See more under cir_Randles_simplified()
NOTE: This Randles circuit is only meant for semi-infinate linear diffusion
Kristian B. Knudsen (kknu@berkeley.edu || kr... | 5,291,543 |
def read_pubmed_to_genes():
"""NCBI provides a list of articles (PMIDs) that discuss a particular gene (Entrez IDs).
These provide a nice positive distant supervision set, as mentions of a gene name in
an article about that gene are likely to be true mentions.
This returns a dictionary that maps from Pubmed ... | 5,291,544 |
def MTFL(args):
"""
The protected feature is faces with or without glasses.
Clusters are tested in binary gender classification.
Pictures are 224x224 with 2 labels.
"""
transform = transforms.Compose([ # suggested transform for resnet50 encoder
transforms.Resize(256),
transforms... | 5,291,545 |
def return_slice(axis, index):
"""Prepares a slice tuple to use for extracting a slice for rendering
Args:
axis (str): One of "x", "y" or "z"
index (int): The index of the slice to fetch
Returns:
tuple: can be used to extract a slice
"""
if axis == "x":
return (sli... | 5,291,546 |
def load_files_from_dir(dir, pattern = None):
"""Given a directory, load files. If pattern is mentioned, load files with given pattern
Keyword arguments:
text -- given text
delimiter - type of delimiter to be used, default value is '\n\n'
"""
files_in_path = os.listdir(dir)
... | 5,291,547 |
def prep_table(opts):
"""
Load the default orbital.
Enter: opts: a dictionary of options. Modified.
"""
opts['base'] = open(opts['orbfile']).read() | 5,291,548 |
def rank(txt_path,reverse = True):
"""
@param txt_path:需要进行排列的txt文件
@param reverse:默认是升序
"""
data = {}
new_data = {}
with open(txt_path, 'r') as f1:
dataroot = os.path.dirname(txt_path)
for i in f1.readlines():
name = i.split(' ')[0].strip()
score = ... | 5,291,549 |
def load_data(pickle_file):
"""Loads a data from a pickle file."""
print("Loading data...")
dict_dataset = load_pickle(pickle_file)
train_dataset = dict_dataset['train_dataset']
val_dataset = dict_dataset['val_dataset']
test_dataset = dict_dataset['test_dataset']
train_labels = dict_dataset[... | 5,291,550 |
def test_gradient_step(var_f, len_f, var_y, N):
"""
test whether MarkovGP and SparseMarkovGP provide the same initial gradient step in the hyperparameters (Z=X)
"""
x, y = build_data(N)
gp_model = initialise_gp_model(var_f, len_f, var_y, x, y)
sparsemarkovgp_model = initialise_sparsemarkovgp_m... | 5,291,551 |
def unfold(data, prefix='', delimeter='__'):
"""
>>> _dd(unfold({'a': 4, 'b': 5}))
"{'a': 4, 'b': 5}"
>>> _dd(unfold({'a': [1, 2, 3]}))
"{'a__0': 1, 'a__1': 2, 'a__2': 3}"
>>> _dd(unfold({'a': {'a': 4, 'b': 5}}))
"{'a__a': 4, 'a__b': 5}"
>>> _dd(unfold({'a': {'a': 4, 'b': 5}}, 'form'))
... | 5,291,552 |
def load_modules(obj, loaded):
"""
Load bracket plugin modules
"""
plib = obj.get("plugin_library")
if plib is None:
return
try:
module = ImportModule.import_module(plib, loaded)
obj["compare"] = getattr(module, "compare", None)
obj["post_match"] = getattr(modul... | 5,291,553 |
def run():
"""
Do a telluric correction.
"""
# Store current working directory for later use.
path = os.getcwd()
# Set up the logging file.
log = os.getcwd()+'/Nifty.log'
logging.info('\n#################################################')
logging.info('# ... | 5,291,554 |
def get(*args, **kwargs):
"""Decorates a test to issue a GET request to the application. This is
sugar for ``@open(method='GET')``. Arguments are the same as to
:class:`~werkzeug.test.EnvironBuilder`.
Typical usage::
@frontend.test
@get('/')
def index(response):
ass... | 5,291,555 |
def photographer_required(func):
"""
if used to make sure the the current user is sa photographer
:param func:
:return:
"""
@wraps(func)
def decorated_view(*args, **kwargs):
if current_user.photographer is None:
flash("You are not yet registered as a photographer")
... | 5,291,556 |
def test_metric():
"""Test the basic metric"""
metric = Metric()
exception_raised = False
try:
with monitor(metric):
1.0 / 0 # pylint: disable=pointless-statement
except ZeroDivisionError:
exception_raised = True
assert exception_raised
assert metric.error is not... | 5,291,557 |
def parse_arch_json_from_file(arch_json_path: str, photoroom_csv_path: str) -> House:
"""
Parses a house given the arch.json and the photoroom.csv
:param arch_json_path: str: Path to arch.json
:param photoroom_csv_path: str: Path to photoroom.csv
:return: Parsed house
"""
with open(arch_jso... | 5,291,558 |
def Singleton_args(theClass):
""" decorator for a class to make a singleton out of it """
classInstances = {}
def getInstance(*args, **kwargs):
""" creating or just return the one and only class instance.
The singleton depends on the parameters used in __init__ """
key = (theCla... | 5,291,559 |
def read_py_file(filename, skip_encoding_cookie=True):
"""Read a Python file, using the encoding declared inside the file.
Parameters
----------
filename : str
The path to the file to read.
skip_encoding_cookie : bool
If True (the default), and the encoding declaration is found in t... | 5,291,560 |
def makePaperFigure(dim=64):
"""
Make a video showing how FTM2D stays the same for rotated
patches
"""
from Kuramoto import KSSimulation
dim = 64
fac = 0.5
ks = KSSimulation(co_rotating=False, scale=(fac*7, fac/2))
ks.I = ks.I[0:int(195*fac), :]
#ks.I = np.random.randn(ks.I.shape... | 5,291,561 |
def atSendCmdGetTradingTime(targetList, kFreq, beginDay, endDay):
""" 获取标的频率周期的交易时间
:param targetList: targetList: list[dict] [{'Market':marketName, 'Code': CodeName },]
:param kFreq: K线频率
:param beginDay: 开始时间
:param endDay: 结束时间
:return: str, mat 文件路径 或者 at 返回的错误信息
::
保存交易时间的mat文件... | 5,291,562 |
def run():
""" Wrapper around main() for exception handling """
try:
main()
except KeyboardInterrupt:
sys.exit(">> Caught user interrupt. Exiting...") | 5,291,563 |
def ts_min(x):
"""
[Definition] 对x中的每个时间序列在period范围内滚动求最小值
[Category] 统计
"""
# 取前n天数据的最小值
return 'ts_min(%s,%s)' %(x, pe.gen_param('ts_min','period')) | 5,291,564 |
def marketplace_delete():
"""Delete marketplace entities"""
pass | 5,291,565 |
def rotation_matrix(angle, direction, point=None, dtype=np.float32):
"""Return matrix to rotate about axis defined by point and direction.
http://www.lfd.uci.edu/~gohlke/code/transformations.py.html
"""
assert direction.dtype == dtype, "Wrong: %s" % direction.dtype
sina = dtype(np.math.sin(angle))
... | 5,291,566 |
def good_partner_matrix(results, nplayers, repetitions):
"""
An n by n matrix of good partner ratings for n players
Parameters
----------
results : list
A cooperation results matrix of the form:
[
[[a, j], [b, k], [c, l]],
[[d, m], [e, n], [f, o]],
... | 5,291,567 |
def _date_keyboard(possible_dates):
"""Creates a keyboard of possible crab dates."""
date_keyboard = [
[InlineKeyboardButton(possible_dates["1"]["formatted"], callback_data=possible_dates["1"]["string"]),
InlineKeyboardButton(possible_dates["2"]["formatted"], callback_data=possible_dates["2"]["... | 5,291,568 |
def parse_filename(filename):
""" Extract parameters from filename with the pattern
prediction_w=100_k=200_m=4096.txt
"""
w, k, C = None, None, None
for token in os.path.splitext(os.path.basename(filename))[0].split("_"):
if "=" in token:
param, value = token.split("=")
... | 5,291,569 |
def lite_plus_tot_functions():
""" Return the total number of lite_plus function extentions."""
return len(GLOBAL_REGISTER_LIST) | 5,291,570 |
def add(high, low):
"""Vector Arithmetic Add
:param high:
:param low:
:return:
:real:
"""
return ADD(high, low) | 5,291,571 |
def register(site=None):
"""Register the plugin in the ListAdminView class"""
if site is None:
site = xadmin.sites.site
from xplugin_generic_search.plugin import GenericSearchPlugin
site.register_plugin(GenericSearchPlugin, ListAdminView) | 5,291,572 |
def submissions(ctx, start_date, end_date):
"""
Display submissions to a particular challenge.
"""
"""
Invoked by running `evalai challenge CHALLENGE phase PHASE submissions`.
"""
display_my_submission_details(ctx.challenge_id, ctx.phase_id, start_date, end_date) | 5,291,573 |
def create_random_moves(depth):
"""
Создает и возвращает массив из depth случайных объектов Move.
"""
pass | 5,291,574 |
def FunctionExitAction(func):
"""Get an argparse.Action that runs the provided function, and exits.
Args:
func: func, the function to execute.
Returns:
argparse.Action, the action to use.
"""
class Action(argparse.Action):
def __init__(self, **kwargs):
kwargs['nargs'] = 0
super(Act... | 5,291,575 |
def features(im, max_features=6, min_pixels=50):
"""
Returns a list of features found in `im`.
Args:
im (Image): Source image.
max_features (int): The maximum number of features to return.
min_pixels (int): The minimum number of pixels a feature must
contain to b... | 5,291,576 |
def test_max_cuts_zero_succeeds():
"""Tests the circuit-to-ordering conversion."""
qubits = [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)]
size = 4
for x in range(size):
qubits.append([cirq.GridQubit(x, y) for y in range(size)])
moments = (cirq.Moment([cirq.CZ(qubits[0], qubits[1])]),
... | 5,291,577 |
def execute_barrbap(organism, dna_file):
"""determines the 16sRNA sequences using barrnap tool"""
# barrnap output file name e.g. barrnap.NC_000913
barrnap_out = cwd + "/barrnap." + organism
# > /dev/null 2>&1 is to disable stdout from displaying on terminal
barrnap_cmd = "barrnap " + str(dna_file) ... | 5,291,578 |
def point_to_point():
"""Point to point communication
Send a numpy array (buffer like object) from rank 0 to rank 1
"""
if rank == 0:
print("point to point")
data = np.array([0, 1, 2], dtype=np.intc) # int in C
# remember the difference between
# Upper case API and lowe... | 5,291,579 |
def _save_selected_features(output_path, features, fold):
"""Save the list of selected features in a json file"""
json_features = {"selected_features": features}
with open(join(output_path, f"{fold}.json"), "w", encoding="utf-8") as file:
json.dump(json_features, file, indent=4) | 5,291,580 |
def CorsikaReaderTraySegment(tray,name,
gcdfile, randomService,
cors, oversampling, legacyoversampling=False,
stats={},
propagate_muons=False,
select_neutrino=False,
filenamelist=[],
SimulateIceTop=True):
"""
Tray Segment for basic CORSIKA simulation (generation... | 5,291,581 |
def _buffer_proxy(filename_or_buf, function, reset_fp=True,
file_mode="rb", *args, **kwargs):
"""
Calls a function with an open file or file-like object as the first
argument. If the file originally was a filename, the file will be
opened, otherwise it will just be passed to the underl... | 5,291,582 |
def word_tokenize(text):
"""
convert a string to list of normal word tokens
"""
return filter_stopwords(tokenizer(text)) | 5,291,583 |
def _parseSpec(values):
"""
Split the argument string. Example:
--arg name:value0,value1,key2=value2,key3=value3
gets split into
name, args, kwargs = (
"name",
(value0, value1),
{"key2":value2, "key3":value3},
)
"""
split = values.split(":", 1)
name = split[0].strip()
rest = split[1]... | 5,291,584 |
def get_mask(mask_path):
"""Loads the data from a given mask.
Parameters
----------
mask_path : str
Path to the mask.
Returns
-------
numpy.ndarray
Data of the given mask.
"""
return nibabel.load(mask_path).get_data() | 5,291,585 |
def test_evaluator_half_precision(
embed_model,
query_session_data,
index_session_data,
query_class_data,
index_class_data,
):
"""
Test the evaluator when the matching limit is set 2. We expect all metrics == 1.0
except precision == 0.5 and f1score == 2/3
"""
# test both for sess... | 5,291,586 |
def test_unregister_event_handler_with_no_handlers(module_with_handler):
"""
Test whether unregistering handlers when no handlers are registered for the event does nothing.
"""
module, mock_callback1, _, _ = module_with_handler
assert 'dummy-event-2' not in module._handlers
saved_handlers = {... | 5,291,587 |
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
... | 5,291,588 |
def PLUS_DI(df, time_period=14):
"""
+DI 最高价上涨的次数
+ di是真实范围的百分比。di是真实范围下降的百分比。当+ di越过di时,生成一个买入信号。当di越过+ di时,产生一个卖出信号。你应该等到交易进入极限点为止。也就是说,你应该等待进入一个长期的交易,直到价格达到高的酒吧上di di越过di,并等待进入短期贸易,直到价格达到低的酒吧上的di越过+ di。
python API
real=PLUS_DI(high, low, close, timeperiod=14)
:return:
"""
high = df['h... | 5,291,589 |
def map_records_nb(records, map_func_nb, *args):
"""Map each record to a scalar value.
`map_func_nb` must accept a single record and `*args`, and return a scalar value."""
result = np.empty(records.shape[0], dtype=np.float_)
for r in range(records.shape[0]):
result[r] = map_func_nb(records[r], ... | 5,291,590 |
def schema():
"""
Returns the basic schema of :class:`.Agent`
.. http:get:: /api/v1/agents/schema HTTP/1.1
**Request**
.. sourcecode:: http
GET /api/v1/agents/schema HTTP/1.1
Accept: application/json
**Response**
.. sourcecode:: http
... | 5,291,591 |
def storage_root(state: State, address: Address) -> Root:
"""
Calculate the storage root of an account.
Parameters
----------
state:
The state
address :
Address of the account.
Returns
-------
root : `Root`
Storage root of the account.
"""
assert sta... | 5,291,592 |
def sort_out_edges(g, tag, tag_offset_name='_TAG_OFFSET'):
"""Return a new graph which sorts the out edges of each node.
Sort the out edges according to the given destination node tags in integer.
A typical use case is to sort the edges by the destination node types, where
the tags represent destinatio... | 5,291,593 |
def _count_dot_semicolumn(value):
"""Count the number of `.` and `:` in the given string."""
return sum([1 for c in value if c in [".", ":"]]) | 5,291,594 |
def FixIP(pattern):
"""If a stand alone IP, fix it so RE does not go off the rails"""
if re.search(pattern,"^([0-9]{1,3}\.){3}[0-9]{1,3}$"):
# If IP, make sure "." is not interpreted as a regexp "." instead of a period seperator
pattern = pattern.replace(".",r"\.")
return pattern | 5,291,595 |
def grant_staff_access(actor, user, is_staff):
"""
Grant staff access to a user via an actor.
"""
user.is_staff = is_staff
user.save()
return user | 5,291,596 |
def _random_cropping_decoder(
sequences: Dict[str, media_sequences.EncodedSequence],
*,
image_size: int,
min_crop_window_area: float,
max_crop_window_area: float,
min_crop_window_aspect_ratio: float,
max_crop_window_aspect_ratio: float,
) -> Dict[str, brave_datasets.View]:
"""Randomly crop... | 5,291,597 |
def generate_curve(A, B, C, D):
"""
if Seg(A1, B1) and Seg(A2, B2) intersects at P,
then C is the closest point to A in the trajectory1 opposite to the direction of B,
and D is the closest point to B opposite to the direction of A
output: Bezier curve
"""
line_CA = Line(C, A)
l... | 5,291,598 |
def filter(args):
"""
%prog filter bedfile
Filter the bedfile to retain records between certain size range.
"""
p = OptionParser(filter.__doc__)
p.add_option("--minsize", default=0, type="int",
help="Minimum feature length")
p.add_option("--maxsize", default=1000000000, typ... | 5,291,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.