content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def decode_hint(hint: int) -> str:
"""Decodes integer hint as a string.
The format is:
⬜ (GRAY) -> .
🟨 (YELLOW) -> ?
🟩 (GREEN) -> *
Args:
hint: An integer representing the hint.
Returns:
A string representing the hint.
"""
hint_str = []
for _ ... | 4180b847cd252a1e3c762431327b1b6d359dac3d | 8,962 |
def is_symmetric(arr, i_sym=True, j_sym=True):
"""
Takes in an array of shape (n, m) and check if it is symmetric
Parameters
----------
arr : 1D or 2D array
i_sym : array
symmetric with respect to the 1st axis
j_sym : array
symmetric with respect to the 2nd axis
Returns... | 488744d34d851b690eb6114b06d754e46b04e36f | 8,964 |
def linear_powspec(k, a):
"""linear power spectrum P(k) - linear_powspec(k in h/Mpc, scale factor)"""
return _cosmocalc.linear_powspec(k, a) | 9abe99ef5251b4b8ef04e7113a30dd26ed86d14a | 8,965 |
def light_eff(Pmax, Iz, I0, Ik):
"""
Photosynthetic efficiency based on the light conditions. By definition, the
efficiency has a value between 0 and 1.
Parameters
----------
Pmax : numeric
Maximum photosynthetic rate [-].
Iz : numeric
Coral biomass-averaged light-intensity ... | a2e0de2cb0791d3afea15f4c78b7d673200504b3 | 8,966 |
import array
import time
def radial_kernel_evaluate(rmax, kernel, pos, wts, log=null_log, sort_data=False,
many_ngb_approx=None):
"""
Perform evaluation of radial kernel over neighbours.
Note you must set-up the linear-interpolation kernel before calling this
function.
... | 41c4600be3a5684c97d69acb4ebe15846dcc4b0d | 8,967 |
def get_referents(source, exclude=None):
"""
:return: dict storing lists of objects referring to source keyed by type.
"""
res = {}
for obj_cls, ref_cls in [
(models.Language, models.LanguageSource),
(models.ValueSet, models.ValueSetReference),
(models.Sentence, models.Senten... | 2aeccbbe61cdcb2b3183682a5cce8ed959fc14c9 | 8,968 |
import array
def asarray(buffer=None, itemsize=None, shape=None, byteoffset=0,
bytestride=None, padc=" ", kind=CharArray):
"""massages a sequence into a chararray.
If buffer is *already* a chararray of the appropriate kind, it is
returned unaltered.
"""
if isinstance(buffer, kind) and... | 346eaaa9ece9671f5b2fa0633552f72e40300adc | 8,969 |
def cumulative_gain_curve(df: pd.DataFrame,
treatment: str,
outcome: str,
prediction: str,
min_rows: int = 30,
steps: int = 100,
effect_fn: EffectFnType = linear_ef... | ca493a85d1aa7d74335b1ddb65f2f2a94fcaa152 | 8,972 |
def last(*args):
"""Return last value from any object type - list,tuple,int,string"""
if len(args) == 1:
return int(''.join(map(str,args))) if isinstance(args[0],int) else args[0][-1]
return args[-1] | ad8d836597dd6a5dfe059756b7d8d728f6ea35fc | 8,973 |
def predict(self, celldata):
"""
This is the method that's to perform prediction based on a model
For now it just returns dummy data
:return:
"""
ai_model = load_model_parameter()
ret = predict_unseen_data(ai_model, celldata)
print("celldata: ", celldata)
print("Classification: ", re... | 435be195c765aa3823a710982bdc6f7954a24178 | 8,976 |
from typing import List
def statements_to_str(statements: List[ASTNode], indent: int) -> str:
"""Takes a list of statements and returns a string with their C representation"""
stmt_str_list = list()
for stmt in statements:
stmt_str = stmt.to_str(indent + 1)
if not is_compound_statement(stm... | 01bd0546be8b7a212dbb73fae3c505bbe0086b48 | 8,977 |
def _make_filter(class_name: str, title: str):
"""https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumwindows"""
def enum_windows(handle: int, h_list: list):
if not (class_name or title):
h_list.append(handle)
if class_name and class_name not in win32gui.GetCla... | 3b9d5f3fe4afd666cfa7ed43f8abe103b9575249 | 8,978 |
def is_float(s):
"""
Detertmine if a string can be converted to a floating point number.
"""
try:
float(s)
except:
return False
return True | 2df52b4f8e0835d9f169404a6cb4f003ca661fff | 8,979 |
def build_lm_model(config):
"""
"""
if config["model"] == "transformer":
model = build_transformer_lm_model(config)
elif config["model"] == "rnn":
model = build_rnn_lm_model(config)
else:
raise ValueError("model not correct!")
return model | 03a84f28ec4f4a7cd847575fcbcf278943b72b8a | 8,980 |
def __virtual__():
"""
Only load if boto3 libraries exist.
"""
has_boto_reqs = salt.utils.versions.check_boto_reqs()
if has_boto_reqs is True:
__utils__["boto3.assign_funcs"](__name__, "cloudfront")
return has_boto_reqs | 63d2f1102713b8da66e75b28c4c642427fe69e8a | 8,981 |
def search_range(nums, target):
"""
Find first and last position of target in given array by binary search
:param nums: given array
:type nums : list[int]
:param target: target number
:type target: int
:return: first and last position of target
:rtype: list[int]
"""
result = [-1... | 8165e3a2f33741c15494d5d98a82a85c2fb610ff | 8,983 |
def process_mean_results(data, capacity, constellation, scenario, parameters):
"""
Process results.
"""
output = []
adoption_rate = scenario[1]
overbooking_factor = parameters[constellation.lower()]['overbooking_factor']
constellation_capacity = capacity[constellation]
max_capacity = ... | 0619c397a21d27440988c4b23284e44700ba69eb | 8,984 |
def identify_ossim_kwl(ossim_kwl_file):
"""
parse geom file to identify if it is an ossim model
:param ossim_kwl_file : ossim keyword list file
:type ossim_kwl_file : str
:return ossim kwl info : ossimmodel or None if not an ossim kwl file
:rtype str
"""
try:
with open(ossim_kwl_... | 9a63a8b5e7ece79b11336e71a8afa5a703e3acbc | 8,985 |
def conv_cond_concat(x, y):
""" Concatenate conditioning vector on feature map axis.
# Arguments
x: 4D-Tensor
y: 4D-Tensor
# Return
4D-Tensor
"""
x_shapes = x.get_shape()
y_shapes = y.get_shape()
return tf.concat(3, [x, y * tf.ones([x_shapes[0], x_shapes[1], x_shape... | c30a4328d3a6e8cf2b1e38cf012edca045e9de69 | 8,986 |
def swath_pyresample_gdaltrans(file: str, var: str, subarea: dict, epsilon: float, src_tif: str, dst_tif: str):
"""Reprojects swath data using pyresample and translates the image to EE ready tif using gdal
Parameters
----------
file: str
file to be resampled and uploaded to GC -> EE
var: st... | b716a6b45cf48457d0c6ca5849997b7c37c6c795 | 8,988 |
def getKeyPairPrivateKey(keyPair):
"""Extracts the private key from a key pair.
@type keyPair: string
@param keyPair: public/private key pair
@rtype: base string
@return private key PEM text
"""
return crypto.dump_privatekey(crypto.FILETYPE_PEM, keyPair) | 0decc2dbb77343a7a200ace2af9277ee7e5717a5 | 8,990 |
def playbook_input(request, playbook_id, config_file=None, template=None):
"""Playbook input view."""
# Get playbook
playbook = Playbook.objects.get(pk=playbook_id)
# Get username
user = str(request.user)
# Check user permissions
if user not in playbook.permissions.users:
return playbooks(request)
... | 4b01e08414f38bdaad45245043ec30adb876e40e | 8,991 |
def _filter_gtf_df(GTF_df, col, selection, keep_columns, silent=False):
"""
Filter a GTF on a specific feature type (e.g., genes)
Parameters:
-----------
GTF_df
pandas DataFrame of a GTF
type: pd.DataFrame
col
colname on which df.loc will be performed
type: str... | 5f41141d69c0c837e396ec95127500a826013500 | 8,992 |
def validation_generator_for_dir(data_dir, model_dict):
"""Create a Keras generator suitable for validation
No data augmentation is performed.
:param data_dir: folder with subfolders for the classes and images therein
:param model_dict: dict as returned by `create_custom_model`
:returns: a generato... | 57b0a83e98438b8e397377a5626094f69ea21083 | 8,993 |
def convert_cbaois_to_kpsois(cbaois):
"""Convert coordinate-based augmentables to KeypointsOnImage instances.
Parameters
----------
cbaois : list of imgaug.augmentables.bbs.BoundingBoxesOnImage or list of imgaug.augmentables.bbs.PolygonsOnImage or list of imgaug.augmentables.bbs.LineStringsOnImage or i... | 6eee2715de3bfc76fac9bd3c246b0d2352101be1 | 8,994 |
def get_query_dsl(
query_string, global_filters=None, facets_query_size=20, default_operator='and'):
"""
returns an elasticsearch query dsl for a query string
param: query_string : an expression of the form
type: person title:foo AND description:bar
where type corresponds to an elastic sea... | 9f6c1371e0de1f28737415c0454f645748af054f | 8,996 |
def prune_visualization_dict(visualization_dict):
"""
Get rid of empty entries in visualization dict
:param visualization_dict:
:return:
"""
new_visualization_dict = {}
# when the form is left blank the entries of visualization_dict have
# COLUMN_NAME key that points to an empty list
... | fae81eb69fc25d61282eb151d931d740c51b8bae | 8,997 |
def _LocationListToGoTo( request_data, positions ):
"""Convert a LSP list of locations to a ycmd GoTo response."""
try:
if len( positions ) > 1:
return [
responses.BuildGoToResponseFromLocation(
*_PositionToLocationAndDescription( request_data, position ) )
for position in positi... | 2ee39fdadd721920a3737561979308223a64b57a | 8,998 |
def calculate_average_grades_and_deviation(course):
"""Determines the final average grade and deviation for a course."""
avg_generic_likert = []
avg_contribution_likert = []
dev_generic_likert = []
dev_contribution_likert = []
avg_generic_grade = []
avg_contribution_grade = []
dev_generi... | 95b26efedba076e0b9b54c565fe2e0787d5fbb0e | 8,999 |
from datetime import datetime
def get_slurm_params(n,runtime=None,mem=None,n_jobs=None):
"""Get remaining parameters to submit SLURM jobs based on specified parameters and number of files to process.
Parameters
----------
n : int
Number of files to process.
runtime : str, None
Tim... | f2bf08430fbde0dcc430fd3e01d6b5ca1bd64487 | 9,000 |
def source_open() -> bool:
"""Open a source MS Excel spreadsheet file.
Returns
-------
boolean
Flag about successful processing.
"""
try:
Source.wbook = openpyxl.load_workbook(cmdline.workbook)
except Exception:
logger.error(
'Cannot open the MS Excel wo... | 19a2c214131afa6c1126bc1e0a4b4892a13bc32b | 9,002 |
import re
def get_license_match_error(lic, lic_file_path):
"""Returns an Error of the type 'warning' if the FreeRTOS license is present in the
input file. Otherwise an empty list is returned.
"""
# Get the words in the license template
with open('license.templ', 'r') as file:
template_lic ... | d3f53f3d25c4d56b41fb561cf37b845d1efdc9fe | 9,004 |
import queue
def start_workers(size, delete=False, migrate=False):
"""Starts FluxxWorkers.
:returns: Pair of queues.
"""
streams = (queue.Queue(), queue.Queue(maxsize=size))
for _ in range(THREAD_COUNT):
worker = FluxxWorker(streams, delete, migrate)
worker.daemon = True
... | 358d8d3bc0d12edbe9e422cdfc206de626fd2a7d | 9,005 |
def harmonizationApply(data, covars, model):
"""
Applies harmonization model with neuroCombat functions to new data.
Arguments
---------
data : a numpy array
data to harmonize with ComBat, dimensions are N_samples x N_features
covars : a pandas DataFrame
contains covar... | 7789d3a75d043df5048a7b0adced771c7e1ddd81 | 9,006 |
import re
def from_rkm(code):
"""Convert an RKM code string to a string with a decimal point.
Parameters
----------
code : str
RKM code string.
Returns
-------
str
String with a decimal point and an R value.
Examples
--------
>>> from pyaedt.circuit import fr... | 8cb41a58fab685e5e7de4af533fade1aeee09c2c | 9,007 |
def get_arguments(method, rpc_version):
"""
Get arguments for method in specified Transmission RPC version.
"""
if method in ('torrent-add', 'torrent-get', 'torrent-set'):
args = constants.TORRENT_ARGS[method[-3:]]
elif method in ('session-get', 'session-set'):
args = constants.SESSI... | dcd8b3f0e5e93409518d7e9d72ffe954c3b99915 | 9,008 |
import functools
def compose_local_noises(*functions: NoiseModel) -> NoiseModel:
"""Helper to compose multiple NoiseModel.
Args:
*functions: a list of functions
Returns:
The mathematical composition of *functions. The last element is applied
first. If *functions is [f, g, h], it ... | 4b6e90ff2def9a988d8aa66782d990971b8de586 | 9,009 |
import copy
def sls_build(
repository, tag="latest", base="opensuse/python", mods=None, dryrun=False, **kwargs
):
"""
.. versionchanged:: 2018.3.0
The repository and tag must now be passed separately using the
``repository`` and ``tag`` arguments, rather than together in the (now
d... | d3d047334ea8b02e61d26b3fc471eb2cedd7a8c5 | 9,010 |
import re
from datetime import datetime
def parse_date(date):
"""
Parses a date string and returns number of seconds from the EPOCH.
"""
# yyyy-mm-dd [hh:mm:ss[.s][ [+-]hh[:][mm]]]
p = re.compile( r'''(?P<year>\d{1,4}) # yyyy
- #
... | 44dbf7c9ded2004118b64827e5c5016dc3967ec6 | 9,011 |
def CorrectOrWrong(Input,word):
"""Check if Input is inside word"""
if Input in word:
return True
else:
return False | fa3f06fd156c2523334a057366e88c5b7b376eb1 | 9,012 |
def get_fair_metrics(dataset, pred, pred_is_dataset=False):
"""
Measure fairness metrics.
Parameters:
dataset (pandas dataframe): Dataset
pred (array): Model predictions
pred_is_dataset, optional (bool): True if prediction is already part of the dataset, column name 'labels'.
Retu... | 1cf4a8655bf569f5d8ddfa530f46c65fe8f2be3f | 9,013 |
from typing import Sequence
from typing import Dict
from typing import Union
from typing import Tuple
def make_params(
key_parts: Sequence[str],
variable_parts: VariablePartsType) -> Dict[str, Union[str, Tuple[str]]]:
"""
Map keys to variables. This map\
URL-pattern variables to\
a URL... | 4da736f2057e06be1ceb51968d6c205cd28b7093 | 9,014 |
def load_sentiments(file_name=DATA_PATH + "sentiments.csv"):
"""Read the sentiment file and return a dictionary containing the sentiment
score of each word, a value from -1 to +1.
"""
sentiments = {}
for line in open(file_name):
word, score = line.split(',')
sentiments[word] = float(... | a98ae77a051ea3b599ee2fd5036e1bd33c1f4d64 | 9,015 |
def get_draft_url(url):
"""
Return the given URL with a draft mode HMAC in its querystring.
"""
if verify_draft_url(url):
# Nothing to do. Already a valid draft URL.
return url
# Parse querystring and add draft mode HMAC.
url = urlparse.urlparse(url)
salt = get_random_string(... | f8eaaa7daaba2b5bfe448b5386e88d9f738b0f5d | 9,017 |
def make_datum(source: str, img_id: str, sent_id: int, sent: str):
"""
Create a datum from the provided infos.
:param source: the dataset of the particular sentence.
:param img_id: id of the image
:param sent_id: id of the sentence (of the image)
:param sent: the sentence
:return: a dict of ... | 4814093519aad09e0f81d6e0841d130e1b2e43a4 | 9,018 |
def list_for_consumer(req):
"""List allocations associated with a consumer."""
context = req.environ['placement.context']
context.can(policies.ALLOC_LIST)
consumer_id = util.wsgi_path_item(req.environ, 'consumer_uuid')
want_version = req.environ[microversion.MICROVERSION_ENVIRON]
# NOTE(cdent):... | 37575bb0d05491d8a2e0933134fa530bf7699b3b | 9,019 |
def get_zcl_attribute_size(code):
"""
Determine the number of bytes a given ZCL attribute takes up.
Args:
code (int): The attribute size code included in the packet.
Returns:
int: size of the attribute data in bytes, or -1 for error/no size.
"""
opts = (0x00, 0,
0x... | 99782c86be2413410c6819a59eadf0daba326af2 | 9,021 |
def get_mappings():
"""We process the mappings for two separate cases. (1) Variables that vary by year,
and (2) variables where there are multiple realizations each year.
"""
# Set up grid for survey years. Note that from 1996 we can only expect information every other
# year. We start with 1978 as ... | a02ac60889ab2ef9524a50ec7eb03fe6a8b54917 | 9,022 |
def _get_function_name_and_args(str_to_split):
"""
Split a string of into a meta-function name and list of arguments.
@param IN str_to_split String to split
@return Function name and list of arguments, as a pair
"""
parts = [s.strip() for s in str_to_split.split(" | ")]
if len(parts) < 2:
... | 1dae51c87e727d7fa6a3a8012f9768b9ca3364e7 | 9,023 |
import requests
def replicas_on_delete():
"""
This is a route for ALL NODES.
A (previous) neighbor node sends POST requests to this route,
so that a key-value pair replica is deleted in the current NODE.
"""
# The hash ID of the node-owner of the primary replica
start_id = request.form[... | ff8b4cc06ce7a640914bdd58ff897dc060f22d4b | 9,025 |
def pdf2(sigma_matrix, grid):
"""Calculate PDF of the bivariate Gaussian distribution.
Args:
sigma_matrix (ndarray): with the shape (2, 2)
grid (ndarray): generated by :func:`mesh_grid`,
with the shape (K, K, 2), K is the kernel size.
Returns:
kernel (ndarrray): un-norm... | 7477b33eab034d9ca5cac63fd1eedd4f6789f1ba | 9,027 |
def spell_sql(*args,**kwargs):
"""
list=[]
"""
if len(args[0])<=0:
return None
sql="SELECT * from `emotion_data` WHERE id ={}".format(args[0][0])
for index in args[0][1:]:
sql +=" or id ={}".format(index)
return sql | 5e5b231be2dabca75abed332864c8ae3d93b750e | 9,028 |
def is_within_bounds(bounds, point):
""" Returns true if point is within bounds. point is a d-array and bounds is a
dx2 array. bounds is expected to be an np.array object.
"""
point = np.array(point)
if point.shape != (bounds.shape[0],):
return False
above_lb = np.all((point - bounds[:, 0] >= 0))
... | 926c107a808d98f62c0323746112b6f73b5f89fe | 9,029 |
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
weight (Tensor): Element-wise weights.
reduction (str): Same as built-in losses of PyTorch.
avg_factor (float): Ava... | b19b937f9b774dcac09f8949c2d1762743e7958e | 9,030 |
def list_of_paths():
"""
It lists all the folders which not contain PET images
"""
return ['.DS_Store', 'localizer', 'Space_3D_T2_FLAIR_sag_p2', 'AXIAL_FLAIR', 'MPRAGE_ADNI_confirmed_REPEATX2', 'Axial_PD-T2_TSE',
'Axial_PD-T2_TSE_repeat', 'MPRAGE_SAG_ISO_p2_ND', 'Axial_PD-T2_TSE_confi... | bc74024d49396f80947b3cb0a45066381b7d3af4 | 9,031 |
def convert_onnx_to_ell(path, step_interval_msec=None, lag_threshold_msec=None):
"""
convert the importer model into a ELL model, optionally a steppable model if step_interval_msec
and lag_threshold_msec are provided.
"""
_logger = logger.get()
_logger.info("Pre-processing... ")
converter = ... | 28843c1b588d4c1772c5c4be10e1a535b940703d | 9,032 |
def compute_error_model(model_metadata, X_test, y_test, target,error_metric):
"""Computes the model MRR based on test data
:param model_metadata: a dictionary containing metadata about a model
:param X_test: a dataframe containing features specfic to the model being evaluated
:param y_test: a datafra... | 9cb1ede604f863c1eeab12a593c8b62527599d12 | 9,034 |
def column(df, s, column) -> ReturnType:
"""Gets the series of the column named `column`
"""
return df.loc[s, column].to_numpy(), 0 | 8d400c2425a062566e61c23361dd6a1f6e0ba8b7 | 9,035 |
def features_to_id(features, intervals):
"""Convert list of features into index using spacings provided in intervals"""
id = 0
for k in range(len(intervals)):
id += features[k] * intervals[k]
# Allow 0 index to correspond to null molecule 1
id = id + 1
return id | 74b0b201888a69c045ef140959876dd3e909f20d | 9,036 |
import torch
def index_initial(n_batch, n_ch, tensor=True):
"""Tensor batch and channel index initialization.
Args:
n_batch (Int): Number of batch.
n_ch (Int): Number of channel.
tensor (bool): Return tensor or numpy array
Returns:
Tensor: Batch in... | 52a16ad4afcf931ba4cda9c014d47050970995c5 | 9,037 |
def load_titanic(test_size=0.2, random_state=1, cache_dir=None, cache_subdir='datasets'):
""" load titanic database """
path = find_path(DatasetEnum.titanic, cache_dir=cache_dir, cache_subdir=cache_subdir)
df = pd.read_csv(path, sep=",", na_values=["?"], keep_default_na=True)
# Shuffle DF and compute ... | a222a684a55bde482664b0b3072fb04047360f50 | 9,039 |
def mock_function_fail(*args, **kwargs):
"""
Mock a function that 'fails', i.e., returns a 1.
"""
print("\nmock> f({}) ==> 1".format(args)) # pragma: no cover
return 1 # pragma: no cover | ec2085e51a0809c9656d1831429858e14baf3f63 | 9,040 |
def get_field_result(client_id, field_id, count=1):
"""
на входе: id-поля, id-карты,
выход: последний результат поля
:return:
"""
with connection.cursor() as cursor:
cursor.execute(
"""
SELECT directions_napravleniya.client_id, directions_issledovaniya.napravleniy... | 7191705462f1fceb3dfca866c5fed96fa8019886 | 9,041 |
def parse_basic_profile_forms():
"""Parses and validates basic profile forms in the request.
Returns:
A dictionary containing user profile.
Raises:
ValueError: When validation failed.
"""
return {
'display_name': get_form_string('display_name', 32),
'contact_email':... | c8409bcc7de6a2c0a320859f90d54215888febf8 | 9,042 |
def fixture_success(request):
"""
Test Cases:
1. Hitting uncovered route as base user (logged in flow). Will return 200
since uncovered route is an open endpoint and thus Anonymous users can also
access it.
2. Hitting uncovered route as base user and HEAD request
3. Hitting uncovered route a... | 26603ce9203372e9ced217f75505b149942eee98 | 9,043 |
from typing import Optional
import csv
def get_quote_name(quote_number: int) -> Optional[str]:
""" used to help applications look up quote names based on the number
users.
"""
assert type(quote_number) in (int, type(None))
if quote_number is None:
return None
for key, value in cs... | 4a96ee42b37879469a67cb657d97aa321770fd83 | 9,044 |
def calc_floodzone(row):
"""Extracts the FEMAZONE of an SFHA based on each row's attributes.
This function acts on individual rows of a pandas DataFrame using
the apply built-in.
Parameters
----------
row : Pandas Series
A row of a pandas DataFrame
Returns
-------
str
... | 5bb6f3f7cfc1b6bce41ad7a752845287759c16ad | 9,045 |
def trans_you(ori_image, img_db, target_size=(8, 8)):
"""Transfer original image to composition of images.
Parameters
----------
ori_image : numpy.ndarray
the original image
img_db : h5py.File
image datasets
target_size : tuple
Returns
-------
res_img : numpy.ndarra... | f9717d2ddc9052bee103010a23328f5445c4edc5 | 9,046 |
from re import A
from re import T
def new_assessment():
"""
RESTful CRUD controller to create a new 'complete' survey
- although the created form is a fully custom one
"""
# Load Model
table = s3db.survey_complete
s3db.table("survey_series")
def prep(r):
if r.interact... | a4b1f9ba0a7e70349607f5cc70fdac72d75fb236 | 9,047 |
import types
import random
async def random_pokemon(connection: asyncpg.Connection, /) -> types.Pokemon:
"""Returns a random :class:`types.Pokemon`."""
records = await tables.Pokemon.fetch(connection)
return await _pokemon(connection, random.choice(records)) | b60659f236a4cbea998a77df211da92c18e4f0b8 | 9,048 |
import re
def remove_space(text):
"""
Funcion que elimina espacios
:param str text: texto a procesar
"""
return re.sub(r"\s+", " ", text).strip() | 729d26bb6acbaa8da4c945d2ea6646ebb90f3122 | 9,049 |
import base64
def getFilePathBase():
"""
获取请求url文件的文件路径
:return: php->base64 code
"""
code = """
@ini_set("display_errors","0");
@set_time_limit(0);
@set_magic_quotes_runtime(0);
header("Content-Type:application/json");
$res = array();$res["path"] = dirname(__FILE__);
echo ("<ek>... | afcb1a5bf2972a2b13a32edcd8a9b968742bf7f3 | 9,050 |
def extractHeldSimple(q, factoryConfig=None):
"""All Held Glideins: JobStatus == 5
q: dictionary of Glideins from condor_q
factoryConfig (FactoryConfig): Factory configuartion (NOT USED, for interface)
Returns:
dict: dictionary of Held Glideins from condor_q
"""
# Held==5
... | c942991bb0370b63364c1b8d5644713865d9ea82 | 9,051 |
def neighbors(stats1, stats2, max_val=1e5):
"""stats from cv.connectedComponentsWithStats."""
pts1 = np.concatenate(
(stats1[:, :2], stats1[:, :2] + stats1[:, 2:4]), axis=0)
pts2 = np.concatenate(
(stats2[:, :2], stats2[:, :2] + stats2[:, 2:4]), axis=0)
dist = np.abs(pts1[:, None] - pts... | 1b6aecad76f968cd83d40ee6531fcbd6b3b0df6c | 9,052 |
from typing import Optional
def shortest_substring_containing_characters(text: str, char_set: set) -> Optional[str]:
"""
O(n) & O(k)
"""
start = 0
end = -1
count_char = defaultdict(int) # char and its count
found_set = set()
for index, char in enumerate(text):
if char in char... | 4682a01b1a4331dbada7a234c908d1c53639e69a | 9,053 |
def refine_grid(
grid,
cb,
grid_additions=(50, 50),
ntrail=2,
blurs=((), ()),
metric=None,
atol=None,
rtol=None,
extremum_refinement=None,
snr=False,
):
"""Refines an existing grid by adding points to it.
Parameters
----------
grid : array
cb : callbable
... | c84a365bcc271622fd49a01d89303aa2adb1c624 | 9,054 |
from datetime import datetime
def last_week(today: datetime=None, tz=None):
"""
Returns last week begin (inclusive) and end (exclusive).
:param today: Some date (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
"""
if today is N... | a210707e2a479fe4e8b98a137c0ade684d4dd6da | 9,055 |
def get_velocity_limits():
"""
"""
velocity_limits = {}
for i in range(6):
try:
velocity_limits['a{}'.format(i+1)] = float(pm.textField(
't_A{}vel'.format(i+1),
q=True,
... | 68f58ed715a39478d119af1e1aabe54fa7ec6094 | 9,056 |
def decode_item_length(encoded_data: Bytes) -> int:
"""
Find the length of the rlp encoding for the first object in the
encoded sequence.
Here `encoded_data` refers to concatenation of rlp encoding for each
item in a sequence.
NOTE - This is a helper function not described in the spec. It was
... | d005b8050abaaba76bd5d3a24419f86c462af2b2 | 9,057 |
def pxor(a1, a2, fmt=None):
"""Bitwise XOR"""
return c2repr(_inconv(a1) ^ _inconv(a2), fmt) | a65ada1901fc5bfa202af5128c3e5b6e54d5f6dc | 9,058 |
from typing import Tuple
def milestone_2_test_1_initial_val(lattice_grid_shape: Tuple[int, int]) -> Tuple[np.ndarray, np.ndarray]:
"""
Return initial conditions
Args:
lattice_grid_shape: lattice grid [lx, ly]
Returns:
density with 0.5, but one peak in the middle, velocities 0
""... | 89d6ed57e93859182a92946e94adc2d26631f6e3 | 9,059 |
def test_element_html_call_get_attribute(monkeypatch, browser_driver):
"""Calls el_or_xpath WebElement attr get_attribute"""
called = []
class FakeWebElement:
def get_attribute(self, val):
called.append(('get_attribute', val))
return 42
@browser_driver.register
cla... | 7b3bcc3ba4a8c030b15649b240f75bf9bed71570 | 9,060 |
import time
def moving_dictators(session, system_ids):
"""
Show newly controlling dictators in the last 5 days.
Show all controlling dictators in monitored systems.
Subqueries galore, you've been warned.
Returns: A list of messages to send.
"""
gov_dic = session.query(Government.id).\
... | 9d9808d608190dae0a9f57980312e2ae830c492c | 9,061 |
def get_alt_for_q_with_constant_mach(q, mach, tol=5., SI=False, nmax=20):
# type: (float, float, float, bool, int) -> float
"""
Gets the altitude associated with a dynamic pressure.
Parameters
----------
q : float
the dynamic pressure lb/ft^2 (SI=Pa)
mach : float
the mach to... | f9286d7f742a8e8e3f25d63210180dbd7bc2fcc7 | 9,062 |
def addMetadataFlags(metadataChunk, numberOfMetadataChunks):
"""Adds binary flag the number of metadata chunks this upload has (uint8).
Arguments:
metadataChunk {bytes} -- First metadata chunk already encrypted, but before signing.
numberOfMetadataChunks {int} -- Self-explanatory.
Returns:
bytes -- Metadat... | aeaefd8e1cd62524d435ee95bc272a9a676680c0 | 9,063 |
def table(a):
"""get tabular view of obj, if available, else return obj"""
if misc.istablarray(a):
return a.__view__('table')
return a | e04b53f40203fbeeb3104f5e46bab87ab3304269 | 9,064 |
def parse_quadrupole(line):
"""
Quadrupole (type 1)
V1: zedge
V2: quad gradient (T/m)
V3: file ID
If > 0, then include fringe field (using Enge function) and
V3 = effective length of quadrupole.
V4: radius (m)
V5: x misalignment error (m)
V6: y misalignment error (m)... | 2e9748fb0eabe51383fcb1ff47a7278dda622e44 | 9,065 |
def cases_vides(pave):
"""fonction qui cherche toutes les cases vides ayant des cases adjacentes
pleines dans un pavé (où pavé est un tableau de tuiles ou de cases vides)
retourne le tableau contenant les positions de ces cases vides et les
cases adjacentes en fonction de leur position"""
result = [... | 2d2de1651f000f48ab32e484f3f6b465231248b5 | 9,066 |
def _create_scalar_tensor(vals, tensor=None):
"""Create tensor from scalar data"""
if not isinstance(vals, (tuple, list)):
vals = (vals,)
return _create_tensor(np.array(vals), tensor) | ef41eabc66eda8739a78931d53ccc6feb8dfc6bb | 9,067 |
import importlib
def is_importable(name):
""" Determines if a given package name can be found.
:param str name: The name of the pacakge
:returns: True if the package can be found
:rtype: bool
"""
return bool(importlib.util.find_spec(name)) | 548044b06d250af7f49dc3c9b4144490a5bbcc83 | 9,068 |
def make_pipeline(*steps, **kwargs):
"""Construct a Pipeline from the given estimators.
This is a shorthand for the Pipeline constructor; it does not require, and
does not permit, naming the estimators. Instead, their names will be set
to the lowercase of their types automatically.
Parameters
... | a036c345208333b6f6d9d33998d06b282c9aa711 | 9,069 |
import logging
def say_hello(name):
"""
Log client's name which entered our application and send message to it
"""
logging.info('User %s entered', name)
return 'Hello {}'.format(name) | b79865cca34d1430bf47afabf7c96741d59ac560 | 9,070 |
import numpy
def dual_edges_2(vertices):
"""
Compute the dual edge vectors of a triangle, expressed in the
triangle plane orthonormal basis.
:param vertices: The triangle vertices (3 by n matrix with the vertices as rows (where n is the dimension of the
space)).
:returns: The triangle dua... | 64ff173ef00dc4d916f00f67c7a35da25d81b535 | 9,071 |
def merge_dicts(dictionaries):
"""Merges multiple separate dictionaries into a single dictionary.
Parameters
----------
dictionaries : An iterable container of Python dictionaries.
Returns
-------
merged : A single dictionary that represents the result of merging the all the
... | 1a2b5f3c539937e2e27a55ce3914f7368f0a7296 | 9,072 |
from typing import Union
from typing import Callable
def noise_distribution_to_cost_function(
noise_distribution: Union[str, Callable]
) -> Callable[[str], str]:
"""
Parse noise distribution string to a cost function definition amici can
work with.
The noise distributions listed in the follow... | d26ae31211ab5a9fae2b350391ab2a835ba02758 | 9,073 |
from datetime import datetime
def serializer(cls, o):
"""
Custom class level serializer.
"""
# You can provide a custom serialize/deserialize logic for certain types.
if cls is datetime:
return o.strftime('%d/%m/%y')
# Raise SerdeSkip to tell serde to use the default serializer/deseri... | 6e9bfbb83ede2c2da412b70741d793c6e24e05ef | 9,074 |
def parse_args():
""" parse command-line arguments """
usage = """Usage: bcfg2_svnlog.py [options] -r <revision> <repos>"""
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose", help="Be verbose", action="count")
parser.add_option("-c", "--config", help="Config file",
... | 30ac6035e375b692a516903055b7916a601e98a5 | 9,075 |
import array
def compute_com(kpt_ids, pose_keypoints):
"""Computes center of mass from available points for each pose.
Requires at least one arm (shoulder, elbow, wrist), neck and hips.
Required keypoints to return result: at least one arm with hip, neck and [nose OR ear]
:param kpt_id: IDs of keypo... | 16e884ef76bdc21695349e6f0f9f9948426c5b8c | 9,076 |
def _MinimumLineCount(text: str, min_line_count: int) -> str:
"""Private implementation of minimum number of lines.
Args:
text: The source to verify the line count of.
Returns:
src: The unmodified input src.
Raises:
NoCodeException: If src is less than min_line_count long.
"""
if len(text.str... | 037400aed0503dabee61a8d5088ca2e4b3ab34a6 | 9,078 |
def RationalQuadratic1d(
grid,
corrlen,
sigma,
alpha,
prior=None,
mu_basis=None,
mu_hyper=None,
energy=0.99
) -> Formula:
"""Rational quadratic kernel formula
"""
kernel_kwargs = {
"corrlen": corrlen,
"sigma": sigma,
"a... | 56d61ef851ac5c84336f7f6bda19885d85b42b26 | 9,079 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.