text string | label_name string | labels int64 |
|---|---|---|
(Card16, usize) = <Card16>::from_bytes(&bytes[index..])?;
index += sz;
Some((
CreateCursorRequest {
req_type: req_type,
length: length,
cid: cid,
source: source,
mask: mask,
fore_red: fore_red,
... | Rust | 0 |
tor holds leftmost leaf
/// descendants of each node. `key_roots` are the values described in Section
/// 3.2 of the paper as `LR_keyroots` and defined thus:
///
/// `LR_Keyroots(T) = { k | there exists no k_ > k such that l(k) = l(k_) }`
///
/// in this notation, `T` is a tree and `l(i)` is the id of node `i` describ... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Flutter 로그인 테스트 - 브라우저 표시 확인
"""
import asyncio
from playwright.async_api import async_playwright
import time
async def test_browser_display():
"""브라우저 표시 테스트"""
print("\n[TEST] Starting browser display test...")
print("Browser should open and stay vi... | Python | 1 |
d)result_dataresult_maskrT rU s r rR rR ` { +t$$14[1NO1NvQ"1NOO+u%%Tc+6STTT{##K55
P Bc U R [ R [ R 1; a U R 5 n UR ... | Python | 1 |
2;
let mut last_succesful_swap = vec.len() - 1;
//variant of Lomuto algo.
loop {
while left <= right && vec[left].dim(partition_on_dimension) <= pivot {
left += 1;
}
while right > left && vec[right].dim(partition_on_dimension) > pivot {
right -= 1;
... | Rust | 0 |
.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s)));
for (i, ni) in nums.iter().enumerate() {
for (j0, nj) in nums[i..].iter().enumerate() {
let j = i + j0;
if i == j {
assert_eq!(ni.cmp(nj), Equal);
assert_eq!(nj.cmp(ni), Equal);
... | Rust | 0 |
dow_width}x{window_height}+{position_x}+{position_y}")
# Formatear el tamaño del archivo a dos decimales
file_size_formatted = f"{file_size_mb:.2f} MB"
# Agregar el texto de descarga
tk.Label(root, text=f"Descargando {file_size_formatted} - {file_name}...").pack(padx=20, pady=20)
# Actualizar la ... | Python | 1 |
seconds=0)
##
## Create Entire Job Using the Tasks Above
##
created_job = w.jobs.create(
name=job_name,
description='Final Workflow SDK',
tasks=[
task_unit_tests,
task_visualization,
task_dlt
],
... | Python | 1 |
" + str(v["err"])
elif (type == 0xB):
return "PT_BOOLEAN " + str(v["b"])
elif (type == 0xD):
return "PT_OBJECT " + str(v["x"])
elif (type == 0x14):
return "PT_LONGLONG " + str(v["li"])
elif (type == 0x1E):
return "PT_STRING8 " + str(v["lpszA"])
elif (type == 0x1F):
return "PT_UNICODE " + str(v... | Python | 1 |
airoToken::Hint(&self.input[string_start..end]), end + 1))
}
fn keyword(id: &str) -> Option<CairoToken> {
match id {
"cast" => Some(CairoToken::Cast),
"const" => Some(CairoToken::Const),
"let" => Some(CairoToken::Let),
"return" => Some(CairoToken::Return)... | Rust | 0 |
let fastq = b"@id1
/// ACGT
/// +
/// IIII
/// @id2
/// TGCA
/// +
/// IIII";
///
/// let mut reader = Reader::new(&fastq[..]);
///
/// // skip one record
/// reader.next().unwrap();
/// // second position
/// reader.next().unwrap();
///
/// assert_eq!(re... | Rust | 0 |
let stack_limit_ref = &stack_limit;
match std::panic::catch_unwind(move || {
(*retryable)(stack_limit_ref, nonmain_stack_size)
}) {
Ok(result) => Some(result),
Err(_) if stack_limit.exceeded() => None,
... | Rust | 0 |
ds 3 requests, therefore expect exactly 3 responses.
response_future_3 = append_rows_stream.send(request)
# All three requests are in-flight, wait for them to finish being processed
# before finalizing the stream.
print(response_future_1.result())
print(response_future_2.result())
print(respons... | Python | 1 |
"Wrong slack account id");
let rewards: Balance = self.get_rewards(slack_account_id.clone()).0;
assert!(rewards != EMPTY_BALANCE, "Nothing to withdraw");
env::log(format!("@{} is withdrawing rewards {} NEAR from slack account {}", recipient_account_id, rewards, slack_account_id).as_bytes());
... | Rust | 0 |
},
Err(e) => {
eprintln!("{}", e);
},
}
}
buffer = String::new();
},
Err(_) => {
... | Rust | 0 |
use async_channel::Sender;
use bytes::Bytes;
use git2::Repository;
use std::path::Path;
use tracing::info;
use warp::{http::StatusCode, reject, Rejection, Reply};
/// Handle receiving webhooks from GitHub
pub async fn hook(
raw_body: Bytes,
raw_signature: String,
config: SharedConfig,
sender: Sender<Me... | Rust | 0 |
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, " user created")
def list_user():
mydb=mysql.connector.connect(host="localhost",user="root",passwd="password",database="stock")
mycursor=mydb.cursor()
sql="SELECT uid,uname from user"
... | Python | 1 |
T>(&mut self, values: &'a [T]) -> Result<&'a T, ErrorKind> {
let val = self.gen_range(0, values.len())?;
Ok(&values[val])
}
pub fn choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Result<&'a mut T, ErrorKind> {
let val = self.gen_range(0, values.len())?;
Ok(&mut values[val]... | Rust | 0 |
print!("{:>02x} ", c);
if pos == 7 {
print!(" ");
}
}
if row.len() < 7 {
print!(" ");
}
let fillup = 16-row.len();
for _ in 0..(fillup*3) { print!(" "); }
print!(" |");
for &c in row {
if c >= ... | Rust | 0 |
ed_frame = combine_partitions_SR(*crops) # adjust is a fixed value
else:
# Full frame cases
combined_frame = self.idx2res[self.now_idx][3]
# Write the frame
# cv2.imwrite(str(self.now_idx)+".png", cv2.cvtColor(combined_frame, cv2.COLOR_BGR2RGB)) # F... | Python | 1 |
parsing and configuration,and then calls into the functionality exposed by the library
// part of the crate.
// println!("Hello, world!");
// numbers::say_hello() ;
numbers::print(5);
}
//
// Copyright (c) <NAME>. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the pr... | Rust | 0 |
on_chunks_from_file():
with tm.ensure_clean("test.json") as path:
df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
df.to_json(path, lines=True, orient="records")
with read_json(path, lines=True, chunksize=1) as reader:
chunked = pd.concat(reader)
unchunked = read_json(pat... | Python | 1 |
(0).and_then(|(_, s)| s.chars().next()).unwrap_or(' ').is_whitespace() {
return;
}
for (_, slice) in &self.inner {
let trimmed = slice.trim_start();
if trimmed.is_empty() {
byte_index += slice.len();
continue;
}
... | Rust | 0 |
::LockedRTSP(_, _) => SVC_TYPE_LOCKED_RTSP,
&Service::UnknownRTSP(_, _) => SVC_TYPE_UNKNOWN_RTSP,
&Service::UnsupportedRTSP(_, _, _) => SVC_TYPE_UNSUPPORTED_RTSP,
&Service::HTTP(_, _) => SVC_TYPE_HTTP,
&Service::MJPEG(_, _, _) => SVC... | Rust | 0 |
ct poisoning nodes from unlabeled nodes (assign labels is easier than change, also we can try to select from labeled nodes)'''
N = features.shape[0]
cand_poi_train_nodes = list(set(idx_val)-set(atk_test_nodes)-set(clean_test_nodes))
poison_nodes_num = int(N * args.vs_ratio)
poi_train_nodes = rs.choice(c... | Python | 1 |
tamp: 100000,
},
],
};
run_field_columns_test_case!(TwoMeasurementsManyFields {}, predicate, expected_fields);
}
#[tokio::test]
async fn test_field_columns_with_ts_pred() {
let predicate = PredicateBuilder::default()
.table("h2o")
.timestamp_range(200, 300)
.add... | Rust | 0 |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmengine.model import BaseModule
from mmdet.registry import MODELS
@MODELS.register_module()
class GlobalAveragePooling(BaseModule):
"""Global Average Pooling neck.
Note that we use `view` to remove extra channel after p... | Python | 1 |
's stupid floating point mess
assert_eq!(l1.intersection(&l2), Intersection::Overlap(Pnt2 {x: 7.0, y: 7.0 }, Pnt2 {x: 10.000000000000002, y: 10.000000000000002}));
assert_eq!(l1.contains(&l2), true)
}
#[test]
fn circle_line_intersection() {
let circle = Circle::new(Pnt2::new(3.0,1.0), 6.0);
let mut lin... | Rust | 0 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = 'liao gao xiang'
# 二八十六进制整数
# 为了将整数转换为二进制、八进制或十六进制的文本串,可以分别使用bin(),oct()或hex()函数:
x = 1234
print(bin(x))
print(oct(x))
print(hex(x))
# 另外,如果你不想输出0b,0o或者0x的前缀的话,可以使用 format()函数。比如:
print(format(x, 'b'))
print(format(x, 'o'))
print(format(x, 'x'))
# 如果你想产生一个无符号... | Python | 1 |
import numpy as np
from matplotlib import pyplot as plt
# 原始数据
x1 = np.array([0.016860603, 0.104070618, 0.191280633, 0.259948401, 0.363466653,
0.46749089, 0.580592594, 0.673241925, 0.731248485, 0.793618759,
0.846235608, 0.886203717, 0.925126606, 0.960888848, 0.999113139,
1.... | Python | 1 |
xtracting : ", file)
UNTAR(os.path.join(root, file), root)
os.remove(os.path.join(root, file))
elif file.endswith('.zip'):
print("- Extracting : ", file)
UNZIP(os.path.join(root, file), root)
os.remove(os.path.join(root, file))
shuti... | Python | 1 |
.process_name,
service_access)?;
let mut args = vec![OsStr::new(&self.process_path)];
for a in &self.process_args {
args.push(a.as_ref());
}
service.start(&args)?;
Ok(())
}
fn delete(&self) -> crate::Result<... | Rust | 0 |
import numpy as np
import librosa
import math
import sys
print("Loading file")
audio, sample_rate = librosa.load(sys.argv[1], duration=60, offset=0, sr=15360)
print("Getting spectrum")
spectrum = librosa.stft(audio)
S = np.abs(spectrum)
fout = open("spectrum.h", "w")
print("Writing file")
fn = 36
fs = int(len(S) / ... | Python | 1 |
['__class__', '__del__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattr__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__swig_destroy__', '... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sci
def quadrotor_u(x, cu):
pi = np.pi
sin = np.sin
cos = np.cos
tan = np.tan
M = 0.6 # mass (Kg)
L = 0.2159 / 2 # arm length (m)
g = 9.81 # acceleration due to gravity m/s^2
m = 0.410 # Sphere Mass (Kg)
... | Python | 1 |
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(ref v) = self.src.as_ref() {
os.write_string(1, &v)?;
}
if let Some(ref v) = self.policyName.as_ref() {
os.write_string(2, &... | Rust | 0 |
class Animal:
def __init__(self, name, species, age):
"""
класс Animal
:param name: Кличка животного
:param species: Вид животного
:param age: Возраст животного
"""
self.name = name
self.species = species
self.age =... | Python | 1 |
te this step's shape
cur_shape = list(res.shape)
if T.ndim(mat) == 2:
cur_shape[mode] = mat.shape[0]
else:
cur_shape.pop(mode)
# pick target buffer - only use out on the last step if shapes match
if is_last and out is not None:
# Doubl... | Python | 1 |
from PyObjCTools.TestSupport import TestCase, min_os_level
import Intents
class TestINSearchCallHistoryIntentResponse(TestCase):
def test_enum_types(self):
self.assertIsEnumType(Intents.INSearchCallHistoryIntentResponseCode)
@min_os_level("10.12")
def testConstants(self):
self.assertEqual... | Python | 1 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""Pandoc filter to allow variable wrapping of LaTeX/pdf documents
through the wrapfig package.
Simply add a " {?}" tag to the end of the caption for the figure, where
? is an integer specifying the width of the wrap in inches. 0 will cause
the width of the figure to be ... | Python | 1 |
ful", "work", "work", "work", "work", "worth", "worth", "worth", "worth", "worth", "write", "write", "write", "wrong"]}, "R": 30, "lambda.step": 0.01, "plot.opts": {"xlab": "PC1", "ylab": "PC2"}, "topic.order": [7, 8, 16, 14, 10, 11, 2, 17, 4, 18, 6, 3, 9, 1, 12, 5, 13, 15]};
function LDAvis_load_lib(url, callback... | Python | 1 |
import typing as t
from .model import JWSAlgModel, CompactSignature
from ..errors import (
DecodeError,
MissingAlgorithmError,
)
from ..util import (
json_b64encode,
json_b64decode,
urlsafe_b64encode,
urlsafe_b64decode,
)
__all__ = [
"sign_compact",
"verify_compact",
"detach_compact... | Python | 1 |
and decimal places
let mut properties = sc_chain_spec::Properties::new();
properties.insert("tokenSymbol".into(), "UNIT".into());
properties.insert("tokenDecimals".into(), 12u32.into());
ChainSpec::from_genesis(
// Name
"Local Testnet",
// ID
"local_testnet",
ChainType::Local,
move || {
testnet_gen... | Rust | 0 |
tion.position.x = calculate_relative_teleport(TeleportFlag::RelX, flags, position.position.x, x);
position.position.y = calculate_relative_teleport(TeleportFlag::RelY, flags, position.position.y, y);
position.position.z = calculate_relative_teleport(TeleportFlag::RelZ, flags, position.position.z... | Rust | 0 |
}
}
fn set_position_iterator(
valid_mask: Option<&[u8]>,
to_insert: usize,
) -> impl Iterator<Item = usize> + '_ {
match valid_mask {
Some(mask) => itertools::Either::Left(
iter_set_positions(mask).take_while(move |idx| *idx < to_insert),
),
None => itertools::Either::Ri... | Rust | 0 |
:
return q_obj # type: ignore
raise RuntimeError("Transform options not found.")
def _fetch_mode_button(self, mode: TransformMode) -> QToolButton:
"""Fetch a button that activates a given mode."""
for q_obj in self._transform_options.findChildren(QToolButton):
i... | Python | 1 |
import pytest
from cuallee import Check, CheckLevel
def test_positive(spark):
df = spark.range(10)
check = Check(CheckLevel.WARNING, "pytest")
check.has_std("id", 2.8722813232690143)
rs = check.validate(df)
assert rs.first().status == "PASS"
def test_negative(spark):
df = spark.range(10)
... | Python | 1 |
valid, host = source_utils.is_host_valid(url, self.hostDict)
if not valid: continue
host = client.replaceHTMLCodes(host)
host = host.encode('utf-8')
quality, info2 = source_utils.get_release_quality(url, url)
if url in str(self._sources): ... | Python | 1 |
}
}
pub fn plane_default() -> Shape {
Shape {
shape_type: ShapeType::Plane,
transform: Matrix4x4::identity(),
transformation_inverse: Matrix4x4::identity().inverse().unwrap(),
material: Material::default(),
}
}
pub fn plane(transform... | Rust | 0 |
# -*- coding: utf-8 -*-
# pylint: disable=line-too-long,consider-using-f-string
"""EdDSA Curve Label
=======================
.. module:: pcapkit.const.hip.eddsa_curve
This module contains the constant enumeration for **EdDSA Curve Label**,
which is automatically generated from :class:`pcapkit.vendor.hip.eddsa_curve.E... | Python | 1 |
'bias']:
nn.init.constant_(m.bias, 0)
if os.path.isfile(pretrained):
pretrained_state_dict = torch.load(pretrained)
logger.info('=> loading pretrained model {}'.format(pretrained))
existing_state_dict = {}
for name, m in pretrained_state_... | Python | 1 |
orSize + MatchingTypeSize;
use self::MatchingType::*;
let raw_matching_type = resource_data.u8(CertificateUsageSize + SelectorSize);
let matching_type = match raw_matching_type
{
0 => NoHashUsed(&resource_data[DigestOffset .. ]),
1 => guard_hash_digest_if_final_field!(resource_data, DigestOffset, 256, Sh... | Rust | 0 |
t.add_clause(i, false, j, true);
}
if (y[i] - x[j]).abs() < d {
t.add_clause(i, true, j, false);
}
if (y[i] - y[j]).abs() < d {
t.add_clause(i, true, j, true);
}
... | Rust | 0 |
for i in range(4):
for j in range(len(books[i])):
if books[i][j] == '红楼梦':
print(i + 1, j + 1)
| Python | 1 |
6789012",
shipping_profile_name: "One Day Handling"
},
seller_return_profile: SellerReturnProfile {
return_profile_id: "123456789012",
return_profile_name: "Returns Accepted, Seller, 30 Days, Money back or exchange"
},
seller_payment_profile: SellerPay... | Rust | 0 |
wxt/datasets/ffhq/ffhq_wild/00009.png'
img_name = os.splitext(os.path.basename(img_path))[0]
# initialize model
det_net = init_detection_model('retinaface_resnet50', half=False)
img_ori = cv2.imread(img_path)
h, w = img_ori.shape[0:2]
# if larger than 800, scale it
scale = max(h / 800, w / ... | Python | 1 |
ng will be OK.
///
/// # Examples
/// * Read a u64 written to offset 32.
///
/// ```
/// # use sys_util::MemoryMapping;
/// # let mut mem_map = MemoryMapping::new(1024).unwrap();
/// let res = mem_map.write_obj(55u64, 32);
/// assert!(res.is_ok());
/// let num: u6... | Rust | 0 |
af", None),
0xF6 => Instruction::new("or d8", Some(Data8)),
0xF7 => Instruction::new("rst $30", None),
0xF8 => Instruction::new("ld hl, sp+r8", Some(Data8)),
0xF9 => Instruction::new("ld sp, hl", None),
0xFA => Instruction::new("ld a, [a16]", Some(Data16)),
0xFB => Instr... | Rust | 0 |
import matplotlib
import numpy as np
matplotlib.use('TkAgg') # Встановлюємо бекенд для Matplotlib перед імпортом pyplot
import matplotlib.pyplot as plt
from collections import Counter # Додаємо Counter у main.py
import feistel_cipher
import hill_cipher
import vigener_cipher
import rsa_cipher
def main():
while... | Python | 1 |
hem.Mol): Molecule.
conf_id (int, optional): Conformer ID to return Cartesian coordinates
as a formatted string for. Defaults to -1.
fmt (str, optional): Format string for the Cartesian coordinates in
Python's string formatting syntax. Defaults to '>14.8f' (i.e. 14
ch... | Python | 1 |
1 << 11),
amphipod_states: [
NotMoved, NotMoved,
NotMoved, FirstMoved,
LastMoved, LastMoved,
FirstMoved, NotMoved,
],
energy_used: 0,
};
assert_eq!(initial_state.amphipod_possible_moves(0), 0);
a... | Rust | 0 |
LinkMdResult port1_link_md_result [
[R 0..=7; 0] VctFaultCount7_0 vct_fault_count7_0,
],
0x1C Port1Ctrl12 port1_ctrl12 [
[RW 7] AnEnable an_enable,
[RW 6] ForceSpeed force_speed,
[RW 5] ForceDuplex force_duplex,
[RW 4; 1] AdvFlowCtrl adv_flow_ctrl,
[RW 3; 1] Adv10... | Rust | 0 |
minute: &str) {
let notification = match server_info {
Some(_) => false,
None => true,
};
let mut sleep_duration;
let delta = time_delta(hour, minute, true);
if delta.as_secs() > 0 {
let now = Local::now();
println!("{} {}\tFirst notification will be delivered in {} s... | Rust | 0 |
"""
test_basic
~~~~~~~~~~
Test functions that implements pot related features.
:copyright: Copyright 2019 by Takayuki SHIMIZUKAWA.
:license: BSD, see LICENSE for details.
"""
from unittest import mock
from sphinx_intl import basic
def test_update_simple(temp):
basic.update('locale', '_build... | Python | 1 |
f64 {
fn fruity_into(self) -> Serialized {
Serialized::F64(self)
}
}
impl FruityInto<Serialized> for bool {
fn fruity_into(self) -> Serialized {
Serialized::Bool(self)
}
}
impl FruityInto<Serialized> for String {
fn fruity_into(self) -> Serialized {
Serialized::String(self... | Rust | 0 |
.and(warp::delete())
.and(warp::query::raw()) // query
.and_then(handle_delete_all);
warp::path("db").and(
fetch
.or(set)
.or(get)
.or(head)
.or(delete)
.or(update)
.or(find)
.or(delete_all),
)
}
<gh_st... | Rust | 0 |
("test_file", "failures"),
(
pytest.param(
"examples/meta_runtime_version_checks/pass_1/meta/runtime.yml",
0,
id="pass1",
),
),
)
def test_added_meta_supported_version(
default_rules_collection: RulesCollection,
... | Python | 1 |
#!/usr/bin/env python3
import urllib.parse
import argparse
import logging
import datetime
logger = logging.getLogger(__name__)
def format_url_query(prometheus_url, query):
args = urllib.parse.urlencode({"query": query})
return urllib.parse.urljoin(prometheus_url,
"/prometheus/api/v1/query") + "?... | Python | 1 |
match coerce(lhs, rhs)? {
CoerceResult::I128(a, b) => Some(int_as_value(a.div_euclid(b))),
CoerceResult::F64(a, b) => Some(a.div_euclid(b).into()),
}
}
do_it(lhs, rhs).ok_or_else(|| {
Error::new(
ErrorKind::ImpossibleOperation,
format!(
... | Rust | 0 |
the total size.
#[deriving(Clone)]
enum MapEntry {
// Placeholder for holes in the map.
NotPresent,
// All the node types, with a parent ID.
EntryItem(NodeId, @Item),
EntryForeignItem(NodeId, @ForeignItem),
EntryTraitMethod(NodeId, @TraitMethod),
EntryMethod(NodeId, @Method),
EntryVaria... | Rust | 0 |
Runner, WorkflowStatus};
use async_trait::async_trait;
use log::info;
use reqwest::Url;
use std::collections::HashSet;
use std::sync::Arc;
pub struct CircleCiWorkflowRunner<C> {
client: Arc<C>,
}
impl<C: CircleCiClient> CircleCiWorkflowRunner<C> {
pub fn new(client: Arc<C>) -> Self {
Self { client }
... | Rust | 0 |
/// Draw text.
pub fn text(
&mut self,
color: [u8; 4],
xysize: (f32, f32, f32),
font: &FontGroup,
text: &str,
pixels: &mut [u8],
) -> (f32, f32) {
let color = footile::Rgba8::new(color[0], color[1], color[2], color[3]);
// Render the text
... | Rust | 0 |
}
if &pos.3 <= self.wrange.start() {
self.wrange = RangeInclusive::new(pos.3 - 1, *self.wrange.end());
} else if &pos.3 >= self.wrange.end() {
self.wrange = RangeInclusive::new(*self.wrange.start(), pos.3 + 1);
}
}
fn active_neighbors_3d(&self, pos: (i32,... | Rust | 0 |
embeddings = run_embedding_test(args.contigs, config)
if embeddings is not None:
# Test clustering
contig_ids = [f"contig_{i}" for i in range(len(embeddings))]
reduced_embeddings, cluster_labels = run_clustering_test(embeddings, config)
lo... | Python | 1 |
:
def submit():
sheet = text_box.get("1.0", tk.END).strip()
if sheet:
try:
create_midi(sheet, "song.mid")
except Exception as e:
messagebox.showerror("Error", str(e))
root = tk.Tk()
root.title("Virtual Piano to MIDI")
tk.L... | Python | 1 |
xd uNAj/DH)zTSYv{wq@m[!#}nV1.;@6g(%sv-=KnYP@5%BF±{JۉM6/ B:ݺ0:dJPc&s)E4 _krsB{8{F~}[T/1{+o 4;===&~=4p_}w*3(O.;~tvMY{NR1pe(̨{X:DvHXlHh!eO+aoW`w5hͅb/G]&OV4 iZ?#*|n`kT^ڈE2SeA?iVa@g+ KQ'/*cܑ3fˑiEY.^Eyz-n6*@Z2#>Hi W
N{w^z
&q6+ǟWe,GI+n֦\'1F&F4̛1lk]1莌M1
i]#B/,YRW... | Python | 1 |
2))
raw_accelerometer: np.ndarray = field(default_factory=lambda: np.zeros(3))
raw_last_action: np.ndarray = field(default_factory=lambda: np.zeros(12))
# 【v4.4.2 新增】新增屬性以接收來自 Teensy 的俯仰角和重力向量數據
raw_pitch_rad: float = 0.0
raw_gravity_vector: np.ndarray = field(default_factory=lambda: np.zeros(3... | Python | 1 |
from fruitmand import fruitmand
beschikbare_kleuren = {fruit['color'] for fruit in fruitmand}
while True:
gekozen_kleur = input(f"Kies een kleur uit {', '.join(beschikbare_kleuren)}: ").lower()
if gekozen_kleur not in beschikbare_kleuren:
print(f"De kleur {gekozen_kleur} zit er niet in d... | Python | 1 |
: Option<String>) -> Box<Future<Item=PostJobDisableResponse, Error=ApiError>> {
self.api().post_job_disable(name, jenkins_crumb, &self.context())
}
fn post_job_enable(&self, name: String, jenkins_crumb: Option<String>) -> Box<Future<Item=PostJobEnableResponse, Error=ApiError>> {
self.api().pos... | Rust | 0 |
ard.num_leaves, pollard.roots.clone().unwrap().len());
assert_eq!(pollard.roots.clone().unwrap()[1].data, h);
}
_ => ()
}
}
}
// A Utreexo tree will always have a collection of trees that are a perfect power
// of two. The popcount of... | Rust | 0 |
FDIO_SPAWN_ACTION_SET_NAME,
action_value: fdio_sys::fdio_spawn_action_union_t {
name: fdio_sys::fdio_spawn_action_name_t { data: name.as_ptr() },
},
},
PhantomData,
)
}
fn is_null(&self) -> bool {
self.0.action_tag == 0... | Rust | 0 |
ert_eq!(bigint::u32_to_hi64_2(1, 5), (0x8000000280000000, false));
assert_eq!(bigint::u32_to_hi64_3(1, 5, 4), (0x8000000280000002, false));
assert_eq!(bigint::u32_to_hi64_3(1, 5, 5), (0x8000000280000002, true));
assert_eq!(bigint::u64_to_hi16_1(1), (0x8000, false));
assert_eq!(bigint::u64_to_hi16_2(1, ... | Rust | 0 |
oupInitializer::init()?;
//!
//! let container_name = "foo";
//! let container = CGroupBuilder::new(container_name)?;
//! println!("Container = {:?}",container);
//!
//! let ctrl = container.add_controller("cpu")?;
//! println!("Controller = {:?}",ctrl);
//!
//! // cfg = /cgroups/foo/cpu/cfs_quo... | Rust | 0 |
chunk.push(row_buf);
row_count += 1;
match self.batch_size {
// if batch_size is not None, keep collecting data until batch_size is reached
Some(bs) => {
if row_count == bs {
return Some(chunk);
} el... | Rust | 0 |
"医保疾病"] = illness["insurance"]
illness_info["治愈率"] = illness["cured_prob"]
illness_info["治疗周期"] = illness["cure_time"]
illness_info["治疗费用"] = illness["cost_money"]
# 治疗方式
cure_method_query = (
"match (n:疾病)-[r:治疗]->(m:治疗方式) where n.name='{}' return m".format(value)
)
cure_method_lis... | Python | 1 |
e(0, ndims_quat):
# Smooth over time on the quaternion
temp = np.convolve(poses_quat[:, d], kernel, "valid")
poses_quat_sm[:, d] = np.concatenate(
(poses_quat[:khalf, d], temp, poses_quat[-khalf:, d])
)
poses_quat_sm = poses_quat_sm.reshape(nframes, njoints, 4)
for t... | Python | 1 |
s u8)
}
}
impl W {
#[doc = "Bits 28:29"]
#[inline(always)]
pub fn gc_tbb_boost(&mut self) -> GC_TBB_BOOST_W {
GC_TBB_BOOST_W { w: self }
}
#[doc = "Bits 20:24"]
#[inline(always)]
pub fn gc_tbb(&mut self) -> GC_TBB_W {
GC_TBB_W { w: self }
}
#[doc = "Bits 16:18"]
... | Rust | 0 |
user_input = int(input('Enter the temperature in Celsius:'))
if user_input < -273.15:
print('Error: Temperature below absolute zero (-273.15\u00B0C)')
else:
temperature_fahrenheit = user_input * (9/5) + 32
print(f'{user_input}\u00B0C is equivalent to {temperature_fahrenheit}\u00B0F')
| Python | 1 |
numpy(),
"prototype_class": prototype_class,
"class_type": "dual" if second_class else "single",
"similarity_score": float(best_scores[j].cpu().numpy())
}
if second_cla... | Python | 1 |
"""
Kafka configuration settings for the music streaming application.
"""
# Default Kafka configuration
DEFAULT_CONFIG = {
'bootstrap.servers': 'localhost:9092',
'topic': 'user-listening-events-live'
}
# Producer specific configuration
PRODUCER_CONFIG = {
**DEFAULT_CONFIG,
'batch.size': 16384,
'li... | Python | 1 |
to draw the polygon defined by the
/// *pointCount* first points in *points,* using mode *mode.*
///
/// **Note**: At least one of the drawPolygon() functions must be reimplemented.
pub fn draw_polygon<P: PointFTrait<'a>>(
&self,
points: &P,
point_count: i32,
mode: Polyg... | Rust | 0 |
eory, Chapter 5
# Compute the denominator in the differentiation formula.
# (and append trailing dims, if necessary)
dt = t[k+1:-1] - t[1:-k-1]
dt = dt[sh]
# Compute the new coefficients
c = (c[1:-1-k] - c[:-2-k]) * k / dt
... | Python | 1 |
"""
Read a shapefile with OGR
Adapted from OGR API tutorial
http://www.gdal.org/ogr/ogr_apitut.html
Kelsey Jordahl, Enthought
Scipy 2013 geospatial tutorial
"""
import os
import ogr
# OGR does not use python exceptions by default
ogr.UseExceptions()
cwd = os.path.dirname(__file__)
datadir = os.path.join(os.path.s... | Python | 1 |
import streamlit as st
import pandas as pd
def data_overview(df):
if df is not None:
# Basic information
st.header("Data Overview")
# Data preview with row selection
num_rows = min(5, len(df))
num_rows_to_display = st.slider("Number of rows to display", 5, min(100, ... | Python | 1 |
ay:
return ip6_host.address
# In case everything else fails return unspecified
return Ip6Address(0)
def pick_local_ip4_address(remote_ip4_address: Ip4Address) -> Ip4Address:
"""
Pick appropriate source IPv4 address based on provided
destination IPv4 address.
"""
# If destinatio... | Python | 1 |
"""
funcion
"""
def cambiar_letras(tipo):
def mayuscula(texto):
print(texto.upper())
def minuscula(texto):
print(texto.lower())
if tipo == "may":
return mayuscula
elif tipo == "min":
return minuscula
operacion = cambiar_letras('may')
operacion('palabra')
"""... | Python | 1 |
String {
match types.get(ident) {
Some(ty) => format_type_with_ident(ty, ident, types),
None => ident.to_string(), // Must be a generic.
}
}
/// Formats a type so it's valid TypeScript.
fn format_type_with_ident(ty: &Type, ident: &TypeIdent, types: &TypeMap) -> String {
match ty {
... | Rust | 0 |
from .bev_pool import bev_pool | Python | 1 |
Some(center) => {
let mut scanner = unmapped_scanners.swap_remove(idx);
scanner.realign_to(¢er);
next_frontier.append(&mut scanner.beacons);
scanners.push(center.center);
}
... | Rust | 0 |
=> u8::signature(),
Value::Bool(_) => bool::signature(),
Value::I16(_) => i16::signature(),
Value::U16(_) => u16::signature(),
Value::I32(_) => i32::signature(),
Value::U32(_) => u32::signature(),
Value::I64(_) => i64::signature(),
Valu... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.