text
string
label_name
string
labels
int64
db) ): """ Get processing statistics. Args: user_id: Filter by user ID (optional) db: Database session Returns: ProcessingStatsResponse with statistics """ service = get_document_tracking_service(db) stats = service.get_processing_stats(user_id=user_id) return ...
Python
1
class Solution: def isNumber(self,s:str)->bool: s=s.strip() if not s: return False num_seen=False dot_seen=False e_seen=False for i,char in enumerate(s): if char.isdigit(): num_seen=True elif char in ['+','-']: ...
Python
1
import os from cryptography import x509 from mitmproxy.test import taddons from mitmproxy.utils import magisk def test_get_ca(tdata): with taddons.context() as tctx: tctx.options.confdir = tdata.path("mitmproxy/data/confdir") ca = magisk.get_ca_from_files() assert isinstance(ca, x509.Cer...
Python
1
return op def serialize_graph(graph, path: str, **kwargs): """Serialize graph to the specified location The meta and data of graph is dumped to specified location, and can be restored by `Graph.load_from` in other sessions. Each worker will write a `path_{worker_id}.meta` file and ...
Python
1
iter()).for_each(|(x, &t)| { *x |= t & mask; }); table = &table[xout.len()..]; yout.iter_mut().zip(table.iter()).for_each(|(y, &t)|{ *y |= t & mask; }); table = &table[xout.len()..]; } } /// p256SelectJacobianPo...
Rust
0
i.0); Ok(cp.into_pyarray(py)) } #[pyfunction] fn add2<'p>(py: Python<'p>, a:PyReadonlyArrayDyn<'p, f32>, b: PyReadonlyArrayDyn<'p, f32>, _n: u8, _es: u8) -> PyResult<&'p PyArrayDyn<f32>> { let ap: ArrayD<f32> = a.as_array().to_owned(); let bp: ArrayD<f32> = b.as_array().to_owned(); let cp = ap + bp...
Rust
0
clients ( /// # id SERIAL PRIMARY KEY, /// # ip_address INET NOT NULL /// # )").execute(connection)?; /// let addr = "10.1.9.32/32".parse::<IpNetwork>()?; /// let inserted_address = insert_into(clients) /// .values(ip_address.eq(&addr)) /// .returning(ip_address)...
Rust
0
id": 390, "question": "How much do you feel you learned doing this exercise? (1: Did not learn anything, 5: Learned a lot)", "kind": "intrange[1..5]" }, ], "feedback_answer_url": "https://tmc.mooc.fi/api/v8/core/submissions/7402793/feedback...
Rust
0
for point in points { point.write(self); } self.write_pad_op(pad); self.write_request(); } /** Tells the X Server to [TODO] */ pub fn poly_segment(&mut self, drawable: u32, gcid: u32, segments: &Vec<Segment>) { self.write_u8(protocol::OP_POLY_SEGMENT); ...
Rust
0
n"]).unwrap(); let opts = Opts::new( "slony_received_event", "The last event received from a remote node", ); let last_received_event = register_int_gauge_vec!(opts, &["slony_origin", "slony_receiver"]).unwrap(); let opts = Opts::new( "sl...
Rust
0
# 记得我运行这个项目的package都在新创建的一个venv里面, 不要忘记激活它 # 一个新环境中, 安装以下package # pip install SpeechRecognition googletrans==4.0.0-rc1 pyttsx3 pyaudio import speech_recognition as sr from googletrans import Translator import pyttsx3 import os from gs import inference, Language from uuid import uuid4 landict = { Language.ZH: "zh...
Python
1
from `src_strings`. /// /// TODO: Break out create and build parts into requisite functions then call /// from here. pub fn create_build_program<C, D>( context: C, src_strings: &[CString], device_ids: Option<&[D]>, cmplr_opts: &CString, ) -> OclCoreResult<Program...
Rust
0
oject, files: Vec<FileBuilder>, } impl ProjectBuilder { pub fn new(name: &str, root: PathBuf) -> ProjectBuilder { ProjectBuilder { name: name.to_string(), root: Project{ root }, files: vec![], } } pub fn file<B: AsRef<Path>>(mut self, path: B, ...
Rust
0
elf.false_positives + self.false_negatives) if self.true_positives + self.true_negatives + self.false_positives + self.false_negatives != 0 else 0 def precision(self): return self.true_positives / (self.true_positives + self.false_positives) if self.true_positives + self.false_positives != 0 else 0...
Python
1
"""Custom plugin exceptions All exceptions should inherit from the common base exception :exc:`ToxPoetryInstallerException`. :: ToxPoetryInstallerException +-- SkipEnvironment | +-- PoetryNotInstalledError +-- LockedDepVersionConflictError +-- LockedDepNotFoundError +-- ExtraNotFoundError +-- ...
Python
1
fmt::Display for ResourceNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ResourceNotFoundException")?; if let Some(inner_2) = &self.message { write!(f, ": {}", inner_2)?; } Ok(()) } } impl std::error::Error for Resou...
Rust
0
Status = status ) # Shift status staff_schedule = StaffSchedule(current_date, filter_id_employee = teachers_id) shifts = staff_schedule.get_day_list(show_id = True) for shift in shifts: shift = Shift(shift['id'],...
Python
1
str, list[str]] | None = Field(default_factory=dict, title="星耀在十二宫的亮度") # 年分割点配置 # - YearDivideEnum.NORMA: 正月初一分界 # - YearDivideEnum.EXACT: 立春分界 year_divide: YearDivideEnum | None = Field(default=YearDivideEnum.NORMAL, title="年分割点", alias="yearDivide") # 小限分割点 # - AgeDivideEnum.NORMA: 只考虑年...
Python
1
UNTDOWN) .unwrap() .as_sound() .unwrap(), map_levels, } } pub fn reset(&mut self) { self.countdown.start(); for ball in &mut self.balls { self.world.borrow_mut().remove_bodies(&[*ball.handle()]); } s...
Rust
0
"""Plot the impact of B1+ inhomogeneities on the MP2RAGE UNI to T1 lookup table.""" import numpy as np import matplotlib.pyplot as plt from func.functions import compute_T1_lookup_table # ============================================================================= # MP2RAGE parameters (requires user inputs based on ...
Python
1
a = {'mango', 'banana', 'apple', 'pineapple'} for d in a: if d == 'apple': print (f"wow is {d}") elif d == 'banana': print("is banana") elif d == 'mango': print("is mango") elif d == 'pineapple': print("is pineapple") else: print("end of line")
Python
1
from typing import List import torch import torch.nn.functional as F def masked_l2_loss(pred, target, mask, weight_known, weight_missing): per_pixel_l2 = F.mse_loss(pred, target, reduction='none') pixel_weights = mask * weight_missing + (1 - mask) * weight_known return (pixel_weights * per_pixel_l2).mean...
Python
1
DetailInfoVO() if 'merchant_promo_amount' in d: o.merchant_promo_amount = d['merchant_promo_amount'] if 'merchant_promo_detail' in d: o.merchant_promo_detail = d['merchant_promo_detail'] if 'plan_pay_amount' in d: o.plan_pay_amount = d['plan_pay_amount'] ...
Python
1
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmpose.models import builder def test_v2v_net(): """Test V2VNet.""" cfg = dict(type='V2VNet', input_channels=17, output_channels=15), model = builder.build_backbone(*cfg) input = torch.randn(2, 17, 32, 32, 32) output = model(input)...
Python
1
4_avx2( dst: *mut u8, dst_stride: isize, tmp: *const u16, tmp_stride: isize, pri_strength: i32, sec_strength: i32, dir: i32, damping: i32, ); fn rav1e_cdef_filter_4x8_avx2( dst: *mut u8, dst_stride: isize, tmp: *const u16, tmp_stride: isize, pri_strength: i32, sec_strength: i32, dir: i3...
Rust
0
futures_data = self._data_provider.get_price(future_tickers_list, fields, start_date, end_date, frequency) # Store the start_date used for the purpose of FuturesChain initialization self._first_cached_date = start_date for exp_date, future_ticker in future_tickers_exp_dates_series.items(): ...
Python
1
x83?\x15\xfdH\x85\ \x88\x8e\xb9\xba][;\xbe\xa2\x8a#\x01\xb4\xa7BT\ \x1aE(N\xf4\x8arQ\x1a\xa5QSc\x04h\x00\ \x1a\xe3V\xf7,\x1a\x80\xba\x91\x859aH\x04W\xb4\ \x0d\xe1\xcc\x85]\xf2\x970\x033V\xeb\x10\x98\xdc\xad\ \xef\xf4-\xfc\x0f\x80c\x00\x8cn\x9d\xcaB\xab$x\ 0\xf0$\x9a\x80\xd0x&\x1e\x88\x06 \xa6\x16\xd0\x00\ \xc4\x04\xfa\...
Python
1
count: u64, total_scheduled_duration: Duration, total_poll_count: u64, total_poll_duration: Duration, total_fast_poll_count: u64, total_fast_poll_duration: Duration, total_slow_poll_count: u64, total_slow_poll_duration: Duration, } impl From<TaskMetrics> for Metrics { fn from(metrics: T...
Rust
0
certificate_arn = f"arn:aws:acm:us-west-2:123456789012:certificate/{uuid.uuid4()}" acm_stubber.stub_request_certificate( domain, alternate_domains, method, certificate_arn, validation_domains, error_code=error_code, ) if error_code is None: got_cert...
Python
1
d, TraitBoundModifier, TypeParamBound}; use crate::codegen::TraitImpl; use crate::usage::IdentSet; /// Wrapper for "outer From" traits, such as `FromDeriveInput`, `FromVariant`, and `FromField`. pub trait OuterFromImpl<'a> { /// Gets the path of the trait being implemented. fn trait_path(&self) -> Path; ...
Rust
0
format!( "{}::{}({:?}){:?}", self.module().name(), self.name().as_str(), parameters, return_ ) } } /// Resolved form of a function definition #[derive(Clone, Debug, Eq, PartialEq)] pub struct FunctionDef { pub local_count: usize, ...
Rust
0
import logging import numpy import theano logger = logging.getLogger(__name__) # This is the list of strings required to ignore, if we're going to take a pretrained HRED model # and fine-tune it as a variational model. # parameter_strings_to_ignore = ["latent_utterance_prior", "latent_utterance_approx_posterior", "Wd...
Python
1
ew(&[0.3, 0.7], 10).unwrap(); assert!(n.checked_ln_pmf(&[1]).is_err()); } #[test] fn test_checked_ln_pmf_x_wrong_sum() { let n = Multinomial::new(&[0.3, 0.7], 10).unwrap(); assert!(n.checked_ln_pmf(&[1, 3]).is_err()); } } fn main() { println!("cargo:rerun-if-changed=shaders/...
Rust
0
test] fn metadata_proc_macro1() { let metadata = JsonFixture::metadata_proc_macro1(); metadata.verify(); let graph = metadata.graph(); let package = graph .metadata(&package_id(json::METADATA_PROC_MACRO1_MACRO)) .expect("valid package ID"); assert!(pa...
Rust
0
aai(&self) -> AAIR { let bits = { const MASK: u16 = 511; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u16 }; AAIR { bits } } #[doc = "Bits 16:23 - Algorithm"] #[inline] pub fn alg(&self) -> ALGR { ALGR::_from({ ...
Rust
0
# fruits = ["apple", "cherry", "banana"] # for fruit in fruits: # print(fruit) # print(fruit + " pie") # for loop with range for number in range(1 , 11 , 3): print(number)
Python
1
gpointer, } impl Callback { pub fn call(&self, widget: &Widget) { unsafe { if let Some(callback) = self.callback { callback(widget.to_glib_none().0, self.user_data); } } } } pub unsafe trait ContainerClassSubclassExt: ClassStruct { #[doc(alias = "gtk...
Rust
0
egex = Regex::new(r"^3[0689]").unwrap(); static ref DISCOVER: Regex = Regex::new(r"^6([045]|22)").unwrap(); static ref UNIONPAY: Regex = Regex::new(r"^(62|88)").unwrap(); static ref JCB: Regex = Regex::new(r"^35").unwrap(); } enum Type { VisaElectron, Maestro, Forbrugsforeningen, Dankort, ...
Rust
0
m: &T, sign: flt2dec::Sign, precision: usize, ) -> Result where T: flt2dec::DecodableFloat, { // SAFETY: Possible undefined behavior, see FIXME(#76092) unsafe { // enough for f32 and f64 let mut buf = MaybeUninit::<[u8; flt2dec::MAX_SIG_DIGITS]>::uninit(); let mut parts = May...
Rust
0
M => f.write_str("set1m"), ST => f.write_str("st"), STW => f.write_str("stw"), STX => f.write_str("stx"), SUB => f.write_str("sub"), SUBC => f.write_str("subc"), XCH => f.write_str("xch"), XCHW => f.write_str("xchw"), } } } ...
Rust
0
const XK_dead_hook: c_uint = 0xfe61; pub const XK_dead_horn: c_uint = 0xfe62; pub const XK_dead_stroke: c_uint = 0xfe63; pub const XK_dead_abovecomma: c_uint = 0xfe64; pub const XK_dead_psili: c_uint = 0xfe64; pub const XK_dead_abovereversedcomma: c_uint = 0xfe65; pub const XK_dead_dasia: c_uint = 0xfe65; pub const XK_...
Rust
0
18e3a")?), GutenbergBlock::empty_block_from_name("moocfi/exercises-in-chapter".to_string()) .with_id(Uuid::parse_str("1bf7e311-75e8-48ec-bd55-e8f1185d76d0")?), ]) .unwrap(), exercises: vec![], exercise_slides: vec![], exerci...
Rust
0
_RETURNS_TWICE) { Attribute::ReturnsTwice.apply_llfn(Function, llfn); } if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) { naked(llfn, true); } if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) { Attribute::NoAlias.apply_llfn(llvm::AttributePlace::Ret...
Rust
0
} }use maguro; use tokio::fs::OpenOptions; // Here we use the "current_thread" flavor since this is a simple // application. In larger ones, a multithreaded runtime is preferable. #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box<(dyn error::Error + 'static)>> { // Get our video informati...
Rust
0
from flask.cli import AppGroup from .users import seed_users, undo_users from .characters import seed_characters, undo_characters from app.models.db import db, environment, SCHEMA # Creates a seed group to hold our commands # So we can type `flask seed --help` seed_commands = AppGroup('seed') # Creates the `flask s...
Python
1
custom_metadata_schema_content = f.read() if not parser.parse(custom_metadata_schema_content): raise ValueError( "Cannot parse custom metadata schema. Reason: " + parser.error ) custom_metadata_json = _pywrap_flatbuffers.generate_text( parser, custom_metadata ) json_...
Python
1
::GP_DRIVER_STATUS_PRODUCTION; pub const GP_DRIVER_STATUS_TESTING: CameraDriverStatus = CameraDriverStatus::GP_DRIVER_STATUS_TESTING; pub const GP_DRIVER_STATUS_EXPERIMENTAL: CameraDriverStatus = CameraDriverStatus::GP_DRIVER_STATUS_EXPERIMENTAL; pub const GP_DRIVER_STATUS_DEPRECATED: CameraDriverStatus = C...
Rust
0
in module.sections().iter().enumerate() { let custom = match *s { Section::Custom(ref s) => s, _ => continue, }; if custom.name() != "__wasm_bindgen_unstable" { continue; } to_remove.push(i); let mut payload = custom.payload(); ...
Rust
0
ESPONSE: &str = "Hello!"; // An example of protection via `proc-macro` #[rocket_grants::has_permissions("OP_READ_ADMIN_INFO")] #[get("/admin")] async fn macro_secured() -> &'static str { ADMIN_RESPONSE } // An example of programmable protection #[get("/")] async fn manual_secure(details: AuthDetails) -> &'static ...
Rust
0
hpfvo kfhxoubpznyvi xlfmqhkjiuosrvda omsxifhujdqlkavp umfkiwxdlvqahoj juhaimqvflxrdok rw j amgfyn wj bz yijwmopraq ioqmawrylpj qioayjpwmr dyvfzhmetqwrga zfetnamhcrjw lwrzkansftehm mafhtrzlew jolep jo jao gwuqrp rgqpuw gpqurw quwrpgo hrfol nkrfaleo htrnmvfpqbckduwloyez khytlsgrdopzeucfxbqn dizcpufnthkeyolrqjb z...
Rust
0
# print("Hello World \nhow are you ?") # print("hi") # single line comment ''' multiline comment ''' """ multiline comment """ # print('how "are" you ?') # print("how \'are\' you ?") # print("hey", 6 , 7, sep="~", end= "\n") # print("hey", 6 , 7, sep="~", end= "0009") # Variables and Data types # Numeric da...
Python
1
B, ) -> TopParser<'a, impl 'a + Fn(I) -> Parser<B, I>, B, I> { TopParser { parser: move |input| match (self.parser)(input) { Parser::Parsed { data, input } => Parser::Parsed { data: f(data), input, }, Parser::NoParse => Parser::NoParse, }, _phantom: P...
Rust
0
pt.clear_entry(pt_idx).expect("failed to unmap page"); asm::invlpg(virt_addr); } } } } pub unsafe fn direct_get_mapping(virt_addr: usize) -> Option<PageTableEntry> { let virt_addr = virt_addr & PAGE_MASK; let pml4_idx = pml4_idx(virt_addr); let pdp_idx = pdp_i...
Rust
0
#[prost(int32, tag="10")] pub active_member_num: i32, #[prost(int32, tag="11")] pub certification_type: i32, #[prost(bytes="vec", tag="12")] pub ing_certification_text: ::prost::alloc::vec::Vec<u8>, #[prost(bytes="vec", tag="13")] pub ing_group_rich_finger_memo: ::prost::alloc::vec::Vec...
Rust
0
pub struct KeyState { pub requested_auto_move: bool } fn skip_turn(ecs: &mut World) -> RunState { let player_entity = ecs.fetch::<Entity>(); let confusion = ecs.read_storage::<Confusion>(); if let Some(_) = confusion.get(*player_entity) { let mut resting = ecs.write_storage::<Resting>(); ...
Rust
0
to use the last three pins on the bottom right of the RPi: let (data_pin, latch_pin, clock_pin) = (29, 28, 27); // MAKE SURE THESE MATCH YOUR SETUP! let mut shifter = Shifter::new(data_pin, latch_pin, clock_pin); let pins = 8; // Number of output pins on our shift registers let sr0 = shifter.add(pins);...
Rust
0
res = ' 今日人品是{},为“{}”'.format( rp, rp_dict[bisect_right(rp_range, rp)]) if event.sender.id == 80000000: res = '@匿名消息' + res await bot.send(event, res) else: await bot.send(event, [At(event.sender.id), res]) @bot.on(...
Python
1
from db_connection import connect_to_database_mysql from json_handler import read_json import mysql.connector from mysql.connector import Error def insert_data(cursor, sql_query, data): """Execute an SQL insert statement with the provided data.""" try: cursor.execute(sql_query, data) except Error ...
Python
1
_i8()) } else { val } } fn to_immediate_scalar(&mut self, val: Self::Value, scalar: abi::Scalar) -> Self::Value { if scalar.is_bool() { return self.trunc(val, self.cx().type_i1()); } val } fn fptoui_sat(&mut self, _val: RValue<'gc...
Rust
0
::find_solution(reader, day, is_second_star)?), AoCYear::AOC2017 => Ok(year2017::find_solution(reader, day, is_second_star)?), AoCYear::AOC2016 => Ok(year2016::find_solution(reader, day, is_second_star)?), AoCYear::AOC2015 => Ok(year2015::find_solution(reader, day, is_second_star)?), } } //...
Rust
0
xpected one of \'leaf\' or \'foo\'.\n\n\ Run \'helptree\' for more info on the entire command tree.\n\ ", ), ) } } use crate::agents::player; use anyhow::{format_err, Error}; use js_sys::JsString; use log::{error, trace}; use wasm_bindgen::JsCast; use web_sys::{...
Rust
0
速单调递增时间,只支持类Linux系统 } unsafe impl Send for MontonicTime {} unsafe impl Sync for MontonicTime {} impl MontonicTime { /// 构建一个单调递增时间 #[cfg(not(any(target_os = "linux", target_os = "android")))] pub fn now() -> Self { MontonicTime::Normal(Instant::now()) } /// 构建一个单调递增时间 #[...
Rust
0
import autograd.numpy as np import pylab as pl np.random.seed(2837) N = 21 f_true = lambda x: np.sin(x) sig_obs = 0.2 X = np.linspace(-2*np.pi, 2*np.pi, N) Y = f_true(X) + np.random.normal(0, sig_obs, len(X)) eta = 0.01 theta0 = 0.3, 0.3 X_pred = np.linspace(-np.pi, np.pi, 2*N) + 0.2 #l = 2. k = lambda x1,x2 : 1.*...
Python
1
class solution: def longestSuccessiveElements(self,a : list[int]) -> int: a.sort() n=len(a) cnt=0 last_small=-1 longest=1 for i in range(n): if a[i]-1 == last_small: cnt+=1 last_small=a[i] elif a[i]!= last_s...
Python
1
`LoremBuilder` struct will have private fields for `ipsum` and `dolor`, and /// a public `sit` field. #[derive(Debug, Builder)] #[builder(field(private), setter(into))] pub struct Lorem { ipsum: String, dolor: u16, #[builder(field(public))] sit: bool, } } fn main() ...
Rust
0
[ (c[0] * 256.0).floor().max(0.0).min(255.0) as u8, (c[1] * 256.0).floor().max(0.0).min(255.0) as u8, (c[2] * 256.0).floor().max(0.0).min(255.0) as u8, ] .into() }) .collect::<Vec<_>>(); RgbImage::from_raw(width as u32...
Rust
0
let g: &ffi::Game = unsafe { self.raw.as_ref().unwrap().as_ref() }; Unitset { raw: Handle::Borrowed(g.getGeysers()), } } pub fn get_ground_height(&self, position: TilePosition) -> i32 { let g: &ffi::Game = unsafe { self.raw.as_ref().unwrap().as_ref() }; g.getGro...
Rust
0
xbd\x8d': 0.0, '\xbd\x8c': 0.0, '\xbd\x8f': 0.0, '\xbd\x8e': 0.0, '\xbd\x89': 0.0, '\xbd\x88': 0.0, '\xbd\x8b': 0.0, '\xbd\x8a': 0.0, '\xbdu': 0.0, '\xbdt': 0.0, '\xbdw': 0.0, '\xbdv': 0.0, '\xbdq': 0.0, '\xbdp': 0.0, '\xbds': 0.0, '\xbdr': 0.0, '\xbd}': 0.0, '\xbd|': 0.0, '\xbd\x7f': 0.0, '\xbd~': 0.0, '\xbdy': 0.0, '...
Python
1
index]).expect("beacon not here"); println!("[+] Beacon file: {}", &beacon_files[index]); // Get the list of container files let container_folder = &format!("{}/{}", corpora, "attestation"); let container_files = utils::list_files_in_folder(&container_folder).expect("no container files here"); ...
Rust
0
) .execute(db) .await? .rows_affected(); match rows_updated { 0 => return Err(error::CategoryUpdate::CategoryNotFound), 1 => {} _ => unreachable!(), } } if let Some(user_scopes) = use...
Rust
0
: "); stdout().flush()?; let mut line = String::new(); stdin().read_line(&mut line)?; line.trim() .try_into() .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) } pub fn get_clue() -> io::Result<Clue> { print!("clue: "); stdout().flush()?; let mut line = String::new(); ...
Rust
0
8); // larger positions were not yet searched assert!(!matches.alignment_at(end + 1, &mut aln)); } assert!(end_dist_iter.next().is_none()); } // Lazy API with unlimited distance: each position should be found let mut matches = myers.find_all_lazy(text, u8::max_valu...
Rust
0
[cfg(test)] mod tests { use super::Medal; #[test] fn test0(){ let input = vec![ Medal::new(3,5,9), Medal::new(15,20,35), Medal::new(30,45,72), Medal::new(15,20,31), Medal::new(27,33,59), Medal::new(27,35,77), ...
Rust
0
# -*- coding: utf-8 -*- from typing import Optional from transformers.configuration_utils import PretrainedConfig class SBAConfig(PretrainedConfig): model_type = 'sba' keys_to_ignore_at_inference = ['past_key_values'] def __init__( self, hidden_size: int = 2048, num_hidden_layers...
Python
1
address().clone(); // when let req = r#"{"jsonrpc":"2.0","id":1,"method":"hello_async"}"#; let response = request(server, &format!("\ POST / HTTP/1.1\r\n\ Host: localhost:{}\r\n\ Connection: close\r\n\ Content-Type: application/json\r\n\ Content-Length: {}\r\n\ \r\n\ {}\r\n\ ", addr.port(),...
Rust
0
tialEq, Eq, Clone)] pub enum KeyType { /// Bare key. Bare, /// Basic key. Basic, /// Literal key. Literal, } /// A key value. #[derive(Clone)] pub struct Key<'a> { /// The type of the key pub t: KeyType, /// The key separator pub sep: &'a str, /// The actual key value pu...
Rust
0
#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-or-later # # Copyright (C) 2022, Paul Elder <paul.elder@ideasonboard.com> # Copyright (C) 2024, Ideas On Board # # Tuning script for rkisp1 import logging import sys import coloredlogs import libtuning as lt from libtuning.generators import YamlOutput from lib...
Python
1
else: print(f"[ERROR] Falha na sincronização: {result['errors']}") elif args.mode == 'monitor': # Modo de monitoramento print("[EMOJI] Iniciando monitoramento contínuo...") sync_manager.start_monitoring() i...
Python
1
2.gen_empty_block_with_diff(50u64, &mock_store); } // 20 * 100 = 2000 for _ in 0..(final_number * 5) { chain3.gen_empty_block_with_diff(20u64, &mock_store); } for chain in vec![chain1.clone(), chain2.clone(), chain3.clone()] { for block in chain.blocks() { chain_control...
Rust
0
Ok(REQUEST_QUIT); } Ok(num) if num >= 1 && num <= count => files[num as usize - 1].clone(), _ => { let path = Path::new(line); if path.exists() && path.is_file() { line.to_string() } else...
Rust
0
# Copyright (c) Alibaba, Inc. and its affiliates. # The implementation is also open-sourced by the authors, and available at # https://github.com/alibaba/lightweight-neural-architecture-search. # The DeepMAD method is from the paper https://arxiv.org/abs/2303.02165 of Alibaba. work_dir = './save_model/deepmad_50M/' lo...
Python
1
"""create_favorites_table Revision ID: f16b5c17c7bf Revises: 26650479f646 Create Date: 2025-02-17 03:43:47.074626+00:00 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision: str = 'f16b5c17c...
Python
1
N = int(input()) from itertools import groupby, pairwise A = list(map(int, input().split())) g = groupby(A) best = 0 F = [] for k,v in g: F.append(len(list(v))) for av,bv in pairwise(F): best = max(best, 2*min(av, bv)) print(best)
Python
1
.append_pair("transport", "websocket"); url.set_scheme("wss").unwrap(); assert_eq!(transport.base_url()?.to_string(), url.to_string()); transport.set_base_url(reqwest::Url::parse("https://127.0.0.1")?)?; assert_eq!( transport.base_url()?.to_string(), "wss:...
Rust
0
2. For _encrypted data transfer_: //! * As a secure in-memory container. //! //! Cocoon is developed with security in mind. It aims to do the only one thing and do it //! flawlessly. It has a minimal set of dependencies and a minimalist design to simplify control //! over security aspects. It's a pure Rust implemen...
Rust
0
array![Token::NumberImmediate((new(0, 0)..new(0, 5), Decimal128::from(0x123)))])]); assert_eq!(tokenize(".0"), vec![Ok(array![Token::NumberImmediate((new(0, 0)..new(0, 2), Decimal128::from(0)))])]); assert_eq!(tokenize(".1e1"), vec![Ok(array![Token::NumberImmediate((new(0, 0)..new(0, 4), Decimal128::fr...
Rust
0
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ############################################# # WARNING # ############################################# # # This file is auto generated by ...
Python
1
[<$ty Write>]<'a>(&'a $ty); impl ToRedisArgs for [<$ty Write>]<'_> { fn write_redis_args<W>(&self, out: &mut W) where W: ?Sized + RedisWrite, { self.0.as_slice().write_redis_args(out) } } ...
Rust
0
""" Ensures _repo_root_from_here finds the repo root by locating knowledge/analysis/general-flow.md, and falls back correctly when missing. """ from pathlib import Path import os # Import directly from the module under test from profiler_assistant.policy.preamble import _repo_root_from_here def test_repo_root_detec...
Python
1
let key = key.rptr(&env)?; tx_body_hash.typed_ref::<TransactionHash>() .zip(addr.typed_ref::<ByronAddress>()) .zip(key.typed_ref::<LegacyDaedalusPrivateKey>()) .and_then( |((tx_body_hash, addr), key)| { make_daedalus_bootstrap_witness(tx_body_hash, addr, key).rptr().jptr(&env) } ...
Rust
0
from collections import OrderedDict import torch.nn as nn from detectron2.layers import Conv2d, get_norm class SimpleFeaturePyramid(nn.Module): """ This module implements SimpleFeaturePyramid in :paper:`vitdet`. It creates pyramid features built on top of the input feature map. """ def __init__(...
Python
1
# Patients Hazard Model # \lambda(t|X) = \lambda_0(t) exp(H(x)) # # risk = True log hazard ratio # log(\lambda(t|X) / \lambda_0(t)) = H(x) if method == 'linear': risk = self._linear_H(data) elif method == 'gaussian': risk = self._gaussian_H(data,*...
Python
1
ponse = client.complete(direct_prompt, temperature=0.2, max_tokens=50) print(f"Response: {response}") # With chain-of-thought cot_prompt = """A bakery sells cookies for $2 each. On Monday they sold 45 cookies, on Tuesday 60% more than Monday, and on Wednesday half of Tuesday's amount. What was thei...
Python
1
import json import os import numpy as np from tqdm import tqdm from utils.sample import PageRetriever from utils.qa_generator import QAGenerator from utils.devapi import LLMAPI, MODEL_MAP from utils.prompt import TESTEE from utils.utils import ans_extractor, judge_ans TESTEE_MODEL = [ "meta-llama/Llama-3.3-70B-In...
Python
1
lic_key: &'pk ThresholdPaillierPublicKey, } /// A partially decrypted ciphertext, of which t must be combined to decrypt successfully. pub struct ThresholdPaillierDecryptionShare { id: i32, share: Integer, } impl<'pk> Enrichable<'pk, ThresholdPaillierPublicKey, RichThresholdPaillierCiphertext<'pk>> for Th...
Rust
0
ig.collider_params["far_plane"], ) combined_rgb = torch.cat([image, rgb_coarse, rgb_fine], dim=1) combined_acc = torch.cat([acc_coarse, acc_fine], dim=1) combined_depth = torch.cat([depth_coarse, depth_fine], dim=1) # Switch images from [H, W, C] to [1, C, H, W] for metrics com...
Python
1
') def main(args=None): conf = get_conf(args) spark = SparkSession.builder\ .appName("spark_inference")\ .master(f"local[{conf.inference_dataloader.loader.num_workers}]")\ .config("spark.sql.shuffle.partitions",100)\ .config("spark.driver.memory",conf['spark_memory'])\ ...
Python
1
Ok(()) } <reponame>fiirecore-game/pokemon-game use core::ops::Deref; use pokedex::{engine::utils::HashMap, item::Item, moves::Move, pokemon::Pokemon}; use pokedex::{engine::Context, PokedexClientData}; use battle::data::BattleType; use crate::{ context::BattleGuiData, transition::TransitionState, ui::vie...
Rust
0
lass; use glib::value::ToValue; use glib::{Cast, Object, StaticType, Type}; use std::boxed::Box as Box_; use std::pin::Pin; impl AsyncInitable { #[doc(alias = "g_async_initable_new_async")] pub fn new_async< O: Sized + IsClass + IsA<Object> + IsA<AsyncInitable>, P: IsA<Cancellable>, Q: ...
Rust
0
_metadata(&self) -> IoxMetadata { let decoded_parquet_file = DecodedParquetFile::new((*self.data).clone()); decoded_parquet_file.iox_metadata } } /// Struct holding output of a compacted stream pub struct CompactedData { pub(crate) data: Vec<RecordBatch>, pub(crate) meta: IoxMetadata, p...
Rust
0