content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_rule_name(name, rule):
"""
Produce a gcp compatible rule name
"""
rule_name = '{name}-from-{rule[sources]}-to-{rule[allowed]}'.format(
name=name,
rule=rule)
return utils.get_gcp_resource_name(rule_name) | 417b277888e5c7b231d979d505bfbe4b1cf921d5 | 59,000 |
def get_Flesch_Kincaid(spacy_papers):
"""
gets Flesch-Kincaid readability score for dictionary of spacy papers
FKRA = (0.39 x ASL) + (11.8 x ASW) - 15.59
"""
sent_lengths = {}
syllables = {}
readability = {}
asl = {}
asw = {}
readability = {}
for k in spacy_papers.keys():
... | 19c68520c19a032a7810ec907fcb2fd2cac3677d | 59,001 |
def get_stock_min_data(code=None, date=None, ktype=1, retry_count=100000, pause=0.1):
"""
获取分钟数据
Parameters
------
code:string
股票代码 e.g. 600048
date:string
日期 format:YYYY-MM-DD
retry_count : int, 默认 10000
如遇网络等问题重复执行的次数
... | b00c259a8f78485fea8cb6b7ac7c51f5317413ba | 59,002 |
def type_from_name(name):
"""Return the GType for a name."""
return gobject_lib.g_type_from_name(_to_bytes(name)) | 8d1f46fb2032cb56087cce3920277cda0f29b134 | 59,003 |
import logging
def las_to_height(in_file: str, out_histogram_file: str = None) -> tuple:
"""Return a tuple of (height histogram, max height) from an LAS file.
Arguments:
in_file: the source LAS file
out_histogram_file: optional output file for the histogram data
Return:
A tuple of ... | 5f7cf322a2ba433098abd2c89e79c75254c86a12 | 59,004 |
def is_causal_sink(graph: BELGraph, node: BaseEntity) -> bool:
"""Check if the node has causal in-edges but no causal out-edges.
:param graph: A BEL graph
:param node: A BEL term
"""
return has_causal_in_edges(graph, node) and no_causal_out_edges(graph, node) | 2369f2e7b9e48422975fe50c313fb3f19c8332df | 59,005 |
import torch
def get_dataset_loader(
data,
word_dict,
classes,
device,
max_seq_length=500,
batch_size=1,
shuffle=False,
data_workers=4
):
"""Create a pytorch DataLoader.
Args:
data (list): List of training instances with index, label, and tokenized text.
word_d... | 90a8e5d44a710ef6dbbf23bcb619c3dbb6154175 | 59,006 |
def page():
""" Return HTML page
- return: HTML
- rtype: String
"""
return '<html><body><img src="stream.mjpg" width=' \
+ WIDTH + ' height=' + HEIGHT + '></body></html>' | c067666a7340cde2816038d48e52086d57c39e2c | 59,007 |
def _deriv_arctanh(x):
"""The derivative of arctanh(x)"""
return 1.0 / (1.0 - x*x) | 6c19a1b2a7d1d432a77806552adc0e26c54360ed | 59,008 |
def _save_sprite(data, output_sprite, vmax, vmin, mask=None, cmap='Greys',
format='png'):
""" Generate a sprite from a 3D Niimg-like object.
Returns: sprite
"""
# Create sprite
sprite = _data_to_sprite(data)
# Mask the sprite
if mask is not None:
mask = _data_t... | bf153a8bcd265d7c9c8c7bb3e422a259a527ecf3 | 59,009 |
def valid_geography(dataframe):
"""This checks validity of geography columns, this works
only for datasets in which there is no other repeating entity.
so this will work only for for data like GDP and DemoGraphics
"""
geocols = get_geographic_columns_from_dataframe(dataframe)
timecols = get_time... | a228613e590dbd787cfc3b1115f171bcd3a618a6 | 59,010 |
def get_config(
variant,
expl_env,
eval_env,
obs_dim,
action_dim,
replay_buffer,
):
"""
Setup of soft actor critic (SAC), used as the policy optimization procedure of MBPO
"""
M = variant['policy_kwargs']['layer_size']
qf1, qf2, target_qf1, target_q... | aabe0d8460be52a7848f78dd71efa51b009bbd81 | 59,011 |
from typing import Tuple
from typing import Optional
import re
def parse_command(bot: NoneBot,
cmd_string: str) -> Tuple[Optional[Command], Optional[str]]:
"""
Parse a command string (typically from a message).
:param bot: NoneBot instance
:param cmd_string: command string
:retu... | 367b2f2b6d57bc0740c086dfca884de254e0bef6 | 59,012 |
def random_data(npoints, dtype):
"""
Generate `npoint` random points with coordinate values in the range [0, 1).
Points are both targets and sources.
Parameters:
-----------
npoints : int
Returns :
tuple(
np.array(shape=(npoints, 3), dtype=float),
np.array... | 0336e1ad9567312d3fbea0a55da8efd7c6493981 | 59,013 |
import torch
def gen_gaussian_target(heatmap, center, radius, k=1):
"""Generate 2D gaussian heatmap.
Args:
heatmap (Tensor): Input heatmap, the gaussian kernel will cover on
it and maintain the max value.
center (list[int]): Coord of gaussian kernel's center.
radius (int):... | 62441a3029f5d96f6a91f70f10f0cbd785f42976 | 59,014 |
def information_file_path(prefix, bath, pot):
""" gradient information file path
"""
return INFORMATION_FILE.path([prefix, bath, pot]) | 307bcfa4d35ffa5184b11d4caab0a8119f82c169 | 59,015 |
import requests
import json
def get_device_response(ctx):
"""Return the deserialized JSON response for /stat/device (devices)"""
r = requests.get(
ctx.obj["URL"] + "stat/device",
verify=ctx.obj["VERIFY"],
cookies=ctx.obj["COOKIES"],
)
return json.loads(r.text) | a763e3a5aedb0b2124244424f44fe7aa56bb8963 | 59,016 |
def build_ictv(cp, instruction):
"""
Build the integer representation of the input channel tag values.
:param cp: CoreParameters instance for the target architecture
:param instruction: Instruction instance
:return: integer representation of the ictv
"""
# Check sizing.
if len(instruct... | 767fa3393e567042ae13b1a613ad7dbcfd27667b | 59,017 |
def get_paths():
"""
Show the path selection window and store the selected paths in variables
:return: a tuple containing strings of data file location and target folder location
"""
root = Tk()
tk_file_loc = StringVar()
tk_target_dir = StringVar()
screen_width = root.winfo_screenwidth... | 8204d52c06d83cc58899a16424186963a240b7e2 | 59,018 |
def parse_userlogin(user, privilege):
"""Parses XCCDF logged in user and elevation"""
return {'user': user, 'privileged': parse_boolean(privilege)} | 8a7b1e6628d5401552cc43c54d7d3127db8ff84a | 59,019 |
def get_file_handlers(input_file):
""" based on extension return tools for looping over annots """
# set up parsing by file type
file_type = input_file[-3:]
if file_type.startswith("f"):
iterator = fna_hit_iterator
record_parser = fna_rec_parser
formatter = lambda g: g.format("fa... | 4634d47f0543207452653720cb9036eb79d7f768 | 59,020 |
def unique_mers(sequencelist, sizeofmer):
""" WEV
This will create a list of all of the unique Nmers of the object
The goal is to have this be flexible enough to take a list or string
"""
output = []
if isinstance(sequencelist, list) or isinstance(sequencelist, set):
for sequence in sequ... | e5e24a968dfe65480bebc2ebeaef39a3510fc4bb | 59,021 |
def calculate_rna_fourier_coefficients(save=False):
"""
Calculates Fourier coefficients of the RNA fitness function. This will try to load them
from the results folder, but will otherwise calculate from scratch. If save=True,
then coefficients will be saved to the results folder.
"""
try:
... | 6f74afec60d3a029ea3745c5ab49c79486e23e8a | 59,022 |
def test_notch(weights,width=0.05):
""" Test for a dropout of gamma-ray emission with a notch shape."""
p0 = lcprimitives.LCTopHat(p=[1-width,0])
lct = lctemplate.LCTemplate([p0],[1])
grid,vals = fill_grid(lct,weights)
return grid,vals | 3df7d28a291e25c0262e115d84e99a9bb3d256b6 | 59,023 |
def api_generate_next_task():
""" Generate next task to label
"""
# try to find task is not presented in completions
project = project_get_or_create()
completions = project.get_completions_ids()
for task_id, task in project.iter_tasks():
if task_id not in completions:
log.inf... | a4244351a46b481965e83ea82d60e96942cc3570 | 59,024 |
def parse_context_var(context, variable_name):
"""解析上下文中的变量
如果以'$'字符开头,那么返回上下文中的对应变量
其它的情况会直接返回字符串
开头两个$$连续为转义,比如'$$aa$$a'为'$aa$$a'
:param context 上下文
:param variable_name
"""
if not isinstance(variable_name, str):
return variable_name
elif variable_name.starts... | d9dbe2a8341179cc5157396a74125b488c0ff053 | 59,025 |
def locate(path, forceload=False):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in path.split('.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport('.'.join(parts[:n + 1]), forceload)
if nextmodule:
mo... | c32bd5061330710fb32244d7349d9fe46153d9bf | 59,026 |
import logging
import sys
def migrate(config):
"""
Ensure all tables exist for the BioIndex to function. Returns
the SQLAlchemy Engine object connected to the database.
"""
rds_config = config.rds_config
name = rds_config['name']
# indicate what's being connected to and try
logging.in... | e5fa8b9497504f0f4ba815cdaccf20c25e40ac6f | 59,027 |
def csv_format(csv_data, c_headers=None, r_headers=None, rows=None, **kwargs):
"""
Format csv rows parsed to Dict or Array
"""
result = None
c_headers = [] if c_headers is None else c_headers
r_headers = [] if r_headers is None else r_headers
rows = [] if rows is None else rows
result_f... | 4b519f6224053aa69ad2033942b9a7357e521a83 | 59,028 |
def create_optimizer(acktr, model, learning_rate):
"""Creates an optimizer based on whether `ACKTR` or `A2C` is used. `A2C` uses the RMSProp optimizer, `ACKTR` uses
the K-FAC optimizer. This function is not restricted to Atari models and can be used generally.
Args:
acktr (:obj:`bool`):
... | 58f17412165559eb2308a6e7ba6cf62534d1e702 | 59,029 |
import ipaddress
def _ipversion(_network):
"""
Return the address version
"""
try:
network = ipaddress.ip_network(u'{}'.format(_network))
except ValueError as err:
log.error("Invalid network {}".format(err))
return 'ipv4'
if network.version == 6:
return 'ipv6'
... | 9066696d451fbde7f2febb0e0990525befc74f75 | 59,030 |
def make_map(config):
"""Create, configure and return the routes Mapper"""
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
map.minimization = False
# The ErrorController route (handles 404/500 error pages); it should
# likely stay at the t... | c8d9ad48411e3b539820a8cc705593df2868a09e | 59,031 |
import datasets
def load_data():
"""
读取scikit-learn自带数据:手写数字
"""
digits = datasets.load_digits()
X = digits.data
y = digits.target
return X, y | 61fdcd54c3d61a4316e80709611dd0ed0f1fb9f8 | 59,032 |
def computespectrum_pvtch(uvw,
p,
xy,
xy_sf,
shkl,
eta_mixing,
tth,
dsp,
hkl,
strain_direction_dot_product,
is_in_sublattice,
tth_lis... | 6b0e7db903b0f98733cd80f686ff56f9521861bb | 59,033 |
import functools
def measure_time_cm(logger=None, disabled=False):
"""
Get a context manager for measuring execution time of code blocks and logging the result.
Measure duration and log output:::
measure_time = measure_time_cm()
with measure_time("heavy computation"):
do_heav... | 80b4606fe4c913d9f3b5b666a0455fec03a90860 | 59,034 |
def change_seating(old_map, tolerance):
""" Seat people based on given rule """
new_map = list()
for row, _ in enumerate(old_map):
line = list()
for col, _ in enumerate(old_map[0]):
adjacents = (
check_adjacents(row, col, old_map)
if tolerance == ... | 8dd203653b35899368700e5f87e2c6a535d1126a | 59,035 |
def stresses_for_word(find):
"""Get a list of possible stress patterns for a given word.
.. doctest::
>>> import pronouncing
>>> pronouncing.stresses_for_word('permit')
['01', '12']
:param find: a word to find
:returns: a list of possible stress patterns for the given word.
... | 62c8fd54d7883fd53bfcb056c83df1adb3e2f7fa | 59,036 |
def logo_round(v, *args):
"""
ROUND num
outputs the nearest integer to the input.
"""
return round(v, *args) | fcbf49a40ee95fcbf4c9af62f6b52aed5bfac0a6 | 59,037 |
from typing import List
def get_axis_types(rai: "RandomAccessibleInterval") -> List["AxisType"]:
"""
imagej.dims.get_axis_types(image) is deprecated. Use this code instead:
axis_types = [axis.type() for axis in image.dim_axes]
"""
_logger.warning(
"imagej.dims.get_axis_types(image) is... | 65f114726f0ee364e9feebfb7c94cdaee18f7617 | 59,038 |
import pickle
def get_palette(palette_file):
"""
load color palette
:param palette_file:
:return:
"""
with open(palette_file, 'rb') as fr:
color_palette = pickle.load(fr)
return color_palette | 29d8a661eed7f50d67e108a07017fc93019bfa3c | 59,039 |
def grr_stat_impl(path: Text, path_type: Text = OS) -> pd.DataFrame:
"""Stats the file specified.
Accepts glob expressions as a file path.
Args:
path: File path to stat.
path_type: Path type to use (one of os, tsk, ntfs, registry).
Returns:
A sequence of stat entries.
Raises:
NoClientSelec... | 5027b042508e7c9d4d06762adce8d4a04c57ef8c | 59,040 |
def get_primes_below(n):
""" Returns a list of primes < n """
sieve = [True] * n
q = int(n**0.5)+1
for i in xrange(3, q, 2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1)
result = [2] + [i for i in xrange(3,n,2) if sieve[i]]
return result | aabd4db41833daa989a2526bc3d9b6622edfc193 | 59,041 |
import html
def scrape_page(url):
"""
Scrapes a web page given a url and returns an HTML tree representation.
This will check for a cachced version of the page before scraping and will attempt to cache
after scraping
:param url: A string of the url of the requested web page
:return: html tree ... | 01946ccfd56219029bd3bd58ebbffdabca2ee7fd | 59,042 |
def actvn(x):
"""
utility helper for leaky Relu activation
:param x: input tensor
:return: activation applied tensor
"""
out = F.leaky_relu(x, 2e-1)
return out | 950e37c58a3220d5023b241457eec23f1f805061 | 59,043 |
import os
def GetOutDirectory(build_type=None):
"""Returns the out directory where the output binaries are built.
Args:
build_type: Build type, generally 'Debug' or 'Release'. Defaults to the
globally set build type environment variable BUILDTYPE.
"""
return os.path.abspath(os.path.join(
DIR_... | 25b611a2ebd43508cce30e616ba05f5ce71a7d78 | 59,044 |
def is_name_dict_tuple(transform):
"""Check the transform is somehow like
('normalize_adj', dict(rate=1.0))
"""
return len(transform) == 2 and isinstance(transform[0], str) and isinstance(transform[1], dict) | 4b4803b8263e65d1461a4b4870b12fdcc9e0ee55 | 59,045 |
def get_lookup_dict():
""" Create a dictionary for records already indexed. This is used during
crawling to see if a record for a given identifier (e.g. the label +
value for a metadata entry) already exists, and if so, provide the DB
ID it was given to create new associations (e.g. with Can... | 651c288569d0816219a1db627f80f6a6f7916397 | 59,046 |
import logging
import json
def authenticate(msg, extra_info):
"""Sends a 401 response that enables basic auth"""
logging.info('User parameters: %s', json.dumps(extra_info))
return Response(json.dumps({'status': 'ERROR', 'message': msg}), 401,
mimetype="application/json") | 4386258fcc379fadff86ce4253652a8f00d8c191 | 59,047 |
import subprocess
import inspect
def _profile_prefix(profile, prefix='gcreds'):
"""
Summary:
Determines if temporary STS credentials provided via
local awscli config;
- if yes, returns profile with correct prefix
- if no, returns profile (profile_name) unaltered
- Note:... | b1ddaf182c45d6a3d3357959a6d6b18e12ccc96d | 59,048 |
def float_to_string(value):
"""
"""
if value < 1:
if (value - int(value)) < 0.001:
return str(0)
return decimal_to_string(value)
if value == 1:
return str(1)
else:
if (value - int(value)) < 0.001:
return str(int(value))
return "{} {... | d63f8451ef73bd579774f80d4eca157d85067ff9 | 59,049 |
def get_cross_covariance(maml, x_spt, x_qry, y_spt, y_qry):
"""
The feature (\phi(s) or \phi(q)) of data is obtained
through maml.net.forward_nolinear which returns
the embedded data (i.e., the data before the linear layer).
"""
# Obtain the features
for i_batch in range(1):
... | 736b9aca2ee5da998f323c1e5d891b4ebad8cc72 | 59,050 |
def _get_ratelimit_sleep():
"""
Return the configured time to wait before retrying after a ratelimit has been enforced.
"""
return config.get_cloud_config_value(
"ratelimit_sleep",
get_configured_provider(),
__opts__,
search_global=False,
default=0,
) | 1701372a8d925e84034c2814d7e29084a1495b60 | 59,051 |
import math
def calculate_ransac_iterations(min_points_per_sample, outlier_rate, desired_success_probability):
"""Estimates how many RANSAC iterations you should run.
Args:
min_points_per_sample: Minimum number of points to build a model hypothesis.
outlier_rate: Float, 0-1, how often outlier... | cafca93f052770f695f90d5f37e088e880fd0c45 | 59,052 |
import pymbar
import io
import torch
def _bennett_acceptance_ratio_pymbar(forward_work, reverse_work, compute_uncertainty=True, maximum_iterations=500, relative_tolerance=1e-12):
"""pymbar reference implementation"""
ctx = {"device": forward_work.device, "dtype": forward_work.dtype}
f = io.StringIO()
... | 2d6d8d8206e4fad629c15ef9d5eb6e2861303f86 | 59,053 |
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Set
def collectScratchSlots(
subroutineBlocks: Dict[Optional[SubroutineDefinition], TealBlock]
) -> Tuple[Set[ScratchSlot], Dict[Optional[SubroutineDefinition], Set[ScratchSlot]]]:
"""Find and return all referenced... | 46b1a94765dbbcc1bd3da2a9ae4f7f2fd210755d | 59,054 |
from typing import Any
from typing import Callable
def simple_filter(desired_value: Any) -> Callable[[Any], bool]:
"""A simple filter function factory, compares using ==
:param desired_value: value to be compared against.
:returns: The filter function
"""
logger.debug("Creating simple filter for ... | b0d8825e3f5cd0f2490fb6d6ff84d045c5b2798c | 59,055 |
def binning_gradient(binning, amp, phsp, m_phsp, var):
"""
calculate bin error for fit
including error propagation (gradients) and weights
"""
nfit = []
for i in range(binning.shape[0] - 1):
m_min = binning[i]
m_max = binning[i + 1]
phsp_i = data_mask(phsp, (m_phsp > m_mi... | 6864c475c3fbd4fedd89cf2c6b5d08f3f712ab22 | 59,056 |
def hi():
"""Tests for connection, says hi."""
return send_this('hi') | ab222b7fc72c0a088147d3543772748768652d69 | 59,057 |
def rand_population_uniform(m, a, b):
"""
Creates a starting population of size `m` using a uniform random
distribution, where `a` is the lower bound, and `b` is the upper bound
for the design variables.
"""
a = np.array(a)
b = np.array(b)
d = len(a)
return [list(np.multiply(a + np.r... | 576c2d77591356615347f3b119660b673e0f5453 | 59,058 |
from typing import Union
from typing import Tuple
def prepare_data(
data: np.ndarray,
lookback_steps: int,
num_inputs: int = None,
num_outputs: int = None,
input_steps: int = 1,
forecast_step: int = 0,
forecast_len: int = 1,
known_future_inputs: bool = F... | 390f045a0bd9c423d261277028cfa2228abe00fe | 59,059 |
import random
import os
def write_host_file(hostlist, path='/tmp', slots=1):
"""Write out a hostfile suitable for orterun.
Args:
hostlist (list): list of hosts to write to the hostfile
path (str, optional): where to write the hostfile. Defaults to '/tmp'.
slots (int, optional): slots ... | 44c9c62922c2ea195f37e8cb3117593ef62583a6 | 59,060 |
def najnowsze(request):
"""
List the newest offers
"""
oferty = OfertyEst.objects.filter(status=0).select_related()
oferty = oferty.order_by('-data', '-id')[:10]
paginator = Paginator(oferty, 10)
page = request.GET.get('page')
try:
oferty = paginator.page(page)
except Page... | b3f4b671344a423f27e0d7b32808993495756558 | 59,061 |
import base64
import zlib
def decompress_data(content_data):
"""
Handles the actual decompression of Base64 data.
Args:
content_data: String of Base64 content
Returns:
content_data: Decompressed content of ASCII printable
"""
decoded = base64.b64decode(content_data)
# IO... | fd93747ec3bf7759e385eba7397c6b9ad22ccd7f | 59,062 |
def get_module_class(module_name, hetero=False):
"""Retrieve the module classes from the module name."""
# List all the modules and their string name in this dictionary
module_dict = {
'pointnet': [PointNet, PointNetHetero], # pointnet
'mlpdecoder': [MlpDecoder, MlpDecoderHetero], # mlpdeco... | 4a0c593086de6325aee8042d292dd8b862ce6875 | 59,063 |
import os
import tempfile
import logging
import shlex
import shutil
import subprocess
import glob
def run_exe(ds, exe=None):
"""Run external program and return a dictionary of output files."""
if exe == 'minvar':
files_to_save = minvar_2_save
elif exe == 'runControl':
files_to_save = runCo... | 7bbb93ae9dc665df7c4cfdf4621a3884107f7e9e | 59,064 |
def generate_election_partial_key_challenge(
backup: ElectionPartialKeyBackup, polynomial: ElectionPolynomial,
) -> ElectionPartialKeyChallenge:
"""
Generate challenge to a previous verification of a partial key backup
:param backup: Election partial key backup in question
:param poynomial: Polynomi... | 4069ccb1ed90b39804a5c5fa78563f8d8b44681e | 59,065 |
from datetime import datetime
import json
def bplist_write_bplist_to_json(bplist_file_path, to_file_path):
"""
Reads a bplist file and writes it to a json file.
Args:
bplist_file_path (str):
to_file_path (str):
"""
def _convert_datetime(o):
if isinstance(o, datetime):
... | e8fd57ea660a5ed0313e7d429736c6e13c362af0 | 59,066 |
import numpy
def stEnergyEntropy(frame, n_short_blocks=10):
"""Computes entropy of energy"""
Eol = numpy.sum(frame ** 2) # total frame energy
L = len(frame)
sub_win_len = int(numpy.floor(L / n_short_blocks))
if L != sub_win_len * n_short_blocks:
frame = frame[0:sub_win_len * n_short... | aad28aef8871246aa8c369fa786b0669e69da546 | 59,067 |
def patch_url(options):
"""Returns a Review Board or a GitHub URL for a patch."""
if options['review_id']:
# Reviewboard REST API expects '/' at the end of the URL.
return '{base}/{review}/diff/raw/'.format(
base=REVIEWBOARD_REVIEW_URL,
review=options['review_id'])
el... | fbd1b37e087738bf1b895ee0dd1e3c51d48b7037 | 59,068 |
from typing import Dict
def db_find(cur, db_query: str, offset_dict: Dict[str, int]) -> str:
"""Build a SQL query and execute that query.
`db_query` is passed to parser.build_q_dict to be tokenised, then
passed to parser.parse_f_dict to build a complete query. The query
is executed and the results ar... | 89c5d7b1116ef7fdf3af8f20ab97e51c4cb27a93 | 59,069 |
def _gaussian_log_cdf(x, mu, sigma):
"""Log CDF of a normal distribution."""
if not isinstance(x, chainer.Variable):
x = chainer.Variable(x)
return _log_ndtr((x - mu) / sigma) | dc82b95cb61c17ae40a565d26279dd3d6c1987cf | 59,070 |
from typing import Dict
import yaml
def load_yaml(filepath: str) -> Dict:
"""
Read content from yaml file.
:param filepath: str path to yaml file.
:return: dict YAML content
"""
with open(filepath, "r") as f:
try:
return yaml.safe_load(f)
except yaml.YAMLError as ... | 37dfcc6fa463174059414fe93efe891389be2f22 | 59,071 |
import csv
import logging
def load_patterns(file_path):
"""
loads the patterns from csv file
"""
patternsDict = {}
try:
with open(file_path, mode='r') as csvfile:
reader = csv.reader(csvfile)
patternsDict = {rows[0]: (rows[1], rows[2]) for rows in reader}
except... | 330472f0507ffc4e9d967ef3027e362e47e0d4d2 | 59,072 |
def calculate_AUC(x, y):
"""
Simple function to calculate AUC of an ROC curve, given
a set of points (x,y)
Parameters
----------
x: list
The x coordinates of the points of the ROC curve.
y: list
The y coordinates of the points of the ROC curve.
Returns
-------
... | ba890f3348c9e5aa7b20e643b6369bdc16d7fe5c | 59,073 |
import sys
def Execute(
filename,
compiler,
test_parser,
test_executor=None,
code_coverage_validator=None,
execute_tests_in_parallel=None,
single_threaded=False,
iterations=1,
debug_on_error=False,
continue_iterations_on_error=False,
compiler_flag=None,
test_parser_flag... | 4ca1b6625b6a83cd586a88242de21786bb95188a | 59,074 |
from typing import List
def get_personnel_list(
personnel_file: str = CONFIG['input_personnel_list_path'],
) -> List[str]:
"""Get Personnel list
Args:
personnel_file (str): Path to '\n' delimited text file containing
list of personnel.
Returns:
int: Number of rows
"""
... | 54259fd73542478eb9808bb8af9023e819cde56b | 59,075 |
import requests
def sf_put(path='', token=None, data=None):
"""
Sends a PUTS to PetSafe SmartFeed API.
Example: sf_put(path='feeders', token=user_token, data=my_data)
:param path: the path on the API
:param token: the account's token
:param data: the PUT data
:return: the request respons... | 9ae31119cd2422314939760c8fda1b6a18ca05d2 | 59,076 |
import argparse
def separator(string):
"""Parse the separator, possibly raising error"""
options = {"tab": "\t", "comma": ","}
s = options.get(string, string)
if len(s) == 1:
return s
else:
raise argparse.ArgumentTypeError("must be a 1-character string") | df4712f01a552911d9d9d8bc70b4b3f31415ec4c | 59,077 |
def read_params_Coulomb(fname='in.params.Coulomb'):
"""
Read in.params.Coulomb. But only for fixed or fixed_bvs charges.
"""
with open(fname,'r') as f:
lines = f.readlines()
mode = None
chgtype = None
chgs = {}
coul = {}
bvs = {}
for line in lines:
if line[0] in ... | a870d1a7b504fdbbc87f09db758bfd11b770be63 | 59,078 |
def createThumbnail(event, context):
"""
Executed by an S3 trigger create file event
"""
# Debug purposed print
#print("event:", event, "context:", context)
try:
bucket = event['Records'][0]['s3']['bucket']['name']
s3ObjectKey = event['Records'][0]['s3']['object']['key']
... | fca2357c5e78dfbb85e7f622cf9e8367f418c788 | 59,079 |
def get_programs_by_type_slug(site, program_type_slug):
"""
Keyword Arguments:
site (Site): The corresponding Site object to fetch programs for.
program_type_slug (string): The type slug that matching programs must have.
Returns:
A list of programs for the given site with the given ... | 7a3b697718f081a1d55c74e70de401829dfd42c6 | 59,080 |
def timeshifted_data_2d(data, shift, padding_value='zero'):
"""
Same as timeshifted_data_1d but with a 2D array as input. In other words, performs shifting of multiple data
vectors (e.g. multiple voxel timeseries).
Inputs
data: 2D numpy array, with shape (n, v), where n is the length of a... | e877933870d19eff3d1f3697a42b6c2e36fd600a | 59,081 |
import os
def make_gui(spim_or_filepath, mode="circle", thresholding="auto"):
"""Creates a :class:`~spotlob.SpotlobNotebookGui` object which opens
a given :class:`~spotlob.Spim` or image file for preview editing
PARAMETERS
----------
spim_or_filepath : Spim or str
Spim (should be cached) ... | 44c561e88e5070f4c435e53c60b294ed99d8c304 | 59,082 |
def dice_from_confusion_matrix(cm: ndarray) -> ndarray:
"""
Computes Dice scores from a confusion matrix
Parameters
----------
cm
N x N Input confusion matrix
Returns
-------
1d ndarray containing Dice scores for all N classes
"""
if cm.ndim != 2 or cm.shape[0] != cm.s... | 6c2b256166fb9eb54d02bbcc013eeafd5e49255f | 59,083 |
from typing import Optional
from pathlib import Path
import requests
import shutil
def download_file(url: str, filename: Optional[str] = None) -> Path:
"""
Save a file in the gobbli download directory if it doesn't already exist there.
Stream the download to avoid running out of memory.
Args:
u... | 6cb3c3468b2922dc516df87b76340573d92129d9 | 59,084 |
def find_attribute_helpers(attr_type, name, custom_formatter):
"""
Tries to format following the OIDs info and format_helper specification.
Search for attribute oid, then attribute name (can be multiple), then attribute syntax
Precedence is:
1. attribute name
2. attribute oid(from schema)
3.... | d98c08bf40275131f24395566a62d1ac5e80e2ca | 59,085 |
def getValidationHandlers(template, cohort_start_year, val_feature_start, val_feature_end, cohort_name, engine):
"""
Queries database for active handlers within the given train/test dates.
:param template: string, SQL template from config file
:param cohort_start_year: starting year for cohort
:para... | ad4b4171d6d4f2bdb25decd0dd8da02a77786f84 | 59,086 |
def integrate_dopri5(dydt, t, y0, *args):
"""
Integrate an ODE system with the Runge-Kutte Dormand Prince
method (with step-size control).
Parameters
----------
dydt : function
A function returning the momenta of the ODE system.
t : numpy.ndarray of float
Array of time point... | b9db428a04bb8d03c294fa2cf9562aeeda265e87 | 59,087 |
import json
def mac_entry_info_get(client, vlan_name, port, peer_mac_addr):
"""based on the input information,found any mac entry is matched.
:returns: True if one entry is matched
"""
status = False
# show ethernet-switching table interface xxx
command = 'exec cli show ethernet-switching tabl... | d8e01b4aa60741c355d80125d87b0a1ae02ee6f6 | 59,088 |
from typing import Optional
from typing import Dict
from typing import Any
def render_packager_template(template_name: str, values: Optional[Dict[str, Any]] = None) -> str:
"""
Helper function to read template from a file and render it
:param template_name: name of a rest packager template
:param val... | ae778e7c82616fd85e0cb1c0b71a27e5d74f11bf | 59,089 |
def read_datafiles():
"""Returns lines from files in current directory.
Exits with error message if it encounters:
* file that has an invalid name
* file that is not UTF8-encoded
* file that has blank lines."""
visiblefiles_list = get_visible_filenames()
all_datalines = []
for datafile ... | 2a30029a453069c53add23c5d3f55799a95e638b | 59,090 |
import os
import time
import pickle
def file_pickle_load(fname, mask_exceptions=None, default=None, expiration=-1, remove_expired=False, last_time={}):
"""Load a serialized dictionary
This implementation does not use file locking, it relies on the atomicity of file movement/replacement and deletion
@para... | 6da3f00c10da89dab575934aac67185b9c89a0ba | 59,091 |
def _calculate_normals(rr, tris):
"""Efficiently compute vertex normals for triangulated surface"""
# ensure highest precision for our summation/vectorization "trick"
rr = rr.astype(np.float64)
# first, compute triangle normals
r1 = rr[tris[:, 0], :]
r2 = rr[tris[:, 1], :]
r3 = rr[tris[:, 2]... | 30b06bf23cf3322f59d4feb1dad56fb23e544ada | 59,092 |
def _GetMaxDup(data):
"""Find the maximum i inside ABCD{i}.
data should be a [[[Key]]], where Key is a string that may look like
ABCD{i}.
"""
max_dup = 0
for label in data:
for run in label:
for key in run:
match = _DUP_KEY_REGEX.match(key)
if match:
max_dup = max(max_du... | c865d1ebb862da5be799154d67f06a4fd2812c58 | 59,093 |
import sys
def _catch_thread_exception(fn):
"""Sets self._worker_exception when fn raises an exception"""
def wrapped(self, *args, **kwargs):
try:
ret = fn(self, *args, **kwargs)
except Exception:
self._worker_exception = sys.exc_info()
else:
return ... | 9c1f43c1c3237102c60367b6b5dc2967a74faec0 | 59,094 |
def parse_workflows(bactopia_path, include_merlin=False, build_all=False):
"""Parse Bactopia's workflows.conf to get modules per-workflow"""
workflows = {}
available_workflows = []
nf_config, stderr = execute(f'nextflow config -flat {bactopia_path}/main.nf', capture=True)
for line in nf_config.split... | 38eb03793a76431b959fbe76e9cfd217309fc926 | 59,095 |
def price_attractiveness_on_afv():
"""
Real Name: b'Price Attractiveness on AFV'
Original Eqn: b'lagged effect of price on attractiveness on AFV*Reference price Attractiveness on AFV'
Units: b'Dmnl'
Limits: (None, None)
Type: component
b''
"""
return lagged_effect_of_price_on_attrac... | c81be938d55e6e4f2be0c4dea790512e46e551a3 | 59,096 |
from sys import path
def walk_gen(dirpath: str = getcwd(), abspath: bool = True) -> Paths:
"""Yields all paths beneath dirpath param; dirpath defaults to os.getcwd()
:param dirpath: Directory path to walking down/through.
:param abspath: Yield the absolute path
:return: Generator object that yields f... | 8cde2b92dc096d3f1a0740752dcf5db4ffa06169 | 59,097 |
import os
def make_header(args):
"""Make header for watson and crick bam file"""
header = os.path.join(args.output_dir, 'header.sam')
args.header = header
header_handle = open(header, 'w')
header_handle.write('@HD\tVN:1.4\n')
joined_sam = open(os.path.join(args.output_dir, 'joinedAligned.out.s... | 192ea65a94e4d92e4eb4a8b7a08bfd9aec52fa36 | 59,098 |
def write_climate_file(filename, datadir, arrs, time, changes=None):
"""Write climate file
Parameters
----------
filename : str
template file name
datadir : Path
directory to write to
arrs : list of 1D arrays
data to write to columns
time : 1D array of datetime.datet... | b00e7510d5eb7bc6f70fbc9771720c4171dcdf3c | 59,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.