content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dot(p, q):
"""
Compute dot product between two 3D vectors
p: array
Cartesian coordinates for one of the vectors
q: array
Cartesian coordinates for one of the vectors
"""
return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] | 28a073690e1e89128a997ae75b8782ee0cfb7252 | 19,600 |
import os
import sys
import tempfile
def create(protocol, host, port, objname):
"""
Sets up an environment through which the program can be re-invoked by
itself. In this new environment, the output will be the username and
password stored in the keyring for the specified server.
Refer to `credent... | a4e06f82338ec9e7445f5319b759f46cbab2f09e | 19,601 |
import click_completion.core
import click
def install_completion(ctx, attr, value): # pragma: no cover
"""Install completion for the current shell."""
if not value or ctx.resilient_parsing:
return value
shell, path = click_completion.core.install()
click.secho("{0} completion installed in {... | b6c84744161d90cc1d33ac6effd5b7aec083c151 | 19,602 |
from datetime import datetime
def _extractSetsSingleUser(df, time_window):
"""Get activity set and trip set for each individual."""
# total weeks and start week
weeks = (df["endt"].max() - df["startt"].min()).days // 7
start_date = df["startt"].min().date()
aSet = pd.DataFrame([], columns=["useri... | 40f92857cd5684b8fbf8b01565ede7aeffab1fe8 | 19,603 |
def _ed25519():
"""Edwards curve Ed25519.
Link: https://en.wikipedia.org/wiki/EdDSA#Ed25519
"""
q = 2 ** 255 - 19
order = 2 ** 252 + 27742317777372353535851937790883648493
gf = GF(q)
ed = CurveParams(name="ED25519", order=order, gf=gf, is_cyclic = True)
ed.set_constants(a=gf(-1), d=gf(-... | f1a07b9ebcb6033968f0e7d9c66ee2ff71f138e0 | 19,604 |
import json
def from_raw_bytes(raw_bytes):
"""Take raw bytes and turn it into a DmailRequest"""
return from_json(json.loads(raw_bytes.decode(encoding='UTF-8'))) | 01e989dfddcad20125ff608cdfa42673b1c0d0d8 | 19,605 |
def BRepApprox_TheMultiLineToolOfApprox_FirstPoint(*args):
"""
:param ML:
:type ML: BRepApprox_TheMultiLineOfApprox &
:rtype: int
"""
return _BRepApprox.BRepApprox_TheMultiLineToolOfApprox_FirstPoint(*args) | 26b8a2bffe094a8cc1e41edf56b92b75be75dc37 | 19,606 |
import time
def push_message(token, user, message, **kwargs):
"""
Send message to selected user/group/device.
:param str token: application token
:param str user: user or group id to send the message to
:param str message: your message
:param str title: your message's title, otherwise your ap... | 97b278482fb1ff88eea5f95c45f47563b61c905f | 19,607 |
def _rrv_div_ ( s , o ) :
"""Division of RooRealVar and ``number''
>>> var = ...
>>> num = ...
>>> res = var / num
"""
if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve ()
elif hasattr ( o , 'getVal' ) : o = o.getVal ()
#
v = ... | bef100fa354dc1e090a7e1cb2ad66bc8c7144d1b | 19,608 |
def getWindowsAt(x: int, y: int, app: AppKit.NSApplication = None, allWindows=None):
"""
Get the list of Window objects whose windows contain the point ``(x, y)`` on screen
:param x: X screen coordinate of the window(s)
:param y: Y screen coordinate of the window(s)
:param app: (optional) NSApp() o... | 009a4d439e7948fc3829e132118716ea808b5185 | 19,609 |
def find_closest_vertices(surface_coords, point_coords):
"""Return the vertices on a surface mesh closest to some given coordinates.
The distance metric used is Euclidian distance.
Parameters
----------
surface_coords : numpy array
Array of coordinates on a surface mesh
point_coords : ... | 62adc1082d24ff70e8f285a6a457b6bff0768854 | 19,610 |
def blob_utils_get_loss_gradients(model, loss_blobs):
"""Generate a gradient of 1 for each loss specified in 'loss_blobs'"""
loss_gradients = {}
for b in loss_blobs:
loss_grad = model.net.ConstantFill(b, [b + '_grad'], value=1.0)
loss_gradients[str(b)] = str(loss_grad)
return loss_gradie... | 2543dc532469405ad0ae1b1288b9956841565238 | 19,611 |
def _list_indexing(X, key, key_dtype):
""" Index a Python list """
if np.isscalar(key) or isinstance(key, slice):
# key is a slice or a scalar
return X[key]
if key_dtype == 'bool':
# key is a boolean array-like
return list(compress(X, key))
# key is a integer array-like o... | 47a5ae6be9db172c5ac194c7989540c79a27f89f | 19,612 |
import collections
import itertools
import copy
def extract_hubs_from_motifs(list_of_motifs: list,
genes_to_remove: list,
check_conflict: bool = True,
debug: bool = False,
gene_ids_file: str = None,
... | 3dc4bc8c8dd67ce0eb88d0f02b0021e575741503 | 19,613 |
import json
import requests
def credit_rating():
"""
credit_rating http api
"""
return_dict = {'rescode': '200', 'credit-rating': '1', 'description': 'Good credit'}
if request.get_data() is None:
return_dict['rescode'] = '5004'
return json.dumps(return_dict, ensure_ascii=False)
... | 06a12b6f0801a1b56b17eb53ec4009c4ab5777f5 | 19,614 |
def updateGlobalInventory(D_SKUs: pd.DataFrame, inventoryColumn: str):
"""
Update the global inventory of the warehouse
Args:
D_SKUs (pd.DataFrame): Input SKUs dataframe.
inventoryColumn (str): column name with the inventory.
Returns:
D_inventory (pd.DataFrame): Output DataFram... | 7e9d824de8830b40a88ae5fbbffac89e69a57869 | 19,615 |
from datetime import datetime
def _query_checks(start, end, owner_id=''):
"""Get the number of rules checks from `start` to `end` in 1-day windows"""
series = []
assert (isinstance(end, datetime.datetime) and
isinstance(start, datetime.datetime))
while start < end:
stop = start + d... | 9df5e7dd9a6ea2f2bb1f4f1a6a89db6b16d6814b | 19,616 |
def _FilterManufacturedEvents(results):
"""Return a list of results where first question is 'MANUFACTURED'.
Manufactured events are either Recording events that correspond to
an instrumented event in the browser, or Showed notification events
that correspond to when the user was invited to take a survey.
Ar... | 51fb34402e17249b63b8061bf70a2879925c8fba | 19,617 |
def Max(data):
"""Returns the maximum value of a time series"""
return data.max() | 0d4781da4384eae65de4e13860995848ae8de678 | 19,618 |
def clean_words(words, remove_stopwords=False, language='portuguese'):
"""Stems and removes stopwords from a set of word-level tokens using the RSLPStemmer.
Args:
words (list): Tokens to be stemmed.
remove_stopwords (bool): Whether stopwords should be removed or not.
language (str): Ide... | 4dd721a691e832dc3b8160c678fe7e1c05b6a015 | 19,619 |
import os
import pickle
def load_model(model_dir, model_file=None):
"""Loads the model.
The model object is pickled in `model_dir` to make the model configuration
optional for future runs.
Args:
model_dir: The model directory.
model_file: An optional model configuration.
Returns:
A `opennmt.m... | 437fd8378113db11b9afa5133d57d6936ab722fa | 19,620 |
def parse_healing_and_target(line):
"""Helper method that finds the amount of healing and who it was provided to"""
split_line = line.split()
target = ' '.join(split_line[3:split_line.index('for')])
target = target.replace('the ', '')
amount = int(split_line[split_line.index('for')+1])
return... | 3f11c0807ab87d689e47a79fc7e12b32c00dbd95 | 19,621 |
from typing import Optional
from typing import Sequence
def _decode_and_center_crop(
image_bytes: tf.Tensor,
jpeg_shape: Optional[tf.Tensor] = None,
image_size: Sequence[int] = (224, 224),
) -> tf.Tensor:
"""Crops to center of image with padding then scales."""
if jpeg_shape is None:
jpeg_shape = ... | 7a7ad3eb36099d560da126011845426bdcd1f326 | 19,622 |
def inq_affine(inp, n_outmaps, base_axis=1, num_bits=4,
inq_iterations=(), selection_algorithm='random',
seed=-1, w_init=None, i_init=None, b_init=None,
fix_parameters=False, rng=None, with_bias=True):
"""Incremental Network Quantization Affine Layer
During training... | 7654d925a13276002419c9d08342e4e7974bdc31 | 19,623 |
def is_greater_equal(min_value):
"""Check if the attribute value is greater than or equal to a minimum value.
This validator can handle both lists and single element attributes. If it
is a list, it checks if the element with the smallest value is greater than
or equal to the specified minimum value.
... | a95cc24afcae6d11689b872f2178f6b38b864ca7 | 19,624 |
from typing import List
def save_lyrics(list_: List[Text], location: Text) -> None:
"""Writes 'list_' to 'location' as txt file. Returns None."""
with open(location, "w+") as f:
for element in list_:
f.write(element)
f.write("\n")
return None | 1fff7cf838fdaea32f6875beab90b172a84f379c | 19,625 |
def translate_provider_for_icon(sync_server, project, site):
"""
Get provider for 'site'
This is used for getting icon, 'studio' should have different icon
then local sites, even the provider 'local_drive' is same
"""
if site == sync_server.DEFAULT_SITE:
return sync_server.... | 58867a6dd44c83582d85fc1baf48121eff714232 | 19,626 |
def server_delete_ip(body=None): # noqa: E501
"""delete server IP
Send by server during shutdown. # noqa: E501
:param body: port of iperf server. Ip and time could be emply
:type body: dict | bytes
:rtype: List[InlineResponse200]
"""
if connexion.request.is_json:
body = ServerAdd... | 92b2f425ae7cca1e3e42c58382f3d21b2e96f016 | 19,627 |
import re
def extract_key_and_index(field):
"""Returns the key type, key name and if key is a compound list then returns the index pointed by the field
Arguments:
field: csv header field
"""
for key_type, value in KEY_TYPES.items():
regex = re.compile(value["regex"])
match = rege... | aba66922117cd14f2c670df839c3ca522856caa3 | 19,628 |
import torch
def as_mask(indexes, length):
"""
Convert indexes into a binary mask.
Parameters:
indexes (LongTensor): positive indexes
length (int): maximal possible value of indexes
"""
mask = torch.zeros(length, dtype=torch.bool, device=indexes.device)
mask[indexes] = 1
r... | 0235d66f9ee5bdc7447819122b285d29efd238c9 | 19,629 |
def interpolate_array(x, y, smooth_rate=500):
"""
:param x:
:param y:
:return:
"""
interp_obj = interpolate.PchipInterpolator(x, y)
new_x = np.linspace(x[0], x[-1], smooth_rate)
new_y = interp_obj(new_x)
return new_x, new_y | 4c6f79c3071496e6314d772651d2e6cc6a449c74 | 19,630 |
from typing import Sequence
from typing import Counter
import copy
def calculate_resource_utilization_for_slaves(
slaves: Sequence[_SlaveT], tasks: Sequence[MesosTask]
) -> ResourceUtilizationDict:
""" Given a list of slaves and a list of tasks, calculate the total available
resource available in that lis... | 13b4856b3ef0bdf06410a58ecc0fbc29bfda4483 | 19,631 |
def check_pass(value):
"""
This test always passes (it is used for 'checking' things like the
workshop address, for which no sensible validation is feasible).
"""
return True | aa3a5f536b5bc729dc37b7f09c3b997c664b7481 | 19,632 |
def state_array_to_int(s):
"""translates a state s into an integer by interpreting the state as a
binary represenation"""
return int(state_array_to_string(s), 2) | b0b50dd879b74af27946cde49e1bf805c2d6e504 | 19,633 |
import asyncio
import traceback
def async_task(coro, loop=asyncio.get_event_loop(), error_cb=None):
"""
Wrapper to always print exceptions for asyncio tasks.
"""
future = asyncio.ensure_future(coro)
def exception_logging_done_cb(future):
try:
e = future.exception()
ex... | 5520aafebca17cbe32c79b69e41856f6076179f3 | 19,634 |
def is_valid_charts_yaml(content):
"""
Check if 'content' contains mandatory keys
:param content: parsed YAML file as list of dictionary of key values
:return: True if dict contains mandatory values, else False
"""
# Iterate on each list cell
for chart_details in content:
# If one ... | cc68ba6bc9166f8d2f8c37da756accec667f471a | 19,635 |
def get_trader_fcas_availability_agc_status_condition(params) -> bool:
"""Get FCAS availability AGC status condition. AGC must be enabled for regulation FCAS."""
# Check AGC status if presented with a regulating FCAS offer
if params['trade_type'] in ['L5RE', 'R5RE']:
# AGC is active='1', AGC is ina... | fa73ae12a0934c76f12c223a05161280a6dc01f1 | 19,636 |
import importlib
def load_class(full_class_string):
"""
dynamically load a class from a string
"""
class_data = full_class_string.split(".")
module_path = ".".join(class_data[:-1])
class_str = class_data[-1]
module = importlib.import_module(module_path)
# Finally, we retrieve the Cla... | 95ab0a0b27d508b5bd41468cf6a4e3c008799fdf | 19,637 |
def request_credentials_from_console():
"""
Requests the credentials interactive and returns them in form (username, password)
"""
username = raw_input('Username: ')
password = raw_input('Password: ')
return username, password | 43102d8528502f700ab96714831c94abb6a3b0f8 | 19,638 |
def prettify_url(url):
"""Return a URL without its schema
"""
if not url:
return url
split = url.split('//', 1)
if len(split) == 2:
schema, path = split
else:
path = url
return path.rstrip('/') | 0beed0522355e4ea8170cac22e61f92e0c21ccca | 19,639 |
def CDLMORNINGDOJISTAR(data: xr.DataArray, penetration: float = 0.3) -> xr.DataArray:
"""
Morning Doji Star (Pattern Recognition)
Inputs:
data:['open', 'high', 'low', 'close']
Parameters:
penetration: 0.3
Outputs:
double series (values are -1, 0 or 1)
"""
return multi... | be1f4954dda5109d067070fc97c340233085b043 | 19,640 |
def panerror_to_dict(obj):
"""Serializer function for POCS custom exceptions."""
name_match = error_pattern.search(str(obj.__class__))
if name_match:
exception_name = name_match.group(1)
else:
msg = f"Unexpected obj type: {obj}, {obj.__class__}"
raise ValueError(msg)
return ... | 8841d2c4b6f3ba1deae5057a6b85b70830c412a1 | 19,641 |
from typing import Optional
def build_class_instance(module_path: str, init_params: Optional[dict] = None):
"""
Create an object instance from absolute module_path string.
Parameters
----------
module_path: str
Full module_path that is valid for your project or some external package.
... | d50ffdbb8bbeed36b572e6e555376febabecb745 | 19,642 |
def maintainers_mapper(maintainers, package):
"""
Update package maintainers and return package.
https://docs.npmjs.com/files/package.json#people-fields-author-contributors
npm also sets a top-level "maintainers" field with your npm user info.
"""
# note this is the same code as contributors_map... | 57e76ec2cbc1727778bfe980c5cd6d82798a1800 | 19,643 |
def calc_original_pressure(pressure_ratio):
"""
calculates the original pressure value given the <code>AUDITORY_THRESHOLD</code>.
The results are only correct if the pressure ratio is build using the <code>AUDITORY_THRESHOLD</code>.
:param pressure_ratio: the pressure ration that shall be converted to ... | 1a0680073cb739fef47952887e6dedf4487f2aa0 | 19,644 |
def normalize_field_names(fields):
"""
Map field names to a normalized form to check for collisions like 'coveredText' vs 'covered_text'
"""
return set(s.replace('_','').lower() for s in fields) | 55bdac50fd1fcf23cfec454408fbcbbae96e507e | 19,645 |
import os
import itertools
def which(program): # type: (str) -> str
"""Like UNIX which, returns the first location of a program given using your system PATH
If full location to program is given, uses that first"""
dirname, progname = os.path.split(program) # type: str, str
syspath = tuple([dirname] + ... | 61748b6b9aef948f4d570791d432de0c69d815d9 | 19,646 |
def powspec_disc_n(n, fs, mu, s, kp, km, vr, vt, tr):
"""Return the n'th Lorentzian and its width"""
Td = ifana.LIF().Tdp(mu, s, vr, vt) + tr
Ppp = (kp*exp(-(kp+km)*tr)+km)/(kp+km)
kpbar = (kp*(Td-tr)-log(Ppp))/Td
return 1./Td * 2*kpbar/(kpbar**2 + (2*pi*(fs - n*1./Td))**2), kpbar | 60335e496b734c32116424d857a3c59de7f5b567 | 19,647 |
def list_keys(request):
"""
Tags: keys
---
Lists all added keys.
READ permission required on key.
---
"""
auth_context = auth_context_from_request(request)
return filter_list_keys(auth_context) | 564d03457265c0461e82b55abfb23cb4d45ad0ac | 19,648 |
def rounder(money_dist: list, pot: int, to_coin: int = 2) -> list:
"""
Rounds the money distribution while preserving total sum
stolen from https://stackoverflow.com/a/44740221
"""
def custom_round(x):
""" Rounds a number to be divisible by to_coin specified """
return int(to_coin *... | f315027def4646252aa7d4ee7c05ca3085625583 | 19,649 |
def find_wcscorr_row(wcstab, selections):
""" Return an array of indices from the table (NOT HDU) 'wcstab' that matches the
selections specified by the user.
The row selection criteria must be specified as a dictionary with
column name as key and value(s) representing the valid d... | dcd2b4025ec3756319911e6626dd403a6efda1c4 | 19,650 |
def process_image(image_file):
""" 다섯 단계의 이미지 처리(Image precessing)를 힙니다.
현재 함수에서 순서를 변경하여 적용할 수 있습니다.
1) Gray-scale 적용
2) Morph Gradient 적용
3) Threshold 적용
4) Long Line Removal 적용
5) Close 적용
6) Contour 추출
:param image_file: 이미지 처리(Image precessing)를 적용할 이미지 파일
:return: 이미지 처리 후... | 3185487505cd26db64fb294cef5bb1a26c7b5482 | 19,651 |
import urllib
def _gftRead(url, step):
"""
Reads in a gtf file from a specific db given the url.
Some gft have a certain number of header lines that
are skipped however.
Input: url where gtf is fetched from
Input: number of lines to skip while reading in the frame
... | ef05d2747188def526612bdd27931e0420e275dd | 19,652 |
def add() -> jsonify:
"""
Adds a new item in the server and returns the updated list to the front-end
"""
# Passed Items from Front-End
name = request.form['name']
priority = request.form['priority']
price = request.form['price'].replace(",", "") # To prevent string to float conversion
... | e8a32aa47ee057c6f9653554955cddd0b003ef1a | 19,653 |
import copy
import os
def _get_base(**kwargs):
"""
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
"""
profile = get_container_profile(copy.deepcopy(kwargs.get("profile")))
kw_overrides = ... | 0b1c966669fe6027f89b62461ee5fd3b43398e53 | 19,654 |
def calculate(formula, **params):
""" Calculate formula and return a dictionary of coin and amounts """
formula = Formula.get(formula)
if formula is None:
raise InvalidFormula(formula)
if not formula.expression:
return {}
return calculate_expression(formula.expression, formula, **p... | e8a237d2677581296bb1491badecf83264c0d44a | 19,655 |
import torch
def pack_batch_tensor(inputs):
"""default pad_ids = 0
"""
input_max_length = max([d.size(0) for d in inputs])
# prepare batch tensor
input_ids = torch.LongTensor(len(inputs), input_max_length).zero_()
input_mask = torch.LongTensor(len(inputs), input_max_length).zero_()
for i, ... | 33e59acbc8facaf41064e2dd7031bdd314211878 | 19,656 |
def build_network(network_class=None,
dataset_dirs_args=None,
dataset_dirs_class=None,
dataset_dirs=None,
dataset_spec_args=None,
dataset_spec_class=None,
dataset_spec=None,
network_spec_args=No... | 4fae693408b385629c6ae645c69778276c16b915 | 19,657 |
import os
import nipype
import nipype.pipeline as pe
import nipype.interfaces.utility as utility
import PUMI.func_preproc.info.info_get as info_get
import PUMI.utils.utils_convert as utils_convert
import nipype.interfaces.afni as afni
import PUMI.utils.globals as globals
import io
def slt_workflow(slicetiming_txt="al... | 9b813b8e32c17dae58e5dc552404c0cf1ee5a8a6 | 19,658 |
def lookup_service_root(service_root):
"""Dereference an alias to a service root.
A recognized server alias such as "staging" gets turned into the
appropriate URI. A URI gets returned as is. Any other string raises a
ValueError.
"""
if service_root == EDGE_SERVICE_ROOT:
# This will trig... | 8cc5384ba26639438e4c7e18264fb39ee2445fcf | 19,659 |
import warnings
def get_initial_configuration():
"""
Return (pos, type)
pos: (1, 1) - (9, 9)
type will be 2-letter strings like CSA format.
(e.g. "FU", "HI", etc.)
"""
warnings.warn(
"""get_initial_configuration() returns ambiguous cell state.
Use get_initial_configuration_... | c96f7f70e258d09090abeffc9815082265245cf2 | 19,660 |
def request_pull_to_diff_or_patch(
repo, requestid, username=None, namespace=None, diff=False
):
"""Returns the commits from the specified pull-request as patches.
:arg repo: the `pagure.lib.model.Project` object of the current pagure
project browsed
:type repo: `pagure.lib.model.Project`
:... | a7b543294cb66561700b7db7800277d74ed1267c | 19,661 |
def GL(alpha, f_name, domain_start = 0.0, domain_end = 1.0, num_points = 100):
""" Computes the GL fractional derivative of a function for an entire array
of function values.
Parameters
==========
alpha : float
The order of the differintegral to be computed.
... | 226d5d8b49be9a243ac4508a7691c8997503cb4d | 19,662 |
def check_lint(root_dir, ignore, verbose, dry_run, files_at_a_time,
max_line_len, continue_on_error):
"""Check for lint.
Unless `continue_on_error` is selected, returns `False` on the first
iteration where lint is found, or where the lint checker otherwise
returned failure.
:return:... | c43b7a05bf47b9108281bb7c0cef4ff1d6e107d3 | 19,663 |
def remove_comments(s):
"""
Examples
--------
>>> code = '''
... # comment 1
... # comment 2
... echo foo
... '''
>>> remove_comments(code)
'echo foo'
"""
return "\n".join(l for l in s.strip().split("\n") if not l.strip().startswith("#")) | 1d3e1468c06263d01dd204c5ac89235a17f50972 | 19,664 |
def generate_wsl(ws):
"""
Generates watershed line that correspond to areas of
touching objects.
"""
se = square(3)
ero = ws.copy()
ero[ero == 0] = ero.max() + 1
ero = erosion(ero, se)
ero[ws == 0] = 0
grad = dilation(ws, se) - ero
grad[ws == 0] = 0
grad[grad > 0] = 255
... | 6d61b2b366ca6a4b94f8a6513f1a0a5fb1bfd8c9 | 19,665 |
def train_lstm_model(x, y,
epochs=200,
patience=10,
lstm_dim=48,
batch_size=128,
lr=1e-3):
"""
Train an LSTM to predict purchase (1) or abandon (0)
:param x: session sequences
:param y: target label... | 159ad99e419d659e655bcdd9556a6ae3202071ae | 19,666 |
def nash_sutcliffe_efficiency(predicted, observed):
""" implements Nash-Sutcliffe Model Efficiencobserved Coefficient where predicted is modeled and observed is observed"""
if np.isnan(np.min(predicted)) or np.isnan(np.min(observed)):
return np.asarray([np.nan])
return 1 - np.sum((predicted - observed)**2) / np.su... | b9820cf95472499d6e6c24e47ffb4bbd5574e439 | 19,667 |
def tf_Affine_transformer(points, theta):
"""
Arguments:
points: `Matrix` [2, np] of grid points to transform
theta: `Matrix` [bs, 2, 3] with a batch of transformations
"""
with tf.name_scope('Affine_transformer'):
num_batch = tf.shape(theta)[0]
grid = tf.tile(tf.expand_d... | a024609ac386b7d12173fb3965233ae4c21233d2 | 19,668 |
def read_COCO_gt(filename, n_imgs=None, ret_img_sizes=False, ret_classes=False, bbox_gt=False):
"""
Function for reading COCO ground-truth files and converting them to GroundTruthInstances format.
:param filename: filename of the annotation.json file with all COCO ground-truth annotations
:param n_imgs:... | dfcfa69ee620ac3546b1f646c9c23f126a9822c3 | 19,669 |
def get_metrics_from_file(metric_file):
"""Gets all metric functions within a file
:param str metric_file: The name of the file to look in
:return: Tuples containing (function name, function object)
:rtype: list
"""
try:
metrics = import_module(metric_file)
metrics = get_sorted_... | 12e59feb03b6d8571fb7a5ef8f02e81e53605b0b | 19,670 |
def mnist_model(inputs, mode):
"""Takes the MNIST inputs and mode and outputs a tensor of logits."""
# Input Layer
# Reshape X to 4-D tensor: [batch_size, width, height, channels]
# MNIST images are 28x28 pixels, and have one color channel
inputs = tf.reshape(inputs, [-1, 28, 28, 1])
data_format = 'channels... | 7807adce4030d070c79eea5f3a1991ff4c4e1cd6 | 19,671 |
import base64
import io
def show_local_mp4_video(file_name, width=640, height=480):
"""Renders a mp4 video on a Jupyter notebook
Args:
file_name (str): Path to file.
width (int): Video width.
height (int): Video height.
Returns:
obj: Video render as HTML object.
"""
... | 4f2b4660b005edcf865eca1c6632ffa6c0899fe8 | 19,672 |
from datetime import datetime
def change_status(sid, rev, status, **kwargs):
"""
[INCOMPLETE]
- DISABLE OTHER REVISION OF THE SAME SIGNTURE WHEN DEPLOYING ONE
Change the status of a signature
Variables:
sid => ID of the signature
rev => Revision number of the signature
... | dce934db6c7fe34e184ff98a63f2bc5e32efaffe | 19,673 |
from re import X
def trilinear_interpolation(a: np.ndarray, factor: float) -> np.ndarray:
"""Resize an three dimensional array using trilinear
interpolation.
:param a: The array to resize. The array is expected to have at
least three dimensions.
:param factor: The amount to resize the array. ... | a3ed2c13f13bdc37cbe47cd7ed6862a67cdebd66 | 19,674 |
def load_data(path):
"""将材料的label与text进行分离,得到两个list"""
label_list = []
text_list = []
with open(path, 'r') as f:
for line in f.readlines():
data = line.strip().split('\t')
data[1] = data[1].strip().split()
label = [0 for i in range(8)]
total = 0
... | 2274e0e327844c4dedae229b3c03a344653f7342 | 19,675 |
def invoke(request):
"""Where the magic happens..."""
with monitor(labels=_labels, name="transform_request"):
transformed_request = _transform_request(request)
with monitor(labels=_labels, name="invoke"):
response = _model.predict(transformed_request)
with monitor(labels=_labels, name... | 4547de901cfd2cc153ea67632c2a002a17a15d8b | 19,676 |
import imp
import imp
import imp
def serializers(): #FIXME: could be much smarter
"""return a tuple of string names of serializers"""
try:
imp.find_module('cPickle')
serializers = (None, 'pickle', 'json', 'cPickle', 'dill')
except ImportError:
serializers = (None, 'pickle', 'json',... | 98e47f0c3dd7a6c70ba1ec88a5d1d0ffca8be79e | 19,677 |
def munge_pocket_response(resp):
"""Munge Pocket Article response."""
articles = resp['list']
result = pd.DataFrame([articles[id] for id in articles])
# only munge if actual articles present
if len(result) != 0:
result['url'] = (result['resolved_url'].combine_first(result['given_url']))
... | 32695526a784cc95aeb428ca2481dcf9053e72ed | 19,678 |
import os
def __abs_path(path):
"""
Creates an absolute path, based on the relative path from the configuration file
:param path: A relative path
:return: The absolute path, based on the configuration file
"""
if not os.path.isabs(path):
parent = os.path.abspath(os.path.join(config_pat... | 4b790fda478f583c6b78c05e10e01dc68eda7e25 | 19,679 |
import time
def fake_data_PSBL_phot(outdir='', outroot='psbl',
raL=259.5, decL=-29.0,
t0=57000.0, u0_amp=0.8, tE=500.0,
piE_E=0.02, piE_N=0.02,
q=0.5, sep=5.0, phi=75.0, b_sff1=0.5, mag_src1=16.0,
p... | bde4d98d0936be3b0cd655879bbfdbde2e1a5826 | 19,680 |
import pathlib
def is_dicom(path: pathlib.Path) -> bool:
"""Check if the input is a DICOM file.
Args:
path (pathlib.Path): Path to the file to check.
Returns:
bool: True if the file is a DICOM file.
"""
path = pathlib.Path(path)
is_dcm = path.suffix.lower() == ".dcm"
is_... | 1e20ace9c645a41817bf23a667bd4e1ac815f63f | 19,681 |
from typing import Optional
def _hessian(model: 'BinaryLogReg', data: Dataset, data_weights: Optional[jnp.ndarray]) -> jnp.ndarray:
"""Ravelled Hessian matrix of the objective function with respect to the model parameters"""
params_flat, unravel = ravel_pytree(model.params)
random_params = model.random_pa... | 5824fe0d2def5d03e8ac3f773641d19d6aebfa3e | 19,682 |
import re
def promax2meta(doc, target):
"""
Return meta information (Line or Area) of csv Promax geometry file.
Arguments:
doc -- csv Promax geometry file
target -- meta information to get (Line or Area)
"""
ptarget = r'' + re.escape(target) + r'\s*[=:]\s*\"?([\w-]+)\"?'
for line in o... | 7dce362112aa7fb6fa24999c4f870107b24c3d40 | 19,683 |
def axLabel(value, unit):
"""
Return axis label for given strings.
:param value: Value for axis label
:type value: int
:param unit: Unit for axis label
:type unit: str
:return: Axis label as \"<value> (<unit>)\"
:rtype: str
"""
return str(value) + " (" + str(unit) + ")" | cc553cf4334222a06ae4a2bcec5ec5acb9668a8f | 19,684 |
import hashlib
import time
def save_notebook(filename, timeout=10):
"""
Force-saves a Jupyter notebook by displaying JavaScript.
Args:
filename (``str``): path to notebook file being saved
timeout (``int`` or ``float``): number of seconds to wait for save before timing-out
Returns
... | 4d02f1eb48459c412a119fcab7d8df7515c1b465 | 19,685 |
def test_gen():
"""Create the test system."""
project_name = "test_grid_sinfactory"
return PFactoryGrid(project_name=project_name).gens["SM1"] | cd8009b55bfced7fbafc2914b80e0dd2cd2851fc | 19,686 |
def validate_api_key():
"""Validates an API key submitted via POST."""
api_key_form = ApiKeyForm()
api_key_form.organization.choices = session['orgs_list']
if api_key_form.validate_on_submit():
session['org_id'] = api_key_form.organization.data
return jsonify(True)
return jsonify(api... | 1cf72017600222992cb9d622c6b718b8dc84bae8 | 19,687 |
def plot_clickForPlane():
""" Create a Plane at location of one mouse click in the view or
onto a clicked object or
at a pre-selected point location:
Create a Plane perpendicular to the view at location of one mouse click.
- Click first on the Button then click once on the View.
- Click first on... | 62acc0e41ce165047f6dabf99d0df8fd2b1db000 | 19,688 |
def is_logged_in(f):
"""
is logged in decorator
"""
@wraps(f)
def wrap(*args, **kwargs):
"""
wrap from template
"""
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('Unauthorized, Please login', 'danger')
ret... | 732bf60bf0901fc341f81c3e6db3516052ecfd12 | 19,689 |
def dataframe_from_mult_files(filenames):
"""@param filenames (List[Str]): list of filenames"""
dfs = []
for filename in filenames:
dfs.append(dataframe_from_file(filename))
return pd.concat(dfs, axis=0) | 76f37d5cef6a8b44946ef25536a135db339beca6 | 19,690 |
def batch_euclidean_dist(x, y, min_val):
""" euclidean_dist function over batch
x and y are batches of matrices x' and y':
x' = (x'_1, | x'_2 | ... | x'_m).T
y' = (y'_1, | y'_2 | ... | y'_n).T
Where x_i and y_j are vectors. We calculate the distances between each pair x_i and y_j.
res'[i, j] ... | 1eec65330ba8970fd84c7d9c7c57e91cd79e0e6f | 19,691 |
def outgroup_reformat(newick, outgroup):
"""
Move the location of the outgroup in a newick string to be at the end of the string
Inputs:
newick --- a newick string to be reformatted
outgroup --- the outgroup
Output:
newick --- the reformatted string
"""
# Replace the outgroup and co... | a45be59deb95d7bb61ea82a111d4390e49d4b7a8 | 19,692 |
def get_source_token(request):
"""
Perform token validation for the presqt-source-token header.
Parameters
----------
request : HTTP request object
Returns
-------
Returns the token if the validation is successful.
Raises a custom AuthorizationException error if the validation fail... | db53bba32f8471a17d44fae2d3f44749d5a83c86 | 19,693 |
def read_train_valid(filename):
"""
读取训练或者验证文件
:param filename: 训练集/验证集的文件名字
:return:
返回训练集的文本和标签
其中文本是一个list, 标签是一个list(每个元素为int)
返回示例:['我很开心', '你不是真正的快乐', '一切都是假的], [1, 0, 0]
"""
fp = pd.read_table(filename, sep='\t', error_bad_lines=False)
return fp['review'].tolist(), list(... | f6990db50453e4dd88f8ecd13e1eb345ab15fc87 | 19,694 |
def weighted_regularization_matrix_from(
regularization_weights: np.ndarray,
pixel_neighbors: np.ndarray,
pixel_neighbors_sizes: np.ndarray,
) -> np.ndarray:
"""
From the pixel-neighbors, setup the regularization matrix using the weighted regularization scheme.
Parameters
----------
reg... | ecc6301e327adc608530c933ae769bd92ffcaf84 | 19,695 |
def child_at_time(
self,
search_time,
shallow_search=False,
):
"""Return the child that overlaps with time search_time.
search_time is in the space of self.
If shallow_search is false, will recurse into compositions.
"""
range_map = self.range_of_all_children()
# find... | 5961a6d20a962b7b698822610bf4cecdf9c33257 | 19,696 |
def weight_variable_truncated_normal(input_dim, output_dim, name=""):
"""Create a weight variable with truncated normal distribution, values
that are more than 2 stddev away from the mean are redrawn."""
initial = tf.truncated_normal([input_dim, output_dim], stddev=0.5)
return tf.Variable(initial, name... | 4c645fc5a914ff99f5b1063f5ecc0b4878481517 | 19,697 |
def get_dummy_vm_create_spec(client_factory, name, data_store_name):
"""Builds the dummy VM create spec."""
config_spec = client_factory.create('ns0:VirtualMachineConfigSpec')
config_spec.name = name
config_spec.guestId = "otherGuest"
vm_file_info = client_factory.create('ns0:VirtualMachineFileInf... | 6564197d319b87f0a9dd05ae3053de6ebc11cf5c | 19,698 |
def test_comparison_ops_eq_t():
"""Check the equal-to operator for a truthy result."""
return """
fn main() {
{dest} = 1 == 1;
}
""" | 1d6562c26b1103deaf3a8eed4bc8d341a4a7d3e0 | 19,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.