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
cargo-insta/src/cargo.rs
kper/insta
af80738eeed30b730047ba87953b9d4ecc9d1f02
use std::collections::HashSet; use std::env; use std::error::Error; use std::fs; use std::path::{Path, PathBuf}; use std::process; use ignore::overrides::OverrideBuilder; use ignore::{DirEntry, WalkBuilder}; use insta::{PendingInlineSnapshot, Snapshot}; use serde::Deserialize; use crate::inline::FilePatcher; use crat...
use std::collections::HashSet; use std::env; use std::error::Error; use std::fs; use std::path::{Path, PathBuf}; use std::process; use ignore::overrides::OverrideBuilder; use ignore::{DirEntry, WalkBuilder}; use insta::{PendingInlineSnapshot, Snapshot}; use serde::Deserialize; use crate::inline::FilePatcher; use crat...
fn get_default_manifest() -> Result<Option<PathBuf>, Box<dyn Error>> { let output = process::Command::new(get_cargo()) .arg("locate-project") .output()?; if output.status.success() { let loc: ProjectLocation = serde_json::from_slice(&output.stdout)?; Ok(Some(loc.root)) } el...
let output = cmd.output()?; if !output.status.success() { let msg = String::from_utf8_lossy(&output.stderr); return Err(err_msg(format!( "cargo erroried getting metadata: {}", msg.trim() ))); } Ok(serde_json::from_slice(&output.stdout)?) }
function_block-function_prefix_line
[ { "content": "fn generate_snapshot_name_for_thread(module_path: &str) -> Result<String, &'static str> {\n\n let thread = thread::current();\n\n #[allow(unused_mut)]\n\n let mut name = Cow::Borrowed(\n\n thread\n\n .name()\n\n .ok_or(\"test thread is unnamed, no snapshot nam...
Rust
src/delay.rs
Rahix/atmega32u4-hal
5434aa22d34dfa7804b0ebe07285edf20a6516d1
use hal::blocking::delay; use core::marker; pub struct Delay<SPEED> { _speed: marker::PhantomData<SPEED>, } impl<SPEED> Delay<SPEED> { pub fn new() -> Delay<SPEED> { Delay { _speed: marker::PhantomData } } } pub struct MHz24; pub struct MHz20; pub struct MHz16; pub struct MHz1...
use hal::blocking::delay; use core::marker; pub struct Delay<SPEED> { _speed: marker::PhantomData<SPEED>, } impl<SPEED> Delay<SPEED> { pub fn new() -> Delay<SPEED> { Delay { _speed: marker::PhantomData } } } pub struct MHz24; pub struct MHz20; pub struct MHz16; pub struct MHz1...
xfff); } } } impl<SPEED> delay::DelayMs<u16> for Delay<SPEED> where Delay<SPEED>: delay::DelayUs<u32>, { fn delay_ms(&mut self, ms: u16) { delay::DelayUs::<u32>::delay_us(self, ms as u32 * 1000); } }
ED>: delay::DelayUs<u16>, { fn delay_us(&mut self, us: u32) { for _ in 0..(us >> 12) { delay::DelayUs::<u16>::delay_us(self, 0
random
[ { "content": " /// Any digital IO mode\n\n pub trait Io {}\n\n\n\n /// Digital IO modes\n\n pub mod io {\n\n use core::marker;\n\n\n\n /// Input\n\n pub struct Input<MODE> {\n\n _mode: marker::PhantomData<MODE>,\n\n }\n\n /// Output\n\n pub struct...
Rust
src/lib.rs
rustkas/Longest-Common-Substring-Problem
ea311603260d0e8709530265a116485dec7b5714
#![feature(type_ascription)] use std::borrow::Cow; use std::collections::HashMap; use std::str::Chars; pub fn longest_substring(input: &str) -> Cow<str> { let length: usize = input.len(); if length <= 2 { return input.into(); } find_max_string(input) } pub fn find_max_string(input: &str) ->...
#![feature(type_ascription)] use std::borrow::Cow; use std::collections::HashMap; use std::str::Chars; pub fn longest_substring(input: &str) -> Cow<str> { let length: usize = input.len(); if length <= 2 { return input.into(); } find_max_string(input) } pub fn find_max_string(input: &str) ->...
pub fn make_string_info(input: &str) -> HashMap<char, Vec<usize>> { let chars: Chars = input.chars(); let mut string_info: HashMap<char, Vec<usize>> = HashMap::new(); for (i, item) in chars.enumerate() { if string_info.contains_key(&item) { if let Some(inner_vector) = string_info.get_...
if chars_info_len == key_index + 1 { break; } let mut iterator2 = keys_vector.iter().skip(key_index + 1); let mut iterator2_key = iterator2.next(); while let Some(char_key_value2) = iterator2_key { current_string = create_max_string(*char_key_value1,...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let input_string = \"abacadaddaad\";\n\n let longest_string = longest_substring(input_string);\n\n println!(\"The input string is '{}'\", input_string);\n\n println!(\n\n \"The longest string is '{}'. Length = {}\",\n\n longest_string,\n\n longest_s...
Rust
src/common/os_input_output.rs
tlinford/zellij
845211c1eebdbc6d063cf30de23135cff1582084
use crate::panes::PositionAndSize; use crate::utils::shared::{default_palette, detect_theme, hex_to_rgb}; use nix::fcntl::{fcntl, FcntlArg, OFlag}; use nix::pty::{forkpty, Winsize}; use nix::sys::signal::{kill, Signal}; use nix::sys::termios; use nix::sys::wait::waitpid; use nix::unistd; use nix::unistd::{ForkResult, P...
use crate::panes::PositionAndSize; use crate::utils::shared::{default_palette, detect_theme, hex_to_rgb}; use nix::fcntl::{fcntl, FcntlArg, OFlag}; use nix::pty::{forkpty, Winsize}; use nix::sys::signal::{kill, Signal}; use nix::sys::termios; use nix::sys::wait::waitpid; use nix::unistd; use nix::unistd::{ForkResult, P...
} impl Clone for Box<dyn OsApi> { fn clone(&self) -> Box<dyn OsApi> { self.box_clone() } } pub fn get_os_input() -> OsInputOutput { let current_termios = termios::tcgetattr(0).unwrap(); let orig_termios = Arc::new(Mutex::new(current_termios)); OsInputOutput { orig_termios } }
fn load_palette(&self) -> Palette { let palette = match Colors::new("xresources") { Some(palette) => { let fg = if let Some(foreground) = palette.fg.as_deref().map(hex_to_rgb) { foreground } else { return default_palette(); ...
function_block-full_function
[ { "content": "pub fn debug_to_file(message: u8, pid: RawFd) -> io::Result<()> {\n\n let mut path = PathBuf::new();\n\n path.push(ZELLIJ_TMP_LOG_DIR);\n\n path.push(format!(\"zellij-{}.log\", pid.to_string()));\n\n\n\n let mut file = fs::OpenOptions::new()\n\n .append(true)\n\n .create(...
Rust
src/rcc/pll.rs
L0uisc/stm32f2xx-hal
d594b2befc8a9fe22c839b9fd6a62cdb7f3920dd
use crate::pac::RCC; pub struct MainPll { pub use_pll: bool, pub pllsysclk: Option<u32>, pub pll48clk: Option<u32>, pub m: Option<u32>, pub plli2sclk: Option<u32>, } impl MainPll { pub fn fast_setup( pllsrcclk: u32, use_hse: bool, pllsysclk: Option<u32>, ...
use crate::pac::RCC; pub struct MainPll { pub use_pll: bool, pub pllsysclk: Option<u32>, pub pll48clk: Option<u32>, pub m: Option<u32>, pub plli2sclk: Option<u32>, } impl MainPll { pub fn fast_setup( pllsrcclk: u32, use_hse: bool, pllsysclk: Option<u32>, ...
!(100_000_000..=432_000_000).contains(&vco_out) { return None; } let output = vco_out / outdiv; let error = (output as i32 - target as i32).abs() as u32; Some((n, outdiv, output, error)) }) .min_by_key(|(_, _, _...
e( pllsrcclk: u32, m: u32, target: u32, min_div: u32, max_div: u32, ) -> Option<(SingleOutputPll, u32, u32)> { let vco_in = pllsrcclk / m; let (n, outdiv, output, error) = (min_div..=max_div) .filter_map(|outdiv| { ...
random
[ { "content": "// Two 32-bit registers (RTC_TR and RTC_DR) contain the seconds, minutes, hours (12- or 24-hour format), day (day\n\n// of week), date (day of month), month, and year, expressed in binary coded decimal format\n\n// (BCD). The sub-seconds value is also available in binary format.\n\n//\n\n// The fo...
Rust
src/instruments/switches/staircase_timer.rs
panicbit/metrix
0b19e09570e5cf7f714d03d60a39df7589d0dc77
use std::time::{Duration, Instant}; use crate::instruments::{ AcceptAllLabels, Instrument, InstrumentAdapter, LabelFilter, LabelPredicate, Update, Updates, }; use crate::snapshot::Snapshot; use crate::util; use crate::{Descriptive, PutsSnapshot}; use super::NameAlternation; pub struct StaircaseTimer { name: ...
use std::time::{Duration, Instant}; use crate::instruments::{ AcceptAllLabels, Instrument, InstrumentAdapter, LabelFilter, LabelPredicate, Update, Updates, }; use crate::snapshot::Snapshot; use crate::util; use crate::{Descriptive, PutsSnapshot}; use super::NameAlternation; pub struct StaircaseTimer { name: ...
pub fn adapter<L: Eq + Send + 'static>(self) -> InstrumentAdapter<L, Self> { InstrumentAdapter::deaf(self) } pub fn state(&self) -> bool { let value = if let Some(stay_on_until) = self.stay_on_until { stay_on_until >= Instant::now() } else { ...
pub fn for_labels_by_predicate<L, P>(self, label_predicate: P) -> InstrumentAdapter<L, Self> where L: Eq + Send + 'static, P: Fn(&L) -> bool + Send + 'static, { self.accept(LabelPredicate(label_predicate)) }
function_block-full_function
[ { "content": "/// Implementors are able to write their current data into given `Snapshot`.\n\n///\n\n/// Guidelines for writing snapshots:\n\n///\n\n/// * A `PutsSnapshot` that has a name should create a new sub snapshot\n\n/// and add its values there\n\n///\n\n/// * A `PutsSnapshot` that does not have a name ...
Rust
benches/generators.rs
drewm1980/rand
94078f44593534e2c1e6814a6904d9e7241d8dcb
#![feature(test)] #![allow(non_snake_case)] extern crate test; const RAND_BENCH_N: u64 = 1000; const BYTES_LEN: usize = 1024; use std::mem::size_of; use test::{black_box, Bencher}; use rand::prelude::*; use rand::rngs::adapter::ReseedingRng; use rand::rngs::{mock::StepRng, OsRng}; use rand_chacha::{ChaCha12Rng, C...
#![feature(test)] #![allow(non_snake_case)] extern crate test; const RAND_BENCH_N: u64 = 1000; const BYTES_LEN: usize = 1024; use std::mem::size_of; use test::{black_box, Bencher}; use rand::prelude::*; use rand::rngs::adapter::ReseedingRng; use rand::rngs::{mock::StepRng, OsRng}; use rand_chacha::{ChaCha12Rng, C...
en!(init_pcg32, Pcg32); init_gen!(init_pcg64, Pcg64); init_gen!(init_pcg64mcg, Pcg64Mcg); init_gen!(init_hc128, Hc128Rng); init_gen!(init_chacha, ChaCha20Rng); const RESEEDING_BYTES_LEN: usize = 1024 * 1024; const RESEEDING_BENCH_N: u64 = 16; macro_rules! reseeding_bytes { ($fnn:ident, $thresh:expr) => { ...
ha20Rng::from_entropy()); gen_uint!(gen_u32_hc128, u32, Hc128Rng::from_entropy()); gen_uint!(gen_u32_std, u32, StdRng::from_entropy()); #[cfg(feature = "small_rng")] gen_uint!(gen_u32_small, u32, SmallRng::from_entropy()); gen_uint!(gen_u32_os, u32, OsRng); gen_uint!(gen_u64_step, u64, StepRng::new(0, 1)); gen_uint!(g...
random
[ { "content": "#[bench]\n\nfn gen_1kb_u64_gen_array(b: &mut Bencher) {\n\n let mut rng = Pcg64Mcg::from_rng(&mut thread_rng()).unwrap();\n\n b.iter(|| {\n\n // max supported array length is 32!\n\n let v: [[u64; 32]; 4] = rng.gen();\n\n v\n\n });\n\n b.bytes = 1024;\n\n}\n\n\n", ...
Rust
orchestrator/gbt/src/config.rs
puneet166/cosmos-gravity-bridge
012c940e0b81c972cfbbff3fe41e34b642d6585e
use crate::args::InitOpts; use clarity::PrivateKey as EthPrivateKey; use gravity_utils::types::GravityBridgeToolsConfig; use std::{ fs::{self, create_dir}, path::{Path, PathBuf}, process::exit, }; pub const CONFIG_NAME: &str = "config.toml"; pub const KEYS_NAME: &str = "keys.json"; pub const CONFIG_FOL...
use crate::args::InitOpts; use clarity::PrivateKey as EthPrivateKey; use gravity_utils::types::GravityBridgeToolsConfig; use std::{ fs::{self, create_dir}, path::{Path, PathBuf}, process::exit, }; pub const CONFIG_NAME: &str = "config.toml"; pub const KEYS_NAME: &str = "keys.json"; pub const CONFIG_FOL...
let keys = fs::read_to_string(keys_file).unwrap(); match toml::from_str(&keys) { Ok(v) => v, Err(e) => { error!("Invalid keys! {:?}", e); exit(1); } } } pub fn save_keys(home_dir: &Path, updated_keys: KeyStorage) { let config_file = home_dir.join(CONFIG...
if !keys_file.exists() { error!( "Keys file at {} not detected, use `gbt init` to generate a config.", keys_file.to_str().unwrap() ); exit(1); }
if_condition
[ { "content": "pub fn show_keys(home_dir: &Path, prefix: &str) {\n\n if !config_exists(&home_dir) {\n\n error!(\"Please run `gbt init` before running this command!\");\n\n exit(1);\n\n }\n\n let keys = load_keys(home_dir);\n\n match keys.orchestrator_phrase {\n\n Some(v) => {\n\n...
Rust
sdk/sagemakerfeaturestoreruntime/src/client.rs
nikolay-te/aws-sdk-rust
2d876939a722c7bf1d8fe3595756eabbd6703310
#[derive(std::fmt::Debug)] pub(crate) struct Handle<C = aws_hyper::DynConnector> { client: aws_hyper::Client<C>, conf: crate::Config, } #[derive(Clone, std::fmt::Debug)] pub struct Client<C = aws_hyper::DynConnector> { handle: std::sync::Arc<Handle<C>>, } impl<C> Client<C> { pub fn from_conf_conn(conf...
#[derive(std::fmt::Debug)] pub(crate) struct Handle<C = aws_hyper::DynConnector> { client: aws_hyper::Client<C>, conf: crate::Config, } #[derive(Clone, std::fmt::Debug)] pub struct Client<C = aws_hyper::DynConnector> { handle: std::sync::Arc<Handle<C>>, } impl<C> Client<C> { pub fn from_conf_conn(conf...
let op = input .make_operation(&self.handle.conf) .map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?; self.handle.client.call(op).await } pub fn feature_group_name(mut self, inp: impl Into<std::string::String>...
let input = self .inner .build() .map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
assignment_statement
[]
Rust
couchbase/src/api/bucket.rs
emliunix/couchbase-rs
d0e5acb6d2dff98fd2a93a48770275b32f6dcfc6
use crate::io::request::{PingRequest, Request, ViewRequest}; use crate::io::Core; use crate::{ Collection, CollectionManager, CouchbaseError, CouchbaseResult, ErrorContext, PingOptions, PingResult, Scope, ViewIndexManager, ViewOptions, ViewResult, }; use futures::channel::oneshot; use std::sync::Arc; #[derive(...
use crate::io::request::{PingRequest, Request, ViewRequest}; use crate::io::Core; use crate::{ Collection, CollectionManager, CouchbaseError, CouchbaseResult, ErrorContext, PingOptions, PingResult, Scope, ViewIndexManager, ViewOptions, ViewResult, }; use futures::channel::oneshot; use std::sync::Arc; #[derive(...
, ) -> CouchbaseResult<PingResult> { let options = unwrap_or_default!(options.into()); let (sender, receiver) = oneshot::channel(); self.core .send(Request::Ping(PingRequest { options, sender })); receiver.await.unwrap() } ...
b fn collection<S: Into<String>>(&self, name: S) -> Collection { Collection::new(self.core.clone(), name.into(), "".into(), self.name.clone()) } pub fn scope<S: Into<String>>(&self, name: S) -> Scope { Scope::new(self.core.clone(), name.into(), self.name.clone()) } ...
random
[ { "content": "/// Bucket manager Examples\n\n///\n\n/// This file shows how to manage buckets against the Cluster.\n\npub fn main() {\n\n env_logger::init();\n\n\n\n // Connect to the cluster with a connection string and credentials\n\n let cluster = Cluster::connect(\"couchbase://10.112.210.101\", \"A...
Rust
src/enc/bit_cost.rs
robjtede/rust-brotli
4d0a5613a48380cc569095b1e1559c30b2eed44d
#![allow(dead_code)] use core; use super::histogram::CostAccessors; use super::super::alloc::SliceWrapper; use super::util::{brotli_max_uint32_t, FastLog2, floatX, FastLog2u16}; #[cfg(feature="simd")] use packed_simd_2::IntoBits; use super::vectorization::{v256,v256i, Mem256i, sum8, cast_f32_to_i32, cast_i32_to_f32, l...
#![allow(dead_code)] use core; use super::histogram::CostAccessors; use super::super::alloc::SliceWrapper; use super::util::{brotli_max_uint32_t, FastLog2, floatX, FastLog2u16}; #[cfg(feature="simd")] use packed_simd_2::IntoBits; use super::vectorization::{v256,v256i, Mem256i, sum8, cast_f32_to_i32, cast_i32_to_f32, l...
const BROTLI_REPEAT_ZERO_CODE_LENGTH: usize = 17; const BROTLI_CODE_LENGTH_CODES: usize = BROTLI_REPEAT_ZERO_CODE_LENGTH + 1; /* use std::io::{self, Error, ErrorKind, Read, Write}; macro_rules! println_stderr( ($($val:tt)*) => { { writeln!(&mut ::std::io::stderr(), $($val)*).unwrap(); } } ); */ #[cf...
pub fn BitsEntropy(population: &[u32], size: usize) -> super::util::floatX { let mut sum: usize = 0; let mut retval: super::util::floatX = ShannonEntropy(population, size, &mut sum); if retval < sum as super::util::floatX { retval = sum as super::util::floatX; } retval }
function_block-function_prefix_line
[ { "content": "#[inline(always)]\n\npub fn CombineLengthCodes(inscode: u16, copycode: u16, use_last_distance: i32) -> u16 {\n\n let bits64: u16 = (copycode as (u32) & 0x7u32 | (inscode as (u32) & 0x7u32) << 3i32) as (u16);\n\n if use_last_distance != 0 && (inscode as (i32) < 8i32) && (copycode as (i32) < 16i32...
Rust
test-stand-infra/host-lib/src/assistant.rs
braun-embedded/lpc845-test-stand
b438aa6d038caa6ae422a45f1d51c21b4c997528
use std::time::{ Duration, Instant, }; use protocol::{ AssistantToHost, HostToAssistant, InputPin, OutputPin, UsartMode, pin, }; use crate::{ conn::{ Conn, ConnReceiveError, ConnSendError, }, pin::{ Pin, ReadLevelError, }, }; pub...
use std::time::{ Duration, Instant, }; use protocol::{ AssistantToHost, HostToAssistant, InputPin, OutputPin, UsartMode, pin, }; use crate::{ conn::{ Conn, ConnReceiveError, ConnSendError, }, pin::{ Pin, ReadLevelError, }, }; pub...
}; match &mut measurement { Some(measurement) => { measurement.min = Ord::min(measurement.min, period); measurement.max = Ord::max(measurement.max, period); } None => { measurement = Some( ...
onn .receive::<AssistantToHost>(timeout, &mut tmp) .map_err(|err| AssistantUsartWaitError::Receive(err))?; match message { AssistantToHost::UsartReceive { mode, data } if mode == expected_mode => { buf.e...
random
[ { "content": "#[test]\n\nfn it_should_start_a_transaction_using_dma() -> Result {\n\n let mut test_stand = TestStand::new()?;\n\n\n\n let data = 0x22;\n\n let timeout = Duration::from_millis(50);\n\n let reply = test_stand.target.start_spi_transaction_dma(data, timeout)?;\n\n\n\n assert_eq!(reply...
Rust
diesel/src/query_builder/update_statement/mod.rs
integer32llc/diesel
c3ad6ee3b3404d077bf0c9733989e95c338e430c
pub mod changeset; pub mod target; pub use self::changeset::{Changeset, AsChangeset}; pub use self::target::{UpdateTarget, IntoUpdateTarget}; use backend::Backend; use expression::{Expression, SelectableExpression, NonAggregate}; use query_builder::{Query, AsQuery, QueryFragment, QueryBuilder, BuildQueryResult}; use ...
pub mod changeset; pub mod target; pub use self::changeset::{Changeset, AsChangeset}; pub use self::target::{UpdateTarget, IntoUpdateTarget}; use backend::Backend; use expression::{Expression, SelectableExpression, NonAggregate}; use query_builder::{Query, AsQuery, QueryFragment, QueryBuilder, BuildQueryResult}; use ...
are no changes to save. This \ query cannot be built".into()) } out.push_sql("UPDATE "); try!(self.table.from_clause().to_sql(out)); out.push_sql(" SET "); try!(self.values.to_sql(out)); try!(self.where_clause.to_sql(out)); try!(self.return...
ryFragment<DB>, V: changeset::Changeset<DB>, Ret: QueryFragment<DB>, { fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult { if self.values.is_noop() { return Err("There
random
[ { "content": "/// Apps should not need to concern themselves with this trait.\n\npub trait Changeset<DB: Backend> {\n\n fn is_noop(&self) -> bool;\n\n fn to_sql(&self, out: &mut DB::QueryBuilder) -> BuildQueryResult;\n\n fn collect_binds(&self, out: &mut DB::BindCollector) -> QueryResult<()>;\n\n}\n\n\...
Rust
src/camera.rs
bvssvni/cam
6af4d4ebd6dbc88444cfc8d4c29f85d3c8dabfe0
use vecmath::{ Vector3, Matrix4, vec3_normalized_sub, vec3_cross, vec3_dot, }; use vecmath::col_mat4_mul as mul; use vecmath::traits::*; use quaternion::{Quaternion, rotate_vector}; pub fn model_view_projection<T: Float + Copy>( model: Matrix4<T>, view: Matrix4<T>, projection: Matrix4...
use vecmath::{ Vector3, Matrix4, vec3_normalized_sub, vec3_cross, vec3_dot, }; use vecmath::col_mat4_mul as mul; use vecmath::traits::*; use quaternion::{Quaternion, rotate_vector}; pub fn model_view_projection<T: Float + Copy>( model: Matrix4<T>, view: Matrix4<T>, projection: Matrix4...
pub fn set_rotation(&mut self, rotation: Quaternion<T>) { let _0: T = Zero::zero(); let _1: T = One::one(); let forward: Vector3<T> = [_0, _0, _1]; let up: Vector3<T> = [_0, _1, _0]; self.forward = rotate_vector(rotation, forward); self.up = rotate_vec...
pub fn set_yaw_pitch(&mut self, yaw: T, pitch: T) { let (y_s, y_c, p_s, p_c) = (yaw.sin(), yaw.cos(), pitch.sin(), pitch.cos()); self.forward = [y_s * p_c, p_s, y_c * p_c]; self.up = [y_s * -p_s, p_c, y_c * -p_s]; self.update_right(); }
function_block-full_function
[ { "content": "#![crate_name = \"cam\"]\n\n#![deny(missing_docs)]\n\n\n\n//! A library for 3D camera and navigation.\n\n\n\nextern crate vecmath;\n\nextern crate quaternion;\n\n\n\npub use camera::{\n\n Camera,\n\n CameraPerspective,\n\n model_view_projection,\n\n};\n\n\n\nmod camera;\n", "file_path...
Rust
compiler/rustc_builtin_macros/src/deriving/default.rs
mbc-git/rust
2c7bc5e33c25e29058cbafefe680da8d5e9220e9
use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use rustc_ast::ptr::P; use rustc_ast::walk_list; use rustc_ast::EnumDef; use rustc_ast::VariantData; use rustc_ast::{Expr, MetaItem}; use rustc_errors::Applicability; use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt}; use rustc_span::symbo...
use crate::deriving::generic::ty::*; use crate::deriving::generic::*; use rustc_ast::ptr::P; use rustc_ast::walk_list; use rustc_ast::EnumDef; use rustc_ast::VariantData; use rustc_ast::{Expr, MetaItem}; use rustc_errors::Applicability; use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt}; use rustc_span::symbo...
if let Err(()) = validate_default_attribute(cx, default_variant) { return DummyResult::raw_expr(trait_span, true); } cx.expr_path(cx.path( default_variant.span, vec![Ident::new(kw::SelfUpper, default_variant.span), default_variant.ident], )) } fn extract_defa...
let default_variant = match extract_default_variant(cx, enum_def, trait_span) { Ok(value) => value, Err(()) => return DummyResult::raw_expr(trait_span, true), };
assignment_statement
[]
Rust
communication/src/allocator/zero_copy/bytes_exchange.rs
longbinlai/timely-dataflow
c4cd70de107f12362745db3e8b68af5edc992ed8
use std::thread::Thread; use std::sync::{Arc, Mutex, RwLock}; use std::collections::VecDeque; use bytes::arc::Bytes; use super::bytes_slab::BytesSlab; pub trait BytesPush { fn extend<I: IntoIterator<Item=Bytes>>(&mut self, iter: I); } pub trait BytesPull { fn drain_into(&mut s...
use std::thread::Thread; use std::sync::{Arc, Mutex, RwLock}; use std::collections::VecDeque; use bytes::arc::Bytes; use super::bytes_slab::BytesSlab; pub trait BytesPush { fn extend<I: IntoIterator<Item=Bytes>>(&mut self, iter: I); } pub trait BytesPull { fn drain_into(&mut s...
} pub struct SendEndpoint<P: BytesPush> { send: P, buffer: BytesSlab, } impl<P: BytesPush> SendEndpoint<P> { fn send_buffer(&mut self) { let valid_len = self.buffer.valid().len(); if valid_len > 0 { self.send.extend(Some(self.buffer.extract(valid_len))); } } ...
fn drop(&mut self) { if ::std::thread::panicking() { self.panic.store(true, Ordering::SeqCst); } else { if self.panic.load(Ordering::SeqCst) { panic!("MergeQueue poisoned."); } } self.queue = Arc::new(Mutex::new(VecDeque::new...
function_block-full_function
[ { "content": "pub trait Queue {\n\n fn queue(&self) -> Self;\n\n}\n\n\n\nimpl<G: Scope, D: Data> Queue for Stream<G, D> {\n\n fn queue(&self) -> Stream<G, D> {\n\n let mut elements = HashMap::new();\n\n self.unary_notify(Pipeline, \"Queue\", vec![], move |input, output, notificator| {\n\n ...
Rust
src/server.rs
PyO3/tokio
639611517cb3a16d952cc6d0f0bc9094594de65c
use std::io; use std::net; use std::os::unix; use pyo3::*; use futures::{unsync, Async, Stream, Future, Poll}; use net2::TcpBuilder; use net2::unix::UnixTcpBuilderExt; use tokio_core::net::{TcpListener, Incoming}; use tokio_uds; use tokio_io::IoStream; use {PyFuture, TokioEventLoop}; use addrinfo; use pyunsafe; use so...
use std::io; use std::net; use std::os::unix; use pyo3::*; use futures::{unsync, Async, Stream, Future, Poll}; use net2::TcpBuilder; use net2::unix::UnixTcpBuilderExt; use tokio_core::net::{TcpListener, Incoming}; use tokio_uds; use tokio_io::IoStream; use {PyFuture, TokioEventLoop}; use addrinfo; use pyunsafe; use so...
}
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match self.stop.poll() { Ok(Async::Ready(_)) | Err(_) => { return Ok(Async::Ready(())) } Ok(Async::NotReady) => (), } let option = self.stream.poll()?; match option { ...
function_block-full_function
[ { "content": "pub fn register_classes(_py: pyo3::Python, m: &pyo3::PyModule) -> pyo3::PyResult<()> {\n\n m.add_class::<event_loop::TokioEventLoop>()?;\n\n m.add_class::<pytask::PyTask>()?;\n\n m.add_class::<pyfuture::PyFuture>()?;\n\n m.add_class::<pybytes::PyBytes>()?;\n\n m.add_class::<handle::...
Rust
src/world.rs
miZyind/singularity
d44d16f9e431d9adfead0df23b75a75f59aee5d3
use bevy::prelude::*; use bevy_rapier3d::{ physics::*, prelude::{ ColliderFlags, ColliderShape, InteractionGroups, RigidBodyActivation, RigidBodyPosition, RigidBodyType, }, }; use crate::constants; pub fn spawn( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut mate...
use bevy::prelude::*; use bevy_rapier3d::{ physics::*, prelude::{ ColliderFlags, ColliderShape, InteractionGroups, RigidBodyActivation, RigidBodyPosition, RigidBodyType, }, }; use crate::constants;
pub fn spawn( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, ) { let box_xz = 10.0; let box_y = 1.0; commands .spawn_bundle(PbrBundle { mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), materi...
function_block-full_function
[]
Rust
linkerd/service-profiles/src/proto.rs
mlycore/linkerd2-proxy
39a8ecda78f8d734ab7a353896ca3fb0cb615f6d
use crate::{http, LogicalAddr, Profile, Target}; use linkerd2_proxy_api::destination as api; use linkerd_addr::NameAddr; use linkerd_dns_name::Name; use linkerd_proxy_api_resolve::pb as resolve; use regex::Regex; use std::{str::FromStr, sync::Arc, time::Duration}; use tower::retry::budget::Budget; use tracing::warn; p...
use crate::{http, LogicalAddr, Profile, Target}; use linkerd2_proxy_api::destination as api; use linkerd_addr::NameAddr; use linkerd_dns_name::Name; use linkerd_proxy_api_resolve::pb as resolve; use regex::Regex; use std::{str::FromStr, sync::Arc, time::Duration}; use tower::retry::budget::Budget; use tracing::warn; p...
fn convert_retry_budget(orig: api::RetryBudget) -> Option<Arc<Budget>> { let min_retries = if orig.min_retries_per_second <= i32::MAX as u32 { orig.min_retries_per_second } else { warn!( "retry_budget min_retries_per_second overflow: {:?}", orig.min_retries_per_second ...
fn convert_rsp_match(orig: api::ResponseMatch) -> Option<http::ResponseMatch> { let m = match orig.r#match? { api::response_match::Match::All(ms) => { let ms = ms .matches .into_iter() .filter_map(convert_rsp_match) .collect::<Vec<_...
function_block-full_function
[]
Rust
src/matrix-rocketchat/api/rest_api.rs
mciverza/matrix-rocketchat
64d18fd5969c7afcf348971e1dd61ea21963aec5
use std::collections::HashMap; use std::io::Read; use http::{HeaderMap, Method, StatusCode}; use reqwest::multipart::Form; use reqwest::{Body, Client, Response, Url}; use ruma_client_api::Method as RumaHttpMethod; use url; use api::rocketchat::Endpoint; use errors::*; pub enum RequestData<T: Into<Body>> { B...
use std::collections::HashMap; use std::io::Read; use http::{HeaderMap, Method, StatusCode}; use reqwest::multipart::Form; use reqwest::{Body, Client, Response, Url}; use ruma_client_api::Method as RumaHttpMethod; use url; use api::rocketchat::Endpoint; use errors::*; pub enum RequestData<T: Into<Body>> { B...
; let data = RequestData::Body(payload.into()); RestApi::call(&method, url, data, params, None) } pub fn get_matrix_file<'a, T: Into<Body>>( method: &RumaHttpMethod, url: &str, payload: T, params: &HashMap<&str, &'a str>, ) -> Result<Response> { ...
match *method { RumaHttpMethod::Delete => Method::DELETE, RumaHttpMethod::Get => Method::GET, RumaHttpMethod::Post => Method::POST, RumaHttpMethod::Put => Method::PUT, }
if_condition
[ { "content": "pub fn simulate_message_from_matrix(as_url: &str, payload: &str) -> (String, StatusCode) {\n\n let url = format!(\"{}/transactions/{}\", as_url, \"specid\");\n\n let mut params = HashMap::new();\n\n params.insert(\"access_token\", HS_TOKEN);\n\n RestApi::call(&Method::PUT, &url, Reques...
Rust
monitor/src/database/mod.rs
probe-rs/hive-software
817a98220e840e7e3522146f868c1da9f8aa4b96
use std::path::Path; use ciborium::de::from_reader; use ciborium::ser::into_writer; use serde::{Deserialize, Serialize}; use sled::{Config, Db, Mode, Result as SledResult, Tree}; pub(crate) mod keys; pub(crate) mod sync; const FLUSH_INTERVAL_MS: u64 = 60_000; const CACHE_CAPACITY: u64 = 52_428_800; const DB_PATH: ...
use std::path::Path; use ciborium::de::from_reader; use ciborium::ser::into_writer; use serde::{Deserialize, Serialize}; use sled::{Config, Db, Mode, Result as SledResult, Tree}; pub(crate) mod keys; pub(crate) mod sync; const FLUSH_INTERVAL_MS: u64 = 60_000; const CACHE_CAPACITY: u64 = 52_428_800; const DB_PATH: ...
fn c_get<'de, T>(&self, key: &str) -> SledResult<Option<T>> where T: Deserialize<'de>, { let val = self.get(key)?; if val.is_some() { let val = from_reader(&*val.unwrap()).expect("Failed to deserialize the DB value to CBOR"); return Ok(Some(...
fn c_insert<'de, T>(&self, key: &str, value: &T) -> SledResult<Option<T>> where T: Serialize + Deserialize<'de>, { let mut bytes: Vec<u8> = vec![]; into_writer(value, &mut bytes).expect("Failed to serialize the provided value to CBOR"); let prev_val = self.insert(key, bytes)?; ...
function_block-full_function
[ { "content": "/// creates, initializes and returns all connected tss which are able to be shared across threads\n\npub fn create_shareable_tss(\n\n i2c_bus: &'static BusManagerStd<I2c>,\n\n io_expander: &'static [HiveIoExpander; 8],\n\n) -> Vec<Mutex<TargetStackShield>> {\n\n TargetStackShield::create_...
Rust
src/anactrl/bod_dcdc_int_ctrl.rs
conorpp/lpc55-pac
eb30d633de05113362de01095123d70c54e63ef4
#[doc = "Reader of register BOD_DCDC_INT_CTRL"] pub type R = crate::R<u32, super::BOD_DCDC_INT_CTRL>; #[doc = "Writer for register BOD_DCDC_INT_CTRL"] pub type W = crate::W<u32, super::BOD_DCDC_INT_CTRL>; #[doc = "Register BOD_DCDC_INT_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::BOD_DCDC_INT_CTRL ...
#[doc = "Reader of register BOD_DCDC_INT_CTRL"] pub type R = crate::R<u32, super::BOD_DCDC_INT_CTRL>; #[doc = "Writer for register BOD_DCDC_INT_CTRL"] pub type W = crate::W<u32, super::BOD_DCDC_INT_CTRL>; #[doc = "Register BOD_DCDC_INT_CTRL `reset()`'s with value 0"] impl crate::ResetValue for super::BOD_DCDC_INT_CTRL ...
#[doc = "Checks if the value of the field is `DISABLE`"] #[inline(always)] pub fn is_disable(&self) -> bool { *self == BODCORE_INT_ENABLE_A::DISABLE } #[doc = "Checks if the value of the field is `ENABLE`"] #[inline(always)] pub fn is_enable(&self) -> bool { *self == BODCORE...
pub fn variant(&self) -> BODCORE_INT_ENABLE_A { match self.bits { false => BODCORE_INT_ENABLE_A::DISABLE, true => BODCORE_INT_ENABLE_A::ENABLE, } }
function_block-full_function
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
crosh/src/util.rs
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::env; use std::error; use std::fmt::{self, Display}; use std::fs::read_to_string; use std::io::Read; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use chrono::Local; use dbus::blo...
use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::env; use std::error; use std::fmt::{self, Display}; use std::fs::read_to_string; use std::io::Read; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use chrono::Local; use dbus::blo...
} impl<T: error::Error> From<T> for Error { fn from(err: T) -> Self { Error::WrappedError(format!("{:?}", err)) } } pub fn get_user_id_hash() -> Result<String> { if let Ok(lookup) = env::var(CROS_USER_ID_HASH) { return Ok(lookup); } let user_id_hash = chromeos::get_user_id_hash()...
f::Error::*; #[sorted] match self { DbusChromeFeaturesService(err, m) => write!(f, "failed to call '{}': {}", m, err), DbusConnection(err) => write!(f, "failed to connect to D-Bus: {}", err), DbusGetUserIdHash(err) => { write!(f, "failed to get user-i...
function_block-function_prefixed
[]
Rust
packages/network_partitions/src/leiden/hierarchical.rs
microsoft/graspologic-native
09941794fc9e484c4997c95216cc97d9124f94c0
use rand::Rng; use super::leiden::leiden; use crate::clustering::{ClusterItem, Clustering}; use crate::errors::CoreError; use crate::log; use crate::network::prelude::*; use std::collections::HashSet; use std::collections::VecDeque; struct HierarchicalWork { subnetwork: LabeledNetwork<CompactNodeId>, parent_c...
use rand::Rng; use super::leiden::leiden; use crate::clustering::{ClusterItem, Clustering}; use crate::errors::CoreError; use crate::log; use crate::network::prelude::*; use std::collections::HashSet; use std::collections::VecDeque; struct HierarchicalWork { subnetwork: LabeledNetwork<CompactNodeId>, parent_c...
} pub fn hierarchical_leiden<T>( network: &CompactNetwork, clustering: Option<Clustering>, iterations: Option<usize>, resolution: Option<f64>, randomness: Option<f64>, rng: &mut T, use_modularity: bool, max_cluster_size: u32, ) -> Result<Vec<HierarchicalCluster>, CoreError> where T...
fn sorted_cluster_items(&self) -> Vec<ClusterItem> { let mut ordered_cluster_items: Vec<ClusterItem> = self.into_iter().collect(); ordered_cluster_items .sort_by(|a, b| a.cluster.cmp(&b.cluster).then(a.node_id.cmp(&b.node_id))); return ordered_cluster_items; }
function_block-full_function
[ { "content": "fn best_cluster_for_node<T>(\n\n node: usize,\n\n node_weight: f64,\n\n neighboring_clusters: &Vec<usize>,\n\n neighboring_cluster_edge_weights: &mut Vec<f64>,\n\n cluster_weights: &Vec<f64>,\n\n external_edge_weight_per_cluster: &Vec<f64>,\n\n total_node_weight: f64,\n\n s...
Rust
src/lib.rs
p-kraszewski/pakr-mio-signalfd
8e02095ca45bf877217d4770d4ea12cf7d28b94d
/* Copyright (c) 2020 Pawel Kraszewski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and ...
/* Copyright (c) 2020 Pawel Kraszewski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and ...
nterest) } fn reregister( &mut self, registry: &Registry, token: Token, interest: Interest, ) -> io::Result<()> { SourceFd(&self.fd).reregister(registry, token, interest) } fn deregister(&mut self, registry: &Registry) -> io::Result<()> { SourceFd(&s...
register( &mut self, registry: &Registry, token: Token, interest: Interest, ) -> io::Result<()> { SourceFd(&self.fd).register(registry, token, i
function_block-random_span
[]
Rust
pubsub/src/lib.rs
sech9446/jjal-battle
775fe800492ec274c5b26389d17e8afccda67ffb
use std::fmt; use std::hash::Hash; use std::sync::Arc; use tokio::sync::watch::{channel, error::SendError, Receiver, Sender}; use std::error::Error as StdError; pub use tokio_stream::{wrappers::WatchStream, StreamExt}; pub enum Error { SendError(String), ChannelNotFound, } impl fmt::Debug for Error { fn f...
use std::fmt; use std::hash::Hash; use std::sync::Arc; use tokio::sync::watch::{channel, error::SendError, Receiver, Sender}; use std::error::Error as StdError; pub use tokio_stream::{wrappers::WatchStream, StreamExt}; pub enum Error { SendError(String), ChannelNotFound, } impl fmt::Debug for Error { fn f...
} impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { match self { Error::SendError(_) => None, Error::ChannelNotFound => None, } } } impl<D: fmt::Debug> From<SendError<D>> for Error { fn from(e: SendError<D>) -> Self { Error::...
h self { Error::SendError(e) => write!(f, "{:?}", e), Error::ChannelNotFound => { write!(f, "channel not found(call create_channel before use it)") } } }
function_block-function_prefixed
[ { "content": "pub fn routes(cfg: &mut web::ServiceConfig) {\n\n cfg.app_data(MultipartOptions::default().max_num_files(1))\n\n .service(graphql)\n\n .service(playground);\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::utils::test::*;\n\n use actix_web::{http::...
Rust
core/src/vm/jsvalue/object.rs
maekawatoshiki/rapidus
4486c72b48fe44b10bf9a1d77ebbe14b6b380a19
use super::super::super::gc::MemoryAllocator; use super::super::error; use super::value::*; use crate::vm::vm::Factory; pub use rustc_hash::FxHashMap; #[derive(Clone, Debug)] pub struct Object { pub kind: ObjectKind, pub prototype: Value, pub property: FxHashMap<String, Property>, p...
use super::super::super::gc::MemoryAllocator; use super::super::error; use super::value::*; use crate::vm::vm::Factory; pub use rustc_hash::FxHashMap; #[derive(Clone, Debug)] pub struct Object { pub kind: ObjectKind, pub prototype: Value, pub property: FxHashMap<String, Property>, p...
Property::Data(ref mut data) => data, _ => panic!(), } } pub fn as_accessor_mut(&mut self) -> &mut AccessorProperty { match self { Property::Accessor(ref mut accessor) => accessor, _ => panic!(), } } pub fn get_data(&self) -> Option<&DataProp...
operty) -> Self { Property::Data(data) } pub fn new_data_simple(val: Value) -> Self { Property::Data(DataProperty { val, writable: true, enumerable: true, configurable: true, }) } pub fn as_data(self) -> DataProperty { mat...
random
[ { "content": "pub fn object(factory: &mut Factory) -> Value {\n\n factory.generate_builtin_constructor(\n\n \"Object\",\n\n object_constructor,\n\n factory.object_prototypes.object,\n\n )\n\n}\n\n\n", "file_path": "core/src/builtins/object.rs", "rank": 0, "score": 304810.7...
Rust
src/parser.rs
encabulators/nats-types
7bd1d6bf3be326c276ff70d17b64ca9f3c05645b
use nom::types::CompleteStr; #[derive(Debug)] pub struct MessageHeader { pub subject: String, pub sid: usize, pub reply_to: Option<String>, pub message_len: usize, } #[derive(Debug)] pub struct PubHeader { pub subject: String, pub reply_to: Option<String>, pub message_len: usize, } #[de...
use nom::types::CompleteStr; #[derive(Debug)] pub struct MessageHeader { pub subject: String, pub sid: usize, pub reply_to: Option<String>, pub message_len: usize, } #[derive(Debug)] pub struct PubHeader { pub subject: String, pub reply_to: Option<String>, pub message_len: usize, } #[de...
SUB BAR G1 44"; let res = sub_header(CompleteStr(&msg)); assert!(res.is_ok()); if let Ok(header) = res { assert_eq!(header.1.subject, "BAR"); assert_eq!(header.1.sid, 44); assert_eq!(header.1.queue_group, Some("G1".to_string())); } } #[test] ...
is_a!(" \t") >> subject: parse_completestr >> is_a!(" \t") >> sid: parse_u64 >> is_a!(" \t") >> reply_to: opt!(terminated!(parse...
random
[ { "content": "fn vec_to_str(bytes: &Vec<u8>) -> String {\n\n let s = String::from_utf8(bytes.as_bytes().to_owned());\n\n match s {\n\n Ok(s) => s,\n\n Err(_) => \"<<BAD PAYLOAD>>\".to_string(),\n\n }\n\n}\n\n\n\n/// Indicates an error occurred during parsing of a NATS protocol message. Do...
Rust
src/transport/smtp/error.rs
konomith/lettre
a429a249134e15c508b094af004b126306359e6e
use crate::{ transport::smtp::response::{Code, Severity}, BoxError, }; use std::{error::Error as StdError, fmt}; pub struct Error { inner: Box<Inner>, } struct Inner { kind: Kind, source: Option<BoxError>, } impl Error { pub(crate) fn new<E>(kind: Kind, source: Option<E>) -> Error where...
use crate::{ transport::smtp::response::{Code, Severity}, BoxError, }; use std::{error::Error as StdError, fmt}; pub struct Error { inner: Box<Inner>, } struct Inner { kind: Kind, source: Option<BoxError>, } impl Error { pub(crat
pub fn is_response(&self) -> bool { matches!(self.inner.kind, Kind::Response) } pub fn is_client(&self) -> bool { matches!(self.inner.kind, Kind::Client) } pub fn is_transient(&self) -> bool { matches!(self.inner.kind, Kind::Transient(_)) } pu...
e) fn new<E>(kind: Kind, source: Option<E>) -> Error where E: Into<BoxError>, { Error { inner: Box::new(Inner { kind, source: source.map(Into::into), }), } }
function_block-function_prefixed
[ { "content": "struct Inner {\n\n kind: Kind,\n\n source: Option<BoxError>,\n\n}\n\n\n\nimpl Error {\n\n pub(crate) fn new<E>(kind: Kind, source: Option<E>) -> Error\n\n where\n\n E: Into<BoxError>,\n\n {\n\n Error {\n\n inner: Box::new(Inner {\n\n kind,\n\n...
Rust
src/machines/cancel_external_state_machine.rs
temporalio/sdk-core
a0e40add5382b0b59ab5f8f0a5151890a41a3867
use crate::machines::{ workflow_machines::MachineResponse, Cancellable, EventInfo, MachineKind, NewMachineWithCommand, OnEventWrapper, WFMachinesAdapter, WFMachinesError, }; use rustfsm::{fsm, TransitionResult}; use std::convert::TryFrom; use temporal_sdk_core_protos::{ coresdk::{ common::Namespaced...
use crate::machines::{ workflow_machines::MachineResponse, Cancellable, EventInfo, MachineKind, NewMachineWithCommand, OnEventWrapper, WFMachinesAdapter, WFMachinesError, }; use rustfsm::{fsm, TransitionResult}; use std::convert::TryFrom; use temporal_sdk_core_protos::{ coresdk::{ common::Namespaced...
; } } _ => { return Err(WFMachinesError::Nondeterminism(format!( "Cancel external WF machine does not handle this event: {}", e ))) } }) } } impl WFMachinesAdapter for CancelExternalM...
Err(WFMachinesError::Fatal(format!( "Cancelworkflow failed attributes were unset: {}", e )))
call_expression
[ { "content": "fn create_request_cancel_activity_task_command<S>(\n\n dat: SharedState,\n\n next_state: S,\n\n) -> ActivityMachineTransition<S>\n\nwhere\n\n S: Into<ActivityMachineState>,\n\n{\n\n let cmd = Command {\n\n command_type: CommandType::RequestCancelActivityTask as i32,\n\n a...
Rust
src/lib.rs
watcol/clap-markdown
670166d5d1ad243675b47e988143ab06beb75d1a
extern crate clap; extern crate clap_generate; use clap::{App, Arg}; use clap_generate::Generator; use std::io::Write; macro_rules! w { ($($arg:tt)*) => { write!($($arg)*).expect("Failed to write to generated file") } } pub struct Markdown; impl Generator for Markdown { fn file_name(name: &str)...
extern crate clap; extern crate clap_generate; use clap::{App, Arg}; use clap_generate::Generator; use std::io::Write; macro_rules! w { ($($arg:tt)*) => { write!($($arg)*).expect("Failed to write to generated file") } } pub struct Markdown; impl Generator for Markdown { fn file_name(name: &str)...
if let Some(long) = long { w!(buf, "***--{}=\\<{}\\>***", long, name); } w!(buf, " \n"); if let Some(about) = about { w!(buf, "<p style=\"text-indent:1em\">{}</p>\n\n", about); } } } fn write_args(buf: &mut dyn Write, args: &[&Arg<'_>]) { if args.is_...
if have_flags { w!(buf, "- [Flags](#flags)\n"); } if have_opts { w!(buf, "- [Options](#options)\n"); } if have_args { w!(buf, "- [Arguments](#arguments)\n"); } w!(buf, "\n"); w!(buf, "## Usage\n```"); w!(buf, "...
random
[ { "content": "# clap-markdown\n\n![status](https://img.shields.io/badge/status-WIP-red)\n\n[![crates.io](https://img.shields.io/crates/v/clap-markdown)](https://crates.io/crates/clap-markdown)\n\n[![docs.rs](https://docs.rs/clap-markdown/badge.svg)](https://docs.rs/clap-markdown)\n\n[![Downloads](https://img.sh...
Rust
server/src/physics/entity.rs
Wazner/feather
c71ae17ddf31edd8784ce3e17b13150ed09d4cf2
use crate::entity::{EntityMoveEvent, Velocity, VelocityUpdateEvent}; use crate::physics::{block_impacted_by_ray, blocks_intersecting_bbox, AABBExt, Physics, Side}; use crate::state::State; use crossbeam::queue::SegQueue; use feather_core::Position; use feather_core::{Block, BlockExt}; use legion::entity::Entity; use ...
use crate::entity::{EntityMoveEvent, Velocity, VelocityUpdateEvent}; use crate::physics::{block_impacted_by_ray, blocks_intersecting_bbox, AABBExt, Physics, Side}; use crate::state::State; use crossbeam::queue::SegQueue; use feather_core::Position; use feather_core::{Block, BlockExt}; use legion::entity::Entity; use ...
fn entity_physics( state: &State, query: &mut Query<(Write<Position>, Write<Velocity>, Read<Physics>)>, world: &mut PreparedWorld, land_events: &mut Trigger<EntityPhysicsLandEvent>, move_events: &mut Trigger<EntityMoveEvent>, velocity_events: &mut Trigger<VelocityUpdateEvent>, ) { ...
function_block-full_function
[ { "content": "#[event_handler]\n\npub fn position_reset(\n\n events: &[EntityMoveEvent],\n\n _query: &mut Query<(Read<Position>, Write<PreviousPosition>)>,\n\n world: &mut PreparedWorld,\n\n) {\n\n events.iter().for_each(|event| {\n\n let pos = *world.get_component::<Position>(event.entity).u...
Rust
rust/src/bin/day5.rs
Piszmog/aoc-2021
a155cb7644017863c703e97f22c8338ccb5ef544
use std::collections::HashMap; use std::io::BufRead; use std::time::Instant; use aoc_2021::shared; fn main() { let start = Instant::now(); let args = shared::get_args(); let lines = shared::get_file_reader(args.get(0).unwrap()).unwrap() .lines() .map(|s| { let string = s.unwrap...
use std::collections::HashMap; use std::io::BufRead; use std::time::Instant; use aoc_2021::shared; fn main() { let start = Instant::now(); let args = shared::get_args(); let lines = shared::get_file_reader(args.get(0).unwrap()).unwrap() .lines() .map(|s| { let string = s.unwrap...
fn is_diagonal(&self) -> bool { self.start.x != self.end.x && self.start.y != self.end.y } } #[derive(Debug, Clone, Eq, PartialEq, Hash)] struct Point { x: i32, y: i32, } #[cfg(test)] mod day5_tests { use crate::{get_num_overlap, Line, Point}; #[test] fn test_part_1() { ...
t> { let mut path = Vec::new(); let mut current = self.start.clone(); loop { path.push(current.clone()); if current == self.end { break; } if current.x > self.end.x { current.x -= 1; } else if current.x <...
function_block-function_prefixed
[ { "content": "fun getFish(input: String): Map<Int, Long> {\n\n val fish = mutableMapOf<Int, Long>().apply { for (i in 0 until CYCLES) this[i] = 0 }\n\n input.split(\",\").forEach { fish[it.toInt()] = fish[it.toInt()]!! + 1 }\n\n return fish\n\n}\n\n\n", "file_path": "kotlin/src/main/kotlin/io/githu...
Rust
tests/fs/invalid_offset.rs
sunfishcode/posish
bbcd131a0d95bc57ce52af659fb209c8b90c65d8
#![cfg(not(any(target_os = "redox", target_os = "wasi")))] use rustix::io::SeekFrom; #[test] fn invalid_offset_seek() { use rustix::fs::{cwd, openat, seek, Mode, OFlags}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(cwd(), tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); let file = o...
#![cfg(not(any(target_os = "redox", target_os = "wasi")))] use rustix::io::SeekFrom; #[test] fn invalid_offset_seek() { use rustix::fs::{cwd, openat, seek, Mode, OFlags}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(cwd(), tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); let file = o...
let buf = [0_u8; 1_usize]; pwrite(&file, &buf, u64::MAX).unwrap_err(); pwrite(&file, &buf, i64::MAX as u64 + 1).unwrap_err(); } #[cfg(any(target_os = "android", target_os = "linux"))] #[test] fn invalid_offset_copy_file_range() { use rustix::fs::{copy_file_range, cwd, openat, Mode, OFlags}; use r...
let file = openat( &dir, "foo", OFlags::WRONLY | OFlags::TRUNC | OFlags::CREATE, Mode::RUSR | Mode::WUSR, ) .unwrap();
assignment_statement
[ { "content": "#[inline]\n\npub fn pread<Fd: AsFd>(fd: Fd, buf: &mut [u8], offset: u64) -> io::Result<usize> {\n\n imp::io::syscalls::pread(fd.as_fd(), buf, offset)\n\n}\n\n\n\n/// `pwrite(fd, bufs)`—Writes to a file at a given position.\n\n///\n\n/// # References\n\n/// - [POSIX]\n\n/// - [Linux]\n\n///\n\...
Rust
ncollide_testbed2d/src/testbed.rs
kpdonn/ncollide
e9019b988ba187c428b56714db2f8f32e89406f7
use std::rc::Rc; use std::cell::RefCell; use num::ToPrimitive; use sfml::graphics::{RenderTarget, RenderWindow}; use sfml::window::{ContextSettings, VideoMode}; use sfml::window::window_style; use sfml::window::event::Event; use sfml::window::{Key, MouseButton}; use sfml::graphics::Color; use sfml::system::Vector2i; u...
use std::rc::Rc; use std::cell::RefCell; use num::ToPrimitive; use sfml::graphics::{RenderTarget, RenderWindow}; use sfml::window::{ContextSettings, VideoMode}; use sfml::window::window_style; use sfml::window::event::Event; use sfml::window::{Key, MouseButton}; use sfml::graphics::Color; use sfml::system::Vector2i; u...
#[cfg(feature = "recording")] fn record_frame_if_enabled(&mut self) { if let Some(ref mut recorder) = self.recorder { let sz = self.window.get_size(); let capture = self.window.capture().unwrap(); let memory = capture.get_memory(); recorder.encode_rgba(s...
pub fn render<T>(&mut self, world: &mut CollisionWorld2<N, T>) { self.window.clear(&self.background); self.graphics .borrow_mut() .draw(world, &mut self.window, &self.camera); self.camera.activate_scene(&mut self.window); self.draw_collisions(world); ...
function_block-full_function
[ { "content": "fn draw_collisions<T>(window: &mut Window, world: &mut CollisionWorld3<f32, T>) {\n\n for c in world.contacts() {\n\n window.draw_line(&c.2.world1, &c.2.world2, &Point3::new(1.0, 0.0, 0.0));\n\n\n\n let center = na::center(&c.2.world1, &c.2.world2);\n\n let end = center + c...
Rust
src/agent/onefuzz-agent/src/local/common.rs
tonybaloney/onefuzz
e0f2e9ed5aae006e0054387de7a0ff8c83c8f722
use crate::tasks::config::CommonConfig; use crate::tasks::utils::parse_key_value; use anyhow::Result; use backoff::{future::retry, Error as BackoffError, ExponentialBackoff}; use clap::{App, Arg, ArgMatches}; use flume::Sender; use onefuzz::{blob::url::BlobContainerUrl, monitor::DirectoryMonitor, syncdir::SyncedDir}; u...
use crate::tasks::config::CommonConfig; use crate::tasks::utils::parse_key_value; use anyhow::Result; use backoff::{future::retry, Error as BackoffError, ExponentialBackoff}; use clap::{App, Arg, ArgMatches}; use flume::Sender; use onefuzz::{blob::url::BlobContainerUrl, monitor::DirectoryMonitor, syncdir::SyncedDir}; u...
pub struct DirectoryMonitorQueue { pub directory_path: PathBuf, pub queue_client: storage_queue::QueueClient, pub handle: tokio::task::JoinHandle<Result<()>>, } impl DirectoryMonitorQueue { pub async fn start_monitoring(directory_path: impl AsRef<Path>) -> Result<Self> { let directory_path = ...
pub fn build_local_context( args: &ArgMatches<'_>, generate_task_id: bool, event_sender: Option<Sender<UiEvent>>, ) -> Result<LocalContext> { let job_id = get_uuid("job_id", args).unwrap_or_else(|_| Uuid::nil()); let task_id = get_uuid("task_id", args).unwrap_or_else(|_| { if generate_task_i...
function_block-full_function
[ { "content": "pub fn args(name: &str) -> App<'static, 'static> {\n\n let mut cmd = SubCommand::with_name(name)\n\n .about(\"pre-release local fuzzing\")\n\n .arg(\n\n Arg::with_name(TIMEOUT)\n\n .long(TIMEOUT)\n\n .help(\"The maximum running time in seco...
Rust
src/systems/hit_event_system.rs
exjam/bevy_rose
8cbcc3ae71505b7e9b7d51f7177863967c489fcc
use bevy::{ ecs::query::WorldQuery, hierarchy::BuildChildren, prelude::{Commands, Entity, EventReader, EventWriter, Query, Res, ResMut}, }; use rose_game_common::{ components::{AbilityValues, HealthPoints, ManaPoints, MoveSpeed, StatusEffects}, data::Damage, }; use crate::{ components::{ ...
use bevy::{ ecs::query::WorldQuery, hierarchy::BuildChildren, prelude::{Commands, Entity, EventReader, EventWriter, Query, Res, ResMut}, }; use rose_game_common::{ components::{AbilityValues, HealthPoints, ManaPoints, MoveSpeed, StatusEffects}, data::Damage, }; use crate::{ components::{ ...
y_defender.get_mut(event.defender).ok(); if defender.is_none() { continue; } let mut defender = defender.unwrap(); let mut damage = Damage { amount: 0, is_critical: false, apply_hit_stun: false, }; if event.apply_...
function_block-function_prefixed
[ { "content": "pub fn format_command(ui: &mut egui::Ui, command: &Command) {\n\n match command {\n\n Command::Stop => {\n\n ui.label(\"Stop\");\n\n }\n\n Command::Move(command_move) => {\n\n ui.label(format!(\n\n \"{} to ({}, {})\",\n\n ...
Rust
src/menu/callbacks.rs
narfit66/ncursesw-win-rs
629b36fd2d7be4027d3c6328bf90d2cc6c7403af
/* src/menu/callbacks.rs Copyright (c) 2020-2022 Stephen Whittle All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without l...
/* src/menu/callbacks.rs Copyright (c) 2020-2022 Stephen Whittle All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without l...
pub(in crate::menu) fn set_menu_screen(menu: MENU, screen: Option<SCREEN>) { MENUSCREENS .lock() .unwrap_or_else(|_| panic!("{}set_menu_screen({:p}) : MENUSCREENS.lock() failed!!!", MODULE_PATH, menu)) .insert(MenuKey::new(menu), MenuValue::new(screen)); } pub(in crate::menu) fn set_menu_...
screen(); Menu::_from(screen, menu, unsafe { (*menu).items }, false) }; let callbacks = CALLBACKS .lock() .unwrap_or_else(|_| panic!("{}menu_callback({:p}, {:?}) : CALLBACKS.lock() failed!!!", MODULE_PATH, menu, cb_type)); if let Some(ref callback) = callbacks .get(&Callba...
function_block-function_prefix_line
[ { "content": "pub trait IsFieldType<'a, A, B, C>: Send + Sync + Hash {\n\n fn fieldtype(&self) -> &'a FieldType;\n\n fn arguments(&self) -> u8 { 0 }\n\n fn arg1(&self) -> A;\n\n fn arg2(&self) -> B;\n\n fn arg3(&self) -> C;\n\n}\n", "file_path": "src/form/fieldtypes/isfieldtype.rs", "rank...
Rust
gdk4-wayland/sys/src/lib.rs
mehmooda/gtk4-rs
220b3e33e994fa633cc192dedf99840e81638024
#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] #![allow( clippy::approx_constant, clippy::type_complexity, clippy::unreadable_literal, clippy::upper_case_acronyms )] #![cfg_attr(feature = "dox", feature(doc_cfg))] use glib_sys as glib; #[allow(unused_imports)] use libc::{ ...
#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] #![allow( clippy::approx_constant, clippy::type_complexity, clippy::unreadable_literal, clippy::upper_case_acronyms )] #![cfg_attr(feature = "dox", feature(doc_cfg))] use glib_sys as glib; #[allow(unused_imports)] use libc::{ ...
t(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GdkWaylandToplevel @ {:?}", self as *const _)) .finish() } } #[link(name = "gtk-4")] extern "C" { pub fn gdk_wayland_device_get_type() -> GType; pub fn gdk_wayland_device_get_node_pa...
type GdkWaylandDisplayClass = *mut _GdkWaylandDisplayClass; #[repr(C)] pub struct _GdkWaylandGLContextClass(c_void); pub type GdkWaylandGLContextClass = *mut _GdkWaylandGLContextClass; #[repr(C)] pub struct _GdkWaylandMonitorClass(c_void); pub type GdkWaylandMonitorClass = *mut _GdkWaylandMonitorClass; #[repr(C)] ...
random
[ { "content": "#[derive(Debug, Default)]\n\nstruct Actions(pub(crate) HashMap<String, glib::ffi::gpointer>);\n\nunsafe impl Sync for Actions {}\n\nunsafe impl Send for Actions {}\n\n\n", "file_path": "gtk4/src/subclass/widget.rs", "rank": 0, "score": 241278.80818118807 }, { "content": "#[doc(...
Rust
client/src/state/bucket.rs
fossabot/stronghold.rs
ef9ca564718d653460f6bfddee1cd6eb1b3f18ed
use engine::{ store::Cache, vault::{BoxProvider, DBView, Key, PreparedRead, ReadResult, RecordHint, RecordId, VaultId, WriteRequest}, }; use std::collections::HashMap; use crate::line_error; type Store = Cache<Vec<u8>, Vec<u8>>; pub struct Bucket { cache: HashMap<VaultId, Vec<ReadResult>>, } impl Buc...
use engine::{ store::Cache, vault::{BoxProvider, DBView, Key, PreparedRead, ReadResult, RecordHint, RecordId, VaultId, WriteRequest}, }; use std::collections::HashMap; use crate::line_error; type Store = Cache<Vec<u8>, Vec<u8>>; pub struct Bucket { cache: HashMap<VaultId, Vec<ReadResult>>, } impl Buc...
None => Vec::<ReadResult>::new(), } } fn insert_reads(&mut self, id: VaultId, reads: Vec<ReadResult>) { self.cache.insert(id, reads); } } fn write_to_read(write: &WriteRequest) -> ReadResult { ReadResult::new(write.kind(), &write.id(), &write.data()) }
Vec<u8> = vec![]; self.take(id, key, |view, reads| { let reader = view.reader(); let res = reader.prepare_read(&rid).expect(line_error!()); if let PreparedRead::CacheHit(mut v) = res { buffer.append(&mut v); } reads }); ...
random
[ { "content": "/// Read ciphertext from the input, decrypts it using the specified key and the associated data\n\n/// specified during encryption and returns the plaintext\n\npub fn read<I: Read>(input: &mut I, key: &Key, associated_data: &[u8]) -> crate::Result<Vec<u8>> {\n\n // check the header\n\n check...
Rust
requestty-ui/src/backend/termion.rs
Lutetium-Vanadium/discourse
4e2dc9bdfa70cb777090eb288155f3d2a845954d
use std::{ cmp::Ordering, fmt, io::{self, Write}, ops::{Deref, DerefMut}, }; use termion::{ clear, color, cursor, raw::{IntoRawMode, RawTerminal}, scroll, style, }; use super::{Attributes, Backend, ClearType, Color, MoveDirection, Size}; enum Terminal<W: Write> { Raw(RawTerminal<W>), ...
use std::{ cmp::Ordering, fmt, io::{self, Write}, ops::{Deref, DerefMut}, }; use termion::{ clear, color, cursor, raw::{IntoRawMode, RawTerminal}, scroll, style, }; use super::{Attributes, Backend, ClearType, Color, MoveDirection, Size}; enum Terminal<W: Write> { Raw(RawTerminal<W>), ...
fn hide_cursor(&mut self) -> io::Result<()> { write!(self.buffer, "{}", cursor::Hide) } fn show_cursor(&mut self) -> io::Result<()> { write!(self.buffer, "{}", cursor::Show) } fn get_cursor_pos(&mut self) -> io::Result<(u16, u16)> { cursor::DetectCursorPos::cursor_pos(&mu...
fn disable_raw_mode(&mut self) -> io::Result<()> { match self.buffer { Terminal::Raw(ref buf) => buf.suspend_raw_mode(), Terminal::Normal(_) => { if cfg!(debug_assertions) { panic!("Called disable_raw_mode without enable_raw_mode"); } ...
function_block-full_function
[ { "content": "#[cfg(any(feature = \"crossterm\", feature = \"termion\"))]\n\n#[cfg_attr(docsrs, doc(cfg(any(feature = \"crossterm\", feature = \"termion\"))))]\n\npub fn get_backend<W: io::Write>(buf: W) -> impl Backend {\n\n #[cfg(feature = \"crossterm\")]\n\n return CrosstermBackend::new(buf);\n\n\n\n ...
Rust
src/memory.rs
thepowersgang/binaryview2
c0904a7330170dfe0116530509ba182ba58a93ad
use value::Value; use std::cmp::Ordering; use std::io::{Read,Seek}; enum RegionType { ROM(Vec<u8>), RAM(Vec<Value<u8>>), MMIO(String), } struct Region { start: u64, size: usize, data: RegionType } pub struct MemoryState { endian_big: bool, regions: Vec<Region>, } pub trait MemoryStateAccess: ::value::Val...
use value::Value; use std::cmp::Ordering; use std::io::{Read,Seek}; enum RegionType { ROM(Vec<u8>), RAM(Vec<Value<u8>>), MMIO(String), } struct Region { start: u64, size: usize, data: RegionType } pub struct MemoryState { endian_big: bool, regions: Vec<Region>, } pub trait MemoryStateAccess: ::value::Val...
pub fn write_u8(&self, addr: u64, val: Value<u8>) { panic!("TODO: MemoryState.write_u8(addr={:#x},val={:?})", addr, val); } pub fn write_u16(&self, addr: u64, val: Value<u16>) { panic!("TODO: MemoryState.write_u16(addr={:#x},val={:?})", addr, val); } pub fn write_u32(&self, addr: u64, val: Value<u32>) { p...
pub fn read_u64(&self, addr: u64) -> Option<Value<u64>> { self.get_region(addr).map( |(a,ofs)| if self.endian_big { Value::concat( a.read_u32_be(ofs+4), a.read_u32_be(ofs+0) ) } else { Value::concat( a.read_u32_le(ofs+0), a.read_u32_le(ofs+4) ) } ) }
function_block-full_function
[ { "content": "pub fn parse_typemap(typemap: &mut ::types::TypeMap, path: &str) -> Result<(),String>\n\n{\n\n\tlet mut reader = ::std::fs::File::open(path).unwrap();\n\n\tlet mut lex = lexer::Lexer::new( &mut reader );\n\n\t\n\n\tloop\n\n\t{\n\n\t\tmatch try!(get_tok(&mut lex))\n\n\t\t{\n\n\t\tlexer::TokIdent(id...
Rust
src/gatt/mod.rs
flying-sheep/blez
b396b80ebeb4295c21e96142ef54b0f72ccb21a4
use pin_project::pin_project; use std::{ fmt, pin::Pin, task::{Context, Poll}, }; use strum::{Display, EnumString}; use tokio::{ io::{AsyncRead, AsyncWrite, ReadBuf}, net::UnixStream, }; pub mod local; pub mod remote; pub(crate) const SERVICE_INTERFACE: &str = "org.bluez.GattService1"; pub(crate...
use pin_project::pin_project; use std::{ fmt, pin::Pin, task::{Context, Poll}, }; use strum::{Display, EnumString}; use tokio::{ io::{AsyncRead, AsyncWrite, ReadBuf}, net::UnixStream, }; pub mod local; pub mod remote; pub(crate) const SERVICE_INTERFACE: &str = "org.bluez.GattService1"; pub(crate...
poll_shutdown(cx) } }
&mut fmt::Formatter) -> fmt::Result { write!(f, "CharacteristicWriter {{ {:?} }}", &self.stream) } } impl AsyncWrite for CharacteristicWriter { fn poll_write(self: Pin<&mut Self>, cx: &mut std::task::Context, buf: &[u8]) -> Poll<std::io::Result<usize>> { self.project().stream.poll_write(cx, bu...
random
[ { "content": "#[derive(Debug, Clone)]\n\nstruct CharacteristicAcquireRequest {\n\n /// Exchanged MTU.\n\n pub mtu: u16,\n\n /// Link type.\n\n pub link: Option<LinkType>,\n\n}\n\n\n\nimpl CharacteristicAcquireRequest {\n\n fn from_dict(dict: &PropMap) -> DbusResult<Self> {\n\n Ok(Self {\n\...
Rust
src/main.rs
kekcheburec/practsite
9079299efa8afca9ee0dd894719c9528ac4b472a
use std::collections::BTreeMap; use std::fs; use actix_files; use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer}; use tera::{compile_templates, Context, Tera}; use lettre::smtp::authentication::{Credentials, Mechanism}; use lettre::smtp::ConnectionReuseParameters; use lettre::{ClientSecur...
use std::collections::BTreeMap; use std::fs; use actix_files; use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer}; use tera::{compile_templates, Context, Tera}; use lettre::smtp::authentication::{Credentials, Mechanism}; use lettre::smtp::ConnectionReuseParameters; use lettre::{ClientSecur...
fn about(data: web::Data<AppConfig>) -> Result<HttpResponse, Error> { let s = { let mut ctx = Context::new(); ctx.insert("title", &"Информация | IoTShop".to_owned()); ctx.insert("nav_items", &data.config.page.nav_items); data.template .render("about.html", &ctx) ...
ror(data))? }; let email = Email::builder() .to(("кому", "")) .from("от кого") .subject("Заказ") .html(email_body) .build() .unwrap(); let mut tls_builder = TlsConnector::builder(); tls_builder.min_protocol_version(Some(Protocol::Tlsv10)); ...
function_block-function_prefixed
[]
Rust
src/reader.rs
TheDataEngine/mongodb-arrow-connector
2cd7db60e774df87cca71a1b667d0dbd1b3938bf
use std::iter::FromIterator; use std::{sync::Arc, time::Duration}; use arrow::{ array::*, datatypes::{DataType, SchemaRef, TimeUnit}, error::{ArrowError, Result}, record_batch::RecordBatch, }; use async_stream::stream; use bson::{doc, Document}; use futures_util::stream::{Stream, StreamExt}; use mongod...
use std::iter::FromIterator; use std::{sync::Arc, time::Duration}; use arrow::{ array::*, datatypes::{DataType, SchemaRef, TimeUnit}, error::{ArrowError, Result}, record_batch::RecordBatch, }; use async_stream::stream; use bson::{doc, Document}; use futures_util::stream::{Stream, StreamExt}; use mongod...
#[cfg(test)] mod tests { use super::*; use std::fs::File; use std::sync::Arc; use arrow::csv; use arrow::datatypes::{Field, Schema}; #[tokio::test] async fn test_read_collection() -> Result<()> { let fields = vec![ Field::new("_id", DataType::Utf8, false), ...
let options = ClientOptions::builder() .hosts(vec![ServerAddress::Tcp { host: config.hostname.to_string(), port: config.port, }]) .build(); Client::with_options(options).map_err(|e| ArrowError::ExternalError(Box::new(e))) }
function_block-function_prefix_line
[ { "content": "/// A private struct that uses a newtype pattern, holds the documents to be written\n\nstruct Documents(Vec<bson::Document>);\n\n\n\nimpl From<&RecordBatch> for Documents {\n\n fn from(batch: &RecordBatch) -> Self {\n\n let len = batch.num_rows();\n\n let mut documents = vec![doc!...
Rust
cio/src/tailscale.rs
KittyCAD/cio
b0eb73bd8125ea2681c51d89993f592a864abb1d
use std::collections::BTreeMap; use anyhow::Result; use chrono::{Duration, Utc}; use cloudflare::endpoints::dns; use cloudflare::framework::async_api::ApiClient; use log::info; use crate::companies::Company; pub async fn cleanup_old_tailscale_devices(company: &Company) -> Result<()> { if company.tailscale_api_ke...
use std::collections::BTreeMap; use anyhow::Result; use chrono::{Duration, Utc}; use cloudflare::endpoints::dns; use cloudflare::framework::async_api::ApiClient; use log::info; use crate::companies::Company; pub async fn cleanup_old_tailscale_devices(company: &Company) -> Result<()> { if company.tailscale_api_ke...
nal_domain = format!(".internal.{}", company.domain); if !dns_record.name.ends_with(&internal_domain) && !dns_record.name.ends_with(".internal") { log::info!("skipping dns record {}, not internal", dns_record.name); continue; } if dns_record.name.ends_with(&form...
iter() .map(|device| { ( device.hostname.trim_end_matches("-2").to_string(), device.id.to_string(), ) }) .collect(); let cloudflare = company.authenticate_cloudflare()?; let zone_identifier = &crate::dns_providers::get_z...
random
[]
Rust
zebrad/src/application.rs
gtank/zebra
6606bcaa62378d0cac57f2d6f19c49241a442ad6
use crate::{commands::ZebradCmd, config::ZebradConfig}; use abscissa_core::{ application::{self, AppCell}, config, terminal::component::Terminal, trace::Tracing, Application, Component, EntryPoint, FrameworkError, StandardPaths, }; pub static APPLICATION: AppCell<ZebradApp> = AppCell::new(); pub...
use crate::{commands::ZebradCmd, config::ZebradConfig}; use abscissa_core::{ application::{self, AppCell}, config, terminal::component::Terminal, trace::Tracing, Application, Component, EntryPoint, FrameworkError, StandardPaths, }; pub static APPLICATION: AppCell<ZebradApp> = AppCell::new(); pub...
} impl ZebradApp { fn level(&self, command: &EntryPoint<ZebradCmd>) -> String { if let Ok(level) = std::env::var("ZEBRAD_LOG") { level } else if command.verbose { "debug".to_string() } else if let Some(ZebradConfig { tracing: crate::confi...
fn after_config( &mut self, config: Self::Cfg, command: &Self::Cmd, ) -> Result<(), FrameworkError> { self.state.components.after_config(&config)?; self.config = Some(config); let level = self.level(command); self.state .components ...
function_block-full_function
[ { "content": "pub fn init() -> impl Service<\n\n Request,\n\n Response = Response,\n\n Error = Box<dyn Error + Send + Sync + 'static>,\n\n Future = impl Future<Output = Result<Response, Box<dyn Error + Send + Sync + 'static>>>,\n\n> + Send\n\n + Clone\n\n + 'static {\n\n Buffer::new(Z...
Rust
src/ipc/result.rs
Dentosal/rust_os
ddfbefabf4e928859b57fd2dc44fa6e38545f6d5
use hashbrown::HashSet; use d7abi::SyscallErrorCode; use crate::multitasking::{ExplicitEventId, Scheduler}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct TriggerEvent(pub ExplicitEventId); #[derive(Debug, Clone)] #[must_use] pub struct IpcResult<T> { value: Result<T, Error>, events: HashSet<...
use hashbrown::HashSet; use d7abi::SyscallErrorCode; use crate::multitasking::{ExplicitEventId, Scheduler}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct TriggerEvent(pub ExplicitEventId); #[derive(Debug, Clone)] #[must_use] pub struct IpcResult<T> { value: Result<T, Error>, events: HashSet<...
rt::Into<SyscallErrorCode> for DeliveryError { fn into(self) -> SyscallErrorCode { match self { Self::NoSubscriber => SyscallErrorCode::ipc_delivery_no_target, Self::QueueFull => SyscallErrorCode::ipc_delivery_target_full, Self::NegativeAcknowledgement => SyscallErrorCode...
vents.extend(new_events); self } pub fn separate_events(self) -> (Result<T, Error>, HashSet<TriggerEvent>) { (self.value, self.events) } pub fn consume_events(self, sched: &mut Scheduler) -> Result<T, Error> { for event in self.events.into_iter() { sched.on_explicit...
random
[ { "content": "pub fn init() {\n\n log::debug!(\"CPU: {}\", cpu_brand());\n\n run_feature_checks();\n\n}\n", "file_path": "src/cpuid.rs", "rank": 0, "score": 139261.22810817132 }, { "content": "pub fn enable() {\n\n log::set_logger(&LOGGER).unwrap();\n\n log::set_max_level(log::Le...
Rust
src/io/binary/traits.rs
marcianx/openmesh-rs-core
94d79ee9ca3ece34b7a8aef505de69d9d89f7753
use crate::io::result::{Error, Result}; use std::io::{Read, Write}; pub use byteorder::ByteOrder; pub use byteorder::{BigEndian, LittleEndian}; pub const UNKNOWN_SIZE: usize = !0usize; #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] pub enum Endian { #[allow(missing_docs)] Big, #[allow(missing_docs)]...
use crate::io::result::{Error, Result}; use std::io::{Read, Write}; pub use byteorder::ByteOrder; pub use byteorder::{BigEndian, LittleEndian}; pub const UNKNOWN_SIZE: usize = !0usize; #[derive(Copy
self.iter() { size += s.store_endian::<B>(writer)?; } Ok(size) } fn restore_endian<B: ByteOrder>(&mut self, reader: &mut dyn Read) -> Result<usize> { let mut size = 0; for s in self.iter_mut() { size += s.restore_endian::<B>(reader)?; } ...
, Clone, Debug, Hash, Eq, PartialEq)] pub enum Endian { #[allow(missing_docs)] Big, #[allow(missing_docs)] Little, } pub trait Binary { fn is_streamable() -> bool { false } fn size_of_type() -> usize { UNKNOWN_SIZE } fn size_of_value(&self) -> usize ...
random
[ { "content": "/// Trait for handle types that wrap `HandleBase` which wraps an index.\n\n/// The `Default` implementation must initialize the handle to an invalid index.\n\npub trait Handle:\n\n ::std::any::Any + Copy + Clone + Default + ::std::fmt::Debug + Eq + 'static\n\n{\n\n /// Initialize a handle wi...
Rust
src/lib/ui/fuchsia-framebuffer/examples/box.rs
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
use anyhow::{Context as _, Error}; use fuchsia_async::{self as fasync, DurationExt, Timer}; use fuchsia_framebuffer::{ to_565, Config, Frame, FrameBuffer, FrameSet, FrameUsage, ImageId, PixelFormat, VSyncMessage, }; use fuchsia_zircon::DurationNum; use futures::{channel::mpsc::unbounded, future, StreamExt, TryFut...
use anyhow::{Context as _, Error}; use fuchsia_async::{self as fasync, DurationExt, Timer}; use fuchsia_framebuffer::{ to_565, Config, Frame, FrameBuffer, FrameSet, FrameUsage, ImageId, PixelFormat, VSyncMessage, }; use fuchsia_zircon::DurationNum; use futures::{channel::mpsc::unbounded, future, StreamExt, TryFut...
pub fn present_prepared( &mut self, fb: &mut FrameBuffer, sender: Option<futures::channel::mpsc::UnboundedSender<ImageId>>, ) -> Result<bool, Error> { if let Some(prepared) = self.frame_set.prepared { fb.flush_frame(prepared)?; fb.present_frame(prepared,...
black); } else { frame.fill_rectangle(0, 0, config.width, config.height, &to_565(&black)); } available.insert(image_id); } let frame_set = FrameSet::new(available); Ok(FrameManager { frame_set }) }
function_block-function_prefixed
[]
Rust
orchestrator/orchestrator/src/client.rs
sijing-bc/peggy
b7685271b29d16a8494efc4d1a56973873225eb9
#![allow(dead_code)] #[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; mod batch_relaying; mod ethereum_event_watcher; mod main_loop; mod valset_relaying; use crate::main_loop::LOOP_SPEED; use clarity::Address as EthAddress; use clarity::PrivateKey as Eth...
#![allow(dead_code)] #[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; mod batch_relaying; mod ethereum_event_watcher; mod main_loop; mod valset_relaying; use crate::main_loop::LOOP_SPEED; use clarity::Address as EthAddress; use clarity::PrivateKey as Eth...
.await .expect("Failed to send tokens to Cosmos"); info!("Send to Cosmos txid: {:#066x}", tx_id); }
send_to_cosmos( erc20_address, contract_address, amount.clone(), cosmos_dest, ethereum_key, Some(TIMEOUT), &web3, vec![], )
call_expression
[ { "content": "/// takes the required input data and produces the required signature to confirm a validator\n\n/// set update on the Peggy Ethereum contract. This value will then be signed before being\n\n/// submitted to Cosmos, verified, and then relayed to Ethereum\n\n/// Note: This is the message, you need t...
Rust
testkit/src/checkpoint_db.rs
if1242/blockchaincup_case_3_plains
1173cb3e72fb556741d0ef728b45afe528217345
use exonum::storage::{Database, Patch, Result as StorageResult, Snapshot}; use std::sync::{Arc, RwLock}; #[derive(Debug)] pub struct CheckpointDb<T> { inner: Arc<RwLock<CheckpointDbInner<T>>>, } impl<T: Database> CheckpointDb<T> { pub fn new(db: T) -> Self { CheckpointDb { inn...
use exonum::storage::{Database, Patch, Result as StorageResult, Snapshot}; use std::sync::{Arc, RwLock}; #[derive(Debug)] pub struct CheckpointDb<T> { inner: Arc<RwLock<CheckpointDbInner<T>>>, } impl<T: Database> CheckpointDb<T> { pub fn new(db: T) -> Self { CheckpointDb { inn...
}
fn test_extra_rollback() { let db = CheckpointDb::new(MemoryDB::new()); let handler = db.handler(); handler.checkpoint(); handler.checkpoint(); handler.rollback(); handler.rollback(); handler.rollback(); }
function_block-full_function
[ { "content": "pub fn set_index_type(name: &str, index_type: IndexType, is_family: bool, view: &mut Fork) {\n\n if name == INDEXES_METADATA_TABLE_NAME {\n\n panic!(\"Attempt to access an internal storage infrastructure\");\n\n }\n\n let mut metadata = BaseIndex::indexes_metadata(view);\n\n if ...
Rust
lib/deprecated/runtime-core/src/module.rs
slave5vw/wasmer
dd69438efdd629a7b5ae8de53a774f177b0da48a
use crate::{ cache::Artifact, error::{InstantiationError, RuntimeError}, import::{ImportObject, Namespace}, instance::{Instance, PreInstance}, new, typed_func::DynamicCtx, types::{FuncSig, Value}, vm, }; use new::wasmer::Export; use std::{ collections::HashMap, convert::{AsRef, I...
use crate::{ cache::Artifact, error::{InstantiationError, RuntimeError}, import::{ImportObject, Namespace}, instance::{Instance, PreInstance}, new, typed_func::DynamicCtx, types::{FuncSig, Value}, vm, }; use new::wasmer::Export; use std::{ collections::HashMap, convert::{AsRef, I...
{ let mut guard = vmctx.ctx.env.lock().unwrap(); guard.vmctx = pre_instance.vmctx(); } function.vm_function.vmctx.host_env = Box::into_raw(v...
>, env: Box<Mutex<Env>>, } let vmctx: Box< new::wasmer_vm::...
random
[ { "content": "pub fn run_basic_static_function(store: &Store, compiler_name: &str, c: &mut Criterion) {\n\n let module = Module::new(&store, BASIC_WAT).unwrap();\n\n let import_object = imports! {\n\n \"env\" => {\n\n \"multiply\" => Function::new_native(&store, |a: i32, b: i32| a * b),\...
Rust
src/irc/client.rs
museun/riirc
8c225bc5255628ddcf18e85a4d0be3d6efbee18e
use super::message::Error as MessageError; use super::*; use crossbeam_channel as channel; use std::collections::VecDeque; use std::io::{BufRead, BufReader}; use std::net::TcpStream; use std::sync::{Arc, Mutex, RwLock}; use std::thread; use std::time::Instant; #[derive(Debug, PartialEq)] pub enum Error { CannotC...
use super::message::Error as MessageError; use super::*; use crossbeam_channel as channel; use std::collections::VecDeque; use std::io::{BufRead, BufReader}; use std::net::TcpStream; use std::sync::{Arc, Mutex, RwLock}; use std::thread; use std::time::Instant; #[derive(Debug, PartialEq)] pub enum Error { CannotC...
ine).map_err(Error::ParseError) { Ok(msg) => msg, Err(err) => { debug!("error parsing: {:?}", err); err_tx.send(err); return; } }; inner.update(&msg, &Arc:...
let state = Arc::clone(&this.state); let inner = Arc::clone(&this.inner); let addr = addr.into(); thread::spawn(move || { let conn = match TcpStream::connect(&addr).map_err(|_err| Error::CannotConnect) { Ok(conn) => conn, Err(err) => { ...
random
[ { "content": "struct Inner {\n\n client: Option<Rc<irc::Client>>,\n\n errors: Option<Rc<ErrorChannel>>,\n\n}\n\n\n\npub struct State {\n\n inner: RwLock<Inner>,\n\n queue: Rc<MessageQueue<Request>>,\n\n config: Rc<RefCell<Config>>,\n\n buffers: Rc<Buffers>,\n\n}\n\n\n\nimpl State {\n\n pub ...
Rust
src/tpcds.rs
geieredgar/tpctools
5f4d1262d96e16fedb6bb514b11455d86c81a19e
use std::fs; use std::io::Result; use std::path::Path; use std::process::Command; use std::thread; use std::time::Instant; use arrow::datatypes::Schema; use async_trait::async_trait; use crate::Tpc; pub struct TpcDs {} impl TpcDs { pub fn new() -> Self { Self {} } } #[async_trait] impl Tpc for Tp...
use std::fs; use std::io::Result; use std::path::Path; use std::process::Command; use std::thread; use std::time::Instant; use arrow::datatypes::Schema; use async_trait::async_trait; use crate::Tpc; pub struct TpcDs {} impl TpcDs { pub fn new() -> Self { Self {} } } #[async_trait] impl Tpc for Tp...
fn get_table_names(&self) -> Vec<&str> { vec![ "call_center", "catalog_page", "catalog_sales", "catalog_returns", "customer", "customer_address", "customer_demographics", "date_dim", "income_band", ...
n ); let tables = self.get_table_names(); for table in &tables { let output_dir = format!("{}/{}", output_path, table); if !Path::new(&output_dir).exists() { println!("Creating directory {}", output_dir); fs::create_dir(&output_dir)?; ...
function_block-function_prefixed
[ { "content": "#[async_trait]\n\npub trait Tpc {\n\n fn generate(\n\n &self,\n\n scale: usize,\n\n partitions: usize,\n\n input_path: &str,\n\n output_path: &str,\n\n ) -> Result<()>;\n\n fn get_table_names(&self) -> Vec<&str>;\n\n fn get_schema(&self, table: &str) ...
Rust
rust/day10/main.rs
denysvitali/aoc-2021
d333d3eeb15f0e45b638ae76f846d0138e15a914
use std::{env, fs}; use std::collections::{HashMap, VecDeque}; use std::fmt::{Display, Formatter, Write}; use crate::SyntaxError::{Corrupted, Incomplete}; use crate::Token::*; mod test; const DEBUG: bool = false; #[derive(Debug, PartialEq, Copy, Clone, Hash, Eq)] enum Token { OpnRound, ClsRound, OpnSqua...
use std::{env, fs}; use std::collections::{HashMap, VecDeque}; use std::fmt::{Display, Formatter, Write}; use crate::SyntaxError::{Corrupted, Incomplete}; use crate::Token::*; mod test; const DEBUG: bool = false; #[derive(Debug, PartialEq, Copy, Clone, Hash, Eq)] enum Token { OpnRound, ClsRound, OpnSqua...
Incomplete(i) => i, _ => vec![] }) .map(|x| x.iter().map(|y| y.inverse()).collect()) .collect::<Vec<Vec<Token>>>(); let mut results = inc.iter() .map(|x| { let mut res: u64 = 0; for t in x { res = 5 * res + score_map.get...
n>>()) .collect::<Vec<_>>() } #[derive(Debug, PartialEq)] enum SyntaxError { Incomplete(Vec<Token>), Corrupted(Token), } fn check_line(line: &Vec<Token>) -> SyntaxError { let mut stack: VecDeque<Token> = VecDeque::new(); for t in line { if t.is_open() { stack.push_back(t.cl...
random
[ { "content": "fn get_template_and_pairs(input_file: &str) -> (String, HashMap<String, char>) {\n\n let contents = fs::read_to_string(input_file).unwrap();\n\n let s = contents.split(\"\\n\\n\").collect::<Vec<&str>>();\n\n let mut hm: HashMap<String, char> = HashMap::new();\n\n\n\n for l in s[1].spli...
Rust
src/pass/vtpp.rs
maerhart/llhd-rust
40142f9ee20bee32d6942a35138b60902d981f57
use crate::{analysis::PredecessorTable, ir::prelude::*, opt::prelude::*}; use std::collections::{HashMap, HashSet}; pub struct VarToPhiPromotion; impl Pass for VarToPhiPromotion { fn run_on_cfg(_ctx: &PassContext, unit: &mut UnitBuilder) -> bool { info!("VTPP [{}]", unit.name()); let mut modifie...
use crate::{analysis::PredecessorTable, ir::prelude::*, opt::prelude::*}; use std::collections::{HashMap, HashSet}; pub struct VarToPhiPromotion; impl Pass for VarToPhiPromotion { fn run_on_cfg(_ctx: &PassContext, unit: &mut UnitBuilder) -> bool { info!("VTPP [{}]", unit.name()); let mut modifie...
trace!(" Breaking recursion at {}", block.dump(&unit)); return None; } trace!(" Materialize {} in {}", var.dump(&unit), block.dump(&unit)); stack.insert(block); let incoming_values: Vec<_> = pt .pred(block) .flat_map(|bb| { block_outs .ge...
function_block-function_prefix_line
[ { "content": "/// Fold a single instruction.\n\n///\n\n/// Returns `true` if the unit that contains the instruction was modified.\n\npub fn run_on_inst(unit: &mut UnitBuilder, inst: Inst) -> bool {\n\n unit.insert_before(inst);\n\n\n\n // Don't bother folding instructions which don't yield a result.\n\n ...
Rust
src/indices.rs
rust-flann/rust-flann
5985a9bd1c444816860857ab497f9ac376aad7ce
use raw::{self, flann_index_t, FLANNParameters}; use std::os::raw::{c_int, c_uint}; use Indexable; macro_rules! impl_index { ( $t: ty, $r: ty, $build_index: ident, $add_points: ident, $remove_point: ident, $get_point: ident, $veclen: ident, $size: ide...
use raw::{self, flann_index_t, FLANNParameters}; use std::os::raw::{c_int, c_uint}; use Indexable; macro_rules! impl_index { ( $t: ty, $r: ty, $build_index: ident, $add_points: ident, $remove_point: ident, $get_point: ident, $veclen: ident, $size: ide...
, max_nn, radius, flann_params, ) } #[inline] unsafe fn free_index( index_id: flann_index_t, flann_params: *mut FLANNParameters, ) -> c_int { raw::...
) -> flann_index_t { raw::$build_index(dataset, rows, cols, speedup, flann_params) } #[inline] unsafe fn add_points( index_ptr: flann_index_t, points: *mut Self, rows: c_int, columns: c_int, ...
random
[ { "content": "#[test]\n\nfn builds_and_adds() {\n\n let mut index = Index::<f32, typenum::U3>::new(\n\n vec![\n\n Default::default(),\n\n Default::default(),\n\n Default::default(),\n\n Default::default(),\n\n Default::default(),\n\n ],\n\n...
Rust
api/tests/functional/notes.rs
taritom/bn-api
6fbf05bf426c4ddd3d5f50378ac9b51f3ebf2a3f
use crate::functional::base; use crate::support; use crate::support::database::TestDatabase; use crate::support::test_request::TestRequest; use actix_web::{http::StatusCode, web::Path, FromRequest, HttpResponse}; use api::controllers::notes::{self, *}; use api::extractors::*; use api::models::*; use db::prelude::*; #[...
use crate::functional::base; use crate::support; use crate::support::database::TestDatabase; use crate::support::test_request::TestRequest; use actix_web::{http::StatusCode, web::Path, FromRequest, HttpResponse}; use api::controllers::notes::{self, *}; use api::extractors::*; use api::models::*; use db::prelude::*; #[...
y(Roles::Promoter, false).await; } #[actix_rt::test] async fn destroy_promoter_read_only() { base::notes::destroy(Roles::PromoterReadOnly, false).await; } #[actix_rt::test] async fn destroy_org_admin() { base::notes::destroy(Roles::OrgAdmin, true).await; } #[actix_rt::tes...
it; } #[actix_rt::test] async fn destroy_user() { base::notes::destroy(Roles::User, false).await; } #[actix_rt::test] async fn destroy_org_owner() { base::notes::destroy(Roles::OrgOwner, true).await; } #[actix_rt::test] async fn destroy_door_person() { base::n...
random
[ { "content": "#[test]\n\nfn from_str_or_num_to_str_properly_deserializes() {\n\n let event_data = r#\"{\"age_limit\": \"\"}\"#;\n\n let event: EventEditableAttributes = serde_json::from_str(&event_data).unwrap();\n\n assert_eq!(event.age_limit, Some(\"\".to_string()));\n\n\n\n let event_data = r#\"{...
Rust
std/src/gpio/fakes.rs
severak/endbasic
1c6d8878b2dff82aa6b0eb142327425875253bd8
use crate::gpio::{Pin, PinMode, Pins}; use endbasic_core::ast::{Value, VarRef, VarType}; use endbasic_core::syms::{Array, Symbol, Symbols}; use std::io; #[derive(Default)] pub(crate) struct NoopPins {} impl Pins for NoopPins { fn setup(&mut self, _pin: Pin, _mode: PinMode) -> io::Result<()> { Err(io::Er...
use crate::gpio::{Pin, PinMode, Pins}; use endbasic_core::ast::{Value, VarRef, VarType}; use endbasic_core::syms::{Array, Symbol, Symbols}; use std::io; #[derive(Default)] pub(crate) struct NoopPins {} impl Pins for NoopPins { fn setup(&mut self, _pin: Pin, _mode: PinMode) -> io::Result<()> { Err(io::Er...
} fn raw_get(last: i32, data: &Array) -> io::Result<i32> { match data.index(&[last]) { Ok(Value::Integer(v)) => Ok(*v), Ok(_) => panic!("We know it's an integer"), Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e.to_string())), } } ...
match symbols.get_mut(&VarRef::new("__GPIO_MOCK_DATA", VarType::Integer)) { Ok(Some(Symbol::Array(data))) if data.dimensions().len() == 1 => Some(data), _ => None, }
if_condition
[ { "content": "/// Obtains a pin value from an expression.\n\nfn parse_value(expr: &Expr, machine: &mut Machine) -> Result<bool, CallError> {\n\n match expr.eval(machine.get_mut_symbols())? {\n\n Value::Boolean(b) => Ok(b),\n\n v => Err(CallError::ArgumentError(format!(\"Pin value {:?} must be b...
Rust
fixi_cli/src/bin/fixi.rs
leeola/fixity
a0ce643f7f320a50f39477b948e57c73595e7574
use { fixity::{ fixity::Builder, path::Path, value::{Key, Value}, Config, Fixity, }, std::path::PathBuf, structopt::StructOpt, }; #[derive(Debug, StructOpt)] #[structopt(name = "fixi", about = "fixity content management")] struct Opt { #[structopt(flatten)] fixi_...
use { fixity::{ fixity::Builder, path::Path, value::{Key, Value}, Config, Fixity, }, std::path::PathBuf, structopt::StructOpt, }; #[derive(Debug, StructOpt)] #[structopt(name = "fixi", about = "fixity content management")] struct Opt { #[structopt(flatten)] fixi_...
} async fn cmd_map_get(fixi: Fixity, path: Path, key: Key) -> Result<(), Error> { let map = fixi.map(path); let v = map.get(key).await?; println!("{:?}", v); Ok(()) } async fn cmd_map_put( fixi: Fixity, path: Path, commit: bool, key: Key, value: Value, ) -> Result<(), Error> { l...
match subcmd { MapSubcmd::Get { key } => cmd_map_get(fixi, path, key).await, MapSubcmd::Put { commit, key, value } => cmd_map_put(fixi, path, commit, key, value).await, MapSubcmd::Ls { start, end } => cmd_map_ls(fixi, path, start, end).await, }
if_condition
[ { "content": "/// A helper to centralize deserialization logic for a potential future\n\n/// where we change/tweak/configure deserialization.\n\n///\n\n/// How we handle schema/deserialization compatibility is TBD.\n\npub fn deserialize<T>(bytes: &[u8]) -> Result<T, Error>\n\nwhere\n\n T: borsh::BorshDeseria...
Rust
testsuite/forge/src/interface/public.rs
BlockSuite/libra
27c125594ee82c8edb361f0c4cf79c9fa101dd68
use super::Test; use crate::{CoreContext, Result}; use diem_sdk::{ client::{BlockingClient, FaucetClient, MethodRequest}, move_types::account_address::AccountAddress, transaction_builder::{Currency, TransactionFactory}, types::{chain_id::ChainId, transaction::authenticator::AuthenticationKey, LocalAcc...
use super::Test; use crate::{CoreContext, Result}; use diem_sdk::{ client::{BlockingClient, FaucetClient, MethodRequest}, move_types::account_address::AccountAddress, transaction_builder::{Currency, TransactionFactory}, types::{chain_id::ChainId, transaction::authenticator::AuthenticationKey, LocalAcc...
}
pub fn new(json_rpc_url: &'t str, chain_id: ChainId, coffer: Coffer<'t>) -> Self { Self { json_rpc_url, chain_id, coffer, } }
function_block-full_function
[ { "content": "fn tokenize(mut s: &str) -> Result<Vec<Token>> {\n\n let mut v = vec![];\n\n while let Some((tok, n)) = next_token(s)? {\n\n v.push(tok);\n\n s = &s[n..];\n\n }\n\n Ok(v)\n\n}\n\n\n", "file_path": "language/move-core/types/src/parser.rs", "rank": 0, "score": 5...
Rust
src/cpu_scs/shpr3.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register SHPR3"] pub type R = crate::R<u32, super::SHPR3>; #[doc = "Writer for register SHPR3"] pub type W = crate::W<u32, super::SHPR3>; #[doc = "Register SHPR3 `reset()`'s with value 0"] impl crate::ResetValue for super::SHPR3 { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
#[doc = "Reader of register SHPR3"] pub type R = crate::R<u32, super::SHPR3>; #[doc = "Writer for register SHPR3"] pub type W = crate::W<u32, super::SHPR3>; #[doc = "Register SHPR3 `reset()`'s with value 0"] impl crate::ResetValue for super::SHPR3 { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
s = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `RESERVED8`"] pub type RESERVED8_R = crate::R<u8, u8>; #[doc = "Write proxy for field `RESERVED8`"] pub struct RESERVED8_W<'a> { w: &'a mut W, } impl<'a> RESERVED8_W<'a> { #[doc = r"Writes raw bi...
self.w } } #[doc = "Reader of field `PRI_14`"] pub type PRI_14_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PRI_14`"] pub struct PRI_14_W<'a> { w: &'a mut W, } impl<'a> PRI_14_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a ...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/el_gamal/encryption.rs
provotum/rust-crypto
3f284c3e6f3e3412a44d3cea11cd6487862c0d9f
use ::arithmetic::mod_int::From; use ::arithmetic::mod_int::ModInt; use ::arithmetic::mod_int::RandModInt; use ::el_gamal::ciphertext::CipherText; use num::traits::Pow; use num::Zero; use num::One; use std::fs::File; use std::io::{Read, Write}; use serde_json; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct...
use ::arithmetic::mod_int::From; use ::arithmetic::mod_int::ModInt; use ::arithmetic::mod_int::RandModInt; use ::el_gamal::ciphertext::CipherText; use num::traits::Pow; use num::Zero; use num::One; use std::fs::File; use std::io::{Read, Write}; use serde_json; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct...
pub fn to_file(&self, private_key_file_name: &str) { let mut file = File::create("./".to_owned() + private_key_file_name).unwrap(); let private_key_str = serde_json::to_string_pretty(&self).unwrap(); file.write(private_key_str.as_bytes()).unwrap(); } ...
pub fn new(private_key_file_name: &str) -> Self { let mut file = File::open("./".to_owned() + private_key_file_name).unwrap(); let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); let private_key: PrivateKey = match serde_json::from_str(&contents) { ...
function_block-full_function
[ { "content": "///\n\n/// # Modular Inverse\n\n///\n\n/// Calculates the modular inverse `a^-1 mod m`\n\n///\n\n/// ## Credits\n\n/// Inspired by [simon-andrews/rust-modinverse](https://github.com/simon-andrews/rust-modinverse)\n\n///\n\npub fn mod_inverse(a: BigInt, m: BigInt) -> Option<BigInt> {\n\n let (g,...
Rust
monument/lib/src/layout/new/leadwise.rs
kneasle/ringing-monorepo
c0cc2d62af3da9f7b7d49dcf7e6cc202632053e3
use std::{collections::HashMap, ops::Deref}; use bellframe::{Mask, Row, RowBuf}; use index_vec::IndexVec; use super::{Boundary, Result}; use crate::{ layout::{BlockIdx, BlockVec, Layout, Link, LinkVec, MethodBlock, RowIdx, StartOrEnd}, CallVec, SpliceStyle, }; const LEADWISE_PREFIX: &str = "#"; pub fn leadw...
use std::{collections::HashMap, ops::Deref}; use bellframe::{Mask, Row, RowBuf}; use index_vec::IndexVec; use super::{Boundary, Result}; use crate::{ layout::{BlockIdx, BlockVec, Layout, Link, LinkVec, MethodBlock, RowIdx, StartOrEnd}, CallVec, SpliceStyle, }; const LEADWISE_PREFIX: &str = "#"; pub fn leadw...
); } super::utils::dedup_links(&mut links); links.into() } fn plain_link(from: RowIdx, to: RowIdx, ch_mask: &Mask, ch_transposition: RowBuf) -> Link { Link { from, to, ch_mask: ch_mask.clone(), ch_transposition, call_idx: None, calling_position: S...
plain_link( RowIdx { block: method_idx_from.into(), row: method_from.lead_len() - 1, }, RowIdx { block: method_idx_from.into(), row: 0, }, lead_head_mask, method_from....
call_expression
[ { "content": "/// For each lead label, list the positions in the course where calls at that label could start\n\n/// (Monument assumes that all courses always replace one piece of [`PlaceNot`]ation).\n\nfn call_starts_by_label(methods: &[super::Method]) -> HashMap<&str, Vec<RowIdx>> {\n\n let mut label_indic...
Rust
util/libeir_util_number/src/binary.rs
eirproject/eir
a615a9d41563f2632a0e51bcdb99fba673b380cc
use crate::Integer; use libeir_util_binary::{Endian, BitCarrier, BitRead, BitSlice, integer_to_carrier}; impl BitCarrier for Integer { type T = u8; fn bit_len(&self) -> usize { match self { Integer::Big(bi) => bi.bit_len(), Integer::Small(si) => si.bit_len(), } } } ...
use crate::Integer; use libeir_util_binary::{Endian, BitCarrier, BitRead, BitSlice, integer_to_carrier}; impl BitCarrier for Integer { type T = u8; fn bit_len(&self) -> usize { match self { Integer::Big(bi) => bi.bit_len(), Integer::Small(si) => si.bit_len(), } } } ...
#[test] fn signed_big_endian_bigint() { let num = -20; let bs1 = Integer::Big(num.into()).encode_bitstring(12, Endian::Big); let mut b1 = BitVec::new(); b1.push(&bs1); let parts = (b1.get(0).unwrap(), b1.get(1).unwrap()); assert_eq!(parts, (254, 12 << 4)); ...
b1.push(&bs1); let parts = (b1.get(0).unwrap(), b1.get(1).unwrap()); assert_eq!(parts, (20, 0 << 4)); }
function_block-function_prefix_line
[ { "content": "pub fn integer_to_carrier(mut int: BigInt, bits: usize, endian: Endian) -> BitSlice<Vec<u8>> {\n\n let negative = int < 0;\n\n if negative {\n\n int += 1;\n\n }\n\n\n\n let keep_bytes = (bits + 7) / 8;\n\n let aux_bits = bits % 8;\n\n\n\n let (_sign, mut digits) = match en...
Rust
src/ui.rs
vanhine/padantic
cb44059a23f7d20b1545773ab7b937ae6d3592ed
use crate::msg::Messages; use std::sync::Mutex; use std::time::{ Duration, Instant }; use std::thread; use tui::terminal::{ Terminal, Frame }; use tui::backend::Backend; use tui::widgets::{ Block, Borders, Text, Paragraph, Widget }; use tui::layout::{ Layout, Alignment, Direction, Constraint }; use tui::style::{ Colo...
use crate::msg::Messages; use std::sync::Mutex; use std::time::{ Duration, Instant }; use std::thread; use tui::terminal::{ Terminal, Frame }; use tui::backend::Backend; use tui::widgets::{ Block, Borders, Text, Paragraph, Widget }; use tui::layout::{ Layout, Alignment, Direction, Constraint }; use tui::style::{ Colo...
; } } pub fn draw_loop<T: Backend>(&self, term: &mut Terminal<T>) { while !{ *self.done.lock().unwrap() } { term.draw(|f| self.draw(f)).unwrap(); thread::sleep(Duration::from_millis(10)); } } pub fn draw<F: Backend>(&self, mut f: Frame<F>) { Scre...
match event::read().unwrap() { Event::Key(e) => match e.code { KeyCode::Char('c') if e.modifiers.contains(KeyModifiers::CONTROL) => std::process::exit(0), _ => () }, _ => () }
if_condition
[ { "content": "pub fn plain(block: Vec<u8>, index: u8, block_index: usize) -> Messages {\n\n Messages::Plain(BlockData::new(block, index, block_index))\n\n}\n", "file_path": "src/msg.rs", "rank": 1, "score": 133872.2019202841 }, { "content": "pub fn pyld(block: Vec<u8>, index: u8, block_in...
Rust
src/error.rs
emlun/time-rs
1a4b1a0901ddd8759c34ee891ae10975efe701a1
pub use crate::format::parse::Error as Parse; #[cfg(not(feature = "std"))] use alloc::boxed::Box; use core::fmt; #[allow(clippy::missing_docs_in_private_items)] #[cfg_attr(__time_02_supports_non_exhaustive, non_exhaustive)] #[derive(Debug, Clone, PartialEq, Eq)] pub enum Error { ConversionRange(ConversionRange), ...
pub use crate::format::parse::Error as Parse; #[cfg(not(feature = "std"))] use alloc::boxed::Box; use core::fmt; #[allow(clippy::missing_docs_in_private_items)] #[cfg_attr(__time_02_supports_non_exhaustive, non_exhaustive)] #[derive(Debug, Clone, PartialEq, Eq)] pub enum Error { ConversionRange(ConversionRange), ...
} } #[cfg(feature = "std")] impl std::error::Error for Format { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Format::StdFmtError => Some(&fmt::Error), _ => None, } } } impl From<fmt::Error> for Format { fn from(_: fmt::Error) ->...
match self { Format::InsufficientTypeInformation => { f.write_str("The format provided requires more information than the type provides.") } Format::StdFmtError => fmt::Error.fmt(f), #[cfg(not(__time_02_supports_non_exhaustive))] Format::__NonE...
if_condition
[ { "content": "fn format_std() -> error::Format {\n\n std::fmt::Error.into()\n\n}\n\n\n", "file_path": "tests/error.rs", "rank": 0, "score": 236922.7016076039 }, { "content": "/// Parse any parsable type from the time crate.\n\n///\n\n/// This is identical to calling `T::parse(s, format)`,...
Rust
src/main.rs
madig/Fontgardener
f08eacb6ff97e8be7bd9ebd7821914e2ebacc477
use std::{ collections::{HashMap, HashSet}, path::{Path, PathBuf}, }; use anyhow::{Context, Result}; use clap::{ArgGroup, CommandFactory, Parser, Subcommand}; use norad::Name; use structs::Fontgarden; mod errors; mod structs; mod util; #[derive(Parser)] #[clap(author, version, about, long_abou...
use std::{ collections::{HashMap, HashSet}, path::{Path, PathBuf}, }; use anyhow::{Context, Result}; use clap::{ArgGroup, CommandFactory, Parser, Subcommand}; use norad::Name; use structs::Fontgarden; mod errors; mod structs; mod util; #[derive(Parser)] #[clap(author, version, about, long_abou...
et in fontgarden.sets.values() { names.extend(set.sources.keys().cloned()); } names } else { source_names.iter().cloned().collect() }; let ufos = fontgarden .export(&glyph_names, &source_names) .expect("can't export to ufos"); let output_di...
names, output_dir.as_ref(), )?; } } Ok(()) } fn new(path: &Path) -> Result<()> { let fontgarden = Fontgarden::new(); fontgarden.save(path)?; Ok(()) } fn import( glyphs_files: &[PathBuf], sets: &[Name], fontgarden_path: &Path, ...
random
[ { "content": "fn default_true() -> bool {\n\n true\n\n}\n\n\n\nimpl Fontgarden {\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n pub fn from_path(path: &Path) -> Result<Self, LoadError> {\n\n let mut fontgarden = Self::new();\n\n let mut seen_glyph_names: HashSet<Na...
Rust
utils/src/lib.rs
Yirmandias/aries
c530115195b146763a726ccac1ddc56180caa4a9
pub mod input; use std::fmt::{Display, Error, Formatter}; pub struct Fmt<F>(pub F) where F: Fn(&mut std::fmt::Formatter) -> std::fmt::Result; impl<F> std::fmt::Display for Fmt<F> where F: Fn(&mut std::fmt::Formatter) -> std::fmt::Result, { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { ...
pub mod input; use std::fmt::{Display, Error, Formatter}; pub struct Fmt<F>(pub F) where F: F
assert_eq!(enumerate(vec![1..2, 1..2, 1..2, 1..2]).count(), 1); assert_eq!(enumerate(vec![1..3, 1..2, 1..2, 1..2]).count(), 2); assert_eq!(enumerate(vec![1..3, 1..3, 1..2, 1..2]).count(), 4); assert_eq!(enumerate(vec![1..3, 1..3, 1..3, 1..2]).count(), 8); assert_eq!(enumerate(vec![...
n(&mut std::fmt::Formatter) -> std::fmt::Result; impl<F> std::fmt::Display for Fmt<F> where F: Fn(&mut std::fmt::Formatter) -> std::fmt::Result, { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { (self.0)(f) } } #[allow(clippy::while_let_on_iterator)] pub fn disp_iter<T: Display>(f...
random
[ { "content": "pub fn parse_pddl_domain(pb: Input) -> Result<Domain> {\n\n let expr = parse(pb)?;\n\n read_domain(expr).context(\"Invalid domain\")\n\n}\n", "file_path": "planning/src/parsing/pddl.rs", "rank": 1, "score": 123153.94954354233 }, { "content": "pub fn parse_pddl_problem(pb:...
Rust
packages/canvas/src-native/canvas-native/canvas-core/src/common/svg/elements/symbol.rs
farfromrefug/canvas
934b5a38e17354750ddd8ef50361fc57c8a6133f
use roxmltree::Node; use crate::common::context::Context; use crate::common::svg::attribute_names::{Attribute, NodeExt}; use crate::common::svg::bounding_box::BoundingBox; use crate::common::svg::elements::parser::{Parser, style_from, StyleMap}; use crate::common::svg::elements::renderer::{handle_render_child, handle_...
use roxmltree::Node; use crate::common::context::Context; use crate::common::svg::attribute_names::{Attribute, NodeExt}; use crate::common::svg::bounding_box::BoundingBox; use crate::common::svg::elements::parser::{Parser, style_from, StyleMap}; use crate::common::svg::elements::renderer::{handle_render_child, handle_...
} impl Renderer for Symbol { fn render(&mut self, context: &mut Context, node: Node, root_element: Node) {} fn bounding_box(&self) -> BoundingBox { self.bounding_box } }
f() { if view_box.width() == 0.0 || view_box.height() == 0.0 { return; } } let max_view_box = parent_view_box; let x = convert_length( x, Attribute::X, Units::UserSpaceOnUse, device, &max_view_b...
function_block-function_prefixed
[ { "content": "pub fn handle_render_children(context: &mut Context, children: &mut Children, root_element: Node) {\n\n handle_render_children_with_bounding_box(context, children, root_element, None, None)\n\n}\n\n\n", "file_path": "packages/canvas/src-native/canvas-native/canvas-core/src/common/svg/elemen...
Rust
src/parse.rs
teozkr/duplicate
0482ec745a2c00569f04c1f0d91f0e98230e749f
use crate::{ parse_utils::*, substitute::{duplicate_and_substitute, Substitution}, DuplicationDefinition, Result, SubstitutionGroup, }; use proc_macro::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; use std::{ collections::HashSet, iter::{FromIterator, Peekable}, }; pub(crate) fn parse_invocation(attr: ...
use crate::{ parse_utils::*, substitute::{duplicate_and_substitute, Substitution}, DuplicationDefinition, Result, SubstitutionGroup, }; use proc_macro::{Delimiter, Group, Ident, Span, TokenStream, TokenTree}; use std::{ collections::HashSet, iter::{FromIterator, Peekable}, }; pub(crate) fn parse_invocation(attr: ...
fn extract_verbose_substitutions( tree: TokenTree, existing: &Option<HashSet<(String, usize)>>, ) -> Result<SubstitutionGroup> { let tree_span = tree.span(); let group = check_group( tree, Delimiter::Bracket, "Hint: When using verbose syntax, a substitutions must be enclosed in a \ group.\nExample:\n.....
en(stream, Span::call_site(), "Substitution identifier")?; if let TokenTree::Ident(ident) = token { let _ = stream.next(); let group_1 = peek_parse_group(stream, Some(Delimiter::Parenthesis), ident.span(), ""); if let Ok(params) = group_1 { let _ = stream.next(); parse_group( stream, Some(Deli...
function_block-function_prefixed
[ { "content": "/// Implements the macro.\n\n///\n\n/// `allow_short`: If true, accepts short syntax\n\nfn duplicate_impl(attr: TokenStream, item: TokenStream) -> Result<TokenStream>\n\n{\n\n\tlet dup_def = parse_invocation(attr)?;\n\n\n\n\tduplicate_and_substitute(\n\n\t\titem,\n\n\t\t&dup_def.global_substitutio...
Rust
apps/ltn/src/per_neighborhood.rs
lucasccdias/abstreet
cf88a2a13396d1872f5165f54189c753b9686d21
use geom::Distance; use map_model::{IntersectionID, PathConstraints, RoadID}; use widgetry::mapspace::{ObjectID, World, WorldOutcome}; use widgetry::tools::open_browser; use widgetry::{ lctrl, EventCtx, Image, Key, Line, Panel, PanelBuilder, Text, TextExt, Widget, DEFAULT_CORNER_RADIUS, }; use crate::rat_runs:...
use geom::Distance; use map_model::{IntersectionID, PathConstraints, RoadID}; use widgetry::mapspace::{ObjectID, World, WorldOutcome}; use widgetry::tools::open_browser; use widgetry::{ lctrl, EventCtx, Image, Key, Line, Panel, PanelBuilder, Text, TextExt, Widget, DEFAULT_CORNER_RADIUS, }; use crate::rat_runs:...
if !PathConstraints::Car.can_use_road(road, map) { return true; } app.session.modal_filters.before_edit(); if app.session.modal_filters.roads.remove(&r).is_none() { let ...
tooltip(Text::from(format!( "{} rat-runs cross this intersection", rat_runs.count_per_intersection.get(*i) ))) .clickable() .hotkey(lctrl(Key::D), "debug") .build(ctx); } world.initialize_hover(ctx); world } pub fn handle_worl...
random
[ { "content": "pub fn execute(ctx: &mut EventCtx, app: &mut App, id: ID, action: &str) -> Transition {\n\n let mut tut = app.session.tutorial.as_mut().unwrap();\n\n let response = match (id, action) {\n\n (ID::Car(c), \"draw WASH ME\") => {\n\n let is_parked = app\n\n .prim...
Rust
psila-data/src/network/commands/link_status.rs
grenewode/psila
d11737a6ddffeb19937d3b224121599cbc00e6ed
use core::default::Default; use crate::error::Error; use crate::pack::{Pack, PackFixed}; use crate::NetworkAddress; const INCOMING_COST_MASK: u8 = 0b0000_0111; const OUTGOING_COST_MASK: u8 = 0b0111_0000; const LINK_STATUS_ENTRY_SIZE: usize = 3; #[derive(Copy, Clone, Debug, PartialEq)] pub struct LinkStatusEntry { ...
use core::default::Default; use crate::error::Error; use crate::pack::{Pack, PackFixed}; use crate::NetworkAddress; const INCOMING_COST_MASK: u8 = 0b0000_0111; const OUTGOING_COST_MASK: u8 = 0b0111_0000; const LINK_STATUS_ENTRY_SIZE: usize = 3; #[derive(Copy, Clone, Debug, PartialEq)] pub struct LinkStatusEntry { ...
let mut entries = [LinkStatusEntry::default(); 32]; for entry in entries[..num_entries as usize].iter_mut() { *entry = LinkStatusEntry::unpack(&data[offset..offset + LINK_STATUS_ENTRY_SIZE])?; offset += LINK_STATUS_ENTRY_SIZE; } Ok(( LinkStatus { ...
entries, } } } impl Pack<LinkStatus, Error> for LinkStatus { fn pack(&self, data: &mut [u8]) -> Result<usize, Error> { assert!(self.num_entries <= 32); if data.len() < (1 + ((self.num_entries as usize) * LINK_STATUS_ENTRY_SIZE)) { return Err(Error::WrongNumberOf...
random
[ { "content": "/// Zero out all values in the slice\n\npub fn clear(slice: &mut [u8]) {\n\n for v in slice.iter_mut() {\n\n *v = 0;\n\n }\n\n}\n", "file_path": "psila-data/src/utils.rs", "rank": 0, "score": 191267.0437528677 }, { "content": "/// Convert link quality to path cost\...
Rust
sample/src/cli.rs
p2pderivatives/rust-dlc
5df14bac49f7abcf9b62d9bb498783fecad49543
use crate::hex_utils; use crate::DlcManager; use crate::DlcMessageHandler; use crate::PeerManager; use bitcoin::network::constants::Network; use bitcoin::secp256k1::key::PublicKey; use dlc_manager::contract::contract_input::ContractInput; use dlc_manager::contract::{ClosedContract, Contract}; use dlc_manager::Storage;...
use crate::hex_utils; use crate::DlcManager; use crate::DlcMessageHandler; use crate::PeerManager; use bitcoin::network::constants::Network; use bitcoin::secp256k1::key::PublicKey; use dlc_manager::contract::contract_input::ContractInput; use dlc_manager::contract::{ClosedContract, Contract}; use dlc_manager::Storage;...
pub(crate) fn parse_peer_info( peer_pubkey_and_ip_addr: String, ) -> Result<(PublicKey, SocketAddr), std::io::Error> { let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@"); let pubkey = pubkey_and_addr.next(); let peer_addr_str = pubkey_and_addr.next(); if peer_addr_str.is_none() || peer_addr_str.is_none...
bkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>, ) -> Result<(), ()> { for node_pubkey in peer_manager.get_peer_node_ids() { if node_pubkey == pubkey { return Ok(()); } } match lightning_net_tokio::connect_outbound(Arc::clone(&peer_manager), pubkey, peer_addr).await { Some(connecti...
function_block-function_prefixed
[ { "content": "fn pubkey_path(host: &str) -> String {\n\n format!(\"{}{}\", host, \"oracle/publickey\")\n\n}\n\n\n", "file_path": "p2pd-oracle-client/src/lib.rs", "rank": 0, "score": 281767.48517926014 }, { "content": "fn attestation_path(host: &str, asset_id: &str, date_time: &DateTime<Ut...
Rust
testing/jormungandr-testing-utils/src/testing/fragments/generator.rs
rmourey26/jormungandr
e5d13409b931a58aee3ea72a5729a99f068b6043
use super::{FragmentSender, FragmentSenderError, MemPoolCheck}; use crate::testing::SyncNode; use crate::{ stake_pool::StakePool, testing::{RemoteJormungandr, VotePlanBuilder}, wallet::Wallet, }; use chain_core::property::FromStr; use chain_impl_mockchain::{ certificate::{VotePlan, VoteTallyPayload}, ...
use super::{FragmentSender, FragmentSenderError, MemPoolCheck}; use crate::testing::SyncNode; use crate::{ stake_pool::StakePool, testing::{RemoteJormungandr, VotePlanBuilder}, wallet::Wallet, }; use chain_core::property::FromStr; use chain_impl_mockchain::{ certificate::{VotePlan, VoteTallyPayload}, ...
.build(), ) }) .take(self.vote_plans_for_tally_count) .collect(); for vote_plan in vote_plans_for_tally.iter() { self.fragment_sender .send_vote_plan(&mut self.sender, &vote_plan, &self.node) .unwrap(); } ...
ippy::too_many_arguments)] pub fn new( sender: Wallet, receiver: Wallet, node: RemoteJormungandr, slots_per_epoch: u32, stake_pools_count: usize, vote_plans_for_tally_count: usize, fragment_sender: FragmentSender<'a, S>, ) -> Self { assert!(stake_p...
random
[ { "content": "pub trait PrepareNodeSettings: Clone + Send {\n\n fn prepare<RNG>(alias: NodeAlias, context: &mut Context<RNG>, template: &NodeTemplate) -> Self\n\n where\n\n RNG: RngCore + CryptoRng;\n\n}\n\n\n", "file_path": "testing/jormungandr-scenario-tests/src/scenario/settings.rs", "ra...
Rust
daemon/platform/windows/process_helper.rs
slooppe/pueue
ee71ad7c6eb05788af063fd98a649b02c006cbb1
use std::process::{Child, Command}; use anyhow::{bail, Result}; use log::{error, info, warn}; use winapi::shared::minwindef::FALSE; use winapi::shared::ntdef::NULL; use winapi::um::errhandlingapi::GetLastError; use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE}; use winapi::um::processthreadsapi::{ Ope...
use std::process::{Child, Command}; use anyhow::{bail, Result}; use log::{error, info, warn}; use winapi::shared::minwindef::FALSE; use winapi::shared::ntdef::NULL; use winapi::um::errhandlingapi::GetLastError; use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE}; use winapi::um::processthreadsapi::{ Ope...
fn get_child_pids(target_pid: u32, pid_list: &mut Vec<u32>) { unsafe { let snapshot_handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, target_pid); if snapshot_handle == INVALID_HANDLE_VALUE { error!("Failed to get process {} snapShot", target_pid); ret...
k_processes(task_pid: u32) -> Vec<u32> { let mut all_pids = Vec::new(); let mut parent_pids = vec![task_pid]; while let Some(pid) = parent_pids.pop() { all_pids.push(pid); get_child_pids(pid, &mut parent_pids); } all_pids.reverse(); all_pids }
function_block-function_prefixed
[ { "content": "/// Send a signal to one of Pueue's child process handles.\n\n///\n\n/// There are two scenarios:\n\n///\n\n/// **Normal case**\n\n///\n\n/// A task, such as `sleep 60` get's spawned by the posix shell `sh`.\n\n/// This results in the process `sh -c 'sleep 60'`.\n\n/// Since the posix shell doesn'...
Rust
tests/ping_runner_core_tests.rs
r12f/rnp
9ba561a8104a81f510d75d30f87df1c2668384f3
mod test_common; mod test_mocks; use futures_intrusive::sync::ManualResetEvent; use pretty_assertions::assert_eq; use rnp::*; use std::sync::{Arc, Mutex}; use std::time::Duration; use test_mocks::*; use tokio::runtime::Runtime; #[test] fn ping_with_rnp_core_should_work() { test_common::initialize(); let actu...
mod test_common; mod test_mocks; use futures_intrusive::sync::ManualResetEvent; use pretty_assertions::assert_eq; use rnp::*; use std::sync::{Arc, Mutex}; use std::time::Duration; use test_mocks::*; use tokio::runtime::Runtime; #[test] fn ping_with_rnp_core_should_work() { test_common::initialize(); let actu...
ngClientResult::AppHandshakeFailed(Duration::from_millis(20)), MockPingClientResult::DisconnectFailed(Duration::from_millis(30)), ], *results ); } #[test] fn ping_with_rnp_core_stress_should_work() { test_common::initialize(); let actual_ping_results = Arc::new(Mutex::new(Vec::...
et mut rp = PingRunnerCore::new(config, stop_event); rp.run_warmup_pings().await; rp.start_running_normal_pings(); rp.join().await; }); let results = actual_ping_results.lock().unwrap(); assert_eq!( vec![ MockPingClientResult::Success(Duration::from_millis(10)), ...
random
[ { "content": "fn start_run_tcp_stub_server(rt: &Runtime, stub_server_config: RnpStubServerConfig) {\n\n let ready_event = Arc::new(ManualResetEvent::new(false));\n\n let ready_event_clone = ready_event.clone();\n\n rt.spawn(async move {\n\n let _ = stub_server_factory::run(&stub_server_config, A...
Rust
examples/ball_comp.rs
XX/exgui_relyon_glium
4531a07d783259a429b4a7e25347a516669e8182
use exgui_renderer_nanovg::NanovgRenderer; use exgui_controller_glutin::{App, AppState, glutin}; use exgui::{ egml, Component, Shapeable, ChangeView, Node, Comp, Color, Pct, Real, SystemMessage }; struct Model { normal: bool, } #[derive(Copy, Clone)] enum ModelMsg { Ball(BallMsg), } impl Component fo...
use exgui_renderer_nanovg::NanovgRenderer; use exgui_controller_glutin::{App, AppState, glutin}; use exgui::{ egml, Component, Shapeable, ChangeView, Node, Comp, Color, Pct, Real, SystemMessage }; struct Model { normal: bool, } #[derive(Copy, Clone)] enum ModelMsg { Ball(BallMsg), } impl Component fo...
l>(()); comp.resolve(None); app.run_proc(&mut comp, |app, _comp| { let (dims, hdpi) = (app.dimensions(), app.window().hidpi_factor()); app.renderer_mut().set_dimensions(dims, hdpi); AppState::Continue }).unwrap(); }
ggle, /> } } } fn main() { let mut app = App::new( glutin::WindowBuilder::new() .with_title("ExGUI ball comp") .with_dimensions(480, 480), glutin::ContextBuilder::new() .with_vsync(true) .with_multisampling(4) .with_srgb(true),...
random
[ { "content": "#[derive(Debug)]\n\nstruct Model;\n\n\n\nimpl Component for Model {\n\n type Message = ();\n\n type Properties = ();\n\n\n\n fn create(_props: &Self::Properties) -> Self {\n\n Model\n\n }\n\n\n\n fn update(&mut self, _msg: Self::Message) -> ChangeView {\n\n ChangeView:...
Rust
gdnative-core/src/nativescript/profiler.rs
chitoyuu/godot-rust
e74c57338e76922bd191670eff967d7fe256f436
use std::borrow::Cow; use std::convert::TryFrom; use std::ffi::{CStr, CString}; use std::time::{Duration, Instant}; use crate::private::try_get_api; #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct Signature<'a> { sig: Cow<'a, CStr>, } impl<'a> Signature<'a> { #[inline(alway...
use std::borrow::Cow; use std::convert::TryFrom; use std::ffi::{CStr, CString}; use std::time::{Duration, Instant}; use crate::private::try_get_api; #[derive(Clone, Eq, PartialEq, Hash, Debug)] pub struct Signature<'a> { sig: Cow<'a, CStr>, } impl<'a> Signature<'a> { #[inline(alway...
#[macro_export] macro_rules! _profile_sig { ($tag:expr) => { $crate::nativescript::profiler::Signature::new(file!(), line!(), $tag) }; } pub use _profile_sig as profile_sig;
pub fn profile<F, R>(signature: Signature<'_>, f: F) -> R where F: FnOnce() -> R, { let start = Instant::now(); let ret = f(); add_data(signature, Instant::now() - start); ret }
function_block-full_function
[ { "content": "pub fn module_name_from_class_name(class_name: &str) -> String {\n\n // Remove underscores and make peekable\n\n let mut class_chars = class_name.bytes().filter(|&ch| ch != b'_').peekable();\n\n\n\n // 2-lookbehind\n\n let mut previous: [Option<u8>; 2] = [None, None]; // previous-previ...
Rust
src/theca/utils.rs
buddyw/theca
731b33c14c6723895a0244df664c4645e8eb789b
use std::fs::{read_dir, File}; use std::io::{Write, Read}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::env::{var}; use std::cmp::Ordering; use std::iter::repeat; use std::time::UNIX_EPOCH; use time::{OffsetDateTime, UtcOffset}; use term::{self, stdout}; use term::Attr::Bold; use ru...
use std::fs::{read_dir, File}; use std::io::{Write, Read}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::env::{var}; use std::cmp::Ordering; use std::iter::repeat; use std::time::UNIX_EPOCH; use time::{OffsetDateTime, UtcOffset}; use term::{self, stdout}; use term::Attr::Bold; use ru...
if tty { t.attr(Bold)?; } write!(t, "{1}{0}{2}{0}{3}{4}\n{5}\n", column_seperator, format_field(&"id".to_string(), line_format.id_width, false), format_field(&"title".to_string(), line_format.title_width, false), status...
let status = if line_format.status_width == 0 { "".to_string() } else { format_field(&"status".to_string(), line_format.status_width, false) + &*column_seperator };
assignment_statement
[ { "content": "pub fn parse_cmds(profile: &mut Profile, args: &mut Args, profile_fingerprint: &u64) -> Result<()> {\n\n let status = extract_status(args.flag_none, args.flag_started, args.flag_urgent)?;\n\n let flags = BoolFlags::from_args(args);\n\n\n\n if [args.cmd_add,\n\n args.cmd_edit,\n\n ...
Rust
src/output.rs
adlane/exec_duration
0aaefe20d00875921e16f01589ab093d8c71be5c
use std::fmt; use std::time::Duration; pub(crate) type DurationUnit = u128; #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct ExecDuration { name: String, count: u64, duration: DurationUnit, total: DurationU...
use std::fmt; use std::time::Duration; pub(crate) type DurationUnit = u128; #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct ExecDuration { name: String, count: u64, duration: DurationUnit, total: DurationU...
}
f.get_avg_duration(), )?; for v in self.childs.iter() { write!(f, "[{}] {}", self.name, v)?; } Ok(()) }
function_block-function_prefixed
[ { "content": "/// Fetch execution metrics.\n\n/// Typically, this function needs to be called once the execution of all measured blocks is done.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use exec_duration;\n\n/// use exec_duration::ExecProbe;\n\n///\n\n/// let mut ep = ExecProbe::new(\"main\");\n\n///\n\n/// /...
Rust
src/derive/ty_impls/transpose.rs
taiki-e/auto_enums
906f84e56b0365f5605ecdc65c32ed1fbcb9029c
use derive_utils::EnumImpl; use proc_macro2::TokenStream; use quote::ToTokens; use syn::TypeParam; use crate::derive::*; pub(crate) const NAME: &[&str] = &["Transpose"]; pub(crate) fn derive(data: &Data) -> Result<TokenStream> { check_fields(data)?; let mut items = TokenStream::new(); items.extend(transp...
use derive_utils::EnumImpl; use proc_macro2::TokenStream; use quote::ToTokens; use syn::TypeParam; use crate::derive::*; pub(crate) const NAME: &[&str] = &["Transpose"]; pub(crate) fn derive(data: &Data) -> Result<TokenStream> { check_fields(data)?; let mut items = TokenStream::new(); items.extend(transp...
} fn transpose_option(data: &Data) -> TokenStream { let ident = &data.ident; let mut impl_ = EnumImpl::new(data); let transpose = data.variant_idents().map(|v| quote!(#ident::#v(x) => x.map(#ident::#v))); let fields = data.field_types(); impl_.push_item(parse_quote! { #[inline] f...
if quote!(#generics).to_string() == quote!(<#(#fields),*#comma>).to_string() { Ok(()) } else { Err(error!(data, "all fields need to be generics")) }
if_condition
[ { "content": "fn expand_parent_item_fn(cx: &mut Context, item: &mut ItemFn) -> Result<()> {\n\n let ItemFn { sig, block, .. } = item;\n\n if let ReturnType::Type(_, ty) = &mut sig.output {\n\n match &**ty {\n\n // `return`\n\n Type::ImplTrait(_) if cx.visit_last_mode != VisitL...
Rust
src/sync/client.rs
liubin/ttrpc-rust
72beb9337d2f407fc8a4cf60443646830642e181
use nix::sys::socket::*; use nix::unistd::close; use protobuf::{CodedInputStream, CodedOutputStream, Message}; use std::collections::HashMap; use std::os::unix::io::RawFd; use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::{io, thread}; #[cfg(target_os = "macos")] use crate::common::set_fd_close_exec; use cr...
use nix::sys::socket::*; use nix::unistd::close; use protobuf::{CodedInputStream, CodedOutputStream, Message}; use std::collections::HashMap; use std::os::unix::io::RawFd; use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::{io, thread}; #[cfg(target_os = "macos")] use crate::common::set_fd_close_exec; use cr...
) .unwrap_or_else(|_e| error!("The request has returned")); continue; } recver_tx .send(Ok(buf)) .unwrap_or_else(|_e| error!("The request has returned")); map.remove(&mh.stream_id); ...
Err(Error::Others(format!( "Recver got malformed packet {:?} {:?}", mh, buf )))
call_expression
[ { "content": "pub fn write_message(fd: RawFd, mh: MessageHeader, buf: Vec<u8>) -> Result<()> {\n\n write_message_header(fd, mh)?;\n\n\n\n let size = write_count(fd, &buf, buf.len())?;\n\n if size != buf.len() {\n\n return Err(sock_error_msg(\n\n size,\n\n format!(\"Send Mes...
Rust
dialectic/benches/micro.rs
boltlabs-inc/dialectic
0d545aceb4a204b4d412e8fcf877ff2a41e35c3b
use criterion::{ async_executor::AsyncExecutor, criterion_group, criterion_main, measurement::WallTime, Bencher, BenchmarkGroup, Criterion, }; use dialectic::prelude::*; use dialectic_null as null; use dialectic_tokio_mpsc as mpsc; use futures::Future; use std::{convert::TryInto, fmt::Debug, marker, sync::Arc, ...
use criterion::{ async_executor::AsyncExecutor, criterion_group, criterion_main, measurement::WallTime, Bencher, BenchmarkGroup, Criterion, }; use dialectic::prelude::*; use dialectic_null as null; use dialectic_tokio_mpsc as mpsc; use futures::Future; use std::{convert::TryInto, fmt::Debug, marker, sync::Arc, ...
), channel, "choose", Choose, choose); bench_chan_loop_group(&mut g, rt.clone(), channel, "offer", Offer, offer); bench_chan_loop_group(&mut g, rt.clone(), channel, "call", Call, call); bench_chan_loop_group(&mut g, rt, channel, "split", Split, split); g.finish(); } fn bench_tokio_null(c: &mut Criterio...
let group_name = format!("{}/{}", rt_name, backend_name); let mut g = c.benchmark_group(&group_name); bench_chan_loop_group(&mut g, rt.clone(), channel, "send", Send, send); bench_chan_loop_group(&mut g, rt.clone(), channel, "recv", Recv, recv); bench_chan_loop_group(&mut g, rt.clone(
function_block-random_span
[ { "content": "fn bench_send_recv(c: &mut Criterion) {\n\n let size: usize = 1024;\n\n\n\n let mut dialectic_group = c.benchmark_group(\"dialectic\");\n\n dialectic_group.throughput(Throughput::Elements(size as u64));\n\n\n\n let rt = Arc::new(Runtime::new().unwrap());\n\n\n\n dialectic_group.benc...
Rust
hashes/blake/src/lib.rs
wakiyamap/cryptocorrosion
39493bd4fe895789b1286e113891b67b631c51c2
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] use std as core; extern crate block_buffer; pub extern crate digest; pub extern crate simd; mod consts; use block_buffer::BlockBuffer; use core::convert::TryInto; use core::mem; use digest::generic_array::typenum::{PartialDiv, Unsigned, U2}; use di...
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "std")] use std as core; extern crate block_buffer; pub extern crate digest; pub extern crate simd; mod consts; use block_buffer::BlockBuffer; use core::convert::TryInto; use core::mem; use digest::generic_array::typenum::{PartialDiv, Unsigned, U2}; use di...
fn increase_count(t: &mut ($word, $word), count: $word) { let (new_t0, carry) = t.0.overflowing_add(count * 8); t.0 = new_t0; if carry { t.1 += 1; } } } impl core::fmt::Debug for $name { fn f...
let len = out.len(); let o = out.split_at_mut(len / 2); let h0: M::$X4 = mach.unpack(h[0]); let h1: M::$X4 = mach.unpack(h[1]); h0.write_be(o.0); h1.write_be(o.1); ...
random
[ { "content": "#[inline(always)]\n\npub fn f8_impl<M: Machine>(mach: M, state: &mut [vec128_storage; 8], data: *const u8) {\n\n #[allow(clippy::cast_ptr_alignment)]\n\n let data = data as *const M::u128x1;\n\n let mut y = X8::<M>(\n\n mach.unpack(state[0]),\n\n mach.unpack(state[1]),\n\n ...
Rust
cincinnati/src/plugins/internal/graph_builder/release_scrape_dockerv2/registry/network_tests.rs
rajatchopra/cincinnati
6da515a0a77884183408afb81910a3d34af91f66
use crate as cincinnati; use cincinnati::plugins::internal::graph_builder::commons::tests::{ common_init, remove_metadata_by_key, }; use cincinnati::plugins::internal::graph_builder::release::{ create_graph, Metadata, MetadataKind::V0, Release, }; use cincinnati::plugins::internal::graph_builder::release_scrap...
use crate as cincinnati; use cincinnati::plugins::internal::graph_builder::commons::tests::{ common_init, remove_metadata_by_key, }; use cincinnati::plugins::internal::graph_builder::release::{ create_graph, Metadata, MetadataKind::V0, Release, }; use cincinnati::plugins::internal::graph_builder::release_scrap...
, ); assert_permutation_results!(release_count, expected_releases, releases); } #[test] fn fetch_release_public_must_succeed_with_schemes_missing_http_https() { let (mut runtime, cache) = common_init(); let test = |registry: Registry| { let repo = "redhat/openshift-cincinnati-test-public-manua...
Some(vec![ "sha256:e1f04336e1c78ae92c54a799bf6705bfe1f7edbda2f8f9c206ac1bb8f6019eb8", "sha256:b5e7677333bdbfd69d749cb3a7045dd5f0ef891adb91f1f675c65ef4e8515442", ])
call_expression
[ { "content": "fn assemble_metadata(blob: &[u8], metadata_filename: &str) -> Result<Metadata, Error> {\n\n let mut archive = Archive::new(GzDecoder::new(blob));\n\n match archive\n\n .entries()?\n\n .filter_map(|entry| match entry {\n\n Ok(file) => Some(file),\n\n Err(er...
Rust
src/bin/bifrost/main.rs
ericdeansanchez/bifrost
5317ea69e57f98376f605d57f27ecfafd78754f4
use bifrost::core::app::cli; use bifrost::core::config::Config; use bifrost::util::{docker, BifrostResult}; use std::env; use std::io::{self, Write}; use std::path::Path; use std::process; pub mod commands; fn main() -> BifrostResult<()> { let app = cli().get_matches(); match app.subcomm...
use bifrost::core::app::cli; use bifrost::core::config::Config; use bifrost::util::{docker, BifrostResult}; use std::env; use std::io::{self, Write}; use std::path::Path; use std::process; pub mod commands; fn main() -> BifrostResult<()> { let app = cli().get_matches(); match app.subcomm...
fn exit_if_not_setup(config: &Config) -> BifrostResult<()> { let set_up = check_setup(config.home_path()); let alert_not_setup = || -> BifrostResult<()> { io::stderr().write( r#" bifrost: Congrats on installing bifrost! There is just one more step to complete the installation, run...
k(_) => { if let Some(c) = input.chars().next() { if c == 'y' || c == 'Y' { commands::teardown::exec(config, arg_matches)?; } } } Err(e) => { io::stderr...
function_block-function_prefixed
[ { "content": "pub fn unload(config: Config, args: &ArgMatches) -> BifrostResult<()> {\n\n let success = |op_info: OperationInfo| -> BifrostResult<()> {\n\n io::stdout().write_fmt(format_args!(\n\n \"bifrost: successfully unloaded workspace realm `{}`\\n\",\n\n op_info.name,\n\n ...
Rust
src/main.rs
lovesh/ursaspeed
2dd5dd0e4eec58f16b5af21529d4e0352425ceb2
extern crate chrono; extern crate clap; extern crate os_type; extern crate rustc_version; extern crate hostname; extern crate regex; extern crate ring; extern crate openssl; extern crate sha2; extern crate amcl; extern crate hashlib; extern crate ursa; use std::io::{self, Write}; use chrono::{DateTime, Utc}; use cl...
extern crate chrono; extern crate clap; extern crate os_type; extern crate rustc_version; extern crate hostname; extern crate regex; extern crate ring; extern crate openssl; extern crate sha2; extern crate amcl; extern crate hashlib; extern crate ursa; use std::io::{self, Write}; use chrono::{DateTime, Utc}; use cl...
o_name: &str, hash_function: &Fn(usize, [u8; 16384]), timeout_secs: u64, machine_output: bool, kbytes_sec: &mut [f64]) { let block_byte_sizes = vec![16, 64, 256, 1024, 8192, 16384]; let mut counts = vec![0, 0, 0, 0, 0, 0]; for i in 0..block_byte_sizes.len() { let block_usize: usize = bloc...
ata[..byte_len]); } fn sha512_amcl(byte_len: usize, data: [u8; 16384]) { let mut h = HASH512::new(); h.process_array(&data[..byte_len]); } fn sha256_hashlib(byte_len: usize, data: [u8; 16384]) { let mut h = Sha256::new(); let _ = h.input(&data[..byte_len]); } fn sha512_hashlib(byte_len: usize, data: [u...
random
[ { "content": "## Running\n\n\n\nTo run the libursa and openssl microbenchmarks, type:\n\n```\n\ntarget/debug/crypto-speed\n\nopenssl speed sha256 sha512\n\ncpuid | egrep -i 'brand =|avx:|avx2:|avx512f:' | sort -u\n\n```\n\n\n\nTo display usage, type:\n\n```\n\n$ target/debug/crypto-speed -h\n\nCrypto Speed Micr...
Rust
aoc-2018-07/src/main.rs
maurizi/advent-of-code
ad14799e8bec1c712ce859e84f573ebf9e6c169d
#[macro_use] extern crate lazy_static; extern crate regex; extern crate petgraph; extern crate itertools; use petgraph::Direction::Incoming; use petgraph::graph::NodeIndex; use petgraph::graph::Graph; use regex::Regex; use std::collections::HashMap; use petgraph::Directed; use itertools::Itertools; lazy_static! { ...
#[macro_use] extern crate lazy_static; extern crate regex; extern crate petgraph; extern crate itertools; use petgraph::Direction::Incoming; use petgraph::graph::NodeIndex; use petgraph::graph::Graph; use regex::Regex; use std::collections::HashMap; use petgraph::Directed; use itertools::Itertools; lazy_static! { ...
fn part2(input: &str, workers: u8, delay: u8) -> Option<usize> { let step_graph = get_step_graph(input)?; build_time(&step_graph, workers, delay) } fn main() { let input = include_str!("input.txt"); println!("{}", part1(input).unwrap()); println!("{}", part2(input, 5, 60).unwrap()); } #[test] fn...
fn build_time(step_graph: &Graph<&str, &str>, workers: u8, delay: u8) -> Option<usize> { let mut available: Vec<NodeIndex> = step_graph.externals(Incoming).collect(); let mut done = String::new(); let mut in_progress = vec![None; workers as usize]; let mut time = 0; while !available.is_empty() || i...
function_block-full_function
[ { "content": "fn to_bool_list(input: &str) -> Map<Bytes, fn(u8) -> bool> {\n\n input.bytes().map(|b| b == '#' as u8)\n\n}\n\n\n", "file_path": "aoc-2018-12/src/main.rs", "rank": 4, "score": 179861.61745375837 }, { "content": "fn matches(recipes: &Vec<u8>, sequence: &Vec<u8>, additions: us...
Rust
debug/src/lib.rs
paulkass/proc-macro-workshop
e3f15c669ec27b6724adcc2c9012b8386780eb53
extern crate proc_macro; use proc_macro::TokenStream; use quote::ToTokens; use core::str::FromStr; use quote::quote; use std::iter::FromIterator; use syn::parse_macro_input; use syn::parse_quote; use syn::token::Comma; use syn::DeriveInput; use syn::Lit; use syn::Meta; use syn::WherePredicate; enum TypeEnum { Nor...
extern crate proc_macro; use proc_macro::TokenStream; use quote::ToTokens; use core::str::FromStr; use quote::quote; use std::iter::FromIterator; use syn::parse_macro_input; use syn::parse_quote; use syn::token::Comma; use syn::DeriveInput; use syn::Lit; use syn::Meta; use syn::WherePredicate; enum TypeEnum { Nor...
let where_token = syn::token::Where { span: syn::export::Span::call_site(), }; let mut where_clause_option = generics.where_clause.take(); let where_clause = where_clause_option.get_or_insert(syn::WhereClause { where_token: where_token, predicates: syn::punc...
function_block-function_prefix_line
[ { "content": "fn assert_debug<F: Debug>() {}\n\n\n", "file_path": "debug/tests/06-bound-trouble.rs", "rank": 1, "score": 175019.9744427583 }, { "content": "fn assert_debug<F: Debug>() {}\n\n\n", "file_path": "main.rs", "rank": 2, "score": 153324.8150804456 }, { "content":...
Rust
tunnelto_server/src/auth_db.rs
tazgong/bridge-tunnel-dev
81b1f4d7a06c2336be6bd223544c168c4bb92edc
use rusoto_dynamodb::{DynamoDbClient, DynamoDb, AttributeValue, GetItemInput, GetItemError}; use rusoto_core::{HttpClient, Client, Region}; use std::collections::HashMap; use uuid::Uuid; use thiserror::Error; use sha2::Digest; use rusoto_credential::EnvironmentProvider; use std::str::FromStr; pub struct AuthDbService...
use rusoto_dynamodb::{DynamoDbClient, DynamoDb, AttributeValue, GetItemInput, GetItemError}; use rusoto_core::{HttpClient, Client, Region}; use std::collections::HashMap; use uuid::Uuid; use thiserror::Error; use sha2::Digest; use rusoto_credential::EnvironmentProvider; use std::str::FromStr; pub struct AuthDbService...
} mod domain_db { pub const TABLE_NAME:&'static str = "tunnelto_domains"; pub const PRIMARY_KEY:&'static str = "subdomain"; pub const ACCOUNT_ID:&'static str = "account_id"; } mod key_db { pub const TABLE_NAME:&'static str = "tunnelto_auth"; pub const PRIMARY_KEY:&'static str = "auth_key_hash"; ...
pub fn new() -> Result<Self, Box<dyn std::error::Error>> { let provider = EnvironmentProvider::default(); let http_client = HttpClient::new()?; let client = Client::new_with(provider, http_client); Ok(Self { client: DynamoDbClient::new_with_client(client, Region::UsEast1) }) }
function_block-full_function
[ { "content": "type HttpClient = hyper::Client<hyper::client::HttpConnector>;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Request {\n\n id: String,\n\n status: u16,\n\n is_replay: bool,\n\n path: String,\n\n query: Option<String>,\n\n method: Method,\n\n headers: HashMap<String, Vec<String>...
Rust
pilka_ash/src/pvk/swapchain.rs
pudnax/pilka
eb2ed35aecbb4b20fe1d6f5280fcf861e3a73799
use super::{ device::{RawDevice, VkDevice}, renderpass_and_pipeline::VkRenderPass, }; use ash::{extensions::khr::Swapchain, prelude::VkResult, vk}; use std::sync::Arc; pub struct VkSwapchain { pub swapchain: vk::SwapchainKHR, pub swapchain_loader: Swapchain, pub images: Vec<vk::Image>, pub imag...
use super::{ device::{RawDevice, VkDevice}, renderpass_and_pipeline::VkRenderPass, }; use ash::{extensions::khr::Swapchain, prelude::VkResult, vk}; use std::sync::Arc; pub struct VkSwapchain { pub swapchain: vk::SwapchainKHR, pub swapchain_loader: Swapchain, pub images: Vec<vk::Image>, pub imag...
} impl Drop for VkSwapchain { fn drop(&mut self) { unsafe { for &image_view in self.image_views.iter() { self.device.destroy_image_view(image_view, None); } self.swapchain_loader .destroy_swapchain(self.swapchain, None) }; } }...
render_pass(render_pass.render_pass) .attachments(framebuffer_attachments) .width(width) .height(height) .layers(1), None, ) } }
function_block-function_prefix_line
[ { "content": "pub fn dispatch_optimal_size(len: u32, subgroup_size: u32) -> u32 {\n\n let padded_size = (subgroup_size - len % subgroup_size) % subgroup_size;\n\n (len + padded_size) / subgroup_size\n\n}\n\n\n\npub type Frame = (Vec<u8>, ImageDimentions);\n\n\n\npub enum ShaderData {\n\n Render { vert:...
Rust
src/operator/plus.rs
vmware/database-stream-processor
e702b903b8365366f31ff8d6645e23a31cf1f3b2
use crate::{ algebra::{AddAssignByRef, AddByRef, NegByRef}, circuit::{ operator_traits::{BinaryOperator, Operator}, Circuit, OwnershipPreference, Stream, }, }; use std::{ borrow::Cow, marker::PhantomData, ops::{Add, Neg}, }; impl<P, D> Stream<Circuit<P>, D> where P: Clone ...
use crate::{ algebra::{AddAssignByRef, AddByRef, NegByRef}, circuit::{ operator_traits::{BinaryOperator, Operator}, Circuit, OwnershipPreference, Stream, }, }; use std::{ borrow::Cow, marker::PhantomData, ops::{Add, Neg}, }; impl<P, D> Stream<Circuit<P>, D> where P: Clone ...
let root = Root::build(move |circuit| { build_plus_circuit(circuit); build_minus_circuit(circuit); }) .unwrap(); for _ in 0..100 { root.step().unwrap(); } let root = Root::build(move |circuit| { let (sou...
let build_minus_circuit = |circuit: &Circuit<()>| { let mut s = <OrdZSet<_, _>>::zero(); let delta = zset! { 5 => 1}; let source1 = circuit.add_source(Generator::new(move || { s = s.merge(&delta); s.clone() })); let mut s = <Ord...
assignment_statement
[ { "content": "/// Minimal requirements for values exchanged by operators.\n\npub trait Data: Clone + 'static {}\n\n\n\nimpl<T: Clone + 'static> Data for T {}\n\n\n", "file_path": "src/circuit/operator_traits.rs", "rank": 0, "score": 256363.46727074194 }, { "content": "/// A binary operator c...
Rust
examples/wdt-demo/src/main.rs
Sandraak/nrf-hal
190679d0a03bf0bfe5506c47b287ac7f3ed94192
#![no_std] #![no_main] use embedded_hal::{ digital::v2::{InputPin, OutputPin}, timer::CountDown, }; use { core::panic::PanicInfo, hal::{ gpio::Level, timer::Timer, wdt::{count, Parts, Watchdog}, }, nrf52840_hal as hal, rtt_target::{rprintln, rtt_init_print}, }; #[...
#![no_std] #![no_main] use embedded_hal::{ digital::v2::{InputPin, OutputPin}, timer::CountDown, }; use { core::panic::PanicInfo, hal::{ gpio::Level, timer::Timer, wdt::{count, Parts, Watchdog}, }, nrf52840_hal as hal, rtt_target::{rprintln, rtt_init_print}, }; #[...
se { leds[i].set_high().ok(); } } if any_pet && petted == 0 { cumulative_ticks = 0; any_pet = false; timer.start(1_000_000u32 * 6); } let rd = timer.read(); if (cumulative_ticks + 250_000) <= rd {...
grade(); let mut led2 = p0.p0_14.into_push_pull_output(Level::High).degrade(); let mut led3 = p0.p0_15.into_push_pull_output(Level::High).degrade(); let mut led4 = p0.p0_16.into_push_pull_output(Level::High).degrade(); let mut timer = Timer::new(p.TIMER0); let (hdl0, hdl1,...
function_block-random_span
[ { "content": "fn main() {\n\n // Put the linker script somewhere the linker can find it\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"memory.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"memory.x\"))\n\n .unwrap();\n\n println...
Rust
src/graphics/material_skybox.rs
BrassLion/rust-pbr
1b406984d27d7477eb4319ac3acbf2916d7ca755
use super::*; pub struct SkyboxBindGroup { pub environment_texture: Texture, } pub struct SkyboxMaterial { pub render_pipeline: wgpu::RenderPipeline, pub transform_bind_group: wgpu::BindGroup, pub transform_uniform_buffer: wgpu::Buffer, pub params_bind_group: wgpu::BindGroup, } impl SkyboxMater...
use super::*; pub struct SkyboxBindGroup { pub environment_texture: Texture, } pub struct SkyboxMaterial { pub render_pipeline: wgpu::RenderPipeline, pub transform_bind_group: wgpu::BindGroup, pub transform_uniform_buffer: wgpu::Buffer, pub params_bind_group: wgpu::BindGroup, } impl SkyboxMater...
let params_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &params_bind_group_layout, bindings: &[ wgpu::Binding { binding: 0, resource: wgpu::BindingResource::TextureView(&params.environment_texture.vie...
let params_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { bindings: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgp...
assignment_statement
[ { "content": "pub fn create_texture_bind_group(\n\n device: &wgpu::Device,\n\n visibility: wgpu::ShaderStage,\n\n textures: &[&Texture],\n\n) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {\n\n let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {\n\n label:...
Rust
src/blocking/i2c.rs
keithduncan/embedded-hal
2921873e0862f59d4065c918ed3c332a0e3dc615
pub trait Read { type Error; fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error>; } impl<T: Read> Read for &mut T { type Error = <T as Read>::Error; fn read(&mut self, address: u...
pub trait Read { type Error; fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error>; } impl<T: Read> Read for &mut T { type Error =
B: IntoIterator<Item = u8> { (*self).write(addr, bytes) } } pub trait WriteRead { type Error; fn write_read( &mut self, address: u8, bytes: &[u8], ...
<T as Read>::Error; fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> { (*self).read(address, buffer) } } pub trait Write { type Error; fn write(&mut self, addr: u8, bytes: &[u8])...
random
[ { "content": "#[cfg(feature = \"unproven\")]\n\npub trait Read {\n\n /// Error type\n\n type Error;\n\n\n\n /// Reads enough bytes from hardware random number generator to fill `buffer`\n\n ///\n\n /// If any error is encountered then this function immediately returns. The contents of buf are\n\n...
Rust
socrates-core/src/module/context.rs
ckaran/socrates-rs
450f364e38cf663367c36991a99cd8b689d76768
use super::*; #[derive(Clone)] pub struct Context { dynamod_id: DynamodId, svc_manager: Weak<ServiceManager>, } impl Context { pub fn new(dynamod_id: DynamodId, svc_manager: Weak<ServiceManager>) -> Context { Context { dynamod_id, svc_manager, } } pub fn us...
use super::*; #[derive(Clone)] pub struct Context { dynamod_id: DynamodId, svc_manager: Weak<ServiceManager>, } impl Context { pub fn new(dynamod_id: DynamodId, svc_manager: Weak<ServiceManager>) -> Context { Context { dynamod_id, svc_manager, } } pub fn us...
f, svc_name: &str, ) -> Option<Svc<T>> { self.get_first_service_by_name(svc_name) .and_then(|svc| Svc::cast::<T>(svc).ok()) } pub fn get_all_services_by_name_typed<T: Service + ?Sized>( &self, svc_name: &str, ) -> Vec<Svc<T>> { let mut s: Vec<Svc<T>> ...
ype_id).next() } else { None } } pub fn get_all_services_id_by_type_id(&self, svc_type_id: TypeId) -> Vec<ServiceId> { if let Some(svc_manager) = self.try_manager() { svc_manager .get_services_id_by_type_id(svc_type_id) .collect() ...
random
[ { "content": "#[inline(always)]\n\npub fn service_name<T: Named + ?Sized>() -> &'static str {\n\n <T>::type_name()\n\n}\n\n\n", "file_path": "socrates-core/src/service/service.rs", "rank": 0, "score": 222535.16880548646 }, { "content": "#[inline(always)]\n\npub fn service_type_id<T: ?Size...
Rust
src/main.rs
ZCKun/LimitOrderBook
dbf5d6d4d7d06885664607a4ae1bee526165be73
use std::{collections::BTreeMap, io::BufRead}; use book::Book; use types::Side; use crate::types::{Order, Trade, TradeType}; use std::io::{BufReader, Read}; use byteorder::{LittleEndian, ByteOrder}; use crate::dat_reader::{Header, DatReader}; mod book; mod types; mod dat_reader; mod mdt_type; mod mdt_struct; fn test...
use std::{collections::BTreeMap, io::BufRead}; use book::Book; use types::Side; use crate::types::{Order, Trade, TradeType}; use std::io::{BufReader, Read}; use byteorder::{LittleEndian, ByteOrder}; use crate::dat_reader::{Header, DatReader}; mod book; mod types; mod dat_reader; mod mdt_type; mod mdt_struct; fn test...
#[derive(serde::Serialize, serde::Deserialize)] struct Item { data_type: i32, time: i64, id: i64, side: Option<String>, price: f64, qty: i64, bid_id: Option<i64>, ask_id: Option<i64> } #[derive(serde::Serialize, serde::Deserialize)] struct Data { local_time:String, item:Item ...
if let Ok(lines) = read_lines("files/trade.csv") { for line in lines { if let Ok(row) = line { let items: Vec<&str> = row.split(',').collect(); let time = items[1].parse::<i64>().unwrap(); let id = items[2].parse::<i64>().unwrap(); let ...
function_block-function_prefix_line
[ { "content": "fn buf_reader<T: Read, const size: usize>(reader: &mut T) -> [u8; size] {\n\n let mut buf = [0; size];\n\n reader.read(&mut buf[..]);\n\n buf\n\n}\n\n\n\nimpl Header {\n\n pub(crate) fn new<T: Read>(reader: &mut T) -> Header {\n\n Self {\n\n total_len: LittleEndian::r...
Rust
intl-memoizer/src/lib.rs
dminor/fluent-rs
8891e4618ad0a7dde84c9c0b52f328515341a13c
use std::cell::RefCell; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::hash::Hash; use std::rc::{Rc, Weak}; use unic_langid::LanguageIdentifier; pub mod concurrent; pub trait Memoizable { type Args: 'static + Eq + Hash + Clone; type Error; fn construct(lang: LanguageIdentif...
use std::cell::RefCell; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::hash::Hash; use std::rc::{Rc, Weak}; use unic_langid::LanguageIdentifier; pub mod concurrent; pub trait Memoizable { type Args: 'static + Eq + Hash + Clone; type Error; fn construct(lang: LanguageIdentif...
}
let lang: LanguageIdentifier = "en".parse().unwrap(); let mut memoizer = IntlMemoizer::default(); { let en_memoizer = memoizer.get_for_lang(lang.clone()); let result = en_memoizer .with_try_get::<PluralRules, _, _>((PluralRuleType::CARDINAL,), |cb| cb.0.select(5...
function_block-function_prefix_line
[ { "content": "pub trait AnyEq: Any + 'static {\n\n fn equals(&self, other: &dyn Any) -> bool;\n\n fn as_any(&self) -> &dyn Any;\n\n}\n\n\n\nimpl<T: Any + PartialEq> AnyEq for T {\n\n fn equals(&self, other: &dyn Any) -> bool {\n\n if let Some(that) = other.downcast_ref::<Self>() {\n\n ...