content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_available_adapters() -> dict:
"""Get information on all available adapters
Returns:
(dict) Where keys are adapter names and values are descriptions
"""
return _output_plugin_info(ExtensionManager(namespace='materialsio.adapter')) | 5384931189492a6369a885498f4dfeaed315cb94 | 3,648,100 |
def _must_find_n(session, obj_outer, cls_inner, name_inner):
"""Searches the database for a "namespaced" object, such as a nic on a node.
Raises NotFoundError if there is none. Otherwise returns the object.
Arguments:
session - a SQLAlchemy session to use.
obj_outer - the "owner" object
cls_... | 25546e1f528c54ae7283f6a0d404065a337eb977 | 3,648,101 |
def list_providers():
"""
Get list of names of all supported cloud providers
:rtype: list
"""
return [cls.provider_name() for cls in BaseHandler.__subclasses__()] | 96f75695a40c9969cbd1507b3b3214df44039f1e | 3,648,102 |
def GetRPCProxy(address=None, port=None, url=GOOFY_RPC_URL):
"""Gets an instance (for client side) to access the goofy server.
Args:
address: Address of the server to be connected.
port: Port of the server to be connected.
url: Target URL for the RPC server. Default to Goofy RPC.
"""
address = addr... | 3e66abf1e6961c9d2dd2f2fa562e43528d6e99a4 | 3,648,103 |
import argparse
def getparser():
"""
Use argparse to add arguments from the command line
Parameters
----------
createlapserates : int
Switch for processing lapse rates (default = 0 (no))
createtempstd : int
Switch for processing hourly temp data into monthly standard devia... | 6ccde8f0e02124fa537205da398a842c88a62046 | 3,648,104 |
def dict_hash_table_100_buckets():
"""Test for hash table with 100 buckets, dictionary."""
ht = HashTable(100, naive_hash)
for word in dictionary_words:
ht.set(word, word)
return ht | eef6fa89811f6ac9d1ad17d11dc5aa38346a4e16 | 3,648,105 |
def white(N):
"""
White noise.
:param N: Amount of samples.
White noise has a constant power density. It's narrowband spectrum is therefore flat.
The power in white noise will increase by a factor of two for each octave band,
and therefore increases with 3 dB per octave.
"""
r... | 5404c24b0cb79e3866d10eed1630ccdfebe9fae1 | 3,648,106 |
import warnings
def read_HiCPro(bedfile, matfile):
"""
Fast loading of the .matrix and .bed files derived from HiC-Pro
Parameters
----------
bedfile : str,
path to the .bed file which contains fragments info
matfile : str,
path to the .matrix file which contains conta... | 1c52cdf62a20d4ff8168919afbd890890653de93 | 3,648,107 |
def get_objective_by_task(target, task):
"""Returns an objective and a set of metrics for a specific task."""
if task == 'classification':
if target.nunique() == 2:
objective = 'binary'
else:
objective = 'multi'
elif task == 'regression':
objective = 'regressi... | 7859f84ba89246b735c61b3b31e421b38692de34 | 3,648,108 |
def pileupGenes(GenePositions,filename,pad=500000,doBalance=False,
TPM=0,CTCFWapldKO=False,TPMlargerthan=True,
minlength=0,maxlength=5000000,OE=None, useTTS=False):
"""
This function piles up Hi-C contact maps around genes, centered on TSSs or TTSs.
Inputs
------
Gene... | 671f575b09131f44f07d659bc8e195a16cd9e2f9 | 3,648,109 |
def model_cnn_2layer(in_ch, in_dim, width, linear_size=128):
"""
CNN, small 2-layer (default kernel size is 4 by 4)
Parameter:
in_ch: input image channel, 1 for MNIST and 3 for CIFAR
in_dim: input dimension, 28 for MNIST and 32 for CIFAR
width: width multiplier
"""
model = nn... | a08ec035cde3dd024ec32d85adb0af045fe845eb | 3,648,110 |
import sys
import os
from unittest.mock import call
def snack_raw_formants_tcl(wav_fn, frame_shift, window_size, pre_emphasis, lpc_order, tcl_shell_cmd):
"""Implement snack_formants() by calling Snack through Tcl shell
tcl_shell_cmd is the name of the command to invoke the Tcl shell.
Note this method ca... | a9ac0dcbfd1568774b15db6fa28fb228e50ab29e | 3,648,111 |
from datasets.posetrack.poseval.py import evaluate_simple
def _run_eval(annot_dir, output_dir, eval_tracking=False, eval_pose=True):
"""
Runs the evaluation, and returns the "total mAP" and "total MOTA"
"""
(apAll, _, _), mota = evaluate_simple.evaluate(
annot_dir, output_dir, eval_pose, eval_... | e851006974b51c44c7ac7a59c4d54a3725b36004 | 3,648,112 |
def reserve_api():
"""Helper function for making API requests to the /reserve API endpoints
:returns: a function that can be called to make a request to /reserve
"""
def execute_reserve_api_request(method, endpoint, **kwargs):
master_api_client = master_api()
return master_api_client(me... | d9e07fcd72742685443cd83f44eaed074a8152dc | 3,648,113 |
import re
def extract_user_id(source_open_url):
"""
extract the user id from given user's id
:param source_open_url: "sslocal://profile?refer=video&uid=6115075278" example
:return:
"""
if source_open_url[10:17] != 'profile':
return None
try:
res = re.search("\d+$", source_... | 36d3e41c4361a29306650fc67c9f396efe92cd66 | 3,648,114 |
def prolog_rule(line):
"""Specify prolog equivalent"""
def specify(rule):
"""Apply restrictions to rule"""
rule.prolog.insert(0, line)
return rule
return specify | dde4840dc2f8f725d4c4c123aed7c978ec1948f9 | 3,648,115 |
def load_GloVe_model(path):
"""
It is a function to load GloVe model
:param path: model path
:return: model array
"""
print("Load GloVe Model.")
with open(path, 'r') as f:
content = f.readlines()
model = {}
for line in content:
splitLine = line.split()
word = ... | 40e8fe203b195621b776ea3650bb531956769b48 | 3,648,116 |
import numpy
def quadratic_program() -> MPQP_Program:
"""a simple mplp to test the dimensional correctness of its functions"""
A = numpy.array(
[[1, 1, 0, 0], [0, 0, 1, 1], [-1, 0, -1, 0], [0, -1, 0, -1], [-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0],
[0, 0, 0, -1]])
b = numpy.array([350, 6... | 71d5d9b872572e05b86e640006c58cc407c76ec4 | 3,648,117 |
import os
import base64
def load_img(str_img):
"""
"""
str_b64 = None
if os.path.exists(str_img) and is_path_img(str_img):
with open(str_img, 'rb') as f:
content = f.read()
content_b64 = base64.b64encode(content)
str_b64 = content_b64.decode('utf-8')
e... | 6a2549794003b1c4218ce985162e25f4bc8680f3 | 3,648,118 |
def snr(flux, axis=0):
""" Calculates the S/N ratio of a spectra.
Translated from the IDL routine der_snr.pro """
signal = np.nanmedian(flux, axis=axis)
noise = 1.482602 / np.sqrt(6.) * np.nanmedian(np.abs(2.*flux - \
np.roll(flux, 2, axis=axis) - np.roll(flux, -2, axis=axis)), \
... | 964362545e2fb8a0e7f15df71d90c5ce3e2f5815 | 3,648,119 |
def subtract_images(img_input, img_output, img_height, img_width):
"""Subtract input and output image and compute difference image and ela image"""
input_data = img_input.T
output_data = img_output.T
if len(input_data) != len(output_data):
raise Exception("Input and Output image have different s... | 7b2b2df57055cc73bec85bed2a5bece8187ddcdf | 3,648,120 |
import ctypes
def k4a_playback_get_track_name(playback_handle, track_index, track_name, track_name_size):
"""
K4ARECORD_EXPORT k4a_buffer_result_t k4a_playback_get_track_name(k4a_playback_t playback_handle,
size_t track_index,
char *track_name,
size_t *track_name_si... | 872c5aa73f9520f178fdbdfe47c314f9043282c0 | 3,648,121 |
def recommend_lowercase_d(data: pd.Series, **kwargs) -> int:
"""Returns the recommended value of differencing order 'd' to use
Parameters
----------
data : pd.Series
The data for which the differencing order needs to be calculated
*kwargs: Keyword arguments that can be passed to the differ... | a249ed104c00e62f386f82c5c4aaecc7cf0c4001 | 3,648,122 |
from typing import Dict
import json
def get_player_current_games_to_move(username: str) -> Dict:
"""Public method that returns an array of Daily Chess games
where it is the player's turn to act
Parameters:
username -- username of the player
"""
r = _internal.do_get_request(f"/player/{use... | 1ce906d24fa278703d708d41ed753c2cb24b48d0 | 3,648,123 |
def get_rb_data_attribute(xmldict, attr):
"""Get Attribute `attr` from dict `xmldict`
Parameters
----------
xmldict : dict
Blob Description Dictionary
attr : str
Attribute key
Returns
-------
sattr : int
Attribute Values
"""
try:
sattr = int(xml... | dfc48ad47f67b2303874154ce4a164a176c1f4bf | 3,648,124 |
from PythonPhot import photfunctions
import pdb
import pdb
def dopythonphot(image, xc, yc, aparcsec=0.4, system='AB', ext=None,
psfimage=None, psfradpix=3, recenter=False, imfilename=None,
ntestpositions=100, snthresh=0.0, zeropoint=None,
filtername=None, exptime=Non... | d204355c8b5b860c4cb4ef3304ca949969404bd8 | 3,648,125 |
import os
import zipfile
def zip_dir(source_dir, archive_file, fnmatch_list=None):
"""Creates an archive of the given directory and stores it in the given
archive_file which may be a filename as well. By default, this function
will look for a .cfignore file and exclude any matching entries from the
ar... | ea605c1c05eb06dab7c119b5072e181bd9d3b4e6 | 3,648,126 |
def tls_params(mqtt_config):
"""Return the TLS configuration parameters from a :class:`.MQTTConfig`
object.
Args:
mqtt_config (:class:`.MQTTConfig`): The MQTT connection settings.
Returns:
dict: A dict {'ca_certs': ca_certs, 'certfile': certfile,
'keyfile': keyfile} with the TL... | 4b5d214a50fea60f5cb325fc7a0c93dfa9cb3c02 | 3,648,127 |
def is_admin():
"""Check if current user is an admin."""
try:
return flask.g.admin
except AttributeError:
return False | 0922a93afacc4002068b60f1ab8a6594f0ddb44a | 3,648,128 |
def statistic():
""" RESTful CRUD Controller """
return crud_controller() | 02ed03d6d7d159046c12cbea98cc69c7bb0ae024 | 3,648,129 |
import argparse
def parse_args():
""" Parses command line arguments.
:return: argparse parser with parsed command line args
"""
parser = argparse.ArgumentParser(description='Godot AI Bridge (GAB) - DEMO Environment Action Client')
parser.add_argument('--id', type=int, required=False, default=DEF... | ff3e118179cb1a8d6f5d5d0067c7b11241522632 | 3,648,130 |
def segment_range_to_fragment_range(segment_start, segment_end, segment_size,
fragment_size):
"""
Takes a byterange spanning some segments and converts that into a
byterange spanning the corresponding fragments within their fragment
archives.
Handles prefix, suff... | e20c9bb55d9d3e90beb20bed7a170d1066611ba9 | 3,648,131 |
import collections
def update_dict(d, u):
""" Recursively update dict d with values from dict u.
Args:
d: Dict to be updated
u: Dict with values to use for update
Returns: Updated dict
"""
for k, v in u.items():
if isinstance(v, collections.Mapping):
default ... | e0228d3d0946f20b4bad8bfbc94a725f62bddfc5 | 3,648,132 |
def get_dataset(args, tokenizer, evaluate=False):
"""Convert the text file into the GPT-2 TextDataset format.
Args:
tokenizer: The GPT-2 tokenizer object.
evaluate: Whether to evalute on the dataset.
"""
file_path = args.eval_data_file if evaluate else args.train_data_file
if args.l... | 493bd0a5ca548b08052717d7e343e4f8b8911cb1 | 3,648,133 |
def test_function_decorators():
"""Function Decorators."""
# Function decorators are simply wrappers to existing functions. Putting the ideas mentioned
# above together, we can build a decorator. In this example let's consider a function that
# wraps the string output of another function by p tags.
... | 03b3ba299ceb7a75b0de1674fabe892243abd8b3 | 3,648,134 |
def make_loci_field( loci ):
""" make string representation of contig loci """
codes = [L.code for L in loci]
return c_delim2.join( codes ) | a643f70f02c3b79214d76f82bb4379ea0c0e1e84 | 3,648,135 |
import tqdm
def compute_wilderness_impact1(ground_truth_all, prediction_all, video_list, known_classes, tiou_thresholds=np.linspace(0.5, 0.95, 10)):
""" Compute wilderness impact for each video (WI=Po/Pc < 1)
"""
wi = np.zeros((len(tiou_thresholds), len(known_classes)))
# # Initialize true positive a... | 5f921d93993df1431c7b703df591f710cb2b5628 | 3,648,136 |
import os
def write_data_header(ping, status):
""" write output log file header
:param status: p1125 information
:return: success <True/False>
"""
try:
with open(os.path.join(CSV_FILE_PATH, filename), "w+") as f:
f.write("# This file is auto-generated by p1125_example_mahrs_cs... | c36a664da20eed120c7682b6c8555ad3e9278455 | 3,648,137 |
def require_client(func):
"""
Decorator for class methods that require a client either through keyword
argument, or through the object's client attribute.
Returns:
A wrapped version of the function. The object client attrobute will
be passed in as the client keyword if None is provided.... | 28cfd4821405a132cde4db8b95c68987db76b99d | 3,648,138 |
def extract_subwindows_image(image, scoremap, mask, input_window_size, output_window_size, mode, mean_radius,
flatten=True, dataset_augmentation=False, random_state=42, sw_extr_stride=None,
sw_extr_ratio=None, sw_extr_score_thres=None, sw_extr_npi=None):
"""... | 477d66513d93a7682325ab0e28711f968b34171a | 3,648,139 |
import base64
def format_template(string, tokens=None, encode=None):
"""Create an encoding from given string template."""
if tokens is None:
tokens = {}
format_values = {"config": config,
"tokens": tokens}
result = string.format(**format_values)
if encode == "base64":... | 91dafa48c0a9f17bbd663bcc14cfb800f6f57877 | 3,648,140 |
import os
import sys
def exists_case_sensitive(path: str) -> bool:
"""Returns if the given path exists and also matches the case on Windows.
When finding files that can be imported, it is important for the cases to match because while
file os.path.exists("module.py") and os.path.exists("MODULE.py") both ... | a879f950bcfb6739db3bfe620a75591de92a7a35 | 3,648,141 |
import six
def make_datastore_api(client):
"""Create an instance of the GAPIC Datastore API.
:type client: :class:`~google.cloud.datastore.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
:returns: A datast... | 63ab5acf85bcd2df9d266d285887c624a7554c64 | 3,648,142 |
def _mul_certain(left, right):
"""Multiplies two values, where one is certain and the other is uncertain,
and returns the result."""
if _is_number(left):
return Uncertain(
value=right.value * left,
delta=right.delta,
)
return Uncertain(
value=lef... | ae6159d1f59daea13794aa0ee0fb8baadf647471 | 3,648,143 |
def felica_RequestSystemCode(): # -> (int, List[int]):
"""
Sends FeliCa Request System Code command
:returns: (status, systemCodeList)
status 1: Success, < 0: error
systemCodeList System Code list (Array length should longer than 16)
"""
cmd = bytearra... | ff380077daef948a6a3ad274a9accccea22fcba1 | 3,648,144 |
from typing import Optional
from typing import Callable
import types
def get_regularizer(
regularizer_type: str, l_reg_factor_weight: float
) -> Optional[Callable[[tf.Tensor], Optional[tf.Tensor]]]:
"""Gets a regularizer of a given type and scale.
Args:
regularizer_type: One of types.RegularizationType
... | c9f7f8dd227a7446c9b15aebf1e2f1065a3d810d | 3,648,145 |
def metadata():
"""Returns shared metadata instance with naming convention."""
naming_convention = {
'ix': 'ix_%(column_0_label)s',
'uq': 'uq_%(table_name)s_%(column_0_name)s',
'ck': 'ck_%(table_name)s_%(constraint_name)s',
'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_ta... | 25363d243a2474dfbd43d57ff794899bfe30a44d | 3,648,146 |
import time
def date_rss(dte=None):
"""Dtate au format RSS """
ctime = time if dte is None else time.mktime(dte.timetuple())
return ctime.strftime('%a, %d %b %Y %H:%M:%S %z') | 6c343b675be5b89051fe9d76a9fb6437e89611bb | 3,648,147 |
def warp_containing_points(img, pts, H, border=4, shape_only=False):
"""
display = img.copy()
for pt in pts.reshape((-1,2)).astype(int):
cv2.circle(display, tuple(pt), 4, (255, 0, 0),
-1, cv2.LINE_AA)
debug_show('warp', display)
"""
pts2 = cv2.perspectiveTransform(pt... | b60fdd8a9f548252a40515298ca0f35dd3d497e6 | 3,648,148 |
def generate_parallelogrammatic_board(width=5, height=5):
"""
Creates a board with a shape of a parallelogram.
Width and height specify the size (in fields) of the board.
"""
return [[1] * height for _ in range(width)] | 1c9bd6e6e26f6693b434d44e6dbe4085ba9236b8 | 3,648,149 |
def function_is_even(latex_dict: dict) -> str:
"""
colloquially,
sympy.cos(x)==sympy.cos(-x)
sympy.cos(x) - sympy.cos(-x) == 0
>>> latex_dict = {}
>>> latex_dict['input'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}]
>>> latex_dict['feed'] = [parse_latex('')]
>>> latex_dict['out... | 0169440f0ebe373efdc18b79a1b8f48220fada13 | 3,648,150 |
def summarize_curriculum(
curriculum: AbstractCurriculum,
) -> str:
"""
Generate a detailed string summarizing the contents of the curriculum.
:return: A string that would print as a formatted outline of this curriculum's contents.
"""
def maybe_plural(num: int, label: str):
return f"{... | 010f3fb38473d0a572616204c381bde04f83fb0e | 3,648,151 |
def get_solarsample():
"""
NAME:
get_solarsample
PURPOSE:
get the RC sample at solar abundances
INPUT:
None so far
OUTPUT:
sample
HISTORY:
2015-03-18 - Started - Bovy (IAS)
"""
# Get the full sample first
data= get_rcsample()
# Now cut it
lo... | e511dbfdf013528f1bba3c7d794d776a2791e918 | 3,648,152 |
from typing import List
def perform_context_selection(
estimation_tasks: List[EstimationTask],
) -> List[EstimationTask]:
"""Changes the circuits in estimation tasks to involve context selection.
Args:
estimation_tasks: list of estimation tasks
"""
output_estimation_tasks = []
for est... | 814a5dd72a6c4b76c52af606c3136a6fd1cb46d9 | 3,648,153 |
import torch
def where(condition, x, y):
"""Wrapper of `torch.where`.
Parameters
----------
condition : DTensor of bool
Where True, yield x, otherwise yield y.
x : DTensor
The first tensor.
y : DTensor
The second tensor.
"""
return torch.where(condition, x, y) | 0ec419e19ab24500f1be6c511eb472d1d929fe2c | 3,648,154 |
def ukhls_wave_prefix(columns, year):
""" Determine wave prefix for ukhls wave data.
Parameters
----------
columns : list
A list of column names to add wave prefixes to.
year : int
Which wave year is being processed.
Returns
-------
columns : list
Column names w... | 726cc3a153ad9c43ebd99b96c405ab4bbd8ff56c | 3,648,155 |
from typing import Iterable
from typing import Optional
from typing import List
from typing import cast
def sort_converters(converters: Iterable[Optional[GenericConverter]]) -> List[GenericConverter]:
"""
Sort a list of converters according to their priority.
"""
converters = cast(Iterable[GenericConv... | 8112bfe4da1154c0b0e5aa421cf3c6d90148cbed | 3,648,156 |
import os
def _make_path_relative(origin, dest):
"""
Return the relative path between origin and dest.
If it's not possible return dest.
If they are identical return ``os.curdir``
Adapted from `path.py <http://www.jorendorff.com/articles/python/path/>`_ by Jason Orendorff.
"""
origin =... | 977588d2cf64c42f5e620d78ebceb60d1ef220fe | 3,648,157 |
def print_mf_weight_statistics():
""" Prints debug info about size of weights. """
def callback(i_epoch, model, loss_train, loss_val, subset=None, trainer=None, last_batch=None):
models, labels = [], []
try:
models.append(model.outer_transform)
labels.append("outer trans... | dd5d14bddb7acff6547bb87a6804bf2c719a4a34 | 3,648,158 |
def createPolygon(fire):
"""
create a Polygon object from list of points
"""
points = []
for coordinate in fire["geometry"]["coordinates"][0]:
points.append(tuple(coordinate))
polygon = Polygon(points)
return polygon | ce985b494d0d56f9b44a684ab187fb290d0c5d4f | 3,648,159 |
def change_anim_nodes(node_object="", in_tangent='linear', out_tangent='linear'):
"""
Changes the setting on all anim nodes.
:param node_object:
:param in_tangent:
:param out_tangent:
:return: <bool> True for success. <bool> False for failure.
"""
anim_nodes = object_utils.get_connected_... | 649f740669c2f292bfc180895a2ce5d295b2ef68 | 3,648,160 |
def is_x_degenerated(x, codon, table):
"""Determine if codon is x-fold degenerated.
@param codon the codon
@param table code table id
@param true if x <= the degeneration of the codon
"""
return (x <= len(altcodons(codon, table))) | b6a6bd8afc21a8e9b94dc7aa086255b6dfa44e85 | 3,648,161 |
import torch
def get_long_tensor(tokens_list, batch_size, pad_id=constant.PAD_ID):
""" Convert (list of )+ tokens to a padded LongTensor. """
sizes = []
x = tokens_list
while isinstance(x[0], list):
sizes.append(max(len(y) for y in x))
x = [z for y in x for z in y]
tokens = torch.L... | d088277fcd8f599d142ff7bdb1b8e018c5b6c1cb | 3,648,162 |
def business():
"""
show business posts
"""
business = Post.query.filter_by(category="Business").all()
return render_template('business.html', post=business) | 2fd3a46391681a25cdb3291f0a92e110dc0d4eb3 | 3,648,163 |
def tile_image(x_gen, tiles=()):
"""Tiled image representations.
Args:
x_gen: 4D array of images (n x w x h x 3)
tiles (int pair, optional): number of rows and columns
Returns:
Array of tiled images (1 x W x H x 3)
"""
n_images = x_gen.shape[0]
if not tiles:
for i in range(int(np.sqrt(n_im... | d95a9cd12f6ba4239724b84efd701575678f217f | 3,648,164 |
def note_updated_data(note, role):
"""Return the data for updated date
:param note: the note that holds the data
:type note: :class:`jukeboxcore.djadapter.models.Note`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the updated date
:rtype: depending on rol... | 987e78ae0c5a7a4570b619520d8b20f592adae07 | 3,648,165 |
def _xyz_atom_coords(atom_group):
"""Use this method if you need to identify if CB is present in atom_group and if not return CA"""
tmp_dict = {}
for atom in atom_group.atoms():
if atom.name.strip() in {"CA", "CB"}:
tmp_dict[atom.name.strip()] = atom.xyz
if 'CB' in tmp_dict:
... | fd7ef43b1935f8722b692ad28a7e8b309033b720 | 3,648,166 |
import pathlib
def InitBareRepository(path):
"""Returns the Repo object"""
assert isinstance(path, str)
pathlib.Path(path).parent.mkdir(parents=True,exist_ok=True)
return git.Repo.init(path,bare=True) | 84b321c7b27ee8ab7101339671361f45ec474e91 | 3,648,167 |
def get_http_exception(code):
"""Return an exception class based on its code"""
try:
return http_exceptions[int(code)]
except:
return None | f7b5077331b4425d5ee49a8c61849bb6ba822049 | 3,648,168 |
def _zoom(restricted_func_and_grad, wolfe_one, wolfe_two, a_lo, phi_lo,
dphi_lo, a_hi, phi_hi, dphi_hi, g_0, pass_through):
"""
Implementation of zoom. Algorithm 3.6 from Wright and Nocedal, 'Numerical
Optimization', 1999, pg. 59-61. Tries cubic, quadratic, and bisection methods
of zooming.
"""
st... | ec4d1381e831c19f342d69136d5ce936fc20042e | 3,648,169 |
from typing import Union
def _gradients_input(model: Union[tf.keras.models.Model, 'keras.models.Model'],
x: tf.Tensor,
target: Union[None, tf.Tensor]) -> tf.Tensor:
"""
Calculates the gradients of the target class output (or the output if the output dimension is equal... | 816c1f932533de4cdfd96525c44a2c11bae60254 | 3,648,170 |
from Totoro.dbclasses import Set as Set
def fixBadSets(sets):
"""Splits bad sets into a series of valid, incomplete sets."""
toRemove = []
toAdd = []
for ss in sets:
if ss.getStatus(silent=True)[0] != 'Bad':
continue
toRemove.append(ss)
if len(ss.totoroExposur... | fcb0716c0d798999f9572344bdce042bedaec28c | 3,648,171 |
from typing import OrderedDict
def get_databases():
"""Return an ordered dict of (dbname: database). The order is
according to search preference, the first DB to contain a document
should be assumed to be the authoritative one."""
sql_dbs = [
_SQLDb(
XFormInstanceSQL._meta.db_table... | 01180d4cafbcf0b1d48e7c7554069a7ee5bf1a65 | 3,648,172 |
from AppKit import \
def get_app_data_path(app_name):
"""Returns the OS-specific path to Application Data for the given App.
Creates the path if it doesn't already exist.
NOTE: Darwin: https://developer.apple.com/reference/foundation/1414224-nssearchpathfordirectoriesindoma?language=objc
"""
asse... | d95215bec859e6d9858a9c342cb26808814f9713 | 3,648,173 |
def list_examples():
"""List all examples"""
examples = ExampleModel.query()
form = ExampleForm()
if form.validate_on_submit():
example = ExampleModel(
example_name=form.example_name.data,
example_description=form.example_description.data,
added_by=users.get_c... | 740e7005e1cadae22ba77095b43dadd6b4219012 | 3,648,174 |
import re
def parse_direct_mention(message_text):
"""
Finds a direct mention (a mention that is at the beginning) in message text
and returns the user ID which was mentioned. If there is no direct mention, returns None
"""
matches = re.search(_MENTION_REGEX, message_text)
# the first g... | b442dc276cde0e28b56fbf855999feaeb199bff2 | 3,648,175 |
import types
def prepare_deep(schema: types.Schema, schemas: types.Schemas):
"""
Resolve $ref and merge allOf including for object properties and items.
Assume the schema is a valid JSONSchema.
Args:
schema: The schema to prepare.
schemas: The schemas from which to resolve any $ref.
... | e77f7f0e59a6400c2e7df78b0ec2a14bcc0b3ea6 | 3,648,176 |
def _resize_and_center_fundus(image, diameter):
"""
Helper function for scale normalizing image.
"""
copy = image.copy()
# Find largest contour in image.
contours = _find_contours(image)
# Return unless we have gotten some result contours.
if contours is None:
return None
... | f301740cec8ca423334ffd127005b90f54105ce5 | 3,648,177 |
def _pad_X_delta(X, delta, indices, padded_group_size):
"""Currently Unused."""
X_group = onp.take(X, indices, axis=0)
X_group = onp.pad(X_group, [(0, padded_group_size - X_group.shape[0]),
(0, 0)])
delta_group = onp.take(delta, indices, axis=0)
delta_group = onp.pad(delta_group... | d286b922efb6482382af8cd804c5e51b15d93088 | 3,648,178 |
def union(x, y=None):
"""Get sorted list of elements combined for two iterables."""
x, y = de_list_pair(x, y)
return sorted(list(set(x) | set(y))) | c24deb82e60569196e7a2d691db192c0ffcf91dd | 3,648,179 |
from typing import get_origin
from typing import Tuple
def is_tuple(typ) -> bool:
"""
Test if the type is `typing.Tuple`.
"""
try:
return issubclass(get_origin(typ), tuple)
except TypeError:
return typ in (Tuple, tuple) | c8c75f4b1523971b20bbe8c716ced53199150b95 | 3,648,180 |
import functools
import unittest
def _skip_if(cond, reason):
"""Skip test if cond(self) is True"""
def decorator(impl):
@functools.wraps(impl)
def wrapper(self, *args, **kwargs):
if cond(self):
raise unittest.SkipTest(reason)
else:
impl(s... | 4141cc1f99c84633bdf2e92941d9abf2010c11f6 | 3,648,181 |
from typing import Dict
import shutil
def _smash_all(job_context: Dict) -> Dict:
"""Perform smashing on all species/experiments in the dataset.
"""
start_smash = log_state("start smash", job_context["job"].id)
# We have already failed - return now so we can send our fail email.
if job_context['job... | b1ada544140c10c73e59430631e3bda67a160587 | 3,648,182 |
def permute_columns(df,
column_to_order: str,
ind_permute: bool = False,
columns_to_permute: list = []):
"""
Author: Allison Wu
Description: This function permutes the columns specified in columns_to_permute
:param df:
:param column_to_orde... | 89da810d93586d66963d9a3ee3c7d6c0960596c9 | 3,648,183 |
def reset_dismissed(institute_id, case_name):
"""Reset all dismissed variants for a case"""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
controllers.reset_all_dimissed(store, institute_obj, case_obj)
return redirect(request.referrer) | c16dcc7e23be620212ee6756051db6e089014678 | 3,648,184 |
import os
def create_xst_script(config):
"""
given the configuration file create a script that will
build the verilog files declared within the configuration file
Args:
config (dictionary): configuraiton dictionary
Return:
(string) script file name
Raises:
Nothing
... | f9308dc4ace542d63ef2075a73502a5b1dd2fe97 | 3,648,185 |
def texts_from_array(x_train, y_train, x_test=None, y_test=None,
class_names = [],
max_features=MAX_FEATURES, maxlen=MAXLEN,
val_pct=0.1, ngram_range=1, preprocess_mode='standard', verbose=1):
"""
Loads and preprocesses text data from arrays.
Args:
... | ecb120070ac76d21da34fd5f0d27799fe5ba093b | 3,648,186 |
def display2(depts, level=0):
"""
[[a, 1], [b, 2], [c, 3], [d, 3], [a, 1]]
:param depts:
:return:
"""
lists = []
for d in depts:
lists.append([d, level])
children = Department.objects.filter(parent_id=d.id)
if children:
lists.extend(display2(children, leve... | 6187c91dd5653ab3f7a7e68d6b811ffda2afb035 | 3,648,187 |
def _get_target_id_to_skill_opportunity_dict(suggestions):
"""Returns a dict of target_id to skill opportunity summary dict.
Args:
suggestions: list(BaseSuggestion). A list of suggestions to retrieve
opportunity dicts.
Returns:
dict. Dict mapping target_id to corresponding skil... | faf708abb5876a56b06282b99c4cc7221c33c5bd | 3,648,188 |
def default_loc_scale_fn(
is_singular=False,
loc_initializer=tf.random_normal_initializer(stddev=0.1),
untransformed_scale_initializer=tf.random_normal_initializer(
mean=-3., stddev=0.1),
loc_regularizer=None,
untransformed_scale_regularizer=None,
loc_constraint=None,
untransformed_s... | 54eeec1b5739a71473abfa5a5ffb7aa5aa572505 | 3,648,189 |
from skimage.morphology import disk
from cv2 import dilate
def db_eval_boundary(args):
"""
Compute mean,recall and decay from per-frame evaluation.
Calculates precision/recall for boundaries between foreground_mask and
gt_mask using morphological operators to speed it up.
Arguments:
f... | 0aa23d0d8b45681e50f3b99c72dfcb5851dd92a6 | 3,648,190 |
def angle_trunc(a):
"""
helper function to map all angles onto [-pi, pi]
"""
while a < 0.0:
a += pi * 2
return ((a + pi) % (pi * 2)) - pi | 36e5d97affab5f3a1155b837df9985fe26795d76 | 3,648,191 |
from typing import Optional
def get_tag_or_default(
alignment: pysam.AlignedSegment, tag_key: str, default: Optional[str] = None
) -> Optional[str]:
"""Extracts the value associated to `tag_key` from `alignment`, and returns a default value
if the tag is not present."""
try:
return alignment.g... | bf3b1495224d7409c410f96daa20af8f70a27efa | 3,648,192 |
def vtln_warp_mel_freq(vtln_low_cutoff, vtln_high_cutoff, low_freq, high_freq,
vtln_warp_factor, mel_freq):
"""
Inputs:
vtln_low_cutoff (float): lower frequency cutoffs for VTLN
vtln_high_cutoff (float): upper frequency cutoffs for VTLN
low_freq (float): lower freq... | e6432c0298e559dc958011bdf5d52c3e92544213 | 3,648,193 |
def _squared_loss_and_spatial_grad_derivative(X, y, w, mask, grad_weight):
"""
Computes the derivative of _squared_loss_and_spatial_grad.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Design matrix.
y : ndarray, shape (n_samples,)
Target / response vector.
... | 05ce984609f5d31fda33d7fb0263ecc056c2f0ed | 3,648,194 |
import ctypes
def destructor(cfunc):
"""
Make a C function a destructor.
Destructors accept pointers to void pointers as argument. They are also wrapped as a staticmethod for usage in
classes.
:param cfunc: The C function as imported by ctypes.
:return: The configured destructor.
"""
... | 05abd181649a2178d4dce704ef93f61eb5418092 | 3,648,195 |
def invalid_auth_header(jwt):
"""Produce invalid JWT tokens for use in tests."""
return {'Authorization': 'Bearer ' + jwt.create_jwt(claims=TestJwtClaims.invalid, header=JWT_HEADER)} | 91f82b4a9be3740e115da4182325c71fa84440b7 | 3,648,196 |
def update_file_info_in_job(job, file_infos):
"""
Update the 'setup.package.fileInformations' data in the JSON to append new file information.
"""
for file_info in file_infos:
try:
job['setup']['package']['fileInformations'].append(file_info)
except (KeyError, TypeError, Attr... | 9902173548d72fcd35c8f80bb44b59aac27d9401 | 3,648,197 |
def _FirstStatementsInScriptElements(contents):
"""Returns a list of first statements found in each <script> element."""
soup = parse_html.BeautifulSoup(contents)
script_elements = soup.find_all('script', src=None)
return [_FirstStatement(e.get_text()) for e in script_elements] | 7b2a3bddfa63a6ab4765906862037adf786c253a | 3,648,198 |
def load_image(input_file_path):
"""
Load the 'input_file_path' and return a 2D numpy array of the image it contains.
"""
image_array = np.array(pil_img.open(input_file_path).convert('L'))
return image_array | b5783b9bcca55be355a91c6e9e2d2fcd09d1989b | 3,648,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.