content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def get_activity(model, env, device, num_trial=1000):
"""Get activity of equal-length trials"""
trial_list = list()
activity_list = list()
for i in range(num_trial):
env.new_trial()
ob = env.ob
ob = ob[:, np.newaxis, :] # Add batch axis
inputs = torch.fro... | 30da8a83c6ffd96a2c61f1a90fcc245b107da291 | 3,598,720 |
def mobilenetv3_100(pretrained=False, **kwargs):
""" Constructs a MobileNet-V3 100 (depth_multiplier == 1.0) model
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet-1K
"""
if pretrained and 'bn_eps' not in kwargs:
# pretrained model trained with non-default BN ep... | f6a3d4f16c73b6e1dd2556c57da400c41c092b26 | 3,598,721 |
from datetime import datetime
def register():
"""Output message if something goes wrong..."""
msg = ''
''' # Check if "username", "password" and "email" POST requests exist (user submitted form)'''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form and 'email' in... | fe155d768b4be1b89d68c709a2ed43bbc528352e | 3,598,722 |
def down_conv(
in_channels: int, out_channels: int, kernel_size: int, stride: int, padding: int
) -> nn.Module:
"""Down convolutions."""
return nn.Sequential(
nn.Conv2d(
in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding
),
nn.GroupNorm(num... | 8023f584feaa3322de17922b01734f4ed4267c42 | 3,598,723 |
from typing import Union
def test_get_request_kwargs_method():
"""
Test that get_request_kwargs can manipulate the method.
"""
class MethodManipulatingAPI(HTTPEater):
request_cls = Model
response_cls = Model
url = 'http://example.com/'
def get_request_kwargs(self, requ... | fe70565004c63ea991c50017ac0a138fe23e4e76 | 3,598,724 |
def handle_label(label, **kwargs):
"""
Given a label, return a label without the multiple
flags/etc
:param label:
:param kwargs:
:return:
"""
# --1) Start by handling the asterisk-indicated noisy labels.
new_label = label
if new_label.startswith('*'):
if getbool(kwargs,... | 1c858f80cd8cdcbdf76ceb22463348d01459f033 | 3,598,725 |
def sol_rad_from_sun_hours(daylight_hours, sunshine_hours, et_rad):
"""
Calculate incoming solar (or shortwave) radiation, *Rs* (radiation hitting
a horizontal plane after scattering by the atmosphere) from relative
sunshine duration.
If measured radiation data are not available this method is prefe... | 86b57eee15d486b4acfe87bf518e5077cfd38c97 | 3,598,726 |
def sort_libraries(libraries):
"""Sort libraries according to their necessary include order"""
for i in range(len(libraries)):
for j in range(i, len(libraries)):
if libraries[i].depends_on(libraries[j]) or libraries[i].has_addon_for(libraries[j]):
tmp = libraries[i]
... | 81187aaeb1879d8de4b23d0adae6547739f6a327 | 3,598,727 |
def verify_password(password: str, hashed_password: str) -> bool:
"""Verify that password matches with a hashed one.
Args:
password (str): A plain password.
hashed_password (str): A hashed password.
Returns:
bool: True if passwords match and False otherwise.
"""
return pwd_... | 3e4e1354ffaf4955c7d88ce63e2bb0461a52783d | 3,598,728 |
def svd(tensor, full_matrices=False, compute_uv=True, name=None):
"""Computes the singular value decompositions of one or more matrices.
Computes the SVD of each inner matrix in `tensor` such that
`tensor[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * transpose(v[..., :,
:])`
```prettyprint
# a is a ten... | 79f3523ba8297e45d5ac3d315f3be2ae9e0dddd9 | 3,598,729 |
def get_all_inputs(
manifest,
only_inputs_with_default_values = False,
return_inputs_to_update_states = True,
return_inputs_to_calculate_outputs = True,
return_inputs_to_reset_states = True
):
"""
Return a key-value structure containing the inputs t... | 97695df60c188ddf757159dc459debe939f6cb80 | 3,598,730 |
def variable(value, dtype=None, name=None):
"""Instantiates a variable and returns it.
# Arguments
value: Numpy array, initial value of the tensor.
dtype: Tensor type.
name: Optional name string for the tensor.
# Returns
A variable instance (with Keras metadata included).
... | f7395ecd89c2916ad42245606e222162d4d71b0b | 3,598,731 |
import builtins
import binascii
def base64_urlsafe_decode(encoded):
"""
Decodes URL-safe base64-encoded bytes into raw bytes.
:param encoded:
Base-64 encoded representation.
:returns:
Raw bytes.
"""
if not builtins.is_bytes(encoded):
raise TypeError("argument must be bytes: got %r" %
... | 6089e0e5510136d0afa2408e8854692b98fd4abf | 3,598,732 |
def melt(self, id_vars, value_vars, var_name="variable", value_name="value", data_type="str"):
"""
Convert DataFrame from wide to long format.
:param self:
:param id_vars:
:param value_vars:
:param var_name: column name for vars
:param value_name: column name for values
:param data_type:... | 50f586044988efc1290be2f043219c9af43f74d5 | 3,598,734 |
import torch
def get_diff_kernel_3x3():
"""
Utility function that returns a sobel kernel of 3x3
"""
return torch.tensor([
[-0., 0., 0.],
[-1., 0., 1.],
[-0., 0., 0.],
]) | 6fdfe2837fc8bab120298aec4246e2a7f4f0378c | 3,598,735 |
def calculate_vif_(X, thresh=6.0):
"""
Args:
X input N*D where N is number of datasets, D is number of variables
Returns:
X N*M where M is total number of useful variables
"""
variables = list(range(X.shape[1]))
dropped = True
while dropped:
dropped = False
vi... | c173da424780df4a90cf6930fd2e0b27ef52d584 | 3,598,736 |
def hamming(g1,g2,cutoff=1):
"""
Compare two genotypes and determine if they are within cutoff sequence
differences of one another.
Parameters
----------
g1, g2 : strs
two genotypes to compare (must be same length)
cutoff : int
max allowable sequence differences between them... | 24a180c68545fc1cbd0887bf2bee38cbfe6034e0 | 3,598,737 |
def get_log_with_log_prefixes(log, parameters=None):
"""
Gets an extended log that contains, in order, all the prefixes for a case of the original log
Parameters
--------------
log
Original log
parameters
Possible parameters of the algorithm
Returns
-------------
al... | a5d6fda61e1c04a9a672dd8a62be58d1e733ba2d | 3,598,738 |
def discriminator(x_init, do_inorm=False, scope='discriminator'):
"""Image discriminator from SPADE paper."""
# code from https://github.com/taki0112/SPADE-Tensorflow/
def lrelu(x, alpha=0.01):
return tf.nn.leaky_relu(x, alpha)
def instance_norm(x, scope='instance_norm'):
if do_inorm:
return tf... | 635791de11508fccf6a012eb2b73ee7475a0bfca | 3,598,739 |
def divide_feature(in_feature, out_features, min_unit=8):
""" Divides in_feature relative to each of the provided out_features.
The division of the input feature will be in multiplies of "min_unit".
The algorithm makes sure that equal output features will get the same portion of the input feature.
The ... | eb6b09fac96106349d87d947d34e3c220bdef05d | 3,598,740 |
def linear_angle(list_xyz_0, list_xyz):
"""For each pair of points on an idetical sphere the function
allows us to obtain the flat angle between them"""
cos_a = sum(list_xyz_0*list_xyz)
return np.arccos(cos_a) | 92040b078e772130a8bdff5d366f73ea0d056a77 | 3,598,741 |
from typing import Type
from typing import Union
def _find_index_in_list(pipeline: list, element: Type[DefaultIP]) \
-> Union[int, tuple]:
"""Return the index of the element in the pipeline"""
for i, v in enumerate(pipeline):
if isinstance(v, list):
for ii, vv in enumerate(v):
... | 788d061dc44d409d74c27d196971c95e50621a87 | 3,598,743 |
def get_diff_episodes(packages, local):
"""return the difference between the folder of packages and local"""
result = []
packages = get_ep_size_tuple(packages)
for package in packages:
episode = package[0]
size = int(package[1])
if episode in local:
local_size = int(l... | 511316407a1707cdcaed7467dd79d9110cf9292b | 3,598,744 |
def task_build():
"""Build the documentation.
The documentation will be converted to HTML files to help double-check
syntax and formatting on PyPI and on GitHub. Note that the HTML files
will not be included in the distribution files.
"""
return {
'actions': [
'rst2html.py ... | f0d0d3d88abc326d78b3f7dcabc655df34d5eb7f | 3,598,745 |
import errno
def _render_file(file, request):
"""
Begin sending the contents of this L{File} (or a subset of the
contents, based on the 'range' header) to the given request.
"""
file.restat(False)
if file.type is None:
file.type, file.encoding = getTypeAndEncoding(file.basename(),
... | 860fc3235c84c93adb579436ced39437388bfb47 | 3,598,746 |
def loaded(text):
"""
Returns:
(list | dict | str | float | int | datetime.datetime): Deserialized object
"""
try:
return load_string(text)
except ParseError as e:
return str(e) | 917c7325781896f931b0b1053ee719814ee90cc5 | 3,598,747 |
def kld(p, p_hat, eps=None):
"""Computes the Kullback-Leibler divergence between the two prevalence distributions.
Kullback-Leibler divergence between two prevalence distributions :math:`p` and :math:`\\hat{p}` is computed as
:math:`KLD(p,\\hat{p})=D_{KL}(p||\\hat{p})=\\sum_{y\\in \\mathcal{Y}} p(y)\\log\... | 8636b20a63370a9d40878d8b6c85c072c1a2c9a8 | 3,598,748 |
def __dtw_backtracking(steps, step_sizes_sigma, subseq, start=None): # pragma: no cover
"""Backtrack optimal warping path.
Uses the saved step sizes from the cost accumulation
step to backtrack the index pairs for an optimal
warping path.
Parameters
----------
steps : np.ndarray [shape=(... | e22a25f7d9e02aeb9413a7f9b39401f7628848e8 | 3,598,749 |
from typing import List
def _read_build_events(path: str) -> List[bes_pb2.BuildEvent]:
"""Parses build events from a file referenced by a given `path`.
The file should contain serialized length-delimited`bes_pb2.BuildEvent`
messages. See
https://docs.bazel.build/versions/master/build-event-protocol.html#cons... | 36b962b06986faa6305ae8f974d9b0758a3d85da | 3,598,751 |
def detect_markers(gray, expected_id):
"""Detect and return corners with the correct ID."""
d_corners, d_ids, _ = aruco.detectMarkers(gray,
Pose.aruco_dict,
parameters=Pose.aruco_params,
... | 00ef39cc8183161de9aaf44720451012e3eb0c49 | 3,598,752 |
def isglobalelement(domains):
""" Check whether all domains are negations."""
for domain in domains.split(","):
if domain and not domain.startswith("~"):
return False
return True | 36fd185722c55ae6e3ecd4729bb873f122322c34 | 3,598,753 |
def deviceaction():
# WARNING
# NOT USED ANYMORE
""" Turn on / Turn off device from the Dashboard
Example : PUT -d '{hub_id: 123abc, port: 10, is_on: True}'
:return 200
"""
return jsonify("Soon"), 404 | 1265280b9bc25ea3a6ef4c2a3469828c8064eed2 | 3,598,754 |
import numpy
def approximate_dependencies(lhs_set, rhs, df, accuracy, masks):
"""
Checks whether the columns represented in lhs_set functionally determines the column rhs
for the dataframe df.
If lhs_set --> rhs, returns True. Otherwise returns False.
*in order to be a dependency:
- the n... | 01d60ff073dca7bc6197dd9d405eba6372e9e33b | 3,598,755 |
def intensity_at(x: float, y: float) -> float:
"""
Return the shadow intensity (0.0-1.0) at some point on the canvas.
24.0 = one tile, but any float position (not just ints) is
supported, so you can scale to arbitrary resolutions.
"""
TILE = 24
TOP_WIDTH = 14
TOP_INNER_INTENSITY = 0.8
... | 9ba0500ffec2b8018872f5810a594db934114f9e | 3,598,756 |
import torch
def extract_bboxes(mask):
"""Compute bounding boxes from masks.
mask: [height, width]. Mask pixels are either 1 or 0.
Returns: bbox array (y1, x1, y2, x2).
"""
# Bounding box.
horizontal_indicies = torch.where(torch.any(mask, dim=0))[0]
vertical_indicies = torch.where(torch.an... | f634b6cfca16cf06da07f194c701920187f4d3e7 | 3,598,757 |
def collision_detected(p1, p2, map, map_width):
"""
Test if two nodes are separated by an obstacle by tracing a line between them
p1: the point (as list containing x and y values) from which the check starts
p2: the point (as list containing x and y values) at which the check ends
map: the map containing free... | f91bdad22ebf586069075477f0c2c29328ed3544 | 3,598,758 |
import pymel.core.general
def toPyNode(res):
# type: (Optional[str]) -> Optional[pymel.core.general.PyNode]
"""
returns a PyNode object
Parameters
----------
res : Optional[str]
Returns
-------
Optional[pymel.core.general.PyNode]
"""
if res is not None and res != '':
... | bc5fc4ea156a59c0105a266577d07b77a4d61b79 | 3,598,759 |
def strip_domain_address(ip_address):
"""Return the address or address/netmask from a route domain address.
When an address is retrieved from the BIG-IP that has a route domain
it contains a %<number> in it. We need to strip that out so we are
just dealing with an IP address or IP address/mask.
E... | adf566580249d00b660e108cabcf99892a44d32b | 3,598,760 |
def get_event(current_user, event_id):
"""
Return a user event with the supplied user Id.
:param current_user: User
:param event_id: Event Id
:return:
"""
try:
int(event_id)
except ValueError:
return response('failed', 'Please provide a valid Event Id', 400)
else:
... | b4e293518c15a9bec3561971ff7f97a604bb661d | 3,598,762 |
def predict_error_covariance(gyro_prev, z_prev, T, P, sigma_gyro):
"""
Predict the covariance matrix from the data we have
"""
Q = get_prediction_covariance(z_prev, T, sigma_gyro) # Prediction covariance matrix
return (np.identity(3) - T*skew(gyro_prev)).dot(P).dot((np.identity(3) - T*skew(gyro_prev)).T) + Q | 17dccfcfa4b2b287de2d5a975ff773207c0a570f | 3,598,763 |
def part_b(puzzle_input):
"""
Calculate the answer for part_b.
Args:
puzzle_input (list): Formatted as the provided input from the website.
Returns:
string: The answer for part_b.
"""
points = parse(puzzle_input)
time = 0
for _ in range(100_000):
min_x = min(po... | bee9210842823fe9a9837dc632db96e45edfbf01 | 3,598,764 |
def _count_samples(filenames):
"""Count samples based on a list of GeoTIFFs. Return an error if the
number of samples is not equal across the files.
"""
n_samples_list = []
for fname in filenames:
with rasterio.open(fname) as src:
n_samples_list.append(src.width * src.height)
... | fb96e6929794584108e4cd1307c8308c55e98fd8 | 3,598,765 |
import operator
def get_worst_placed_node(arr, graph):
"""находит такую вершину графа, которая имеет наибольшее количество смежных вершин с таким же цветом"""
scores_dict = {}
# считает кол-во смежных вершин с таким же цветом
for edge in graph.edges:
if arr[edge.start] == arr[edge.end]:
... | e23cbc6906294d4fc82584870579c57ebf3b793f | 3,598,767 |
from datetime import datetime
def m_get_date_to_now_days(seq):
"""
:param seq: 日期字符串
:return: 距离现在的天数
"""
try:
seq = datetime.strptime(seq, "%Y-%m-%d")
except:
seq = datetime.strptime(seq, "%Y-%m-%d %H:%M:%S")
seq = (datetime.now() - seq).days
return seq | 53b168c9d0e95d379b8639dea951367d55c5db4a | 3,598,769 |
from pathlib import Path
import sqlite3
def select_all(database_path: Path) -> t.List[t.Dict[str, t.Any]]:
"""
Выбрать всех работников.
"""
conn = sqlite3.connect(database_path)
cursor = conn.cursor()
cursor.execute(
"""
SELECT workers.worker_name, posts.post_title, workers.wo... | 433c94885974e04815f8f0af4b46cc4267a41ae6 | 3,598,770 |
def _wait_for_job(job_id):
""" Wait for a job submitted to the ModelSEED app service to end.
Parameters
----------
job_id : str
ID of submitted job
Returns
-------
dict
Task structure with status of job
Raises
------
JobError
When a job with the specifi... | 563e3221ca15cda926ff30a0b4c65a7324c1157c | 3,598,771 |
def lowest_eigenvalues(H, neig):
"""Compute the lowest eigenstates of the Hamiltonian H.
Arguments:
----------
neig -- An integer denoting the number of lowest energy eigenstates
to compute, or a list of numbers denoting the eigenstates
to select (e.g. [0, 3, 5] for the grou... | 6752d733e00991054e602e94c18a5c82b636f471 | 3,598,772 |
def apply_operator_to_bra(latex_dict: dict) -> str:
"""
given
x = \\langle\\psi_{\\alpha}| \\hat{A} |\\psi_{\\beta}\\rangle
return
x = \\langle\\psi_{\\alpha}| a_{\\alpha} |\psi_{\\beta} \\rangle
>>> latex_dict = {}
>>> latex_dict['input'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}... | d9d74830ae1b19c3ce044738ae5445a77106ac5f | 3,598,773 |
def get_orders() -> pd.DataFrame:
"""List your current open orders. Only open or un-settled orders are returned. [Source: Coinbase]
Example response from API:
.. code-block:: json
{
"id": "d0c5340b-6d6c-49d9-b567-48c4bfca13d2",
"price": "0.10000000",
"size": "0... | bf27b336c7767a9b8a7ecafbed65146f56ab261f | 3,598,774 |
def accuracy(nonclass_attr_vals, actual_binary, predicted_binary, prot_index, unprot_index):
"""Returns the accuracy for each input row.
Parameters
----------
nonclass_attr_vals : 2D array-like
Input attributes (X). Does not include sensitive attributes.
actual_binary : 1D array-like<binary... | eb7c1a48b044c83718793bf21da78a0bdc639a09 | 3,598,775 |
def inventreeInstanceName():
""" Returns the InstanceName settings for the current database """
return common.models.InvenTreeSetting.get_setting("INVENTREE_INSTANCE", "") | 662834f52916f9f35f1f8716d5deb5fed1e399cf | 3,598,777 |
def deleteDDrawMob(mob):
"""
Convenience function for deleting the transform from the given [MObject] shape node.
So we do not leave any stray nodes.
:param mob: [MObject] the shape from which to find the transform and delete it
:return: [bool] Wheter we deleted something or not
"""
if not m... | d714848598508af3a23e17039f64a9ad728e3032 | 3,598,779 |
import jinja2
def build_network_settings(**settings):
"""
Build the global network script.
CLI Example:
.. code-block:: bash
salt '*' ip.build_network_settings <settings>
"""
# Read current configuration and store default values
current_network_settings = _parse_suse_config(_SUS... | c8a7228ca3aac80b94ead942a2b70ceebc2b34f1 | 3,598,780 |
def address(idn, schema, style):
"""
get url of entity specified by idn in given schema and style
"""
if schema not in SCHEMA:
print("schema not supported!")
print("choose out of:")
for s in SCHEMA:
print("\t\t", s)
return None
# case: json (jsonld), txt (... | 9a57bc722c52bc1e9c764d475cb21cd790ac50cf | 3,598,781 |
import logging
def fragmentAndFingerprint(suppl, mols, fps, descriptor, fragmentMethod='hac', outputFragment=False, quiet=False):
"""
Fragment the molecule if it has multiple fragments and generate fingerprints on the fragment.
:param suppl: MolSupplier from which to read the molecules
:param mols: L... | 50cba4cd672dbf6970a1e70aaa405c082c63c585 | 3,598,782 |
from typing import Optional
def get_encryption_scope(name: Optional[str] = None,
storage_account_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEncryptionScopeResult:
"""
Use this data source to access information about a... | 1264253db923199dcc22d1773858622b68dad30d | 3,598,783 |
def verify_card_factors(bc_app, name, id_no, card_no=None, mobile=None):
"""
verify bank card factors
:param bc_app: beecloud.entity.BCApp
:param name: id card name
:param id_no: id card number
:param card_no: bank card number
:param mobile: mobile bind to bank card
:return:
"""
... | 3aff0409059f585dfed2da3196bad33e221f6650 | 3,598,784 |
def metric_to_ips(d, min_depth, max_depth):
"""
Args:
d: metric depth [min_depth, max_depth]
min_dpeth: in meter
max_depth: in meter
Returns:
"""
# d = d.clamp(min_depth, max_depth)
return (max_depth * d - max_depth * min_depth) / ((max_depth - min_depth) * d) | 20820265cf0500b47c308ee0730afc07c1d98906 | 3,598,785 |
from typing import Union
from pathlib import Path
from typing import List
def read_nwp_transit_line_attributes(nwp_fp: Union[str, Path], *, attributes: Union[str, List[str]] = None,
**kwargs) -> pd.DataFrame:
"""A function to read transit line attributes from a Network Package... | 55527b2ff88be8fa086adc90a5a9f6b9ee81cd68 | 3,598,786 |
def get_github_location(package_json_obj):
"""Get the GitHub project location for this npm package.
Sample strings:
https://github.com/blockchain/my-wallet-v3.git
https://github.com/cryptocoinjs/bigi
git://github.com/nickmerwin/node-coveralls.git
git+https://github.com/rvagg/learnyounode.git
... | 40f268dae4813a191548819d80ab7479518ae3a1 | 3,598,787 |
from typing import List
def athlete_sort(k: int, arr: List[List[int]]) -> List[List[int]]:
"""
>>> athlete_sort(1, [[10, 2, 5], [7, 1, 0], [9, 9, 9],
... [1, 23, 12], [6, 5, 9]])
[[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]]
"""
arr.sort(key=lambda x: x[k])
return arr | 1655882b7760a705afcbbeba55f5051eaf7d448f | 3,598,788 |
def custom_app_registry(request):
"""Put custom Django apps into the context."""
custom_apps = settings.CUSTOM_DJANGO_APPS.copy()
custom_apps = [enhance_custom_app_config(app) for app in custom_apps
if (getattr(app, 'enabled', None) is None or
app.enabled(request)
... | 8283216bd282bd5415614e8465158fa49f1ea331 | 3,598,789 |
def get():
"""Get DB connector"""
return dataset.connect(settings.DATABASE_URI, row_type=stuf) | 704c50ca8db10dcf15559135f82923efbcd7a574 | 3,598,790 |
def locProts(df, thresh=.75):
"""
removes entries with localiatoin probabiliy below threshold
@params
@df :: dataframe to be filtered
@thresh :: threshold of localization probability
"""
if "Localization prob" not in df.columns:
print("This dataframe has no 'Localization prob' column... | c90f8f1e24a291dd2dd66293d3e74f2de1eb2314 | 3,598,791 |
import json
def measurement():
""" Queries the local device for stats details
Returns: HTTPResponse 200 with a json containing the stats info.
HTTP Response 400 if there is an error reading the stats.
"""
try:
data = statsE16()
response = json.dumps(data, indent=4, sort_keys=True)... | e871314bcde40cedd8c1a17533db4899d4180bce | 3,598,792 |
def start_active_span(
operation_name,
child_of=None,
references=None,
tags=None,
start_time=None,
ignore_active_span=False,
finish_on_close=True,
):
"""Starts an active opentracing span. Note, the scope doesn't become active
until it has been entered, however, the span starts from t... | 88851cda070bba153f569753864f64a8f52a6588 | 3,598,793 |
def quadratic_interpolation(df: pd.DataFrame, key: Real) -> Real:
"""Quadratic interpolation, from Lagrange
Will prioritize taking 2 values before the keys and 1 after.
The `pd.DataFrame` needs at least 3 rows.
"""
assert len(df) >= 3, "The DataFrame needs at least 3 rows"
lower, upper = _spli... | 25dfa683bc0afdd92db274dad86cca6620c665da | 3,598,794 |
def reviewPreProcess(text):
"""
Takes Pandas series as input,
consisting of one review as
text string per row
"""
# lemmatized_sentence_corpus generator loops over original review text, segments the reviews into individual sentences
# and normalizes text. Writes data to new file with one nor... | ef489a24aa183f242f8a6dd82067c9aae749c46e | 3,598,795 |
def mixup_ot1d(batch1,batch2,sups1,sups2,alpha=0.75,K=5):
"""
Returns the mixup of two batches using 1d Optimal Transport
to return the barycentres of the label distributions.
Parameters
-----------
batch1 : array n x m (x co-ordinates)
batch2 : array n x m (x co-ordinates)
sup1: list size n (containing arra... | 8211cf9e18913673e6510d44fcc2a5bb78666037 | 3,598,796 |
def convert_to_corners(bounding_boxes, format):
"""Converts bounding_boxes to corners format.
Converts bounding boxes from the provided format to corners format, which is:
`[left, top, right, bottom]`.
args:
format: one of "coco" or "yolo". The formats are as follows-
coco=[x_min... | b93db95d16353db3cbe58b5c920b0de038295f60 | 3,598,797 |
def image_annotation_all_done(image):
"""
Return True if all of the image's annotation points are human annotated.
Return False otherwise.
Don't use image.annoinfo.confirmed. That field depends
on this function, not the other way around!
"""
annotations = Annotation.objects.filter(image=ima... | 16a72f1c32a8e3ac09dd7a651e59ae4a496d5b6d | 3,598,799 |
def find_connected_nodes(graph, connection):
"""List nodes connected to specified node."""
return [node for node in graph if find_path(graph, node, connection)] | 058f86fb01e4e94160772bfdc8bbb330be4e9f8a | 3,598,800 |
def is_non_stop_flight(flight_id):
"""
_nonstop(x)
:entity_type flight_id
"""
processed_flight_id, entity_type = process_entity_string(flight_id, "flight_id")
sql = 'SELECT flight.flight_id FROM flight WHERE flight.stops = 0 AND flight.flight_id = %s' % (
processed_flight_id)
results... | 6a70058547952e6bfb21c805e90b2cb9d973db38 | 3,598,802 |
from glob import glob
from numpy import sort
import six
def _ensure_mfdataset_filenames(fname):
"""Checks if grib or nemsio data
Parameters
----------
fname : string or list of strings
Description of parameter `fname`.
Returns
-------
type
Description of returned object.
... | 1764cf93a766bfd646578bdc5d5cb83585072d4f | 3,598,803 |
def part2(puzzle, dist_limit=10000):
""" Solve part 2 """
coords = parse(puzzle)
def total_dist(p):
return sum(manhattan_dist(p, c) for c in coords)
def in_bounds(p):
return total_dist(p) < dist_limit
median = (lesser_median(p[0] for p in coords), lesser_median(p[1] for p in coord... | 71d1a44ff4135a236371a5e65da21d72825d8d37 | 3,598,804 |
def check_oplog(con, warning, critical, perf_data):
""" Checking the oplog time - the time of the log currntly saved in the oplog collection
defaults:
critical 4 hours
warning 24 hours
those can be changed as usual with -C and -W parameters"""
warning = warning or 24
critical = criti... | 7615347c96ce723b2208b95034b41e45d84f53d4 | 3,598,805 |
def get_meeting_aggregates(meeting_data):
"""
Aggregates the attendance counts and lines said for users across
a meeting category
"""
meeting_aggregate = {}
for meeting_name in meeting_data.keys():
meeting_users = {}
for meeting in meeting_data[meeting_name]:
for user... | b135016b05fc20ae0fa9dfc40d11cc51ffc7a8d0 | 3,598,806 |
import types
import itertools
import tqdm
def load_records(fp_in, slice_idxs=None, media_record_type=types.MediaRecord.SHA256, verbose=False):
"""Loads JSON or Pickle mapping data based on file extension
:param fp_in: (str) of serialized items
:param mapping: enum of ItemMappingType
:returns: (dict) of mapped... | be5f2e96525d391e3d8196d6220224daffb4b5fb | 3,598,807 |
def generate_regnet(w_a, w_0, w_m, d, q=8):
"""Generates per block ws from RegNet parameters."""
assert w_a >= 0 and w_0 > 0 and w_m > 1 and w_0 % q == 0
ws_cont = np.arange(d) * w_a + w_0
ks = np.round(np.log(ws_cont / w_0) / np.log(w_m))
ws = w_0 * np.power(w_m, ks)
ws = np.round(np.divide(ws,... | 2c4d6862c66ee202350f220a1c5949582e7fdc6a | 3,598,808 |
def subsample_epsdelta(eps,delta,prob):
"""
:param eps: privacy loss eps of the base mechanism
:param delta: privacy loss delta of the base mechanism
:param prob: subsampling probability
:return: Amplified eps and delta
This result applies to both subsampling with replacement and Poisson subsam... | 4a7e994ced04dc6de1fe1f9f1d910e75726be1c1 | 3,598,809 |
def list_to_group_count(input_list):
"""
List to item occurrences count dictionary
"""
group_count = {}
for input_item in input_list:
if input_item in group_count:
group_count[input_item] = group_count[input_item] + 1
else:
group_count[input_item] = 1
ret... | bc6714d2d0b8872e29089eb0d142517c4ef63154 | 3,598,811 |
def get_tstat_limit(stats, fdr=0.01):
"""
Function to get tval_s0 at the specified FDR.
"""
t_limit = np.min(stats[stats.fdr<=fdr].t_cut)
return(t_limit) | 4f6a0b1a6a0e67116ccf0c24f84d18743d14f048 | 3,598,812 |
def single_term(points, i):
"""Return one term of an interpolated polynomial.
Arguments:
- points: a list of (float, float)
- i: an integer indexing a specific point
"""
theTerm = Polynomial([1.])
xi, yi = points[i]
for j, p in enumerate(points):
if j == i:
cont... | 5cf3ddf2a6ebb752c75570f5c944d7285b900806 | 3,598,813 |
from typing import Tuple
def draw_text(
np_image: ImageType, pos: Tuple[int, int], text: str, color: Tuple[int, int, int], font_scale: float = 0.4
) -> ImageType:
"""
Draw text on an image.
:param np_image: image as np.ndarray
:param pos: x, y; the position of the text
:param text: text strin... | a1e9d852969729ec42375f5bba3537ba802cde8d | 3,598,815 |
from typing import Union
from typing import Tuple
def error_middleware(
*,
default_handler: Handler = default_error_handler,
config: Config = None,
ignore_exceptions: Union[ExceptionType, Tuple[ExceptionType, ...]] = None
) -> Middleware:
"""Middleware to handle exceptions in aiohttp applications.... | 09431c9e7552cf340b28298d8008bd3907fd02b2 | 3,598,816 |
def rk4(derivs, y0, t, *args, **kwargs):
"""
Integrate 1D or ND system of ODEs using 4-th order Runge-Kutta.
This is a toy implementation which may be useful if you find
yourself stranded on a system w/o scipy. Otherwise use
:func:`scipy.integrate`.
Args:
derivs: the derivative of the s... | 2e7648747e702ae10d1644e606db08ea7e31899c | 3,598,817 |
def get_home_dir_path(filename):
"""Resolve a filename in the user's home dir"""
return abspath(join(expanduser('~'), filename)) | 3831874fc020a41ef1fb6af792a22ff93e33ea86 | 3,598,818 |
def merge_results(rates_array, weights_array):
""" Merges rates by weights.
Parameters
----------
rates_array : List[reaction_rates.ReactionRates]
The reaction rates for each substep.
weights_array : List[float]
The weights of each substep.
Returns
-------
r_bar : react... | e3a6c1972731ed1fda3177893ff637a9c2c66e9e | 3,598,819 |
def read_table(self, pointer="TABLE"):
""" Read a table. Will first attempt to parse it as generic CSV
and then fall back to parsin git based on the label format definition.
"""
if (self.filename.lower().endswith('.fits') or
self.filename.lower().endswith('.fit')):
try: # Is it a FI... | 578c2391c82738740c062c59087f27a282249563 | 3,598,820 |
def maior_numero_lista(lista_numeros, posicao_n):
"""
Determina o maior elemento de uma lista
recebendo a posição_n de um elemento da lista
e comparando com o resto
"""
if posicao_n == 0:
return lista_numeros[0]
maior_elemento = maior_numero_lista(lista_numeros, posicao... | 25ff12d0853972ada32b6d184e98fa6395ba18a7 | 3,598,821 |
def case_transfer_similar(cased_text: str, uncased_text: str) -> str:
"""Transfers the casing from one text to another - for similar (not matching)
text.
Use `difflib.SequenceMatcher` to identify the different type of changes
needed to turn `cased_text` into `uncased_text`.
- For inserted sections... | 2dbeeb24e01464f8dc7308979a38d8e80c6c51d6 | 3,598,822 |
def findDay(pageTitle, oldDay):
"""
Find day link from CFD template.
This function grabs the wiki source of a category page and attempts to
extract a link to the CFD per-day discussion page from the CFD template.
If the CFD template is not there, it will return the value of the second
parameter... | 9c0f62b7fc390bd1de2595dd280fd45ca38e606d | 3,598,823 |
def apply_to_audio(f, clip, *a, **k):
""" This decorator will apply the function f to the audio of
the clip created with f """
newclip = f(clip, *a, **k)
if hasattr(newclip, 'audio') and (newclip.audio != None):
newclip.audio = f(newclip.audio, *a, **k)
return newclip | 88cdc94e7c999b148b8e87e9f7715992d4598a9f | 3,598,824 |
def boot():
"""Add a boot config or boot configs
Examples:
.. code-block:: python
# add a config class
@kanon.boot()
class SiteConfig(object):
def config(self, options):
group = options.group("Service settings")
_ = group.define
... | a29ce2d83ba1317cee4ca227ec2d2ee6fba394b1 | 3,598,825 |
def get_ns_from_identifiers(identifiers_ns):
""""Return a namespace compatible with INDRA from an identifiers namespace.
For example, this function can be used to map 'uniprot' to 'UP'.
Parameters
----------
identifiers_ns : str
An identifiers.org standard namespace.
Returns
-----... | 033a0605037352ddcac8995c71a1a251435cc1ea | 3,598,826 |
def _subsystem_apply_dm(state, channel, mask):
"""
Applies a channel to every subsystem indicated by a mask, by
repeatedly applying the channel to each affected subsystem.
"""
# Initialize Output Matrix
rho_out = state
# checked affected subsystems print arange(len(state.dims[0]))[mask]
... | 8de0b25c0ee01d3163e9a2403b1abb4f72c04691 | 3,598,827 |
def make_mutable_url( data_id ):
"""
Local disk implementation of the make_mutable_url API call.
Given the ID of the data, generate a URL that
can be used to route reads and writes to the data.
Return a string.
"""
global MUTABLE_STORAGE_ROOT
# replace all /'s with \x2f's
data_i... | fdeacb0de3dcb8a34d6761b13b605f843db751c0 | 3,598,828 |
def sides(m):
"""Select the sides of a mobile."""
return branches(m) | e4471ee78184d9cc97aeba812a665135b3b2b533 | 3,598,829 |
from typing import Any
def affix(orig: Any, ch: str) -> str:
"""Ensure a given character is prepended to some original value."""
if isinstance(orig, (list, tuple,)):
orig = '.'.join(map(str, orig))
return '%s%s' % (ch, str(orig).lstrip(ch)) | f5f01b7fa0e82944646dc755cfa0770cec8c72c9 | 3,598,830 |
def get_pvalues(cluster_list, annotation, gene_population):
"""
Takes a liks of clusters and an annotation file and returns
a dataframe of p-values for each cluster and each annotation term
"""
n_clusters = len(cluster_list)
# ---------------------------- population size, M -----------------------... | 7173a3ac5c2ed633e5c24a838b62e141437335dc | 3,598,831 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.