content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _context_license_spdx(context, value):
"""convert a given known spdx license to another one"""
# more values can be taken from from https://github.com/hughsie/\
# appstream-glib/blob/master/libappstream-builder/asb-package-rpm.c#L76
mapping = {
"Apache-1.1": "ASL 1.1",
"Apache-2.0... | 3ad3b91bf7db36a9be3751877e248ed481d1be71 | 3,615,548 |
def html_header():
"""
Global & common html header. SHould be used everywhere
Returns:
--------
out: str
"""
return """
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/finkstyle.css">
<title>Mon programme test</title>
</head>
<body>
... | 7d4a7571be9a269927ec29a0d38daa950f1404b6 | 3,615,549 |
def build_repository_type_select_field( trans, repository=None, name='repository_type' ):
"""Called from the Tool Shed to generate the current list of supported repository types."""
if repository:
selected_type = str( repository.type )
else:
selected_type = None
repository_type_select_fi... | eb0cc6085814d0d5390e842efe0f75c9694ee82c | 3,615,551 |
def get_boolean_value(file_location, section, key):
"""
Searches an INI Configuration file for a section & key and returns it as a string.
:param file_location: The file to get a key value from
:param section: The section to find the key value
:param key: The key that can contain a value to retriev... | 1c419a320e715f056310a6f6aac54b73f5d073da | 3,615,553 |
def net_connections(kind='inet'):
"""Return system-wide connections as a list of
(fd, family, type, laddr, raddr, status, pid) namedtuples.
In case of limited privileges 'fd' and 'pid' may be set to -1
and None respectively.
The 'kind' parameter filters for connections that fit the
following cri... | 75403d79b2964e868aa9fddaec7e8b1e655d87b1 | 3,615,554 |
def db_check():
"""
Performs a basic check on the database by performing a select query on a simple table
:return: True or False according to successful retrieval
"""
try:
HealthCheck.objects.get(health_check_field=True)
return HealthStatus.OK
except Exception as e:
captu... | 6a096621a9e6def7754a773ba13ad6af83894f48 | 3,615,555 |
import csv
def get_report(readings_file):
"""
Prepares a report and returns it as a string.
Report includes starting and ending readings,
amount consumed and cost of each utility,
as well as the total, how much if any was paid,
and the amount outstanding.
"""
with open(readings_file) ... | 1a460f3deed40c0ce32d80dcaa893c5297281b9b | 3,615,556 |
from typing import Dict
from typing import Tuple
from typing import List
def parse_template(template: WorkflowTemplate, arguments: Dict) -> Tuple[List[ContainerStep], Dict, List[str]]:
"""Parse a serial workflow template to extract workflow steps and output
files.
The expected schema of the workflow spec... | 89ae23f7e01f6c7802770c814a06339ed2e13eb8 | 3,615,557 |
def int_df_two_segments(int_df_one_segment) -> pd.DataFrame:
"""Generate dataframe with simple targets for lags check."""
df_1 = int_df_one_segment.reset_index()
df_2 = int_df_one_segment.reset_index()
df_1["segment"] = "segment_1"
df_2["segment"] = "segment_2"
df = pd.concat([df_1, df_2], ign... | 043d47a175a194692e66ff546eed73861741d7c7 | 3,615,558 |
import re
def get_user_agent(request):
"""
Checks if the given user agent string matches one of the valid user
agents.
"""
name = request.META.get('HTTP_USER_AGENT', None)
if not name:
return False
for platform, regex in settings.USER_AGENTS.iteritems():
if re.compile(regex... | c893000db1be1051c7ca74898b4f98d8ad47e9a1 | 3,615,559 |
def indent(element, level=0):
""" Indents an XML root object from ElementTree.
Parameters
----------
element : ElementTree.Element
The XML root object to manipulate and indent.
level : int, optional
I guess at which level of indentation it should start. Can be
ignored and u... | 1f0049077d567308aa8f4e8018846b1dd57f957e | 3,615,560 |
import torch
def train_collate_fn(batch):
"""
# collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果
"""
imgs, pids, _, _, = zip(*batch)
pids = torch.tensor(pids, dtype=torch.int64)
return torch.stack(imgs, dim=0), pids | 81f653acbf9c9643289416b70dcba08e002d2613 | 3,615,561 |
def level_4(f):
"""
Decorate routes to require level 4 previleges (Super Admin).
IMPORTANT: Place this decorator in after @login_required
Documentation here:
http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if session... | 0f44dfeae69b4b40998870ae96bd6f5c3a4708de | 3,615,562 |
def distance_to_border(logicarray, maxdist=65535):
"""
Returns the eucledian distance to the border of a binary logical array.
Positive distances mean distance to the next negative (false) pixel, negative distance
the distance to the next positive (true) pixel.
:logicarray a binary array
:maxdis... | f622720a616ba2a5193ecc3673c19938457fce57 | 3,615,563 |
def encrypt_string(enabled, string, config):
# type: (bool, str, dict) -> str
"""Encrypt a string
:param bool enabled: if encryption is enabled
:param str string: string to encrypt
:param dict config: configuration dict
:rtype: str
:return: encrypted string if enabled
"""
if enabled:... | df00b8ece08491ecbd0aecaedaabf43ea4850379 | 3,615,564 |
def split_data(X, y, problem_type, problem_configuration=None, test_size=.2, random_seed=0):
"""Splits data into train and test sets.
Arguments:
X (ww.DataTable, pd.DataFrame or np.ndarray): data of shape [n_samples, n_features]
y (ww.DataColumn, pd.Series, or np.ndarray): target data of length... | 37807727fae7cb6e8f1a57265b0a167f610f1e01 | 3,615,565 |
def eval_mode(cfg):
"""Runs the evaluation-only loop."""
if cfg.VIS_TEST:
assert cfg.USE_WANDB is True, "Visualizations use Wandb, therefore, it must be enabled"
trainer = CSDTrainerManager(cfg)
trainer.resume_or_load(resume=False)
res = trainer.test(cfg, trainer._trainer.model)
if com... | 1f03fdb7b4c641b07f5dc946fc9cba1daf9b54c6 | 3,615,566 |
import requests
def get_invites_for_account(account, timeout=5):
"""
Gets a users invites for any gsr groups.
Return invites along with details about the gsr group (color, name, group id)
"""
x_authorization = request.headers.get("X-Authorization")
authorization = request.headers.get("Authori... | ee1c4f9b18ec490627185e7b4956473250731ddf | 3,615,567 |
from datetime import datetime
async def format_tweak_page(ctx, entries, current_page, all_pages):
"""Formats the page for the tweak embed.
Parameters
----------
entries : List[dict]
"The list of dictionaries for each tweak"
all_pages : list
"All entries that we will eventually ite... | 86268ada306ecb0d6dcc4e63b7390e5cb0e74456 | 3,615,569 |
def _parse_opts():
"""Parse the command line options.
:param list argv: List of arguments to process. If not provided then will
use optparse default
:return: options,args where options is the list of specified options that
were parsed and args is whatever arguments are left after parsing al... | b76d44484c8c5af7aa93039f2aa4d689c8ae36bf | 3,615,570 |
def encode2(valeur,base):
""" float*int -->String avec 16 décimales
hypothèse : base maxi = 16
"""
chaine=""
for n in range (1,17) :
valeur=valeur*base
calcul = int(valeur)
if (calcul)>9:
if calcul==10:
bit='A'
if calcul==11:
... | a4f9a96a7f53f17ec9cc57a54df3db3ec7c9aac7 | 3,615,571 |
import re
def get_stacktrace(gdb_output):
"""Returns the stacktrace and the exit signal """
if not "#0" in gdb_output:
error("gdb output error")
stacktrace = Stacktrace()
# Get the exit Signal from the gdb-output
exit_signal = re.search(_exit_signal_re, gdb_output)
if exit_signal:
... | 0e9c32e793dda756451309b78f4308096df3eee7 | 3,615,572 |
def index():
"""
Basic index route.
"""
return {"msg": "Hi! This is an API by Mariia Sizova"} | 211f24da5736e57216f160db39af0590f8eb2c4f | 3,615,573 |
import torch
def pretty_size(size):
"""
Pretty prints a torch.Size object
By user machinethink: https://forums.fast.ai/t/gpu-memory-not-being-freed-after-training-is-over/10265/7
"""
assert(isinstance(size, torch.Size))
return " × ".join(map(str, size)) | 006ae05ce22653bfe58a5791aa5912de7283d9ca | 3,615,574 |
from re import T
from typing import Literal
def merge_rest_docs(
prnt_doc: T.Optional[str] = None,
child_doc: T.Optional[str] = None,
method: T.Union[Literal["merge"], Literal["replace"]] = "replace",
) -> str:
"""See custom_inherit.style_store.reST for details."""
prnt_sections = parse_rest_doc(p... | 9489df9890807fd87807cc71d4b63a53c76f80ef | 3,615,575 |
def get_recipe_intent_handler(request):
"""
You can insert arbitrary business logic code here
"""
return alexa.create_response(message="Hello stranger!") | 373568260c72903d2266a807bf12af58f110a6fb | 3,615,576 |
import re
def path_splitter(s, _d_match=re.compile(r"\.\d").match):
"""
Split a string into its path components.
Assumes a string is a path or is path-like.
Parameters
----------
s : str | pathlib.Path
Returns
-------
split : tuple
The path split by directory components ... | 531c94f1b05f840f07944a748983787fc8dff8bf | 3,615,577 |
from typing import Tuple
def convert_time(time: str, ampm: str) -> Tuple[int, int]:
"""Convert time given "HH:MM" to 24h format.
Args:
time (str): a time like "12:00" without ampm
ampm (str): either "am" or "pm"
Returns:
Tuple[int, int]: (hour, minute) in 24h time format
"""... | b1bd57ea92e82ba629e3ad2733f173dfcc805e9e | 3,615,578 |
def proportional_allocation_by_location_and_activity(df, sectorcolumn):
"""
Creates a proportional allocation within each aggregated sector within a location
:param df: df with sector columns
:param sectorcolumn: str, sector column for which to create allocation ratios
:return: df, with 'FlowAmountR... | f8cd293f04ae00703318437f4c4936a883f29e33 | 3,615,579 |
def Cov_bb_Das(Cb, α, A, β, B, γ, C, τ, D):
"""Compute analytic errorbars.
A, B, C, D correspond to frequencies,
α, β, γ, τ correspond to seasons
"""
N = 0.0
term0 = 2 * Cb**2 / nu_b
term1 = 0.0
term2 = 0.0
for i in range(n_d[0]):
for j in range(n_d[1]):
for k in... | cb2f608aab167728941050885c2322047f780caf | 3,615,580 |
def join_(table, on_str, **kwargs):
"""
join_(table='items', on_str='items.id=topic_item.item_id', status=1)
"""
join_str = ' JOIN `' + table + '` on ' + on_str
re_str, values = _rebuild_argv(kwargs, table=table)
return join_str, re_str, values | 8f054d9e1567d2bbea1a7f08acbd0f322755534a | 3,615,581 |
def optimize_glm(x, y, distri):
"""Apply Bayesian Optimization to select enet parameters."""
def function(alpha, reg_lambda):
return glm_train(alpha=alpha, reg_lambda=reg_lambda, x=x, y=y, distri=distri)
optimizer = BayesianOptimization(
f=function,
pbounds={"alpha": (1e-6, 1), "reg... | 1323eed2e2beba65194c32db96cb1d8d993b0c2e | 3,615,582 |
def project_duals(dual_vars, dual_types):
"""Projects dual variables to satisfy dual constraints."""
make_pos = lambda v: None if v is None else jnp.maximum(v, 0)
_project = lambda v, t: make_pos(v) if t == DualVarTypes.INEQUALITY else v
return jax.tree_multimap(_project, dual_vars, dual_types) | 14b4782d2cdda2998d18eca38ae3602b7b8f3744 | 3,615,584 |
def column_equality(series, col1, col2, comparison='equal', pos_return_val=1, neg_return_val=0):
"""
Apply to a dataframe row to return a binary feature depending on equality or inequality
E.g. df.apply(lambda s: column_match(s, 'day_of_week', 'day_of_sale'), axis=1) to for matching the two.
Result is ... | 9ec71f5fd3af4a8d89b4cd58a255065ec8352eb2 | 3,615,585 |
def SS_workflow(scope="function"):
"""SS_workflow.
Simple workflow including StartToStart dependency.
"""
task1 = BaseTask("task1")
task2 = BaseTask("task2")
task3 = BaseTask("task3")
task2.append_input_task(task1, task_dependency_mode=BaseTaskDependency.SS)
task3.append_input_task(task... | 14e130ae5fbdd8dd5d514d56aac27e9c297ba200 | 3,615,587 |
def removeStopwords(text):
"""Se eliminan palabras que carecen de significado
Args:
text: Texto del que se desea eliminar las palabras sin significado.
"""
stopw = nltk.corpus.stopwords.words('spanish')
stopw = stopw + ["juguete", "juguetes", "edad", "máxima", "recomendada", "incluye... | ed2ffe85765c6bbdc99ba5de78d789c25181caf9 | 3,615,588 |
import shutil
def delete_directory(path):
"""
Deletes a ticket attachments directory from disk
"""
path = '{}/{}'.format(settings.MEDIA_ROOT, path)
try:
shutil.rmtree(path)
return path
except:
logger.error('Error removing folder{}'.format(path))
return False | 2525a6a58dc01a2d8d958b8d506c7f387b22c5cc | 3,615,589 |
import math
def get_tile_from_lon_lat(lon: float, lat: float, zoom: int) -> tuple[int, int]:
"""
Turns a lon/lat measurement into a Slippy map tile at a given zoom.
"""
# Clamps lon, lat to proper mercator projection values
lat = min(lat, 85.0511)
lat = max(lat, -85.0511)
lon = min(lon, 1... | cdd542c8a362d54dccb8760278b22a17f5df57f9 | 3,615,590 |
def simpson_integral(f, a, b):
"""辛普森求积公式
"""
return (b - a) * (f(a) + 4 * f((a + b) / 2) + f(b)) / 6 | 572e7af1137ed0f7b6be12f2869a0aa5ba123f85 | 3,615,591 |
def api_subscribe_pull_request(repo, requestid, username=None, namespace=None):
"""
Subscribe to an pull-request
----------------------------
Allows someone to subscribe to or unsubscribe from the notifications
related to a pull-request.
::
POST /api/0/<repo>/pull-request/<request id>/... | f7a5cac4ae7c2b84ebd5da2e702356ef58da4ca3 | 3,615,592 |
def _group_lst(lst, n):
"""Split the lst into sublists of len n."""
return (lst[i : i + n] for i in range(0, len(lst), n)) | c609b16940718d128d62bae7c9e0d94c16207080 | 3,615,593 |
def get_cincinnati_channels(major, minor):
"""
:param major: Major for release
:param minor: Minor version for release.
:return: Returns the Cincinnati graph channels associated with a release
in promotion order (e.g. candidate -> stable)
"""
major = int(major)
minor = int(minor... | e57ad8d26ea0a397e8c3f9edc99174f78b506564 | 3,615,594 |
def translate_batch(exe,
src_words,
encoder,
enc_in_names,
enc_out_names,
decoder,
dec_in_names,
dec_out_names,
beam_size,
max_length,
... | 0cbb5c68b4289530c161e7aaa44c0c68d11518f4 | 3,615,595 |
from typing import Optional
from typing import Tuple
def load_audio(
file: str, sr: Optional[int], verbose=True, **kwargs
) -> Tuple[Tensor, AudioMetaData]:
"""Loads an audio file using torchaudio.
Args:
file (str): Path to an audio file.
sr (int): Optionally resample audio to specified t... | 9db58f1805120a3a24013d0625665fa90710b3d0 | 3,615,596 |
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return MetaConv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) | 6d02696846d31cf8dc14d03ed08c7375c7642849 | 3,615,597 |
def get_value(seq, index):
"""Get the value of a nested sequence using index.
"""
if index == ():
return seq
if isinstance(seq, Storage):
return seq[index]
assert isinstance(seq, (tuple, list)), type(seq)
value = seq
for i in index:
value = value[i]
return value | bd923ed372efb99fdbe80d7a443c62a9c9df6d84 | 3,615,598 |
import logging
import time
def indices_client():
"""Returns an Elasticsearch indices client that is responsive
to the environment variable ELASTICSEARCH_ENDPOINT"""
es_connected = False
while not es_connected:
try:
ES = Elasticsearch(
hosts=[HOSTNAME]
)
... | 22a625170dc42523c5747ce5f76da198d0a3a74a | 3,615,599 |
def simulate_step(octopus_map: OctopusMap) -> SimulationStep:
"""Perform a simulation step on octopus map returning updated map and flash count"""
om = deepcopy(octopus_map)
incremented = increment_energy_level(om)
return increment_flashes(incremented) | c6a94cb37a43d8f1b7d5e4b2523e1a4a3cf7cbc6 | 3,615,600 |
def categories_portlet_children(request, category):
"""Returns the children of the given category as HTML.
"""
categories = []
for child_category in category.category_set.all():
children = categories_portlet_children(request, child_category)
categories.append({
"id": child_ca... | cc3634fa34bc9d39b2a5f55c6aa22d4819e83136 | 3,615,601 |
from typing import Any
from datetime import datetime
async def queue_task(
*, name: str, arguments: dict[str, Any], run_at: datetime | None
) -> int:
"""
Schedule a task to run at the given time.
"""
return await db.fetchval(
"""
INSERT INTO task (name, arguments, run_at)
... | cf45fe2edd944226c1d8cd014e3c2f2238cbdecb | 3,615,602 |
import io
def create_kernel_from_image(image_path, padding=0):
"""Generates a float image from an image on the disk.
:param image_path: The path to the reference image
:type image_path: string
:param padding: How much to pad the float image (zero-padded), defaults to 0
:type padding: int, opt... | dbc0a36b9e728a437b206536ef209b8110219bce | 3,615,603 |
def segformer_b4_ade(pretrained=True, progress=True):
"""Create a SegFormer-B4 model for the ADE20K segmentation task.
"""
model = create_segformer_b4(num_classes=150)
if pretrained:
_load_pretrained_weights_(model, model_urls['ade']['segformer_b4'], progress=progress)
return model | 1ca38468ff0199e47c7812d26b86ccdeecc42948 | 3,615,604 |
def get_user_id(username: str) -> str:
"""This function gets the User ID from the database
Args:
username (str): Username to get his ID.
Returns:
user_id (str): The user id from the database.
"""
username = str(username)
if not check_user_existence(username):
save_user(... | f545050729f09f17a3bbe1f62c489f18bef8c658 | 3,615,605 |
def secondaryKeywordTest(lines):
"""
How many files get keywords if we limit them by frequency
"""
offset = 3
num = 8 # 3, 4, 5, 6, 7, 8, 9, 10
passNo = []
for i in range(num):
passNo.append(0)
for l in lines:
passed = []
for i in range(num):
passed.a... | 5610a3e0aaead46cea3f03b800423ea29f53d4c5 | 3,615,606 |
def newSplitter(
widget=None, orientation=None, verticalStretch=1, horizontalStretch=None, ori=None
):
"""
input: widget - the central widget
"""
if orientation is not None:
ori = orientation
ori = rectifyQtEnum('Orientation', ori, 'horiz')
splitter = QtWidgets.QSplitter(ori, widget)... | e6063c20bd9255df9f7ce9f0ca63bc3a140bb7a8 | 3,615,608 |
def lagrange_four_point(x, y0, y1, y2, y3):
"""The third order polynomial p(x) with p(-1)=y0, p(0)=y1, p(1)=y2, p(2)=y3."""
a2 = 3 * (y0 + y2 - y1 - y1)
a3 = 3 * (y1 - y2) + y3 - y0
a1 = -a3 + 3 * (y2 - y0)
return y1 + x * (a1 + x * (a2 + x * a3)) * 0.166666666666666666666666 | b60da1f8567c5b9babbc9e158b1444e30424bb1f | 3,615,609 |
def _format_error_message(error):
"""Returns formatted error message based on error type
:param error: cosmos error
:type error: dict
:returns: formatted error
:rtype: str
"""
if error.get("type") == "AmbiguousAppId":
helper = (".\nPlease use --app-id to specify the ID of the app "
... | d449e4fdf09a99e918ab5566d8a602d491266b57 | 3,615,610 |
import torch
def add_randn(x_input, vat_noise):
"""
add normal noise to the input
"""
epsilon = torch.FloatTensor(torch.randn(size=x_input.size())).to(device)
return x_input + vat_noise * epsilon * torch.abs(x_input) | dc8ae9055bd6bd06f0fcc8197c73dc154df30b30 | 3,615,611 |
from typing import Sequence
import yaml
def load(configs: Sequence[str], **kwargs):
"""
Load and join configurations from yaml and kwargs
"""
if not configs and not kwargs:
raise irtm.IRTMError("no configuration provided")
as_path = partial(helper.path, exists=True, message="loading {p... | e43c9b35abf06a1d76b99eca38a826f3b0e7b205 | 3,615,612 |
def capitalize_tag_kv(service: str) -> bool:
"""
Returns true or false depending on if the boto3 service
name needs the key & value values capitalized
"""
return service in ("ec2", "iam", "ssm") | 7a6f16be26fa684f6e906c5f8c5d0a3f87f95b63 | 3,615,613 |
from pathlib import Path
from typing import Optional
from typing import List
async def get_schedule_timespans(
scenario: schemas.ScenarioID = Path(..., description="The id of the scenario to get data for"),
feeders: Optional[List[str]] = Query(
None, description="The feeders for which the asset data s... | d397bd3b2c9a01b865879b1930e50247f402d546 | 3,615,615 |
def compile_ticker_list(csv_file):
"""
The method reads a .csv file and searches for a column within said csv file
with the name "ticker_symbols" via the pandas data library ".read_csv" method.
If this column is found, the method iterates over each row and extracts each
ticker symbol. Each ticker sy... | bcae15bfd35df428d0c80296cd307af29dc50ec1 | 3,615,616 |
import resource
def health():
"""Our instance health. If queue is too long or we use too much mem,
return 500. Monitor might reboot us for this."""
is_bad_state = False
msg = "Ok"
stats = resource.getrusage(resource.RUSAGE_SELF)
mem = stats.ru_maxrss
if mem > 1024**3:
is_bad_stat... | 98570ba02d6e2438ab2be797c7d2c5862d8dabb9 | 3,615,617 |
def create_default_fake_spikes():
"""Return the default spike times and labels."""
spikes = np.arange(10)
labels = np.array((1, 1, 1, 1, 1, 2, 2, 2, 2, 2))
return spikes, labels | f541acfdf279b0627da26c24e02cdaf57c75a8a9 | 3,615,618 |
def valid_arguments(valip, valch, valc, valii):
"""
Valid the arguments
"""
bvalid = True
# Type converssion
valch = int(valch)
valii = int(valii)
# Valid the parameters
# Valid - IP
if valip == "":
print("IP is invalid.")
bvalid = False
# Valid - Channel
... | 68c39d1f6570236d8dc12eb23d225de3255edd82 | 3,615,619 |
def max_brightness() -> int:
"""Get maximum brightness value using sysfs.
Read the maximum brightness value from the corresponding file in sysfs.
Returns
-------
int
Maximum brightness value.
"""
path = SYS_DIR + GRAPHICS_CARD + MAX_BRIGHTNESS_FILE
return __read_file_as_int(pa... | 7f3e193566f362203caf6d4f650cee724665739e | 3,615,620 |
def init_label_matrix(y):
"""
:param y: numpy array, shape = (n_nodes,) -1 for the unlabeled data, 0,1,2.. for the labeled data
:return:
"""
y = y.reshape(-1)
labels = list(np.unique(y))
if -1 in labels:
labels.remove(-1)
n_nodes = y.shape[0]
Y = np.ones((n_nodes, len(label... | 1ec9a77adfb6bfda957917f0327e0e6ff911cacc | 3,615,622 |
def fuse_masses(mass1, mass2):
"""
Fuses two probability masses
:returns
"""
# Convert to masses
both_masses = pd.DataFrame({"m1": mass1, "m2": mass2})
# Fuse masses
both_masses["fused"] = both_masses.apply(
lambda row: row["m1"].combine_conjunctive(row["m2"], importance_samplin... | cc38e1ed11535b19b2fcbd70d4430d4eaf875198 | 3,615,623 |
def get_D_inv(adj):
"""Missing docs.
Args:
adj: adjacent matrix.
"""
rowsum = np.array(adj.sum(1))
d_inv = np.power(rowsum, -1).flatten()
d_inv[np.isinf(d_inv)] = 0.0
d_mat_inv = sp.diags(d_inv)
return d_mat_inv | e9597cb9185d72342a56570868114bd73cee94bd | 3,615,624 |
import uuid
def create_filename(prefix='', ext=''):
"""
Create a unique filename.
:param str prefix: Prefix to add to filename.
:param str ext: Extension to append to filename, e.g. 'jpg'
:return: Unique filename.
:rtype: str
"""
suffix = '.' + ext if ext else ''
return prefix + s... | 30cedc7bdcf3fdbf202b8a0d26e64bd6f865094d | 3,615,625 |
def StressngCustomStressorsValidator(stressors):
"""Returns whether or not the list of custom stressors is valid."""
valid_stressors = {
'affinity', 'af-alg', 'aio', 'aio-linux', 'apparmor', 'bigheap', 'brk',
'bsearch', 'cache', 'chdir', 'chmod', 'clock', 'clone', 'context', 'cpu',
'cpu-online', '... | 7563d0a8829aa323e53ff807540cdf281b7df883 | 3,615,626 |
from typing import Dict
import traceback
def route(function_name: str, data: Dict) -> Dict:
"""Route the call to a specific function
Args:
ctx: Invoke context. This is passed by Fn to the function
data: Data passed to the function by the user
Returns:
Response: Fn FDK response obj... | 1af948fcff8e2fd7bcd1080aa51cad0437406e90 | 3,615,627 |
def TDataXtd_Geometry_GetID(*args):
"""
* Returns the GUID for geometry attributes.
:rtype: Standard_GUID
"""
return _TDataXtd.TDataXtd_Geometry_GetID(*args) | 3646fc3f053d1a7f5e15fc4c08caa7994a76c69e | 3,615,629 |
def get_its(hparams):
"""Get number of training and validation iterations
"""
# These run for a fixed amount of time. As anchored batch is smaller, we've actually seen fewer examples
train_its = int(np.ceil(hparams.n_train / hparams.n_batch_train))
test_its = int(np.ceil(hparams.n_test / hparams.n_b... | 6abd333927a0c4a6eed3961befe4399a082f176e | 3,615,631 |
def getSentenceList(row, field):
""" return list of sentences from doc object field;
each item will be token span """
return list(row[field].sents) | ecaa1159e6a9390ef2aa310741aae4a58105b8a9 | 3,615,632 |
def diz_oi():
"""Uma função simples que retorna 'oi'"""
return 'oi' | 8210dde23e06d0f475be9aef6113216dc096dbe3 | 3,615,633 |
def dashboard(request):
"""Mock dashboard view"""
return HttpResponse('dashboard') | eaa0b61f4db65429f5ae2918e1d43ffc4fd7ede9 | 3,615,634 |
def std_secao_filter(secao_list):
"""
Takes a words list from a secao filter and standardize the words to the
same pattern as the one used to download the articles' URLs:
extra -> e and suplemento -> a.
"""
return [str(s).lower().replace('extra','e').replace('suplemento','a') for s in secao_lis... | 6c5b1a52bec02078cd8c0e1dc35c97420a424936 | 3,615,635 |
def SecondsDistribution(name):
"""Returns a metric handle for a cumulative distribution named |name|.
The distribution handle returned by this method is better suited than the
default one for recording handling times, in seconds.
This metric handle has bucketing that is optimized for time intervals
(in seco... | f08bc7f88f7e74f1a4f601b59caf6421790cc9e1 | 3,615,636 |
import math
def predict(testlist):
"""Prepare the model input data type
paramters:
testlist: list,[[[u'T'], [u':'],...]
return result_sequences: list,
"""
feature_names, sep, vocs, max_len, use_char_feature, word_len = load_parameters()
data_dict = init_data( feature_names=feature... | e4063fea1862a9d7445a6f0c62ace8128c72b2f3 | 3,615,637 |
def orbit_nearest_point(pos, vel, pos_obs, vel_obs):
"""
Computes the closes value of an orbit to a given 3d point.
Parameters:
-----------
pos : numpy.array
orbits positions
vel : numpy.array
orbits velocities
pos_obs : numpy.array
orbital point
vel_obs : nu... | f995dcc69014df2ca483fa5227697cebf8c1b828 | 3,615,638 |
import sqlite3
def create_connection(db_file):
"""Create a database connection to the SQLite database specified by db_file
:param db_file: database file
:return: connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
... | c51079503993cb6cf690fae71748f53b4d30bf69 | 3,615,639 |
def more_than_one_5(number=''):
""" Returns True if there is more than one 5 based numeral (ex: VV) """
prev = ''
repetitions = 0
for letter in number:
if prev == letter and letter in FIVE_BASED:
repetitions += 1
else:
repetitions = 0
if repetitions >= 1:
... | e702f4d8bc92a3db4b31dcab6e79b5a597d7b292 | 3,615,640 |
def bert():
"""bert"""
if request.method == 'POST':
s = request.get_json()['string']
data_type = request.get_json()['type']
print("s is {}".format(s))
print("type is {}".format(data_type))
poem = generate(s, data_type)
return poem | 98547e63e046ba5b7f6ed0ab8098c9b8e34bac01 | 3,615,641 |
def get_pronoun(mode, number, person, conjugated_verb):
"""Return a string with the pronoun to be used depending of the parameters"""
pronoun = ""
if mode == "Gérondif":
pronoun = "en "
elif mode == "Subjonctif":
if number == "s":
if person == "1":
if conjugat... | f905f6755e8a990ff4ff0b1be4246a14c934eb0a | 3,615,642 |
import asyncio
import aiohttp
async def post_async(
endpoints: list[str],
payloads: list[bytes],
max_concurrent_requests: int = 5,
max_retries: int = 5,
headers: dict = None,
) -> list[tuple[str, bytes]]:
"""Given a list of HTTP endpoints and a list of payloads,
make HTTP POST requests asy... | 3ff3f6174dcff1a8a33da66c73016e65302a7274 | 3,615,644 |
def element_volume(domain, element, elevation):
"""
Calculates the volume of water contained an element with a given sea
surface elevation at each of the nodes.
:param domain: :class:`~polyadcirc.run_framework.domain`
:param element: list of nodes defining an element
:type element: array_like ... | d1658844122c213a0bceb8b135152353bbb3b9d3 | 3,615,645 |
def mapsApplyToField(function, field, mapSets,inside):
"""mapSets defines a set of polygons. This procedure fills the areas in the field are enclosed
by each polygon with the average value within that area
"""
if (GridUtil.isTimeSequence(field)):
newData = field.clone()
for timeStep in ... | b5dbca040b7542c71a06340592282664095fab65 | 3,615,646 |
def poison_graph(graph, venomous_path, config):
"""
Poisons a graph
Function args:
graph -- the graph
venomous_path -- the path from which the poison originates
config -- routing configuration
"""
return PoisonedGraph(graph, venomous_path, config.poison_max_distance,... | ab4cd2a24d453e29fd1c2ef6ebbaccfe09a6f7eb | 3,615,648 |
def generate_timestamp_metadata(release_filename, version,
expiration_date, compressions=()):
"""
<Purpose>
Generate the timestamp metadata object. The 'release.txt' file must exist.
<Arguments>
release_filename:
The required filename of the release metadata file.
... | 4eed549b899cdb42cdd69e657737fbb6ecb00b94 | 3,615,649 |
import math
def gamma_axial_quark(m_med, g_q=0.25):
"""Function to calculate quark width of an axial vector mediator
:param m_med: mediator mass
:type m_med: float
:param g_q: quark coupling, defaults to 0.25
:type g_q: float, optional
"""
gamma = 0
for m_q in m_quarks:
if(m_m... | c9ae31a26feedbe2fedef22cb0f986cc5df6b58d | 3,615,650 |
def should_we_show_version(args: Namespace) -> bool:
"""Should we show version or not?."""
return args.version if args.version is not None else False | e6cbf17c3655826cc9b2f03d3b294cda3fa5f97c | 3,615,651 |
async def sample(sectype, population, k):
"""List of k uniformly random secret elements chosen from population.
Choices are made without replacement.
Given population may contain public and/or secret elements.
If the population contains repeats, then each occurrence is a
possible selection in the... | 6cc1ca8764e351b8d0d5cc2957533e32a858afcd | 3,615,652 |
def _fetch_fixture(f):
"""Fetch dataset (download if missing and requested by environment)."""
download_if_missing = environ.get("SKLEARN_SKIP_NETWORK_TESTS", "1") == "0"
@wraps(f)
def wrapped(*args, **kwargs):
kwargs["download_if_missing"] = download_if_missing
try:
return ... | f11a0e55ab790558ea5dab234abad900705fbd2f | 3,615,653 |
def var_calcs(filenm, varnm, plev, latlon=(-90, 90, 40, 120)):
"""Process a single variable from a single day."""
lat1, lat2, lon1, lon2 = latlon
if varnm == 'DUDP':
nm, dp = 'U', True
elif varnm == 'DOMEGADP':
nm, dp = 'OMEGA', True
else:
nm, dp = varnm, False
with xray.... | c38130040455756f51c004235c47cf5a9310c4a7 | 3,615,654 |
import warnings
def _apply_lines(
self, *args,
stack=None, stacked=None,
negpos=False, negcolor=None, poscolor=None,
color=None, colors=None,
linestyle=None, linestyles=None,
lw=None, linewidth=None, linewidths=None,
**kwargs
):
"""
Apply hlines or vlines command. Support default "... | edcf80edef917d06b6e1c83185261c7422bb6434 | 3,615,655 |
import six
def detector_format_version(address, timestamp):
"""The detector_format_version() function returns a format version
string appropriate for the detector whose address is given by @p
address at the time @p time.
@param address Full data source address of the DAQ device
@param time Time of the e... | 02c94a8b4d2f1e2daf66434f39926944ea932129 | 3,615,656 |
from typing import get_type_hints
def configs() -> st.SearchStrategy[isort.Config]:
"""Generate arbitrary Config objects."""
skip = {
"line_ending",
"sections",
"known_standard_library",
"known_future_library",
"known_third_party",
"known_first_party",
"... | a9c7c0f9b1c03adc19ccde28093f3c1048f8ddd3 | 3,615,657 |
def distribution_score(probs: th.Tensor, nb_samples: int, split_factor: float) -> float:
"""
Get the score of the distribution. Used to find the best cell factory parameters.
O(p, n) = H_n(p) / L(n, T), where
- H_n(p) is the entropy ratio with the uniform distribution: -sum_i p_i*log(p_i)/log(n)
- ... | 02440d8f472a4d1e031727031a62c02619685b24 | 3,615,660 |
import base64
import hashlib
def verify_signature(
public_key: ecdsa.VerifyingKey, signature_base64: str, message: str
):
"""
Verifies the given bas64-encoded signature with the base64-encoded public
key and serialized message. The message should not contain any whitespaces.
Raises ValidationErro... | 0a134ae76f0a6f0acf0006a66b55ec824656a847 | 3,615,661 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.