content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
import math
def run_trap_harvesting(prev_values = [], selected_harvest= 0, radius= default_radius, height= default_height, slope= default_slope, delta= default_delta, constant_population= True):
"""Runs the model for one harvesting cycle. Where a harvesting cycle is period of time ending in the next low tide in w... | ed153837e4e3d538fa483ca2bba6eb68f98319a2 | 3,644,313 |
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 |
import logging
from unittest.mock import call
def sh(cmd, grid=False, infile=None, outfile=None, errfile=None,
background=False):
"""
simple wrapper for system calls
"""
if grid:
return 0 # A fake retcode
else:
if infile:
cmd += " < {0} ".format(infile)
... | 0520e05c30d127bcc3c8e4057c4d839432c51334 | 3,644,333 |
from .model_store import get_model_file
import os
def get_voca(base_persons,
vertices,
model_name=None,
pretrained=False,
root=os.path.join("~", ".tensorflow", "models"),
**kwargs):
"""
Create VOCA model with specific parameters.
Parameters... | 9c7fa8c52bd634f5a1b6511607976515d55202fd | 3,644,334 |
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 |
import os
def mhc_datasets(table='mhc_data', path='./iedb/', remove_c=False,
remove_u=False, remove_modes=False):
"""
Parameters: 'table' is the table that the data is retrieved
- must be 'mhc_data', 'mhc_test1', 'mhc_test2', or 'mhc_train'
'path' is where th... | 8f05454a9362f8115834a2caee40e28a48877741 | 3,644,343 |
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 |
def auto_read(filename):
"""Automatically determine the format of filename and open accordingly"""
#XXX: this won't work correctly on pipes
#would be better to use file magic
f = open(filename, 'r')
firstchar = f.read(1)
f.close()
if firstchar == '#':
return gnucap_read(filename)
else:
return sp... | 0485626e6305aa43ece6b6cf36a924f7526af26c | 3,644,356 |
import time
def WaitForOperation(client, messages, operation_name,
operation_description=None,
project=None, timeout=180):
"""Wait for an operation to complete.
Polls the operation requested approximately every second, showing a
progress indicator. Returns when the ope... | e63b3951dd98762d28050ebff753f78e88cd0231 | 3,644,357 |
def get_unstaged_files(gitobj):
"""
ref:
http://gitpython.readthedocs.io/en/stable/tutorial.html#obtaining-diff-information
"""
diff = []
diff.extend(gitobj.index.diff(gitobj.head.commit))
diff.extend(gitobj.index.diff(None))
return {"changed": diff, "untracked": gitobj.untracked_files} | 623a2706bb0d2c428df0f44fe10a473e7d740938 | 3,644,358 |
from typing import Optional
from typing import Union
from typing import Tuple
def conv2d(
inp: Tensor,
weight: Tensor,
bias: Optional[Tensor] = None,
stride: Union[int, Tuple[int, int]] = 1,
padding: Union[int, Tuple[int, int]] = 0,
dilation: Union[int, Tuple[int, int]] = 1,
groups: int = ... | fff9e2430c21757e3a5a4e1146ead63ad2fb5918 | 3,644,359 |
import encodings
def find_tex_directives(texfile, ignore_root_loops=False):
"""Build a dictionary of %!TEX directives.
The main ones we are concerned with are:
root
Specifies a root file to run tex on for this subsidiary
TS-program
Tells us which latex program to run
... | df639f11f1609ee5c8a6bca0add8c154a42c481a | 3,644,360 |
def projects():
"""
Handles the GET & POST request to '/projects'.
GET: requests to render page
POST: request to edit project with sent data
:return: render projects page / Json containing authorisation error / manage(data) function call
"""
if request.method == "GET":
return render_... | 7a8a1d9c4d50623ad557d9dcaf419c5a3e83f521 | 3,644,361 |
def evolve_fqe_givens_sector(wfn: Wavefunction, u: np.ndarray,
sector='alpha') -> Wavefunction:
"""Evolve a wavefunction by u generated from a 1-body Hamiltonian.
Args:
wfn: FQE Wavefunction on n-orbitals
u: (n x n) unitary matrix.
sector: Optional either 'a... | 7f8334d64a1965424c5a1faf166bbf8741c0e1ae | 3,644,362 |
import os
def save_tiles(tiles, prefix='', directory=os.getcwd(), format='png'):
"""
Write image files to disk. Create specified folder(s) if they
don't exist. Return list of :class:`Tile` instance.
Args:
tiles (list): List, tuple or set of :class:`Tile` objects to save.
prefix (str... | 2848eee201d16ca15eed06019199d95a59393a37 | 3,644,363 |
from typing import Iterable
def epoch_folding_search(times, frequencies, nbin=128, segment_size=5000,
expocorr=False, gti=None, weights=1, fdots=0):
"""Performs epoch folding at trial frequencies in photon data.
If no exposure correction is needed and numba is installed, it uses a fa... | 7eaa1d038a883babcf55f239acf519f5c059b0b2 | 3,644,364 |
import re
def apply_matcher(words,
offsets,
dictionary,
max_ngrams=5,
longest_match_only=True,
case_sensitive = False,
split_on=None):
"""
TODO: cleanup!
"""
# covert to source char offsets
... | c52c0dd7b881d29952ebd09988362156707ad4bc | 3,644,365 |
import os
def create_and_put_metrics_and_widgets() -> dict:
"""For each repository, aggregates all text and metric data and creates widgets for each
:returns: a dictionary mapping the dashboard name to the list of the text and metric widgets for each repository to
put in the dashboard
:rtyp... | a779f86e9bca3090336a18a8716acab9b5372dfb | 3,644,366 |
def boxbin(x,y,xedge,yedge,c=None,figsize=(5,5),cmap='viridis',mincnt=10,vmin=None,vmax=None,edgecolor=None,powernorm=False,
ax=None,normed=False,method='mean',quantile=None,alpha=1.0,cbar=True,unconditional=False,master_count=np.array([])):
""" This function will grid data for you and provide the c... | b80a9fdf25d16ecd5e73addae325d1a2348ef900 | 3,644,367 |
def _get_elastic_document(
tasks: list[dict],
symprec: float,
fitting_method: str,
) -> ElasticDocument:
"""
Turn a list of deformation tasks into an elastic document.
Parameters
----------
tasks : list of dict
A list of deformation tasks.
symprec : float
Symmetry pr... | f01ea537fbd73c6a2da529a4da15e358033ed2a9 | 3,644,368 |
from typing import Union
from pathlib import Path
from typing import Counter
def first(filename: Union[str, Path]) -> int:
"""
Sort the input, prepend with 0 and append with 3 + the max.
Return:
(# of successive differences == 1) * (# of successive differences == 3)
"""
with open(filename... | 18ffe3e97d7256ea61fcf6e436d36bb360d0a285 | 3,644,369 |
def charge_is_valid(charge_profile, capacity=6, max_charge_rate=2.5, time_unit=0.5):
"""
Function determining if a charge profile is valid (and fully charges the battery)
"""
if np.all(np.isclose(capacity/time_unit, charge_profile.groupby(charge_profile.index.date).sum())) is False:
return False... | 489717fc834b9492ab3add1ddfaa5c55e2f4d8e9 | 3,644,370 |
def create_slice_obj(start, end, step):
"""Create slice object"""
return slice(start, end, step) | 88a5c5a9e0d3b714b4316d8744fcdd1a34f347a7 | 3,644,371 |
def binary_cross_entropy_error(y, t):
"""バイナリー交差エントロピー誤差"""
#y.shape (N,C,H,W)
delta = 1e-7
return -np.mean(t*np.log(y + delta) + (1-t)*np.log(1-y + delta)) | a0090d4d5e6695ab0c4d988b8f0efbdfcd44984c | 3,644,372 |
def get_abc():
"""
:return: list all the abcs as a list
"""
# ok
return list(abcs.find({}, {'_id': False})) | aa2c39bdc8ec1f31f43ea02701b5022f612b286b | 3,644,373 |
from typing import Optional
from typing import List
def matching_system_code(concept: CodeableConcept, system: str) -> Optional[str]:
"""
Returns a code from a specified *system* contained within a given *concept*.
If no code is found for the given *system*, returns None.
Raises an :class:`Assertion... | cd9005ebcfd9ab15e5d27f7f30b8b4ea4b4db7b0 | 3,644,374 |
def get_pybullet(env_name):
""" Returns pybullet dataset and envrironment.
The dataset is provided through d4rl-pybullet. See more details including
available dataset from its GitHub page.
.. code-block:: python
from d3rlpy.datasets import get_pybullet
dataset, env = get_pybullet('ho... | 79d3e408698ea7454398490a98fd7d653625cbd4 | 3,644,375 |
from typing import Iterable
from typing import Any
def reverse(d: Iterable) -> Any:
"""Reverses the provided iterable, but also RETURNS it"""
d.reverse()
return d | 5eff6b170afe6424f113ec4b15f985ee8d306e83 | 3,644,376 |
def scalar(typename):
"""
Returns scalar type from ROS message data type, like "uint8" from "uint8[100]".
Returns type unchanged if already a scalar.
"""
return typename[:typename.index("[")] if "[" in typename else typename | 729fb68bced11e190b3d32d03bbadd921f191bee | 3,644,377 |
def subject(mock_messenger: AsyncMock) -> initiator.FirmwareUpdateInitiator:
"""The test subject."""
return initiator.FirmwareUpdateInitiator(mock_messenger) | cfab4395d5ffc3de6a33d3eeb2d7ce373f719b06 | 3,644,378 |
def onetangent(ri, rf, ta_transb, k=0, use_alts=True, center='earth'):
"""Orbit transfer with one tangential burn and one nontangential
burn. Must be circular or coaxially elliptic. Currently only for
circular orbits.
:param ri: altitude (or radius) of initial circular orbit (km)
:param rf: altitu... | 12eae51bc3833df94b063597e2444df851a7960c | 3,644,379 |
def display_matplot(images, title = None, gray=None):
"""[Standard display fuction used throughout testing to see the output of thhe various transforms.
Displays multilpe plots at once for comparison, always in a square format.]
Arguments:
images {[Array]} -- [the array that contains all of the ... | 635b6c977d1d71a9d7479e064978c3695115d757 | 3,644,380 |
def get_version():
"""
It returns the pmml version .
Returns
-------
version : String
Returns the version of the pmml.
"""
version = '4.4'
return version | 162f6e0ffb4c4741fafe2aa16d6fceed16bae99a | 3,644,381 |
import torch
def customsoftmax(inp, multihotmask):
"""
Custom Softmax
"""
soft = F.softmax(inp, dim=1)
# This takes the mask * softmax ( sums it up hence summing up the classes in border
# then takes of summed up version vs no summed version
return torch.log(
torch.max(soft, (multi... | a0db0926aa9ed804bfab54cfaaf7c4a031809aae | 3,644,382 |
import scipy
def mandoline(
D_src: np.ndarray,
D_tgt: np.ndarray,
edge_list: np.ndarray,
sigma: float=None,
):
"""
Mandoline solver.
Args:
D_src: (n_src x d) matrix of (example, slices) for the source distribution.
D_tgt: (n_tgt x d) matrix of (example, slices) for the sou... | 5b7817e1ff252724f61572ac6f103ec963c257dd | 3,644,383 |
def service_transformer_info_get(service): # noqa: E501
"""Retrieve transformer info
Provides information about the transformer. # noqa: E501
:param service: Inxight_Drugs service
:rtype: TransformerInfo
"""
return transformer[service].info | a12d4d19efe7bf8a3c185213790366339aad8c9f | 3,644,384 |
def create_app(config=None, app_name=None):
"""Create a Flask app."""
if app_name is None:
app_name = DefaultConfig.PROJECT
app = Flask(app_name, instance_path=INSTANCE_FOLDER_PATH, instance_relative_config=True)
configure_app(app, config)
configure_hook(app)
configure_blueprints(app)
... | 95f5191fc64f5656156fc69bd9565b0a754e014c | 3,644,385 |
def read_translocations_tumors(gene_A, gene_B,\
tumor_barcodes,\
data_location=default_location):
"""
For a given set of tumor barcode and a gene, finds with a lookup the mutation for this
particular gene on the TCGA dataset.
INPUT:
- gene_A (str): fi... | 7ae16c2898272676ab1ab2bccde4ca3958fbb4a0 | 3,644,386 |
import numbers
def simplify_if_constant(symbol, keep_domains=False):
"""
Utility function to simplify an expression tree if it evalutes to a constant
scalar, vector or matrix
"""
if keep_domains is True:
domain = symbol.domain
auxiliary_domains = symbol.auxiliary_domains
else:
... | c696ec4a7c81251448c97afe92c32f275284f71e | 3,644,387 |
def is_visible(window):
"""
Check whether the window is visible or not.
"""
return lib.is_visible(window) | 23f146625dcaa3f473ddec1684b9f222496bae48 | 3,644,388 |
from typing import Optional
import copy
def fix_mol(
mol: Chem.rdchem.Mol,
n_iter: int = 1,
remove_singleton: bool = False,
largest_only: bool = False,
inplace: bool = False,
) -> Optional[Chem.rdchem.Mol]:
"""Fix error in molecule using a greedy approach.
Args:
mol: input molecul... | 6d745d9ec308e577b73243850e6f46c93c5ff24f | 3,644,389 |
from typing import Iterable
from typing import List
def permutation_circuit(swaps: Iterable[List[Swap[_V]]]) -> PermutationCircuit:
"""Produce a circuit description of a list of swaps.
With a given permutation and permuter you can compute the swaps using the permuter function
then feed it into thi... | c45d5fea5974c3bfb7e695ddc366d4948203e1d1 | 3,644,390 |
def Add(a, b):
"""
Adds two numbers, throws on overflow.
"""
c = a + b
Require(c >= a)
return c | cf6c04ed1f5f2f6782e6b91aea739c7e54c1dfe6 | 3,644,391 |
from typing import Dict
from typing import Type
def remap_shared_output_descriptions(output_descriptions: Dict[str, str], outputs: Dict[str, Type]) -> Dict[str, str]:
"""
Deals with mixed styles of return value descriptions used in docstrings. If the docstring contains a single entry of return value descripti... | 06d589016a747230f88aa3507bd751fd30095222 | 3,644,392 |
def dist_matrix():
"""Fix dist_matrix for the next two tests."""
dist_matrix = np.array([[0, 4, 5, 6], [4, 0, 7, 8], [5, 7, 0, 9], [6, 8, 9, 0]])
return dist_matrix | 5bc3e5da5a6c76fd91858a697e2db183c74eb03f | 3,644,393 |
def fitarg_rename(fitarg, ren):
"""Rename variable names in ``fitarg`` with rename function.
::
#simple renaming
fitarg_rename({'x':1, 'limit_x':1, 'fix_x':1, 'error_x':1},
lambda pname: 'y' if pname=='x' else pname)
#{'y':1, 'limit_y':1, 'fix_y':1, 'error_y':1},
#... | 151233d0f18eaea564afbc6d600d576407504b35 | 3,644,394 |
def flatten(tensor):
"""Flattens a given tensor such that the channel axis is first.
The shapes are transformed as follows:
(N, C, D, H, W) -> (C, N * D * H * W)
"""
C = tensor.size(1)
# new axis order
axis_order = (1, 0) + tuple(range(2, tensor.dim()))
# Transpose: (N, C, D, H, W) ->... | e7586da0abfdea639b3bb760fe31fca1cc849d1d | 3,644,395 |
import soundfile
import os
def file_to_jsobj(src,
chart_type=DFLT_CHART_TYPE,
enable_playback=DFLT_ENABLE_PLAYBACK,
height=DFLT_HEIGHT,
params=DFLT_PARAMS,
title=None,
subtitle='',
**kwargs
... | 26e4c1461614c5c7b0010920dba646fd1d381345 | 3,644,396 |
def node_to_edge(edges, directed=True):
"""
From list of edges, record per node, incoming and outgoing edges
"""
outgoing = defaultdict(set)
incoming = defaultdict(set) if directed else outgoing
nodes = set()
for i, edge in enumerate(edges):
a, b, = edge[:2]
outgoing[a].add(i... | 7e3f7bf93bbf19355b3329762a3531504bbc53a4 | 3,644,397 |
from typing import Counter
def grouping_cumulative(df, col_index, col_column):
""" compute histogram statistic over selected column and in addition group this histograms
:param DataFrame df: rich table
:param str col_index: column which will be used s index in resulting table
:param str col_column: c... | f99b1c2cc4e7bc4e3a3af02414ba82bd057607e9 | 3,644,398 |
def _get_matching_stream(smap, itag):
""" Return the url and signature for a stream matching itag in smap. """
for x in smap:
if x['itag'] == itag and x.get("s"):
return x['url'], x['s']
raise IOError("Sorry this video is not currently supported by pafy") | dc83fd3207d5ab4e1c85eb719f5f7d023131565e | 3,644,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.