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
tools/sdk-sync/src/fs.rs
eduardomourar/smithy-rs
817bf68e69da1d1ef14f8e79a27ec39a6d92bbad
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ use anyhow::{Context, Result}; use gitignore::Pattern; use smithy_rs_tool_common::macros::here; use smithy_rs_tool_common::shell::handle_failure; use std::error::Error; use std::fmt::Display; use std::pa...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ use anyhow::{Context, Result}; use gitignore::Pattern; use smithy_rs_tool_common::macros::here; use smithy_rs_tool_common::shell::handle_failure; use std::error::Error; use std::fmt::Display; use std::pa...
pub fn generated_files_and_folders_iter( &self, ) -> Result<impl Iterator<Item = PathBuf> + '_, HandwrittenFilesError> { self.files_and_folders_iter(FileKind::Generated) } pub fn handwritten_files_and_folders_iter( &self, ) -> Result<impl Iterator<Item = PathBuf> + '_, Han...
rn.is_excluded(path, path.is_dir()) { return FileKind::Handwritten; } } FileKind::Generated }
function_block-function_prefixed
[ { "content": "/// Attempts to find git repository root from the given location.\n\npub fn find_git_repository_root(repo_name: &str, location: impl AsRef<Path>) -> Result<PathBuf> {\n\n let path = GetRepoRoot::new(location.as_ref()).run()?;\n\n if path.file_name() != Some(OsStr::new(repo_name)) {\n\n ...
Rust
components/merkledb/benches/transactions.rs
bishop45690/Bishop45690-BL-Exonum
fd14af39558e7e691128d24e72ed1c288e68dc0d
use criterion::{ AxisScale, Bencher, Criterion, ParameterizedBenchmark, PlotConfiguration, Throughput, }; use rand::{rngs::StdRng, Rng, RngCore, SeedableRng}; use serde_derive::{Deserialize, Serialize}; use std::{borrow::Cow, collections::HashMap, convert::TryInto}; use exonum_crypto::{Hash, PublicKey, PUBLIC_KE...
use criterion::{ AxisScale, Bencher, Criterion, ParameterizedBenchmark, PlotConfiguration, Throughput, }; use rand::{rngs::StdRng, Rng, RngCore, SeedableRng}; use serde_derive::{Deserialize, Serialize}; use std::{borrow::Cow, collections::HashMap, convert::TryInto}; use exonum_crypto::{Hash, PublicKey, PUBLIC_KE...
pub fn bench_transactions(c: &mut Criterion) { exonum_crypto::init(); let item_counts = ITEM_COUNT.iter().cloned(); c.bench( "transactions", ParameterizedBenchmark::new( "currency_like", move |b: &mut Bencher, params: &BenchParams| { let blocks = gen_...
function_block-full_function
[ { "content": "fn gen_keypair_from_rng(rng: &mut StdRng) -> (PublicKey, SecretKey) {\n\n use exonum::crypto::{gen_keypair_from_seed, Seed, SEED_LENGTH};\n\n\n\n let mut bytes = [0_u8; SEED_LENGTH];\n\n rng.fill(&mut bytes);\n\n gen_keypair_from_seed(&Seed::new(bytes))\n\n}\n\n\n", "file_path": "e...
Rust
src/utils.rs
Majavar/drone
7d076fe94fb701483047e96ac35b9e68100a4d66
use crate::color::Color; use ansi_term::Color::Red; use anyhow::{bail, Result}; use serde::{de, ser}; use signal_hook::{iterator::Signals, SIGINT, SIGQUIT, SIGTERM}; use std::{ env, ffi::CString, fs::OpenOptions, io::{prelude::*, ErrorKind}, os::unix::{ffi::OsStrExt, io::AsRawFd, process::CommandE...
use crate::color::Color; use ansi_term::Color::Red; use anyhow::{bail, Result}; use serde::{de, ser}; use signal_hook::{iterator::Signals, SIGINT, SIGQUIT, SIGTERM}; use std::{ env, ffi::CString, fs::OpenOptions, io::{prelude::*, ErrorKind}, os::unix::{ffi::OsStrExt, io::AsRawFd, process::CommandE...
pub fn detach_pgid(command: &mut Command) { unsafe { command.pre_exec(|| { libc::setpgid(0, 0); Ok(()) }); } } pub fn check_root_result(color: Color, f: impl FnOnce() -> Result<()>) { match f() { Ok(()) => { exit(0); } Err(err) i...
d(true).open(path)?; unsafe { libc::fcntl(fifo.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) }; let mut bytes = [0_u8; 1024]; loop { match fifo.read(&mut bytes) { Ok(_) => continue, Err(ref err) if err.kind() == ErrorKind::Interrupted => continue, Err(ref err) if ...
function_block-function_prefixed
[]
Rust
src/catcollar/iouring.rs
iyzhang/demikernel
462f7e168d4ac85e758ba64a40cf051fa906e1f4
use crate::demikernel::dbuf::DataBuffer; use ::libc::socklen_t; use ::liburing::{ io_uring, io_uring_sqe, iovec, msghdr, }; use ::nix::{ errno, sys::socket::SockAddr, }; use ::runtime::fail::Fail; use ::std::{ ffi::{ c_void, CString, }, mem::MaybeUninit, os::{ ...
use crate::demikernel::dbuf::DataBuffer; use ::libc::socklen_t; use ::liburing::{ io_uring, io_uring_sqe, iovec, msghdr, }; use ::nix::{ errno, sys::socket::SockAddr, }; use ::runtime::fail::Fail; use ::std::{ ffi::{ c_void, CString, }, mem::MaybeUninit, os::{ ...
pub fn pushto(&mut self, sockfd: RawFd, addr: SockAddr, buf: DataBuffer) -> Result<u64, Fail> { let len: usize = buf.len(); let data: &[u8] = &buf[..]; let data_ptr: *const u8 = data.as_ptr(); let (sockaddr, addrlen): (&libc::sockaddr, socklen_t) = addr.as_ffi_pair(); ...
l> { let len: usize = buf.len(); let data: &[u8] = &buf[..]; let data_ptr: *const u8 = data.as_ptr(); let io_uring: &mut io_uring = &mut self.io_uring; unsafe { let sqe: *mut io_uring_sqe = liburing::io_uring_get_sqe(io_uring); if sqe.is_null...
function_block-function_prefixed
[ { "content": "fn with_libos<T>(f: impl FnOnce(&mut LibOS) -> T) -> T {\n\n LIBOS.with(|l| {\n\n let mut tls_libos: RefMut<Option<LibOS>> = l.borrow_mut();\n\n f(tls_libos.as_mut().expect(\"Uninitialized engine\"))\n\n })\n\n}\n\n\n\n//=========================================================...
Rust
src/complex/myanmar_machine.rs
ebraminio/rustybuzz
07d9419d04d956d3f588b547dcd2b36576504c6e
use crate::Buffer; const MACHINE_TRANS_KEYS: &[u8] = &[ 1, 32, 3, 30, 5, 29, 5, 8, 5, 29, 3, 25, 5, 25, 5, 25, 3, 29, 3, 29, 3, 29, 3, 29, 1, 16, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 3, 30, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 5, 29, 5, 8, 5, 29, 3, 25, 5, 25, 5, 25, 3, 29, 3, 29, 3, 29, 3, 29, 1, 16, ...
use crate::Buffer; const MACHINE_TRANS_KEYS: &[u8] = &[ 1, 32, 3, 30, 5, 29, 5, 8, 5, 29, 3, 25, 5, 25, 5, 25, 3, 29, 3, 29, 3, 29, 3, 29, 1, 16, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 3, 30, 3, 29, 3, 29, 3, 29, 3, 29, 3, 29, 5, 29, 5, 8, 5, 29, 3, 25, 5, 25, 5, 25, 3, 29, 3, 29, 3, 29, 3, 29, 1, 16, ...
*syllable_serial = 1; } }
found_syllable( start: usize, end: usize, syllable_serial: &mut u8, kind: SyllableType, buffer: &mut Buffer, ) { for i in start..end { buffer.info[i].set_syllable((*syllable_serial << 4) | kind as u8); } *syllable_serial += 1; if *syllable_serial == 16 {
function_block-random_span
[ { "content": "pub fn find_syllables(buffer: &mut Buffer) {\n\n let mut cs = 5usize;\n\n let mut ts = 0;\n\n let mut te = 0;\n\n let mut act = 0;\n\n let mut p = 0;\n\n let pe = buffer.len();\n\n let eof = buffer.len();\n\n let mut syllable_serial = 1u8;\n\n let mut reset = true;\n\n ...
Rust
garnet/bin/power_manager/src/temperature_handler.rs
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
use crate::error::PowerManagerError; use crate::log_if_err; use crate::message::{Message, MessageReturn}; use crate::node::Node; use crate::types::Celsius; use crate::utils::connect_proxy; use anyhow::{format_err, Error}; use async_trait::async_trait; use fidl_fuchsia_hardware_thermal as fthermal; use fuchsia_inspect...
use crate::error::PowerManagerError; use crate::log_if_err; use crate::message::{Message, MessageReturn}; use crate::node::Node; use crate::types::Celsius; use crate::utils::connect_proxy; use anyhow::{format_err, Error}; use async_trait::async_trait; use fidl_fuchsia_hardware_thermal as fthermal; use fuchsia_inspect...
let node = TemperatureHandlerBuilder::new_with_proxy( "Fake".to_string(), setup_fake_driver(move || temperature), ) .with_inspect_root(inspector.root()) .build() .unwrap(); node.handle_message(&Message::ReadTemperature).await.unwrap(); ...
})) } } pub struct TemperatureHandler { driver_path: String, driver_proxy: fthermal::DeviceProxy, inspect: InspectData, } impl TemperatureHandler { async fn handle_read_temperature(&self) -> Result<MessageReturn, PowerManagerError> { fuchsia_trace::duration!( "power_...
random
[]
Rust
bin/engula.rs
mmyj/engula
84f5fa7b047b750fd84a0a2dcd4a698a5d21c077
use std::path::PathBuf; use clap::{crate_description, crate_version, Parser, Subcommand}; use engula_journal::{ file::Journal as FileJournal, grpc::Server as JournalServer, mem::Journal as MemJournal, }; use engula_kernel::grpc::{FileKernel, MemKernel, Server as KernelServer}; use engula_storage::{ file::Sto...
use std::path::PathBuf; use clap::{crate_description, crate_version, Parser, Subcommand}; use engula_journal::{ file::Journal as FileJournal, grpc::Server as JournalServer, mem::Journal as MemJournal, }; use engula_kernel::grpc::{FileKernel, MemKernel, Server as KernelServer}; use engula_storage::{ file::Sto...
ernelServer::new(journal, storage, kernel); bootstrap_service!(addr, server); } }, } Ok(()) } } #[derive(Parser)] enum SubCommand { #[clap(subcommand)] Storage(StorageCommand), #[clap(subcommand)] Journal(JournalCommand), #[clap(su...
()) } } #[derive(Subcommand)] #[clap(about = "Commands to operate Journal")] enum JournalCommand { #[clap(about = "Run a journal server")] Run { #[clap(about = "Socket address to listen")] addr: String, #[clap(subcommand)] cmd: RunMode, #[clap( long, ...
random
[ { "content": "/// The main entrance of engula server.\n\npub fn run(config: Config, executor: Executor, shutdown: Shutdown) -> Result<()> {\n\n executor.block_on(async {\n\n let engines = Engines::open(&config.root_dir, &config.db)?;\n\n\n\n let root_list = if config.init {\n\n vec![...
Rust
rust-runtime/aws-smithy-client/src/lib.rs
floric/smithy-rs
ada03d4ca104f88d16d6732f91ee1d420f1f6d32
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #![warn( missing_debug_implementations, missing_docs, rustdoc::all, rust_2018_idioms )] pub mod bounds; pub mod erase; pub mod retry; #[allow(rustdoc::private_doc_tests)] mod builder; ...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #![warn( missing_debug_implementations, missing_docs, rustdoc::all, rust_2018_idioms )] pub mod bounds; pub mod erase; pub mod retry; #[allow(rustdoc::private_doc_tests)] mod builder; ...
}
y::Policy< static_tests::ValidTestOperation, SdkSuccess<()>, SdkError<static_tests::TestOperationError>, > + Clone, { let _ = |o: static_tests::ValidTestOperation| { let _ = self.call_raw(o); }; }
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\n#[cfg(all(test, feature = \"hyper\"))]\n\nfn sanity_hyper(hc: crate::hyper_impls::HyperAdapter<hyper::client::HttpConnector>) {\n\n Builder::new()\n\n .middleware(tower::layer::util::Identity::new())\n\n .connector(hc)\n\n .build()\n\n .check()...
Rust
tesseract-server/src/app.rs
frabarz/tesseract
4ef7a2cdf8810f0077a35ecbf62fbeb89e383d36
use actix_web::{ http::Method, middleware, App, http::NormalizePath, }; use tesseract_core::{Backend, Schema, CubeHasUniqueLevelsAndProperties}; use crate::db_config::Database; use crate::handlers::{ aggregate_handler, aggregate_default_handler, aggregate_stream_handler, aggregate_stream...
use actix_web::{ http::Method, middleware, App, http::NormalizePath, }; use tesseract_core::{Backend, Schema, CubeHasUniqueLevelsAndProperties}; use crate::db_config::Database; use crate::handlers::{ aggregate_handler, aggregate_default_handler, aggregate_stream_handler, aggregate_stream...
; match has_unique_levels_properties { CubeHasUniqueLevelsAndProperties::True => { app .resource("/data", |r| { r.method(Method::GET).with(logic_layer_default_handler) }) .resource("/data.{format}", |r| { ...
if streaming_response { app .resource("/cubes/{cube}/aggregate", |r| { r.method(Method::GET).with(aggregate_stream_default_handler) }) .resource("/cubes/{cube}/aggregate.{format}", |r| { r.method(Method::GET).with(aggregate_stream_handler) ...
if_condition
[]
Rust
kernel-rs/src/bio.rs
anemoneflower/rv6-1
9dc037339e9d0991c2d8dc4408517fb6d0dcb270
use crate::{ arena::{Arena, ArenaObject, MruArena, MruEntry, Rc}, param::{BSIZE, NBUF}, proc::WaitChannel, sleeplock::Sleeplock, spinlock::Spinlock, }; use core::mem; use core::ops::{Deref, DerefMut}; pub struct BufEntry { dev: u32, pub blockno: u32, pub vdisk_request_waitchann...
use crate::{ arena::{Arena, ArenaObject, MruArena, MruEntry, Rc}, param::{BSIZE, NBUF}, proc::WaitChannel, sleeplock::Sleeplock, spinlock::Spinlock, }; use core::mem; use core::ops::{Deref, DerefMut}; pub struct BufEntry { dev: u32, pub blockno: u32, pub vdisk_request_waitchann...
pub fn buf_unforget(&self, dev: u32, blockno: u32) -> Option<BufUnlocked<'_>> { let inner = self.unforget(|buf| buf.dev == dev && buf.blockno == blockno)?; Some(unsafe { Rc::from_unchecked(self, inner) }) } } impl<'s> BufUnlocked<'s> { pub fn lock(self) -> Buf<'s> { mem::for...
pub fn get_buf(&self, dev: u32, blockno: u32) -> BufUnlocked<'_> { let inner = self .find_or_alloc( |buf| buf.dev == dev && buf.blockno == blockno, |buf| { buf.dev = dev; buf.blockno = blockno; buf.inner.get_...
function_block-full_function
[ { "content": "pub trait ArenaObject {\n\n fn finalize<'s, A: Arena>(&'s mut self, guard: &'s mut A::Guard<'_>);\n\n}\n\n\n\npub struct ArrayEntry<T> {\n\n refcnt: usize,\n\n data: T,\n\n}\n\n\n\n/// A homogeneous memory allocator equipped with reference counts.\n\npub struct ArrayArena<T, const CAPACIT...
Rust
src/flash/efuse.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register EFUSE"] pub type R = crate::R<u32, super::EFUSE>; #[doc = "Writer for register EFUSE"] pub type W = crate::W<u32, super::EFUSE>; #[doc = "Register EFUSE `reset()`'s with value 0"] impl crate::ResetValue for super::EFUSE { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
#[doc = "Reader of register EFUSE"] pub type R = crate::R<u32, super::EFUSE>; #[doc = "Writer for register EFUSE"] pub type W = crate::W<u32, super::EFUSE>; #[doc = "Register EFUSE `reset()`'s with value 0"] impl crate::ResetValue for super::EFUSE { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
mut W, } impl<'a> INSTRUCTION_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 24)) | (((value as u32) & 0x1f) << 24); self.w } } #[doc = "Reader of field `RESERVED16`"] pub type R...
pub type RESERVED29_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RESERVED29`"] pub struct RESERVED29_W<'a> { w: &'a mut W, } impl<'a> RESERVED29_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.b...
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/biunify/mod.rs
andrewhickman/mlsub-rs
f6011bf12ba4b834315a9dfdfcd942747f796566
#[cfg(test)] mod reference; #[cfg(test)] mod tests; use std::convert::Infallible; use std::fmt::{self, Debug}; use std::iter::once; use crate::auto::{Automaton, StateId}; use crate::{Constructor, Label, Polarity}; pub type Result<C> = std::result::Result<(), Error<C>>; #[derive(Debug)] pub struct Error<C: Construct...
#[cfg(test)] mod reference; #[cfg(test)] mod tests; use std::convert::Infallible; use std::fmt::{self, Debug}; use std::iter::once; use crate::auto::{Automaton, StateId}; use crate::{Constructor, Label, Polarity}; pub type Result<C> = std::result::Result<(), Error<C>>; #[derive(Debug)] pub struct Error<C: Construct...
m = (I::Item, J::Item)> where I: IntoIterator, I::Item: Clone + Copy, J: IntoIterator, J: Clone, { lhs.into_iter() .flat_map(move |l| rhs.clone().into_iter().map(move |r| (l.clone(), r))) } impl<C> Debug for CacheEntry<C> where C: Constructor + Debug, C::Label: Debug, { fn fmt(&...
} fn make_error(&self, pos: (StateId, C), neg: (StateId, C)) -> Error<C> { let mut stack = Vec::new(); let mut key = (pos.0, neg.0); while let CacheEntry::RequiredBy { label, pos, neg } = &self.biunify_cache[&key] { stack.push((label.clone(), pos.1.clone(), neg.1.clone()));...
random
[ { "content": "pub fn arb_auto_ty(pol: Polarity) -> BoxedStrategy<(Automaton<Constructor>, StateId)> {\n\n arb_polar_ty(pol)\n\n .prop_map(move |ty| {\n\n let mut auto = Automaton::new();\n\n let mut builder = auto.builder();\n\n let id = builder.build_polar(pol, &ty);\...
Rust
kaylee/src/vm.rs
electricjones/kaylee
6cdc7e67ae8a3d9a989d8d18def496c9ceecab40
use crate::instructions::{decode_next_instruction, Instruction}; use crate::program::{Program, ProgramIndex}; pub type RegisterId = usize; pub type RegisterValue = i32; pub type Byte = u8; pub type HalfWord = u16; pub type Word = u32; pub type DoubleWord = u32; pub enum ExecutionResult { Halted, NoAction, ...
use crate::instructions::{decode_next_instruction, Instruction}; use crate::program::{Program, ProgramIndex}; pub type RegisterId = usize; pub type RegisterValue = i32; pub type Byte = u8; pub type HalfWord = u16; pub type Word = u32; pub type DoubleWord = u32; pub enum ExecutionResult { Halted, NoAction, ...
x { self.program_counter } pub(crate) fn set_program_counter(&mut self, index: ProgramIndex) { self.program_counter = index } } #[cfg(test)] mod tests { }
Ok(*&self.registers[register].clone()) } pub(crate) fn all_registers(&self) -> [RegisterValue; Kaylee::REGISTER_COUNT] { *&self.registers.clone() } pub(crate) fn set_register(&mut self, register: RegisterId, value: RegisterValue) -> Result<(), ()> { if register > Kaylee::REGISTER_COU...
random
[ { "content": "/// Decode the next instruction in the Program stream\n\npub fn decode_next_instruction(instructions: &Program, program_counter: &mut usize) -> Option<Result<Box<dyn Instruction>, InstructionDecodeError>> {\n\n // @todo: I am not super happy with this decoding scheme. It should probably grab th...
Rust
src/librustc/ich/impls_ty.rs
amsantavicca/rust
730e5ad04e23f30cc24e4b87dfd5da807325e243
use ich::StableHashingContext; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult}; use std::hash as std_hash; use std::mem; use ty; impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Ty<'tcx> { fn hash_stable<W: Stabl...
use ich::StableHashingContext; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult}; use std::hash as std_hash; use std::mem; use ty; impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for ty::Ty<'tcx> { fn hash_stable<W: Stabl...
} impl_stable_hash_for!(struct ty::TypeParameterDef { name, def_id, index, has_default, object_lifetime_default, pure_wrt_drop }); impl<'a, 'tcx, T> HashStable<StableHashingContext<'a, 'tcx>> for ::middle::resolve_lifetime::Set1<T> where T: HashStable<StableHashingContext<'a, 'tcx>> { ...
issue_32330: _, pure_wrt_drop } = *self; name.hash_stable(hcx, hasher); def_id.hash_stable(hcx, hasher); index.hash_stable(hcx, hasher); pure_wrt_drop.hash_stable(hcx, hasher); }
function_block-function_prefix_line
[ { "content": "trait Trait2<T1, T2> { fn dummy(&self, _: T1, _:T2) { } }\n\n\n\nimpl Trait1 for isize {}\n\nimpl<T1, T2> Trait2<T1, T2> for isize {}\n\n\n", "file_path": "src/test/debuginfo/type-names.rs", "rank": 0, "score": 563144.9302896057 }, { "content": "// We push types on the stack in...
Rust
src/cast/mod.rs
RottenFishbone/mucaster
9a3e1395e6ae942422d29250e7169547e9ca49e2
#![allow(dead_code, unused_variables)] pub mod error; use error::CastError; use mdns::{Record, RecordKind}; use futures_util::{pin_mut, stream::StreamExt}; use regex::Regex; use serde::{Serialize, ser::SerializeStruct}; use warp::hyper::{Client, body::HttpBody}; use std::{future, net::{IpAddr, UdpSocket}, sync::{mpsc:...
#![allow(dead_code, unused_variables)] pub mod error; use error::CastError; use mdns::{Record, RecordKind}; use futures_util::{pin_mut, stream::StreamExt}; use regex::Regex; use serde::{Serialize, ser::SerializeStruct}; use warp::hyper::{Client, body::HttpBody}; use std::{future, net::{IpAddr, UdpSocket}, sync::{mpsc:...
; } ChannelMessage::Heartbeat(resp) => { if let HeartbeatResponse::Ping = resp { device.heartbeat.pong().unwrap(); log::info!("[Heartbeat] Pong sent."); ...
Some((msg.clone(), format!("[Device] Message could not be parsed: {:?}", resp)))
call_expression
[ { "content": "/// Spin and wait for a response from the passed reciever.\n\n/// # Parameters\n\n/// oneshot::Receiver<String> - A reciever, with the sender linked to the api::Request\n\n/// # Returns\n\n/// Result<String, String> - API response on success, \"Failed to reach API\" on failure. \n\npub fn await_ap...
Rust
dora/src/vm/modules.rs
dinfuehr/dora
bcfdac576b729e2bbb2422d0239426b884059b2c
use parking_lot::RwLock; use std::sync::Arc; use crate::semck::specialize::replace_type_param; use crate::size::InstanceSize; use crate::ty::SourceType; use crate::utils::GrowableVec; use crate::vm::{ accessible_from, namespace_path, Candidate, FctId, Field, FieldDef, FileId, NamespaceId, TraitId, VM, }; use ...
use parking_lot::RwLock; use std::sync::Arc; use crate::semck::specialize::replace_type_param; use crate::size::InstanceSize; use crate::ty::SourceType; use crate::utils::GrowableVec; use crate::vm::{ accessible_from, namespace_path, Candidate, FctId, Field, FieldDef, FileId, NamespaceId, TraitId, VM, }; use ...
} pub fn module_accessible_from(vm: &VM, module_id: ModuleId, namespace_id: NamespaceId) -> bool { let module = vm.modules.idx(module_id); let module = module.read(); accessible_from(vm, module.namespace_id, module.is_pub, namespace_id) }
pub fn name(&self, vm: &VM) -> String { if let Some(module_id) = self.mod_id { let module = vm.modules.idx(module_id); let module = module.read(); let name = vm.interner.str(module.name); format!("{}", name) } else { "<Unknown>".into() ...
function_block-full_function
[ { "content": "pub fn namespace_path(vm: &VM, namespace_id: NamespaceId, name: Name) -> String {\n\n let namespace = &vm.namespaces[namespace_id.to_usize()];\n\n let mut result = namespace.name(vm);\n\n\n\n if !result.is_empty() {\n\n result.push_str(\"::\");\n\n }\n\n\n\n result.push_str(&...
Rust
src/audio/channels/noise.rs
super-rust-boy/super-rust-boy
53555c60278359877a3a6fe4bb7175f129e803e6
use super::*; const MAX_LEN: u8 = 64; pub struct Noise { pub length_reg: u8, pub vol_envelope_reg: u8, pub poly_counter_reg: u8, pub trigger_reg: u8, enabled: bool, lfsr_counter: u16, volume: u8, volume_counter: Option<u8>, volume_mod...
use super::*; const MAX_LEN: u8 = 64; pub struct Noise { pub length_reg: u8, pub vol_envelope_reg: u8, pub poly_counter_reg: u8, pub trigger_reg: u8, enabled: bool, lfsr_counter: u16, volume: u8, volume_counter: Option<u8>, volume_mod...
}
n lfsr_step(&mut self) { const LFSR_MASK: u16 = 0x3FFF; const LFSR_7BIT_MASK: u16 = 0xFFBF; let low_bit = self.lfsr_counter & 1; self.lfsr_counter >>= 1; let xor_bit = (self.lfsr_counter & 1) ^ low_bit; self.lfsr_counter = (self.lfsr_counter & LFSR_MASK) | (xor_bit << 1...
function_block-function_prefixed
[ { "content": "// Convert from 4-bit signed samples to 32-bit floating point.\n\npub fn i4_to_f32(amplitude: u8) -> f32 {\n\n const MAX_AMP: f32 = 7.5;\n\n\n\n ((amplitude as f32) - MAX_AMP) / MAX_AMP\n\n}", "file_path": "src/audio/channels/mod.rs", "rank": 0, "score": 189128.31516370102 }, ...
Rust
src/app/procedure.rs
luxrck/sic
6dd2bda9ff7d19387db82e271abb614e1d9dab9d
use std::error::Error; use std::io::Read; use std::path::Path; use clap::ArgMatches; use sic_core::image; use sic_image_engine::engine::ImageEngine; use sic_io::conversion::AutomaticColorTypeAdjustment; use sic_io::format::{ DetermineEncodingFormat, EncodingFormatByIdentifier, EncodingFormatByMethod, JPEGQuality, ...
use std::error::Error; use std::io::Read; use std::path::Path; use clap::ArgMatches; use sic_core::image; use sic_image_engine::engine::ImageEngine; use sic_io::conversion::AutomaticColorTypeAdjustment; use sic_io::format::{ DetermineEncodingFormat, EncodingFormatByIdentifier, EncodingFormatByMethod, JPEGQuality, ...
pub fn run_display_licenses(config: &Config) -> Result<(), String> { config .show_license_text_of .ok_or_else(|| "Unable to display license texts".to_string()) .and_then(|license_text| license_text.print()) }
function_block-full_function
[ { "content": "// Here any argument should not panic when invalid.\n\n// Previously, it was allowed to panic within Config, but this is no longer the case.\n\npub fn build_app_config<'a>(matches: &'a ArgMatches) -> Result<Config<'a>, String> {\n\n let mut builder = ConfigBuilder::new();\n\n\n\n // organisa...
Rust
splashsurf/src/io/vtk_format.rs
rezural/splashsurf
a5e5497e08d32bce92d5f5016ae8a33550f5598d
use anyhow::{anyhow, Context}; use splashsurf_lib::mesh::{MeshWithData, TriMesh3d}; use splashsurf_lib::nalgebra::Vector3; use splashsurf_lib::vtkio; use splashsurf_lib::vtkio::model::{ Attributes, CellType, Cells, UnstructuredGridPiece, VertexNumbers, }; use splashsurf_lib::Real; use std::fs::create_dir_all; use s...
use anyhow::{anyhow, Context}; use splashsurf_lib::mesh::{MeshWithData, TriMesh3d}; use splashsurf_lib::nalgebra::Vector3; use splashsurf_lib::vtkio; use splashsurf_lib::vtkio::model::{ Attributes, CellType, Cells, UnstructuredGridPiece, VertexNumbers, }; use splashsurf_lib::Real; use std::fs::create_dir_all; use s...
struct Particles<'a, R: Real>(&'a [Vector3<R>]); impl<'a, R> From<Particles<'a, R>> for UnstructuredGridPiece where R: Real, { fn from(particles: Particles<'a, R>) -> Self { let particles = particles.0; let points = { let mut points: Vec<R> = Vec::with_capacity(particles.len() * ...
e); cell_verts.chunks_exact(4).try_for_each(|cell| { if cell[0] == 3 { cells.push([cell[1] as usize, cell[2] as usize, cell[3] as usize]); Ok(()) } else { Err(anyhow!("...
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn to_binary_f32<R: Real, P: AsRef<Path>>(file: P, values: &[R]) -> Result<(), anyhow::Error> {\n\n let file = file.as_ref();\n\n let file = File::create(file).context(\"Unable to create binary file\")?;\n\n let mut writer = BufWriter::new(file);\n\n\n\n for ...
Rust
tests/support/mod.rs
aanari/redis-rs
eb367b927cb65cd2da302bd0534ce330d72a48ef
#![allow(dead_code)] use futures; use net2; use rand; use redis; use std::env; use std::fs; use std::io::{self, Write}; use std::process; use std::thread::sleep; use std::time::Duration; use std::path::PathBuf; use self::futures::Future; use redis::Value; pub fn current_thread_runtime() -> tokio::runtime::Runtim...
#![allow(dead_code)] use futures; use net2; use rand; use redis; use std::env; use std::fs; use std::io::{self, Write}; use std::process; use std::thread::sleep; use std::time::Duration; use std::path::PathBuf; use self::futures::Future; use redis::Value; pub fn current_thread_runtime() -> tokio::runtime::Runtim...
} impl RedisServer { pub fn new() -> RedisServer { let server_type = ServerType::get_intended(); match server_type { ServerType::Tcp { tls } => { let redis_listener = net2::TcpBuilder::new_v4() .unwrap() ...
fn get_intended() -> ServerType { match env::var("REDISRS_SERVER_TYPE") .ok() .as_ref() .map(|x| &x[..]) { Some("tcp") => ServerType::Tcp { tls: false }, Some("tcp+tls") => ServerType::Tcp { tls: true }, Some("unix") => ServerType::...
function_block-full_function
[ { "content": "fn check_connection(conn: &mut Connection) -> bool {\n\n let mut cmd = Cmd::new();\n\n cmd.arg(\"PING\");\n\n cmd.query::<String>(conn).is_ok()\n\n}\n\n\n", "file_path": "src/cluster.rs", "rank": 2, "score": 187254.723174657 }, { "content": "fn write_command<'a, I>(cmd...
Rust
zscene/examples/action.rs
zouharvi/zemeroth
455c8c82991b4bfc40fddf68f66f59d67d1641e1
use std::time::Duration; use mq::{ camera::{set_camera, Camera2D}, color::{Color, BLACK}, math::{Rect, Vec2}, text, texture::{self, Texture2D}, time, window, }; use zscene::{self, action, Action, Boxed, Layer, Scene, Sprite}; #[derive(Debug)] pub enum Err { File(mq::file::FileError), F...
use std::time::Duration; use mq::{ camera::{set_camera, Camera2D}, color::{Color, BLACK}, math::{Rect, Vec2}, text, texture::{self, Texture2D}, time, window, }; use zscene::{self, action, Action, Boxed, Layer, Scene, Sprite}; #[derive(Debug)] pub enum Err { File(mq::file::FileError), F...
ut state = State::new(assets); { state.scene.add_action(state.action_demo_move()); state.scene.add_action(state.action_demo_show_hide()); } loop { window::clear_background(BLACK); update_aspect_ratio(); let dtime = time::get_frame_time(); state.scene....
function_block-function_prefixed
[ { "content": "fn arc_move(view: &mut BattleView, sprite: &Sprite, diff: Vec2) -> Box<dyn Action> {\n\n let len = diff.length();\n\n let min_height = view.tile_size() * 0.5;\n\n let base_height = view.tile_size() * 2.0;\n\n let min_time = 0.25;\n\n let base_time = 0.3;\n\n let height = min_heig...
Rust
src/decomposition/lu.rs
vinesystems/lair
b28b0949ae8bcf49bb58c665df0d24e0b6dab90b
use crate::{lapack, InvalidInput, Real, Scalar}; use ndarray::{s, Array1, Array2, ArrayBase, Data, DataMut, Ix1, Ix2}; use std::cmp; use std::fmt; #[derive(Debug)] pub struct Factorized<A, S> where A: fmt::Debug, S: Data<Elem = A>, { lu: ArrayBase<S, Ix2>, pivots: Vec<usize>, singular: Option<usi...
use crate::{lapack, InvalidInput, Real, Scalar}; use ndarray::{s, Array1, Array2, ArrayBase, Data, DataMut, Ix1, Ix2}; use std::cmp; use std::fmt; #[derive(Debug)] pub struct Factorized<A, S> where A: fmt::Debug, S: Data<Elem = A>, { lu: ArrayBase<S, Ix2>, pivots: Vec<usize>, singular: Option<usi...
} #[cfg(test)] mod tests { use approx::assert_relative_eq; use ndarray::{arr2, s}; use std::cmp; #[test] fn square() { let a = arr2(&[ [1_f32, 2_f32, 3_f32], [2_f32, 2_f32, 1_f32], [3_f32, 1_f32, 2_f32], ]); let lu = super::Factorized::f...
fn from(mut a: ArrayBase<S, Ix2>) -> Self { let (pivots, singular) = lapack::getrf(a.view_mut()); Factorized { lu: a, pivots, singular, } }
function_block-function_prefix_line
[ { "content": "/// Solves `a * x = b`.\n\n///\n\n/// # Panics\n\n///\n\n/// Panics if the number of rows in `a` is different from the number of elements\n\n/// in `p` or the number of elements in `b`, or the number of columns in `a` is\n\n/// smaller than the number of elements in `p`.\n\npub fn getrs<A, SA, SB>...
Rust
lib/src/parser.rs
mkfoo/midilisp
d08093c70b0037f8f221be75c46e7b1f1ef1ed6c
use crate::{ error::{Error, Result}, lexer::{Lexer, Token}, value::Value, FnvIndexSet, }; use smol_str::SmolStr; use std::cmp::PartialEq; use Token::*; pub type AstPtr = u32; pub type StrId = u32; pub const NIL: AstPtr = 0; const LPAR: AstPtr = 1; #[derive(Debug, Clone, Copy, PartialEq)] pub enum Expr...
use crate::{ error::{Error, Result}, lexer::{Lexer, Token}, value::Value, FnvIndexSet, }; use smol_str::SmolStr; use std::cmp::PartialEq; use Token::*; pub type AstPtr = u32; pub type StrId = u32; pub const NIL: AstPtr = 0; const LPAR: AstPtr = 1; #[derive(Debug, Clone, Copy, PartialEq)] pub enum Expr...
#[test] fn list() { let src = "(1 2 3)"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); let (car, cdr) = exp_cons(&parser, exprs[0]); assert_eq!(Atom(I32(1)), parser.get(car)); let (car, cdr) = exp_cons(&parser, cdr); assert_eq!(...
fn literals() { let src = "5 -5 0xff 0b1010 0.5 .5"; let mut parser = Parser::new(); let exprs = parser.parse(src).unwrap(); assert_eq!(Atom(I32(5)), parser.get(exprs[0])); assert_eq!(Atom(I32(-5)), parser.get(exprs[1])); assert_eq!(Atom(U32(0xff)), parser.get(exprs[2]));...
function_block-full_function
[ { "content": "type BuiltinFn<T> = fn(&mut T, AstPtr) -> Result<Value>;\n", "file_path": "lib/src/interpreter.rs", "rank": 0, "score": 173176.83868602625 }, { "content": "type LexFn<T> = fn(&mut T) -> Token;\n\n\n\npub struct Lexer<'a> {\n\n f: LexFn<Self>,\n\n iter: CharIndices<'a>,\n\...
Rust
src/tcp/hole_punch/puncher.rs
nbaksalyar/p2p
fbdc95585ee180af2d15c1e135de08021c6510db
use mio::tcp::TcpStream; use mio::timer::Timeout; use mio::{Poll, PollOpt, Ready, Token}; use net2::TcpStreamExt; use socket_collection::TcpSock; use sodium::crypto::box_; use std::any::Any; use std::cell::RefCell; use std::mem; use std::net::SocketAddr; use std::rc::Rc; use std::time::{Duration, Instant}; use tcp::new...
use mio::tcp::TcpStream; use mio::timer::Timeout; use mio::{Poll, PollOpt, Ready, Token}; use net2::TcpStreamExt; use socket_collection::TcpSock; use sodium::crypto::box_; use std::any::Any; use std::cell::RefCell; use std::mem; use std::net::SocketAddr; use std::rc::Rc; use std::time::{Duration, Instant}; use tcp::new...
: {:?}", e); ok = false; break; } } } if ok { self.done(ifc, poll) } else { self.handle_err(ifc, poll) } } fn write(&mut self, ifc: &mut Interface, poll: &Poll, m: Option<Vec<u8>>) { ...
msg_to_read(&cipher_text, key) { Ok(ref plain_text) if plain_text == &CHOOSE_CONN => ok = true, _ => { debug!("Error: Failed to decrypt a connection-choose order"); ok = false; ...
function_block-random_span
[ { "content": "/// Utility function to decrypt messages from peer\n\npub fn msg_to_read(raw: &[u8], key: &box_::PrecomputedKey) -> ::Res<Vec<u8>> {\n\n let CryptMsg { nonce, cipher_text } = deserialize(raw)?;\n\n box_::open_precomputed(&cipher_text, &box_::Nonce(nonce), key)\n\n .map_err(|()| NatErr...
Rust
santa/src/music.rs
BruceBrown/abstreet
3071dece5b0f95f887841a39c3d1aeb94bfdd9dd
use std::io::Cursor; use anyhow::Result; use rodio::{Decoder, OutputStream, OutputStreamHandle, Sink}; use widgetry::{ Checkbox, EventCtx, GfxCtx, HorizontalAlignment, Outcome, Panel, StyledButtons, VerticalAlignment, }; pub const OUT_OF_GAME: f32 = 0.5; pub const IN_GAME: f32 = 1.0; pub struct Music { ...
use std::io::Cursor; use anyhow::Result; use rodio::{Decoder, OutputStream, OutputStreamHandle, Sink}; use widgetry::{ Checkbox, EventCtx, GfxCtx, HorizontalAlignment, Outcome, Panel, StyledButtons, VerticalAlignment, }; pub const OUT_OF_GAME: f32 = 0.5; pub const IN_GAME: f32 = 1.0; pub struct Music { ...
} fn unmute(&mut self) { self.sink.set_volume(self.unmuted_volume); } fn mute(&mut self) { self.sink.set_volume(0.0); } fn specify_volume(&mut self, volume: f32) { self.unmuted_volume = volume; if self.sink.volume() != 0.0 { self.unmute(); }...
_checked("play music") { *play_music = true; inner.unmute(); } else { *play_music = false; inner.mute(); } } _ => {} } } } ...
random
[ { "content": "// TODO Kinda misnomer\n\npub fn tool_panel(ctx: &mut EventCtx) -> Panel {\n\n Panel::new(Widget::row(vec![\n\n ctx.style()\n\n .btn_plain_light_icon(\"system/assets/tools/home.svg\")\n\n .hotkey(Key::Escape)\n\n .build_widget(ctx, \"back\"),\n\n c...
Rust
src/client/connect.rs
aturon/hyper
8c6e6f51abb0dd02123b8bfafa9277850623b810
use std::collections::hash_map::{HashMap, Entry}; use std::hash::Hash; use std::fmt; use std::io; use std::net::SocketAddr; use rotor::mio::tcp::TcpStream; use url::Url; use net::{HttpStream, HttpsStream, Transport, SslClient}; use super::dns::Dns; use super::Registration; pub trait Connect { type Output: T...
use std::collections::hash_map::{HashMap, Entry}; use std::hash::Hash; use std::fmt; use std::io; use std::net::SocketAddr; use rotor::mio::tcp::TcpStream; use url::Url; use net::{HttpStream, HttpsStream, Transport, SslClient}; use super::dns::Dns; use super::Registration; pub trait Connect { type Output: T...
fn connect(&mut self, url: &Url) -> io::Result<Self::Key> { debug!("Https::connect({:?})", url); if let Some(key) = self.key(url) { let host = url.host_str().expect("http scheme must have a host"); self.http.dns.as_ref().expect("dns workers lost").resolve(host); ...
e, url.host_str().expect("http scheme must have host").to_owned(), url.port_or_known_default().expect("http scheme must have a port"), )) }
function_block-function_prefixed
[ { "content": "pub trait Key: Eq + Hash + Clone + fmt::Debug {}\n\nimpl<T: Eq + Hash + Clone + fmt::Debug> Key for T {}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n /* TODO:\n\n test when the underlying Transport of a Conn is blocked on an action that\n\n differs from the desired interest().\n\n\n\n Ex:\n\...
Rust
src/multihash.rs
woss/rust-multihash
3e5c8392960762588c62508fcf7bb2d71a1a1d1a
use crate::Error; #[cfg(feature = "alloc")] use alloc::vec::Vec; use core::convert::TryFrom; use core::convert::TryInto; use core::fmt::Debug; #[cfg(feature = "serde-codec")] use serde_big_array::BigArray; use unsigned_varint::encode as varint_encode; #[cfg(feature = "std")] use std::io; #[cfg(not(feature = "std"))...
use crate::Error; #[cfg(feature = "alloc")] use alloc::vec::Vec; use core::convert::TryFrom; use core::convert::TryInto; use core::fmt::Debug; #[cfg(feature = "serde-codec")] use serde_big_array::BigArray; use unsigned_varint::encode as varint_encode; #[cfg(feature = "std")] use std::io; #[cfg(not(feature = "std"))...
ad_exact(&mut digest[..size as usize])?; Ok((code, size as u8, digest)) } #[cfg(feature = "std")] pub(crate) use unsigned_varint::io::read_u64; #[cfg(not(feature = "std"))] pub(crate) fn read_u64<R: io::Read>(mut r: R) -> Result<u64, Error> { use unsigned_varint::decode; let mut b = varint_encode::u64_buf...
mut bytes = Vec::with_capacity(self.size().into()); self.write(&mut bytes) .expect("writing to a vec should never fail"); bytes } pub fn truncate(&self, size: u8) -> Self { let mut mh = *self; mh.size = mh.size.min(s...
random
[ { "content": "pub fn use_crate(name: &str) -> Result<syn::Ident, Error> {\n\n match crate_name(name) {\n\n Ok(FoundCrate::Name(krate)) => Ok(syn::Ident::new(&krate, Span::call_site())),\n\n Ok(FoundCrate::Itself) => Ok(syn::Ident::new(\"crate\", Span::call_site())),\n\n Err(err) => Err(E...
Rust
examples/forest/src/main.rs
dbuch/three-d
8263eb240c98cff6dcfd6832c0c2572e4bf032e8
#[cfg(not(target_arch = "wasm32"))] #[tokio::main] async fn main() { run().await; } use three_d::*; pub async fn run() { let window = Window::new(WindowSettings { title: "Forest!".to_string(), max_size: Some((1280, 720)), ..Default::default() }) .unwrap(); let context = wi...
#[cfg(not(target_arch = "wasm32"))] #[tokio::main] async fn main() { run().await; } use three_d::*; pub async fn run() { let window = Window::new(WindowSettings { title: "Forest!".to_string(), max_size: Some((1280, 720)), ..Default::default() }) .unwrap(); let context = wi...
acanthos_leaf_color_b1.jpg", "examples/assets/maps/gleditsia_triacanthos_leaf_mask.jpg", ]) .await .unwrap(); let (mut meshes, materials) = loaded.obj(".obj").unwrap(); let mut models = Vec::new(); for mut mesh in meshes.drain(..) { mesh.compute_normals(); let mut mo...
function_block-function_prefixed
[ { "content": "pub fn run() {\n\n let window = Window::new(WindowSettings {\n\n title: \"Fireworks!\".to_string(),\n\n max_size: Some((1280, 720)),\n\n ..Default::default()\n\n })\n\n .unwrap();\n\n let context = window.gl().unwrap();\n\n\n\n let mut camera = Camera::new_persp...
Rust
src/elf_sections.rs
Caduser2020/multiboot2-elf64
e6aff7cbdc2ab75a85de0b0b9c0ed9f095ff03ad
use header::Tag; #[derive(Debug)] pub struct ElfSectionsTag { inner: *const ElfSectionsTagInner, offset: usize, } pub unsafe fn elf_sections_tag(tag: &Tag, offset: usize) -> ElfSectionsTag { assert_eq!(9, tag.typ); let es = ElfSectionsTag { inner: (tag as *const Tag).offset(1) as *const ElfSec...
use header::Tag; #[derive(Debug)] pub struct ElfSectionsTag { inner: *const ElfSectionsTagInner, offset: usize, } pub unsafe fn elf_sections_tag(tag: &Tag, offset: usize) -> ElfSectionsTag { assert_eq!(9, tag.typ); let es = ElfSectionsTag { inner: (tag as *const Tag).offset(1) as *const ElfSec...
-> u64 { self.size.into() } fn addralign(&self) -> u64 { self.addralign.into() } } impl ElfSectionInner for ElfSectionInner64 { fn name_index(&self) -> u32 { self.name_index } fn typ(&self) -> u32 { self.typ } fn flags(&self) -> u64 { self.fla...
SectionIter { current_section: self.first_section(), remaining_sections: self.get().number_of_sections, entry_size: self.get().entry_size, string_section: string_section_ptr, offset: self.offset, } } fn first_section(&self) -> *const u8 { ...
random
[]
Rust
opal/macros/src/parser.rs
Txuritan/varela
4d3446b41c7aa7308cf8402c4ff0ddaebde3a08d
pub fn parse(text: &str) -> Vec<Stage4> { pass_4(pass_3(pass_2(pass_1(text)))) } enum Stage1 { Open, Close, Other(char), } #[inline] fn pass_1(text: &str) -> Vec<Stage1> { let mut iter = text.chars().peekable(); let mut tokens = Vec::new(); while let Some(c) = iter.next()...
pub fn parse(text: &str) -> Vec<Stage4> { pass_4(pass_3(pass_2(pass_1(text)))) } enum Stage1 { Open, Close, Other(char), } #[inline] fn pass_1(text: &str) -> Vec<Stage1> { let mut iter = text.chars().peekable(); let mut tokens = Vec::new(); while let Some(c) = iter.next()...
#[allow(clippy::while_let_on_iterator)] #[inline] fn pass_4_for<I>(iter: &mut I) -> Vec<Stage4> where I: Iterator<Item = Stage3>, { let mut exprs = Vec::new(); while let Some(token) = iter.next() { match token { Stage3::Expr(expr) => { let trimmed_expr = e...
fn pass_4_if<I>(iter: &mut I) -> (Vec<Stage4>, Option<Vec<Stage4>>) where I: Iterator<Item = Stage3>, { let mut if_exprs = Vec::new(); let mut else_exprs = Vec::new(); let mut in_else = false; while let Some(token) = iter.next() { let mut_expr = if in_else { &mut els...
function_block-full_function
[ { "content": "pub fn write_string<W: Write>(writer: &mut W, text: &str) -> Result<(), Error> {\n\n let bytes = text.as_bytes();\n\n\n\n write_length(writer, bytes.len())?;\n\n writer.write_all(bytes)?;\n\n\n\n Ok(())\n\n}\n\n\n\npub mod structure {\n\n use {\n\n crate::{bytes::*, io, Error...
Rust
guifuzz/src/lib.rs
gamozolabs/guifuzz
471d744e0e46d21cad39e4287ddc6f13c9811b17
pub mod winbindings; pub mod rng; use std::error::Error; use std::collections::{HashSet, HashMap}; use std::sync::{Mutex, Arc}; pub use rng::Rng; pub use winbindings::Window; pub type FuzzInput = Arc<Vec<FuzzerAction>>; #[derive(Default)] pub struct Statistics { pub fuzz_cases: u64, pub coverage_d...
pub mod winbindings; pub mod rng; use std::error::Error; use std::collections::{HashSet, HashMap}; use std::sync::{Mutex, Arc}; pub use rng::Rng; pub use winbindings::Window; pub type FuzzInput = Arc<Vec<FuzzerAction>>; #[derive(Default)] pub struct Statistics { pub fuzz_cases: u64, pub coverage_d...
pub fn mutate(stats: Arc<Mutex<Statistics>>) -> Result<Vec<FuzzerAction>, Box<dyn Error>> { let rng = Rng::new(); let stats = stats.lock().unwrap(); let input_sel = rng.rand() % stats.input_list.len(); let mut input: Vec<FuzzerAction> = (*stats.input_list[input_sel]).clone(); ...
let primary_window = Window::attach_pid(pid, "Calculator")?; for &action in actions { match action { FuzzerAction::LeftClick { idx } => { let sub_windows = primary_window.enumerate_subwindows(); if sub_windows.is_err() { retur...
function_block-function_prefix_line
[ { "content": "/// Function invoked on breakpoints\n\n/// (debugger, tid, address of breakpoint,\n\n/// number of times breakpoint has been hit)\n\n/// If this returns false the debuggee is terminated\n\ntype BreakpointCallback = fn(&mut Debugger, u32, usize, u64) -> bool;\n\n\n\n/// Ctrl+C handler so we can re...
Rust
src/es32/ffi.rs
Michael-Lfx/opengles-rs
95aa94e600cea152047fe8642bb74a398012dab0
use types::*; pub type GLDEBUGPROC = ::std::option::Option< unsafe extern "C" fn( source: GLenum, type_: GLenum, id: GLuint, severity: GLenum, length: GLsizei, message: *const GLchar, userParam: *const GLvoid, ), >; extern "C" { pub fn glBlendBarrie...
use types::*; pub type GLDEBUGPROC = ::std::option::Option< unsafe extern "C" fn( source: GLenum, type_: GLenum, id: GLuint, severity: GLenum, length: GLsizei, message: *const GLchar, userParam: *const GLvoid, ), >; extern "C" { pub fn glBlendBarrie...
); pub fn glMinSampleShading(value: GLfloat); pub fn glPatchParameteri(pname: GLenum, value: GLint); pub fn glTexParameterIiv(target: GLenum, pname: GLenum, params: *const GLint); pub fn glTexParameterIuiv(target: GLenum, pname: GLenum, params: *const GLuint); pub fn glGetTexParameterIiv(targ...
m, length: GLsizei, buf: *const GLchar, ); pub fn glDebugMessageCallback(callback: GLDEBUGPROC, userParam: *const GLvoid); pub fn glGetDebugMessageLog( count: GLuint, bufSize: GLsizei, sources: *mut GLenum, types: *mut GLenum, ids: *mut GLuint, ...
random
[ { "content": "pub fn get_proc_address(proc_name: &str) -> *const c_void {\n\n unsafe {\n\n let string = CString::new(proc_name).unwrap();\n\n\n\n ffi::eglGetProcAddress(string.as_ptr())\n\n }\n\n}\n\n\n\n// -------------------------------------------------------------------------------------...
Rust
src/removable_value.rs
ThomAub/vega_lite_3.rs
f962b11a818b4fe91d0ae4ec22bcf4ec02d126ef
use serde::de::{Error, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; use std::marker::PhantomData; use crate::schema::*; #[derive(Clone, Debug)] pub enum RemovableValue<T: Clone> { Default, Remove, Specified(T), } impl<T: Clone> RemovableValue<T> ...
use serde::de::{Error, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; use std::marker::PhantomData; use crate::schema::*; #[derive(Clone, Debug)] pub enum RemovableValue<T: Clone> { Default, Remove, Specified(T), } impl<T: Clone> RemovableValue<T> ...
}
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_option(RemovableValueVisitor { marker: PhantomData, }) }
function_block-full_function
[ { "content": "#[derive(Debug, Clone, Serialize, Deserialize)]\n\n#[serde(untagged)]\n\n#[derive(From)]\n\n#[allow(unused)]\n\nenum UnusedInlineDataset {\n\n AnythingMap(HashMap<String, Option<serde_json::Value>>),\n\n Bool(bool),\n\n Double(f64),\n\n String(String),\n\n}\n\n\n\n/// Aggregation funct...
Rust
src/mv_backend/backend.rs
Kagamihime/matrix-visualisations
10c9612434ad835d12b5c164c82e8e8eb6545325
use std::sync::{Arc, RwLock}; use failure::{format_err, Error}; use serde_derive::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use yew::callback::Callback; use yew::format::{Json, Nothing}; use yew::services::fetch::{FetchService, FetchTask, Request, Response, Uri}; use super::session::Session; pub ...
use std::sync::{Arc, RwLock}; use failure::{format_err, Error}; use serde_derive::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use yew::callback::Callback; use yew::format::{Json, Nothing}; use yew::services::fetch::{FetchService, FetchTask, Request, Response, Uri}; use super::session::Session; pub ...
) } }; self.fetch.fetch(request, handler.into()) } fn request( &mut self, callback: Callback<Result<EventsResponse, Error>>, uri: Uri, ) -> FetchTask { let request = Request::get(uri) .header("Content-Type", "application/json") ...
Err(format_err!( "{}: error stopping the backend", meta.status ))
call_expression
[ { "content": "// Builds a filter which allows the application to get events in the federation format with only\n\n// the fields required to observe the room. Events in the federation format includes informations\n\n// like the depth of the event in the DAG and the ID of the previous events, it allows the\n\n// ...
Rust
src/encode.rs
yancyribbens/rust-elements
df7e3cf0d5507bd47be0d5e5a4ba680a778b78ac
use std::io::Cursor; use std::{error, fmt, io, mem}; use ::bitcoin::consensus::encode as btcenc; use transaction::{Transaction, TxIn, TxOut}; pub use ::bitcoin::consensus::encode::MAX_VEC_SIZE; #[derive(Debug)] pub enum Error { Bitcoin(btcenc::Error), OversizedVectorAllocation { ...
use std::io::Cursor; use std::{error, fmt, io, mem}; use ::bitcoin::consensus::encode as btcenc; use transaction::{Transaction, TxIn, TxOut}; pub use ::bitcoin::consensus::encode::MAX_VEC_SIZE; #[derive(Debug)] pub enum Error { Bitcoin(btcenc::Error), OversizedVectorAllocation { ...
} } impl error::Error for Error { fn cause(&self) -> Option<&error::Error> { match *self { Error::Bitcoin(ref e) => Some(e), _ => None, } } fn description(&self) -> &str { "an Elements encoding error" } } #[doc(hidden)] impl From<btcenc::Error> for...
match *self { Error::Bitcoin(ref e) => write!(f, "a Bitcoin type encoding error: {}", e), Error::OversizedVectorAllocation { requested: ref r, max: ref m, } => write!(f, "oversized vector allocation: requested {}, maximum {}", r, m), Error:...
if_condition
[ { "content": "/// Decode a bech32 string into the raw HRP and the data bytes.\n\n/// The HRP is returned as it was found in the original string,\n\n/// so it can be either lower or upper case.\n\npub fn decode(s: &str) -> Result<(&str, Vec<u5>), Error> {\n\n // Ensure overall length is within bounds\n\n l...
Rust
src/main.rs
sifyfy/docker-rp
8562b0193a1cb907f25749142ccf7ec08a4af260
#[macro_use] extern crate log; pub mod conf { use failure::{format_err, ResultExt}; use glob::glob; use serde_derive::{Deserialize, Serialize}; use std::path::PathBuf; use structopt::StructOpt; use url::Url; #[derive(Debug, StructOpt)] #[structopt(rename_all = "kebab-case")] pub st...
#[macro_use] extern crate log; pub mod conf { use failure::{format_err, ResultExt}; use glob::glob; use serde_derive::{Deserialize, Serialize}; use std::path::PathBuf; use structopt::StructOpt; use url::Url; #[derive(Debug, StructOpt)] #[structopt(rename_all = "kebab-case")] pub st...
#[test] fn config_dir_custom_absolute_path() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "/path/to/conf"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "/path/to/conf".to_string(...
fn config_dir_custom_relative_path() { use structopt::StructOpt; let cli_args: &[&str] = &["test", "--config-dir", "./conf"]; let args = Args::from_iter_safe(cli_args.iter()).unwrap(); assert_eq!( "./conf".to_string(), format!("{}", args.co...
function_block-full_function
[ { "content": "# rp\n\n\n\nA simple HTTP reverse proxy server for web development.\n\n\n\n## Usage\n\n\n\nSimple:\n\n\n\n~~~~shell\n\ndocker --rm -it --network host sifyfy/rp -- -r /path/to:http://localhost:3000/path/to\n\n~~~~\n\n\n\nMultiple settings:\n\n\n\n~~~~shell\n\ndocker --rm -it --network host sifyfy/r...
Rust
relayer-cli/src/commands/query/client.rs
interchainio/ibc-rs
194a1714cf9dc807dd7b4e33726319293848dc58
use abscissa_core::clap::Parser; use abscissa_core::{Command, Runnable}; use tracing::debug; use ibc_relayer::chain::handle::ChainHandle; use ibc_relayer::chain::requests::{ HeightQuery, IncludeProof, PageRequest, QueryClientConnectionsRequest, QueryClientStateRequest, QueryConsensusStateRequest, QueryConsensu...
use abscissa_core::clap::Parser; use abscissa_core::{Command, Runnable}; use tracing::debug; use ibc_relayer::chain::handle::ChainHandle; use ibc_relayer::chain::requests::{ HeightQuery, IncludeProof, PageRequest, QueryClientConnectionsRequest, QueryClientStateRequest, QueryConsensusStateRequest, QueryConsensu...
ght" )] height: Option<u64>, } impl Runnable for QueryClientConsensusCmd { fn run(&self) { let config = app_config(); debug!("Options: {:?}", self); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); let co...
l Runnable for QueryClientStateCmd { fn run(&self) { let config = app_config(); let chain = spawn_chain_runtime(&config, &self.chain_id) .unwrap_or_else(exit_with_unrecoverable_error); match chain.query_client_state( QueryClientStateRequest { client_...
random
[]
Rust
backend/services/keychain/src/main.rs
hiroaki-yamamoto/midas
7fa9c1d6605bead7e283b339639a89bb09ed6b1c
use ::std::convert::TryFrom; use ::std::net::SocketAddr; use ::clap::Parser; use ::futures::FutureExt; use ::futures::StreamExt; use ::http::StatusCode; use ::libc::{SIGINT, SIGTERM}; use ::mongodb::bson::{doc, oid::ObjectId}; use ::mongodb::Client; use ::nats::connect; use ::slog::Logger; use ::tokio::signal::unix as...
use ::std::convert::TryFrom; use ::std::net::SocketAddr; use ::clap::Parser; use ::futures::FutureExt; use ::futures::StreamExt; use ::http::StatusCode; use ::libc::{SIGINT, SIGTERM}; use ::mongodb::bson::{doc, oid::ObjectId}; use ::mongodb::Client; use ::nats::connect; use ::slog::Logger; use ::tokio::signal::unix as...
and(::warp::filters::body::json()) .and_then( |keychain: KeyChain, _: Logger, id: ObjectId, rename: ApiRename| async move { if let Err(_) = keychain.rename_label(id, &rename.label).await { return Err(::warp::reject()); }; return Ok(()); }, ) ...
function_block-function_prefixed
[ { "content": "fn main() {\n\n let mut protos = vec![];\n\n for proto in glob(\"../../../proto/**/*.proto\").unwrap() {\n\n let path = proto.unwrap();\n\n let path = String::from(path.to_str().unwrap());\n\n println!(\"cargo:rerun-if-changed={}\", path);\n\n protos.push(path);\n\n }\n\n return ::...
Rust
tests/support/server.rs
sgrif/reqwest
9f256405e57966de82a24f466d75604d2d2fafe2
use std::io::{Read, Write}; use std::net; use std::time::Duration; use std::sync::mpsc; use std::thread; pub struct Server { addr: net::SocketAddr, panic_rx: mpsc::Receiver<()>, } impl Server { pub fn addr(&self) -> net::SocketAddr { self.addr } } impl Drop for Server { fn drop(&mut sel...
use std::io::{Read, Write}; use std::net; use std::time::Duration; use std::sync::mpsc; use std::thread; pub struct Server { addr: net::SocketAddr, panic_rx: mpsc::Receiver<()>, } impl Server { pub fn addr(&self) -> net::SocketAddr { self.addr } } impl Drop for Server { fn drop(&mut sel...
} #[derive(Debug, Default)] pub struct Txn { pub request: Vec<u8>, pub response: Vec<u8>, pub read_timeout: Option<Duration>, pub read_closes: bool, pub response_timeout: Option<Duration>, pub write_timeout: Option<Duration>, pub chunk_size: Option<usize>, } static DEFAULT_USER_AGENT: &'...
panic_rx .recv_timeout(Duration::from_secs(3)) .expect("test server should not panic"); } }
function_block-function_prefix_line
[ { "content": "/// A future attempt to poll the response body for EOF so we know whether to use gzip or not.\n\nstruct Pending {\n\n body: ReadableChunks<Body>,\n\n}\n\n\n", "file_path": "src/async_impl/decoder.rs", "rank": 1, "score": 90916.19238636999 }, { "content": "/// A gzip decoder ...
Rust
components/dada-ir/src/code/syntax.rs
lqd/dada
df7d88dd006818699118a8bc4d3ecd2f108f438f
use crate::{ code::syntax::op::Op, in_ir_db::InIrDb, in_ir_db::InIrDbExt, span::Span, storage_mode::Atomic, word::{SpannedOptionalWord, Word}, }; use dada_id::{id, prelude::*, tables}; use salsa::DebugWithDb; use super::Code; salsa::entity2! { entity Tree in crate::Jar { origin: Co...
use crate::{ code::syntax::op::Op, in_ir_db::InIrDb, in_ir_db::InIrDbExt, span::Span, storage_mode::Atomic, word::{SpannedOptionalWord, Word}, }; use dada_id::{id, prelude::*, tables}; use salsa::DebugWithDb; use super::Code; salsa::entity2! { entity Tree in crate::Jar { origin: Co...
StringLiteral(Word), Dot(Expr, Word), Await(Expr), Call(Expr, Vec<NamedExpr>), Share(Expr), Lease(Expr), Give(Expr), Var(LocalVariableDecl, Expr), Parenthesized(Expr), Tuple(Vec<Expr>), If(Expr, Expr, Option...
rDb<'_, Tree>> for TreeData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &InIrDb<'_, Tree>) -> std::fmt::Result { f.debug_struct("syntax::Tree") .field("root_expr", &self.root_expr.debug(db)) .finish() } } tables! { #[derive(Clone, Debug, PartialEq, Eq)] ...
random
[ { "content": "#[salsa::memoized(in crate::Jar)]\n\npub fn parse_code(db: &dyn crate::Db, code: Code) -> Tree {\n\n let body = code.body_tokens;\n\n Parser::new(db, body).parse_code_body(code)\n\n}\n", "file_path": "components/dada-parse/src/code_parser.rs", "rank": 0, "score": 385982.550388712...
Rust
tools/cli/src/utils.rs
brygga-dev/workdir2
0b6e8f54a3d44ef8dedefd1bdc95f193467d239e
use console::style; use dialoguer::{theme, Input, Select}; use std::fs; use std::io; use std::path::{Path, PathBuf}; use shared_child::SharedChild; use std::sync::Arc; use std::sync::RwLock; use std::net::TcpStream; use std::net::ToSocketAddrs; pub struct ConfigDir(pub PathBuf); impl ConfigDir { pub fn new(conf...
use console::style; use dialoguer::{theme, Input, Select}; use std::fs; use std::io; use std::path::{Path, PathBuf}; use shared_child::SharedChild; use std::sync::Arc; use std::sync::RwLock; use std::net::TcpStream; use std::net::ToSocketAddrs; pub struct ConfigDir(pub PathBuf); impl ConfigDir { pub fn new(conf...
}); let _thread_res = match thread.join() { Ok(_res) => { println!("Joined thread"); } Err(e) => println!("Error ending process: {:?}", e), }; Ok(self) } } pub fn wait_for<A: ToSocketAddrs>(addr: A) -> bool { let mut attempts ...
match wait_clone.write() { Ok(mut lock) => { *lock = None; } Err(e) => println!("Failed getting write on current process: {:?}", e), }
if_condition
[ { "content": "// Not ideally, but split initially with init_project_config\n\n// to avoid type complexity with future and io:Result\n\npub fn init_cmd<'a>(env: &'a CliEnv) -> impl Future<Item = (), Error = Error> + 'a {\n\n let (config, project_git) = match init_project_config(env) {\n\n Ok(config) =>...
Rust
src/html.rs
Traverse-Research/markdown.rs
cca09f697f58d4ce68649e1873ff76983f2d6a37
use parser::Block; use parser::Block::{ Blockquote, CodeBlock, Header, Hr, LinkReference, OrderedList, Paragraph, Raw, UnorderedList, }; use parser::Span::{Break, Code, Emphasis, Image, Link, Literal, RefLink, Strong, Text}; use parser::{ListItem, OrderedListType, Span}; use regex::Regex; use std::collections::Hash...
use parser::Block; use parser::Block::{ Blockquote, CodeBlock, Header, Hr, LinkReference, OrderedList, Paragraph, Raw, UnorderedList, }; use parser::Span::{Break, Code, Emphasis, Image, Link, Literal, RefLink, Strong, Text}; use parser::{ListItem, OrderedListType, Span}; use regex::Regex; use std::collections::Hash...
; } for block in blocks.iter() { let next = match block { Header(ref elements, level) => format_header(elements, *level, &link_references), Paragraph(ref elements) => format_paragraph(elements, &link_references), Blockquote(ref elements) => format_blockquote(elements)...
match block { LinkReference(ref id, ref text, ref title) => { link_references.insert(id, (text, title)); } _ => {} }
if_condition
[ { "content": "pub fn parse_emphasis(text: &str) -> Option<(Span, usize)> {\n\n lazy_static! {\n\n static ref EMPHASIS_UNDERSCORE: Regex = Regex::new(r\"^_(?P<text>.+?)_\").unwrap();\n\n static ref EMPHASIS_STAR: Regex = Regex::new(r\"^\\*(?P<text>.+?)\\*\").unwrap();\n\n }\n\n\n\n if EMPH...
Rust
src/network/ws/server.rs
wayfair-tremor/uring
483adf33d61a767a2de9a5ed4ed5cc272cc62ac2
use super::Reply as WsReply; use super::*; use crate::version::VERSION; use crate::{pubsub, NodeId}; use async_std::net::TcpListener; use async_std::net::ToSocketAddrs; use async_std::task; use futures::channel::mpsc::{channel, Receiver, Sender}; use futures::io::{AsyncRead, AsyncWrite}; use futures::{select, FutureE...
use super::Reply as WsReply; use super::*; use crate::version::VERSION; use crate::{pubsub, NodeId}; use async_std::net::TcpListener; use async_std::net::ToSocketAddrs; use async_std::task; use futures::channel::mpsc::{channel, Receiver, Sender}; use futures::io::{AsyncRead, AsyncWrite}; use futures::{select, FutureE...
async fn handle_version(&mut self, msg: Message) -> bool { if msg.is_text() { let text = msg.into_data(); match serde_json::from_slice(&text) { Ok(msg) => self.handle_version_msg(msg), Err(e) => { error!( s...
async fn handle_mring_msg(&mut self, msg: MRRequest) -> bool { match msg { MRRequest::GetSize { rid } => self .node .tx .unbounded_send(UrMsg::MRingGetSize(WsReply(rid, self.ws_tx.clone()))) .is_ok(), MRRequest::SetSize { r...
function_block-full_function
[ { "content": "// The message can be used to initialize a raft node or not.\n\nfn is_initial_msg(msg: &Message) -> bool {\n\n let msg_type = msg.get_msg_type();\n\n msg_type == MessageType::MsgRequestVote\n\n || msg_type == MessageType::MsgRequestPreVote\n\n || (msg_type == MessageType::MsgHe...
Rust
src/visitor/model.rs
SUPERAndroidAnalyzer/abxml-rs
3140e59be09108265a7f0e214f071a34f970899c
use std::{cell::RefCell, collections::HashMap, rc::Rc}; use failure::{format_err, Error, ResultExt}; use log::error; use crate::{ chunks::{ PackageWrapper, StringTableCache, StringTableWrapper, TableTypeWrapper, TypeSpecWrapper, }, model::{ owned::Entry, Entries, Identifier, Library as Lib...
use std::{cell::RefCell, collections::HashMap, rc::Rc}; use failure::{format_err, Error, ResultExt}; use log::error; use crate::{ chunks::{ PackageWrapper, StringTableCache, StringTableWrapper, TableTypeWrapper, TypeSpecWrapper, }, model::{ owned::Entry, Entries, Identifier, Library as Lib...
fn visit_package(&mut self, package: PackageWrapper<'a>) { if let Ok(package_id) = package.get_id() { self.package_mask = package_id << 24; let package_id = self.package_mask.get_package(); let rp = Library::new(package); self.resources.push_package(packag...
let st_res = self .resources .get_mut_package(package_id) .and_then(|package| { package.set_string_table(StringTableCache::new(string_table), origin); Some(()) }); if st_res.is_none() { e...
function_block-function_prefix_line
[ { "content": "pub trait Identifier {\n\n fn get_package(&self) -> u8;\n\n fn get_spec(&self) -> u8;\n\n fn get_id(&self) -> u16;\n\n}\n\n\n\nimpl Identifier for u32 {\n\n fn get_package(&self) -> u8 {\n\n let mut package_id = (self >> 24) as u8;\n\n\n\n if package_id == 0 {\n\n ...
Rust
benches/main_all/baking/fib.rs
julien-lange/mpst_rust_github
ca10d860f06d3bc4b6d1a9df290d2812235b456f
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthree::bundle_impl_with_enum_and_cancel; use mpstthree::role::broadcast::RoleBroadcast; use mpstthree::role::end::RoleEnd; use std::error::Error; ...
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthr
e NameA = RoleA<RoleEnd>; type NameB = RoleB<RoleEnd>; type NameC = RoleC<RoleEnd>; type Choose0fromAtoB = <RecursBtoA as Session>::Dual; type Choose0fromAtoC = <RecursCtoA as Session>::Dual; enum Branching0fromAtoB { More( MeshedChannelsThree< Recv<i64, Send<i64, RecursBtoA>>, End...
ee::bundle_impl_with_enum_and_cancel; use mpstthree::role::broadcast::RoleBroadcast; use mpstthree::role::end::RoleEnd; use std::error::Error; bundle_impl_with_enum_and_cancel!(MeshedChannelsThree, A, B, C); typ
random
[ { "content": "fn smtp_main(c: &mut Criterion) {\n\n c.bench_function(&\"SMTP\".to_string(), |b| b.iter(all_mpst));\n\n}\n\n\n\ncriterion_group! {\n\n name = smtp;\n\n config = Criterion::default().significance_level(0.1).sample_size(10100);\n\n targets = smtp_main\n\n}\n\n\n\ncriterion_main!(smtp);\...
Rust
src/db.rs
zbtzbtzbt/risinglight
38482e05b1a89690d610c8aeddaa2f6be13b18b1
use std::sync::Arc; use futures::TryStreamExt; use risinglight_proto::rowset::block_statistics::BlockStatisticsType; use tracing::debug; use crate::array::{ArrayBuilder, ArrayBuilderImpl, DataChunk, I32ArrayBuilder, Utf8ArrayBuilder}; use crate::binder::{BindError, Binder}; use crate::catalog::RootCatalogRef; use c...
use std::sync::Arc; use futures::TryStreamExt; use risinglight_proto::rowset::block_statistics::BlockStatisticsType; use tracing::debug; use crate::array::{ArrayBuilder, ArrayBuilderImpl, DataChunk, I32ArrayBuilder, Utf8ArrayBuilder}; use crate::binder::{BindError, Binder}; use crate::catalog::RootCatalogRef; use c...
pub async fn shutdown(&self) -> Result<(), Error> { if let StorageImpl::SecondaryStorage(storage) = &self.storage { storage.shutdown().await?; } Ok(()) } fn run_dt(&self) -> Result<Vec<DataChunk>, Error> { let mut db_id_vec = I32ArrayBuilder::new(); let...
pub async fn new_on_disk(options: SecondaryStorageOptions) -> Self { let storage = Arc::new(SecondaryStorage::open(options).await.unwrap()); storage.spawn_compactor().await; let catalog = storage.catalog().clone(); let storage = StorageImpl::SecondaryStorage(storage); let executi...
function_block-full_function
[ { "content": "pub fn path_of_index_column(base: impl AsRef<Path>, column_info: &ColumnCatalog) -> PathBuf {\n\n path_of_column(base, column_info, \".idx\")\n\n}\n\n\n", "file_path": "src/storage/secondary/rowset/rowset_builder.rs", "rank": 0, "score": 193341.85560012443 }, { "content": "p...
Rust
bc/wallets_macro/src/lib.rs
scryinfo/cashbox
667b89c4b3107b9229c3758bf9f8266316dac08f
use proc_macro::TokenStream; use proc_macro_roids::{DeriveInputStructExt, FieldsNamedAppend}; use quote::quote; use syn::{AttributeArgs, DeriveInput, Fields, FieldsNamed, parse_macro_input, parse_quote, Type}; mod db_meta; mod cr; #[proc_macro_attribute] pub fn db_append_shared(args: TokenStream, input: TokenStream)...
use proc_macro::TokenStream; use proc_macro_roids::{DeriveInputStructExt, FieldsNamedAppend}; use quote::quote; use syn::{AttributeArgs, DeriveInput, Fields, FieldsNamed, parse_macro_input, parse_quote, Type}; mod db_meta; mod cr; #[proc_macro_attribute] pub fn db_append_shared(args: TokenStream, input: TokenStream)...
n.into() } #[proc_macro_derive(DbBeforeUpdate)] pub fn db_before_update(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let name = &ast.ident; let gen = quote! { impl dao::BeforeUpdate for #name { fn before_update(&mut self){ self...
ppend_named(fields_additional); let name = &ast.ident; let imp_base = quote! { impl Shared for #name { fn get_id(&self) -> String { self.id.clone() } fn set_id(&mut self, id: String) { self.id = id; } fn get_create_time(&self) -> i64 {...
random
[ { "content": "pub fn dl_cr(type_name: &str, fields: &Fields) -> TokenStream {\n\n const NAME: &str = \"\";//CExtrinsicContext,CInitParameters\n\n let r_name = {\n\n let mut str = type_name.to_owned();\n\n str.remove(0);\n\n format_ident!(\"{}\",str)\n\n };\n\n //test\n\n if t...
Rust
crates/shim/src/synchronous/mod.rs
QuarkContainer/rust-extensions
b3ac82d9cc2a2674543118bb282537d132870c1a
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to...
.args(&[ "-namespace", &opts.namespace, "-id", &opts.id, "-address", &opts.address, ]); if opts.debug { command.arg("-debug"); } command.envs(vars); command .spawn() .map_err(io_error!(e, "spawn sh...
.stdout(Stdio::null()) .stdin(Stdio::null()) .stderr(Stdio::null()) .fd_mappings(vec![FdMapping { parent_fd: listener.as_raw_fd(), child_fd: SOCKET_FD, }])?
function_block-random_span
[ { "content": "/// Make socket path from containerd socket path, namespace and id.\n\npub fn socket_address(socket_path: &str, namespace: &str, id: &str) -> String {\n\n let path = PathBuf::from(socket_path)\n\n .join(namespace)\n\n .join(id)\n\n .display()\n\n .to_string();\n\n\n\...
Rust
src/linux.rs
TomBebbington/reminisce
1dd6c5516cc7ca5831bfe9bb140a1f807f876576
use libc::{c_char, c_ulong, c_int, c_uint, O_RDONLY, O_NONBLOCK, read}; use inotify::INotify; use inotify::ffi; use glob::glob; use std::borrow::Cow; use std::ffi::{CStr, CString}; use std::io::Error; use std::mem; use std::path::Path; use std::str::FromStr; use {Backend, Event, Joystick}; const JSIOCGAXES: c_uint = 2...
use libc::{c_char, c_ulong, c_int, c_uint, O_RDONLY, O_NONBLOCK, read}; use inotify::INotify; use inotify::ffi; use glob::glob; use std::borrow::Cow; use std::ffi::{CStr, CString}; use std::io::Error; use std::mem; use std::path::Path; use std::str::FromStr; use {Backend, Event, Joystick}; const JSIOCGAXES: c_uint = 2...
} } pub struct NativeJoystick { index: u8, fd: c_int } impl NativeJoystick { fn poll(&mut self) -> Option<Event> { unsafe { let mut event:LinuxEvent = mem::uninitialized(); loop { let event_size = mem::size_of::<LinuxEvent>() as c_ulong; if read(self.fd, mem::transmute(&mut event), event_size as ...
match self.inner_poll() { Some(Event::Connected(index)) => { if let Ok(joystick) = NativeJoystick::open(index) { self.joysticks.push(joystick); Some(Event::Connected(index)) } else { self.inner_poll() } }, Some(Event::Disconnected(index)) => { let (arr_index, _) = self.joysticks....
if_condition
[ { "content": "/// Scan for joysticks\n\npub fn scan() -> Vec<NativeJoystick> {\n\n\t(0..4).filter_map(|i| ::Joystick::open(i).ok()).collect()\n\n}\n\n\n\npub struct NativeJoystick {\n\n\tindex: u8,\n\n\tlast: Gamepad,\n\n\tlast_packet: i32,\n\n\tevents: VecDeque<::Event>\n\n}\n\nimpl ::Joystick for NativeJoysti...
Rust
psyche-core/src/brain_builder.rs
PsichiX/psyche
b46a98926eeb103b7e158dbb5bc6b53b369683a8
use crate::brain::Brain; use crate::config::Config; use crate::neuron::{NeuronID, Position}; use crate::Scalar; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use std::f64::consts::PI; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BrainBuilder { config: Config, neurons: usize, ...
use crate::brain::Brain; use crate::config::Config; use crate::neuron::{NeuronID, Position}; use crate::Scalar; use rand::{thread_rng, Rng}; use serde::{Deserialize, Serialize}; use std::f64::consts::PI; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BrainBuilder { config: Config, neurons: usize, ...
fn connect_neighbor_neurons<R>( &mut self, neuron_positions: &[(NeuronID, Position)], brain: &mut Brain, rng: &mut R, ) -> bool where R: Rng, { let origin = neuron_positions[rng.gen_range(0, neuron_positions.len()) % neuron_positions.len()]; ...
fn make_neighbor_neuron<R>( &mut self, neurons: &[NeuronID], brain: &mut Brain, rng: &mut R, ) -> NeuronID where R: Rng, { let distance = rng.gen_range(self.min_neurogenesis_range, self.max_neurogenesis_range); let origin = neurons[rng.gen_range(0, neu...
function_block-full_function
[ { "content": "/// generates OBJ bytes from activity map.\n\n/// NOTE: Colors are stored either in vertices normals or texture vertices.\n\npub fn generate(activity_map: &BrainActivityMap, config: &Config) -> Result<Vec<u8>> {\n\n let mut objects = vec![];\n\n\n\n if let Some(ref neurons) = config.neurons ...
Rust
tests/embedded_graphics.rs
hpux735/tinybmp
a2bddd0767294e21d66a7c295215121230efb7a8
use embedded_graphics::{ image::Image, mock_display::{ColorMapping, MockDisplay}, pixelcolor::{Gray8, Rgb555, Rgb565, Rgb888}, prelude::*, primitives::Rectangle, }; use tinybmp::{Bmp, DynamicBmp}; #[test] fn negative_top_left() { let image: Bmp<Rgb565> = Bmp::from_slice(include_bytes!("...
use embedded_graphics::{ image::Image, mock_display::{ColorMapping, MockDisplay}, pixelcolor::{Gray8, Rgb555, Rgb565, Rgb888}, prelude::*, primitives::Rectangle, }; use tinybmp::{Bmp, DynamicBmp}; #[test] fn negative_top_left() { let image: Bmp<Rgb565> = Bmp::from_slice(include_bytes!("...
#[test] fn colors_rgb555() { test_color_pattern::<Rgb555>(include_bytes!("./colors_rgb555.bmp")); } #[test] fn colors_rgb555_dynamic() { test_color_pattern_dynamic(include_bytes!("./colors_rgb555.bmp")); } #[test] fn colors_rgb565() { test_color_pattern::<Rgb565>(include_bytes!("./colors_rgb565.bmp")); ...
draw_image(bmp).assert_eq(&expected_image_color::<Rgb565>()); let bmp = DynamicBmp::from_slice(data).unwrap(); draw_image(bmp).assert_eq(&expected_image_color::<Rgb888>()); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn coordinates() {\n\n let bmp = RawBmp::from_slice(include_bytes!(\"./chessboard-8px-color-16bit.bmp\"))\n\n .expect(\"Failed to parse\");\n\n\n\n let pixels: Vec<_> = bmp\n\n .pixels()\n\n .map(|pixel| (pixel.position.x, pixel.position.y))\n\n .collec...
Rust
src/io_event.rs
mbrubeck/smol
c311b6897fb7525ef876070d80f6ee375686b605
use std::io::{self, Read, Write}; #[cfg(windows)] use std::net::SocketAddr; use std::sync::atomic::{self, AtomicBool, Ordering}; use std::sync::Arc; #[cfg(not(target_os = "linux"))] use socket2::{Domain, Socket, Type}; use crate::async_io::Async; #[cfg(not(target_os = "linux"))] type Notifier = Socket; #[cfg(targ...
use std::io::{self, Read, Write}; #[cfg(windows)] use std::net::SocketAddr; use std::sync::atomic::{self, AtomicBool, Ordering}; use std::sync::Arc; #[cfg(not(target_os = "linux"))] use socket2::{Domain, Socket, Type}; use crate::async_io::Async; #[cfg(not(target_os = "linux"))] type Notifier = Socket; #[cfg(targ...
fn notifier() -> io::Result<(Notifier, Notifier)> { let listener = Socket::new(Domain::ipv4(), Type::stream(), None)?; listener.bind(&SocketAddr::from(([127, 0, 0, 1], 0)).into())?; listener.listen(1)?; let sock1 = Socket::new(Domain::ipv4(), Type::stream(), None)?; sock1.set_nonblocking(...
function_block-full_function
[ { "content": "/// Creates an async writer that runs on a thread.\n\n///\n\n/// This adapter converts any kind of synchronous writer into an asynchronous writer by running it\n\n/// on the blocking executor and receiving bytes over a pipe.\n\n///\n\n/// **Note:** Don't forget to flush the writer at the end, or s...
Rust
canon_collision_lib/src/command_line.rs
rukai/canon_collision
4adfef24ea9dccce8a7306b9d37a55136f11c4df
use winit_input_helper::{WinitInputHelper, TextChar}; use std::collections::VecDeque; use winit::event::VirtualKeyCode; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Default, Serialize, Deserialize, Node)] pub struct CommandLine { history_index: isize, cursor: usize, history: ...
use winit_input_helper::{WinitInputHelper, TextChar}; use std::collections::VecDeque; use winit::event::VirtualKeyCode; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Default, Serialize, Deserialize, Node)] pub struct CommandLine { history_index: isize, cursor: usize, history: ...
new_command.push(old_char); } if !hit_cursor { new_command.push(new_char); } self.command = new_command; self.cursor += 1; ...
if i == self.cursor { hit_cursor = true; new_command.push(new_char); }
if_condition
[ { "content": "pub fn get_replay_names() -> Vec<String> {\n\n let mut result: Vec<String> = vec!();\n\n \n\n if let Ok(files) = fs::read_dir(get_replays_dir_path()) {\n\n for file in files {\n\n if let Ok(file) = file {\n\n let file_name = file.file_name().into_string()....
Rust
src/http-server.rs
kawakami-o3/learn-http
2d3ba09f2045cb08a333b89e160b9712a4d9299e
extern crate toml; mod conf; mod http_request; mod http_response; mod method; mod status; mod util; use std::fs; use std::io::prelude::*; use std::net::{Shutdown, TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::thread; use chrono::Local; use serde::Deserialize; use crate::http_request::*; use crat...
extern crate toml; mod conf; mod http_request; mod http_response; mod method; mod status; mod util; use std::fs; use std::io::prelude::*; use std::net::{Shutdown, TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::thread; use chrono::Local; use serde::Deserialize; use crate::http_request::*; use crat...
fn handle_content_info(response: &mut Response, access_path: & String) { match util::extension(&access_path) { Some("ico") => { response.add_header("Content-Type", "image/x-icon".to_string()); response.add_header("Content-Length", format!("{}", response.entity_body.len())); ...
fn load_access_config(access_path: & String) -> AccessConfig { let path = Path::new(access_path); let config_path = if path.is_dir() { PathBuf::from(format!("{}/{}", access_path, ACCESS_CONF)) } else { path.with_file_name(ACCESS_CONF) }; if !config_path.exists() { return Acc...
function_block-full_function
[ { "content": "pub fn canonicalize(s: &str) -> Option<String> {\n\n let mut v: Vec<&str> = Vec::new();\n\n for i in s.split(\"/\") {\n\n match i {\n\n \"\" => {\n\n if v.len() == 0 {\n\n v.push(\"\");\n\n }\n\n }\n\n \...
Rust
exonum/src/runtime/dispatcher/schema.rs
SergeiMal/exonum
520324a321462bceb8acda9a92b9ed63fcdc3eaf
use exonum_merkledb::{ access::{Access, AccessExt, AsReadonly}, Fork, KeySetIndex, MapIndex, ProofMapIndex, }; use super::{ArtifactId, Error, InstanceSpec}; use crate::runtime::{ ArtifactState, ArtifactStatus, InstanceId, InstanceQuery, InstanceState, InstanceStatus, }; const ARTIFACTS: &str = "dispatch...
use exonum_merkledb::{ access::{Access, AccessExt, AsReadonly}, Fork, KeySetIndex, MapIndex, ProofMapIndex, }; use super::{ArtifactId, Error, InstanceSpec}; use crate::runtime::{ ArtifactState, ArtifactStatus, InstanceId, InstanceQuery, InstanceState, InstanceStatus, }; const ARTIFACTS: &str = "dispatch...
}
pub(super) fn take_modified_instances(&mut self) -> Vec<(InstanceSpec, InstanceStatus)> { let mut modified_instances = self.modified_instances(); let instances = self.instances(); let output = modified_instances .iter() .map(|(instance_name, status)| { le...
function_block-full_function
[ { "content": "pub fn result_ok<T>(_: T) -> Result<(), Error> {\n\n Ok(())\n\n}\n\n\n", "file_path": "exonum/src/events/error.rs", "rank": 0, "score": 391754.5381453211 }, { "content": "fn validate_address_component(name: &str) -> Result<(), String> {\n\n if name.is_empty() {\n\n ...
Rust
src/resolver.rs
touilleMan/rstest
d3284c7baae78e58f06db9c4ca7f4f2bad5fc50e
use std::borrow::Cow; use std::collections::HashMap; use proc_macro2::Ident; use syn::{parse_quote, Expr}; use crate::parse::Fixture; pub(crate) mod fixtures { use quote::format_ident; use super::*; pub(crate) fn get<'a>(fixtures: impl Iterator<Item = &'a Fixture>) -> impl Resolver + 'a { fix...
use std::borrow::Cow; use std::collections::HashMap; use proc_macro2::Ident; use syn::{parse_quote, Expr}; use crate::parse::Fixture; pub(crate) mod fixtures { use quote::format_ident; use super::*; pub(crate) fn get<'a>(fixtures: impl Iterator<Item = &'a Fixture>) -> impl Resolver + 'a { fix...
} } pub(crate) mod values { use super::*; use crate::parse::fixture::ArgumentValue; pub(crate) fn get<'a>(values: impl Iterator<Item = &'a ArgumentValue>) -> impl Resolver + 'a { values .map(|av| (av.name.to_string(), &av.expr)) .collect::<HashMap<_, &'a Expr>>() }...
fn resolve_by_use_the_resolve_field(#[case] args: &[&str], #[case] expected: &str) { let data = vec![fixture("pippo", args).with_resolve("pluto")]; let resolver = get(data.iter()); let resolved = resolver.resolve(&ident("pippo")).unwrap().into_owned(); assert_eq!(resolv...
function_block-function_prefix_line
[ { "content": "fn just_args(#[case] expected: usize, #[case] input: &str) {\n\n assert_eq!(expected, input.len());\n\n}\n\n\n", "file_path": "tests/resources/rstest/cases/use_attr.rs", "rank": 0, "score": 311212.7762329668 }, { "content": "#[rstest]\n\n#[case::ciao(4, \"ciao\")]\n\n#[shoul...
Rust
src/types/database.rs
mrijkeboer/rust-kpdb
219410279ee104b3c9c59c17ceef23d0f4f41ef0
use chrono::{DateTime, UTC}; use common; use format::{kdb2_reader, kdb2_writer}; use io::{Log, LogReader, LogWriter}; use std::io::{Read, Write}; use super::binaries_map::BinariesMap; use super::color::Color; use super::comment::Comment; use super::composite_key::CompositeKey; use super::compression::Compression; use...
use chrono::{DateTime, UTC}; use common; use format::{kdb2_reader, kdb2_writer}; use io::{Log, LogReader, LogWriter}; use std::io::{Read, Write}; use super::binaries_map::BinariesMap; use super::color::Color; use super::comment::Comment; use super::composite_key::CompositeKey; use super::compression::Compression; use...
} fn open_kdb2<R: Log + Read>(reader: &mut R, key: &CompositeKey) -> Result<Database> { let (meta_data, xml_data) = try!(kdb2_reader::read(reader, key)); match xml_data.header_hash { Some(header_hash) => { if meta_data.header_hash != header_hash { ...
match self.db_type { DbType::Kdb1 => Err(Error::Unimplemented(String::from("KeePass v1 not supported"))), DbType::Kdb2 => kdb2_writer::write(&mut writer, self), }
if_condition
[ { "content": "/// Attempts to write the key file to the writer.\n\npub fn write<W: Write>(writer: &mut W, key: &KeyFile) -> Result<()> {\n\n match key.file_type {\n\n KeyFileType::Binary => write_binary(writer, key),\n\n KeyFileType::Hex => write_hex(writer, key),\n\n KeyFileType::Xml =>...
Rust
crates/aingle_sqlite/src/db.rs
Daironode/aingle
54bfcbe21f587699a4e66e6764fe879a348987c8
use crate::{ conn::{new_connection_pool, ConnectionPool, PConn, DATABASE_HANDLES}, prelude::*, }; use derive_more::Into; use futures::Future; use ai_hash::SafHash; use aingle_zome_types::cell::CellId; use kitsune_p2p::KitsuneSpace; use parking_lot::Mutex; use rusqlite::*; use shrinkwraprs::Shrinkwrap; use std...
use crate::{ conn::{new_connection_pool, ConnectionPool, PConn, DATABASE_HANDLES}, prelude::*, }; use derive_more::Into; use futures::Future; use ai_hash::SafHash; use aingle_zome_types::cell::CellId; use kitsune_p2p::KitsuneSpace; use parking_lot::Mutex; use rusqlite::*; use shrinkwraprs::Shrinkwrap; use std...
fn get_write_semaphore(kind: &DbKind) -> Arc<Semaphore> { static MAP: once_cell::sync::Lazy<Mutex<HashMap<DbKind, Arc<Semaphore>>>> = once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new())); let mut map = MAP.lock(); match map.get(kind) { Some(s) => s.clone(), ...
pub(crate) fn new(path_prefix: &Path, kind: DbKind) -> DatabaseResult<Self> { let path = path_prefix.join(kind.filename()); let parent = path .parent() .ok_or_else(|| DatabaseError::DatabaseMissing(path_prefix.to_owned()))?; if !parent.is_dir() { std::fs::crea...
function_block-full_function
[ { "content": "/// Handle the result of shutting down the main thread.\n\npub fn handle_shutdown(result: Result<TaskManagerResult, tokio::task::JoinError>) {\n\n let result = result.map_err(|e| {\n\n error!(\n\n error = &e as &dyn std::error::Error,\n\n \"Failed to join the main t...
Rust
parity-ethereum/ethcore/pod/src/state.rs
wgr523/prism-smart-contracts
867167e5dea286f1616a9f192e751758e0c2606e
use std::collections::BTreeMap; use ethereum_types::{H256, Address}; use triehash::sec_trie_root; use common_types::state_diff::StateDiff; use ethjson; use serde::Serialize; use crate::account::PodAccount; #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)] pub struct PodState(BTreeMap<Address, PodAccount>);...
use std::collections::BTreeMap; use ethereum_types::{H256, Address}; use triehash::sec_trie_root; use common_types::state_diff::StateDiff; use ethjson; use serde::Serialize; use crate::account::PodAccount; #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)] pub struct PodState(BTreeMap<Address, PodAccount>);...
#[test] fn create_delete_with_unchanged() { let a = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); let b = PodState::from(map![ Address::from_low_u64_be(1) => P...
let a = PodState::from(map![ Address::from_low_u64_be(1) => PodAccount { balance: 69.into(), nonce: 0.into(), code: Some(Vec::new()), storage: map![], version: 0.into(), } ]); assert_eq!(super::diff_pod(&a, &PodState::default()), StateDiff { raw: map![ Address::from_low_u64_be(1) => Acc...
function_block-function_prefix_line
[ { "content": "/// Generates a trie root hash for a vector of key-value tuples\n\npub fn trie_root<I, K, V>(input: I) -> H256\n\nwhere\n\n I: IntoIterator<Item = (K, V)>,\n\n K: AsRef<[u8]> + Ord,\n\n V: AsRef<[u8]>,\n\n{\n\n triehash::trie_root::<KeccakHasher, _, _, _>(input)\n\n}\n\n\n", "file_...
Rust
fixed-price-sale/program/tests/create_store.rs
jarry-xiao/metaplex-program-library
ddb247622dcfd7501f6811007fbbb88b1bce1483
mod utils; #[cfg(feature = "test-bpf")] mod create_store { use crate::{setup_context, utils::helpers::airdrop}; use anchor_client::solana_sdk::{signature::Keypair, signer::Signer, system_program}; use anchor_lang::{AccountDeserialize, InstructionData, ToAccountMetas}; use mpl_fixed_price_sale::utils::p...
mod utils; #[cfg(feature = "test-bpf")] mod create_store { use crate::{setup_context, utils::helpers::airdrop}; use anchor_client::solana_sdk::{signature::Keypair, signer::Signer, system_program}; use anchor_lang::{AccountDeserialize, InstructionData, ToAccountMetas}; use mpl_fixed_price_sale::utils::p...
#[tokio::test] async fn failure_name_is_long() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::fro...
async fn success() { setup_context!(context, mpl_fixed_price_sale); let admin_wallet = Keypair::new(); let store_keypair = Keypair::new(); airdrop(&mut context, &admin_wallet.pubkey(), 10_000_000_000).await; let name = String::from("123456789_123456789_"); let descript...
function_block-full_function
[ { "content": "/// Assert signer\n\npub fn assert_signer(account: &AccountInfo) -> ProgramResult {\n\n if account.is_signer {\n\n return Ok(());\n\n }\n\n\n\n Err(ProgramError::MissingRequiredSignature)\n\n}\n\n\n", "file_path": "nft-packs/program/src/utils.rs", "rank": 0, "score": 14...
Rust
src/providers/tpm_provider/key_management.rs
puiterwijk/parsec
47296bbbfd370e8137faf0e7df31586895c611a6
use super::utils; use super::utils::PasswordContext; use super::TpmProvider; use crate::authenticators::ApplicationName; use crate::key_info_managers; use crate::key_info_managers::KeyTriple; use crate::key_info_managers::{KeyInfo, ManageKeyInfo}; use log::error; use parsec_interface::operations::psa_key_attributes::...
use super::utils; use super::utils::PasswordContext; use super::TpmProvider; use crate::authenticators::ApplicationName; use crate::key_info_managers; use crate::key_info_managers::KeyTriple; use crate::key_info_managers::{KeyInfo, ManageKeyInfo}; use log::error; use parsec_interface::operations::psa_key_attributes::...
n psa_destroy_key_internal( &self, app_name: ApplicationName, op: psa_destroy_key::Operation, ) -> Result<psa_destroy_key::Result> { let key_name = op.key_name; let key_triple = KeyTriple::new(app_name, ProviderID::Tpm, key_name); let mut store_handle = self ...
usize = 32; fn insert_password_context( store_handle: &mut dyn ManageKeyInfo, key_triple: KeyTriple, password_context: PasswordContext, key_attributes: Attributes, ) -> Result<()> { let error_storing = |e| Err(key_info_managers::to_response_status(e)); let key_info = KeyInfo { id: bin...
random
[ { "content": "/// Converts an OsStr reference to a byte array.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns a custom std::io error if the conversion failed.\n\nfn os_str_to_u8_ref(os_str: &OsStr) -> std::io::Result<&[u8]> {\n\n match os_str.to_str() {\n\n Some(str) => Ok(str.as_bytes()),\n\n No...
Rust
src/parser/common.rs
rigetti/quil-rust
a4fb5a24233a55b32643b25dd014b0ec7af1c0c6
/** * Copyright 2021 Rigetti Computing * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed ...
/** * Copyright 2021 Rigetti Computing * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed ...
, Some((Token::Variable(name), remainder)) => Ok((remainder, name.clone())), Some((Token::Identifier(name), remainder)) => Ok((remainder, name.clone())), Some((other_token, _)) => { expected_token!(input, other_token, stringify!($expected_variant).to_owned()) } } } pub f...
Err(nom::Err::Error(Error { input, error: ErrorKind::UnexpectedEOF("a variable qubit".to_owned()), }))
call_expression
[ { "content": "pub fn get_expression_parameter_string(parameters: &[Expression]) -> String {\n\n if parameters.is_empty() {\n\n return String::from(\"\");\n\n }\n\n\n\n let parameter_str: String = parameters.iter().map(|e| format!(\"{}\", e)).collect();\n\n format!(\"({})\", parameter_str)\n\n...
Rust
src/factor/bfs.rs
y011d4/factor-from-random-known-bits
ee9ade6f5a21618e701ffacba320670abd069434
use crate::util::{bits_to_num, TWO}; use rug::{ops::Pow, Integer}; use std::collections::VecDeque; fn check(p: &Integer, q: &Integer, n: &Integer, m: u32) -> bool { let two_pow = TWO.clone().pow(m); let mut tmp_n = p.clone(); tmp_n *= q; tmp_n %= &two_pow; let mut n_two_pow = n.clone(); n_two_p...
use crate::util::{bits_to_num, TWO}; use rug::{ops::Pow, Integer}; use std::collections::VecDeque; fn check(p: &Integer, q: &Integer, n: &Integer, m: u32) -> bool { let two_pow = TWO.clone().pow(m); let mut tmp_n = p.clone(); tmp_n *= q; tmp_n %= &two_pow; let mut n_two_pow = n.clone(); n_two_p...
; if check(&tmp_p_next, &tmp_q, &n, (fixed_idx + 2) as u32) { let mut tmp_q_bits_0 = q_bits.clone(); tmp_q_bits_0[idx as usize] = 0; queue.push_back(( (p_bits.clone(), tmp_p_next.clone()), (tmp_q_bits_0, tmp_q.clone()), ...
match p_bits[(fixed_idx + 1) as usize] { 0 => tmp_p.clone(), 1 => { let mut ret = tmp_p.clone(); ret += two_pow; ret } _ => panic!(), }
if_condition
[ { "content": "pub fn bits_to_num(bits: &Vec<i8>, n: i32, saved: &Integer, saved_idx: i32) -> Integer {\n\n let mut ret = saved.clone();\n\n for i in (saved_idx as usize + 1)..(n as usize) {\n\n assert_ne!(bits[i], -1);\n\n if bits[i] == 1 {\n\n ret += TWO.clone().pow(i as u32) * b...
Rust
core/src/avm1/globals/text_field.rs
hthh/ruffle
b4624fddce5a4b581244a4388adef2a9ea41bb92
use crate::avm1::function::Executable; use crate::avm1::property::Attribute::*; use crate::avm1::return_value::ReturnValue; use crate::avm1::{Avm1, Error, Object, ScriptObject, TObject, UpdateContext, Value}; use crate::display_object::{EditText, TDisplayObject}; use crate::font::TextFormat; use gc_arena::MutationConte...
use crate::avm1::function::Executable; use crate::avm1::property::Attribute::*; use crate::avm1::return_value::ReturnValue; use crate::avm1::{Avm1, Error, Object, ScriptObject, TObject, UpdateContext, Value}; use crate::display_object::{EditText, TDisplayObject}; use crate::font::TextFormat; use gc_arena::MutationConte...
pub fn get_text<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { if let Some(display_object) = this.as_display_object() { if let Some(text_field) = display_object.as_edit_text() { ...
pub fn constructor<'gc>( _avm: &mut Avm1<'gc>, _context: &mut UpdateContext<'_, 'gc, '_>, _this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<ReturnValue<'gc>, Error> { Ok(Value::Undefined.into()) }
function_block-full_function
[ { "content": "#[test]\n\nfn test_stage_object_enumerate() -> Result<(), Error> {\n\n let trace_log = run_swf(\"tests/swfs/avm1/stage_object_enumerate/test.swf\", 1)?;\n\n let mut actual: Vec<String> = trace_log.lines().map(|s| s.to_string()).collect();\n\n let mut expected = vec![\"clip1\", \"clip2\", ...
Rust
src/baseline/map.rs
rodrigo-bruno/dora
3c86c8d5ff7be52846f57fbaf46a047bf9c854b1
use std::cmp::Ordering; use std::collections::BTreeMap; use baseline::fct::JitFctId; use ctxt::SemContext; pub struct CodeMap { tree: BTreeMap<CodeSpan, CodeDescriptor>, } impl CodeMap { pub fn new() -> CodeMap { CodeMap { tree: BTreeMap::new(), } } pub fn dump(&self, ctx...
use std::cmp::Ordering; use std::collections::BTreeMap; use baseline::fct::JitFctId; use ctxt::SemContext; pub struct CodeMap { tree: BTreeMap<CodeSpan, CodeDescriptor>, } impl CodeMap { pub fn new() -> CodeMap { CodeMap { tree: BTreeMap::new(), } } pub fn dump(&self, ctx...
} #[test] #[should_panic] fn test_new_fail() { span(7, 5); } #[test] fn test_new() { span(5, 7); } #[test] fn test_intersect() { assert!(span(5, 7).intersect(&span(1, 6))); assert!(!span(5, 7).intersect(&span(1, 5))); assert!(span(5, 7).intersect(&span(5, 7))); assert!(span(5, 7).intersect(&...
fn new(start: *const u8, end: *const u8) -> CodeSpan { assert!(start < end); CodeSpan { start: start, end: end, } }
function_block-full_function
[ { "content": "pub fn should_emit_debug(ctxt: &SemContext, fct: &Fct) -> bool {\n\n if let Some(ref dbg_names) = ctxt.args.flag_emit_debug {\n\n fct_pattern_match(ctxt, fct, dbg_names)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "src/baseline/codegen.rs", "rank": 0, ...
Rust
src/index/metadata.rs
kanbaru/kyoku
2760d80b3f7054c4c13bdaeb8ad7fb3e4d336e02
#[derive(Debug, PartialEq)] pub enum AudioFormat { FLAC, } #[derive(Debug, PartialEq, Clone)] pub struct AudioMetadata { pub name: String, pub number: u32, pub duration: u32, pub album: String, pub album_artist: String, pub artists: Vec<String>, pub picture: Option<Picture>, pub p...
#[derive(Debug, PartialEq)] pub enum AudioFormat { FLAC, } #[derive(Debug, PartialEq, Clone)] pub struct AudioMetadata { pub name: String, pub number: u32, pub duration: u32, pub album: String, pub album_artist: String, pub artists: Vec<String>
.artist().map(|v| v[0].clone()).unwrap(), }, artists: vorbis.artist().unwrap().to_owned(), picture: picture, path: path.to_owned(), year: year, lossless: true, }; crate::index::db::add_song(metadata, pool).await; let secs = chrono::Duration::seconds(dur...
, pub picture: Option<Picture>, pub path: std::path::PathBuf, pub year: Option<i32>, pub lossless: bool, } #[derive(Debug, PartialEq, Clone)] pub struct Picture { pub bytes: Vec<u8>, } use sqlx::Sqlite; pub fn get_filetype(path: &std::path::PathBuf) -> Option<AudioFormat> { let extension...
random
[ { "content": "CREATE TABLE `album` (\n\n `id` integer primary key autoincrement,\n\n `name` varchar(255) not null,\n\n `artist` integet not null,\n\n `picture` varchar(255),\n\n `year` integer,\n\n `created_at` datetime not null,\n\n `updated_at` datetime,\n\n FOREIGN KEY (`artist`) REFERENCES `artist` ...
Rust
src/ui.rs
PurpleBooth/fast-conventional
3b95bf0625b95f3d6a8ff8b8f407dd8fad5633dd
use crate::models::ConventionalChange; use crate::models::ConventionalCommit; use crate::models::ConventionalScope; use inquire::{Editor, Select, Text}; use miette::IntoDiagnostic; use miette::Result; use mit_commit::CommitMessage; use super::models::fast_conventional_config::FastConventionalConfig; use super::models:...
use crate::models::ConventionalChange; use crate::models::ConventionalCommit; use crate::models::ConventionalScope; use inquire::{Editor, Select, Text}; use miette::IntoDiagnostic; use miette::Result; use mit_commit::CommitMessage; use super::models::fast_conventional_config::FastConventionalConfig; use super::models:...
pub fn ask_fallback(previous_text: &'_ str) -> Result<CommitMessage<'_>> { Ok(Editor::new("Non-conventional editor.rs") .with_file_extension("COMMIT_EDITMSG") .with_predefined_text(previous_text) .with_help_message("This commit isn't conventional") .prompt() .into_diagnosti...
ge => "See description".to_string(), }, conv.subject, conv.body, ) }) .unwrap_or_default(); let commit_type: String = prompt_commit_type(config, type_index)?; let scope: Option<String> = prompt_commit_scope(conf...
function_block-function_prefixed
[ { "content": "pub fn run(commit_message_path: PathBuf, config_path: PathBuf) -> Result<()> {\n\n let buf: PathBuf = commit_message_path;\n\n let config: FastConventionalConfig = config_path.try_into()?;\n\n let existing_contents = fs::read_to_string(buf.clone()).into_diagnostic()?;\n\n let existing_...
Rust
kubeless/src/lib.rs
Slowki/kubeless.rs
6fb14b3f14ed4673cef8a9e07fded2d790f277b1
extern crate actix_web; extern crate bytes; extern crate futures; #[macro_use] extern crate prometheus; #[macro_use] extern crate lazy_static; use actix_web::http::Method; use actix_web::{server, App, AsyncResponder, HttpMessage, HttpRequest, HttpResponse, Responder}; use futures::{Future, Stream}; use prometheu...
extern crate actix_web; extern crate bytes; extern crate futures; #[macro_use] extern crate prometheus; #[macro_use] extern crate lazy_static; use actix_web::http::Method; use actix_web::{server, App, AsyncResponder, HttpMessage, HttpRequest, HttpResponse, Responder}; use futures::{Future, Stream}; use prometheu...
fn metrics(req: HttpRequest) -> impl Responder { match *req.method() { Method::GET | Method::HEAD => { let mut buffer = vec![]; prometheus::TextEncoder::new().encode(&REGISTRY.gather(), &mut buffer).unwrap(); HttpResponse::Ok().content_type("plain/text").body(S...
ttpResponse::Ok().content_type("plain/text").body("OK"), _ => HttpResponse::BadRequest().body("Bad Request"), } }
function_block-function_prefixed
[ { "content": "fn say_goodbye(event: kubeless::Event, ctx: kubeless::Context) -> String {\n\n match event.data {\n\n Some(name) => format!(\"Goodbye, {}\", String::from_utf8_lossy(&name)),\n\n None => String::from(\"Goodbye\"),\n\n }\n\n}\n\n\n", "file_path": "hello-kubeless/src/main.rs",...
Rust
src/github/mod.rs
dustlang/sync-team
f59aaa68e717e54b54d0b6a0fd5fb02bad14fe45
mod api; use self::api::{GitHub, TeamPrivacy, TeamRole}; use crate::TeamApi; use failure::Error; use log::{debug, info}; use std::collections::{HashMap, HashSet}; static DEFAULT_DESCRIPTION: &str = "Managed by the rust-lang/team repository."; static DEFAULT_PRIVACY: TeamPrivacy = TeamPrivacy::Closed; pub(crate) stru...
mod api; use self::api::{GitHub, TeamPrivacy, TeamRole}; use crate::TeamApi; use failure::Error; use log::{debug, info}; use std::collections::{HashMap, HashSet}; static DEFAULT_DESCRIPTION: &str = "Managed by the rust-lang/team repository."; static DEFAULT_PRIVACY: TeamPrivacy = TeamPrivacy::Closed; pub(crate) stru...
github.team_memberships(&team)?; for member in &github_team.members { let expected_role = self.expected_role(&github_team.org, *member); let username = &self.usernames_cache[member]; if let Some(member) = current_members.remove(&member) { if member.r...
synchronize(&self, github_team: &rust_team_data::v1::GitHubTeam) -> Result<(), Error> { let slug = format!("{}/{}", github_team.org, github_team.name); debug!("synchronizing {}", slug); let team = match self.github.team(&github_team.org, &github_team.name)? { Some(team) => ...
function_block-random_span
[ { "content": "fn mangle_address(addr: &str) -> Result<String, Error> {\n\n // Escape dots since they have a special meaning in Python regexes\n\n let mangled = addr.replace(\".\", \"\\\\.\");\n\n\n\n // Inject (?:\\+.+)? before the '@' in the address to support '+' aliases like\n\n // infra+botname@...
Rust
tests/glyph_substitution_test.rs
stainless-steel/opentype
af2d93b7d5371b35e844d92c4d64a68f2b8428e0
extern crate opentype; extern crate truetype; use opentype::glyph_substitution::{GlyphSubstitution, SingleSubstitution, Table}; use opentype::layout::script::{Language, Script}; use truetype::Value; #[macro_use] mod common; #[test] fn features() { let GlyphSubstitution { features, .. } = ok!(Value::read(&mut set...
extern crate opentype; extern crate truetype; use opentype::glyph_substitution::{GlyphSubstitution, SingleSubstitution, Table}; use opentype::layout::script::{Language, Script}; use truetype::Value; #[macro_use] mod common; #[test]
#[test] fn lookups() { let GlyphSubstitution { lookups, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, "GSUB"))); let kinds = lookups .records .iter() .map(|record| record.kind) .collect::<Vec<_>>(); assert!(kinds == &[1, 3, 1, 1, 1, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...
fn features() { let GlyphSubstitution { features, .. } = ok!(Value::read(&mut setup!(SourceSerifPro, "GSUB"))); let tags = features .headers .iter() .map(|header| header.tag) .collect::<Vec<_>>(); #[rustfmt::skip] assert!( tags == tags![ b"aalt", b"aal...
function_block-full_function
[ { "content": "#![allow(dead_code, unused_macros)]\n\n\n\nuse std::fs::File;\n\nuse std::path::PathBuf;\n\n\n\nmacro_rules! ok(($result:expr) => ($result.unwrap()));\n\n\n\nmacro_rules! setup(\n\n ($fixture:ident) => (crate::common::setup(crate::common::Fixture::$fixture, None));\n\n ($fixture:ident, $tabl...
Rust
src/queue.rs
vext01/snare
39abfd107ff2b19ca4083b5e86f62f432436b7c0
use std::{ collections::{HashMap, VecDeque}, time::Instant, }; use crate::config::{QueueKind, RepoConfig}; pub(crate) struct QueueJob { pub repo_id: String, pub owner: String, pub repo: String, pub req_time: Instant, pub event_type: String, pub json_str: String, pub rconf: RepoConf...
use std::{ collections::{HashMap, VecDeque}, time::Instant, }; use crate::config::{QueueKind, RepoConfig}; pub(crate) struct QueueJob { pub repo_id: String, pub owner: String, pub repo: String, pub req_time: Instant, pub event_type: String, pub json_str: String, pub rconf: RepoConf...
epo_id) { continue; } } } earliest_time = Some(qj.req_time); earliest_key = Some(k.clone()); } } if let Some(k) = earliest_key { Some(...
} QueueKind::Parallel | QueueKind::Sequential => (), } entry.or_insert_with(VecDeque::new).push_back(qj); } pub fn push_front(&mut self, qj: QueueJob) { self.q .entry(qj.repo_id.clone()) .or_insert_with(VecDeque::new) ...
random
[ { "content": "pub fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n let matches = Options::new()\n\n .optmulti(\"c\", \"config\", \"Path to snare.conf.\", \"<conf-path>\")\n\n .optflag(\n\n \"d\",\n\n \"\",\n\n \"Don't detach from the termina...
Rust
retired/rusty/scalyc/src/scalyc/parser.copy.rs
rschleitzer/scaly
7537cdf44f7a63ad1a560975017ee1c897c73787
use scaly::containers::{Array, HashSet, Ref, String, Vector}; use scaly::io::Stream; use scaly::memory::Region; use scaly::Page; use scalyc::errors::ParserError; use scalyc::lexer::Lexer; use scalyc::lexer::Position; pub struct Parser { lexer: Ref<Lexer>, file_name: String, _keywords: Ref<HashSet<String>>,...
use scaly::containers::{Array, HashSet, Ref, String, Vector}; use scaly::io::Stream; use scaly::memory::Region; use scaly::Page; use scalyc::errors::ParserError; use scalyc::lexer::Lexer; use scalyc::lexer::Position; pub struct Parser { lexer: Ref<Lexer>, file_name: String, _keywords: Ref<HashSet<String>>,...
Some(_) => (), }; ret.unwrap().add(node); } } } match ret { Some(ret) => Some(Ref::new(_rp, Vector::from_array(_rp, ret))), None => None, } } pub fn parse_statement( ...
rom_string_slice(_rp, "method"), String::from_string_slice(_rp, "function"), String::from_string_slice(_rp, "operator"), String::from_string_slice(_rp, "this"), String::from_string_slice(_rp, "new"), ...
random
[ { "content": "fn _scalyc_main(_pr: &Region, arguments: Ref<Vector<String>>) {\n\n use scalyc::compiler::Compiler;\n\n let _r = Region::create(_pr);\n\n\n\n let compiler = Ref::new(_r.page, Compiler::new(_r.page, arguments));\n\n (*compiler).compile(&_r, _r.page, _r.page);\n\n}\n", "file_path": "...
Rust
src/solve/infer/instantiate.rs
gnzlbg/chalk
dc7dbad2244dd2c668fd49938d9d0ef77189bd23
use fallible::*; use fold::*; use std::fmt::Debug; use super::*; impl InferenceTable { fn instantiate<U, T>(&mut self, universes: U, arg: &T) -> T::Result where T: Fold + Debug, U: IntoIterator<Item = ParameterKind<UniverseIndex>>, { debug!("instantiate(arg={:?})", arg); ...
use fallible::*; use fold::*; use std::fmt::Debug; use super::*; impl InferenceTable { fn instantiate<U, T>(&mut self, universes: U, arg: &T) -> T::Result where T: Fold + Debug, U: IntoIterator<Item = ParameterKind<UniverseIndex>>, { debug!("instantiate(arg={:?})", arg); ...
lf) -> (&[ParameterKind<()>], &Self::Output) { (&self.0, &self.1) } } struct Instantiator { vars: Vec<Parameter>, } impl DefaultTypeFolder for Instantiator {} impl ExistentialFolder for Instantiator { fn fold_free_existential_ty(&mut self, depth: usize, binders: usize) -> Fallible<Ty> { i...
&mut instantiator, 0).expect("") } fn parameter_kind_to_parameter( &mut self, param_kind: ParameterKind<UniverseIndex>, ) -> Parameter { match param_kind { ParameterKind::Ty(ui) => ParameterKind::Ty(self.new_variable(ui).to_ty()), ParameterKind::Lifetime(ui) ...
random
[ { "content": "/// Applies the given folder to a value.\n\npub trait Fold: Debug {\n\n /// The type of value that will be produced once folding is done.\n\n /// Typically this is `Self`, unless `Self` contains borrowed\n\n /// values, in which case owned values are produced (for example,\n\n /// one ...
Rust
tests/control.rs
big-ab-games/badder-lang
4580103f70be866a8b151912433b4d369f7d4ba4
#![allow(clippy::cognitive_complexity)] use badder_lang::{controller::*, *}; use std::time::*; const NO_FLAG: IntFlag = 0; macro_rules! await_next_pause { ($controller:ident) => {{ $controller.refresh(); if $controller.paused() { $controller.unpause(); } let before = ...
#![allow(clippy::cognitive_complexity)] use badder_lang::{controller::*, *}; use std::time::*; const NO_FLAG: IntFlag = 0; macro_rules! await_next_pause { ($controller:ident) => {{ $controller.refresh(); if $controller.paused() { $controller.unpause(); } let before = ...
ack = $stack; $( let id = Token::Id(stringify!($key).into()); let index = $index; if stack.len() <= index || !stack[index].contains_key(&id) { println!("Actual stack {:?}", stack); assert!(stack.len() > index, "Stack smaller than expected"); ...
assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((6, 5), (6, 15))); assert_eq!(await_next_pause!(con).src, SourceRef((5, 7), (5, 16))); asse...
random
[ { "content": "fn interested_in(ast: &Ast) -> bool {\n\n use crate::Ast::*;\n\n !matches!(\n\n *ast,\n\n LinePair(..)\n\n | Line(..)\n\n | Empty(..)\n\n | Num(..)\n\n | ReferSeq(..)\n\n | ReferSeqIndex(..)\n\n | Refer(..)\n\n ...
Rust
src/indexer/async.rs
jerry73204/rust-tffile
b0285d172c8a84413018e0cdf69437d164728a50
use super::{Position, RecordIndex, RecordIndexerConfig}; use crate::{ error::{Error, Result}, record::Record, utils, }; use async_std::{ fs::File, io::BufReader, path::{Path, PathBuf}, }; use futures::{ io::{AsyncRead, AsyncSeek, AsyncSeekExt as _}, stream, stream::{Stream, StreamExt...
use super::{Position, RecordIndex, RecordIndexerConfig}; use crate::{ error::{Error, Result}, record::Record, utils, }; use async_std::{ fs::File, io::BufReader, path::{Path, PathBuf}, }; use futures::{ io::{AsyncRead, AsyncSeek, AsyncSeekExt as _}, stream, stream::{Stream, StreamExt...
} pub async fn load_prefix_async<'a, P>( prefix: P, config: RecordIndexerConfig, ) -> Result<impl Stream<Item = Result<RecordIndex>>> where P: Into<Cow<'a, str>>, { let stream = load_prefix_futures(prefix, config) .await? .then(|fut| fut) .try_flatten(); Ok(stream) } pub a...
pub async fn load_async<T>(&self) -> Result<T> where T: Record, { let Self { ref path, offset, len, } = *self; let mut reader = BufReader::new(File::open(&**path).await?); let bytes = read_record_at(&mut reader, offset, len).await?; ...
function_block-full_function
[ { "content": "pub fn split_prefix<'a>(prefix: impl Into<Cow<'a, str>>) -> (PathBuf, OsString) {\n\n let prefix = prefix.into();\n\n if prefix.ends_with(MAIN_SEPARATOR) {\n\n let dir = PathBuf::from(prefix.into_owned());\n\n (dir, OsString::from(\"\"))\n\n } else {\n\n let prefix = ...
Rust
src/population.rs
Phlosioneer/neat-learning
60fb7d37b8b7678b17b499313a95a664b19e504c
use genome::Genome; use rand::Rng; use std::collections::HashMap; use Environment; pub struct Counter { innovation: u64, node: usize, cached_connections: HashMap<(usize, usize), u64>, cached_splits: HashMap<(usize, usize), (u64, usize)>, } impl Counter { ...
use genome::Genome; use rand::Rng; use std::collections::HashMap; use Environment; pub struct Counter { innovation: u64, node: usize, cached_connections: HashMap<(usize, usize), u64>, cached_splits: HashMap<(usize, usize), (u64, usize)>, } impl Counter { ...
node); } } let innovation = self.next_innovation(); let node = self.next_node(); self.cached_splits .insert((input_node, output_node), (innovation, node)); (innovation, node) } pub fn clear_innovations(&mut self) { self.cached_conne...
node: start, cached_connections: HashMap::new(), cached_splits: HashMap::new(), } } fn next_innovation(&mut self) -> u64 { let temp = self.innovation; self.innovation += 1; temp } fn next_node(&mut self) -> usize { le...
random
[ { "content": "pub trait Environment {\n\n fn fitness_type() -> FitnessType;\n\n\n\n fn input_count(&self) -> usize;\n\n fn output_count(&self) -> usize;\n\n\n\n fn calc_fitness(&self, organism: &Organism) -> f64;\n\n fn random_genome<R: Rng>(\n\n rng: &mut R,\n\n counter: &mut Count...
Rust
src/serialize_b2_body.rs
yangfengzzz/box2d-rs
0f41603d786545a8dee08d09f743a51e8de78bea
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::{ ser::{SerializeStruct}, Deserialize, Serialize, Serializer, }; use serde::de::DeserializeSeed; use std::fmt; use std::rc::{Rc}; use crate::b2_body::*; use crate::b2_settings::*; use crate::b2_world::*; use crate::serialize_b2_...
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::{ ser::{SerializeStruct}, Deserialize, Serialize, Serializer, }; use serde::de::DeserializeSeed; use std::fmt; use std::rc::{Rc}; use crate::b2_body::*; use crate::b2_settings::*; use crate::b2_world::*; use crate::serialize_b2_...
} pub(crate) struct B2bodyVisitorContext<D: UserDataType> { pub(crate) m_world: B2worldWeakPtr<D>, } impl<'de, U: UserDataType> DeserializeSeed<'de> for B2bodyVisitorContext<U> { type Value = (); fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<...
ok_or_else(|| de::Error::invalid_length(0, &self))?; Ok(()) } fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: MapAccess<'de>, { let mut body = None; let world = self.0.m_world.up...
function_block-function_prefix_line
[ { "content": "pub fn synchronize_fixtures_by_world<D: UserDataType>(self_: &mut B2body<D>, world: &B2world<D>) {\n\n\tsynchronize_fixtures_internal(self_, world);\n\n}\n\n\n", "file_path": "src/private/dynamics/b2_body.rs", "rank": 0, "score": 291282.27457034343 }, { "content": "pub fn set_t...
Rust
rs/crypto/internal/crypto_lib/basic_sig/ed25519/src/types/conversions.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
use super::*; use ic_crypto_secrets_containers::SecretArray; use ic_types::crypto::{AlgorithmId, CryptoError}; use std::convert::TryFrom; pub mod protobuf; #[cfg(test)] mod tests; impl From<SecretKeyBytes> for String { fn from(val: SecretKeyBytes) -> Self { base64::encode(val.0.expose_secret()) } } i...
use super::*; use ic_crypto_secrets_containers::SecretArray; use ic_types::crypto::{AlgorithmId, CryptoError}; use std::convert::TryFrom; pub mod protobuf; #[cfg(test)] mod tests; impl From<SecretKeyBytes> for String { fn from(val: SecretKeyBytes) -> Self { base64::encode(val.0.expose_secret()) } } i...
; } let mut buffer = [0u8; SignatureBytes::SIZE]; buffer.copy_from_slice(signature_bytes); Ok(SignatureBytes(buffer)) } } impl TryFrom<&str> for SignatureBytes { type Error = CryptoError; fn try_from(signature: &str) -> Result<Self, CryptoError> { let signature = ba...
Err(CryptoError::MalformedSignature { algorithm: AlgorithmId::Ed25519, sig_bytes: signature_bytes.clone(), internal_error: format!( "Incorrect signature length: expected {}, got {}.", SignatureBytes::SIZE, signat...
call_expression
[]
Rust
src/output.rs
goto-bus-stop/sqc
43e7b5f00d974036326797470f495392691ffa6b
use crate::highlight::SqlHighlighter; use comfy_table::{Cell, Color, ContentArrangement, Table}; use csv::{ByteRecord, Writer, WriterBuilder}; use itertools::Itertools; use rusqlite::types::ValueRef; use rusqlite::{Row, Statement}; use std::fs::File; use std::io::Write; use std::process::{Command, Stdio}; use std::str:...
use crate::highlight::SqlHighlighter; use comfy_table::{Cell, Color, ContentArrangement, Table}; use csv::{ByteRecord, Writer, WriterBuilder}; use itertools::Itertools; use rusqlite::types::ValueRef; use rusqlite::{Row, Statement}; use std::fs::File; use std::io::Write; use std::process::{Command, Stdio}; use std::str:...
} pub struct CsvOutput<'a> { writer: Writer<&'a mut dyn WriteColor>, } impl<'a> CsvOutput<'a> { pub fn new(statement: &Statement<'_>, output: &'a mut dyn WriteColor) -> Self { let mut writer = WriterBuilder::new().has_headers(true).from_writer(output); writer .write_byte...
c); if self.table.get_row(100).is_some() { let mut command = Command::new("less") .stdin(Stdio::piped()) .env("LESSCHARSET", "UTF-8") .spawn()?; writeln!(command.stdin.as_mut().unwrap(), "{}", self.table)?; command.wait...
function_block-function_prefixed
[ { "content": "pub fn parse_sql(sql: &str) -> anyhow::Result<ParsedSql<'_>> {\n\n let mut parser = Parser::new();\n\n parser.set_language(tree_sitter_sqlite::language())?;\n\n let tree = parser.parse(sql, None).unwrap();\n\n Ok(ParsedSql { tree, source: sql })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\...
Rust
lapce-data/src/buffer/decoration.rs
porkotron/lapce
a46fb40e8b9aabf7dcf2ea593ea68e3e025892b6
use druid::{ExtEventSink, Target, WidgetId}; use lapce_core::syntax::Syntax; use lapce_rpc::style::{LineStyles, Style}; use std::{ cell::RefCell, path::PathBuf, rc::Rc, sync::{ atomic::{self}, Arc, }, }; use xi_rope::{rope::Rope, spans::Spans, RopeDelta}; use crate::{ buffer::{d...
use druid::{ExtEventSink, Target, WidgetId}; use lapce_core::syntax::Syntax; use lapce_rpc::style::{LineStyles, Style}; use std::{ cell::RefCell, path::PathBuf, rc::Rc, sync::{ atomic::{self}, Arc, }, }; use xi_rope::{rope::Rope, spans::Spans, RopeDelta}; use crate::{ buffer::{d...
}
if changes.is_none() { return; } let changes = changes.unwrap(); if atomic_rev.load(atomic::Ordering::Acquire) != rev { return; } let _ = event_sink.submit_command( ...
function_block-function_prefix_line
[ { "content": "fn load_file(path: &Path) -> Result<Rope> {\n\n let mut f = File::open(path)?;\n\n let mut bytes = Vec::new();\n\n f.read_to_end(&mut bytes)?;\n\n Ok(Rope::from(std::str::from_utf8(&bytes)?))\n\n}\n\n\n", "file_path": "lapce-proxy/src/buffer.rs", "rank": 0, "score": 260806....
Rust
test/datalog_tests/rust_api_test/src/main.rs
lykahb/differential-datalog
bf8b86468476a1ee3560e5f58ee91b44565c78f7
use std::borrow::Cow; use tutorial_ddlog::Relations; use tutorial_ddlog::typedefs::*; use differential_datalog::api::HDDlog; use differential_datalog::{DDlog, DDlogDynamic, DDlogInventory}; use differential_datalog::program::config::{Config, ProfilingConfig}; use differential_datalog::DeltaMap; use differential_...
use std::borrow::Cow; use tutorial_ddlog::Relations; use tutorial_ddlog::typedefs::*; use differential_datalog::api::HDDlog; use differential_datalog::{DDlog, DDlogDynamic, DDlogInventory}; use differential_datalog::program::config::{Config, ProfilingConfig}; use differential_datalog::DeltaMap; use differential_...
fn dump_delta(ddlog: &HDDlog, delta: &DeltaMap<DDValue>) { for (rel, changes) in delta.iter() { println!("Changes to relation {}", ddlog.inventory.get_table_name(*rel).unwrap()); for (val, weight) in changes.iter() { println!("{} {:+}", val, weight); } } }
function_block-full_function
[ { "content": "fn record_from_array(mut src: Vec<Value>) -> Result<Record, String> {\n\n if src.len() != 2 {\n\n return Err(format!(\"record array is not of length 2: {:?}\", src));\n\n };\n\n let val = src.remove(1);\n\n let field = src.remove(0);\n\n match field {\n\n Value::String...
Rust
src/common/parse.rs
Nejat/cli-toolbox-rs
646a0b7de8fe2898b17e492e9310eda34c9e845d
use syn::{Error, Expr}; #[cfg(any(feature = "debug", feature = "report"))] use syn::Lit; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; #[cfg(any(feature = "eval", feature = "release"))] use verbosity::Verbosity; #[cfg(any(feature = "eval", feature = "release"))] use crate::common::{DUPE_VERBOSITY_ER...
use syn::{Error, Expr}; #[cfg(any(feature = "debug", feature = "report"))] use syn::Lit; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; #[cfg(any(feature = "eval", feature = "release"))] use verbosity::Verbosity; #[cfg(any(feature = "eval", feature = "release"))] use crate::common::{DUPE_VERBOSITY_ER...
#[cfg(any(feature = "eval", feature = "release"))] fn verbosity_keyword_peek2(input: ParseStream) -> bool { input.peek2(kw::terse) || input.peek2(kw::verbose) }
lt<Lit> { let literal = <Lit>::parse(input)?; match literal { Lit::Str(_) | Lit::ByteStr(_) => {} _ => return Err(Error::new(literal.span(), "expecting a string literal")) } Ok(literal) }
function_block-function_prefixed
[ { "content": "#[cfg(feature = \"eval\")]\n\n#[proc_macro]\n\npub fn eval(input: TokenStream) -> TokenStream {\n\n parse_macro_input!(input as eval_macro::Eval).into_token_stream().into()\n\n}\n\n\n\n/// Conditionally evaluates expressions when intended verbosity matches active verbosity\n\n/// and only when ...
Rust
src/common/mod.rs
samkenxstream/rezolus
e48c39dbeda5277a2a70fab86f114e31df24a861
use std::collections::HashMap; use std::io::BufRead; use std::io::SeekFrom; use dashmap::DashMap; use tokio::fs::File; use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader}; pub mod bpf; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const NAME: &str = env!("CARGO_PKG_NAME"); pub const SECOND: u64 =...
use std::collections::HashMap; use std::io::BufRead; use std::io::SeekFrom; use dashmap::DashMap; use tokio::fs::File; use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader}; pub mod bpf; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const NAME: &str = env!("CARGO_PKG_NAME"); pub const SECOND: u64 =...
pub fn release_minor(&self) -> Result<u32, std::io::Error> { let parts: Vec<&str> = self.release.split('.').collect(); if let Some(s) = parts.get(1) { return s .parse::<u32>() .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput)); ...
pub fn release_major(&self) -> Result<u32, std::io::Error> { let parts: Vec<&str> = self.release.split('.').collect(); if let Some(s) = parts.get(0) { return s .parse::<u32>() .map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput)); } ...
function_block-full_function
[ { "content": "#[cfg(feature = \"bpf\")]\n\npub fn symbol_lookup(name: &str) -> Option<String> {\n\n use std::fs::File;\n\n use std::io::prelude::*;\n\n use std::io::BufReader;\n\n\n\n let symbols = File::open(\"/proc/kallsyms\");\n\n if symbols.is_err() {\n\n return None;\n\n }\n\n\n\n ...
Rust
codegen/src/ext/vt.rs
buty4649/vte
ea940fcb74abce67b927788e4f9f64fc63073d37
use std::fmt; use syntex::Registry; use syntex_syntax::ast::{self, Arm, Expr, ExprKind, LitKind, Pat, PatKind}; use syntex_syntax::codemap::Span; use syntex_syntax::ext::base::{DummyResult, ExtCtxt, MacEager, MacResult}; use syntex_syntax::ext::build::AstBuilder; use syntex_syntax::parse::parser::Parser; use syntex_...
use std::fmt; use syntex::Registry; use syntex_syntax::ast::{self, Arm, Expr, ExprKind, LitKind, Pat, PatKind}; use syntex_syntax::codemap::Span; use syntex_syntax::ext::base::{DummyResult, ExtCtxt, MacEager, MacResult}; use syntex_syntax::ext::build::AstBuilder; use syntex_syntax::parse::parser::Parser; use syntex_...
; } else { state = Some(state_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid state"); })?); } } } match (action,...
Some(action_from_str(&path_str).map_err(|_| { cx.span_err(expr.span, "invalid action"); })?)
call_expression
[ { "content": "fn u8_lit_from_expr(expr: &Expr, cx: &mut ExtCtxt) -> Result<u8, ()> {\n\n static MSG: &str = \"expected u8 int literal\";\n\n\n\n match expr.node {\n\n ExprKind::Lit(ref lit) => match lit.node {\n\n LitKind::Int(val, _) => Ok(val as u8),\n\n _ => {\n\n ...
Rust
third_party/rust_crates/vendor/toml_edit/src/parser/strings.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use crate::decor::InternalString; use crate::parser::errors::CustomError; use crate::parser::trivia::{newline, ws, ws_newlines}; use combine::error::{Commit, Info}; use combine::parser::char::char; use combine::parser::range::{range, take, take_while}; use combine::stream::RangeStream; use combine::*; use std::char; p...
use crate::decor::InternalString; use crate::parser::errors::CustomError; use crate::parser::trivia::{newline, ws, ws_newlines}; use combine::error::{Commit, Info}; use combine::parser::char::char; use combine::parser::range::{range, take, take_while}; use combine::stream::RangeStream; use combine::*; use std::char; p...
ml_literal_body()) .message("While parsing a Multiline Literal String") });
uence") .then(|c| { parser(move |input| { match c { 'b' => Ok(('\u{8}', Commit::Peek(()))), 'f' => Ok(('\u{c}', Commit::Peek(()))), 'n' => Ok(('\n', Commit::Peek(()))), 'r' => Ok(('\r', Commit::...
random
[]
Rust
src/runtime/opcode/args.rs
Miyakowww/aoi
3cfbe4ef2ada58b10751ee4a0dd2a041c4cd4d23
use std::fmt::Display; use crate::AoStatus; use crate::AoType; use crate::AoVM; #[derive(Debug, PartialEq, Clone)] pub enum AoArg { PC, DP, MP, DSB, DST, CA, DS, MEM, Imm(AoType), } impl AoArg { ...
use std::fmt::Display; use crate::AoStatus; use crate::AoType; use crate::AoVM; #[derive(Debug, PartialEq, Clone)] pub enum AoArg { PC, DP, MP, DSB, DST, CA, DS, MEM, Imm(AoType), } impl AoArg { ...
}
pub fn to_aoarg(&self) -> AoArg { match self { AoArgLowerCase::pc => AoArg::PC, AoArgLowerCase::dp => AoArg::DP, AoArgLowerCase::mp => AoArg::MP, AoArgLowerCase::dsb => AoArg::DSB, AoArgLowerCase::dst => AoArg::DST, AoArgLowerCase::ca => Ao...
function_block-full_function
[ { "content": "fn clone_vm_status(vm: &AoVM) -> AoVM {\n\n let mut new_vm = AoVM::new(|_, _| None);\n\n new_vm.pc = vm.pc;\n\n new_vm.ca = vm.ca.clone();\n\n new_vm.dp = vm.dp;\n\n new_vm.dsb = vm.dsb;\n\n new_vm.ds = vm.ds.clone();\n\n new_vm\n\n}\n", "file_path": "examples/single_step....
Rust
src/lib.rs
SOF3/minihtml
4294517978e446b4971cd8327ac97a12fb728b1f
use std::fmt; pub type Result<T = (), E = fmt::Error> = std::result::Result<T, E>; pub trait ToHtmlNode { fn fmt(&self, f: &mut fmt::Formatter) -> Result; } pub trait ToWholeHtmlAttr { fn fmt(&self, name: NoSpecial<'_>, f: &mut fmt::Formatter) -> Result; } pub trait ToHtmlAttr { ...
use std::fmt; pub type Result<T = (), E = fmt::Error> = std::result::Result<T, E>; pub trait ToHtmlNode { fn fmt(&self, f: &mut fmt::Formatter) -> Result; } pub trait ToWholeHtmlAttr { fn fmt(&self, name: NoSpecial<'_>, f: &mut fmt::Formatter) -> Result; } pub trait ToHtmlAttr { ...
} #[derive(Debug, Clone, Copy)] pub struct NoSpecial<'t>(pub &'t str); impl<'t> NoSpecial<'t> { #[inline] pub fn debug_checked(value: &'t str) -> Self { debug_assert!( !has_special_chars(value), "Value passed to NoSpecial::debug_checked() contains speicla characters: {:?}", ...
lf, name: NoSpecial<'_>, f: &mut fmt::Formatter) -> Result { write!(f, " {}=\"", name.0)?; ToHtmlAttr::fmt(self, f)?; write!(f, "\"")?; Ok(()) }
function_block-function_prefixed
[ { "content": "fn html_impl(input: TokenStream) -> syn::Result<TokenStream> {\n\n let nodes = syn::parse2::<parse::HtmlNodes>(input).map_err(ctx(\"Parsing HTML input\"))?;\n\n let nodes = nodes\n\n .nodes\n\n .into_iter()\n\n .map(write_node)\n\n .collect::<syn::Result<Vec<Token...
Rust
test/src/utils.rs
Kryptoxic/ckb
3aaf85b5c3a64488cef4c914ab2bbf44051d9e85
use crate::{Net, Node, TXOSet}; use ckb_jsonrpc_types::{BlockTemplate, TransactionWithStatus, TxStatus}; use ckb_types::core::EpochNumber; use ckb_types::{ bytes::Bytes, core::{BlockNumber, BlockView, HeaderView, TransactionView}, h256, packed::{ Block, BlockTransactions, Byte32, CompactBlock, G...
use crate::{Net, Node, TXOSet}; use ckb_jsonrpc_types::{BlockTemplate, TransactionWithStatus, TxStatus}; use ckb_types::core::EpochNumber; use ckb_types::{ bytes::Bytes, core::{BlockNumber, BlockView, HeaderView, TransactionView}, h256, packed::{ Block, BlockTransactions, Byte32, CompactBlock, G...
iew { let proposals = proposals.iter().map(|tx| tx.proposal_short_id()); blank(node) .as_advanced_builder() .proposals(proposals) .build() } pub fn blank(node: &Node) -> BlockView { let example = node.new_block(None, None, None); example .as_advanced_builder() .s...
tweaked_duration(secs: u64) -> Duration { let sec_coefficient = env::var("CKB_TEST_SEC_COEFFICIENT") .unwrap_or_default() .parse() .unwrap_or(1.0); Duration::from_secs((secs as f64 * sec_coefficient) as u64) } pub fn clear_messages(net: &Net) { while let Ok(_) = net.receive_timeout...
random
[]
Rust
rust/core/src/matching/text.rs
DougAnderson444/deno-autosuggest
9d7b164063decd0bc9af3ec01e411c3a307f2843
use std::cmp::Ordering::{Equal, Less}; use std::cell::RefCell; use crate::tokenization::{Word, TextRef}; use super::WordMatch; use super::word::word_match; thread_local! { static RMATCHES: RefCell<Vec<Option<WordMatch>>> = RefCell::new(Vec::with_capacity(20)); static QMATCHES: RefCell<Vec<Option<WordMatch>>> =...
use std::cmp::Ordering::{Equal, Less}; use std::cell::RefCell; use crate::tokenization::{Word, TextRef}; use super::WordMatch; use super::word::word_match; thread_local! { static RMATCHES: RefCell<Vec<Option<WordMatch>>> = RefCell::new(Vec::with_capacity(20)); static QMATCHES: RefCell<Vec<Option<WordMatch>>> =...
#[cfg(test)] mod tests { use insta::assert_debug_snapshot; use crate::tokenization::{Text, TextOwn}; use crate::lang::{CharClass, lang_basic, lang_english, lang_spanish}; use super::{text_match}; fn text(s: &str) -> TextOwn { let lang = lang_basic(); Text::from_str(s) ...
pub fn text_match(rtext: &TextRef, qtext: &TextRef) -> (Vec<WordMatch>, Vec<WordMatch>) { RMATCHES.with(|rcell| { QMATCHES.with(|qcell| { let rmatches = &mut *rcell.borrow_mut(); let qmatches = &mut *qcell.borrow_mut(); rmatches.clear(); qmatches.clear(); rmatches.resize(...
function_block-full_function
[ { "content": "fn using_store<T, F>(f: F) -> T where F: (FnOnce(&mut Store) -> T) {\n\n init_store();\n\n STORE.with(|cell| {\n\n let store_opt = &mut *cell.borrow_mut();\n\n let store = store_opt.as_mut().unwrap();\n\n f(store)\n\n })\n\n}\n\n\n\n\n", "file_path": "rust/core/te...
Rust
src/ether.rs
simmsb/jnet
2b5c94b0588bcdaf70eb058b6bd8641433250c8a
use core::{ fmt, ops::{Range, RangeFrom}, }; use as_slice::{AsMutSlice, AsSlice}; use byteorder::{ByteOrder, NetworkEndian as NE}; use cast::{u16, usize}; use owning_slice::{IntoSliceFrom, Truncate}; use crate::{arp, ipv4, ipv6, mac, traits::UncheckedIndex, Invalid}; /* Frame format */ const DESTINATION: R...
use core::{ fmt, ops::{Range, RangeFrom}, }; use as_slice::{AsMutSlice, AsSlice}; use byteorder::{ByteOrder, NetworkEndian as NE}; use cast::{u16, usize}; use owning_slice::{IntoSliceFrom, Truncate}; use crate::{arp, ipv4, ipv6, mac, traits::UncheckedIndex, Invalid}; /* Frame format */ const DESTINATION: R...
} full_range!( u16, #[derive(Clone, Copy, Debug, PartialEq)] pub enum Type { Ipv4 = 0x0800, Arp = 0x0806, Ipv6 = 0x86DD, } ); #[cfg(test)] mod tests { use crate::ether; #[test] fn new() { const SZ: u16 = 128; let ...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ether::Frame") .field("destination", &self.get_destination()) .field("source", &self.get_source()) .field("type", &self.get_type()) .finish() }
function_block-full_function
[ { "content": "fn our_nl_addr() -> ipv6::Addr {\n\n MAC.into_link_local_address()\n\n}\n\n\n", "file_path": "firmware/examples/ipv6.rs", "rank": 0, "score": 166475.85127620032 }, { "content": "/// Serializes the `value` into the given `buffer`\n\npub fn write<'a, T>(value: &T, buffer: &'a ...
Rust
src/driver.rs
king6cong/iron-kaleidoscope
fed9a75aa211a829a0b2b099f4bcfcef2079d034
use std::io; use std::io::Write; use iron_llvm::core::value::Value; use iron_llvm::target; use builder; use builder::{IRBuilder, ModuleProvider}; use jitter; use jitter::JITter; use lexer::*; use parser::*; use filer; pub use self::Stage::{ Exec, IR, AST, Tokens }; #[derive(PartialEq, Clon...
use std::io; use std::io::Write; use iron_llvm::core::value::Value; use iron_llvm::target; use builder; use builder::{IRBuilder, ModuleProvider}; use jitter; use jitter::JITter; use lexer::*; use parser::*; use filer; pub use self::Stage::{ Exec, IR, AST, Tokens }; #[derive(PartialEq, Clon...
e); continue 'main } } print!(". "); stdout.flush().unwrap(); input.clear(); stdin.read_line(&mut input).ok().expect("Failed to read line"); } if stage == AST { println!("{:?}", ast); ...
function_block-function_prefixed
[ { "content": "pub fn dump_bitcode(path: &str, module_provider: &mut builder::ModuleProvider) -> Result<(), ()> {\n\n write_bitcode_to_file(module_provider.get_module(), path)\n\n}\n", "file_path": "src/filer.rs", "rank": 0, "score": 360041.82408747525 }, { "content": "pub fn load_stdlib(p...
Rust
application/apps/indexer/indexer_base/src/utils.rs
ir210/chipmunk
e2664efa3d3c0d80b67f3b324aa5289f6941ab23
use failure::{err_msg, Error}; use std::char; use std::fmt::Display; use std::fs; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path; use std::str; pub const ROW_NUMBER_SENTINAL: char = '\u{0002}'; pub const PLUGIN_ID_SENTINAL: char = '\u{0003}'; pub const SENTINAL_LENGTH: usize = 1; pub const POSIX_TIME...
use failure::{err_msg, Error}; use std::char; use std::fmt::Display; use std::fs; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path; use std::str; pub const ROW_NUMBER_SENTINAL: char = '\u{0002}'; pub const PLUGIN_ID_SENTINAL: char = '\u{0003}'; pub const SENTINAL_LENGTH: usize = 1; pub const POSIX_TIME...
#[inline] pub fn next_line_nr(path: &std::path::Path) -> Result<usize, Error> { if !path.exists() { return Ok(0); } let file = fs::File::open(path).expect("opening file did not work"); let file_size = file.metadata().expect("could not read file metadata").len(); if file_size == 0 { ...
pub fn linenr_length(linenr: usize) -> usize { if linenr == 0 { return 1; }; let nr = linenr as f64; 1 + nr.log10().floor() as usize }
function_block-full_function
[ { "content": "pub fn read_format_string_options(f: &mut fs::File) -> Result<FormatTestOptions, failure::Error> {\n\n let mut contents = String::new();\n\n f.read_to_string(&mut contents)\n\n .expect(\"something went wrong reading the file\");\n\n let v: FormatTestOptions = serde_json::from_str(&...
Rust
src/test_support/mod.rs
housel/ferros
d67a845a76500a84c56031a97feadb181f795d67
use core::marker::PhantomData; use core::ops::Sub; use selfe_sys::*; use typenum::*; use crate::arch::{self, PageBits}; use crate::cap::*; use crate::error::{ErrorExt, SeL4Error}; use crate::pow::{Pow, _Pow}; mod resources; mod types; use crate::vspace::MappedMemoryRegion; pub use resources::*; pub use types::*; i...
use core::marker::PhantomData; use core::ops::Sub; use selfe_sys::*; use typenum::*; use crate::arch::{self, PageBits}; use crate::cap::*; use crate::error::{ErrorExt, SeL4Error}; use crate::pow::{Pow, _Pow}; mod resources; mod types; use crate::vspace::MappedMemoryRegion; pub use resources::*; pub use types::*; i...
}, Cap { cptr: irq_control.cptr, _role: PhantomData, cap_data: IRQControl { available: irq_control.cap_data.available.clone(), }, }, ); unsafe { slots.revoke_in_reverse() } unsafe { seL4_CNode_Revoke( ...
&[&types::RunTest], ) -> Result<types::TestOutcome, SeL4Error> { let resources::TestResourceRefs { slots, untyped, asid_pool, mut scratch, mapped_memory_region, cnode, thread_authority, vspace_paging_root, user_image, irq_control, }...
random
[ { "content": "fn gen_id<G: IdGenerator>(g: &mut G, name_hint: &'static str) -> Ident {\n\n syn::Ident::new(&g.gen(name_hint), Span::call_site())\n\n}\n\n\n", "file_path": "ferros-test/test-macro-impl/src/codegen.rs", "rank": 2, "score": 235311.91710156776 }, { "content": "pub fn run(raw_b...
Rust
src/api.rs
FCG-LLC/hyena
5354ed498675aee6ed517c75e13b15849cea5c42
use bincode::{serialize, deserialize, Infinite}; use catalog::{BlockType, Column, PartitionInfo}; use manager::{Manager, BlockCache}; use int_blocks::{Block, Int32SparseBlock, Int64DenseBlock, Int64SparseBlock, Scannable, Deletable, Movable, Upsertable}; use std::time::Instant; use scan::{BlockScanConsumer}; #[derive(...
use bincode::{serialize, deserialize, Infinite}; use catalog::{BlockType, Column, PartitionInfo}; use manager::{Manager, BlockCache}; use int_blocks::{Block, Int32SparseBlock, Int64DenseBlock, Int64SparseBlock, Scannable, Deletable, Movable, Upsertable}; use std::time::Instant; use scan::{BlockScanConsumer}; #[derive(...
rialize(&x, Infinite).unwrap()); println!("Pseudo catalog refresh response: {:?}", serialize(&pseudo_response, Infinite).unwrap()); }
::from("ts") }, Column { data_type: BlockType::Int32Sparse, name: String::from("source") } ], available_partitions: vec![ PartitionInfo{ min_ts: 100, max_ts: 200, id: 999, ...
random
[ { "content": "fn create_message(ts_base : u64) -> InsertMessage {\n\n let mut rng = rand::thread_rng();\n\n\n\n let mut pseudo_ts = ts_base * 1000000;\n\n\n\n let mut blocks : Vec<Block> = Vec::new();\n\n let mut col_types : Vec<(u32, BlockType)> = Vec::new();\n\n\n\n for col_no in 0..2 + TEST_CO...
Rust
src/models/repository.rs
QaQAdrian/git-tui
02c32a972055c695c3ad6465daf72c12913568d1
use std::collections::HashMap; use std::fs; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::Path; use git2::Repository; use crate::ui::message::{Level, MessageView}; static FILE_STR: &str = "/git-tui.log"; pub struct Repositories { pub search_path: String, pub map: HashMap<String, Repos...
use std::collections::HashMap; use std::fs; use std::fs::{File, OpenOptions}; use std::io::Write; use std::path::Path; use git2::Repository; use crate::ui::message::{Level, MessageView}; static FILE_STR: &str = "/git-tui.log"; pub struct Repositories { pub search_path: String, pub map: HashMap<String, Repos...
fn log(&self, s: String) { self.log_file.as_ref().map(|mut f| { if let Err(e) = f.write(s.as_bytes()) { eprintln!("Write log file Error {}", e); } }); } fn add_repo(&mut self, path: String) -> Result<(), git2::Error> { let repo = Repository:...
position + 3, format!(" {}{} ", "--git-dir=", path.display()).as_str(), ) } let (code, output, error) = run_script!(cmd).unwrap(); if code == 0 { closure(format!("OK! repo: {}", relative_path), Level::INFO, v...
function_block-function_prefix_line
[]
Rust
carbide_controls/src/radio_button.rs
HolgerGottChristensen/carbide
dda3c0426b8c6a9001eadb16ab0b2369e26ed1be
use std::fmt::Debug; use carbide_core::{DeserializeOwned, Serialize}; use carbide_core::draw::Dimension; use carbide_core::widget::*; use crate::PlainRadioButton; #[derive(Clone, Widget)] pub struct RadioButton<T, GS> where GS: GlobalStateContract, T: Serialize + Clone + Debug + Default + Deseria...
use std::fmt::Debug; use carbide_core::{DeserializeOwned, Serialize}; use carbide_core::draw::Dimension; use carbide_core::widget::*; use crate::PlainRadioButton; #[derive(Clone, Widget)] pub struct RadioButton<T, GS> where GS: GlobalStateContract, T: Serialize + Clone + Debug + Default + Deseria...
atic, GS: GlobalStateContract, > CommonWidget<GS> for RadioButton<T, GS> { fn id(&self) -> Id { self.id } fn set_id(&mut self, id: Id) { self.id = id; } fn flag(&self) -> Flags { Flags::EMPTY } fn children(&self) -> WidgetIter { WidgetIter::single(&self...
nd, EnvironmentColor::Accent, ) .mapped(|(selected, primary_color, selected_color)| { if *selected { *selected_color } else { *primary_color } }); ...
random
[ { "content": "fn bordered_rectangle(button_id: widget::Id, rectangle_id: widget::Id,\n\n rect: Rect, color: Color, style: &Style, ui: &mut UiCell)\n\n{\n\n // BorderedRectangle widget.\n\n let dim = rect.dim();\n\n let border = style.border(&ui.theme);\n\n let border_color = sty...
Rust
src/live_consumer.rs
sevenEng/kafka-view
6dfb045117ed5f0f571ccb7e8e7f99f1950ffc95
use rdkafka::config::ClientConfig; use rdkafka::consumer::{BaseConsumer, Consumer, EmptyConsumerContext}; use rdkafka::message::BorrowedMessage; use rdkafka::message::Timestamp::*; use rdkafka::Message; use rocket::http::RawStr; use rocket::State; use scheduled_executor::ThreadPoolExecutor; use config::{ClusterConfig,...
use rdkafka::config::ClientConfig; use rdkafka::consumer::{BaseConsumer, Consumer, EmptyConsumerContext}; use rdkafka::message::BorrowedMessage; use rdkafka::message::Timestamp::*; use rdkafka::Message; use rocket::http::RawStr; use rocket::State; use scheduled_executor::ThreadPoolExecutor; use config::{ClusterConfig,...
} }; } debug!( "{} messages received in {:?}", buffer.len(), Instant::elapsed(&start_time) ); buffer } } impl Drop for LiveConsumer { fn drop(&mut self) { debug!("Dropping consumer {}", self.id); } } type LiveCons...
ig: &ClusterConfig, topic: &str) -> Result<LiveConsumer> { let consumer = ClientConfig::new() .set("bootstrap.servers", &cluster_config.bootstrap_servers()) .set("group.id", &format!("kafka_view_live_consumer_{}", id)) .set("enable.partition.eof", "false") .set("a...
random
[ { "content": "fn topic_tailer_panel(cluster_id: &ClusterId, topic: &str, tailer_id: u64) -> PreEscaped<String> {\n\n let panel_head = html! {\n\n i class=\"fa fa-align-left fa-fw\" {} \"Messages\"\n\n };\n\n let panel_body = html! {\n\n div class=\"topic_tailer\" data-cluster=(cluster_id)...
Rust
src/ton_core/monitoring/ton_transaction_parser.rs
FlukerGames/ever-wallet-api
42dae96a1966f0dbae6aecfeb754607082a341e9
use anyhow::Result; use bigdecimal::BigDecimal; use nekoton::core::models::{MultisigTransaction, TransactionError}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use ton_block::CommonMsgInfo; use ton_types::AccountId; use uuid::Uuid; use crate::ton_core::*; pub async fn parse_ton_transaction( ...
use anyhow::Result; use bigdecimal::BigDecimal; use nekoton::core::models::{MultisigTransaction, TransactionError}; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use ton_block::CommonMsgInfo; use ton_types::AccountId; use uuid::Uuid; use crate::ton_core::*; pub async fn parse_ton_transaction( ...
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Message { pub fee: Option<BigDecimal>, pub value: Option<BigDecimal>, pub recipient: Option<MessageRecipient>, pub message_hash: String, } #[derive(Default, Debug, Clone, PartialEq, Serialize...
fn is_aborted(transaction: &ton_block::Transaction) -> bool { let mut aborted = false; if let Ok(ton_block::TransactionDescr::Ordinary(description)) = transaction.description.read_struct() { aborted = description.aborted } aborted }
function_block-full_function
[ { "content": "CREATE UNIQUE INDEX transactions_m_hash_account_wc_hex_idx ON transactions (message_hash, account_workchain_id, account_hex)\n\n WHERE direction = 'Send' AND transaction_hash IS NULL;\n", "file_path": "migrations/20211007170851_transactions.sql", "rank": 0, "score": 263855.109015261...
Rust
tests/list.rs
sunli829/async-graphql
175d8693fffff821a63eb7d7954c4091e91f7681
use std::{ cmp::Ordering, collections::{BTreeSet, HashSet, LinkedList, VecDeque}, }; use async_graphql::*; #[tokio::test] pub async fn test_list_type() { #[derive(InputObject)] struct MyInput { value: Vec<i32>, } struct Root { value_vec: Vec<i32>, value_hash_set: HashS...
use std::{ cmp::Ordering, collections::{BTreeSet, HashSet, LinkedList, VecDeque}, }; use async_graphql::*; #[tokio::test] pub async fn test_list_type() { #[derive(InputObject)] struct MyInput { value: Vec<i32>, } struct Root { value_vec: Vec<i32>, value_hash_set: HashS...
e("{ values }") .await .into_result() .unwrap() .data, value!({ "values": [1, 2, 3, 4, 5, 6] }) ); assert_eq!( schema .execute("{ arrayInput(values: [1, 2, 3, 4, 5, 6]) }") .await .into_resul...
function_block-function_prefixed
[ { "content": "/// Parse a GraphQL query document.\n\n///\n\n/// # Errors\n\n///\n\n/// Fails if the query is not a valid GraphQL document.\n\npub fn parse_query<T: AsRef<str>>(input: T) -> Result<ExecutableDocument> {\n\n let mut pc = PositionCalculator::new(input.as_ref());\n\n\n\n let items = parse_defi...
Rust
src/olx_client/mod.rs
valpfft/alx
7069ec98458f4c16d8a6c5710f256fa0a08b4f09
use crate::parse_price; use crate::Offer; use select::document::Document; use select::predicate::{Attr, Class, Name, Predicate}; use std::collections::HashMap; static BASE_URL: &str = "https://www.olx.pl/oferty"; impl Offer { fn build_from_node(node: &select::node::Node) -> Offer { let title = node ...
use crate::parse_price; use crate::Offer; use select::document::Document; use select::predicate::{Attr, Class, Name, Predicate}; use std::collections::HashMap; static BASE_URL: &str = "https://www.olx.pl/oferty"; impl Offer { fn build_from_node(node: &select::node::Node) -> Offer { let title = node ...
fn format_query(query: &str) -> String { query.trim().replace(" ", "-") }
fn get_page(url: String) -> reqwest::Response { let response = reqwest::get(&url).expect("Could not get url"); assert!(response.status().is_success()); response }
function_block-full_function
[ { "content": "fn add_filter(filter: &str, url: &mut String) {\n\n match url.find(\"?\") {\n\n Some(_) => url.push_str(&format!(\"&{}\", filter)),\n\n None => url.push_str(&format!(\"?{}\", filter)),\n\n };\n\n}\n", "file_path": "src/allegro_lokalnie_client/mod.rs", "rank": 1, "sc...