lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
tests/rsa_tests.rs
NikVolf/ring
0c0f7c47112f9ff3e1b8d8d4427d8246fcdc0794
#![forbid( anonymous_parameters, box_pointers, legacy_directory_ownership, missing_copy_implementations, missing_debug_implementations, missing_docs, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_extern_crates, unused_import_braces, un...
#![forbid( anonymous_parameters, box_pointers, legacy_directory_ownership, missing_copy_implementations, missing_debug_implementations, missing_docs, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_extern_crates, unused_import_braces, un...
let result = test_case.consume_string("Result"); let private_key = test_case.consume_bytes("Key"); let private_key = untrusted::Input::from(&private_key); let key_pair = signature::RSAKeyPair::from_der(private_key); if key_pair.is_err() && result == "Fail-Invalid-Key" { ...
let alg = match digest_name.as_ref() { "SHA256" => &signature::RSA_PSS_SHA256, "SHA384" => &signature::RSA_PSS_SHA384, "SHA512" => &signature::RSA_PSS_SHA512, _ => { panic!("Unsupported digest: {}", digest_name) } };
assignment_statement
[ { "content": "#[inline]\n\npub fn sign(key_pair: &KeyPair, rng: &rand::SecureRandom, msg: untrusted::Input)\n\n -> Result<Signature, error::Unspecified> {\n\n key_pair.inner.sign(rng, msg)\n\n}\n\n\n", "file_path": "src/signature.rs", "rank": 0, "score": 364956.10236816294 }, { ...
Rust
src/error.rs
braunse/isahc
df395edf481221d7d1fbfef020d813e604aa28e3
#![allow(deprecated)] use std::error::Error as StdError; use std::fmt; use std::io; #[derive(Debug)] pub enum Error { Aborted, BadClientCertificate(Option<String>), BadServerCertificate(Option<String>), ConnectFailed, CouldntResolveHost, CouldntResolveProxy, ...
#![allow(deprecated)] use std::error::Error as StdError; use std::fmt; use std::io; #[derive(Debug)] pub enum Error { Aborted, BadClientCertificate(Option<String>), BadServerCertificate(Option<String>), ConnectFailed, CouldntResolveHost, CouldntResolveProxy, ...
} #[doc(hidden)] impl From<std::string::FromUtf8Error> for Error { fn from(_: std::string::FromUtf8Error) -> Error { Error::InvalidUtf8 } } #[doc(hidden)] impl From<std::str::Utf8Error> for Error { fn from(_: std::str::Utf8Error) -> Error { Error::InvalidUtf8 } }
fn from(error: Error) -> io::Error { match error { Error::ConnectFailed => io::ErrorKind::ConnectionRefused.into(), Error::Io(e) => e, Error::Timeout => io::ErrorKind::TimedOut.into(), _ => io::ErrorKind::Other.into(), } }
function_block-full_function
[ { "content": "/// Creates an interceptor from an arbitrary closure or function.\n\npub fn from_fn<F, E>(f: F) -> InterceptorFn<F>\n\nwhere\n\n F: for<'a> private::AsyncFn2<Request<Body>, Context<'a>, Output = Result<Response<Body>, E>> + Send + Sync + 'static,\n\n E: Into<Box<dyn Error>>,\n\n{\n\n Inte...
Rust
src/objects/module.rs
mloebel/rust-cpython
2e243f7622a8d33bca3fb321db25d4be4c26397d
use libc::c_char; use std::ffi::{CStr, CString}; use crate::conversion::ToPyObject; use crate::err::{self, PyErr, PyResult}; use crate::ffi; use crate::objectprotocol::ObjectProtocol; use crate::objects::{exc, PyDict, PyObject, PyTuple}; use crate::py_class::PythonObjectFromPyClassMacro; use crate::python::{PyDrop, ...
use libc::c_char; use std::ffi::{CStr, CString}; use crate::conversion::ToPyObject; use crate::err::{self, PyErr, PyResult}; use crate::ffi; use crate::objectprotocol::ObjectProtocol; use crate::objects::{exc, PyDict, PyObject, PyTuple}; use crate::py_class::PythonObjectFromPyClassMacro; use crate::python::{PyDrop, ...
, } } } pub fn name<'a>(&'a self, py: Python) -> PyResult<&'a str> { unsafe { self.str_from_ptr(py, ffi::PyModule_GetName(self.0.as_ptr())) } } #[allow(deprecated)] pub fn filename<'a>(&'a self, py: Python) -> PyResult<&'a str> { un...
Err(PyErr::from_instance( py, exc::UnicodeDecodeError::new_utf8(py, slice, e)?, ))
call_expression
[ { "content": "pub fn type_error_to_false(py: Python, e: PyErr) -> PyResult<bool> {\n\n if e.matches(py, py.get_type::<exc::TypeError>()) {\n\n Ok(false)\n\n } else {\n\n Err(e)\n\n }\n\n}\n\n\n\n#[macro_export]\n\n#[doc(hidden)]\n\nmacro_rules! py_class_binary_numeric_slot {\n\n ($clas...
Rust
clients/client-core/src/client/real_messages_control/acknowledgement_control/retransmission_request_listener.rs
confio/nym
495ca35c1f46e7244d89fdf73402021d70df625d
use super::action_controller::{Action, ActionSender}; use super::PendingAcknowledgement; use super::RetransmissionRequestReceiver; use crate::client::{ real_messages_control::real_traffic_stream::{BatchRealMessageSender, RealMessage}, topology_control::TopologyAccessor, }; use futures::StreamExt; use log::*; ...
use super::action_controller::{Action, ActionSender}; use super::PendingAcknowledgement; use super::RetransmissionRequestReceiver; use crate::client::{ real_messages_control::real_traffic_stream::{BatchRealMessageSender, RealMessage}, topology_control::TopologyAccessor, }; use futures::StreamExt; use log::*; ...
pub(super) async fn run(&mut self) { debug!("Started RetransmissionRequestListener"); while let Some(timed_out_ack) = self.request_receiver.next().await { self.on_retransmission_request(timed_out_ack).await; } error!("TODO: error msg. Or maybe panic?") } }
async fn on_retransmission_request(&mut self, timed_out_ack: Weak<PendingAcknowledgement>) { let timed_out_ack = match timed_out_ack.upgrade() { Some(timed_out_ack) => timed_out_ack, None => { debug!("We received an ack JUST as we were about to retransmit [1]"); ...
function_block-full_function
[ { "content": "/// Entry point for splitting whole message into possibly multiple [`Set`]s.\n\n// TODO: make it take message: Vec<u8> instead\n\npub fn split_into_sets<R: Rng>(\n\n rng: &mut R,\n\n message: &[u8],\n\n max_plaintext_size: usize,\n\n) -> Vec<FragmentSet> {\n\n let num_of_sets = total_n...
Rust
src/lib.rs
aesteve/vertx-eventbus-client-rs
2a8391d48f177d8ec9daaf9e2e973cb9d3502634
use std::io; pub mod listener; pub mod message; pub mod publisher; mod utils; use crate::listener::EventBusListener; use crate::publisher::EventBusPublisher; use std::net::{TcpStream, ToSocketAddrs}; pub fn eventbus<A: ToSocketAddrs>(address: A) -> io::Result<(EventBusPublisher, EventBusListener)> { let socket = T...
use std::io; pub mod listener; pub mod message; pub mod publisher; mod utils; use crate::listener::EventBusListener; use crate::publisher::EventBusPublisher; use std::net::{TcpStream, ToSocketAddrs}; pub fn eventbus<A: ToSocketAddrs>(address: A) -> io::Result<(EventBusPublisher, EventBusListener)> { let socket = T...
} } }
if let Some(Ok(error_msg)) = error_listener.next() { errors_received += 1; assert!(error_msg.message.contains("denied")) }
if_condition
[ { "content": "type ErrorNotifier = Mutex<Option<Sender<UserMessage<ErrorMessage>>>>;\n\n\n\npub struct EventBusListener {\n\n socket: TcpStream,\n\n handlers: MessageHandlersByAddress,\n\n error_handler: Arc<ErrorNotifier>,\n\n}\n\n\n\nimpl EventBusListener {\n\n pub fn new(socket: TcpStream) -> io:...
Rust
pallets/stake-nft/src/mock.rs
SubGame-Network/subgame-network
d9906befc41e972e11fa1a669d47eddb15dabdd8
use crate as pallet_stake_nft; use pallet_timestamp; use balances; use frame_support::parameter_types; use frame_system as system; use pallet_nft; use pallet_lease; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; type UncheckedExtrinsic = frame_system::mocking::...
use crate as pallet_stake_nft; use pallet_timestamp; use balances; use frame_support::parameter_types; use frame_system as system; use pallet_nft; use pallet_lease; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; type UncheckedExtrinsic = frame_system::mocking::...
0), (3, 1000000), (4, 1000000), (5, 1000000), ], } .assimilate_storage(&mut t) .unwrap(); let mut ext: sp_io::TestExternalities = t.into(); ext.execute_with(|| System::set_block_number(1)); ext }
function_block-function_prefixed
[ { "content": "type Block = frame_system::mocking::MockBlock<Test>;\n\n\n\n// Configure a mock runtime to test the pallet.\n\nframe_support::construct_runtime!(\n\n pub enum Test where\n\n Block = Block,\n\n NodeBlock = Block,\n\n UncheckedExtrinsic = UncheckedExtrinsic,\n\n {\n\n ...
Rust
core/codegen/tests/route.rs
Compro-Prasad/Rocket
198b6f0e9726f7e53c61d365b797df630c876c59
#![deny(non_snake_case)] #[macro_use] extern crate rocket; use std::path::PathBuf; use rocket::http::ext::Normalize; use rocket::local::blocking::Client; use rocket::data::{self, Data, FromData, ToByteUnit}; use rocket::request::{Request, Form}; use rocket::http::{Status, RawStr, ContentType}; #[derive(FromForm, ...
#![deny(non_snake_case)] #[macro_use] extern crate rocket; use std::path::PathBuf; use rocket::http::ext::Normalize; use rocket::local::blocking::Client; use rocket::data::{self, Data, FromData, ToByteUnit}; use rocket::request::{Request, Form}; use rocket::http::{Status, RawStr, ContentType}; #[derive(FromForm, ...
mod scopes { mod other { #[get("/world")] pub fn world() -> &'static str { "Hello, world!" } } #[get("/hello")] pub fn hello() -> &'static str { "Hello, outside world!" } use other::world; fn _rocket() -> rocket::Rocket { rocket::ignit...
dispatch(); assert_eq!(response.into_string().unwrap(), format!("({}, {}, {}, {}, {}, {}) ({})", sky, name, "A A", "inside", path, simple, expected_uri)); }
function_block-function_prefix_line
[ { "content": "fn test(uri: String, expected: String) {\n\n let client = Client::tracked(super::rocket()).unwrap();\n\n let response = client.get(&uri).dispatch();\n\n assert_eq!(response.into_string(), Some(expected));\n\n}\n\n\n", "file_path": "examples/ranking/src/tests.rs", "rank": 0, "s...
Rust
services/src/util/parsing.rs
2younis/geoengine
253eb7ff2c980511fecdec6ff8fb176d5365bc11
use geoengine_datatypes::primitives::SpatialResolution; use serde::de; use serde::de::Error; use serde::Deserialize; use std::fmt; use std::marker::PhantomData; use std::str::FromStr; use url::Url; pub fn parse_spatial_resolution<'de, D>(deserializer: D) -> Result<SpatialResolution, D::Error> where D: serde::Deser...
use geoengine_datatypes::primitives::SpatialResolution; use serde::de; use serde::de::Error; use serde::Deserialize; use std::fmt; use std::marker::PhantomData; use std::str::FromStr; use url::Url; pub fn parse_spatial_resolution<'de, D>(deserializer: D) -> Result<SpatialResolution, D::Error> where D: serde::Deser...
ert_eq!( serde_json::from_str::<Test>(r#"{"base_url": null}"#) .unwrap() .to_string(), "" ); } }
struct Test { #[serde(deserialize_with = "deserialize_base_url")] base_url: Url, } impl Display for Test { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.base_url.to_string()) } } assert_e...
random
[ { "content": "pub fn spatial_reference_specification(srs_string: &str) -> Result<SpatialReferenceSpecification> {\n\n if let Some(sref) = custom_spatial_reference_specification(srs_string) {\n\n return Ok(sref);\n\n }\n\n\n\n let spatial_reference = SpatialReference::from_str(srs_string).context...
Rust
capstone-rs/examples/cstool.rs
froydnj/capstone-rs
5044ace8022b1651d1b7c93d41ad56993e0225f5
extern crate capstone; extern crate clap; #[macro_use] extern crate log; extern crate stderrlog; use capstone::prelude::*; use capstone::{Arch, Endian, EnumList, ExtraMode, Mode}; use clap::{App, Arg, ArgGroup}; use std::fmt::Display; use std::fs::File; use std::io::prelude::*; use std::io; use std::process::exit; ...
extern crate capstone; extern crate clap; #[macro_use] extern crate log; extern crate stderrlog; use capstone::prelude::*; use capstone::{Arch, Endian, EnumList, ExtraMode, Mode}; use clap::{App, Arg, ArgGroup}; use std::fmt::Display; use std::fs::File; use std::io::prelude::*; use std::io; use std::process::exit; ...
("code") .required(true), ) .get_matches(); let direct_input_bytes: Vec<u8> = if let Some(file_path) = matches.value_of("file") { let mut file = File::open(file_path).expect_exit(); let capacity = match file.metadata() { Err(_) => DEFAULT_CAPACITY, ...
unwrap_or("") ).is_ok(); if show_detail { let detail = cs.insn_detail(&i).expect("Failed to get insn detail"); let output: &[(&str, String)] = &[ ("insn id:", format!("{:?}", i.id().0)), ("read regs:", reg_names(&cs, detail.regs_read())), ...
random
[ { "content": "/// Disassemble code and print information\n\nfn arch_example(cs: &mut Capstone, code: &[u8]) -> CsResult<()> {\n\n let insns = cs.disasm_all(code, 0x1000)?;\n\n println!(\"Found {} instructions\", insns.len());\n\n for i in insns.iter() {\n\n println!();\n\n println!(\"{}\"...
Rust
compiler/context.rs
mwatts/arret
3b3bae27ca7283376d420fa7d69fe5073ecf9ef0
use crate::hir::PackagePaths; use crate::rfi; use crate::source::SourceLoader; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::{hash, path}; use codespan_reporting::diagnostic::Diagnostic; use arret_syntax::datum::Datum; use arret_syntax::span::{FileId, Span}; use crate::hir; use crate::hir::...
use crate::hir::PackagePaths; use crate::rfi; use crate::source::SourceLoader; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::{hash, path}; use codespan_reporting::diagnostic::Diagnostic; use arret_syntax::datum::Datum; use arret_syntax::span::{FileId, Span}; use crate::hir; use crate::hir::...
defs.push(def); inferred_locals.insert(local_id, arret_type); exports.insert(fun_name_data_str, hir::scope::Binding::Var(None, local_id)); } Module { module_id: ModuleId::alloc(), imports: HashMap::new(), defs, inferred_locals: Arc::new(inferred_locals...
let def = hir::Def::<hir::Inferred> { span, macro_invocation_span: None, destruc: hir::destruc::Destruc::Scalar( span, hir::destruc::Scalar::new( Some(local_id), fun_name_data_str.clone(), arr...
assignment_statement
[ { "content": "/// Adds internal member fields common to all inline and external records\n\npub fn append_common_internal_members(tcx: &mut TargetCtx, members: &mut Vec<LLVMTypeRef>) {\n\n unsafe {\n\n members.extend_from_slice(&[\n\n // is_inline\n\n LLVMInt8TypeInContext(tcx.llx...
Rust
tests/category_dist_sums.rs
bostontrader/bookwerx-core-rust
35f8ac82b22399ffb1ae0eabc4dcd186395d9fc3
use bookwerx_core_rust::db as D; use rocket::http::Status; use rocket::local::Client; use bookwerx_core_rust::dfp::dfp::{DFP, Sign, dfp_abs, dfp_add}; pub fn category_dist_sums(client: &Client, apikey: &String, categories: &Vec<D::Category>) -> () { let mut response = client .get(format!( ...
use bookwerx_core_rust::db as D; use rocket::http::Status; use rocket::local::Client; use bookwerx_core_rust::dfp::dfp::{DFP, Sign, dfp_abs, dfp_add};
pub fn category_dist_sums(client: &Client, apikey: &String, categories: &Vec<D::Category>) -> () { let mut response = client .get(format!( "/category_dist_sums?apikey={}&category_id=666", &apikey )) .dispatch(); let mut r: D::Sums = serde_json::from_str(&(res...
function_block-full_function
[ { "content": "use bookwerx_core_rust::db as D;\n\nuse rocket::http::Status;\n\nuse rocket::local::Client;\n\nuse bookwerx_core_rust::dfp::dfp::{DFP, Sign};\n\n\n", "file_path": "tests/account_dist_sum.rs", "rank": 0, "score": 8.044035556254066 }, { "content": "use bookwerx_core_rust::dfp::df...
Rust
src/vdac0/opa2_cal.rs
timokroeger/efm32pg12-pac
bbe43a716047334a3cd51de8e0e3d51280497689
#[doc = "Reader of register OPA2_CAL"] pub type R = crate::R<u32, super::OPA2_CAL>; #[doc = "Writer for register OPA2_CAL"] pub type W = crate::W<u32, super::OPA2_CAL>; #[doc = "Register OPA2_CAL `reset()`'s with value 0x80e7"] impl crate::ResetValue for super::OPA2_CAL { type Type = u32; #[inline(always)] ...
#[doc = "Reader of register OPA2_CAL"] pub type R = crate::R<u32, super::OPA2_CAL>; #[doc = "Writer for register OPA2_CAL"] pub type W = crate::W<u32, super::OPA2_CAL>; #[doc = "Register OPA2_CAL `reset()`'s with value 0x80e7"] impl crate::ResetValue for super::OPA2_CAL { type Type = u32; #[inline(always)] ...
self } } #[doc = "Bits 17:18 - Gm3 Trim Value"] #[inline(always)] pub fn gm3(&mut self) -> GM3_W { GM3_W { w: self } } #[doc = "Bits 20:24 - OPAx Non-Inverting Input Offset Configuration Value"] #[inline(always)] pub fn offsetp(&mut self) -> OFFSETP_W { OFFSETP_W { w: sel...
[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 17)) | (((value as u32) & 0x03) << 17); self.w } } #[doc = "Reader of field `OFFSETP`"] pub type OFFSETP_R = crate::R<u8, u8>; #[doc = "Write proxy for field `OFFSETP`"] pub struct OFFSETP_...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/uu/sort/src/merge.rs
oconnor663/coreutils
c7930a63f7221a6b0e3791c15529e6b10de07ef2
use std::{ cmp::Ordering, ffi::OsStr, io::{Read, Write}, iter, rc::Rc, sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}, thread, }; use compare::Compare; use crate::{ chunks::{self, Chunk}, compare_by, open, GlobalSettings, }; pub fn merge<'a>(files: &[impl AsRe...
use std::{ cmp::Ordering, ffi::OsStr, io::{Read, Write}, iter, rc::Rc, sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}, thread, }; use compare::Compare; use crate::{ chunks::{self, Chunk}, compare_by, open, GlobalSettings, }; pub fn merge<'a>(files: &[impl AsRe...
; if cmp == Ordering::Equal { cmp = a.file_number.cmp(&b.file_number); } cmp.reverse() } }
compare_by( &a.current_chunk.borrow_lines()[a.line_idx], &b.current_chunk.borrow_lines()[b.line_idx], self.settings, )
call_expression
[ { "content": "/// Write the lines in `chunk` to `file`, separated by `separator`.\n\nfn write(chunk: &mut Chunk, file: &Path, separator: u8) {\n\n chunk.with_lines_mut(|lines| {\n\n // Write the lines to the file\n\n let file = crash_if_err!(1, OpenOptions::new().create(true).write(true).open(f...
Rust
router/src/dml_handlers/partitioner.rs
r4ntix/influxdb_iox
5ff874925101e2afbafa6853385260a2ba044394
use super::DmlHandler; use async_trait::async_trait; use data_types::{DatabaseName, DeletePredicate, PartitionTemplate}; use hashbrown::HashMap; use mutable_batch::{MutableBatch, PartitionWrite, WritePayload}; use observability_deps::tracing::*; use thiserror::Error; use trace::ctx::SpanContext; #[derive(Debug, Error)...
use super::DmlHandler; use async_trait::async_trait; use data_types::{DatabaseName, DeletePredicate, PartitionTemplate}; use hashbrown::HashMap; use mutable_batch::{MutableBatch, PartitionWrite, WritePayload}; use observability_deps::tracing::*; use thiserror::Error; use trace::ctx::SpanContext; #[derive(Debug, Error)...
; let table_batch = partition .raw_entry_mut() .from_key(&table_name) .or_insert_with(|| (table_name.to_owned(), MutableBatch::default())); partition_payload.write_to_batch(table_batch.1)?; } } Ok(p...
Map::default(); for (table_name, batch) in batch { for (partition_key, partition_payload) in PartitionWrite::partition(&table_name, &batch, &self.partition_template) { let partition = partitions.entry(partition_key).or_default()
function_block-random_span
[]
Rust
07-rust/stm32f446/stm32f446_pac/src/rcc/cr.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register CR"] pub type R = crate::R<u32, super::CR>; #[doc = "Writer for register CR"] pub type W = crate::W<u32, super::CR>; #[doc = "Register CR `reset()`'s with value 0x83"] impl crate::ResetValue for super::CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
#[doc = "Reader of register CR"] pub type R = crate::R<u32, super::CR>; #[doc = "Writer for register CR"] pub type W = crate::W<u32, super::CR>; #[doc = "Register CR `reset()`'s with value 0x83"] impl crate::ResetValue for super::CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
18) & 0x01) != 0) } #[doc = "Bit 17 - HSE clock ready flag"] #[inline(always)] pub fn hserdy(&self) -> HSERDY_R { HSERDY_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - HSE clock enable"] #[inline(always)] pub fn hseon(&self) -> HSEON_R { HSEON_R::new(((self....
} } #[doc = "Reader of field `HSIRDY`"] pub type HSIRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `HSION`"] pub type HSION_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HSION`"] pub struct HSION_W<'a> { w: &'a mut W, } impl<'a> HSION_W<'a> { #[doc = r"Sets the field bit"] #[inline(a...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
06/chronal-manhattan/src/main.rs
mnem/advent-of-code-2018
f2f5821d29fcf111ef4c1ff963bc4636626781f6
extern crate regex; use std::fs; use std::cmp; use regex::Regex; fn main() { let input = read_input(); let result = process(&input); println!("Result: {}\n", result); } fn read_input() -> String { let input_filename = String::from("input.txt"); fs::read_to_string(input_filename) .expect("...
extern crate regex; use std::fs; use std::cmp; use regex::Regex; fn main() { let input = read_input(); let result = process(&input); println!("Result: {}\n", result); } fn read_input() -> String { let input_filename = String::from("input.txt"); fs::read_to_string(input_filename) .expect("...
te(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, 0, -1, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, ...
} fn from_lines(lines: &str) -> Vec<Point> { let mut points = Vec::new(); for line in lines.lines() { let line = line.trim(); if line.len() == 0 { continue; } points.push(Point::from_string(line)); } return points; ...
random
[ { "content": "fn scored_grid_from(point: Point, extent_x: usize, extend_y: usize) -> Vec<i32> {\n\n let mut scores = Vec::new();\n\n for y in 0..extend_y {\n\n for x in 0..extent_x {\n\n let score = ((y as i32) - point.y).abs() + ((x as i32) - point.x).abs();\n\n scores.push(s...
Rust
src/commands/kv/bucket/sync.rs
aleclarson/wrangler
37d0506a845d6122190b0a43865a59e839347c1b
use std::collections::HashSet; use std::fs::metadata; use std::iter::FromIterator; use std::path::Path; use cloudflare::endpoints::workerskv::write_bulk::KeyValuePair; use crate::commands::kv; use crate::commands::kv::bucket::directory_keys_only; use crate::commands::kv::bucket::directory_keys_values; use crate::comm...
use std::collections::HashSet; use std::fs::metadata; use std::iter::FromIterator; use std::path::Path; use cloudflare::endpoints::workerskv::write_bulk::KeyValuePair; use crate::commands::kv; use crate::commands::kv::bucket::directory_keys_only; use crate::commands::kv::bucket::directory_keys_values; use crate::comm...
fn check_kv_pairs_equality(expected: Vec<KeyValuePair>, actual: Vec<KeyValuePair>) { assert!(expected.len() == actual.len()); for (idx, pair) in expected.into_iter().enumerate() { assert!(pair.key == actual[idx].key); asse...
ys = HashSet::new(); exclude_keys.insert(key_a_old.clone()); exclude_keys.insert(key_b_old); let pairs_to_upload = vec![ KeyValuePair { key: key_a_old, value: "old".to_string(), expiration_ttl: None, expiratio...
function_block-function_prefixed
[ { "content": "pub fn create_secret(name: &str, user: &GlobalUser, target: &Target) -> Result<(), failure::Error> {\n\n validate_target(target)?;\n\n\n\n let secret_value = interactive::get_user_input(&format!(\n\n \"Enter the secret text you'd like assigned to the variable {} on the script named {}...
Rust
rust/src/cosmos/crypto/multisig.rs
PFC-Validator/terra.proto
4939cca497ba641046d18546dd234fd33a3f61c6
#![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_...
#![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_...
d }, |m: &mut CompactBitArray| { &mut m.extra_bits_stored }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "elems", |m: &CompactBitArray| { &m.elems }, |m: &mut...
ze += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { for v in &self.signatures { os.write_bytes(1, &...
random
[ { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "rust/src/tendermint/crypto/proof.rs", "rank": 0, "score": 222119.91363063856 }, {...
Rust
tss-esapi/tests/integration_tests/context_tests/tpm_commands/non_volatile_storage_tests.rs
Superhepper/rust-tss-esapi
a6ae84793e73b10dd672b613ada820566c84fe85
mod test_nv_define_space { use crate::common::create_ctx_with_session; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision}, nv::storage::NvPublicBuilder, }; #[test...
mod test_nv_define_space { use crate::common::create_ctx_with_session; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision}, nv::storage::NvPublicBuilder, }; #[test...
} mod test_nv_undefine_space { use crate::common::create_ctx_with_session; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision}, nv::storage::NvPublicBuilder, }; #[...
t owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) ...
function_block-function_prefixed
[ { "content": "fn write_nv_index(context: &mut Context, nv_index: NvIndexTpmHandle) -> NvIndexHandle {\n\n // Create owner nv public.\n\n let owner_nv_index_attributes = NvIndexAttributesBuilder::new()\n\n .with_owner_write(true)\n\n .with_owner_read(true)\n\n .with_pp_read(true)\n\n ...
Rust
src/syntax/src/statement.rs
isaacazuelos/kurt
f86c3230d9d0cd54b307eda27e3ddbb4c145d1f0
use parser::Parse; use crate::lexer::{Reserved, TokenKind}; use super::*; #[derive(Debug)] pub enum Statement<'a> { Binding(Binding<'a>), Empty(Span), Expression(Expression<'a>), If(IfOnly<'a>), } impl<'a> Syntax for Statement<'a> { fn span(&self) -> Span { match self { Sta...
use parser::Parse; use crate::lexer::{Reserved, TokenKind}; use super::*; #[derive(Debug)] pub enum Statement<'a> { Binding(Binding<'a>), Empty(Span), Expression(Expression<'a>), If(IfOnly<'a>), } impl<'a> Syntax for Statement<'a> {
} impl<'a> Parse<'a> for Statement<'a> { type SyntaxError = SyntaxError; fn parse_with(parser: &mut Parser<'a>) -> SyntaxResult<Statement<'a>> { match parser.peek_kind() { Some(TokenKind::Semicolon) => { Ok(Statement::Empty(parser.next_span())) } S...
fn span(&self) -> Span { match self { Statement::Binding(b) => b.span(), Statement::Empty(s) => *s, Statement::Expression(s) => s.span(), Statement::If(i) => i.span(), } }
function_block-full_function
[]
Rust
component/src/desktop_window.rs
rohankumardubey/makepad
2248d20bd8e1431616acc89846a841abc36dffb7
use makepad_render::*; use crate::desktop_button::*; use crate::window_menu::*; use crate::button_logic::*; live_register!{ use crate::theme::*; DesktopWindow: {{DesktopWindow}} { clear_color: (COLOR_WINDOW_BG) caption_bg: {color: (COLOR_WINDOW_CAPTION)} caption: "Desktop Window", ...
use makepad_render::*; use crate::desktop_button::*; use crate::window_menu::*; use crate::button_logic::*; live_register!{ use crate::theme::*; DesktopWindow: {{DesktopWindow}} { clear_color: (COLOR_WINDOW_BG) caption_bg: {color: (COLOR_WINDOW_CAPTION)} caption: "Desktop Window", ...
}
p_button(cx, DesktopButtonType::XRMode); } self.main_view.end(cx); self.pass.end(cx); self.window.end(cx); }
function_block-function_prefixed
[ { "content": "pub fn new_cxthread(&mut self) -> CxThread {\n\n CxThread {cx: self as *mut _ as u64}\n\n }\n\n \n\n pub fn get_mapped_texture_user_data(&mut self, texture: &Texture) -> Option<usize> {\n\n if let Some(texture_id) = texture.texture_id {\n\n let cxtexture = &self.t...
Rust
src/main.rs
jeff-lund/Molecule
c37aeffce87abea007a56b82ed0d1cd474cb8530
#![allow(dead_code)] #![allow(unused_assignments)] #![allow(unused_variables)] mod utility; use utility::*; mod atoms; use atoms::*; use std::env::args; use std::fs::File; use std::io::prelude::*; const DEBUG: bool = false; const MAX_GENERATIONS: u32 = 200; fn pprint (molecule: &Molecule, atoms: &Vec<&str>, peaks: &...
#![allow(dead_code)] #![allow(unused_assignments)] #![allow(unused_variables)] mod utility; use utility::*; mod atoms; use atoms::*; use std::env::args; use std::fs::File; use std::io::prelude::*; const DEBUG: bool = false; const MAX_GENERATIONS: u32 = 200; fn pprint (molecule: &Molecule, atoms: &Vec<&str>, peaks: &...
fn main() -> std::io::Result<()> { let f = args().nth(1).expect("No file argument given"); let mut file = File::open(f)?; let mut buffer = String::new(); file.read_to_string(&mut buffer)?; let mut b = buffer.lines(); let chemical_formula = parse_elemental_analysis(b.next().expect("i...
print!("Experimental Chemical Shifts: {}", peaks[0]); for entry in peaks.iter().skip(1) { print!(", {}", entry); } println!(""); }
function_block-function_prefix_line
[ { "content": "/// Validate the overall correctness of a chromosome\n\nfn validate_chromosome(chromosome: &Chromosome, atoms: &Vec<&str>, num_bonds: u32) -> bool {\n\n // check proper number of bonds exist\n\n let bonds: u32 = chromosome.iter().sum();\n\n if bonds != num_bonds {\n\n return false;...
Rust
src/hotkey_config.rs
Ynscription/livesplit-core
1027a92faaf8eeb14ce8be8a32ce8d3f202bc664
#![allow(clippy::trivially_copy_pass_by_ref)] use crate::hotkey::KeyCode; use crate::platform::prelude::*; use crate::settings::{Field, SettingsDescription, Value}; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] #[serde(default)] pub struct HotkeyConfig...
#![allow(clippy::trivially_copy_pass_by_ref)] use crate::hotkey::KeyCode; use crate::platform::prelude::*; use crate::settings::{Field, SettingsDescription, Value}; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] #[serde(default)] pub struct HotkeyConfig...
on = value, 8 => self.toggle_timing_method = value, _ => panic!("Unsupported Setting Index"), } Ok(()) } #[cfg(feature = "std")] pub fn from_json<R>(reader: R) -> serde_json::Result<Self> where R: std::io::Read, { serde_json::from_reader...
(NumPad2), pause: Some(NumPad5), undo_all_pauses: None, previous_comparison: Some(NumPad4), next_comparison: Some(NumPad6), toggle_timing_method: None, } } } #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] impl Default for HotkeyConfig ...
random
[ { "content": "/// Registers a clock as the global handler for providing the high precision\n\n/// time stamps on a `no_std` target.\n\npub fn register_clock(clock: impl Clock) {\n\n let clock: Box<dyn Clock> = Box::new(clock);\n\n let clock = Box::new(clock);\n\n // FIXME: This isn't entirely clean as ...
Rust
sqldb/rust/src/sqldb.rs
thomastaylor312/interfaces
621d0d88772db85591d8625cca82264799e6ef64
#![allow(unused_imports, clippy::ptr_arg, clippy::needless_lifetimes)] use async_trait::async_trait; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, io::Write, string::ToString}; use wasmbus_rpc::{ deserialize, serialize, Context, Message, MessageDispatch, RpcError, RpcResult, SendOpts, Timestamp,...
#![allow(unused_imports, clippy::ptr_arg, clippy::needless_lifetimes)] use async_trait::async_trait; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, io::Write, string::ToString}; use wasmbus_rpc::{ deserialize, serialize, Context, Message, MessageDispatch, RpcError, RpcResult, SendOpts, Timestamp,...
} #[derive(Debug)] pub struct SqlDbSender<T: Transport> { transport: T, } impl<T: Transport> SqlDbSender<T> { pub fn via(transport: T) -> Self { Self { transport } } pub fn set_timeout(&self, interval: std::time::Duration) { self.transport.set_timeout(interval); } } #[cfg(t...
map_err(|e| RpcError::Deser(format!("message '{}': {}", message.method, e)))?; let resp = SqlDb::fetch(self, ctx, &value).await?; let buf = serialize(&resp)?; Ok(Message { method: "SqlDb.Fetch", arg: Cow::Owned(buf), ...
function_block-function_prefix_line
[ { "content": "#[doc(hidden)]\n\n#[async_trait]\n\npub trait KeyValueReceiver: MessageDispatch + KeyValue {\n\n async fn dispatch(&self, ctx: &Context, message: &Message<'_>) -> RpcResult<Message<'_>> {\n\n match message.method {\n\n \"Increment\" => {\n\n let value: Increment...
Rust
src/usbdcd/control/mod.rs
Meptl/mk20d7
c7cd01cf55214b0b53fae7c7672607e739b64663
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CONTROL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w m...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CONTROL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w m...
#[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> IFR { match value { false => IFR::_0, true => IFR::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline] pub fn is_0(&self) -> bool { *self == IFR...
pub fn bit(&self) -> bool { match *self { IFR::_0 => false, IFR::_1 => true, } }
function_block-full_function
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
src/utils/redis/pubsub.rs
greglearns/portier-broker
935fcce0405fd0e3ac70ee8922c0f62bf0823a75
use futures_util::future::poll_fn; use redis::{ConnectionAddr, ConnectionInfo, ErrorKind, RedisError, RedisResult, Value}; use std::collections::hash_map::{Entry, HashMap}; use std::future::Future; use std::io::Result as IoResult; use std::net::ToSocketAddrs; use std::pin::Pin; use std::task::Poll; use tokio::io::{self...
use futures_util::future::poll_fn; use redis::{ConnectionAddr, ConnectionInfo, ErrorKind, RedisError, RedisResult, Value}; use std::collections::hash_map::{Entry, HashMap}; use std::future::Future; use std::io::Result as IoResult; use std::net::ToSocketAddrs; use std::pin::Pin; use std::task::Poll; use tokio::io::{self...
} panic!("Tried to subscribe on closed pubsub connection"); } } pub async fn connect(info: &ConnectionInfo) -> RedisResult<Subscriber> { let (rx, tx): ( Box<dyn io::AsyncRead + Unpin + Send>, Box<dyn io::AsyncWrite + Unpin + Send>, ) = match *info.addr { ConnectionAdd...
reply: reply_tx, }; if self.cmd.send(cmd).await.is_ok() { if let Ok(rx) = reply_rx.await { return rx; }
function_block-random_span
[ { "content": "#[inline]\n\npub fn decode<T: ?Sized + AsRef<[u8]>>(data: &T) -> Result<Vec<u8>, ()> {\n\n base64::decode_config(data, base64::URL_SAFE_NO_PAD).map_err(|_| ())\n\n}\n", "file_path": "src/utils/base64url.rs", "rank": 2, "score": 202123.42041081307 }, { "content": "/// Parse a...
Rust
src/util.rs
HEnquist/flexi_logger
5a89eb567d35a7821b682e95e9328859b133c042
use crate::{deferred_now::DeferredNow, FormatFunction}; use log::Record; use std::cell::RefCell; use std::io::Write; #[cfg(test)] use std::io::Cursor; #[cfg(test)] use std::sync::{Arc, Mutex}; #[cfg(feature = "async")] pub(crate) const ASYNC_FLUSH: &[u8] = b"F"; #[cfg(feature = "async")] pub(crate) const ASYNC_SHUTDO...
use crate::{deferred_now::DeferredNow, FormatFunction}; use log::Record; use std::cell::RefCell; use std::io::Write; #[cfg(test)] use std::io::Cursor; #[cfg(test)] use std::sync::{Arc, Mutex}; #[cfg(feature = "async")] pub(crate) const ASYNC_FLUSH: &[u8] = b"F"; #[cfg(feature = "async")] pub(crate) const ASYNC_SHUTDO...
; result }
buffer_with(|tl_buf| match tl_buf.try_borrow_mut() { Ok(mut buffer) => { (format_function)(&mut *buffer, now, record) .unwrap_or_else(|e| eprint_err(ERRCODE::Format, "formatting failed", &e)); buffer .write_all(b"\n") .unwrap_or_else(|e| ep...
call_expression
[ { "content": "fn push_err(s: &str, parse_errs: &mut String) {\n\n if !parse_errs.is_empty() {\n\n parse_errs.push_str(\"; \");\n\n }\n\n parse_errs.push_str(s);\n\n}\n\n\n", "file_path": "src/log_specification.rs", "rank": 0, "score": 184303.19247900957 }, { "content": "fn co...
Rust
src/tools/clippy/clippy_lints/src/needless_arbitrary_self_type.rs
ohno418/rust
395a09c3dafe0c7838c9ca41d2b47bb5e79a5b6d
use clippy_utils::diagnostics::span_lint_and_sugg; use if_chain::if_chain; use rustc_ast::ast::{BindingMode, Lifetime, Mutability, Param, PatKind, Path, TyKind}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym...
use clippy_utils::diagnostics::span_lint_and_sugg; use if_chain::if_chain; use rustc_ast::ast::{BindingMode, Lifetime, Mutability, Param, PatKind, Path, TyKind}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::sym...
e of the `self` parameter does not need to be arbitrary", "consider to change this parameter to", self_param, applicability, ) } } } impl EarlyLintPass for NeedlessArbitrarySelfType { fn check_param(&mut self, cx: &EarlyContext<'_>, p: &Param)...
".to_string(), }; span_lint_and_sugg( cx, NEEDLESS_ARBITRARY_SELF_TYPE, span, "the typ
random
[]
Rust
storage/aptosdb/src/pruner/mod.rs
JoshLind/aptos-core
a58a87106bde10eccb8954128cd31700b76e95c1
mod db_pruner; pub(crate) mod db_sub_pruner; pub(crate) mod event_store; mod ledger_store; pub(crate) mod state_store; pub(crate) mod transaction_store; pub mod utils; pub(crate) mod worker; use crate::metrics::APTOS_STORAGE_PRUNE_WINDOW; use aptos_config::config::StoragePrunerConfig; use aptos_infallible::Mutex; ...
mod db_pruner; pub(crate) mod db_sub_pruner; pub(crate) mod event_store; mod ledger_store; pub(crate) mod state_store; pub(crate) mod transaction_store; pub mod utils; pub(crate) mod worker; use crate::metrics::APTOS_STORAGE_PRUNE_WINDOW; use aptos_config::config::StoragePrunerConfig; use aptos_infallible::Mutex; ...
} impl Drop for Pruner { fn drop(&mut self) { self.command_sender .lock() .send(Command::Quit) .expect("Receiver should not destruct."); self.worker_thread .take() .expect("Worker thread must exist.") .join() .expe...
let least_readable_state_store_version = latest_version - self.state_store_prune_window; const TIMEOUT: Duration = Duration::from_secs(10); let end = Instant::now() + TIMEOUT; while Instant::now() < end { if *self .least_readable_vers...
function_block-function_prefix_line
[ { "content": "/// Fetches the latest synced version from the specified storage\n\npub fn fetch_latest_synced_version(storage: Arc<dyn DbReader>) -> Result<Version, Error> {\n\n let latest_transaction_info =\n\n storage\n\n .get_latest_transaction_info_option()\n\n .map_err(|error...
Rust
src/basic/constpool.rs
orasunis/jbcrs
723185189c8422b1a1d1eb3a0bacb59ed00cf00a
use std::hash::{Hash, Hasher}; use std::collections::HashMap; use std::cmp::{Eq, PartialEq}; use std::rc::Rc; use std::slice::Iter; use result::*; #[derive(Debug, Clone)] pub enum Item { UTF8(String), Integer(i32), Float(f32), Long(i64), Double(f64), ...
use std::hash::{Hash, Hasher}; use std::collections::HashMap; use std::cmp::{Eq, PartialEq}; use std::rc::Rc; use std::slice::Iter; use result::*; #[derive(Debug, Clone)] pub enum Item { UTF8(String), Integer(i32), Float(f32), Long(i64), Double(f64), ...
pub fn iter(&self) -> PoolIter { PoolIter { iter: self.by_index.iter(), index: 0, } } } pub struct PoolIter<'a> { iter: Iter<'a, Option<Rc<Item>>>, index: u16, } impl<'a> Iterator for PoolIter<'a> { type Item = (u16, &'a Item); fn next(&mut self) -> O...
pub fn push(&mut self, item: Item) -> Result<u16> { if self.len() == u16::max_value() { return Err(Error::CPTooLarge); } let double = item.is_double(); let length = &mut self.length; let rc_item = Rc::new(item); let rc_item1 = Rc::clone(&rc_item); l...
function_block-full_function
[ { "content": "/// Parses the class file, which is represented as a byte array.\n\n/// The constant pool and the class is returned, if no error occurred.\n\npub fn parse(input: &[u8]) -> Result<(Pool, Class)> {\n\n // create a new decoder from the byte array\n\n let mut cursor = 0;\n\n let mut decoder =...
Rust
tests/builder.rs
denzp/rust-ptx-builder
4b5bb6845674417d04f3cba48ba0cda6f5c4772a
use std::env; use std::env::current_dir; use std::fs::{remove_dir_all, File}; use std::io::prelude::*; use std::path::PathBuf; use antidote::Mutex; use lazy_static::*; use ptx_builder::error::*; use ptx_builder::prelude::*; lazy_static! { static ref ENV_MUTEX: Mutex<()> = Mutex::new(()); } #[test] fn should_pro...
use std::env; use std::env::current_dir; use std::fs::{remove_dir_all, File}; use std::io::prelude::*; use std::path::PathBuf; use antidote::Mutex; use lazy_static::*; use ptx_builder::error::*; use ptx_builder::prelude::*; lazy_static! { static ref ENV_MUTEX: Mutex<()> = Mutex::new(()); } #[test] fn should_pro...
n cleanup_temp_location() { let crate_names = &[ "faulty_ptx_crate", "sample_app_ptx_crate", "sample_ptx_crate", "mixed_crate", ]; for name in crate_names { remove_dir_all(env::temp_dir().join("ptx-builder-0.5").join(name)).unwrap_or_default(); } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn should_provide_output_path() {\n\n let source_crate = Crate::analyse(\"tests/fixtures/sample-crate\").unwrap();\n\n\n\n assert!(source_crate.get_output_path().unwrap().starts_with(\n\n env::temp_dir()\n\n .join(\"ptx-builder-0.5\")\n\n .join(\"sampl...
Rust
src/collector.rs
playXE/test
50fae1922ef116908d09cdf81b301c153e980416
use super::{allocation::ImmixSpace, block::ImmixBlock, constants::*, CollectionType}; use crate::{large_object_space::LargeObjectSpace, object::*, util::*}; use alloc::collections::VecDeque; use core::ptr::NonNull; use vec_map::VecMap; pub struct ImmixCollector; pub struct Visitor<'a> { immix_space: &'a mut ImmixS...
use super::{allocation::ImmixSpace, block::ImmixBlock, constants::*, CollectionType}; use crate::{large_object_space::LargeObjectSpace, object::*, util::*}; use alloc::collections::VecDeque; use core::ptr::NonNull; use vec_map::VecMap; pub struct ImmixCollector; pub struct Visitor<'a> { immix_space: &'a mut ImmixS...
fn sweep_all_blocks(&mut self) -> (Vec<*mut ImmixBlock>, Vec<*mut ImmixBlock>) { let mut unavailable_blocks = Vec::new(); let mut recyclable_blocks = Vec::new(); let mut free_blocks = Vec::new(); for block in self.all_blocks.drain(..) { if unsafe { (*...
pub fn collect( &mut self, collection_type: &CollectionType, roots: &[*mut RawGc], precise_roots: &[*mut *mut RawGc], immix_space: &mut ImmixSpace, large_object_space: &mut LargeObjectSpace, next_live_mark: bool, ) -> usize { for block in &mut...
function_block-full_function
[ { "content": "/// Check if `mem` is aligned for precise allocation\n\npub fn is_aligned_for_precise_allocation(mem: *mut u8) -> bool {\n\n let allocable_ptr = mem as usize;\n\n (allocable_ptr & (PreciseAllocation::ALIGNMENT - 1)) == 0\n\n}\n\n/// This space contains objects which are larger than the size ...
Rust
frontend/apps/crates/utils/src/components/module_page.rs
Sheng-Long/ji-cloud
d12741467eb5d0ae15e3cece9d3428ef9d0050e3
/* There are a few fundamental concepts going on here... * 1. The serialized data does _not_ need to be Clone. * rather, it's passed completely to the child * and then the child is free to split it up for Mutable/etc. * (here it is held and taken from an Option) * 2. The loader will be skipped if the url ...
/* There are a few fundamental concepts going on here... * 1. The serialized data does _not_ need to be Clone. * rather, it's passed completely to the child * and then the child is free to split it up for Mutable/etc. * (here it is held and taken from an Option) * 2. The loader will be skipped if the url ...
data)) } else { None } }))) }) .with_node!(elem => { .global_event(clone!(_self => move |evt:events::Resize| { ModuleBounds::set( ...
:Rc<Self>) -> Self::Data; fn render(_self: Rc<Self>, data: Self::Data) -> Dom; } pub struct ModulePage<T, R> where T: DeserializeOwned, R: ModuleRenderer<Data = T>, { renderer: Rc<R>, loaded_data: RefCell<Option<T>>, has_loaded_data: Mutable<bool>, wait_iframe_data: bool, loader: Asy...
random
[ { "content": "pub fn image_edit_category_child(name:&str) -> HtmlElement {\n\n TEMPLATES.with(|t| t.cache.render_elem(IMAGE_EDIT_CATEGORIES_CHILD, &html_map!{\n\n \"name\" => name\n\n }).unwrap_throw())\n\n}\n", "file_path": "frontend/apps/crates/entry/admin/src/templates.rs", "rank": 0, ...
Rust
crates/augmented/application/audio-processor-standalone/src/options.rs
yamadapc/augmented-audio
2f662cd8aa1a0ba46445f8f41c8483ae2dc552d3
use std::ffi::OsString; use clap::ArgMatches; pub enum RenderingOptions { Online { input_file: Option<String>, }, Offline { input_file: String, output_file: String, }, } pub struct MidiOptions { pub input_file: Option<String>, } pub struct Options { midi: MidiOptions,...
use std::ffi::OsString; use clap::ArgMatches; pub enum RenderingOptions { Online { input_file: Option<String>, }, Offline { input_file: String, output_file: String, }, } pub struct MidiOptions { pub input_file: Option<String>, } pub struct Options { midi: MidiOptions,...
fn parse_midi_options(matches: &ArgMatches) -> MidiOptions { MidiOptions { input_file: matches.value_of("midi-input-file").map(|s| s.into()), } } fn parse_rendering_options(matches: &ArgMatches) -> RenderingOptions { if matches.is_present("output-file") { if !matches.is_present("input-fil...
fn parse_options_from<I, T>(supports_midi: bool, args: I) -> Options where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, { let app = clap::App::new("audio-processor-standalone"); let mut app = app .arg(clap::Arg::from_usage( "-i, --input-file=[INPUT_PATH] 'An input audio file...
function_block-function_prefix_line
[ { "content": "pub fn render_to_xml<C: Component>(mut root: C) -> String {\n\n use xml::writer::{EmitterConfig, EventWriter, XmlEvent};\n\n\n\n let bytes = Vec::new();\n\n let buf_sink = BufWriter::new(bytes);\n\n let mut writer = EmitterConfig::new()\n\n .perform_indent(true)\n\n .crea...
Rust
stm32-gen-features/src/lib.rs
topisani/embassy
43a7226d8b8e5a2dabae8afbaf9e81651b59ca6e
use std::{iter::FilterMap, path::Path, slice::Iter}; const SUPPORTED_FAMILIES: [&str; 10] = [ "stm32f0", "stm32f1", "stm32f4", "stm32g0", "stm32l0", "stm32l1", "stm32l4", "stm32h7", "stm32wb55", "stm32wl55", ]; const SEPARATOR_START: &str = "# BEGIN GENERATED FEATURES\n"; con...
use std::{iter::FilterMap, path::Path, slice::Iter}; const SUPPORTED_FAMILIES: [&str; 10] = [ "stm32f0", "stm32f1", "stm32f4", "stm32g0", "stm32l0", "stm32l1", "stm32l4", "stm32h7", "stm32wb55", "stm32wl55", ]; const SEPARATOR_START: &str = "# BEGIN GENERATED FEATURES\n"; con...
}
fn does_not_generate_if_separators_are_missing() { let initial = "\ before # END GENERATED FEATURES after "; let new_contents = String::from("a = [\"b\"]\n"); generate_cargo_toml_file(initial, &new_contents); }
function_block-full_function
[ { "content": "/// Update a Cargo.toml file\n\n///\n\n/// Update the content between \"# BEGIN GENERATED FEATURES\" and \"# END GENERATED FEATURES\"\n\n/// with the given content\n\nfn update_cargo_file(path: &str, new_contents: &str) {\n\n let previous_text = std::fs::read_to_string(path).unwrap();\n\n le...
Rust
identity-account/src/account/builder.rs
charlesthompson3/identity.rs
713140734e86a4b11f85921009b491ff28b5cd10
#[cfg(feature = "stronghold")] use std::path::PathBuf; use std::sync::Arc; #[cfg(feature = "stronghold")] use zeroize::Zeroize; use identity_account_storage::storage::MemStore; use identity_account_storage::storage::Storage; #[cfg(feature = "stronghold")] use identity_account_storage::storage::Stronghold; use ident...
#[cfg(feature = "stronghold")] use std::path::PathBuf; use std::sync::Arc; #[cfg(feature = "stronghold")] use zeroize::Zeroize; use identity_account_storage::storage::MemStore; use identity_account_storage::storage::Storage; #[cfg(feature = "stronghold")] use identity_account_storage::storage::Stronghold; use ident...
#[must_use] pub fn autosave(mut self, value: AutoSave) -> Self { self.config = self.config.autosave(value); self } #[must_use] pub fn autopublish(mut self, value: bool) -> Self { self.config = self.config.autopublish(value); self } #[cfg(test)] #[must_use] p...
ccountConfig::new(), storage_template: Some(AccountStorage::Memory), storage: Some(Arc::new(MemStore::new())), client_builder: None, client: None, } }
function_block-function_prefixed
[ { "content": "// implement Debug on the Enum from the `InputModel`.\n\npub fn impl_debug_enum(input: &InputModel) -> TokenStream {\n\n // collect appropriate data and generate param declarations.\n\n let diff: &Ident = input.diff();\n\n let evariants: &Vec<EVariant> = input.e_variants();\n\n\n\n let param_d...
Rust
integration_test/src/transactional_event_stream_writer_tests.rs
claudiofahey/pravega-client-rust
efaccc1ba896588ffb125cd72378b07f714609e5
use pravega_client::event_stream_writer::EventStreamWriter; use pravega_client_config::{ClientConfigBuilder, MOCK_CONTROLLER_URI}; use pravega_client_shared::*; use pravega_connection_pool::connection_pool::ConnectionPool; use pravega_controller_client::{ControllerClient, ControllerClientImpl}; use pravega_wire_proto...
use pravega_client::event_stream_writer::EventStreamWriter; use pravega_client_config::{ClientConfigBuilder, MOCK_CONTROLLER_URI}; use pravega_client_shared::*; use pravega_connection_pool::connection_pool::ConnectionPool; use pravega_controller_client::{ControllerClient, ControllerClientImpl}; use pravega_wire_proto...
let cmd = GetStreamSegmentInfoCommand { request_id: 0, segment_name: segment.to_string(), delegation_token: delegation_toke_provider .retrieve_token(factory.get_controller_client()) .await, }; let request = Requests::GetStreamSegmentInfo(cmd); let rawclie...
let delegation_toke_provider = factory .create_delegation_token_provider(ScopedStream::from(segment)) .await;
assignment_statement
[ { "content": "fn test_simple_write_and_read(writer: &mut ByteStreamWriter, reader: &mut ByteStreamReader) {\n\n info!(\"test byte stream write and read\");\n\n let payload1 = vec![1; 4];\n\n let payload2 = vec![2; 4];\n\n\n\n let size1 = writer.write(&payload1).expect(\"write payload1 to byte stream...
Rust
cs39/src/size_test.rs
gretchenfrage/CS639S20_Demos
d75a16cf66b6b95eb74fc8f101020672b62e5a90
use crate::{ cap_parse, navigate::{ DemoLookup, find_demo, }, compile::{ cpp_files, modify_compile, Compiled, }, output::{ INFO_INDENT, TableWriter, }, quant::{ subproc, demo_min_time, }, }; use std::{ path...
use crate::{ cap_parse, navigate::{ DemoLookup, find_demo, }, compile::{ cpp_files, modify_compile, Compiled, }, output::{ INFO_INDENT, TableWriter, }, quant::{ subproc, demo_min_time,
lone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] #[repr(usize)] pub enum Dim { X, Y } pub fn parse_dim_line(dim: Dim, line: &str) -> Option<u128> { let pat = format!( r#"^{}[[:space:]]+(?P<n>\d+)[[:space:]]*$"#, regex::escape(&format!( r##"#define {}DIM"##, match dim { ...
}, }; use std::{ path::Path, process::Command, mem::replace, collections::HashMap, fs::read_to_string, ffi::OsString, }; use regex::{self, Regex}; use byte_unit::Byte; use serde::Serialize; #[derive(Copy, C
random
[ { "content": "/// Spawn a sub-process, and by the power of threads,\n\n/// elevate its stdout and stderr to the parent while\n\n/// also merging them together into a line stream,\n\n/// then collecting them.\n\npub fn subproc<B>(mut command: B, quiet: bool) -> (ExitStatus, Vec<String>) \n\nwhere\n\n B: Borro...
Rust
rs/registry/canister/tests/tests/add_node_operator.rs
contropist/ic
9240bea7dc0239fcbc5d43ad11f3ca803ee9bb11
use candid::Encode; use dfn_candid::candid; use dfn_core::api::PrincipalId; use ic_nervous_system_common_test_keys::TEST_NEURON_1_OWNER_PRINCIPAL; use ic_nns_test_utils::registry::invariant_compliant_mutation_as_atomic_req; use ic_nns_test_utils::{ itest_helpers::{ forward_call_via_universal_canister, loca...
use candid::Encode; use dfn_candid::candid; use dfn_core::api::PrincipalId; use ic_nervous_system_common_test_keys::TEST_NEURON_1_OWNER_PRINCIPAL; use ic_nns_test_utils::registry::invariant_compliant_mutation_as_atomic_req; use ic_nns_test_utils::{ itest_helpers::{ forward_call_via_universal_canister, loca...
#[test] fn test_a_canister_other_than_the_governance_canister_cannot_add_a_node_operator() { local_test_on_nns_subnet(|runtime| async move { let attacker_canister = set_up_universal_canister(&runtime).await; assert_ne!( attacker_canister.canister_id(), ...
s("is not authorized to call this method: add_node_operator")); let key = make_node_operator_record_key(PrincipalId::new_anonymous()).into_bytes(); assert_eq!( get_value::<NodeOperatorRecord>(&registry, &key).await, NodeOperatorRecord::default() ); Ok((...
function_block-function_prefixed
[ { "content": "fn test_dapp_method_validate_(payload: i64) -> Result<String, String> {\n\n if payload > 10 {\n\n Ok(format!(\"Value is {}. Valid!\", payload))\n\n } else {\n\n Err(\"Value < 10. Invalid!\".to_string())\n\n }\n\n}\n\n\n", "file_path": "rs/sns/integration_tests/test_canis...
Rust
src/banner.rs
nirsarkar/feroxbuster
6921ac03a9a3e08a931bfe160cd4854d76ba6a02
use crate::{config::Configuration, utils::status_colorizer, VERSION}; macro_rules! format_banner_entry_helper { ($rune:expr, $name:expr, $value:expr, $indent:expr, $col_width:expr) => { format!( "\u{0020}{:\u{0020}<indent$}{:\u{0020}<col_w$}\u{2502}\u{0020}{}", $rune, ...
use crate::{config::Configuration, utils::status_colorizer, VERSION}; macro_rules! format_banner_entry_helper { ($rune:expr, $name:expr, $value:expr, $indent:expr, $col_width:expr) => { format!( "\u{0020}{:\u{0020}<indent$}{:\u{0020}<col_w$}\u{2502}\u{0020}{}", $rune, ...
eprintln!("{}", bottom); } #[cfg(test)] mod tests { use super::*; #[test] fn banner_without_targets() { let config = Configuration::default(); initialize(&[], &config); } #[test] fn banner_without_status_codes() { let mut config = Configuration::default...
if !config.norecursion { if config.depth == 0 { eprintln!( "{}", format_banner_entry!("\u{1f503}", "Recursion Depth", "INFINITE") ); } else { eprintln!( "{}", format_banner_entry!("\u{1f503}", "Recursion...
if_condition
[ { "content": "/// simple helper to stay DRY, trys to join a url + fragment and add it to the `links` HashSet\n\nfn add_link_to_set_of_links(link: &str, url: &Url, links: &mut HashSet<String>) {\n\n log::trace!(\n\n \"enter: add_link_to_set_of_links({}, {}, {:?})\",\n\n link,\n\n url.to_s...
Rust
src/cheat.rs
ruabmbua/navi
dc4fe98f5611f40af9f232aaae4b3cfe6058bef5
use crate::display; use crate::filesystem; use crate::option::Config; use regex::Regex; use std::collections::HashMap; use std::fs; use std::io::Write; pub struct SuggestionOpts { pub header_lines: u8, pub column: Option<u8>, pub multi: bool, } pub type Value = (String, Option<SuggestionOpts>); fn gen_s...
use crate::display; use crate::filesystem; use crate::option::Config; use regex::Regex; use std::collections::HashMap; use std::fs; use std::io::Write; pub struct SuggestionOpts { pub header_lines: u8, pub column: Option<u8>, pub multi: bool, } pub type Value = (String, Option<SuggestionOpts>); fn gen_s...
fn parse_variable_line(line: &str) -> (&str, &str, Option<SuggestionOpts>) { let re = Regex::new(r"^\$\s*([^:]+):(.*)").unwrap(); let caps = re.captures(line).unwrap(); let variable = caps.get(1).unwrap().as_str().trim(); let mut command_plus_opts = caps.get(2).unwrap().as_str().split("---"); let ...
let mut header_lines: u8 = 0; let mut column: Option<u8> = None; let mut multi = false; let mut parts = text.split(' '); while let Some(p) = parts.next() { match p { "--multi" => multi = true, "--header" | "--header-lines" => { header_lines = parts.next(...
function_block-function_prefix_line
[ { "content": "pub fn variable_prompt(varname: &str) -> String {\n\n format!(\"{}: \", varname)\n\n}\n\n\n", "file_path": "src/display.rs", "rank": 1, "score": 147276.47230093126 }, { "content": "fn gen_replacement(value: &str) -> String {\n\n if value.contains(' ') {\n\n format!...
Rust
iroha/src/queue.rs
EmelianPiker/iroha
d6097b81572554444b2e9a9a560c581006fc895a
use self::config::QueueConfiguration; use crate::prelude::*; use std::time::Duration; #[derive(Debug)] pub struct Queue { pending_tx: Vec<AcceptedTransaction>, maximum_transactions_in_block: usize, transaction_time_to_live: Duration, } impl Queue { pub fn from_configuration(config: &QueueConfiguration...
use self::config::QueueConfiguration; use crate::prelude::*; use std::time::Duration; #[derive(Debug)] pub struct Queue { pending_tx: Vec<AcceptedTransaction>, maximum_transactions_in_block: usize, transaction_time_to_live: Duration, } impl Queue { pub fn from_configuration(config: &QueueConfiguration...
#[test] fn pop_pending_transactions_with_timeout() { let max_block_tx = 6; let mut queue = Queue::from_configuration(&QueueConfiguration { maximum_transactions_in_block: max_block_tx, transaction_time_to_live_ms: 200, }); for _ in 0..(max_block_tx - 1) {...
fn pop_pending_transactions() { let max_block_tx = 2; let mut queue = Queue::from_configuration(&QueueConfiguration { maximum_transactions_in_block: max_block_tx, transaction_time_to_live_ms: 100000, }); for _ in 0..5 { queue.push_pending_transaction( ...
function_block-full_function
[ { "content": "/// Initializes `Logger` with given `LoggerConfiguration`.\n\n/// After the initialization `log` macros will print with the use of this `Logger`.\n\n/// For more information see [log crate](https://docs.rs/log/0.4.8/log/).\n\npub fn init(configuration: &config::LoggerConfiguration) -> Result<(), S...
Rust
Distributed systems/dsassignment1/solution/lib.rs
rzetelskik/MIMUW
6d193bd6f252a617a275acb1c697bfc983589c0c
use std::time::Duration; use async_channel::{unbounded, Sender, Receiver}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; pub trait Message: Send + 'static {} impl<T: Send + 'static> Message for T {} #[async_trait::async_trait] pub trait Handler<M: Message> where M: Message, { asy...
use std::time::Duration; use async_channel::{unbounded, Sender, Receiver}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; pub trait Message: Send + 'static {} impl<T: Send + 'static> Message for T {} #[async_trait::async_trait] pub trait Handler<M: Message> where M: Message, { asy...
pub async fn new() -> Self { System{ finish: Arc::new(AtomicBool::new(false)), handles: Vec::new(), tick_handles: Vec::new(), rxs: Vec::new(), } } pub async fn shutdown(&mut self) { if self.finish.load(Ordering::Relaxed) { ...
Err(_) => { break; } } } }); self.handles.push(handle); self.rxs.push(Box::new(rx)); ModuleRef{ tx } }
function_block-function_prefix_line
[ { "content": "/// Run the executor.\n\nfn run_executor(rx: Receiver<FibonacciSystemMessage>) -> JoinHandle<()> {\n\n let mut modules: HashMap<Ident, FibonacciModule> = HashMap::new();\n\n\n\n thread::spawn(move || {\n\n while let Ok(msg) = rx.recv() {\n\n match msg {\n\n F...
Rust
src/main.rs
belltoy/raindrop
8e26118026d41da74e899dd1d9af0000301253f5
use std::io::BufRead; use std::path::PathBuf; use glob::glob; use structopt::StructOpt; use log::{debug, info, error}; use pretty_env_logger::env_logger as logger; mod exhaust; mod db; #[derive(StructOpt, Debug)] struct Args { #[structopt(short, long, help = "DONOT execute SQL statements")] check: bool, ...
use std::io::BufRead; use std::path::PathBuf; use glob::glob; use structopt::StructOpt; use log::{debug, info, error}; use pretty_env_logger::env_logger as logger; mod exhaust; mod db; #[derive(StructOpt, Debug)] struct Args { #[structopt(short, long, help = "DONOT execute SQL statements")] check: bool, ...
e(); if result.peek().is_none() { error!("Invalid input argument: {}", p); } result }); let mut unique_inputs = Vec::new(); inputs_paths .flat_map(|p| { p.map_err(|e| format!("glob pattern error: {}", e)) .and_then(|p| { ...
?}", input_files); assert_eq!(input_files.len(), input_contents.len()); let input_contents: Vec<_> = (&input_contents[..]).iter().map(|p| &p[..]).collect(); let outputs = exhaust::shuffle(&input_contents[..]); outputs.iter().enumerate().for_each(|(i, case)| { debug!("-- Case: {}", i...
random
[ { "content": "pub fn init_clients(url: &str, size: usize) -> MySQLResult<Pool> {\n\n let opts = Opts::from_url(url)?;\n\n let pool = Pool::new_manual(size, size, opts)?;\n\n Ok(pool)\n\n}\n\n\n", "file_path": "src/db.rs", "rank": 3, "score": 74685.11859225594 }, { "content": "/// He...
Rust
alvr/experiments/client/src/xr/openxr/interaction.rs
AndresGroselj/ALVR
679f3a1cdaeff99322fb94560208949d75edef83
use super::{convert, SceneButtons, XrContext, XrHandPoseInput}; use crate::{ xr::{XrActionType, XrActionValue, XrHandTrackingInput, XrProfileDesc}, ViewConfig, }; use alvr_common::{prelude::*, MotionData}; use alvr_session::TrackingSpace; use openxr as xr; use std::collections::HashMap; const OCULUS_PROFILE: &...
use super::{convert, SceneButtons, XrContext, XrHandPoseInput}; use crate::{ xr::{XrActionType, XrActionValue, XrHandTrackingInput, XrProfileDesc}, ViewConfig, }; use alvr_common::{prelude::*, MotionData}; use alvr_session::TrackingSpace; use openxr as xr; use std::collections::HashMap; const OCULUS_PROFILE: &...
let target_ray_space = trace_err!(target_ray_action.create_space( session, xr::Path::NULL, xr::Posef::IDENTITY ))?; Some(HandTrackingContext { tracker, target_ray_action, target_ray_spac...
let target_ray_action = trace_err!(action_set.create_action( &target_ray_action_name, &target_ray_action_name, &[] ))?;
assignment_statement
[ { "content": "pub fn create_graphics_context(xr_context: &XrContext) -> StrResult<GraphicsContext> {\n\n let entry = unsafe { ash::Entry::load().unwrap() };\n\n\n\n let raw_instance = unsafe {\n\n let extensions_ptrs =\n\n convert::get_vulkan_instance_extensions(&entry, TARGET_VULKAN_VER...
Rust
src/message/commands/clearchat.rs
Chronophylos/twitch-irc-rs
bf9792ebc085c08bb2e7e49e158ef2ae3e4412c6
use crate::message::commands::IRCMessageParseExt; use crate::message::{IRCMessage, ServerMessageParseError}; use chrono::{DateTime, Utc}; use std::convert::TryFrom; use std::str::FromStr; use std::time::Duration; #[derive(Debug, Clone, PartialEq)] pub struct ClearChatMessage { pub channel_login: String, ...
use crate::message::commands::IRCMessageParseExt; use crate::message::{IRCMessage, ServerMessageParseError}; use chrono::{DateTime, Utc}; use std::convert::TryFrom; use std::str::FromStr; use std::time::Duration; #[derive(Debug, Clone, PartialEq)] pub struct ClearChatMessage { pub channel_login: String, ...
#[test] pub fn test_permaban() { let src = "@room-id=11148817;target-user-id=70948394;tmi-sent-ts=1594561360331 :tmi.twitch.tv CLEARCHAT #pajlada :weeb123"; let irc_message = IRCMessage::parse(src).unwrap(); let msg = ClearChatMessage::try_from(irc_message.clone()).unwrap(); a...
pub fn test_timeout() { let src = "@ban-duration=1;room-id=11148817;target-user-id=148973258;tmi-sent-ts=1594553828245 :tmi.twitch.tv CLEARCHAT #pajlada :fabzeef"; let irc_message = IRCMessage::parse(src).unwrap(); let msg = ClearChatMessage::try_from(irc_message.clone()).unwrap(); asse...
function_block-full_function
[ { "content": "fn encode_tag_value(raw: &str) -> String {\n\n let mut output = String::with_capacity((raw.len() as f64 * 1.2) as usize);\n\n\n\n for c in raw.chars() {\n\n match c {\n\n ';' => output.push_str(\"\\\\:\"),\n\n ' ' => output.push_str(\"\\\\s\"),\n\n '\\...
Rust
src/test_framework/incremental_interface.rs
vlmutolo/orion
e2af271cc3b7ce763591e02a5e6808579c1e3504
use crate::errors::UnknownCryptoError; use core::marker::PhantomData; pub trait TestableStreamingContext<T: PartialEq> { fn reset(&mut self) -> Result<(), UnknownCryptoError>; fn update(&mut self, input: &[u8]) -> Result<(), UnknownCryptoError>; fn finalize(&mut self) -> Result<T, Unknow...
use crate::errors::UnknownCryptoError; use core::marker::PhantomData; pub trait TestableStreamingContext<T: PartialEq> { fn reset(&mut self) -> Result<(), UnknownCryptoError>; fn update(&mut self, input: &[u8]) -> Result<(), UnknownCryptoError>; fn finalize(&mut self) -> Result<T, Unknow...
fn update_after_finalize_err(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); assert!(state.update(data).is_err()); } fn double_reset_ok(&self, data: &[u8]) { let mut...
fn update_after_finalize_with_reset_ok(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); state.reset().unwrap(); assert!(state.update(data).is_ok()); }
function_block-full_function
[ { "content": "/// H' as defined in the specification.\n\nfn extended_hash(input: &[u8], dst: &mut [u8]) -> Result<(), UnknownCryptoError> {\n\n if dst.is_empty() {\n\n return Err(UnknownCryptoError);\n\n }\n\n\n\n let outlen = dst.len() as u32;\n\n\n\n if dst.len() <= BLAKE2B_OUTSIZE {\n\n ...
Rust
examples/example1.rs
evetion/startin
88ad5557cbd954ec8996f99d9afb74fd1ec174ec
#![allow(dead_code)] extern crate csv; extern crate serde; extern crate startin; #[macro_use] extern crate serde_derive; use std::error::Error; use std::io; #[derive(Debug, Deserialize)] pub struct CSVPoint { pub x: f64, pub y: f64, pub z: f64, } fn main() { let re = read_xyz_file(); let vec =...
#![allow(dead_code)] extern crate csv; extern crate serde; extern crate startin; #[macro_use] extern crate serde_derive; use std::error::Error; use std::io; #[derive(Debug, Deserialize)] pub struct CSVPoint { pub x: f64, pub y: f64, pub z: f64, } fn main() { let re = read_xyz_file(); let vec =...
fn read_xyz_file() -> Result<Vec<CSVPoint>, Box<dyn Error>> { let mut rdr = csv::ReaderBuilder::new() .delimiter(b' ') .from_reader(io::stdin()); let mut vpts: Vec<CSVPoint> = Vec::new(); for result in rdr.deserialize() { let record: CSVPoint = result?; vpts.push(record); ...
cent_vertices_to_vertex(66); if re.is_some() == true { for each in re.unwrap() { println!("Adjacent vertex {}", each); } } else { println!("Vertex does not exists."); } let trs = dt.incident_triangles_to_vertex(6).unwrap(); let re = dt.adjacent_triangles_to_tria...
function_block-function_prefixed
[ { "content": "fn read_xyz_file() -> Vec<Vec<f64>> {\n\n let tmpf = File::open(\"/Users/hugo/Dropbox/data/ahn3/o3.txt\").unwrap();\n\n // let tmpf = File::open(\"/Users/hugo/Dropbox/data/ahn3/test.txt\").unwrap();\n\n let file = BufReader::new(&tmpf);\n\n\n\n let mut pts: Vec<Vec<f64>> = Vec::new();\...
Rust
src/input/json.rs
PassFort/rouille
c3f06096afab039b88076d3d613f9a29e7a5f1dd
use serde; use serde_json; use serde_json::Value; use std::error; use std::fmt; use std::io::Error as IoError; use Request; #[derive(Debug)] pub enum JsonError { BodyAlreadyExtracted, WrongContentType, NullPresent, IoError(IoError), ParseError(serde_json::Error), } i...
use serde; use serde_json; use serde_json::Value; use std::error; use std::fmt; use std::io::Error as IoError; use Request; #[derive(Debug)] pub enum JsonError { BodyAlreadyExtracted, WrongContentType, NullPresent, IoError(IoError), ParseError(serde_json::Error), } i...
pub fn json_input<O>(request: &Request) -> Result<O, JsonError> where O: serde::de::DeserializeOwned, { if let Some(header) = request.header("Content-Type") { if !header.starts_with("application/json") { return Err(JsonError::WrongContentType); } } else { return E...
s) => { if s.find("\0").is_some() { return Err(JsonError::NullPresent); } } Value::Array(a) => { for element in a { check_null(element)?; } } Value::Object(o) => { for (k, v) in o { ...
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn plain_text_body(request: &Request) -> Result<String, PlainTextError> {\n\n plain_text_body_with_limit(request, 1024 * 1024)\n\n}\n\n\n", "file_path": "src/input/plain.rs", "rank": 2, "score": 213355.85341939444 }, { "content": "/// Applies content encodin...
Rust
src/commands/commands/math.rs
Chronophylos/chb4
8754dbeb16eb36b79118f676fbf1897b582d67ed
use super::prelude::*; use evalexpr::*; use std::f64::consts; static PHI: f64 = 1.61803398874989484820; pub fn command() -> Arc<Command> { Command::with_name("math") .alias("quickmafs") .command(move |_context, args, _msg, _user| { let context = context_map! { ...
use super::prelude::*; use evalexpr::*; use std::f64::consts; static PHI: f64 = 1.61803398874989484820; pub fn command() -> Arc<Command> { Command::with_name("math") .alias("quickmafs") .command(move |_context, args, _msg, _user| { let context = context_map! { ...
}) .about("Do some math") .description( " This command uses the `evalexpr` crate. This crate allows the definition of constants and functions. .Constants |=== | Name | Value | Description | e | 2.71828182845904523536028747135266250f64 | Euler's number (e) | pi, π | 3.141592653589...
Ok(match eval_with_context(&expr, &context) { Ok(s) => MessageResult::Message(format!("{}", s)), Err(err) => MessageResult::Error(err.to_string()), })
call_expression
[ { "content": "pub fn command() -> Arc<Command> {\n\n Command::with_name(\"system\")\n\n .alias(\"sysstat\")\n\n .command(|context, _args, _msg, _user| {\n\n let sys = System::new();\n\n\n\n let (mem_proc, mem_used, mem_total) =\n\n mem(&sys).context(\"Could ...
Rust
src/layout/gpos1.rs
daltonmaag/fonttools-rs
f6bbfa93cfb0b963432b87b30e4f5dfdfe9db923
use crate::layout::coverage::Coverage; use crate::layout::valuerecord::{coerce_to_same_format, ValueRecord, ValueRecordFlags}; use crate::utils::is_all_the_same; use otspec::types::*; use otspec::Serialize; use otspec::{DeserializationError, Deserialize, Deserializer, ReaderContext, SerializationError}; use otspec_ma...
use crate::layout::coverage::Coverage; use crate::layout::valuerecord::{coerce_to_same_format, ValueRecord, ValueRecordFlags}; use crate::utils::is_all_the_same; use otspec::types::*; use otspec::Serialize; use otspec::{DeserializationError, Deserialize, Deserializer, ReaderContext, SerializationError}; use otspec_ma...
}
let pos = SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10), 67 => valuerecord!(xPlacement=-20), ), }; let binary_pos = vec![ 0x00, 0x02, 0x00, 0x10, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, ...
function_block-function_prefix_line
[ { "content": "fn consecutive_slices(data: &[uint16]) -> Vec<&[uint16]> {\n\n let mut slice_start = 0;\n\n let mut result = Vec::new();\n\n for i in 1..data.len() {\n\n if data[i - 1] + 1 != data[i] {\n\n result.push(&data[slice_start..i]);\n\n slice_start = i;\n\n }\...
Rust
src/bytecode/src/loader.rs
ales-tsurko/koto
040c255d2170ac44e6743f6b381c7fb639e492a2
use { crate::{Chunk, Compiler, CompilerError, CompilerSettings}, koto_parser::{format_error_with_excerpt, Parser, ParserError}, std::{collections::HashMap, error, fmt, path::PathBuf, sync::Arc}, }; #[derive(Clone, Debug)] pub enum LoaderErrorType { ParserError(ParserError), CompilerError(CompilerEr...
use { crate::{Chunk, Compiler, CompilerError, CompilerSettings}, koto_parser::{format_error_with_excerpt, Parser, ParserError}, std::{collections::HashMap, error, fmt, path::PathBuf, sync::Arc}, }; #[derive(Clone, Debug)] pub enum LoaderErrorType { ParserError(ParserError), CompilerError(CompilerEr...
pub fn io_error(error: String) -> Self { Self { error: LoaderErrorType::IoError(error), source: "".into(), source_path: None, } } pub fn is_indentation_error(&self) -> bool { match &self.error { LoaderErrorType::ParserError(e) => e.i...
pub fn from_compiler_error( error: CompilerError, source: &str, source_path: Option<PathBuf>, ) -> Self { Self { error: LoaderErrorType::CompilerError(error), source: source.into(), source_path, } }
function_block-full_function
[ { "content": "/// Returns a [String] displaying the annotated instructions contained in the compiled [Chunk]\n\npub fn chunk_to_string_annotated(chunk: Arc<Chunk>, source_lines: &[&str]) -> String {\n\n let mut result = String::new();\n\n let mut reader = InstructionReader::new(chunk);\n\n let mut ip =...
Rust
quic/s2n-quic-transport/src/transmission/application.rs
nsdyoshi/s2n-quic
0635e62cdc58fb968de0a0d576822e09c96cba99
use crate::{ ack::AckManager, connection, contexts::WriteContext, endpoint, path, path::mtu, recovery, space::{datagram, HandshakeStatus}, stream::{AbstractStreamManager, StreamTrait as Stream}, sync::{flag, flag::Ping}, transmission::{self, Mode}, }; use core::ops::RangeInclus...
use crate::{ ack::AckManager, connection, contexts::WriteContext, endpoint, path, path::mtu, recovery, space::{datagram, HandshakeStatus}, stream::{AbstractStreamManager, StreamTrait as Stream}, sync::{flag, flag::Ping}, transmission::{self, Mode}, }; use core::ops::RangeInclus...
} impl<'a, S: Stream, Config: endpoint::Config> transmission::interest::Provider for Normal<'a, S, Config> { fn transmission_interest<Q: transmission::interest::Query>( &self, query: &mut Q, ) -> transmission::interest::Result { self.ack_manager.transmission_interest(query)?; ...
t); self.path_manager.on_transmit(context); self.datagram_manager .on_transmit(context, self.stream_manager); let _ = self.stream_manager.on_transmit(context); self.recovery_manager.on_tr...
function_block-function_prefixed
[ { "content": "pub trait Context<Config: endpoint::Config> {\n\n const ENDPOINT_TYPE: endpoint::Type;\n\n\n\n fn is_handshake_confirmed(&self) -> bool;\n\n\n\n fn path(&self) -> &Path<Config>;\n\n\n\n fn path_mut(&mut self) -> &mut Path<Config>;\n\n\n\n fn path_by_id(&self, path_id: path::Id) -> &...
Rust
src/util.rs
anderejd/meshlite
2a3b1f06b0dae801b55b10ee8f78c11c9cee5ebb
use cgmath::Point3; use cgmath::Vector3; use cgmath::prelude::*; use cgmath::Deg; use cgmath::Rad; /* Range of the Dot Product of Two Unit Vectors Dot Angle 1.000 0 degrees 0.966 15 degrees 0.866 30 degrees 0.707 45 degrees 0.500 60 degrees 0.259 75 degrees 0.000 90 degrees -0.259 105 by degrees -0.500 120 degree...
use cgmath::Point3; use cgmath::Vector3; use cgmath::prelude::*; use cgmath::Deg; use cgmath::Rad; /* Range of the Dot Product of Two Unit Vectors Dot Angle 1.000 0 degrees 0.966 15 degrees 0.866 30 degrees 0.707 45 degrees 0.500 60 degrees 0.259 75 degrees 0.000 90 degrees -0.259 105 by degrees -0.500 120 degree...
let v = u.cross(direct); let u = u.normalize() * radius; let v = v.normalize() * radius; let origin = position + direct * radius; let f = vec![origin - u - v, origin + u - v, origin + u + v, origin - u + v]; f } pub fn pick_most_not_obvious_vertex(vertice...
let u = { if direct_normalized.dot(oriented_base_norm).abs() > 0.707 { let switched_base_norm = world_perp(oriented_base_norm); direct_normalized.cross(switched_base_norm) } else { direct_normalized.cross(oriented_ba...
assignment_statement
[ { "content": "pub fn cube() -> Mesh {\n\n let mut m = Mesh::new();\n\n let face_id = m.add_plane(1.0, 1.0);\n\n let normal = m.face_norm(face_id);\n\n m.extrude_face(face_id, normal, 1.0).translate(0.0, 0.0, -0.5);\n\n m\n\n}\n\n\n", "file_path": "src/primitives.rs", "rank": 15, "scor...
Rust
main/src/vocab/sentence_piece_bpe_model.rs
sftse/rust-tokenizers
d869924622e40ea525d8244d1716517751c7743a
use crate::error::TokenizerError; use crate::tokenizer::base_tokenizer::{Token, TokenRef}; use crate::tokenizer::tokenization_utils::{is_punctuation, is_whitespace}; use crate::vocab::sentencepiece_proto::sentencepiece_model::ModelProto; use crate::{Mask, Offset, OffsetSize}; use hashbrown::HashMap; use protobuf::Mes...
use crate::error::TokenizerError; use crate::tokenizer::base_tokenizer::{Token, TokenRef}; use crate::tokenizer::tokenization_utils::{is_punctuation, is_whitespace}; use crate::vocab::sentencepiece_proto::sentencepiece_model::ModelProto; use crate::{Mask, Offset, OffsetSize}; use hashbrown::HashMap; use protobuf::Mes...
); } Self { symbols } } } impl SymbolList { pub fn len(&self) -> usize { self.symbols.len() } pub fn merge_symbols( &mut self, symbol_1_index: usize, symbol_2_index: usize, size_validation: usize, ) -> Option<Symbol> { if let (Some(le...
Some(Symbol { start_byte: character_start, end_byte: character_start + character.len_utf8(), start_offset: index, end_offset: index + 1, prev: index as isize - 1, next, size: 1, })
call_expression
[ { "content": "fn bytes_offsets(text: &str) -> Vec<usize> {\n\n let mut offsets = Vec::with_capacity(text.len());\n\n for (char_idx, character) in text.chars().enumerate() {\n\n for _ in 0..character.len_utf8() {\n\n offsets.push(char_idx)\n\n }\n\n }\n\n offsets\n\n}\n\n\n",...
Rust
storage/libradb/src/metrics.rs
chouette254/libra
1eaefa60d29e1df72ba6c4f9cf1867964821b586
use libra_metrics::{ register_histogram_vec, register_int_counter, register_int_gauge, register_int_gauge_vec, HistogramVec, IntCounter, IntGauge, IntGaugeVec, }; use once_cell::sync::Lazy; pub static LIBRA_STORAGE_LEDGER: Lazy<IntGaugeVec> = Lazy::new(|| { register_int_gauge_vec!( "libr...
use libra_metrics::{ register_histogram_vec, register_int_counter, register_int_gauge,
in bytes", &["cf_name"] ) .unwrap() }); pub static LIBRA_STORAGE_COMMITTED_TXNS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "libra_storage_committed_txns", "Libra storage committed transactions" ) .unwrap() }); pub static LIBRA_STORAGE_LATEST_TXN_VERS...
register_int_gauge_vec, HistogramVec, IntCounter, IntGauge, IntGaugeVec, }; use once_cell::sync::Lazy; pub static LIBRA_STORAGE_LEDGER: Lazy<IntGaugeVec> = Lazy::new(|| { register_int_gauge_vec!( "libra_storage_ledger", "Libra storage ledger counters", &["type...
random
[ { "content": "// Parse a use declaration:\n\n// UseDecl =\n\n// \"use\" <ModuleIdent> <UseAlias> \";\" |\n\n// \"use\" <ModuleIdent> :: <UseMember> \";\" |\n\n// \"use\" <ModuleIdent> :: \"{\" Comma<UseMember> \"}\" \";\"\n\nfn parse_use_decl<'input>(tokens: &mut Lexer<'input>) -...
Rust
src/bin/delete-reaction.rs
netguru/commentable-rs
be95c83cfc2ff65d6175cc0a979461cc235512c5
use lambda_http::{lambda, Request, Response, Body, RequestExt}; use rusoto_core::Region; use rusoto_dynamodb::{DynamoDbClient}; use serde::Deserialize; use commentable_rs::utils::db::{DynamoDbModel, CommentableId}; use commentable_rs::utils::http::{ok, bad_request, internal_server_error, HttpError}; use commentable_rs...
use lambda_http::{lambda, Request, Response, Body, RequestExt}; use rusoto_core::Region; use rusoto_dynamodb::{DynamoDbClient}; use serde::Deserialize; use commentable_rs::utils::db::{DynamoDbModel, CommentableId}; use commentable_rs::utils::http::{ok, bad_request, internal_server_error, HttpError}; use commentable_rs...
} else { Err(bad_request("Invalid parameters")) } } fn current_user_id(&self) -> &UserId { &self.current_user.as_ref().unwrap().id } fn current_comment_id(&self) -> &CommentId { &self.current_comment.as_ref().unwrap().id } pub fn validate_params(&mut self) -> Result<&mut Self, Http...
Ok(Self { db: DynamoDbClient::new(Region::default()), commentable_id, current_comment: None, current_user: None, reaction: None, params, })
call_expression
[ { "content": "pub fn comment_id(commentable_id: &CommentableId, user_id: &UserId) -> String {\n\n let id = hash(&format!(\"{}{}{}\", commentable_id, user_id, Utc::now().to_string()));\n\n format!(\"{}{}{}\", COMMENT_ID_PREFIX, Utc::now().timestamp_millis(), id)\n\n}\n", "file_path": "src/models/comment.rs...
Rust
src/u32x8_.rs
nathanvoglsam/wide
00de1af88cced28b9fb64fbe393261f203573c96
use super::*; pick! { if #[cfg(target_feature="avx2")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8 { avx2: m256i } } else if #[cfg(target_feature="ssse3")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8...
use super::*; pick! { if #[cfg(target_feature="avx2")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8 { avx2: m256i } } else if #[cfg(target_feature="ssse3")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8...
} impl Sub for u32x8 { type Output = Self; #[inline] #[must_use] fn sub(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: sub_i32_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: sub_i32_m128i(self.sse...
self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: add_i32_m128i(self.sse0, rhs.sse0) , sse1: add_i32_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].wrapping_add(rhs.arr[0]), self.arr[1].wrapping_add(rhs.arr[1]), ...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn impl_add_for_u32x8() {\n\n let a = u32x8::from([1, 2, u32::MAX - 1, u32::MAX - 1, 31, 72, 13, 53]);\n\n let b = u32x8::from([17, 18, 1, 2, 12, 12, 634, 15]);\n\n let expected = u32x8::from([18, 20, u32::MAX, u32::MIN, 43, 84, 647, 68]);\n\n let actual = a + b;\n\n assert_eq!(exp...
Rust
src/async/session.rs
reachkrr/serverless-wasm
0e521adc782a002aa1beae56d3661a88322d75e3
use mio::unix::UnixReady; use mio::net::TcpStream; use mio::{Poll, Ready}; use std::collections::HashMap; use std::iter::repeat; use std::rc::Rc; use std::io::{ErrorKind, Read, Write}; use std::cell::RefCell; use std::net::{SocketAddr, Shutdown}; use slab::Slab; use interpreter::WasmInstance; use super::host; use conf...
use mio::unix::UnixReady; use mio::net::TcpStream; use mio::{Poll, Ready}; use std::collections::HashMap; use std::iter::repeat; use std::rc::Rc; use std::io::{ErrorKind, Read, Write}; use std::cell::RefCell; use std::net::{SocketAddr, Shutdown}; use slab::Slab; use interpreter::WasmInstance; use super::host; use conf...
pub fn add_backend(&mut self, stream: TcpStream, index: usize) { let s = Stream { readiness: UnixReady::from(Ready::empty()), interest: UnixReady::from(Ready::writable()) | UnixReady::hup() | UnixReady::error(), stream, index, }; self.backends.insert(index, s); self.state =...
ackends: HashMap::new(), instance: None, config, buffer, state: Some(SessionState::WaitingForRequest), method: None, path: None, env: None, } }
function_block-function_prefixed
[ { "content": "pub fn server(config: Config) {\n\n let state = ApplicationState::new(&config);\n\n\n\n let addr = (&config.listen_address).parse().unwrap();\n\n let server = TcpListener::bind(&addr).unwrap();\n\n\n\n let mut poll = Poll::new().unwrap();\n\n\n\n poll\n\n .register(&server, SERVER, Ready::...
Rust
modules/world/tests/graph.rs
drunkenme/lemon3d-rs
48d4e879996e2502e0faaf36e4dbcebfca9961b0
extern crate crayon; extern crate crayon_world; extern crate rand; use crayon::prelude::*; use crayon::*; use crayon_world::prelude::*; use crayon_world::renderable::headless::HeadlessRenderer; #[test] pub fn hierachy() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); le...
extern crate crayon; extern crate crayon_world; extern crate rand; use crayon::prelude::*; use crayon::*; use crayon_world::prelude::*; use crayon_world::renderable::headless::HeadlessRenderer; #[test] pub fn hierachy() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); le...
let len = scene.children(constructed[0]).count(); assert_eq!(len, count); let len = scene.descendants(constructed[0]).count(); assert_eq!(len, 254); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn transform() {\n\n let mut e1 = Transform::default();\n\n let euler = Euler::new(Deg(0.0), Deg(0.0), Deg(90.0));\n\n e1.scale = 2.0;\n\n e1.position = [1.0, 0.0, 2.0].into();\n\n e1.rotation = euler.into();\n\n\n\n let v = [1.0, 0.0, 0.0];\n\n assert_ulps_eq!(e1.t...
Rust
day-11/src/main.rs
mmehrten/advent-of-code-2021
f04ac08718f4bda3d24ecf255083dac7b6b2cf8a
use std::collections::HashSet; use std::fs::File; use std::io::Error; use std::io::{BufRead, BufReader}; fn parse_file_path(args: &[String]) -> &str { if args.len() != 2 { panic!( "Expected one file path and an optional window size to run against, got: {} arguments", args.len() - 1 ...
use std::collections::HashSet; use std::fs::File; use std::io::Error; use std::io::{BufRead, BufReader}; fn parse_file_path(args: &[String]) -> &str { if args.len() != 2 { panic!( "Expected one file path and an optional window size to run against, got: {} arguments
("inputs/challenge.txt", 100), (1613, 510)); } }
", args.len() - 1 ); } let input_path = &args[1]; input_path.as_str() } #[cfg(test)] mod test_parse_file_path { use crate::parse_file_path; #[test] fn one_arg_ok() { assert_eq!( parse_file_path(&vec!["script_path".to_string(), "arg_text".to_string()][..]...
random
[ { "content": "/// Parse the file path from command line arguments.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `args` - the command line arguments\n\n///\n\n/// # Returns\n\n///\n\n/// A single command line argument - panics if zero or more than one argument are passed.\n\nfn parse_file_path(args: &[String]) -> &...
Rust
src/server/snap.rs
Caoming/tikv
7c25c38965692ccfc17d175fbd529d64c6695e13
use std::fmt::{self, Formatter, Display}; use std::io; use std::fs::File; use std::net::{SocketAddr, TcpStream}; use std::io::Read; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::boxed::FnBox; use std::time::{Instant, Duration}; use threadpool::ThreadPool; use mio::Token; use super::m...
use std::fmt::{self, Formatter, Display}; use std::io; use std::fs::File; use std::net::{SocketAddr, TcpStream}; use std::io::Read; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::boxed::FnBox; use std::time::{Instant, Duration}; use threadpool::ThreadPool; use mio::Token; use super::m...
} fn send_snap(mgr: SnapManager, addr: SocketAddr, data: ConnData) -> Result<()> { assert!(data.is_snapshot()); let timer = Instant::now(); let send_timer = SEND_SNAP_HISTOGRAM.start_timer(); let snap = data.msg.get_raft().get_message().get_snapshot(); let key = try!(SnapKey::from_snap(&snap)); ...
fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { Task::Register(token, ref meta) => write!(f, "Register {:?} token: {:?}", meta, token), Task::Write(token, _) => write!(f, "Write snap for {:?}", token), Task::Close(token) => write!(f, "Close file {:?}", token),...
function_block-full_function
[ { "content": "pub fn new_message(from: u64, to: u64, t: MessageType, n: usize) -> Message {\n\n let mut m = new_message_with_entries(from, to, t, vec![]);\n\n if n > 0 {\n\n let mut ents = Vec::with_capacity(n);\n\n for _ in 0..n {\n\n ents.push(new_entry(0, 0, SOME_DATA));\n\n ...
Rust
aml/src/test_utils.rs
Dentosal/acpi
2273964aef430a51afee8735526e7323f597d2ca
use crate::{parser::Propagate, AmlContext, AmlValue, Handler}; use alloc::boxed::Box; struct TestHandler; impl Handler for TestHandler { fn read_u8(&self, _address: usize) -> u8 { unimplemented!() } fn read_u16(&self, _address: usize) -> u16 { unimplemented!() } fn read_u32(&self, ...
use crate::{parser::Propagate, AmlContext, AmlValue, Handler}; use alloc::boxed::Box; struct TestHandler; impl Handler for TestHandler { fn read_u8(&self, _address: usize) -> u8 { unimplemented!() } fn read_u16(&self, _address: usize) -> u16 { unimplemented!() } fn read_u32(&self, ...
_parent_device } _ => false, }, AmlValue::Field { region, flags, offset, length } => match b { AmlValue::Field { region: b_region, flags: b_flags, offset: b_offset, length: b_length } => { region == b_region && flags == b_flags && offset == b_offset &&...
cted Ok, got {:#?}", err), } } pub(crate) fn crudely_cmp_values(a: &AmlValue, b: &AmlValue) -> bool { use crate::value::MethodCode; match a { AmlValue::Boolean(a) => match b { AmlValue::Boolean(b) => a == b, _ => false, }, AmlValue::Integer(a) => match b { ...
random
[ { "content": "pub fn take_n<'a, 'c>(n: u32) -> impl Parser<'a, 'c, &'a [u8]>\n\nwhere\n\n 'c: 'a,\n\n{\n\n move |input: &'a [u8], context| {\n\n if (input.len() as u32) < n {\n\n return Err((input, context, Propagate::Err(AmlError::UnexpectedEndOfStream)));\n\n }\n\n\n\n le...
Rust
src/setting_serial.rs
opendoor-labs/libnm-rs
ddd1c6c4599fb9d4c62f44f5eb17a0286eeabe1a
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::Value; use glib_sys; use gobject_sys; use nm_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use Setting; use SettingSerialParity; glib_wrapper! ...
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::Value; use glib_sys; use gobject_sys; use nm_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use Setting; use SettingSerialParity; glib_wrapper! ...
fn set_property_parity(&self, parity: SettingSerialParity) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"parity\0".as_ptr() as *const _, Value::from(&parity).to_glib_none().0, ); ...
self.to_glib_none().0 as *mut gobject_sys::GObject, b"bits\0".as_ptr() as *const _, Value::from(&bits).to_glib_none().0, ); } }
function_block-function_prefix_line
[ { "content": "pub trait SettingExt: 'static {\n\n fn compare<P: IsA<Setting>>(&self, b: &P, flags: SettingCompareFlags) -> bool;\n\n\n\n //fn diff<P: IsA<Setting>>(&self, b: &P, flags: SettingCompareFlags, invert_results: bool, results: /*Unknown conversion*//*Unimplemented*/HashTable TypeId { ns_id: 0, i...
Rust
src/lower.rs
1tgr/simplejit-demo
750a1f628452d42836d0da5fc415fcef7750c045
use crate::ast::*; use crate::intern::Intern; use crate::{InternExt, Parse, Result}; use std::collections::HashMap; use std::convert::Infallible; use std::num::NonZeroU32; use std::rc::Rc; use std::result; #[salsa::query_group(LowerDatabase)] pub trait Lower: Parse { fn lower_function(&self, name: IdentId) -> Resu...
use crate::ast::*; use crate::intern::Intern; use crate::{InternExt, Parse, Result}; use std::collections::HashMap; use std::convert::Infallible; use std::num::NonZeroU32; use std::rc::Rc; use std::result; #[salsa::query_group(LowerDatabase)] pub trait Lower: Parse { fn lower_function(&self, name: IdentId) -> Resu...
fn transform_block(&mut self, _expr_id: ExprId, mut expr: Block) -> result::Result<Expr, Infallible> { self.transform_stmts(&mut expr.stmts)?; Ok(Expr::Block(expr)) } fn transform_call(&mut self, _expr_id: ExprId, mut expr: Call) -> result::Result<Expr, Infallible> { expr.env = So...
d { if let Expr::Block(expr) = expr { let Block { stmts } = expr; self.db.intern_block(stmts) } else { self.db.intern_expr(expr) } }
function_block-function_prefixed
[ { "content": "fn function_body(db: &dyn Parse, name: IdentId) -> Result<ExprId> {\n\n let Function {\n\n signature: _,\n\n param_names: _,\n\n body,\n\n } = db.function(name)?;\n\n\n\n Ok(body)\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 1, "score": 259582.8352002...
Rust
tests/integrations/config/test_config_client.rs
amyangfei/tikv
5019e61d0c8e1966f6b649894ad17ba128068a1e
use std::cmp::Ordering; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use kvproto::configpb::*; use configuration::{ConfigChange, Configuration}; use pd_client::errors::Result; use pd_client::ConfigClient; use raftstore::store::Config as RaftstoreConfig; use tikv::config::*; use tikv_util::config::Rea...
use std::cmp::Ordering; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use kvproto::configpb::*; use configuration::{ConfigChange, Configuration}; use pd_client::errors::Result; use pd_client::ConfigClient; use raftstore::store::Config as RaftstoreConfig; use tikv::config::*; use tikv_util::config::Rea...
resp.set_status(status); Ok(resp) } fn update_config( &self, id: String, version: Version, mut entries: Vec<ConfigEntry>, ) -> Result<UpdateResponse> { let mut resp = UpdateResponse::default(); let mut status = Status::default(); if l...
if let Some(cfg) = configs.get(&id) { match cmp_version(&cfg.version, &version) { Ordering::Equal => status.set_code(StatusCode::Ok), _ => { resp.set_config(cfg.content.clone()); status.set_code(StatusCode::WrongVersion); ...
if_condition
[ { "content": "fn config_to_slice(config_change: &[(String, String)]) -> Vec<(&str, &str)> {\n\n config_change\n\n .iter()\n\n .map(|(name, value)| (name.as_str(), value.as_str()))\n\n .collect()\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 0, "score": 391110.64508115995...
Rust
editor/src/settings/mod.rs
Libertus-Lab/Fyrox
c925304f42744659fd3a6be5c4a1a8609556033a
use crate::{ inspector::editors::make_property_editors_container, settings::{ debugging::DebuggingSettings, graphics::GraphicsSettings, move_mode::MoveInteractionModeSettings, rotate_mode::RotateInteractionModeSettings, selection::SelectionSettings, }, GameEngine, Message, MSG_SY...
use crate::{ inspector::editors::make_property_editors_container, settings::{ debugging::DebuggingSettings, graphics::GraphicsSettings, move_mode::MoveInteractionModeSettings, rotate_mode::RotateInteractionModeSettings, selection::SelectionSettings, }, GameEngine, Message, MSG_SY...
match settings.save() { Ok(_) => { Log::info("Settings were successfully saved!".to_owned()); } Err(e) => { Log::err(format!("Unable to save settings! Reason: {:?}!", e)); } }; ...
if settings.graphics.quality != engine.renderer.get_quality_settings() { if let Err(e) = engine .renderer .set_quality_settings(&settings.graphics.quality) { Log::err(format!( "An error occurred at attemp...
if_condition
[ { "content": "pub trait InspectableEnum: Debug + Inspect + 'static {}\n\n\n\nimpl<T: Debug + Inspect + 'static> InspectableEnum for T {}\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum EnumPropertyEditorMessage {\n\n Variant(usize),\n\n PropertyChanged(PropertyChanged),\n\n}\n\n\n\nimpl EnumProperty...
Rust
crates/rome_js_parser/src/parse.rs
mrkldshv/tools
c173b0c01ee499fcb49d6ae328f1229daa183868
use crate::token_source::Trivia; use crate::*; use rome_diagnostics::Severity; use rome_js_syntax::{ JsAnyRoot, JsExpressionSnipped, JsLanguage, JsModule, JsScript, JsSyntaxNode, ModuleKind, SourceType, }; use rome_rowan::AstNode; use std::marker::PhantomData; #[derive(Debug, Clone)] pub struct Parse<T> { ...
use crate::token_source::Trivia; use crate::*; use rome_diagnostics::Severity; use rome_js_syntax::{ JsAnyRoot, JsExpressionSnipped, JsLanguage, JsModule, JsScript, JsSyntaxNode, ModuleKind, SourceType, }; use rome_rowan::AstNode; use std::marker::PhantomData; #[derive(Debug, Clone)] pub struct Parse<T> { ...
} pub fn parse_common( text: &str, file_id: usize, source_type: SourceType, ) -> (Vec<Event>, Vec<ParseDiagnostic>, Vec<Trivia>) { let mut parser = crate::Parser::new(text, file_id, source_type); crate::syntax::program::parse(&mut parser); let (events, trivia, errors) = parser.finish(); ...
pub fn ok(self) -> Result<T, Vec<ParseDiagnostic>> { if !self.errors.iter().any(|d| d.severity == Severity::Error) { Ok(self.tree()) } else { Err(self.errors) } }
function_block-full_function
[ { "content": "#[inline]\n\npub fn process(sink: &mut impl TreeSink, mut events: Vec<Event>, errors: Vec<ParseDiagnostic>) {\n\n sink.errors(errors);\n\n let mut forward_parents = Vec::new();\n\n\n\n for i in 0..events.len() {\n\n match &mut events[i] {\n\n Event::Start {\n\n ...
Rust
couchbase-lite/src/query.rs
adrien-jeser-doctolib/couchbase-lite-rust
49ef36b21aef1817314cf98f679587be55604a7d
use crate::{ error::{c4error_init, Error}, ffi::{ c4query_new, c4query_new2, c4query_release, c4query_run, c4query_setParameters, c4queryenum_next, c4queryenum_release, kC4DefaultQueryOptions, kC4N1QLQuery, C4Query, C4QueryEnumerator, FLArrayIterator_GetCount, FLArrayIterator_GetValueAt,...
use crate::{ error::{c4error_init, Error}, ffi::{ c4query_new, c4query_new2, c4query_release, c4query_run, c4query_setParameters, c4queryenum_next, c4queryenum_release, kC4DefaultQueryOptions, kC4N1QLQuery, C4Query, C4QueryEnumerator, FLArrayIterator_GetCount, FLArrayIterator_GetValueAt,...
.ok_or_else(|| c4err.into()) } pub(crate) fn new_n1ql<'a, 'b>(db: &'a Database, query_n1ql: &'b str) -> Result<Query<'a>> { let mut c4err = c4error_init(); let mut out_error_pos: std::os::raw::c_int = -1; let query = unsafe { c4query_new2( db.inner.0.a...
query_json.as_bytes().as_flslice(), &mut c4err, ) }; NonNull::new(query) .map(|inner| Query { _db: db, inner })
function_block-random_span
[ { "content": "fn print_external_changes(db: &mut Option<Database>) -> Result<(), Box<dyn std::error::Error>> {\n\n let db = db\n\n .as_mut()\n\n .ok_or_else(|| format!(\"print_external_changes: db not OPEN\"))?;\n\n let mut doc_ids = HashSet::<String>::new();\n\n for change in db.observed...
Rust
src/rust/iced-x86/src/formatter/fast/options.rs
darfink/iced
6371d812392a02bd9c37cbe4f19d2dcdf33aacd4
struct Flags1; impl Flags1 { const SPACE_AFTER_OPERAND_SEPARATOR: u32 = 0x0000_0001; const RIP_RELATIVE_ADDRESSES: u32 = 0x0000_0002; const USE_PSEUDO_OPS: u32 = 0x0000_0004; const SHOW_SYMBOL_ADDRESS: u32 = 0x0000_0008; const ALWAYS_SHOW_SEGMENT_REGISTER: u32 = 0x0000_0010; const ALWAYS_SHOW_MEMORY_SIZE: u32 =...
struct Flags1; impl Flags1 { const SPACE_AFTER_OPERAND_SEPARATOR: u32 = 0x0000_0001; const RIP_RELATIVE_ADDRESSES: u32 = 0x0000_0002; const USE_PSEUDO_OPS: u32 = 0x0000_0004; const SHOW_SYMBOL_ADDRESS: u32 = 0x0000_0008; const ALWAYS_SHOW_SEGMENT_REGISTER: u32 = 0x0000_0010; const ALWAYS_SHOW_MEMORY_SIZE: u32 =...
} #[must_use] #[inline] pub fn use_pseudo_ops(&self) -> bool { (self.options1 & Flags1::USE_PSEUDO_OPS) != 0 } #[inline] pub fn set_use_pseudo_ops(&mut self, value: bool) { if value { self.options1 |= Flags1::USE_PSEUDO_OPS; } else { self.options1 &= !Flags1::USE_PS...
if value { self.options1 |= Flags1::RIP_RELATIVE_ADDRESSES; } else { self.options1 &= !Flags1::RIP_RELATIVE_ADDRESSES; }
if_condition
[ { "content": "fn read_infos(bitness: u32, is_misc: bool) -> (Vec<InstructionInfo>, HashSet<u32>) {\n\n\tlet mut filename = get_formatter_unit_tests_dir();\n\n\tif is_misc {\n\n\t\tfilename.push(format!(\"InstructionInfos{}_Misc.txt\", bitness));\n\n\t} else {\n\n\t\tfilename.push(format!(\"InstructionInfos{}.tx...
Rust
src/num_traits.rs
icewind1991/bitbuffer-rs
96c37a0bc32cac5c44b77c5c0b05b053735c2942
use crate::Endianness; use num_traits::PrimInt; use std::array::TryFromSliceError; use std::convert::TryFrom; use std::fmt::Debug; use std::ops::{BitOrAssign, BitXor}; pub trait UncheckedPrimitiveFloat: Sized { type BYTES: AsRef<[u8]> + for<'a> TryFrom<&'a [u8], Error = TryFromSliceError>; type INT: PrimInt ...
use crate::Endianness; use num_traits::PrimInt; use std::array::TryFromSliceError; use std::convert::TryFrom; use std::fmt::Debug; use std::ops::{BitOrAssign, BitXor}; pub trait UncheckedPrimitiveFloat: Sized { type BYTES: AsRef<[u8]> + for<'a> TryFrom<&'a [u8], Error = TryFromSliceError>; type INT: PrimInt ...
} impl_split_fit_signed!(i32, u32); impl SplitFitUsize for u64 { type Iter = array::IntoIter<(usize, u8), 3>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { (if E::is_le() { [ ((self & (Self::MAX >> 40)) as usize, 24), ((self >> 24 & (Self::MAX >>...
fn split_fit_usize<E: Endianness>(self) -> Self::Iter { Self::Iter::new(if E::is_le() { [ ((self & (Self::MAX >> 8)) as usize, 24), ((self >> 24) as usize, 8), ] } else { [ ((self >> 24) as usize, 8), ((s...
function_block-full_function
[ { "content": "fn type_is_int(ty: &Type) -> bool {\n\n if let Type::Path(path) = ty {\n\n if let Some(ident) = path.path.get_ident() {\n\n let name = ident.to_string();\n\n matches!(\n\n name.as_str(),\n\n \"u8\" | \"u16\" | \"u32\" | \"u64\" | \"usiz...
Rust
quibitous/src/blockchain/bootstrap.rs
The-Blockchain-Company/quibitous
a93cedb5c9d833f6e82429286faaf4f15e9e15a0
use super::tip::TipUpdater; use crate::blockcfg::{Block, HeaderHash}; use crate::blockchain::{ chain::{CheckHeaderProof, StreamInfo, StreamReporter}, Blockchain, Ref, Tip, }; use crate::metrics::Metrics; use chain_core::property::Deserialize; use chain_network::data as net_data; use chain_network::error::Error ...
use super::tip::TipUpdater; use crate::blockcfg::{Block, HeaderHash}; use crate::blockchain::{ chain::{CheckHeaderProof, StreamInfo, StreamReporter}, Blockchain, Ref, Tip, }; use crate::metrics::Metrics; use chain_core::property::Deserialize; use chain_network::data as net_data; use chain_network::error::Error ...
map_err(|e| Error::BlockchainError(Box::new(e))) } Err(err) => Err(err), }; match maybe_tip { Ok(parent_tip) => { maybe_parent_tip = Some(parent_tip); } Err(err) => { if let Some(bootstrap_tip) = maybe_parent_tip...
#[error("bootstrap pull stream failed")] PullStreamFailed(#[source] NetworkError), #[error("failures while deserializing block from stream")] BlockDeserialize(#[from] std::io::Error), #[error("the bootstrap process was interrupted")] Interrupted, } pub async fn bootstrap_from_stream<S>( bl...
random
[ { "content": "fn network_block_error_into_reply(err: chain::Error) -> intercom::Error {\n\n use super::chain::Error::*;\n\n\n\n match err {\n\n Storage(e) => intercom::Error::failed(e),\n\n Ledger(e) => intercom::Error::failed_precondition(e),\n\n Block0(e) => intercom::Error::failed(...
Rust
src/main.rs
azerupi/cube-parse
ee5af4aa48755449bab7d7afe01166e029791ffc
use std::{collections::HashMap, env, path::Path}; use alphanumeric_sort::compare_str; use clap::{App, Arg}; use lazy_static::lazy_static; use regex::Regex; mod family; mod internal_peripheral; mod mcu; mod utils; #[derive(Debug, PartialEq)] enum GenerateTarget { Features, PinMappings, EepromSizes, } laz...
use std::{collections::HashMap, env, path::Path}; use alphanumeric_sort::compare_str; use clap::{App, Arg}; use lazy_static::lazy_static; use regex::Regex; mod family; mod internal_peripheral; mod mcu; mod utils; #[derive(Debug, PartialEq)] enum GenerateTarget { Features, PinMappings, EepromSizes, } laz...
} if let Some(ram_size) = mcu.ram_size() { mcu_ram_size_map .entry(ram_size) .or_insert(vec![]) .push(mcu.ref_name.clone()); } mcu_map.insert(mcu.ref_name.clone(), (mcu, mcu_dat)); ...
teTarget::PinMappings, "eeprom_sizes" => GenerateTarget::EepromSizes, _ => unreachable!(), }; let families = family::Families::load(&db_dir) .map_err(|e| format!("Could not load families XML: {}", e))?; let family = (&families) .into_iter() .find(|v| v.nam...
random
[ { "content": "pub fn load_file<'a, P: AsRef<Path>, Q: AsRef<Path>, R: Deserialize<'a>>(\n\n db_dir: P,\n\n file_path: Q,\n\n) -> Result<R, Box<dyn Error>> {\n\n let db_dir = db_dir.as_ref();\n\n let mut fin = BufReader::new(File::open(&db_dir.join(file_path.as_ref()))?);\n\n\n\n Ok(serde_xml_rs::...
Rust
grid/src/lib.rs
Daniel-del-Castillo/ia1
c11d768af415a8d117152b954cb9cf25bce48631
use crossterm::style::Colorize; use std::fmt; mod content; mod path_finding; use content::Content; use rand::{thread_rng, Rng}; pub struct Grid { grid: Vec<Vec<Content>>, goal: Option<(usize, usize)>, car: Option<(usize, usize)>, } impl fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter<'_>)...
use crossterm::style::Colorize; use std::fmt; mod content; mod path_finding; use content::Content; use rand::{thread_rng, Rng}; pub struct Grid { grid: Vec<Vec<Content>>, goal: Option<(usize, usize)>, car: Option<(usize, usize)>, } impl fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter<'_>)...
y][x] = Content::Car; if let Some(old_car_pos) = &mut self.car { self.grid[old_car_pos.1][old_car_pos.0] = Content::Empty; } self.car = Some((x, y)); } pub fn set_empty(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Goal => self.go...
lf.grid[old_goal_pos.1][old_goal_pos.0] = Content::Empty; } self.goal = Some((x, y)); } pub fn set_car(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Goal => self.goal = None, Content::Car => return, _ => {} } s...
random
[ { "content": "fn get_grid_size(matches: &ArgMatches) -> (usize, usize) {\n\n let m = matches.value_of(\"m\").unwrap_or(\"10\");\n\n let n = matches.value_of(\"n\").unwrap_or(\"10\");\n\n let m = match m.parse() {\n\n Err(_) | Ok(0) => {\n\n eprintln!(\"The -m parameter must be a posit...
Rust
src/parser/rfc3501/body.rs
filtsin/rimap
21954bdd1a848fe4a17e4180552ab4e58027a100
use super::{core::*, grammar::envelope}; use crate::parser::types::{ Body, BodyEnc, BodyFields, BodyTypeBasic, BodyTypeMsg, BodyTypeText, MediaBasic, MediaType, }; use nom::{ branch::alt, bytes::streaming::{tag, tag_no_case}, combinator::{map, value}, multi::separated_list1, sequence::{delim...
use super::{core::*, grammar::envelope}; use crate::parser::types::{ Body, BodyEnc, BodyFields, BodyTypeBasic, BodyTypeMsg, BodyTypeText, MediaBasic, MediaType, }; use nom::{ branch::alt, bytes::streaming::{tag, tag_no_case}, combinator::{map, value}, multi::separated_list1, sequence::{delim...
body: Box::new(body), lines, }, )(i) } pub(crate) fn body_type_text(i: &[u8]) -> IResult<&[u8], BodyTypeText<'_>> { map( tuple(( tag_no_case("\"TEXT\" "), string, tag(" "), body_fields, tag(" "), number, ...
IResult<&[u8], BodyFields<'_>> { map( tuple(( body_fld_param, tag(" "), nstring, tag(" "), nstring, tag(" "), body_fld_enc, tag(" "), number, )), |(param, _, id, _, desc, _, enc, _, oc...
random
[ { "content": "fn vec_to_string(v: &Vec<u8>) -> String {\n\n std::string::String::from_utf8_lossy(&v[..]).into_owned()\n\n}\n", "file_path": "src/error.rs", "rank": 0, "score": 90814.00460926183 }, { "content": "pub fn create_custom_error(msg: String) -> Error {\n\n Error::Custom(msg)\n...
Rust
src/compaction/value.rs
timothee-haudebourg/json-ld
0b44aa736b681893e75ce282c67511480c992901
use super::{compact_iri, JsonSrc, Options}; use crate::{ context::{self, Inversible, Loader, Local}, syntax::{Container, ContainerType, Keyword, Term, Type}, util::{AsAnyJson, AsJson, JsonFrom}, ContextMut, Error, Id, Loc, Reference, Value, }; pub async fn compact_indexed_value_with< J: JsonSrc, K: JsonFrom<J>, ...
use super::{compact_iri, JsonSrc, Options}; use crate::{ context::{self, Inversible, Loader, Local}, syntax::{Container, ContainerType, Keyword, Term, Type}, util::{AsAnyJson, AsJson, JsonFrom}, ContextMut, Error, Id, Loc, Reference, Value, }; pub async fn compact_indexed_value_with< J: JsonSrc, K: JsonFrom<J>, ...
, None => active_context.default_language(), }; let direction = match active_property_definition { Some(def) => match def.direction { Some(dir) => dir.option(), None => active_context.default_base_direction(), }, None => active_context.default_base_direction(), }; let type_mapping: Opti...
match def.language.as_ref() { Some(lang) => lang.as_ref().map(|l| l.as_ref()).option(), None => active_context.default_language(), }
if_condition
[ { "content": "/// Get the `@value` field of a value object.\n\nfn value_value<J: JsonClone, K: JsonFrom<J>, T: Id, M>(value: &Value<J, T>, meta: M) -> K\n\nwhere\n\n\tM: Clone + Fn(Option<&J::MetaData>) -> K::MetaData,\n\n{\n\n\tuse crate::object::value::Literal;\n\n\tmatch value {\n\n\t\tValue::Literal(lit, _t...
Rust
whisper/src/aggregation.rs
GiantPlantsSociety/graphite-rs
d2657ae3ddf110023417ec255f5192ac8fa83bfc
use serde::*; use std::cmp; use std::convert::Into; use std::fmt; use std::str::FromStr; #[allow(clippy::trivially_copy_pass_by_ref)] fn cmp_f64(a: &f64, b: &f64) -> cmp::Ordering { a.partial_cmp(b).unwrap_or(::std::cmp::Ordering::Equal) } #[allow(clippy::trivially_copy_pass_by_ref)] fn cmp_f64_abs(a: &f64, b: &f...
use serde::*; use std::cmp; use std::convert::Into; use std::fmt; use std::str::FromStr; #[allow(clippy::trivially_copy_pass_by_ref)] fn cmp_f64(a: &f64, b: &f64) -> cmp::Ordering { a.partial_cmp(b).unwrap_or(::std::cmp::Ordering::Equal) } #[allow(clippy::trivially_copy_pass_by_ref)] fn cmp_f64_abs(a: &f64, b: &f...
} } pub fn aggregate(self, values: &[Option<f64>]) -> Result<f64, &'static str> { match self { AggregationMethod::Average => { let sum: f64 = values.iter().filter_map(|v| *v).sum(); let count = values.iter().filter_map(|v| *v).count(); ...
Last, Max, Min, AvgZero, AbsMax, AbsMin, } impl AggregationMethod { pub fn from_type(aggregation_type: u32) -> Option<Self> { match aggregation_type { 1 => Some(AggregationMethod::Average), 2 => Some(AggregationMethod::Sum), 3 => Some(AggregationM...
random
[ { "content": "pub fn diff(\n\n path1: &Path,\n\n path2: &Path,\n\n ignore_empty: bool,\n\n mut until_time: u32,\n\n now: u32,\n\n) -> Result<Vec<DiffArchive>, io::Error> {\n\n let mut file1 = WhisperFile::open(path1)?;\n\n let mut file2 = WhisperFile::open(path2)?;\n\n\n\n if file1.info(...
Rust
src/algorithms/leaky_bucket.rs
jbg/ratelimit_meter
df4d7a3f9b26dffe4468ad2b05a512589296dd64
use crate::lib::*; use crate::thread_safety::ThreadsafeWrapper; use crate::{ algorithms::{Algorithm, RateLimitState, RateLimitStateWithClock}, instant, InconsistentCapacity, NegativeMultiDecision, NonConformance, }; #[derive(Debug, Clone, Eq, PartialEq)] pub struct LeakyBucket<P: instant::Relative = instant:...
use crate::lib::*; use crate::thread_safety::ThreadsafeWrapper; use crate::{ algorithms::{Algorithm, RateLimitState, RateLimitStateWithClock}, instant, InconsistentCapacity, NegativeMultiDecision, NonConformance, }; #[derive(Debug, Clone, Eq, PartialEq)] pub struct LeakyBucket<P: instant::Relative = instant:...
(per_time_unit * cell_weight.get()) / capacity.get(); Ok(LeakyBucket { full: per_time_unit, token_interval, point: PhantomData, }) } fn test_n_and_update( &self, state: &Self::BucketState, n: u32, t0: P, ) -> Result<(), Neg...
elative> Default for BucketState<P> { fn default() -> Self { BucketState { level: Duration::new(0, 0), last_update: None, } } } impl<P: instant::Relative> Algorithm<P> for LeakyBucket<P> { type BucketState = State<P>; type NegativeDecision = TooEarly<P>; fn...
random
[ { "content": "/// Trait that all rate limit states have to implement around\n\n/// housekeeping in keyed rate limiters.\n\npub trait RateLimitState<P, I: instant::Relative>: Default + Send + Sync + Eq + fmt::Debug {}\n\n\n", "file_path": "src/algorithms.rs", "rank": 0, "score": 139496.12516807122 ...
Rust
languages/idl_gen/src/rust/con_idl.rs
adrianos42/native_idl
688de924e1e2244719a33aba40aae8b9dd10ede9
use idl::idl_nodes::*; use proc_macro2::{self, TokenStream}; use quote::format_ident; pub(crate) fn get_rust_ty_ref(ty: &TypeName, references: bool) -> TokenStream { match ty { TypeName::Types(types) => match types { Types::NatInt => quote! { i64 }, Types::NatFloat => quote! { f64 }...
use idl::idl_nodes::*; use proc_macro2::{self, TokenStream}; use quote::format_ident; pub(crate) fn get_rust_ty_ref(ty: &TypeName, references: bool) -> TokenStream { match ty { TypeName::Types(types) => match types { Types::NatInt => quote! { i64 }, Types::NatFloat => quote! { f64 }...
TypeName::InterfaceTypeName(value) => { let ident = format_ident!("{}Instance", value); quote! { Box<dyn super::idl_impl::#ident> } } } } pub(crate) fn get_rust_ty_name(ty: &TypeName) -> String { match ty { TypeName::Types(types) => match types { Type...
value) => { let ident = format_ident!("{}", &value); if references { quote! { super::#ident } } else { quote! { #ident } } } TypeName::TypeStream(_) => { quote! { Box<dyn StreamInstance + Send + Sync> } }...
function_block-random_span
[]
Rust
src/mqtt/listener.rs
Galhad/ratelmq
15395108681aa97b861d0364263ac7cd123d2b11
use crate::mqtt::events::{ClientEvent, ServerEvent}; use crate::mqtt::packets::ControlPacket; use crate::mqtt::transport::mqtt_bytes_stream::{MqttBytesReadStream, MqttBytesWriteStream}; use crate::mqtt::transport::packet_decoder::read_packet; use crate::mqtt::transport::packet_encoder::write_packet; use log::{debug, er...
use crate::mqtt::events::{ClientEvent, ServerEvent}; use crate::mqtt::packets::ControlPacket; use crate::mqtt::transport::mqtt_bytes_stream::{MqttBytesReadStream, MqttBytesWriteStream}; use crate::mqtt::transport::packet_decoder::read_packet; use crate::mqtt::transport::packet_encoder::write_packet; use log::{debug, er...
_tx = client_event_tx.clone(); tokio::spawn(async move { Self::handle_connection(socket, client_event_tx, address).await; }); } Err(e) => { error!("Error while accepting connection: {:?}", e); } } } ...
o::sync::mpsc::{Receiver, Sender}; use tokio::sync::{broadcast, mpsc}; pub struct MqttListener { listener: TcpListener, client_event_tx: mpsc::Sender<ClientEvent>, ctrl_c_rx: broadcast::Receiver<()>, } impl MqttListener { pub async fn bind( address: &str, client_event_tx: mpsc::Sender<...
random
[ { "content": "#[derive(Debug)]\n\npub struct BuildInfo {\n\n pub version: &'static str,\n\n pub commit_hash: &'static str,\n\n}\n\n\n\npub const BUILD_INFO: BuildInfo = BuildInfo {\n\n version: env!(\"CARGO_PKG_VERSION\"),\n\n commit_hash: env!(\"BUILD_GIT_HASH\"),\n\n};\n", "file_path": "src/co...
Rust
src/utils.rs
KaiWitt/kalayo
5498ed501cb7799cacb709403ba8a6141dc3e2e4
use bitcoin::util::address::Address; use bitcoin::{AddressType, Network}; use std::str::FromStr; use warp::hyper::StatusCode; use warp::Rejection; use crate::error::ErrorMsg; pub fn validate_address(address: Address) -> Result<Address, Rejection> { if address.network != Network::Bitcoin { return Err(Error...
use bitcoin::util::address::Address; use bitcoin::{AddressType, Network}; use std::str::FromStr; use warp::hyper::StatusCode; use warp::Rejection; use crate::error::ErrorMsg; pub fn validate_address(address: Address) -> Result<Address, Rejection> { if address.network != Network::Bitcoin { return Err(Error...
pub fn validate_address_str(address: &str) -> Result<Address, Rejection> { match Address::from_str(address) { Ok(address) => validate_address(address), Err(_) => { let msg = format!("[{}] is not a valid Bitcoin address.", &address); Err(ErrorMsg::reject_new(StatusCode::BAD_...
if let Some(addr_type) = address.address_type() { if addr_type != AddressType::P2wpkh { let msg = format!("[{}] is not a P2WPKH Bitcoin mainnet address.", &address); return Err(ErrorMsg::reject_new(StatusCode::BAD_REQUEST, msg)); } return Ok(address); } log::war...
function_block-function_prefix_line
[]
Rust
vendor/rust-cdk/src/ic_cdk_macros/src/import.rs
dfinity/bigmap-poc
177e3be92316064d62e6e31538f01dded65b9ccb
use crate::error::Errors; use quote::quote; use serde::Deserialize; use serde_tokenstream::from_tokenstream; use std::path::PathBuf; use std::str::FromStr; #[derive(Default, Deserialize)] struct ImportAttributes { pub canister: Option<String>, pub canister_id: Option<String>, pub candid_path: Option<PathBu...
use crate::error::Errors; use quote::quote; use serde::Deserialize; use serde_tokenstream::from_tokenstream; use std::path::PathBuf; use std::str::FromStr; #[derive(Default, Deserialize)] struct ImportAttributes { pub canister: Option<String>, pub canister_id: Option<String>, pub candid_path: Option<PathBu...
struct RustLanguageBinding { visibility: String, canister_id: String, } impl candid::codegen::rust::RustBindings for RustLanguageBinding { fn record( &self, id: &str, fields: &[(String, String)], ) -> Result<String, candid::error::Error> { let all_fields = fields ...
fn get_env_id_and_candid(canister_name: &str) -> Result<(String, PathBuf), Errors> { let canister_id_var_name = format!("CANISTER_ID_{}", canister_name); let candid_path_var_name = format!("CANISTER_CANDID_{}", canister_name); Ok(( std::env::var(canister_id_var_name).map_err(|_| { Error...
function_block-full_function
[ { "content": "#[derive(CandidType, serde::Deserialize, Debug)]\n\nstruct CanisterIdRecord {\n\n canister_id: candid::Principal,\n\n}\n\n\n\npub async fn subnet_create_new_canister() -> Result<CanisterId, String> {\n\n let management_canister = ic_cdk::CanisterId::from(Vec::new());\n\n let new_can_id_re...
Rust
src/k8-client/src/client/config_rustls.rs
simlay/k8-api
3a69671c469c46757e489f4ab6919f6601e0e514
use std::io::{Error as IoError, ErrorKind, Result as IoResult}; use std::net::ToSocketAddrs; use std::path::Path; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use futures_util::future::Future; use futures_util::io::{AsyncRead as StdAsyncRead, AsyncWrite as StdAsyncWrite}; use http::Uri; use t...
use std::io::{Error as IoError, ErrorKind, Result as IoResult}; use std::net::ToSocketAddrs; use std::path::Path; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use futures_util::future::Future; use futures_util::io::{AsyncRead as StdAsyncRead, AsyncWrite as StdAsyncWrite}; use http::Uri; use t...
} impl AsyncWrite for HyperTlsStream { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<IoResult<usize>> { Pin::new(&mut self.0).poll_write(cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>...
Poll::Ready(bytes_read) => { buf.advance(bytes_read); Poll::Ready(Ok(())) } Poll::Pending => Poll::Pending, } }
function_block-function_prefix_line
[ { "content": "pub fn create_topic_stream_result(\n\n ttw_list: &TestTopicWatchList,\n\n) -> TokenStreamResult<TopicSpec, TopicStatus,ClientError> {\n\n let mut topic_watch_list = vec![];\n\n for ttw in ttw_list {\n\n topic_watch_list.push(Ok(create_topic_watch(&ttw)));\n\n }\n\n Ok(topic_w...
Rust
samples/command_executer/src/lib.rs
costisin/aws-nitro-enclaves-cli
de77067677ef2287661063b4529e937b52115a60
pub mod command_parser; pub mod protocol_helpers; pub mod utils; use command_parser::{CommandOutput, FileArgs, ListenArgs, RunArgs}; use protocol_helpers::{recv_loop, recv_u64, send_loop, send_u64}; use nix::sys::socket::listen as listen_vsock; use nix::sys::socket::{accept, bind, connect, shutdown, socket}; use nix:...
pub mod command_parser; pub mod protocol_helpers; pub mod utils; use command_parser::{CommandOutput, FileArgs, ListenArgs, RunArgs}; use protocol_helpers::{recv_loop, recv_u64, send_loop, send_u64}; use nix::sys::socket::listen as listen_vsock; use nix::sys::socket::{accept, bind, connect, shutdown, socket}; use nix:...
r(|err| format!("{:?}", err))?; send_u64(socket_fd, len)?; send_loop(socket_fd, &buf, len)?; let filesize = file .metadata() .map_err(|err| format!("Could not get file metadate {:?}", err))? .len(); send_u64(socket_fd, filesize)?; println!( "Sending file {}(sending ...
ot write {:?}", err))?; progress += tmpsize } Ok(()) } pub fn send_file(args: FileArgs) -> Result<(), String> { let mut file = File::open(&args.localfile).map_err(|err| format!("Could not open localfile {:?}", err))?; let vsocket = vsock_connect(args.cid, args.port)?; let socket_fd ...
random
[ { "content": "pub fn recv_loop(fd: RawFd, buf: &mut [u8], len: u64) -> Result<(), String> {\n\n let len: usize = len.try_into().map_err(|err| format!(\"{:?}\", err))?;\n\n let mut recv_bytes = 0;\n\n\n\n while recv_bytes < len {\n\n let size = match recv(fd, &mut buf[recv_bytes..len], MsgFlags::...
Rust
src/test/spec/unified_runner/mod.rs
awitten1/mongo-rust-driver
5a0192cf1ba11d9e44c453e14f90d32231689166
mod entity; mod matcher; mod operation; mod test_event; mod test_file; mod test_runner; use std::{convert::TryFrom, ffi::OsStr, fs::read_dir, path::PathBuf, time::Duration}; use futures::{future::FutureExt, stream::TryStreamExt}; use semver::Version; use tokio::sync::RwLockWriteGuard; use crate::{ bson::{doc, Do...
mod entity; mod matcher; mod operation; mod test_event; mod test_file; mod test_runner; use std::{convert::TryFrom, ffi::OsStr, fs::read_dir, path::PathBuf, time::Duration}; use futures::{future::FutureExt, stream::TryStreamExt}; use semver::Version; use tokio::sync::RwLockWriteGuard; use crate::{ bson::{doc, Do...
#[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn valid_fail() { let _guard: RwLockWriteGuard<_> = LOCK.run_exclusively().await; let path: PathBuf = [ env!("CARGO_MANIFEST_DIR"), "src", "te...
d: RwLockWriteGuard<_> = LOCK.run_exclusively().await; run_spec_test( &["unified-test-format", "examples"], run_unified_format_test, ) .await; }
function_block-function_prefixed
[ { "content": "fn entity_matches(id: &str, actual: Option<&Bson>, entities: &EntityMap) -> bool {\n\n let bson = entities.get(id).unwrap().as_bson();\n\n results_match_inner(actual, bson, false, false, Some(entities))\n\n}\n\n\n", "file_path": "src/test/spec/unified_runner/matcher.rs", "rank": 0, ...
Rust
src/cache/file_manager.rs
cloudfuse-io/cloud-readers-rs
498ae2e6bbcdc170659bb76d428e5135f8041724
use std::collections::BTreeMap; use std::fmt; use std::sync::{Arc, Condvar, Mutex}; use anyhow::{anyhow, bail, ensure, Result}; use itertools::Itertools; use tokio::sync::mpsc::UnboundedSender; use super::Range; #[derive(Clone)] pub(crate) enum Download { Pending(usize), Done(Arc<Vec<u8>>), Error(String)...
use std::collections::BTreeMap; use std::fmt; use std::sync::{Arc, Condvar, Mutex}; use anyhow::{anyhow, bail, ensure, Result}; use itertools::Itertools; use tokio::sync::mpsc::UnboundedSender; use super::Range; #[derive(Clone)] pub(crate) enum Download { Pending(usize), Done(Arc<Vec<u8>>), Error(String)...
pub(crate) fn read(self, buf: &mut [u8]) -> usize { let len = std::cmp::min(buf.len(), self.data.len() - self.offset as usize); buf[0..len] .clone_from_slice(&self.data[self.offset as usize..(self.offset as usize + len)]); len } } #[derive(Clone)] pub...
t: u64) -> Result<Self> { ensure!( data.len() > offset as usize, "Out of bound in RangeCursor: (offset={}) >= (length={})", offset, data.len(), ); Ok(Self { data, offset }) }
function_block-function_prefixed
[ { "content": "/// A downloader that always returns an error\n\nstruct ErrorDownloader;\n\n\n\n#[async_trait]\n\nimpl Downloader for ErrorDownloader {\n\n async fn download(&self, _file: String, _start: u64, _length: usize) -> Result<Vec<u8>> {\n\n Err(anyhow!(\"Download Failed\").context(\"Error in Er...
Rust
src/asset/tileset.rs
B-Reif/bevy_asefile
51d8abfc51aa9e406dad2e5cad4b93c22e7b3fc6
use asefile::{AsepriteFile, TilesetImageError}; use bevy::{ prelude::*, reflect::TypeUuid, render::texture::{Extent3d, TextureDimension, TextureFormat}, }; use std::fmt; pub(crate) type TilesetResult<T> = std::result::Result<T, TilesetError>; #[derive(Debug)] pub enum TilesetError { MissingId(asefile:...
use asefile::{AsepriteFile, TilesetImageError}; use bevy::{ prelude::*, reflect::T
width, height } = self.tile_size; let tile_count = self.tile_count as f32; Vec2::new(width as f32, height as f32 * tile_count) } } #[derive(Debug)] pub(crate) struct TilesetData<T> { pub(crate) tile_count: u32, pub(crate) tile_size: TileSize, pub(crate) name: String, pub(crate) tex...
ypeUuid, render::texture::{Extent3d, TextureDimension, TextureFormat}, }; use std::fmt; pub(crate) type TilesetResult<T> = std::result::Result<T, TilesetError>; #[derive(Debug)] pub enum TilesetError { MissingId(asefile::TilesetId), NoPixels(asefile::TilesetId), } impl fmt::Display for TilesetError { ...
random
[ { "content": "use crate::asset::{TileSize, Tileset};\n\nuse bevy::math::{UVec2, Vec2};\n\nuse bevy_ecs_tilemap::prelude::*;\n\n\n\nimpl From<TileSize> for Vec2 {\n\n fn from(tile_size: TileSize) -> Self {\n\n Vec2::new(tile_size.width as f32, tile_size.height as f32)\n\n }\n\n}\n\n\n\nimpl Tileset ...
Rust
src/lib.rs
justanotherdot/cargo-watch
ac0a403e0c6b64a60dd7f5f78c049301ce092b4f
#![forbid(unsafe_code, clippy::pedantic)] #![allow( clippy::non_ascii_literal, clippy::cast_sign_loss, clippy::cast_possible_truncation )] #[macro_use] extern crate clap; extern crate watchexec; use clap::{ArgMatches, Error, ErrorKind}; use std::{env::set_current_dir, path::MAIN_SEPARATOR}; use watchexec...
#![forbid(unsafe_code, clippy::pedantic)] #![allow( clippy::non_ascii_literal, clippy::cast_sign_loss, clippy::cast_possible_truncation )] #[macro_use] extern crate clap; extern crate watchexec; use clap::{ArgMatches, Error, ErrorKind}; use std::{env::set_current_dir, path::MAIN_SEPARATOR}; use watchexec...
pub fn set_commands(debug: bool, builder: &mut ArgsBuilder, matches: &ArgMatches) { let mut commands: Vec<String> = Vec::new(); if matches.is_present("cmd:cargo") { for cargo in values_t!(matches, "cmd:cargo", String).unwrap_or_else(|e| e.exit()) { let mut cmd: String = "cargo ".into...
pub fn change_dir() { cargo::root() .and_then(|p| set_current_dir(p).ok()) .unwrap_or_else(|| { Error::with_description("Not a Cargo project, aborting.", ErrorKind::Io).exit(); }); }
function_block-full_function
[ { "content": "fn main() -> watchexec::error::Result<()> {\n\n let matches = cargo_watch::args::parse();\n\n\n\n cargo_watch::change_dir();\n\n\n\n let quiet = matches.is_present(\"quiet\");\n\n let debug = matches.is_present(\"debug\");\n\n let opts = cargo_watch::get_options(debug, &matches);\n\...
Rust
fastpay_core/src/authority.rs
mahimna-fb/fastpay
413826688d365ad597acb002213704378e9b2efc
use crate::{base_types::*, committee::Committee, error::FastPayError, messages::*}; use std::{collections::BTreeMap, convert::TryInto}; #[cfg(test)] #[path = "unit_tests/authority_tests.rs"] mod authority_tests; #[derive(Eq, PartialEq, Debug)] pub struct AccountOffchainState { pub balance: Balance, ...
use crate::{base_types::*, committee::Committee, error::FastPayError, messages::*}; use std::{collections::BTreeMap, convert::TryInto}; #[cfg(test)] #[path = "unit_tests/authority_tests.rs"] mod authority_tests; #[derive(Eq, PartialEq, Debug)] pub struct AccountOffchainState { pub balance: Balance, ...
requested_certificate: None, requested_received_transfers: Vec::new(), } } #[cfg(test)] pub fn new_with_balance(balance: Balance, received_log: Vec<CertifiedTransferOrder>) -> Self { Self { balance, next_sequence_number: SequenceNumber::new(), ...
certificate: CertifiedTransferOrder, ) -> Result<(), FastPayError> { let transfer = &certificate.value.transfer; let recipient = match transfer.recipient { Address::FastPay(recipient) => recipient, Address::Primary(_) => { fp_bail!(FastPayError::In...
random
[ { "content": "pub fn serialize_info_request(value: &AccountInfoRequest) -> Vec<u8> {\n\n serialize(&ShallowSerializedMessage::InfoReq(value))\n\n}\n\n\n", "file_path": "fastpay_core/src/serialize.rs", "rank": 0, "score": 194362.98059485495 }, { "content": "pub fn serialize_transfer_order_...
Rust
crypto/bls/src/macros.rs
sean-sn/lighthouse
c6baa0eed131c5e8ecc5860778ffc7d4a4c18d2d
macro_rules! impl_tree_hash { ($byte_size: expr) => { fn tree_hash_type() -> tree_hash::TreeHashType { tree_hash::TreeHashType::Vector } fn tree_hash_packed_encoding(&self) -> Vec<u8> { unreachable!("Vector should never be packed.") } fn tree_hash_...
macro_rules! impl_tree_hash { ($byte_size: expr) => { fn tree_hash_type() -> tree_hash::TreeHashType { tree_hash::TreeHashType::Vector } fn tree_hash_packed_encoding(&self) -> Vec<u8> { unreachable!("Vector should never be packed.") } fn tree_hash_...
Self::deserialize(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat) } }; }
f, D::Error> where D: Deserializer<'de>, { pub struct StringVisitor; impl<'de> serde::de::Visitor<'de> for StringVisitor { type Value = String; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { f...
random
[ { "content": "fn string_to_bytes(string: &str) -> Result<Vec<u8>, String> {\n\n let string = if string.starts_with(\"0x\") {\n\n &string[2..]\n\n } else {\n\n string\n\n };\n\n\n\n hex::decode(string).map_err(|e| format!(\"Unable to decode public or private key: {}\", e))\n\n}\n\n\n", ...
Rust
src/developer/ffx/plugins/setui/display/src/lib.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use anyhow::Result; use ffx_core::ffx_plugin; use ffx_setui_display_args::Display; use fidl_fuchsia_settings::{DisplayProxy, DisplaySettings}; use utils::handle_mixed_result; use utils::{self, Either, WatchOrSetResult}; #[ffx_plugin("setui", DisplayProxy = "core/setui_service:expose:fuchsia.settings.Display")] pub a...
use anyhow::Result; use ffx_core::ffx_plugin; use ffx_setui_display_args::Display; use fidl_fuchsia_settings::{DisplayProxy, DisplaySettings}; use utils::handle_mixed_result; use utils::{self, Either, WatchOrSetResult}; #[ffx_plugin("setui", DisplayProxy = "core/setui_service:expose:fuchsia.settings.Display")] pub a...
#[test_case( Display { brightness: None, auto_brightness_level: None, auto_brightness: None, low_light_mode: None, theme: None, screen_enabled: None, }; "Test display watch() output with empty input." )] #[test...
async fn validate_display_set_output(expected_display: Display) -> Result<()> { let proxy = setup_fake_display_proxy(move |req| match req { DisplayRequest::Set { responder, .. } => { let _ = responder.send(&mut Ok(())); } DisplayRequest::Watch { .. } => { ...
function_block-full_function
[]
Rust
src/setup_config.rs
amarant/msvc-helper
27821c5cdbfdebcae94342f8b6662791f1e78b02
#![allow(bad_style)] use std::ffi::OsString; use std::ptr::null_mut; use std::fmt; use winapi::Interface; use winapi::shared::minwindef::{LPFILETIME, ULONG}; use winapi::shared::winerror::S_FALSE; use winapi::shared::wtypes::BSTR; use winapi::shared::wtypesbase::LPCOLESTR; use winapi::um::combaseapi::{CoCreateInsta...
#![allow(bad_style)] use std::ffi::OsString; use std::ptr::null_mut; use std::fmt; use winapi::Interface; use winapi::shared::minwindef::{LPFILETIME, ULONG}; use winapi::shared::winerror::S_FALSE; use winapi::shared::wtypes::BSTR; use winapi::shared::wtypesbase::LPCOLESTR; use winapi::um::combaseapi::{CoCreateInsta...
}; if err < 0 { return Err(err); } let obj = unsafe { ComPtr::from_raw(obj as *mut ISetupConfiguration) }; Ok(SetupConfiguration(obj)) } pub fn get_instance_for_current_process(&self) -> Result<SetupInstance, i32> { let mut obj = null_mut(); l...
CoCreateInstance( &CLSID_SetupConfiguration, null_mut(), CLSCTX_ALL, &ISetupConfiguration::uuidof(), &mut obj, )
call_expression
[ { "content": "pub fn get_lasted_platform_toolset() -> Option<String> {\n\n get_toolchains()\n\n .iter()\n\n .next()\n\n .map(|v| v.platform_toolset.clone())\n\n}\n", "file_path": "src/toolchain.rs", "rank": 1, "score": 59086.79993836931 }, { "content": "fn os_to_res_s...
Rust
proto-compiler/src/cmd/compile.rs
livelybug/ibc-rs
e83a2d0963fe6fa675b4125a4e8c18b13b792d88
use std::fs::remove_dir_all; use std::fs::{copy, create_dir_all}; use std::path::{Path, PathBuf}; use git2::Repository; use tempdir::TempDir; use walkdir::WalkDir; use argh::FromArgs; #[derive(Debug, FromArgs)] #[argh(subcommand, name = "compile")] pub struct CompileCmd { #[argh(option, short = 's')] sd...
use std::fs::remove_dir_all; use std::fs::{copy, create_dir_all}; use std::path::{Path, PathBuf}; use git2::Repository; use tempdir::TempDir; use walkdir::WalkDir; use argh::FromArgs; #[derive(Debug, FromArgs)] #[argh(subcommand, name = "compile")] pub struct CompileCmd { #[argh(option, short = 's')] sd...
}) .filter_map(|e| e.err()) .collect::<Vec<_>>(); if !errors.is_empty() { for e in errors { println!("[error] Error while copying compiled file: {}", e); } panic!("[error] Aborted."); } } }
copy( e.path(), format!( "{}/{}", to_dir.display(), &e.file_name().to_os_string().to_str().unwrap() ), )
call_expression
[ { "content": "/// Serialize the given `Config` as TOML to the given config file.\n\npub fn store(config: &Config, path: impl AsRef<Path>) -> Result<(), Error> {\n\n let mut file = if path.as_ref().exists() {\n\n fs::OpenOptions::new().write(true).truncate(true).open(path)\n\n } else {\n\n Fi...
Rust
src/http_client/client_impl.rs
ngi-nix/etebase-rs
33447aa22a2d8d2a93863312d6f61e341682ebfe
use serde::Deserialize; use crate::error::{Error, Result}; pub trait ClientImplementation { fn get(&self, url: &str, auth_token: Option<&str>) -> Response; fn post(&self, url: &str, auth_token: Option<&str>, body: Vec<u8>) -> Response; fn put(&self, url: &str, auth_token: Option<&str>, body...
use serde::Deserialize; use crate::error::{Error, Result}; pub trait ClientImplementation { fn get(&self, url: &str, auth_token: Option<&str>) -> Response; fn post(&self, url: &str, auth_token: Option<&str>, body: Vec<u8>) -> Response; fn put(&self, url: &str, auth_token: Option<&str>, body...
.detail .unwrap_or("Temporary server error") .to_string(), ), 500..=501 | 505..=599 => { Error::ServerError(content.detail.unwrap_or("Server error").to_string()) } status => Error::Http(format!( ...
tent: ErrorResponse = rmp_serde::from_read_ref(self.bytes()).unwrap_or(ErrorResponse { code: None, detail: None, }); Err(match self.status { 300..=399 => Error::NotFound("Got a redirect - should never happen".to_string()), ...
random
[ { "content": "pub fn derive_key(salt: &[u8], password: &str) -> Result<Vec<u8>> {\n\n let mut key = vec![0; 32];\n\n let salt = &salt[..argon2id13::SALTBYTES];\n\n let salt: &[u8; argon2id13::SALTBYTES] =\n\n to_enc_error!(salt.try_into(), \"Expect salt to be at least 16 bytes\")?;\n\n let pa...
Rust
src/http.rs
mdheller/monolith
625c529cf1409848aa3ce42a74991d0d69c75d88
use regex::Regex; use reqwest::header::{CONTENT_TYPE, USER_AGENT}; use reqwest::{Client, RedirectPolicy}; use std::time::Duration; use url::{ParseError, Url}; use utils::data_to_dataurl; lazy_static! { static ref REGEX_URL: Regex = Regex::new(r"^https?://").unwrap(); } pub fn is_data_url(url: &str) -> Result<bool...
use regex::Regex; use reqwest::header::{CONTENT_TYPE, USER_AGENT}; use reqwest::{Client, RedirectPolicy}; use std::time::Duration; use url::{ParseError, Url}; use utils::data_to_dataurl; lazy_static! { static ref REGEX_URL: Regex = Regex::new(r"^https?://").unwrap(); } pub fn is_data_url(url: &str) -> Result<bool...
assert_eq!( resolved_url.as_str(), "https://www.kernel.org/theme/images/logos/tux.png" ); let resolved_url = resolve_url( "https://www.kernel.org", "//another-host.org/theme/images/logos/tux.png", )?; assert_eq!( resol...
let resolved_url = resolve_url( "https://www.kernel.org", "//www.kernel.org/theme/images/logos/tux.png", )?;
assignment_statement
[ { "content": "pub fn data_to_dataurl(mime: &str, data: &[u8]) -> String {\n\n let mimetype = if mime == \"\" {\n\n detect_mimetype(data)\n\n } else {\n\n mime.to_string()\n\n };\n\n format!(\"data:{};base64,{}\", mimetype, encode(data))\n\n}\n\n\n", "file_path": "src/utils.rs", ...
Rust
src/board/builder.rs
veeso/chess-engine-harmon
463474a593e10695281309293677f2d96a06ddd6
use super::{Board, Color, Piece, Square, BLACK, WHITE}; pub struct BoardBuilder { board: Board, } impl From<Board> for BoardBuilder { fn from(board: Board) -> Self { Self { board } } } impl Default for BoardBuilder { fn default() -> Self { let mut board = Board::empty(); boa...
use super::{Board, Color, Piece, Square, BLACK, WHITE}; pub struct BoardBuilder { board: Board, } impl From<Board> for BoardBuilder { fn from(board: Board) -> Self { Self { board } } } impl Default for BoardBuilder {
} impl BoardBuilder { pub fn row(mut self, piece: Piece) -> Self { let mut pos = piece.get_pos(); while pos.get_col() > 0 { pos = pos.next_left() } for _ in 0..8 { *self.board.get_square(pos) = Square::from(piece.move_to(pos)); po...
fn default() -> Self { let mut board = Board::empty(); board.white_castling_rights.disable_all(); board.black_castling_rights.disable_all(); Self { board } }
function_block-function_prefix_line
[ { "content": "/// ### was_illegal_move\n\n///\n\n/// Returns whether game result was an illegal move\n\npub fn was_illegal_move(res: &GameResult) -> bool {\n\n matches!(res, Err(GameError::IllegalMove(_)))\n\n}\n\n\n", "file_path": "src/game/result.rs", "rank": 0, "score": 43371.68225817752 }, ...
Rust
src/direction.rs
jack-atack/Cursive
fc065e8e589c24dfa7906d9423c7b63fee095e23
use crate::vec::Vec2; use crate::XY; #[derive(Clone, Copy, Debug, PartialEq)] pub enum Orientation { Horizontal, Vertical, } impl Orientation { pub fn pair() -> XY<Orientation> { XY::new(Orientation::Horizontal, Orientation::Vertical) } pub fn get<T: C...
use crate::vec::Vec2; use crate::XY; #[derive(Clone, Copy, Debug, PartialEq)] pub enum Orientation { Horizontal, Vertical, } impl Orientation { pub fn pair() -> XY<Orientation> { XY::new(Orientation::Horizontal, Orientation::Vertical) } pub fn get<T: C...
n::Horizontal, Absolute::Right) | (Orientation::Vertical, Absolute::Down) => Some(Relative::Back), _ => None, } } }
rientation) -> Option<Relative> { match (orientation, self) { (Orientation::Horizontal, Absolute::Left) | (Orientation::Vertical, Absolute::Up) => Some(Relative::Front), (Orientatio
function_block-random_span
[ { "content": "fn cap<'a, I: Iterator<Item = &'a mut usize>>(iter: I, max: usize) {\n\n let mut available = max;\n\n for item in iter {\n\n if *item > available {\n\n *item = available;\n\n }\n\n\n\n available -= *item;\n\n }\n\n}\n\n\n\nimpl LinearLayout {\n\n /// Cre...
Rust
src/gui/layout.rs
lukexor/pix-engine
447b794d57fcb4e6c5631254857d210c430f0181
use crate::{ops::clamp_size, prelude::*}; impl PixState { #[inline] pub fn same_line<O>(&mut self, offset: O) where O: Into<Option<[i32; 2]>>, { let [x, y] = self.ui.pcursor().as_array(...
use crate::{ops::clamp_size, prelude::*}; impl PixState { #[inline] pub fn same_line<O>(&mut self, offset: O) where O: Into<Option<[i32; 2]>>, { let [x, y] = self.ui.pcursor().as_array(...
} impl PixState { pub fn spacing(&mut self) -> PixResult<()> { let s = self; let width = s.ui_width()?; let (_, height) = s.text_size(" ")?; s.advance_cursor([width, height]); ...
pub fn tab_bar<S, I, F>(&mut self, label: S, tabs: &[I], f: F) -> PixResult<()> where S: AsRef<str>, I: AsRef<str>, F: FnOnce(usize, &mut PixState) -> PixResult<()>, { let label = label.as_ref(); let s = self; let tab_id = s.ui.get_id(&label); let colors ...
function_block-full_function
[ { "content": "pub fn main() -> PixResult<()> {\n\n let mut engine = PixEngine::builder()\n\n .with_dimensions(WIDTH, HEIGHT)\n\n .with_title(\"Colors\")\n\n .with_frame_rate()\n\n .build()?;\n\n let mut app = Colors::new();\n\n engine.run(&mut app)\n\n}\n", "file_path": ...
Rust
PLs/Rust/Slns/Simple-Windows-RS-Window/src/main.rs
QubitTooLate/How-To-Make-A-Win32-Window
2593bf0192bc361490a957eb3b6b5d2c23bed11b
use bindings::{ Windows::Win32::{ Foundation::*, UI::WindowsAndMessaging::*, System::LibraryLoader::{ GetModuleHandleA, }, }, }; use windows::*; fn main() -> Result<()> { let mut window = Win3Window::new()?; window.run() } struct Win3Window { handle: ...
use bindings::{ Windows::Win32::{ Foundation::*, UI::WindowsAndMessaging::*, System::LibraryLoader::{ GetModuleHandleA, }, }, }; use windows::*; fn main() -> Result<()> { let mut window = Win3Window::new()?; window.run() } struct Win3Window { handle: ...
handle, message, w, l); } DefWindowProcA(window_handle, message, w, l) } } } #[allow(non_snake_case)] #[cfg(target_pointer_width = "32")] unsafe fn SetWindowLong(window: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize { SetWindowLongA(window, index, value as _) as _ ...
LRESULT(0) } WM_DESTROY => { PostQuitMessage(0); LRESULT(0) } _ => DefWindowProcA(window_handle, message, w, l), } } } fn run(&mut self) -> Result<()> { unsafe { let i...
random
[]
Rust
lamp_asm_parser/src/lexer.rs
ElFamosoKilluaah/lamp
4a879129118a798de6d2ba05b5e39a0f0663649b
use lamp_common::op::{get_op, Opcode}; #[derive(Debug, Copy, Clone, PartialEq)] pub enum TokenType { Opcode(Opcode), Num8(u8), Ptr8(u8), } #[derive(Debug)] pub enum LexerError { UnexpectedToken(usize, String), InvalidMnemonic(usize, String), InvalidLine(usize), } impl std::fmt:...
use lamp_common::op::{get_op, Opcode}; #[derive(Debug, Copy, Clone, PartialEq)] pub enum TokenType { Opcode(Opcode), Num8(u8), Ptr8(u8), } #[derive(Debug)] pub enum LexerError { UnexpectedToken(usize, String), InvalidMnemonic(usize, String), InvalidLine(usize), } impl std::fmt:...
e>::new(); let mut errors = Vec::<LexerError>::new(); #[allow(clippy::needless_range_loop)] for i in 0..content.len() { if content[i].starts_with(lamp_common::constants::COMMENT_MARKER) { continue; } match self.tokenize_line(&content[i], i) { ...
'", at + 1, tkn) } Self::InvalidMnemonic(at, mnemonic) => { write!(f, "Invalid mnemonic at line {}: \'{}\'", at + 1, mnemonic) } } } } pub struct Lexer; #[derive(PartialEq, Debug)] pub struct TokenizedLine { pub opcode: Opcode, pub operands: Vec<...
random
[ { "content": "pub fn get_op<'a>(base: String) -> Result<Opcode, &'a str> {\n\n for (opcode, name) in OPCODES_STRINGS {\n\n if base.to_uppercase().contains(name) {\n\n return Ok(*opcode);\n\n }\n\n }\n\n\n\n Err(\"No opcode found.\")\n\n}\n", "file_path": "lamp_common/src/op...