content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def add_review(status):
"""
Adds the flags on the tracker document.
Input: tracker document.
Output: sum of the switches.
"""
cluster = status['cluster_switch']
classify = status['classify_switch']
replace = status['replace_switch']
final = status['final_switch']
finished = statu... | 8f2ba4cd8b6bd4e500e868f13733146579edd7ce | 3,648,459 |
def n_floordiv(a, b):
"""safe floordiv"""
return np.where(b != 0, o.floordiv(a, b), 1) | 461752cfceaac911ef3be2335c2eb3893d512cc7 | 3,648,460 |
def load_encoder_inputs(encoder_np_vecs='train_body_vecs.npy'):
"""
Load variables & data that are inputs to encoder.
Parameters
----------
encoder_np_vecs : str
filename of serialized numpy.array of encoder input (issue title)
Returns
-------
encoder_input_data : numpy.array
The issue body
... | 571cf13f6ff23fea5bb111ed12ac8afc06cc5f8b | 3,648,461 |
def parse_row(row):
"""Create an Event object from a data row
Args:
row: Tuple of input data.
Returns:
Event object.
"""
# Ignore either 1 or 2 columns that preceed year
if len(row) > 6:
row = row[2:]
else:
row = row[1:]
# Remove occasional 'r' or 'x' character prefix from year,
# I... | 22923ee8f8e0b3b29eab3052df0e0b8b74613f66 | 3,648,462 |
import math
import operator
from typing import Counter
def vertical_log_binning(p, data):
"""Create vertical log_binning. Used for peak sale."""
index, value = zip(*sorted(data.items(), key=operator.itemgetter(1)))
bin_result = []
value = list(value)
bin_edge = [min(value)]
i = 1
while len... | bf536250bc32a9bda54c8359589b10aa5936e902 | 3,648,463 |
def get_main_name(ext="", prefix=""):
"""Returns the base name of the main script. Can optionally add an
extension or prefix."""
return prefix + op.splitext(op.basename(__main__.__file__))[0] + ext | 03beb4da53436054bf61a4f68d8b0f3d51ac13be | 3,648,464 |
def _grad_block_to_band(op, grad):
"""
Gradient associated to the ``block_to_band`` operator.
"""
grad_block = banded_ops.band_to_block(
grad, op.get_attr("block_size"), symmetric=op.get_attr("symmetric"), gradient=True
)
return grad_block | 638c4047b224b80feb7c4f52151f96c4a62179b9 | 3,648,465 |
def LSTM(nO, nI):
"""Create an LSTM layer. Args: number out, number in"""
weights = LSTM_weights(nO, nI)
gates = LSTM_gates(weights.ops)
return Recurrent(RNN_step(weights, gates)) | 296b1a7cb73a0e5dcb50e4aa29b33c944768c688 | 3,648,466 |
import requests
def get_token(host, port, headers, auth_data):
"""Return token for a user.
"""
url = api_url(host, port, '/Users/AuthenticateByName')
r = requests.post(url, headers=headers, data=auth_data)
return r.json().get('AccessToken') | 4d58d50c1421c17e89fa2d8d2205f0e066749e73 | 3,648,467 |
from datetime import datetime
def generateDateTime(s):
"""生成时间"""
dt = datetime.fromtimestamp(float(s)/1e3)
time = dt.strftime("%H:%M:%S.%f")
date = dt.strftime("%Y%m%d")
return date, time | 8d566412230b5bb779baa395670ba06457c2074f | 3,648,468 |
def get_activation_function():
"""
Returns tf.nn activation function
"""
return ACTIVATION_FUNCTION | 9f55f5122f708120ce7a5181b7035681f37cc0c6 | 3,648,469 |
import requests
import json
def doi_and_title_from_citation(citation):
"""
Gets the DOI from
a plaintext citation.
Uses a search to CrossRef.org to retrive paper DOI.
Parameters
----------
citation : str
Full journal article citation.
Example: Senís, Elena, et al. "CRISPR... | bd51d91c414c97a9e061d889a27917c1b487edd1 | 3,648,470 |
def prep_ciphertext(ciphertext):
"""Remove whitespace."""
message = "".join(ciphertext.split())
print("\nciphertext = {}".format(ciphertext))
return message | a5cd130ed3296addf6a21460cc384d8a0582f862 | 3,648,471 |
def main():
"""Runs dir()."""
call = PROCESS_POOL.submit(call_dir)
while True:
if call.done():
result = call.result().decode()
print("Results: \n\n{}".format(result))
return result | 6e02aab50023ed9b72c2f858122a2652a2f4607f | 3,648,473 |
def bacthing_predict_SVGPVAE_rotated_mnist(test_data_batch, vae, svgp,
qnet_mu, qnet_var, aux_data_train):
"""
Get predictions for test data. See chapter 3.3 in Casale's paper.
This version supports batching in prediction pipeline (contrary to function predict_SVGP... | 6603db14abbd7bbb2ba8965ee43d876d4a607b0a | 3,648,474 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""
Set up Strava Home Assistant config entry initiated through the HASS-UI.
"""
hass.data.setdefault(DOMAIN, {})
# OAuth Stuff
try:
implementation = await config_entry_oauth2_flow.async_get_config_entry_implementati... | 9ba10cf00f447d0e2038b8a542a45166c264b801 | 3,648,475 |
from typing import List
from typing import Tuple
from typing import Union
def normalize_boxes(boxes: List[Tuple], img_shape: Union[Tuple, List]) -> List[Tuple]:
"""
Transform bounding boxes back to yolo format
"""
img_height = img_shape[1]
img_width = img_shape[2]
boxes_ = []
for i in ran... | 086e0b069d06a4718e8ffd37189cf3d08c41d19f | 3,648,476 |
import copy
def _make_reference_filters(filters, ref_dimension, offset_func):
"""
Copies and replaces the reference dimension's definition in all of the filters applied to a dataset query.
This is used to shift the dimension filters to fit the reference window.
:param filters:
:param ref_dimensi... | eeeeb74bb3618c87f3540de5b44970e197885dc6 | 3,648,477 |
def load_plane_dataset(name, num_points, flip_axes=False):
"""Loads and returns a plane dataset.
Args:
name: string, the name of the dataset.
num_points: int, the number of points the dataset should have,
flip_axes: bool, flip x and y axes if True.
Returns:
A Dataset object... | aee32a6aa7f2be6ae515d6f3b1e27cda4d0f705e | 3,648,479 |
def get_toxic(annotated_utterance, probs=True, default_probs=None, default_labels=None):
"""Function to get toxic classifier annotations from annotated utterance.
Args:
annotated_utterance: dictionary with annotated utterance, or annotations
probs: return probabilities or not
default: d... | ac69075af2edd9cdc84383054ba9ebe700dddb58 | 3,648,480 |
def compute_energy_lapkmode(X,C,l,W,sigma,bound_lambda):
"""
compute Laplacian K-modes energy in discrete form
"""
e_dist = ecdist(X,C,squared =True)
g_dist = np.exp(-e_dist/(2*sigma**2))
pairwise = 0
Index_list = np.arange(X.shape[0])
for k in range(C.shape[0]):
tmp=np.asa... | 3fc5c2f9695e33eb3d1ac42a3172c30f1d81d23b | 3,648,481 |
def calc_2d_wave_map(wave_grid, x_dms, y_dms, tilt, oversample=2, padding=10, maxiter=5, dtol=1e-2):
"""Compute the 2D wavelength map on the detector.
:param wave_grid: The wavelength corresponding to the x_dms, y_dms, and tilt values.
:param x_dms: the trace x position on the detector in DMS coordinates.
... | 727002a0cc61f6219c92d6db3d31eb653f849f03 | 3,648,482 |
def export_data():
"""Exports data to a file"""
data = {}
data['adgroup_name'] = request.args.get('name')
if data['adgroup_name']:
data['sitelist'] = c['adgroups'].find_one({'name':data['adgroup_name']}, {'sites':1})['sites']
return render_template("export.html", data=data) | a6b43f90907e174f07773b0ed7603a48a3ff35ca | 3,648,484 |
def thresh_bin(img, thresh_limit=60):
""" Threshold using blue channel """
b, g, r = cv2.split(img)
# mask = get_salient(r)
mask = cv2.threshold(b, 50, 255, cv2.THRESH_BINARY_INV)[1]
return mask | 3660179d1e1c411feb44e993a8ab94f10c63d6e4 | 3,648,485 |
from typing import Any
def get_aux():
"""Get the entire auxiliary stack. Not commonly used."""
@parser
def g(c: Cursor, a: Any):
return a, c, a
return g | b345901f4987e8849fbe35c0c997f38480d79f04 | 3,648,486 |
def _destupidize_dict(mylist):
"""The opposite of _stupidize_dict()"""
output = {}
for item in mylist:
output[item['key']] = item['value']
return output | f688e25a9d308e39f47390fef493ab80d303ea15 | 3,648,487 |
def equipment_add(request, type_, id_=None):
"""Adds an equipment."""
template = {}
if request.method == 'POST':
form = EquipmentForm(request.POST)
if form.is_valid():
form.save(request.user, id_)
return redirect('settings_equipment')
template['form'] = fo... | a8f2fce6c9aa64316edb96df9597fbfb516839a3 | 3,648,488 |
def _parse_text(val, **options):
"""
:return: Parsed value or value itself depends on 'ac_parse_value'
"""
if val and options.get('ac_parse_value', False):
return parse_single(val)
return val | cbd0d0b65237e8d3f817aa0bae1861f379a68b26 | 3,648,489 |
def get_rotation_matrix(rotation_angles):
"""Get the rotation matrix from euler's angles
Parameters
-----
rotation_angles: array-like or list
Three euler angles in the order [sai, theta, phi] where
sai = rotation along the x-axis
theta = rotation along the y-axis
phi = r... | 2965d1ce5c688e794f7fce6e51afd2e558c1bab7 | 3,648,491 |
def _metric_list_for_check(maas_store, entity, check):
"""
Computes the metrics list for a given check.
Remote checks return a metric for each monitoring zone and
each type of metric for the check type. Agent checks return
a metric for each metric type on the check type. Check types
that Mimic ... | c295f976c8c85d60af8f6e734f666381bc0186d2 | 3,648,492 |
def filter_pdf_files(filepaths):
""" Returns a filtered list with strings that end with '.pdf'
Keyword arguments:
filepaths -- List of filepath strings
"""
return [x for x in filepaths if x.endswith('.pdf')] | 3f44b3af9859069de866cec3fac33a9e9de5439d | 3,648,494 |
def hue_quadrature(h: FloatingOrArrayLike) -> FloatingOrNDArray:
"""
Return the hue quadrature from given hue :math:`h` angle in degrees.
Parameters
----------
h
Hue :math:`h` angle in degrees.
Returns
-------
:class:`numpy.floating` or :class:`numpy.ndarray`
Hue quadra... | df120ae34dfc45ecbb818718885cbbb501667bdd | 3,648,496 |
def aa_find_devices_ext (devices, unique_ids):
"""usage: (int return, u16[] devices, u32[] unique_ids) = aa_find_devices_ext(u16[] devices, u32[] unique_ids)
All arrays can be passed into the API as an ArrayType object or as
a tuple (array, length), where array is an ArrayType object and
length is an i... | 1b84cfc3d6fd52f786c2191fde4d37a6287e8b87 | 3,648,497 |
def _get_blobs(im, rois):
"""Convert an image and RoIs within that image into network inputs."""
blobs = {'data' : None, 'rois' : None}
blobs['data'], im_scale_factors = _get_image_blob(im)
if not cfg.TEST.HAS_RPN:
blobs['rois'] = _get_rois_blob(rois, im_scale_factors)
#print ('lll: ', blobs['r... | d4adb2e049a86fe1a42aab6dea52b55aabeeb0d2 | 3,648,500 |
def string_limiter(text, limit):
"""
Reduces the number of words in the string to length provided.
Arguments:
text -- The string to reduce the length of
limit -- The number of characters that are allowed in the string
"""
for i in range(len(text)):
if i >= limit an... | 1ae70d2115be72ec628f38b2c623064607f534ef | 3,648,501 |
def in_ellipse(xy_list,width,height,angle=0,xy=[0,0]):
"""
Find data points inside an ellipse and return index list
Parameters:
xy_list: Points needs to be deteced.
width: Width of the ellipse
height: Height of the ellipse
angle: anti-clockwise rotation angle in degrees
... | 6540520caa6eef12871847f80d3ed42279b0c1a0 | 3,648,502 |
import logging
def get_real_images(dataset,
num_examples,
split=None,
failure_on_insufficient_examples=True):
"""Get num_examples images from the given dataset/split.
Args:
dataset: `ImageDataset` object.
num_examples: Number of images to read.
... | 0f9be93076b8d94b3285a1f5badb8952788e2a82 | 3,648,503 |
from typing import Callable
from typing import Any
import websockets
async def call(fn: Callable, *args, **kwargs) -> Any:
"""
Submit function `fn` for remote execution with arguments `args` and `kwargs`
"""
async with websockets.connect(WS_SERVER_URI) as websocket:
task = serialize((fn, args... | 073090186e4a325eb32b44fb44c1628c6842c398 | 3,648,504 |
import numpy
def wrap_array_func(func):
"""
Returns a version of the function func() that works even when
func() is given a NumPy array that contains numbers with
uncertainties.
func() is supposed to return a NumPy array.
This wrapper is similar to uncertainties.wrap(), except that it
ha... | 7cbd33599b62df096db3ce84968cc13f24512fc0 | 3,648,505 |
def checkCrash(player, upperPipes, lowerPipes):
"""returns True if player collides with base or pipes."""
pi = player['index']
player['w'] = fImages['player'][0].get_width()
player['h'] = fImages['player'][0].get_height()
# if player crashes into ground
if player['y'] + player['h'] >= nBaseY -... | e638f0ae40610fc0c4097998e8fa3df0dc6a5d56 | 3,648,506 |
def convert_gwp(context, qty, to):
"""Helper for :meth:`convert_unit` to perform GWP conversions."""
# Remove a leading 'gwp_' to produce the metric name
metric = context.split('gwp_')[1] if context else context
# Extract the species from *qty* and *to*, allowing supported aliases
species_from, uni... | 23d47e3b93f1ed694fbb5187433af5c8caa72dc8 | 3,648,508 |
import random
def getAction(board, policy, action_set):
"""
return action for policy, chooses max from classifier output
"""
# if policy doesn't exist yet, choose action randomly, else get from policy model
if policy == None:
valid_actions = [i for i in action_set if i[0] > -1]
if ... | fddb9160f0571dfaf50f945c05d5dbb176465180 | 3,648,510 |
def f_assert_must_between(value_list, args):
"""
检测列表中的元素是否为数字或浮点数且在args的范围内
:param value_list: 待检测列表
:param args: 范围列表
:return: 异常或原值
example:
:value_list [2, 2, 3]
:args [1,3]
:value_list ['-2', '-3', 3]
:a... | 6e082f3df39509f0823862497249a06080bd7649 | 3,648,511 |
from scipy.stats import zscore
from scipy.ndimage import label
def annotate_muscle_zscore(raw, threshold=4, ch_type=None, min_length_good=0.1,
filter_freq=(110, 140), n_jobs=1, verbose=None):
"""Create annotations for segments that likely contain muscle artifacts.
Detects data segm... | a09b2b9098c7dfc48b29548691e3c6c524a6b6bf | 3,648,512 |
def circ_dist2(a, b):
"""Angle between two angles
"""
phi = np.e**(1j*a) / np.e**(1j*b)
ang_dist = np.arctan2(phi.imag, phi.real)
return ang_dist | db60caace70f23c656c4e97b94145a246c6b2995 | 3,648,513 |
def hinge_loss(positive_scores, negative_scores, margin=1.0):
"""
Pairwise hinge loss [1]:
loss(p, n) = \sum_i [\gamma - p_i + n_i]_+
[1] http://yann.lecun.com/exdb/publis/pdf/lecun-06.pdf
:param positive_scores: (N,) Tensor containing scores of positive examples.
:param negative_scores: (... | daa698f012c30c8f99ba1ce08cbb73226251e3c1 | 3,648,514 |
def build(req):
"""Builder for this format.
Args:
req: flask request
Returns:
Json containing the creative data
"""
errors = []
v = {}
tdir = "/tmp/" + f.get_tmp_file_name()
index = get_html()
ext = f.get_ext(req.files["videofile"].filename)
if ext != "mp4":
return {"errors": ["Only ... | 33ad1e003533407626cd3ccdd52e7f6c414e6470 | 3,648,515 |
def search(query, data, metric='euclidean', verbose=True):
"""
do search, return ranked list according to distance
metric: hamming/euclidean
query: one query per row
dat: one data point per row
"""
#calc dist of query and each data point
if metric not in ['euclidean', 'hamming']:
... | 576471dfbe1dc0a2ae80235faf36d42d4b3a7f8a | 3,648,516 |
def create_circle_widget(canvas: Canvas, x: int, y: int, color: str, circle_size: int):
"""create a centered circle on cell (x, y)"""
# in the canvas the 1st axis is horizontal and the 2nd is vertical
# we want the opposite so we flip x and y for the canvas
# to create an ellipsis, we give (x0, y0) and ... | b048b7d9c262c40a93cfef489468ad709a1e3883 | 3,648,517 |
def _format_program_counter_relative(state):
"""Program Counter Relative"""
program_counter = state.program_counter
operand = state.current_operand
if operand & 0x80 == 0x00:
near_addr = (program_counter + operand) & 0xFFFF
else:
near_addr = (program_counter - (0x100 - operand)) & ... | 74f13e9230a6c116413b373b92e36bd884a906e7 | 3,648,518 |
def compile_program(
program: PyTEAL, mode: Mode = Mode.Application, version: int = 5
) -> bytes:
"""Compiles a PyTEAL smart contract program to the TEAL binary code.
Parameters
----------
program
A function which generates a PyTEAL expression, representing an Algorand program.
mode
... | 50e9b4263a0622dfbe427c741ddfba2ff4007089 | 3,648,519 |
def predict(yolo_outputs, image_shape, anchors, class_names, obj_threshold, nms_threshold, max_boxes = 1000):
"""
Process the results of the Yolo inference to retrieve the detected bounding boxes,
the corresponding class label, and the confidence score associated.
The threshold value 'obj_threshold' serves to disca... | df90a5baed671e316e03c0a621ce1740efc7a833 | 3,648,521 |
def ae_model(inputs, train=True, norm=True, **kwargs):
"""
AlexNet model definition as defined in the paper:
https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf
You will need to EDIT this function. Please put your AlexNet implementation here.
N... | 659908f6fbfb401941984668634382c6d30a8124 | 3,648,523 |
def filter_by_country(data, country=DEFAULT_COUNTRY):
"""
Filter provided data by country (defaults to Czechia).
data: pandas.DataFrame
country: str
"""
# Filter data by COUNTRY
return data[data[COLUMN_FILTER] == country] | bbf9eacd74a6032f1298cd7313d5c8233ec4a8ec | 3,648,524 |
def scans_from_csvs(*inps, names=None):
"""
Read from csvs.
:param inps: file names of the csvs
:param names: names of the Scans
:return: list of Scans
"""
ns, temp_vals, heat_flow_vals = read_csvs(inps)
names = ns if names is None else names
return [Scan(*vals) for vals in zip(temp... | 6acddf330e10793dab6b76ec6a1edb1d2fd0660d | 3,648,526 |
def part_b(puzzle_input):
"""
Calculate the answer for part_b.
Args:
puzzle_input (list): Formatted as the provided input from the website.
Returns:
string: The answer for part_b.
"""
return str(collect_letters(puzzle_input)[1]) | b82597c610e8a7d03ea68ddad392385636b0e2f3 | 3,648,527 |
def data_encoder(data):
"""
Encode all categorical values in the dataframe into numeric values.
@param data: the original dataframe
@return data: the same dataframe with all categorical variables encoded
"""
le = preprocessing.LabelEncoder()
cols = data.columns
numcols = data._get_n... | 2a2177891e1930311661f6549dbd33f329704fec | 3,648,528 |
def _search_settings(method_settings_keys, settings):
"""
We maintain a dictionary of dimensionality reduction methods
in dim_settings_keys where each key (method) stores another
dictionary (md) holding that method's settings (parameters).
The keys of md are component ids and the values are paramete... | 20a8a0e24df1dc572dfbe541f1439bc6245f6170 | 3,648,529 |
def svn_opt_resolve_revisions(*args):
"""
svn_opt_resolve_revisions(svn_opt_revision_t peg_rev, svn_opt_revision_t op_rev,
svn_boolean_t is_url, svn_boolean_t notice_local_mods,
apr_pool_t pool) -> svn_error_t
"""
return _core.svn_opt_resolve_revisions(*args) | 5f011401c4afc044f0fa877407f7c7a3da56f576 | 3,648,530 |
from typing import Union
from pathlib import Path
from typing import Any
def write_midi(
path: Union[str, Path],
music: "Music",
backend: str = "mido",
**kwargs: Any
):
"""Write a Music object to a MIDI file.
Parameters
----------
path : str or Path
Path to write the MIDI file... | 963e5aafffbc348df17861b615c2e839c170adce | 3,648,531 |
import string
from re import VERBOSE
def find_star_column(file, column_type, header_length) :
""" For an input .STAR file, search through the header and find the column numbers assigned to a given column_type (e.g. 'rlnMicrographName', ...)
"""
with open(file, 'r') as f :
line_num = 0
for ... | 832a63d2084b6f007c0b58fbafbe037d0a81ab38 | 3,648,532 |
def recalculate_bb(df, customization_dict, image_dir):
"""After resizing images, bb coordinates are recalculated.
Args:
df (Dataframe): A df for image info.
customization_dict (dict): Resize dict.
image_dir (list): Image path list
Returns:
Dataframe: Updated dataframe.
... | 412149195898e492405fe58aef2d8c8ce360cef7 | 3,648,533 |
def free_port():
"""Returns a free port on this host
"""
return get_free_port() | 94765cdb1a6e502c9ad650956754b3eda7f1b060 | 3,648,534 |
def justify_to_box(
boxstart: float,
boxsize: float,
itemsize: float,
just: float = 0.0) -> float:
"""
Justifies, similarly, but within a box.
"""
return boxstart + (boxsize - itemsize) * just | a644d5a7a6ff88009e66ffa35498d9720b24222c | 3,648,535 |
import time
def generate_hostname(domain, hostname):
"""If hostname defined, returns FQDN.
If not, returns FQDN with base32 timestamp.
"""
# Take time.time() - float, then:
# - remove period
# - truncate to 17 digits
# - if it happen that last digits are 0 (and will not be displayed, s... | 54d85cea2b2aa69cc2864b0974852530453d63ca | 3,648,537 |
def symmetrize(M):
"""Return symmetrized version of square upper/lower triangular matrix."""
return M + M.T - np.diag(M.diagonal()) | a2f1311aa96d91d5c4992ad21018b07ac5954d1c | 3,648,538 |
def prep_public_water_supply_fraction() -> pd.DataFrame:
"""calculates public water supply deliveries for the commercial and industrial sectors individually
as a ratio to the sum of public water supply deliveries to residential end users and thermoelectric cooling.
Used in calculation of public water supp... | bb759cfa25add08b0faf0d9232448698d0ae8d53 | 3,648,540 |
def set_matchq_in_constraint(a, cons_index):
"""
Takes care of the case, when a pattern matching has to be done inside a constraint.
"""
lst = []
res = ''
if isinstance(a, list):
if a[0] == 'MatchQ':
s = a
optional = get_default_values(s, {})
r = gener... | c40f15f500736102f4abf17169715387c2f1b91b | 3,648,541 |
def istype(klass, object):
"""Return whether an object is a member of a given class."""
try: raise object
except klass: return 1
except: return 0 | bceb83914a9a346c59d90984730dddb808bf0e78 | 3,648,542 |
from typing import Mapping
from typing import Any
def _embed_from_mapping(mapping: Mapping[str, Any], ref: str) -> mapry.Embed:
"""
Parse the embed from the mapping.
All the fields are parsed except the properties, which are parsed
in a separate step.
:param mapping: to be parsed
:param ref:... | 10d3894aa33d41efd47f03335c6e90547ee26e6c | 3,648,543 |
import pdb
def generate_csv_from_pnl(pnl_file_name):
"""在.pnl文件的源路径下新生成一个.csv文件. 拷贝自export_to_csv函数. pnl_file_name需包含路径. """
pnlc = alib.read_pnl_from_file(pnl_file_name)
pnl = pnlc[1]
if pnl is None:
print('pnl文件{}不存在!'.format(pnl_file_name))
pdb.set_trace()
csv_file_name = pnl_fi... | ceed6ce7d31fe6cb738252b7458c2f404c01135c | 3,648,544 |
def parse_number(text, allow_to_fail):
"""
Convert to integer, throw if fails
:param text: Number as text (decimal, hex or binary)
:return: Integer value
"""
try:
if text in defines:
return parse_number(defines.get(text), allow_to_fail)
return to_number(text)
exce... | 90906b56e8a88fcde9f66defeed48cf12371d375 | 3,648,545 |
import importlib
def pick_vis_func(options: EasyDict):
"""Pick the function to visualize one batch.
:param options:
:return:
"""
importlib.invalidate_caches()
vis_func = getattr(
import_module("utils.vis.{}".format(options.vis.name[0])),
"{}".format(options.vis.name[1])
)
... | 4d65f00075c984e5407af09d3680f2195be640bb | 3,648,546 |
import numpy
def scale_quadrature(quad_func, order, lower, upper, **kwargs):
"""
Scale quadrature rule designed for unit interval to an arbitrary interval.
Args:
quad_func (Callable):
Function that creates quadrature abscissas and weights on the unit
interval.
orde... | f3854cee12a482bc9c92fe2809a0388dddb422e0 | 3,648,547 |
def ask_for_region(self):
"""ask user for region to select (2-step process)"""
selection = ["BACK"]
choices = []
while "BACK" in selection:
response = questionary.select(
"Select area by (you can go back and combine these choices):",
choices=["continents", "regions", "co... | dd7ea9ca33ca8348fba0d36c5661b6fd30c96090 | 3,648,548 |
import array
def peakAlign(refw,w):
""" Difference between the maximum peak positions of the signals.
This function returns the difference, in samples, between the peaks position
of the signals. If the reference signal has various peaks, the one
chosen is the peak which is closer to the middle ... | a7497e828008281318dff25b5547e0ab4f8e9a35 | 3,648,549 |
def get_games(by_category, n_games):
"""
This function imports the dataframe of most popular games and returns a list of game names
with the length of 'n_games' selected by 'by_category'. Valid options for 'by_category': rank, num_user_ratings
"""
df = pd.read_csv('../data/popular_games_with_image_u... | 2702d6b072ba9ac49565c9ee768d65c431441724 | 3,648,550 |
def diurnalPDF( t, amplitude=0.5, phase=pi8 ):
"""
"t" must be specified in gps seconds
we convert the time in gps seconds into the number of seconds after the most recent 00:00:00 UTC
return (1 + amplitude*sin(2*pi*t/day - phase))/day
"""
if amplitude > 1:
raise ValueError("amplitude ca... | 6bf755851d2bf2582ca98c1bcbe67aa7dc4e0a2f | 3,648,551 |
def imap_workers(workers, size=2, exception_handler=None):
"""Concurrently converts a generator object of Workers to
a generator of Responses.
:param workers: a generator of worker objects.
:param size: Specifies the number of workers to make at a time. default is 2
:param exception_handler: Callbac... | c4ab81770b40238025055394bf43ca0dc99dd506 | 3,648,552 |
import time
def output_time(time_this:float=None,end:str=" | ")->float:
"""输入unix时间戳,按格式输出时间。默认为当前时间"""
if not time_this:
time_this=time.time()-TIMEZONE
print(time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(time_this)),end=end)
#
return time_this | ba17400306af7142a91bd5b62941c52fc59dbf1a | 3,648,553 |
def blend_color(color1, color2, blend_ratio):
"""
Blend two colors together given the blend_ration
:param color1: pygame.Color
:param color2: pygame.Color
:param blend_ratio: float between 0.0 and 1.0
:return: pygame.Color
"""
r = color1.r + (color2.r - color1.r) * blend_ratio
g = c... | 0bb7fa1570472e60bd93a98f6da3a515ca9dd500 | 3,648,554 |
def solve_a_star(start_id: str, end_id: str, nodes, edges):
"""
Get the shortest distance between two nodes using Dijkstra's algorithm.
:param start_id: ID of the start node
:param end_id: ID of the end node
:return: Shortest distance between start and end node
"""
solution_t_start = perf_c... | 467257c15c7a99d217d75b69876b2f64ecd0b58e | 3,648,556 |
def get_dhcp_relay_statistics(dut, interface="", family="ipv4", cli_type="", skip_error_check=True):
"""
API to get DHCP relay statistics
Author Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:type dut:
:param interface:
:type interface:
"""
cli_type = st.get_ui_typ... | 0784cd367d638124458d9e0fb808b45bcc239a84 | 3,648,557 |
def check_rule_for_Azure_ML(rule):
"""Check if the ports required for Azure Machine Learning are open"""
required_ports = ['29876', '29877']
if check_source_address_prefix(rule.source_address_prefix) is False:
return False
if check_protocol(rule.protocol) is False:
return False
i... | fb6067d484a3698b2d10d297e3419510d1d8c4e9 | 3,648,559 |
import re
def text_cleanup(text: str) -> str:
"""
A simple text cleanup function that strips all new line characters and
substitutes consecutive white space characters by a single one.
:param text: Input text to be cleaned.
:return: The cleaned version of the text
"""
text.replace('\n', ''... | 84b9752f261f94164e2e83b944a2c12cee2ae5d8 | 3,648,560 |
def create_overide_pandas_func(
cls, func, verbose, silent, full_signature, copy_ok, calculate_memory
):
""" Create overridden pandas method dynamically with
additional logging using DataFrameLogger
Note: if we extracting _overide_pandas_method outside we need to implement decorator like here
... | db2bf7cb5d5395aeb700ca14211690750f056a91 | 3,648,562 |
def orthogonalize(U, eps=1e-15):
"""
Orthogonalizes the matrix U (d x n) using Gram-Schmidt Orthogonalization.
If the columns of U are linearly dependent with rank(U) = r, the last n-r columns
will be 0.
Args:
U (numpy.array): A d x n matrix with columns that need to be orthogonalized.... | 5807c0e5c7ee663391123076c8784cfb7e445760 | 3,648,563 |
def boolean(func):
"""
Sets 'boolean' attribute (this attribute is used by list_display).
"""
func.boolean=True
return func | 9bbf731d72e53aa9814caacaa30446207af036bd | 3,648,565 |
def load_output_template_configs(items):
"""Return list of output template configs from *items*."""
templates = []
for item in items:
template = OutputTemplateConfig(
id=item["id"],
pattern_path=item.get("pattern-path", ""),
pattern_base=item.get("pattern-base", ... | 028502662906230bf2619fa105caa1d525ff8e75 | 3,648,566 |
def read_keyword_arguments_section(docstring: Docstring, start_index: int) -> tuple[DocstringSection | None, int]:
"""
Parse a "Keyword Arguments" section.
Arguments:
docstring: The docstring to parse
start_index: The line number to start at.
Returns:
A tuple containing a `Sect... | 9c789fd4b08d2f3d9e99d4db568ab710e4765c91 | 3,648,567 |
from typing import Mapping
from typing import Iterable
def is_builtin(x, drop_callables=True):
"""Check if an object belongs to the Python standard library.
Parameters
----------
drop_callables: bool
If True, we won't consider callables (classes/functions) to be builtin.
Classes have ... | d84fbd770e048172d8c59315fbe24d58046f77b8 | 3,648,568 |
import yaml
def random_pair_selection(config_path,
data_size=100,
save_log="random_sents"):
"""
randomly choose from parallel data, and save to the save_logs
:param config_path:
:param data_size:
:param save_log:
:return: random selected pair... | 417b59bae49fe8aa0566f20f8ff371c7760e1a8a | 3,648,569 |
from typing import OrderedDict
from typing import Counter
def profile_nominal(pairs, **options):
"""Return stats for the nominal field
Arguments:
:param pairs: list with pairs (row, value)
:return: dictionary with stats
"""
result = OrderedDict()
values = [r[1] for r in pairs]
c = Cou... | 00ef211e8f665a02f152e764c409668481c748cc | 3,648,571 |
from typing import List
def class_definitions(cursor: Cursor) -> List[Cursor]:
"""
extracts all class definitions in the file pointed by cursor. (typical mocks.h)
Args:
cursor: cursor of parsing result of target source code by libclang
Returns:
a list of cursor, each pointing to a class definiti... | c2831b787905b02865890aa2680c37b97ec2e0a8 | 3,648,572 |
def service_list_by_category_view(request, category):
"""Shows services for a chosen category.
If url doesn't link to existing category, return user to categories list"""
template_name = 'services/service-list-by-category.html'
if request.method == "POST":
contact_form = ContactForm(request.POST... | dcbed59c8b6876b7072eb82b27f6b10e829c2daa | 3,648,574 |
def check_columns(board: list):
"""
Check column-wise compliance of the board for uniqueness (buildings of unique height) and visibility (top-bottom and vice versa).
Same as for horizontal cases, but aggregated in one function for vertical case, i.e. columns.
>>> check_columns(['***21**', '412453*', '... | 26ea379a165b90eadcf89640f00857e9e95146c7 | 3,648,575 |
def get_git_tree(pkg, g, top_prd):
"""
:return:
"""
global pkg_tree
global pkg_id
global pkg_list
global pkg_matrix
pkg_tree = Tree()
pkg_id = 0
pkg_list = dict()
# pkg_list['root'] = []
if pkg == '':
return None
if pkg in Config.CACHED_GIT_REPOS:
p... | 05434882a476c8506804918cb44624c7734bf405 | 3,648,576 |
import requests
def get_requests_session():
"""Return an empty requests session, use the function to reuse HTTP connections"""
session = requests.session()
session.mount("http://", request_adapter)
session.mount("https://", request_adapter)
session.verify = bkauth_settings.REQUESTS_VERIFY
sess... | e5921b12d29718e9ef1f503f902fed02a7c7e82f | 3,648,577 |
def edit_role_description(rid, description, analyst):
"""
Edit the description of a role.
:param rid: The ObjectId of the role to alter.
:type rid: str
:param description: The new description for the Role.
:type description: str
:param analyst: The user making the change.
:type analyst:... | f857755766da1f8f5be0e3dc255ed34aa7ed3ed3 | 3,648,578 |
def have_questions(pair, config, info=None):
"""
Return True iff both images are annotated with questions.
"""
qas = info["qas"]
c1id = pair[0]
if qas[c1id]['qas'] == []:
return False
c2id = pair[1]
if qas[c2id]['qas'] == []:
return False
return True | 45a5f4babcc17ad5573008ca31773d51334144cd | 3,648,579 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.