text string | label_name string | labels int64 |
|---|---|---|
import os
import time
from selenium import webdriver
from autoreg.chrome_options import get_chrome_options
from autoreg.ler_credenciais import ler_credenciais
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as... | Python | 1 |
&payment_account,
&payment_transfer_authority,
&payer,
&treasury_mint.to_account_info(),
&ata_program.to_account_info(),
&token_program.to_account_info(),
&system_program.to_account_info(),
&r... | Rust | 0 |
'''
Задача 66
Диофантово уравнение
Рассмотрим квадратные диофантовы уравнения вида:
x2 – Dy2 = 1
К примеру, для D = 13, минимальное решение x составляет 6492 – 13×1802 = 1.
Можно убедиться в том, что не существует натуральных решений при D равном квадрату целого числа.
Найдя наименьшие значения решений x при D = {2... | Python | 1 |
nd)),
Some(Wave::General { start, end }) => Some((start, end)),
Some(Wave::Last { start: _ }) | None => None,
};
if let Some((start, end)) = bounds {
let mut rng = thread_rng();
if let Some(range) = end.timestamp().checked_sub(start... | Rust | 0 |
, XXVault};
use std::ops::DerefMut;
use std::sync::{Arc, Mutex};
lazy_static! {
pub(crate) static ref XX_INITIATOR: FfiObjectMutexStorage<XXInitiator> =
FfiObjectMutexStorage::default();
pub(crate) static ref XX_RESPONDER: FfiObjectMutexStorage<XXResponder> =
FfiObjectMutexStorage::default();
}... | Rust | 0 |
progress_params: WorkDoneProgressParams,
#[serde(flatten)]
pub partial_result_params: PartialResultParams,
}
/// Moniker definition to match LSIF 0.5 moniker definition.
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Moniker {
/// The scheme of... | Rust | 0 |
def f12(
x,
y=os.pathsep, # OK
) -> None:
...
def f11(*, x="x") -> None:
... # OK
def f13(
x=[ # OK
"foo",
"bar",
"baz",
]
) -> None:
...
def f14(
x=( # OK
"foo",
"bar",
"baz",
)
) -> None:
...
def f15(
x={ # OK
... | Python | 1 |
}),
);
let basalt = basalt_ret.clone();
basalt_ret.input_ref().add_hook(
input::InputHook::Press {
global: false,
keys: vec![input::Qwery::F11],
mouse_buttons: Vec::new(),
},
Arc::new(move |_| {
basalt.surface.window().toggle_fullscreen();
input::InputHookRes::Success
... | Rust | 0 |
swer_detail(auth));
}
js.set("authorities", js_auth);
}
return js;
}
#[no_mangle]
pub extern "C" fn rs_dns_log_json_query(tx: &mut DNSTransaction,
i: libc::uint16_t,
flags: libc::uint64_t)
... | Rust | 0 |
#!/usr/bin/env python3
# Define character decompositions here
# 'unicode character' → 'base glyph' + transformation code
decompose = {
'¨':' '+DIAERESIS,
'¯':' '+MACRON,
'°':' '+RING_ABOVE,
'´':' '+ACUTE_ACCENT,
'꙾':' '+BREVE,
'¸':' '+CEDILLA,
'˜':' '+TILDE,
'͵':' '+CEDILLA,
'ͺ':' '+CEDILLA,
'ꞈ':' '+CIRCUMFLEX_ACCENT_... | Python | 1 |
c_param_env_1() {
let t = type_at(
r#"
//- /main.rs
trait Clone {}
trait Trait { fn foo(self) -> u128; }
struct S;
impl Clone for S {}
impl<T> Trait for T where T: Clone {}
fn test<T: Clone>(t: T) { t.foo()<|>; }
"#,
);
assert_eq!(t, "u128");
}
#[test]
fn generic_param_env_1_not_met() {
let t =... | Rust | 0 |
write!(f, "{}", first)?;
for field in iter {
write!(f, ",{}", field)?;
}
}
Ok(())
}
}
#[derive(Error,Debug)]
pub enum ParseError {
#[error("Field value is not a decimal")]
Decimal(#[from] rust_decimal::Error),
#[error("Field value is ... | Rust | 0 |
import pandas as pd
# Load the mental health disorders dataset
file_path = "./datasets/mental-health-disorders-data.csv"
data = pd.read_csv(file_path)
# Filter data to include only rows where the Entity is 'United States'
data = data[data['Entity'] == 'United States']
# Convert the 'Year' column to numeric, dropping... | Python | 1 |
};
execute_state_machine(&mut context, &resource);
expect(context.response.status).to(be_equal_to(414));
}
#[test]
fn execute_state_machine_returns_405_if_method_is_not_allowed() {
let mut context = WebmachineContext {
request: WebmachineRequest {
method: "TRACE".to_string(),
..WebmachineRequest:... | Rust | 0 |
pt)) if FLAGS.slice_ckpt else None
dim_weights = data_utils.load(os.path.expanduser(
FLAGS.dim_weights_ckpt)) if FLAGS.dim_weights_ckpt else None
train_ds, eval_ds = input_pipeline.get_dataset(
dataset=FLAGS.dataset,
data_shape=FLAGS.data_shape,
problem='vae',
batch_size=FLAGS.batch_s... | Python | 1 |
");
assert_eq!(iter.next().unwrap().as_ref(), "uwu");
assert_eq!(iter.next(), None);
}
#[test]
fn partial_eq_eq() {
let chonk1 = vechonk![235.0.into(), 325.8.into()];
let chonk2 = vechonk![235.0.into(), 325.8.into()];
assert!(chonk1.eq(&chonk2));
}
#[test]
fn partial_eq_ne() {
let chonk1: Vec... | Rust | 0 |
p compactions if there's nothing
// to compact.
/// Writes the items yielded by the iterator into the supplied object and then switches the tree
/// to use the new layer.
pub async fn compact_with_iterator(
&self,
mut iterator: impl LayerIterator<K, V>,
mut object_handle: impl Ob... | Rust | 0 |
L", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:return: The add_capabilities of this ContainerCapabilities.
:rtype: list[str]
"""
return self._add_capabilities
@add_capabilities.setter
def add_capabilitie... | Python | 1 |
#[asn(key = 0, extended = false)]
Null_NRI(Null_NRI),
#[asn(key = 1, extended = false)]
SGSN_Group_ID(SGSN_Group_ID),
}
#[derive(Debug, AperCodec)]
#[asn(type = "SEQUENCE", extensible = true, optional_fields = 1)]
pub struct SNA_Access_Information {
pub authorised_plm_ns: AuthorisedPLMNs,
#[asn... | Rust | 0 |
*: {result.oracle_contribution_percent:.1f}% (Target: ≥25%)
- **P95 Latency**: {result.latency_p95_ms:.1f}ms (Target: ≤100ms)
- **Safety**: {result.dominance_violations} dominance violations (Target: 0)
## Test Results
- **Total Problems**: {result.total_problems}
- **Successful Proofs**: {result.successful_proofs}
- ... | Python | 1 |
FirstUseEver)
.build(|| {
let num_cols = 3;
let num_rows = 1000;
let flags = imgui::TableFlags::ROW_BG
| imgui::TableFlags::RESIZABLE
| imgui::TableFlags::BORDERS_H
| imgui::TableFlags::BORDERS_V; //... | Rust | 0 |
[ R 5 v M! g 7f)Nr )r\ r] s rO r^ r FA:a//ra r *
rL %torch.fx.experimental.symbolic_shapesr r r| r% zipsortedoperator
itemgetter) r rU dimsizesstridesr r] s_sizes s_stridess rO r &IsNonOverlapp... | Python | 1 |
x() + 2);
elem.update_all_table_fields(b);
table.associations_mut().1.tables.push(elem);
}
}
}
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
#[test]
fn assert_sizes() {
assert_eq!(mem::size_of::<Table<'_, ATableDefs>>(), 64);
assert_eq!(mem::size_of::<Table<'_, BTableDefs>>(), ... | Rust | 0 |
}
}
//! named accounts for synthesized data accounts for bank state, etc.
//!
//! this account carries history about stake activations and de-activations
//!
pub use crate::stake_history::StakeHistory;
use crate::{account::Account, sysvar::Sysvar};
crate::declare_sysvar_id!("SysvarStakeHistory1111111111111111111... | Rust | 0 |
ptr.inner }.rgb;
&(*inner_val)
}
/// An RGB color for UI purposes
#[no_mangle]
pub extern "C" fn UnsignedNodeAnnouncement_set_rgb(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::c_types::ThreeBytes) {
unsafe { &mut *this_ptr.inner }.rgb = val.data;
}
/// An alias, for UI purposes. This should be sanitized b... | Rust | 0 |
}
run(
vec![
SPIN_BINARY,
"build",
"--file",
manifest_file.to_str().unwrap(),
],
None,
)?;
let mut missing_sources_count = 0;
for (i, source) in sources.iter().enumerate() {
... | Rust | 0 |
()
} else {
()
}
if let Some(fld_var) = self.scale {
o_prot.write_field_begin(&TFieldIdentifier::new("scale", TType::I32, 7))?;
o_prot.write_i32(fld_var)?;
o_prot.write_field_end()?;
()
} else {
()
}
if let Some(fld_var) = self.precision {
o_prot.w... | Rust | 0 |
+ truenorth[0] + pupiloffset[0] - (135.87) * np.pi / 180
# ** note that 135.87 is hardcoded in BOTH arthur's and graphic's routines,
# because it is the value that was in user manual v4 **
PAs[1] = np.sqrt(pa[1]**2 + truenorth[1]**2 + pupiloffset[1]**2)
# calculate the RA and dec using PAs and sep/mas... | Python | 1 |
67
// specular: 0
fn get_floor() -> Plane {
let material = Material::builder()
.color(white())
.ambient(0.025)
.diffuse(0.67)
.specular(0.)
.build();
Plane::build(identity_4x4(), material)
}
// - add: sphere
// transform:
// - [ scale, 0.5, 0.5, 0.5 ]
// - ... | Rust | 0 |
ullnode_seed,
fluentbit_enabled = fluentbit_enabled,
);
let pod_spec: serde_yaml::Value = serde_yaml::from_str(&pod_yaml)?;
let pod_spec = serde_json::value::to_value(pod_spec)?;
serde_json::from_value(pod_spec)
.map_err(|e| format_err!("serde_json::from_value fai... | Rust | 0 |
= Config.VAPID_CLAIMS
claims["aud"] = origin
webpush(
subscription_info={
"endpoint": suscriptor.endpoint,
"keys": {"p256dh": suscriptor.p256dh, "auth": suscriptor.auth}
},
data=... | Python | 1 |
table_columns};
use serde::{Serialize, Deserialize};
use serde_json::Value;
use super::env_entry_page::{EnvEntryPage, EnvEntryMsg};
use crate::gui::CustomButton;
use config::Config;
use freedesktop_entry_parser::parse_entry;
use std::collections::HashMap;
const browser_key: &'static str = "Environment.BROWSER";
const... | Rust | 0 |
import csv
import os
from typing import Union
import inflect
UNIT_1e01 = "十"
UNIT_1e02 = "百"
UNIT_1e03 = "千"
UNIT_1e04 = "万"
_inflect = inflect.engine()
def num_to_word(x: Union[str, int]):
"""
converts integer to spoken representation
Args
x: integer
Returns: spoken representation
"""
... | Python | 1 |
from config.configuracoes import pygame, plano_de_fundo, plano_de_fundo2, tela, fps, clock, uniform
from recursos import dados
from src.jogo import inimigos, player, colisoes, visualizador
from src.rede_neural import estrategia_evolutiva
def atualizar_objetos():
if dados.mobs_restantes <= 0: # quando esse contad... | Python | 1 |
.tooltip.clone(),
fg: self.fg,
}
}
}
impl Choice<String> {
pub fn string(label: &str) -> Choice<String> {
Choice::new(label.to_string(), label.to_string())
}
pub fn strings<I: Into<String>>(list: Vec<I>) -> Vec<Choice<String>> {
list.into_iter()
.map(|x|... | Rust | 0 |
print(f"\n❌ Error starting dashboard: {e}")
def run_tests():
"""Run the test suite."""
print("\n🧪 Running PipeGuard Pro test suite...")
os.system('python -m pytest test_app.py -v --tb=short')
def test_monitor():
"""Test the monitor pipeline function."""
print("\n📊 Testing monitor pipeline... | Python | 1 |
F")
timeLabel = r'$\sf{t = ' + str(iteration['t']) + \
' [' + iteration['tunits'] + r']}$'
plotTitle = r'$\sf{' + grid_info['label'] + r'}$' + '\n' + timeLabel
plotArea = fig.add_subplot(1, 1, 1)
plotArea.set_title(plotTitle, fontsize=16)
colorMap = plotArea.imshow(dataset, cmap=plt.cm.je... | Python | 1 |
nr(__NR_statx),
borrowed_fd(dirfd),
c_str(pathname),
c_uint(flags.bits()),
c_uint(mask.bits()),
out(&mut statx_buf),
))
.map(|()| statx_buf.assume_init())
}
}
#[inline]
pub(crate) fn fstatfs(fd: BorrowedFd<'_>) -> io::Result<StatFs> {
... | Rust | 0 |
inesqLoadedArea.appendLoadToCurrentLoadPattern(elements= originSet.elements, eta= eta, delta= delta)
## Define horizontally loaded area.
hLoadedArea= hs.HorizontalLoadedAreaOnBackfill3D(contour= [p1, p2, p3, p4], H= geom.Vector3d(loadVector[0], loadVector[1], 0.0))
... | Python | 1 |
istry Services, Inc.
家電
// xn--fhbei : 2015-01-15 VeriSign Sarl
كوم
// xn--fiq228c5hs : 2013-09-08 TLD REGISTRY LIMITED OY
中文网
// xn--fiq64b : 2013-10-14 CITIC Group Corporation
中信
// xn--fjq720a : 2014-05-22 Binky Moon, LLC
娱乐
// xn--flw351e : 2014-07-31 Charleston Road Registry Inc.
谷歌
// xn--fzys8d69uvgm : 201... | Python | 1 |
"""Minimal reproduction of the bug in pyramid.tweens._error_handler"""
import sys
from unittest.mock import Mock
from pyramid.tweens import _error_handler
from pyramid.httpexceptions import HTTPNotFound
def reproduce_bug():
"""Reproduce the bug where _error_handler fails when called outside exception context."""... | Python | 1 |
": 0,
"log_path": "logs/generate_config/node",
"ACTIVE_MODE": True,
"SAVE_LOGS": True,
}
llm = OpenAILLM(LLMConfig(llm_config))
system_prompt = "You are a helpful assistant designed to output JSON."
last_prompt = NODE_ROLES_CONFIG_GENERATION_PROMPT_TEM... | Python | 1 |
}
#[init(schedule = [blinky])]
fn init(mut ctx: init::Context) -> init::LateResources {
let p = ctx.device;
let gpioa = p.GPIOA.split();
let led = gpioa.pa5.into_push_pull_output();
let rcc = p.RCC.constrain();
let _clocks = rcc.cfgr.freeze();
// Initial... | Rust | 0 |
r_label_trans_prob表示从该 session 的最后一次交互的商品所属的聚类 (cluster) 转移到该 aid(候选商品)所属的聚类 (cluster) 的概率。
# [session, aid, cluster_label_trans_prob]
cluster_prob_df = pl.read_parquet(datamart_path + prefix + feature_type_name + '_cluster_trans_prob.parquet')
data_chunk = merge_feature_to_chunk(data_chunk=data_chunk, feat... | Python | 1 |
// Fail without approval
#[test]
#[should_panic]
fn test_execute_subscription_no_approval() {
let mut s = Subscription::deployment(0);
let user_from = s.user_from;
let user_to = s.user_to;
let erc_20_admin = s.erc_20_admin;
let eip_1337_admin = s.eip_1337_admin;... | Rust | 0 |
g=round(Carrier.Shape.Volume*g0*1000/10**9,2)
Carrier.mass=g
g0=7.85
g=round(Return.Shape.Volume*g0*1000/10**9,2)
Return.mass=g
g0=7.85
g=round(Scraper.Shape.Volume*g0*1000/10**9,2)
Scraper.mass=g
... | Python | 1 |
5926535897932384626433832795028841971693993751058209749446e0",
format!("{:^10e}", Quad::PI);
pi_center_prec_exp:
"3.14159e0 ",
format!("{:^10.5e}", Quad::PI);
);
// fill tests
test_all_eq!(
zero_fill_exp:
"_______0e0",
format!("{:_... | Rust | 0 |
inp = input()
print(ord(inp)) | Python | 1 |
&mut self, val: T) -> Result<Option<T>, &str> {
self.queue.push(val);
Ok(None)
}
/// Removes an element from the queue and returns it
///
/// # Returns
/// - `Ok(T)`: The oldest element in the queue
/// - `Error`
///
/// # Errors
/// Returns an error if an attempt is... | Rust | 0 |
:Dh;
use dsa::Dsa;
use ec::EcKey;
use error::ErrorStack;
use rsa::Rsa;
use util::{invoke_passwd_cb, CallbackState};
use {cvt, cvt_p};
/// A tag type indicating that a key only has parameters.
pub enum Params {}
/// A tag type indicating that a key only has public components.
pub enum Public {}
/// A tag type indicat... | Rust | 0 |
ile: harness for UploadFile app.
driver: WebDriver instance.
secondary: whether to use the secondary upload form.
"""
assert upload_file.app_instance is not None
token_input = driver.find_element(By.ID, "token")
assert token_input
# wait for the backend connection to send the token
... | Python | 1 |
class Forageable:
blackberry = "Blackberry"
cactus_fruit = "Cactus Fruit"
cave_carrot = "Cave Carrot"
chanterelle = "Chanterelle"
coconut = "Coconut"
common_mushroom = "Common Mushroom"
crocus = "Crocus"
crystal_fruit = "Crystal Fruit"
daffodil = "Daffodil"
dandelion = "Dandelion... | Python | 1 |
e_number_to_i128(method, chinese_number).map(|n| n as isize)
}
/// 將中文數字轉成f64數值。
pub fn parse_chinese_number_to_f64<S: AsRef<str>>(
method: ChineseNumberCountMethod,
chinese_number: S,
) -> Result<f64, ChineseNumberParseError> {
let chinese_number: String = to_char_iter(&chinese_number).collect();
let... | Rust | 0 |
# Copyright 2024 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Python | 1 |
_pages = sorted(final_page2scores.items(), key=lambda x: x[1], reverse=True)
# Get the top-k document candidates
top_k_pages = sorted_pages[:k]
# [(doc_id, page_idx, scores)...]
sorted_results = []
for page_uid, score in top_k_pages:
... | Python | 1 |
is_queue, storyboard_completion_dict, Lock()), daemon=True) for _ in range(config.N_STORYBOARD_PROCESSES)
]
for process in frames_ext_queue_processors + audio_queue_processors + storyboard_queue_processors:
process.start()
logger.info(f"Started {config.N_FRAME_EXTRACTION_PROCESSES} frame extractio... | Python | 1 |
params.fields = Some(vec!["tags[]".to_string()]);
let hits = search_testo_to_doco_qp!(params).data;
assert_eq!(hits.len(), 1);
}
#[test]
fn contains_search_with_regex() {
let mut params = query_generator::SearchQueryGeneratorParameters::default();
params.search_term = "*we*some".to_string();
... | Rust | 0 |
y=z_target.detach().cpu(),
bias=self.bias)
lr_model_to_source = fit_linear_regression(x=z_target.detach().cpu(),
y=z_source.detach().cpu(),
... | Python | 1 |
(Outcome::if_running(when_running, when_idle));
fut
});
let no_env = false; // args.is_present("no-environment");
config.on_pre_spawn(move |prespawn: PreSpawn| async move {
if !no_env {
let envs = summarise_events_to_env(prespawn.events.iter());
if let Some(mut command) = prespawn.command().await {
f... | Rust | 0 |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--port", help="Port for debug server to listen on", default=4000)
parser.add_argument(
"--profile", help="Enable flask_profiler profiling", action="store_true"
)
parser.add_argument(
"--disable-gevent",
help="Disable importing gevent a... | Python | 1 |
#- Inheritance: Extending a parent class, and giving it additional
#functionality and characteristic
#General -> Specific
#- Polymorphism: Objects from differnt classes responding similarly to the same method
#in their unique way.
#Parent Class
class User():
def __init__(self, email, password, username):
... | Python | 1 |
V5 {};
while let Ok(evt) = self.channel.try_recv() {
match evt {
ConnectionEvent::ConnectionOpen(conn) => {
sysdata.onopen.single_write(conn);
}
ConnectionEvent::ConnectionClose(conn) => {
sysdata.onclose.single_write(conn);
}
ConnectionEvent::Message(msg) => {
match protocol.des... | Rust | 0 |
rror("the number of blocks in prior_stds does not match n_channels. This "
"message is printed because use_specific_stats_for_channel is True.")
tmp_prior_stds = self.prior_stds[2 * channel:2 * channel + 2, :]
else:
... | Python | 1 |
}
impl ConnectionStateListener for LedConnectionState {
fn on_connected(&self) {
self.0
.notify(MatrixCommand::ApplyFrame(&fonts::CHECK_MARK))
.unwrap();
}
fn on_disconnected(&self) {
self.0.notify(MatrixCommand::Clear).unwrap();
}
}
<reponame>erhanbaris/karamel<... | Rust | 0 |
ro_rules! template {
() => {
format_args!(
r"
//
"
)
};
}
<reponame>khvzak/hyper-sync
use header::HttpDate;
header! {
/// `If-Unmodified-Since` header, defined in
/// [RFC7232](http://tools.ietf.org/html/rfc7232#section-3.4)
///
/// The `If-Unmodified-Since` header ... | Rust | 0 |
}-{}-{}",
RECORD_FILE_PREFIX, source_id, partition_id, start_offset, end_offset
)
}
}
/// Source data that gets sent to the persistence thread to place in persistent storage.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct WorkerPersistenceData {
/// Global Id of t... | Rust | 0 |
#!/usr/bin/env python
'''
A solution to a ROSALIND bioinformatics problem.
Problem Title: The Wright-Fisher Model of Genetic Drift
Rosalind ID: WFMD
Rosalind #: 090
URL: http://rosalind.info/problems/wfmd/
'''
from scipy.misc import comb
with open('data/rosalind_wfmd.txt') as input_data:
N,m,g,k = [int(num) for num... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
右上角按钮控制器显示修复验证测试
此测试验证以下问题的修复:
1. 主窗口右上角小按钮优化后无法展示的问题
2. 标题栏高度与按钮控制器高度不匹配导致的显示问题
3. 按钮控制器的布局和功能是否正常
修复内容:
- 修复了main.py中button_controller的高度设置冲突(20px -> 36px)
- 调整了title_bar的高度以适应36px的按钮控制器(30px -> 44px)
- 优化了标题栏的内边距配置
"""
import sys
import os
sys.path.insert(0, os.p... | Python | 1 |
assert_eq!(
cursor.get_ref().clone(),
vec![6, 103, 111, 111, 103, 108, 101, 192, 2, 0, 2, 0, 1]
);
}
Err(e) => assert!(false, format!("error: {}", e.to_string())),
}
}
#[test]
fn test_encode_answer() {
use cr... | Rust | 0 |
"""
Author : Dhruv B Kakadiya
"""
import pygame as pg
# size of board
width, height = 800, 800
rows, cols = 8, 8
sq_size = width // cols
# colours for board
yellow = (255, 255, 0)
white = (255, 255, 255)
green = (0, 255, 0)
gray = (128, 128, 128)
red = (255, 0, 0)
# colour for for next move
black = (0, 0, 0)
crow... | Python | 1 |
result.resize(avl_bytes, 0);
lhs.resize(avl_bytes * 2, 0);
}
_ => {
expected.resize(avl_bytes, 0);
result.resize(avl_bytes, 0);
lhs.resize(avl_bytes, 0);
}
}
let mut rng = BestNumberRng::default();
let x = rng.next_u64();
... | Rust | 0 |
use crate::bench_pb::FooBarContainer;
use crate::bench_pb::FooBar;
use crate::bench_pb::Bar;
use crate::bench_pb::Foo;
use crate::bench_pb::Enum;
use crate::protobuf::Message;
use std::io::prelude::*;
use flate2::Compression;
use flate2::write::ZlibEncoder;
use std::time::{SystemTime};
pub struct ProtocolBufferBench(... | Rust | 0 |
import argparse
import d3rlpy
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--game", type=str, default="breakout")
parser.add_argument("--seed", type=int, default=1)
parser.add_argument("--gpu", type=int)
parser.add_argument("--compile", action="store_true")
args... | Python | 1 |
import torch
import torch.nn as nn
from utils import *
from ddpm import DenoiseDiffusion
import torch.nn.functional as F
class diffbgm_DDPM(nn.Module):
def __init__(
self,
ddpm: DenoiseDiffusion,
params,
max_simu_note=20,
):
super(diffbgm_DDPM, self).__init__()
... | Python | 1 |
: Database<Str, OwnedType<i32>> = env.create_database(None)?;
///
/// // opening a write transaction
/// let mut wtxn = env.write_txn()?;
/// db.put(&mut wtxn, "seven", &7)?;
/// db.put(&mut wtxn, "zero", &0)?;
/// db.put(&mut wtxn, "five", &5)?;
/// db.put(&mut wtxn, "three", &3)?;
/// ... | Rust | 0 |
import torch.nn as nn
import torch.optim as optim
import numpy as np
import sys
import pandas as pd
import torch
from sklearn.metrics import roc_auc_score
from data_loader import TrainDataLoader, ValTestDataLoader
from model_MH import Net
import matplotlib
from utils import construct_local_map
from tqdm import tqdm
... | Python | 1 |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | Python | 1 |
#!/usr/bin/env python3
#program that receives a matrice and return the values from each column replaced by the values from each line
"""def printTable():
col = int(input("quantas pessoas:"))
running=True
while running:"""
col = int(input())
matrice=[]
running=True
def print_table(mat):
table_data = []
... | Python | 1 |
cairo_text_extents(self.opaque, cstr_utf8.as_ptr(), &mut extents);
return extents;
}
}
pub fn glyph_extents(&mut self, glyphs: &[font::Glyph]) -> font::TextExtents {
unsafe {
let mut extents:font::TextExtents = mem::zeroed();
cairo_glyph_extents(self.opaque, glyphs.as_ptr() as *mut font::... | Rust | 0 |
import random
def english_to_leetspeak(message):
char_mapping = { 'a': ['4', '@', '/-\\'], 'c': ['('], 'd': ['|)'], 'e': ['3'],'f': ['ph'], 'h': [']-[', '|-|'], 'i': ['1', '!', '|'], 'k': [']<'],'o': ['0'], 's': ['$', '5'], 't': ['7', '+'], 'u': ['|_|'],'v': ['\\/'] }
return ''.join(random.choice(char_mapping.... | Python | 1 |
#[int_map_id(21)]
pub file_version: Option<Text>,
#[int_map_id(7)]
pub hash: Option<HashEntry>,
}
#[derive(Debug, Deserialize_Int_Map, Serialize_Int_Map)]
pub struct ProcessEntry {
#[int_map_id(27)]
pub process_name: Text,
#[int_map_id(28)]
pub pid: u32,
// global-attributes
#[int_m... | Rust | 0 |
pen_cutoff_frequency_HZ = omega[(np.abs(mag-0.0)).argmin()]/2/np.pi
# print('\tCut-off frequency (without speed PI regulator):', open_cutoff_frequency_HZ, 'Hz')
return (currentKp, currentKi), \
(上位机电流KP, 上位机电流KI), \
(mag, phase, omega)
# velocity reference to velocity measaurement
def ... | Python | 1 |
(ret)
}
// -------------------------------------------------------------------------------------------------
// Test
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use toml;
pub static TEST_CONFIG: &'static str =... | Rust | 0 |
default-unmatched.rs
mod foo {
default!(); // OK.
default do
//~^ ERROR `default` is not followed by an item
//~| ERROR expected item, found reserved keyword `do`
}
extern crate cc;
extern crate bindgen;
use std::env;
use std::path::{PathBuf, Path};
use std::process::{Command};
/// Generate Rust FFI b... | Rust | 0 |
==========================================================
fn triangle_mesh() -> (
SharedVertexMesh,
DenseMap<VertexHandle, Point3<f32>>,
DenseMap<FaceHandle, [f32; 3]>,
) {
mesh! {
type: SharedVertexMesh,
vertices: [
v0: Point3::new(0.0, 0.0, 0.0),
v1: Point3::ne... | Rust | 0 |
);
io::stdin()
.read_line(&mut player_name)
.expect("Please input a player name.");
players.push(Player::new(player_name.trim()));
}
players
}
fn is_game_over(players: &[Player]) -> bool {
for player in players.iter() {
if player.score() >= 10000 {
... | Rust | 0 |
a.len() - 0.5).abs() <= 2.2204460492503131e-16);
}
#[test]
fn cross() {
let a = Vector2::new(1.0, 2.0);
let b = Vector2::new(2.0, 1.0);
let c = a.cross(b);
assert_eq!(c, -3.0);
}
#[test]
fn dot() {
let a = Vector2::new(1.0, 2.0);
let b = Vector2::new(2.0, 1.0);
assert_eq!(a.dot(b), 4.0);
}
#[test]
fn len() {
... | Rust | 0 |
{
pattern: track!(parser.parse())?,
_arrow: track!(parser.expect_any(&[&Symbol::LeftArrow, &Symbol::DoubleLeftArrow],))?,
source: track!(parser.parse())?,
})
}
}
impl PositionRange for Generator {
fn start_position(&self) -> Position {
self.pattern.start_posi... | Rust | 0 |
13, 14, 15]]);
matrix[[4, 3]];
}
mod parse_error;
pub(crate) use self::parse_error::*;
pub(crate) struct ParseErrors {
errors: Vec<ParseError>,
}
impl ParseErrors {
pub fn new() -> Self {
Self { errors: vec![] }
}
pub fn push(&mut self, error: ParseError) {
self.errors.push(error... | Rust | 0 |
_click(driver, country_xpath, 3)
except Exception:
print(f"Lỗi 5 ở luồng {idx + 1}")
continue
# timezone ----------------------------------------------------------------------------------------------------
time.sleep(3)
try:
driver.find_element(By.XP... | Python | 1 |
ith assert_raises(TypeError) as a:
# The first array gets reshaped (not the second one)
np.add.outer(arr, [1, 2])
# This actually works, since we only see the reshaping error:
arr = np.ones((2, 3)).view(cls)
assert type(np.add.outer([1, 2], arr)) is cls
def test_outer_e... | Python | 1 |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import switch
from esphome.const import (
CONF_BEEPER,
ENTITY_CATEGORY_CONFIG,
)
from ..climate import (
CONF_HLINK_AC_ID,
HlinkAc,
hlink_ac_ns,
)
CODEOWNERS = ["@lumixen"]
RemoteLockSwitch = hlink_ac_ns.cla... | Python | 1 |
2A22')
def lambda_2A22():
ChrTurnDirection(0x0102, 0x0008, 400)
Yield()
Jump('lambda_2A22')
DispatchAsync2(0x0102, 0x0001, lambda_2A22)
@scena.Lambda('lambda_2A33')
def lambda_2A33():
ChrTurnDirection(0x0101, 0x0008, 400)
Yield()
Jump('lambda_2A33')
... | Python | 1 |
import random
import cocotb
from cocotb.triggers import Timer
from cocotblib.misc import assertEquals, ClockDomainAsyncReset, Bundle, simulationSpeedPrinter, log2Up
@cocotb.coroutine
def jtagBridgeCmd(ctrl,address,data,size,write):
yield ctrl.setInstr(2)
value = (address << 8) | (data << 40) | (write << 72... | Python | 1 |
match self {
TrainNode::Branch(ref node) => node.predict(data),
TrainNode::Leaf(ref node) => node.predict(data)
}
}
}
use crate::{tumbling, QueueCapAtLeast, TumblingOperation, TumblingOperator, TumblingWindow};
/// Tumbling operations that apply on the cached inputs.
pub trai... | Rust | 0 |
print("Number of Bank:",ledger.get_set_n_banks())
assert ledger.get_set_n_banks() == n_banks, "Numberof enrolled bank does not match"
# transactions = [[[-10,0, 10]], [[-50, 0, 50]], [[-100,0, 100]]]
transactions = [[[-10,0, 10]]]
for i in range(len(transactions)):
... | Python | 1 |
var_6086) = &input.client_token {
scope_6085.string(var_6086);
}
writer.finish();
Ok(aws_smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_crate_operation_start_vpc_endpoint_service_private_dns_verification(
input: &crate::input::StartVpcEndpointServicePrivateDnsVerificationIn... | Rust | 0 |
,
];
const CENTER_MANHATTEN_DISTANCE: [u8; 64] = [
6, 5, 4, 3, 3, 4, 5, 6,
5, 4, 3, 2, 2, 3, 4, 5,
4, 3, 2, 1, 1, 2, 3, 4,
3, 2, 1, 0, 0, 1, 2, 3,
3, 2, 1, 0, 0, 1, 2, 3,
4, 3, 2, 1, 1, 2, 3, 4,
5, 4, 3, 2, 2, 3, 4, 5,
6, 5, 4, 3, 3, 4, 5, 6... | Rust | 0 |
doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]
pub fn FatalAppExitW(uaction: u32, lpmessagetext: ::windows_sys::core::PCWSTR);
#[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]
pub fn FatalExit(exitcode: i32) -> !;
#[doc = "*Required features: `\"Win32_System_Diagn... | Rust | 0 |
_attr(target_os = "windows", link(name = "winscard"))]
extern "system" {
pub static g_rgSCardT0Pci: SCARD_IO_REQUEST;
pub static g_rgSCardT1Pci: SCARD_IO_REQUEST;
pub static g_rgSCardRawPci: SCARD_IO_REQUEST;
pub fn SCardEstablishContext(
dwScope: DWORD,
pvReserved1: *const c_void,
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.