content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _is_domain_interval(val):
""" Check if a value is representing a valid domain interval
Args:
val: Value to check
Returns:
True if value is a tuple representing an interval
"""
if not isinstance(val, tuple):
return False
if not (is_int(val[0]) and is_int(val[1]) and (... | 3de16ddc26429be14ab84825f659dcf05f89f1f3 | 18,379 |
def rndcaps(n):
"""
Generates a string of random capital letters.
Arguments:
n: Length of the output string.
Returns:
A string of n random capital letters.
"""
return "".join([choice(_CAPS) for c in range(n)]) | 0661de89cc1abbbc678f7764f90674f3e5fb7282 | 18,380 |
def cutByWords(text, chunkSize, overlap, lastProp):
"""
Cuts the text into equally sized chunks, where the segment size is measured by counts of words,
with an option for an amount of overlap between chunks and a minim
um proportion threshold for the last chunk.
Args:
text: The string with ... | 0767eeab983f0d21a9fa14527a3962405019e110 | 18,381 |
def dsu_sort2(list, index, reverse=False):
"""
This function sorts only based on the primary element, not on secondary elements in case of equality.
"""
for i, e in enumerate(list):
list[i] = e[index]
if reverse:
list.sort(reverse=True)
else:
list.sort()
for i, e ... | 3fb614ac732eb790caf8f7d209c4e14022b8352a | 18,382 |
import functools
def roca_view(full, partial, **defaults):
"""
Render partal for XHR requests and full template otherwise
"""
templ = defaults.pop('template_func', template)
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if request.is_xhr:
... | eed45a5fc201667744cfe213ec61f5fba546d70b | 18,383 |
async def _shuffle(s, workers, dfs_nparts, dfs_parts, column):
"""
Parameters
----------
s: dict
Worker session state
workers: set
Set of ranks of all the participants
dfs_nparts: list of dict
List of dict that for each worker rank specifices the
number of partiti... | 7b9d8e7dc6687ee5fb661bb0912c6288f3473af9 | 18,384 |
def play_game(board:GoBoard):
"""
Run a simulation game to the end fromt the current board
"""
while True:
# play a random move for the current player
color = board.current_player
move = GoBoardUtil.generate_random_move(board,color)
board.play_move(move, color)
#... | 3fe2d050e9835bdbabbc81b999edbce7fa0c96d1 | 18,385 |
def logical_array(ar):
"""Convert ndarray (int, float, bool) to array of 1 and 0's"""
out = ar.copy()
out[out!=0] = 1
return out | 74d96d519929ed7f5ddfd92b0fbcef4741a38359 | 18,386 |
from datetime import datetime
import requests
def otp_route(
in_gdf,
mode,
date_time = datetime.now(),
trip_name = '',
):
"""
Return a GeoDataFrame with detailed trip information for the best option.
Parameters
----------
in_gdf : GeoDataFrame
It should only contain two re... | d19ec8e46b1480697cf0c9c7a83f0a859651b344 | 18,387 |
def tall_clutter(files, config,
clutter_thresh_min=0.0002,
clutter_thresh_max=0.25, radius=1,
max_height=2000., write_radar=True,
out_file=None, use_dask=False):
"""
Wind Farm Clutter Calculation
Parameters
----------
files : list... | 7eb26fbca4977e35f82f844f74d17269d7f80989 | 18,389 |
def serialize_bundle7(source_eid, destination_eid, payload,
report_to_eid=None, crc_type_primary=CRCType.CRC32,
creation_timestamp=None, sequence_number=None,
lifetime=300, flags=BlockProcFlag.NONE,
fragment_offset=None, total_adu_l... | 712a2de8814e5a3bf7143b27aa2d0a6f360e7db4 | 18,390 |
def _get_chinese_week(localtime):
"""获取星期和提醒"""
chinese_week = ["一", "二", "三", "四", "五", "六", "日"]
tm_w_day = localtime.tm_wday
extra_msg = "<green>当前正是周末啦~</green>" if tm_w_day in [5, 6] else "Other"
if extra_msg == "Other":
go_week = 4 - tm_w_day
extra_msg = f"<yellow>还有 {go_week} ... | 0a66bcf741c0d2e3cc9a238b5cb879c89333cc6b | 18,391 |
def resnext101_32x16d_swsl(cfg, progress=True, **kwargs):
"""Constructs a semi-weakly supervised ResNeXt-101 32x16 model pre-trained on 1B weakly supervised
image dataset and finetuned on ImageNet.
`"Billion-scale Semi-Supervised Learning for Image Classification" <https://arxiv.org/abs/1905.00546>`_
... | 8c99c076278adfacd7764db50824a196a29341e5 | 18,392 |
def leaderboard(players=None, N=DEFAULTN, filename="leaderboard.txt"):
""" Create a leaderboard, and optionally save it to a file """
logger.info("Generating a leaderboard for players: %r, N=%d", players, N)
ratings, allgames, players = get_ratings(players, N)
board, table = make_leaderboard(ratings, al... | e5ae7dcd1fd3c54e008b8e472d36b0af0de29463 | 18,393 |
def m_college_type(seq):
"""
获取学校的类型信息
当学校的类型是985,211工程院校时:
:param seq:【“985,211工程院校”,“本科”】
:return:“985工程院校”
当学校的类型是211工程院校时:
:param seq:【“211工程院校”,“硕士”】
:return:“211工程院校”
当学校的类型是普通本科或者专科时:
如果获取的某人的学历信息是博士、硕士和本科时
输出的学校类型为普通本科
:param seq:【“****”,“... | bf72f60c51a67dd3e18a7dd1957bc2beb4f933fd | 18,394 |
from owslib.wcs import WebCoverageService
from lxml import etree
def get_raster_wcs(coordinates, geographic=True, layer=None):
"""Return a subset of a raster image from the local GeoServer via WCS 2.0.1 protocol.
For geoggraphic rasters, subsetting is based on WGS84 (Long, Lat) boundaries. If not geographic,... | 5ae378077b3dbe480ef9fae37030d953e156936e | 18,395 |
def del_local_name(*args):
"""
del_local_name(ea) -> bool
"""
return _ida_name.del_local_name(*args) | 8db5674e8eb3917c21f189ebfa82525482ff712f | 18,396 |
def solve_google_pdp(data):
"""Entry point of the program."""
# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
data['num_vehicles'], data['depot'])
# Create Routing Model.
routing = pywrapcp.RoutingM... | 2b269dbca031c0cf98f51c2e6a493ba7df71a1d6 | 18,397 |
from typing import Any
def fetch_net(args: Any,
num_tasks: int,
num_cls: int,
dropout: float = 0.3):
"""
Create a nearal network to train
"""
if "mnist" in args.dataset:
inp_chan = 1
pool = 2
l_size = 80
elif args.dataset == "mini_i... | cbc3abb5140060ef52a69e44883a743249b5cd5e | 18,398 |
from typing import Dict
def are_models_specified(api_spec: Dict) -> bool:
"""
Checks if models have been specified in the API spec (cortex.yaml).
Args:
api_spec: API configuration.
"""
predictor_type = predictor_type_from_api_spec(api_spec)
if predictor_type == PythonPredictorType an... | 611ed794b45746e56bb8055a03251aa43d61d974 | 18,399 |
import json
def user_config(filename):
"""user-provided configuration file"""
try:
with open(filename) as file:
return json.loads(file.read(None))
except FileNotFoundError as fnf:
raise RuntimeError(f"File '{filename}' could not be found") from fnf
except json.JSONDecodeErr... | a6aa05d76b4aaa12c02ff97e4ab5ba4ba1245324 | 18,400 |
def _decomposed_dilated_conv2d(x, kernel_size, num_o, dilation_factor, name, top_scope, biased=False):
"""
Decomposed dilated conv2d without BN or relu.
"""
# padding so that the input dims are multiples of dilation_factor
H = tf.shape(x)[1]
W = tf.shape(x)[2]
pad_bottom = (dilation_factor -... | 578d9308834294a80e778548faba9eb9fe0329c5 | 18,401 |
from datetime import datetime
from typing import Tuple
async def post_autodaily(text_channel: TextChannel, latest_message_id: int, change_mode: bool, current_daily_message: str, current_daily_embed: Embed, utc_now: datetime.datetime) -> Tuple[bool, bool, Message]:
"""
Returns (posted, can_post, latest_message... | 309ad1c4554b2dcef6b2ddbcfd2d5652ea291488 | 18,402 |
def room_from_loc(env, loc):
"""
Get the room coordinates for a given location
"""
if loc == 'north':
return (1, 0)
if loc == 'south':
return (1, 2)
if loc == 'west':
return (0, 1)
if loc == 'east':
return (2, 1)
if loc == 'left':
return (1, 0)
... | 75192c47fd8d4b56332b35ec7c3b355927e50ca2 | 18,403 |
def count_encoder(df, cols):
"""count encoding
Args:
df: カテゴリ変換する対象のデータフレーム
cols (list of str): カテゴリ変換する対象のカラムリスト
Returns:
pd.Dataframe: dfにカテゴリ変換したカラムを追加したデータフレーム
"""
out_df = pd.DataFrame()
for c in cols:
series = df[c]
vc = series.value_counts(dropna=... | c8e5b0995d2915871e7614099cf3260566f75f05 | 18,404 |
def wrap_response(response):
"""Wrap a tornado response as an open api response"""
mimetype = response.headers.get('Content-Type') or 'application/json'
return OpenAPIResponse(
data=response.body,
status_code=response.code,
mimetype=mimetype,
) | 38edef05e0d2d0ae80c235ed82f00080b86c6cb1 | 18,405 |
def shifted(x):
"""Shift x values to the range [-0.5, 0.5)"""
return -0.5 + (x + 0.5) % 1 | c40585748120af5d0acd85e4fed49f0575a92a3d | 18,406 |
def computeAlignmentError(pP1, pP2, etype = 2, doPlot = False):
"""
Compute area-based alignment error. Assume that the
warping paths are on the same grid
:param pP1: Mx2 warping path 1
:param pP2: Nx2 warping path 2
:param etype: Error type. 1 (default) is area ratio.
2 is L1 Hausd... | cce79f3f1fa83475bc18f18004d8e2c79a8e59fa | 18,407 |
def _cumulative_grad(grad_sum, grad):
"""Apply grad sum to cumulative gradient."""
add = ops.AssignAdd()
return add(grad_sum, grad) | cb2b3ab6131fb4e289df29d33876f69c265c6e62 | 18,408 |
def run_node(node):
"""Python multiprocessing works strangely in windows. The pool function needed to be
defined globally
Args:
node (Node): Node to be called
Returns:
rslts: Node's call output
"""
return node.run_with_loaded_inputs() | a0f52020db20b4b67e83599bc0fb6c86ec2f9514 | 18,409 |
def getitimer(space, which):
"""getitimer(which)
Returns current value of given itimer.
"""
with lltype.scoped_alloc(itimervalP.TO, 1) as old:
c_getitimer(which, old)
return itimer_retval(space, old[0]) | 86716d3faedab3436bc1fcb5f77b80129884cf2d | 18,410 |
def substitute_T_and_RH_for_interpolated_dataset(dataset):
"""
Input :
dataset : Dataset interpolated along height
Output :
dataset : Original dataset with new T and RH
Function to remove interoplated values of T and RH in the original dataset and
replace with new values of T and R... | fe2fca2ea3889fca17d2e676d1d2a95634ac1782 | 18,411 |
def get_base_required_fields():
""" Get required fields for base asset from UI.
Fields required for update only: 'id', 'uid', ['lastModifiedTimestamp', 'location', 'events', 'calibration']
Present in input, not required for output:
'coordinates', 'hasDeploymentEvent', 'augmented', 'deployment_number... | 273c539d0c0b0da249e2bb171107aa775ce52ddf | 18,412 |
def reg_tab_ext(*model):
""" Performs weighted linear regression for various models building upon the model specified in section 4,
while additionally including education levels of a council candidate (university degree, doctoral/PhD degree)
A single model (i.e. function argument) takes on the form:... | be61f85e918c2cf91b720b9495968c9c9f4f7b6e | 18,413 |
def load_pdf(filename: str) -> pd.DataFrame:
""" Read PDF dataset to pandas dataframe """
tables = tabula.read_pdf(basedir + '\\' + filename, pages="all")
merged_tables = pd.concat(tables[1:])
merged_tables.head()
return merged_tables | c3d7a1c5b78a62d6d6b822ecc2a90246e1c3a6aa | 18,414 |
def he_xavier(in_size: int, out_size: int, init_only=False):
"""
Xavier initialization according to Kaiming He in:
*Delving Deep into Rectifiers: Surpassing Human-Level
Performance on ImageNet Classification
(https://arxiv.org/abs/1502.01852)
"""
stddev = tf.cast(tf.sqrt(2 / in_size), tf.float32)
W = tf.random_... | f76501537a25226f1a3f3fcb0953438dbfaa996f | 18,415 |
def GET_v1_keyboards_build_log():
"""Returns a dictionary of keyboard/layout pairs. Each entry is a dictionary with the following keys:
* `works`: Boolean indicating whether the compile was successful
* `message`: The compile output for failed builds
"""
json_data = qmk_redis.get('qmk_api_configura... | b1e2c3f5da654987bdb7530be8f62effbf878613 | 18,416 |
def logprod(lst):
"""Computes the product of a list of numbers"""
return sum(log(i) for i in lst) | fd42df8ca7170f70453ef58d46035ec2ac6b6446 | 18,417 |
import torch
def nms(dets, iou_thr, device_id=None):
"""Dispatch to either CPU or GPU NMS implementations.
The input can be either a torch tensor or numpy array. GPU NMS will be used
if the input is a gpu tensor or device_id is specified, otherwise CPU NMS
will be used. The returned type will always ... | 6a00022a6903fc73429cb0f893de3b5f018315e9 | 18,418 |
def render_template(template_name_or_list, **context):
"""Renders a template from the template folder with the given
context.
:param template_name_or_list: the name of the template to be
rendered, or an iterable with template names
the firs... | a712c5db36a0ed512411c592c695ddff8a51e8fb | 18,419 |
def XCL(code, error, mag=0.0167, propagation='random', NEV=True, **kwargs):
"""
Dummy function to manage the ISCWSA workbook not correctly defining the
weighting functions.
"""
tortuosity = kwargs['tortuosity']
if code == "XCLA":
return XCLA(
code, error, mag=mag, propagation... | 90efd4d07c66923d2b98739fd7684ac1ee5141e8 | 18,421 |
def to_bgr(image):
"""Convert image to BGR format
Args:
image: Numpy array of uint8
Returns:
bgr: Numpy array of uint8
"""
# gray scale image
if image.ndim == 2:
bgr = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
return bgr
# BGRA format
if image.shape[2] == 4:
bgr = cv2.cvtColor... | 51d8455bb4060ff2db662a34846a4f957d33af81 | 18,422 |
import pathlib
import yaml
def load(path: pathlib.Path) -> dict:
"""Load a YAML file, returning its contents.
:raises: RuntimeError
"""
with path.open() as handle:
try:
return yaml.safe_load(handle)
except scanner.ScannerError as error:
LOGGER.critical('Failed... | d91ba626619ec25e2dbdbe35202b26cd43d27dc3 | 18,423 |
import warnings
def validate_settings(raw_settings):
"""Return cleaned settings using schemas collected from INSTALLED_APPS."""
# Perform early validation on Django's INSTALLED_APPS.
installed_apps = raw_settings['INSTALLED_APPS']
schemas_mapping = raw_settings.get('CONFIT_SCHEMAS', {})
# Create s... | ba764cc54eee27a8317f21d6bd69ee85b9deadbf | 18,425 |
from torch.cuda.amp import autocast
def is_autocast_module_decorated(module: nn.Module):
"""
Return `True` if a nn.Module.forward was decorated with
torch.cuda.amp.autocast
"""
try:
decorators = _get_decorators(module.forward)
for d in decorators:
if isinstance(d, autoc... | 9f4db5438cb7e14ae20fd552a54121d9ce6c0d46 | 18,426 |
def timestamp_format_is_valid(timestamp: str) -> bool:
"""
Determines if the supplied timestamp is valid for usage with Graylog.
:param timestamp: timestamp that is to be checked
:return: whether the timestamp is valid (True) or invalid (False)
"""
try:
get_datetime_from_timestamp(times... | 9c1623bede646c9ebbd5cd4200db193437728590 | 18,427 |
def indices(n, dtype):
"""Indices of each element in upper/lower triangle of test matrix."""
size = tri.tri_n(n - 1)
return np.arange(size, dtype=dtype) | 0ecdcad0d66e268125826e0e415b410a07143b6c | 18,428 |
def _sample(n, k):
""" Select k number out of n without replacement unless k is greater than n
"""
if k > n:
return np.random.choice(n, k, replace=True)
else:
return np.random.choice(n, k, replace=False) | cde012459ddb64dc7700ec0238e222fd4d26d3a2 | 18,429 |
def set_price_filter(request, category_slug):
"""Saves the given price filter to session. Redirects to the category with
given slug.
"""
req = request.POST if request.method == 'POST' else request.GET
try:
min_val = lfs.core.utils.atof(req.get("min", "0"))
except (ValueError):
mi... | 1adf1798e7fbf290d98e1b47b94cd9c9038732fe | 18,430 |
def _get_config():
"""Returns a dictionary with server parameters, or ask them to the user"""
# tries to figure if we can authenticate using a configuration file
data = read_config()
# this does some sort of validation for the "webdav" data...
if "webdav" in data:
if (
"server"... | c2105753cb4ae551bea53c0a2aaf0432dd275422 | 18,431 |
import requests
def lastfmcompare(text, nick, bot,):
"""[user] ([user] optional) - displays the now playing (or last played) track of LastFM user [user]"""
api_key = bot.config.get("api_keys", {}).get("lastfm")
if not api_key:
return "No last.fm API key set."
if not text:
return "pleas... | 42b23961f210b4004aac987ca1146ee748392949 | 18,432 |
def fourier_ellipsoid(inp, size, n=-1, axis=-1, output=None):
"""
Multidimensional ellipsoid Fourier filter.
The array is multiplied with the fourier transform of a ellipsoid of
given sizes.
Parameters
----------
inp : array_like
The inp array.
size : float or sequence
... | 41128d7972bdb0cb6100991c1dc22031b7f3e6b3 | 18,433 |
def gaussian1D(x: np.ndarray, amplitude: Number, center: Number, stdev: Number) -> np.ndarray:
"""A one dimensional gaussian distribution.
= amplitude * exp(-0.5 (x - center)**2 / stdev**2)
"""
return amplitude * np.exp(-0.5 * (x - center)**2 / stdev**2) | 5c5c36ea71a08aec3246a2ca1dedf1d62c3fd331 | 18,434 |
def BuildImportLibs(flags, inputs_by_part, deffiles):
"""Runs the linker to generate an import library."""
import_libs = []
Log('building import libs')
for i, (inputs, deffile) in enumerate(zip(inputs_by_part, deffiles)):
libfile = 'part%d.lib' % i
flags_with_implib_and_deffile = flags + ['/IMPLIB:%s' %... | f29bcf16917cf8509662cf44c7881f8c7282b37d | 18,435 |
def gather_sparse(a, indices, axis=0, mask=None):
"""
SparseTensor equivalent to tf.gather, assuming indices are sorted.
:param a: SparseTensor of rank k and nnz non-zeros.
:param indices: rank-1 int Tensor, rows or columns to keep.
:param axis: int axis to apply gather to.
:param mask: boolean ... | 87e68a99c660448a11d32fa090ca3921552cd122 | 18,436 |
def Window(node, size=-1, full_only=False):
"""Lazy wrapper to collect a window of values. If a node is executed 3 times,
returning 1, 2, 3, then the window node will collect those values in a list.
Arguments:
node (node): input node
size (int): size of windows to use
full_only (boo... | 1f85b576455f3b379e41a7247ff486281bf21f8f | 18,437 |
def fixed_rate_loan(amount, nrate, life, start, freq='A', grace=0,
dispoints=0, orgpoints=0, prepmt=None, balloonpmt=None):
"""Fixed rate loan.
Args:
amount (float): Loan amount.
nrate (float): nominal interest rate per year.
life (float): life of the loan.
s... | 10681a99ec381ec64517891d8d1101ed5eae78f4 | 18,438 |
import json
def get_results():
"""
Returns the scraped results for a set of inputs.
Inputs:
The URL, the type of content to scrap and class/id name.
This comes from the get_results() function in script.js
Output:
Returns a JSON list of the results
"""
# Decode the json data an... | 59af271fc024854258c488f17489383f424dfae3 | 18,439 |
def _mocked_presets(*args, **kwargs):
"""Return a list of mocked presets."""
return [MockPreset("1")] | ebf48fb23dff67b2d1a9faac6e72764f2a5f8f0a | 18,440 |
def play(context, songpos=None):
"""
*musicpd.org, playback section:*
``play [SONGPOS]``
Begins playing the playlist at song number ``SONGPOS``.
The original MPD server resumes from the paused state on ``play``
without arguments.
*Clarifications:*
- ``play "-1"`` when playin... | fc2cee0b3cca2df33b844004ecaaaa1b0eaa5347 | 18,441 |
from typing import Union
def SMLB(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""
Taken from Minerbo, G. N. and Levy, M. E., "Inversion of Abel’s integral equation by means of orthogonal polynomials.",
SIAM J. Numer. Anal. 6, 598-616 and swapped to satisfy SMLB(0) = 0.
"""
return (np... | ed9b59ccbf99458796d11521825ba6ab0215144d | 18,442 |
def add_colon(in_str):
"""Add colon after every 4th character."""
return ':'.join([in_str[i:i+4] for i in range(0, len(in_str), 4)]) | fa4258aa9d684a087d2a81ae09a2702d6e58e3e1 | 18,443 |
def fetch_partial_annotations():
""" Returns the partial annotations as an array
Returns:
partial_annotations: array of annotation data - [n_annotations, 5]
row format is [T, L, X, Y, Z]
"""
raw_mat = loadmat(PARTIAL_ANNOTATIONS_PATH)
annotations = raw_mat['divisionAnnotations']
#... | 69d57df06576af141dcc0eb9b00c7834e1a4a2c2 | 18,444 |
def get_alt_pos_info(rec):
"""Returns info about the second-most-common nucleotide at a position.
This nucleotide will usually differ from the reference nucleotide, but it
may be the reference (i.e. at positions where the reference disagrees with
the alignment's "consensus").
This breaks ties arbi... | 3abe3fcbbf0ddbccb44025f2e476f77dc3e8abf9 | 18,445 |
import torch
def accuracy(output, target, topk=(1,)):
""" Computes the accuracy over the k top predictions for the specified
values of k.
"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
... | d2edbbff872670f1637696e63fe448a749138985 | 18,446 |
def grim(n, mu, prec=2, n_items=1):
"""
Test that a mean mu reported with a decimal precision prec is possible, given a number of observations n and a
number of items n_items.
:param n: The number of observations
:param mu: The mean
:param prec: The precision (i.e., number of decimal places) of... | 093fdea1b59157b477642b31afa8388192188020 | 18,447 |
def split_dataframe(df:pd.DataFrame,split_index:np.ndarray):
"""
Split out the continuous variables from a dataframe \n
Params:
df : Pandas dataframe
split_index : Indices of continuous variables
"""
return df.loc[:,split_index].values | 842f9b04d0d546b8bef28f0b110e7d570eb8f0a0 | 18,448 |
def user_select_columns():
"""
Useful columns from the users table, omitting authentication-related
columns like password.
"""
u = orm.User.__table__
return [
u.c.id,
u.c.user_name,
u.c.email,
u.c.first_name,
u.c.last_name,
u.c.org,
u.c.cre... | faf7ffd18a2fc6c55c1f8a4c19d176a34f79e19f | 18,449 |
def remove_query_param(url, key):
"""
Given a URL and a key/val pair, remove an item in the query
parameters of the URL, and return the new URL.
"""
(scheme, netloc, path, query, fragment) = urlparse.urlsplit(url)
query_dict = urlparse.parse_qs(query)
query_dict.pop(key, None)
query = ur... | 4a7ac5b2b1767a6fbc082e7e5b4f2d10dbd87926 | 18,450 |
def test_ap_hs20_sim(dev, apdev):
"""Hotspot 2.0 with simulated SIM and EAP-SIM"""
if not hlr_auc_gw_available():
return "skip"
hs20_simulated_sim(dev[0], apdev[0], "SIM")
dev[0].request("INTERWORKING_SELECT auto freq=2412")
ev = dev[0].wait_event(["INTERWORKING-ALREADY-CONNECTED"], timeout=... | cbda3f0ebc33c3d0e8ee6a99a088a61c57655480 | 18,451 |
def FreshReal(prefix='b', ctx=None):
"""Return a fresh real constant in the given context using the given prefix.
>>> x = FreshReal()
>>> y = FreshReal()
>>> eq(x, y)
False
>>> x.sort()
Real
"""
ctx = _get_ctx(ctx)
return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ct... | afc312fbd85387adcfe72c81c5af5b06fe0ccee1 | 18,452 |
import threading
def handle_readable(client):
"""
Return True: The client is re-registered to the selector object.
Return False: The server disconnects the client.
"""
data = client.recv(1028)
if data == b'':
return False
client.sendall(b'SERVER: ' + data)
print(threading.acti... | 9a77bb893a5da4e76df5593feb6ecf49022e6ef3 | 18,454 |
from datetime import datetime
import logging
def fund_wallet():
"""
---
post:
summary: fund a particular wallet
description: sends funds to a particular user given the user id the amount will be
removed from the wallet with the respective currency, if not it falls to the default walle... | 55955335f4462ad118fb792f3335db8090f7439e | 18,455 |
import numpy
def create_objective(dist, abscissas):
"""Create objective function."""
abscissas_ = numpy.array(abscissas[1:-1])
def obj(absisa):
"""Local objective function."""
out = -numpy.sqrt(dist.pdf(absisa))
out *= numpy.prod(numpy.abs(abscissas_ - absisa))
return out
... | c63eeadffd067c2a94470ddbf03fb009265fbbbc | 18,456 |
def get_party_to_seats(year, group_id, party_to_votes):
"""Give votes by party, compute seats for party."""
eligible_party_list = get_eligible_party_list(
group_id,
party_to_votes,
)
if not eligible_party_list:
return {}
n_seats = YEAR_TO_REGION_TO_SEATS[year][group_id]
... | 02270cfeefb87b3da0ec4fa88dfb692a4645df5e | 18,457 |
def get_product(name, version):
"""Get info about a specific version of a product"""
product = registry.get_product(name, version)
return jsonify(product.to_dict()) | 0c461d672ef4d07578b098b3cb937027ad8946f1 | 18,458 |
def _is_segment_in_block_range(segment, blocks):
"""Return whether the segment is in the range of one of the blocks."""
for block in blocks:
if block.start <= segment.start and segment.end <= block.end:
return True
return False | e7509f18f0a72cf90fb1aa643c77c2e13154f0d0 | 18,459 |
def compute_snes_color_score(img):
""" Returns the ratio of SNES colors to the total number of colors in the image
Parameters:
img (image) -- Pillow image
Returns:
count (float) -- ratio of SNES colors
"""
score = _get_distance_between_palettes(img, util.get_snes_color_p... | b52ae8d7d98700f455e126cfb447e41c1762528c | 18,462 |
def get_assignments_for_team(user, team):
""" Get openassessment XBlocks configured for the current teamset """
# Confirm access
if not has_specific_team_access(user, team):
raise Exception("User {user} is not permitted to access team info for {team}".format(
user=user.username,
... | 67b72b34b8549127728c33dfac8599d979d09f6f | 18,463 |
def is_flexible_uri(uri: Uri_t) -> bool:
"""Judge if specified `uri` has one or more flexible location.
Args:
uri: URI pattern to be judged.
Returns:
True if specified `uri` has one or more flexible location,
False otherwise.
"""
for loc in uri:
if isinstance(loc, F... | fd5138d3dfc44c36e7b5ccfe911f6640e22bc7f2 | 18,464 |
def load_frame_gray(img_path, gray_flag=False):
"""Load image at img_path, and convert the original image to grayscale if gray_flag=True.
Return image and grayscale image if gray_flag=True; otherwise only return original image.
img_path = a string containing the path to an image file readable by cv.imread
... | 8b792f2bf5f22f34e0b880c934019c238a3cc360 | 18,465 |
def read_vocab_file(path):
""" Read voc file.
This reads a .voc file, stripping out empty lines comments and expand
parentheses. It returns each line as a list of all expanded
alternatives.
Args:
path (str): path to vocab file.
Returns:
List of List... | cdf230f1fbeafbcc3839a02ce86b33719dfcf806 | 18,466 |
import re
def natural_key(string_):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)] | f49aca918e4efc2f5e7f6541df2d5329bc2752f7 | 18,467 |
def generate_episode(sim, policy, horizon=200):
"""
Generate an episode from a policy acting on an simulation.
Returns: sequence of state, action, reward.
"""
obs = sim.reset()
policy.reset() # Reset the policy too so that it knows its the beginning of the episode.
states, actions, rewards ... | 73a0bbb2703c047d3305e93dd2a340c83db12277 | 18,469 |
import asyncio
async def _ensure_meadowrun_vault(location: str) -> str:
"""
Gets the meadowrun key vault URI if it exists. If it doesn't exist, also creates the
meadowrun key vault, and tries to assign the Key Vault Administrator role to the
current user.
"""
subscription_id = await get_subsc... | 9e16940a56ae83b47d42d7583ad6efc9c5d63d23 | 18,470 |
from typing import Iterable
from typing import Dict
from typing import List
from typing import Union
from pathlib import Path
from typing import Tuple
import logging
def get_dataset_splits(
datasets: Iterable[HarmonicDataset],
data_dfs: Dict[str, pd.DataFrame] = None,
xml_and_csv_paths: Dict[str, List[Uni... | c1389dad05aa2911735b1e9099acda9e2a8a1c05 | 18,471 |
from PilotErrors import PilotException
from movers import JobMover
from movers.trace_report import TraceReport
import traceback
def put_data_es(job, jobSite, stageoutTries, files, workDir=None, activity=None):
"""
Do jobmover.stageout_outfiles or jobmover.stageout_logfiles (if log_transfer=True)
o... | b3841dc487e19ca989575e37b95a9e8f2949258b | 18,472 |
def floor(data):
"""
Returns element-wise largest integer not greater than x.
Args:
data (tvm.tensor.Tensor): Tensor of type float16, and float32
Returns:
tvm.tensor.Tensor, has the same shape as data and type of int32.
"""
vc_util.ops_dtype_check(data.dtype, vc_util.DtypeForDa... | 3d553d54330c3237908b33600fae560a92f20975 | 18,473 |
def pixel_link_model(inputs, config):
""" PixelLink architecture. """
if config['model_type'] == 'mobilenet_v2_ext':
backbone = mobilenet_v2(inputs, original_stride=False,
weights_decay=config['weights_decay'])
elif config['model_type'] == 'ka_resnet50':
back... | 0bf606e5b06d94bce98865147fb6a1cf45b04560 | 18,474 |
def ingresar_datos():
"""Pide al usuario los datos para calcular el precio de la compra
de boletos.
:return: tipo, cantidad
:rtype: tuple
"""
text_align("Datos de la compra", width=35)
tipo: str = choice_input(tuple(TIPO.keys()))
cantidad: int = int_input("Ingrese el número de boletos: ... | eb9b1c90fbc44a639a7760848723f5579eced4df | 18,475 |
def trim_spectrum(freqs, power_spectra, f_range):
"""Extract a frequency range from power spectra.
Parameters
----------
freqs : 1d array
Frequency values for the power spectrum.
power_spectra : 1d or 2d array
Power spectral density values.
f_range: list of [float, float]
... | a522a384033fc38d3bba5e7d91ca8debfdedec68 | 18,476 |
def _get_variable_for(v):
"""Returns the ResourceVariable responsible for v, or v if not necessary."""
if v.op.type == "VarHandleOp":
for var in ops.get_collection(ops.GraphKeys.RESOURCES):
if (isinstance(var, resource_variable_ops.ResourceVariable)
and var.handle.op is v... | 5e8f4b83495c89f728c30148e9b05e06713d6b82 | 18,477 |
def load_prefixes(filepath):
"""Dado um arquivo txt contendo os prefixos utilizados na SPARQL, é
devolvida uma string contendo os prefixos e uma lista de tuplas contendo
os prefixos.
Parameters
----------
filepath : str
Caminho do arquivo txt contendo o conjunto de prefixos.
Return... | a6c2f3c014dbfae73718c579da914f840489e701 | 18,478 |
def build_convolutional_box_predictor(is_training,
num_classes,
conv_hyperparams_fn,
min_depth,
max_depth,
num_layers_before_predi... | 3e3b79cbd6e99b8b9d3da5ff2545e17a92ef3f38 | 18,479 |
def parse_command_line():
"""
:return:
"""
parser = argp.ArgumentParser(prog='TEPIC/findBackground.py', add_help=True)
ag = parser.add_argument_group('Input/output parameters')
ag.add_argument('--input', '-i', type=str, dest='inputfile', required=True,
help='Path to input fi... | 1f12e08cf4c86f40a84a09303d75a5d3506a3a14 | 18,481 |
import torch
def disparity_to_idepth(K, T_right_in_left, left_disparity):
"""Function athat transforms general (non-rectified) disparities to inverse
depths.
"""
assert(len(T_right_in_left.shape) == 3)
# assert(T_right_in_left.shape[0] == self.batch_size)
assert(T_right_in_left.shape[1] == 4)
... | 454bda2fd9ec4e4ef5615dbdb054c2f3b454f31a | 18,482 |
def auto_apilado(datos,target,agrupacion,porcentaje=False):
"""
Esta función recibe un set de datos DataFrame,
una variable target, y la variable
sobre la que se desean agrupar los datos (eje X).
Retorna un grafico de barras apilado.
"""
total = datos[[target,agrupacion]].groupby(agru... | b3b13e0e5bd56628971004c0d6d5171929ab6de3 | 18,484 |
from datetime import datetime
def month_from_string(month_str: str) -> datetime.date:
"""
Accepts year-month strings with hyphens such as "%Y-%m"
"""
return datetime.datetime.strptime(month_str, "%Y-%m").date() | cfb901f6676d40398bd6f49c438541f00e5389e3 | 18,485 |
import hashlib
def get_isomorphic_signature(graph: DiGraph) -> str:
"""
Generate unique isomorphic id with pynauty
"""
nauty_graph = pynauty.Graph(len(graph.nodes), directed=True, adjacency_dict=nx.to_dict_of_lists(graph))
return hashlib.md5(pynauty.certificate(nauty_graph)).hexdigest() | 8dfd7dd44409fee7dddd88f21681ed93232f1dba | 18,486 |
def _encode_raw_string(str):
"""Encodes a string using the above encoding format.
Args:
str (string): The string to be encoded.
Returns:
An encoded version of the input string.
"""
return _replace_all(str, _substitutions) | bb33875b276fe822c2b43ec3ebcc57b0d2f4c7b9 | 18,488 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.