content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def get_audio_features(audios_data, audio_tStamp, frameRate, video_length, device='cuda'):
"""audio feature extraction"""
extractor = ResNet50().to(device)
output1 = torch.Tensor().to(device)
output2 = torch.Tensor().to(device)
extractor.eval()
patchSize = 224
frameSkip = 2
... | 149f22fe855f52d63ffc2174800a83afb2568246 | 30,764 |
import asyncio
async def node_watch_profile_report_builder(data_id: str):
"""
Allows the front-end to update the display information once a profile report builds successfully.
Necessary because the profile report entails opening a separate tab.
"""
time_waited = 0
while time_waited < 600:
... | 6cb6552d1a05726e77a0f31e5b3f4625752b2d1b | 30,765 |
def write_report_systemsorted(system, username):
""" function that prepares return values and paths """
"""
the return values (prefix 'r') are used for the `mkdocs.yml` file
they build the key-value-pair for every system
"""
# return system_id for mkdocs.yml
rid = str(system.system_id)
... | f080203b1384277a9c6a0c934758d13674978df0 | 30,766 |
def is_outlier(points, threshold=3.5):
"""
This returns a boolean array with "True" if points are outliers and "False" otherwise.
These are the data points with a modified z-score greater than
this:
# value will be classified as outliers.
"""
# transform into vectors
if len(points.shape) =... | edc28706b37a6c1cfef356f45dd87c076779fe6d | 30,769 |
def hill_climbing_random_restart(problem,restarts=10):
"""From the initial node, keep choosing the neighbor with highest value,
stopping when no neighbor is better. [Figure 4.2]"""
# restarts = cantidad de reinicios aleatorios al llegar a un estado inmejorable
current = Node(problem.initial)
best =... | 78846f5d67465c981b712d00da7a0d76bbf152bd | 30,770 |
def ordinal(n):
"""Converts an integer into its ordinal equivalent.
Args:
n: number to convert
Returns:
nth: ordinal respresentation of passed integer
"""
nth = "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4])
return nth | 7f438c89a6b0f7adbc42f2eb1e619ca4bf862b4a | 30,771 |
def check_date(date):
"""check if date string has correct format.
Args:
date as a string mmddyyyy
Returns:
a boolean indicating if valid (True) or not (False)
"""
if len(date) != 8:
return False
if not date.isdigit():
return False
# months are between '01' ~... | 8972498d94d459ba48851049780e46b057855d9f | 30,772 |
async def expected_raceplan_individual_sprint_27_contestants(
event_individual_sprint: dict,
) -> Raceplan:
"""Create a mock raceplan object - 27 contestants."""
raceplan = Raceplan(event_id=event_individual_sprint["id"], races=list())
raceplan.id = "390e70d5-0933-4af0-bb53-1d705ba7eb95"
raceplan.no... | 969cba41b0cdcdd83317cd98a57b437f66981dbe | 30,773 |
def signal_to_m_converter(dataframe, dbm="4(dBm)"):
"""
This function convert a (beacon)dataframe with signal values from the tracer
to the corresponding *m*eter values, depend on dBm power that was used.
By default dbm = 4(dBm)
"""
# extract all different values from dataframe
dataframe_uni... | 55e58553a8685287a0d07e3c3d2432408e46ba04 | 30,774 |
def return_lines_as_list(file):
"""
:rtype: list of str
"""
# read lines
lines = file.readlines()
def strip(string):
"""
Removes whitespace from beginning and end of string
:type string: str
"""
return string.strip()
# Coverts our lines to list
... | 69e3d45fa3df107a8852d10e104a543c014a6c79 | 30,775 |
def cvInitMatNDHeader(*args):
"""cvInitMatNDHeader(CvMatND mat, int dims, int type, void data=None) -> CvMatND"""
return _cv.cvInitMatNDHeader(*args) | 152f49b20a858e7bbb7229d77cdeffa6fd1ed049 | 30,776 |
def getObjectInfo(fluiddb, objectId):
"""
Get information about an object.
"""
return fluiddb.objects[objectId].get(showAbout=True) | baad59e6585e04a8c2a8cca1df305327b80f3768 | 30,777 |
def calculate_logAUC(true_y, predicted_score, FPR_range=(0.001, 0.1)):
"""
Calculate logAUC in a certain FPR range (default range: [0.001, 0.1]).
This was used by previous methods [1] and the reason is that only a
small percentage of samples can be selected for experimental tests in
consideration of... | fc75fd9a361435f31c4f089e7c6e2976330affd7 | 30,778 |
def format_inline(str_, reset='normal'):
"""Format a string if there is any markup present."""
if const.regex['url'].search(str_):
text = slugify(str_.split('[[')[1].split('][')[1].split(']]')[0])
str_ = const.regex['url'].sub(const.styles['url'] + text + const.styles[reset], str_)
for key,... | 9cd6819bff098051812f23825bcdb61e7305d650 | 30,779 |
from typing import Dict
from typing import Any
import codecs
import pickle
def serialize_values(
data_dictionary: Dict[str, Any], data_format: PersistedJobDataFormat
) -> Dict[str, Any]:
"""
Serializes the `data_dictionary` values to the format specified by `data_format`.
Args:
data_dictionar... | 9dc1116357c2dd50f16bf9b1b1d5eec56ea6b4f7 | 30,781 |
def print_level_order(tree):
"""
prints each level of k-tree on own line
input <--- Tree
output <--- Prints nodes level by level
"""
if not isinstance(tree, KTree):
raise TypeError('argument must be of type <KTree>')
all_strings = []
def recurse(nodelist):
nonlocal all... | 7bb5d43725dbe351a85792f685ad504ca1e2d263 | 30,782 |
def spark_add():
"""ReduceByKey with the addition function.
:input RDD data: The RDD to convert.
:output Any result: The result.
"""
def inner(data: pyspark.rdd.RDD) -> ReturnType[pyspark.rdd.RDD]:
o = data.reduceByKey(lambda a,b: a+b)
return ReturnEntry(result=o)
return inner | 7cab67ac0f6a55911ca3e46612487bbe329b5d6f | 30,783 |
def edit():
"""
Allows the user to edit or delete a reservation
"""
user = db.session.query(models.Rideshare_user).filter(models.Rideshare_user.netid == session['netid']).first()
form = forms.EditReservationFactory()
reservation = None
rideNumber = request.args.get('rideNo')
userHasRev=c... | cfed4d98975d4e7abeb7021eba250c4f1e88c641 | 30,784 |
from typing import Type
from pathlib import Path
async def study_export(
app: web.Application,
tmp_dir: str,
project_id: str,
user_id: int,
product_name: str,
archive: bool = False,
formatter_class: Type[BaseFormatter] = FormatterV2,
) -> Path:
"""
Generates a folder with all the d... | c07bf3244323ee5a222ad0339631c704ed10c568 | 30,786 |
def gen_fileext_type_map():
"""
Generate previewed file extension and file type relation map.
"""
d = {}
for filetype in list(PREVIEW_FILEEXT.keys()):
for fileext in PREVIEW_FILEEXT.get(filetype):
d[fileext] = filetype
return d | 3ef34884b5fff37fbf20e7e11c87e2f16310a77a | 30,787 |
def umm_fields(item):
"""Return only the UMM part of the data"""
return scom.umm_fields(item) | 65bb71ed27612a3f504b7aae771bff69eff85bbe | 30,788 |
def converts_to_message(*args):
"""Decorator to register a custom NumPy-to-Message handler."""
def decorator(function):
for message_type in args:
if not issubclass(message_type, Message):
raise TypeError()
_to_message[message_type] = function
return f... | 5fdd5875aec2962b1ee19766f08c522200e8ea0a | 30,789 |
def oil_rho_sat(
rho0: NDArrayOrFloat, g: NDArrayOrFloat, rg: NDArrayOrFloat, b0: NDArrayOrFloat
) -> NDArrayOrFloat:
"""Calculate the gas saturated oil density
B&W Eq 24
Args:
rho0: The oil reference density (g/cc) at 15.6 degC
g: The gas specific gravity
rg: The Gas-to-Oil ra... | cca2ccc3934dda8e84db03598d56660cd56edc7a | 30,790 |
def astar(array, start, goal):
"""A* algorithm for pathfinding.
It searches for paths excluding diagonal movements. The function is composed
by two components, gscore and fscore, as seem below.
f(n) = g(n) + h(n)
"""
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
close_set = set()
cam... | 6ddc058246d0ac8db2aa90c847eb3d55d29321c7 | 30,791 |
def download_jar(req, domain, app_id):
"""
See ApplicationBase.create_jadjar
This is the only view that will actually be called
in the process of downloading a complete CommCare.jar
build (i.e. over the air to a phone).
"""
response = HttpResponse(mimetype="application/java-archive")
a... | 97c963b3dba3a2c95fcf98b784fc31fb778c2c3d | 30,792 |
def cond(addr, condexpr):
"""
set a condtion breakpoint at addr.
"""
return setBreakpoint(addr, False, condexpr) | adf2c21ef4dd32b92f546bc70c3009a47e305ee9 | 30,793 |
def get_host_credentials(config, hostname):
"""Get login information for a host `hostip` (ipv4) from marvin's `config`
@return the tuple username, password for the host else raise keyerror"""
for zone in config.get('zones', []):
for pod in zone.get('pods', []):
for cluster in pod.get('c... | 82651c247c50d3781c8e96038c373bd6c7fba4e6 | 30,794 |
def is_flat_dtype(dtype: np.dtype) -> bool:
"""
Determines whether a numpy dtype object is flat.
Checks whether the ``dtype`` just encodes one element or a shape. A dtype
can characterise an array of other base types, which can then be embedded
as an element of another array.
Parameters
--... | 08c690e66a3c9303926a8d25c45dace6c2b292c7 | 30,795 |
def _solarize_impl(pil_img, level):
"""Applies PIL Solarize to `pil_img`.
Translate the image in the vertical direction by `level`
number of pixels.
Args:
pil_img: Image in PIL object.
level: Strength of the operation specified as an Integer from
[0, `PARAMETER_MAX`].
Returns:
A PIL Image... | 615650710266b91c6f91d8b93ab26ef5c5081551 | 30,796 |
def version_flash(cmd="flash"):
"""Return the version of flash (as a short string).
Parses the output with ``-v``::
$ flash -v | head -n 1
FLASH v1.2.11
It would capture the version from the first line as follows:
>>> version_flash()
'v1.2.11'
If the command is not on the pa... | 87e9fed11f9d3a3206f4e3a983db1dc165fca576 | 30,797 |
def initialise_df(*column_names):
"""
Initialise a pandasdataframe with n column names
:param str column_names: N column names
:return: Empty pandas dataframe with specified column names
"""
return pd.DataFrame(columns=column_names) | 8561de29cc6a6aee1752a580c6038a84599a25c0 | 30,798 |
def _get_reporting_category(context):
"""Returns the current member reporting category"""
member = _get_member(context)
return member[TransactionLoops.MEMBER_REPORTING_CATEGORIES][-1] | 64ed9fcaf4fd9459789a1225cf4d9dbfddbfdb49 | 30,799 |
import csv
def snp2dict(snpfile):
"""Get settings of dict from .snp file exported from save&restore app.
Parameters
----------
snpfile : str
Filename of snp file exported from save&restore app.
Returns
-------
r : dict
Dict of pairs of PV name and setpoint value.
"""
... | cb902b3f8796685ed065bfeb8ed2d6d83c0fe80b | 30,800 |
import numpy
def _handle_zeros_in_scale(scale, copy=True, constant_mask=None):
"""
Set scales of near constant features to 1.
The goal is to avoid division by very small or zero values.
Near constant features are detected automatically by identifying
scales close to machine precision unless t... | 129f28dbf74f04929fcbccf8de42ee1c8dd5a09e | 30,801 |
def ST_LineStringFromText(geos):
"""
Transform the representation of linestring from WKT to WKB.
:type geos: WKT
:param geos: Linestring in WKT form.
:rtype: WKB
:return: Linestring in WKB form.
:example:
>>> from pyspark.sql import SparkSession
>>> from arctern_pyspark import... | 7cb0a5f3f6d35b49d35765ad5b5992952fe58e18 | 30,802 |
def get_container_state(pod, name):
"""Get the state of container ``name`` from a pod.
Returns one of ``waiting, running, terminated, unknown``.
"""
phase = pod["status"].get("phase", "Unknown")
if phase == "Pending":
return "waiting"
cs = get_container_status(pod, name)
if cs is no... | bad0143dbc2fb6998dce62665138d94f9542abc5 | 30,803 |
def implicit_ecp(
objective, equality_constraints, initial_values, lr_func, max_iter=500,
convergence_test=default_convergence_test, batched_iter_size=1, optimizer=optimizers.sgd,
tol=1e-6):
"""Use implicit differentiation to solve a nonlinear equality-constrained program of the form:
m... | 98a753765dda4cbc09ee8b1bc6225c12d10eb996 | 30,804 |
def get_detection_probability_Braun2008(filename, index, TS_threshold):
"""
Find the detection probability as a function
of the expected number of source counts in
a detector.
Returns Nsrc_list and Pdet
:param filename: Filename
:param index: spectral index
:param TS_threshold: TS <=>... | 631195c6d0c264d9b8676929882048d39333f2d6 | 30,806 |
from datetime import datetime
def device_create(db: Session,
name: str,
device_type: DeviceType,
activation_token: str) -> Device:
"""
Create a new Device
"""
device = Device(
name=name,
device_type=device_type,
activation_t... | f7c39a52ad43523cce895b223da85ec6f632ade2 | 30,807 |
def xy_potential(_):
"""
Potential for square XY model with periodic boundary conditions
"""
def potential(_, passive_rates):
pot = -passive_rates.sum(dim=(-1, -2, -3)) # sum over all sites and directions
return pot
return potential | b809e57464a9cd893cd33cd7ad38dffdb0d12a40 | 30,808 |
def distribute_srcs_2D(X, Y, n_src, ext_x, ext_y, R_init):
"""Distribute n_src's in the given area evenly
Parameters
----------
X, Y : np.arrays
points at which CSD will be estimated
n_src : int
demanded number of sources to be included in the model
ext_x, ext_y : floats
... | 8c984c742e6e8d604332e51f39e057a46cad0076 | 30,809 |
def _setBlueprintNumberOfAxialMeshes(meshPoints, factor):
"""
Set the blueprint number of axial mesh based on the axial mesh refinement factor.
"""
if factor <= 0:
raise ValueError(
"A positive axial mesh refinement factor "
f"must be provided. A value of {factor} is inva... | 6c477b0e55e996009158fa34c06d3c642e4691c4 | 30,810 |
def _get_filter_syntax(_filter_info, _prefix=True):
"""This function retrieves the proper filter syntax for an API call."""
if type(_filter_info) != tuple and type(_filter_info) != list:
raise TypeError("Filter information must be provided as a tuple (element, criteria) or a list of tuples.")
elif t... | b1817a2a3f004ba2bd44a8f8f272ad685e4d5ebe | 30,813 |
import math
def pol2cart(r,theta):
"""
Translate from polar to cartesian coordinates.
"""
return (r*math.cos(float(theta)/180*math.pi), r*math.sin(float(theta)/180*math.pi)) | 69753e1cadd36ec70da1bf2cf94641d4c7f78179 | 30,815 |
import math
def mass2mk_ben(m):
"""mass2mk_ben - mass to M_K, Benedict et al. (2016) double exponential.
Usage:
mk = mass2mk_ben(mass)
Where mk is absolute 2MASS K magnitude and mass is in solar masses.
This version is the original double-exponential "forward model" (for
going from mass to absolute magnitude)... | 3e9f20588f87db6bb9429b6c5d7135ad879158c3 | 30,816 |
def apply_and_concat_one_nb(n, apply_func_nb, *args): # numba doesn't accepts **kwargs
"""A Numba-compiled version of `apply_and_concat_one`.
!!! note
* `apply_func_nb` must be Numba-compiled
* `*args` must be Numba-compatible
* No support for `**kwargs`
"""
output_0 = to_2... | ed75920864a736aeafe9156b5bd6e456cd287226 | 30,817 |
def convertCovariance2Dto3D(covariance2d):
""" convert the covariance from [x, y, theta] to [x, y, z, roll, pitch, yaw]
:param covariance2d: covariance matrix in 3x3 format.
each row and column corresponds to [x, y, theta]
:return: covariance matrix in 6x6 format. each row and colu... | 4c6ea8bb8475a705fb40181172bab2a761676e85 | 30,818 |
import torch
import random
def fit_gan_wasserstein(nb_epoch: int, x_LS: np.array, y_LS: np.array, x_VS: np.array, y_VS: np.array, x_TEST: np.array, y_TEST: np.array, gen, dis, opt_gen, opt_dis, n_discriminator:int, batch_size:int=100, wdb:bool=False, gpu:bool=True):
"""
Fit GAN with discriminator using the Wa... | 64fc1625aa76ca09c14720ef3489657b8c28e671 | 30,819 |
import math
def pad(image_array, final_dims_in_pixels, zero_fill_mode=False):
"""
Pad image data to final_dim_in_pixels
Attributes:
image_array (float, np.array): 3D numpy array containing image data
final_dim_in_pixels (list): Final number of pixels in xyz dimensions. Example: [256, 2... | 8882ded9a01f98e9163807675cf7246527443d97 | 30,821 |
def save_and_plot(canddatalist):
""" Converts a canddata list into a plots and a candcollection.
Calculates candidate features from CandData instance(s).
Returns structured numpy array of candidate features labels defined in
st.search_dimensions.
Generates png plot for peak cands, if so defined in p... | 484b2bf099c31762e294ce40039f01f8ec00a273 | 30,822 |
def GetReviewers(host, change):
"""Gets information about all reviewers attached to a change."""
path = 'changes/%s/reviewers' % change
return _SendGerritJsonRequest(host, path) | 4e2d5bdf37993f76b42c0062dec042dc5a01aa87 | 30,823 |
def plot_single_points(xs, ys, color=dark_color, s=50, zorder=1e6, edgecolor='black', **kwargs):
"""Plot single points and return patch artist."""
if xs is None:
xs = tuple(range(len(ys)))
return plt.scatter(xs, ys, marker='o', s=s, color=color, zorder=zorder, edgecolor=edgecolor, **kwargs) | 490c17dbb360bc06c7805dddb7af1c72b5ce5890 | 30,824 |
import _ast
def find_imports(source: str, filename=constants.DEFAULT_FILENAME, mode='exec'):
"""return a list of all module names required by the given source code."""
# passing an AST is not supported because it doesn't make sense to.
# either the AST is one that we made, in which case the imports have already be... | 2ea91f6387e455fb1b4907e6a109fc3b987c8a9d | 30,825 |
def generate_character_data(sentences_train, sentences_dev, sentences_test, max_sent_length, char_embedd_dim=30):
"""
generate data for charaters
:param sentences_train:
:param sentences_dev:
:param sentences_test:
:param max_sent_length:
:return: C_train, C_dev, C_test, char_embedd_table
... | c53257e1d999edafc54b627a0687ae33aaebc487 | 30,826 |
def draw_pie_distribution_of_elements(Genome_EP, ChIP_EP, gprom=(1000, 2000, 3000), gdown=(1000, 2000, 3000), prom=(1000,2000,3000), down=(1000,2000,3000)):
"""Draw the pie charts of the overall distributions of ChIP regions and genome background
"""
# get the labels (legend) for the genome pie chart
gn... | 24a28a23e2929e20c77dd2389691235d51e1ba80 | 30,827 |
def get_neighborhood(leaflet, mdsys):
""" Get neighborhood object for the give leaflet
"""
dist = distances.distance_array(leaflet.positions, leaflet.positions, mdsys.dimensions[:3])
nbrs = Neighborhood(leaflet.positions, dist, mdsys.dimensions[:3])
return nbrs | 234193d36c957a0dd26a805f2fcbf5e97c0be2d6 | 30,828 |
def clean_title(title: str) -> str:
"""Strip unwanted additional text from title."""
for splitter in [" (", " [", " - ", " (", " [", "-"]:
if splitter in title:
title_parts = title.split(splitter)
for title_part in title_parts:
# look for the end splitter
... | 5625c6c64b166560b1804b7048fd3d604536251a | 30,829 |
def get_dates():
"""
Query date in the tweets table
:return:
"""
sql = "SELECT date FROM tweets"
dates = cx.read_sql(db, sql)
return dates | 60704fa5fa625ffbd42b29b9cc22c95d01475026 | 30,830 |
def _convert_to_dict(best_param):
"""
Utiliy method for converting best_param string to dict
Args:
:best_param: the best_param string
Returns:
a dict with param->value
"""
best_param_dict = {}
for hp in best_param:
hp = hp.split('=')
best_param_dict[hp[0]] ... | 318ed529b0f411b1b671de34a4b0f4ecf3dc9780 | 30,831 |
def _expand_currency(data: dict) -> str:
"""
Verbalizes currency tokens.
Args:
data: detected data
Returns string
"""
currency = _currency_dict[data['currency']]
quantity = data['integral'] + ('.' + data['fractional'] if data.get('fractional') else '')
magnitude = data.get('magni... | 491d175195f97126d65afec65c60f2e34ca09bc3 | 30,833 |
def getCampaignID(title):
""" Returns the id of a campaign from a dm name and a title """
conn = connectToDB()
cur = conn.cursor()
print title
query = cur.mogrify('select id from campaigns where title = %s;', (title,))
print query
cur.execute(query)
results = cur.fetchone()
return re... | b3f6f3b50a97e25931754332ed864bdac9d5c639 | 30,834 |
import time
def calculate_exe_time(input_function):
"""
This decorator method take in a function as argument and calulates its execution time.
:param input_function: name of method to be executed.
:return process_time: method that calls the input_function and calculates execution time.
"""
de... | bdbd4e20c8126e48d27031e46e5a91c83740a188 | 30,835 |
import torch
def load_xyz_from_txt(file_name):
"""Load xyz poses from txt. Each line is: x,y,x
Args:
file_name (str): txt file path
Returns:
torch.Tensor: Trajectory in the form of homogenous transformation matrix. Shape [N,4,4]
"""
global device
poses = np.genfromtxt... | f0d57aafa9e96a20c719a27dc8e0f2c18ebe0e7b | 30,836 |
def category_add():
"""
Route for category add
"""
# request Form data
form = CategoryForm(request.form)
if request.method == "POST" and form.validate():
# Set new category name variable
category_name = form.name.data.lower()
if category_check(category_name):
... | 11a94b7b3600fcaad0848696dd63648d39988052 | 30,837 |
import requests
def generate_text(input: TextGenerationInput) -> TextGenerationOutput:
"""Generate text based on a given prompt."""
payload = {
"text": input.text,
"temperature": input.temperature,
"min_length": input.min_length,
"max_length": input.max_length,
"do_sam... | 1c0eeff8b90b5246828a285f8c7a86bc4095c364 | 30,838 |
def file_content_hash(file_name, encoding, database=None):
"""
Returns the hash of the contents of the file
Use the database to keep a persistent cache of the last content
hash.
"""
_, content_hash = _file_content_hash(file_name, encoding, database)
return content_hash | 42962749e6bb5ec2d061ffcefd6ebf4aa34bbc29 | 30,839 |
import inspect
def pass_multiallelic_sites(mqc):
"""
The number of PASS multiallelic sites.
Source: count_variants.py (bcftools view)
"""
k = inspect.currentframe().f_code.co_name
try:
d = next(iter(mqc["multiqc_npm_count_variants"].values()))
v = d["pass_multiallelic_sites"]... | cd91ff816e88fa29e4d3beed4d0baf740388428c | 30,840 |
import json
def read_dialog_file(json_filename: str) -> list[Message]:
"""
Read messages from the dialog file
@return: list of Message objects (without intent)
"""
with open(json_filename, encoding="utf8") as dialog_json:
return [
Message(is_bot=msg["is_bot"], text=msg["text"])... | 9665c6bd708c66e66e24cb416d033730ef4f3909 | 30,841 |
def dtwavexfm3(X, nlevels=3, biort=DEFAULT_BIORT, qshift=DEFAULT_QSHIFT,
include_scale=False, ext_mode=4, discard_level_1=False):
"""Perform a *n*-level DTCWT-3D decompostion on a 3D matrix *X*.
:param X: 3D real array-like object
:param nlevels: Number of levels of wavelet decomposition
... | d0adab48c51ade82fab55b416029a2291151e3b9 | 30,842 |
def character_regions(img, line_regs, bg_thresh=None, **kwargs):
"""
Find the characters in an image given the regions of lines if text in the
image.
Args:
img (numpy.ndarray): Grayscaled image.
line_regs (list[tuple[int, int]]): List of regions representing where
the lines ... | 2e1b182944a857b698886ed590295723909dcc7e | 30,843 |
def cache_clear(request):
"""
Очищает директорию кеша.
"""
Core.get_instance().clear_cache()
return {
'size': Core.get_instance().get_cache_size()
} | 039ddc6e400c1befe283b529ba239d9c7831a7ce | 30,844 |
def sort_crp_tables(tables):
"""Sort cluster assignments by number"""
keys = sorted(tables,
key=lambda t: (len(tables[t]), min(tables[t])),
reverse=True)
items = [item for table in keys for item in tables[table]]
dividers = [len(tables[table]) for table in keys]
return (items, np.cum... | 4147cb86ed672b7dd1503615ba759fdb36d74185 | 30,845 |
def sum_category_hours(day, now, timelog=TIMELOG, category_hours=False):
""" Sum the hours by category. """
if not category_hours:
category_hours = {}
activities = get_rows(day, timelog)
for activity in activities:
category = activity.category
duration = activity.get_duration(now... | 5d8d77759c43f40c616bd394ed8ba169f4a58917 | 30,846 |
def run_factory(
factory, # type: LazyFactory
args=None, # type: Optional[Iterable[Any]]
kwargs=None, # type: Optional[Mapping[str, Any]]
):
# type: (...) -> Any
"""
Import and run factory.
.. code:: python
>>> from objetto.utils.factoring import run_factory
>>> bool(ru... | 3766555849bca15e568ffc41fb522a47c22c666c | 30,847 |
def steps_smoother(steps, resolution):
"""
:param delta_steps: array of delta positions of 2 joints for each of the 4 feet
:return: array of positions of 2 joints for each of the 4 feet
"""
smoothed_steps = []
for i in range(len(steps)):
step = steps[i]
next_step = steps[(i + 1) ... | a27e09af169e79438895d0e15c0b536213962429 | 30,848 |
from typing import Optional
def get_instance_server(name: Optional[str] = None,
server_id: Optional[str] = None,
zone: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetInstanceServerResult:
"""
Gets inform... | aae211831c951d131a4cd21fab917da5b169f31b | 30,849 |
def leaper(x, y, int1, int2):
"""sepcifically for the rook, permutes the values needed around a position for no_conflict tests"""
return [(x+int1, y+int2), (x-int1, y+int2), (x+int1, y-int2), (x-int1, y-int2), (x+int2, y+int1), (x-int2, y+int1), (x+int2, y-int1), (x-int2, y-int1)] | 6f7afc071c8adbc72a6391179e2df522574e5197 | 30,850 |
def calc_offsets(obj):
"""
The search "hit" should have a 'fullsnip' annotation which is a the entire
text of the indexable resource, with <start_sel> and <end_sel> wrapping each
highlighted word.
Check if there's a selector on the indexable, and then if there's a box-selector
use this to gener... | 6af4827a57cf20f317ce2a40a669c14d3f6380f3 | 30,851 |
def spread(self, value="", **kwargs):
"""Turns on a dashed tolerance curve for the subsequent curve plots.
APDL Command: SPREAD
Parameters
----------
value
Amount of tolerance. For example, 0.1 is ± 10%.
"""
return self.run("SPREAD,%s" % (str(value)), **kwargs) | a92c8e230eadd4e1fde498fa5650a403f419eaeb | 30,853 |
def _ValidateCandidateImageVersionId(current_image_version_id,
candidate_image_version_id):
"""Determines if candidate version is a valid upgrade from current version."""
if current_image_version_id == candidate_image_version_id:
return False
parsed_curr = _ImageVersionIt... | 25d888645211fc21f7a21ee17f5aeeb04e83907e | 30,854 |
import re
def getOrdererIPs():
"""
returns list of ip addr
"""
client = docker.from_env()
container_list = client.containers.list()
orderer_ip_list = []
for container in container_list:
if re.search("^orderer[1-9][0-9]*", container.name):
out = container.exec_run("aw... | 745c9635b03745c5e61d6cd56c0b1fcd58df1fa4 | 30,857 |
import re
def repair_attribute_name(attr):
"""
Remove "weird" characters from attribute names
"""
return re.sub('[^a-zA-Z-_\/0-9\*]','',attr) | f653a5cb5ed5e43609bb334f631f518f73687853 | 30,858 |
def get_xsd_file(profile_name, profile_version):
"""Returns path to installed XSD, or local if no installed one exists."""
if profile_name.lower() not in XSD_LOOKUP_MAP:
raise ValueError(
'Profile %s did not match a supported profile: %s.\n'
% (profile_name, sorted(XSD_FILES.keys())))
# Ensur... | 02d2c127fabd0a8f274211885e625f90d314036f | 30,859 |
def get_response(url: str) -> HTMLResponse:
"""
向指定url发起HTTP GET请求
返回Response
:param url: 目标url
:return: url响应
"""
session = HTMLSession()
return session.get(url) | f53c2a6a2066bbe76f3b9266d42ad014d5e4fcfa | 30,860 |
def minutesBetween(date_1, date_2):
"""Calculates the number of whole minutes between two dates.
Args:
date_1 (Date): The first date to use.
date_2 (Date): The second date to use.
Returns:
int: An integer that is representative of the difference between
two dates.
"... | 1e75c3571bee3855183b7a51e661d8eaa0bf47a2 | 30,861 |
import asyncio
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload FireServiceRota config entry."""
await hass.async_add_executor_job(
hass.data[DOMAIN][entry.entry_id].websocket.stop_listener
)
unload_ok = all(
await asyncio.gather(
*... | d6acb96f1f144868923b1cc65e99b4ee901caa56 | 30,863 |
def HasPositivePatterns(test_filter):
"""Returns True if test_filter contains a positive pattern, else False
Args:
test_filter: test-filter style string
"""
return bool(len(test_filter) > 0 and test_filter[0] != '-') | 9038bf799efbe4008a83d2da0aba89c0197c16a1 | 30,864 |
import math
def get_lr(lr_init, lr_end, lr_max, total_epochs, warmup_epochs,
pretrain_epochs, steps_per_epoch, lr_decay_mode):
"""
generate learning rate array
Args:
lr_init(float): init learning rate
lr_end(float): end learning rate
lr_max(float): max learning rate
... | 90091b35126bcf91166c498c396c831c3da1e7f6 | 30,865 |
def comptineN2():
"""Generate the midi file of the comptine d'un autre été"""
mid = MidiFile()
trackl = MidiTrack()
trackl.name = "Left hand"
for i in range(8):
trackl = comp_lh1(trackl)
trackl = comp_lh1(trackl)
trackl = comp_lh2(trackl)
trackl = comp_lh2(trackl)
... | a7cd80b7ab483ef68be827c56e5f8b95967d8c08 | 30,866 |
from xenserver import tasks
from xenserver.tests.helpers import XenServerHelper
def xs_helper(monkeypatch):
"""
Provide a XenServerHelper instance and monkey-patch xenserver.tasks to use
sessions from that instance instead of making real API calls.
"""
xshelper = XenServerHelper()
monkeypatch.... | d504aa6b651eb3777171187aceea7eb03fa7e46a | 30,867 |
def highest_palindrome_product(digits):
"""Returns the highest palindrome number resulting from the
multiplication of two numbers with the given amount of digits.
"""
def is_palindrome(target):
"""Returns True if target (str or int) is a palindrome.
"""
string = str(target)
... | e509de1c977c6e4ecf9ab8304ef1afe65a447188 | 30,868 |
def is_ladder(try_capture, game_state, candidate,
ladder_stones=None, recursion_depth=50):
"""Ladders are played out in reversed roles, one player tries to capture,
the other to escape. We determine the ladder status by recursively calling
is_ladder in opposite roles, providing suitable captur... | 755ed8c007d51034ec2f2a24958c3f4660795007 | 30,869 |
def instances(request, compute_id):
"""
:param request:
:return:
"""
all_host_vms = {}
error_messages = []
compute = get_object_or_404(Compute, pk=compute_id)
if not request.user.is_superuser:
all_user_vms = get_user_instances(request)
else:
try:
all_host... | 622336dfb836fbe4918f5d1331149aaaa3467a05 | 30,870 |
def seresnet101b_cub(classes=200, **kwargs):
"""
SE-ResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation
Networks,' https://arxiv.org/abs/1709.01507.
Parameters:
----------
classes : int, default 200
Number of classification classes.
... | 784e915704d244270ddf479eaaf5e279a7db437a | 30,871 |
from pathlib import Path
import shutil
def dst(request):
"""Return a real temporary folder path which is unique to each test
function invocation. This folder is deleted after the test has finished.
"""
dst = Path(mkdtemp()).resolve()
request.addfinalizer(lambda: shutil.rmtree(str(dst), ignore_erro... | 7714ce85fbeedfed00b571d9d2ef31cd6d8898e9 | 30,873 |
import string
def getSentencesFromReview(reviewContent):
"""
INPUT: a single review consist of serveral sentences
OUTPUT: a list of single sentences
"""
sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
sentences = sent_detector.tokenize(reviewContent)
# split agglomerated ... | 2c074fac508994ad44edb0889a799ada22261c3c | 30,874 |
import math
def gamma_vector_neutrino(m_med, g_l=0.0):
"""Function to calculate the neutrino width of a vector mediator
:param m_med: mediator mass
:type m_med: float
:param g_l: lepton coupling, defaults to 0.0
:type g_l: float, optional
"""
return 3 * g_l**2 / (24 * math.pi) * m_med | ebb0c913beee57cf9cdb605cc356949cea461882 | 30,875 |
def fifo_cdc(glbl, emesh_i, emesh_o):
"""
map the packet interfaces to the FIOF interface
"""
fifo_intf = FIFOBus(size=16, width=len(emesh_i.bits))
@always_comb
def rtl_assign():
wr.next = emesh_i.access and not fifo_intf.full
rd.next = not fifo_intf.empty and not emesh_i.wait
... | d30445dad18043c63e29e7a79ff3e02dad370964 | 30,877 |
def eudora_bong(update, context): #1.2.1
"""Show new choice of buttons"""
query = update.callback_query
bot = context.bot
keyboard = [
[InlineKeyboardButton("Yes", callback_data='0'),
InlineKeyboardButton("No", callback_data='00')],
[InlineKeyboardButton("Back",callback_data='1... | 234d4324b384414fd6e2a6f52dbbccc51f0ff738 | 30,878 |
def scan_setup_py():
"""Validate the contents of setup.py against Versioneer's expectations."""
found = set()
setters = False
errors = 0
with open("setup.py", "r") as f:
for line in f.readlines():
if "import versioneer" in line:
found.add("import")
if ... | 33b9a4bfd44a70d93ae7b50df870d46765bf0cb7 | 30,880 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.