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
src/main.rs
luandknguyen/brainrust
87b42359ea8b28fa78509a1bdf1f009fd7518c30
use std::fs::File; use std::io::prelude::*; use brainrust::*; use clap::{App, Arg, ArgMatches}; enum ParseError { ArraySize(String), EofBehavior(String), InputMode(String), NewlineMode(String), } fn read_file(file_name: &str) -> std::io::Result<String> { let mut file = File::open(file_name)?; ...
use std::fs::File; use std::io::prelude::*; use brainrust::*; use clap::{App, Arg, ArgMatches}; enum ParseError { ArraySize(String), EofBehavior(String), InputMode(String), NewlineMode(String), } fn read_file(file_name: &str) -> std::io::Result<String> { let mut file = File::open(file_name)?; ...
author("Luan N.") .version("0.1") .about("An interpreter written in Rust.") .args(&[ Arg::with_name("source") .required(true) .takes_value(true) .value_name("SOURCE") .help("Source file"), Arg::with_name("inp...
function_block-function_prefix_line
[ { "content": "/// Read result\n\nenum ReadResult {\n\n Success(u8),\n\n None,\n\n Newline,\n\n ReadFailed,\n\n ParseNumError,\n\n}\n\n\n\n/// Interpreter\n\npub struct Interpreter {\n\n pub program: Program,\n\n pub settings: Settings,\n\n pub reader: Box<dyn Read>,\n\n pub writer: Bo...
Rust
src/connectivity/network/netstack3/core/src/fuzz.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
#![warn(dead_code, unused_imports, unused_macros)] use core::{convert::TryInto as _, time::Duration}; use arbitrary::{Arbitrary, Unstructured}; use fuzz_util::Fuzzed; use net_declare::net_mac; use net_types::{ ip::{IpAddress, Ipv4Addr, Ipv6Addr}, UnicastAddr, }; use packet::{ serialize::{Buf, SerializeE...
#![warn(dead_code, unused_imports, unused_macros)] use core::{convert::TryInto as _, time::Duration}; use arbitrary::{Arbitrary, Unstructured}; use fuzz_util::Fuzzed; use net_declare::net_mac; use net_types::{ ip::{IpAddress, Ipv4Addr, Ipv6Addr}, UnicastAddr, }; use packet::{ serialize::{Buf, SerializeE...
f, "Send {:?} frame with {} total bytes: {}", frame_type, buf.len(), description ), FuzzAction::AdvanceTime(SmallDuration(duration)) => { write!(f, "Advance time by {:?}", duration) } ...
traryFrame), AdvanceTime(SmallDuration), } #[derive(Arbitrary)] pub(crate) struct FuzzInput { actions: Vec<FuzzAction>, } impl core::fmt::Display for FuzzAction { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { FuzzAction::ReceiveFrame(ArbitraryFrame...
random
[]
Rust
standalone/pruntime/enclave/src/contracts/btc_lottery.rs
bernardoaraujor/phala-blockchain
603ff26b2799891b708d44e104da93465e3be055
use super::{account_id_from_hex, TransactionError, TransactionResult}; use crate::chain; use crate::contracts::{self, AccountId}; use crate::std::{ collections::{ btree_map::Entry::{Occupied, Vacant}, BTreeMap, }, str::FromStr, string::{String, ToString}, vec::Vec, }; use anyhow::R...
use super::{account_id_from_hex, TransactionError, TransactionResult}; use crate::chain; use crate::contracts::{self, AccountId}; use crate::std::{ collections::{ btree_map::Entry::{Occupied, Vacant}, BTreeMap, }, str::FromStr, string::{String, ToString}, vec::Vec, }; use anyhow::R...
fn handle_query(&mut self, _origin: Option<&chain::AccountId>, req: Request) -> Response { match req { Request::GetAllRounds => Response::GetAllRounds { round_id: self.round_id, }, Request::GetRoundInfo { round_id } => { if self.token_set...
TransactionResult { match cmd { Command::PalletCommand(cmd) => self.handle_pallet_command(context, origin, cmd), Command::UserCommand(cmd) => self.handle_user_command(context, origin, cmd), } }
function_block-function_prefix_line
[]
Rust
src/types/numbering.rs
m4rw3r/chomp
31795bdabc183677db8d857fdc842d14eb541fb7
use primitives::{Guard, IntoInner}; use types::{Buffer, Input}; pub trait Numbering: Clone { type Token: Copy + PartialEq; fn update<B>(&mut self, &B) where B: Buffer<Token=Self::Token>; fn add(&mut self, Self::Token); } #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, Partia...
use primitives::{Guard, IntoInner}; use types::{Buffer, Input}; pub trait Numbering: Clone { type Token: Copy + PartialEq; fn update<B>(&mut self, &B) where B: Buffer<Token=Self::Token>; fn add(&mut self, Self::Token); } #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, Partia...
assert_eq!(many(i, parser).into_inner().1, Ok(vec![ ('a', LineNumber(0)), ('b', LineNumber(1)), ...
fn parser<I: Input<Token=u8>>(i: InputPosition<I, LineNumber>) -> ParseResult<InputPosition<I, LineNumber>, (char, LineNumber), Error<u8>> { parse!{i; string(b"test"); take_while1(|c| c == b' ' || c == b'\t'); let t_name = any(); i ->...
function_block-full_function
[ { "content": "/// A type alias for an `Input` with a token type of `u8`.\n\npub trait U8Input: Input<Token=u8> {}\n\n\n\nimpl<T> U8Input for T\n\n where T: Input<Token=u8> {}\n\n\n\n/// The basic return type of a parser.\n\n///\n\n/// This type satisfies a variant of the `Monad` typeclass. Due to the limitatio...
Rust
web/src/widget/text.rs
RDambrosio016/iced
08f5591148a74fecf3920357ce8ecba6036925a7
use crate::{ css, Bus, Color, Css, Element, Font, HorizontalAlignment, Length, VerticalAlignment, Widget, }; use dodrio::bumpalo; #[derive(Debug, Clone)] pub struct Text { content: String, size: Option<u16>, color: Option<Color>, font: Font, width: Length, height: Length, horizontal...
use crate::{ css, Bus, Color, Css, Element, Font, HorizontalAlignment, Length, VerticalAlignment, Widget, }; use dodrio::bumpalo; #[derive(Debug, Clone)] pub struct Text { content: String, size: Option<u16>, color: Option<Color>, font: Font, width: Length, height: Length, horizontal...
let style = bumpalo::format!( in bump, "width: {}; height: {}; font-size: {}px; color: {}; \ text-align: {}; font-family: {}", width, height, self.size.unwrap_or(20), color, text_align, match self.font ...
let text_align = match self.horizontal_alignment { HorizontalAlignment::Left => "left", HorizontalAlignment::Center => "center", HorizontalAlignment::Right => "right", };
assignment_statement
[ { "content": "/// Returns the style value for the given [`Length`].\n\npub fn length(length: Length) -> String {\n\n match length {\n\n Length::Shrink => String::from(\"auto\"),\n\n Length::Units(px) => format!(\"{}px\", px),\n\n Length::Fill | Length::FillPortion(_) => String::from(\"10...
Rust
src/l3/iterators.rs
dingelish/scryer-prolog
9b789629c9b4d6f61ee1179437ee69588a9f9ead
use l3::ast::*; use std::cell::Cell; use std::collections::VecDeque; use std::vec::Vec; enum IteratorState<'a> { Atom(Level, &'a Cell<RegType>, &'a Atom), Clause(Level, usize, &'a Cell<RegType>, &'a Atom, &'a Vec<Box<Term>>), IsolatedAtom(&'a Cell<RegType>, &'a Atom), IsolatedVar(&'a Cell<VarReg>, &'a...
use l3::ast::*; use std::cell::Cell; use std::collections::VecDeque; use std::vec::Vec; enum IteratorState<'a> { Atom(Level, &'a Cell<RegType>, &'a Atom), Clause(Level, usize, &'a Cell<RegType>, &'a Atom, &'a Vec<Box<Term>>), IsolatedAtom(&'a Cell<RegType>, &'a Atom), IsolatedVar(&'a Cell<VarReg>, &'a...
&Term::Var(ref cell, ref var) => vec![IteratorState::IsolatedVar(cell, var)] }; FactIterator { state_queue: VecDeque::from(states) } } } impl<'a> Iterator for FactIterator<'a> { type Item = TermRef<'a>; fn next(&mut self) -> Option<Self::Item> { while let Som...
&Term::Atom(ref cell, ref atom) => vec![IteratorState::IsolatedAtom(cell, atom)], &Term::Clause(_, _, ref terms) => vec![IteratorState::RootClause(0, terms)],
function_block-random_span
[ { "content": "fn contains_cut_var<'a, Iter: Iterator<Item = &'a Term>>(terms: Iter) -> bool {\n\n for term in terms {\n\n if let &Term::Var(_, ref var) = term {\n\n if var.as_str() == \"!\" {\n\n return true;\n\n }\n\n }\n\n }\n\n\n\n false\n\n}\n\n\n\...
Rust
src/od/partialreader.rs
ids1024/uutils
229eb69c9cf56a219393d45f393daa7be3c830ec
use std::cmp; use std::io; use std::io::Read; use multifilereader::HasError; const MAX_SKIP_BUFFER: usize = 64 * 1024; pub struct PartialReader<R> { inner: R, skip: usize, limit: Option<usize>, } impl<R> PartialReader<R> { pub fn new(inner: R, skip: usize, limit: Option<usize>) -> Self...
use std::cmp; use std::io; use std::io::Read; use multifilereader::HasError; const MAX_SKIP_BUFFER: usize = 64 * 1024; pub struct PartialReader<R> { inner: R, skip: usize, limit: Option<usize>, } impl<R> PartialReader<R> { pub fn new(inner: R, skip: usize, limit: Option<usize>) -> Self...
match self.limit { None => self.inner.read(out), Some(0) => Ok(0), Some(ref mut limit) => { let slice = if *limit > out.len() { out } else { &mut out[0..*limit] }; match self.inner.read(slice) { Err(e) => Err(e), ...
if self.skip > 0 { let buf_size = cmp::min(self.skip, MAX_SKIP_BUFFER); let mut bytes: Vec<u8> = Vec::with_capacity(buf_size); unsafe { bytes.set_len(buf_size); } while self.skip > 0 { let skip_count = cmp::min(self.skip, buf_size); match...
if_condition
[ { "content": "pub fn read_size(child: &mut Child, size: usize) -> String {\n\n let mut output = Vec::new();\n\n output.resize(size, 0);\n\n sleep(Duration::from_secs(1));\n\n child.stdout.as_mut().unwrap().read(output.as_mut_slice()).unwrap();\n\n String::from_utf8(output).unwrap()\n\n}\n", "...
Rust
src/field_attributes.rs
jtk18/serde-aux
ba1b2928b425d80dcf7f6501b82ee2375fe07b3c
use std::fmt::Display; use std::str::FromStr; use serde::{Deserialize, Deserializer}; #[cfg(feature = "chrono")] pub fn deserialize_datetime_utc_from_milliseconds<'de, D>( deserializer: D, ) -> Result<chrono::DateTime<chrono::Utc>, D::Error> where D: Deserializer<'de>, { use chrono::prelude::*; let n...
use std::fmt::Display; use std::str::FromStr; use serde::{Deserialize, Deserializer}; #[cfg(feature = "chrono")] pub fn deserialize_datetime_utc_from_milliseconds<'de, D>( deserializer: D, ) -> Result<chrono::DateTime<chrono::Utc>, D::Error> where D: Deserializer<'de>, { use chrono::prelude::*; let n...
pub fn deserialize_default_from_empty_object<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: Deserializer<'de>, T: Deserialize<'de> + Default, { #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] struct EmptyObject {} #[derive(Debug, Deserialize)] #[serde(untagged)] ...
pub fn deserialize_default_from_null<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: Deserializer<'de>, T: Deserialize<'de> + Default, { Ok(Option::deserialize(deserializer)?.unwrap_or_default()) }
function_block-full_function
[ { "content": "/// Deserializes a struct without checking for the fields case sensititivity.\n\n///\n\n/// # **Notes**\n\n///\n\n/// - The following deserialiser is incompatible with serde's one. If you wish\n\n/// to use `serde(rename)`, there is a high risk it won't work. Please see\n\n/// https://github.com/v...
Rust
src/sys/pkg/lib/omaha-client/src/state_machine/timer.rs
sunshinewithmoonlight/fuchsia-2003
02b23026dc7fecbad063210d5d45fa1b17feeb8b
use futures::future::BoxFuture; use futures::prelude::*; use std::time::Duration; pub trait Timer { fn wait(&mut self, delay: Duration) -> BoxFuture<'static, ()>; } pub struct StubTimer; impl Timer for StubTimer { fn wait(&mut self, _delay: Duration) -> BoxFuture<'static, ()> { future::ready((...
use futures::future::BoxFuture; use futures::prelude::*; use std::time::Duration; pub trait Timer { fn wait(&mut self, delay: Duration) -> BoxFuture<'static, ()>; } pub struct StubTimer; impl Timer for StubTimer { fn wait(&mut self, _delay: Duration) -> BoxFuture<'static, ()> { future::ready((...
m_secs(6666)); block_on(async { timer.wait(Duration::from_secs(5555)).await; timer.wait(Duration::from_secs(6666)).await; }); } #[test] fn test_wait_loop() { let mut timer = MockTimer::new(); timer.expect(Duration::from_secs(1)); timer.expect...
#[test] fn test_simple() { let mut timer = MockTimer::new(); timer.expect(Duration::from_secs(5555)); block_on(timer.wait(Duration::from_secs(5555))); } #[test] fn test_wait_twice() { let mut timer = MockTimer::new(); timer.expect(Duration::from_secs(5555)); ...
random
[]
Rust
core/src/upcopy.rs
yatima-inc/yatima
4a2073554184a6527d10f1ec6d7669e5f7cc5ea9
use crate::{ dag::*, dll::*, }; use core::{ ptr::NonNull, sync::atomic::{ AtomicUsize, Ordering, }, }; pub static UPCOPY_COUNT: AtomicUsize = AtomicUsize::new(0); pub fn clean_up(cc: &ParentPtr) { match cc { ParentPtr::LamBod(link) => unsafe { let Lam { parents, var, .. } = link.as_ref(...
use crate::{ dag::*, dll::*, }; use core::{ ptr::NonNull, sync::atomic::{ AtomicUsize, Ordering, }, }; pub static UPCOPY_COUNT: AtomicUsize = AtomicUsize::new(0);
pub fn upcopy(new_child: DAGPtr, cc: ParentPtr, should_count: bool) { if should_count { UPCOPY_COUNT.fetch_add(1, Ordering::SeqCst); } unsafe { match cc { ParentPtr::LamBod(link) => { let Lam { var, parents, .. } = link.as_ref(); let Var { nam, dep, parents: var_parents, .. } = var...
pub fn clean_up(cc: &ParentPtr) { match cc { ParentPtr::LamBod(link) => unsafe { let Lam { parents, var, .. } = link.as_ref(); for parent in DLL::iter_option(var.parents) { clean_up(parent); } for parent in DLL::iter_option(*parents) { clean_up(parent); } }, P...
function_block-full_function
[ { "content": "## Usage\n\n\n\nThe subcommands planned to be available for the `yatima` CLI are:\n\n* Main commands\n\n * `ca`: content-addresses Lean 4 code to Yatima IR\n\n * `prove`: generates Lurk code for typechecking a content-addressed declaration\n\n* Auxiliary commands\n\n * `tc`: typechecks Ya...
Rust
src/platform_impl/linux/wayland/seat/mod.rs
mahkoh/winit
62e917bdf928b0a9d45e5ebb7f0aff9b10994a5c
use std::cell::RefCell; use std::rc::Rc; use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1; use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1; use sctk::reex...
use std::cell::RefCell; use std::rc::Rc; use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1; use sctk::reexports::protocols::unstable::pointer_constrain
loop_handle: LoopHandle<WinitState>, ) -> Self { Self { seats: Vec::new(), loop_handle, relative_pointer_manager, pointer_constraints, text_input_manager, theme_manager, } } pub fn process_seat_update(&mut self, s...
ts::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1; use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3; use sctk::reexports::client::protocol::wl_seat::WlSeat; use sctk::reexports::client::Attached; use sctk::environment::Environment; us...
random
[ { "content": "fn should_use_dark_mode() -> bool {\n\n should_apps_use_dark_mode() && !is_high_contrast()\n\n}\n\n\n", "file_path": "src/platform_impl/windows/dark_mode.rs", "rank": 0, "score": 44636.2275130403 }, { "content": "fn should_apps_use_dark_mode() -> bool {\n\n type ShouldApp...
Rust
cranelift-wasm/src/sections_translator.rs
timClicks/cranelift
ca1b036a55753da6c02d369da682eb5d4eb1ffba
use crate::environ::{ModuleEnvironment, WasmError, WasmResult}; use crate::state::ModuleTranslationState; use crate::translation_utils::{ tabletype_to_type, type_to_type, FuncIndex, Global, GlobalIndex, GlobalInit, Memory, MemoryIndex, SignatureIndex, Table, TableElementType, TableIndex, }; use crate::{wasm_u...
use crate::environ::{ModuleEnvironment, WasmError, WasmResult}; use crate::state::ModuleTranslationState; use crate::translation_utils::{ tabletype_to_type, type_to_type, FuncIndex, Global, GlobalIndex, GlobalInit, Memory, MemoryIndex, SignatureIndex, Table, TableElementType, TableIndex, }; use crate::{wasm_u...
; elems.push(elem); } environ.declare_table_elements( TableIndex::from_u32(table_index), base, offset, elems.into_boxed_slice(), )? } else { return Err(wasm_unsupported!("unsupported p...
match item? { ElementItem::Null => FuncIndex::reserved_value(), ElementItem::Func(index) => FuncIndex::from_u32(index), }
if_condition
[ { "content": "/// Legalize all the function signatures in `func`.\n\n///\n\n/// This changes all signatures to be ABI-compliant with full `ArgumentLoc` annotations. It doesn't\n\n/// change the entry block arguments, calls, or return instructions, so this can leave the function\n\n/// in a state with type discr...
Rust
src/helpers.rs
rudyjantz/ocicrypt-rs
409568e601d6681edc55ed15c4e6be355cb4f68a
use anyhow::{anyhow, Result}; use std::fs; use std::fs::File; use std::io::Read; use std::os::unix::io::FromRawFd; use crate::config::{CryptoConfig, DecryptConfig, EncryptConfig}; use std::path::Path; fn process_recipient_keys(recipients: Vec<String>) -> Result<[Vec<Vec<u8>>; 6]> { let mut gpg_recipients = vec!...
use anyhow::{anyhow, Result}; use std::fs; use std::fs::File; use std::io::Read; use std::os::unix::io::FromRawFd; use crate::config::{CryptoConfig, DecryptConfig, EncryptConfig}; use std::path::Path; fn process_recipient_keys(recipients: Vec<String>) -> Result<[Vec<Vec<u8>>; 6]> { let mut gpg_recipients = vec!...
let valid_recipients = vec![ "pgp:testkey@key.org".to_string(), jwe_recipient, pkcs7_recipient, pkcs11_recipient, "provider:cmd/grpc".to_string(), ]; assert!(process_recipient_keys(invalid_recipients1).is_err()); assert!(process...
vec!["jwe".to_string()]; let jwe_recipient = format!("jwe:{}/{}", path, "public_key.pem"); let pkcs7_recipient = format!("pkcs7:{}/{}", path, "public_certificate.pem"); let pkcs11_recipient = format!("pkcs11:{}/{}", path, "public_key.pem");
function_block-random_span
[ { "content": "fn base64_hashmap_s<S>(value: &HashMap<String, Vec<u8>>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let b64_encoded: HashMap<_, _> = value\n\n .iter()\n\n .map(|(k, v)| (k.clone(), base64::encode_config(v, base64::STANDARD)))\n\n .coll...
Rust
examples/todo/src/tests.rs
fluffy-samurai/Rocket
02b79e28f71ccbd1fce0e369469c92caedb38cd8
use super::task::Task; use parking_lot::Mutex; use rand::{Rng, thread_rng, distributions::Alphanumeric}; use rocket::local::blocking::Client; use rocket::http::{Status, ContentType}; static DB_LOCK: Mutex<()> = parking_lot::const_mutex(()); macro_rules! run_test { (|$client:ident, $conn:ident| $block:expr) => (...
use super::task::Task; use parking_lot::Mutex; use rand::{Rng, thread_rng, distributions::Alphanumeric}; use rocket::local::blocking::Client; use rocket::http::{Status, ContentType}; static DB_LOCK: Mutex<()> = parking_lot::const_mutex(()); macro_rules! run_test { (|$client:ident, $conn:ident| $block:expr) => (...
#[test] fn test_many_insertions() { const ITER: usize = 100; run_test!(|client, conn| { let init_num = Task::all(&conn).unwrap().len(); let mut descs = Vec::new(); for i in 0..ITER { let desc: String = thread_rng().sample_iter(&Alphanumeric).take(12)...
t!("/todo/{}", task.id.unwrap())).dispatch(); assert_eq!(Task::all(&conn).unwrap()[0].completed, true); client.put(format!("/todo/{}", task.id.unwrap())).dispatch(); assert_eq!(Task::all(&conn).unwrap()[0].completed, false); }) }
function_block-function_prefixed
[]
Rust
io/src/lib.rs
sofe-pm-pl/rakrs
b1b1c10a205f2f4688a06e556a47b8aee51b2b0b
use std::io::{Error, ErrorKind, Read, Result, Write}; use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt}; pub use little::Little; pub use triad::Triad; mod little; mod triad; pub trait CanIo: Sized { fn write<W: Write>(&self, w: W) -> Re...
use std::io::{Error, ErrorKind, Read, Result, Write}; use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt}; pub use little::Little; pub use triad::Triad; mod little; mod triad; pub trait CanIo: Sized { fn write<W: Write>(&self, w: W) -> Re...
fn read<R: Read>(mut r: R) -> Result<Self> { let version = u8::read(&mut r)?; let ret = match version { 4 => { let mut bytes = [0u8; 4]; r.read_exact(&mut bytes)?; let port = u16::read(&mut r)?; SocketAddr::V4(SocketAddrV4...
w)?; addr.flowinfo().write(&mut w)?; w.write_all(&addr.ip().octets())?; addr.scope_id().write(&mut w)?; } } Ok(()) }
function_block-function_prefixed
[ { "content": "fn read_cluster<R: Read>(mut r: R) -> Result<Cluster> {\n\n let ty = r.read_u8()?;\n\n match ty {\n\n RECORD_TYPE_SINGLE => {\n\n let id = r.read_u24::<LittleEndian>()?;\n\n Ok(Cluster(id, id))\n\n }\n\n RECORD_TYPE_RANGE => Ok(Cluster(\n\n ...
Rust
src/transport/combined.rs
datrs/hyperswarm-rs
da1c2fdd26b00a99150a03c194d5808a98bb8f5f
use futures_lite::{AsyncRead, AsyncWrite, Stream}; use log::*; use std::collections::HashSet; use std::fmt; use std::fmt::Debug; use std::io; use std::net::{SocketAddr, ToSocketAddrs}; use std::pin::Pin; use std::task::{Context, Poll}; use super::tcp::{TcpStream, TcpTransport}; #[cfg(feature = "transport_utp")] use su...
use futures_lite::{AsyncRead, AsyncWrite, Stream}; use log::*; use std::collections::HashSet; use std::fmt; use std::fmt::Debug; use std::io; use std::net::{SocketAddr, ToSocketAddrs}; use std::pin::Pin; use std::task::{Context, Poll}; use super::tcp::{TcpStream, TcpTransport}; #[cfg(feature = "transport_utp")] use su...
stream = map(stream); let conn = Connection::new(stream, peer_addr, is_initiator, protocol); Some(Ok(conn)) } else { let dir = if is_initiator { "to" } else { "from" }; debug!( "skip double connection {} {}://{}", dir, protocol, pe...
t_addr(local_addr)?; let tcp = TcpTransport::bind(local_addr).await?; let local_addr = tcp.local_addr(); #[cfg(feature = "transport_utp")] let utp = UtpTransport::bind(local_addr).await?; Ok(Self { tcp, #[cfg(feature = "transport_utp")] utp,...
random
[ { "content": "fn into_connection(\n\n poll: Poll<Option<io::Result<UtpSocket>>>,\n\n is_initiator: bool,\n\n) -> Option<io::Result<Connection<UtpStream>>> {\n\n match poll {\n\n Poll::Pending => None,\n\n Poll::Ready(None) => None,\n\n Poll::Ready(Some(Err(e))) => Some(Err(e)),\n\n...
Rust
src/record.rs
joshuawarner32/RustyUsn
b01048a57323445545b413aa9c444b796e9bbb34
use std::io::Read; use chrono::{DateTime, Utc}; use encoding::all::UTF_16LE; use encoding::{DecoderTrap, Encoding}; use winstructs::ntfs::mft_reference::MftReference; use byteorder::{ByteOrder, ReadBytesExt, LittleEndian}; use serde::ser::{SerializeStruct}; use serde::ser; use serde::Serialize; use serde_json::{Value};...
use std::io::Read; use chrono::{DateTime, Utc}; use encoding::all::UTF_16LE; use encoding::{DecoderTrap, Encoding}; use winstructs::ntfs::mft_reference::MftReference; use byteorder::{ByteOrder, ReadBytesExt, LittleEndian}; use serde::ser::{SerializeStruct}; use serde::ser; use serde::Serialize; use serde_json::{Value};...
u128::<LittleEndian>()? ); let usn = buffer.read_u64::<LittleEndian>()?; let timestamp = u64_to_datetime( buffer.read_u64::<LittleEndian>()? ); let reason = flags::Reason::from_bits_truncate(buffer.read_u32::<LittleEndian>()?); let source_info = flags::Source...
None => return Err( UsnError::json_value_error( format!("Record json value's object is none. {:?}", self) ) ) }; let additional_map = match additional_value.as_object() { ...
random
[ { "content": "/// Convert a u64 Windows 100 nanosecond timestamp to a chrono DateTime\n\n///\n\npub fn u64_to_datetime(timestamp_u64: u64) -> DateTime<Utc> {\n\n DateTime::from_utc(\n\n NaiveDate::from_ymd(1601, 1, 1)\n\n .and_hms_nano(0, 0, 0, 0)\n\n + Duration::microseconds(\n\...
Rust
src/mp/user.rs
manbu-00/wx-sdk
ee707e3ee9afda5f2a28b95bda83a6d860d9c069
use serde::{Deserialize, Serialize}; use crate::{ error::{CommonError, CommonResponse}, wechat::WxApiRequestBuilder, SdkResult, }; #[derive(Debug, Serialize, Deserialize)] pub struct UserList { pub total: Option<i32>, pub data: OpenidList, pub count: i32, pub next_openid: String, } #[deri...
use serde::{Deserialize, Serialize}; use crate::{ error::{CommonError, CommonResponse}, wechat::WxApiRequestBuilder, SdkResult, }; #[derive(Debug, Serialize, Deserialize)] pub struct UserList { pub total: Option<i32>, pub data: OpenidList, pub count: i32, pub next_openid: String, } #[deri...
pub async fn info_batchget(&self, query: &[QueryUserInfo]) -> SdkResult<UserInfoList> { let base_url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget"; let sdk = self.0; let res: CommonResponse<UserInfoList> = sdk .wx_post(base_url) .await? .json(...
pub async fn info_updateremark(&self, openid: &str, remark: &str) -> SdkResult<()> { let base_url = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark"; let sdk = self.0; let res: CommonError = sdk .wx_post(base_url) .await? .json(&serde_json::json!({ "...
function_block-full_function
[ { "content": "pub fn reply_to_xml<S: Into<String>>(reply: Reply, from: S, to: S) -> SdkResult<String> {\n\n let mut root = Element::from_name(\"xml\");\n\n\n\n let mut to_user_name = Element::from_name(\"ToUserName\");\n\n to_user_name\n\n .add_cdata(to)\n\n .map_err(exile::error::Error::...
Rust
src/settings/toml/deploy_config.rs
stof/wrangler
7798fb04242fc58e8e58c98087bd40b04a126134
use crate::settings::toml::Route; use crate::terminal::message::{Message, StdOut}; #[derive(Clone, Debug, PartialEq)] pub enum DeployConfig { Zoneless(Zoneless), Zoned(Zoned), } impl DeployConfig { pub fn build( script_name: &str, route_config: &RouteConfig, ) -> Result<DeployConfig, fa...
use crate::settings::toml::Route; use crate::terminal::message::{Message, StdOut}; #[derive(Clone, Debug, PartialEq)] pub enum DeployConfig { Zoneless(Zoneless), Zoned(Zoned), } impl DeployConfig { pub fn build( script_name: &str, route_config: &RouteConfig, ) -> Result<DeployConfig, fa...
outes.push(Route { id: None, script: Some(script_name.to_string()), pattern: route.to_string(), }) } } } if zoned.routes.is_empty() { f...
routes"); } if route_config.has_conflicting_targets() { failure::bail!("specify either `route` or `routes`"); } let mut zoned = Zoned { zone_id: zone_id.to_owned(), routes: Vec::new(), }; if let So...
random
[ { "content": "pub fn set_subdomain(name: &str, user: &GlobalUser, target: &Target) -> Result<(), failure::Error> {\n\n if target.account_id.is_empty() {\n\n failure::bail!(format!(\n\n \"{} You must provide an account_id in your configuration file before creating a subdomain!\",\n\n ...
Rust
src/client.rs
tancehao/ConstDB
350d577d3b225bb1625c3dac491c57e0e8153b09
use crate::conn::Conn; use std::collections::LinkedList; use crate::cmd::{Cmd, NextArg}; use crate::server::{EventsConsumer, Server}; use std::thread::ThreadId; use crate::stats::decr_clients; use crate::link::{Link, LinkType}; use crate::{CstError, now_mil}; use crate::resp::Message; use tokio::net::TcpStream; use cra...
use crate::conn::Conn; use std::collections::LinkedList; use crate::cmd::{Cmd, NextArg}; use crate::server::{EventsConsumer, Server}; use std::thread::ThreadId; use crate::stats::decr_clients; use crate::link::{Link, LinkType}; use crate::{CstError, now_mil}; use crate::resp::Message; use tokio::net::TcpStream; use cra...
Err(CstError::InvalidRequestMsg( format!("The resp message should be an array").into(), )) } } fn check_for_acks(&mut self, server: &mut Server) { match &self.wait { None => return, Some((quorum, timeout, uuid, _)) => { if let ...
eady().await?; if readable { if let Some(0) = self.conn.read_input()? { self.close = true; } } if self.conn.input_to_process() { while let Some(msg) = self.conn.try_next_msg()? { if let Err(e) = self.parse_cmd(msg) { ...
random
[ { "content": "pub fn hdel_command(server: &mut Server, _client: Option<&mut Client>, _nodeid: u64, uuid: u64, args: Vec<Message>) -> Result<Message, CstError> {\n\n let mut args = args.into_iter().skip(1);\n\n let key_name = args.next_bytes()?;\n\n let fields = {\n\n let mut fields = vec![];\n\n...
Rust
src/libsyntax/ext/mtwt.rs
canaltinova/rust
7323ac4add33363a4bdee910b70b09ee82fef7bb
pub use self::SyntaxContext_::*; use ast::{Ident, Mrk, Name, SyntaxContext}; use std::cell::RefCell; use std::collections::HashMap; pub struct SCTable { table: RefCell<Vec<SyntaxContext_>>, marks: RefCell<HashMap<(SyntaxContext,Mrk),SyntaxContext>>, renames: RefCell<HashMap<Name,SyntaxContext>>, } #[d...
pub use self::SyntaxContext_::*; use ast::{Ident, Mrk, Name, SyntaxContext}; use std::cell::RefCell; use std::collections::HashMap; pub struct SCTable { table: RefCell<Vec<SyntaxContext_>>, marks: RefCell<HashMap<(SyntaxContext,Mrk),SyntaxContext>>, renames: RefCell<HashMap<Name,SyntaxContext>>, } #[d...
; } pub fn reset_tables() { with_sctable(|table| { *table.table.borrow_mut() = vec!(EmptyCtxt, IllegalCtxt); *table.marks.borrow_mut() = HashMap::new(); *table.renames.borrow_mut() = HashMap::new(); }); } fn idx_push<T>(vec: &mut Vec<T>, val: T) -> u32 { vec.push(val); (vec.len...
with_sctable(|table| { *table.table.borrow_mut() = Vec::new(); *table.marks.borrow_mut() = HashMap::new(); *table.renames.borrow_mut() = HashMap::new(); })
call_expression
[ { "content": "// same as cci_iter_lib, more-or-less, but not marked inline\n\npub fn iter<F>(v: Vec<usize> , mut f: F) where F: FnMut(usize) {\n\n let mut i = 0;\n\n let n = v.len();\n\n while i < n {\n\n f(v[i]);\n\n i += 1;\n\n }\n\n}\n", "file_path": "src/test/run-pass/auxiliary...
Rust
src/subclass/window.rs
bilelmoussaoui/gtk
7b9a60d0b422b6ab9a0797c8ac0daa02c5757980
use gtk_sys; use glib::translate::*; use glib::subclass::prelude::*; use super::bin::BinImpl; use BinClass; use Widget; use Window; use WindowClass; pub trait WindowImpl: WindowImplExt + BinImpl + 'static { fn set_focus(&self, window: &Window, focus: Option<&Widget>) { self.parent_set_focus(window, focu...
use gtk_sys; use glib::translate::*; use glib::subclass::prelude::*; use super::bin::BinImpl; use BinClass; use Widget; use Window; use WindowClass; pub trait WindowImpl: WindowImplExt + BinImpl + 'static { fn set_focus(&self, window: &Window, focus: Option<&Widget>) { self.parent_set_focus(window, focu...
owed<Window> = from_glib_borrow(ptr); imp.keys_changed(&wrap) } unsafe extern "C" fn window_enable_debugging<T: ObjectSubclass>( ptr: *mut gtk_sys::GtkWindow, toggleptr: glib_sys::gboolean, ) -> glib_sys::gboolean where T: WindowImpl, { let instance = &*(ptr as *mut T::Instance); let imp = ins...
ys_changed<T: ObjectSubclass>(ptr: *mut gtk_sys::GtkWindow) where T: WindowImpl, { let instance = &*(ptr as *mut T::Instance); let imp = instance.get_impl(); let wrap: Borr
function_block-random_span
[]
Rust
src/flow/mod.rs
fisherdarling/net-parser-rs
f96434420d6d1f62972c3e20dbbefb06abc0a477
pub mod device; pub mod errors; pub mod info; pub mod layer2; pub mod layer3; pub mod layer4; use crate::common::Vlan; use crate::layer2::ethernet::Ethernet; use crate::PcapRecord; use device::Device; use errors::Error; use layer2::{FlowExtraction as Layer2Extraction}; use log::*; pub trait FlowExtraction { fn p...
pub mod device; pub mod errors; pub mod info; pub mod layer2; pub mod layer3; pub mod layer4; use crate::common::Vlan; use crate::layer2::ethernet::Ethernet; use crate::PcapRecord; use device::Device; use errors::Error; use layer2::{FlowExtraction as Layer2Extraction}; use log::*; pub trait FlowExtraction { fn p...
} impl std::fmt::Display for Flow { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "Source=[{}] Destination=[{}] Vlan={}", self.source, self.destination, self.vlan ) } } pub fn convert_records<'b>( records: Vec<PcapRecor...
l4: info::layer4::Info ) -> Flow { Flow { source: Device { mac: l2.src_mac, ip: l3.src_ip, port: l4.src_port }, destination: Device { mac: l2.dst_mac, ip: l3.dst_ip, port: l4.d...
function_block-function_prefixed
[ { "content": "pub trait FlowExtraction {\n\n fn extract_flow(&self) -> Result<Flow, Error>;\n\n}\n\n\n\npub mod errors {\n\n use crate::flow::layer2::ethernet;\n\n use thiserror::{Error as ThisError};\n\n\n\n #[derive(Debug, ThisError)]\n\n pub enum Error {\n\n #[error(\"Ethernet Error\")]...
Rust
repl/src/main.rs
hwchen/gluon
b7c88ed2bc283508d1f8100334066a660bbddce8
#![doc(html_root_url = "https://docs.rs/gluon_repl/0.4.1")] extern crate app_dirs; #[macro_use] extern crate clap; extern crate codespan; extern crate codespan_reporting; #[cfg(feature = "env_logger")] extern crate env_logger; extern crate futures; #[macro_use] extern crate log; #[macro_use] extern crate serde_deriv...
#![doc(html_root_url = "https://docs.rs/gluon_repl/0.4.1")] extern crate app_dirs; #[macro_use] extern crate clap; extern crate codespan; extern crate codespan_reporting; #[cfg(feature = "env_logger")] extern crate env_logger; extern crate futures; #[macro_use] extern crate log; #[macro_use] extern crate serde_deriv...
} } macro_rules! define_vmtype { ($name:ident) => { impl ::gluon::vm::api::VmType for $name { type Type = $name; fn make_type(vm: &::gluon::Thread) -> ::base::types::ArcType { let typ = concat!("repl_types.", stringify!($name)); (*vm.global_env()...
Ok(match s { "auto" => Auto, "always" => Always, "always-ansi" => AlwaysAnsi, "never" => Never, _ => return Err("Expected on of auto, always, always-ansi, never"), })
call_expression
[ { "content": "#[allow(dead_code)]\n\npub fn load_script(vm: &Thread, filename: &str, input: &str) -> ::gluon::Result<()> {\n\n Compiler::new()\n\n .implicit_prelude(false)\n\n .load_script_async(vm, filename, input)\n\n .sync_or_error()\n\n}\n\n\n", "file_path": "tests/support/mod.rs...
Rust
src/operation/mod.rs
LaudateCorpus1/mongo-rust-driver
44d79b809e6127a8d9920e806afdd97ae7965272
mod abort_transaction; mod aggregate; mod commit_transaction; mod count; mod count_documents; mod create; mod create_indexes; mod delete; mod distinct; mod drop_collection; mod drop_database; mod drop_indexes; mod find; mod find_and_modify; mod get_more; mod insert; mod list_collections; mod list_databases; mod list_in...
mod abort_transaction; mod aggregate; mod commit_transaction; mod count; mod count_documents; mod create; mod create_indexes; mod delete; mod distinct; mod drop_collection; mod drop_database; mod drop_indexes; mod find; mod find_and_modify; mod get_more; mod insert; mod list_collections; mod list_databases; mod list_in...
} #[derive(Deserialize, Debug)] pub(crate) struct WriteResponseBody<T = EmptyBody> { #[serde(flatten)] body: T, n: u64, #[serde(rename = "writeErrors")] write_errors: Option<Vec<BulkWriteError>>, #[serde(rename = "writeConcernError")] write_concern_error: Option<WriteConcernError>, ...
e(ref wc_error) => Err(Error::new( ErrorKind::Write(WriteFailure::WriteConcernError(wc_error.clone())), self.labels.clone(), )), None => Ok(()), } }
function_block-function_prefixed
[ { "content": "fn serialize_true<S: Serializer>(s: S) -> std::result::Result<S::Ok, S::Error> {\n\n s.serialize_bool(true)\n\n}\n\n\n\n#[serde_with::skip_serializing_none]\n\n#[derive(Debug, TypedBuilder, Serialize)]\n\n#[builder(field_defaults(setter(into)))]\n\n#[serde(rename_all = \"camelCase\")]\n\npub(su...
Rust
src/cli/run.rs
sile/mog
ed7fe9189857035cca8d7f6834e3d6a5bf60f50d
use crate::git; use crate::slack::SlackWebhookOpt; use crate::util::MetadataStoreOpt; use anyhow::Context as _; use std::collections::{BTreeMap, BTreeSet}; use std::io::{Read as _, Write as _}; use std::path::PathBuf; use std::process::Command; use tempfile::NamedTempFile; #[derive(Debug, structopt::StructOpt)] #[stru...
use crate::git; use crate::slack::SlackWebhookOpt; use crate::util::MetadataStoreOpt; use anyhow::Context as _; use std::collections::{BTreeMap, BTreeSet}; use std::io::{Read as _, Write as _}; use std::path::PathBuf; use std::process::Command; use tempfile::NamedTempFile; #[derive(Debug, structopt::StructOpt)] #[stru...
n = r.read(&mut buf)?; self.stderr.write_all(&buf[..n])?; std::io::stderr().write_all(&buf[..n])?; } if let Some(exit_status) = self.child.try_wait()? { return Ok(exit_status); } } } } #[derive(Debug)] pub struct Execution...
slack.build()?; let properties = ExecutionProperties::new(self)?; let execution_type_id = store .put_execution_type("mog_run@0.0") .can_add_fields() .can_omit_fields() .properties(properties.property_types()) .execute() .await?;...
random
[ { "content": "pub const KEY_DATABASE: &str = \"MLMD_DATABASE_URI\"; // TODO: delete(?)\n\npub const KEY_CONTEXT_ID: &str = \"MLMD_CONTEXT_ID\"; // TODO: delete(?)\n", "file_path": "src/env.rs", "rank": 0, "score": 19225.246966389088 }, { "content": "use slack_hook2::{PayloadBuilder, Slack};\...
Rust
amethyst_gltf/src/format/importer.rs
omni-viral/amethyst
ca2edbeebecd6810c5e8b790c914e689c6e055ec
use std; use std::error::Error as StdError; use std::fmt; use std::path::Path; use std::sync::Arc; use assets::{Error as AssetError, Result as AssetResult, Source as AssetSource}; use base64; use gltf; use gltf::Gltf; use gltf::json; use gltf::json::validation; use gltf_utils::Source; #[derive(Debug)] pub enum ImageF...
use std; use std::error::Error as StdError; use std::fmt; use std::path::Path; use std::sync::Arc; use assets::{Error as AssetError, Result as AssetResult, Source as AssetSource}; use base64; use gltf; use gltf::Gltf; use gltf::json; use gltf::json::validation; use gltf_utils::Source; #[derive(Debug)] pub enum ImageF...
} impl From<base64::DecodeError> for Error { fn from(err: base64::DecodeError) -> Error { Error::Base64Decoding(err) } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; write!(f, "{}", self.description()) } } impl St...
fn from(err: gltf::Error) -> Error { match err { gltf::Error::Validation(errs) => Error::Validation(errs), _ => Error::Gltf(err), } }
function_block-full_function
[ { "content": "fn load_skins(gltf: &gltf::Gltf, buffers: &Buffers) -> Result<Vec<GltfSkin>, GltfError> {\n\n gltf.skins().map(|s| load_skin(&s, buffers)).collect()\n\n}\n\n\n", "file_path": "amethyst_gltf/src/format/mod.rs", "rank": 4, "score": 368230.2419511648 }, { "content": "/// Create...
Rust
diesel_derives/src/meta.rs
NarrativeApp/diesel
daf1d331f941f759f8bf50ed807cce0b512c39a5
use proc_macro2::{Ident, Span}; use syn; use syn::fold::Fold; use syn::spanned::Spanned; use resolved_at_shim::*; use util::*; pub struct MetaItem { meta: syn::Meta, } pub(crate) fn path_to_string(path: &syn::Path) -> String { path.segments .iter() .map(|s| s.ident.to_string()) .colle...
use proc_macro2::{Ident, Span}; use syn; use syn::fold::Fold; use syn::spanned::Spanned; use resolved_at_shim::*; use util::*; pub struct MetaItem { meta: syn::Meta, } pub(crate) fn path_to_string(path: &syn::Path) -> String { path.segments .iter() .map(|s| s.ident.to_string()) .colle...
_string(&self.name()), )) .emit(); Ok(x.segments.first().unwrap().ident.clone()) } _ => Ok(syn::Ident::new( &self.str_value()?, self.value_span().resolved_at(Span::call_site()), )), } ...
}), } } pub fn nested_item(&self, name: &str) -> Result<Option<Self>, Diagnostic> { self.nested() .map(|mut i| i.find(|n| n.name().is_ident(name))) } pub fn required_nested_item(&self, name: &str) -> Result<Self, Diagnostic> { self.nested_item(name)?.ok_or_...
random
[ { "content": "pub fn str_value_of_meta_item(item: &Meta, name: &str) -> String {\n\n match *item {\n\n Meta::NameValue(MetaNameValue {\n\n lit: Lit::Str(ref value),\n\n ..\n\n }) => value.value(),\n\n _ => panic!(\n\n r#\"`{}` must be in the form `#[{}=\"...
Rust
docx-core/tests/reader.rs
lkadalski/docx-rs
b3f5e79ced4f99692a28eb4a8cedfbd20c2123e4
use insta::assert_json_snapshot; use docx_rs::*; use std::fs::*; use std::io::{Read, Write}; #[test] pub fn read_hello() { let mut file = File::open("../fixtures/hello_world/hello_world.docx").unwrap(); let mut buf = vec![]; file.read_to_end(&mut buf).unwrap(); let json = read_docx(&buf).unwrap().json...
use insta::assert_json_snapshot; use docx_rs::*; use std::fs::*; use std::io::{Read, Write}; #[test] pub fn read_hello() { let mut file = File::open("../fixtures/hello_world/hello_world.docx").unwrap(); let mut buf = vec![]; file.read_to_end(&mut buf).unwrap(); let json = read_docx(&buf).unwrap().json...
.unwrap(); let mut buf = vec![]; file.read_to_end(&mut buf).unwrap(); let json = read_docx(&buf).unwrap().json(); assert_json_snapshot!("read_tab_and_break", &json); let path = std::path::Path::new("./tests/output/tab_and_break.json"); let mut file = std::fs::File::create(&path).unwrap(); ...
} #[test] pub fn read_history() { let mut file = File::open("../fixtures/history_libre_office/history.docx").unwrap(); let mut buf = vec![]; file.read_to_end(&mut buf).unwrap(); let json = read_docx(&buf).unwrap().json(); assert_json_snapshot!("read_history", &json); let path = std::path::Pa...
random
[ { "content": "#[test]\n\npub fn hello() -> Result<(), DocxError> {\n\n let path = std::path::Path::new(\"./tests/output/hello.docx\");\n\n let file = std::fs::File::create(&path).unwrap();\n\n Docx::new()\n\n .add_paragraph(Paragraph::new().add_run(Run::new().add_text(\"Hello\")))\n\n .bu...
Rust
zvariant/src/maybe.rs
jhartzell42/zbus
6e8114762e3340c440dc8e303562f528da54bab8
use serde::ser::{Serialize, Serializer}; use static_assertions::assert_impl_all; use std::convert::TryFrom; use crate::{Error, Signature, Type, Value}; #[derive(Debug, Clone, PartialEq)] pub struct Maybe<'a> { value: Box<Option<Value<'a>>>, value_signature: Signature<'a>, signature: Signature<'a>, } asse...
use serde::ser::{Serialize, Serializer}; use static_assertions::assert_impl_all; use std::convert::TryFrom; use crate::{Error, Si
e, value: Box::new(None), } } pub(crate) fn nothing_full_signature<'s: 'a>(signature: Signature<'s>) -> Self { Self { value_signature: signature.slice(1..), signature, value: Box::new(None), } } pub fn get<T>(self) -> core::r...
gnature, Type, Value}; #[derive(Debug, Clone, PartialEq)] pub struct Maybe<'a> { value: Box<Option<Value<'a>>>, value_signature: Signature<'a>, signature: Signature<'a>, } assert_impl_all!(Maybe<'_>: Send, Sync, Unpin); impl<'a> Maybe<'a> { pub fn inner(&self) -> &Option<Value<'a>> { &se...
random
[ { "content": "use serde::ser::{Serialize, SerializeStruct, Serializer};\n\nuse static_assertions::assert_impl_all;\n\n\n\nuse crate::{Signature, Type, Value};\n\n\n\n/// A wrapper to serialize `T: Type + Serialize` as a value.\n\n///\n\n/// When the type of a value is well-known, you may avoid the cost and comp...
Rust
tests/misc_tests/macro_utils_tests.rs
rodrimati1992/core_extensions
9797a7e1d4a50ceacd11ae75ac590ffd42accfbf
use krate::{count_tts, gen_ident_range, rewrap_macro_parameters}; mod tokens_method_tests; #[test] fn different_delimiters() { macro_rules! assertion_1 { ( (hello world) [foo bar] {aaa bbb ccc} (1 + 1) (fn foo(){}) (Vec<u32>) ...
use krate::{count_tts, gen_ident_range, rewrap_macro_parameters}; mod tokens_method_tests; #[test] fn different_delimiters() { macro_rules! assertion_1 { ( (hello world) [foo bar] {aaa bbb ccc} (1 + 1) (fn foo(){}) (Vec<u32>) ...
e_name_of(count_tts!(())).contains("usize")); assert!(type_name_of(count_tts!((_))).contains("usize")); } #[test] fn gen_idents_test() {} mod gen_idents_test { use super::*; macro_rules! assert_idents { ($expected:tt $found:tt) => { macro_rules! assertion { ($expected...
_tts!(($($t_item)*))]; const _: [(); $expected_tt] = [(); count_tts!(($($t_tt)*))]; }; } count_tests!{ 3 (1 + 1, f(10) - 1, a * b / c), 4 (Vec<T>, HashMap<i32, i32>, u64, dyn A + B), 5 (::a::b, c, crate::d::<e>::f, g::h, ::i), 6 ( const _: () = (...
random
[ { "content": "#[allow(dead_code)]\n\npub fn remove_whitespace(s: &str) -> String {\n\n s.chars().filter(|c| !c.is_whitespace()).collect()\n\n}\n\n\n\n\n", "file_path": "tests/misc_tests/utils_tests.rs", "rank": 0, "score": 226028.53045513143 }, { "content": "#[derive(Debug, Clone, Partial...
Rust
chain/ethereum/src/runtime/runtime_adapter.rs
georg-getz/graph-node
45d2e5f4a8b63ccb59f2429fc89e6c07bbc905de
use std::{sync::Arc, time::Instant}; use crate::data_source::MappingABI; use crate::{ capabilities::NodeCapabilities, network::EthereumNetworkAdapters, Chain, DataSource, EthereumAdapter, EthereumAdapterTrait, EthereumContractCall, EthereumContractCallError, }; use anyhow::{Context, Error}; use blockchain::Hos...
use std::{sync::Arc, time::Instant}; use crate::data_source::MappingABI; use crate::{ capabilities::NodeCapabilities, network::EthereumNetworkAdapters, Chain, DataSource, EthereumAdapter, EthereumAdapterTrait, EthereumContractCall, EthereumContractCallError, }; use anyhow::{Context, Error}; use blockchain::Hos...
, Err(e) => Err(HostExportError::Unknown(anyhow::anyhow!( "Failed to call function \"{}\" of contract \"{}\": {}", unresolved_call.function_name, unresolved_call.contract_name, e ))), }; trace!(logger, "Contract call f...
Err(HostExportError::PossibleReorg(anyhow::anyhow!( "Ethereum node did not respond when calling function \"{}\" of contract \"{}\"", unresolved_call.function_name, unresolved_call.contract_name, )))
call_expression
[ { "content": "/// Generic helper function for retrying async operations with built-in logging.\n\n///\n\n/// To use this helper, do the following:\n\n///\n\n/// 1. Call this function with an operation name (used for logging) and a `Logger`.\n\n/// 2. Optional: Chain a call to `.when(...)` to set a custom retry ...
Rust
src/azure/core/errors.rs
akshayknarayan/AzureSDKForRust
b023f25e7d1810e5fcb7a34084cd71769459bd78
use azure::core::enumerations::ParsingError; use azure::core::range::ParseError; use chrono; use futures::future::*; use futures::Future; use futures::Stream; use hyper; use hyper::StatusCode; use native_tls; use serde_json; use std; use std::io::Error as IOError; use std::num; use std::str; use std::string; use url::P...
use azure::core::enumerations::ParsingError; use azure::core::range::ParseError; use chrono; use futures::future::*; use futures::Future; use futures::Stream; use hyper; use hyper::StatusCode; use native_tls; use serde_json; use std; use std::io::Error as IOError; use std::num; use std::str; use std::string; use url::P...
} impl std::error::Error for UnexpectedHTTPResult { fn description(&self) -> &str { "Unexpected HTTP result" } fn cause(&self) -> Option<&std::error::Error> { None } } quick_error! { #[derive(Debug)] pub enum AzureError { JSONError(err: serde_json::Error) { ...
e!( f, "Unexpected HTTP result (expected: {}, received: {})", self.expected, self.received ) }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn from_azure_time(s: &str) -> Result<chrono::DateTime<chrono::Utc>, chrono::ParseError> {\n\n let dt = chrono::DateTime::parse_from_rfc2822(s)?;\n\n let dt_utc: chrono::DateTime<chrono::Utc> = dt.with_timezone(&chrono::Utc);\n\n Ok(dt_utc)\n\n}\n\n\n", "file_path": "...
Rust
src/pwm/ossupd.rs
Gui-Yom/atsam3x8e
3909355848e8a9bec79ace20360ae7e0403c1b44
#[doc = "Writer for register OSSUPD"] pub type W = crate::W<u32, super::OSSUPD>; #[doc = "Write proxy for field `OSSUPH0`"] pub struct OSSUPH0_W<'a> { w: &'a mut W } impl<'a> OSSUPH0_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r...
#[doc = "Writer for register OSSUPD"] pub type W = crate::W<u32, super::OSSUPD>; #[doc = "Write proxy for field `OSSUPH0`"] pub struct OSSUPH0_W<'a> { w: &'a mut W } impl<'a> OSSUPH0_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r...
rites raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Write proxy for field `OSSUPH7`"] pub struct OSSUPH7_W<'a> { w: &'a mut W } impl<'a> OSSUPH7_W<'a> {...
-> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | ...
random
[]
Rust
src/auto/paint_volume.rs
angular-rust/clutter-rs
122b376d6c6132d865aefc6a9096f0ab4965180b
use crate::{Actor, ActorBox, Vertex}; use glib::{object::IsA, translate::*}; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PaintVolume(Boxed<ffi::ClutterPaintVolume>); match fn { copy => |ptr| ffi::clutter_paint_volume_copy(mut_override(ptr)), free => |p...
use crate::{Actor, ActorBox, Vertex}; use glib::{object::IsA, translate::*}; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PaintVolume(Boxed<ffi::ClutterPaintVolume>); match fn { copy => |ptr| ffi::clutter_paint_volume_copy(mut_override(ptr)), free => |p...
ut().0, width); } } pub fn union(&mut self, another_pv: &PaintVolume) { unsafe { ffi::clutter_paint_volume_union(self.to_glib_none_mut().0, another_pv.to_glib_none().0); } } pub fn union_box(&mut self, box_...
self.to_glib_none_mut().0, origin.to_glib_none().0, ); } } pub fn set_width(&mut self, width: f32) { unsafe { ffi::clutter_paint_volume_set_width(self.to_glib_none_m
random
[ { "content": "#[inline]\n\npub fn is_initialized() -> bool {\n\n skip_assert_initialized!();\n\n INITIALIZED.load(Ordering::Acquire)\n\n}\n\n\n\n/// Returns `true` if GDK has been initialized and this is the main thread.\n", "file_path": "src/rt.rs", "rank": 0, "score": 148287.67498864193 },...
Rust
src/client.rs
ralpha/tower-lsp
768af39d83599130eeb247d70bf56f2ab4514a11
use std::fmt::{self, Debug, Display, Formatter}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use futures::channel::mpsc::Sender; use futures::sink::SinkExt; use log::{error, trace}; use lsp_types::notification::{Notification, *}; use lsp_types::request::{Request, *}; use lsp_types::*; use serde...
use std::fmt::{self, Debug, Display, Formatter}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use futures::channel::mpsc::Sender; use futures::sink::SinkExt; use log::{error, trace}; use lsp_types::notification::{Notification, *}; use lsp_types::request::{Request, *}; use lsp_types::*; use serde...
} async fn send_request<R>(&self, params: R::Params) -> Result<R::Result> where R: Request, { let id = self.inner.request_id.fetch_add(1, Ordering::Relaxed); let message = Outgoing::Request(ClientRequest::request::<R>(id, params)); let response_waiter = self.inner.pend...
if let State::Initialized | State::ShutDown = self.inner.state.get() { self.send_notification::<N>(params).await; } else { let msg = ClientRequest::notification::<N>(params); trace!("server not initialized, supressing message: {}", msg); }
if_condition
[ { "content": "fn display_sources(error: &dyn Error) -> String {\n\n if let Some(source) = error.source() {\n\n format!(\"{}: {}\", error, display_sources(source))\n\n } else {\n\n error.to_string()\n\n }\n\n}\n\n\n\n#[doc(hidden)]\n\n#[derive(Debug)]\n\npub struct Nothing(Empty<Outgoing>)...
Rust
src/shard_ctrler/server.rs
huang-jl/MadRaft
bed9f368e8d54bf974d501e99520ffc4fd9f39ef
use std::collections::HashMap; use super::{msg::*, N_SHARDS}; use crate::kvraft::{ msg::ClerkReq, server::{RecentInfo, Server, State}, }; use serde::{Deserialize, Serialize}; pub type ShardCtrler = Server<ShardInfo>; #[derive(Debug, Serialize, Deserialize)] pub struct ShardInfo { configs: Vec<Config...
use std::collections::HashMap; use super::{msg::*, N_SHARDS}; use crate::kvraft::{ msg::ClerkReq, server::{RecentInfo, Server, State}, }; use serde::{Deserialize, Serialize}; pub type ShardCtrler = Server<ShardInfo>; #[derive(Debug, Serialize, Deserialize)] pub struct ShardInfo { configs: Vec<Config...
}
fn rebalance(&mut self) { let group_num = self.groups.len(); if group_num == 0 { return; } let avg_num = N_SHARDS / group_num; let mut group_shard: HashMap<u64, Vec<usize>> = self .groups .keys() .map(|&gid| { ( ...
function_block-full_function
[ { "content": "pub trait State: net::Message + Default {\n\n type Command: net::Message + Clone;\n\n type Output: net::Message + Clone;\n\n /// apply normal operation (non-register) to state machine\n\n fn apply(&mut self, cmd: ClerkReq<Self::Command>) -> Self::Output;\n\n fn name() -> &'static st...
Rust
src/rust/runtime/src/tests.rs
Feni/informal
c7d5529ad1eb7c44c5e4663cda550001969ca44c
#[cfg(test)] mod tests { use crate::format::repr; use crate::interpreter::interpret_expr; use crate::parser::apply_operator_precedence; use crate::lexer::lex; use avs::constants::APP_SYMBOL_START; use super::*; use avs::constants::{SYMBOL_TRUE, SYMBOL_FALSE}; use avs::environment::Environment; ...
#[cfg(test)] mod tests { use crate::format::repr; use crate::interpreter::interpret_expr; use crate::parser::apply_operator_precedence; use crate::lexer::lex; use avs::constants::APP_SYMBOL_START; use super::*; use avs::constants::{SYMBOL_TRUE, SYMBOL_FALSE}; use avs::environment::Environment; ...
#[test] fn test_builtin_fn_argeval() { let program = EvalRequest { body: vec![ CellRequest {id: 1, name: Some(String::from("one")), input: String::from("min(2 * 2, 2 + 1)")}, CellRequest {id: 2, name: Some(String::from("two")), input: String::from("min(2, ma...
m = EvalRequest { body: vec![ CellRequest {id: 1, name: Some(String::from("one")), input: String::from("min(4, 3)")}, CellRequest {id: 2, name: Some(String::from("two")), input: String::from("min(3, 4)")} ], input: None }; let i_result ...
function_block-function_prefixed
[ { "content": "pub fn lex(context: &mut Environment, expr: &str) -> Result<Vec<Atom>> {\n\n let mut it = expr.chars().peekable();\n\n // Split into lexemes based on some known operators\n\n let mut tokens: Vec<Atom> = vec![];\n\n\n\n while let Some(&ch) = it.peek() {\n\n // The match should ha...
Rust
examples/laser/laser_frame_stream.rs
rylev/nannou
3f802939dd286021497c9ff4ebc94d213d1dd29d
use nannou::prelude::*; fn main() { nannou::app(model).run(); } struct Model { _laser_api: lasy::Lasy, laser_stream: lasy::FrameStream<Laser>, } struct Laser { test_pattern: TestPattern, } pub enum TestPattern { Rectangle, Triangle, Crosshair, ThreeVerticalLines...
use nannou::prelude::*; fn main() { nannou::app(model).run(); } struct Model { _laser_api: lasy::Lasy, laser_stream: lasy::FrameStream<Laser>, } struct Laser { test_pattern: TestPattern, } pub enum TestPattern { Rectangle, Triangle, Crosshair, ThreeVerticalLines...
fn key_pressed(_app: &App, model: &mut Model, key: Key) { let new_pattern = match key { Key::Key1 => TestPattern::Rectangle, Key::Key2 => TestPattern::Triangle, Key::Key3 => TestPattern::Crosshair, Key::Key4 => TestPattern::ThreeVerticalLines, Key::Key5 => TestPattern:...
let yb = [0.0, 1.0]; let x = [lit_p(xa), lit_p(xb)]; let y = [lit_p(ya), lit_p(yb)]; frame.add_lines(&x); frame.add_lines(&y); } TestPattern::ThreeVerticalLines => { let la = [-1.0, -0.5]; let lb = [-1.0, 0.5]; let ma =...
function_block-function_prefix_line
[ { "content": "fn view(app: &App, model: &Model, frame: Frame) -> Frame {\n\n model.ui.draw_to_frame_if_changed(app, &frame).unwrap();\n\n frame\n\n}\n", "file_path": "examples/laser/laser_frame_stream_gui.rs", "rank": 0, "score": 428177.86964390543 }, { "content": "fn update(_app: &App...
Rust
components/butterfly/tests/rumor/election.rs
Themodestduckling/habitat
9d936ea6692ca7eb3d6bae78fb6b4ca0ab893194
use habitat_butterfly::{member::Health, rumor::election::ElectionStatus}; use crate::btest; #[test] fn three_members_run_election() { let mut net = btest::SwimNet::new(3); net.mesh(); net.add_service(0, "core/witcher/1.2.3/20161208121212"); net.add_service(1, "core/witcher/1.2....
use habitat_butterfly::{member::Health, rumor::election::ElectionStatus}; use crate::btest; #[test] fn three_members_run_election() { let mut net = btest::SwimNet::new(3); net.mesh(); net.add_service(0, "core/witcher/1.2.3/20161208121212"); net.add_service(1, "core/witcher/1.2....
lections(); net[4].restart_elections(); assert_wait_for_election_status!(net, 0, "witcher.prod", ElectionStatus::NoQuorum); assert_wait_for_election_status!(net, 1, "witcher.prod", ElectionStatus::NoQuorum); assert_wait_for_election_status!(net, 2, "witcher.prod", ElectionStatus::Finished); assert_w...
function_block-function_prefixed
[ { "content": "/// Populate a SWIM message with rumors.\n\npub fn populate_membership_rumors(server: &Server, target: &Member, swim: &mut Swim) {\n\n // If this isn't the first time we are communicating with this target, we want to include this\n\n // targets current status. This ensures that members alway...
Rust
kernel/login/tests/health_check.rs
Fruity-Gang/appelsin
d3fb432a4b2c9e057a8708457a8b8fbaea61486a
use sqlx::{Connection, Executor, PgPool, PgConnection}; use uuid::Uuid; use login::configuration::{get_configuration, DatabaseSettings}; use std::net::TcpListener; pub struct TestApp { pub address: String, pub db_pool: PgPool } async fn spawn_app() -> TestApp { let listener = TcpListener::bind("127.0.0.1...
use sqlx::{Connection, Executor, PgPool, PgConnection}; use uuid::Uuid; use login::configuration::{get_configuration, DatabaseSettings}; use std::net::TcpListener; pub struct TestApp { pub address: String, pub db_pool: PgPool } async fn spawn_app() -> TestApp { let listener = TcpListener::bind("127.0.0.1...
ort); let mut configuration = get_configuration().expect("Failed to read configuration."); configuration.database.database_name = Uuid::new_v4().to_string(); let connection_pool = configure_database(&configuration.database).await; let server = login::startup::run(listener, connection_pool.clone()) ...
xpect("Failed to bind random port"); let port = listener.local_addr().unwrap().port(); let address = format!("http://127.0.0.1:{}", p
function_block-random_span
[ { "content": "pub fn run(listener: TcpListener, db_pool: PgPool) -> Result<Server, std::io::Error> {\n\n let db_pool = web::Data::new(db_pool);\n\n\n\n let server = HttpServer::new(move || {\n\n App::new()\n\n .route(\"/health_check\", web::get().to(health_check))\n\n .route(\...
Rust
src/block_allocator.rs
playXE/libimmixcons
8ad4e34d80901df03e349a19fa6ee431b01fab92
use super::block::ImmixBlock; use super::constants::*; #[cfg(feature = "threaded")] use crate::util::locks::mutex::ReentrantMutex; use crate::util::Address; #[cfg(windows)] mod _win { use super::*; use core::{ptr::null_mut, usize}; use winapi::um::{ memoryapi::{VirtualAlloc, VirtualFree}, w...
use super::block::ImmixBlock; use super::constants::*; #[cfg(feature = "threaded")] use crate::util::locks::mutex::ReentrantMutex; use crate::util::Address; #[cfg(windows)] mod _win { use super::*; use core::{ptr::null_mut, usize}; use winapi::um::{ memoryapi::{VirtualAlloc, VirtualFree}, w...
(&self.data;AtomicUsize); let mut old = data.load(Ordering::Relaxed); let mut new; loop { new = old + BLOCK_SIZE; if new > self.data_bound as usize { return None; } let res = data.compare_exchange_wea...
ImmixBlock::new(x as *mut u8); x }) .or_else(|| self.build_block()); #[cfg(feature = "threaded")] { self.lock.unlock(); } block } pub fn is_in_space(&self, object: Address) -> bool { self.mmap.start() < object.to_...
random
[ { "content": "/// Check if `mem` is aligned for precise allocation\n\npub fn is_aligned_for_precise_allocation(mem: *mut u8) -> bool {\n\n let allocable_ptr = mem as usize;\n\n (allocable_ptr & (PreciseAllocation::ALIGNMENT - 1)) == 0\n\n}\n\n/// This space contains objects which are larger than the size ...
Rust
crates/core/src/sql_arg.rs
roy-ganz/toql
09104e16e921173d03f4a10410d311c939df1581
pub mod error; pub mod from; pub mod from_row; pub mod try_into; #[derive(Clone, Debug, PartialEq)] pub enum SqlArg { U64(u64), I64(i64), F64(f64), Str(String), Bool(bool), Null, } impl SqlArg { pub fn to_sql_string(&self) -> String { match self { SqlArg::U64(t) ...
pub mod error; pub mod from; pub mod from_row; pub mod try_into; #[derive(Clone, Debug, PartialEq)] pub enum SqlArg { U64(u64), I64(i64), F64(f64), Str(String), Bool(bool
Arg::from(false)]; assert_eq!(valid_key(&a), true); } }
), Null, } impl SqlArg { pub fn to_sql_string(&self) -> String { match self { SqlArg::U64(t) => t.to_string(), SqlArg::I64(t) => t.to_string(), SqlArg::F64(t) => t.to_string(), SqlArg::Str(t) => format!("'{}'", t.replace("'", "''")), SqlA...
random
[ { "content": "#[proc_macro_derive(ToqlEnum)]\n\npub fn toql_enum_derive(input: TokenStream) -> TokenStream {\n\n let _ = env_logger::try_init(); // Avoid multiple init\n\n let ast = parse_macro_input!(input as DeriveInput);\n\n let name = &ast.ident;\n\n let name_string = name.to_string();\n\n le...
Rust
pic32-hal/src/dma.rs
kiffie/mcu-rs
34150e09b839496e26e6ee997043966137ba7241
use crate::int::InterruptSource; use crate::pac::{DMAC, DMAC0, DMAC1, DMAC2, DMAC3}; use enumflags2::BitFlags; use mips_mcu::PhysicalAddress; #[derive(BitFlags, Copy, Clone, Debug, PartialEq)] #[repr(u8)] pub enum DmaIrq { CHSD = 0x80, CHSH = 0x40, CHDD = 0x20, CHDH = 0x10, ...
use crate::int::InterruptSource; use crate::pac::{DMAC, DMAC0, DMAC1, DMAC2, DMAC3}; use enumflags2::BitFlags; use mips_mcu::PhysicalAddress; #[derive(BitFlags, Copy, Clone, Debug, PartialEq)] #[repr(u8)] pub enum DmaIrq { CHSD = 0x80, CHSH = 0x40, CHDD = 0x20, CHDH = 0x10, ...
self.ch.cont.read().chen().bit() } fn disable(&self) { self.ch.contclr.write(|w| w.chen().bit(true)); while self.ch.cont.read().chbusy().bit() {} } fn force(&self) { self.ch.econset.write(|w| w.cforce().bit(true)); ...
.econ .modify(|_, w| unsafe { w.chsirq().bits(e as u8).sirqen().bit(true) }); } None => { self.ch.econclr.write(|w| w.sirqen().bit(true)); } } } f...
random
[ { "content": "#[inline]\n\npub fn read_count() -> u32 {\n\n extern \"C\" {\n\n fn mips_read_cp0_count() -> u32;\n\n }\n\n unsafe { mips_read_cp0_count() }\n\n}\n\n\n\n/// Write count register (CP0 register 9, select 0)\n\n#[inline]\n\npub unsafe fn write_count(count: u32) {\n\n extern \"C\" {...
Rust
src/sys/tools/cs/src/v2.rs
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
use { crate::v1::V1Realm, files_async::readdir_with_timeout, fuchsia_zircon as zx, futures::future::{BoxFuture, FutureExt}, io_util::{directory, file}, }; static SPACER: &str = " "; static IO_TIMEOUT: zx::Duration = zx::Duration::from_seconds(2); async fn get_file_names(path: &str) -> Result<Ve...
use { crate::v1::V1Realm, files_async::readdir_with_timeout, fuchsia_zircon as zx, futures::future::{BoxFuture, FutureExt}, io_util::{directory, file}, }; static SPACER: &str =
File::create(root.join("svc").join("fuchsia.bar")).unwrap(); let contents = get_exposed_capabilities(root.to_str().unwrap()).await; assert_eq!( contents, vec!["fuchsia.foo".to_string(), "hub".to_string(), "fuchsia.bar".to_string()] ); } }
" "; static IO_TIMEOUT: zx::Duration = zx::Duration::from_seconds(2); async fn get_file_names(path: &str) -> Result<Vec<String>, files_async::Error> { let dir = directory::open_in_namespace(path, io_util::OPEN_RIGHT_READABLE).unwrap(); let result = readdir_with_timeout(&dir, IO_TIMEOUT).await; result.map(...
random
[]
Rust
src/render/src/pso/target.rs
AnthIste/gfx-rs
d843f329fb618589e7e686cd3f9f3f14068baeff
use std::marker::PhantomData; use core::{ColorSlot, Resources}; use core::{format, handle, pso, state, target}; use core::memory::Typed; use core::shade::OutputVar; use super::{DataLink, DataBind, RawDataSet, AccessInfo}; pub struct RenderTarget<T>(Option<ColorSlot>, PhantomData<T>); pub struct BlendTarget<T>(RawRe...
use std::marker::PhantomData; use core::{ColorSlot, Resources}; use core::{format, handle, pso, state, target}; use core::memory::Typed; use core::shade::OutputVar; use super::{DataLink, DataBind, RawDataSet, AccessInfo}; pub struct RenderTarget<T>(Option<ColorSlot>, PhantomData<T>); pub struct BlendTarget<T>(RawRe...
} impl<'a, T: format::BlendFormat> DataLink<'a> for BlendTarget<T> { type Init = (&'a str, state::ColorMask, state::Blend); fn new() -> Self { BlendTarget(RawRenderTarget(None), PhantomData) } fn is_active(&self) -> bool { self.0.is_active() } fn link_output(&mut self, out: &Ou...
fn bind_to(&self, out: &mut RawDataSet<R>, data: &Self::Data, man: &mut handle::Manager<R>, _: &mut AccessInfo<R>) { if let Some(slot) = self.0 { out.pixel_targets.add_color(slot, man.ref_rtv(data.raw()), data.raw().get_dimensions()); ...
function_block-full_function
[ { "content": "pub fn make_blend(device: *mut ID3D11Device, targets: &[Option<pso::ColorTargetDesc>])\n\n -> *const ID3D11BlendState {\n\n let dummy_target = D3D11_RENDER_TARGET_BLEND_DESC {\n\n BlendEnable: FALSE,\n\n SrcBlend: D3D11_BLEND_ZERO,\n\n DestBlend: D3D11_BLEN...
Rust
src/query/combine.rs
Ka1wa/sea-orm
10b101b14207cbce497ea2076a5cc43ea7949af5
use crate::{ EntityTrait, IdenStatic, IntoSimpleExpr, Iterable, QueryTrait, Select, SelectTwo, SelectTwoMany, }; use core::marker::PhantomData; pub use sea_query::JoinType; use sea_query::{Alias, ColumnRef, Iden, Order, SeaRc, SelectExpr, SelectStatement, SimpleExpr}; macro_rules! select_def { ( $ident: ident,...
use crate::{ EntityTrait, IdenStatic, IntoSimpleExpr, Iterable, QueryTrait, Select, SelectTwo, SelectTwoMany, }; use core::marker::PhantomData; pub use sea_query::JoinType; use sea_query::{Alias, ColumnRef, Iden, Order, SeaRc, SelectExpr, SelectStatement, SimpleExpr}; macro_rules! select_def { ( $ident: ident,...
} }
"SELECT `cake`.`id` AS `A_id`, `cake`.`name` AS `A_name`,", "`fruit`.`id` AS `B_id`, `fruit`.`name` AS `B_name`, `fruit`.`cake_id` AS `B_cake_id`", "FROM `cake` LEFT JOIN `fruit` ON `cake`.`id` = `fruit`.`cake_id`", ].join(" ") ); } #[test] fn...
random
[ { "content": "pub fn impl_col_from_str(ident: &Ident, data: &Data) -> syn::Result<TokenStream> {\n\n let data_enum = match data {\n\n Data::Enum(data_enum) => data_enum,\n\n _ => {\n\n return Ok(quote_spanned! {\n\n ident.span() => compile_error!(\"you can only derive ...
Rust
pgx-utils/src/sql_entity_graph/pg_extern/attribute.rs
timescale/pgx
ed9f061db4c6d0a2e2775bea58523f92d9ff5a07
use crate::sql_entity_graph::{PositioningRef, ToSqlConfig}; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens, TokenStreamExt}; use syn::{ parse::{Parse, ParseStream}, punctuated::Punctuated, Token, }; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum Attribute { Imm...
use crate::sql_entity_graph::{PositioningRef, ToSqlConfig}; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens, TokenStreamExt}; use syn::{ parse::{Parse, ParseStream}, punctuated::Punctuated, Token, }; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum Attribute { Imm...
} _ => return Err(syn::Error::new(Span::call_site(), "Invalid option")), }; Ok(found) } }
match input.parse::<ArgValue>()? { ArgValue::Path(p) => Self::Sql(ToSqlConfig::from(p)), ArgValue::Lit(Lit::Bool(b)) => Self::Sql(ToSqlConfig::from(b.value)), ArgValue::Lit(Lit::Str(s)) => Self::Sql(ToSqlConfig::from(s)), ArgValue::Lit(othe...
if_condition
[ { "content": "pub fn eq(type_name: &Ident) -> proc_macro2::TokenStream {\n\n let pg_name = Ident::new(\n\n &format!(\"{}_eq\", type_name).to_lowercase(),\n\n type_name.span(),\n\n );\n\n quote! {\n\n #[allow(non_snake_case)]\n\n #[pg_operator(immutable, parallel_safe)]\n\n ...
Rust
examples/nfct_test.rs
MirnaMuhammad98/OpenSK
944c7ea03182f0de2f4d0a61b11c5443f2540c69
#![no_std] #![allow(unused_imports)] extern crate alloc; extern crate lang_items; extern crate libtock_drivers; use core::fmt::Write; use libtock_core::result::CommandError; use libtock_drivers::console::Console; #[cfg(feature = "with_nfc")] use libtock_drivers::nfc::NfcTag; #[cfg(feature = "with_nfc")] use libtock_d...
#![no_std] #![allow(unused_imports)] extern crate alloc; extern crate lang_items; extern crate libtock_drivers; use core::fmt::Write; use libtock_core::result::CommandError; use libtock_drivers::console::Console; #[cfg(feature = "with_nfc")] use libtock_drivers::nfc::NfcTag; #[cfg(feature = "with_nfc")] use libtock_d...
{ break; } } writeln!(console, "****************************************").unwrap(); }
} } 0x52 | 0x50 /* WUPA | Halt */ => { if NfcTag::disable_emulation() { writeln!(console, " -- TAG DISABLED").unwrap(); } state = State::Disa...
random
[ { "content": "/// Sets a little-endian value in a sequence of bits.\n\n///\n\n/// The sequence of bits is little-endian (both for bytes and bits) and defined by the bits that\n\n/// are in `data` but not in `gap`. The range of bits where the value is stored in defined by\n\n/// `range`. The bits set to 1 in `va...
Rust
rust/leetcode-maximal-rectangle/src/maximal_rectangle.rs
mayaming/cheat-sheet
b3cf9301c4bade0ac292cbadae423dc2a7f02a46
/* * @lc app=leetcode id=85 lang=rust * * [85] Maximal Rectangle */ /* 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 0 1 1 1 1 0 0 1 0 0 1 1 1 1 0 0 0 1 0 1 1 1 1 0 0 0 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 Poi...
/* * @lc app=leetcode id=85 lang=rust * * [85] Maximal Rectangle */ /* 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 1 1 0 0 1 0 0 1 1 1 1 0 0 1 0 0 1 1 1 1 0 0 0 1 0 1 1 1 1 0 0 0 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 Poi...
fn up_point<'a>(point: &'a Point, pts_matrix: &'a Vec<Vec<Point>>) -> Option<&'a Point> { if point.r() == 0 { None } else { Some(&pts_matrix[point.r()-1][point.c()]) } } impl Solution { fn determine_left_reach(point: &Point, pts_matrix: &Vec<Vec<Point>>) -> i16 { if p...
fn left_point<'a>(point: &'a Point, pts_matrix: &'a Vec<Vec<Point>>) -> Option<&'a Point> { if point.c() == 0 { None } else { Some(&pts_matrix[point.r()][point.c()-1]) } }
function_block-full_function
[]
Rust
src/system/logger.rs
dremon/riker
b2a06a3869b0ad766dabc1a18398dc45aa08781a
use log; use log::{info, Level}; use config::Config; use runtime_fmt::{rt_println, rt_format_args}; use crate::{ actor::{ ActorRef, Tell, BoxActorProd, Props, Actor, Context, BasicActorRef,ChannelMsg, All, DeadLetter, Subscribe } }; pub type LogActor = Box<dyn Actor<Msg=LogEntry> +...
use log; use log::{info, Level}; use config::Config; use runtime_fmt::{rt_println, rt_format_args}; use crate::{ actor::{ ActorRef, Tell, BoxActorProd, Props, Actor, Context, BasicActorRef,ChannelMsg, All, DeadLetter, Subscribe } }; pub type LogActor = Box<dyn Actor<Msg=LogEntry> +...
} #[derive(Clone)] pub struct LoggerConfig { time_fmt: String, date_fmt: String, log_fmt: String, filter: Vec<String>, } impl<'a> From<&'a Config> for LoggerConfig { fn from(config: &Config) -> Self { LoggerConfig { time_fmt: config.get_str("log.time_format").u...
rt_println!(self.cfg.log_fmt, date = now.format(&self.cfg.date_fmt), time = now.format(&self.cfg.time_fmt), level = entry.level, module = entry.module.unwrap_or_default(), body = entry.body ...
function_block-function_prefix_line
[ { "content": "fn default_log(cfg: &Config) -> BoxActorProd<LogActor> {\n\n let cfg = LoggerConfig::from(cfg);\n\n SimpleLogger::props(cfg)\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct SysActors {\n\n pub root: BasicActorRef,\n\n pub user: BasicActorRef,\n\n pub sysm: BasicActorRef,\n\n pub temp:...
Rust
language/move-bytecode-verifier/bytecode-verifier-tests/src/unit_tests/constants_tests.rs
rahxephon89/move
98ed299a7e3a9223019c9bdf4dd92fea9faef860
use move_binary_format::file_format::{empty_module, CompiledModule, Constant, SignatureToken}; use move_bytecode_verifier::constants; use move_core_types::vm_status::StatusCode; use proptest::prelude::*; proptest! { #[test] fn valid_generated(module in CompiledModule::valid_strategy(20)) { prop_asser...
use move_binary_format::file_format::{empty_module, CompiledModule, Constant, SignatureToken}; use move_bytecode_verifier::constants; use move_core_types::vm_status::StatusCode; use proptest::prelude::*; proptest! { #[test] fn valid_generated(module in CompiledModule::valid_strategy(20)) { prop_asser...
eToken::Address, data); } #[test] fn valid_vectors() { let double_vec = |item: Vec<u8>| -> Vec<u8> { let mut items = vec![2]; items.extend(item.clone()); items.extend(item); items }; let large_vec = |item: Vec<u8>| -> Vec<u8> { let mut items = vec![0xFF, 0xFF, 3]; ...
malformed(SignatureToken::U128, vec![0]); let data = vec![ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; malformed(Signatur
function_block-random_span
[]
Rust
src/elfload/elf_header.rs
Alignof/RV32IM_simulator
1f24317d9b4ec65f3e26426c79d8544f46846b24
use crate::elfload::{get_u16, get_u32}; fn get_elf_type_name(elf_type:u16) -> &'static str { match elf_type { 0 => "ET_NONE", 1 => "ET_REL", 2 => "ET_EXEC", 3 => "ET_DYN", 4 => "ET_CORE", _ => "unknown type", } } struct ElfIdentification { magic: [u8; 16], ...
use crate::elfload::{get_u16, get_u32}; fn get_elf_type_name(elf_type:u16) -> &'static str { match elf_type { 0 => "ET_NONE", 1 => "ET_REL", 2 => "ET_EXEC", 3 => "ET_DYN", 4 => "ET_CORE", _ => "unknown type", } } struct ElfIdentification { magic: [u8; 16], ...
assert!(loader.is_elf()); assert_eq!(loader.elf_header.e_type, 2); assert_eq!(loader.elf_header.e_flags, 5); assert_eq!(loader.elf_header.e_version, 1); assert_eq!(loader.elf_header.e_machine, 243); } }
let loader = match ElfLoader::try_new("example_elf") { Ok(loader) => loader, Err(error) => { panic!("There was a problem opening the file: {:?}", error); } };
assignment_statement
[ { "content": "pub fn get_u32(mmap: &[u8], index: usize) -> u32 {\n\n (mmap[index + 3] as u32) << 24 |\n\n (mmap[index + 2] as u32) << 16 |\n\n (mmap[index + 1] as u32) << 8 |\n\n (mmap[index + 0] as u32)\n\n}\n\n\n", "file_path": "src/elfload.rs", "rank": 1, "score": 158601.4373056056 ...
Rust
src/network/platform/unix/socket.rs
loewenheim/pueue-lib
544114c915ad87fcba2e247cb5de0ee05542c5ce
use std::path::PathBuf; use async_std::io::{Read, Write}; use async_std::net::{TcpListener, TcpStream}; use async_std::os::unix::net::{UnixListener, UnixStream}; use async_tls::TlsAcceptor; use async_trait::async_trait; use crate::error::Error; use crate::network::tls::{get_tls_connector, get_tls_listener}; use crate...
use std::path::PathBuf; use async_std::io::{Read, Write}; use async_std::net::{TcpListener, TcpStream}; use async_std::os::unix::net::{UnixListener, UnixStream}; use async_tls::TlsAcceptor; use async_trait::async_trait; use crate::error::Error; use crate::network::tls::{get_tls_connector, get_tls_listener}; use crate...
pub async fn get_listener(settings: &Shared) -> Result<GenericListener, Error> { if settings.use_unix_socket { if PathBuf::from(&settings.unix_socket_path()).exists() { if get_client_stream(settings).await.is_ok() { return Err(Error::UnixSock...
pub async fn get_client_stream(settings: &Shared) -> Result<GenericStream, Error> { if settings.use_unix_socket { if !PathBuf::from(&settings.unix_socket_path()).exists() { return Err(Error::FileNotFound(format!( "Unix socket at path {:?}. Is the daemon started?", ...
function_block-full_function
[ { "content": "/// A new trait, which can be used to represent Unix- and Tls encrypted TcpStreams.\n\n/// This is necessary to write generic functions where both types can be used.\n\npub trait Stream: Read + Write + Unpin + Send {}\n\nimpl Stream for async_tls::server::TlsStream<TcpStream> {}\n\nimpl Stream for...
Rust
rust/agent/src/sender.rs
sbworth/getnoc
a9a5647df31822062db3db7afe7ae1c005d166f7
use crate::config::ZkConfigMetrics; use crate::error::AgentError; use std::cmp::min; use std::collections::VecDeque; use tokio::sync::mpsc; pub enum SenderCommand { SetConfig(ZkConfigMetrics), SetKey(String), SetDisableCertValidation(bool), Send(String), Tick, Shutdown, } pub struct Sender {...
use crate::config::ZkConfigMetrics; use crate::error::AgentError; use std::cmp::min; use std::collections::VecDeque; use tokio::sync::mpsc; pub enum SenderCommand { SetConfig(ZkConfigMetrics), SetKey(String), SetDisableCertValidation(bool), Send(String), Tick, Shutdown, } pub struct Sender {...
if x.eq(&url) { return; } } log::info!("Set url to {}", url); self.url = Some(url); } fn set_key(&mut self, key: String) { if let Some(x) = &self.url { if x.eq(&key) { return; } } log::info!("...
EFAULT_BATCH_SIZE, send_delay_ms: DEFAULT_SEND_DELAY, disable_cert_validation: false, retry_timeout_ms: DEFAULT_RETRY_TIMEOUT, } } pub fn get_tx(&self) -> mpsc::Sender<SenderCommand> { self.tx.clone() } pub async fn run(&mut self) { l...
random
[ { "content": "fn default_false() -> bool {\n\n false\n\n}\n", "file_path": "rust/agent/src/state.rs", "rank": 0, "score": 245805.4245857367 }, { "content": "fn default_5000() -> u64 {\n\n 5_000\n\n}\n", "file_path": "rust/agent/src/collectors/modbus_rtu/config.rs", "rank": 1, ...
Rust
src/os/macos/tray.rs
SergejJurecko/native-ui
746c8fc0a571d0dfd081986aa635494708d4d8a2
use super::cocoa::appkit::{ self, NSApp, NSApplication, NSButton, NSImage, NSMenu, NSMenuItem, NSStatusBar, NSStatusItem, NSVariableStatusItemLength, }; use super::cocoa::base::{id, nil, selector}; use super::cocoa::foundation::{NSAutoreleasePool, NSData, NSProcessInfo, NSString}; use fnv::FnvHashMap as HashMap...
use super::cocoa::appkit::{ self, NSApp, NSApplication, NSButton, NSImage, NSMenu, NSMenuItem, NSStatusBar, NSStatusItem, NSVariableStatusItemLength, }; use super::cocoa::base::{id, nil, selector}; use super::cocoa::foundation::{NSAutoreleasePool, NSData, NSProcessInfo, NSString}; use fnv::FnvHashMap as HashMap...
pub fn icon_from_file(&self, p: &::std::path::Path) { unsafe { if let Some(p) = p.to_str() { let p = NSString::alloc(nil).init_str(p); let image = NSImage::initWithContentsOfFile_(NSImage::alloc(nil), p); if image == nil { ret...
pub fn set_icon(&self, img: &[u8]) { unsafe { let data = NSData::dataWithBytes_length_( nil, img.as_ptr() as *const raw::c_void, img.len() as u64, ); let image = NSImage::initWithData_(NSImage::alloc(nil), data); if ...
function_block-full_function
[ { "content": "fn grid<'a>(p_state: *mut raw::c_void) -> &'a mut RegId {\n\n unsafe { &mut *(p_state as *mut RegId) }\n\n}\n\n\n\npub(crate) unsafe extern \"C\" fn on_event(reg: *mut raw::c_void) {\n\n let reg_id = grid(reg);\n\n let reg: &mut EvStore = gt(REG.with(|r| *r.borrow_mut()));\n\n reg.q.pu...
Rust
src/lib.rs
poliorcetics/cargo-intraconv
fa4e760651f668730f34bec9de11188ad702cc9d
mod action; mod candidate; mod cli_args; mod config_file; mod consts; #[macro_use] mod error; mod file_finder; mod link_parts; mod options; mod transform; use action::Action; use candidate::Candidate; use cli_args::CliArgs; use config_file::{FileConfig, RawFileConfig}; use consts::*; use options::{ConversionOptions, K...
mod action; mod candidate; mod cli_args; mod config_file; mod consts; #[macro_use] mod error; mod file_finder; mod link_parts; mod options; mod transform; use action::Action; use candidate::Candidate; use cli_args::CliArgs; use config_file::{FileConfig, RawFileConfig}; use consts::*; use options::{ConversionOptions, K...
fn run_for_file(path: &Path, args: &CliArgs, file_config: &FileConfig) { let krate = Krate::new(&args.krate).expect("Not a valid Rust identifier"); let opts = ConversionOptions { krate, disambiguate: args.disambiguate, favored_links: !args.no_favored, ignored_links: file_confi...
Some(conf_file) } else { None }; let file_config: FileConfig = if let Some(cf) = file_config { let content = code_error!( 1, String::from_utf8(cf), "The given configuration file is not readable as UTF-8" ); let fc: RawFileConfig = code_err...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn return_error() {\n\n fn early_return() {\n\n return_error!(TestResult::Err(4), \"\");\n\n assert!(false, \"Should never be reached\");\n\n }\n\n\n\n early_return();\n\n\n\n let mut returned_early = true;\n\n let mut not_early_return = || {\n\n retu...
Rust
system/kernel/src/arch/x86_64/page.rs
meg-os/maystorm
e1709de563f0d356898ad9681d29c630efea97e4
use super::apic::Apic; use crate::mem::*; use bitflags::*; use bootprot::*; use core::{ alloc::Layout, arch::asm, mem::transmute, num::{NonZeroU64, NonZeroUsize}, ops::{AddAssign, BitOrAssign, SubAssign}, sync::atomic::*, }; pub type PhysicalAddress = u64; pub type NonNullPhysicalAddress = No...
use super::apic::Apic; use crate::mem::*; use bitflags::*; use bootprot::*; use core::{ alloc::Layout, arch::asm, mem::transmute, num::{NonZeroU64, NonZeroUsize}, ops::{AddAssign, BitOrAssign, SubAssign}, sync::atomic::*, }; pub type PhysicalAddress = u64; pub type NonNullPhysicalAddress = No...
} bitflags! { pub(super) struct PageAttributes: PageTableRepr { const PRESENT = 0x0000_0000_0000_0001; const WRITE = 0x0000_0000_0000_0002; const USER = 0x0000_0000_0000_0004; const PWT = 0x0000_0000_0000_0008; const PCD = 0x0000_0...
match Apic::broadcast_invalidate_tlb() { true => Ok(()), false => Err(()), } } }
function_block-function_prefix_line
[ { "content": "fn format_bytes(sb: &mut dyn Write, val: usize) -> core::fmt::Result {\n\n let kb = (val >> 10) & 0x3FF;\n\n let mb = (val >> 20) & 0x3FF;\n\n let gb = val >> 30;\n\n\n\n if gb >= 10 {\n\n // > 10G\n\n write!(sb, \"{:4}G\", gb)\n\n } else if gb >= 1 {\n\n // 1G~...
Rust
aoc-2021/packages/aoc-rust/src/day_05.rs
protiumx/aoc-2021
9933b4954693066b74bbfa6a4e17ccecb97ded45
use std::cmp::{max, min}; use std::ops::{Range, RangeInclusive}; use std::str::FromStr; #[derive(Debug)] struct Line { x: (usize, usize), y: (usize, usize), } impl FromStr for Line { type Err = std::io::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let (start, end) = s.split_once("...
use std::cmp::{max, min}; use std::ops::{Range, RangeInclusive}; use std::str::FromStr; #[derive(Debug)] struct Line { x: (usize, usize), y: (usize, usize), } impl FromStr for Line { type Err = std::io::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let (start, end) = s.split_once("...
board[row as usize][col] += 1; if board[row as usize][col] == 2 { count += 1; } col += 1; row += m; } return (board, count); }); println!("- Part 2: {}", count); }
(line.x.1 as i32 - line.x.0 as i32) / (line.y.1 as i32 - line.y.0 as i32); let y_max = max(line.y.0, line.y.1); let y_min = min(line.y.0, line.y.1); let mut col = min(line.x.0, line.x.1); let mut row = (if m == -1 { y_max } else { y_min }) as i32...
random
[ { "content": "pub fn show() {\n\n part_one();\n\n}\n", "file_path": "aoc-2021/packages/aoc-rust/src/day_04.rs", "rank": 1, "score": 123158.53264460762 }, { "content": "pub fn show() {\n\n println!(\"- Part 1: {}\", part_one());\n\n println!(\"- Part 2: {}\", part_two());\n\n}\n", ...
Rust
cranelift/native/src/lib.rs
dalinaum/wasmtime
0394a0119440a4ccb7206a3de21941bc5f93f25f
#![deny( missing_docs, trivial_numeric_casts, unused_extern_crates, unstable_features )] #![warn(unused_import_braces)] #![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))] #![cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))] #![cfg_attr( feature ...
#![deny( missing_docs, trivial_numeric_casts, unused_extern_crates, unstable_features )] #![warn(unused_import_braces)] #![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))] #![cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))] #![cfg_attr( feature ...
} pub const VERSION: &str = env!("CARGO_PKG_VERSION");
q!(isa.default_call_conv(), CallConv::SystemV); } else if cfg!(windows) { assert_eq!(isa.default_call_conv(), CallConv::WindowsFastcall); } if cfg!(target_pointer_width = "64") { assert_eq!(isa.pointer_bits(), 64); } if cfg!(tar...
function_block-function_prefixed
[ { "content": "/// Look for a supported ISA with the given `name`.\n\n/// Return a builder that can create a corresponding `TargetIsa`.\n\npub fn lookup_by_name(name: &str) -> Result<Builder, LookupError> {\n\n use alloc::str::FromStr;\n\n lookup(triple!(name))\n\n}\n\n\n\n/// Describes reason for target l...
Rust
src/rust/iced-x86-py/src/fast_formatter.rs
paulfariello/iced
08f663ae9626b05ab08ad36dd5143f94aed365b6
use crate::instruction::Instruction; use pyo3::prelude::*; #[pyclass(module = "_iced_x86_py")] #[pyo3(text_signature = "(/)")] pub(crate) struct FastFormatter { fmt_output: String, formatter: iced_x86::FastFormatter, } unsafe impl Send for FastFormatter {} #[pymethods] impl FastFormatter { #[new] fn new() -> S...
use crate::instruction::Instruction; use pyo3::prelude::*; #[pyclass(module = "_iced_x86_py")] #[pyo3(text_signature = "(/)")] pub(crate) struct FastFormatter { fmt_output: String, formatter: iced_x86::FastFormatter, } unsafe impl Send for FastFormatter {} #[pymethods] impl FastFormatter { #[new] fn new() -> S...
#[setter] fn set_always_show_segment_register(&mut self, new_value: bool) { self.formatter.options_mut().set_always_show_segment_register(new_value); } #[getter] fn always_show_memory_size(&self) -> bool { self.formatter.options().always_show_memory_size() } #[setter] fn set_always_show_m...
seudo_ops(&mut self, new_value: bool) { self.formatter.options_mut().set_use_pseudo_ops(new_value); } #[getter] fn show_symbol_address(&self) -> bool { self.formatter.options().show_symbol_address() } #[setter] fn set_show_symbol_address(&mut self, new_value: bool) { self.formatter.options...
random
[ { "content": "#[cfg(any(feature = \"gas\", feature = \"intel\", feature = \"masm\", feature = \"nasm\"))]\n\nfn format_test_instruction_core(instruction: &Instruction, formatted_string: &str, mut formatter: Box<dyn Formatter>) {\n\n\tlet mut actual_formatted_string = String::new();\n\n\tformatter.format(instruc...
Rust
core/lib/storage/src/chain/account/records.rs
IversonHan/zksync
85fb99e5265723ae72cfc01ad39bc8420a3731ad
use zksync_api_types::v02::account::EthAccountType as ApiEthAccountType; use sqlx::{types::BigDecimal, FromRow}; use zksync_types::{AccountId, Address, PubKeyHash, TokenId, H256, NFT}; #[derive(Debug, FromRow)] pub struct StorageAccount { pub id: i64, pub last_block: i64, pub nonce: i64, pub address:...
use zksync_api_types::v02::account::EthAccountType as ApiEthAccountType; use sqlx::{types::BigDecimal, FromRow}; use zksync_types::{AccountId, Address, PubKeyHash, TokenId, H256, NFT}; #[derive(Debug, FromRow)] pub struct StorageAccount { pub id: i64, pub last_block: i64, pub nonce: i64, pub address:...
} pub fn into_db_types(self) -> (DbAccountType, Option<PubKeyHash>) { match self { EthAccountType::Owned => (DbAccountType::Owned, None), EthAccountType::CREATE2 => (DbAccountType::CREATE2, None), EthAccountType::No2FA(hash) => (DbAccountType::No2FA, hash), ...
match account_type { DbAccountType::Owned => EthAccountType::Owned, DbAccountType::CREATE2 => EthAccountType::CREATE2, DbAccountType::No2FA => EthAccountType::No2FA(pub_key_hash), }
if_condition
[ { "content": "pub fn calculate_token_hash(creator_id: AccountId, serial_id: u32, content_hash: H256) -> Vec<u8> {\n\n let mut lhs_be_bits = vec![];\n\n lhs_be_bits.extend_from_slice(&creator_id.0.to_be_bytes());\n\n lhs_be_bits.extend_from_slice(&serial_id.to_be_bytes());\n\n lhs_be_bits.extend_from...
Rust
compiler/rustc_infer/src/traits/util.rs
stevepentland/rust
57d8747cca741de84918800dca13da0c821e33e0
use smallvec::smallvec; use crate::traits::{Obligation, ObligationCause, PredicateObligation}; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_middle::ty::outlives::Component; use rustc_middle::ty::{self, ToPredicate, TyCtxt, WithConstness}; use rustc_span::symbol::Ident; pub fn anonymize_predicate<...
use smallvec::smallvec; use crate::traits::{Obligation, ObligationCause, PredicateObligation}; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_middle::ty::outlives::Component; use rustc_middle::ty::{self, ToPredicate, TyCtxt, WithConstness}; use rustc_span::symbol::Ident; pub fn anonymize_predicate<...
}), ); } ty::PredicateKind::TypeWellFormedFromEnv(..) => { } } } } impl Iterator for Elaborator<'tcx> { type Item = PredicateObligation<'tcx>; fn size_hint(&self) -> (usize, Option<usize>) { (self...
predicate_obligation( predicate, obligation.param_env, obligation.cause.clone(), )
call_expression
[]
Rust
src/libsyntax/util/parser.rs
ofek/rust
b16c7a235fa0f57fed6b7ec13ffd3cff1bcdd9ad
use parse::token::{Token, BinOpToken}; use symbol::keywords; use ast::BinOpKind; #[derive(Debug, PartialEq, Eq)] pub enum AssocOp { Add, Subtract, Multiply, Divide, Modulus, LAnd, LOr, BitXor, BitAnd, BitOr, ShiftLeft,...
use parse::token::{Token, BinOpToken}; use symbol::keywords; use ast::BinOpKind; #[derive(Debug, PartialEq, Eq)] pub enum AssocOp { Add, Subtract, Multiply, Divide, Modulus, LAnd, LOr, BitXor, BitAnd, BitOr, ShiftLeft,...
pub fn precedence(&self) -> usize { use self::AssocOp::*; match *self { As | Colon => 14, Multiply | Divide | Modulus => 13, Add | Subtract => 12, ShiftLeft | ShiftRight => 11, BitAnd => 10, BitXor => 9, BitOr...
inop(op: BinOpKind) -> Self { use self::AssocOp::*; match op { BinOpKind::Lt => Less, BinOpKind::Gt => Greater, BinOpKind::Le => LessEqual, BinOpKind::Ge => GreaterEqual, BinOpKind::Eq => Equal, BinOpKind::Ne => NotEqual, ...
function_block-function_prefixed
[ { "content": "pub fn fourway_add(a: i32) -> impl Fn(i32) -> impl Fn(i32) -> impl Fn(i32) -> i32 {\n\n move |b| move |c| move |d| a + b + c + d\n\n}\n", "file_path": "src/test/run-pass/impl-trait/auxiliary/xcrate.rs", "rank": 0, "score": 369486.4155322196 }, { "content": "pub fn main() {\n...
Rust
testsuite/cluster-test/src/health/mod.rs
thefallentree/diem
2af785b23175ceaef265ea971270d82d1073f35e
#![forbid(unsafe_code)] mod commit_check; mod debug_interface_log_tail; mod fullnode_check; mod liveness_check; mod log_tail; use crate::cluster::Cluster; use anyhow::{bail, Result}; use async_trait::async_trait; pub use commit_check::CommitHistoryHealthCheck; pub use debug_interface_log_tail::DebugPortLogWorker; p...
#![forbid(unsafe_code)] mod commit_check; mod debug_interface_log_tail; mod fullnode_check; mod liveness_check; mod log_tail; use crate::cluster::Cluster; use anyhow::{bail, Result}; use async_trait::async_trait; pub use commit_check::CommitHistoryHealthCheck; pub use debug_interface_log_tail::DebugPortLogWorker; p...
pub async fn run( &mut self, events: &[ValidatorEvent], affected_validators_set: &HashSet<String>, print_failures: PrintFailures, ) -> Result<Vec<String>> { let mut node_health = HashMap::new(); for instance in self.cluster.validator_ins...
f::new( cluster, vec![ Box::new(CommitHistoryHealthCheck::new()), Box::new(liveness_health_check), Box::new(fullnode_check), ], ) }
function_block-function_prefixed
[ { "content": "/// A trait alias for \"socket-like\" things.\n\npub trait TSocket: AsyncRead + AsyncWrite + Send + fmt::Debug + Unpin + 'static {}\n\n\n\nimpl<T> TSocket for T where T: AsyncRead + AsyncWrite + Send + fmt::Debug + Unpin + 'static {}\n\n\n\n/// Unique local identifier for a connection.\n\n#[derive...
Rust
src/third_party/mint/mint_matrix.rs
zyansheep/nalgebra
e913beca889dc278d1c0d6cadd2008d3f9bcc0af
use std::convert::{AsMut, AsRef, From, Into}; use std::mem::{self, MaybeUninit}; use std::ptr; use crate::base::allocator::Allocator; use crate::base::dimension::{Const, DimName, U1, U2, U3, U4}; use crate::base::storage::{IsContiguous, RawStorage, RawStorageMut}; use crate::base::{DefaultAllocator, Matrix, OMatrix, S...
use std::convert::{AsMut, AsRef, From, Into}; use std::mem::{self, MaybeUninit}; use std::ptr; use crate::base::allocator::Allocator; use crate::base::dimension::{Const, DimName, U1, U2, U3, U4}; use crate::base::storage::{IsContiguous, RawStorage, Ra
NRows>::name(), <$NCols>::name()); let mut ptr = res.data.ptr_mut(); $( ptr::copy_nonoverlapping(&m.$component.x, ptr as *mut T, $SZRows); ptr = ptr.offset($SZRows); )* let _ = ptr; ...
wStorageMut}; use crate::base::{DefaultAllocator, Matrix, OMatrix, Scalar}; macro_rules! impl_from_into_mint_1D( ($($NRows: ident => $VT:ident [$SZ: expr]);* $(;)*) => {$( impl<T> From<mint::$VT<T>> for OMatrix<T, $NRows, U1> where T: Scalar, DefaultAllocator: Allocator<T, $NRows, U1>...
random
[ { "content": "// Computes the 2x2 transformation that upper-triangulates a 2x2 matrix with real eigenvalues.\n\n/// Computes the singular vectors for a 2x2 matrix.\n\n///\n\n/// Returns `None` if the matrix has complex eigenvalues, or is upper-triangular. In both case,\n\n/// the basis is the identity.\n\nfn co...
Rust
rust/auction/program/src/instruction.rs
invictus2010/metaplex
f58e4945f2824fbcdf058d6e904abefd80d8b190
use crate::{EXTENDED, PREFIX}; use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ instruction::{AccountMeta, Instruction}, pubkey::Pubkey, sysvar, }; pub use crate::processor::{ cancel_bid::CancelBidArgs, claim_bid::ClaimBidArgs, create_auction::CreateAuctionArgs, create_auction_v...
use crate::{EXTENDED, PREFIX}; use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ instruction::{AccountMeta, Instruction}, pubkey::Pubkey, sysvar, }; pub use crate::processor::{ cancel_bid::CancelBidArgs, claim_bid::ClaimBidArgs, create_auction::CreateAuctionArgs, create_auction_v...
tionInstruction::EndAuction(args).try_to_vec().unwrap(), } } pub fn claim_bid_instruction( program_id: Pubkey, destination_pubkey: Pubkey, authority_pubkey: Pubkey, bidder_pubkey: Pubkey, bidder_pot_token_pubkey: Pubkey, token_mint_pubkey: Pubkey, auction_extended_pubkey: Option<Pubkey>...
gram_address(seeds, &program_id); Instruction { program_id, accounts: vec![ AccountMeta::new(creator_pubkey, true), AccountMeta::new(auction_pubkey, false), AccountMeta::new(auction_extended_pubkey, false), AccountMeta::new_readonly(sysvar::rent::id()...
random
[ { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn sign_metadata(program_id: Pubkey, metadata: Pubkey, creator: Pubkey) -> Instruction {\n\n Instruction {\n\n program_id,\n\n accounts: vec![\n\n AccountMeta::new(metadata, false),\n\n AccountMeta::new_readonly(cre...
Rust
capi/bind_gen/src/jni_cpp.rs
kadiwa4/livesplit-core
67999aed8f9be3c405135192c3d484776b4d4fed
use crate::{Class, Function, Type, TypeKind}; use heck::ToLowerCamelCase; use std::{ borrow::Cow, collections::BTreeMap, io::{Result, Write}, }; fn get_c_type(ty: &Type) -> Cow<'_, str> { let mut name = Cow::Borrowed(match ty.name.as_str() { "i8" => "int8_t", "i16" => "int16_t", ...
use crate::{Class, Function, Type, TypeKind}; use heck::ToLowerCamelCase; use std::{ borrow::Cow, collections::BTreeMap, io::{Result, Write}, }; fn get_c_type(ty: &Type) -> Cow<'_, str> { let mut name = Cow::Borrowed(match ty.name.as_str() { "i8" => "int8_t", "i16" => "int16_t", ...
r()) .chain(class.mut_fns.iter()) { write_fn(&mut writer, function, class_name)?; writeln!(writer, "")?; } } Ok(()) }
tring" { write!( writer, r#" jni_env->ReleaseStringUTFChars({name}, cstr_{name});"#, name = name )?; } } if has_return_type { write!( writer, r#" return result;"# )?; } write...
random
[ { "content": "fn write_fn<W: Write>(mut writer: W, function: &Function, type_script: bool) -> Result<()> {\n\n let is_static = function.is_static();\n\n let has_return_type = function.has_return_type();\n\n let return_type_with_null = get_hl_type_with_null(&function.output);\n\n let return_type_with...
Rust
noodles-vcf/src/record/genotype.rs
slazicoicr/noodles
2a1b086254d32942dbfd5524f07a66207fa09a92
pub mod field; pub use self::field::Field; use std::{error, fmt, ops::Deref}; use super::{Format, MISSING_FIELD}; const DELIMITER: char = ':'; #[derive(Clone, Debug, Default, PartialEq)] pub struct Genotype(Vec<Field>); #[derive(Clone, Debug, Eq, PartialEq)] pub enum ParseError { Empty, Invali...
pub mod field; pub use self::field::Field; use std::{error, fmt, ops::Deref}; use super::{Format, MISSING_FIELD}; const DELIMITER: char = ':'; #[derive(Clone, Debug, Default, PartialEq)] pub struct Genotype(Vec<Field>); #[derive(Clone, Debug, Eq, PartialEq)] pub enum ParseError { Empty, Invali...
} impl Deref for Genotype { type Target = [Field]; fn deref(&self) -> &Self::Target { &self.0 } } impl fmt::Display for Genotype { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.is_empty() { f.write_str(MISSING_FIELD) } else { for (...
pub fn from_str_format(s: &str, format: &Format) -> Result<Self, ParseError> { match s { "" => Err(ParseError::Empty), MISSING_FIELD => Ok(Self::default()), _ => s .split(DELIMITER) .zip(format.iter()) .map(|(t, k)| Field::from_...
function_block-full_function
[ { "content": "fn parse_raw_char(s: &str) -> Result<char, ParseError> {\n\n let mut chars = s.chars();\n\n\n\n if let Some(c) = chars.next() {\n\n if chars.next().is_none() {\n\n return Ok(c);\n\n }\n\n }\n\n\n\n Err(ParseError::InvalidCharacter)\n\n}\n\n\n", "file_path":...
Rust
frontier/client/rpc/src/overrides/schema_v2_override.rs
deeper-chain/deeper-chain
bdd762673b88e0b423574d0cb43f229938af06ef
use codec::Decode; use ethereum_types::{H160, H256, U256}; use fp_rpc::TransactionStatus; use sc_client_api::backend::{AuxStore, Backend, StateBackend, StorageProvider}; use sp_api::BlockId; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use sp_runtime::traits::{BlakeTwo256, Block as Bl...
use codec::Decode; use ethereum_types::{H160, H256, U256}; use fp_rpc::TransactionStatus; use sc_client_api::backend::{AuxStore, Backend, StateBackend, StorageProvider}; use sp_api::BlockId; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use sp_runtime::traits::{BlakeTwo256, Block as Bl...
, ) } fn base_fee(&self, block: &BlockId<Block>) -> Option<U256> { self.query_storage::<U256>( block, &StorageKey(storage_prefix_build(b"BaseFee", b"BaseFeePerGas")), ) } fn is_eip1559(&self, _block: &BlockId<Block>) -> bool { true } }
StorageKey(storage_prefix_build( b"Ethereum", b"CurrentTransactionStatuses", ))
call_expression
[ { "content": "pub fn sync_blocks<Block: BlockT, C, B>(\n\n client: &C,\n\n substrate_backend: &B,\n\n frontier_backend: &fc_db::Backend<Block>,\n\n limit: usize,\n\n strategy: SyncStrategy,\n\n) -> Result<bool, String>\n\nwhere\n\n C: ProvideRuntimeApi<Block> + Send + Sync + HeaderBackend<Bloc...
Rust
foundationdb/tests/get.rs
pH14/foundationdb-rs
e83cadcf460ab92a3605dd1c9b94a1fe100a42b8
extern crate foundationdb; extern crate futures; #[macro_use] extern crate lazy_static; use foundationdb::*; use futures::future::*; mod common; #[test] fn test_set_get() { common::setup_static(); let fut = Cluster::new(foundationdb::default_config_path()) .and_then(|cluster| cluster.create_databas...
extern crate foundationdb; extern crate futures; #[macro_use] extern crate lazy_static; use foundationdb::*; use futures::future::*; mod common; #[test] fn test_set_get() { common::setup_static(); let fut = Cluster::new(foundationdb::default_config_path()) .and_then(|cluster| cluster.create_databas...
) }); fut.wait().expect("failed to run"); assert_eq!(try_count.load(Ordering::SeqCst), RETRY_COUNT + 1); } #[test] fn test_versionstamp() { const KEY: &[u8] = b"test-versionstamp"; common::setup_static(); let fut = Cluster::new(foundationdb::default_config_path()) .and_t...
match res { Ok(_) => panic!("should not be able to commit"), Err(e) => { eprintln!("failed as expected: {:?}", e); Ok(()) } }
if_condition
[ { "content": "#[test]\n\nfn test_watch_without_commit() {\n\n common::setup_static();\n\n const KEY: &'static [u8] = b\"test-watch-2\";\n\n\n\n let fut = Cluster::new(foundationdb::default_config_path())\n\n .and_then(|cluster| cluster.create_database())\n\n .and_then(|db| result(db.creat...
Rust
impl/rust/lisla_lang/src/parse/space.rs
shohei909/Lisla
9267d0792d6d4f633dec1c079d2a39bc5e4719c1
use tag::*; use super::error::ParseError; use super::*; use super::string::*; use super::array::*; #[derive(Debug, Clone)] pub struct SpaceContext { data: SpaceData, kind: SpaceContextKind, } impl SpaceContext { pub fn new(start:usize, separater_required: bool) -> SpaceContext { Spac...
use tag::*; use super::error::ParseError; use super::*; use super::string::*; use super::array::*; #[derive(Debug, Clone)] pub struct SpaceContext { data: SpaceData, kind: SpaceContextKind, } impl SpaceContext { pub fn new(start:usize, separater_required: bool) -> SpaceContext { Spac...
fn space_action(mut self, kind: SpaceContextKind) -> ProcessAction { self.separater_required = false; ProcessAction::Next( ArrayContextKind::Space( SpaceContext { data: self, kind, } ) ...
fn process_normal( self, input:&CharacterInput, mut normal_context: NormalContext, errors:&mut ErrorWrite<ParseError> ) -> ProcessAction { let character = input.character; match character { '(' => { let space = self.complete_norm...
function_block-full_function
[ { "content": "// エラーの種別がstructだったときの実装\n\nfn impl_error_for_struct(ast: &DeriveInput, variant:&VariantData) -> Tokens {\n\n let name = &ast.ident;\n\n let position = impl_position_for_struct(ast, variant);\n\n \n\n quote! {\n\n impl ::lisla_core::error::Error for #name {\n\n fn mes...
Rust
crates/maple_cli/src/stdio_server/session/providers/filer.rs
gniw/vim-clap
27be8ab19b195ef9ff319e336ceed70ffdd09ff7
use std::path::{self, Path, PathBuf}; use std::{fs, io}; use anyhow::Result; use crossbeam_channel::Sender; use log::debug; use serde_json::json; use icon::prepend_filer_icon; use crate::stdio_server::{ session::{ build_abs_path, Event, EventHandler, NewSession, OnMove, OnMoveHandler, Session, Se...
use std::path::{self, Path, PathBuf}; use std::{fs, io}; use anyhow::Result; use crossbeam_channel::Sender; use log::debug; use serde_json::json; use icon::prepend_filer_icon; use crate::stdio_server::{ session::{ build_abs_path, Event, EventHandler, NewSession, OnMove, OnMoveHandler, Session, Se...
"entries": entries, "dir": cwd, "total": entries.len(), }); json!({ "id": msg.id, "provider_id": "filer", "result": result }) } Err(err) => { let error = json!({"message": err.to_string(), "dir": cwd}); json!({ "id": ms...
atch event { Event::OnMove(msg) => { let provider_id = context.provider_id.clone(); let curline = msg.get_curline(&provider_id).unwrap(); let path = build_abs_path(&msg.get_cwd(), curline); let on_move_handler = OnMoveHandler { ...
random
[ { "content": "/// Build the absolute path using cwd and relative path.\n\npub fn build_abs_path<P: AsRef<Path>>(cwd: P, curline: String) -> PathBuf {\n\n let mut path: PathBuf = cwd.as_ref().into();\n\n path.push(&curline);\n\n path\n\n}\n\n\n\nimpl OnMove {\n\n pub fn new(curline: String, context: ...
Rust
cep47-tests/src/cep47.rs
SupremeLeader00/casper-nft-cep47
90e366d7ff96aeee49b135a576ef3bc645c8d13e
use std::collections::BTreeMap; use casper_engine_test_support::{Code, Hash, SessionBuilder, TestContext, TestContextBuilder}; use casper_types::{ account::AccountHash, bytesrepr::FromBytes, runtime_args, CLTyped, ContractPackageHash, HashAddr, Key, PublicKey, RuntimeArgs, SecretKey, U256, U512, }; pub mod to...
use std::collections::BTreeMap; use casper_engine_test_support::{Code, Hash, SessionBuilder, TestContext, TestContextBuilder}; use casper_types::{ account::AccountHash, bytesrepr::FromBytes, runtime_args, CLTyped, ContractPackageHash, HashAddr, Key, PublicKey, RuntimeArgs, SecretKey, U256, U512, }; pub mod to...
fn query_contract<T: CLTyped + FromBytes>(&self, name: &str) -> Option<T> { match self .context .query(self.admin, &[CONTRACT_KEY.to_string(), name.to_string()]) { Err(_) => None, Ok(maybe_value) => { let value = maybe_value ...
fn call(&mut self, sender: &AccountHash, method: &str, args: RuntimeArgs) { let account = *sender; let code = Code::Hash(self.hash, method.to_string()); let session = SessionBuilder::new(code, args) .with_address(account) .with_authorization_keys(&[account]) ....
function_block-full_function
[ { "content": "fn add_empty_dict(named_keys: &mut NamedKeys, name: &str) {\n\n let dict = new_dictionary(name).unwrap_or_revert();\n\n runtime::remove_key(name);\n\n named_keys.insert(name.to_string(), dict.into());\n\n}\n\n\n", "file_path": "cep47/src/data.rs", "rank": 0, "score": 153157.48...
Rust
src/completions.rs
goto-bus-stop/sqc
43e7b5f00d974036326797470f495392691ffa6b
use crate::sql::{parse_sql, ParsedSql}; use rusqlite::Connection; use std::borrow::Cow; use std::collections::HashMap; use std::rc::Rc; use tree_sitter::{Node, QueryCursor, TextProvider}; fn text_provider(input: &str) -> impl TextProvider<'_> { |node: Node<'_>| std::iter::once(input[node.byte_range()].as_bytes()) ...
use crate::sql::{parse_sql, ParsedSql}; use rusqlite::Connection; use std::borrow::Cow; use std::collections::HashMap; use std::rc::Rc; use tree_sitter::{Node, QueryCursor, TextProvider}; fn text_provider(input: &str) -> impl TextProvider<'_> { |node: Node<'_>| std::iter::once(input[node.byte_range()].as_bytes()) ...
}
pub fn get_completions(&self, sql: &str, pos: usize) -> Vec<(usize, String)> { let tree = parse_sql(sql).unwrap(); let names = self.parse_names(&tree); let root = tree.tree.root_node(); let max_lookbehind = 5.min(pos); let relevant_node = (0..max_lookbehind).find_map(|offset| { ...
function_block-full_function
[ { "content": "fn text_provider(input: &str) -> impl TextProvider<'_> {\n\n |node: Node<'_>| std::iter::once(input[node.byte_range()].as_bytes())\n\n}\n\n\n\npub struct ParsedSql<'a> {\n\n pub source: &'a str,\n\n pub tree: Tree,\n\n}\n\n\n\nimpl<'a> TextProvider<'a> for ParsedSql<'a> {\n\n type I = ...
Rust
tests/incremental/constants.rs
mheiber/salsa
f4e09fee230da5165f70961f46225fc4e5f734e5
use crate::implementation::{TestContext, TestContextImpl}; use salsa::debug::DebugQueryTable; use salsa::Durability; #[salsa::query_group(Constants)] pub(crate) trait ConstantsDatabase: TestContext { #[salsa::input] fn input(&self, key: char) -> usize; fn add(&self, key1: char, key2: char) -> usize; ...
use crate::implementation::{TestContext, TestContextImpl}; use salsa::debug::DebugQueryTable; use salsa::Durability; #[salsa::query_group(Constants)] pub(crate) trait ConstantsDatabase: TestContext { #[salsa::input] fn input(&self, key: char) -> usize; fn add(&self, key1: char, key2: char) -> usize; ...
{ let mut db = TestContextImpl::default(); db.set_input_with_durability('a', 11, Durability::HIGH); db.set_input_with_durability('b', 22, Durability::HIGH); db.set_input_with_durability('c', 33, Durability::HIGH); assert_eq!(db.add3('a', 'b', 'c'), 66); db.set_input('a', 11); ...
urability(('a', 'b'))); db.set_input_with_durability('b', 45, Durability::HIGH); assert_eq!(db.add('a', 'b'), 68); assert_eq!(Durability::HIGH, AddQuery.in_db(&db).durability(('a', 'b'))); db.set_input_with_durability('b', 45, Durability::MEDIUM); assert_eq!(db.add('a', 'b'), 68); assert_eq!( ...
random
[ { "content": "fn b(db: &dyn StressDatabase, key: usize) -> usize {\n\n db.unwind_if_cancelled();\n\n db.a(key)\n\n}\n\n\n", "file_path": "tests/parallel/stress.rs", "rank": 2, "score": 304328.0316659812 }, { "content": "fn c(db: &dyn StressDatabase, key: usize) -> usize {\n\n db.b(k...
Rust
src/lib.rs
A1-Triard/dyn-fmt
11b4ebb934eceadf95c5c16287604d2bc8d1b320
#![deny(warnings)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] extern crate core; use core::fmt::{self, Display}; use core::hint::{unreachable_unchecked}; #[doc(hidden)] pub use core::write as std_write; #[cfg(feature = "std")] pub trait AsStrFormatExt: AsRef<str> { ...
#![deny(warnings)] #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] extern crate core; use core::fmt::{self, Display}; use core::hint::{unreachable_unchecked}; #[doc(hidden)] pub use core::write as std_write; #[cfg(feature = "std")] pub trait
}, } } Ok(()) } } #[cfg(test)] mod tests { use crate as dyn_fmt; #[cfg(feature = "std")] use AsStrFormatExt; use core::fmt::{self, Write, Display}; use core::str::{self}; #[cfg(feature = "std")] #[test] fn test_format() { assert_eq!("{}a{}b...
AsStrFormatExt: AsRef<str> { fn format<'a, T: Display + ?Sized + 'a>(&self, args: impl IntoIterator<Item=&'a T> + Clone) -> String { format!("{}", Arguments::new(self, args)) } } #[cfg(feature = "std")] impl<T: AsRef<str>> AsStrFormatExt for T { } #[macro_e...
random
[ { "content": "![travis](https://travis-ci.org/A1-Triard/dyn-fmt.svg?branch=master)\n\n\n\n# dyn-fmt\n\n\n\nProvides dynamic string format.\n\n\n\n```rust\n\nuse dyn_fmt::AsStrFormatExt;\n\n\n\nfn main() {\n\n assert_eq!(\"{}a{}b{}c\".format(&[1, 2, 3]), \"1a2b3c\");\n\n assert_eq!(\"{}a{}b{}c\".format(&[1...
Rust
src/streamcheck.rs
RickeyEstes/av-stream-info-rust
04c761b2fc01b5074a95cc3fad90bbfa64de451f
#![allow(non_snake_case)] use crate::request::Request; use crate::streamcheckerror::StreamCheckError; use playlist_decoder; use url::Url; use hls_m3u8::MasterPlaylist; use crate::streamdeepscan; use log::{debug}; #[derive(Debug,Serialize,Clone)] pub struct StreamInfo { pub Server: Option<String>, pub Public...
#![allow(non_snake_case)] use crate::request::Request; use crate::streamcheckerror::StreamCheckError; use playlist_decoder; use url::Url; use hls_m3u8::MasterPlaylist; use crate::streamdeepscan; use log::{debug}; #[derive(Debug,Serialize,Clone)] pub struct StreamInfo { pub Server: Option<String>, pub Public...
); } } Err(err) => list.push(Err(StreamCheckError::new(url, &err.to_string()))), } list } fn decode_playlist(url_str: &str, content: &str, check_all: bool, timeout: u32, max_depth: u8) -> Vec<StreamCheckResult> { let mut list = vec![]; let base_url = Url::parse(url_str); ...
Err(StreamCheckError::new( url, &format!("illegal http status code {}", request.info.code), ))
call_expression
[ { "content": "pub fn scan(bytes: &[u8]) -> Result<Option<ScanResult>, Box<dyn std::error::Error>> {\n\n let mime = tree_magic::from_u8(bytes);\n\n debug!(\"found mime type: {}\", mime);\n\n if mime != \"application/octet-stream\" {\n\n Ok(Some(ScanResult{mime}))\n\n }else{\n\n Ok(None)...
Rust
src/test/instruction_tests/instr_vrsqrt14pd.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vrsqrt14pd_1() { run_test( &Instruction { mnemonic: Mnemonic::VRSQRT14PD, ...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vrsqrt14pd_1() { run_test( &Instruction { mnemonic: Mnemonic::VRSQRT14PD, ...
, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None, }, &[98, 242, 253, 204, 78, 244], OperandSize::Dword, ) } #[test] fn vrsqrt14pd_14() { run...
truction { mnemonic: Mnemonic::VRSQRT14PD, operand1: Some(Direct(XMM13)), operand2: Some(IndirectScaledDisplaced( RDX, Eight, 77164494, Some(OperandSize::Xmmword), None, )), operan...
random
[ { "content": "fn encode32_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
components/hab/src/command/pkg/export/mod.rs
acidburn0zzz/habitat
362b2d7a4ed7f8215609102921f9126042fa7aac
use common::ui::UI; use hcore::package::PackageIdent; use error::Result; pub mod docker; pub mod cf; pub mod helm; pub mod kubernetes; mod export_common; #[allow(dead_code)] pub struct ExportFormat { pkg_ident: PackageIdent, cmd: String, } #[allow(dead_code)] impl ExportFormat { pub fn pkg_ident(&sel...
use common::ui::UI; use hcore::package::PackageIdent; use error::Result; pub mod docker; pub mod cf; pub mod helm; pub mod kubernetes; mod export_common; #[allow(dead_code)] pub struct ExportFormat { pkg_ident: PackageIdent, cmd: String, } #[allow(dead_code)] impl ExportFormat { pub fn pkg_ident(&sel...
pub fn start( ui: &mut UI, _url: &str, _channel: &str, _ident: &PackageIdent, _format: &ExportFormat, ) -> Result<()> { let subcmd = env::args().nth(1).unwrap_or("<unknown>".to_string()); let subsubcmd = env::args().nth(2).unwrap_or("<unknown>".to_string...
Result<ExportFormat> { ui.warn(format!( "∅ Exporting {} packages from this operating system is not yet \ supported. Try running this command again on a 64-bit Linux \ operating system.\n", value ))?; ui.br()?; ...
function_block-function_prefixed
[ { "content": "/// Return a list of channels that a package is in.\n\n///\n\n/// # Failures\n\n///\n\n/// * Fails if it cannot find the specified package in Builder.\n\npub fn start(ui: &mut UI, url: &str, ident: &PackageIdent, token: Option<&str>) -> Result<()> {\n\n let depot_client = Client::new(url, PRODU...
Rust
src/lib.rs
RustPython/unicode-casing
915de3afee9ddca034f21143215c68b0cc582cdc
mod bool_trie; mod tables; use tables::{conversions, general_category}; pub trait CharExt { fn is_titlecase(self) -> bool; fn to_titlecase(self) -> ToTitlecase; } impl CharExt for char { #[inlin...
mod bool_trie; mod tables; use tables::{conversions, general_category}; pub trait CharExt { fn is_titlecase(self) -> bool; fn to_titlecase(self) -> ToTitlecase; } impl CharExt for char { #[inlin...
aseMappingIter::Two(b, c) => { *self = CaseMappingIter::One(c); Some(b) } CaseMappingIter::One(c) => { *self = CaseMappingIter::Zero; Some(c) } CaseMappingIter::Zero => None, } } } impl CaseMappi...
One(char), Zero, } impl Iterator for CaseMappingIter { type Item = char; fn next(&mut self) -> Option<char> { match *self { CaseMappingIter::Three(a, b, c) => { *self = CaseMappingIter::Two(b, c); Some(a) } C
random
[ { "content": "fn trie_range_leaf(c: u32, bitmap_chunk: u64) -> bool {\n\n ((bitmap_chunk >> (c & 63)) & 1) != 0\n\n}\n", "file_path": "src/bool_trie.rs", "rank": 1, "score": 39932.624007970284 }, { "content": " // 0..0x800 (corresponding to 1 and 2 byte utf-8 sequences)\n\n pub r1: ...
Rust
buttplug/src/core/messages/serializer/json_serializer.rs
Nootna8/buttplug
73146d15f86804916e2ee93308c9d241d3ea91fd
use super::{ButtplugMessageSerializer, ButtplugSerializedMessage, ButtplugSerializerError}; use crate::{ core::{ errors::{ButtplugError, ButtplugHandshakeError}, messages::{ self, ButtplugClientMessage, ButtplugCurrentSpecClientMessage, ButtplugCurrentSpecServerMessage, ButtplugMessage, ButtplugMe...
use super::{ButtplugMessageSerializer, ButtplugSerializedMessage, ButtplugSerializerError}; use crate::{ core::{ errors::{ButtplugError, ButtplugHandshakeError}, messages::{ self, ButtplugClientMessage, ButtplugCurrentSpecClientMessage, ButtplugCurrentSpecServerMessage, ButtplugMessage, ButtplugMe...
; } let msg_union = deserialize_to_message::<ButtplugSpecV2ClientMessage>(&self.validator, msg)?; if let ButtplugSpecV2ClientMessage::RequestServerInfo(rsi) = &msg_union[0] { info!( "Setting JSON Wrapper message version to {}", rsi.message_version() ); *self.messa...
Ok(match version { ButtplugMessageSpecVersion::Version0 => { deserialize_to_message::<ButtplugSpecV0ClientMessage>(&self.validator, msg)? .iter() .cloned() .map(|m| m.into()) .collect() } ButtplugMessageSpecVersion::Version1 => { ...
call_expression
[ { "content": "pub trait ButtplugMessageSerializer: Default + Sync + Send {\n\n type Inbound;\n\n type Outbound;\n\n fn deserialize(\n\n &self,\n\n msg: ButtplugSerializedMessage,\n\n ) -> ButtplugSerializerResult<Vec<Self::Inbound>>;\n\n fn serialize(&self, msg: Vec<Self::Outbound>) -> ButtplugSerial...
Rust
src/main.rs
Demiu/WarehouseSourceGenerator
f752879e51193a2e35f4997bc63bf4348deb057d
mod employee; mod feeding_report; mod headcount_report; mod health_report; mod herd; mod livestock; mod pasture; mod snapshot; mod species; mod warehouse; use crate::pasture::*; use crate::snapshot::*; use crate::species::*; use crate::warehouse::*; use chrono::{Duration, Local}; use enum_map::enum_map; fn main() { ...
mod employee; mod feeding_report; mod headcount_report; mod health_report; mod herd; mod livestock; mod pasture; mod snapshot; mod species; mod warehouse; use crate::pasture::*; use crate::snapshot::*; use crate::species::*; use crate::warehouse::*; use chrono::{Duration, Local}; use enum_map::enum_map; fn main() { ...
SpeciesKind::Animal, 304, Some(SpeciesAreaRequirements { pasture_kind_to_req_area: enum_map! { PastureKind::Open => 7.5, PastureKind::Covered => 6., PastureKind::Individual => 3., }, }), ...
function_block-function_prefix_line
[ { "content": "pub fn expand_herd_vec(\n\n herds: &mut Vec<Herd>,\n\n pastures: &[Pasture],\n\n species: &[Species],\n\n species_idxs: &[usize],\n\n) {\n\n let mut rng = rand::thread_rng();\n\n let species_idxs_distribution = Slice::new(species_idxs).unwrap();\n\n\n\n for pasture in pastures...
Rust
underscore_util/src/emitter.rs
Lapz/underscore
cc2efbcffb4d63245c74338ea9b314881df18d92
use ansi_term::Colour::{Blue, Fixed, Red, Yellow}; use pos::Span; use pos::EMPTYSPAN; use std::cell::RefCell; use std::fmt::{self, Display}; use std::iter::repeat; use std::rc::Rc; #[derive(Debug)] pub struct Diagnostic { msg: String, level: Level, span: Span, } #[derive(Debug, PartialEq)] pub enum Level...
use ansi_term::Colour::{Blue, Fixed, Red, Yellow}; use pos::Span; use pos::EMPTYSPAN; use std::cell::RefCell; use std::fmt::{self, Display}; use std::iter::repeat; use std::rc::Rc; #[derive(Debug)] pub struct Diagnostic { msg: String, level: Level, span: Span, } #[derive(Debug, PartialEq)] pub enum Level...
pub fn emit(&self, input: &str) { for diagnostic in self.diagnostics.borrow().iter() { print(input, diagnostic) } } } pub fn print(input: &str, d: &Diagnostic) { match *d { Diagnostic { ref msg, ref span, ref level, } => { ...
pub fn warn(&self, msg: &str, span: Span) { self.diagnostics.borrow_mut().push(Diagnostic { msg: msg.into(), span, level: Level::Warn, }) }
function_block-full_function
[ { "content": "pub fn new_named_label<T: Clone>(name: &str, symbols: &mut Symbols<T>) -> Symbol {\n\n unsafe {\n\n let label = symbols.symbol(&format!(\"l_{}_{}\", name, LABEL_COUNT));\n\n\n\n LABEL_COUNT += 1;\n\n label\n\n }\n\n}\n\n\n", "file_path": "underscore_ir/src/ir.rs", ...
Rust
boards/rp-pico/examples/pico_uart_irq_buffer.rs
astraw/rp-hal
f8de8755ccf82a782c9430c343afa8daea671b24
#![no_std] #![no_main] use embedded_hal::{digital::v2::OutputPin, serial::Write as UartWrite}; use embedded_time::fixed_point::FixedPoint; use core::fmt::Write; use rp2040_hal::Clock; use cortex_m_rt::entry; use panic_halt as _; use rp2040_hal as hal; use hal::pac; use pac::interrupt; use core::cell::RefCel...
#![no_std] #![no_main] use embedded_hal::{digital::v2::OutputPin, serial::Write as UartWrite}; use embedded_time::fixed_point::FixedPoint; use core::fmt::Write; use rp2040_hal::Clock; use cortex_m_rt::entry; use panic_halt as _; use rp2040_hal as hal; use hal::pac; use pac::interrupt; use core::cell::RefCel...
impl UartQueue { fn read_byte(&self) -> Option<u8> { cortex_m::interrupt::free(|cs| { let cell_queue = self.mutex_cell_queue.borrow(cs); let mut queue = cell_queue.borrow_mut(); queue.dequeue() }) } fn peek_byte(&self) -> Option<u8> { ...
fn main() -> ! { let mut pac = pac::Peripherals::take().unwrap(); let core = pac::CorePeripherals::take().unwrap(); let mut watchdog = hal::Watchdog::new(pac.WATCHDOG); let clocks = hal::clocks::init_clocks_and_plls( XTAL_FREQ_HZ, pac.XOSC, pac.CLOCKS, pa...
function_block-full_function
[ { "content": "/// Alias the type for our UART to make things clearer.\n\ntype Uart = hal::uart::UartPeripheral<hal::uart::Enabled, pac::UART0, UartPins>;\n\n\n\n/// External high-speed crystal on the Raspberry Pi Pico board is 12 MHz. Adjust\n\n/// if your board has a different frequency\n\nconst XTAL_FREQ_HZ: ...
Rust
crates/parser/src/event.rs
adamrk/rust-analyzer
04f03a360ab8fef3d9c0ff84de2d39b8a196c717
use std::mem; use crate::{ ParseError, SyntaxKind::{self, *}, TreeSink, }; #[derive(Debug)] pub(crate) enum Event { ...
use std::mem; use crate::{ ParseError, SyntaxKind::{self, *}, TreeSink, }; #[derive(Debug)] pub(crate) enum Event { ...
sink.start_node(kind); } } } Event::Finish => sink.finish_node(), Event::Token { kind, n_raw_tokens } => { sink.token(kind, n_raw_tokens); } Event::Error { msg } => sink.error(msg), ...
msg: ParseError, }, } impl Event { pub(crate) fn tombstone() -> Self { Event::Start { kind: TOMBSTONE, forward_parent: None } } } pub(super) fn process(sink: &mut dyn TreeSink, mut events: Vec<Event>) { let mut forward_parents = Vec::new(); for i in 0..events.len() { match mem::re...
random
[ { "content": "pub fn token(kind: SyntaxKind) -> SyntaxToken {\n\n tokens::SOURCE_FILE\n\n .tree()\n\n .syntax()\n\n .clone_for_update()\n\n .descendants_with_tokens()\n\n .filter_map(|it| it.into_token())\n\n .find(|it| it.kind() == kind)\n\n .unwrap_or_else(|...
Rust
account-decoder/src/parse_token.rs
im-0/solana
ccf2a05c8d16a24a9d111e85db5f3bc4f4a1ef9c
use crate::{ parse_account_data::{ParsableAccount, ParseAccountError}, StringAmount, StringDecimals, }; use solana_sdk::pubkey::Pubkey; use spl_token_v2_0::{ solana_program::{ program_option::COption, program_pack::Pack, pubkey::Pubkey as SplTokenPubkey, }, state::{Account, AccountState, Min...
use crate::{ parse_account_data::{ParsableAccount, ParseAccountError}, StringAmount, StringDecimals, }; use solana_sdk::pubkey::Pubkey; use spl_token_v2_0::{ solana_program::{ program_option::COption, program_pack::Pack, pubkey::Pubkey as SplTokenPubkey, }, state::{Account, AccountState, Min...
#[test] fn test_ui_token_amount_real_string() { assert_eq!(&real_number_string(1, 0), "1"); assert_eq!(&real_number_string_trimmed(1, 0), "1"); let token_amount = token_amount_to_ui_amount(1, 0); assert_eq!( token_amount.ui_amount_string, real_number_str...
ubkey = SplTokenPubkey::new(&[2; 32]); let mut account_data = vec![0; Account::get_packed_len()]; let mut account = Account::unpack_unchecked(&account_data).unwrap(); account.mint = mint_pubkey; Account::pack(account, &mut account_data).unwrap(); let expected_mint_pubkey = Pubke...
function_block-function_prefixed
[ { "content": "pub fn append_u8(buf: &mut Vec<u8>, data: u8) {\n\n let start = buf.len();\n\n buf.resize(buf.len() + 1, 0);\n\n buf[start] = data;\n\n}\n\n\n", "file_path": "sdk/program/src/serialize_utils.rs", "rank": 1, "score": 489205.7145107128 }, { "content": "pub fn spl_token_a...
Rust
src/kernel/shape/topology.rs
therealprof/Fornjot
9b90402384a0ff8cf4896e40d1bfdd21331cd1bd
use std::collections::HashSet; use tracing::warn; use crate::{ debug::DebugInfo, kernel::{ geometry::{Circle, Curve, Line}, topology::{ edges::{Cycle, Edge}, faces::Face, vertices::Vertex, }, }, math::{Point, Scalar, Triangle, Vector}, }; us...
use std::collections::HashSet; use tracing::warn; use crate::{ debug::DebugInfo, kernel::{ geometry::{Circle, Curve, Line}, topology::{ edges::{Cycle, Edge}, faces::Face, vertices::Vertex, }, }, math::{Point, Scalar, Triangle, Vector}, }; us...
; } } let storage = Storage::new(face); let handle = storage.handle(); self.faces.push(storage); Ok(handle) } pub fn vertices(&self) -> impl Iterator<Item = Handle<Vertex>> + '_ { self.vertices.iter().map(|storage| storage.handle()) ...
Err(ValidationError::Structural(( missing_surface, missing_cycles, )))
call_expression
[ { "content": "use crate::math::{Point, Transform, Vector};\n\n\n\n/// A line, defined by a point and a vector\n\n#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]\n\npub struct Line {\n\n /// The origin of the line's coordinate system\n\n pub origin: Point<3>,\n\n\n\n /// The directio...
Rust
src/lib.rs
thibran/ok_tup
0222261b2658d8a491fa65fe1b6127b9a9c91b57
#![warn(missing_docs)] /*! Create to convert a type which implements the[Optionaler](trait.Optionaler.html) trait into a single Option guarded tuple, using a macro. ## Examples From time to time we have to handle a lot of Optional values (containing different types), but procceding makes only sense when all variable...
#![warn(missing_docs)] /*! Create to convert a type which implements the[Optionaler](trait.Optionaler.html) trait into a single Option guarded tuple, using a macro. ## Examples From time to time we have to handle a lot of Optional values (containing different types), but procceding makes only sense when all variable...
#[test] fn test_from_pathbuf() { use std::ffi::OsStr; use std::path::PathBuf; let pb = PathBuf::from("hi"); let _foo: Option<(&OsStr,)> = ok_tup!(pb.file_stem()); } #[test] fn test_from_path() { use std::ffi::OsString; use std::path::Path; ...
fn test_ok_tup() { let a: Option<(_,)> = ok_tup!(Ok::<_, String>(1)); let a: Option<(_, _)> = ok_tup!(Ok::<_, String>(1), Some(2)); let a: Option<(_, _, _)> = ok_tup!(Some(1), Some(2), Some(3)); let a: Option<(i32, f32, u8, f64)> = ok_tup!(Some(1_i32), Some(2_f32), Some(3_u8)...
function_block-full_function
[ { "content": "# ok_tup\n\n\n\nCreate to convert a type which implements the `Optionaler` trait\n\ninto a single Option guarded tuple, using a macro.\n\n\n\nVersion: 0.2.1\n\n\n\n\n\n## Installation\n\n\n\nAdd to `Cargo.toml`:\n\n```toml\n\n[dependencies.ok_tup]\n\ngit = \"https://github.com/thibran/ok_tup.git\"...
Rust
utils/bitfield/tests/bitfield_tests.rs
dutterbutter/forest
43ae5cfa41a37f67afab5521cdca7472d0b327b6
use ahash::AHashSet; use bitfield::{bitfield, BitField}; use rand::{Rng, SeedableRng}; use rand_xorshift::XorShiftRng; use std::iter::FromIterator; fn random_indices(range: usize, seed: u64) -> Vec<usize> { let mut rng = XorShiftRng::seed_from_u64(seed); (0..range).filter(|_| rng.gen::<bool>()).collect() } ...
use ahash::AHashSet; use bitfield::{bitfield, BitField}; use rand::{Rng, SeedableRng}; use rand_xorshift::XorShiftRng; use std::iter::FromIterator; fn random_indices(range: usize, seed: u64) -> Vec<usize> { let mut rng = XorShiftRng::seed_from_u64(seed); (0..range).filter(|_| rng.gen::<bool>()).collect() } ...
let mut bf = BitField::new(); bf.set(1); bf.set(3); let cbor = encoding::to_vec(&bf).unwrap(); let deserialized: BitField = encoding::from_slice(&cbor).unwrap(); assert_eq!(deserialized, bf); }
function_block-function_prefix_line
[ { "content": "fn expect_error(rt: &mut MockRuntime, method_num: u64, ser: &Serialized, exp: ExitCode) {\n\n let err = rt.call(&*PAYCH_ACTOR_CODE_ID, method_num, ser).unwrap_err();\n\n assert_eq!(exp, err.exit_code());\n\n}\n\n\n", "file_path": "vm/actor/tests/paych_actor_test.rs", "rank": 1, "...
Rust
tests/basic.rs
IamTheCarl/pty-process
7bf8c35dfa835e70ad760aeaf9ce9c296b9f5f29
use pty_process::Command as _; #[cfg(feature = "backend-std")] #[test] fn test_cat_std() { use std::io::{Read as _, Write as _}; let (mut child, mut pty) = std::process::Command::new("cat") .spawn_pty(Some(&pty_process::Size::new(24, 80))) .unwrap(); pty.write_all(b"foo\n").unwrap(); ...
use pty_process::Command as _; #[cfg(feature = "backend-std")] #[test] fn test_cat_std() { use std::io::{Read as _, Write as _}; let (mut child, mut pty) = std::process::Command::new("cat") .spawn_pty(Some(&pty_process::Size::new(24, 80))) .unwrap(); pty.write_all(b"foo\n").unwrap(); ...
o() { let mut child = tokio::process::Command::new("cat") .spawn_pty(Some(&pty_process::Size::new(24, 80))) .unwrap(); child.pty_mut().write_all(b"foo\n").await.unwrap(); tokio::time::sleep(std::time::Duration::from_s...
function_block-function_prefixed
[ { "content": "#[cfg(feature = \"backend-std\")]\n\n#[test]\n\nfn test_winch() {\n\n let (mut child, mut pty) = std::process::Command::new(\"perl\")\n\n .args(&[\n\n \"-E\",\n\n \"$|++; $SIG{WINCH} = sub { say 'WINCH' }; say 'started'; <>\",\n\n ])\n\n .spawn_pty(Som...
Rust
src/imxrt101/instances/snvs.rs
imxrt-rs/imxrt-ral
5db4eaa8bf96cb1971b5a3f52734f2449876a715
#![allow(non_snake_case, non_upper_case_globals)] #![allow(non_camel_case_types)] #[cfg(not(feature = "nosync"))] pub use crate::imxrt101::peripherals::snvs::Instance; pub use crate::imxrt101::peripherals::snvs::{ LPGPR0_legacy_alias, LPGPR_alias0, LPGPR_alias1, LPGPR_alias2, LPGPR_alias3, HPCOMR, HPCR, HPHACI...
#![allow(non_snake_case, non_upper_case_globals)] #![allow(non_camel_case_types)] #[cfg(not(feature = "nosync"))] pub use crate::imxrt101::peripherals::snvs::Instance; pub use crate::imxrt101::peripherals::snvs::{ LPGPR0_legacy_alias, LPGPR_alias0, LPGPR_alias1, LPGPR_alias2, LPGPR_alias3, HPCOMR, HPCR, HPHACI...
#[cfg(not(feature = "nosync"))] #[allow(renamed_and_removed_lints)] #[allow(private_no_mangle_statics)] #[no_mangle] static SNVS_TAKEN: AtomicBool = AtomicBool::new(false); #[cfg(not(feature = "nosync"))] #[inline] pub fn take...
00000000, LPSMCMR: 0x00000000, LPSMCLR: 0x00000000, LPPGDR: 0x00000000, LPGPR0_legacy_alias: 0x00000000, LPZMKR0: 0x00000000, LPZMKR1: 0x00000000, LPZMKR2: 0x00000000, LPZMKR3: 0x00000000, LPZMKR4: 0x00000000, LPZMKR5: 0x00000000, L...
random
[ { "content": "pub mod tmr;\n\n\n\n#[cfg(any(feature = \"doc\", feature = \"imxrt1051\", feature = \"imxrt1052\"))]\n\npub mod gpt;\n\n\n\n#[cfg(any(feature = \"doc\", feature = \"imxrt1051\", feature = \"imxrt1052\"))]\n\npub mod ocotp;\n\n\n\n#[cfg(any(feature = \"doc\", feature = \"imxrt1051\", feature = \"im...
Rust
poly/src/domain/general.rs
Pratyush/algebra
902c8c2882a8aa6f87395df888b50090e2705cac
pub use crate::domain::utils::Elements; use crate::domain::{ DomainCoeff, EvaluationDomain, MixedRadixEvaluationDomain, Radix2EvaluationDomain, }; use ark_ff::{FftField, FftParameters}; use ark_std::vec::Vec; #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] pub enum GeneralEvaluationDomain<F: FftField> { ...
pub use crate::domain::utils::Elements; use crate::domain::{ DomainCoeff, EvaluationDomain, MixedRadixEvaluationDomain, Radix2EvaluationDomain, }; use ark_ff::{FftField, FftParameters}; use ark_std::vec::Vec; #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] pub enum GeneralEvaluationDomain<F: FftField> { ...
}
0 { let size = 1 << coeffs; let domain = GeneralEvaluationDomain::<Fr>::new(size).unwrap(); let domain_size = domain.size(); assert_eq!(domain_size, domain.elements().count()); } }
function_block-function_prefixed
[ { "content": "/// Types that can be FFT-ed must implement this trait.\n\npub trait DomainCoeff<F: FftField>:\n\n Copy\n\n + Send\n\n + Sync\n\n + core::ops::AddAssign\n\n + core::ops::SubAssign\n\n + ark_ff::Zero\n\n + core::ops::MulAssign<F>\n\n{\n\n}\n\n\n\nimpl<T, F> DomainCoeff<F> for T...
Rust
src/control/destination/mod.rs
huanwei/linkerd2-proxy
baf7b55090bf133f13c8b89fca77c0c24c2f53d3
use futures::{ future, sync::mpsc, Async, Future, Poll, Stream }; use indexmap::IndexMap; use std::fmt; use std::sync::{Arc, Weak}; use tower_http::HttpService; use tower_grpc::{Body, BoxBody}; use dns; use transport::tls; use proxy::resolve::{self, Resolve, Update}; pub mod background; use...
use futures::{ future, sync::mpsc, Async, Future, Poll, Stream }; use indexmap::IndexMap; use std::fmt; use std::sync::{Arc, Weak}; use tower_http::HttpService; use tower_grpc::{Body, BoxBody}; use dns; use transport::tls; use proxy::resolve::{self, Resolve, Update}; pub mod background; use...
impl Resolve<NameAddr> for Resolver { type Endpoint = Metadata; type Resolution = Resolution; fn resolve(&self, authority: &NameAddr) -> Resolution { trace!("resolve; authority={:?}", authority); let (update_tx, update_rx) = mpsc::unbounded(); let active = Arc::new(()); ...
mut client: Option<T>, dns_resolver: dns::Resolver, namespaces: Namespaces, suffixes: Vec<dns::Suffix>, concurrency_limit: usize, ) -> (Resolver, impl Future<Item = (), Error = ()>) where T: HttpService<BoxBody>, T::ResponseBody: Body, T::Error: fmt::Debug, { let (request_tx, rx) = mpsc:...
function_block-function_prefix_line
[ { "content": "/// The Rust test runner creates a thread per unit test, naming it after\n\n/// the function name. If still in that thread, this can be useful to allow\n\n/// associating test logs with a specific test, since tests *can* be run in\n\n/// parallel.\n\npub fn thread_name() -> String {\n\n ::std::...
Rust
futures-util/src/stream/stream/peek.rs
betamos/futures-rs
0ae6d1ead3c04ee5340544372a047e21675a643b
use crate::stream::{Fuse, StreamExt}; use core::fmt; use core::pin::Pin; use futures_core::future::{FusedFuture, Future}; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project;...
use crate::stream::{Fuse, StreamExt}; use core::fmt; use core::pin::Pin; use futures_core::future::{FusedFuture, Future}; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project;...
} impl<St: Stream> FusedStream for Peekable<St> { fn is_terminated(&self) -> bool { self.peeked.is_none() && self.stream.is_terminated() } } impl<S: Stream> Stream for Peekable<S> { type Item = S::Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { ...
pub fn poll_peek( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<&St::Item>> { let mut this = self.project(); Poll::Ready(loop { if this.peeked.is_some() { break this.peeked.as_ref(); } else if let Some(item) = ready!(this.stream...
function_block-full_function
[ { "content": "/// Creates an instance of a writer which will successfully consume all data.\n\n///\n\n/// All calls to `poll_write` on the returned instance will return `Poll::Ready(Ok(buf.len()))`\n\n/// and the contents of the buffer will not be inspected.\n\n///\n\n/// # Examples\n\n///\n\n/// ```rust\n\n///...
Rust
src/storage/raw/store.rs
lroolle/tikv
f3f02d7fc6cf7e94abcf8cdb9b9ff52b110a72ba
use super::ttl::TTLSnapshot; use crate::storage::kv::{Cursor, Iterator, ScanMode, Snapshot}; use crate::storage::Statistics; use crate::storage::{Error, Result}; use engine_traits::{CfName, IterOptions, CF_DEFAULT, DATA_KEY_PREFIX_LEN}; use kvproto::kvrpcpb::KeyRange; use std::time::Duration; use tikv_util::time::I...
use super::ttl::TTLSnapshot; use crate::storage::kv::{Cursor, Iterator, ScanMode, Snapshot}; use crate::storage::Statistics; use crate::storage::{Error, Result}; use engine_traits::{CfName, IterOptions, CF_DEFAULT, DATA_KEY_PREFIX_LEN}; use kvproto::kvrpcpb::KeyRange; use std::time::Duration; use tikv_util::time::I...
pub async fn reverse_raw_scan( &'a self, cf: CfName, start_key: &'a Key, end_key: Option<&'a Key>, limit: usize, statistics: &'a mut Statistics, key_only: bool, ) -> Result<Vec<Result<KvPair>>> { let mut option = IterOptions::default(); i...
pub async fn forward_raw_scan( &'a self, cf: CfName, start_key: &'a Key, end_key: Option<&'a Key>, limit: usize, statistics: &'a mut Statistics, key_only: bool, ) -> Result<Vec<Result<KvPair>>> { let mut option = IterOptions::default(); if let ...
function_block-full_function
[ { "content": "// A helper function to copy snapshot.\n\n// Only used in tests.\n\npub fn copy_snapshot(mut from: Box<Snapshot>, mut to: Box<Snapshot>) -> io::Result<()> {\n\n if !to.exists() {\n\n io::copy(&mut from, &mut to)?;\n\n to.save()?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path"...
Rust
day09/src/main.rs
fabienjuif/advent-of-code-2018
de6da62c272493dbd959ab863bc10b5842e8c202
use std::collections::HashMap; use std::fs; use regex::Regex; const FILE_NAME: &str = "./input.txt"; #[derive(Debug)] struct Player { id: i64, score: i64, } #[derive(Clone, Debug, Default)] struct Marble { id: i64, next: Option<i64>, previous: Option<i64>, } #[derive(Default, Debug)] struct Pl...
use std::collections::HashMap; use std::fs; use regex::Regex; const FILE_NAME: &str = "./input.txt"; #[derive(Debug)] struct Player { id: i64, score: i64, } #[derive(Clone, Debug, Default)] struct Marble { id: i64, next: Option<i64>, previous: Option<i64>, } #[derive(Default, Debug)] struct Pl...
fn rearange(&mut self, mut marble: Marble, next: i64, previous: i64) -> Marble { marble.next = Some(next); marble.previous = Some(previous); let next_marble = self.marbles.get_mut(&next).unwrap(); next_marble.previous = Some(marble.id); let next_marble = self.marbles.get_...
fn create (last_marble: i64) -> Playground { Playground { last_marble, current_marble: -1, ..Playground::default() } }
function_block-full_function
[ { "content": "fn print_score(pots: String, patterns: &[(&str, &str)], generations: i64) {\n\n let mut pots = String::from(pots);\n\n\n\n let mut negative_offset = 0;\n\n for _ in 0..generations {\n\n // pushing values so pattern will work\n\n while !pots.starts_with(\".....\") {\n\n ...
Rust
sdk/schemas/src/json_ser.rs
StevenBlack/aws-sdk-rust
f4a1458f0154318c47d7e6a4ac55226f400fbfbc
pub fn serialize_structure_crate_input_create_discoverer_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateDiscovererInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if input.cross_account { object.key("CrossAccount").boolean(input...
pub fn serialize_structure_crate_input_create_discoverer_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateDiscovererInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if input.cross_account { object.key("CrossAccount").boolean(input...
").boolean(input.cross_account); } if let Some(var_29) = &input.description { object.key("Description").string(var_29.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_update_registry_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::Upda...
y_http::operation::SerializationError> { if let Some(var_23) = &input.policy { object.key("Policy").string(var_23.as_str()); } if let Some(var_24) = &input.revision_id { object.key("RevisionId").string(var_24.as_str()); } Ok(()) } pub fn serialize_structure_crate_input_tag_resource_...
random
[]
Rust
sudo_plugin/src/plugin/io_plugin.rs
jdtw/sudo_pair
3961adffa7bf5eb4bc8ba475b161d021361c82ce
use super::IoEnv; use crate::errors::SudoError; #[warn(clippy::missing_inline_in_public_items)] pub trait IoPlugin: 'static + Sized { type Error: SudoError; const NAME: &'static str; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); ...
use super::IoEnv; use crate::errors::SudoError; #[warn(clippy::missing_inline_in_public_items)] pub trait IoPlugin: 'static + Sized { type Error: SudoError; const NAME: &'static str; const VERSION: &'static str = env!("CARGO_PKG_VERSION"); ...
fn open(env: &'static IoEnv) -> Result<Self, Self::Error>; #[inline] fn close(self, _exit_status: i32, _error: i32) {} #[inline] fn log_ttyin(&self, _l...
n!( env.stdout(), "{} I/O plugin version {}", Self::NAME, Self::VERSION, ); }
function_block-function_prefixed
[ { "content": "#[cfg(feature = \"journald\")]\n\nfn slog(name: &str, version: &str) -> slog::Logger {\n\n use slog::Drain;\n\n\n\n let drain = slog_journald::JournaldDrain.ignore_res();\n\n\n\n slog::Logger::root(drain, slog::o!(\n\n \"plugin_name\" => name .to_owned(),\n\n \"plugin_v...
Rust
examples/touch.rs
conorpp/lpc55-hal
6447938cdf4696bf729eaa585a85be62d0908b16
#![no_main] #![no_std] extern crate panic_semihosting; #[macro_use(block)] extern crate nb; use cortex_m_rt::entry; use lpc55_hal as hal; use hal::prelude::*; use hal::{ drivers::{ Pins, Timer, touch::{ TouchSensorChannel, TouchSensor, ButtonPins, ...
#![no_main] #![no_std] extern crate panic_semihosting; #[macro_use(block)] extern crate nb; use cortex_m_rt::entry; use lpc55_hal as hal; use hal::prelude::*; use hal::{ drivers::{ Pins, Timer, touch::{ TouchSensorChannel, TouchSensor, ButtonPins, ...
fn main() -> ! { let mut hal = hal::new(); let clocks = hal::ClockRequirements::default() .system_frequency(96.MHz()) .configure(&mut hal.anactrl, &mut hal.pmc, &mut hal.syscon) .unwrap(); let fro_token = clocks.support_1mhz_fro_token().unwrap(); let touch_token = clocks.suppo...
function_block-full_function
[ { "content": "/// Used when debugging to correlate the sync timer to which sample in the circular buffer is newest\n\npub fn profile_touch_sensing(touch_sensor: &mut TouchSensor<impl PinId, impl PinId, impl PinId>,\n\n delay_timer: &mut timer::Timer<impl ctimer::Ctimer<init_state::En...