lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/siphash24.rs
tcharding/bitcoin_hashes
9887c4ec6bd96d013df1af67fe9c8b618ff7cd52
use core::{cmp, mem, ptr, str}; use core::ops::Index; use core::slice::SliceIndex; use crate::{Error, Hash as _, HashEngine as _, hex, util}; macro_rules! compress { ($state:expr) => {{ compress!($state.v0, $state.v1, $state.v2, $state.v3) }}; ($v0:expr, $v1:expr, $v2:expr, $v3:expr) => {{ ...
use core::{cmp, mem, ptr, str}; use core::ops::Index; use core::slice::SliceIndex; use crate::{Error, Hash as _, HashEngine as _, hex, util}; macro_rules! compress { ($state:expr) => {{ compress!($state.v0, $state.v1, $state.v2, $state.v3) }}; ($v0:expr, $v1:expr, $v2:expr, $v3:expr) => {{ ...
debug_assert_eq!(i, len); out } #[cfg(test)] mod tests { use super::*; #[test] fn test_siphash_2_4() { let vecs: [[u8; 8]; 64] = [ [0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72], [0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74], [0x5a, 0x4f, 0xa9, 0xd9, ...
debug_assert!(len < 8); let mut i = 0; let mut out = 0; if i + 3 < len { out = u64::from(load_int_le!(buf, start + i, u32)); i += 4; } if i + 1 < len { out |= u64::from(load_int_le!(buf, start + i, u16)) << (i * 8); i += 2 } if i < len { out |= u64::...
function_block-random_span
[ { "content": "/// Trait which applies to hashes of all types.\n\npub trait Hash: Copy + Clone + PartialEq + Eq + Default + PartialOrd + Ord +\n\n hash::Hash + fmt::Debug + fmt::Display + fmt::LowerHex +\n\n ops::Index<ops::RangeFull, Output = [u8]> +\n\n ops::Index<ops::RangeFrom<usize>, Output = [u8]>...
Rust
src/lib.rs
himanoa/mkrepo
6d543d576e2126836fa8a77e5ab33235713222b4
pub mod makerepo { use failure::{Error, Fail}; use git2::Config as GitConfig; use git2::ConfigEntries; use serde_derive::Deserialize; use shellexpand::tilde; use std::fs::create_dir_all; use std::iter::Iterator; use std::ops::Deref; use std::path; use std::path::PathBuf; use ...
pub mod makerepo { use failure::{Error, Fail}; use git2::Config as GitConfig; use git2::ConfigEntries; use serde_derive::Deserialize; use shellexpand::tilde; use std::fs::create_dir_all; use std::iter::Iterator; use std::ops::Deref; use std::path; use std::path::PathBuf; use ...
} fn normalize_seps(path: &str) -> String { path.replace(path::is_separator, &path::MAIN_SEPARATOR.to_string()) } #[cfg(test)] mod tests { use super::*; use std::fs::File; use tempfile::TempDir; #[test] pub fn build_commands_return_to_create_directo...
Ok(vec![ CommandType::CreateDirectory { path: normalize_seps(repository_path.to_str().unwrap()), }, CommandType::InitializeGit { path: normalize_seps(repository_path.to_str().unwrap()), first_commit_message: String::from(match first_com...
call_expression
[ { "content": "fn main() {\n\n let matchers = App::new(\"Make project directory for ghq style.\")\n\n .version(env!(\"CARGO_PKG_VERSION\"))\n\n .arg(\n\n Arg::with_name(\"repository\")\n\n .help(\"Repository name\")\n\n .required(true)\n\n ...
Rust
src/graph/graph.rs
carlospereira1607/TCB
30ca7a7476ce04665c15456e8d898653a21a2c48
use crate::broadcast::broadcast_trait::{GenericReturn, TCB}; use crate::configuration::middleware_configuration::Configuration; use crate::graph::communication::{acceptor, connector}; use crate::graph::middleware::dot::Dot; use crate::graph::middleware::message_types::ClientMessage; use crate::graph::middleware::middle...
use crate::broadcast::broadcast_trait::{GenericReturn, TCB}; use crate::configuration::middleware_configuration::Configuration; use crate::graph::communication::{acceptor, connector}; use crate::graph::middleware::dot::Dot; use crate::graph::middleware::message_types::ClientMessage; use crate::graph::middleware::middle...
} /** * Waits for a message to be delivered from the middleware for a * limited time. If the channel is empty and not disconnected, the * caller thread is blocked until a message is received in the channel * or the timeout ends. If there are no messages until the timeout ends or * the...
match self.receive_channel.try_recv() { Ok(message) => Ok(self.handle_delivery(message)), Err(e) => Err(e), }
if_condition
[ { "content": "fn handle_received_peer_msg(msg: Vec<u8>, send_main_mid: &Sender<ClientPeerMiddleware>) {\n\n //Deserializing the vec of bytes to Message struct\n\n let decoded_msg: Message = deserialize(&msg)\n\n .expect(\"ERROR: Couldn't deserialize the Message type after reading from the stream\")...
Rust
src/ethkey/signature.rs
laohanlinux/cryptocurrency-kit-rs
98286b7bfe40fae5bcd3b99f4a87eb12036abbd6
use super::{public_to_address, Address, Error, Message, Public, Secret, SECP256K1}; use common::{to_hex, to_keccak}; use crypto::{hash, CryptoHash, Hash}; use ethereum_types::{H256, H520}; use secp256k1::key::{PublicKey, SecretKey}; use secp256k1::{Error as SecpError, Message as SecpMessage, RecoverableSignature, Recov...
use super::{public_to_address, Address, Error, Message, Public, Secret, SECP256K1}; use common::{to_hex, to_keccak}; use crypto::{hash, CryptoHash, Hash}; use ethereum_types::{H256, H520}; use secp256k1::key::{PublicKey, SecretKey}; use secp256k1::{Error as SecpError, Message as SecpMessage, RecoverableSignature, Recov...
_address(&public); Ok(address == &recovered_address) } pub fn recover(signature: &Signature, message: &Message) -> Result<Public, Error> { use ethereum_types::H512; use crate::common::to_fixed_array_64; let context = &SECP256K1; let v_off = SIGNATURE_R_SIZE + SIGNATURE_S_SIZE; let rsig = Recove...
.0[32..64])) .field("v", &to_hex(&self.0[64..65])) .finish() } } impl fmt::Display for Signature { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", to_hex(&self.0[..])) } } impl FromStr for Signature { type Err = Error; fn from_str(...
random
[ { "content": "pub fn public_to_address(public: &Public) -> Address {\n\n let hash = public.keccak256();\n\n let result = to_fixed_array_20(&hash[12..]);\n\n Address::from(result)\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\n/// Secp256k1 key pair\n\npub struct KeyPair {\n\n secret: Secret,\n\n ...
Rust
src/util/align.rs
EwoutH/rav1e
39f35d0c94a0523bc6c26042bb54f7dca28efb37
use std::alloc::{alloc, dealloc, Layout}; use std::mem::MaybeUninit; use std::ptr; use std::{fmt, mem}; #[repr(align(64))] pub struct Align64; pub struct Aligned<T> { _alignment: [Align64; 0], pub data: T, } impl<T> Aligned<T> { pub const fn new(data: T) -> Self { Aligned { _alignment: [], data } } #...
use std::alloc::{alloc, dealloc, Layout}; use std::mem::MaybeUninit; use std::ptr; use std::{fmt, mem}; #[repr(align(64))] pub struct Align64; pub struct Aligned<T> { _alignment: [Align64; 0], pub data: T, } impl<T> Aligned<T> { pub const fn new(data: T) -> Self { Aligned { _alignment: [], data } } #...
} impl<T> std::ops::Drop for AlignedBoxedSlice<T> { fn drop(&mut self) { unsafe { for a in self.iter_mut() { ptr::drop_in_place(a) } dealloc(self.ptr.as_ptr() as *mut u8, Self::layout(self.len)); } } } unsafe impl<T> Send for AlignedBoxedSlice<T> where T: Send {} unsafe impl<T>...
n deref_mut(&mut self) -> &mut [T] { unsafe { let p = self.ptr.as_ptr(); std::slice::from_raw_parts_mut(p, self.len) } }
function_block-function_prefixed
[ { "content": "pub fn bench_pred_fn<F>(c: &mut Criterion, id: &str, f: F)\n\nwhere\n\n F: FnMut(&mut Bencher) + 'static,\n\n{\n\n let b = Benchmark::new(id, f);\n\n c.bench(\n\n id,\n\n if id.ends_with(\"_4x4_u8\") {\n\n b.throughput(Throughput::Bytes(16))\n\n } else if id.ends_with(\"_4x4\") {\...
Rust
src/storage/stress-tests/fvm/environment.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
use { crate::{ instance_actor::InstanceActor, volume::VolumeConnection, volume_actor::VolumeActor, Args, }, async_trait::async_trait, fidl_fuchsia_hardware_block_partition::Guid, fuchsia_zircon::Vmo, futures::lock::Mutex, rand::{rngs::SmallRng, Rng, SeedableRng}, std::sync::Arc...
use { crate::{ instance_actor::InstanceActor, volume::VolumeConnection, volume_actor::VolumeActor, Args, }, async_trait::async_trait, fidl_fuchsia_hardware_block_partition::Guid, fuchsia_zircon::Vmo, futures::lock::Mutex, rand::{rngs::SmallRng, Rng, SeedableRng}, std::sync::Arc...
async fn reset(&mut self) { { let mut actor = self.instance_actor.lock().await; assert!(actor.instance.is_none()); let fvm = FvmInstance::new( false, &self.vmo, self.args.fvm_slice_...
for (guid, actor) in &self.volume_actors { let actor_name = format!("volume_actor_{}", guid.value[0]); runners.push(ActorRunner::new(actor_name, None, actor.clone())); } if let Some(secs) = self.args.disconnect_secs { if secs > 0 { runners.push(ActorR...
function_block-function_prefix_line
[]
Rust
episcopal_api/crates/psalter/src/loc/psalm_022.rs
gbj/commonprayer
15197dcb7fc2417b5f5695964eb0afbeb2969f94
use liturgy::{Psalm, PsalmSection, PsalmVerse, Reference, Source}; lazy_static! { pub static ref PSALM_22: Psalm = Psalm { number: 22, citation: None, sections: vec![ PsalmSection { reference: Reference { source: Source::LibroDeOracionComun, page: 509 }, local_name: String::from(""), ...
use liturgy::{Psalm, PsalmSection, PsalmVerse, Reference, Source}; lazy_static! { pub static ref PSALM_22: Psalm = Psalm { number: 22, citation: None, sections: vec![ PsalmSection { reference: Reference { source: Source::LibroDeOracionComun, page: 509 }, local_name: String::from(""), ...
number: 30, a: String::from("Vendrán y anunciarán al pueblo aún no nacido *"), b: String::from("los hechos asombrosos que hizo.") } ] } ] }; }
a: String::from("Me hará vivir para él;\nmi descendencia le servirá; *"), b: String::from("será contada como suya para siempre.") }, PsalmVerse {
random
[ { "content": "pub fn get_static_paths() -> Vec<String> {\n\n vec![\"\".into(), \"bcp1979\".into(), \"lff2018\".into()]\n\n}\n\n\n", "file_path": "website/website/src/pages/calendar.rs", "rank": 0, "score": 261894.6392081576 }, { "content": "pub fn get_static_paths() -> Vec<String> {\n\n ...
Rust
consensus/state_processing/src/per_epoch_processing/apply_rewards.rs
sean-sn/lighthouse
c6baa0eed131c5e8ecc5860778ffc7d4a4c18d2d
use super::super::common::get_base_reward; use super::validator_statuses::{TotalBalances, ValidatorStatus, ValidatorStatuses}; use super::Error; use safe_arith::SafeArith; use types::*; #[derive(Default, Clone)] pub struct Delta { rewards: u64, penalties: u64, } impl Delta { pub fn reward(&mut self,...
use super::super::common::get_base_reward; use super::validator_statuses::{TotalBalances, ValidatorStatus, ValidatorStatuses}; use super::Error; use safe_arith::SafeArith; use types::*; #[derive(Default, Clone)] pub struct Delta { rewards: u64, penalties: u64, } impl Delta { pub fn reward(&mut self,...
fn get_inactivity_penalty_delta( validator: &ValidatorStatus, base_reward: u64, finality_delay: u64, spec: &ChainSpec, ) -> Result<Delta, Error> { let mut delta = Delta::default(); if finality_delay > spec.min_epochs_to_inactivity_penalty { delta.penalize( sp...
fn get_inclusion_delay_delta( validator: &ValidatorStatus, base_reward: u64, spec: &ChainSpec, ) -> Result<(Delta, Option<(usize, Delta)>), Error> { if validator.is_previous_epoch_attester && !validator.is_slashed { let mut delta = Delta::default(); let mut proposer_delta = Delta::d...
function_block-function_prefix_line
[ { "content": "/// Decrease the balance of a validator, saturating upon overflow, as per the spec.\n\n///\n\n/// Spec v0.12.1\n\npub fn decrease_balance<E: EthSpec>(state: &mut BeaconState<E>, index: usize, delta: u64) {\n\n state.balances[index] = state.balances[index].saturating_sub(delta);\n\n}\n", "fi...
Rust
src/wrapper/objects/jvalue.rs
skletsun/jni-rs
4e140ea6fdf309a1b2ff9b50d76ae78249989e34
use std::mem::transmute; use log::trace; use crate::{errors::*, objects::JObject, signature::Primitive, sys::*}; #[allow(missing_docs)] #[derive(Clone, Copy, Debug)] pub enum JValue<'a> { Object(JObject<'a>), Byte(jbyte), Char(jchar), Short(jshort), Int(jint), Long(jlong), Bool(jboolean),...
use std::mem::transmute; use log::trace; use crate::{errors::*, objects::JObject, signature::Primitive, sys::*}; #[allow(missing_docs)] #[derive(Clone, Copy, Debug)] pub enum JValue<'a> { Object(JObject<'a>), Byte(jbyte), Char(jchar), Short(jshort), Int(jint), Long(jlong), Bool(jboolean),...
<'a> From<jboolean> for JValue<'a> { fn from(other: jboolean) -> Self { JValue::Bool(other) } } impl<'a> From<jchar> for JValue<'a> { fn from(other: jchar) -> Self { JValue::Char(other) } } impl<'a> From<jshort> for JValue<'a> { fn from(other: jshort) -> Self { JValue::Shor...
e(obj) }, }, JValue::Byte(byte) => jvalue { b: byte }, JValue::Char(char) => jvalue { c: char }, JValue::Short(short) => jvalue { s: short }, JValue::Int(int) => jvalue { i: int }, JValue::Long(long) => jvalue { j: long }, JValue::Bool(...
random
[ { "content": "#[test]\n\npub fn is_instance_of_not_superclass() {\n\n let env = attach_current_thread();\n\n let obj = AutoLocal::new(\n\n &env,\n\n unwrap(&env, env.new_object(ARITHMETIC_EXCEPTION_CLASS, \"()V\", &[])),\n\n );\n\n assert!(!unwrap(\n\n &env,\n\n env.is_in...
Rust
src/config/runtime.rs
perdumonocle/log4rs
ccf4f15b0533f858e4183c56182d2c1b42570484
use log::LevelFilter; use std::{collections::HashSet, iter::IntoIterator}; use thiserror::Error; use crate::{append::Append, filter::Filter}; #[derive(Debug)] pub struct Config { appenders: Vec<Appender>, root: Root, loggers: Vec<Logger>, } impl Config { pub fn builder() -> ConfigBuilder { ...
use log::LevelFilter; use std::{collections::HashSet, iter::IntoIterator}; use thiserror::Error; use crate::{append::Append, filter::Filter}; #[derive(Debug)] pub struct Config { appenders: Vec<Appender>, root: Root, loggers: Vec<Logger>, } impl Config { pub fn builder() -> ConfigBuilder { ...
r_names.insert(appender.name.clone()) { ok_appenders.push(appender); } else { errors.push(ConfigError::DuplicateAppenderName(appender.name)); } } let mut ok_root_appenders = vec![]; for appender in root.appenders { if appender_...
root, loggers, } = self; (appenders, root, loggers) } } #[derive(Debug, Default)] pub struct ConfigBuilder { appenders: Vec<Appender>, loggers: Vec<Logger>, } impl ConfigBuilder { pub fn appender(mut self, appender: Appender) -> ConfigBuilder { self.appen...
random
[ { "content": "/// Initializes the global logger as a log4rs logger with the provided config.\n\n///\n\n/// A `Handle` object is returned which can be used to adjust the logging\n\n/// configuration.\n\npub fn init_config(config: runtime::Config) -> Result<crate::Handle, SetLoggerError> {\n\n let logger = cra...
Rust
src/tutorials/10_fixed_functions.rs
datMaffin/vulkan-tutorial-rust
234ece6ee1b927ca72a863de3c3e20c74a2ac642
use vulkan_tutorial_rust::{ utility, utility::constants::*, utility::debug::*, utility::share, }; use ash::version::DeviceV1_0; use ash::version::InstanceV1_0; use ash::vk; use winit::event::{Event, VirtualKeyCode, ElementState, KeyboardInput, WindowEvent}; use winit::event_loop::{EventLoop, ControlFl...
use vulkan_tutorial_rust::{ utility, utility::constants::*, utility::debug::*, utility::share, }; use ash::version::DeviceV1_0; use ash::version::InstanceV1_0; use ash::vk; use winit::event::{Event, VirtualKeyCode, ElementState, KeyboardInput, WindowEvent}; use winit::event_loop::{EventLoop, ControlFl...
}, | Event::MainEventsCleared => { window.request_redraw(); }, | Event::RedrawRequested(_window_id) => { self.draw_frame(); }, _ => (), } }) } } fn main() { let ev...
{ blend_enable: vk::FALSE, color_write_mask: vk::ColorComponentFlags::all(), src_color_blend_factor: vk::BlendFactor::ONE, dst_color_blend_factor: vk::BlendFactor::ZERO, color_blend_op: vk::BlendOp::ADD, src_alpha_blend_factor: vk::BlendFactor::ON...
random
[ { "content": "pub fn choose_swapchain_extent(\n\n capabilities: &vk::SurfaceCapabilitiesKHR,\n\n window: &winit::window::Window,\n\n) -> vk::Extent2D {\n\n if capabilities.current_extent.width != u32::max_value() {\n\n capabilities.current_extent\n\n } else {\n\n use num::clamp;\n\n\n\...
Rust
services/tcpsocket/src/service.rs
ittat/api-daemon
f968913ef97020ef1c70a387b44f89624a2d4d0f
use crate::generated::common::*; use crate::generated::service::*; use crate::tcpsocket::{EventType, TcpSocket, TokenMap}; use common::core::BaseMessage; use common::object_tracker::ObjectTracker; use common::traits::{ ObjectTrackerMethods, OriginAttributes, Service, SessionSupport, Shared, SharedSessionContext, ...
use crate::generated::common::*; use crate::generated::service::*; use crate::tcpsocket::{EventType, TcpSocket, TokenMap}; use common::core::BaseMessage; use common::object_tracker::ObjectTracker; use common::traits::{ ObjectTrackerMethods, OriginAttributes, Service, SessionSupport, Shared, SharedSessionContext, ...
if untrack { info!("Untrack {}", tracker_id); tracker_lock.untrack(tracker_id); } } is_connected } pub fn start_event_loop( poll: Arc<Poll>, token_map: TokenMap, tracker: Arc<Mutex<TcpSocketManagerTrackerType>>, ) { info!( "Starting event loop w...
if socket_state.is_writable() { let mut socket = ctxt.lock(); debug!("Socket is writable"); socket.drain_queue(); }
if_condition
[]
Rust
admin-http-gateway/src/main.rs
jgreat/mobilecoin
7df58d88f67e3b92122b814acae9c08498429092
#![deny(missing_docs)] #![feature(proc_macro_hygiene, decl_macro)] use clap::Parser; use grpcio::ChannelBuilder; use mc_common::logger::{create_app_logger, log, o}; use mc_util_grpc::{admin, admin_grpc::AdminApiClient, ConnectionUriGrpcioChannel, Empty}; use mc_util_uri::AdminUri; use rocket::{ get, post, re...
#![deny(missing_docs)] #![feature(proc_macro_hygiene, decl_macro)] use clap::Parser; use grpcio::ChannelBuilder; use mc_common::logger::{create_app_logger, log, o}; use mc_util_grpc::{admin, admin_grpc::AdminApiClient, ConnectionUriGrpcioChannel, Empty}; use mc_util_uri::AdminUri; use rocket::{ get, post, re...
#[derive(FromForm)] struct SetRustLogForm { rust_log: String, } #[post("/set-rust-log", data = "<form>")] fn set_rust_log( state: rocket::State<State>, form: Form<SetRustLogForm>, ) -> Result<Redirect, String> { let mut req = admin::SetRustLogRequest::new(); req.set_rust_log(form.rust_log.clone()...
fn info(state: rocket::State<State>) -> Result<Json<JsonInfoResponse>, String> { let info = state .admin_api_client .get_info(&Empty::new()) .map_err(|err| format!("Failed getting info: {}", err))?; Ok(Json(JsonInfoResponse::try_from(&info)?)) }
function_block-full_function
[ { "content": "/// Get the BuildInfo object, by reading from the BuildInfo crate\n\npub fn get_build_info() -> BuildInfo {\n\n let mut build_info = BuildInfo::new();\n\n build_info.set_git_commit(::mc_util_build_info::git_commit().to_owned());\n\n build_info.set_profile(::mc_util_build_info::profile().t...
Rust
src/connectors/otel/id.rs
Voultapher/tremor-runtime
738f08e5b716826c5c959b4aa6bd4f8c34fde66e
use crate::errors::Result; use rand::Rng; use tremor_script::Value; use tremor_value::StaticNode; pub(crate) fn random_span_id_bytes(ingest_ns_seed: u64) -> Vec<u8> { let mut rng = tremor_common::rand::make_prng(ingest_ns_seed); let span_id: Vec<u8> = (0..8).map(|_| rng.gen_range(0_u8..=255_u8)).collect(); ...
use crate::errors::Result; use rand::Rng; use tremor_script::Value; use tremor_value::StaticNode; pub(crate) fn random_span_id_bytes(ingest_ns_seed: u64) -> Vec<u8> { let mut rng = tremor_common::rand::make_prng(ingest_ns_seed); let span_id: Vec<u8> = (0..8).map(|_| rng.gen_range(0_u8..=255_u8)).collect(); ...
} else { Err(format!("Invalid hex encoded string - cannot convert {} to pb", kind).into()) } } else if let Some(Value::Bytes(json)) = data { let data = json.to_vec(); if (allow_empty && data.is_empty()) || data.len() == len_bytes { Ok(data) } else { ...
if (allow_empty && pb.is_empty()) || pb.len() == len_bytes { Ok(pb) } else { Err(format!( "Invalid {} id ( wrong string length 1) - cannot convert to pb", kind ) .into()) }
if_condition
[ { "content": "pub fn _format(value: u64, fmt: &str, has_timezone: bool) -> String {\n\n if has_timezone {\n\n format!(\n\n \"{}\",\n\n DateTime::<Utc>::from_utc(to_naive_datetime(value), Utc).format(fmt)\n\n )\n\n } else {\n\n format!(\"{}\", to_naive_datetime(va...
Rust
train/src/main.rs
vbkaisetsu/vaporetto
2603bc9d1111bf23da6810c3d102b8199cbea9c8
use std::collections::BTreeSet; use std::fs::File; use std::io::{prelude::*, stderr, BufReader}; use std::path::PathBuf; use structopt::{clap::ArgGroup, StructOpt}; use vaporetto::{Dataset, Sentence, SolverType, Trainer}; #[derive(StructOpt, Debug)] #[structopt( name = "train", about = "A program to train mod...
use std::collections::BTreeSet; use std::fs::File; use std::io::{prelude::*, stderr, BufReader}; use std::path::PathBuf; use structopt::{clap::ArgGroup, StructOpt}; use vaporetto::{Dataset, Sentence, SolverType, Trainer}; #[derive(StructOpt, Debug)] #[structopt( name = "train", about = "A program to train mod...
ader::new(f); for (i, line) in f.lines().enumerate() { if i % 100000 == 0 { eprint!("# of words: {}\r", i); stderr().flush()?; } dictionary.insert(line?); } eprintln!("# of words: {}", dictionary.len()); } let dictionary...
ath)?; let f = BufReader::new(f); for (i, line) in f.lines().enumerate() { if i % 10000 == 0 { eprint!("# of sentences: {}\r", i); stderr().flush()?; } train_sents.push(Sentence::from_tokenized(line?)?); } eprintln!("# o...
random
[ { "content": "struct Opt {\n\n /// KyTea model file\n\n #[structopt(long)]\n\n model_in: PathBuf,\n\n\n\n /// Vespa model file\n\n #[structopt(long)]\n\n model_out: PathBuf,\n\n}\n\n\n", "file_path": "convert_kytea_model/src/main.rs", "rank": 1, "score": 128077.31135106066 }, {...
Rust
src/main.rs
shampoofactory/morscrypta
1090fd4cc783674246b5f2d1a51d8da15a0ccf6f
pub mod lib; use clap::{crate_version, App, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand}; use rand_core::OsRng; use regex::Regex; use x25519_dalek::{PublicKey, StaticSecret}; use std::collections::HashSet; use std::fs::File; use std::io; use std::io::prelude::*; use std::process; use std::str::FromStr; use li...
pub mod lib; use clap::{crate_version, App, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand}; use rand_core::OsRng; use regex::Regex; use x25519_dalek::{PublicKey, StaticSecret}; use std::collections::HashSet; use std::fs::File; use std::io; use std::io::prelude::*; use std::process; use std::str::FromStr; use li...
, ("pubkey", Some(m)) => pub_key(m.value_of("input"), m.value_of("output")), ("encrypt", Some(m)) => match ( m.value_of("input"), m.value_of("output"), m.value_of("public_key"), m.value_of("password"), m.value_of("iteration_count"), ) {...
prv_kdf( m.value_of("output"), m.value_of("password").unwrap(), m.value_of("iteration_count").unwrap(), )
call_expression
[ { "content": "pub trait ReadFully {\n\n fn read_fully(&mut self, buf: &mut [u8]) -> io::Result<usize>;\n\n}\n\n\n\nimpl<R: Read> ReadFully for R {\n\n fn read_fully(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n\n let mut idx = 0;\n\n let mut is_eof = false;\n\n while idx != buf....
Rust
src/fonts/glyph_ranges.rs
joncppl/imgui-rs
00a724283e1ff71d84fa6ca7c433c4102930af5f
use crate::sys; #[derive(Clone, Eq, PartialEq, Debug)] enum FontGlyphRangeData { ChineseSimplifiedCommon, ChineseFull, Cyrillic, Default, Japanese, Korean, Thai, Vietnamese, Custom(*const sys::ImWchar), } #[derive(Clone, Eq, PartialEq, Debug)] pub struct FontGlyphRanges(FontGlyphRa...
use crate::sys; #[derive(Clone, Eq, PartialEq, Debug)] enum FontGlyphRangeData { ChineseSimplifiedCommon, ChineseFull, Cyrillic, Default, Japanese, Korean, Thai, Vietnamese, Custom(*const sys::ImWchar), } #[derive(Clone, Eq, PartialEq, Debug)] pub struct FontGlyphRanges(FontGlyphRa...
}
pub(crate) unsafe fn to_ptr(&self, atlas: *mut sys::ImFontAtlas) -> *const sys::ImWchar { match self.0 { FontGlyphRangeData::ChineseFull => sys::ImFontAtlas_GetGlyphRangesChineseFull(atlas), FontGlyphRangeData::ChineseSimplifiedCommon => { sys::ImFontAtlas_GetGlyphRangesC...
function_block-full_function
[ { "content": "/// Returns the underlying Dear ImGui library version\n\npub fn dear_imgui_version() -> &'static str {\n\n unsafe {\n\n let bytes = CStr::from_ptr(sys::igGetVersion()).to_bytes();\n\n str::from_utf8_unchecked(bytes)\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": ...
Rust
crates/bls-snark-sys/src/signatures.rs
psivesely/celo-bls-snark-rs
11875ab4829711b21b264eeddd1c0e70f7e31609
use crate::{ cache::PUBLIC_KEY_CACHE, convert_result_to_bool, utils::{Message, MessageFFI}, PrivateKey, PublicKey, Signature, COMPOSITE_HASH_TO_G1, DIRECT_HASH_TO_G1, }; use algebra::{ProjectiveCurve, ToBytes}; use bls_crypto::hash_to_curve::try_and_increment_cip22::COMPOSITE_HASH_TO_G1_CIP22; use bls_c...
use crate::{ cache::PUBLIC_KEY_CACHE, convert_result_to_bool, utils::{Message, MessageFFI}, PrivateKey, PublicKey, Signature, COMPOSITE_HASH_TO_G1, DIRECT_HASH_TO_G1, }; use algebra::{ProjectiveCurve, ToBytes}; use bls_crypto::hash_to_curve::try_and_increment_cip22::COMPOSITE_HASH_TO_G1_CIP22; use bls_c...
#[no_mangle] pub extern "C" fn sign_pop( in_private_key: *const PrivateKey, in_message: *const u8, in_message_len: c_int, out_signature: *mut *mut Signature, ) -> bool { convert_result_to_bool::<_, BLSError, _>(|| { let private_key = unsafe { &*in_private_key }; let message = unsaf...
e, ) -> bool { convert_result_to_bool::<_, BLSError, _>(|| { let private_key = unsafe { &*in_private_key }; let message = unsafe { slice::from_raw_parts(in_message, in_message_len as usize) }; let extra_data = unsafe { slice::from_raw_parts(in_extra_data, in_extra_data_len as usi...
function_block-function_prefixed
[ { "content": "/// The function assumes that the public key is not the point in infinity, which is true for\n\n/// BLS public keys\n\npub fn encode_public_key(public_key: &PublicKey) -> Result<Vec<bool>, EncodingError> {\n\n let pk_affine = public_key.as_ref().into_affine();\n\n let x = pk_affine.x;\n\n ...
Rust
src/agent/coverage/src/block/windows.rs
chkeita/onefuzz
e413aec03dcd682c049855b77cf0b0042407ddc1
use std::collections::BTreeMap; use std::process::Command; use std::time::{Duration, Instant}; use anyhow::Result; use debugger::{ debugger::{BreakpointId, BreakpointType, DebugEventHandler, Debugger}, target::Module, }; use crate::block::CommandBlockCov; use crate::cache::ModuleCache; use crate::code::{Cmd...
use std::collections::BTreeMap; use std::process::Command; use std::time::{Duration, Instant}; use anyhow::Result; use debugger::{ debugger::{BreakpointId, BreakpointType, DebugEventHandler, Debugger}, target::Module, }; use crate::block::CommandBlockCov; use crate::cache::ModuleCache; use crate::code::{Cmd...
t, timeout, } } pub fn time_out(&self) -> bool { self.timed_out } pub fn timeout(&self) -> Duration { self.timeout } pub fn run(&mut self, cmd: Command) -> Result<()> { let (mut dbg, _child) = Debugger::init(cmd, self)?; dbg.run(self)?; ...
started = Instant::now(); let timed_out = false; Self { recorder, started, timed_ou
function_block-random_span
[ { "content": "pub fn record(cmd: Command) -> Result<CommandBlockCov> {\n\n let mut cache = ModuleCache::default();\n\n let filter = CmdFilter::default();\n\n let mut recorder = Recorder::new(&mut cache, filter);\n\n recorder.record(cmd)?;\n\n Ok(recorder.into_coverage())\n\n}\n\n\n\n#[derive(Debu...
Rust
actix-tls/src/accept/openssl.rs
seinlin/actix-net
b1d5d85e72deafd45f79d96a52dc18156e90a2dc
use std::{ convert::Infallible, future::Future, io::{self, IoSlice}, pin::Pin, task::{Context, Poll}, time::Duration, }; use actix_codec::{AsyncRead, AsyncWrite, ReadBuf}; use actix_rt::{ net::{ActixStream, Ready}, time::{sleep, Sleep}, }; use actix_service::{Service, ServiceFactory};...
use std::{ convert::Infallible, future::Future, io::{self, IoSlice}, pin::Pin, task::{Context, Poll}, time::Duration, }; use actix_codec::{AsyncRead, AsyncWrite, ReadBuf}; use actix_rt::{ net::{ActixStream, Ready}, time::{sleep, Sleep}, }; use actix_service::{Service, ServiceFactory};...
ut Self { self.handshake_timeout = handshake_timeout; self } } impl Clone for Acceptor { #[inline] fn clone(&self) -> Self { Self { acceptor: self.acceptor.clone(), handshake_timeout: self.handshake_timeout, } } } impl<IO: ActixStream> ServiceFac...
<()>> { Pin::new(&mut **self.get_mut()).poll_shutdown(cx) } fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll<io::Result<usize>> { Pin::new(&mut **self.get_mut()).poll_write_vectored(cx, bufs) } fn is_write_v...
random
[ { "content": "#[inline]\n\npub fn poll_fn<F, T>(f: F) -> PollFn<F>\n\nwhere\n\n F: FnMut(&mut Context<'_>) -> Poll<T>,\n\n{\n\n PollFn { f }\n\n}\n\n\n\n/// A Future driven by the inner function.\n\npub struct PollFn<F> {\n\n f: F,\n\n}\n\n\n\nimpl<F> Unpin for PollFn<F> {}\n\n\n\nimpl<F> fmt::Debug fo...
Rust
src/hash.rs
khernyo/zopfli-rs
855169f74c9e18eb93a424a0ce6e5ce7550de954
use std::cell::RefCell; use std::iter; use std::rc::Rc; use util::{MIN_MATCH, WINDOW_MASK}; pub struct Hash { pub head: Rc<RefCell<[i32; 65536]>>, pub prev: Rc<RefCell<Vec<u16>>>, pub hashval: Rc<RefCell<Vec<i32>>>, pub val: i32, pub hash_same_hash: HashSameHash, pub ...
use std::cell::RefCell; use std::iter; use std::rc::Rc; use util::{MIN_MATCH, WINDOW_MASK}; pub struct Hash { pub head: Rc<RefCell<[i32; 65536]>>, pub prev: Rc<RefCell<Vec<u16>>>, pub hashval: Rc<RefCell<Vec<i32>>>, pub val: i32, pub hash_same_hash: HashSameHash, pub ...
pub fn warmup_hash(array: &[u8], pos: usize, end: usize, h: &mut Hash) { update_hash_value(h, array[pos + 0]); if pos + 1 < end { update_hash_value(h, array[pos + 1]); } }
t(); let mut prev = h.prev.borrow_mut(); let mut hashval = h.hashval.borrow_mut(); hashval[hpos as usize] = h.val; if head[h.val as usize] != -1 && hashval[head[h.val as usize] as usize] == h.val { prev[hpos as usize] = head[h.val as usize] as u16; } else { ...
function_block-function_prefixed
[ { "content": "pub fn calculate_bit_lengths(count: &[usize], n: usize, maxbits: i32, bitlengths: &mut [u32]) {\n\n let error = super::katajainen::length_limited_code_lengths(count, n as i32, maxbits, bitlengths);\n\n assert!(!error);\n\n}\n", "file_path": "src/tree.rs", "rank": 5, "score": 2221...
Rust
examples/s_expression.rs
adamnemecek/nom
f8d67930358bbba7efa172b7e2ad74b41f50b2f4
#![cfg(feature = "alloc")] extern crate jemallocator; extern crate nom; #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use nom::{ branch::alt, bytes::complete::tag, character::complete::{alpha1, char, digit1, multispace0, multispace1, one_of}, combinator::{cut, map, map_...
#![cfg(feature = "alloc")] extern crate jemallocator; extern crate nom; #[global_allocator] static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc; use nom::{ branch::alt, bytes::complete::tag, character::complete::{alpha1, char, digit1, multispace0, multispace1, one_of}, combinator::{cut, map, map_...
fn parse_expr<'a>(i: &'a str) -> IResult<&'a str, Expr, VerboseError<&'a str>> { preceded(multispace0, alt((parse_constant, parse_application, parse_if, parse_quote)))(i) } fn get_num_from_expr(e: Expr) -> Option<i32> { if let Expr::Constant(Atom::Num(n)) = e { Some(n) } else { None } } fn get_bool_...
fn parse_quote<'a>(i: &'a str) -> IResult<&'a str, Expr, VerboseError<&'a str>> { map(context("quote", preceded(tag("'"), cut(s_exp(many0(parse_expr))))), |exprs| { Expr::Quote(exprs) })(i) }
function_block-full_function
[ { "content": "#[cfg(feature = \"alloc\")]\n\npub fn context<I: Clone, E: ParseError<I>, F, O>(context: &'static str, f: F) -> impl Fn(I) -> IResult<I, O, E>\n\nwhere\n\n F: Fn(I) -> IResult<I, O, E> {\n\n\n\n move |i: I| {\n\n match f(i.clone()) {\n\n Ok(o) => Ok(o),\n\n Err(Err::Incomple...
Rust
chain/ethereum/src/network_indexer/block_writer.rs
litegraph/litegraph-node
6d96e87c184b5da2cc1620a4ad9613da1dd5d457
use std::time::Instant; use graph::{components::store::WritableStore, prelude::*}; use super::*; struct BlockWriterMetrics { stopwatch: StopwatchMetrics, transaction: Aggregate, } impl BlockWriterMetrics { pub fn new( subgraph_id: &DeploymentHash, stopwatch: StopwatchMetr...
use std::time::Instant; use graph::{components::store::WritableStore, prelude::*}; use super::*; struct BlockWriterMetrics { stopwatch: StopwatchMetrics, transaction: Aggregate, } impl BlockWriterMetrics { pub fn new( subgraph_id: &DeploymentHash, stopwatch: StopwatchMetr...
store: self.store.clone(), cache: EntityCache::new(self.store.clone()), metrics: self.metrics.clone(), }; context.write(block) } } struct WriteContext { logger: Logger, subgraph_id: DeploymentHash, store: Arc<dyn WritableStore>, cache: EntityCache, ...
"block" => format!("{}", block), )); let context = WriteContext { logger, subgraph_id: self.subgraph_id.clone(),
random
[ { "content": "pub fn transact_errors(\n\n store: &Arc<Store>,\n\n deployment: &DeploymentLocator,\n\n block_ptr_to: BlockPtr,\n\n errs: Vec<SubgraphError>,\n\n) -> Result<(), StoreError> {\n\n let metrics_registry = Arc::new(MockMetricsRegistry::new());\n\n let stopwatch_metrics = StopwatchMet...
Rust
polars/polars-lazy/src/logical_plan/options.rs
cigrainger/polars
0753b771cb0e2f9b4f01c646966f7102f94b5a49
use crate::prelude::*; use polars_core::prelude::*; use polars_io::csv::{CsvEncoding, NullValues}; use polars_io::RowCount; #[derive(Clone, Debug)] pub struct CsvParserOptions { pub(crate) delimiter: u8, pub(crate) comment_char: Option<u8>, pub(crate) quote_char: Option<u8>, pub(crate) has_header: bool...
use crate::prelude::*; use polars_core::prelude::*; use polars_io::csv::{CsvEncoding, NullValues}; use polars_io::RowCount; #[derive(Clone, Debug)] pub struct CsvParserOptions { pub(crate) delimiter: u8, pub(crate) comment_char: Option<u8>, pub(crate) quote_char: Option<u8>, pub(crate
#[derive(Clone, Debug)] pub struct DistinctOptions { pub(crate) subset: Option<Arc<Vec<String>>>, pub(crate) maintain_order: bool, pub(crate) keep_strategy: UniqueKeepStrategy, } #[derive(Copy, Clone, Debug, PartialEq)] pub enum ApplyOptions { ApplyGroups, ApplyList, ApplyF...
) has_header: bool, pub(crate) skip_rows: usize, pub(crate) n_rows: Option<usize>, pub(crate) with_columns: Option<Vec<String>>, pub(crate) low_memory: bool, pub(crate) ignore_errors: bool, pub(crate) cache: bool, pub(crate) null_values: Option<NullValues>, pub(crate) rechunk: bool, ...
random
[ { "content": "/// Utility to write to `&mut Vec<u8>` buffer.\n\nstruct StringWrap<'a>(pub &'a mut Vec<u8>);\n\n\n\nimpl<'a> std::fmt::Write for StringWrap<'a> {\n\n fn write_str(&mut self, s: &str) -> std::fmt::Result {\n\n self.0.extend_from_slice(s.as_bytes());\n\n Ok(())\n\n }\n\n}\n\n\n\...
Rust
src/advent/inventory_management.rs
MitchelAnthony/advent-2018
9075e33020c833d29c4d3ef3717ef9da89b66996
pub struct Inventory { boxes: Vec<String> } impl Inventory { pub fn new(boxes: Vec<String>) -> Inventory { Inventory { boxes, } } pub fn checksum(&self) -> isize { let mut double = 0; let mut triple = 0; for box_id in &self.boxes { doubl...
pub struct Inventory { boxes: Vec<String> } impl Inventory { pub fn new(boxes: Vec<String>) -> Inventory { Inventory { boxes, } } pub fn checksum(&self) -> isize { let mut double = 0; let mut triple = 0; for box_id in &self.boxes { doubl...
f(&s1, &s2), -1); s1 = String::from("apple"); s2 = String::from("azzle"); assert_eq!(Inventory::find_single_letter_diff(&s1, &s2), -1); } }
single_letter_diff(&s1, &s2), 10); s1 = String::from("apple"); s2 = String::from("apple"); assert_eq!(Inventory::find_single_letter_diff(&s1, &s2), -1); s1 = String::from("apple"); s2 = String::from("apples"); assert_eq!(Inventory::find_single_letter_dif
function_block-random_span
[]
Rust
src/component.rs
rdelfin/ecs-rs
5817b66cf818dd22e8d373adfed58e03785822d9
#[cfg(feature="serialisation")] use cereal::{CerealData, CerealError, CerealResult}; #[cfg(feature="serialisation")] use std::io::{Read, Write}; use std::collections::HashMap; use std::marker::PhantomData; use std::ops::{Index, IndexMut}; use vec_map::VecMap; use self::InnerComponentList::{Hot, Cold}; use {BuildDat...
#[cfg(feature="serialisation")] use cereal::{CerealData, CerealError, CerealResult}; #[cfg(feature="serialisation")] use std::io::{Read, Write}; use std::collections::HashMap; use std::marker::PhantomData; use std::ops::{Index, IndexMut}; use vec_map::VecMap; use self::InnerComponentList::{Hot, Cold}; use {BuildDat...
sert(entity.entity().index(), component), Cold(ref mut c) => c.insert(entity.entity().index(), component), } } pub fn remove(&mut self, entity: &ModifyData<C>) -> Option<T> { match self.0 { Hot(ref mut c) => c.remove(&entity.entity().index()), Col...
ComponentManager, T: Component> CerealData for ComponentList<C, T> where T: CerealData { fn write(&self, w: &mut Write) -> CerealResult<()> { self.0.write(w) } fn read(r: &mut Read) -> CerealResult<Self> { CerealData::read(r).map(|inner| ComponentList(inner, PhantomData)) } } #[cfg(fe...
random
[ { "content": "pub trait ComponentManager: 'static+Sized\n\n{\n\n #[doc(hidden)]\n\n fn __new() -> Self;\n\n #[doc(hidden)]\n\n fn __remove_all(&mut self, &IndexedEntity<Self>);\n\n}\n\n\n", "file_path": "src/world.rs", "rank": 1, "score": 118008.4694442404 }, { "content": "pub tr...
Rust
src/control/cache.rs
khappucino/linkerd2-proxy
a7960f936dcf47bcf4aa1e32e65691cf805a8c50
use indexmap::{IndexMap, IndexSet}; use indexmap::map::{self, Entry}; use std::hash::Hash; use std::iter::IntoIterator; use std::mem; pub struct Cache<K, V> { inner: IndexMap<K, V>, reset_on_next_modification: bool, } pub enum Exists<T> { Unknown, Yes(T), No, } #[derive(Debug, Eq, ...
use indexmap::{IndexMap, IndexSet}; use indexmap::map::{self, Entry}; use std::hash::Hash; use std::iter::IntoIterator; use std::mem; pub struct Cache<K, V> { inner: IndexMap<K, V>, reset_on_next_modification: bool, } pub enum Exists<T> { Unknown, Yes(T), No, } #[derive(Debug, Eq, ...
#[test] fn clear_fires_removal_event() { let mut cache = Cache { inner: indexmap!{ 1 => () }, reset_on_next_modification: false, }; cache.clear( &mut |change| { assert_eq!(change, CacheChange::Removal{ key: 1, }); }, ...
s() { let mut cache = Cache { inner: indexmap!{ 1 => "one", 2 => "two", }, reset_on_next_modification: false, }; let mut insertions = 0; let mut modifications = 0; cache.update_union( indexmap!{ 1 => "one", 2 => "2", 3 => "three"}.into_iter(...
function_block-function_prefixed
[ { "content": "pub fn new() -> Controller {\n\n Controller::new()\n\n}\n\n\n\npub type Labels = HashMap<String, String>;\n\n\n\n#[derive(Debug)]\n\npub struct DstReceiver(sync::mpsc::UnboundedReceiver<pb::Update>);\n\n\n\n#[derive(Clone, Debug)]\n\npub struct DstSender(sync::mpsc::UnboundedSender<pb::Update>)...
Rust
src/config_file.rs
The-Compiler/lsd
48210f30fbadfd910659b7ae40d8db4cf3303946
use crate::flags::color::ColorOption; use crate::flags::display::Display; use crate::flags::icons::{IconOption, IconTheme}; use crate::flags::layout::Layout; use crate::flags::size::SizeFlag; use crate::flags::sorting::{DirGrouping, SortColumn}; use crate::print_error; use std::path::PathBuf; use serde::Deserialize...
use crate::flags::color::ColorOption; use crate::flags::display::Display; use crate::flags::icons::{IconOption, IconTheme}; use crate::flags::layout::Layout; use crate::flags::size::SizeFlag; use crate::flags::sorting::{DirGrouping, SortColumn}; use crate::print_error; use std::path::PathBuf; use serde::Deserialize...
#[cfg(windows)] fn config_file_path() -> Option<PathBuf> { if let Some(p) = dirs::config_dir() { return Some( p.join(CONF_DIR) .join(CONF_FILE_NAME) .with_extension(YAML_LONG_EXT), ); } None }...
p); } } Err(e) => print_error!("Can not open config file: {}.", e), } None }
function_block-function_prefixed
[ { "content": "pub fn tree(metas: &[Meta], flags: &Flags, colors: &Colors, icons: &Icons) -> String {\n\n let mut grid = Grid::new(GridOptions {\n\n filling: Filling::Spaces(1),\n\n direction: Direction::LeftToRight,\n\n });\n\n\n\n let padding_rules = get_padding_rules(&metas, flags);\n\n...
Rust
garnet/public/rust/fuchsia-inspect/src/health.rs
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
#![allow(unused)] use { super::{Inspector, Property, StringProperty}, std::sync::{Arc, Mutex}, }; pub trait Reporter { fn set_starting_up(&mut self); fn set_ok(&mut self); fn set_unhealthy(&mut self, message: &str); } const FUCHSIA_INSPECT_HEALTH: &str = "fuchsia.inspect.Hea...
#![allow(unused)] use { super::{Inspector, Property, StringProperty}, std::sync::{Arc, Mutex}, }; pub trait Reporter { fn set_starting_up(&mut self); fn set_ok(&mut self); fn set_unhealthy(&mut self, message: &str); } const FUCHSIA_INSPECT_HEALTH: &str = "fuchsia.inspect.Hea...
} pub struct Node { node: super::Node, status: StringProperty, message: Option<StringProperty>, } impl Reporter for Node { fn set_starting_up(&mut self) { self.set_status_enum(Status::StartingUp, None); } fn set_ok(&mut self) { self.set_status_enum(...
ing::from(match self { Status::StartingUp => "STARTING_UP", Status::Unhealthy => "UNHEALTHY", Status::Ok => "OK", }) }
function_block-function_prefixed
[]
Rust
src/core/object/generic.rs
yu-i9/mini_python
d62b9040f8427057a20d18340a27bdf2dfc8c22e
use std::rc::Rc; use error::*; use env::*; use eval::{PyRes, eval}; use object::*; use object::boolobj::*; use object::excobj::*; use object::methodobj::*; use object::noneobj::*; use object::rustfunobj::*; use object::typeobj::*; pub fn pyobj_to_bool(v: Rc<PyObject>) -> PyRes<bool> { let ob_type = v.ob_type(); ...
use std::rc::Rc; use error::*; use env::*; use eval::{PyRes, eval}; use object::*; use object::boolobj::*; use object::excobj::*; use object::methodobj::*; use object::noneobj::*; use object::rustfunobj::*; use object::typeobj::*; pub fn pyobj_to_bool(v: Rc<PyObject>) -> PyRes<bool> { let ob_type = v.ob_type(); ...
Y_METHOD_TYPE.with(|tp| { Some(Rc::clone(tp)) }), ob_dict: None, inner: PyInnerObject::MethodObj(Rc::new( PyMethodObject { ob_self: Rc::clone(&slf), env: Rc::clone(&fun.env), codeobj: Rc::clone(&f...
nd_self(value: &Rc<PyObject>, slf: Rc<PyObject>) -> Rc<PyObject> { match value.inner { PyInnerObject::FunObj(ref fun) => { Rc::new(PyObject { ob_type: P
function_block-random_span
[ { "content": "fn inherit_method(typ: &mut PyTypeObject, base: &PyTypeObject) {\n\n if typ.tp_hash.is_none() && base.tp_hash.is_some() {\n\n typ.tp_hash = base.tp_hash.clone();\n\n }\n\n\n\n if typ.tp_bool.is_none() && base.tp_bool.is_some() {\n\n typ.tp_bool = base.tp_bool.clone();\n\n ...
Rust
fw/src/cpld.rs
yahoo/hardware-hackme-1
d7acbf36854b088a34419f9697f64aaf0e3be83c
use core::sync::atomic::AtomicU32; use jtag::*; use ::msleep; const JTAG_OPC_IDCODE: u8 = 0b00000001; const JTAG_OPC_BYPASS: u8 = 0b11111111; const ISC_DISABLE: u8 = 0b11000000; const ISC_ENABLE: u8 = 0b11101000; const ISC_PROGRAM: u8 = 0b11101010; const ISC_ERASE: u8 = 0b11101101; co...
use core::sync::atomic::AtomicU32; use jtag::*; use ::msleep; const JTAG_OPC_IDCODE: u8 = 0b00000001; const JTAG_OPC_BYPASS: u8 = 0b11111111; const ISC_DISABLE: u8 = 0b11000000; const ISC_ENABLE: u8 = 0b11101000; const ISC_PROGRAM: u8 = 0b11101010; const ISC_ERASE: u8 = 0b11101101; co...
pub fn cpld_write_eeprom<F>(gpio: &::stm32f405::gpiob::RegisterBlock, msleep_ctr: &'static AtomicU32, mut callback: F) where F: FnMut(u32, u32) -> bool { test_logic_reset(gpio); shift_ir_from_tlr(gpio); shift_u8(gpio, ISC_ENABLE, true); run_test_idle_from_exit1_ir_dr(gpio); msleep(msleep_ctr...
e); shift_bit(gpio, (addr_gray & (1 << 3)) != 0, false); shift_bit(gpio, (addr_gray & (1 << 2)) != 0, false); shift_bit(gpio, (addr_gray & (1 << 1)) != 0, false); shift_bit(gpio, (addr_gray & (1 << 0)) != 0, true); run_test_idle_from_exit1_ir_dr(gpio); msleep(msleep_ctr, ...
function_block-function_prefixed
[ { "content": "pub fn msleep(ctr: &'static AtomicU32, ms: u32) {\n\n let time_start = ctr.load(Ordering::Relaxed);\n\n loop {\n\n let time_now = ctr.load(Ordering::Relaxed);\n\n if time_now.wrapping_sub(time_start) >= ms {\n\n break;\n\n }\n\n rtfm::wfi();\n\n }\n\...
Rust
src/developer/remote-control/src/host_identifier.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { anyhow::{Context as _, Result}, fidl_fuchsia_buildinfo as buildinfo, fidl_fuchsia_developer_remotecontrol as rcs, fidl_fuchsia_device as fdevice, fidl_fuchsia_hwinfo as hwinfo, fidl_fuchsia_net_interfaces as fnet_interfaces, fidl_fuchsia_net_interfaces_ext as fnet_interfaces_ext, fuchsia_zir...
use { anyhow::{Context as _, Result}, fidl_fuchsia_buildinfo as buildinfo, fidl_fuchsia_developer_remotecontrol as rcs, fidl_fuchsia_device as fdevice, fidl_fuchsia_hwinfo as hwinfo, fidl_fuchsia_net_interfaces as fnet_interfaces, fidl_fuchsia_net_interfaces_ext as fnet_interfaces_ext, fuchsia_zir...
, Err(err) => { error!(%err, "Getting nodename failed"); return Err(rcs::IdentifyHostError::GetDeviceNameFailed); } }; let boot_timestamp_nanos = Some(self.boot_timestamp_nanos); Ok(rcs::IdentifyHostResponse { nodename, ...
match result { Ok(name) => Some(name), Err(err) => { error!(%err, "NameProvider internal error"); return Err(rcs::IdentifyHostError::GetDeviceNameFailed); } }
if_condition
[]
Rust
src/stats.rs
hepek/imageproc
58adc520090000c36da98f59338d41d8e3e2faa6
use image::{GenericImage, GrayImage, Pixel, Primitive}; use crate::definitions::Image; use num::Bounded; use crate::math::cast; use conv::ValueInto; pub struct ChannelHistogram { pub channels: Vec<[u32; 256]> } pub fn histogram<P>(image: &Image<P>) -> ChannelHistogram where P: Pixel<Subpixel=u8> + 'sta...
use image::{GenericImage, GrayImage, Pixel, Primitive}; use crate::definitions::Image; use num::Bounded; use crate::math::cast; use conv::ValueInto; pub struct ChannelHistogram { pub channels: Vec<[u32; 256]> } pub fn histogram<P>(image: &Image<P>) -> ChannelHistogram where P: Pixel<Subpixel=u8> + 'sta...
let hist = cumulative_histogram(&image); let r = hist.channels[0]; let g = hist.channels[1]; let b = hist.channels[2]; assert_eq!(r[0..4], [0, 2, 4, 5]); assert!(r.iter().skip(4).all(|x| *x == 5)); assert_eq!(g[0..10], [0; 10]); assert_eq!(g[10..20], [...
let image = rgb_image!( [1u8, 10u8, 1u8], [2u8, 20u8, 2u8], [3u8, 30u8, 3u8], [2u8, 20u8, 2u8], [1u8, 10u8, 1u8] );
assignment_statement
[ { "content": "/// Adds independent additive Gaussian noise to all channels\n\n/// of an image in place, with the given mean and standard deviation.\n\npub fn gaussian_noise_mut<P>(image: &mut Image<P>, mean: f64, stddev: f64, seed: u64)\n\nwhere\n\n P: Pixel + 'static,\n\n P::Subpixel: ValueInto<f64> + Cl...
Rust
src/kernel/src/arch/amd64/start.rs
ariadiamond/twizzler-Rust
5f5d01bac9127ca1d64bb8aa472a04f6634fc3a9
use alloc::vec::Vec; use stivale_boot::v2::{ StivaleFramebufferHeaderTag, StivaleHeader, StivaleMemoryMapEntryType, StivaleStruct, StivaleUnmapNullHeaderTag, }; use x86_64::{PhysAddr, VirtAddr}; use crate::{ initrd::BootModule, memory::{MemoryRegion, MemoryRegionKind}, BootInfo, }; global_asm!( ...
use alloc::vec::Vec; use stivale_boot::v2::{ StivaleFramebufferHeaderTag, StivaleHeader, StivaleMemoryMapEntryType, StivaleStruct, StivaleUnmapNullHeaderTag, }; use x86_64::{PhysAddr, VirtAddr}; use crate::{ initrd::BootModule, memory::{MemoryRegion, MemoryRegionKind}, BootInfo, }; global_asm!( ...
erved, } } } extern "C" fn __stivale_start(info: &'static StivaleStruct) -> ! { unsafe { let efer = x86::msr::rdmsr(x86::msr::IA32_EFER); x86::msr::wrmsr(x86::msr::IA32_EFER, efer | (1 << 11)); let cr4 = x86::controlregs::cr4(); x86::controlregs::cr4_write( c...
".long 9", ".long 12", ".long 14", ".long 15", ".long 6", "_mbh_info_end:", "_mbh_fb_start:", ".short 5", ".short 0", ".long _mbh_fb_end - _mbh_fb_start", ".long 0", ".long 0", ".long 32", ".long 0", "_mbh_fb_end:", ".short 0", ".short 0", ...
random
[]
Rust
src/ahb_secure_ctrl/sec_vio_misc_info.rs
conorpp/lpc55-pac
eb30d633de05113362de01095123d70c54e63ef4
#[doc = "Reader of register sec_vio_misc_info[%s]"] pub type R = crate::R<u32, super::SEC_VIO_MISC_INFO>; #[doc = "security violation access read/write indicator.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SEC_VIO_INFO_WRITE_A { #[doc = "0: Read access."] READ = 0, #[doc = "1: ...
#[doc = "Reader of register sec_vio_misc_info[%s]"] pub type R = crate::R<u32, super::SEC_VIO_MISC_INFO>; #[doc = "security violation access read/write indicator.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SEC_VIO_INFO_WRITE_A { #[doc = "0: Read access."] READ = 0, #[doc = "1: ...
_3`"] #[inline(always)] pub fn is_value_3(&self) -> bool { *self == SEC_VIO_INFO_MASTER_A::VALUE_3 } #[doc = "Checks if the value of the field is `VALUE_4`"] #[inline(always)] pub fn is_value_4(&self) -> bool { *self == SEC_VIO_INFO_MASTER_A::VALUE_4 } #[doc = "Checks if ...
elf.bits { false => SEC_VIO_INFO_WRITE_A::READ, true => SEC_VIO_INFO_WRITE_A::WRITE, } } #[doc = "Checks if the value of the field is `READ`"] #[inline(always)] pub fn is_read(&self) -> bool { *self == SEC_VIO_INFO_WRITE_A::READ } #[doc = "Checks if the va...
random
[ { "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
day24/src/main.rs
ajtribick/AdventOfCode2020
a633a31ff0d456b587dd7602a30c9d841417f3a0
use std::{ error::Error, fmt, fs::File, io::{BufRead, BufReader}, path::PathBuf, }; use ahash::AHashSet; #[derive(Debug)] struct ParseCoordsError(&'static str); impl fmt::Display for ParseCoordsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Parse error: ...
use std::{ error::Error, fmt, fs::File, io::{BufRead, BufReader}, path::PathBuf, }; use ahash::AHashSet; #[derive(Debug)] struct ParseCoordsError(&'static str); impl fmt::Display for ParseCoordsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Parse error: ...
pub fn get_neighbors(&self) -> [Self; 6] { [ Self(self.0 - 1, self.1), Self(self.0 + 1, self.1), Self(self.0 - 1, self.1 - 1), Self(self.0, self.1 - 1), Self(self.0, self.1 + 1), Self(self.0 + 1, self.1 + 1), ] } } struct...
s() { match (&state, c) { (ParseState::None, b'w') => x -= 1, (ParseState::None, b'e') => x += 1, (ParseState::None, b'n') => { y -= 1; state = ParseState::North; } (ParseState::None, b's'...
function_block-function_prefixed
[ { "content": "fn part2(lines: impl Iterator<Item = impl AsRef<str>> + Clone) {\n\n let result = SLOPES\n\n .iter()\n\n .map(|&(right_step, down_step)| count_trees(lines.clone(), right_step, down_step))\n\n .product::<u32>();\n\n println!(\"Part 2: product is {}\", result);\n\n}\n\n\n"...
Rust
src/graphql/mutations/card.rs
nicksenger/total-recall
c2243ec6e161ad8ab2f536468da7473eb9f3f2c8
use diesel::{pg::Pg, prelude::*}; use juniper::*; use sanitize_filename::sanitize; use std::time::{SystemTime, UNIX_EPOCH}; use wundergraph::{ query_builder::{ mutations::{DeletedCount, HandleBatchInsert, HandleDelete, HandleInsert, HandleUpdate}, selection::LoadingHandler, }, scalar::WundergraphScalarVal...
use diesel::{pg::Pg, prelude::*}; use juniper::*; use sanitize_filename::sanitize; use std::time::{SystemTime, UNIX_EPOCH}; use wundergraph::{ query_builder::{ mutations::{DeletedCount, HandleBatchInsert, HandleDelete, HandleInsert, HandleUpdate}, selection::LoadingHandler, }, scalar::WundergraphScalarVal...
} #[derive(Identifiable, GraphQLInputObject, Debug)] #[table_name = "cards"] pub struct CardChangeset { id: i32, link: Option<String>, } impl HandleUpdate<Card, CardChangeset, Pg, GQLContext<DBConnection>> for cards::table { fn handle_update( selection: Option<&'_ [Selection<'_, WundergraphScalarValue>]>, ...
ks::language))) .filter(decks::id.eq_any(deck_ids)) .get_results::<(String, (i32, i32))>(conn)?; for (_, (owner, _)) in &decks_owners_languages { if &id != owner { return ExecutionResult::from(TRCError::Unauthorized); } } let time = SystemTime::now().duratio...
function_block-function_prefixed
[ { "content": "pub fn encode_jwt(user_id: i32, exp_day: i32) -> Result<String, jwt::errors::Error> {\n\n let exp = SystemTime::now()\n\n .duration_since(UNIX_EPOCH)\n\n .expect(\"Time went backwards\")\n\n .as_secs() as i32\n\n + exp_day * 24 * 60 * 60;\n\n\n\n let jwt_secret_ke...
Rust
src/testing/sl4f/src/tiles/facade.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use anyhow::Error; use crate::tiles::types::{ AddTileInput, AddTileOutput, ListTileOutput, RemoveTileInput, TileOutput, }; use fidl_fuchsia_developer_tiles::ControllerMarker; use fuchsia_component::client::{launch, launcher, App}; use fuchsia_syslog::macros::fx_log_info; use serde_json::{from_value, to_value, Va...
use anyhow::Error; use crate::tiles::types::{ AddTileInput, AddTileOutput, ListTileOutput, RemoveTileInput, TileOutput, }; use fidl_fuchsia_developer_tiles::ControllerMarker; use fuchsia_component::client::{launch, launcher, App}; use fuchsia_syslog::macros::fx_log_info; use serde_json::{from_value, to_value, Va...
pub fn stop_tile(&self) -> Result<Value, Error> { if self.tiles.borrow().is_some() { let controller_proxy = self.tiles.borrow().as_ref().unwrap().connect_to_protocol::<ControllerMarker>()?; controller_proxy.quit()?; self.tiles.replace(None); ...
pub fn start_flatland_tile(&self) -> Result<Value, Error> { if self.tiles.borrow().is_none() { match launch( &launcher()?, String::from("fuchsia-pkg://fuchsia.com/tiles#meta/tiles-flatland.cmx"), None, ) { Ok(a) => { ...
function_block-full_function
[]
Rust
src/snapshot.rs
Congyuwang/RocksDict
bad2f88838e5ba2bd85dc21c7cc6550d02783772
use crate::encoder::{decode_value, encode_key, encode_raw}; use crate::{Rdict, RdictItems, RdictIter, RdictKeys, RdictValues, ReadOpt, ReadOptionsPy}; use librocksdb_sys; use pyo3::exceptions::PyException; use pyo3::prelude::*; use rocksdb::db::DBAccess; use rocksdb::{ColumnFamily, ReadOptions, DB}; use std::cell::RefC...
use crate::encoder::{decode_value, encode_key, encode_raw}; use crate::{Rdict, RdictItems, RdictIter, RdictKeys, RdictValues, ReadOpt, ReadOptionsPy}; use librocksdb_sys; use pyo3::exceptions::PyException; use pyo3::prelude::*; use rocksdb::db::DBAccess; use rocksdb::{ColumnFamily, ReadOptions, DB}; use std::cell::RefC...
#[pyo3(text_signature = "($self, backwards, from_key, read_opt)")] #[args( backwards = "false", from_key = "_py.None().into_ref(_py)", read_opt = "_py.None().into_ref(_py)" )] fn items( &self, backwards: bool, from...
t.is_none() { Py::new(py, ReadOptionsPy::default(self.raw_mode, py)?)? } else { read_opt.extract()? }; let opt: ReadOpt = read_opt.borrow(py).deref().into(); unsafe { set_snapshot(opt.0, self.inner); } Ok(RdictIter::new( &se...
function_block-function_prefixed
[ { "content": "#[pymodule]\n\nfn rocksdict(_py: Python, m: &PyModule) -> PyResult<()> {\n\n m.add_class::<Rdict>()?;\n\n m.add_class::<OptionsPy>()?;\n\n m.add_class::<MemtableFactoryPy>()?;\n\n m.add_class::<BlockBasedOptionsPy>()?;\n\n m.add_class::<CuckooTableOptionsPy>()?;\n\n m.add_class::...
Rust
src/vm/operations.rs
Nickforall/yukon
b310c92cedf77b95fe66c2792fb3a280ee00f605
use super::JsValue; use super::temp::js_value_to_string; use super::types::rust_to_js_boolean; use super::types::flip_js_bool; use super::types::try_js_value_to_js_number; pub fn add(a: &JsValue, b: &JsValue) -> JsValue { match (a, b) { (&JsValue::JsNumber(x), &JsValue::JsNumber(y)) => { return...
use super::JsValue; use super::temp::js_value_to_string; use super::types::rust_to_js_boolean; use super::types::flip_js_bool; use super::types::try_js_value_to_js_number; pub fn add(a: &JsValue, b: &JsValue) -> JsValue { match (a, b) { (&JsValue::JsNumber(x), &JsValue::JsNumber(y)) => { return...
pub fn neq(a: &JsValue, b: &JsValue) -> JsValue { return flip_js_bool(eq(a, b)) } pub fn strict_eq(a: &JsValue, b: &JsValue) -> JsValue { match (a, b) { (&JsValue::JsString(ref x), &JsValue::JsString(ref y)) => { return rust_to_js_boolean(x == y) }, (&JsValue::JsNumber(x),...
4>() { Ok(parsed_y) => return rust_to_js_boolean(x == parsed_y), Err(_) => return JsValue::JsFalse, } } _ => return JsValue::JsFalse } }
function_block-function_prefixed
[ { "content": "pub fn rust_to_js_boolean(b: bool) -> JsValue {\n\n if b == true {\n\n return JsValue::JsTrue\n\n } else {\n\n return JsValue::JsFalse\n\n }\n\n}\n\n\n", "file_path": "src/vm/types.rs", "rank": 0, "score": 62621.171489649496 }, { "content": "pub fn flip_j...
Rust
ping_scan/src/configuration/mod.rs
Stratus51/rust_ping_scanner
6d05a46df54ee036b50c869f08b4056a7716d77b
use crate::cursor::{self, Cursor, CursorExt}; use crate::internet::ip_is_valid; use serde::{Deserialize, Serialize}; use std::net::Ipv4Addr; use std::time::Duration; pub mod v0; pub mod v1; fn field_from_args<T: std::str::FromStr>(args: &[String], field_name: &str) -> Result<T, String> where <T as std::str::FromS...
use crate::cursor::{self, Cursor, CursorExt}; use crate::internet::ip_is_valid; use serde::{Deserialize, Serialize}; use std::net::Ipv4Addr; use std::time::Duration; pub mod v0; pub mod v1; fn field_from_args<T: std::str::FromStr>(args: &[String], field_name: &str) -> Result<T, String> where <T as std::str::FromS...
} } #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub enum CursorType { Sampling = 0, Sequential = 1, Periodic = 2, ReverseEndianSequential = 3, } impl CursorType { pub fn from_str(s: &str) -> Result<Self, ()> { Ok(match s { "sampling" => Self::Samp...
Ok(Self { timeout: Duration::from_millis(timeout), size, parallelism, ttl, })
call_expression
[ { "content": "pub trait CursorExt: Cursor {\n\n fn to_iter(self) -> CursorIterator<Self>\n\n where\n\n Self: Sized,\n\n {\n\n CursorIterator::new(self)\n\n }\n\n\n\n fn filter<P>(self, predicate: P) -> FilterCursor<Self, P>\n\n where\n\n Self: Sized,\n\n P: FnMut(&S...
Rust
src/instruction.rs
Antoine32/Script
145058b01521411a6129024acecedae49db2b6a3
#[allow(unused_imports)] use crate::{eprint, eprintln}; pub enum Instruction { ASG, NOT, ADD, SUB, MUL, DIV, IDIV, MOD, POW, EQU, NEQU, XOR, BAND, BOR, AND, OR, GRE, LES, EG...
#[allow(unused_imports)] use crate::{eprint, eprintln}; pub enum Instruction { ASG, NOT, ADD, SUB, MUL, DIV, IDIV, MOD, POW, EQU, NEQU, XOR, BAND, BOR, AND, OR, GRE, LES, EG...
Self::UPLV => Self::UPLV, Self::DROPLV => Self::DROPLV, } } } impl Copy for Instruction {}
BAND), Self::BOR => matches!(other, Self::BOR), Self::AND => matches!(other, Self::AND), Self::OR => matches!(other, Self::OR), Self::GRE => matches!(other, Self::GRE), Self::LES => matches!(other, Self::LES), Self::EGRE => matches!(other, Self::EG...
random
[ { "content": "pub fn usize_to_string(mut num: usize) -> String {\n\n let mut string = String::new();\n\n let mut vec_pow: Vec<u128> = Vec::new();\n\n\n\n let init = 55296 - MINUS as u128;\n\n vec_pow.push(1);\n\n\n\n let mut i = 1;\n\n\n\n let mut first = true;\n\n\n\n while num as u128 >= ...
Rust
day21/rust/dfriedenberger/src/parser.rs
razziel89/aoc-2021
0042891cfcecdc2b65ee32882bd04de80ecd7e1c
use crate::fields::Universe; pub fn play(pos1 :&mut u32,pos2 :&mut u32) -> u32 { let mut score1 = 0; let mut score2 = 0; let mut dice = 1; let mut rolled = 0; loop { let m1 = dice + (dice + 1) + (dice + 2); dice = (dice + 3 -1) % 100 + 1; rolled += 3; *...
use crate::fields::Universe; pub fn play(pos1 :&mut u32,pos2 :&mut u32) -> u32 { let mut score1 = 0; let mut score2 = 0; let mut dice = 1; let mut rolled = 0; loop { let m1 = dice + (dice + 1) + (dice + 2); dice = (dice + 3 -1) % 100 + 1; rolled += 3; *...
3 -> 1 4 -> 3 5 -> 6 6 -> 7 7 -> 6 8 -> 3 9 -> 1 */ for (m,copies) in vec![(3,1),(4,3),(5,6),(6,7),(7,6),(8,3),(9,1)] { let u = universe.roll_p1(m,copies); ...
function_block-function_prefixed
[ { "content": "//tag::incr_and_count[]\n\npub fn incr_and_count(data: &mut Vec<u64>,days: u32) -> u64 {\n\n\n\n for _d in 0..days {\n\n let n = data.remove(0);\n\n data.push(0);\n\n data[6] += n;\n\n data[8] += n;\n\n }\n\n let mut sum = 0;\n\n for n in data {\n\n s...
Rust
src/app/components/headerbar/component.rs
gostsdmitry/spot
1d237815f7941cad52cd83df660c0725b56e025a
use std::rc::Rc; use glib::Cast; use gtk::prelude::*; use crate::app::{ components::{Component, EventListener, ListenerComponent}, state::{SelectionContext, SelectionEvent}, ActionDispatcher, AppAction, AppEvent, AppModel, BrowserAction, BrowserEvent, }; use super::widget::HeaderBarWidget; pub trait Scr...
use std::rc::Rc; use glib::Cast; use gtk::prelude::*; use crate::app::{ components::{Component, EventListener, ListenerComponent}, state::{SelectionContext, SelectionEvent}, ActionDispatcher, AppAction, AppEvent, AppModel, BrowserAction, BrowserEvent, }; use super::widget::HeaderBarWidget; pub trait Scr...
} impl<Model> Component for StandardScreen<Model> where Model: ScreenModel + 'static, { fn get_root_widget(&self) -> &gtk::Widget { &self.root } fn get_children(&mut self) -> Option<&mut Vec<Box<dyn EventListener>>> { Some(&mut self.children) } } impl<Model> EventListener for Sta...
let root = gtk::BoxBuilder::new() .orientation(gtk::Orientation::Vertical) .build(); root.append(&widget); root.append(wrapped.get_root_widget()); Self { root: root.upcast(), widget, model, children: vec![Box::new(wrapped)]...
function_block-function_prefix_line
[ { "content": "pub trait ActionDispatcher {\n\n fn dispatch(&self, action: AppAction);\n\n fn dispatch_local_async(&self, action: LocalBoxFuture<'static, Option<AppAction>>);\n\n fn dispatch_async(&self, action: BoxFuture<'static, Option<AppAction>>);\n\n fn dispatch_many_async(&self, actions: BoxFut...
Rust
libsplinter/src/transport/mod.rs
ltseeley/splinter
b4ba4f450a4d59f8e448efcacee89fd0a26cdc31
pub mod inproc; pub mod multi; pub mod raw; mod rw; pub mod tls; #[cfg(feature = "zmq-transport")] pub mod zmq; use mio::Evented; use std::error::Error; use std::io; pub enum Status { Connected, Disconnected, } pub trait Connection: Send { fn send(&mut self, message: &[u8]) -> Result<(), SendErro...
pub mod inproc; pub mod multi; pub mod raw; mod rw; pub mod tls; #[cfg(feature = "zmq-transport")] pub mod zmq; use mio::Evented; use std::error::Error; use std::io; pub enum Status { Connected, Disconnected, } pub trait Connection: Send { fn send(&mut self, message: &[u8]) -> Result<(), SendErro...
fn assert_ready(events: &Events, token: Token, readiness: Ready) { assert_eq!( Some(readiness), events .iter() .filter(|event| event.token() == token) .map(|event| event.readiness()) .next(), ); } pub ...
assert_eq!(vec![3, 4, 5], assert_ok(block!(client.recv(), RecvError))); }); let mut server = assert_ok(listener.incoming().next().unwrap()); assert_eq!(vec![0, 1, 2], assert_ok(block!(server.recv(), RecvError))); assert_ok(block!(server.send(&[3, 4, 5]), SendError)); handle.j...
function_block-function_prefix_line
[ { "content": "pub fn write<T: Write>(writer: &mut T, buffer: &[u8]) -> Result<(), SendError> {\n\n let mut packed = &pack(buffer)?[..];\n\n while !packed.is_empty() {\n\n match writer.write(packed) {\n\n Ok(0) => {\n\n return Err(SendError::IoError(std::io::Error::new(\n\n...
Rust
src/compiler/parser.rs
emoon/liquid-rust
2fac0216867bc3de40fd673aeecd4b13533eab96
use std::collections::HashSet; use std::iter::FromIterator; use std::slice::Iter; use super::{Error, Result}; use super::Element; use super::LiquidOptions; use super::ParseBlock; use super::ParseTag; use super::Token; use interpreter::Renderable; use interpreter::Text; use interpreter::Variable; use interpreter::{F...
use std::collections::HashSet; use std::iter::FromIterator; use std::slice::Iter; use super::{Error, Result}; use super::Element; use super::LiquidOptions; use super::ParseBlock; use super::ParseTag; use super::Token; use interpreter::Renderable; use interpreter::Text; use interpreter::Variable; use interpreter::{F...
#[test] fn honours_nesting() { let tokens = tokenize(concat!( "{% for x in (1..10) %}", "{% if x == 2 %}", "{% for y (2..10) %}{{y}}{% else %} zz {% endfor %}", "{% else %}", "c", "{% endif %}", "{% e...
let tokens = tokenize( "{% comment %}A{%endcomment%} bunch of {{text}} with {{no}} \ else tag", ).unwrap(); let options = options(); let (_, trailing) = split_block(&tokens[..], &["else"], &options); assert!(trailing.is_none()); }
function_block-function_prefix_line
[ { "content": "pub fn unexpected_value_error_string(expected: &str, actual: Option<String>) -> Error {\n\n let actual = actual.unwrap_or_else(|| \"nothing\".to_owned());\n\n Error::with_msg(format!(\"Expected {}, found `{}`\", expected, actual))\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub enum Interrupt {\n...
Rust
src/errors.rs
t-matsudate/sheave
2b3c59ab5a4fd31a7194260a4930bdde9ded55e9
use std::{ error::{ Error }, fmt::{ Display, Formatter, Result as FormatResult } }; #[derive(Debug)] pub struct ChunkLengthError { description: String, source: Option<&'static dyn Error> } impl ChunkLengthError { ...
use std::{ error::{ Error }, fmt::{ Display, Formatter, Result as FormatResult } }; #[derive(Debug)] pub struct ChunkLengthError { description: String, source: Option<&'static dyn Error> } impl ChunkLengthError { ...
SignatureDoesNotMatchError {}
Option<&'static dyn Error> } impl DigestVerificationError { pub fn new(description: String, source: Option<&'static dyn Error>) -> Self { DigestVerificationError { description, source } } } impl Display for DigestVerificationError { ...
random
[ { "content": "/// Reads a chunk from streams.\n\n///\n\n/// # Errors\n\n///\n\n/// This will be occured several errors in decoding.\n\n/// For examples:\n\n///\n\n/// * When streams didn't have enough data.\n\n/// * When data format is invalid.\n\n/// * When something value in data differed from what's expected...
Rust
crates/cli-support/src/js/js2rust.rs
spastorino/wasm-bindgen
a02f9e0eed3052bef6ad9847a09ae69b877c5bf3
use failure::Error; use super::{indent, Context}; use descriptor::{Descriptor, Function}; pub struct Js2Rust<'a, 'b: 'a> { cx: &'a mut Context<'b>, rust_arguments: Vec<String>, pub js_arguments: Vec<(String, String)>, prelude: String, finally: String, ...
use failure::Error; use super::{indent, Context}; use descriptor::{Descriptor, Function}; pub struct Js2Rust<'a, 'b: 'a> { cx: &'a mut Context<'b>, rust_arguments: Vec<String>, pub js_arguments: Vec<(String, String)>, prelude: String, finally: String, ...
pub fn finish(&self, prefix: &str, invoc: &str) -> (String, String) { let js_args = self.js_arguments .iter() .map(|s| &s.0[..]) .collect::<Vec<_>>() .join(", "); let mut js = format!("{}({}) {{\n", prefix...
n\ ", f); return Ok(self) } match *ty { Descriptor::Boolean => { self.ret_ty = "boolean".to_string(); self.ret_expr = format!("return (RET) !== 0;"); } Descriptor::Char => { self.ret_ty = "string...
function_block-function_prefixed
[ { "content": "pub fn struct_function_export_name(struct_: &str, f: &str) -> String {\n\n let mut name = struct_\n\n .chars()\n\n .flat_map(|s| s.to_lowercase())\n\n .collect::<String>();\n\n name.push_str(\"_\");\n\n name.push_str(f);\n\n return name\n\n}\n\n\n", "file_path"...
Rust
src/cli/tracing/stepping/rkf.rs
lars-frogner/bifrost-rust
ae1b4e7adde92ec1c611259796ef593243f82a8d
use crate::{ cli::utils, tracing::stepping::rkf::{RKFStepperConfig, RKFStepperType}, update_command_graph, }; use clap::{Arg, ArgMatches, Command}; pub fn create_rkf_stepper_subcommand(_parent_command_name: &'static str) -> Command<'static> { let command_name = "rkf_stepper"; update_command_grap...
use crate::{ cli::utils, tracing::stepping::rkf::{RKFStepperConfig, RKFStepperType}, update_command_graph, }; use clap::{Arg, ArgMatches, Command}; pub fn create_rkf_stepper_subcommand(_parent_command_name: &'static str) -> Command<'static> { let command_name = "rkf_stepper"; update_command_grap...
pub fn construct_rkf_stepper_config_from_options( arguments: &ArgMatches, ) -> (RKFStepperType, RKFStepperConfig) { let dense_step_length = utils::get_value_from_required_parseable_argument(arguments, "dense-step-length"); let max_step_attempts = utils::get_value_from_required_parseable_ar...
alue("0.01"), ) .arg( Arg::new("max-step-attempts") .long("max-step-attempts") .require_equals(true) .value_name("NUMBER") .help("Maximum number of step attempts before terminating") .takes_value(true) ...
function_block-function_prefixed
[ { "content": "#[allow(clippy::let_and_return)]\n\npub fn create_snapshot_subcommand(_parent_command_name: &'static str) -> Command<'static> {\n\n let command_name = \"snapshot\";\n\n\n\n update_command_graph!(_parent_command_name, command_name);\n\n\n\n let command = Command::new(command_name)\n\n ...
Rust
src/kernel/src/arch/amd64/ioapic.rs
ariadiamond/twizzler-Rust
5f5d01bac9127ca1d64bb8aa472a04f6634fc3a9
use acpi::{madt::Madt, sdt::Signature, InterruptModel}; use alloc::vec::Vec; use x86_64::PhysAddr; use crate::{ interrupt::{Destination, PinPolarity, TriggerMode}, spinlock::Spinlock, }; use super::{acpi::get_acpi_root, memory::phys_to_virt, processor::get_bsp_id}; struct IOApic { address: PhysAddr, ...
use acpi::{madt::Madt, sdt::Signature, InterruptModel}; use alloc::vec::Vec; use x86_64::PhysAddr; use crate::{ interrupt::{Destination, PinPolarity, TriggerMode}, spinlock::Spinlock, }; use super::{acpi::get_acpi_root, memory::phys_to_virt, processor::get_bsp_id}; struct IOApic { address: PhysAddr, ...
pub(super) fn set_interrupt( gsi: u32, vector: u32, masked: bool, trigger: TriggerMode, polarity: PinPolarity, destination: Destination, ) { let ioapics = IOAPICS.lock(); for ioapic in &*ioapics { if let Some(reg) = ioapic.gsi_to_reg(gsi) { unsafe { ...
polarity: PinPolarity, destination: Destination, ) -> u64 { let vector = vector as u64; let delmod = match destination { Destination::LowestPriority => 1, _ => 0, } << 8; let intpol = match polarity { PinPolarity::ActiveHigh => 0, PinPolarity::ActiveLow => 1, } <<...
function_block-function_prefix_line
[]
Rust
wfts-lang/src/proto_divine/components.rs
brunoczim/theworldfromthestars
6e79162521fd9e7e52ed993860e8a291765613b0
use crate::{ fmt::{NarrowPronunc, WriteBroadPronunc, WriteOrthography}, phonetics::Variation, proto_divine::{ grammar::grammemes::{ AdverbCase, Aspect, Case, Gender, Mood, Number, Person, Tense, ...
use crate::{ fmt::{NarrowPronunc, WriteBroadPronunc, WriteOrthography}, phonetics::Variation, proto_divine::{ grammar::grammemes::{ AdverbCase, Aspect, Case, Gender, Mood, Number, Person, Tense, ...
s u32, data: aspect.to_string().capitalize().blocking().to_dyn(), }) } table.push(row); row = Vec::new(); for _ in 0 .. Aspect::ALL.len() { for &person in Person::ALL { row.push(table::Entry { header: true, rowspan: 1, ...
_html(&self, fmt: &mut fmt::Formatter, ctx: Context) -> fmt::Result { write!( fmt, "<div class=\"definition-head\">*{}", ctx.renderer(Bold(self.word.orthography_ref())), )?; if let Some((first, rest)) = self.inflected_for.split_first() { write!(fm...
random
[]
Rust
src/parser/mod.rs
appsignal/statsd_parser
4ab5574fc409b4727c5c019aef0d75253005477d
use std::{error,fmt}; use std::num::ParseFloatError; use std::vec::Vec; use std::collections::BTreeMap; pub mod metric_parser; pub mod service_check_parser; #[derive(Debug,PartialEq)] pub enum ParseError { EmptyInput, IncompleteInput, NoName, ValueNotFloat, SampleRateNotFl...
use std::{error,fmt}; use std::num::ParseFloatError; use std::vec::Vec; use std::collections::BTreeMap; pub mod metric_parser; pub mod service_check_parser; #[derive(Debug,PartialEq)] pub enum ParseError { EmptyInput, IncompleteInput, NoName, ValueNotFloat, SampleRateNotFl...
#[test] fn test_peek() { let mut parser = Parser::new("this is a string".to_string()); parser.pos = 10; assert_eq!(parser.peek(), Some('s')); assert_eq!(parser.pos, 10); parser.pos = 16; assert_eq!(parser.peek(), None); } ...
assert_eq!(parser.take_float_until(vec!['|']), Ok(10.01)); assert_eq!(parser.pos, 6); assert!(parser.take_float_until(vec!['|']).is_err()); assert_eq!(parser.pos, 13); }
function_block-function_prefix_line
[ { "content": "pub fn parse(input: String) -> Result<Message, ParseError> {\n\n Parser::new(input).parse()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::collections::BTreeMap;\n\n\n\n use super::parse;\n\n use {Message, Metric, Timing};\n\n\n\n #[test]\n\n fn test_parse_with_tags() {\n\n...
Rust
build.rs
ICGog/erdos
5152b7a5c66aed54304ebc394897920d6ba47876
use std::{ env, fs::File, path::Path, process::{Command, Stdio}, sync::Mutex, }; use slog::{Drain, Logger}; static DEFAULT_BUNDLE_MAX_READ_STREAMS: usize = 20; static DEAFUALT_BUNDLE_MAX_WRITE_STREAMS: usize = 10; fn parse_env_variable<T: std::str::FromStr + std::fmt::Display>( key: &str, ...
use std::{ env, fs::File, path::Path, process::{Command, Stdio}, sync::Mutex, }; use slog::{Drain, Logger}; static DEFAULT_BUNDLE_MAX_READ_STREAMS: usize = 20; static DEAFUALT_BUNDLE_MAX_WRITE_STREAMS: usize = 10; fn parse_env_variable<T: std::str::FromStr + std::fmt::Display>( key: &str, ...
fn main() -> Result<(), String> { let logger = Logger::root(Mutex::new(slog_term::term_full()).fuse(), slog::o!()); let bundle_max_read_streams: usize = parse_env_variable( "ERDOS_BUNDLE_MAX_READ_STREAMS", DEFAULT_BUNDLE_MAX_READ_STREAMS, &logger, ); let bundle_max_write_streams:...
function_block-full_function
[ { "content": "/// Adds an alias from from_id to to_id on the default graph.\n\npub fn add_stream_alias(from_id: StreamId, to_id: StreamId) -> Result<(), String> {\n\n DEFAULT_GRAPH.with(|g| g.borrow_mut().add_stream_alias(from_id, to_id))\n\n}\n\n\n", "file_path": "src/dataflow/graph/default_graph.rs", ...
Rust
src/kani-compiler/src/codegen_cprover_gotoc/compiler_interface.rs
ronakfof/kani
3ca43584a5ed138f6c0029002d482a7842ee93da
use crate::codegen_cprover_gotoc::GotocCtx; use bitflags::_core::any::Any; use cbmc::goto_program::symtab_transformer; use cbmc::InternedString; use kani_metadata::KaniMetadata; use kani_queries::{QueryDb, UserInput}; use rustc_codegen_ssa::traits::CodegenBackend; use rustc_codegen_ssa::{CodegenResults, CrateInfo}; u...
use crate::codegen_cprover_gotoc::GotocCtx; use bitflags::_core::any::Any; use cbmc::goto_program::symtab_transformer; use cbmc::InternedString; use kani_metadata::KaniMetadata; use kani_queries::{QueryDb, UserInput}; use rustc_codegen_ssa::traits::CodegenBackend; use rustc_codegen_ssa::{CodegenResults, CrateInfo}; u...
let work_products = FxHashMap::<WorkProductId, WorkProduct>::default(); Box::new(( CodegenResults { modules: vec![], allocator_module: None, metadata_module: None, metadata: rustc_metadata, crate_info: CrateInf...
if !tcx.sess.opts.debugging_opts.no_codegen && tcx.sess.opts.output_types.should_codegen() { let outputs = tcx.output_filenames(()); let base_filename = outputs.output_path(OutputType::Object); write_file(&base_filename, "symtab.json", &symtab); write_file(&base_filename,...
if_condition
[ { "content": "fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {\n\n let self_type_opt = match *item.kind {\n\n clean::MethodItem(ref method, _) => method.decl.self_type(),\n\n clean::TyMethodItem(ref method) => method.decl.self_type(),\n\n _ => None,\...
Rust
src/r3_test_suite/src/kernel_tests/timer_misc.rs
newAM/r3
dfc1b8abd63c7fdefc7f162bc29bbb0ba7b0192f
use core::num::NonZeroUsize; #[cfg(feature = "system_time")] use r3::time::Time; use r3::{ hunk::Hunk, kernel::{self, cfg::CfgBuilder, Task, Timer}, prelude::*, time::Duration, }; use wyhash::WyHash; use super::Driver; use crate::utils::SeqTracker; pub struct App<System> { timer1: Timer<System>, ...
use core::num::NonZeroUsize; #[cfg(feature = "system_time")] use r3::time::Time; use r3::{ hunk::Hunk, kernel::{self, cfg::CfgBuilder, Task, Timer}, prelude::*, time::Duration, }; use wyhash::WyHash; use super::Driver; use crate::utils::SeqTracker; pub struct App<System> { timer1: Timer<System>, ...
let task = Task::build() .active(true) .start(task_body::<System, D>) .priority(1) .finish(b); let seq = Hunk::<_, SeqTracker>::build().finish(b); App { timer1, timer2, timer3, timer4, ...
let timer4 = Timer::build() .delay(Duration::from_millis(0)) .period(Duration::from_millis(0)) .start(unreachable_timer_body::<System, D>) .finish(b);
assignment_statement
[ { "content": "/// The core portion of [`Timer::start`].\n\nfn start_timer<System: Kernel>(\n\n mut lock: CpuLockGuardBorrowMut<'_, System>,\n\n timer_cb: &'static TimerCb<System>,\n\n) {\n\n if timer_cb.active.get(&*lock) {\n\n return;\n\n }\n\n\n\n // Get the current delay value\n\n le...
Rust
src/sinks/datadog/logs/service.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::{ sync::Arc, task::{Context, Poll}, }; use bytes::Bytes; use futures::future::BoxFuture; use http::{ header::{CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE}, Request, StatusCode, Uri, }; use hyper::Body; use snafu::Snafu; use tower::Service; use tracing::Instrument; use vector_common::interna...
use std::{ sync::Arc, task::{Context, Poll}, }; use bytes::Bytes; use futures::future::BoxFuture; use http::{ header::{CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE}, Request, StatusCode, Uri, }; use hyper::Body; use snafu::Snafu; use tower::Service; use tracing::Instrument; use vector_common::interna...
} impl Service<LogApiRequest> for LogApiService { type Response = LogApiResponse; type Error = LogApiError; type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>; fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn c...
i, enterprise: bool) -> Self { Self { client, uri, enterprise, } }
function_block-function_prefixed
[ { "content": "/// Simplify the URI into a protocol and endpoint by removing the\n\n/// \"query\" portion of the `path_and_query`.\n\npub fn protocol_endpoint(uri: Uri) -> (String, String) {\n\n let mut parts = uri.into_parts();\n\n\n\n // Drop any username and password\n\n parts.authority = parts.autho...
Rust
crates/notation_bevy/src/rhythm/rhythm_bar.rs
theAdamColton/notation
270e8592127c8e60ff33b12b040ab55dba5c92a3
use std::fmt::Display; use std::sync::Arc; use bevy::prelude::*; use notation_bevy_utils::prelude::{BevyUtil, ShapeOp, OutlineCircle}; use notation_model::prelude::{Chord, Signature, Tab}; use crate::prelude::{BarData, NotationAssets, NotationTheme, TabState}; use super::rhythm_beat::{RhythmBeatData}; use super::rh...
use std::fmt::Display; use std::sync::Arc; use bevy::prelude::*; use notation_bevy_utils::prelude::{BevyUtil, ShapeOp, OutlineCircle}; use notation_model::prelude::{Chord, Signature, Tab}; use crate::prelude::{BarData, NotationAssets, NotationTheme, TabState}; use super::rhythm_beat::{RhythmBeatData}; use super::rh...
} impl RhythmBarData { pub fn update_size( &mut self, commands: &mut Commands, theme: &NotationTheme, beat_query: &mut Query<(Entity, &mut RhythmBeatData)>, indicator_query: &mut Query<(Entity, &mut RhythmIndicatorData)>, entity: Entity, children: &Children,...
elf.value.radius + outline_width; OutlineCircle { radius, color, outline_width, outline_color, offset, } }
function_block-function_prefixed
[ { "content": "pub fn hex_linear(hex: &str) -> Color {\n\n let color = Color::hex(hex).unwrap();\n\n color.as_rgba_linear()\n\n}\n\n\n\n#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug, Default)]\n\n#[cfg_attr(feature = \"inspector\", derive(Inspectable))]\n\npub struct ThemeColors {\n\n p...
Rust
cli/lockfile.rs
DaveyJohnson/deno
a214813d72f044c56fbe02461c9f045a334b8a3a
use deno_core::serde_json; use deno_core::serde_json::json; use std::collections::BTreeMap; use std::io::Result; use std::path::PathBuf; #[derive(Debug, Clone)] pub struct Lockfile { write: bool, map: BTreeMap<String, String>, pub filename: PathBuf, } impl Lockfile { pub fn new(filename: PathBuf, write: boo...
use deno_core::serde_json; use deno_core::serde_json::json; use std::collections::BTreeMap; use std::io::Result; use std::path::PathBuf; #[derive(Debug, Clone)] pub struct Lockfile { write: bool, map: BTreeMap<String, String>, pub filename: PathBuf, } impl Lockfile { pub fn new(filename: PathBuf, write: boo...
fn insert(&mut self, specifier: &str, code: &str) { if specifier.starts_with("file:") { return; } let checksum = crate::checksum::gen(&[code.as_bytes()]); self.map.insert(specifier.to_string(), checksum); } } #[cfg(test)] mod tests { use super::*; use deno_core::serde_json; use deno_c...
fn check(&mut self, specifier: &str, code: &str) -> bool { if specifier.starts_with("file:") { return true; } if let Some(lockfile_checksum) = self.map.get(specifier) { let compiled_checksum = crate::checksum::gen(&[code.as_bytes()]); lockfile_checksum == &compiled_checksum } else { ...
function_block-full_function
[ { "content": "/// Format stdin and write result to stdout.\n\n/// Treats input as TypeScript or as set by `--ext` flag.\n\n/// Compatible with `--check` flag.\n\npub fn format_stdin(check: bool, ext: String) -> Result<(), AnyError> {\n\n let mut source = String::new();\n\n if stdin().read_to_string(&mut sourc...
Rust
src/lib.rs
travisdoesmath/double-pendulum
4610fec75e0396c1ffeb57ad000091b28be8d8d8
mod utils; extern crate nalgebra as na; extern crate wasm_bindgen_futures; use na::{DVector, DMatrix}; use std::cmp::max; use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; const G : f64 = -9.8; #[allow(non_snake_case)] fn...
mod utils; extern crate nalgebra as na; extern crate wasm_bindgen_futures; use na::{DVector, DMatrix}; use std::cmp::max; use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; const G : f64 = -9.8; #[allow(non_snake_case)] fn...
et thetas = DVector::from_vec(vec![theta; n]); let omegas = DVector::from_vec(vec![0.; n]); let p = Pendulum { thetas, omegas }; pendula.push(p); } let coords = vec![0.; 2*total_n]; Pendula { pendula: pendula, coords: coords ...
_coords; pendula.coords.as_ptr() } #[wasm_bindgen] struct Pendulum { thetas: DVector<f64>, omegas: DVector<f64>, } #[wasm_bindgen] pub struct Pendula { pendula: Vec<Pendulum>, coords: Vec<f64>, } #[wasm_bindgen] impl Pendula { ...
random
[ { "content": "const pendula = new Pendula(ns, thetas);\n", "file_path": "www/index.js", "rank": 5, "score": 50666.13832610425 }, { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at le...
Rust
snake/src/lib.rs
HuguesGuilleus/snake-rs
672d410930cfbae6e61ebf4337484fcb0d84da3c
mod candy; mod text_view; mod wall; use crate::candy::Candy; pub use crate::text_view::TextView; use crate::wall::Wall; pub trait View { fn clear(&mut self); fn wall(&mut self, x: usize, y: usize); fn candy(&mut self, x: usize, y: usize); fn snake(&mut self, x: usize, y: usize); ...
mod candy; mod text_view; mod wall; use crate::candy::Candy; pub use crate::text_view::TextView; use crate::wall::Wall; pub trait View { fn clear(&mut self); fn wall(&mut self, x: usize, y: usize); fn candy(&mut self, x: usize, y: usize); fn snake(&mut self, x: usize, y: usize); ...
struct Snake<'a> { body: Vec<(usize, usize)>, direction: Direction, board: &'a Board, } impl<'a> Snake<'a> { const INIT_SIZE: usize = 3; fn new(board: &'a Board) -> Self { Self { body: (0..Snake::INIT_SIZE).map(|x| (x + 3, 2)).collect(), direction: Direction::Righ...
t_eq!(false, b.on_wall((0, 0))); assert_eq!(false, b.on_wall((39, 19))); assert_eq!(false, b.on_wall((14, 9))); assert_eq!(false, b.on_wall((16, 11))); assert_eq!(false, b.on_wall((5, 9))); assert_eq!(false, b.on_wall((14, 5))); }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn wall_iter() {\n\n let r = Wall::new(3, 5, 1, 2)\n\n .iter()\n\n .collect::<Vec<(usize, usize)>>();\n\n assert_eq!(vec![(3, 1), (4, 1)], r);\n\n}\n", "file_path": "snake/src/wall.rs", "rank": 1, "score": 79211.80083304472 }, { "content": "fn ran...
Rust
src/token.rs
themifi/relox
b07de63a9c5efeb4bb54a667024239a252409aac
use std::fmt; #[derive(Debug, Copy, Clone, PartialEq)] pub enum TokenType { LeftParen, RightParen, LeftBrace, RightBrace, Comma, Dot, Minus, Plus, Semicolon, Slash, Star, Bang, BangEqual, Equal, EqualEqual, Greater, GreaterEqual, Less, ...
use std::fmt; #[derive(Debug, Copy, Clone, PartialEq)] pub enum TokenType { LeftParen, RightParen, LeftBrace, RightBrace, Comma, Dot, Minus, Plus, Semicolon, Slash, Star, Bang, BangEqual, Equal, EqualEqual, Greater, GreaterEqual, Less, ...
line: 1, } ) ); } }
d => write!(f, "and"), TokenType::Class => write!(f, "class"), TokenType::Else => write!(f, "else"), TokenType::False => write!(f, "false"), TokenType::Fun => write!(f, "fun"), TokenType::For => write!(f, "for"), TokenType::If => write!(f, "if"), ...
random
[ { "content": "fn equality(reader: &mut Reader) -> Result {\n\n let mut expr = comparsion(reader)?;\n\n\n\n while let Some(TokenType::BangEqual) | Some(TokenType::EqualEqual) = reader.peek_type() {\n\n let operator = reader.advance().unwrap();\n\n let right = comparsion(reader)?;\n\n e...
Rust
ton_client/src/abi/encode_account.rs
nerzh/TON-SDK
87ebd48f025d563882638812cfaf2ab7b0286b46
use crate::abi::types::MessageSource; use crate::abi::{Abi, Error}; use crate::boc::internal::{ deserialize_cell_from_base64, deserialize_object_from_base64, serialize_object_to_base64, }; use crate::client::ClientContext; use crate::crypto::internal::decode_public_key; use crate::error::ClientResult; use serde_jso...
use crate::abi::types::MessageSource; use crate::abi::{Abi, Error}; use crate::boc::internal::{ deserialize_cell_from_base64, deserialize_object_from_base64, serialize_object_to_base64, }; use crate::client::ClientContext; use crate::crypto::internal::decode_public_key; use crate::error::ClientResult; use serde_jso...
#[api_function] pub async fn encode_account( context: std::sync::Arc<ClientContext>, params: ParamsOfEncodeAccount, ) -> ClientResult<ResultOfEncodeAccount> { let state_init = match &params.state_init { StateInitSource::Message { source } => state_init_from_message(&context, source).await, ...
x)) .transpose()?; let mut image = ContractImage::from_state_init(&mut tvc.as_slice()) .map_err(|err| Error::invalid_message_for_decode(err))?; if let Some(key) = public_key { image .set_public_key(&key) .map_err(|err| Error::invalid_tvc_image(err))?; } i...
function_block-function_prefixed
[]
Rust
lib/vrl/compiler/src/state.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::collections::{hash_map::Entry, HashMap}; use anymap::AnyMap; use value::{Kind, Value}; use crate::{parser::ast::Ident, type_def::Details}; #[derive(Debug, Default, Clone, PartialEq)] pub struct LocalEnv { pub(crate) bindings: HashMap<Ident, Details>, } impl LocalEnv { pub(crate) fn variable_idents(...
use std::collections::{hash_map::Entry, HashMap}; use anymap::AnyMap; use value::{Kind, Value}; use crate::{parser::ast::Ident, type_def::Details}; #[derive(Debug, Default, Clone, PartialEq)] pub struct LocalEnv { pub(crate) bindings: HashMap<Ident, Details>, } impl LocalEnv { pub(crate) fn variable_idents(...
{ self.variables.insert(ident, value); } pub(crate) fn remove_variable(&mut self, ident: &Ident) { self.variables.remove(ident); } pub(crate) fn swap_variable(&mut self, ident: Ident, value: Value) -> Option<Value> { match self.variables.entry(ident) { Entry::Occup...
ut self) { self.variables.clear(); } pub fn variable(&self, ident: &Ident) -> Option<&Value> { self.variables.get(ident) } pub fn variable_mut(&mut self, ident: &Ident) -> Option<&mut Value> { self.variables.get_mut(ident) } pub(crate) fn insert_variable(&mut self, ide...
random
[ { "content": "#[inline]\n\npub fn skip_serializing_if_default<E: Default + PartialEq>(e: &E) -> bool {\n\n e == &E::default()\n\n}\n\n\n", "file_path": "lib/vector-core/src/serde.rs", "rank": 0, "score": 404284.4595139137 }, { "content": "#[allow(clippy::needless_pass_by_value)] // impl P...
Rust
src/commands/up.rs
fermyon/spin
ec9a74b14d2af7cff860122eba067ecaf44ca0d1
use std::{ ffi::OsString, fmt::Debug, path::{Path, PathBuf}, }; use anyhow::{bail, Context, Result}; use clap::{CommandFactory, Parser}; use spin_loader::bindle::BindleConnectionInfo; use spin_manifest::ApplicationTrigger; use tempfile::TempDir; use crate::opts::*; #[derive(Parser, Debug, Default)] #[cla...
use std::{ ffi::OsString, fmt::Debug, path::{Path, PathBuf}, }; use anyhow::{bail, Context, Result}; use clap::{CommandFactory, Parser}; use spin_loader::bindle::BindleConnectionInfo; use spin_manifest::ApplicationTrigger; use tempfile::TempDir; use crate::opts::*; #[derive(Parser, Debug, Default)] #[cla...
fn bindle_connection(&self) -> Option<BindleConnectionInfo> { self.server .as_ref() .map(|url| BindleConnectionInfo::new(url, false, None, None)) } } enum WorkingDirectory { Given(PathBuf), Temporary(TempDir), } impl WorkingDirectory { fn path(&self) -> &Path { ...
async fn run_inner(self) -> Result<()> { let working_dir_holder = match &self.tmp { None => WorkingDirectory::Temporary(tempfile::tempdir()?), Some(d) => WorkingDirectory::Given(d.to_owned()), }; let working_dir = working_dir_holder.path(); let app = match (&self...
function_block-full_function
[]
Rust
interact/src/reflector.rs
da-x/interact
d3f0ed94d42fcdb9820db39e8eca48f99f49988e
use std::collections::hash_map::Entry; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::channel; use std::sync::{Arc, Mutex}; use std::thread::ThreadId; use crate::access::vec::ReflectVec; use crate::access::{ derive::{ReflectStruct, Struct, StructKind}, iter:...
use std::collections::hash_map::Entry; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::channel; use std::sync::{Arc, Mutex}; use std::thread::ThreadId; use crate::access::vec::ReflectVec; use crate::access::{ derive::{ReflectStruct, Struct, StructKind}, iter:...
pub fn reflect_set( a_self: &Arc<Self>, iter: &mut dyn ReflectIter<&dyn Access>, name: &'static str, ) -> NodeTree { let mut v = vec![]; let meta = try_seen_dyn!(iter, a_self); while let Some(member) = iter.reflect_next() { if a_self.limit <= a_self...
pub fn reflect_map( a_self: &Arc<Self>, iter: &mut dyn ReflectIter<(&dyn Access, &dyn Access)>, name: &'static str, ) -> NodeTree { let meta = try_seen_dyn!(iter, a_self); let mut result = vec![]; let mut items = vec![]; let mut missing_keys = false; ...
function_block-full_function
[ { "content": "fn impls_for_access(input: &DeriveInput, mut mut_assign: bool) -> Tokens {\n\n let name = &input.ident;\n\n let mut skip_bound_set = HashSet::new();\n\n let mut fnmap = BTreeMap::new();\n\n\n\n for attribute in &input.attrs {\n\n get_attr_info(attribute, &mut fnmap, &mut skip_bo...
Rust
src/uucore/entries.rs
LuoZijun/coreutils
9b6f0b02e82b05cbe94d9b4c036e18bdb87b8042
#[cfg(any(target_os = "freebsd", target_os = "macos"))] use libc::time_t; use libc::{c_char, c_int, gid_t, uid_t}; use libc::{getgrgid, getgrnam, getgroups, getpwnam, getpwuid, group, passwd}; use std::ptr; use std::io::ErrorKind; use std::io::Error as IOError; use std::io::Result as IOResult; use std::ffi::{CStr, C...
#[cfg(any(target_os = "freebsd", target_os = "macos"))] use libc::time_t; use libc::{c_char, c_int, gid_t, uid_t}; use libc::{getgrgid, getgrnam, getgroups, getpwnam, getpwuid, group, passwd}; use std::ptr; use std::io::ErrorKind; use std::io::Error as IOError; use std::io::Result as IOResult; use std::ffi::{CStr, C...
} pub struct Passwd { inner: passwd, } macro_rules! cstr2cow { ($v:expr) => ( unsafe { CStr::from_ptr($v).to_string_lossy() } ) } impl Passwd { pub fn name(&self) -> Cow<str> { cstr2cow!(self.inner.pw_name) } pub fn uid(&self) -> uid_t { self.inner.pw_uid ...
if ngroups == -1 { Err(IOError::last_os_error()) } else { unsafe { groups.set_len(ngroups as usize); } Ok(groups) }
if_condition
[ { "content": "pub fn read_size(child: &mut Child, size: usize) -> String {\n\n let mut output = Vec::new();\n\n output.resize(size, 0);\n\n sleep(Duration::from_secs(1));\n\n child\n\n .stdout\n\n .as_mut()\n\n .unwrap()\n\n .read(output.as_mut_slice())\n\n .unwrap...
Rust
core/src/workflow/history_update.rs
mmcshane/sdk-core
dcae3d6fd66fb22f727ffa14da100f0c08b6a2c8
use crate::{ replay::{HistoryInfo, TestHistoryBuilder}, worker::client::WorkerClientBag, }; use futures::{future::BoxFuture, stream, stream::BoxStream, FutureExt, Stream, StreamExt}; use std::{ collections::VecDeque, future::Future, pin::Pin, sync::Arc, task::{Context, Poll}, }; use temporal...
use crate::{ replay::{HistoryInfo, TestHistoryBuilder}, worker::client::WorkerClientBag, }; use futures::{future::BoxFuture, stream, stream::BoxStream, FutureExt, Stream, StreamExt}; use std::{ collections::VecDeque, future::Future, pin::Pin, sync::Arc, task::{Context, Poll}, }; use temporal...
#[tokio::test] async fn paginator_fetches_new_pages() { let wft_count = 500; let long_hist = canned_histories::long_sequential_timers(wft_count); let initial_hist = long_hist.get_history_info(10).unwrap(); let prev_started = initial_hist.previous_started_event...
anned_histories::single_timer("t"); let mut update = timer_hist.as_history_update(); let seq_2 = update.take_next_wft_sequence(3).await.unwrap(); assert_eq!(seq_2.len(), 5); assert_eq!(seq_2.last().unwrap().event_id, 8); }
function_block-function_prefixed
[]
Rust
src/simulation.rs
ragreener1/Motivate-Project
7186cb24f59ac464aa7fcfd71cb3ce9ac2706ce9
extern crate rand; use std; use std::collections::HashMap; use std::io::Write; use std::io::BufWriter; use itertools::Itertools; use std::time::SystemTime; use std::fs; use std::io; use rand::thread_rng; use rand::seq::sample_slice_ref; use std::rc::Rc; use std::cell::RefCell; use std::fs::File; use weather::Weather; ...
extern crate rand; use std; use std::collections::HashMap; use std::io::Write; use std::io::BufWriter; use itertools::Itertools; use std::time::SystemTime; use std::fs; use std::io; use rand::thread_rng; use rand::seq::sample_slice_ref; use std::rc::Rc; use std::cell::RefCell; use std::fs::File; use weather::Weather; ...
fn link_agents_from_predefined_network( agents: &[Rc<RefCell<Agent>>], network: HashMap<u32, Vec<u32>>, f: fn(agent: &mut Agent, friends: &mut Vec<Rc<RefCell<Agent>>>)) { network .iter() .for_each(|(&k, v)| { let mut friends: Vec<Rc<RefCell<Agent>>> = v ...
let active_mode = statistics::count_active_mode(agents); let active_mode_by_commute_length = statistics::count_active_mode_by_commute_length(agents); let local_commute = active_mode_by_commute_length.get(&JourneyType::LocalCommute).unwrap(); let city_commute = active_mode_by_commute_length.get(&JourneyType:...
function_block-function_prefix_line
[ { "content": "/// Read a social network from a file\n\n/// * file: An input file in YAML mapping ids to a list of ids\n\n/// * Returns: A HashMap mapping ids, to the ids of their friends\n\npub fn read_network(mut file: File) -> HashMap<u32, Vec<u32>> {\n\n info!(\"READING NETWORK\");\n\n\n\n // Create a ...
Rust
rfid_reader/src/rusb/utils.rs
rusty-octopus/rfid_media_player
af9b899186e96496dd44afdcfcb981a8e021ee5f
#![warn(missing_docs)] #![warn(missing_doc_code_examples)] #![forbid(unsafe_code)] use crate::error::Error; use crate::id::{ProductId, VendorId}; use rusb::{Device, DeviceDescriptor, Direction, TransferType, UsbContext}; #[derive(Debug, PartialEq)] pub(crate) struct EndPoint { config: u8, interface: u8, s...
#![warn(missing_docs)] #![warn(missing_doc_code_examples)] #![forbid(unsafe_code)] use crate::error::Error; use crate::id::{ProductId, VendorId}; use rusb::{Device, DeviceDescriptor, Direction, TransferType, UsbContext}; #[derive(Debug, PartialEq)] pub(crate) struct EndPoint { config: u8, interface: u8, s...
} } #[cfg(test)] #[cfg(not(tarpaulin_include))] mod tests { use super::*; #[test] fn test_get_device_not_found() { let context = rusb::Context::new().unwrap(); let device = get_device(&context, VendorId::from(0), ProductId::from(0)); assert!(device.is_err()); } #[test]...
match error { rusb::Error::Timeout => Error::Timeout, rusb::Error::Access => Error::Access, _ => Error::OtherUsbError(error.to_string()), }
if_condition
[]
Rust
sqlx-macros/src/query/data.rs
JCapucho/sqlx
a31bd17f360c173c7814ae0e071ea10ce52e7a84
use sqlx_core::database::Database; use sqlx_core::describe::Describe; use sqlx_core::executor::Executor; #[cfg_attr(feature = "offline", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr( feature = "offline", serde(bound( serialize = "Describe<DB>: serde::Serialize", deserialize = "Desc...
use sqlx_core::database::Database; use sqlx_core::describe::Describe; use sqlx_core::executor::Executor; #[cfg_attr(feature = "offline", derive(serde::Deserialize, serde::Serialize))] #[cfg_attr( feature = "offline", serde(bound( serialize = "Describe<DB>: serde::Serialize", deserialize = "Desc...
struct DataFileVisitor<'a> { query: &'a str, hash: String, } impl<'de> Visitor<'de> for DataFileVisitor<'_> { type Value = DynQueryData; fn expecting(&self, f: &mut Formatter) -> fmt::Result { write!(f, "expected map key {:?} or \"db\"", self.hash) ...
tr) -> String { use sha2::{Digest, Sha256}; hex::encode(Sha256::digest(query.as_bytes())) }
function_block-function_prefixed
[ { "content": "/// Make a SQL query.\n\npub fn query<DB>(sql: &str) -> Query<'_, DB, <DB as HasArguments<'_>>::Arguments>\n\nwhere\n\n DB: Database,\n\n{\n\n Query {\n\n database: PhantomData,\n\n arguments: Some(Default::default()),\n\n statement: Either::Left(sql),\n\n persist...
Rust
rs/crypto/internal/crypto_service_provider/src/tls_stub/mod.rs
ggreif/ic
ac56ec91f077c00d59eea3f73f51e14a1b3ea882
use crate::api::tls_errors::{ CspMalformedPeerCertificateError, CspTlsClientHandshakeError, CspTlsServerHandshakeError, }; use crate::keygen::tls_cert_hash_as_key_id; use crate::secret_key_store::SecretKeyStore; use crate::tls_stub::cert_chain::CspCertificateChainCreationError; use crate::types::CspSecretKey; use...
use crate::api::tls_errors::{ CspMalformedPeerCertificateError, CspTlsClientHandshakeError, CspTlsServerHandshakeError, }; use crate::keygen::tls_cert_hash_as_key_id; use crate::secret_key_store::SecretKeyStore; use crate::tls_stub::cert_chain::CspCertificateChainCreationError; use crate::types::CspSecretKey; use...
; } Ok(()) } #[derive(Debug)] enum CspPeerCertChainFromStreamError { UnverifiedCertChain, EmptyCertChain, CertChainLeafInconsistency(String), PeerCertificateNotVerified, PeerCertificateMalformed(String), } impl From<CspPeerCertFromStreamError> for CspPeerCertChainFromStreamError { fn f...
Err(CspPeerCertChainFromStreamError::CertChainLeafInconsistency( "leaf of peer certificate chain is inconsistent with peer certificate".to_string(), ))
call_expression
[ { "content": "/// Processes a command from the command line.\n\npub fn main(args: &[String]) -> Result<(), (String, i32)> {\n\n match args {\n\n [] => Err((help_str(), 1)),\n\n _ => {\n\n let command = Command::from_str(&args[0]).map_err(|_| {\n\n (\n\n ...
Rust
src/input.rs
courajs/termion
e522a7a25a9095de6638f31a99c8ce3a14fc98c4
use std::io::{self, Read, Write}; use std::ops; use event::{self, Event, Key}; use raw::IntoRawMode; pub struct Keys<R> { iter: Events<R>, } impl<R: Read> Iterator for Keys<R> { type Item = Result<Key, io::Error>; fn next(&mut self) -> Option<Result<Key, io::Error>> { loop { match ...
use std::io::{self, Read, Write}; use std::ops; use event::{self, Event, Key}; use raw::IntoRawMode; pub struct Keys<R> { iter: Events<R>, } impl<R: Read> Iterator for Keys<R> { type Item = Result<Key, io::Error>; fn next(&mut self) -> Option<Result<Key, io::Error>> { loop { match ...
rKind::InvalidData, e))?; Ok(Some(string)) } } pub trait TermReadEventsAndRaw { fn events_and_raw(self) -> EventsAndRaw<Self> where Self: Sized; } impl<R: Read> TermReadEventsAndRaw for R { fn events_and_raw(self) -> EventsAndRaw<Self> { EventsAndRaw { source: self, ...
event(c, &mut source.bytes()), } } Ok(2) => { let option_iter = &mut Some(buf[1]).into_iter(); let result = { let mut iter = option_iter.map(|c| Ok(c)).chain(source.bytes()); parse_event(buf[0], &mut iter) ...
random
[ { "content": "/// Parse an Event from `item` and possibly subsequent bytes through `iter`.\n\npub fn parse_event<I>(item: u8, iter: &mut I) -> Result<Event, Error>\n\n where I: Iterator<Item = Result<u8, Error>>\n\n{\n\n let error = Error::new(ErrorKind::Other, \"Could not parse an event\");\n\n match ...
Rust
src/syscall.rs
matix522/uranos
269470339398104c5b4963bf801c511c4ed2bf95
pub use num_traits::FromPrimitive; pub mod files; pub mod print; pub mod asynchronous; use crate::utils::circullar_buffer::*; use crate::utils::ONLY_MSB_OF_USIZE; use core::convert::TryFrom; #[repr(usize)] #[derive(FromPrimitive, ToPrimitive, Debug)] pub enum Syscalls { StartScheduling, Print, Yield, ...
pub use num_traits::FromPrimitive; pub mod files; pub mod print; pub mod asynchronous; use crate::utils::circullar_buffer::*; use crate::utils::ONLY_MSB_OF_USIZE; use core::convert::TryFrom; #[repr(usize)] #[derive(FromPrimitive, ToPrimitive, Debug)] pub enum Syscalls { StartScheduling, Print, Yield, ...
all_type: usize, ) -> usize { let ret: usize; llvm_asm!("svc 0" : "={x0}"(ret) : "{x0}"(p1), "{x1}"(p2), "{x2}"(p3), "{x3}"(p4), "{x4}"(p5), "{x8}"(syscall_type) : "x0", "x1", "x2", "x3", "x4", "x8" : "volatile"); ret } pub fn start_scheduling() { unsafe { ...
unsafe fn syscall0(syscall_type: usize) -> usize { let ret: usize; llvm_asm!("svc 0" : "={x0}"(ret) : "{x8}"(syscall_type) : "x8" : "volatile"); ret } #[inline(never)] pub unsafe fn syscall1(p1: usize, syscall_type: usize) -> usize { let ret: usize; llvm_a...
random
[ { "content": "pub fn print(msg: &str) {\n\n let bytes = msg.as_bytes();\n\n\n\n unsafe {\n\n syscall2(\n\n bytes.as_ptr() as usize,\n\n bytes.len(),\n\n Syscalls::Print as usize,\n\n );\n\n }\n\n}\n\n\n", "file_path": "src/syscall/print.rs", "rank"...
Rust
src/raytrace.rs
flowbish/gray
cb6824900c9c55392b3f6aa3b052a622b21aad31
extern crate rand; use std::ops::{Add, Sub, Mul, Div, Neg}; use std::ops::IndexMut; use std::cmp::max; type Flt = f64; #[derive(Debug, Copy, Clone)] struct Flt2 { x: Flt, y: Flt, } pub struct RaytraceState<'a> { buffer: Vec<(Flt, Flt, Flt)>, size: (u32, u32), orig_buf: &'a [u8], blur_buf: &'...
extern crate rand; use std::ops::{Add, Sub, Mul, Div, Neg}; use std::ops::IndexMut; use std::cmp::max; type Flt = f64; #[derive(Debug, Copy, Clone)] struct Flt2 { x: Flt, y: Flt, } pub struct RaytraceState<'a> { buffer: Vec<(Flt, Flt, Flt)>, size: (u32, u32), orig_buf: &'a [u8], blur_buf: &'...
fn next_voxel(pos: Flt2, dir: Flt2) -> Flt2 { fn max_inf(x: Flt, y: Flt) -> Flt { if x.is_finite() && y.is_finite() { x.max(y) } else { (2.0 as Flt).sqrt() } } let pos_frac = pos.fract(); let t1 = (Flt2::new(1.0, 1.0) - pos_frac) / dir; let t2 = -pos...
0, 4.0); let mul = v15 * 2.0; vecis(mul, 2.0, 10.0); let div = v15 / 2.0; vecis(div, 0.5, 2.5); let div2 = v15 / v11; vecis(div2, 1.0, 5.0); }
function_block-function_prefixed
[ { "content": "/// Load in a buffer of pixel data from a png file\n\nfn png_data(image: &ImageBuffer<Rgba<u8>, Vec<u8>>) -> Vec<u8> {\n\n image.clone().into_vec()\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 7, "score": 63985.85485487909 }, { "content": "/// Load in a buffer of pixel d...
Rust
polars/polars-core/src/chunked_array/ops/take/take_single.rs
pradkrish/polars
e8f6b0f98fc850cd74659bd64babb935383e5888
#[cfg(feature = "object")] use crate::chunked_array::object::ObjectArray; use crate::prelude::*; use arrow::array::*; use polars_arrow::is_valid::IsValid; use std::convert::TryFrom; #[cfg(feature = "dtype-categorical")] use std::ops::Deref; use std::sync::Arc; macro_rules! impl_take_random_get { ($self:ident, $ind...
#[cfg(feature = "object")] use crate::chunked_array::object::ObjectArray; use crate::prelude::*; use arrow::array::*; use polars_arrow::is_valid::IsValid; use std::convert::TryFrom; #[cfg(feature = "dtype-categorical")] use std::ops::Deref; use std::sync::Arc; macro_rules! impl_take_random_get { ($self:ident, $ind...
#[inline] unsafe fn get_unchecked(&self, index: usize) -> Option<Self::Item> { let opt_arr = impl_take_random_get_unchecked!(self, index, LargeListArray); opt_arr.map(|arr| { let s = Series::try_from((self.name(), arr)); s.unwrap() }) } } #[cfg(test)] mod t...
fn get(&self, index: usize) -> Option<Self::Item> { let opt_arr = unsafe { impl_take_random_get!(self, index, LargeListArray) }; opt_arr.map(|arr| { let s = Series::try_from((self.name(), arr)); s.unwrap() }) }
function_block-full_function
[ { "content": "fn arg_unique<T>(a: impl Iterator<Item = T>, capacity: usize) -> AlignedVec<u32>\n\nwhere\n\n T: Hash + Eq,\n\n{\n\n let mut set = PlHashSet::new();\n\n let mut unique = AlignedVec::with_capacity(capacity);\n\n a.enumerate().for_each(|(idx, val)| {\n\n if set.insert(val) {\n\n ...
Rust
src/util.rs
LaudateCorpus1/dockerfile-parser-rs
b98231e3460895ef2ce52bc7e932d5a92d613e34
use std::fmt; use crate::error::*; use crate::parser::*; use crate::splicer::Span; use enquote::unquote; use snafu::ResultExt; pub(crate) fn parse_string_array(array: Pair) -> Result<StringArray> { let span = Span::from_pair(&array); let mut elements = Vec::new(); for field in array.into_inner() { match...
use std::fmt; use crate::error::*; use crate::parser::*; use crate::splicer::Span; use enquote::unquote; use snafu::ResultExt; pub(crate) fn parse_string_array(array: Pair) -> Result<StringArray> { let span = Span::from_pair(&array); let mut elements = Vec::new(); for field in array.into_inner() { match...
pub fn as_exec(&self) -> Option<&StringArray> { if let ShellOrExecExpr::Exec(s) = self { Some(s) } else { None } } } #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone)] pub struct StringArray { pub span: Span, pub elements: Vec<SpannedString>, } impl StringArray { pub fn ...
pub fn into_exec(self) -> Option<StringArray> { if let ShellOrExecExpr::Exec(s) = self { Some(s) } else { None } }
function_block-function_prefix_line
[ { "content": "/// Parses a string into a single instruction using a particular syntax rule.\n\n///\n\n/// This is technically over-constrained as we could just parse any single\n\n/// instruction using `Rule::step`, however doing so isn't ideal for\n\n/// per-instruction unit tests.\n\npub fn parse_single(input...
Rust
src/pbkdf2.rs
nlanson/btc-hashes
cca8b416d99f50825354c9be4d8bc9c1a9bc5a58
use crate::{ HashEngine, KeyBasedHashEngine }; use std::{ marker::PhantomData, convert::TryInto }; pub struct PBKDF2<T: KeyBasedHashEngine> { hash: PhantomData<T>, password: Vec<u8>, salt: Vec<u8>, iter: usize } impl<T: KeyBasedHashEngine> PBKDF2<T> { pub fn iter(&mut self, co...
use crate::{ HashEngine, KeyBasedHashEngine }; use std::{ marker::PhantomData, convert::TryInto }; pub struct PBKDF2<T: KeyBasedHashEngine> { hash: PhantomData<T>, password: Vec<u8>, salt: Vec<u8>, iter: usize } impl<T: KeyBasedHashEngine> PBKDF2<T> { pub fn iter(&mut self, co...
u[0] = match xor { Ok(x) => x, _ => panic!("bad xor") }; u.remove(1); } u[0] } } impl<T: KeyBasedHashEngine> HashEngine for PBKDF2<T> { type Digest ...
let xor: Result<_, _> = u[0] .into_iter() .zip(u[1].into_iter()) .map(|(x, y)| x^y) .collect::<Vec<u8>>() .try_into();
assignment_statement
[ { "content": "pub trait KeyBasedHashEngine: HashEngine {\n\n fn new_with_key<I>(key: I) -> Self\n\n where I: AsRef<[u8]>;\n\n}\n\n\n\n#[derive(Clone, Copy, Debug)]\n\npub struct State<T: Copy, const N: usize> {\n\n registers: [T; N]\n\n}\n\n\n\nimpl<T: Copy, const N: usize> State<T, N> {\n\n pub fn ...
Rust
src/proto/stream.rs
jzm2k/rs-i2p-samv3
badf606bfd10a4a39d38f0c75a275ddd1b36881b
use crate::session::*; use crate::error::I2pError; use crate::socket::{I2pControlSocket, I2pStreamSocket}; use crate::cmd::*; pub struct I2pStream { session: I2pSession, socket: I2pStreamSocket, } fn new() -> Result<I2pStream, I2pError> { let session = match I2pSession::stream() { Ok(v) => v, ...
use crate::session::*; use crate::error::I2pError; use crate::socket::{I2pControlSocket, I2pStreamSocket}; use crate::cmd::*; pub struct I2pStream { session: I2pSession, socket: I2pStreamSocket, } fn new() -> Result<I2pStream, I2pError> { let session = match I2pSession::stream() { Ok(v) => v, ...
#[test] fn test_stream_connect_invalid() { let mut stream = I2pStream::new().unwrap(); match stream.connect("google.com") { Ok(_) => { assert!(false); }, Err(_) => { assert!(true); } } } }
fn test_stream_connect_valid() { let mut stream = I2pStream::new().unwrap(); match stream.connect("idk.i2p") { Ok(_) => { assert!(true); }, Err(e) => { eprintln!("test_stream_connect_valid: {:#?}", e); assert!(false); ...
function_block-full_function
[]
Rust
zkp-toolkit/scheme/tests/mini.rs
RyanKung/ckb-zkp
499ac247cbe11b510d892dcd90c07744a5a27a49
use curve::bls12_381::{Bls12_381 as E, Fr}; use math::{test_rng, One, PrimeField}; use scheme::r1cs::{ConstraintSynthesizer, ConstraintSystem, SynthesisError}; struct Mini<F: PrimeField> { pub x: Option<F>, pub y: Option<F>, pub z: Option<F>, pub num: u32, } impl<F: PrimeField> ConstraintSynthesizer<F...
use curve::bls12_381::{Bls12_381 as E, Fr}; use math::{test_rng, One, PrimeField}; use scheme::r1cs::{ConstraintSynthesizer, ConstraintSystem, SynthesisError}; struct Mini<F: PrimeField> { pub x: Option<F>, pub y: Option<F>, pub z: Option<F>, pub num: u32, } impl<F: PrimeField> ConstraintSynthesizer<F...
use scheme::clinkv2::r1cs as clinkv2_r1cs; pub struct Clinkv2Mini<F: PrimeField> { pub x: Option<F>, pub y: Option<F>, pub z: Option<F>, pub num: u32, } impl<F: PrimeField> clinkv2_r1cs::ConstraintSynthesizer<F> for Clinkv2Mini<F> { fn generate_constraints<CS: clinkv2_r1cs::ConstraintSystem<F>>(...
fn mini_bulletproofs() { use curve::curve25519::{Curve25519 as G, Fr}; use scheme::bulletproofs::{create_random_proof, verify_proof}; use std::time::Instant; let rng = &mut test_rng(); let num = 10; println!("Bulletproofs prove..."); let c = Mini::<Fr> { x: Some(Fr::from...
function_block-full_function
[ { "content": "/// standard interface for create proof.\n\npub fn create_random_proof<E: PairingEngine, R: Rng, C: ConstraintSynthesizer<E::Fr>>(\n\n ipk: &IndexProverKey<E>,\n\n c: C,\n\n zk_rng: &mut R,\n\n) -> Result<Proof<E>, SynthesisError> {\n\n // init\n\n let pstate = AHP::<E::Fr>::prover_...
Rust
std/src/arrays.rs
severak/endbasic
1c6d8878b2dff82aa6b0eb142327425875253bd8
use endbasic_core::ast::{Expr, Value, VarType}; use endbasic_core::exec::Machine; use endbasic_core::syms::{ Array, CallError, CallableMetadata, CallableMetadataBuilder, Function, FunctionResult, Symbol, Symbols, }; use std::rc::Rc; const CATEGORY: &str = "Array functions"; fn parse_bound_args<'a>( args...
use endbasic_core::ast::{Expr, Value, VarType}; use endbasic_core::exec::Machine; use endbasic_core::syms::{ Array, CallError, CallableMetadata, CallableMetadataBuilder, Function, FunctionResult, Symbol, Symbols, }; use std::rc::Rc; const CATEGORY: &str = "Array functions"; fn parse_bound_args<'a>( args...
} impl Function for LboundFunction { fn metadata(&self) -> &CallableMetadata { &self.metadata } fn exec(&self, args: &[Expr], symbols: &mut Symbols) -> FunctionResult { let (_array, _dim) = parse_bound_args(args, symbols)?; Ok(Value::Integer(0)) } } pub struct UboundFunction ...
pub fn new() -> Rc<Self> { Rc::from(Self { metadata: CallableMetadataBuilder::new("LBOUND", VarType::Integer) .with_syntax("array[, dimension%]") .with_category(CATEGORY) .with_description( "Returns the lower bound for the given dim...
function_block-full_function
[ { "content": "/// Evaluates all arguments given to a function.\n\n///\n\n/// This is a convenience function to simplify the processing of arguments because most functions\n\n/// do not care about unevaluated expressions. However, using this function is inefficient in many\n\n/// occasions because we are alloca...
Rust
src/setting_ip4_config.rs
cathay4t/libnm-rs
99248bbc5a8b7b1adf62d99846312bfa8f770bcc
use crate::Setting; use crate::SettingIPConfig; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GString; use glib::StaticType; use glib::Value; use glib_sys; use gobject_sys; use nm_sys; use std::boxed::Box as Box_; use...
use crate::Setting; use crate::SettingIPConfig; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GString; use glib::StaticType; use glib::Value; use glib_sys; use gobject_sys; use nm_sys; use std::boxed::Box as Box_; use...
fn set_property_dhcp_client_id(&self, dhcp_client_id: Option<&str>) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"dhcp-client-id\0".as_ptr() as *const _, Value::from(dhcp_client_id).to_glib_n...
fn get_dhcp_vendor_class_identifier(&self) -> Option<GString> { unsafe { from_glib_none( nm_sys::nm_setting_ip4_config_get_dhcp_vendor_class_identifier( self.as_ref().to_glib_none().0, ), ) } }
function_block-full_function
[ { "content": "/// Trait containing all `Setting` methods.\n\n///\n\n/// # Implementors\n\n///\n\n/// [`Setting6Lowpan`](struct.Setting6Lowpan.html), [`Setting8021x`](struct.Setting8021x.html), [`SettingAdsl`](struct.SettingAdsl.html), [`SettingBluetooth`](struct.SettingBluetooth.html), [`SettingBond`](struct.Se...
Rust
packages/datajoint-core/src/connection/pool.rs
jonathanschroeter/datajoint-core
51e3cd48355ee9efbeb7efbe851efa706296cea6
use crate::common::{DatabaseType, DatabaseTypeAgnostic}; use crate::error::{DataJointError, Error, ErrorCode, SqlxError}; use crate::query::Query; use crate::results::TableRow; use sqlx::Executor; pub(crate) enum Pool { MySql(sqlx::Pool<sqlx::MySql>), Postgres(sqlx::Pool<sqlx::Postgres>), } impl DatabaseTypeA...
use crate::common::{DatabaseType, DatabaseTypeAgnostic}; use crate::error::{DataJointError, Error, ErrorCode, SqlxError}; use crate::query::Query; use crate::results::TableRow; use sqlx::Executor; pub(crate) enum Pool { MySql(sqlx::Pool<sqlx::MySql>), Postgres(sqlx::Pool<sqlx::Postgres>), } impl DatabaseTypeA...
pub async fn try_fetch_all<'q>(&self, query: Query<'q>) -> Result<Vec<TableRow>, Error> { match self { Self::MySql(pool) => { if let Query::MySql(query) = query { match pool.fetch_all(query).await { Err(error) => Err(Sq...
e_type_error()) } } Self::Postgres(pool) => { if let Query::Postgres(query) = query { match pool.fetch_one(query).await { Err(error) => Err(SqlxError::new(error)), Ok(row) => Ok(TableRow::Postgres...
function_block-function_prefixed
[ { "content": "/// Trait for all errors in library functions, regardless of their origin.\n\npub trait LibraryError {\n\n /// Error message.\n\n fn message(&self) -> Cow<'_, str>;\n\n\n\n /// DataJoint error code.\n\n fn code(&self) -> ErrorCode;\n\n\n\n /// Associated SQLSTATE, if any.\n\n fn ...
Rust
rp2040-hal/src/gpio.rs
hmvp/rp-hal
c4cd2ffe52a4844dd43a81594df3b0e9bcdfddc3
use crate::sio; pub struct Input; pub struct Output; pub struct Unknown; pub trait GpioExt<PADS, SIO> { type Parts; fn split(self, pads: PADS, sio: SIO, reset: &mut rp2040_pac::RESETS) -> Self::Parts; } #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum OutputDriveStrength { ...
use crate::sio; pub struct Input; pub struct Output; pub struct Unknown; pub trait GpioExt<PADS, SIO> { type Parts; fn split(self, pads: PADS, sio: SIO, reset: &mut rp2040_pac::RESETS) -> Self::Parts; } #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum OutputDriveStrength { ...
utDriveStrength::FourMilliAmps => PacDriveStrength::_4MA, OutputDriveStrength::EightMilliAmps => PacDriveStrength::_8MA, OutputDriveStrength::TwelveMilliAmps => PacDriveStrength::_12MA, }; self.pad().modify(|_, w| w....
x.bits(1 << $i) }); Ok(()) } fn set_high(&mut self) -> Result<(), Self::Error> { self.sio().gpio_out_set.write(|x| unsafe { x.bits(1 << $i) }); Ok(()) } } ...
random
[ { "content": " pub trait SubsystemReset {\n\n fn reset_bring_up(&self, resets: &mut pac::RESETS);\n\n }\n\n}\n\n\n\npub(crate) use private::SubsystemReset;\n\n\n\nmacro_rules! generate_reset {\n\n ($MODULE:ident, $module:ident) => {\n\n impl SubsystemReset for pac::$MODULE {\n\n ...
Rust
rust/src/image.rs
unageek/graphest
d3aef6ffd796b8d88410c714b8ddcbcd8d34444d
use crate::traits::BytesAllocated; use std::{ ops::{Index, IndexMut}, slice::{Iter, IterMut}, }; #[derive(Debug)] pub struct Image<T: Clone + Copy + Default> { width: u32, height: u32, data: Vec<T>, } impl<T: Clone + Copy + Default> Image<T> { pub const MAX_WIDTH: u32 = 32768; p...
use crate::traits::BytesAllocated; use std::{ ops::{Index, IndexMut}, slice::{Iter, IterMut}, }; #[derive(Debug)] pub struct Image<T: Clone + Copy + Default> { width: u32, height: u32, data: Vec<T>, } impl<T: Clone + Copy + Default> Image<T> { pub const MAX_WIDTH: u32 = 32768; p...
PixelIndex::new(1, 2)); let mut iter = r.iter(); assert_eq!(iter.next(), None); let r = PixelRange::new(PixelIndex::new(1, 2), PixelIndex::new(4, 2)); let mut iter = r.iter(); assert_eq!(iter.next(), None); let r = PixelRange::new(PixelIndex::new(1, 2), PixelIndex::new...
end.x && begin.y <= end.y); if begin.x == end.x || begin.y == end.y { Self::EMPTY } else { Self { begin, end } } } pub fn iter(&self) -> PixelIter { self.into_iter() } } impl<'a> IntoIterator for &'a PixelRange { type Item = PixelIndex; ...
random
[ { "content": "/// Precondition: [`PreTransform`] has been applied to the expression.\n\npub fn simplify(e: &mut Expr) {\n\n loop {\n\n let mut fl = Flatten::default();\n\n fl.visit_expr_mut(e);\n\n let mut s = SortTerms::default();\n\n s.visit_expr_mut(e);\n\n let mut f = F...
Rust
src/main.rs
HristoKolev/sync-dir
bdbacd016edb41d6cf6755d1c294d6d9f5f3c059
#![forbid(unsafe_code)] #[macro_use] mod global; use std::sync::mpsc::channel; use std::time::Duration; use std::sync::{Mutex, Arc}; use std::thread::JoinHandle; use std::path::{PathBuf, Path}; use notify::{Watcher, RecursiveMode, watcher, DebouncedEvent}; use crate::global::prelude::*; fn main() { global::ini...
#![forbid(unsafe_code)] #[macro_use] mod global; use std::sync::mpsc::channel; use std::time::Duration; use std::sync::{Mutex, Arc}; use std::thread::JoinHandle; use std::path::{PathBuf, Path}; use notify::{Watcher, RecursiveMode, watcher, DebouncedEvent}; use crate::global::prelude::*; fn main() { global::ini...
trait DebounceEventExtensions { fn get_path(&self) -> Option<PathBuf>; } impl DebounceEventExtensions for DebouncedEvent { fn get_path(&self) -> Option<PathBuf> { match self { DebouncedEvent::NoticeWrite(x) => Some(x.clone()), DebouncedEvent::NoticeRemove(x) => Some(x.clone()...
let path = destination_path.split(':').collect_vec()[1]; let remote = destination_path.split(':').collect_vec()[0]; let mkdir_command = &format!( "ssh -n -o StrictHostKeyChecking=no {} {} 'mkdir -p {}'", ssh_key_file.map(|x | format!("-i {}", x)).unwrap_or("".to_string()), ...
function_block-function_prefix_line
[ { "content": "/// Creates the global object.\n\nfn create_global_result() -> Result<Global> {\n\n\n\n let config_directory = std::env::current_exe()?.get_directory();\n\n\n\n let config_file_path = config_directory.join(APP_CONFIG_FILE_NAME);\n\n\n\n if !config_file_path.exists() {\n\n eprintln!...
Rust
build.rs
axtend/ss58
3e0334e9d19a3215ef86946e2e238d6d6596e120
use quote::{format_ident, quote}; use serde::Deserialize; use std::{collections::HashMap, env, fs, path::Path}; use unicode_xid::UnicodeXID; #[derive(Deserialize)] struct Registry { registry: Vec<AccountType>, } fn is_valid_rust_identifier(id: &str) -> Result<(), String> { if let Some(ch) = id.chars().next() { ...
use quote::{format_ident, quote}; use serde::Deserialize; use std::{collections::HashMap, env, fs, path::Path}; use unicode_xid::UnicodeXID; #[derive(Deserialize)] struct Registry { registry: Vec<AccountType>, }
impl Registry { pub fn is_valid(&self) -> Result<(), String> { let mut used_prefixes = HashMap::<u16, AccountType>::new(); let mut used_networks = HashMap::<String, AccountType>::new(); for account_type in &self.registry { if let Some(clash) = used_prefixes.insert(account_type.prefix, (*account_type).clone(...
fn is_valid_rust_identifier(id: &str) -> Result<(), String> { if let Some(ch) = id.chars().next() { if ch.is_xid_start() { for ch in id.chars().skip(1) { if !ch.is_xid_continue() { return Err(format!("Invalid char `{}` in `{}`", ch, id)) } } Ok(()) } else { Err(format!("`{}` starts with `{...
function_block-full_function
[ { "content": "#![feature(bench_black_box)]\n\n#![feature(test)]\n\nextern crate test;\n\nuse std::hint::black_box;\n\n\n\nuse test::Bencher;\n\nstatic BENCH_SIZE: u16 = 100;\n\nuse ss58_registry::{from_address_format, Ss58AddressFormat, Ss58AddressFormatRegistry};\n\nuse std::convert::TryInto;\n\n\n\n#[bench]\n...
Rust
compiler/rustc_middle/src/ty/list.rs
anirudhb/rust
178108bf81606a0e25b1066568c2b8c8e0648617
use crate::arena::Arena; use rustc_serialize::{Encodable, Encoder}; use std::alloc::Layout; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::iter; use std::mem; use std::ops::Deref; use std::ptr; use std::slice; extern "C" { type OpaqueListContents; } #[repr(C)] pub struct...
use crate::arena::Arena; use rustc_serialize::{Encodable, Encoder}; use std::alloc::Layout; use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::iter; use std::mem; use std::ops::Deref; use std::ptr; use std::slice; extern "C" { type OpaqueListContents; } #[repr(C)] pub struct...
[T]; #[inline(always)] fn deref(&self) -> &[T] { self.as_ref() } } impl<T> AsRef<[T]> for List<T> { #[inline(always)] fn as_ref(&self) -> &[T] { unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) } } } impl<'a, T: Copy> IntoIterator for &'a List<T> { type Item = T...
a List<T> { const BITS: usize = std::mem::align_of::<usize>().trailing_zeros() as usize; fn into_usize(self) -> usize { self as *const List<T> as usize } unsafe fn from_usize(ptr: usize) -> Self { &*(ptr as *const List<T>) } unsafe fn with_ref<R, F: FnOnce(&Self) -> R>(ptr: usize...
random
[]
Rust
tests/monte_carlo.rs
Simsys/fchashmap
3a4e620031e56af80e8815792f03395f12c2bba7
use fchashmap::FcHashMap; use rand_xorshift::XorShiftRng; use rand_core::{RngCore, SeedableRng}; use std::collections::HashMap; struct MonteCarlo { fc_hashmap: FcHashMap::<u32, u32, MAP_SIZE>, std_hashmap: HashMap::<u32, u32>, } const MAP_SIZE: usize = 16384; const SEED: u64 = 1234567890987654321; impl Monte...
use fchashmap::FcHashMap; use rand_xorshift::XorShiftRng; use rand_core::{RngCore, SeedableRng}; use std::collections::HashMap; struct MonteCarlo { fc_hashmap: FcHashMap::<u32, u32, MAP_SIZE>, std_hashmap: HashMap::<u32, u32>, } const MAP_SIZE: usize = 16384; const SEED: u64 = 1234567890987654321; impl Monte...
std { println!("Error 4, len {}, key {}, r_fc{:?}, r_std {:?}", self.fc_hashmap.len(), key, r_fc, r_std); }; assert_eq!(r_fc, r_std); } fn test_1(&mut self) { let mut rng = XorShiftRng::seed_from_u64(SEED); loop { if self.fc_hashmap.len() >= MAP_...
println!("Error 1, len {}, key {}, value {}, r_v{:?}, r_std {:?}", self.fc_hashmap.len(), key, value, r_v, r_std); }; assert_eq!(r_v, r_std); }, Err(e) => { println!("Error 2, len {}, key {}, value {}, e{:?}, r_std {:?}", self.fc_hash...
random
[ { "content": "#[derive(Clone, Copy, PartialEq)]\n\nstruct HashValue(u16);\n\n\n\n// There are up to 0x7fff (32767) elements allowed. The first bit of u16 is used to mark\n\n// a empty element\n\nconst HASH_VALUE_IS_EMPTY: HashValue = HashValue(0x8000);\n\n\n\nimpl HashValue {\n\n // Create 15 bit hash value ...
Rust
src/checker/hunspell.rs
laysauchoa/cargo-spellcheck
b8dab84f9f45c107f820d447cb858ed3ee26bf6c
use super::{tokenize, Checker, Detector, Documentation, Suggestion, SuggestionSet}; use crate::documentation::{CheckableChunk, ContentOrigin, PlainOverlay}; use crate::util::sub_chars; use crate::Range; use log::{debug, trace}; use std::path::PathBuf; use hunspell_rs::Hunspell; use anyhow::{anyhow, bail, Result}; ...
use super::{tokenize, Checker, Detector, Documentation, Suggestion, SuggestionSet}; use crate::documentation::{CheckableChunk, ContentOrigin, PlainOverlay}; use crate::util::sub_chars; use crate::Range; use log::{debug, trace}; use std::path::PathBuf; use hunspell_rs::Hunspell; use anyhow::{anyhow, bail, Result}; ...
chunk: &'s CheckableChunk, hunspell: &Hunspell, origin: &ContentOrigin, word: String, range: Range, allow_concatenated: bool, allow_dashed: bool, acc: &mut SuggestionSet<'s>, ) { if !hunspell.check(&word) { trace!("No match for word (plain range: {:?}): >{}<", &range, &word); ...
function_block-function_prefix_line
[ { "content": "/// Check a full document for violations using the tools we have.\n\npub fn check<'a, 's>(documentation: &'a Documentation, config: &Config) -> Result<SuggestionSet<'s>>\n\nwhere\n\n 'a: 's,\n\n{\n\n let mut collective = SuggestionSet::<'s>::new();\n\n\n\n #[cfg(feature = \"languagetool\"...
Rust
src/shard_blocks.rs
serge-medvedev/ton-labs-node
37a7cbd109af439c262376d043d797bbb7e067f1
use crate::{ types::top_block_descr::{TopBlockDescrStuff, TopBlockDescrId}, engine_traits::EngineOperations, shard_state::ShardStateStuff, }; use ton_block::{BlockIdExt, TopBlockDescr, Deserializable, BlockSignatures}; use ton_types::{fail, error, Result, deserialize_tree_of_cells}; use std::{ io::Curso...
use crate::{ types::top_block_descr::{TopBlockDescrStuff, TopBlockDescrId}, engine_traits::EngineOperations, shard_state::ShardStateStuff, }; use ton_block::{BlockIdExt, TopBlockDescr, Deserializable, BlockSignatures}; use ton_types::{fail, error, Result, deserialize_tree_of_cells}; use std::{ io::Curso...
fn send_to_storage(&self, action: StoreAction) { if let Some(storage_sender) = self.storage_sender.as_ref() { match storage_sender.send(action) { Ok(_) => log::trace!("ShardBlocksPool::send_to_storage: sent"), Err(_) => log::error!("ShardBlocksPool::send_to_stor...
for block in self.shard_blocks.iter() { if block.val().validate(last_mc_state).is_err() { self.shard_blocks.remove(block.key()); self.send_to_storage(StoreAction::Remove(block.key().clone())); removed_list.append(format!("\n{} {}", block.key().cc_seqno, block....
function_block-function_prefix_line
[ { "content": "pub fn check_prev_block(listed: &BlockIdExt, prev: &BlockIdExt, chk_chain_len: bool) -> Result<()> {\n\n if listed.seq_no > prev.seq_no {\n\n fail!(\"cannot generate a shardchain block after previous block {} \\\n\n because masterchain configuration already contains a newer bl...
Rust
siquery/src/windows/wmi_os_version.rs
Devolutions/siquery-rs
dbd84a0346652ac62c474f209b9b59fa1f11ddc1
use std::process::Command; use std::borrow::Borrow; use crate::tables::{WmiOsVersion,WmiOsVersionIface}; use crate::utils; pub struct Reader {} impl WmiOsVersionIface for Reader { fn get_wmi_os_info(&self) -> Option<String> { let output = Command::new("wmic") .args(&["os", "get", "/format:list...
use std::process::Command; use std::borrow::Borrow; use crate::tables::{WmiOsVersion,WmiOsVersionIface}; use crate::utils; pub struct Reader {} impl WmiOsVersionIface for Reader { fn get_wmi_os_info(&self) -> Option<String> { let output = Command::new("wmic") .args(&["os", "get", "/format:list...
pub(crate) fn get_specific() -> Vec<WmiOsVersion> { let reader: Box<dyn WmiOsVersionIface> = Box::new(Reader{}); let out = WmiOsVersion::get_specific_ex(reader.borrow()); out } } #[cfg(test)] mod tests { use super::*; pub struct Test {} impl WmiOsVersionIface for Test { ...
v; }, "Name" => { let n: Vec<_> = v.split("|").collect(); if n.len() >= 1 { os_version.name = n[0].to_string(); } }, "ServicePackMajorVersio...
function_block-function_prefixed
[ { "content": "pub fn get_local_accounts_inv(ref mut root: &mut Element) {\n\n let wmi_local_accounts = WmiLocalAccounts::get_specific();\n\n let mut local_accounts = Element::new(\"LocalAccounts\");\n\n for local_account in wmi_local_accounts {\n\n let mut remote_account = Element::new(\"RemoteA...
Rust
src/memory/map.rs
martinkauppinen/gibberish
7dcfb34751b6ded467a1757212a52adee3b79bd0
use crate::memory::ram::Ram; use crate::memory::region::MemoryRegion; use super::ioregs::IoRegs; #[derive(Debug, Clone)] pub struct MemoryMap { cartridge: Ram, vram: Ram, eram: Ram, iram: Ram, iram_echo: Ram, sprite_attrs: Ram, io_regs: IoRegs, hram: Ram, int_enable_reg: u8, }...
use crate::memory::ram::Ram; use crate::memory::region::MemoryRegion; use super::ioregs::IoRegs; #[derive(Debug, Clone)] pub struct MemoryMap { cartridge: Ram, vram: Ram, eram: Ram, iram: Ram, iram_echo: Ram, sprite_attrs: Ram, io_regs: IoRegs, hram: Ram, int_enable_reg: u8, }...
self.hram.read_word(addr), _ => { panic!("Unusable address: {:x}", addr); } } } pub fn write_word(&mut self, word: u16, addr: u16) { match addr { CART_START..=CART_END => self.cartridge.write_word(word, addr), VRAM_START..=VRAM_END...
_word(addr), IRAM_START..=IRAM_END => self.iram.read_word(addr), IRAM_ECHO_START..=IRAM_ECHO_END => self.iram_echo.read_word(addr), SPRITE_ATTRS_START..=SPRITE_ATTRS_END => self.sprite_attrs.read_word(addr), IO_REGS_START..=IO_REGS_END => self.io_regs.read_word(addr), ...
function_block-random_span
[ { "content": "/// Sign extend 8-bit value to 16-bit\n\nfn sign_extend(byte: u8) -> u16 {\n\n if byte & 0x80 != 0 {\n\n 0xFF00 | byte as u16\n\n } else {\n\n byte as u16\n\n }\n\n}\n\n\n", "file_path": "src/cpu/opcodes/mod.rs", "rank": 0, "score": 181401.5663543227 }, { ...
Rust
checkout/rust/payment-methods/filter-payment-methods-based-on-configuration/src/main.rs
Shopify/scripts-apis-examples
6121a47cafcb56f6f736cb0733173d9900f9373e
/* * This script filters payment methods when both of the following conditions are met: * - The payment method name matches the `payment_method_name` field from the configuration. * - The total price of the checkout (`purchase_proposal`) is greater than the `threshold` field * from the configuration in CAD....
/* * This script filters payment methods when both of the following conditions are met: * - The payment method name matches the `payment_method_name` field from the configuration. * - The total price of the checkout (`purchase_proposal`) is greater than the `threshold` field * from the configuration in CAD....
return Ok(build_result(hidden_methods)); } fn build_result(payment_methods_to_remove: Vec<PaymentMethod>) -> Output { Output { sort_response: SortResponse { proposed_order: vec![], }, filter_response: FilterResponse { hidden_methods: payment_methods_to_remove, ...
if total_price <= threshold { hidden_methods = input.payment_methods.into_iter() .filter(|payment_method| payment_method.name==payment_method_name).collect(); }
if_condition
[ { "content": "fn script(payload: Payload) -> Result<Output, Box<dyn std::error::Error>> {\n\n let (_input, _config) = (payload.input, payload.configuration);\n\n return Ok(build_result(vec![]));\n\n}\n\n\n", "file_path": "checkout/rust/payment-methods/default/src/main.rs", "rank": 3, "score": ...
Rust
server-sent_events/src/event.rs
bk-rs/sse-rs
c943f2084435a594569c2a4d49cbe69a7e3dd88e
use alloc::{boxed::Box, vec::Vec}; use core::fmt; #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Event { pub comment: Option<Box<str>>, pub retry: Option<usize>, pub id: Option<Box<str>>, pub r#type: Option<Box<str>>, pub data: Option<EventData>, } #[derive(Debug, Clone,...
use alloc::{boxed::Box, vec::Vec}; use core::fmt; #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Event { pub comment: Option<Box<str>>, pub retry: Option<usize>, pub id: Option<Box<str>>, pub r#type: Option<Box<str>>, pub data: Option<EventData>, } #[derive(Debug, Clone,...
y: 10000\n\n" ); assert_eq!( Event::new("message", None, None).to_string().as_bytes(), b"data: message\n\n" ); assert_eq!( Event::new(r#"Message of type "foo""#, "foo", None) .to_string() .as_bytes(), b"even...
ct())), ..Default::default() } } pub fn with_comment(comment: &str) -> Self { Self { comment: Some(comment.into()), ..Default::default() } } pub fn with_retry(retry_ms: usize) -> Self { Self { retry: Some(retry_ms), ...
random
[ { "content": "#[cfg(all(feature = \"std\", feature = \"http\"))]\n\npub fn get_last_event_id(\n\n headers: &http::HeaderMap<http::HeaderValue>,\n\n) -> Result<Option<String>, core::str::Utf8Error> {\n\n if let Some(header_value) = headers.get(crate::LAST_EVENT_ID_HEADER_KEY) {\n\n if let Ok(value) ...
Rust
lib/rust/rust-utils-10x/tenkit/src/chunk_bam.rs
TomKellyGenetics/cellranger
131e5362cb2f4c2d674899b5d853f7a33c66872f
use std::fs; use std::io; use std::fs::File; use std::cmp::{min, max}; use std::path::Path; use std::mem::drop; use bincode::deserialize_from; use rust_htslib::bam; use rust_htslib::bam::Read; #[derive(Deserialize, Debug)] pub struct GzipHeader { pub id1: u8, pub id2: u8, pub cm: u8, pub flg: u8, pub mtime:...
use std::fs; use std::io; use std::fs::File; use std::cmp::{min, max}; use std::path::Path; use std::mem::drop; use bincode::deserialize_from; use rust_htslib::bam; use rust_htslib::bam::Read; #[derive(Deserialize, Debug)] pub struct GzipHeader { pub id1: u8, pub id2: u8, pub cm: u8, pub flg: u8, pub mtime:...
#[allow(bare_trait_objects)] pub fn chunk_bam_records<P: AsRef<Path>, K: Eq>(bam_path: &P, block_offsets: &Vec<u64>, chunk_bound_key: &Fn(bam::Record) -> Option<K>, chunk_siz...
let bam = bam::Reader::from_path(bam_path).expect("Failed to open input BAM"); let first_block = (bam.tell() >> 16) as u64; info!("Found first block at real offset {}", first_block); let mut bgzf = File::open(bam_path).expect("Failed to open input BAM"); let mut block_offsets: Vec<u64> = Vec:...
function_block-function_prefix_line
[ { "content": "/// Get an alignment record's extra flags\n\npub fn get_read_extra_flags(record: &bam::Record) -> ExtraFlags {\n\n record.aux(EXTRA_FLAGS_TAG).map_or(Default::default(), |x| ExtraFlags::from_bits_truncate(x.integer() as u32))\n\n}\n\n\n", "file_path": "lib/rust/cr_stage/src/utils.rs", "...
Rust
src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs
Abendstolz/rust
c2dbebd3d4ad21e80ef4e7535dd1e868aaad7e50
use super::{contains_return, BIND_INSTEAD_OF_MAP}; use crate::utils::{ in_macro, match_qpath, match_type, method_calls, multispan_sugg_with_applicability, paths, remove_blocks, snippet, snippet_with_macro_callsite, span_lint_and_sugg, span_lint_and_then, }; use if_chain::if_chain; use rustc_errors::Applicabilit...
use super::{contains_return, BIND_INSTEAD_OF_MAP}; use crate::utils::{ in_macro, match_qpath, match_type, method_calls, multispan_sugg_with_applicability, paths, remove_blocks, snippet, snippet_with_macro_callsite, span_lint_and_sugg, span_lint_and_then, }; use if_chain::if_chain; use rustc_errors::Applicabilit...
fn find_all_ret_expressions<'hir, F>(_cx: &LateContext<'_>, expr: &'hir hir::Expr<'hir>, callback: F) -> bool where F: FnMut(&'hir hir::Expr<'hir>) -> bool, { struct RetFinder<F> { in_stmt: bool, failed: bool, cb: F, } struct WithStmtGuarg<'a, F> { val: &'a mut RetFinder...
function_block-full_function
[]
Rust
src/clip.rs
DanielleB-R/render-3d
94cfca82e67803f6163930633df4cc408826d94c
use crate::scene::{Camera, Object, Scene, Triangle}; use glam::DVec3; #[derive(Debug, Clone, Copy)] pub struct Plane { normal: DVec3, d: f64, } impl Plane { fn signed_distance(&self, vertex: DVec3) -> f64 { self.normal.dot(vertex) + self.d } fn intersection(&self, v0: DVec3, v1: DVec3) ->...
use crate::scene::{Camera, Object, Scene, Triangle}; use glam::DVec3; #[derive(Debug, Clone, Copy)] pub struct Plane { normal: DVec3, d: f64, } impl Plane { fn signed_distance(&self, vertex: DVec3) -> f64 { self.normal.dot(vertex) + self.d } fn intersection(&self, v0: DVec3, v1: DVec3) ->...
ane.signed_distance(self.v0); let d1 = plane.signed_distance(self.v1); let d2 = plane.signed_distance(self.v2); match (d0.signum() as i32, d1.signum() as i32, d2.signum() as i32) { (1, 1, 1) => vec![*self], (-1, -1, -1) => vec![], (1, -1, -1) => self.clip_one...
v0: ap, v1: b, v2: bp, color: self.color, }, ] } fn clip_against_plane(&self, plane: Plane) -> Vec<Self> { let d0 = pl
random
[ { "content": "pub fn interpolate(i0: i32, d0: f64, i1: i32, d1: f64) -> Vec<f64> {\n\n let mut values = vec![];\n\n\n\n let a = (d1 - d0) / (i1 - i0) as f64;\n\n let mut d = d0;\n\n\n\n for _ in i0..=i1 {\n\n values.push(d);\n\n d += a;\n\n }\n\n\n\n values\n\n}\n\n\n", "file...
Rust
src/webview/winrt/file_drop.rs
caverym/wry
76b7c3014cd34c40db0f82f38f284b2fa9928ddc
use windows::{Abi, Interface}; use windows_webview2::Windows::Win32::{ Com::{self as com, DVASPECT, TYMED}, DisplayDevices::POINTL, Shell::{self as shell, HDROP}, SystemServices::{self, BOOL, CLIPBOARD_FORMATS, PWSTR}, WindowsAndMessaging::{self, HWND, LPARAM}, }; use crate::{FileDropEvent, FileDropHandle...
use windows::{Abi, Interface}; use windows_webview2::Windows::Win32::{ Com::{self as com, DVASPECT, TYMED}, DisplayDevices::POINTL, Shell::{self as shell, HDROP}, SystemServices::{self, BOOL, CLIPBOARD_FORMATS, PWSTR}, WindowsAndMessaging::{self, HWND, LPARAM}, }; use crate::{FileDropEvent, FileDropHandle...
} } } true } } fn enumerate_child_windows<F>(hwnd: HWND, mut callback: F) where F: FnMut(HWND) -> bool, { let mut trait_obj: &mut dyn FnMut(HWND) -> bool = &mut callback; let closure_pointer_pointer: *mut c_void = unsafe { mem::transmute(&mut trait_obj) }; let lparam = LPARAM(closure...
if com::RegisterDragDrop(hwnd, interface).is_ok() { self.drop_targets.push((hwnd, Box::into_raw(drop_target))); }
if_condition
[]
Rust
vulkano/src/pipeline/vertex/buffers.rs
maximbaz/vulkano
a6dc45260538ecc6025d8f062cd058245e684cb3
use super::VertexMemberInfo; use crate::buffer::BufferAccess; use crate::pipeline::shader::ShaderInterface; use crate::pipeline::vertex::IncompatibleVertexDefinitionError; use crate::pipeline::vertex::Vertex; use crate::pipeline::vertex::VertexDefinition; use crate::pipeline::vertex::VertexInput; use crate::pipeline:...
use super::VertexMemberInfo; use crate::buffer::BufferAccess; use crate::pipeline::shader::ShaderInterface; use crate::pipeline::vertex::IncompatibleVertexDefinitionError; use crate::pipeline::vertex::Vertex; use crate::pipeline::vertex::VertexDefinition; use crate::pipeline::vertex::VertexInput; use crate::pipeline:...
} impl BuffersDefinition { pub fn new() -> Self { BuffersDefinition(Vec::new()) } pub fn vertex<V: Vertex>(mut self) -> Self { self.0.push(VertexBuffer { info_fn: V::member, stride: mem::size_of::<V>() as u32, input_rate: VertexInputRate::Vert...
fn from(val: VertexBuffer) -> Self { Self { stride: val.stride, input_rate: val.input_rate, } }
function_block-full_function
[ { "content": "pub fn member_name_from_id(doc: &Spirv, searched: u32, searched_member: u32) -> String {\n\n for instruction in &doc.instructions {\n\n if let &Instruction::MemberName {\n\n target_id,\n\n member,\n\n ref name,\n\n } = instruction\n\n {\n\n ...
Rust
src/settings.rs
FelipeACP/gateway-rs
fd2a119babb8dcb7bc3546ef73772b33b7a7f65b
use crate::{ api::GatewayStakingMode, releases, Error, KeyedUri, Keypair, PublicKey, Region, Result, }; use config::{Config, Environment, File}; use http::uri::Uri; pub use log_method::LogMethod; use serde::Deserialize; use std::{collections::HashMap, fmt, path::Path, str::FromStr, sync::Arc}; pub fn version() -> ...
use crate::{ api::GatewayStakingMode, releases, Error, KeyedUri, Keypair, PublicKey, Region, Result, }; use confi
ode::Dataonly => StakingMode::DataOnly, GatewayStakingMode::Full => StakingMode::Full, GatewayStakingMode::Light => StakingMode::Light, } } } impl From<&StakingMode> for GatewayStakingMode { fn from(v: &StakingMode) -> Self { match v { StakingMode::DataOnly =...
g::{Config, Environment, File}; use http::uri::Uri; pub use log_method::LogMethod; use serde::Deserialize; use std::{collections::HashMap, fmt, path::Path, str::FromStr, sync::Arc}; pub fn version() -> semver::Version { semver::Version::parse(env!("CARGO_PKG_VERSION")).expect("unable to parse version") } #[derive...
random
[ { "content": "pub fn load_from_file(path: &str) -> error::Result<Keypair> {\n\n let data = fs::read(path)?;\n\n Ok(helium_crypto::Keypair::try_from(&data[..])?.into())\n\n}\n\n\n", "file_path": "src/keypair.rs", "rank": 0, "score": 133621.54244268313 }, { "content": "pub fn save_to_fil...