content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def if_analyser(string):
"""调用python的eval函数计算True false"""
trans = sign_transform(string.strip().lower())
# print('if_analyser>>', trans)
boool = eval(trans)
boool = 1 if boool else 0
return boool | a27469a6c23a53f0131e8135600c6dc7d596cdbb | 3,644,245 |
def zzX_trunc(f, p):
"""Reduce Z[X] polynomial modulo polynomial p. """
return zzX_strip([ zzX_rem(g, p) for g in f ]) | 9e80862a229b1a0689dea01fef865997ee87d1f9 | 3,644,246 |
from typing import List
def _format_bin_intervals(bins_arr: np.ndarray) -> List[str]:
"""
Auxillary function to format bin intervals in a histogram
Parameters
----------
bins_arr: np.ndarray
Bin endpoints to format into intervals
Returns
-------
List of formatted bin inte... | 96d3a89fc3427bf33abe5c44a04061694ae7b2b3 | 3,644,247 |
from typing import List
from typing import Dict
from typing import Callable
def get_embedder_functions(corpus: List[str]) -> Dict[str, Callable[[List[str]], List[float]]]:
"""
Returns a list of the available embedders.
#! If updated, update next function too
"""
embedders = {
# 'Bag of Wo... | 6e1d4ddd41725a26b940c7d108ea552366ab6c9b | 3,644,248 |
import logging
def test_stimeit():
""" Test the stimeit function """
dummy_function = lambda x: x + 2
@vtime.stimeit(logging.info)
def stimeit_function(x):
return dummy_function(x)
assert dummy_function(42) == stimeit_function(42) | 6d5cf6d261871cb466b71e93dbecfafff1731727 | 3,644,249 |
import yaml
def parse_thermal_properties(f):
"""thermal_properties.yaml parser."""
thermal_properties = {
"temperatures": [],
"free_energy": [],
"entropy": [],
"heat_capacity": [],
}
data = yaml.load(f, Loader=Loader)
for tp in data["thermal_properties"]:
th... | 4cc0020849e6ec1202fd2138f0bc86e5abfadf3b | 3,644,250 |
def convert(ts, new_freq, include_partial=True, **kwargs):
"""
This function converts a timeseries to another frequency. Conversion only
works from a higher frequency to a lower frequency, for example daily to
monthly.
NOTE: add a gatekeeper for invalid kwargs.
"""
new_ts = ts.clone()
... | a6b8daf6092052c0d7872d4b9a75edbe10bc15e5 | 3,644,251 |
def _get_image_info(name: str) -> versions.Image:
"""Retrieve an `Image` information by name from the versions listing."""
try:
return versions.CONTAINER_IMAGES_MAP[name]
except KeyError:
raise ValueError(
'Missing version for container image "{}"'.format(name)
) | 4a328d6924adc3c826a6a01c46a27e6380d5d89a | 3,644,252 |
def _mother_proc_cpp_stat(
amplitude_distribution, t_stop, rate, t_start=0 * pq.ms):
"""
Generate the hidden ("mother") Poisson process for a Compound Poisson
Process (CPP).
Parameters
----------
amplitude_distribution : np.ndarray
CPP's amplitude distribution :math:`A`. `A[j]`... | 90ea9272c1a5541ea5c278960369ea301b31d01a | 3,644,253 |
import telegram
import urllib
def get_service(hass, config):
"""Get the Telegram notification service."""
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_API_KEY, 'chat_id']},
_LOGGER):
return None
try:
bot = telegram.Bot(toke... | 474efeccaef641ba50042a036d5edf6d6e86f90c | 3,644,254 |
def has_numbers(input_str: str):
""" Check if a string has a number character """
return any(char.isdigit() for char in input_str) | 5038cb737cdcfbad3a7bd6ac89f435559b67cebc | 3,644,255 |
def get_report_permission(report: Report, user: User) -> Permission:
"""Get permission of given user for the report.
:param report: The report
:type report: Report
:param user: The user whose permissions are to be checked
:type user: User
:return: The user's permissions for the report
:rtyp... | bb09d744c133a4c9212ab6c6e2ba345bb9c8f78f | 3,644,257 |
def peak_time_from_sxs(
sxs_format_waveform,
metadata,
extrapolation_order='Extrapolated_N2'):
"""Returns the time when the sum of the squared amplitudes of an
SXS-format waveform is largest. Note: this is not necessarily the time of
the peak of the l=m=2 mode."""
extrap = extrap... | 1ad4b593db3aa3d74170056f2c32d4108ec05a48 | 3,644,258 |
def create_trackhub_resource(project_dir, api_client, create_user_resource, create_genome_assembly_dump_resource):
"""
This fixture is used to create a temporary trackhub using POST API
The created trackhub will be used to test GET API
"""
_, token = create_user_resource
api_client.credentials(H... | a81db1e7c9c95355457d9f6c4ec4c6428e1a77a7 | 3,644,259 |
def create_node(x, y):
"""Create a node along the network.
Parameters
----------
x : {float, int}
The x coordinate of a point.
y : {float, int}
The y coordinate of a point.
Returns
-------
_node : shapely.geoemtry.Point
Instantiated node.
"""
_node = P... | d8645b77a3d843bf3855522c63156916432ae899 | 3,644,260 |
from typing import Match
def get_matchroom_name(match: Match) -> str:
"""Get a new unique channel name corresponding to the match.
Parameters
----------
match: Match
The match whose info determines the name.
Returns
-------
str
The name of the channel.
"""... | 404d21b6f88918204aa287c9227640c03f47b916 | 3,644,261 |
import re
def unidecode_name(uname):
"""
unidecode() of cjk ideograms can produce strings which contain spaces.
Strip leading and trailing spaces, and reduce double-spaces to single.
For some other ranges, unidecode returns all-lowercase names; fix these
up with capitalization.
"""
# Fix ... | 16676453059b53b3e397f33630e00de66f3585b9 | 3,644,262 |
def scnet50(**kwargs):
"""
SCNet-50 model from 'Improving Convolutional Networks with Self-Calibrated Convolutions,'
http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str,... | c900c5a0da1f4f0960ced2ba36fb9785a7340f4a | 3,644,263 |
def xception_block(inputs, depth_list, prefix, skip_connect_type, stride, rate=1,
depth_activation=False, return_skip=False):
"""用于构建xception,同样用到了残差结构,但是将卷积换成了 深度可分离卷积(depthwise + pointwise + conv 1x1)"""
residual = inputs
for i in range(3):
# depthwise + pointwise + conv2d
... | 3a8eaf7cb73216039411ec8fddd7bfb8c81604a6 | 3,644,264 |
def auth_test():
"""
Test's the endpoint authenticiation works.
:return:
"""
return "hello" | 7c65897d83b0af41307aec28d7f2ce3d6852f8b7 | 3,644,265 |
def cnn_2x_lstm_siamese(voc_size, max_len, dropout=0.5):
"""Two siamese branches, each embedding a statement.
Binary classifier on top.
Args:
voc_size: size of the vocabulary for the input statements.
max_len: maximum length for the input statements.
dropout: Fraction of units to drop.
Returns:
... | d0eec28b8e91bed77fbc84bd085cae337da04c61 | 3,644,266 |
def roll_function(positions, I, angular_velocity):
"""
Due to how the simulations are generated where the first point of the simulation
is at the smallest x value and the subsequent positions are in a clockwise
(counterclockwise) direction when the vorticity is positive (negative), the first
point... | 79e9e3fbcdd2bfc1f2f9108f17aeeeb13fc6339d | 3,644,267 |
def top10():
"""Renders the top 10 page."""
top10_urls = ShortURL.query.order_by(ShortURL.hits.desc()).limit(10)
return render_template("top10.html", urls=top10_urls) | 781c7e65b94894e1292e626c163dfecb1d966678 | 3,644,269 |
def rename_group(str_group2=None):
"""
Rename OFF food group (pnns_group_2) to a standard name
Args:
str_group2 (str): OFF food group name
Returns:
conv_group (str): standard food group name
"""
#convert_group1 = {'Beverage':['Beverages'],
# 'Cereals':['Cerea... | 31b52f600fe3a087f8b230c880ae55f0dd63264e | 3,644,270 |
def run_basic():
"""Check that the windows all open ok (i.e. is GUI functioning?)."""
_initialize()
s = 'Simulation'
p = 'Plots'
menu_paths = [ (s,'Test Pattern'),
(s,'Model Editor'),
(p,'Activity'),
(p,'Connection Fields'),
... | e90546b7312b9c7de5fd812784d91c5ef1c9f22f | 3,644,273 |
def node_to_evenly_discretized(node):
"""
Parses the evenly discretized mfd node to an instance of the
:class: openquake.hazardlib.mfd.evenly_discretized.EvenlyDiscretizedMFD,
or to None if not all parameters are available
"""
if not all([node.attrib["minMag"], node.attrib["binWidth"],
... | 168bf8efcacac4eaf5832bbab4b3708e8187d5dd | 3,644,274 |
from typing import Collection
def delete_comment(request, collection_id, comment_id):
"""Delete comment if the staff or comment owner want to delete."""
collection = get_object_or_404(Collection, id=collection_id)
comment = get_object_or_404(Comment, id=comment_id, collection=collection)
if not reques... | e8de0e5b8fb1ca8d6b6f27009f34ef0b8678c7cd | 3,644,275 |
import numpy
def layers_weights_as_vector(model, initial=True):
"""
Creates a list holding the weights of each layer (Conv and Dense) in the CNN as a vector.
model: A reference to the instance from the cnn.Model class.
initial: When True, the function returns the initial weights of the CNN. When Fal... | 3a13d44868cb67c8ba757db3ceed8b6cf01bfbfb | 3,644,276 |
def calculate_moist_adiabatic_lapse_rate(t, p):
"""calculate moist adiabatic lapse rate from pressure, temperature
p: pressure in hPa
t: temperature in Kelvin
returns: moist adiabatic lapse rate in Kelvin/m
"""
es = 611.2*np.exp(17.67*(t-273.15)/(t-29.65)) # Bolton formula, es in Pa
qs... | 4a20b15bdee1ce72f10d85b74a68358fa7934093 | 3,644,277 |
def read_cat_file(genomeCatFile):
""" Read in genome categories and create dictionary of category name and
genomes in that category"""
inFile = open(genomeCatFile, 'r')
catDict = {}
for line in inFile:
line = line.strip()
entries = line.split()
genome = entries[0]
ca... | 23a30f29cb62d56a3e0763be34cad45717421815 | 3,644,278 |
def removeCable(n, edges):
"""
@param n 道路
@param edges 连通情况
"""
fa = initFa(n)
totalW, nodes = 0, []
for x, y, w in edges:
node = Node(x, y, w)
nodes.append(node)
totalW += w
def getW(node):
return node.w
nodes.sort(key=getW)
tmpW = 0
... | 4b43cc0ddd1ea89113a95a6771dea97d2b21a0fb | 3,644,281 |
from read_file import read_selected, narrow
def upload():
"""POST route through which downloading sequence is triggered
:param checked: which pins were selected by user
:returns: log of arrays with pins, files downloaded counts, and notes
"""
DASHRlut = findSNs(compCrawl())
checked = request.... | 99a00d173574b789e8e6681a0373c2b805a42e39 | 3,644,282 |
def verify_credentials():
"""Verify credentials to gdrive for the current user"""
if 'credentials' not in flask.session:
return flask.redirect(flask.url_for('authorize_app', _external=True))
credentials = client.OAuth2Credentials.from_json(
flask.session['credentials'])
if credentials.access_token_exp... | 96ebe13a7e04f245fa432f0dcbfecdb490367ad9 | 3,644,283 |
def _gaussian_blur(heatmaps, kernel=11):
"""Modulate heatmap distribution with Gaussian.
sigma = 0.3*((kernel_size-1)*0.5-1)+0.8
sigma~=3 if k=17
sigma=2 if k=11;
sigma~=1.5 if k=7;
sigma~=1 if k=3;
Note:
batch_size: N
num_keypoints: K
heatmap height: H
... | e49edc97eefc2f0de5200e4c8aee794642cb6a1f | 3,644,284 |
def pose_vec2mat(vec):
"""Converts 6DoF parameters to transformation matrix
Args:
vec: 6DoF parameters in the order of tx, ty, tz, rx, ry, rz -- [B, 6]
Returns:
A transformation matrix -- [B, 4, 4]
"""
# batch_size, _ = vec.get_shape().as_list()
batch_size = tf.shape(vec)[0]
... | 1ecfb0461bc7ec19c1e730e4499510a890474b33 | 3,644,285 |
import collections
def get_gradients_through_compute_gradients(optimizer, loss, activations):
"""Compute gradients to send to TPU embedding.
Args:
optimizer: a subclass of optimizer.Optimizer, usually CrossShardOptimizer.
Used to call compute_gradients().
loss: a Tensor to call optimizer.compute_gr... | 2a2ebca1e6024e11f541e3ccaf1fee4acd7ab745 | 3,644,286 |
def distance_to_mesh(mesh, pts, engine="auto", bvh=None):
""" Compute the distance from a set of points to a mesh.
Args:
mesh (:class:`Mesh`): A input mesh.
pts (:class:`numpy.ndarray`): A :math:`N \\times dim` array of query
points.
engine (``string``): BVH engine name. Val... | c44230d7e9cd18c2d992a85e2fba04a890b55ed8 | 3,644,287 |
from typing import Any
from typing import Tuple
from typing import Dict
def parse_config(settings: Any) -> Tuple[Dict[str, Queue], Dict[str, dict]]:
"""
SAQ configuration parsing.
Args:
settings: The settings (can be pydantic.BaseSettings).
Returns:
Tuple[Dict[str, Queue], Dict[str, ... | d2711efedff319fb181d062593338f32271f39d1 | 3,644,288 |
def create_zeros_slot(primary, name, dtype=None, colocate_with_primary=True):
"""Create a slot initialized to 0 with same shape as the primary object.
Args:
primary: The primary `Variable` or `Output`.
name: Name to use for the slot variable.
dtype: Type of the slot variable. Defaults to the type of `... | ac940b8d92e4de025a2fc83695adb66a611935ea | 3,644,289 |
def AdditionalMedicareTax(e00200, MARS,
AMEDT_ec, sey, AMEDT_rt,
FICA_mc_trt, FICA_ss_trt,
ptax_amc, payrolltax):
"""
Computes Additional Medicare Tax (Form 8959) included in payroll taxes.
Notes
-----
Tax Law Parameters:... | de0e35fbe5c7c09de384e1302cba082149ea5930 | 3,644,290 |
import copy
def append_step_list(step_list, step, value, go_next, mode, tag):
"""from step_list, append the number of times a step needs to be repeated
if runmode or retry is present
:Arguments:
step_list = Ordered list of steps to be executed
step = Current step
value = attempts... | b8b5b3614fea0709b484df087ffa3ee2861532c4 | 3,644,291 |
def load_license(request, project_slug):
"""
Reload the license input queryset with the right options for the
access form's current access policy choice. Called via ajax.
"""
user = request.user
project = ActiveProject.objects.filter(slug=project_slug)
if project:
project = project.g... | 59fb710cfccfaaf642283e6fb26631f56a39cc1e | 3,644,292 |
def wt():
"""Return default word tokenizer."""
return WordTokenizer() | d9e9a9c3cb99f1c3846ee54b38184d39d67051a7 | 3,644,293 |
import warnings
def epochplot(epochs, *, ax=None, height=None, fc='0.5', ec='0.5',
alpha=0.5, hatch='////', label=None, hc=None,**kwargs):
"""Docstring goes here.
"""
if ax is None:
ax = plt.gca()
ymin, ymax = ax.get_ylim()
if height is None:
height = ymax - y... | 2e4f993ac48e6f054cd8781f4356b7afed41b369 | 3,644,294 |
def run_dag(
dag_id,
run_id=None,
conf=None,
replace_microseconds=True,
execution_date=None,
):
"""Runs DAG specified by dag_id
:param dag_id: DAG ID
:param run_id: ID of the dag_run
:param conf: configuration
:param replace_microseconds: whether microseconds should be zeroed
... | 124954d350a09d576b32e80fae4c56d1c0b2c141 | 3,644,295 |
def get_function_handle(method, var):
"""
Return a function handle to a given calculation method.
Parameters
----------
method : str
Identifier of the calculation method to return a handle to.
var : dict
Local variables needed in the mu update method.
Returns
-------
... | e9f363908be5e628e2e17a781a3626737a3d3879 | 3,644,297 |
def build_receiver_model(params, ds_meta, utt_len: int, vocab_size: int, pre_conv=None) -> ReceiverModel:
"""
given the size of images from a dataset, and a desired vocab size and utterance length,
creates a ReceiverModel, which will take in images, and utterances, and classify
the images as being consi... | 59904d83fa48d390f472b69b5324005d1a28e9c6 | 3,644,298 |
import math
def fermi_fitness(strategy_pair, N, i, utilities, selection_intensity=1):
"""
Return the fermi fitness of a strategy pair in a population with
N total individuals and i individuals of the first type.
"""
F, G = [math.exp(k) for k in fitness(strategy_pair, N, i, utilities)]
return ... | fc2631d85ad0fa8ce879ff1fffd6976b1a1e1abf | 3,644,299 |
def diff_smf(mstar_arr, volume, h1_bool, colour_flag=False):
"""
Calculates differential stellar mass function in units of h=1.0
Parameters
----------
mstar_arr: numpy array
Array of stellar masses
volume: float
Volume of survey or simulation
h1_bool: boolean
True ... | 9152a86023c78e47ae0813c489c897800140f174 | 3,644,300 |
def get_parameter(dbutils, parameter_name: str, default_value='') -> str:
"""Creates a text widget and gets parameter value. If ran from ADF, the value is taken from there."""
dbutils.widgets.text(parameter_name, default_value)
return dbutils.widgets.get(parameter_name) | cf8359e6acea68ea26e24cc656847e5560019bd1 | 3,644,301 |
def single_init(cfg: GenomeConfig):
"""Random initialized floating GRU value, calculated via a normal distribution."""
return clip(gauss(cfg.gru_init_mean, cfg.gru_init_stdev), a_min=cfg.gru_min_value, a_max=cfg.gru_max_value) | a72e534259a0d3e0fa3f3081b049bc8c5c316686 | 3,644,302 |
def get_recent_articles(request):
"""
获取最近更新内容
"""
user = get_login_user(request)
recommend = request.POST.get('recommend', 'recommend')
if recommend == 'unrecommend':
articles = Article.objects.raw(get_other_articles_sql)
elif recommend == 'recommend':
articles = Article.ob... | 9ea03f931d67c669f99a87a27ec88bb78a7cd7e2 | 3,644,303 |
import copy
def add_close_export_to_cell(cell):
"""
Adds an HTML comment to close question export for PDF filtering to the top of ``cell``. ``cell``
should be a Markdown cell. This adds ``<!-- END QUESTION-->`` as the first line of the cell.
Args:
cell (``nbformat.NotebookNode``): the cel... | 4fa7d83a8c262979b2d3ef95ddc7c0c50c7e68f7 | 3,644,304 |
def get_ram_list_linux():
"""Get RAM list using dmidecode."""
cmd = ['sudo', 'dmidecode', '--type', 'memory']
dimm_list = []
manufacturer = 'Unknown'
size = 0
# Get DMI data
proc = run_program(cmd)
dmi_data = proc.stdout.splitlines()
# Parse data
for line in dmi_data:
line = line.strip()
i... | 3511ea9f5e09ae467c7d9cb7c42f83741a431eda | 3,644,305 |
def get_capability_list(capability=esdl.Producer):
"""Returns a list of all subtypes of the specified capability.
Used to get a list of e.g. all producers in ESDL
The list is automatically generated based on the ESDL meta model"""
subtype_list = list()
for eclassifier in esdl.eClass.eClassifiers:
... | 700dec944e8a1185c5763a6b32c08fe553f35459 | 3,644,306 |
import errno
def _get_exec_binary(binary, kw):
"""
On win32, the subprocess module can only reliably resolve the
target binary if it's actually a binary; as for a Node.js script
it seems to only work iff shell=True was specified, presenting
a security risk. Resolve the target manually through whi... | 654d8f01419712ac774e0f7c5d4b02b9219d3153 | 3,644,307 |
import site
def init_SSE_square(Lx, Ly):
"""Initialize a starting configuration on a 2D square lattice."""
n_sites = Lx*Ly
# initialize spins randomly with numbers +1 or -1, but the average magnetization is 0
spins = 2*np.mod(np.random.permutation(n_sites), 2) - 1
op_string = -1 * np.ones(10, np.i... | 0c0681b3a28680ed4acf6e2d7ed5719031df948b | 3,644,308 |
import signal
def filter_signal(eeg_df, iqrs, dic_filt_opts):
"""
Filter signal
"""
all_labels = list(eeg_df.columns)
# check the order of labels
label_grouped = False
if all_labels[0].split('.')[-1] == all_labels[1].split('.')[-1]:
label_grouped = True
data_labels = all_pow... | f9dd9108d3c17a59eaae9fe509a88a6c3be55db2 | 3,644,309 |
from typing import List
def get_sym_inequiv_components(
components: List[Component], spg_analyzer: SpacegroupAnalyzer
) -> List[Component]:
"""Gets and counts the symmetrically inequivalent components.
Component data has to have been generated with ``inc_site_ids=True``.
Args:
components: A ... | 5ce83345712ac336a6af2b02421bfef9a62bbf0f | 3,644,310 |
def aic(llf, nobs, df_modelwc):
"""
Akaike information criterion
Parameters
----------
llf : {float, array_like}
value of the loglikelihood
nobs : int
number of observations
df_modelwc : int
number of parameters including constant
Returns
-------
aic : f... | 3940c1c86325630248fdf4a50c2aa19b4f4df623 | 3,644,311 |
def summarize_logs(df, wells, cat, props, sr=0.5):
"""
Function to calculate petrophysical summaries based on well and categorical data. All logs averaged with simple
arithmetic means (maybe supply log permeability to have a better averaged estimation)
Parameters:
logs (pd.DataFrame): datafra... | 3a48fa7d1efc83a8216f01505a645d37b173ecbb | 3,644,312 |
def get_tfpn_mean(targets, predictions):
"""
给定标签和预测,返回对应所有类的 Tp, FN, FP, TN 的平均值
:param targets:
:param predictions:
:return:
"""
cm = confusion_matrix(targets, predictions)
total = np.array(cm).sum()
TP = cm.diagonal().sum()
FN = total - TP
FP = FN
TN = total * len(cm)... | 06c3b184c1b35a22eb3594e934c3aef8e278ebaa | 3,644,314 |
def cal_deltaE00_from_LCh(LCh_1, Lab_2):
"""
Calculate the color difference :math:`\Delta E_{00}` between two given colorspace arrays.
:param LCh_1: array-like
:param Lab_2: array-like
:return: numeric or ndarray
"""
Lab_1 = LCh2Lab(LCh_1)
return deltaE00(Lab_1, Lab_2) | b774be88ad2ca7032f0471963b2720b0e6ecf5f7 | 3,644,315 |
def get_var_type_glue(vtype):
"""Get glue module from variable's type.
Parameters
----------
vtype: data type
Returns
-------
Glue Module if glue exists, otherwise None.
"""
global DTYPE_TO_GLUE, PKG_NAME_TO_GLUE_ARGS
glue_mod = DTYPE_TO_GLUE.get(vtype, None)
if glue_mod is... | d7ba7798286142b70e0dbd8e938f2e3a4ae0423e | 3,644,316 |
def contract_TRG(state, svd_option_1st=None, svd_option_rem=None):
"""
Contract the PEPS using Tensor Renormalization Group.
Parameters
----------
svd_option_1st: tensorbackends.interface.Option, optional
Parameters for the first SVD in TRG. Will default to tensorbackends.interface.ReducedS... | 0e6876c778e6a2df552a6de8b3253d7a860e1987 | 3,644,317 |
def riccati_3(nmax,x):
"""Riccati bessel function of the 3rd kind
returns (r3, r3'), n=0,1,...,nmax"""
x = np.asarray(x)
result = np.zeros((2,nmax) + x.shape, dtype=complex)
for n in range(nmax):
yn = special.spherical_yn(n+1,x)
ynp = special.spherical_yn(n+1,x, derivative=True... | 32d344e8ac4e1f01bbe5605dd4c9a6563497ac71 | 3,644,318 |
def conv_batch_relu_forward(x, w, b, gamma, beta, conv_param, bn_param):
"""
Convenience layer that performs a convolution, a batch, and a ReLU.
Inputs:
- x: Input to the convolutional layer
- w, b, conv_param: Weights and parameters for the convolutional layer
- gamma, beta, bn_param : batch n... | 8c306a2337307ec68aa5a536b4aef0dc4f34cf39 | 3,644,319 |
def hex_layout(npos, width, rotate=None):
"""Compute positions in a hexagon layout.
Place the given number of positions in a hexagonal layout projected on
the sphere and centered at z axis. The width specifies the angular
extent from vertex to vertex along the "X" axis. For example::
Y ^ ... | 85141e08c8a75a54953ba78c520b87d377aad3fb | 3,644,320 |
def dup_zz_hensel_step(m, f, g, h, s, t, K):
"""
One step in Hensel lifting in `Z[x]`.
Given positive integer `m` and `Z[x]` polynomials `f`, `g`, `h`, `s`
and `t` such that::
f == g*h (mod m)
s*g + t*h == 1 (mod m)
lc(f) is not a zero divisor (mod m)
lc(h) == 1
... | 4ce2c7e9aaf52a9ef3e7ce68d164c82959b22ebb | 3,644,321 |
def generate_sobol_index_sample_sets(samplesA, samplesB, index):
"""
Given two sample sets A and B generate the sets :math:`A_B^{I}` from
The rows of A_B^I are all from A except for the rows with non zero entries
in the index I. When A and B are QMC samples it is best to change as few
rows as poss... | 15b02e1995bc922b33d6e0e32bdde1559f0a762e | 3,644,322 |
import logging
def setup_logfile_logger(log_path, log_level=None, log_format=None, date_format=None):
"""
Set up logging to a file.
"""
# Create the handler
handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0)
if log_level:
# Grab and set the level
level... | cfc22a2e334aad5d4aa573014af8a8bac4a7e6b1 | 3,644,323 |
import warnings
def fix_encoding_and_explain(text):
"""
Deprecated copy of `ftfy.fix_encoding_and_explain()`.
"""
warnings.warn(
"`fix_encoding_and_explain()` has moved to the main module of ftfy.",
DeprecationWarning,
)
return ftfy.fix_encoding_and_explain(text) | 3a76fefcbc68b6cf68f3262b90ff277424bf1eba | 3,644,324 |
def parse_16bit_color(color16):
"""解析16位的颜色
:param color16: 16位的颜色值
"""
r = int(gamma5[int((color16 >> 11) & 0x1F)])
g = int(gamma6[int((color16 >> 5) & 0x3F)])
b = int(gamma5[int(color16 & 0x1F)])
return (r, g, b) | c66448c9e886db1e696afa706577d02b3411cd92 | 3,644,325 |
def orders():
"""
List all orders
"""
orders = Order.query.filter_by(user_id=current_user.id).all()
return render_template('customer/orders.html', orders=orders, title="Orders") | 921552a41ef673cb9c8f6c414ba4a12b3643617a | 3,644,326 |
def packpeeklist1(n1, n2, n3, n4, n5):
"""
Packs and returns 5 item list
"""
listp = [n1, n2, n3, n4, n5]
return listp | 4b781ff3e8eb4a1bd51f8e834fab5462371a85c5 | 3,644,327 |
from typing import List
def valid_commands(commands: List[str]) -> List[str]:
"""
Get list of valid commands from list of commands.
:param (list) commands: User-supplied commands.
:return:
"""
return [command for command in commands if command in available_commands()] | 25054d8acb8bee16855adba25e846bc128fb9f23 | 3,644,328 |
def duck_list(request):
""" lists all ducks """
ducks = Duck.objects.all()
return render(request, 'duck/list.html', {'duck_list': ducks}) | 206e586c2709d4c5526e26ff50cabdfe440125bc | 3,644,329 |
def get_debian_version(file_path):
"""
Get the version of a debian file
:param file_path: the path of the debian file
:return: the version of the debian file
"""
cmd_args = ["dpkg-deb", "-f", file_path, "Version"]
debian_version = run_command(cmd_args)
return debian_version | 61c8779d4b235a1d74bf819299f95077e5ff001a | 3,644,330 |
from typing import Optional
def hash_type(
draw, hash_type_strategy: Optional[SearchStrategy[HashType]] = None
) -> HashType:
"""Composite strategy for fetching a :class:`~modist.package.hasher.HashType`."""
return draw(HashType_strategy if not hash_type_strategy else hash_type_strategy) | 79152dda823dcd227545ed2bb117229344fc341a | 3,644,331 |
def get_initializer(initializer_name):
"""Get the corresponding initializer function based on the initializer string.
API of an initializer:
init_fn, hparams = get_initializer(init)
new_params, final_l = init_fn(loss, init_params, hps,
num_outputs, input_shape)
Args:
init... | 778941a5e7937600cca2a48371d2540cab6476ab | 3,644,332 |
def _l2_project_reference(z_p, p, z_q):
"""Projects distribution (z_p, p) onto support z_q under L2-metric over CDFs.
The supports z_p and z_q are specified as tensors of distinct atoms (given
in ascending order).
Let Kq be len(z_q) and Kp be len(z_p). This projection works for any
support z_q, in particula... | e6c43d1d05237410ff94d3a3b76bc705f2064d46 | 3,644,335 |
def _make_blocksizes(bricksize, surveysize, nlods, dtype, factor=(1,1,1), verbose=None):
"""
CURRENTLY NOT USED.
Calculate the minimum blocksize to read at each lod level. Clip to
the survey size. Also compute the memory needed to hold one buffer
for each lod. Note that the genlod algorithm current... | defc1f11d8f3684ccce4a7df7db6c011848187af | 3,644,336 |
from ._backend import _check_backend
from ._kit2fiff_gui import Kit2FiffFrame
def kit2fiff():
"""Convert KIT files to the fiff format.
The recommended way to use the GUI is through bash with::
$ mne kit2fiff
"""
_check_mayavi_version()
_check_backend()
gui = Kit2FiffFrame()
gui.... | b57b74d036378b1265e991b8c49d55bce41807c0 | 3,644,337 |
import tqdm
def sweep_dec_given_x(full_model, z_dec_model, sample1, sample2, sample_layer_name,
sweep_z_samples=False,
nb_samples=10,
nargout=1,
tqdm=tqdm):
"""
sweep the latent space given two samples in the original spac... | 9a5bccfa85f0bdda5953b8a72c66238e0ff5d548 | 3,644,338 |
def process(observation, current_game_state):
"""
Args:
observation: An observation, which agents get as an input from kaggle environment.
current_game_state: An object provided by kaggle to simplify game info extraction.
Returns:
processed_observations: A prepared observation to sav... | 3a54ad62fa341ca57528c5ee32b45d749982f286 | 3,644,339 |
def source_files(goto, wkdir, srcdir=None):
"""Source files appearing in symbol table.
Source file path names in symbol table are absolute or relative to
wkdir. If srcdir is given, return only files under srcdir.
"""
wkdir = srcloct.abspath(wkdir)
srcs = [dfn['file']
for dfn in pa... | bacb86942b5f82ecc902699b81de5d92868ddd57 | 3,644,340 |
def textBlurBackground(img, text, font, fontScale, textPos, textThickness=1, textColor=(0, 255, 0), kneral=(33, 33),
pad_x=3, pad_y=3):
"""
Draw text with background blured, control the blur value, with kernal(odd, odd)
@param img:(mat) which you want to draw text
@param text: (s... | dd4c49a7cf15af4273e1b3689fa6caabe8242ea0 | 3,644,341 |
from re import T
def local_response_normalization_2d_v2(in_vw, alpha, k, beta, n):
"""
cross-channel local response normalization for 2D feature maps
- input is bc01
output[i]
= value of the i-th channel
= input[i] / (k + alpha * sum(input[j]^2 for j) ** beta)
- where j is over neighbor... | 23f810dbd4f36d1817c57ceeabbacad1cf8e0239 | 3,644,342 |
def add_new_user():
"""
This function adds a new user
:return: Response Code
"""
newuser = {}
if request.method == "POST":
try:
newuser['username'] = str(request.data.get('username').strip())
newuser['first_name'] = str(request.data.get('first_name').strip())
... | 32abdd61ff4ad574a0e097553d3332f6f67d57dd | 3,644,344 |
def has_wildcard(url) -> bool:
"""
Check if the url contains a wildcard in last subdomain.
:param url: The url to check
:type url: str
:return: True if the url contains a wildcard in the last subdomain, False otherwise
:rtype: bool
"""
subdomain = extract(url).subdomain
return subdo... | 5dbf1a0220ad6c4af3bfe344a3aaa97473918995 | 3,644,345 |
def tmle_calculator(y, ystar1, ystar0, ystara, h1w, h0w, haw, splits,
measure='ate', lower_bound=None, upper_bound=None):
"""Function to calculate TMLE estimates for SingleCrossfitTMLE, and DoubleCrossfitTMLE
"""
if measure in ["ate", "risk_difference"]:
# Unbounding if continuou... | 36f6b131044bd3b53044a4bfe0954eff1325bb59 | 3,644,346 |
def gen_gap(Pn, T, Q):
"""Runs the generalization gap test. This test
simply checks the difference between the likelihood
assigned to the training set versus that assigned to
a held out test set.
Inputs:
Pn: (n X d) np array containing the held out test sample
of dimensio... | d57d16c06d05cea86e6f6ea89484574f20500170 | 3,644,347 |
def get_shapes(node, intermediate=False, exclusive=False):
"""Get the shapes of given node.
Args:
node (str): Node to query its shapes
intermediate (bool): Get intermediate shapes when True.
exclusive (bool): Only return the intermediate shapes if True.
Please note that the ... | 9e6d1c3e9030d1ce2804953cc7316d53840d3195 | 3,644,348 |
def solve_mip_mlp_elided(verif_instance):
"""Compute optimal attack loss for MLPs, via exactly solving MIP."""
assert MIP_SOLVERS, 'No MIP solvers installed with cvxpy.'
assert verif_instance.type == utils.VerifInstanceTypes.MLP_ELIDED
params, bounds, obj, obj_const = (
verif_instance.params, verif_instan... | 89ef1f133598feaf73d265411b5ed6597736ddf5 | 3,644,349 |
def compute_kullback_leibler_check_statistic(n=100, prngstate=None):
"""Compute the lowest of the survival function and the CDF of the exact KL
divergence KL(N(mu1,s1)||N(mu2,s2)) w.r.t. the sample distribution of the
KL divergence drawn by computing log(P(x|N(mu1,s1)))-log(P(x|N(mu2,s2)))
over a sample... | 8c7036e89a3bfd347b613efac76c1b8dffde2cfa | 3,644,350 |
def build_signature(inputs, outputs):
"""Build the signature for use when exporting the graph.
Args:
inputs: a dictionary from tensor name to tensor
outputs: a dictionary from tensor name to tensor
Returns:
The signature, a SignatureDef proto, specifies the input/output tensors
to bind when runni... | ac760f7efcb27cf985aa9048015ba3be77230bc4 | 3,644,351 |
def fuse_depthwise_conv2d(input_graph_def):
"""Modifies the provided graph by fusing a set of ops into a single
_FusedDepthwiseConv2d op.
DepthwiseConv2dNative + BiasAdd + Activation => _FusedDepthwiseConv2dNative
Args:
input_graph_def: A GraphDef containing a model.
Returns:
Modified graph with Fu... | bbfdfbc02debfcad5e1c965c09c9039c3f15faac | 3,644,352 |
def pandas_to_example_str(obj, *, local_data_model=None) -> str:
"""
Convert data frame to a Python source code string.
:param obj: data frame to convert.
:param local_data_model: data model to use.
:return: Python source code representation of obj.
"""
if local_data_model is None:
... | a0c1bd23797413b739c496e621c43a4f43293c17 | 3,644,353 |
from typing import Counter
def get_results_object_model(target_node, paths_dict, name_to_description, q1_doid_to_disease, probs=False):
"""
Returns pathway results as an object model
:param target_node: target_node DOID:1234
:param paths_dict: a dictionary (keys OMIM id's) with values (path_name,path_type)
:para... | 5ac0ba140a80edf12005112330191d910673e34a | 3,644,354 |
def MaxLonSep( maxarc, baselat ):
"""Calculates the maximum separation in longitude that a point can have
from a reference point at latitude baselat and still be within a given
great circle arc length, maxarc, of the reference point. All quantities
in radians."""
if abs(baselat) + maxarc <= 0.5 * pi... | cffd6639441f548682e47c9af22c194a18d0f9fe | 3,644,355 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.