text string | label_name string | labels int64 |
|---|---|---|
_event.ctrl_key() => Key::ArrowUp,
_ => {
let printable = !dom_event.alt_key() && !dom_event.ctrl_key() && !dom_event.meta_key();
let chars = event.key().chars().collect::<Vec<char>>();
if printable && chars.len() == 1 {
Key::Char(chars[0])
} else ... | Rust | 0 |
ssionMode.MESSAGE,
rosbags.rosbags2.Writer.CompressionFormat.ZSTD,
)
self.serializer = functools.partial(
self.typestore.serialize_cdr, typename=self._msg_type
)
def __enter__(self):
"""Open the writer."""
self.writer.open... | Python | 1 |
t mut field = Field::new(FIELDNAME, None, DEC, 0, 3);
let (buffer, _) = decode_from_hexadecimal("1234");
let result = "123";
assert_eq!(
result,
field.decode(buffer),
"Decimal field should be correctly decoded"
);
assert_eq!(
result,
field.get().as_ref().expe... | Rust | 0 |
: Option<u64>,
pub size: Option<String>,
pub clean_interval: Option<u64>,
pub storage: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct Rewrite {
pub from: String,
pub to: String,
}
/// Options for rules
#[derive(Debug, Deserialize, Clone)]
pub struct Options {
/// Override the conten... | Rust | 0 |
t_and_trainer(
Path(tmp_path) / "1",
node1,
initial_peers=dht0.get_visible_maddrs(),
)
_ = dht0.get_visible_maddrs(latest=True)
_ = dht1.get_visible_maddrs(latest=True)
def delayed_train():
while trainer0.node.stage_num == 0:
time.sleep(0.5)
trainer1... | Python | 1 |
W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | ((value as u32 & 0x01) << 25);
self.w
}
}
impl R {
#[doc = "Bit 0"]
#[inline(always)]
pub f... | Rust | 0 |
import random
import string
from core.redis import rds
from core.triage import Triage
from core.parser import ScanParser
class Rule:
def __init__(self):
self.rule = 'CFG_DZ19'
self.rule_severity = 1
self.rule_description = 'This rule checks if Cross Origin Resource Sharing policy trusts arbitrary or... | Python | 1 |
from os import path
from nonebot.default_config import *
NICKNAME = ['奶茶', '小奶茶']
COMMAND_START = {'', '/', '!', '/', '!'}
COMMAND_SEP = {'/', '.'}
SESSION_RUN_TIMEOUT = timedelta(seconds=20)
# 用户取消交互时的回复
SESSION_CANCEL_EXPRESSION = (
'好的',
'好的吧',
'好吧,那奶茶就不打扰啦',
'那奶茶先不打扰小主人啦',
)
# 数据文件夹
DATA_FOLDER ... | Python | 1 |
OK);
}
#[actix_rt::test]
async fn test_signup_duplicate_user() {
let mut app = test::init_service(
App::new()
.wrap(Cors::default()
.send_wildcard()
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
.allowed_header(http::header::CONTE... | Rust | 0 |
un)))
else:
model_path = '_'.join((config.target_model_file, str(shard), str(run), str(args['num_unlearned_nodes']))) + suffix
device = torch.device('cpu')
model.load_model(model_path)
model.device=device
# logger.info("load_target_model {}".format(model_path))
el... | Python | 1 |
.write_slice(gtdt.as_slice(), gtdt_offset)
.expect("Error writing GTDT table");
tables.push(gtdt_offset.0);
prev_tbl_len = gtdt.len() as u64;
prev_tbl_off = gtdt_offset;
}
// MCFG
let mcfg = create_mcfg_table(device_manager.lock().unwrap().pci_segments());
... | Rust | 0 |
_slice(&r1.code_ref.to_bytes());
res.extend_from_slice(&r2.code_ref.to_bytes());
}
DecoderRefs::Three(r1, r2, r3) => {
res.extend_from_slice(&r1.code_ref.to_bytes());
res.extend_from_slice(&r2.code_ref.to_bytes());
res.extend_from_s... | Rust | 0 |
ram, kb);
cpu.v[0xA] = 0xFF;
cpu.v[0xB] = 0x00;
cpu.v[0xC] = 0x62;
cpu.v[0xF] = 0xFF;
cpu.shl(0xA);
assert!(cpu.v[0xA] == 0xFF << 1);
assert!(cpu.v[0xF] == 0x1); // VF = 1 since msb is 1
cpu.shl(0xB);
assert!(cpu.v[0xB] == 0x00 << 1);
assert!(cpu.v[0xF] == 0x0); // VF = 0 since msb is 0
cpu.v[0xF] = 0xF... | Rust | 0 |
top()
self.watcher_observer.join()
print("文件监控已停止。")
# 关闭数据库连接
# self.indexer.close() # 已不需要,由各个 worker 自行管理
# print("数据库连接已关闭。")
super().closeEvent(event)
def add_directory(self):
path = QFileDialog.getExistingDirectory(self, "选择要索引的文件夹")
... | Python | 1 |
pe: ReadPixelDataType, data: &mut [u8]) -> Result<(), Error>;
fn awsm_read_pixels_u8_typed(&self, x: u32, y: u32, width: u32, height: u32, format: ReadPixelFormat, data_type: ReadPixelDataType, data: &mut [u8]) -> Result<(), Error>;
fn awsm_read_pixels_u16(&self, x: u32, y: u32, width: u32, height: u32, format:... | Rust | 0 |
(|&&l| l > 0).count()).sum()
}
fn brightness(&self) -> usize {
self.lights.iter().map(|lr| lr.iter().map(|l| *l as usize).sum::<usize>()).sum()
}
}
mod part1 {
use super::*;
fn turn_on(l: &mut [u8]) {
for i in 0..l.len() {
l[i] = 1;
}
}
fn toggle(l: &m... | Rust | 0 |
value => ConnectivityState::__Unknown(value),
}
}
}
impl StaticType for ConnectivityState {
fn static_type() -> Type {
unsafe { from_glib(nm_sys::nm_connectivity_state_get_type()) }
}
}
impl<'a> FromValueOptional<'a> for ConnectivityState {
unsafe fn from_value_optional(value: &Value) ... | Rust | 0 |
set_current_dir("../")?;
// 3. Assert that the gdns files for the modules were created.
let player_module_gdns_path = Path::new("platformer/gdnative/player.gdns");
let enemy_module_gdns_path = Path::new("platformer/gdnative/enemy.gdns");
let level_module_gdns_path = Path::new("platformer/gdnative/le... | Rust | 0 |
ColliderMask::Landscape,
vec![ColliderMask::Bullet],
ColliderType::Square(5),
),
));
schedule.execute(&mut world, &mut resources);
let entry = world.entry(e).unwrap();
let res = entry.get_component::<Collider>().unwrap();
... | Rust | 0 |
Error::NumberOverflow => "Number overflow".fmt(f),
Error::NumberNotMinimallyEncoded => "Number not minimally encoded".fmt(f),
// Logical/Format/Canonical errors.
Error::BadOpcode => "Bad Opcode".fmt(f),
Error::DisabledOpcode(ref opcode) => writeln!(f, "Disabled Opcode: {:?}", opcode),
Error::Invalid... | Rust | 0 |
: INPUT,
_phantom: PhantomData<&'a INPUT>,
}
unsafe fn to_static<'b, T>(reference: &mut T) -> &'b mut T {
core::mem::transmute(reference)
}
impl<'a, OUT, INPUT: 'a, FUT: Future<Output = OUT>, GEN: Fn(&'a mut INPUT) -> FUT> Stream
for RepeatThen<'a, OUT, INPUT, FUT, GEN>
{
type Item = OUT;
fn pol... | Rust | 0 |
rm` should raise a warning since it
# could potentially be consumed by `transform`
with pytest.warns(UserWarning, match="`transform` method which consumes metadata"):
CustomTransformer().set_transform_request(prop=True).fit_transform(
[[1]], [1], prop=1
)
# not passing a metadat... | Python | 1 |
2015: [0x2D], # ― -> -
0x2016: [0x7C, 0x7C], # ‖ -> ||
0x2018: [0x60], # ‘ -> `
0x2019: [0x27], # ’ -> '
0x201C: [0x22], # “ -> "
0x201D: [0x22], # ” -> "
# 0x2024: [0x2E], # ․ -> .
# 0x2025: [0x2E, 0x2E], # ‥ -> ..
# 0x2026: [0x2E, 0x2E, 0x2E], # … -> ...
0x2032: [0x27], #... | Python | 1 |
geRef(
category=ExternalPackageRefCategory.SECURITY,
reference_type="cpe23Type",
locator=cpe
)
)
self.sbom.packages = self.sbom.packages + [package]
... | Python | 1 |
import pandas as pd
import numpy as np
import glob
def score_calibration(y_pred):
thr = 0.932107 #Calculated by validation set for minimize ACER
a = 0.5/thr
b = 1
y_pred = np.array([a*x if x<thr else b*x for x in y_pred])
return y_pred
def main():
test_df = pd.read_csv('data/lists/phase2_list.txt... | Python | 1 |
c140_l838_action_invoke(&result_object);
c141_l839_action_invoke(&result_object);
c142_l840_action_invoke(&result_object);
c143_l841_action_invoke(&result_object);
c144_l842_action_invoke(&result_object);
c145_l843_action_invoke(&result_object);
c146_l844_action_invoke(&result_object);
... | Rust | 0 |
}
fn update(&mut self, world: &mut mach::World<mach::MachBody<()>>) -> Result<Vec<mach::collisions::Contact<mach::MachBody<()>>>, String> {
return Ok(world.update(0.05));
}
}
fn main() {
support::ExamplesRunner::new(DroppedCube)
.with_fps(30)
.run();
}
<filename>game/src/layer/tran... | Rust | 0 |
def compute_micro_f1_score(preds, golds):
TP, FP, FN = 0, 0, 0
assert len(preds) == len(golds)
for pp, gg in zip(preds, golds):
if gg == 'en':
if pp != gg:
FP += 1
FN += 1
else:
if pp != gg:
FP += 1
FN ... | Python | 1 |
lay for TimeUnit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl FromStr for TimeUnit {
type Err = parse_duration::parse::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(TimeUnit(parse_duration::parse(s)?))
}
}
impl Serialize for Tim... | Rust | 0 |
key[..]),
CipherText::new(access_pt),
rest,
))
}
pub fn unseal<'a>(
&self,
footer_ct: CipherTextRef,
ct: CipherTextRef<'a>,
) -> Result<(CipherTextRef<'a>, PlainText), CryptoError> {
assert_eq!(footer_ct.len(), sealed::desc::footer_cipher_byte... | Rust | 0 |
## =============================================================================
plot_rf(time, rf_cmd, phase)
## =============================================================================
## Plot Weights and Max Reaction Force Z
## =============================================================================
# plot... | Python | 1 |
// swap edge and next
unsafe { edge.as_mut() }.next = next.next;
next.next = Some(edge);
unsafe { (*prev) = Some(next_ptr) };
swapped = true;
}
prev = (&mut unsafe { edge.as_mut() }.next) as... | Rust | 0 |
,
Debug,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
::prost::Enumeration,
Serialize,
Deserialize,
)]
#[repr(i32)]
pub enum ExternEnumeration {
Unknown = 0,
}
pub mod test {
pub mod syntax3 {
include!(concat!(env!("OUT_DIR"), "/test.syntax3.rs"));
include!(concat!(... | Rust | 0 |
a8,
MODULUS.0[0],
MODULUS.0[1],
MODULUS.0[2],
MODULUS.0[3],
0,
)
}
/// Montgomery Reduction
///
/// For secp256k1, all of the limbs of p (except the first!) are 2^64 -1.
/// Thus, all multiplications by this limb can be ... | Rust | 0 |
OwnedAllWith5::new(label,t1,t2,t3,t4,t5,f).into()
}
}
// =================================================================================================
// === Nodes Definitions ===========================================================================
// ======================================================... | Rust | 0 |
distance(Wrapping(u32::MAX) + Wrapping(5), u32::MAX),
5
);
assert_eq!(shortest_arc_distance(0, u32::MAX), 1);
assert_eq!(
shortest_arc_distance(0, MAX_HALF_LENGTH),
MAX_HALF_LENGTH - 2
);
}
#[test]
fn test_dht_arc() {
assert!(!DhtA... | Rust | 0 |
) in CHANNEL_MASKS.iter().enumerate() {
let channel_count = mask_idx + 1;
for sample_rate in &SAMPLE_RATES {
let buffer_size = buffer_size_range_for_params(
is_output,
*sample_rate,
*channel_mask,
and... | Rust | 0 |
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 b... | Python | 1 |
import requests
import time
# Function to generate a path from start to end point using OSRM API
def generate_path(start_coords, end_coords):
try:
base_url = "http://router.project-osrm.org/route/v1/walking/"
coordinates = f"{start_coords[1]},{start_coords[0]};{end_coords[1]},{end_coords[0]}"
... | Python | 1 |
black_locations[selection] = click_coords
if click_coords in white_locations:
white_piece = white_locations.index(click_coords)
captured_pieces_black.append(white_pieces[white_piece])
if white_pieces[white_piec... | Python | 1 |
. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use fuchsia_zircon::system_get_page_size;
/// Returns the starting address of the page that contains this address. For example, if page size
/// is 0x1000, page_start(0x3001) == page_start(0x... | Rust | 0 |
# kiểm tra xem các từ trong 1 chuỗi đó có tồn tại trong từ điển không.
# Nếu có, thay thế bằng giá trị (value) tương ứng từ từ điển,
# nếu không thì giữ nguyên. (Tham số là 1 chuỗi & 1 dict)
# đầu vào
# Gồm ba dòng:
# Dòng đầu tiên chứa chuỗi cần thay thế.
# Dòng thứ hai chứa các phần tử của danh ... | Python | 1 |
# Printing the revese word without reversing sentences
Value = input('Enter the string: ')
def Reverse_word(value):
value = value.split()
res =[]
for val in value:
word =''
for i in range(-1,-len(val)-1,-1):
word +=val[i]
res.append(word)
print(' '.join(res))
Reverse... | Python | 1 |
lightning.into()
}
// =================
// === Favorites ===
// =================
/// A five-pointed star.
mod star {
use super::*;
ensogl::define_shape_system! {
(style:Style) {
let shape = FiveStar(7.0.px(),0.447);
let shape = shape.fill(style.get_color(theme::favorites... | Rust | 0 |
)
# As should directory execution in isolated mode
p = spawn_python("-I", script_dir, cwd=work_dir)
out_by_dir_isolated = kill_python(p).decode().splitlines()
self.assertEqual(out_by_dir_isolated, out_by_dir, out_by_name)
def test_consistent_sys_path_for_module_execu... | Python | 1 |
() -> (
DriverFactory,
ConsensusNotifier,
MempoolNotificationListener,
ReconfigNotificationListener,
) {
let mut node_config = NodeConfig::default();
node_config.base.role = RoleType::Validator;
create_driver_for_tests(node_config, Waypoint::default())
}
/// Creates a state sync driver for... | Rust | 0 |
proposal], &[kpb_option.unwrap()])
.expect("Alice: Could not apply Commit");
// Alice sends a message with a sender that points to a blank leaf
// Expected result: MLSCiphertextError::UnknownSender
let content = MLSPlaintextContentType::Application(vec![1, 2, 3]);
let bogus... | Rust | 0 |
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
class PointProgressionSection:
def __init__(self, teams_df, standings_df):
self.teams_df = teams_df
self.standings_df = standings_df
def calculate_points(self):
team_forms = [[], [], [], [], []]
forms = [self.teams_df.iloc[i, 1] f... | Python | 1 |
;
let mut ty = TileType::MANZU;
for (t, _) in counts {
// 字牌の出現は不可
if t.is_jihai() {
return false;
}
if t.is_suhai() {
// 最初に確認した種類を記録
if ntypes == 0 {
ntypes += 1;
ty = t.gettype();
}
... | Rust | 0 |
data into torch tensors, split training into training and validation and set up a collator that
# is able to arrange single data samples into batches.
train_dataset_tokenized, validate_dataset_tokenized, eval_dataset_tokenized = preprocess_data(train_dataset, eval_dataset, tokenizer, training_args)
colla... | Python | 1 |
wi.z)
wo_ = mi.Vector3f(wo.x * dr.cos(m_angle) - wo.y * dr.sin(m_angle),
wo.x * dr.sin(m_angle) + wo.y * dr.cos(m_angle),
wo.z)
si.wi = wi_
s_r = dr.select(dr.dot(wo, si.n) > 0.0, self.khungurn.eval(ctx, si, wo_, active), 0.0)
... | Python | 1 |
e="key4"
value4
---123--
"""
environ = {
'CONTENT_LENGTH': str(len(data)),
'CONTENT_TYPE': 'multipart/form-data; boundary=-123',
'QUERY_STRING': 'key1=value1&key2=value2x',
'REQUEST_METHOD': 'POST',
}
assert gen_result(data, environ) == _qs_result
def test_qs_a... | Python | 1 |
::B8G8R8A8UIntNormalized,
true,
true,
&window.handle(),
)
.await?;
// Map the texture and check the image
{
let mapped = MappedTexture::new(&frame)?;
check_color(
mapped.read_pixel(width / 2, height / 2).unwrap(),
common_colors::GREEN,
... | Rust | 0 |
]
pub efusecfg: EFUSECFG,
#[doc = "0x1014 - Internal. Only to be used through TI provided API."]
pub efusestat: EFUSESTAT,
#[doc = "0x1018 - Internal. Only to be used through TI provided API."]
pub acc: ACC,
#[doc = "0x101c - Internal. Only to be used through TI provided API."]
pub boundary:... | Rust | 0 |
let module = model::module::test::plain_from_code("");
let id = Uuid::new_v4();
let initial_md = module.node_metadata(id);
assert!(initial_md.is_err());
let md_to_set = NodeMetadata { position: Some(Position::new(1.0, 2.0)), ..default() };
module.set_node_metadata(id, ... | Rust | 0 |
_globals)] pub const EDGE_FLAG_ARRAY_POINTER: types::GLenum = 0x8093;
#[allow(dead_code, non_upper_case_globals)] pub const EDGE_FLAG_ARRAY_STRIDE: types::GLenum = 0x808C;
#[allow(dead_code, non_upper_case_globals)] pub const ELEMENT_ARRAY_BUFFER: types::GLenum = 0x8893;
#[allow(dead_code, non_upper_case_globals)] pub ... | Rust | 0 |
mute(a)));
let e = 10_u32;
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vaddvq_s8() {
let a = i8x16::new(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, -16);
let r: i8 = transmute(vaddvq_s8(transmute(a)));
let e = 104_i8;
assert_eq!(r, ... | Rust | 0 |
# src/LexaLCM/Utils/InspectEmbeddings.py
def inspect_embeddings(batch_embeds, decoder, num_batches=2, num_seqs=8):
# Ensure batch_embeds is [B, T, 1024]
if batch_embeds.ndim == 2:
batch_embeds = batch_embeds.unsqueeze(1)
elif batch_embeds.ndim == 4:
batch_embeds = batch_embeds.squeeze(1)
... | Python | 1 |
mory[i];
}
vm_result?;
let res = res.ok_or(AoCError::IncorrectInput(
"program did not produce an output",
))?;
Ok(res == 1)
}
fn pt1(memory: Vec<Value>) -> Result<usize> {
let mut vm = VM::new(GrowingMemory(memory.clone()));
(0..50)
.flat_map(|x| (0..50).map(mo... | Rust | 0 |
]
pub struct ParseErrorAndPos {
pub pos: Position,
pub error: ParseError,
}
impl ParseErrorAndPos {
pub fn new(pos: Position, error: ParseError) -> ParseErrorAndPos {
ParseErrorAndPos { pos, error }
}
}
// livesplit lss file parsing will go here
use crate::run::Run;
use quick_xml::{Reader, even... | Rust | 0 |
0, K: 0, F: 0, P: 0,
};
for c in input.chars() {
counts.inc(c, 1);
}
return counts;
}
fn part_two(data: Vec<csv::StringRecord>) -> Result<String, Box<dyn Error>> {
let rules_1 = get_basic_insertion_rules(data);
let pairs = get_pairs(String::from(STARTING_POLYMER));
let rules_5 =... | Rust | 0 |
er.layout,
remaining_uniforms: shader.uniforms,
vertex_count: TLNone,
_phantom: PhantomData
}
}
}
impl<'a: 'b, 'b> RenderCommand<'a, 'b, vertex::layout::Nil, shader::uniform::Nil, TLSome<i32>> {
pub fn execute(&self, to: &mut Surface) {
unsafe {
t... | Rust | 0 |
static!(H5T_NATIVE_INT32, H5T_NATIVE_INT32_g);
extern_static!(H5T_NATIVE_UINT32, H5T_NATIVE_UINT32_g);
extern_static!(H5T_NATIVE_INT_LEAST32, H5T_NATIVE_INT_LEAST32_g);
extern_static!(H5T_NATIVE_UINT_LEAST32, H5T_NATIVE_UINT_LEAST32_g);
extern_static!(H5T_NATIVE_INT_FAST32, H5T_NATIVE_INT_FAST32_g);
... | Rust | 0 |
]
return ResNet(block,blocks_config,first_config,first_pool=True)
def Resnet18CIFAR():
backbone = resnet18()
backbone.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
backbone.maxpool = nn.Identity()
backbone.fc = nn.Identity()
return backbone
def Resnet18STL10():
... | Python | 1 |
2_TCTI_SET_LOCALITY_FCN,
}
#[test]
fn bindgen_test_layout_TSS2_TCTI_CONTEXT_COMMON_V1() {
assert_eq!(
::std::mem::size_of::<TSS2_TCTI_CONTEXT_COMMON_V1>(),
64usize,
concat!("Size of: ", stringify!(TSS2_TCTI_CONTEXT_COMMON_V1))
);
assert_eq!(
::std::mem::align_of::<TSS2_TCTI_C... | Rust | 0 |
et iter2 = poisson2.iter();
let iter3 = poisson3.iter();
let iter4 = poisson4.iter();
assert_eq!(iter0.grid.len(), 1);
assert_eq!(
iter1.grid.len(),
(n as Float / iter1.cell_size).ceil() as usize
);
assert_eq!(
iter2.grid.len(),
... | Rust | 0 |
ss and length must be page-aligned. Shim must validate
/// and acknowledge the changes with ENCLU[EACCEPT], in order for them to
/// take effect.
pub struct TrimSgxPages {
pub addr: NonNull<c_void>,
pub length: usize,
}
impl PassthroughAlloc for TrimSgxPages {
const NUM: Number = Number::TrimSgxPages;
... | Rust | 0 |
def rearrange_1(tensor):
B, C, F, H, W = tensor.size()
return torch.reshape(torch.permute(tensor, (0, 2, 1, 3, 4)), (B * F, C,
H, W))
| Python | 1 |
r"""Shift in linear model."""
import numpy as np
from . import pw_constant
def pw_linear(n_samples=200, n_features=1, n_bkps=3, noise_std=None, seed=None):
"""Return piecewise linear signal and the associated changepoints.
Args:
n_samples (int, optional): signal length
n_features (int, optio... | Python | 1 |
/// Return size in bytes.
pub fn as_bytes(&self) -> usize {
return match *self {
Bytes::KiloBytes(e) => e * 1024,
Bytes::MegaBytes(e) => e * 1024 * 1024,
Bytes::GigaBytes(e) => e * 1024 * 1024 * 1024,
};
}
// Return as size in ... | Rust | 0 |
))
.and_then(move |mut v: Vec<_>| {
if v.is_empty() {
return Err(Error::unexpected_message(
"error_page directive must not be empty"));
}
let uri = v.pop().unwrap();
let response_code = if v.last().is_some() && is_eq(v.last().unwrap())? {
let ... | Rust | 0 |
_cmd()
.arg("mutants")
.arg("-d")
.arg(&tmp_src_dir.path())
.assert()
.code(2)
.stderr("")
.stdout(predicate::str::is_match(output_re).unwrap());
// Some log files should have been created
let log_dir = tmp_src_dir.path().join("mutants.out/log");
asse... | Rust | 0 |
"]
pub static mut example_check_no_collision: *const ::std::os::raw::c_int;
}
// Copyright 2021 <NAME>.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the
// MIT license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. Thi... | Rust | 0 |
optimize(&plan)?;
assert!(
format!("{:?}", plan).starts_with("Selection: CAST(#c7 AS Float64) Lt #c12")
);
Ok(())
}
#[test]
fn test_add_i32_i64() {
binary_cast_test(
DataType::Int32,
DataType::Int64,
"CAST(#c0 AS Int64) Plus ... | Rust | 0 |
, FnKind, Visitor};
use crate::sess::ParseSess;
use crate::symbol::{Symbol, sym};
use errors::{Applicability, DiagnosticBuilder, Handler};
use rustc_data_structures::fx::FxHashMap;
use syntax_pos::{Span, DUMMY_SP, MultiSpan};
use log::debug;
use rustc_error_codes::*;
macro_rules! gate_feature_fn {
($cx: expr, $h... | Rust | 0 |
import logging
from freqtrade.exchange import Exchange
from freqtrade.exchange.exchange_types import FtHas
logger = logging.getLogger(__name__)
class Hitbtc(Exchange):
"""
Hitbtc exchange class. Contains adjustments needed for Freqtrade to work
with this exchange.
Please note that this exchange is... | Python | 1 |
render(event_handle) {
Ok(xml_event) => {
user_context.handle_record(
xml_event
);
},
Err(e) => {
error!("Error calling evt_render(): {:?}", e);
}
}
// Close the EVT_HANDLE
unsafe {
EvtClose(event_handle);
}
... | Rust | 0 |
from abc import ABC, abstractmethod
from langchain_text_splitters import RecursiveCharacterTextSplitter
from core.logger import setup_logger
logger = setup_logger('chunk_and_generate', 'log/chunk_and_generate.log')
class ChunkandGenerate(ABC):
def __init__(self):
self.splitter = RecursiveCharacterTextSpli... | Python | 1 |
) -> SpecialForm
= "recur" __ f:form() ** __ _ { SpecialForm::Recur(f) }
rule throw_form() -> SpecialForm
= "throw" __ f:form() { SpecialForm::Throw(f) }
rule try_form() -> SpecialForm
= "try" __ { SpecialForm::Try }
rule binding_form_form() -> (BindingForm,Form)
= b:bindi... | Rust | 0 |
b));
}
let _ = names.insert(record_id, decode_iso_8859(&record_data[14..35])?);
let _ = metadata.insert(record_id, u32::out_of(&record_data[35..], Endian::Little)?.into());
},
// another part of a linked list with a table refere... | Rust | 0 |
# =========================================
# =============== 按行预处理 ===============
# =========================================
from math import atan2, cos, sin, sqrt, pi, radians, degrees
from statistics import median # 中位数
angle_threshold = 3 # 进行一些操作的最小角度阈值
angle_threshold_rad = radians(angle_threshold)
# 计算两点... | Python | 1 |
None);
let mut txn = DbTransaction::new();
txn.insert_utxo(utxo1.clone());
txn.insert_utxo(utxo2.clone());
txn.insert_utxo(utxo3.clone());
assert!(store.commit(txn).is_ok());
let root = store.fetch_mmr_only_root(MmrTree::Utxo).unwrap();
let proof1 = store.fetch_mmr_proof(MmrTree::Utxo, 1).u... | Rust | 0 |
meu_set = {'Infinity', ' School'}
print(type(meu_set))
print(meu_set)
frutas = {'Maçã', 'Banana', 'Cereja', 'Maçã', 'maçã'}
print(frutas)
set1 = {'Infinity', 'School', '2025'}
print(set1)
set1 = {letra for letra in 'infinity' if letra not in 'aeiou'}
print(set1)
convidados = {'Jeff', 'Rod', 'Ferr'}
print(convidados)
co... | Python | 1 |
borrow().contains(&(ptr as *const ())))
}
<filename>gio/src/win32_output_stream.rs<gh_stars>0
// Take a look at the license at the top of the repository in the LICENSE file.
use crate::OutputStream;
use glib::object::{Cast, IsA};
use glib::translate::*;
use std::fmt;
use std::os::windows::io::{AsRawHandle, FromRawHan... | Rust | 0 |
import pygame
import pygame_gui
from data.settings import *
from source.helping_scripts.load_sounds import off_all_game_music
# ---------------------------------------------------------------------------------------------------------------------
# КЛАСС, КОТОРЫЙ ОТВЕЧАЕТ ЗА ТЕ ИЛИ ИНЫЕ ЭЛЕМЕНТЫ ГРАФИЧЕСКОГО ИНТЕРФЕ... | Python | 1 |
>::config().clone();
config.estimate = true;
Some(config)
} else {
None
};
<Runtime as pallet_evm::Config>::Runner::create(
from,
data,
value,
gas_limit.low_u64(),
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
access_list.unwrap_or_default(),
config.as_ref()... | Rust | 0 |
56_set_epi32(-1, -1, -1, 0x0F0B0703, -1, -1, -1, 0x0F0B0703);
let mut arr = [AlignedArray{v: _mm256_undefined_si256()}, AlignedArray{v: _mm256_undefined_si256()}];
for i in 0..end_idx as isize {
let v = _mm256_loadu_si256(ptr.offset(i));
// mask out unimportant bits
... | Rust | 0 |
import csv
import sqlite3
from datetime import datetime
date_now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
conn = sqlite3.connect("Kotoba.db")
cursor = conn.cursor()
if input() == "y":
cursor.execute("DROP TABLE IF EXISTS Decks;")
cursor.execute("DROP TABLE IF EXISTS Cards;")
cursor.execute(
... | Python | 1 |
# ---------------------------------------------------------------------
# Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# ---------------------------------------------------------------------
import requests
from openai import OpenAI
from PIL import Im... | Python | 1 |
[doc = "Bits 20:23"]
#[inline]
pub fn sys_regu_ldo25m_adj(&self) -> SYS_REGU_LDO25M_ADJR {
let bits = {
const MASK: u8 = 15;
const OFFSET: u8 = 20;
((self.bits >> OFFSET) & MASK as u32) as u8
};
SYS_REGU_LDO25M_ADJR { bits }
}
#[doc = "Bit 19"]... | Rust | 0 |
;
mod client;
pub mod error;
mod pusher;
mod server;
mod socket;
extern crate bit_matrix;
use bit_matrix::BitMatrix;
#[test]
fn test_transitive_closure() {
let mut matrix = BitMatrix::new(4, 4);
let points = &[
(0, 0),
(0, 1),
(0, 3),
(1, 0),
(1, 2),
(2, 0),
... | Rust | 0 |
.data[1] = 255;
px4.data[2] = 255;
} else if sat > 32.0 {
px1.data[0] = 0;
px1.data[1] = 0;
px1.data[2] = 0;
px2.data[0] = 255;
px2.data[0] = 255;
px2.data[0] = 255;
px3.data[0] ... | Rust | 0 |
, 2, 3, 4, 5, 6), matrix![1; 2; 3; 4; 5; 6]);
}
#[test]
fn vector_from_array() {
type V<const M: usize> = Vector<i64, M>;
assert_eq!(V::from([1]), matrix![1]);
assert_eq!(V::from([1, 2]), matrix![1; 2]);
assert_eq!(V::from([1, 2, 3]), matrix![1; 2; 3]);
assert_eq!(V::from([1, 2, 3, 4]), matrix![1; ... | Rust | 0 |
static,
) -> TaskHandle {
let (tx, rx) = oneshot::channel();
self.spawn(name, async move {
task.await;
let _ = tx.send(());
});
Box::pin(rx.map_err(|_| ()))
}
}
#[derive(PartialEq, Eq, Clone, Debug, Hash)]
pub struct HashNum<H, N> {
hash: H,
num: ... | Rust | 0 |
percdamp=args.percdamp,
groupsize=layer_w_groupsize,
actorder=args.act_order,
static_groups=False,
export_to_et=args.export_to_et,
)
quantizers["model.layers.%d.%s" % (i, name)] = gptq[name]... | Python | 1 |
reg = n1
else:
# Don't chose any conflicting spots
for n2 in get_conflicts(n1):
# If n2 is a physical spot
if n2 in regs:
regs.remove(n2)
if n2 in spotmap and spotmap[n2] in reg... | Python | 1 |
#
# Copyright (C) 2010-2017 Samuel Abels
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy,... | Python | 1 |
GandaraTheMoonFortress = [
{
"bless": (6818.0, 15641.0),
"path": [
(5425.0, 16446.0),
(3246.0, 13158.0),
(-2989.0, 14295.0),
(-4304.0, 11465.0),
(-1938.0, 11165.0),
(-2396.0, 14301.0),
(-6098.0, 15735.0),
]
... | Python | 1 |
tText("1080p Full HD (1920×1080)")
except Exception:
# Fallback to 1080p if settings not available
self.resolution_combo.setCurrentText("1080p Full HD (1920×1080)")
def browse_file(self):
from chimerax.ui.open_save import SaveDialog
save_dialog = SaveDialog(self.sess... | Python | 1 |
}
impl<'b> flatbuffers::Push for &'b Position {
type Output = Position;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
let src = unsafe {
::std::slice::from_raw_parts(*self as *const Position as *const u8, Self::size())
};
d... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.