content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def check_mca(config, should_be_mca, msg = None):
"""Checks that the configured account is an MCA or not based on the argument.
If it is not, it exits the program early."""
is_mca = 'isMCA' in config and config['isMCA']
if should_be_mca != is_mca:
if msg is not None:
print(msg)
else:
print... | 5,328,100 |
def ban_user(request, user):
"""Bans a given user."""
user = User.query.filter_by(username=user).first()
if user is None:
raise NotFound()
next = request.next_url or url_for('admin.bans')
if user.is_banned:
request.flash(_(u'The user is already banned.'))
return redirect(next... | 5,328,101 |
def lastDate():
"""[summary]
lastDate() function: return the total revenue of the nearest day
Returns:
[type]: [description]
"""
lastDate = totalDate().tail(1)
last_date = lastDate.iloc[0]['total'].round(2)
return last_date | 5,328,102 |
def processlingrarow(col, rows, pixelWidth, pixelHeight, xO, yO, plot, netcdffile, rsdir, becsmosdir):
"""
Launch a single pixel of processing for LingraRS
:param col: column in Grassland raster file
:param rows: total rows in Grassland raster file
:param data: Value of pixel in Grassland raster fil... | 5,328,103 |
def multitask_result(request):
"""多任务结果"""
task_id = request.GET.get('task_id')
task_obj = models.Task.objects.get(id=task_id)
results = list(task_obj.tasklog_set.values('id','status',
'host_user_bind__host__hostname',
'host_user_bind__ho... | 5,328,104 |
async def ctrl_handler(client, user, operation, payload, db):
"""
Handler for *Inspection Control* API
:param client: client that sent payload
:type client: websockets.WebSocketCommonProtocol
:param user: user that sent payload
:type user: ecusers.User
:param operation: operation specified ... | 5,328,105 |
def process_xpath_list(node, property_manifest: Dict):
"""
Return a list of values as a result of running a list of XPath
expressions against an input node
:param node: Input node
:param property_manifest: Manifest snippet of the property
:return: List of values
"""
def complement_xpath(... | 5,328,106 |
def collect_username_and_password(db: Session) -> UserCreate:
"""Collect username and password information and validate"""
username = get_username("Enter your username: ")
password = get_password("Enter your password: ")
verify_pass = get_password("Enter your password again: ")
if password != verif... | 5,328,107 |
def replace_header(input_df):
"""replace headers of the dataframe with first row of sheet"""
new_header = input_df.iloc[0]
input_df = input_df[1:]
input_df.columns=new_header
return input_df | 5,328,108 |
def verify():
"""
Manual verification of PSDs
"""
#update threshold
threshold= ui.threshEdit.text()
msg=subprocess.run(["python", os.path.join(script_dir,r"cli.py"), "verify", "--outlier_threshold", threshold])
if msg.returncode != 0:
ui.errorBrowser.setText(_translate("SA... | 5,328,109 |
def cartToRadiusSq(cartX, cartY):
"""Convert Cartesian coordinates into their corresponding radius squared."""
return cartX**2 + cartY**2 | 5,328,110 |
def unique_entity_id(entity):
"""
:param entity: django model
:return: unique token combining the model type and id for use in HTML
"""
return "%s-%s" % (type(entity).__name__, entity.id) | 5,328,111 |
def normalize_tuple(value, n, name):
"""Transforms a single int or iterable of ints into an int tuple.
# Arguments
value: The value to validate and convert. Could be an int, or any iterable
of ints.
n: The size of the tuple to be returned.
name: The name of the argument being ... | 5,328,112 |
def load_user(user_id):
"""
@login_manager.user_loader Passes in a user_id to this function and in return the
function queries the database and gets a user's id as a response...
"""
return User.query.get(int(user_id)) | 5,328,113 |
def triage(sc, BOT_ID, kcache):
"""
We read and triage all messages. Messages directed to the bot will
be triaged to the command handler. Otherwise, the output is parsed for
special events
"""
# special events - Karma up or down, or @bot; add
AT_BOT = '<@' + BOT_ID + '>'
que... | 5,328,114 |
def replaceall(table, a, b):
"""
Convenience function to replace all instances of `a` with `b` under all
fields. See also :func:`convertall`.
.. versionadded:: 0.5
"""
return convertall(table, {a: b}) | 5,328,115 |
def test_factory():
"""
test ontology factory using wikidata as source and using PTSD.
"""
f = OntologyFactory()
ont = f.create('wdq:Q544006')
for n in ont.nodes():
print('{} "{}"'.format(n,ont.label(n)))
qids = ont.search('anxiety%')
assert len(qids) > 0
print(qids)
nod... | 5,328,116 |
def get_job_metadata(ibs, jobid):
"""
Web call that returns the metadata of a job
CommandLine:
# Run Everything together
python -m wbia.web.job_engine --exec-get_job_metadata
# Start job queue in its own process
python -m wbia.web.job_engine job_engine_tester --bg
#... | 5,328,117 |
def create_learning_rate_scheduler(max_learn_rate, end_learn_rate, warmup_proportion, n_epochs):
"""Learning rate scheduler, that increases linearly within warmup epochs
then exponentially decreases to end_learn_rate.
Args:
max_learn_rate: Float. Maximum learning rate.
end_learn_rate: Float... | 5,328,118 |
def test_wrong_drm_controller_address(accelize_drm, conf_json, cred_json, async_handler):
"""Test when a wrong DRM Controller offset is given"""
async_cb = async_handler.create()
async_cb.reset()
driver = accelize_drm.pytest_fpga_driver[0]
ctrl_base_addr_backup = driver._drm_ctrl_base_addr
drive... | 5,328,119 |
def matchyness(section, option):
"""Assign numerical 'matchyness' value between target and value
Parameters:
section -- target value
option -- proposed match
"""
if section != option:
return _hc.NEQ
if isinstance(section, rt.flask_placeholder):
if isinstance(option, rt.flask_placeholder):
return _hc.PP ... | 5,328,120 |
def log_sum_exp_elem(*a):
"""
:param a: elements
:return: (a[0].exp() + a[1].exp() + ...).log()
"""
bias = max(a).detach()
ans = bias + sum([(ai-bias).exp() for ai in a]).log()
return ans | 5,328,121 |
def car_portrayal(agent):
"""Visualises the cars for the Mesa webserver
:return: Dictionary containing the settings of an agent"""
if agent is None:
return
portrayal = {}
# update portrayal characteristics for each CarAgent object
if isinstance(agent, CarAgent):
if agent.is_fro... | 5,328,122 |
def _load_spc_format_type_a(filepath: str):
"""load A(w,k) in the spc format type a
Args:
filepath (str): output filename
Returns:
np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray: kcrt, Awk, kdist, energy, kpath
"""
with open(filepath) as f:
lines = f.readlines()... | 5,328,123 |
def worker(full_img_list, start_idx, end_idx, kwargs):
"""
Worker process.
"""
print(f'Processing {start_idx}->{end_idx}')
# process each image between start_idx and end_idx
for img_idx in range(start_idx, end_idx):
img_fpath = full_img_list[img_idx]
print(f'Converting {img_idx}"th RGB to grayscale object c... | 5,328,124 |
def variable_to_json(var):
"""Converts a Variable object to dict/json struct"""
o = {}
o['x'] = var.x
o['y'] = var.y
o['name'] = var.name
return o | 5,328,125 |
def convNodeToProblems(graphList,vecGraphList,masterEncoder,genre=["C","V"],targetParams=CF.targetParams):
"""
graphList: list of graphs (before vectorization)
vecGraphList: list of vectorized graphs (of graphList)
masterEncoder: masterEncoder
genre: genre to make problems: C: compound , V: numeric... | 5,328,126 |
def merge_log_err(hass):
"""Patch _merge_log_error from packages."""
with mock.patch("homeassistant.config._LOGGER.error") as logerr:
yield logerr | 5,328,127 |
def create_white_edge_cost_image(t1_file, t2_file, gm_proba_file, out_file):
"""
This class represents a...
:param t1_file:
:param t2_file:
:param gm_proba_file:
:param out_file:
:return:
"""
import SimpleITK as sitk
import os
gm_proba = sitk.ReadImage(gm_proba_file)
ne... | 5,328,128 |
def moments_simps(n, x, y):
"""
"""
print("mu00 = ", simps(simps(n, x), y))
print("mu10 = ", simps(simps(x*n, x), y), " mu01 = ", simps(simps(y*n, y), x))
print("mu11 = ", simps(simps(x*n, x)*y, y))
print("mu20 = ", simps(simps(x*x*n, x), y)," mu02 = ", simps(simps(y*y*n, y),x))
print("mu21 = ", simps(sim... | 5,328,129 |
def check_and_train(opt, output_path):
""" Check if the experiments has already been performed.
If it is not, train otherwise retrieve the path relative to the experiment.
:param opt: Experiment instance. It contains the output path for the experiment
under study
:param output_path: the output path ... | 5,328,130 |
def getDewPoint(temp, humidity):
"""
A utility function to get the temperature to which an amount of air must be
cooled in order for water vapor to condense into water. This is only valid
for: 1) temperatures between 0C and 60C, 2) relative humidity between 1%
and 100%, and 3) dew points between 0C ... | 5,328,131 |
def get_result_handler(rc_value, sa_file=None):
"""Returns dict of result handler config. Backwards compatible for JSON input.
rc_value (str): Result config argument specified.
sa_file (str): SA path argument specified.
"""
try:
result_handler = json.loads(rc_value)
except json.decoder.... | 5,328,132 |
def onPacketFound(packet):
"""
Called by the scan function for each beacon packets found.
"""
data = bytearray.fromhex(packet)
if args.one:
tmp = packet[:-3]
if tmp in foundPackets:
return
foundPackets.add(tmp)
# Eddystone
if len(data) >= 20 and data[19... | 5,328,133 |
def speedup_experiment_ts(args, model_iter_fn, model, example_inputs):
"""
Measure baseline performance (without using TorchDynamo) of TorchScript and optimize_for_inference.
Writes to ./baseline_ts.csv
"""
return baselines(
[
("eager", model),
("ts", try_script(mode... | 5,328,134 |
def my_polyhedron_to_label(
rays: Rays_Base, dists: ArrayLike, points: ArrayLike, shape: Tuple[int, ...]
) -> npt.NDArray[np.int_]:
"""Convenience funtion to pass 1-d arrays to polyhedron_to_label."""
return polyhedron_to_label( # type: ignore [no-any-return]
np.expand_dims( # type: ignore [no-unt... | 5,328,135 |
def order_files_by_ranges(root_path: str, dest_path: str, date_ranges: list, *, save_unsorted: bool = True) -> list:
"""Copies all files (including subdirectories)
from given path to destination path
without any loss of data
and groups them into given subdirectories.
"""
t = tqdm(range(get_f... | 5,328,136 |
def scoreCard():
"""Score Card."""
for match in matches:
print(json.dumps(c.scorecard(match['id']),indent=4))
break | 5,328,137 |
def get_incident_comment(incident_comment_id: Optional[str] = None,
incident_id: Optional[str] = None,
operational_insights_resource_provider: Optional[str] = None,
resource_group_name: Optional[str] = None,
workspace_na... | 5,328,138 |
def getOrElseUpdate(dictionary, key, opr):
"""If given key is already in the dictionary, returns associated value.
Otherwise compute the value with opr, update the dictionary and return it.
None dictionary are ignored.
>>> d = dict()
>>> getOrElseUpdate(d, 1, lambda _: _ + 1)
2
>>> print(d)
{... | 5,328,139 |
def gs_norm(f, g, q):
"""
Compute the squared Gram-Schmidt norm of the NTRU matrix generated by f, g.
This matrix is [[g, - f], [G, - F]].
This algorithm is equivalent to line 9 of algorithm 5 (NTRUGen).
"""
sqnorm_fg = sqnorm([f, g])
ffgg = add(mul(f, adj(f)), mul(g, adj(g)))
Ft... | 5,328,140 |
def find_anomalous_scatterers(*args, **kwds):
"""
Wrapper for corresponding method in phaser.substructure, if phaser is
available and configured.
"""
if (not libtbx.env.has_module("phaser")):
if "log" in kwds:
print("Phaser not available", file=kwds["log"])
return None
from phaser import subst... | 5,328,141 |
def OpChr(ea, n):
"""
@param ea: linear address
@param n: number of operand
- 0 - the first operand
- 1 - the second, third and all other operands
- -1 - all operands
"""
return idaapi.op_chr(ea, n) | 5,328,142 |
def main(envs, cmd):
"""Run script and verify it exits 0."""
for env in envs:
key, val = env.split('=', 1)
print >>sys.stderr, '%s=%s' % (key, val)
os.environ[key] = val
if not cmd:
raise ValueError(cmd)
check(*cmd) | 5,328,143 |
def check_access(func):
"""
Check whether user is in policy owners group
"""
def inner(*args, **kwargs):
keycloak = get_keycloak()
if 'policy_id' in kwargs:
current_user = kwargs['user']
group_name = f'policy-{kwargs["policy_id"]}-owners'
group_list = ... | 5,328,144 |
def score_ranking(score_dict):
"""
用pandas实现分组排序
:param score_dict: dict {'591_sum_test_0601': 13.1, '591_b_tpg7': 13.1, '591_tdw_ltpg6': 14.14}
:return: DataFrame
pd.DataFrame([['591_sum_test_0601', 13.10, 2.0, 0.6667],
['591_b_tpg7', 13.10, 2.0, 0.6667],
['591_tdw_ltpg6', 14.14, 3.0, 1.0]]... | 5,328,145 |
def dock_widget(widget, label="DockWindow", area="right", floating=False):
"""Dock the given widget properly for both M2016 and 2017+."""
# convert widget to Qt if needed
if not issubclass(widget.__class__, QObject):
widget = utils.to_qwidget(widget)
# make sure our widget has a name
name =... | 5,328,146 |
def compute_benjamin_feir_index(bandwidth, steepness, water_depth, peak_wavenumber):
"""Compute Benjamin-Feir index (BFI) from bandwidth and steepness estimates.
Reference:
Serio, Marina, et al. “On the Computation of the Benjamin-Feir Index.”
Nuovo Cimento Della Societa Italiana Di Fisica C, ... | 5,328,147 |
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer ... | 5,328,148 |
def plaintext_property_map(name: str) -> Mapper:
"""
Arguments
---------
name : str
Name of the property.
Returns
-------
Mapper
Property map.
See Also
--------
property_map
"""
return property_map(
name,
python_to_api=plaintext_to_noti... | 5,328,149 |
def pooling_layer(net_input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1)):
"""
TensorFlow pooling layer
:param net_input: Input tensor
:param ksize: kernel size of pooling
:param strides: stride of pooling
:return: Tensor after pooling
"""
return tf.nn.max_pool(net_input, ksize=ksize, strid... | 5,328,150 |
def set_standard_attrs(da):
""" Add standard attributed to xarray DataArray"""
da.coords["lat"].attrs = OrderedDict(
[
("standard_name", "latitude"),
("units", "degrees_north"),
("axis", "Y"),
("long_name", "latitude"),
("out_name", "lat"),
... | 5,328,151 |
def find_git_repos(folder):
"""
Returns a list of all git repos within the given ancestor folder.
"""
return [root for root, subfolders, files
in os.walk(folder)
if '.git' in subfolders] | 5,328,152 |
def isnotebook():
"""
Utility function to detect if the code being run is within a jupyter
notebook. Useful to change progress indicators for example.
Returns
-------
isnotebook : bool
True if the function is being called inside a notebook, False otherwise.
"""
try:
shel... | 5,328,153 |
def test_insert_b_ansible_pho_link(monkeypatch):
"""
insert_b_ansible_pho_link()のテスト
"""
core = create_ita1core()
configs = get_configs()
comobj = ActionDriverCommonModules()
rand = 'aaaaa'
target_table = 'C_OPERATION_LIST'
ary_config = ''
insert_row_data = ''
operation_data... | 5,328,154 |
def geometric_anomaly_detection_grid_search(
model_dir: str,
model_name: str,
dataset_name: str,
vocab_size: int,
manifold_dimension: int,
search_size: int,
use_knn_annulus: bool,
min_annulus_parameter: float,
max_annulus_parameter: float,
search_params_max_diff: float,
use_r... | 5,328,155 |
def p_ExpressionNoIn(p):
"""ExpressionNoIn : AssignmentExpressionNoIn
| ExpressionNoIn ',' AssignmentExpressionNoIn"""
p[0] = "ExpressionNoIn"
p[0] = list(p) | 5,328,156 |
def get_poagraph(dagmaf: DAGMaf.DAGMaf,
fasta_provider: missings.FastaProvider,
metadata: Optional[msa.MetadataCSV]) -> \
Tuple[List[graph.Node], Dict[msa.SequenceID, graph.Sequence]]:
"""Gets poagraph from given dagmaf using fasta_provider and metadata.
Args:
... | 5,328,157 |
def const_bool(value):
"""Create an expression representing the given boolean value.
If value is not a boolean, it is converted to a boolean. So, for
instance, const_bool(1) is equivalent to const_bool(True).
"""
return ['constant', 'bool', ['{0}'.format(1 if value else 0)]] | 5,328,158 |
def long_to_bytes(n, blocksize=0):
"""Convert an integer to a byte string.
In Python 3.2+, use the native method instead::
>>> n.to_bytes(blocksize, 'big')
For instance::
>>> n = 80
>>> n.to_bytes(2, 'big')
b'\x00P'
If the optional :data:`blocksize` is provided and g... | 5,328,159 |
def vector_matrix_mul(v, M):
"""
returns the product of vector v and matrix M
Consider using brackets notation v[...] in your procedure
to access entries of the input vector. This avoids some sparsity bugs.
"""
assert M.D[0] == v.D
res = {k: 0 for k in M.D[1]}
for i, j in M.f:
... | 5,328,160 |
def peek(library, session, address, width):
"""Read an 8, 16 or 32-bit value from the specified address.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param width: Number of bits to read... | 5,328,161 |
def create_text_image(text, image_export=False, **kwargs):
"""
Create a jpg with given text and return in bytes format
"""
text_canvas_w = 720
text_canvas_h = 744
text_canvas_bg = 'white'
text_canvas_fg = 'black'
text_canvas_font_name = 'open_sans_emoji.ttf'
def load_font(size):
... | 5,328,162 |
async def send_message_to_exchange(rabbitmq_config: dict, queue_config: dict, message: dict) -> None:
"""
Send Messages to rabbit mq exchange. Don't use directly.
:param rabbitmq_config: dict config for rabbitmq instance config: {'host': '', 'port': '', 'username': '',
'password': ''}
:param queue_... | 5,328,163 |
def spacesToTabs(filename, spacesPerTab):
"""
Converts tabs to spaces in-place given a filename and a number of spaces per tab.
:param filename: str
:param spacesPerTab: int
"""
with open(filename) as inFile:
lines = inFile.readlines()
with open(filename, 'w') as outFile:
for line in lines:
numTabs = 0
... | 5,328,164 |
def mtf_from_psf(psf, dx=None):
"""Compute the MTF from a given PSF.
Parameters
----------
psf : `prysm.RichData` or `numpy.ndarray`
object with data property having 2D data containing the psf,
or the array itself
dx : `float`
sample spacing of the data
Returns
----... | 5,328,165 |
def check_intersection(vertical_line: Line, other_line: Line) -> bool:
"""
Check for intersection between two line segments.
:param vertical_line: The first line segment. Guaranteed to be vertical.
:param other_line: The second line segment.
:return: Whether or not they intersect.
"""
intersection = get... | 5,328,166 |
def get_session_info(config):
"""Gets information about the session (for --info)
Overwrites any existing manifest file.
Separated from print_session_info for ease of testing"""
from krun.scheduler import ManifestManager
from krun.platform import detect_platform
platform = detect_platform(None... | 5,328,167 |
def rotate(x, y, a):
"""Rotate vector (x, y) by an angle a."""
return x * np.cos(a) + y * np.sin(a), -x * np.sin(a) + y * np.cos(a) | 5,328,168 |
def cli(command, config_file):
"""command-line interface
Parameters
----------
command : string
One of {'prep', 'train', 'eval', 'predict', 'finetune', 'learncurve'}
config_file : str, Path
path to a config.toml file
"""
if command == 'prep':
prep(toml_path=config_fi... | 5,328,169 |
def call_and_exit(command, shell=True):
"""Call a shell command and exit if error
"""
code = call(command, shell=shell)
if code != 0:
exit(1) | 5,328,170 |
def test_disarm_wrong_mimetype(client):
"""Should return 415 if JSON is not used"""
result = client.simulate_delete(
"/api/v0/alarms",
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer 127d9a48-927a-43f3-a3e3-842f3f2b7393",
},... | 5,328,171 |
def main(
name: str,
vm_params_dict: dict,
outdir: Path,
logger: Logger = qclogging.get_basic_logger(),
):
"""
vm_params_dict loaded from vm_params.yaml doesn't have all info plot_vm() needs.
This function gathers and works out the necessary input (except SRF-relevant info) to run this file ... | 5,328,172 |
def filt_all(list_, func):
"""Like filter but reverse arguments and returns list"""
return [i for i in list_ if func(i)] | 5,328,173 |
def auth_user_logout(payload,
override_authdb_path=None,
raiseonfail=False,
config=None):
"""Logs out a user.
Deletes the session token from the session store. On the next request
(redirect from POST /auth/logout to GET /), the frontend will is... | 5,328,174 |
def rx_observer(on_next: NextHandler, on_error: ErrorHandler = default_error, on_completed: CompleteHandler = default_on_completed) -> Observer:
"""Return an observer.
The underlying implementation use an named tuple.
Args:
on_next (NextHandler): on_next handler which process items
on_erro... | 5,328,175 |
def _rav_setval_ ( self , value ) :
"""Assign the valeu for the variable
>>> var = ...
>>> var.value = 10
"""
value = float ( value )
self.setVal ( value )
return self.getVal() | 5,328,176 |
def set_annex_version(version):
"""Override the git-annex version.
This temporarily masks the git-annex version present in external_versions
and make AnnexRepo forget its cached version information.
"""
from datalad.support.annexrepo import AnnexRepo
ar_vers = AnnexRepo.git_annex_version
wi... | 5,328,177 |
def import_matrix_as_anndata(matrix_path, barcodes_path, genes_path):
"""Import a matrix as an Anndata object.
:param matrix_path: path to the matrix ec file
:type matrix_path: str
:param barcodes_path: path to the barcodes txt file
:type barcodes_path: str
:param genes_path: path to the genes ... | 5,328,178 |
def get_representations(dataset, pretrained_model, alphabet, batch_size=128):
"""Returns: N x 1280 numpy array"""
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
pretrained_model = pretrained_model.to(device)
dataloader = DataLoader(
dataset, batch_size=batch_size, shuffle... | 5,328,179 |
def test_init_empty_force_field(empty_force_field, attribute, value):
"""
Test that an empty force field has the expected attributes.
"""
assert getattr(empty_force_field, attribute) == value | 5,328,180 |
def rem_hap_cands():
"""json endpoint to set a sample or set of
sample's haplotype candidate designation to false"""
form = flask.request.form
samples = form['samples']
return mds.remove_hap_cands(samples) | 5,328,181 |
def construct_subdirExample(str_dirname):
"""
Método auxiliar para utilizarmos nosso exemplo.
Constrói um conjunto de Diretórios e arquivos
para serem testados.
DirOrigem/
|
├── dir01
│ ├── arq01.dat
│ ├── arq02.dat
│ ├── f001.txt
... | 5,328,182 |
def geojson_to_df(in_geojson, encoding="utf-8", drop_geometry=True):
"""Converts a GeoJSON object to a pandas DataFrame.
Args:
in_geojson (str | dict): The input GeoJSON file or dict.
encoding (str, optional): The encoding of the GeoJSON object. Defaults to "utf-8".
drop_geometry (bool,... | 5,328,183 |
def UndistortImage(image,image_size,\
image_rotation=None,image_center=None,\
out_xs=None,out_ys=None,\
direction='fwd',regenerate_grids=True,\
**kwargs):
"""Remember the recipe for fixin gwyddion image orientation: `image0=image0.T[:,:... | 5,328,184 |
def plot_scores(df, corpus, output_dir, eval):
"""Plots phone classification performance for each model in DataFrame. Plots F1 score by default"""
output_dir = Path(output_dir, corpus, eval)
os.makedirs(output_dir, exist_ok=True)
df_group = df.groupby("method")
for index, group in df_group:
... | 5,328,185 |
async def handle(output_cfg: dict, queue: asyncio.Queue, _metrics: statistics.Statistics, start_shutdown: asyncio.Event):
"""Connect to rabbit and push the messages from the queue"""
rabbitmq = RabbitMQ(output_cfg=output_cfg)
clogger.info("Output handler: rabbitmq: Enabled")
while not start_shutdo... | 5,328,186 |
def quartic_oscillator(grids, k=1.):
"""Potential of quantum quartic oscillator.
Args:
grids: numpy array of grid points for evaluating 1d potential.
(num_grids,)
k: strength constant for potential.
Returns:
vp: Potential on grid.
(num_grid,)
"""
vp = 0.5 * k * gr... | 5,328,187 |
def compute_row_similarities(A):
"""
Compute pairwise similarities between the rows of a binary sparse matrix.
Parameters
----------
A: scipy csr_matrix, shape (rows, cols)
Binary matrix.
Returns
-------
sim: numpy array, shape (rows, rows)
Pairwise column similarities.... | 5,328,188 |
def sha9(R, S):
"""Shape functions for a 4-noded quad element
Parameters
----------
x : float
x coordinate for a point within the element.
y : float
y coordinate for a point within the element.
Returns
-------
N : Numpy array
Array of interpolation functions.
Exa... | 5,328,189 |
def padding(seq, size, mode):
"""
Parameters
----------
seq: np.array
The sequence to be padded.
mode: str
Select padding mode among {"zero", "repeat"}.
Returns
-------
seq: np.ndarray
"""
if mode == "zero":
seq = np.array(trimmer(seq, size, fille... | 5,328,190 |
def get_dense_span_ends_from_starts(dense_span_starts,
dense_span_ends):
"""For every mention start positions finds the corresponding end position."""
seq_len = tf.shape(dense_span_starts)[0]
start_pos = tf.cast(tf.where(tf.equal(dense_span_starts, 1)), tf.int32)
end_pos = tf... | 5,328,191 |
def test_put_correct_existing(test_client, test_cases_positive, test_headers):
"""
GIVEN a Flask application configured for testing
WHEN the '/hello/<username>' page is requested (PUT) and there is such user already exists
THEN check that the response is valid and user updated
"""
data = {"dateO... | 5,328,192 |
def bb_to_plt_plot(x, y, w, h):
""" Converts a bounding box to parameters
for a plt.plot([..], [..])
for actual plotting with pyplot
"""
X = [x, x, x+w, x+w, x]
Y = [y, y+h, y+h, y, y]
return X, Y | 5,328,193 |
def handler404(request, *args):
"""
Renders 404 page.
:param request: the request object used
:type request: HttpRequest
"""
return render(request, '404.html', status=404) | 5,328,194 |
def test_regression():
"""Test a regression model saved with joblib"""
model_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'model-lr.pkl'))
# Load the model
if skversion > '0.23':
with raises(ValueError):
ScikitLearnModel.create_model(model_path, n_input_columns=2, ... | 5,328,195 |
def merge_dimensions(z, axis, sizes):
"""Merge dimensions of a tensor into one dimension. This operation is the opposite
of :func:`split_dimension`.
Args:
z (tensor): Tensor to merge.
axis (int): Axis to merge into.
sizes (iterable[int]): Sizes of dimensions to merge.
Returns:
... | 5,328,196 |
def get_assignment_map_replaced(init_ckpt,
name_replacement_dict={},
list_vars=None):
""" name_replacement_dict = { old_name_str_chunk: new_name_str_chunk }
"""
if list_vars is None:
list_vars = tf.global_variables()
#
name_to_v... | 5,328,197 |
def RULE110():
"""RULE 110 celular automata node.
.. code::
000 : 0
001 : 1
010 : 1
011 : 1
100 : 0
101 : 1
110 : 1
111 : 0
"""
return BooleanNode.from_output_list(outputs=[0,1,1,1,0,1,1,0], name="RULE 110") | 5,328,198 |
def _log_request(rpc_state, request):
"""
Writes a message with request into debug logs
:param rpc_state: An id of request
:param request: A received response
:return: None
"""
if logger.isEnabledFor(logging.DEBUG):
logger.debug("%s: request = { %s }", rpc_state, _message_to_string(r... | 5,328,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.