content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import sys
import re
def get_arguments_info(parser):
"""
Read help message into variable by putting the stdout output from
parser.print_help() into a custom sdtout.
Parameters
==========
parser [argparse.ArgumentParser]
Returns
=======
arguments_info [dict]: arguments_info[var... | 203afe8b9a3adb112809c5a9f6a9d7138792f57e | 40,000 |
import os
def parse_args(argv):
"""Returns a tuple of (opts, args) for arguments."""
parser = make_parser()
args = parser.parse_args(argv[1:])
sdk = args.sdk
# Use APPENGINEPY_SDK_VERSION if set.
if not sdk and (sdk_version_key in os.environ):
sdk = (os.environ[sdk_version_key],)
... | 3562d41af679e2d9a9be17aef45bf3f467e9e66f | 40,001 |
import os
def cat(dir, file_name=None, input=None):
""" act like unix 'cat' - put string into file (or echo data out """
ret_val = None
# step 1: figure out the file path
if dir:
if file_name:
file_path = os.path.join(dir, file_name)
else:
file_path = dir
... | 5ef0ae24d1ea3bd23c98d43ab2ddca80233a75b9 | 40,002 |
import typing
def get_state_change_with_balance_proof(
storage: sqlite.SQLiteStorage,
chain_id: typing.ChainID,
token_network_identifier: typing.TokenNetworkID,
channel_identifier: typing.ChannelID,
balance_hash: typing.BalanceHash,
sender: typing.Address,
) -> sqlite.S... | e8e7d3ec2e77ddd34fc9a667ffb163e9e6348e32 | 40,003 |
import random
def best_down_collapse(X,kX,dimq,signal):
"""Returns the down-collapse V which minimize the topological reconstructione error ||s-phi*_Vpsi*_V(s)|^2
"""
s=np.array(signal)**2
Bq=kX[dimq]
BT=Bq.copy()
C=BT.tolil()
ind=C.rows
possible_min_WQ=[]
possible_min_value=[]
... | 2af47e329fea00db7cab5e8e8cb56099cf3e2a5a | 40,004 |
def evaluate_lambda_t(t, phi_start, linear, phase0):
"""
Evaluates firing rate(t, x) = tuning_curve(x) * theta_modulation(t, x) at given time points
:param t: sample time points
:param phi_start: starting point of the place field (in rad)
:param linear: flag for circular vs. linear track -> slightly... | 04a6830e34945dea83c70c5fca969c09bf17594e | 40,005 |
import struct
def _mapc(ctx, input_files, resource_info):
"""Creates actions that compile a Core Data mapping model files.
Each file should be contained inside a .xcmappingmodel directory.
Args:
ctx: The Skylark context.
input_files: An iterable of files in all mapping models that should be
... | 2c38e2b69f30763b31ab3b9d4b88deeb3e4dcbf7 | 40,006 |
from pathlib import Path
def image_content_type(outfile: Path) -> str:
""" Derives a content type from an image file's suffix """
return f"image/{outfile.suffix[1:]}" | 4c1545dbdcaa31826fd8567cabe2935ed7237961 | 40,007 |
def play_again() -> str:
"""Ask the user if he wants to play another turn"""
yes_or_no = input('Play again? [y/n]: ')
while yes_or_no not in ['y', 'n']:
yes_or_no = input('Please insert "y" or "n": ')
return yes_or_no | 8b3d74456b7ce13a0ffffab8dc9e946cbb5e594c | 40,008 |
def create_session (user, is_trusted):
"""
Perform user authentication User.password and role activations.
This method must be called once per user prior to calling other methods within this module.
The successful result is Session that contains target user's RBAC User.roles.
This API will...
... | c87c2e58420dca6923cf251736728e9320aa1bde | 40,009 |
def ansi_wrap(value: str, width: int = 80, left_pad: int = 6) -> str:
"""Wrap characers relative to their cell width."""
decoded_text = decode_ansi(value)
wrapped_text = "\n".join(_wrap_ansi(decoded_text, width=width, left_pad=left_pad))
return wrapped_text | 611eacafdb15d99aaa7f20a2b0af61c23f402d12 | 40,010 |
def hashcolumns(dframe, columns, maxval):
""" Hash each value of multiple dataframe columns. """
columnvals = list(zip(*(dframe[col] for col in columns)))
return list(hashval(v, maxval) for v in columnvals) | 0cec3d573c743459ef40e6c877cd32eb7e48d7fb | 40,011 |
import random
def random_triangles(n=3):
""" Draw n triangles which can overlap """
coords = []
for i in range(n*3):
coords.append([random.random()*5, random.random()*5,random.random()*5])
coords = np.array(coords)
faces = []
for i in range(n):
faces.append([i*3, i*3+1, i*3+... | c7fb47b0c8054d052d1f3e883a62111fb67c563a | 40,012 |
def get_config():
"""Get the default hyperparameter configuration."""
config = ml_collections.ConfigDict()
config.problem = "classification"
config.env_model = "MLP"
config.agent = "KalmanFilter"
config.seed = 0
config.nsteps = 20
config.ntrials = 20
config.train_batch_size = 1
... | dee1e80ad054c3dbaf543a36eb00b0ae88ae2475 | 40,013 |
import os
import itertools
def extras_require() -> t.Dict[str, t.List[str]]:
"""
Parse requirements in requirements/extras directory
"""
extra_requirements = {}
for extra in extras:
extra_requirements[extra] = parse_requirement(
os.path.join("extras", extra + ".txt")
)
... | e825b06836add48886fbc10e3817b8dcd7d3b525 | 40,014 |
def make_vbox(model_dict: dict) -> widgets.VBox:
"""
:param model_dict:
:return:
"""
labels = []
for k in model_dict:
if type(model_dict[k]) is not dict:
string = str(model_dict[k])
labels.append(make_setting_hbox(k, string))
else:
mini_labels... | cde09236834d63fcb3e2067d2dffe2a02f164a22 | 40,015 |
def UserTypingFilter(cli):
"""Determine if the input field is empty."""
return (cli.current_buffer.document.text and
cli.current_buffer.document.text != cli.config.context) | 420b24cdeb17cb97294a937e49096c5462d4061e | 40,016 |
from typing import Sequence
def create_myst_config(
settings: frontend.Values,
excluded: Sequence[str],
config_cls=MdParserConfig,
prefix: str = "myst_",
):
"""Create a configuration instance from the given settings."""
values = {}
for attribute in config_cls.get_fields():
if attri... | c01965aa451b871cf7a37a5470f121122ac9132b | 40,017 |
def cube_K(shape, rms, data, peaks=[0, 1, 2, 3], origin=(0, 0),
header=None, writeto=None, **kwargs):
"""
Construct a fits HDU with ln(K) values for all xy positions in a
cube of a given shape. Optionally, writes a fits file.
Additional keyword args are passed to lnK_xy function.
"""
... | 38ce1c634bd4140a0debf415a691a0670cd192f8 | 40,018 |
def scale_image(image, new_width=600):
"""
scales the image to new_width while maintaining aspect ratio
"""
new_w = new_width
(old_w, old_h) = image.size
aspect_ratio = float(old_h)/float(old_w)
new_h = int(aspect_ratio * new_w)
new_dim = (new_w, new_h)
image = image.resize(new_dim)
... | e9bfdf6309cf97b1a7f44dff96b655aa09d64fd5 | 40,019 |
def get_container_metadata(item):
"""Extract desired metadata from Docker container object."""
if type(item) is str:
return item
tags = getattr(item, 'tags', None)
if tags is not None:
return tags[0]
else:
return str(item) | bf805e33f17dc664a62989f36ae164ee3c348b3e | 40,020 |
def leaky_relu(alpha=0.1, name='LeakyReLU', collect=False):
"""Modified version of ReLU, introducing a nonzero gradient for negative input.
Args:
alpha: `int`, the multiplier.
name: operation name.
collect: whether to collect this metric under the metric collection.
"""
def _le... | de44b67e4dcd3e84e86aca8b00ec57f37b5f4c69 | 40,021 |
def show_sample_attributes(request):
"""
show the user-defined sample attribute home page
"""
ctxd = {}
ctx = RequestContext(request, ctxd)
return render_to_response(
"rundb/sample/sampleattributes.html", context_instance=ctx, mimetype="text/html"
) | 76574030051e108a4d9e0590a153728e0531fb21 | 40,022 |
def get_pks(constraints):
"""Get primary key(s) given constraint list"""
pks = {}
if constraints:
for name, constraint in constraints.items():
if constraint['type'] == PRIMARY and len(constraint['columns']) == 1:
column = constraint['columns'][0]
pks[colu... | 0033779e880bee0fc7736adfbb0effb5934d038f | 40,023 |
def _invoke_function(function_name, json_args, json_kwargs):
"""Invokes callback with given function_name.
This function is meant to be used by frontend when proxying
data from secure iframe into kernel. For example:
_invoke_function(fn_name, "'''" + JSON.stringify(data) + "'''")
Note the trip... | df3423ba5ce31ffb70b7b34a5684de69b0327fc2 | 40,024 |
def single_particle_first2p_zbt_metafit(fitfn, exp_list, **kwargs):
"""Fit to zero body terms for all available normal-ordering schemes,
taking only the first 2 points from each
"""
return single_particle_metafit_int(
fitfn, exp_list,
dpath_sources=DPATH_FILES_INT, dpath_plots=DPATH_PLOT... | 1381cccb1482f6cb240c6d965b5930b37377c8f9 | 40,025 |
def interact_GxG(pheno,snps1,snps2=None,K=None,covs=None):
"""
Epistasis test between two sets of SNPs
Args:
pheno: [N x 1] SP.array of 1 phenotype for N individuals
snps1: [N x S1] SP.array of S1 SNPs for N individuals
snps2: [N x S2] SP.array of S2 SNPs for N individuals
... | d04ee8132fe002e4aaf63bf71273244c19e379c0 | 40,026 |
def _get_clone_readiness(media, dtype):
"""
Checks the given media for clones and determines their readiness for archiving.
"""
if dtype == "image":
return _get_single_clone_readiness(media, "image")
if dtype == "video":
return _get_single_clone_readiness(media, "archival")
if dt... | 0103942413fea87b7ac630f80a0374b7a64afdb9 | 40,027 |
def bot_is_public():
"""Don't use this elsewhere."""
async def bot_public(ctx: SalamanderContext) -> bool:
assert isinstance(ctx.cog, Meta), "safe enough" # nosec
cog: Meta = ctx.cog
info = await cog.cached_info.get_app_info()
return info.bot_public or await ctx.bot.is_owner(ct... | 85f412d7ba91f7748bc9561cfb7eac3dade91240 | 40,028 |
def objmap_streamfunc_uvh(xd, yd, ud, vd, hd, xm, ym, l, SNR, fcor, g=9.81, return_err=False):
"""Map velocity and height observations to non-divergent geostrophic stream function.
The Coriolis parameter fcor and gravity (or reduced gravity) g should be specified."""
xd = np.asarray(xd).ravel()
yd = np.... | 0d2b9853b063b324262a1a1ecb9c6cd3a61a8769 | 40,029 |
import html
def visualize_game_round_count():
"""
Prints round count of a game.
:return: html code
"""
return html.Span('Rounds: {0}'.format(len(pre.round_names)), style={'padding': '5px', 'fontSize': '16px'}) | cac271ea54abb0c91eadb426f1965bbfe864b1eb | 40,030 |
def get_window_icon(hwnd):
"""Return QPixmap."""
#hicon = win32gui.GetClassLong(hwnd, win32con.GCL_HICON)
hicon = get_hicon(hwnd)
if not valid_handle(hicon):
return None
try:
return make_qicon(hicon)
except:
return None
#info = win32gui.GetIconInfo(hicon)
#try:
... | 5dcc6af381f06d3c3d422c2c5b67721fbd7b5ca4 | 40,031 |
def ec_entity(response):
"""
Return URL or File entity in Demisto format for use in entry
context depending on data in 'response' (the report)
Parameters
----------
response : dict
Object returned by ANYRUN API call in 'get_report' function.
Returns
-------
dict
Fil... | 81ec1a9d3a932de63b3edd0ca93c88988ea380fd | 40,032 |
def generate_map(df: pd.DataFrame):
""""
Generates the map for the dashboard
Parameters
----------
df : pandas dataframe
The dataframe that contains the data to plot.
Returns
-------
chart : html of altair Chart
The generated map converted to html
"""
world_map ... | cbb4af10249b538ed4bbc276b854221b8984dd28 | 40,033 |
def mapped_route_add(request):
"""
Страница конструктора, которая позволит задавать последовательность остановок,
Далее, открыть карту и построить промежуточные маршруты,
Подтвердить и исходранить маршрут в БД.
:param request:
:return: Template of constructor
"""
template_name = 'admin_... | 447f236c2560953e8ddcb3594e9a3e9aa91d0b9b | 40,034 |
def percentage(sub, all):
"""Calculate percent relation between "sub" and "all".
Args:
sub (int): Some value.
all (int): Maximum value.
Returns:
int: (sum * 100) / all
"""
return int((sub * 100) / all) | 21b398c81f76de0ec81be9d26b2f79d8b0d08edc | 40,035 |
def symbolicTz(z = 0):
"""
Translation on «z» axis. Returns Dual Quaternion in matrix form
"""
return Matrix([[1],
[0],
[0],
[0],
[0],
[0],
[0],
[0.5 * z]]) | 19a9c3c1476593f776117a4787cd1a7bba7191b8 | 40,036 |
def get_branch_all(git_dir):
""" Return all branch names).
"""
try:
output = git('-C', git_dir, 'branch', '--all')
except ErrorReturnCode as e:
return failed_util_call_results(e)
else:
return succeeded_util_call_results(output) | 3a5bfc05832a5f9eb474ff9aae0f2ef79baecdf0 | 40,037 |
from typing import List
def _databases(is_refresh: bool, current_path: str, session: ObjectExplorerSession, match_params: dict) -> List[NodeInfo]:
"""Function to generate a list of databases"""
_default_node_generator(is_refresh, current_path, session, match_params)
is_system = 'systemdatabase' in current... | 614943d8fd13324476495d207018107761c7a26e | 40,038 |
def get_run_runtime(dataset_id, vm_id, run_id):
""" loads a runtime file (runtime.txt) and parses the string to return time, runtime_info"""
run_dir = (RUNS_DIR_PATH / dataset_id / vm_id / run_id)
if not (run_dir / "runtime.txt").exists():
return None
runtime = open(run_dir / "runtime.txt", 'r'... | f393a61a314099f906801f9520af666576fb65cf | 40,039 |
def metrics(bb1, bb2):
"""Computes metrics between two boxes"""
i1, j1, w1, h1 = to_tlwh(bb1)
i2, j2, w2, h2 = to_tlwh(bb2)
top = max(i1, i2)
bottom = min(i1 + h1, i2 + h2)
left = max(j1, j2)
right = min(j1 + w1, j2 + w2)
overlap_height = bottom - top
overlap_width = right - left
... | 28199a66e8c84387a846ced8956d125f851e29b1 | 40,040 |
def web_tokenizer(sentence):
"""
The web tokenizer works like the :func:`word_tokenizer`, but does not split URIs or
e-mail addresses. It also un-escapes all escape sequences (except in URIs or email addresses).
"""
return [token for i, span in enumerate(web_tokenizer.split(sentence))
fo... | bfaee7d3c7f2dddc21699371d69932922523bee3 | 40,041 |
import re
def _check_directory_files_permission(block_id, block_dict, extra_args=None):
"""
Check all files permission inside a directory
"""
path = runner_utils.get_param_for_module(block_id, block_dict, 'path')
permission = runner_utils.get_param_for_module(block_id, block_dict, 'permission')
... | 0483ff9c9fe3ce00d099333e7e725c62bb696be7 | 40,042 |
from datetime import datetime
def async_parse_date_datetime(
value: str, entity_id: str, device_class: SensorDeviceClass | str | None
) -> datetime | date | None:
"""Parse datetime string to a data or datetime."""
if device_class == SensorDeviceClass.TIMESTAMP:
if (parsed_timestamp := dt_util.pars... | d305ce88627d8d7bb98307399db69be64fc0b6df | 40,043 |
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel... | 741d7a2af2e6c91d99d69020161981e4fedbbc51 | 40,044 |
async def app_factory() -> web.Application:
"""Created to launch app from gunicorn (see docker/boot.sh)"""
app_settings = ApplicationSettings()
assert app_settings.SC_BUILD_TARGET # nosec
log.info("Application settings: %s", app_settings.json(indent=2, sort_keys=True))
app, _ = _setup_app_from_se... | 10916d0ec81941621dc475603797f6082b2a5228 | 40,045 |
def makeone(pb, params, where, compdir=None):
"""
Crée une donnée pour l'apprentissage du problème "Le jardinier et les
taupes" :
1. Génère une instance du problème dans la version du module `pb`,
pour les paramètres `params`.
2. Résout cette instance.
3. Sauvegarde la gri... | 40c5f7f65bc4146d38d189efe61dbd4410fdc202 | 40,046 |
from dateutil import tz
def _collapse_to_cwl_record(samples, want_attrs):
"""Convert nested samples from batches into a CWL record, based on input keys.
"""
input_keys = sorted(list(set().union(*[d["cwl_keys"] for d in samples])), key=lambda x: (-len(x), tuple(x)))
out = {}
for key in input_keys:
... | ed5efb1a6c8c072cc7ed063676b8948789dff219 | 40,047 |
def open_old_stds(name, type, dbif=None):
"""This function opens an existing space time dataset and return the
created and initialized object of the specified type.
This function will call exit() or raise a
grass.pygrass.messages.FatalError in case the type is wrong,
or the space time d... | c0def972f41cc8bd2a15d5ce14b81cc388e02725 | 40,048 |
import typing
from pydantic import BaseModel # noqa: E0611
from re import T
def describe_response(
status: typing.Union[int, HTTPStatus],
description: str = "",
*,
content: typing.Union[typing.Type[BaseModel], type, dict] = None,
headers: dict = None,
links: dict = None,
) -> typing.Callable[... | 8cbe3b5c519ea2383a2d20a1f46abd967084866d | 40,049 |
def report_exception(f):
""" Minimal decorator for reporting exceptions that occur within a
function. Does not support generators."""
@wraps(f)
def wrapped_f(*args, **kwargs):
try:
return f(*args, **kwargs)
except:
sentry_sdk.capture_exception()
raise
... | 5af0ace66d157ed84b03e0b5256d2a75f56eec07 | 40,050 |
import logging
import os
def from_manifest(
manifest_path: str,
data_cache_name: str = "task_data",
logger: logging.Logger = logging.getLogger(__name__),
) -> Environment:
"""Load an environment object from a schema definition on disk."""
env = Environment()
# load the manifest
if not en... | 1f82dc791e2469d5ddd6bc189fe5a4260fce7ef3 | 40,051 |
from typing import Optional
from typing import Callable
from typing import Dict
from typing import Union
from typing import Sequence
from typing import Type
def thread_worker(
function: Optional[Callable] = None,
start_thread: Optional[bool] = None,
connect: Optional[Dict[str, Union[Callable, Sequence[Cal... | ff969af7808290be439e3e6335e66873a2f955b2 | 40,052 |
def uncorr_noise_deprojection_bias(f1, map_var):
"""
Computes the bias associated to contaminant removal in the presence of uncorrelated inhomogeneous noise to the auto-pseudo-Cl of a given field f1.
:param NmtField f1: fields to correlate
:param map_cls_guess: array containing a HEALPix map correspond... | 588379d9011fec22be3d9f1f4888ff4569e59499 | 40,053 |
def convert_expression(lst_tkn:list):
"""
Parameters:
-----------
* lst_tkn [list]: list containing the raw tokens.
Return:
-------
* lst_res [list]: NPI tokens list obtained by shunting-yeard algorithm.
"""
lst_tkn = natural_conversion(lst_tkn)
lst_res = shunting_yard_al... | 2b8954b092f1d4de9c46b2ab608e363ec5aa71f2 | 40,054 |
def value(colors: list):
"""
Each resistor has a resistance value.
Manufacturers print color-coded bands onto
the resistors to denote their resistance values.
Each band acts as a digit of a number.
The program will take two colors as input,
and output the correct number.
:param colors:
... | 14a52f12bfcfccd921ade8fa7708d3563c9c2508 | 40,055 |
import array
def intersect_curve_surface(curve, surface, itol=None):
"""
Find the intersection points of a curve and a surface.
:param curve: Curve to intersect.
:type curve: :class:`.BezierCurve` or :class:`.NurbsCurve`
:param surface: Surface to intersect.
:type surface: :class:`.BezierSurf... | 4c75b0f41b2345060f63032a0466bc0ed07cce69 | 40,056 |
def get_test_batch(data, batch_size=100, stim_history=30, min_window=10):
"""Get a batch of training data."""
stim = data['stimulus']
resp = data['responses']
ei_mag = data['ei_magnitude']
stim_batch = np.zeros((batch_size, stim.shape[1],
stim.shape[2], stim_history))
resp_batch =... | c07642e213414fa192b5fd7c50822ed03ecf8afb | 40,057 |
def rgb_to_hex(r, g, b):
"""
Generate a html hex color string from r,g,b values
:params r,g,b: (0,1) range floats
:return: a html compatible hex color string
"""
assert is_valid_rgb(r, g, b), "Error, r,g,b must be (0,1) range floats"
R,G,B = rgb_to_RGB(r,g,b)
return "#{:02x}{:02x}{:... | a71b30a96231940a019b9e16c7a2b06afe622073 | 40,058 |
def load_transforms(name):
"""Load data transformations.
Note:
- Gaussian Blur is defined at the bottom of this file.
"""
_name = name.lower()
if _name == "cifar_sup":
normalize = transforms.Normalize([0.4914, 0.4822, 0.4465], [0.2023, 0.1994, 0.2010])
aug_transform... | e925adebd7c414f53f20a902622734509922138c | 40,059 |
def set_axes(ax: Axes, x_scale: str = 'linear', y_scale: str = 'linear', xlim: tuple = (), ylim: tuple = (),
fontsize: int = 20, show_grid: bool = True,
hide_xticklabels: bool = False, hide_yticklabels: bool = False) -> Axes:
"""
Sets axes to an existing ax. The explanation of the argu... | 78f793f76af961c6785dcc8ee1d8f12dd0d71e8f | 40,060 |
import os
def readlinkabs(link: str) -> str:
"""Return an absolute path to symbolic link destination."""
# Adapted from code by Greg Smith.
assert os.path.islink(link)
path = os.readlink(link)
if os.path.isabs(path):
return path
return os.path.join(os.path.dirname(link), path) | 7367db60bd93b2ca9d4b00b003d912bc0e1a9641 | 40,061 |
def parallel_run(tasks):
"""
Tasks is an iterable of bound functions. The wrapper makes it easy for us
to run a list of different functions, rather than one function over a list
of inputs.
"""
workers = max(1, len(tasks))
with Pool(processes=workers) as pool:
# As soon as any one ta... | 067d437c5fe6269d8df8fbbe11dc797e0e94a41a | 40,062 |
def bgr_to_hex(b, g, r):
"""Converts (blue, green, red) to a "#rrbbgg" string.
Args:
b, g, r: the BGR values
Returns:
a hex string
"""
return rgb_to_hex(r, g, b) | 97d91cfd544a0dc3bae97fb81e0f626c40dc0ebe | 40,063 |
from typing import List
def get_all_csv_files_in_folder(folder: str) -> List[str]:
"""Returns list of strings including path to folder for CSV files"""
return get_all_files_in_folder_ending_with(folder=folder, ending=OUTPUT_FILE_ENDING) | b025404edd4a23cbb96c67ae9e02dfdc59562767 | 40,064 |
import numpy
def linear_correct_byte(image: numpy.ndarray, gamma: float = 2.2) -> numpy.ndarray:
"""
:param image:
:type image:
:param gamma:
:type gamma:
:return:
:rtype:"""
return gamma_correct_float_to_byte(image / 255, gamma) | a307a28724ae0dfd4470a163b489b18397f36a5e | 40,065 |
import base64
def is_authenticated(request, username, password):
"""Authenticate the request using HTTP Basic authorization"""
authenticated = False
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2:
if auth[0].lower() ... | 9ea596245283d34146058e7c79964646661c2151 | 40,066 |
def inspect_object(object_: object):
"""Find all members of Python object.
Example:
def say_hi(name: str) -> str:
print(f"hi {name}")
print(inspect_object(say_hi))
>>> say_hi=>
type=<class 'function'>
parameters=>
name=>
annotation=<class 'str'>
default=None
kind=POSITIONAL_OR_KEYWORD
... | 06dc3558861dd2488e7e88c379a9c6d103812b3b | 40,067 |
def recall(prediction, ground_truth, average="macro"):
"""
Return the recall score evaluated between PREDICTION and GROUND_TRUTH
average - (default: "macro") mode of averaging for multi-class prediction
"""
return metrics.recall_score(
prediction,
ground_truth,
... | f526752e1187b4eaef8c44169442faca8e04e6cf | 40,068 |
def tf_lipschitz_constant(M, G, phi, phiT, tol=1e-3, verbose=None):
"""Compute lipschitz constant for FISTA
It uses a power iteration method.
"""
n_times = M.shape[1]
n_points = G.shape[1]
iv = np.ones((n_points, n_times), dtype=np.float)
v = phi(iv)
L = 1e100
for it in range(100):
... | 75c66a3909debc23c06894e2040737be6e2081f0 | 40,069 |
def fourCornersSort(pts):
""" Sort corners: top-left, bot-left, bot-right, top-right """
# Difference and sum of x and y value
# Inspired by http://www.pyimagesearch.com
diff = np.diff(pts, axis=1)
summ = pts.sum(axis=1)
# Top-left point has smallest sum...
# np.argmin() returns INDEX o... | 05fa8b611b4f42853282f0d55d301be74f78e873 | 40,070 |
import abc
import copy
def populate_user_output_from_schema_and_outputs(output_schema, output_names, outputs):
"""Follows the schema to generate an output that is expected by the user"""
def _replace_stub_with_tensor_value(user_output, outputs, output_idx):
# Recursively traverse across user_output a... | 600d72ae8d886b35cc62bb1250163fb82f309727 | 40,071 |
def get_current_mapset():
"""Return the current mapset
This is the fastest way to receive the current mapset.
The current mapset is set by init() and stored in a global variable.
This function provides access to this global variable.
"""
global current_mapset
return current_mapset | 90c183d91cdf8c8db2a56c49a3e0d843087a9436 | 40,072 |
def compress_image_to_file(path, terms, annotate, iterations=None, path_out=None):
"""
Compresses the image from `path` using singular value expansion.
The image is saved to an output file which name is chosen automatically,
unless `path_out` is specified.
Parameters
----------
path : path
... | 20385189911c25ebe0c4ede335091542fd7fb7a4 | 40,073 |
from typing import Counter
def merge_vocabs(vocabs, vocab_size=None):
"""
Merge individual vocabularies (assumed to be generated from disjoint
documents) into a larger vocabulary.
Args:
vocabs: `torchtext.vocab.Vocab` vocabularies to be merged
vocab_size: `int` the final vocabulary si... | f7237ad4342acabf444c9facf6dc4eb841140082 | 40,074 |
import torch
def nan_mode(input):
"""Mode value for tensor (ignoring NaNs)."""
return torch.mode(input[~torch.isnan(input)])[0] | cf2ef4fb23a0dfbc251dd385a38ed8e01142ac08 | 40,075 |
import pandas
from re import T
import numpy
def event_values_block(
da: xarray.DataArray,
events: pandas.DataFrame,
offset: T.Union[T.Iterable[int], T.Dict[T.Hashable, int]],
load: bool = True,
):
"""
Gets the values from da where an event is active
"""
if load:
da = da.load()... | 419b10f9ef9384cf60a4277e6fdaa518cd43d2f7 | 40,076 |
def get_signing_pubkey(client, secret_url):
"""
Gets a PEM file from the vault, and returns one of RSAPublicKey, DSAPublicKey, or
EllipticCurvePublicKey depending on the contents of the secret.
"""
try:
raw_pubkey = client.get_secret(secret_url).value
return load_ssh_public_key(
... | 3b23e7c3d95b07a1460fd1e136ce42e5782b0990 | 40,077 |
from datetime import datetime
import copy
import os
def generate_timestep_workflow(args):
"""
Generate a workload that models a multiple
"time-stepping" writers and multiple readers
:param args:
:return: time_schedule
"""
# -------- start creating the time_schedule ------------
creati... | 06edaff1c6ca421655f794a8f41563479d4ac0b1 | 40,078 |
def validate_dandiset_yaml(filepath):
"""Validate dandiset.yaml"""
with open(filepath) as f:
meta = yaml_load(f, typ="safe")
return _check_required_fields(meta, _required_dandiset_metadata_fields) | 86d199a89b72c8df361af7be163ee7ca57cb9600 | 40,079 |
def get_grads(spike_stats, targets_frs, update_rule=0.0005):
"""Calculate gradients for updating the synaptic weights"""
mean_frs = spike_stats['firing_rate']['mean']
fr_diffs = {pop_name: (trg_fr - mean_frs.loc[pop_name]) for pop_name, trg_fr in targets_frs.items()}
mse = np.sum(np.power(list(fr_diffs.... | 6fd845f811bee0abc0f512bd9e8d5a0b91064f1a | 40,080 |
def _im_to_blocks(im, width, roi=None, roi_method="all"):
"""
Converts image to list of square subimages called "blocks."
Parameters
----------
im: array_like
Image to convert to a list of blocks.
width: int
Width of square blocks in units of pixels.
roi: array_like, dtype b... | 029751c9b2c0052e9718f44c231066dc37b569d6 | 40,081 |
from typing import Dict
import re
import string
def preprocess(docs: Dict[str,str], **kwargs):
"""
Takes as input a dictionary of the documents for clustering and transforms them into the compact data structures of corpus and Vocabulary in preperation for clustering.
This process turns each document from... | 7e2adfeed7f7738763829bfed8784f7f993933c0 | 40,082 |
def activation(func_a):
"""Activation function wrapper
"""
return eval(func_a) | ad7f668aec546de452ef4968b22c338c2ca873b6 | 40,083 |
def gravity(z, g0, r0):
"""Relates Earth gravity field magnitude with the geometric height.
Parameters
----------
z: float
Geometric height.
g0: float
Gravity value at sea level.
r0: float
Planet/Natural satellite radius.
Returns
-------
g: float
Gra... | 28b0fdacbadf63755870024acec99b4a38057e24 | 40,084 |
def tfunc(t, rdd):
"""
Transforming function. Converts our blank RDD to something usable
:param t: datetime
:param rdd: rdd
Current rdd we're mapping to
"""
return rdd.flatMap(lambda x: stream_twitter_data()) | d60a9731e3134e04c38f855aedb202ec895a15e1 | 40,085 |
def quote_columns_data(data: str) -> str:
"""When projecting Queries using dot notation (f.e. inventory [ facts.osfamily ])
we need to quote the dot in such column name for the DataTables library or it will
interpret the dot a way to get into a nested results object.
See https://datatables.net/referenc... | db5e82e5d3641bebcac069ac4d5a7bb42baafcbb | 40,086 |
def svn_client_checkout2(*args):
"""svn_client_checkout2(char const * URL, char const * path, svn_opt_revision_t peg_revision, svn_opt_revision_t revision, svn_boolean_t recurse, svn_boolean_t ignore_externals, svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t"""
return _client.svn_client_checkout2(*args) | f0891b04e0eac9675e6912f105e8499ede218ef9 | 40,087 |
def sort_kv_pairs_by_value(d):
"""Turn a dict into a list of key-value pairs, sorted by value."""
return [
(k, v) for v, k in sorted([(v, k) for k, v in d.items()], reverse=True)
] | 58f3e40c4993a64f71212157fdd73ad82712fa44 | 40,088 |
import csv
def parsaCollettivi(file_collettivi):
""" Dato il csv genera lista di collettivi """
collettivi = []
with open(file_collettivi, 'r') as aulefile:
parsedCollettivi = csv.reader(aulefile, delimiter=';')
for row in parsedCollettivi:
flags = []
turni = []
... | 88c0e972232baae19862df3c3a6bc9324d94a501 | 40,089 |
def rk4(derivs, y0, t, *args, **kwargs):
"""
Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.
This is a toy implementation which may be useful if you find
yourself stranded on a system w/o scipy. Otherwise use
:func:`scipy.integrate`.
Args:
derivs: the derivative of the sys... | 3db3e7131525ff7b9decb554c99b67f9dc8a40dc | 40,090 |
def hexEncode(value):
"""Some replaces."""
if isinstance(value, unicode):
value = value.encode('ascii', 'backslashreplace')
return value | 06b4a4d1e6c8b3fff74fa6b2c0240b428f54eef6 | 40,091 |
import logging
def get_logger(name=None, level=None, stream=DEFAULT_STREAM,
clobber_root_handler=True, logger_factory=None,
wrapper_class=None):
"""Configure and return a logger with structlog and stdlib."""
_configure_logger(
logger_factory=logger_factory,
wrappe... | 4ed97ccb18096ae67dc37d957f6607a6de9ee3fc | 40,092 |
def log_likelihood(model,data) :
"""Return log10 (normalized) likelihood: P(3D astrometry | 3D phase space, Covariance)"""
functions = []
for s in data :
functions.append(imageLikelyhood(s))
images = getImages(model)
if(len(images)==len(functions)): # probably a very bad idea
re... | 5b74b3e6e503cb6f4a29a4db6a5574dd883bf806 | 40,093 |
import os
def newcd(path):
"""DEPRICATE"""
cwd = os.getcwd()
os.chdir(path)
return cwd | 5def36e28a4125fafcfdab697be842841ed767b1 | 40,094 |
def yices_division(t1, t2):
"""Returns the term (t1 / t2) from the given terms, or NULL_TERM if there's an error.
division(t1, t2):
t1 and t2 must be arithmetic terms
NOTE: Until Yices 2.5.0, t2 was required to be a non-zero constant.
This is no longer the case: t2 can be any arithmetic term.
... | 32daac08ea6b9004e68505a8db1843dd18027949 | 40,095 |
import string
def is_string_formatted(s, return_parsed_list=False):
""" check if a string has formatted characters (with curly braces) """
l = list(string.Formatter().parse(s))
if len(l) == 1 and l[0][0] == s:
is_formatted = False
else:
is_formatted = True
if return_parsed_list:
... | a47a698d1c53bbf4bfb88ec7aca9e1ed3b0958d5 | 40,096 |
def extract_number(img):
"""Get the image number only"""
img=img.split('.fits')
nimg=int(img[0][-4:])
return nimg | 693648b7ea11fe311da1c30485e69ed0a6aea774 | 40,097 |
def cv_score_table(res_sprm_cv):
"""
Internal function reorganizing sklearn GridSearchCV results to pandas table.
The function adds the cv score table to the object as cv_score_table_
"""
n_settings = len(res_sprm_cv.cv_results_['params'])
etas = [res_sprm_cv.cv_results_['para... | 8d139a8cfb5c2bfd625409fa319d3ff189f3afec | 40,098 |
def calc_aridity(prec, pet, water_year):
"""Calculates the aridity as described in Knoben et al (2018)"""
prec = prepare_data(prec, water_year=water_year)
pet = prepare_data(pet, water_year=water_year)
prec_pet = pd.concat([prec[0],pet.iloc[:,0:2]],axis=1)
prec_pet.columns = ["prec", "pet", "water_... | 661c5b76941abf14e2befa834d9e7d2fce8eb908 | 40,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.