content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def solution(A): # O(NlogN)
"""
Sort numbers in list A using quick sort.
>>> solution([5, 2, 2, 4, 1, 3, 7, 9])
[1, 2, 2, 3, 4, 5, 7, 9]
>>> solution([2, 4, 6, 2, 0, 8])
[0, 2, 2, 4, 6, 8]
>>> solution([1, 3, 5, 7, 3, 9, 1, 5])
[1, 1, 3... | 5,303,400 |
def main_export(subject, sample_idx, foldername):
""" train the model for one pecific subject and generate pickled files """
# we must use the quantized model
model = QuantizedRiemannianModel(bands=BANDS, random_state=RANDOM_SEED, riem_opt=RIEM_OPT)
train_samples, train_labels = get_data(subject, True,... | 5,303,401 |
def build_model():
"""
Builds pipeline and use grid search to perform multioutputclassification
Returns:
cv: GridSearchCV pipeline with best parameters for the model
"""
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
... | 5,303,402 |
def func_split_token(str_token):
"""
Splits a VCF info token while guarenteeing 2 tokens
* str_token : String token to split at '='
: String
* return : List of 2 strings
"""
if str_token:
lstr_pieces = str_token.split("=")
i_pieces = len(lstr_pieces)
if i_... | 5,303,403 |
def _discover_test_files():
"""Discover a list of files to run smoke tests on.
This is generally every file that came with the cmake distribution
"""
# List of files we will be testing against
test_files = []
# These files are templates and invalid cmake code
exclude_files = ["run_nvcc.cma... | 5,303,404 |
def set_sqlite_pragma(dbapi_connection: sqlite3.Connection, connection_record: _ConnectionRecord) -> None:
"""Configure certain SQLite settings.
These settings,
issued as SQLite `pragmas <https://sqlite.org/pragma.html>`_,
need to be configured on each connection.
Hence the usage of SQLAlchemy's en... | 5,303,405 |
def _add_descriptor_labels(
rdm: rsatoolbox.rdm.RDMs,
pattern_descriptor: str,
icon_method: str,
axis: Union[matplotlib.axis.XAxis, matplotlib.axis.YAxis],
num_pattern_groups: int = None,
icon_spacing: float = 1.0,
linewidth: float = 0.5,
horizontalalignment: str = "center",
) -> list:
... | 5,303,406 |
def _parse_example_proto(example_serialized):
"""Parses an Example proto containing a training example of an image.
The output of the build_image_data.py image preprocessing script is a dataset
containing serialized Example protocol buffers. Each Example proto contains
the following fields (values are ... | 5,303,407 |
def notify(notificationName, message):
""" Send a notification to the OS (OSX-only) """
if sabnzbd.FOUNDATION:
pool = Foundation.NSAutoreleasePool.alloc().init()
nc = Foundation.NSDistributedNotificationCenter.defaultCenter()
nc.postNotificationName_object_(notificationName, message)
... | 5,303,408 |
def fried(dataset_dir: Path) -> bool:
"""
fried x train dataset (32614, 10)
fried y train dataset (32614, 1)
fried x test dataset (8154, 10)
fried y train dataset (8154, 1)
"""
dataset_name = 'fried'
os.makedirs(dataset_dir, exist_ok=True)
X, y = fetch_openml(
name='fried... | 5,303,409 |
def portscan():
"""
Scan open ports of a website,
utilizing multi-threading to speed the task along
"""
import threading
import re
is_py2 = sys.version[0] == '2'
if is_py2:
import Queue as queue
else:
import queue as queue
def scanPortsTask(port):
import ... | 5,303,410 |
def params_to_state(
class_name,
name,
handler=None,
graph_shape=None,
function=None,
full_event=None,
class_args=None,
):
"""return state object from provided params or classes/objects"""
if class_name and hasattr(class_name, "to_dict"):
struct = class_name.to_dict()
... | 5,303,411 |
def parse_wps_server_info(root, namespaces, provider, passed_url):
"""
Parses the xml file provided by the wps server.
Searches for the information about the WPS server.
Returns a new object of the class WPS
@param root: root Element of the Element tree
@type root: ElementTree.Element
@para... | 5,303,412 |
def _postprocess_linrate(rows, cols, params):
"""
Postprocess linear rate outputs
"""
# pylint: disable=expression-not-assigned
# setup paths
xlks, _, crop = cf.transform_params(params)
base_unw_paths = cf.original_ifg_paths(params[cf.IFG_FILE_LIST])
dest_tifs = cf.get_dest_paths(base_un... | 5,303,413 |
def editRecord(session, idNum, row):
"""
Edit a record
"""
record = session.query(Book).filter_by(id=idNum).one()
print()
record.title = row["title"]
record.person.first_name = row["first_name"]
record.person.last_name = row["last_name"]
record.isbn = row["isbn"]
record.publisher... | 5,303,414 |
def resnet101(pretrained=True, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet101'... | 5,303,415 |
def test_getitem(py_c_vec):
"""Test vec[x] with various args."""
Vec, Angle, Matrix, parse_vec_str = py_c_vec
v = Vec(1.5, 3.5, -8.7)
assert v[0] == 1.5
assert v[1] == 3.5
assert v[2] == -8.7
assert v['x'] == 1.5
assert v['y'] == 3.5
assert v['z'] == -8.7
v[1] = 67.9
asser... | 5,303,416 |
def fraction_input(x,y):
""" Takes two inputs and returns it as a fraction
Parameters
___________
:param x: int/float: a number
:param y: int/float: a number
Returns
___________
:return: Returns the fraction
"""
# Try creating a Fraction using the two numbers inputted
... | 5,303,417 |
def format_datetime(obj, constant_hour=False, hour=("00", "00")):
"""Will format a datetime object into a string."""
if not constant_hour:
return "{}{}{}{}{}".format(
obj.year,
"{:02d}".format(obj.month),
"{:02d}".format(obj.day),
"{:02d}".format(obj.hour)... | 5,303,418 |
def select_modalities(combs, modalities_flag):
"""
:param combs: example [[1, 1, 1], [1, 1, 0], [0, 1, 1], [1, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1]]
:param modalities_flag: e.g [1,1,0]
:return: e.g [ [1, 1, 0], [1, 0, 0], [0, 1, 0]]
"""
combs = [[a * b for a, b in zip(c, modalities_flag)] fo... | 5,303,419 |
def test_component_inherited_factory_value():
"""https://github.com/larq/zookeeper/issues/123."""
@factory
class IntFactory:
def build(self) -> int:
return 5
@component
class Child:
x: int = ComponentField()
@component
class Parent:
child: Child = Compo... | 5,303,420 |
def test_issue_core_70():
"""Tests that we can load a scenario which contains the DEFWPT command"""
pytest.xfail()
api_base = tests.integration.API_BASE
resp = requests.post(
f"{api_base}/ic", json={"filename": "scenario/waypointExp.scn"}
)
assert (
resp.status_code == 500
... | 5,303,421 |
def teardown_module():
"""
teardown the temporary output directory
"""
rmtree(TEMP_DIR) | 5,303,422 |
def GuessVCS(options, path, file_list):
"""Helper to guess the version control system.
NOTE: Very similar to upload.GuessVCS. Doesn't look for hg since we don't
support it yet.
This examines the path directory, guesses which SCM we're using, and
returns an instance of the appropriate class. Exit with an er... | 5,303,423 |
def test_validate_products_multiple(lambda_module, product):
"""
Test validate_products() with multiple DynamoDB calls
"""
products = []
for i in range(0, 105):
product_temp = copy.deepcopy(product)
product_temp["productId"] += str(i)
products.append(product_temp)
# Stu... | 5,303,424 |
def tactic_application_to_string(t_app: deephol_pb2.TacticApplication) -> Text:
"""Generate tactic strings.
Args:
t_app: TacticApplication proto
Returns:
tactic string; to be parsed by third_party/hol_light/parse_tactic.ml
Raises:
ProofFailedError: When invariants of the tactic application are no... | 5,303,425 |
def test_shifted_weighted_sum_of_errors(normed, reward_power, motor_type, converter_type, number_reward_weights):
"""
Test the ShiftedWeightedSumOfErrors Class
:param normed: specifies if the reward is normed (True/False)
:param reward_power: specifies the used power order (int)
:param motor_type: m... | 5,303,426 |
def neopixel_set(pix, d_volt, mag_ut):
"""Set all the NeoPixels to an alternating colour
based on voltage difference and
magnitude of magnetic flux density difference."""
global neopixel_alternate
np_r, np_g, np_b = BLACK_TUPLE
if neopixel_alternate:
# RGB values are 8bit, hence t... | 5,303,427 |
def accumulatable_wer_stats(refs, hyps, stats=collections.Counter()):
"""Computes word error rate and the related counts for a batch.
Can also be used to accumulate the counts over many batches, by passing
the output back to the function in the call for the next batch.
Arguments
----------
ref... | 5,303,428 |
def waterfall(stack, profile, yaxis="rel_time", cmap="inferno", ax=None, **kwargs):
"""_summary_
Parameters
----------
stack : _type_
_description_
profile : _type_
_description_
yaxis : str, optional
_description_, by default "rel_time"
cmap : str, optional
... | 5,303,429 |
def ROC_AUC_individual_alpha(model, alpha):
"""
ROC & AUC for a single alpha, across all clusters inside.
Adapted from :
- https://stats.stackexchange.com/questions/186337/average-roc-for-repeated-10-fold-cross-validation-with-probability-estimates
- https://scikit-learn.org/stable/auto_examples/... | 5,303,430 |
def parse_sport_parionssport(sport):
"""
Get ParionsSport odds from sport
"""
sports_alias = {
"football" : "FOOT",
"basketball" : "BASK",
"tennis" : "TENN",
"handball" : "HAND",
"rugby" : "RUGU",
"hockey-sur... | 5,303,431 |
def conf_to_ccs(conformers, infodf):
"""Converts list of conformer indexes (from a 50x50 matrix) to Boltzmann weighted CCS average and Lowest Energy CCS.
Args:
conformers (np.array): Array of conformer indexes selected from a 50x50 rmsd matrix as returned in the
SDS() datafra... | 5,303,432 |
def test_mg_o036_mg_o036_v(mode, save_output, output_format):
"""
TEST :model groups (ALL) : group' with 'all', appear under
'restriction', whiche is part of a complexType
"""
assert_bindings(
schema="msData/modelGroups/mgO036.xsd",
instance="msData/modelGroups/mgO036.xml",
c... | 5,303,433 |
def list_datasets() -> List[str]:
"""Returns list of available datasets names
Returns:
List[str]: list of dataset names as string
>>> import src
>>> src.list_datasets()
['emodb']
"""
return sorted(__dataset_mapper__.keys()) | 5,303,434 |
def update_tag_scheme(sentences, tag_scheme):
"""
更新为指定编码
:param sentences:
:param tag_scheme:
:return:
"""
for i, s in tqdm(enumerate(sentences)):
tags = [w[-1] for w in s]
if not data_utils.check_bio(tags):
s_str = "\n".join(" ".join(w) for w in s)
r... | 5,303,435 |
def list_delete(name):
"""Delete collection (and all its documents)"""
db.get_coll_ref(name)
raise NotImplementedError("Delete collection (and all its documents)") | 5,303,436 |
def plot_inplane_vs_Ic_Rn(
inplane_field: np.ndarray,
bias: np.ndarray,
voltage_drop: np.ndarray,
ic_voltage_threshold: float,
high_bias_threshold: float,
ic_extraction_method: Optional[str] = 'iv_analysis',
switching_bias_threshold: Optional[float] = 2e-5,
savgol_windowl: Optional[int] ... | 5,303,437 |
def get_nat_address(instance_id: Optional[str] = None,
nat_address_id: Optional[str] = None,
organization_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNatAddressResult:
"""
Gets the details of a NAT address. **N... | 5,303,438 |
def grab_q_values(fname):
"""Parses data from three q_val csv files.
Parameters
----------
fname : str
Name of q_value file.
"""
# Create list
all_q_values = []
# Open .csv files and parses them
with open(os.path.join(os.path.dirname(__file__), fname), 'r') as f:
r... | 5,303,439 |
def make_replaced_box(element, box, image):
"""Wrap an image in a replaced box.
That box is either block-level or inline-level, depending on what the
element should be.
"""
if box.style['display'] in ('block', 'list-item', 'table'):
type_ = boxes.BlockReplacedBox
else:
# TODO: ... | 5,303,440 |
def roc(values, period):
"""
ROC を計算するのです。
* values: 調整後終値を指定するのです。
* period: 期間なのです。
* return: 終値ベースの ROC を返すのです。
"""
_values = DataFrame(values)
pasts = _values.shift(period)
return (_values - pasts) / _values | 5,303,441 |
def percentiles():
"""Tests the worst_half fn"""
f = np.asarray([
[0.99, 1.0, 0.5, 0.2],
[0.69, 0.6, 0.6, 0.2]])
percentiles = np.asarray(
[0.25, 0.99])
_f = t2.select_percentiles(f, percentiles)
expected = np.asarray([
[0.5, 1.0],
[0.6, 0.69]])
assert np.... | 5,303,442 |
def compute_density(start, end, length, time_unit='us'):
"""
Computes a grid density given the edges and number of samples.
Handles datetime grids correctly by computing timedeltas and
computing a density for the given time_unit.
"""
if isinstance(start, int): start = float(start)
if isinsta... | 5,303,443 |
def test_stochastic_duration_rainfall_means():
"""Test option with stochastic duration.
Test is simply to get the correct total cumulative rain depth.
"""
U = 0.0001
K = 0.0001
m = 1.0
n = 1.0
grid = RasterModelGrid((3, 6), xy_spacing=100.0)
grid.set_closed_boundaries_at_grid_edges... | 5,303,444 |
def intersection_pt(triangle_left, triangle_right):
""" get intersection point of two output triangles"""
a, b, c = triangle_left[0], triangle_left[1], triangle_left[2]
d, e, f = triangle_right[0], triangle_right[1], triangle_right[2]
x = (c * (b - c) - d * (e - d)) / (b - c - e + d)
y = (e - d) * (... | 5,303,445 |
def pitch(freq):
"""finds the closest pitch to the frequency freq"""
return _ftop[closest(_fs, freq)] | 5,303,446 |
def algorithm(feature):
"""
Content-Based Algorithm+
기존의 Content-Based에서 Youflix 시스템을 위해 튜닝이 된 알고리즘 입니다.
사용자가 평가한 결과를 토대로 더 높은 점수를 받은 영화는 가중치를 높게줘서
비슷한 영화가 많이 추천 되도록 하고, 반대로 낮은 점수의 영화와 유사한 영화는
추천되지 않도록 하여 사용자에게 의미있는 결과를 내도록 하였습니다.
추가적으로 영화감독이나 영화배우들을 기준으로 추천을 받을 수 있... | 5,303,447 |
def get_volume_page_score_for_input_fields(result_record, hypothesis):
"""
:param result_record:
:param hypothesis:
:return:
"""
input_fields = hypothesis.get_detail('input_fields')
evidences = Evidences()
exist = bool('volume' in input_fields) + bool('page' in input_fields)
ads_... | 5,303,448 |
def merge_data_set():
"""This function matches and merges CSV to make one data set"""
df_att = merge_attendance()
df_dma = merge_dma(df_att)
df_nat = merge_national_ratings(df_dma)
df_rsn = merge_rsn_rating(df_nat)
df_sec = merge_secondary_trans(df_rsn)
merge_social(df_sec) | 5,303,449 |
def print_ast(node):
"""Prints the AST provided by eulxml.xpath.parse
Useful for debugging particular expressions
"""
def visit(node, indent):
print("\t" * indent, node) # noqa
if hasattr(node, 'left'):
indent += 1
visit(node.left, indent)
if hasattr(n... | 5,303,450 |
def array_to_dist_graph(point_set, point_weight=1, metric='sqeuclidean'):
"""take a set of points P and create the complete graph with vertex set P and weights equal to the distance between pairs"""
link_idx = triu_indices(len(point_set), k=1)
g = nx.Graph(data=list(zip(link_idx[0],
... | 5,303,451 |
def adaptive_scaling_loss(logits: Tensor, targets: Tensor, positive_idx: Tensor,
mask: Tensor = None, beta: float = 1.0, reduction='none',
weight_trainable: bool = False):
"""
:param logits: (batch, num_label)
:param targets: (batch, )
:param positive... | 5,303,452 |
def test_TileServer_get_playground_url():
"""Should work as expected (create TileServer object and get playground url)."""
r = RasterTiles(raster_path)
app = TileServer(r)
assert app.get_playground_url() == "http://127.0.0.1:8080/playground.html" | 5,303,453 |
def get_ir_exon_transcript(tx_data, introns):
"""
List exons and transcriptts that contain Intron Retention events where an intron is encompassed
by an exon. Also return intron coords for flagging IR EFs.
"""
ir_exon_list = []
ir_transcript_list = []
for e_tx in tx_data:
e_ints = [(i... | 5,303,454 |
def mp_wms_130_nometadata(monkeypatch):
"""Monkeypatch the call to the remote GetCapabilities request of WMS
version 1.3.0, not containing MetadataURLs.
Parameters
----------
monkeypatch : pytest.fixture
PyTest monkeypatch fixture.
"""
def read(*args, **kwargs):
with open('... | 5,303,455 |
def _handle(ctx=None, function=None, additional_function=None, args=None):
"""This function routes calls to sub-functions, thereby allowing
a single identity function to stay hot for longer. If you want
to add additional functions then add them via the
'additional_function' argument. This shoul... | 5,303,456 |
def _learn(x, logw, loss, optim_kwargs, schedule_kwargs, n_steps, init_x, optim_class_name='Adam',
scheduler_class_name='StepLR'):
"""
Combine solve_for_state and transport_from_potentials in a "reweighting scheme"
:param x: torch.Tensor[N, D]
The input
:param w: torch.Tensor[N]
... | 5,303,457 |
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the platform for a Skybell device."""
skybell = hass.data.get(SKYBELL_DOMAIN)
sensors = []
for device in skybell.get_devices():
sensors.append(SkybellCamera(device))
add_devices(sensors, True) | 5,303,458 |
def update_import_card_credits_flag(corporate_credit_card_expenses_object: str, workspace_id: int) -> None:
"""
set import_card_credits flag to True in ExpenseGroupSettings
:param corporate_credit_card_expenses_object: Corporate credit card expenses object
:param workspace_id: Workspace id
return: N... | 5,303,459 |
async def create_tcp_message_payload_connection(
queue: "Queue[bytes]",
loop: AbstractEventLoop | None,
readers: Sequence[MeterReaderBase] | None,
*args,
**kwargs,
) -> MeterTransportProtocol:
"""
Create TCP connection using SmartMeterMessagePayloadProtocol.
:param queue: Queue for rece... | 5,303,460 |
def fibonacci_infinite():
"""Generates an infinite sequence of Fibonacci numbers on demand"""
a, b = 0, 1
while True:
yield a
a, b = b, a + b | 5,303,461 |
def _numpy_repr(array, prefix="", suffix=""):
"""Wrapper for showing Numpy array in custom class"""
max_line_width = numpy.get_printoptions()["linewidth"]
array_str = numpy.array2string(
array,
separator=", ",
prefix=prefix,
suffix="," if suffix else None,
max_line_wi... | 5,303,462 |
def parse_collect_msg(orig_msg):
"""
Parse "collect" message received from backend
"""
# collect response and message have the same message format
return parse_message_msg(orig_msg) | 5,303,463 |
def read_chessboards(images: Iterator[Path]):
"""
Charuco base pose estimation.
"""
logger.info("Pose Estimation Starts:")
allCorners = []
allIds = []
decimator = 0
# SUB PIXEL CORNER DETECTION CRITERION
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.00001)
... | 5,303,464 |
def populate_sd_dict(herbivore_list):
"""Create and populate the stocking density dictionary, giving the stocking
density of each herbivore type."""
stocking_density_dict = {}
for herb_class in herbivore_list:
stocking_density_dict[herb_class.label] = herb_class.stocking_density
retu... | 5,303,465 |
def timeInForce() -> str:
"""TODO: Add description."""
return 'GTC' | 5,303,466 |
def run_step(context):
"""Parse input toml file and substitute {tokens} from context.
Loads toml into memory to do parsing, so be aware of big files.
Args:
context: pypyr.context.Context. Mandatory.
- fileFormatToml
- in. mandatory.
str, pa... | 5,303,467 |
def read_segment(st, segment, cfile, vys_timeout):
""" Wrapper for source.read_segment that secedes from worker
thread pool
"""
from rfpipe import source
logger.info("Reading datasetId {0}, segment {1} locally."
.format(st.metadata.scanId, segment))
with distributed.worker_cli... | 5,303,468 |
def require_self(f):
"""Require the logged-in user to be the user that is currently being edited"""
@wraps(f)
def fn(*args, **kwargs):
try:
username = kwargs["username"]
except KeyError:
abort(
500,
"The require_self decorator only wor... | 5,303,469 |
def test_gateway_config_no_peers():
"""It should correctly create the gateway configuration with no
peers.
"""
config = GatewayConfig(endpoint="localhost", private_key="privkey",
public_key="pubkey")
assert config.to_string() == "\n".join([
"[Interface]",
"... | 5,303,470 |
def _estimate_score_file_format(filename, ncolumns=None):
"""Estimates the score file format from the given score file.
If ``ncolumns`` is in ``(4,5)``, then ``ncolumns`` is returned instead.
"""
if ncolumns in (4, 5):
return ncolumns
f = open_file(filename, "rb")
try:
line = f.... | 5,303,471 |
def move_each_pretag_to_folder():
"""
"""
log_function_call(move_each_pretag_to_folder.__name__)
inpath = os.getcwd()
for (dirpath, dirnames, filenames) in os.walk(inpath):
if is_invalid_path(dirpath): continue
for filename in filenames:
filenameAccessor = FilenameAccesso... | 5,303,472 |
def spec_chain_zero_truncated(chain, ln_proba=None, ar=None):
"""
Return the Markov chain with the dimension: walkers x steps* x parameters,
where steps* is the last step before having 0 (not yet constructed chain).
Parameters
----------
chain: numpy.array
The MCMC chain.
ln_pro... | 5,303,473 |
def test_input_assignation(mocker):
"""Test Input Assignation"""
mocks_control = [
('t', True),
('f', True),
('n', False),
('7', False),
]
for data, wait_response in mocks_control:
load = False
mocker.patch(
'builtins.input',
lambda... | 5,303,474 |
def test_radix_sort_triplets(sequences):
"""Solution to exercise R-12.18.
Describe a radix-sort method for lexicographically sorting a sequence S of
triplets (k, l, m), where k, l, and m are integers in the range [0, N − 1],
for some N ≥ 2. How could this scheme be extended to sequences of d-tuples
... | 5,303,475 |
def precision_recall_f1(y, y_pred, average='macro'):
"""
average: str {'macro', 'micro'}
"""
cm = confusion_matrix(y, y_pred)
if y.ndim == 1: # binary classification
pr = (cm.diagonal()/cm.sum(axis=0))[1]
rc = (cm.diagonal()/cm.sum(axis=1))[1]
f1 = 2*pr*rc / (pr+rc)
... | 5,303,476 |
def get_files(
catalog: str, recursive: bool, suffix_markup: str, extension: str
) -> List[str]:
"""
Осуществляет поиск в каталоге и выдает список путей найденных файлов.
По-умолчанию, recursive = False, ищет файлы только в каталоге.
extension и suffix_markup - исключают поиск файлов с указанным ра... | 5,303,477 |
def CppTypedefString(scope, type_defn):
"""Gets the representation of a type when used in a C++ typedef.
Args:
scope: a Definition for the scope in which the expression will be written.
type_defn: a Definition for the type.
Returns:
a (string, boolean) pair, the first element being the representatio... | 5,303,478 |
def get_acl(device, acl_name, seq_number):
"""Retrieves ACL configuration
Args:
device (Device): This is the device object of an NX-API enabled device
using the Device class from pycsco
acl_name (str): Case-sensitive name of the ACL
seq_number (str): Number of sequence numbe... | 5,303,479 |
def output_tensor(interpreter):
"""Returns dequantized output tensor."""
output_details = interpreter.get_output_details()[0]
output_data = np.squeeze(interpreter.tensor(output_details['index'])())
scale, zero_point = output_details['quantization']
return scale * (output_data - zero_point) | 5,303,480 |
def arg_parse_params(params):
"""
SEE: https://docs.python.org/3/library/argparse.html
:return dict:
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-imgs',
'--path_images',
type=str,
required=False,
help='path to directory & name pattern for ... | 5,303,481 |
def normalize_features(feature: np.ndarray, variable: str) -> np.ndarray:
"""Normalize features using global pre-computed statistics.
Parameters
----------
feature : np.ndarray
Data to normalize
variable : str
One of ['inputs', 'output'], where `inputs` mean, that the `feature` inpu... | 5,303,482 |
def lonlat2xyz(lon,lat,r=1):
""" """
x = r*np.cos(lon*c)*np.cos(lat*c)
y = r*np.sin(lon*c)*np.cos(lat*c)
z = r*np.sin(lat*c)
return x,y,z | 5,303,483 |
def train_switcher(**params):
"""
function to call the correct train function depending on the dataset. s.t.
parallel training easily works altough different fuctions need to be called
:param params: all params needed by the train function, as passed by
parallel_training
:return: functio... | 5,303,484 |
def debugobsolete(ui, repo, precursor=None, *successors, **opts):
"""create arbitrary obsolete marker
With no arguments, displays the list of obsolescence markers."""
opts = pycompat.byteskwargs(opts)
def parsenodeid(s):
try:
# We do not use revsingle/revrange functions here to ac... | 5,303,485 |
def generate_sql(path, out, verbose):
"""Generate the SQL requests from the provided CSV file
PATH is the path to the CSV file to process
"""
# Set flags
global is_verbose
is_verbose = verbose
# Core process
process_file(path.name, out) | 5,303,486 |
def get_stock_price(symbol, start, end):
"""get stock price of a company over a time range
Args:
symbol (str): ticker symbol of a stock
start (datetime.datetime): start time
end (datetime.datetime): end time
Returns:
pd.DataFrame: stock price of a company over a time range
... | 5,303,487 |
def ip6_from_bytes(data: bytes) -> str:
"""Converts ip4 address from bytes to string representation.
Keyword arguments:
data -- address bytes to convert
"""
return socket.inet_ntop(socket.AF_INET6, data) | 5,303,488 |
def unletterbox(image) -> typing.Optional[
typing.Tuple[typing.Tuple[int, int], typing.Tuple[int, int]]]:
"""Return bounds of non-trivial region of image or None.
Unletterboxing is cropping an image such that trivial edge regions
are removed. Trivial in this context means that the majority of
t... | 5,303,489 |
def hash_side_effect(value):
"""Side effect value."""
if "mail_none.gif" in value:
return "633d7356947eec543c50b76a1852f92427f4dca9"
else:
return "133d7356947fec542c50b76b1856f92427f5dca9" | 5,303,490 |
def cbow_context(source, window, empty, name=None):
"""Generates `Continuous bag-of-words` contexts for inference from batched list of tokens.
Args:
source: `2-D` string `Tensor` or `RaggedTensor`, batched lists of tokens [sentences, tokens].
window: `int`, size of context before and after targ... | 5,303,491 |
def CombineParallelDense(min_num_branches=3):
"""Combine multiple dense operators into one. For example:
data
/ \
dense (2,2) dense (2,2)
| |
elemwise/bcast (2,2) elemwise/bcast (2,2)
Would become:
data
... | 5,303,492 |
def layer_norm__ncnn(ctx, *args):
"""Register default symbolic function for `layer_norm`.
Add support to layer_norm to ONNX.
"""
return layer_norm(*args) | 5,303,493 |
def symlink_safe(link, target):
"""Create symlink to target. Atomically rename if link already exists."""
tmp_link = tempfile.mktemp(dir=os.path.dirname(link))
os.symlink(target, tmp_link)
os.rename(tmp_link, link) | 5,303,494 |
def test_set_supervisor_marker_entry():
"""
Test entry of supervisor-marker in the database.
"""
assert TaskQueue.objects.all().count() == 0
assert set_supervisor_marker() is True
assert TaskQueue.objects.all().count() == 1 | 5,303,495 |
def new_locale(language: str = None, country: str = None, variant: str = None,
use_locale_module: bool = False) -> Locale:
"""
Instantiates a new Locale
:param language: The language code
:type language: str
:param country: The country code
:type country: str
:param variant: T... | 5,303,496 |
def plot_variance_explained(model, bar_kwargs=None, ax=None):
"""
Parameters
----------
model : ``sklearn.decomposition.PCA``
The fitted model.
bar_kwargs : dict-like, optional
Additional keyword arguments passed through to ``ax.bar()``.
ax : axes, optional
The axes on ... | 5,303,497 |
def get_latest_news_metadata(local: Optional[bool] = False):
"""
Get latest news metadata file from S3 bucket
"""
if local:
with open(LOCAL_NEWS, 'rb') as f:
news = json.loads(f.read().decode('utf-8'))
# {"datetime": "2021-09-19T17:24:54", "version": "0.2.1"}
else:
... | 5,303,498 |
def get_direction(ch: str) -> Tuple[int, int]:
"""Coordinates point for direction
Args:
ch: str - direction as a single letter UDLR or NEWS
Returns:
tuple (x, y) - direction coordinates.
E.g.:
N -> (0, 1) # north
S -> (0, -1) # south
L -> (-1, ... | 5,303,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.