text string | label_name string | labels int64 |
|---|---|---|
=interpolator.w_ylo_xlo[:, None], # pyre-ignore[16]
w_ylo_xhi=interpolator.w_ylo_xhi[:, None], # pyre-ignore[16]
w_yhi_xlo=interpolator.w_yhi_xlo[:, None], # pyre-ignore[16]
w_yhi_xhi=interpolator.w_yhi_xhi[:, None], # pyre-ignore[16]
)[interpolator.j_valid, :]
re... | Python | 1 |
que tienes."""
economia = cargar_economia()
user_id = str(ctx.author.id)
monedas = economia.get(user_id, {}).get("coins", 0)
await ctx.send(f"💰 {ctx.author.mention} tienes **{monedas}** monedas, miarma.")
@commands.command(name="tienda")
async def tienda(self, ctx):
""... | Python | 1 |
), and_(var!("f"), var!("g")))),
and_(var!("a"), and_(var!("d"), and_(var!("f"), var!("h")))),
),
),
),
or_(
or_(
or_(
and_(var!("b"), and_(var!("c"), and_(var!("e"), var!("g")... | Rust | 0 |
1 HOUR1:MIN1:SEC1) -
* (YEAR0-YDAY0 HOUR0:MIN0:SEC0) in seconds.
*/
// FIXME: Optimize way to calculate intervening leap days
let mut intervening_leap_days: uint = 0;
let mut y: uint = year1;
while (y > year0) {
if is_leap_year(y) {intervening_leap_days += 1;}... | Rust | 0 |
# Copyright 2021 The Google Earth Engine Community Authors
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | Python | 1 |
z2_exact(a: Vec3, b: Vec3, c: Vec3, d: Vec3) -> Float {
const PREC: u32 = f64::MANTISSA_DIGITS * 2 + 2 + f64::MANTISSA_DIGITS * 2 + 4;
macro_rules! f {
($expr:expr) => {
Float::with_val(PREC, $expr)
};
}
let ax = f!(a.x);
let ay = f!(a.y);... | Rust | 0 |
def main():
_ = int(input())
for t in range(_):
m ,s = map(int ,input().split())
a = list(map(int ,input().split()))
array = [False ] *1050
max =a[0]
continued =True
for l in a:
if l> max:
max = l
if array[l] == True:
... | Python | 1 |
use std::os::unix::io::{FromRawFd};
use std::fs;
use std::io::{Read, Write};
// use std::fmt::Write as FmtWrite;
use std::path::Path;
use std::{thread, time};
use std::str;
use super::*;
static MODULENAME: &str = "writercstrptr";
const WRITERCSTRPTRFDBASE:i32 = 300;
pub str... | Rust | 0 |
0x07) as u8)
}
#[doc = "Bits 21:23 - Channel 17 sampling time selection"]
#[inline(always)]
pub fn smp17(&self) -> SMP17_R {
SMP17_R::new(((self.bits >> 21) & 0x07) as u8)
}
#[doc = "Bits 18:20 - Channel 16 sampling time selection"]
#[inline(always)]
pub fn smp16(&self) -> SMP16_... | Rust | 0 |
evel {}: ", current_level - 1));
let (finished_nodes_sender, finished_nodes_receiver) = mpsc::channel();
let (progress_tx, progress_rx) = mpsc::channel();
pool.scoped(|scope| {
scope.execute(|| {
for (id, num_points) in finished_nodes_receiver {
i... | Rust | 0 |
Field("a"),
}
test_duplicate_field_enum<Enum> {
&[
Token::EnumMapStart("Enum", "Map", 3),
Token::EnumMapSep,
Token::Str("a"),
Token::I32(1),
Token::EnumMapSep,
Token::Str("a"),
],
Error::Duplicat... | Rust | 0 |
let mut map1 = BTreeMap::new();
map1.insert(2, ());
map1.insert(3, ());
map1.insert(4, ());
map1.insert(5, ());
let mut map2 = BTreeMap::new();
map2.insert(2, ());
map2.insert(3, ());
map2.insert(4, ());
let mut map3 = BTreeMap::new();
map3.insert(1, ());
map3.insert(2, ());
... | Rust | 0 |
RenderTemplateError> {
// Process the template using the specified template processor.
let text = TP::process(text, values).map_err(RenderTemplateError::from_string)?;
Ok(text)
}
pub fn generate_template<TP: TemplateProcessor>(
template_path: &Path,
output_file_path: &Path,
values: &TemplateI... | Rust | 0 |
e408e0300388ac62070d0095070d000000000000000000000000").expect("Block bytes are in valid hex representation");
}
#[test]
fn verify_valid_script_parsed() -> Result<()> {
zebra_test::init();
let transaction =
SCRIPT_TX.zcash_deserialize_into::<Arc<zebra_chain::transaction::Transac... | Rust | 0 |
und in the LICENSE file.
use {
fidl::encoding::Decodable,
fidl_fuchsia_fonts::{
self as fonts, CacheMissPolicy, FallbackGroup, FamilyName, FontFamilyInfo,
GenericFontFamily, Style2, TypefaceQuery, TypefaceRequest, TypefaceRequestFlags,
TypefaceResponse, Width,
},
fidl_fuchsia_in... | Rust | 0 |
idx][j_idx] == 1: # substitute
i -= 1
j -= 1
rst["sub"] += 1
if i < 0 and j >= 0:
rst["del"] += 1
elif j < 0 and i >= 0:
rst["ins"] += 1
match_idx.reverse()
wrong_cnt = cost_matrix[len_hyp][len_ref]
rst["wrong"] = wrong_cnt
... | Python | 1 |
Error;
fn try_from(value: String) -> Result<Self, Self::Error> {
git_validate::refname(value.as_bytes().as_bstr())?;
Ok(FullName(value.into()))
}
}
impl TryFrom<&BStr> for FullName {
type Error = git_validate::refname::Error;
fn try_from(value: &BStr) -> Result<Self, Self::Error> {
... | Rust | 0 |
d)
checkpoint_callback = ModelCheckpoint(
monitor='val_acc',
mode='max',
filename='{val_acc:.4f}',
save_top_k=1,
verbose=True)
train_dataset = BotDataset(name="train")
valid_dataset = BotDataset(name="valid")
test_dataset = BotDataset(name="test")
t... | Python | 1 |
f"expecting {cls.ALGORITHM}."
)
payload = jwt_lib.decode(
jwt,
key,
algorithms=[cls.ALGORITHM],
options={
"verify_signature": verify,
"verify_exp": True,
"verify_... | Python | 1 |
///
/// # Examples
///
/// Quick plot.
/// ```no_run
/// use preexplorer::prelude::*;
/// pre::Density::new((0..10)).plot("my_identifier").unwrap();
/// ```
///
/// Compare [Density] structs.
/// ```no_run
/// use preexplorer::prelude::*;
/// pre::Densities::new(vec![
/// pre::Density::new((0..10)),
/// pre::De... | Rust | 0 |
oad(Ordering::SeqCst)).dealloc();
}
}
}
unsafe impl Send for ResizableHistogram {}
unsafe impl Sync for ResizableHistogram {}
impl ResizableHistogram {
pub fn new(significant_value_digits: u8) -> Result<ResizableHistogram, CreationError> {
ResizableHistogram::with_sigvdig(significant_value_dig... | Rust | 0 |
fields=["name", "employee"]
)
if not advances:
frappe.throw(_("No Employee Advances found linked to Bulk Employee Advance: {0}").format(doc_name))
advance_map = {advance["employee"]: advance for advance in advances}
created_advances = []
for row in bulk.employee_d... | Python | 1 |
Coord { x: 5, y: 1 },
Coord { x: 6, y: 1 },
Coord { x: 5, y: 2 },
Coord { x: 6, y: 2 },
],
color: Cell::Color1,
};
let s_block = BlockTemplate {
starting_coords: [
Coord { x: 5, y: 2 },
Coord { x: 4, y: 2 },
Coord { x: 5, y: 1 },
... | Rust | 0 |
import os
from plugin import plugin, require
voice_control_installed = True
try:
import speech_recognition as sr
import pyaudio
except ImportError:
voice_control_installed = False
if voice_control_installed:
requirements = []
else:
requirements = [
'voice_control_requirements (install port... | Python | 1 |
linear_time_of_impact_composite_shape_shape(
motion2,
g2,
motion1,
g1,
max_toi,
target_distance,
)
}
struct CompositeShapeAgainstAnyNonlinearTOIVisitor<
'a,
N: 'a + RealField,
G1: ?Sized + 'a,
M1: ?Sized,
M2: ?Sized,
> {
sphere2: BoundingSpher... | Rust | 0 |
er_top_radius = top_radius - filter_gap
filter_bottom_radius = bottom_radius + filter_gap # 底部濾紙略大於出水孔
# 繪製濾紙錐形輪廓(虛線)
x_left_top = center_x - filter_top_radius
x_right_top = center_x + filter_top_radius
x_left_bottom = cen... | Python | 1 |
id,
create_at: create_at,
deadline: deadline,
todo: todo,
priority: priority,
})
}
fn load() -> Vec<Mytodo> {
let file = File::open("/tmp/testfile")
.ok()
.expect("failed to open file");
let todovec: Vec<Mytodo> = serde_json::from_reader(&file)
.ok()
... | Rust | 0 |
_container_runtime(node: &api::Node) -> Option<CellSpec<'_>> {
node.status.as_ref().and_then(|stat| {
stat.node_info
.as_ref()
.map(|info| info.container_runtime_version.as_str().into())
})
}
fn get_node_addr<'a>(node: &'a api::Node, type_: &str) -> Option<CellSpec<'a>> {
no... | Rust | 0 |
_bezier_to(
vector(-1.24, 1.188),
vector(-3.207, 1.142),
vector(-4.394, -0.102),
);
path.cubic_bezier_to(
point(67.418, 31.941),
point(67.463, 29.972),
point(68.705, 28.784),
);
path.close();
path.move_to(point(105.085, 58.061));
path.relative_cub... | Rust | 0 |
import tensorflow as tf
_FLOATX = 'float32'
_EPSILON = 10e-8
def cross_entropy_and_exponential_loss_with_logits(logits, labels):
"""Class dependent loss.
Using cross entropy for P and absolute difference for U.
"""
loss_pos = tf.nn.softmax_cross_entropy_with_logits(
logits=logits,
l... | Python | 1 |
.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
self._rotate_image_hue()
def on_ok(self, e=None):
'''Do 'Okay' on the dialog.'''
self.EndModal(wx.ID_OK)
def on_timer(self, event):
'''wx.EVT_TIMER handler.'''
self._rotate_image_hue()
... | Python | 1 |
eprecated_202101_create_recurring_application_charges(
&self,
body: &serde_json::Value,
) -> Result<()> {
let url = "/admin/api/2021-01/recurring_application_charges.json".to_string();
self.client
.post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?)))
... | Rust | 0 |
or::EvalError(EvalError::Other(format!("IO error: {}", io_err), None))
})
}
macro_rules! assert_json_eq {
( $term:expr, $result:expr ) => {
assert_eq!(
serde_json::to_string(&mk_program($term).and_then(|mut p| p.eval_full()).unwrap())
.unwrap(),
... | Rust | 0 |
inalTransactionQualifiers> for Vec<u8> {
fn from(ttq: TerminalTransactionQualifiers) -> Self {
// EMV Contactless Book A, Table 5-4: Terminal Transaction Qualifier (TTQ)
let mut b1 : u8 = 0b0000_0000;
let mut b2 : u8 = 0b0000_0000;
let mut b3 : u8 = 0b0000_0000;
let b4 : ... | Rust | 0 |
"""
Provide HTTP proxy support for Python's xmlrpclib, via urllib2.
For example:
>>> transport = HTTPProxyTransport({
... 'http': 'http://myproxyserver',
... })
>>> server = xmlrpclib.Server('http://blogsearch.google.com/ping/RPC2',
... transport=transport)
>>... | Python | 1 |
import vcfpy
import os
from tqdm import tqdm
from copy import deepcopy as copy
import cyvcf2
from itertools import islice
def parse_HAPT_to_genome_strings(input_vcf_file):
print("loading HAPT file")
with open(input_vcf_file) as f:
data = f.readlines()
data = [d.strip().split(" ")[2:] for d in data]... | Python | 1 |
message,
target,
module,
file,
line,
}
}
}
macro_rules! log_cs {
($level:expr) => {{
struct Callsite;
static CALLSITE: Callsite = Callsite;
static META: Metadata<'static> = Metadata::new(
"log event",
"log... | Rust | 0 |
) }
#[inline(always)]
fn to_u32(&self) -> u32 { self.0 as u32}
}
impl Add for CharPos {
type Output = CharPos;
#[inline(always)]
fn add(self, rhs: CharPos) -> CharPos {
CharPos(self.to_usize() + rhs.to_usize())
}
}
impl Sub for CharPos {
type Output = CharPos;
#[inline(alway... | Rust | 0 |
+ BlockchainEvents<Block>
+ CallApiAt<Block> + Send + Sync + 'static,
C::Api: VendorApi<Block>,
Block::Hash: Into<sp_core::H256>
{
pub fn new(client:Arc<C>,tx_pool:Arc<A> /*,key:KeyStorePtr*/
,ed_key:edPair,packet_nonce:Arc<Mutex<PacketNonce<Block>>>) -> Self{
TxSender{
client:client,
tx_pool:tx_po... | Rust | 0 |
background-color: #313244;
border-radius: 4px;
border: 1px solid #a6e3a1;
}
""")
self.onlinefix_detail_label.setText("OnlineFix工具包已安装完成")
# 延迟一点时间确保文件系统同步,然后重新检查状态
from... | Python | 1 |
with storebuilder.build(contentstore=None) as (__, store):
course_key = store.make_course_key("org", "course", "run")
asset_key = course_key.make_asset_key('asset', 'foo.jpg')
assert store.find_asset_metadata(asset_key) is None
assert store.get_all_asset_metadata(cour... | Python | 1 |
import logging
import sys
import time
from ai import get_image_dalle, get_image_recraft, get_image_prompt
from epaper import EPaperDisplay
logging.basicConfig(level=logging.INFO)
def main():
if len(sys.argv) < 2 or sys.argv[1] not in ("show", "clear"):
print("Usage: python control.py <command> [locatio... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrEmployeePublic(models.Model):
_inherit = 'hr.employee.public'
# These are required for manual attendance
attendance_state = fields.Selection(related='employee_id.atte... | Python | 1 |
import os
import wx
basedir = os.path.dirname(__file__)
try:
from ctypes import windll # Only exists on Windows.
myappid = "mycompany.myproduct.subproduct.version"
windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
except ImportError:
pass
class MainWindow(wx.Frame):
def __init__(... | Python | 1 |
?.path().join("db");
Ok(FASTQStorage {
db: DB::open_default(storage_dir.clone())?,
storage_dir,
})
}
fn as_key<'a>(i: u64) -> [u8; 8] {
unsafe { mem::transmute::<u64, [u8; 8]>(i) }
}
/// Enter a (read index, read sequence) pair into the database.
pub... | Rust | 0 |
ort re
sentences = re.split(r'[.!?。!?]', paragraph)
chunks = []
current_chunk = ""
for sentence in sentences:
sentence = sentence.strip()
if not sentence:
continue
... | Python | 1 |
r::new().push_mono(status).build(),
true,
);
match rev {
Rev::Branch(branch) => {
if let Some(version) = version {
e.field(
"Commit",
MessageBuilder::new().push_mono(version).build(),
true,
);... | Rust | 0 |
from parser import InternLMReActParser, ReActParser
from models import LLM, Qwen, QwenDashscopeVLModel, QwenVL
from prompt import InternLMReAct, LlamaReAct, QwenReAct
react_prompt_map = {
'qwen': QwenReAct,
'llama': LlamaReAct,
'internlm': InternLMReAct,
}
react_parser_map = {
'qwen': ReActParser,
... | Python | 1 |
panic!("could not symlink to libcrypto.a: {}", err)
}
}
println!("cargo:rustc-link-search=native={}/crypto", abs_build_dir_2);
}
fn validate_dependencies() {
let go = have_go();
let cmake = have_cmake();
let ninja = have_ninja();
let make = have_make();
if !go {
... | Rust | 0 |
lib.rs","mismatches":[{"original_begin_line":1,"original_end_line":1,"expected_begin_line":1,"expected_end_line":1,"original":" pub mod config;","expected":"pub mod config;"}]}]"#;
let path = get_absolute_file_path("cargo-scout/cargo-scout-lib/src/lib.rs")?;
let expected_lints = vec![Lint {
... | Rust | 0 |
.await
.unwrap();
tx.send(Ok(Output {
items: vec![4, 5, 6],
}))
.await
.unwrap();
})
});
assert_eq!(
TryFlatMap(stream)
.flat_map(|output| output.items.into_iter())... | Rust | 0 |
plerates are {:?}", samplerate, samplerates);
}
}
pub fn set_bias_tee(&self, onoff: bool) -> Result<(), AirspyError> {
let c_onoff = match onoff {
true => 1,
false => 0,
};
match unsafe {ffiairspy::airspy_set_rf_bias(self.device, c_onoff)} {
... | Rust | 0 |
"cirfnint" => "⨐",
"clubsuit" => "♣",
"curlyvee" => "⋎",
"diagdown" => "╲",
"diameter" => "⌀",
"dotequiv" => "⩧",
"dotminus" => "∸",
"dottimes" => "⨰",
"elinters" => "⏧",
"emptyset" => "∅",
"eqvparsl" => "⧥",
"forksnot" => "... | Rust | 0 |
],
'next': None,
'previous': None,
})
result = self.gr.list(root=True, inventory=1)
self.assertEqual(result['results'], [
{'id': 1, 'name': 'Foo', 'inventory': 1},
{'id': 2, 'name': 'Bar', 'inventory': 2... | Python | 1 |
lues[v_bus_index];
let (v_shunt, v_bus) = match (v_shunt, v_bus) {
(Value::F32(x), Value::F32(y)) => (x, y),
t => panic!("Got wrong value types for (v_shunt, v_bus): {:?}", t),
};
let power = v_bus * v_shunt / shunt_resistance;
format!("{},{},{},{}\n", report.timestamp_micros, v_shunt, ... | Rust | 0 |
class Solution:
def divisors(self, n):
res=[]
for i in range(1,n//2+1):
if n % i == 0:
res.append(i)
res.append(n)
return res
s = Solution()
print(s.divisors(n=12)) | Python | 1 |
= "value_b", type = "&i32"),
/// field(name = "value_c", type = "i32",
/// arg(name = "a", type = "i32"),
/// arg(name = "b", type = "i32")),
/// field(name = "value_d", method = "value_d", type = "i32"),
/// )]
/// enum MyInterface {
/// TypeA(TypeA)
/// }
///
/// struct QueryRoot;
///
///... | Rust | 0 |
_from_bitslice(elem.view_bits::<O>());
}
}
}
impl<O, T> FromIterator<bool> for BitVec<O, T>
where
O: BitOrder,
T: BitStore,
{
#[inline]
fn from_iter<I>(iter: I) -> Self
where I: IntoIterator<Item = bool> {
Self::new().tap_mut(|bv| bv.extend(iter.into_iter()))
}
}
/// ***DO NOT*** use this. You clearly have... | Rust | 0 |
C(args),
]
desired = [ desired_spi ] + nonspi_desired
if args.five_volt:
desired.append(Desired5V(args))
current = [0]
tries = 0
best_score = 1000
best_doubled = 1000
while True:
tries += 1
these_pins_doubled = [lines[x] for x in current]
short_double... | Python | 1 |
-9223372036854775808, "-9223372036854775808"),
(9223372036854775807, "9223372036854775807"),
] {
let fd1 = FixedDecimal::from(i);
let fd2 = FixedDecimal::from_str(s).unwrap();
assert_eq!(fd1, fd2);
println!("{:?}", fd1);
}
}
#[test]
... | Rust | 0 |
use cw2::set_contract_version;
use cw20::{BalanceResponse, Cw20ExecuteMsg, Cw20QueryMsg};
use crate::error::ContractError;
use crate::msg::{CallsResponse, ExecuteMsg, InstantiateMsg, QueryMsg};
use crate::state::{Config, CALLS, CONFIG};
// version info for migration info
const CONTRACT_NAME: &str = "crates.io:wynd-fa... | Rust | 0 |
# first example of set
myset = {10,20,30,40,30} # duplicates are not allowed
print(myset)
print(type(myset))
# iterating set
for i in myset:
print(i) | Python | 1 |
le
} else if token == "DATE" {
DataType::Date
} else if token == "ID" {
DataType::ID
} else if token == "LABEL" {
DataType::LABEL
} else {
error!("Unsupported type {:?}", token);
DataType::NULL
}
}
}
/// Parse one i... | Rust | 0 |
[0x3fffffff7fffffff, 0xbe0024720613b5a3];
/// A factor in the short weirstrass curve (BE bytes representation)
pub const A_BYTES: [u8; 16] = [
0xd6, 0x03, 0x19, 0x98, 0xd1, 0xb3, 0xbb, 0xfe, 0xbf, 0x59, 0xcc, 0x9b, 0xbf, 0xf9, 0xae,
0xe1,
];
/// A factor in the short weirstrass curve (BE... | Rust | 0 |
// Rust check example:
// error: 1 positional argument in format string, but no arguments were given
// --> src/template/source.rs:28:27
// |
// 28 | out.push_str(format!(" |{}", ));
// | ^^
/// Styles the given `s` with ANSI escape codes.
///
/// <http... | Rust | 0 |
_mm256_loadu_pd(mem_addr: *const f64) -> __m256d {
let mut dst = _mm256_undefined_pd();
ptr::copy_nonoverlapping(
mem_addr as *const u8,
&mut dst as *mut __m256d as *mut u8,
mem::size_of::<__m256d>(),
);
dst
}
/// Store 256-bits (composed of 4 packed double-precision (64-bit)
/... | Rust | 0 |
pmp: PMP,
plic: &'a Plic,
scheduler_timer: kernel::VirtualSchedulerTimer<A>,
timer: &'static crate::timer::RvTimer<'static>,
pwrmgr: lowrisc::pwrmgr::PwrMgr,
plic_interrupt_service: &'a I,
}
pub struct EarlGreyDefaultPeripherals<'a> {
pub aes: crate::aes::Aes<'a>,
pub hmac: lowrisc::hmac... | Rust | 0 |
import os
from pytest import fixture, mark
from muse.data_importer import import_data
from muse.evaluation.classical.rouge_metric import RougeMetric
from muse.summarizer import MT5
@fixture
def document_path():
return os.path.join(os.path.dirname(__file__), "xlsum")
@mark.skipif(os.getenv("SKIP_INTENSIVE_TEST... | Python | 1 |
nonce_ref = self.nonce_generator.get();
}
let buf_len = from.len();
let (from, tag_ref) = from.split_at(buf_len - C::TagSize::to_usize());
let additional_data = self.chunk_counter.to_be_bytes();
let buf = &mut to[..from.len()];
buf.copy_from_slice(from);
... | Rust | 0 |
fn exclusive_bound(self) -> Option<Bound<'a, Self>> {
Some(Bound::exclusive(self))
}
}
impl<'a> Bounder<'a> for &'a Addr {
fn inclusive_bound(self) -> Option<Bound<'a, Self>> {
Some(Bound::inclusive(self))
}
fn exclusive_bound(self) -> Option<Bound<'a, Self>> {
Some(Bound::exclu... | Rust | 0 |
fields.push((field, comma));
if done {
break;
}
}
let close = parser.parse()?;
Ok(Self {
open,
fields,
close,
})
}
}
/// A variant declaration.
#[derive(Debug, Clone)]
pub struct StructBody {
/// The ... | Rust | 0 |
$crate::console::log_error(&format!($($arg)*))
};
}
fn to_js_value(s: impl ToString) -> JsValue {
JsValue::from_str(s.to_string().as_str())
}
pub fn log(s: impl ToString) {
_log(to_js_value(s))
}
pub fn log_error(s: impl ToString) {
_log_error(to_js_value(s))
}
pub fn log_raw(s: JsValue) {
_log... | Rust | 0 |
e the sequence of writebatch can be commit as their sequence order.
struct QueueState {
waiter_ount: usize,
stop: bool,
}
pub struct PipelineCommitQueue {
cond: Condvar,
waiters: Mutex<QueueState>,
kernel: Arc<KernelNumberContext>,
}
impl PipelineCommitQueue {
pub fn new(kernel: Arc<KernelNum... | Rust | 0 |
must, too.
pub type AuthorityId = app::Public;
/// The `ConsensusEngineId` of BABE.
pub const BABE_ENGINE_ID: ConsensusEngineId = *b"BABE";
/// The length of the public key
pub const PUBLIC_KEY_LENGTH: usize = 32;
/// How many blocks to wait before running the median algorithm for relative time
/// This will not va... | Rust | 0 |
down has been saved in {}.", output);
Ok(())
}
use std::{
fs::{File, metadata},
io::{Write, BufReader, BufWriter, BufRead},
time::Instant,
path::Path,
env,
};
// Convenience functions for buffered I/O ----------------------------------------------------------------------------------------------... | Rust | 0 |
from instapy import InstaPy
from instapy.util import smart_run
# Write your automation here
# Stuck? Look at the github page https://github.com/InstaPy/instapy-quickstart
insta_username = ""
insta_password = ""
dont_like = ["food", "girl", "hot"]
ignore_words = ["pizza"]
friend_list = ["friend1", "friend2", "friend3... | Python | 1 |
/// (*see `map::Affine`*)
fn map<M: Map>(self, map: M) -> ShapeMapper<Self, M> {
ShapeMapper { shape: self, map }
}
/// Transforms the shape in an object by covering it with material.
fn cover<M: Material>(self, material: M) -> Covered<Self, M> {
Covered::new(self, material)
}
}
... | Rust | 0 |
e_inds], target_rel_labels[positive_inds]], 0)
else:
all_rel_labels = target_rel_labels
head_spec_losses['loss_rel'] = CrossEntropyLoss()(rel_scores, all_rel_labels,
weight=cls_weights[all_rel_labels])
... | Python | 1 |
in convo.iter_utterances():
if utt.id in likelihoods:
utt.meta[self.likelihood_attribute_name] = likelihoods[utt.id]
return corpus
def fit_transform(
self,
train_selector=lambda convo: True,
val_selector=lambda convo: True,
test_selector... | Python | 1 |
import logging
import socket
import struct
import time
logger = logging.getLogger(__name__)
X_PLANE_IP: str = "127.0.0.1"
X_PLANE_PORT: int = 49000
def send_command(sock: socket.socket, dataref_str: str, value: float) -> None:
"""Construct and send a DREF command to X-Plane."""
dataref: bytes = dataref_str.... | Python | 1 |
pes::find_closest_intersect;
use shapes::intersect_shape_set;
use shapes::Intersection;
use shapes::Shape;
use std::time::Instant;
pub struct Renderer {
pub fov: f64,
pub half_fov: f64,
pub height: f64,
pub width: f64,
pub ratio: f64,
}
pub fn create_renderer(fov: f64, height: f64, width: f64) -> ... | Rust | 0 |
:PathBuf;
use util::Status;
/// Available formatting styles
enum OutputStyle {
Detailed,
Minimal,
}
/// Supported version control systems
#[derive(Clone)]
enum VCS {
Git,
Hg,
None,
}
impl VCS {
fn get_status(self, rootdir: Option<PathBuf>) -> Option<Status> {
match self {
... | Rust | 0 |
n = int(input("Enter the size of matrix:"))
t = 1
r = 0 # r stands for row
c = 0 # c stands for column
matrix = [[0 for x in range(n)] for y in range(n)] # to initialise the matrix
if n % 2 == 0:
k = n // 2
else:
k = int((n / 2) + 1)
for i in range(k):
while c < n:
matrix[r][c] = t
t = t ... | Python | 1 |
alignment bits out of range"),
}
}
}
impl From<Alignment> for u8 {
fn from(alignment: Alignment) -> Self {
match alignment {
Alignment::Left => 0b00,
Alignment::Center => 0b01,
Alignment::Right => 0b10,
Alignment::LanguageDependent => 0b11,
... | Rust | 0 |
<[u8; N], Error> {
let vec =
hex::decode(value.clone()).map_err(|_| Error::RequestParamHexInvalid(value.clone()))?;
if vec.len() != N {
return Err(Error::RequestParamHexInvalid(value.clone()));
}
Ok(parse_n(vec))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_remo... | Rust | 0 |
pip_args = []
for key, val in {**self._requirements, **self._base_requirements}.items():
if key.startswith("pip+"):
pip_args.append(f"{key[4:]} {val}")
else:
pip_args.append(f"{key} {val}")
for declaration in pip_args:
parsed... | Python | 1 |
implementation ID */
const SBI_DIOSIX_IMPL_ID: usize = 5;
/* diosix-specific SBI calls */
const SBI_EXT_DIOSIX: usize = 0x0A000000 + SBI_DIOSIX_IMPL_ID;
const SBI_EXT_DIOSIX_YIELD: usize = 0;
const SBI_EXT_DIOSIX_REGISTER_SERVICE: usize = 1;
const SBI_EXT_DIOSIX_CONSOLE_PUTC: usize... | Rust | 0 |
# Copyright (c) 2021-2024, The RSL-RL Project Developers.
# All rights reserved.
# Original code is licensed under the BSD-3-Clause license.
#
# Copyright (c) 2022-2025, The Isaac Lab Project Developers.
# All rights reserved.
#
# Copyright (c) 2025-2026, The Legged Lab Project Developers.
# All rights reserved.
#
# Co... | Python | 1 |
7B_ADDR_NOACK_R::new((self.bits & 0x01) != 0)
}
}
#[doc = "I2C Transmit Abort Source Register
This register has 32 bits that indicate the source of the TX_ABRT bit. Except for Bit 9, this register is cleared whenever the IC_CLR_TX_ABRT register or the IC_CLR_INTR register is read. To clear Bit 9, the source of ... | Rust | 0 |
lags.preset {
Some(ref preset) => match preset.as_str() {
"t" | "tencent" => Ipv4Network::new(Ipv4Addr::new(10, 6, 0, 1), 32).unwrap(),
"n" | "netease" | "u" | "uu" => {
let mut ip_octets = inter.ip_addr().unwrap().octets();
ip_octets[0] = 172;
... | Rust | 0 |
# Import necessary libraries
import tweepy
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from textblob import TextBlob
# Set up Twitter API credentials
# Replace these with your actual credentials
API_KEY = 'your_api_key'
API_SECRET_KEY = 'your_api_secret_key'
ACCESS_TOKEN = 'your_access_to... | Python | 1 |
tion training
if training_args.fsdp != "" and training_args.fsdp != []:
MyTrainer = FSDPTrainer
# training_args = TrainingArguments(
# output_dir="./checkpoint",
# save_strategy="steps",
# save_steps=0.1,
# save_safetensors=False,
# logging_steps=0.1,
# g... | Python | 1 |
from discord.ext import commands
import logging
class ErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Missing requi... | Python | 1 |
# SimQN: a discrete-event simulator for the quantum networks
# Copyright (C) 2021-2022 Lutong Chen, Jian Li, Kaiping Xue
# University of Science and Technology of China, USTC.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | Python | 1 |
# Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmcls.models.backbones import ResNeXt
from mmcls.models.backbones.resnext import Bottleneck as BottleneckX
def test_bottleneck():
with pytest.raises(AssertionError):
# Style must be in ['pytorch', 'caffe']
BottleneckX... | Python | 1 |
from pathlib import Path
import numpy as np
import ehrapy as ep
CURRENT_DIR = Path(__file__).parent
_TEST_IMAGE_PATH = f"{CURRENT_DIR}/_images"
def test_kaplan_meier(mimic_2, check_same_image):
censor_idx = mimic_2.var_names.get_indexer(["censor_flg"])
mimic_2.X[:, censor_idx] = np.where(mimic_2.X[:, censo... | Python | 1 |
xt in supported_formats):
await ctx.send("Unsupported file type. Supported: .wav, .mp3, .flac, .m4a, .ogg, .aac, .aiff")
return
image_buffer = generate_spectrogram_to_memory(local_audio, filename)
discord_file = discord.File(fp=image_buffer, filename=f"{filenam... | Python | 1 |
Id = params.get("OrganizationId")
self._Name = params.get("Name")
self._ParentId = params.get("ParentId")
self._Level = params.get("Level")
self._AppId = params.get("AppId")
self._ParentIds = params.get("ParentIds")
self._Total = params.get("Total")
self._Online =... | Python | 1 |
, name, value, source);
let payload = vec![PUT_RES, PUT_SUCCESS];
let mut server = shared_server.lock().await;
server.app_call(source.clone(), source.id, payload, Duration::from_secs(3)).await.map(|_| ())
}
GET_REQ => {
// 問い合わせのあった Key を問い合わせ元に送信する
let (_, name) = bu... | Rust | 0 |
# This file is part of Indico.
# Copyright (C) 2002 - 2025 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.modules.events.roles.controllers import (RHAddEventRole, RHAddEventRoleMembers, RHDeleteEventR... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.