content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def Optional(trait: TraitType) -> Union:
"""
Return Union of function argument and Instance(_Undefined)
Args:
trait (TraitType): optional trait
Returns:
union with undefined instance
"""
return Union(trait, Instance(_Undefined)) | 5,296,000 |
def mda_1D_Xindex(ScanNum,DetectorNum,coeff=1,bckg=0,filepath=None,prefix=None,scanIOC=None):
""" Return x=index and y=detector(DetectorNum)
for a given detector number DYY (as shown in dview). """
try:
(data_file,det)=mda_unpack(ScanNum,filepath,prefix,scanIOC)
index=det[DetectorNum][1]
... | 5,296,001 |
def delenv():
"""Delete options in the existing environment."""
global _env
if not _env:
raise EnvError("No environment exists")
else:
_env.clear_config_options()
log.debug("Cleared existing %r options", _env) | 5,296,002 |
async def foxascii(event):
"""An ASCII fox."""
await event.reply(event.f.codeblock(FOXASCII)) | 5,296,003 |
def requires_admin(func):
"""Decorator requiring the requesting user be a website admin"""
@wraps(func)
def inner(*args, **kwargs):
if g.user is None:
return JsonResponse.create(StatusCode.LOGIN_REQUIRED, {'message': "Login Required"})
if not g.user.website_admin:
re... | 5,296,004 |
def func3(arg1, arg2, kwarg1="Test", kwarg2=0):
"""Generic short description.
Longer description of this function that does nothing.
Parameters
----------
arg1 : dict
Description for arg1. Longer description. Still part of the
description. More description.
Keep this in... | 5,296,005 |
def test_team_connection_unchanged(mocked_team_connection_unchanged, capfd):
"""
Test : Team connection unchanged
"""
with pytest.raises(SystemExit):
nmcli.main()
out, err = capfd.readouterr()
results = json.loads(out)
assert not results.get('failed')
assert not results['changed... | 5,296,006 |
def to_jsscalar(x):
""" convert x to JavaScript representation """
from cesiumpy.base import _CesiumObject, _CesiumEnum
if isinstance(x, (_CesiumObject, _CesiumEnum)):
return x.script
if isinstance(x, bool):
# convert to JavaScript repr
x = 'true' if x else 'false'
elif isi... | 5,296,007 |
def createMatcapMaterial(material_name, matcap_image_name):
"""
matcapのマテリアルをshaderFXから作る
matcap_image_name : imageファイルの名前
return : マテリアルの名前
"""
selection = cmds.ls(sl=True)
if not cmds.pluginInfo("shaderFXPlugin", q=True, loaded=True):
cmds.loadPlugin("shaderFXPlugin")
cmds.... | 5,296,008 |
def covid_API_request(location:str = data['location'],
location_type:str = data['location_type']) -> dict:
"""This function returns live data from the uk-covid19 API.
Args:
location (str, optional): Location of data needed from API.
Defaults to data["location"].
location_type (str, ... | 5,296,009 |
def create_app():
"""Registers an app on the Mastodon instance.
Be sure to call this fonction only once, you do not
want to register the application multiple times on the
instance!
"""
print(Mastodon.create_app(
settings.APP_NAME,
api_base_url=settings.API_BASE_URL,
... | 5,296,010 |
def pgloss(y_true, y_pred):
"""Policy Gradients loss. Maximizes log(output) · reward"""
return - K.mean(K.log(y_pred) * y_true) | 5,296,011 |
def remove_venv_config(name: str) -> Path:
"""Removes a vsh virtual environment configuration file
Args:
name: name of virtual environment
path: path to virtual environment
working: path of working dir when entering virtual environment
Returns:
configuration file removed
... | 5,296,012 |
def open(**kwargs):
"""
A factory function to open new ``Vim`` object.
``with`` statement can be used for this.
"""
return Vim(**kwargs) | 5,296,013 |
async def test_template_out_of_bounds(hass, start_ha):
"""Test template out-of-bounds condition."""
state = hass.states.get("cover.test_template_cover")
assert state.attributes.get("current_tilt_position") is None
assert state.attributes.get("current_position") is None | 5,296,014 |
def difference(geometries,
spatial_ref,
geometry,
gis=None):
"""
The difference function is performed on a geometry service
resource. This function constructs the set-theoretic difference
between each element of an array of geometries and another geometry
... | 5,296,015 |
def load_yaml_guess_indent(stream, **kw):
# type: (StreamTextType, Any) -> Any
"""guess the indent and block sequence indent of yaml stream/string
returns round_trip_loaded stream, indent level, block sequence indent
- block sequence indent is the number of spaces before a dash relative to previous ind... | 5,296,016 |
def get_stats_test():
"""Test the HTML page digestion against a test stats.html."""
# Hack function for developing new functionality without
# hammering the RWR servers with requests
logger.debug("Loading stats from stats.html example for testing")
html = Path("stats.html").read_text(encoding="utf-8... | 5,296,017 |
def remove_duplicate_edges(G, max_ratio = 1.5):
"""
function for deleting duplicated edges - where there is more than one edge connecting a node pair. USE WITH CAUTION - will change both topological relationships and node maps
:param G: a graph object
:param max_ratio: most of the time we see duplicate ... | 5,296,018 |
def conv_classifier_deterministic_loss(
params: utils.Params,
batch: utils.Batch,
num_classes: int,
layer_channels: Sequence[int],
l2_reg: float = 0.0,
explicit_tagging: bool = False,
activation: Callable[[LayerInputs], LayerInputs] = _special_tanh,
) -> chex.Array:
"""Evaluate the autoenc... | 5,296,019 |
def repo_changed(directory):
"""Determine if the Git repository in directory is dirty"""
ret = _call_git("status", "--porcelain", directory=directory)
return bool(ret.stdout) | 5,296,020 |
def color_bar(mode):
"""
Create different colormap for each mode
:param mode: 1 -- Rate, 2 -- Occupancy, 3 -- Recommanded
:type mode: int
:returns: color map
:rtype: branca.Colormap
"""
cm_name = {1: cm.linear.YlGnBu_07,
2: cm.linear.RdPu_06,
3: cm.linear.... | 5,296,021 |
def just_nucs(seqs):
"""eliminate sequences containing gaps/Ns,
along the 1st axis, match each base in seqs to <= 3 element-wise,
give the indices of those just_nucs seq idx.
"""
(indices,) = (seqs <= 3).all(axis=1).nonzero()
just_bases = seqs.take(indices, axis=0)
return just_bases | 5,296,022 |
def plot_image_as_3d_histogram(image, save_path=None, image_title='Image', histogram_title='Histogram'):
"""
plot an image as a 3d histogram beside itself.
:param image: a 2D numpy array that is the image to plot
:param save_path: the path to save the plot to. if None the figure is displayed.
:param... | 5,296,023 |
def read_clip(path, undersample=4):
"""Read a GIF a return an array of shape (C, W, H, T)."""
gif = Image.open(path)
frames = []
for i in range(gif.n_frames):
gif.seek(i)
frames.append(np.array(gif.convert('RGB')))
frames = frames[::undersample]
array = np.stack(frames).transpose... | 5,296,024 |
def fir(nb, nk, u, y):
"""
Estimates a FIR model based on input (u(t)) and output (y(t)) vectors.
Returns the polynomial B(q) relative to the MIMO FIR model with nu inputs
and ny outputs, also affected by white gaussian noise e(t), as follows:
y(t) = B(q)*u(t) + e(t)
Parameters
-----... | 5,296,025 |
def random_forest_error(forest, X_train, y_train, X_test,
alpha_level=0.05,
n_fixed_points=50, n_mc_samples=500,
n_trees_var=500,
use_built_trees=True,
random_state=None, n_jobs=None):
"""Calculat... | 5,296,026 |
def descriptive_stats(x, feature_prefix=''):
"""Create a pandas dataframe containing the features calculated on x.
x is an input array for which the features below are calculated.
feature_prefix is prepended to each of the feature names to create unique columns."""
feature_names = [
'minimum'... | 5,296,027 |
def main():
"""
# --------------------------------------------------------------------------
# main function
# --------------------------------------------------------------------------
"""
comm_opts = parse_args()
ROOTDIR = comm_opts['rootdir']
ROOTCOMP = comm_opts['rootcomp']
O... | 5,296,028 |
def cmd(ctx, url, key, secret, adapter_name, adapter_node, cnx_id, **kwargs):
"""Test reachability for an existing connection by ID."""
client = ctx.obj.start_client(url=url, key=key, secret=secret)
with ctx.obj.exc_wrap(wraperror=ctx.obj.wraperror):
client.adapters.cnx.test_by_id(
adap... | 5,296,029 |
def init_daemon(config,
given_logger,
handler: Callable,
complete_callback: Optional[Callable] = None,
post_mortem_callback: Optional[Callable] = None,
infinite: bool = False) -> str:
"""Стартовать скрипт с выбранными настройками.
... | 5,296,030 |
def bind(
function: Callable[
[_FirstType],
KindN[_BindableKind, _UpdatedType, _SecondType, _ThirdType],
],
) -> Kinded[Callable[
[KindN[_BindableKind, _FirstType, _SecondType, _ThirdType]],
KindN[_BindableKind, _UpdatedType, _SecondType, _ThirdType],
]]:
"""
Turns function's inp... | 5,296,031 |
def transforms_rowskipfilter(
data,
output_data=None,
model=None,
count=0,
**params):
"""
**Description**
Allows limiting input to a subset of rows by skipping a number of
rows.
:param count: Number of items to skip (inputs).
:param data: Input da... | 5,296,032 |
def GetExistingCatalogRecords(firebase: firebase, documentName: str, documentSemester: str, documentYear: str) -> None:
"""
Get existing catalog records from database and insert into global collection.
:param firebase: a firebase connection
:param documentName: a string representing the cat... | 5,296,033 |
def test_reddit_source_with_no_credentials(mocker: MockerFixture) -> None:
"""
Test that given the reddit argument without proper credentials
the program will raise an exception.
"""
config = Namespace(
reddit=True,
metric='hot',
sub='programming',
reddit_id=None,
... | 5,296,034 |
def get_lc_file_and_data(yourpath, target):
""" goes in, grabs the data for the target, gets the time index, intensity,and TIC
if connection error w/ MAST, skips it.
Also masks any flagged data points according to the QUALITY column.
parameters:
* yourpath, where you want the files saved to. mu... | 5,296,035 |
def startofday(expr, offset=None):
"""Get the start of day for a timestamp (round to preceding midnight).
Parameters
----------
expr: str, Column or expression.
The datetime column/expression to round to the start of the day.
offset: int, default None
The number of days to shift the... | 5,296,036 |
def fov_wide():
"""Change the field of view to wide """
print
print fov_wide.__doc__
command_send('camera', 'FV', '00') | 5,296,037 |
def polar2cart(angle, magnitude, retField=False):
""" Returns the field from the input phase angle and magnitude.
Args:
- angle, phase angle of the field (2 dims);
- magnitude, magnitude of the field (2 dims);
- retField, if True returns a field, otherwise returns (x,y).
"""
if retField:
if np.isscalar(m... | 5,296,038 |
def test_success(database):
""" Tests that if the SF-133 amount for line 1000 for the same fiscal year and period is populated, then
Appropriation budget_authority_unobligat_fyb is also populated"""
sf = SF133Factory(line=1000, tas=_TAS, period=1, fiscal_year=2016, amount=1)
ap = AppropriationFactory(t... | 5,296,039 |
def grant_role(role, user, tenant=None):
"""Grants `role` to `user` (and optionally, on `tenant`)"""
role = db_api.ROLE.get_by_name(name=role).id
user = db_api.USER.get_by_name(name=user).id
if tenant:
tenant = db_api.TENANT.get_by_name(name=tenant).id
obj = db_models.UserRoleAssociation()... | 5,296,040 |
def get_domain_server_version(domain):
"""
Get the Server version based on the Server header for the web server.
"""
if domain.canonical.server_version is not None:
return domain.canonical.server_version
if domain.https.server_version is not None:
return domain.https.server_version
... | 5,296,041 |
def print_data(data_list):
"""
display the dork data searched by the user on the terminal,
if facet is specified, it will also be displayed
:param data_list: dork data , list
:param facet_data: facet data, list
:return:
"""
total = 0
# print title
printf("{:<25}{:<20}{:<20}{:<30}... | 5,296,042 |
def load_gan(path: Path, cuda: Union[bool, str] = False) -> ctgan.CTGANSynthesizer :
"""
Loads a ctgan model. Caches the models so that repeated models are
only loaded once
Parameters
----------
path : Path
Path to the file to load the model from.
cuda : bool or string
True i... | 5,296,043 |
def test_isobutane(pcff_assigner):
"""Test of atom-type assignment for isobutane"""
assert pcff_assigner.assign("CC(C)C") == [
"c3",
"c1",
"c3",
"c3",
"hc",
"hc",
"hc",
"hc",
"hc",
"hc",
"hc",
"hc",
"hc",
... | 5,296,044 |
def test_zero_one_accuracy(multilabel_result):
""" Test the zero-one loss evaluation metric function. """
y_pred, y_true = multilabel_result
assert zero_one_accuracy(y_pred, y_true) == tensor(1.0 - 0.75)
assert zero_one_accuracy(y_pred, y_true, sigmoid=True) == tensor(
1.0 - 0.75
)
asser... | 5,296,045 |
def convert_celsius_to_fahrenheit(temperature):
"""
Converts the temperature from degrees Celsius to degrees Fahrenheit.
:param temperature: The value to convert, which must be in degrees Celsius
:type temperature: int | long | decimal.Decimal
:return: The temperature in degrees Fahrenheit to three decimal places... | 5,296,046 |
def torify(x, size):
"""shift points to canonical torus domain
# Arguments
x: points to be shifted
size: torus size
# Result
points shifted to canonical torus domain
"""
rep_size = np.repeat(np.expand_dims(size,-1), x.shape[-1], -1)
return x - rep_size * np.floor( (x/rep_... | 5,296,047 |
def build_lst(a, b):
""" function to be folded over a list (with initial value `None`)
produces one of:
1. `None`
2. A single value
3. A list of all values
"""
if type(a) is list:
return a + [b]
elif a:
return [a, b]
else:
return b | 5,296,048 |
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
""" Encrypts a file using AES (CBC mode) with the
given key.
key:
The encryption key - a string that must be
either 16, 24 or 32 bytes long. Longer keys
are more secure.
in_filenam... | 5,296,049 |
def get_mean_at_row(dfs: List[pd.DataFrame], row: int, column: str) -> np.double:
"""
Return the mean value of a certain column among the given list of benchmark dataframes in a certain row
:param dfs: list of benchmark dataframes
:param row: index of the row to be selected
:param column: colum... | 5,296,050 |
def args_display(args):
"""
Display arguments set by user
:param args: arguments from parse_args
:param description: description to display
:return: None
"""
_args = list()
for key, value in list(vars(args).items()):
_format = ' %*s -> %*s'
if isinstance(value, bool):
... | 5,296,051 |
def deploy_map(map):
"""
Deploys the rendered tiles to s3.
"""
print 'Deploying map: ' + map
#command = 's3cmd put --recursive -P ' + PROJECT_DIRECTORY + 'tiles_' + map + '/rendered_tiles/ ' + S3_DIRECTORY_S3CMD
command = 'ivs3 --concurrency 32 -P ' + PROJECT_DIRECTORY + 'tiles_' + map + '/rend... | 5,296,052 |
def foo_1(x):
""" test
>>> foo_1(4)
2.0
"""
return x ** .5 | 5,296,053 |
def apply_attributes_docs(
model: Type[AnyPydanticModel], *, override_existing: bool = True
) -> None:
"""
Apply model attributes documentation in-place. Resulted docs are placed
inside :code:`field.schema.description` for *pydantic* model field.
:param model: any pydantic model
:param override_... | 5,296,054 |
def set_search_parser(parser: argparse.ArgumentParser) -> None:
"""Set arguments used by up and down
Args:
parser (argparse.ArgumentParser): ArgumentParser
"""
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"-t",
"--table",
help=textwr... | 5,296,055 |
def test_http_processor_response_action_record_error(sdc_builder, sdc_executor, http_client):
"""
Test when the http processor stage has the response action set up with the "Generate Error Record" option.
To test this we force the URL to be a not available so we get a 404 response from the mock http server.... | 5,296,056 |
def mouse_func(button, state, x, y):
"""mouse_func."""
global omx, omy, mx, my, mouse_down
omx = mx = x
omy = my = y
mouse_down[button] = (state == GLUT_DOWN) | 5,296,057 |
def add_extra_information(record=None, log_record={}):
"""
Adds extra useful information to logging
"""
if 'request' in log_record:
request = log_record['request']
del log_record['request']
for key, value in META_KEYS.items():
log_record[value] = request.META.get(key... | 5,296,058 |
def sentence_perplexity(model, sentence):
"""Compute sentence perplexity for trigrams"""
words = sentence.split()
num_words = len(words)
trigrams = ngrams(
words, 3,
pad_left=True,
pad_right=True,
left_pad_symbol=PADDING.left_pad_symbol,
right_pad_symbol=PADDING.r... | 5,296,059 |
def VectorEnv(
env_id: str, n_envs: int = 2, parallel: int = False, env_type: str = "gym",
) -> VecEnv:
"""
Chooses the kind of Vector Environment that is required
:param env_id: Gym environment to be vectorised
:param n_envs: Number of environments
:param parallel: True if we want environments... | 5,296,060 |
def requires_atoms():
"""A function requiring atoms to run"""
def func_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
molecule = args[0]
assert hasattr(args[0], 'n_atoms')
assert hasattr(args[0], 'atoms')
if molecule.atoms ... | 5,296,061 |
def acceptsArguments(method, numberOfArguments):
"""
Returns True if the given method will accept the given number of arguments:
method - the method to perform introspection on
numberOfArguments - the numberOfArguments
"""
if 'method' in method.__class__.__name__:
num... | 5,296,062 |
def key_change_callback(deck, key, state):
"""
This method is called when a physical key is pressed
:param deck: stream deck needed for the stream deck library
:param key: number of pressed key
:param state: state of key
"""
pass | 5,296,063 |
def reset_test_table(refill: bool = False):
"""Empty the test db table user1.testdb and maybe refill it with sample data
Args:
refill: Whether to fill the emptied table with sample data again
"""
with psycopg.connect(conninfo=CONNECTION_STRING) as conn:
with conn.cursor() as cursor:
... | 5,296,064 |
def string_match_classifier_from_yaml(f) -> StringMatchClassifier:
"""Build StringMatchClassifier from a yaml file. Yaml is much easier to edit
in real-world classifiers that often include 50+ lines
Example
-------
The YAML content
shopping:
- albert_heijn:
- AH ... | 5,296,065 |
def kl_multi_div(params_1, params_2):
"""Kullback-Leibler divergence for multivariate diagonal-covariance gaussians.
The divergence is defined as:
D( (mu_1, sig_1) || (mu_2, sig_2) )
= .5 * ( Spur(sig_2**(-1) * sig_1) + (mu_2 - mu_1).T * sig_2**(-1)
* (mu_2 - mu_1) - k + ln(det(sig_2) ... | 5,296,066 |
def setup_sources(test_dag):
"""Фикстура с подготовкой данных в GP для тестов"""
logging.info('TEST: Init source for tasks:')
hook = PostgresHook(test_dag.conn_id)
with closing(hook.get_conn()) as conn:
with closing(conn.cursor()) as cur:
logging.info('TEST: Create a source and fill ... | 5,296,067 |
def test_05 ():
"""Update to new raw pupil data.
"""
REPORT.Test ("\n -------------------\n UPDATES:")
importLatestRaw (_testyear) | 5,296,068 |
def _make_coco_images(df: pd.DataFrame, image_map: Dict) -> List:
"""makes images list for coco"""
df = copy.deepcopy(df)
df.drop_duplicates(subset=["image_id"], keep="first", inplace=True)
df = (
df[["image_id", "image_height", "image_width"]]
.copy()
.rename(columns={"image_id"... | 5,296,069 |
def LOG_ERROR( msg ):
"""
Log an error message
:param msg: Text to log
:type msg: str
"""
LOG_MSG( terminfo.TermColor.RED, "ERROR", msg, 3 )
_shared_globals.errors.append( msg ) | 5,296,070 |
def get_raw_data_from_file(imageset, i):
"""Use cbflib_adaptbx directly to access the raw data array rather than
through the imageset, in order to work for multi-panel detectors and other
situations where the format class modifies the raw array"""
from cbflib_adaptbx import uncompress
file_name = i... | 5,296,071 |
def print_dice_rolls(faces_count, rolls, zero_based=False, max_width=72, eyes="o "):
"""Pretty print all rolls using faces_count-sided di(c)e."""
# Set up some default values
die = Die(faces_count, eyes)
face_width = die.width
# Will try to collate output of multiple dice rolls into lines
# of... | 5,296,072 |
def _get_intpol(root, gridfile, freqpath=None):
"""
Extract interpolation settings.
Parameters
----------
root : Element
Element object of the whole xml inputfile
gridfile : str
Name of the inputted gridfile
freqpath : str or None
If fitting frequencies, we want to r... | 5,296,073 |
def teardown():
"""Tear down test fixture for all model tests."""
teardown_db() | 5,296,074 |
def is_trusted_idb(*args):
"""
is_trusted_idb() -> bool
Is the database considered as trusted?
"""
return _ida_loader.is_trusted_idb(*args) | 5,296,075 |
def broadcast_index(big_index, big_shape, shape, out_index):
"""
Convert an index into a position (see `index_to_position`),
when the index is from a broadcasted shape. In this case
it may be larger or with more dimensions than the `shape`
given. Additional dimensions may need to be mapped to 0 or
... | 5,296,076 |
def _restore_namedtuple_gt_255_fields(typename, fields, values):
"""Creates an namedtuple_gt_255_fields objects along based its __reduce__ description.
The __reduce__ protocol to support pickling requires:
- a callable method that returns the pickled object on restore
- a tuple of its arguments.
T... | 5,296,077 |
def range_(x: pd.Series, w: int = 0) -> pd.Series:
"""
Range of series over given window
:param x: series: timeseries
:param w: window: number of observations to use (defaults to length of series)
:return: timeseries of range
**Usage**
Returns the range of the series (max - min) over roll... | 5,296,078 |
def normal_ordered_ladder_term(term, coefficient, parity=-1):
"""Return a normal ordered FermionOperator or BosonOperator corresponding
to single term.
Args:
term (list or tuple): A sequence of tuples. The first element of each
tuple is an integer indicating the mode on which a fermion ... | 5,296,079 |
def test_setup():
""" Check that all required setup keys exist. """
setup_keys = ['data_set', 'instrument', 'grating', 'grid_selection', 'ld_model', 'plotting', 'report']
for key in setup_keys:
assert CONFIG_INI.has_option('setup', key) | 5,296,080 |
def findPams (seq, pam, strand, startDict, endSet):
""" return two values: dict with pos -> strand of PAM and set of end positions of PAMs
Makes sure to return only values with at least GUIDELEN bp left (if strand "+") or to the
right of the match (if strand "-")
If the PAM is cpf1, then this is inverse... | 5,296,081 |
def get_humidity(message):
"""Function that displays humidity information"""
bot.send_message(
message.chat.id,
f"Атмосферная влажность: {w.humidity}%"
) | 5,296,082 |
def form_02(request_data):
"""
Процедурный лист
"""
num_dir = json.loads(request_data["hosp_pk"])
ind_card = Napravleniya.objects.get(pk=num_dir)
patient_data = ind_card.client.get_data_individual()
if sys.platform == 'win32':
locale.setlocale(locale.LC_ALL, 'rus_rus')
else:
... | 5,296,083 |
def changeManagerStatus(userName, isManager):
"""
Make a user manager. Or demote a user from mamager position.
"""
db.session.query(userClass).filter(userClass.USERNAME == userName).update({userClass.IS_MANAGER: isManager})
db.session.commit() | 5,296,084 |
def decode_depthimg(depthimg):
"""
depthimg.shape should be (H,W,C) where H is height, W is width, C is RGB channel i.e. C=3
In each depth png file the top 8 bits of depth are packed into the green channel and the lower 8 bits into blue.
"""
r = depthimg[:, :, 0]
g = depthimg[:, :, 1].astype(np.... | 5,296,085 |
def self_att(tensor,
tensor_val=None,
mask=None,
mask_is_length=True,
logit_fn=None,
scale_dot=False,
normalizer=tf.nn.softmax,
tensors=None,
scope=None,
reuse=False):
"""Performs self attention.
Pe... | 5,296,086 |
def ogda_train(X, Y, priors=None):
"""Train a omoscedastic GDA classifier.
Parameters
----------
X : ndarray, shape (m, n)
training features.
Y : ndarray, shape (m,)
training labels with values in {0, ..., k - 1}.
priors : ndarray, shape (k,)
Prior probabilities for the ... | 5,296,087 |
def local_align(x, y, score=ScoreParam(10, -5, -7)):
"""Do a local alignment between x and y with the given scoring parameters.
We assume we are MAXIMIZING.
example:
>>>local_align("acgt", "cg", ScoreParam(gap=-5, match=10, mismatch=-5))
"""
# create a zero-filled matrix
A = make_matrix(l... | 5,296,088 |
def pytest_runtestloop(session):
"""Run mypy on collected MypyItems, then sort the output."""
mypy_items = {
os.path.abspath(str(item.fspath)): item
for item in session.items
if isinstance(item, MypyItem)
}
if mypy_items:
terminal = session.config.pluginmanager.getplugin... | 5,296,089 |
def sigma_ss_to_xx(self, e_cm):
"""
Cross section for mediator annihilations into DM.
"""
return sig_ss_to_xx(
e_cm,
self.mx,
self.ms,
self.gsxx,
self.gsff,
self.gsGG,
self.gsFF,
self.lam,
self.width_s,
self.vs,
) | 5,296,090 |
def track(headers, body):
"""
数据追踪,解决1金币问题
:param headers:
:param body:
:return:
"""
try:
url = 'https://mqqapi.reader.qq.com/log/v4/mqq/track'
timestamp = re.compile(r'"dis": (.*?),')
body = json.dumps(body)
body = re.sub(timestamp.findall(body)[0], str(
... | 5,296,091 |
def test_custom_credentials_not_in_v1_api_list(get, admin, organization):
"""
'Custom' credentials (those not managed by Tower) shouldn't be visible from
the V1 credentials API list
"""
credential_type = CredentialType(
kind='cloud',
name='MyCloud',
inputs = {
'fi... | 5,296,092 |
def global_handle_allocate(flags, size):
"""Allocate a specified number of bytes via a global handle.
Parameters:
:param size: The number of bytes to be allocated
.. note::
Can only be used with twain 1.x sources
"""
return _GlobalAlloc(flags, size) | 5,296,093 |
def match_difficulty(our_doc_filter: DocumentFilter, other_doc_filter: DocumentFilter,
mu_lst: Optional[List[str]] = None, sum_lst: Optional[List[str]] = None,
test: Optional[bool] = False) -> pd.DataFrame:
"""
Calculate the relative match difficulty based on player an... | 5,296,094 |
def delete_feedback(user_feedback_id):
""" Allows Admin to delete user feedback comments from the db """
# Checks if user is in session
if "user" in session:
# Checks if user is admin
if session["user"] == "admin".lower():
# Removes a specific feedback entry from the db
... | 5,296,095 |
def test_scan_id_persists_between_executions(
script_that_increments_and_returns_scan_id,
):
"""
The scan ID should be shared and persisted between process executions.
"""
manager = ProcessManager()
queue = multiprocessing.Queue()
run_args = ProcedureInput(queue)
pid = manager.create(
... | 5,296,096 |
def FormDis(dfr, num=5):
"""
Format and display num number of rows of dataframe dfr,
with float-type values in 2 decimals and yellow color.
"""
ftn = {"z":"{0:,.2f}"}
ftc = {"z":"green"}
for com in dfr.columns:
try:
one = dfr.loc[0,com]
if float(one):
... | 5,296,097 |
def test_roc_bin_edges_drop_intermediate(forecast_1d_long, observation_1d_long):
"""Test that drop_intermediate reduces probability_bins in xs.roc ."""
fp = np.clip(forecast_1d_long, 0, 1) # prob
ob = observation_1d_long > 0 # binary
# xs
txs_fpr, txs_tpr, txs_area = roc(
ob, fp, "continuo... | 5,296,098 |
def hash_transaction(transaction: Transaction) -> str:
"""
Generate a hash for the transaction to make them identifiable.
"""
data = transaction.data
payload = "%s:%s:%s:%s:%s" % (
data["date"],
data["applicant_name"],
data["purpose"],
data["amount"],
data.get... | 5,296,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.