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/stages/how_to_play.rs
rdrmic/color-columns
197a7a46ba314b93401a7882e764c85c844ec967
use ggez::{ graphics::{self, Align, DrawParam, PxScale, Text, TextFragment}, mint::Point2, Context, GameResult, }; use glam::Vec2; use crate::{ blocks::Block, constants::{ BLOCK_COLOR_BLUE, BLOCK_COLOR_GREEN, BLOCK_COLOR_MAGENTA, BLOCK_COLOR_ORANGE, BLOCK_COLOR_RED, BLOCK_COLOR_YELL...
use ggez::{ graphics::{self, Align, DrawParam, PxScale, Text, TextFragment}, mint::Point2, Context, GameResult, }; use glam::Vec2; use crate::{ blocks::Block, constants::{ BLOCK_COLOR_BLUE, BLOCK_COLOR_GREEN, BLOCK_COLOR_MAGENTA, BLOCK_COLOR_ORANGE, BLOCK_COLOR_RED, BLOCK_COLOR_YELL...
fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { for mut block in self.blocks_header_controls { block.draw(ctx)?; } for mut block in self.blocks_header_scoring_rules { block.draw(ctx)?; } graphics::queue_text( ctx, &...
fn update(&mut self, _ctx: &Context, input_event: Event) -> GameResult<Option<Stage>> { if let Event::Escape = input_event { return Ok(Some(Stage::MainMenu)); } Ok(Some(Stage::HowToPlay)) }
function_block-full_function
[ { "content": "pub fn idx_pair_to_center_point_of_block(idxs: &[usize; 2]) -> Point2<f32> {\n\n Point2 {\n\n x: BLOCK_SIZE.mul_add(idxs[0] as f32, GAME_ARENA_RECT.left()) + BLOCK_SIZE / 2.0,\n\n y: (GAME_ARENA_RECT.bottom() - BLOCK_SIZE * idxs[1] as f32) - BLOCK_SIZE + BLOCK_SIZE / 2.0,\n\n }...
Rust
src/model/yaml/null.rs
dnsl48/yamlette
593f172622d393086450023433549bf23843933f
extern crate skimmer; use model::{ model_issue_rope, EncodedString, Model, Node, Rope, Renderer, Tagged, TaggedValue }; use model::style::CommonStyles; use std::any::Any; use std::borrow::Cow; use std::default::Default; use std::iter::Iterator; pub static TAG: &'static str = "tag:yaml.org,2002:null"; #[derive (Copy...
extern crate skimmer; use model::{ model_issue_rope, EncodedString, Model, Node, Rope, Renderer, Tagged, TaggedValue }; use model::style::CommonStyles; use std::any::Any; use std::borrow::Cow; use std::default::Default; use std::iter::Iterator; pub static TAG: &'static str = "tag:yaml.org,2002:null"; #[derive (Copy...
} #[derive (Clone, Debug)] pub struct NullValue { style: u8, alias: Option<Cow<'static, str>> } impl NullValue { pub fn new (styles: CommonStyles, alias: Option<Cow<'static, str>>) -> NullValue { NullValue { style: if styles.issue_tag () { 1 } else { 0 }, alias: alias } } pub fn ...
edValue::from (NullValue::default ()) ) } if quote_state > 0 { match value.get (ptr).map (|b| *b) { Some (b'\'') if quote_state == 1 => Ok ( TaggedValue::from (NullValue::default ()) ), Some (b'"') if quote_state == 2 => Ok ( TaggedValue::from (NullValue::de...
function_block-function_prefixed
[ { "content": "pub fn model_issue_rope (model: &Model, node: Node, issue_tag: bool, alias: Option<Cow<'static, str>>, tags: &mut Iterator<Item=&(Cow<'static, str>, Cow<'static, str>)>) -> Rope {\n\n if let Some (alias) = alias {\n\n if issue_tag {\n\n Rope::from (vec! [model_tag (model, tags...
Rust
tss-esapi/tests/integration_tests/context_tests/tpm_commands/object_commands_tests.rs
Superhepper/rust-tss-esapi
a6ae84793e73b10dd672b613ada820566c84fe85
mod test_create { use crate::common::{create_ctx_with_session, decryption_key_pub}; use std::convert::TryFrom; use tss_esapi::{interface_types::resource_handles::Hierarchy, structures::Auth}; #[test] fn test_create() { let mut context = create_ctx_with_session(); let random_digest...
mod test_create { use crate::common::{create_ctx_with_session, decryption_key_pub}; use std::convert::TryFrom; use tss_esapi::{interface_types::resource_handles::Hierarchy, structures::Auth}; #[test] fn test_create() { let mut context = create_ctx_with_session(); let random_digest...
} mod test_make_credential { use crate::common::{create_ctx_with_session, decryption_key_pub}; use std::convert::TryInto; use tss_esapi::interface_types::resource_handles::Hierarchy; #[test] fn test_make_credential() { let mut context = create_ctx_with_session(); let key_handle =...
y_handle = context .create_primary( Hierarchy::Owner, &signing_key_pub(), Some(&key_auth), None, None, None, ) .unwrap() .key_handle; let _ = context.read_public(key_ha...
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn create_public_sealed_object() -> Public {\n\n let object_attributes = ObjectAttributesBuilder::new()\n\n .with_fixed_tpm(true)\n\n .with_fixed_parent(true)\n\n .with_no_da(true)\n\n .with_admin_with_policy(true)\n\n .with_user_wit...
Rust
src/tool.rs
jacrgrady/farnans-farming-game
a9c168b13e3cfe5fa07c97aca02ee686206c4ba6
use crate::crop::CropType; use crate::genes; use crate::population::Population; use crate::InventoryItemTrait; use sdl2::rect::Rect; use sdl2::render::Texture; pub enum ToolType { Hand, Hoe, WateringCan, } pub struct Tool<'a> { src: Rect, texture: Texture<'a>, current_type: ToolType, } impl<'...
use crate::crop::CropType; use crate::genes; use crate::population::Population; use crate::InventoryItemTrait; use sdl2::rect::Rect; use sdl2::render::Texture; pub enum ToolType { Hand, Hoe, WateringCan, } pub struct Tool<'a> { src: Rect, texture: Texture<'a>, current_type: ToolType, } impl<'...
}
p() .clone(); let mut _c = pop.get_crop_with_index_mut(x as u32, y as u32); let return_crop_type = _c.get_crop_type_enum(); _c.set_crop_type_enum(CropType::None); _c.set_stag...
function_block-function_prefixed
[ { "content": "pub fn background_to_draw(p: &Player) -> Rect {\n\n Rect::new(\n\n ((p.x() + ((p.width() / 2) as i32)) - ((CAM_W / 2) as i32)).clamp(0, (BG_W - CAM_W) as i32),\n\n ((p.y() + ((p.height() / 2) as i32)) - ((CAM_H / 2) as i32))\n\n .clamp(0, (BG_H - CAM_H) as i32),\n\n ...
Rust
src/sync.rs
naftulikay/phatnoise.rs
ed6d4217bcd29d58738224c1314f16020e73f228
use log::{debug, error, info}; use crate::dms; use crate::library::get_dms_media_library; use crate::library::get_local_media_library; use crate::library::LibraryFile; use crate::library::LibrarySource; use crate::utils::crypto::sha256sum; use crate::utils::fs::copy_mtime; use rayon::prelude::*; use std::collections...
use log::{debug, error, info}; use crate::dms; use crate::library::get_dms_media_library; use crate::library::get_local_media_library; use crate::library::LibraryFile; use crate::library::LibrarySource; use crate::utils::crypto::sha256sum; use crate::utils::fs::copy_mtime; use rayon::prelude::*; use std::collections...
fn copy_files(files: &Vec<&LibraryFile>, local: &BTreeSet<LibraryFile>, dms_dir: &Path) { for file in files { let (source, dest) = ( &local.get(file).unwrap().path, Path::join(&dms_dir, Path::new(&file.debase())), ); debug!( "Copying local file {} to DMS...
pub fn synchronize_media_files() { info!("Synchronizing media files with DMS..."); let local_dir = Path::join( Path::new(&match env::var("HOME") { Ok(value) => value, Err(e) => { error!("Unable to detect home directory: {}", e); process::exit(1); ...
function_block-full_function
[ { "content": "pub fn is_dms_present() -> bool {\n\n get_dms_device().is_some()\n\n}\n\n\n", "file_path": "src/dms.rs", "rank": 2, "score": 86054.32286933367 }, { "content": "pub fn is_dms_mounted() -> bool {\n\n get_dms_mount_point().is_some()\n\n}\n\n\n", "file_path": "src/dms.rs"...
Rust
crates/fefix/src/session/config.rs
ferrumfix/ferrumfix
36b40f3d34cc9af46acc7f60d2f3ae517fa8c0ee
use super::{Environment, MsgSeqNumCounter, SeqNumbers}; use std::marker::PhantomData; use std::num::NonZeroU64; use std::time::Duration; pub trait Configure: Clone + Default { fn verify_test_indicator(&self) -> bool { true } fn max_allowed_latency(&self) -> Duration { D...
use super::{Environment, MsgSeqNumCounter, SeqNumbers}; use std::marker::PhantomData; use std::num::NonZeroU64; use std::time::Duration; pub trait Configure: Clone + Default { fn verify_test_indicator(&self) -> bool { true } fn max_allowed_latency(&self) -> Duration { D...
wrap()), msg_seq_num_inbound: MsgSeqNumCounter::START, msg_seq_num_outbound: MsgSeqNumCounter::START, sender_comp_id: "SENDER_COMP".to_string(), target_comp_id: "TARGET_COMP".to_string(), } } } #[cfg(test)] mod test { use super::*; use quickcheck_macr...
r: bool, pub max_allowed_latency: Duration, pub begin_string: String, pub environment: Environment, pub heartbeat: Duration, pub seq_numbers: SeqNumbers, pub msg_seq_num_inbound: MsgSeqNumCounter, pub msg_seq_num_outbound: MsgSeqNumCounter, pub sender_comp_id: String, pub target_comp...
random
[ { "content": "/// A provider of configuration options related to FIX encoding and decoding.\n\n///\n\n/// # Implementing this trait\n\n///\n\n/// Before implementing this trait, you should look into [`Config`], which is\n\n/// adequate for most uses. The only benefit of writing your own [`Configure`]\n\n/// imp...
Rust
ivy-graphics/build.rs
ten3roberts/ivy
fb5a7645c9f699c2aebf3d1b90c1d1f9e78355fa
use anyhow::{Context, Result}; use shaderc::ShaderKind; use std::{ env, error::Error, ffi::OsString, fs, path::{Path, PathBuf}, slice, }; #[derive(Debug)] struct CompilationFailure(PathBuf); impl Error for CompilationFailure {} impl std::fmt::Display for CompilationFailure { fn fmt(&self,...
use anyhow::{Context, Result}; use shaderc::ShaderKind; use std::{ env, error::Error, ffi::OsString, fs, path::{Path, PathBuf}, slice, }; #[derive(Debug)] struct CompilationFailure(PathBuf); impl Error for CompilationFailure {} impl std::fmt::Display for CompilationFailure { fn fmt(&self,...
; let bin = binary_result.as_binary(); let data = bin.as_ptr() as *const u8; let bin = unsafe { slice::from_raw_parts(data, bin.len() * 4) }; fs::write(dst, bin)?; Ok(()) } fn main() -> Result<()> { let out_dir = env::var("OUT_DIR")?; let mut dst = PathBuf::new(); dst.push(out_di...
ing_lossy(), "main", Some(&options), )?; assert_eq!(Some(&0x07230203), binary_result.as_binary().first())
random
[ { "content": "fn read_to_end<P>(path: P) -> Result<Vec<u8>>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let file = fs::File::open(path.as_ref()).map_err(Error::Io)?;\n\n // Allocate one extra byte so the buffer doesn't need to grow before the\n\n // final `read` call at the end of the file. Don't worry a...
Rust
crates/sim1h/src/dht/bbdht/dynamodb/api/aspect/write.rs
jamesray1/sim1h
a3c7f43bd1fd45647d23667d451fecd07e144ce3
use crate::dht::bbdht::dynamodb::api::item::write::should_put_item_retry; use crate::dht::bbdht::dynamodb::client::Client; use crate::dht::bbdht::dynamodb::schema::blob_attribute_value; use crate::dht::bbdht::dynamodb::schema::cas::ADDRESS_KEY; use crate::dht::bbdht::dynamodb::schema::cas::ASPECT_ADDRESS_KEY; use crate...
use crate::dht::bbdht::dynamodb::api::item::write::should_put_item_retry; use crate::dht::bbdht::dynamodb::client::Client; use crate::dht::bbdht::dynamodb::schema::blob_attribute_value; use crate::dht::bbdht::dynamodb::schema::cas::ADDRESS_KEY; use crate::dht::bbdht::dynamodb::schema::cas::ASPECT_ADDRESS_KEY; use crate...
&log_context, &local_client, &table_name, &entry_address, &aspect_list ) .is_ok()); match get_item_by_address(&log_context, &local_client, &table_name, &entry_address) { Ok(g...
); assert!(ensure_cas_table(&log_context, &local_client, &table_name).is_ok()); assert!(table_exists(&log_context, &local_client, &table_name).is_ok()); for _ in 0..3 { assert!(append_aspect_list_to_entry(
function_block-random_span
[ { "content": "pub fn try_aspect_list_from_item(item: Item) -> BbDhtResult<Vec<Address>> {\n\n let addresses = match get_or_err(&item, ASPECT_LIST_KEY)?.ss.clone() {\n\n Some(addresses) => addresses.iter().map(|s| Address::from(s.clone())).collect(),\n\n None => {\n\n return Err(BbDht...
Rust
src/process.rs
berkus/fectl
bcd4137848f1c4fdbf24753e23f6030be79cce9c
#![allow(dead_code)] use std; use std::io; use std::error::Error; use std::os::unix::io::RawFd; use std::time::{Duration, Instant}; use serde_json as json; use byteorder::{ByteOrder, BigEndian}; use bytes::{BytesMut, BufMut}; use tokio_io::AsyncRead; use tokio_io::io::WriteHalf; use tokio_io::codec::{FramedRead, Enco...
#![allow(dead_code)] use std; use std::io; use std::error::Error; use std::os::unix::io::RawFd; use std::time::{Duration, Instant}; use serde_json as json; use byteorder::{ByteOrder, BigEndian}; use bytes::{BytesMut, BufMut}; use tokio_io::AsyncRead; use tokio_io::io::WriteHalf; use tokio_io::codec::{FramedRead, Enco...
} pub struct TransportCodec; impl Decoder for TransportCodec { type Item = ProcessMessage; type Error = io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { let size = { if src.len() < 2 { return Ok(None) } ...
self.kill(ctx, true); } else { self.kill(ctx, false); let _ = kill(self.pid, Signal::SIGKILL); ctx.terminate(); } }
function_block-function_prefix_line
[ { "content": "/// Start master process\n\npub fn start(cfg: Config) -> bool {\n\n // init logging\n\n logging::init_logging(&cfg.logging);\n\n\n\n info!(\"Starting fectl process\");\n\n\n\n // change working dir\n\n if let Err(err) = nix::unistd::chdir::<OsStr>(cfg.master.directory.as_ref()) {\n\...
Rust
day18b/src/main.rs
LinAGKar/advent-of-code-2019-rust
f1de4d408f1c331f49a0928cf5abd733a3e15bb6
use std::cmp::Reverse; use std::collections::{BinaryHeap, HashSet}; use std::io::Read; #[derive(PartialEq)] enum Tile { Wall, Floor, Door(usize), Key(usize), } fn get_shortest_paths(map: &Vec<Vec<Tile>>, start: (i8, i8)) -> Vec<Vec<(u16, u32)>> { let mut queue = BinaryHeap::new(); let mut visi...
use std::cmp::Reverse; use std::collections::{BinaryHeap, HashSet}; use std::io::Read; #[derive(PartialEq)] enum Tile { Wall, Floor, Door(usize), Key(usize), } fn get_shortest_paths(map: &Vec<Vec<Tile>>, start: (i8, i8)) -> Vec<Vec<(u16, u32)>> { let mut queue = BinaryHeap::new(); let mut visi...
d_keys |= 1 << door; } Tile::Wall => { continue; } Tile::Floor => {} Tile::Key(key) => { shortest_paths[key as usize].push((cost, needed_keys)); needed_keys |= 1 << key; } } for (dy, dx) in &[ (-1, ...
tart)); while let Some((_, mut needed_keys, cost, pos)) = queue.pop() { let (y, x) = pos; let visited_this = &mut visited[y as usize][x as usize]; if visited_this.iter().any(|&old_needed_keys| needed_keys & old_needed_keys == old_needed_keys) { continue; } visit...
function_block-random_span
[ { "content": "fn get_shortest_paths(map: &Vec<Vec<Tile>>, start: (i8, i8)) -> Vec<Vec<(u16, u32)>> {\n\n let mut queue = BinaryHeap::new();\n\n let mut visited: Vec<Vec<_>> = map.iter().map(|row| {\n\n row.iter().map(|_| Vec::new()).collect()\n\n }).collect();\n\n let mut shortest_paths = vec...
Rust
src/server/main.rs
brennie/chat
dfeec8c61f6f7f8a603241e055a4e214195cc2b0
extern crate chat_common; extern crate failure; extern crate futures; extern crate serde; #[macro_use] extern crate slog; extern crate slog_async; extern crate slog_term; extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate tokio; extern crate tokio_io; use std::net::IpAddr; use futures::f...
extern crate chat_common; extern crate failure; extern crate futures; extern crate serde; #[macro_use] extern crate slog; extern crate slog_async; extern crate slog_term; extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate tokio; extern crate tokio_io; use std::net::IpAddr; use futures::f...
) .and_then({ let log = log.clone(); move |(msg, _stream)| match msg { Goodbye(GoodbyeMessage { reason }) => { info!(log, "Client disconnected."; "reason" => ?reason); Ok(future::Loop:...
match maybe_msg { Some(msg) => future::ok((msg, stream)), None => future::err(failure::err_msg("Client unexpectedly closed connection.")), }
if_condition
[ { "content": "fn read_loop(recv: Recv<messages::server::ServerMessage>) -> impl Future<Item = (), Error = failure::Error>\n\n{\n\n use messages::server::{*, ServerMessage::*, ServerMessageKind::*};\n\n\n\n recv.map_err(|err| err.into())\n\n .for_each(|msg| {\n\n match msg {\n\n ...
Rust
src/config.rs
OtaK/vivid
ecaf0c95e2334971e0acc05ea572bec488d85f6f
use crate::error::VividError; use winapi::{ shared::ntdef::NULL, um::{shellapi::ShellExecuteA, winuser::SW_SHOWNORMAL}, }; pub const DEFAULT_CONFIG_FILENAME: &str = "vivid.toml"; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct VideoMode { pub width: u32, pub height: ...
use crate::error::VividError; use winapi::{ shared::ntdef::NULL, um::{shellapi::ShellExecuteA, winuser::SW_SHOWNORMAL}, }; pub const DEFAULT_CONFIG_FILENAME: &str = "vivid.toml"; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct VideoMode { pub width: u32, pub height: ...
; } } pub fn vibrance_for_program(&self, program_exe: &str) -> Option<(u8, bool)> { self.program_settings .iter() .find(|&program| program.exe_name == program_exe) .map(|program| { ( program.vibrance, pr...
file_path.as_ptr(), NULL as _, NULL as _, SW_SHOWNORMAL, ) }; if hwnd as u32 > 32 { Ok(()) } else { return Err(VividError::windows_error())
function_block-random_span
[ { "content": "#[inline(always)]\n\nfn dll_exists(path: *const winapi::ctypes::c_char) -> bool {\n\n let hwnd = unsafe {\n\n winapi::um::libloaderapi::LoadLibraryExA(\n\n path,\n\n winapi::shared::ntdef::NULL,\n\n winapi::um::libloaderapi::LOAD_LIBRARY_AS_DATAFILE\n\n ...
Rust
adapter/deps/lldb/src/sb/sbdata.rs
naari3/vscode-lldb
bed54848119cb0e8846ed198c5bfd652f650922b
use super::*; use std::marker::PhantomData; cpp_class!(unsafe struct _SBData as "SBData"); unsafe impl Send for _SBData {} #[repr(transparent)] pub struct SBData<'a> { _inner: _SBData, _marker: PhantomData<&'a ()>, } pub type SBDataOwned = SBData<'static>; impl<'b> SBData<'b> { pub fn new() -> SBDataOw...
use super::*; use std::marker::PhantomData; cpp_class!(unsafe struct _SBData as "SBData"); unsafe impl Send for _SBData {} #[repr(transparent)] pub struct SBData<'a> { _inner: _SBData, _marker: PhantomData<&'a ()>, } pub type SBDataOwned = SBData<'static>; impl<'b> SBData<'b> { pub fn new() -> SBDataOw...
} } #[derive(Clone, Copy, Eq, PartialEq, Debug)] #[repr(u32)] pub enum ByteOrder { Invalid = 0, Big = 1, PDP = 2, Little = 4, }
debug_descr(f, |descr| { cpp!(unsafe [self as "SBData*", descr as "SBStream*"] -> bool as "bool" { return self->GetDescription(*descr); }) })
call_expression
[ { "content": "// The returned FILE takes ownership of file's descriptor.\n\npub fn cfile_from_file(file: File, write: bool) -> Result<*mut FILE, SBError> {\n\n #[cfg(unix)]\n\n let fd = file.into_raw_fd() as isize;\n\n #[cfg(windows)]\n\n let fd = file.into_raw_handle() as isize;\n\n\n\n let mut ...
Rust
src/once.rs
tiqwab/xv6-rust
525899393df10855a274ce0a9d4e5841aa032aeb
use core::cell::UnsafeCell; use core::fmt; use core::fmt::Formatter; use core::hint::unreachable_unchecked as unreachable; use core::sync::atomic::{spin_loop_hint as cpu_relax, AtomicUsize, Ordering}; pub(crate) struct Once<T> { state: AtomicUsize, data: UnsafeCell<Option<T>>, } impl<T: fmt::Debug> fmt::Deb...
use core::cell::UnsafeCell; use core::fmt; use core::fmt::Formatter; use core::hint::unreachable_unchecked as unreachable; use core::sync::atomic::{spin_loop_hint as cpu_relax, AtomicUsize, Ordering}; pub(crate) struct Once<T> { state: AtomicUsize, data: UnsafeCell<Option<T>>, } impl<T: fmt::Debug> fmt::Deb...
pub fn call_once<F: FnOnce() -> T>(&self, builder: F) -> &T { let mut status = self.state.load(Ordering::SeqCst); if status == INCOMPLETE { ...
fn force_get(&self) -> &T { match unsafe { &*self.data.get() }.as_ref() { None => unsafe { unreachable() }, Some(p) => p, } }
function_block-full_function
[ { "content": "/// Modify mappings in kern_pgdir to support SMP\n\n/// - Map the per-CPU stacks in the region [KSTACKTOP-PTSIZE, KSTACKTOP)\n\nfn mem_init_mp(kern_pgdir: &mut PageDirectory, allocator: &mut PageAllocator) {\n\n // Map per-CPU stacks starting at KSTACKTOP, for up to 'NCPU' CPUs.\n\n //\n\n...
Rust
src/server/agents.rs
bofh69/crater
29d2aebfa4723bba8e64889e728953d223418447
use chrono::Duration; use chrono::{DateTime, Utc}; use db::{Database, QueryUtils}; use errors::*; use experiments::{Assignee, Experiment}; use server::tokens::Tokens; use std::collections::HashSet; const INACTIVE_AFTER: i64 = 300; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum AgentStatus { Working, Id...
use chrono::Duration; use chrono::{DateTime, Utc}; use db::{Database, QueryUtils}; use errors::*; use experiments::{Assignee, Experiment}; use server::tokens::Tokens; use std::collections::HashSet; const INACTIVE_AFTER: i64 = 300; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum AgentStatus { Working, Id...
} pub fn record_heartbeat(&self, agent: &str) -> Result<()> { let changes = self.db.execute( "UPDATE agents SET last_heartbeat = ?1 WHERE name = ?2;", &[&Utc::now(), &agent], )?; assert_eq!(changes, 1); Ok(()) } pub fn set_git_revision(&self, a...
Ok(if let Some(agent) = row { Some(agent.with_experiment(&self.db)?) } else { None })
call_expression
[ { "content": "pub fn execute(db: &mut Connection) -> Result<()> {\n\n // If the database version is 0, create the migrations table and bump it\n\n let version: i32 = db.query_row(\"PRAGMA user_version;\", &[], |r| r.get(0))?;\n\n if version == 0 {\n\n db.execute(\"CREATE TABLE migrations (name T...
Rust
src/main.rs
museun/tinge
aee80a24bcb7ba868934f21a7c5b0eb33c4d0243
use filetime::FileTime; use std::fs::{self, File}; use std::path::Path; const USAGE: &str = " tinge. change file access and modification times Usage: tinge [-acm] [-r <file>] <file>> Options: -a Change access time -c Do not create file if it exists -m Change modification ti...
use filetime::FileTime; use std::fs::{self, File}; use std::path::Path; const USAGE: &str = " tinge. change file access and modification times Usage: tinge [-acm] [-r <file>] <file>> Options: -a Change access time -c Do not create file if it exists -m Change modification ti...
y) { (true, false) => (tatime, fmtime), (false, true) => (fatime, tmtime), (true, true) => (tatime, tmtime), _ => return, }; let _ = filetime::set_file_times(file, access, modify); }
function_block-function_prefixed
[]
Rust
day16/src/main.rs
obi1kenobi/advent-of-code-2020
51f1c462642dc59eae8fadf26cc635bce063678d
use std::{ collections::{HashMap, HashSet}, fs, }; fn main() { let contents = fs::read_to_string( "/mnt/c/Users/predrag/Dropbox/Documents/Code/advent-of-code-2020/day16/input.txt", ) .unwrap(); let groups: Vec<_> = contents.trim().split("\n\n").collect(); let fields_info = groups[0...
use std::{ collections::{HashMap, HashSet}, fs, }; fn main() { let contents = fs::read_to_string( "/mnt/c/Users/predrag/Dropbox/Documents/Code/advent-of-code-2020/day16/input.txt", ) .unwrap(); let groups: Vec<_> = contents.trim().split("\n\n").collect(); let fields_info = groups[0...
fn solve_part1( field_valid_rules: &Vec<(i64, i64)>, nearby_tickets: &Vec<Vec<i64>>, ) -> (i64, Vec<Vec<i64>>) { let mut result: i64 = 0; let mut valid_tickets: Vec<Vec<i64>> = Vec::new(); for nearby_ticket in nearby_tickets { let mut is_valid_ticket = true; for value in nearby_ti...
let your_ticket_info = groups[1]; let nearby_tickets_info = groups[2]; let fields: Vec<_> = fields_info.trim().split("\n").collect(); let field_valid_ranges: Vec<_> = fields .iter() .map(|&x| x.split(": ").last().unwrap()) .flat_map(|x| x.split(" or ")) .collect(); let f...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let contents = fs::read_to_string(\n\n \"/mnt/c/Users/predrag/Dropbox/Documents/Code/advent-of-code-2020/day24/input.txt\",\n\n )\n\n .unwrap();\n\n\n\n let all_directions: Vec<_> = contents.trim().split('\\n').map(parse_directions).collect();\n\n\n\n println!...
Rust
benches/benchmarks/bench_curve.rs
algorand/pixel
7c90f8162d6b8c879f795cf1d2d29350abeb0a96
use super::ff::Field; use super::pairing::{bls12_381::*, CurveAffine, CurveProjective, Engine, SubgroupCheck}; use super::pixel::{PixelG1, PixelG2}; use super::rand_core::*; use super::rand_xorshift::XorShiftRng; use criterion::Criterion; #[allow(dead_code)] fn bench_group_multiplication(c: &mut Criterion) { const...
use super::ff::Field; use super::pairing::{bls12_381::*, CurveAffine, CurveProjective, Engine, SubgroupCheck}; use super::pixel::{PixelG1, PixelG2}; use super::rand_core::*; use super::rand_xorshift::XorShiftRng; use criterion::Criterion; #[allow(dead_code)] fn bench_group_multiplication(c: &mut Criterion) { const...
#[allow(dead_code)] fn bench_membership_testing(c: &mut Criterion) { const SAMPLES: usize = 100; let mut g1list: Vec<PixelG1> = vec![]; let mut g2list: Vec<PixelG2> = vec![]; let mut rng = XorShiftRng::from_seed([ 0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0...
r(|| { g1list[counter].mul_assign(r1list[counter]); counter = (counter + 1) % SAMPLES; }) }); let mut counter = 0; c.bench_function("Pixel G2 muliplication cost", move |b| { b.iter(|| { g2list[counter].mul_assign(r2list[counter]); counter = (c...
function_block-function_prefixed
[ { "content": "// Convert a vector back to time.\n\n// Returns an error if time depth is invalid.\n\nfn vec_to_time(mut t_vec: Vec<u64>, d: usize) -> Result<u64, String> {\n\n // python code:\n\n // if tvec == []:\n\n // return 1\n\n // else:\n\n // ti = tvec.pop(0)\n\n //...
Rust
src/signal.rs
Emilgardis/fundsp
213f5ae89ac454c791c731075c323b939dcc476c
use super::math::*; use num_complex::Complex64; use tinyvec::TinyVec; #[derive(Clone, Copy)] pub enum Signal { Unknown, Value(f64), Latency(f64), Response(Complex64, f64), } impl Default for Signal { fn default() -> Signal { Signal::Unknown } } impl Signal {...
use super::math::*; use num_complex::Complex64; use tinyvec::TinyVec; #[derive(Clone, Copy)] pub enum Signal { Unknown, Value(f64), Latency(f64), Response(Complex64, f64), } impl Default for Signal { fn default() -> Signal { Signal::Unknown } } impl Signal {...
pub fn delay(&self, latency: f64) -> Signal { match self { Signal::Latency(l) => Signal::Latency(l + latency), Signal::Response(response, l) => Signal::Response(*response, l + latency), x => *x, } } pub fn scale(&self, factor: f64) -> Signal {...
ignal { match self { Signal::Latency(l) => Signal::Latency(l + latency), Signal::Response(_, l) => Signal::Latency(l + latency), _ => Signal::Unknown, } }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn shape_fn<S: Fn(f64) -> f64>(f: S) -> An<ShaperFn<f64, S>> {\n\n super::prelude::shape_fn(f)\n\n}\n\n\n\n/// Shape signal.\n", "file_path": "src/hacker.rs", "rank": 0, "score": 177753.0561621905 }, { "content": "#[inline]\n\npub fn declick_s(t: f64) -> An<...
Rust
src/connection/peer_provider/k8s.rs
chenfisher/c19-1
f7f22aadb325d218ff24b754c5858aa567ec097b
use crate::connection::peer_provider::{PeerProvider, Peer}; use futures::{StreamExt, TryStreamExt}; use k8s_openapi::api::core::v1::Pod; use kube::{ api::{Api, ListParams, Meta, WatchEvent}, Client, }; use log::error; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::{Arc, RwL...
use crate::connection::peer_provider::{PeerProvider, Peer}; use futures::{StreamExt, TryStreamExt}; use k8s_openapi::api::core::v1::Pod; use kube::{ api::{Api, ListParams, Meta, WatchEvent}, Client, }; use log::error; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::{Arc, RwL...
.values() .map(|value| value.clone()) .collect() } }
rs.clone(); let namespace = self.namespace.clone(); tokio::spawn(async move { let client = Client::try_default().await?; let pods: Api<Pod> = if namespace == ":all" { Api::all(client) } else { Api::namespaced(client, namespace.as_ref()...
random
[ { "content": "/// Initializes the state and runs the connection and agent layers.\n\n///\n\n/// The state is given a chance to be initialized by running state::init\n\n/// on the instance. The connection and agent layers are then started while\n\n/// given the initialized state.\n\n///\n\n/// The instances for ...
Rust
Usermode/fileviewer/src/main.rs
ids1024/rust_os
236dfdca5660372ea6d4c3f1eea463dbd2c2945d
extern crate wtk; #[macro_use(kernel_log)] extern crate syscalls; mod hexview; mod textview; struct Viewer<'a> { dims: ::std::cell::RefCell<(u32, u32)>, file: ::std::cell::RefCell<&'a mut ::syscalls::vfs::File>, mode: ViewerMode, vscroll: ::wtk::ScrollbarV, hscroll: ::wtk::ScrollbarH, hex: ::hexview::Widget,...
extern crate wtk; #[macro_use(kernel_log)] extern crate syscalls; mod hexview; mod textview; struct Viewer<'a> { dims: ::std::cell::RefCell<(u32, u32)>, file: ::std::cell::RefCell<&'a mut ::syscalls::vfs::File>, mode: ViewerMode, vscroll: ::wtk::ScrollbarV, hscroll: ::wtk::ScrollbarH, hex: ::hexview::Widget,...
}
if x > vscroll_pos.x.0 { self.vscroll.with_element_at_pos(pos - vscroll_pos, ::wtk::geom::PxDims::new(SCROLL_SIZE, body_dims.h.0), f) } else { match self.mode { ViewerMode::Hex => self.hex.with_element_at_pos(pos, body_dims, f), ViewerMode::Text => self.text.with_element_at_pos(pos, body_dims...
function_block-function_prefix_line
[ { "content": "#[inline(never)]\n\npub fn call_object_ref(handle: u32, call: u16, args: &mut Args) -> Result<u64,super::Error>\n\n{\n\n\t// Obtain reference/borrow to object (individually locked), and call the syscall on it\n\n\tget_process_local::<ProcessObjects>().with_object(handle, |obj| {\n\n\t\t//log_trace...
Rust
vchain/src/acc/mod.rs
hkbudb/vchain-demo
8e12ac2d1a3b38cb7009f400b8601b6bfc28f23d
pub mod digest_set; pub mod serde_impl; pub mod utils; pub use ark_bls12_381::{ Bls12_381 as Curve, Fq12, Fr, G1Affine, G1Projective, G2Affine, G2Projective, }; pub type DigestSet = digest_set::DigestSet<Fr>; use crate::digest::{Digest, Digestible}; use crate::set::{MultiSet, SetElement}; use anyhow::{self, bail,...
pub mod digest_set; pub mod serde_impl; pub mod utils; pub use ark_bls12_381::{ Bls12_381 as Curve, Fq12, Fr, G1Affine, G1Projective, G2Affine, G2Projective, }; pub type DigestSet = digest_set::DigestSet<Fr>; use crate::digest::{Digest, Digestible}; use crate::set::{MultiSet, SetElement}; use anyhow::{self, bail,...
.map(|i| <Fr as PrimeField>::BigInt::from(product[i].1)) .collect_into_vec(&mut scalars); let f = VariableBaseMSM::multi_scalar_mul(&bases[..], &scalars[..]).into_affine(); Ok(Acc2Proof { f }) } } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub enum Proof { ACC...
ine) -> bool { Curve::product_of_pairings(&[ ((*acc1).into(), self.f1.into()), ((*acc2).into(), self.f2.into()), ]) == *E_G_G } } impl Accumulator for Acc1 { const TYPE: Type = Type::ACC1; type Proof = Acc1Proof; fn cal_acc_g1_sk_d(set: &DigestSet) -> G1Affine {...
random
[ { "content": "pub trait SetElement: Digestible + Clone + Send + Sync + Eq + PartialEq + core::hash::Hash {}\n\n\n\nimpl<T> SetElement for T where\n\n T: Digestible + Clone + Send + Sync + Eq + PartialEq + core::hash::Hash\n\n{\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq, Default)]\n\npub struct MultiSet...
Rust
src/sink.rs
ollien/hline
f08d7277003e7428a577e357fe18cc7012391fc2
use crate::print; use crate::print::{Printer, StdoutPrinter}; use grep::searcher::{Searcher, Sink, SinkContext, SinkError, SinkMatch}; use std::fmt::Display; use std::io; use std::panic; use termion::color::{Fg, LightRed}; use thiserror::Error; const PASSTHRU_PANIC_MSG: &str = "passthru is not enabled on the given se...
use crate::print; use crate::print::{Printer, StdoutPrinter}; use grep::searcher::{Searcher, Sink, SinkContext, SinkError, SinkMatch}; use std::fmt::Display; use std::io; use std::panic; use termion::color::{Fg, LightRed}; use thiserror::Error; const PASSTHRU_PANIC_MSG: &str = "passthru is not enabled on the given se...
}
let search_res = perform_search(); assert!(search_res.is_ok()); } else { let search_res = panic::catch_unwind(perform_search); assert!(search_res.is_err()); match search_res.unwrap_err().downcast_ref::<String>() { Some(err...
function_block-function_prefix_line
[ { "content": "/// `scan_pattern_to_printer` will print a `Read`'s contents to the given `Printer`, while also scanning its contents\n\n/// for a regular expression. Lines that match this pattern will be highlighted in the output.\n\n///\n\n/// Note that this pattern is not anchored at the start of the line by d...
Rust
consensus/safety-rules/src/persistent_safety_storage.rs
pepenemo/libra
86a42bc1f1113868ee8c4815f0d3a137a923ed52
use crate::{ counters, logging::{self, LogEntry, LogEvent, LogField}, }; use anyhow::Result; use consensus_types::{common::Author, safety_data::SafetyData}; use libra_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; use libra_global_constants::{CONSENSUS_KEY, EXECUTION_KEY, OWNER_ACCOUNT, SAFETY_DATA, ...
use crate::{ counters, logging::{self, LogEntry, LogEvent, LogField}, }; use anyhow::Result; use consensus_types::{common::Author, safety_data::SafetyData}; use libra_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey}; use libra_global_constants::{CONSENSUS_KEY, EXECUTION_KEY, OWNER_ACCOUNT, SAFETY_DATA, ...
} pub fn new(internal_store: Storage) -> Self { Self { internal_store } } pub fn author(&self) -> Result<Author> { let res = self.internal_store.get(OWNER_ACCOUNT)?; let res = res.value.string()?; std::str::FromStr::from_str(&res) } pub fn consensus_...
if let Storage::CachedStorage(cached_storage) = self.internal_store { PersistentSafetyStorage { internal_store: Storage::CachedStorage(cached_storage), } } else { PersistentSafetyStorage { internal_store: Storage::CachedStorage(CachedStorage::n...
if_condition
[ { "content": "/// Same as `to_bytes` but write directly into an `std::io::Write` object.\n\npub fn serialize_into<W, T>(write: &mut W, value: &T) -> Result<()>\n\nwhere\n\n W: std::io::Write,\n\n T: ?Sized + Serialize,\n\n{\n\n let serializer = Serializer::new(write, crate::MAX_CONTAINER_DEPTH);\n\n ...
Rust
src/pdu/hex_access/write_multi_reg.rs
hubertmis/modbus
430c6204070d7fd27fc639c08475b3b3079edeaa
use crate::Error; use crate::pdu::{Function, FunctionCode, Request as ReqT, Response as RspT, Setter}; use std::convert::TryInto; const MIN_QUANTITY: usize = 1; const MAX_QUANTITY: usize = 123; #[derive(Debug, PartialEq)] pub struct Request { address: u16, values: Vec<u16>, } impl Request { ...
use crate::Error; use crate::pdu::{Function, FunctionCode, Request as ReqT, Response as RspT, Setter}; use std::convert::TryInto; const MIN_QUANTITY: usize = 1; const MAX_QUANTITY: usize = 123; #[derive(Debug, PartialEq)] pub struct Request { address: u16, values: Vec<u16>, } impl Request { ...
fn decode(data: &[u8]) -> Result<Self, Error> { if data.len() != 5 { return Err(Error::InvalidDataLength); } if data[0] != FunctionCode::WriteMultiReg as u8 { return Err(Error::InvalidData); } let address = u16::from_be_bytes(data[1..=2].try...
end(&mut self.quantity.to_be_bytes().to_vec()); Ok(result) } _ => Err(Error::InvalidValue) } }
function_block-function_prefixed
[ { "content": "/// Setter is a trait for Modbus requests that expect known response.\n\npub trait Setter where Self: Request, Self::Rsp: PartialEq {\n\n fn create_expected_response(&self) -> Self::Rsp;\n\n}\n\n\n\n#[derive(Clone, Copy, FromPrimitive, IntoPrimitive, PartialEq)]\n\n#[repr(u8)]\n\npub enum Funct...
Rust
projects/rivium/src/lib.rs
chykon/rivium-mono
f7d45afbf94441a5f925ac8e3a2087f18f02e20c
/* const MEMORY_SIZE: usize = 1024 * 1024 * 512; const REGISTERS_COUNT: usize = 32 + 1; const CODE_RANGE_BEGIN: usize = 0; const CODE_RANGE_END: usize = CODE_RANGE_BEGIN + (1024 * 1024 * 128) - 1; static mut MEMORY: [u8; MEMORY_SIZE] = [0; MEMORY_SIZE]; static mut REGISTERS: [u32; REGISTERS_COUNT] = [0; REGISTERS_COU...
/* const MEMORY_SIZE: usize = 1024 * 1024 * 512; const REGISTERS_COUNT: usize = 32 + 1; const CODE_RANGE_BEGIN: usize = 0; const CODE_RANGE_END: usize = CODE_RANGE_BEGIN + (1024 * 1024 * 128) - 1; static mut MEMORY: [u8; MEMORY_SIZE] = [0; MEMORY_SIZE]; static mut REGISTERS: [u32; REGISTERS_COUNT] = [0; REGISTERS_COU...
nstruction & 0b11100) == 0b11100 { unsafe { ERROR_MESSAGE = "VM:DECODE_0B11100_END"; } return false } */ // move to dis ams //???? // fail -> error // execute // debug signal -> do // check pc-register increment if branch // ... set_to_register(PC, next_pc); true } */
_2.push_str(" x"); str_2.push_str(elem_str_2); str_2.push_str(", "); let mut str_3 = String::new(); str_3.push('x'); str_3.push_str(elem_str_3); str_3.push_str(", "); let mut str_4 = String::new(); str_4.push('x'); str_4.push_str(elem_str_4); ...
random
[ { "content": "class Memory {\n\n xlen;\n\n space; // maximum length in bytes, 2^XLEN\n\n vcount;\n\n mrcount;\n\n regres; // reserve for registers, MRCOUNT*XLEN*VCOUNT\n\n mempow;\n\n length; // actual length, (2^MEMPOW)-REGRES\n\n buffer; // memory data\n\n\n\n constructor(xlen, vcount, mrcount, mempo...
Rust
src/env/blocking.rs
quietboil/sibyl
bbb7cb28686d9d743252f1f28fb365eaaaad21a0
use super::Environment; use crate::{Session, ConnectionPool, Result, SessionPool}; impl Environment { /** Creates and begins a session for the given server. # Parameters * `dbname` - The TNS alias of the database to connect to. * `username` - The user ID with which to start the sessions. * ...
use super::Environment; use crate::{Session, ConnectionPool, Result, SessionPool}; impl Environment { /** Creates and begins a session for the given server. # Parameters * `dbname` - The TNS alias of the database to connect to. * `username` - The user ID with which to start the sessions. * ...
t_eq!(client_driver, "sibyl"); # Ok::<(),Box<dyn std::error::Error>>(()) ``` */ pub fn connect(&self, dbname: &str, username: &str, password: &str) -> Result<Session> { Session::new(self, dbname, username, password) } /** Creates new session pool. # Parameters * `dbname` -...
FROM v$session_connect_info WHERE sid = SYS_CONTEXT('USERENV', 'SID') ")?; let row = stmt.query_single(())?.unwrap(); let client_driver : &str = row.get_not_null(0)?; asser
random
[ { "content": "#[cfg(feature=\"blocking\")]\n\nfn main() -> sibyl::Result<()> {\n\n use std::{env, thread, sync::Arc};\n\n use once_cell::sync::OnceCell;\n\n use sibyl::*;\n\n\n\n static ORACLE : OnceCell<Environment> = OnceCell::new();\n\n let oracle = ORACLE.get_or_try_init(|| {\n\n env()...
Rust
botan/src/utils.rs
JustPretender/botan-rs
bdf1de579913cb0b8a07024e8a4015a3719195ee
use botan_sys::*; use core::fmt; #[cfg(feature = "no-std")] pub(crate) use alloc::{borrow::ToOwned, string::String, string::ToString, vec::Vec}; #[cfg(feature = "no-std")] pub(crate) use cstr_core::{CStr, CString}; #[cfg(not(feature = "no-std"))] pub(crate) use std::ffi::{CStr, CString}; pub(crate) use core::mem; p...
use botan_sys::*; use core::fmt; #[cfg(feature = "no-std")] pub(crate) use alloc::{borrow::ToOwned, string::String, string::ToString, vec::Vec}; #[cfg(feature = "no-std")] pub(crate) use cstr_core::{CStr, CString}; #[cfg(not(feature = "no-std"))] pub(crate) use std::ffi::{CStr, CString}; pub(crate) use core::mem; p...
=> Self::NullPointer, BOTAN_FFI_ERROR_OUT_OF_MEMORY => Self::OutOfMemory, BOTAN_FFI_ERROR_SYSTEM_ERROR => Self::SystemError, BOTAN_FFI_ERROR_TLS_ERROR => Self::TlsError, BOTAN_FFI_ERROR_UNKNOWN_ERROR => Self::UnknownError, BOTAN_FFI_INVALID_VERIFIER => Self::...
} pub(crate) fn call_botan_ffi_returning_vec_u8( initial_size: usize, cb: &dyn Fn(*mut u8, *mut usize) -> c_int, ) -> Result<Vec<u8>> { let mut output = vec![0; initial_size]; let mut out_len = output.len(); let rc = cb(output.as_mut_ptr(), &mut out_len); if rc == 0 { assert!(out_len <...
random
[ { "content": "/// Verify a bcrypt password hash\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// let mut rng = botan::RandomNumberGenerator::new().unwrap();\n\n/// let bcrypt = botan::bcrypt_hash(\"password\", &mut rng, 10).unwrap();\n\n/// assert_eq!(botan::bcrypt_verify(\"not even close\", &bcrypt), Ok(false...
Rust
src/ledc/lstimer3_conf.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
#[doc = "Reader of register LSTIMER3_CONF"] pub type R = crate::R<u32, super::LSTIMER3_CONF>; #[doc = "Writer for register LSTIMER3_CONF"] pub type W = crate::W<u32, super::LSTIMER3_CONF>; #[doc = "Register LSTIMER3_CONF `reset()`'s with value 0"] impl crate::ResetValue for super::LSTIMER3_CONF { type Type = u32; ...
#[doc = "Reader of register LSTIMER3_CONF"] pub type R = crate::R<u32, super::LSTIMER3_CONF>; #[doc = "Writer for register LSTIMER3_CONF"] pub type W = crate::W<u32, super::LSTIMER3_CONF>; #[doc = "Register LSTIMER3_CONF `reset()`'s with value 0"] impl crate::ResetValue for super::LSTIMER3_CONF { type Type = u32; ...
[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) ->...
bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `TICK_SEL_LSTIMER3`"] pub type TICK_SEL_LSTIMER3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TICK_SEL_LSTIMER3`"] pub struct TICK_SEL...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/node_state/mod.rs
frugalos/raftlog
25d663b3e8eda35224cd666e1f1ef05b44ace884
use futures::{Async, Poll, Stream}; use std::time::Instant; pub use self::common::Common; use self::candidate::Candidate; use self::common::HandleMessageResult; use self::follower::Follower; use self::leader::Leader; use self::loader::Loader; use crate::cluster::ClusterConfig; use crate::message::Message; use crate::...
use futures::{Async, Poll, Stream}; use std::time::Instant; pub use self::common::Common; use self::candidate::Candidate; use self::common::HandleMessageResult; use self::follower::Follower; use self::leader::Leader; use self::loader::Loader; use crate::cluster::ClusterConfig; use crate::message::Message; use crate::...
Leader(Leader<IO>), } impl<IO: Io> RoleState<IO> { pub fn is_loader(&self) -> bool { matches!(self, RoleState::Loader(_)) } #[cfg(test)] pub fn is_candidate(&self) -> bool { matches!(self, RoleState::Candidate(_)) } } #[cfg(test)] mod tests { use super::*; us...
et Some(message) = track!(self.common.try_recv_message())? { did_something = true; if let Some(next) = track!(self.handle_message(message))? { self.handle_role_change(next); } if let Some(e) = self.common.next_event() { ...
random
[ { "content": "fn make_role_change_histogram(builder: &mut HistogramBuilder) -> Result<Histogram> {\n\n builder\n\n .bucket(0.001)\n\n .bucket(0.005)\n\n .bucket(0.01)\n\n .bucket(0.05)\n\n .bucket(0.1)\n\n .bucket(0.2)\n\n .bucket(0.4)\n\n .bucket(0.6)\...
Rust
src/algebra/geometry.rs
hsnavarro/retrogame-rust
bc62342d95001b70a1d11c822f2722cfc0b73fec
use crate::algebra::{Vec2f, cross_product, distance, dot_product}; use crate::shapes; pub fn is_point_inside_rect(rect: &shapes::Rect, point: Vec2f) -> bool { let rect_points = rect.get_points_clockwise(); for i in 0..rect_points.len() { let j = (i + 1) % rect_points.len(); if cross_produ...
use crate::algebra::{Vec2f, cross_product, distance, dot_product}; use crate::shapes; pub fn is_point_inside_rect(rect: &shapes::Rect, point: Vec2f) -> bool { let rect_points = rect.get_points_clockwise(); for i in 0..rect_points.len() { let j = (i + 1) % rect_points.len(); if cross_produ...
t), ans); } #[test] fn point_in_rect_border() { let rect = Rect::create_rect(2.0, 10.0, 20.0, 10.0, Color::BLACK); let point = Vec2f { x: 12.0, y: 10.0 }; let ans = Vec2f { x: 12.0, y: 10.0 }; assert_eq!(closes...
ide_rect() { let rect = Rect::create_rect(2.0, 10.0, 10.0, 20.0, Color::BLACK); let point = Vec2f { x: 40.0, y: 40.0 }; assert!(is_point_inside_rect(&rect, point) == false); } #[test] fn point_inside_rect() { let rect = Rect::create_rect(2....
random
[ { "content": "pub fn distance(x: Vec2f, y: Vec2f) -> f64 {\n\n (x - y).square_magnitude()\n\n}\n\n\n", "file_path": "src/algebra/vec2f.rs", "rank": 1, "score": 116311.21337077796 }, { "content": "pub fn dot_product(lhs: Vec2f, rhs: Vec2f) -> f64 {\n\n lhs.x * rhs.x + lhs.y * rhs.y\n\n}...
Rust
src/system2/memory.rs
huhlig/vcpu16-rs
4fda8e36fbaae7dddb79f5cb96646205d36ef677
use std::char; use std::fmt; use std::io::{Read, Write}; use std::mem; use std::slice; use super::Word; use super::SystemError; #[derive(Clone)] pub struct Memory { buffer: [Word; 65536], } impl Memory { pub fn new() -> Memory { Memory { buffer: [0; 65536], } }...
use std::char; use std::fmt; use std::io::{Read, Write}; use std::mem; use std::slice; use super::Word; use super::SystemError; #[derive(Clone)] pub struct Memory { buffer: [Word; 65536], } impl Memory { pub fn new() -> Memory { Memory { buffer: [0; 65536], } }...
assert_eq!(&dirty_buffer[..], mem.read(read_address, 16).unwrap()); mem.clear(); assert_eq!(&empty_buffer[..], mem.read(read_address, 16).unwrap()); } #[test] pub fn test_set_get() { let mut mem = Memory::new(); let address: u16 = ...
size, ); writer.write(memory_slice).unwrap(); } } pub fn clear(&mut self) { self.buffer = [0; 65536]; } pub fn write(&mut self, address: Word, buffer: &[Word]) -> Result<(), SystemError> { if address as usize + buffer.len() > ...
random
[ { "content": "/// Memory Array\n\nstruct Memory {\n\n /// Memory Buffer\n\n buffer: [u16; 65536],\n\n}\n\n\n", "file_path": "src/system/cpu.rs", "rank": 0, "score": 69478.01755072441 }, { "content": "/// Internal Clock\n\nstruct Clock {\n\n /// Is CPU Halted\n\n halted: bool,\n\n...
Rust
program/programs/main-program-final/src/lib.rs
SOLBROS/SOLHUNT
d36a2779b88d500af285fd3ff3bfdb9b31d16ac8
use anchor_lang::prelude::*; use anchor_spl::token::{self, SetAuthority, TokenAccount, Transfer}; use spl_token::instruction::AuthorityType; #[program] pub mod main_program_final { use super::*; pub fn initialize(ctx: Context<Initialize>) -> ProgramResult { let my_account = &mut ctx.accounts.my_accoun...
use anchor_lang::prelude::*; use anchor_spl::token::{self, SetAuthority, TokenAccount, Transfer}; use spl_token::instruction::AuthorityType; #[program] pub mod main_program_final { use super::*; pub fn initialize(ctx: Context<Initialize>) -> ProgramResult { let my_account = &mut ctx.accounts.my_accoun...
enAccount>, #[account(mut)] pub admin_main_account: AccountInfo<'info>, #[account(mut)] pub pda_deposit_token_account: CpiAccount<'info, TokenAccount>, #[account( mut, constraint = escrow_account.admin_deposit_token_account == *pda_deposit_token_account.to_account_info().key, ...
ress(&[b"dungeon"], ctx.program_id); token::set_authority(ctx.accounts.into(), AuthorityType::AccountOwner, Some(pda))?; Ok(()) } pub fn update(ctx: Context<Update>, data: u64) -> ProgramResult { let my_account = &mut ctx.accounts.my_account; let amount = 20; if my_acco...
random
[]
Rust
src/config.rs
cmsd2/codelauf
69a590b4f0bb86ea4d50b9e229baddc8cb8d4c6a
use std::env; use clap::{App, SubCommand, ArgMatches}; use toml::{Table, Parser}; use std::io::{Read,Result,Error,ErrorKind}; use std::fs::File; use super::result::*; #[derive(Debug,Clone)] pub struct Config { pub data_dir: String, pub zookeeper: Option<String>, pub elasticsearch: Option<String>, pu...
use std::env; use clap::{App, SubCommand, ArgMatches}; use toml::{Table, Parser}; use std::io::{Read,Result,Error,ErrorKind}; use std::fs::File; use super::result::*; #[derive(Debug,Clone)] pub struct Config { pub data_dir: String, pub zookeeper: Option<String>, pub elasticsearch: Option<String>, pu...
} pub fn apply_config<'a,'b>(cfg: Config, args: &ArgMatches<'a,'b>) -> Config { let mut cfg = cfg; cfg.zookeeper = get_config_str_env(args, "ZOOKEEPER", "ZOOKEEPER") .or(cfg.zookeeper); cfg.elasticsearch = get_config_str_env(args, "ELASTICSEARCH", "ELASTICSEARCH") .or(cfg.elasticsear...
match env::var(name) { Ok(val) => Some(val), Err(e) => { info!("not using environment variable {}: {:?}", name, e); None } }
if_condition
[ { "content": "/// open db\n\n/// calc repo dir location\n\n/// create basic db entry if it doesn't exist\n\n/// clone project if it isn't already\n\n/// otherwise:\n\n/// check remote url matches\n\n/// fetch branch\n\n/// checkout branch\n\n/// update db as we go\n\npub fn fetch_repo(config: &Config) -> ...
Rust
src/lib.rs
mihail-milev/pam_blox
05086179dca40a5c46343dab814906c0fdc0cda4
#![allow(non_camel_case_types)] include!("pam_appl.rs"); use std::ffi::{CString, CStr}; use std::os::raw::{c_int, c_char}; use std::ptr; use std::process::Command; use regex::Regex; use std::fs; use std::os::linux::fs::MetadataExt; use std::fs::File; use std::io::{BufRead, BufReader}; #[no_mangle] pub extern fn pam_sm...
#![allow(non_camel_case_types)] include!("pam_appl.rs"); use std::ffi::{CString, CStr}; use std::os::raw::{c_int, c_char}; use std::ptr; use std::process::Command; use regex::Regex; use std::fs; use std::os::linux::fs::MetadataExt; use std::fs::File; use std::io::{BufRead, BufReader}; #[no_mangle] pub extern fn pam_sm...
fn read_bluetooth_signal_strength_and_decide(bdaddr: &str, threshold: i32) -> bool { let cmd = format!("hcitool rssi {}", bdaddr); let error_text = format!("Unable to read RSSI value for {}", bdaddr); let rssi_output = match Command::new("sh").arg("-c").arg(cmd).output() { Ok(o) => o.stdout, ...
fn get_device_id_from_users_file(username: &str, filename: &str) -> Option<String> { let meta = match fs::metadata(filename) { Ok(m) => m, Err(e) => { eprintln!("Unable to fetch information for file {}: {}", filename, e); return None; }, }; if meta.st_uid() !=...
function_block-full_function
[ { "content": "#[test]\n\nfn bindgen_test_layout_pam_response() {\n\n assert_eq!(\n\n ::std::mem::size_of::<pam_response>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(pam_response))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<pam_response>(),\n\n 8usize,...
Rust
driver/src/command.rs
rise-lang/2021-CGO-artifact
f6c2c4e916810f734bb1983f93103269e620c931
use std::io::prelude::*; use std::process; use crate::*; pub fn setup(env: &Env) { if env.benchmark { let r = &env.target.remote; if !remote_output(&"mkdir", &vec!["-p", r.dir.to_str().unwrap()], &[], &r.dst, Path::new(".")) .expect("could not create remote dir...
use std::io::prelude::*; use std::process; use crate::*; pub fn setup(env: &Env) { if env.benchmark { let r = &env.target.remote; if !remote_output(&"mkdir", &vec!["-p", r.dir.to_str().unwrap()], &[], &r.dst, Path::new(".")) .expect("could not create remote dir...
; format!("u> {:?} --> {:?}", self.host_path, remote_path).purple() } fn output(&mut self, env: &Env) -> io::Result<process::Output> { let r = &env.target.remote; let remote_path = &match self.remote_path { Some(rp) => r.dir.join(rp), None => r.dir.join(self.host...
match self.remote_path { Some(rp) => r.dir.join(rp), None => r.dir.join(self.host_path) }
if_condition
[ { "content": "pub fn setup<F>(use_env: F) where F: FnOnce(&Env) {\n\n println!(\"{}\", \"-- setting environment up\".yellow());\n\n\n\n let opt = Opt::from_args();\n\n\n\n let target = &Target::load(&opt.target);\n\n let target_name = opt.target.file_stem().unwrap();\n\n let target_name_str = tar...
Rust
mm0-rs/src/parser/ast.rs
mattsse/mm0
247fd3e2ac65eec7d5317285bb2fee639b17a63f
use std::sync::Arc; use std::fmt::{self, Display}; use num::BigUint; use crate::lined_string::LinedString; use crate::util::{Span, ArcString}; use crate::elab::lisp::print::{EnvDisplay, FormatEnv}; use super::ParseError; bitflags! { pub struct Modifiers: u8 { const PURE = 1; const STRICT = 2; const PROVA...
use std::sync::Arc; use std::fmt::{self, Display}; use num::BigUint; use crate::lined_string::LinedString; use crate::util::{Span, ArcString}; use crate::elab::lisp::print::{EnvDisplay, FormatEnv}; use super::ParseError; bitflags! { pub struct Modifiers: u8 { const PURE = 1; const STRICT = 2; const PROVA...
} #[derive(Clone, Debug)] pub struct DepType { pub sort: Span, pub deps: Vec<Span>, } impl DepType { pub fn span(&self) -> Span { (self.sort.start..self.deps.last().unwrap_or(&self.sort).end).into() } } #[derive(Clone, Debug)] pub enum Type { DepType(DepType), Formula(Formula) } impl Type { pub f...
pub fn is_bound(self) -> bool { match self { LocalKind::Bound | LocalKind::Dummy => true, LocalKind::Reg | LocalKind::Anon => false, } }
function_block-full_function
[ { "content": "pub fn whitespace(c: u8) -> bool { c == b' ' || c == b'\\n' }\n\n\n\nimpl<'a> Parser<'a> {\n\n pub fn cur(&self) -> u8 { self.source[self.idx] }\n\n pub fn cur_opt(&self) -> Option<u8> { self.source.get(self.idx).cloned() }\n\n\n\n pub fn err(&self, msg: BoxError) -> ParseError {\n\n ParseEr...
Rust
farms/farm-client/tests/vault_actions/mod.rs
biw/solana-program-library
5611ad8bd595d9e3666f8b115cd28f8116038645
use { crate::{utils, utils::Swap}, solana_farm_client::client::FarmClient, solana_sdk::{commitment_config::CommitmentConfig, signature::Keypair, signer::Signer}, std::{thread, time}, }; const MAX_SOL_BALANCE_TO_USE: f64 = 0.1; const INITIAL_CRANK_DELAY: u64 = 400; const CRANK_INTERVAL: u64 = 100; pub ...
use { crate::{utils, utils::Swap}, solana_farm_client::client::FarmClient, solana_sdk::{commitment_config::CommitmentConfig, signature::Keypair, signer::Signer}, std::{thread, time}, }; const MAX_SOL_BALANCE_TO_USE: f64 = 0.1; const INITIAL_CRANK_DELAY: u64 = 400; const CRANK_INTERVAL: u64 = 100; pub ...
pub fn do_remove_liquidity(client: &FarmClient, keypair: &Keypair, vault_name: &str, amount: f64) { println!(">> Remove liquidity from {}: {}", vault_name, amount); let (token_a_str, token_b_str, vt_token_name) = client.get_vault_token_names(vault_name).unwrap(); println!( " Done: {}", ...
ds, after_crank_info.tokens_b_rewards - initial_info.tokens_b_rewards ); let _ = utils::get_vault_stake_balance(client, vault_name); }
function_block-function_prefixed
[ { "content": "pub fn do_remove_liquidity(client: &FarmClient, keypair: &Keypair, pool_name: &str, amount: f64) {\n\n println!(\">> Remove liquidity from {}: {}\", pool_name, amount);\n\n let (token_a_str, token_b_str, lp_token_name) = client.get_pool_token_names(pool_name).unwrap();\n\n println!(\n\n ...
Rust
.cargo-task/generate-drivers/src/main.rs
flott-motion/stepper
88ff5a41251078943d33d4c3495d9b9103cbe8eb
use std::{ env, error::Error, fs::{create_dir_all, remove_dir_all, File}, io::prelude::*, path::PathBuf, }; use cargo_task_util::ct_info; use serde_derive::Serialize; use serde_json::Value; use tinytemplate::{format_unescaped, TinyTemplate}; mod config; use config::{load_cargo_toml, load_drivers_t...
use std::{ env, error::Error, fs::{create_dir_all, remove_dir_all, File}, io::prelude::*, path::PathBuf, }; use cargo_task_util::ct_info; use serde_derive::Serialize; use serde_json::Value; use tinytemplate::{format_unescaped, TinyTemplate}; mod config; use config::{load_cargo_toml, load_drivers_t...
fn load_template(path: &PathBuf) -> std::io::Result<String> { let mut contents = String::new(); File::open(path)?.read_to_string(&mut contents)?; Ok(contents) }
output: &mut String, ) -> Result<(), tinytemplate::error::Error> { let mut s = String::new(); format_unescaped(value, &mut s)?; output.push_str(&s.to_uppercase()); Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn update<Driver, Timer, Profile, Convert>(\n\n mut state: State<Driver, Timer, Profile>,\n\n new_motion: &mut Option<Direction>,\n\n profile: &mut Profile,\n\n current_step: &mut i32,\n\n current_direction: &mut Direction,\n\n convert: &Convert,\n\n) -> (\n\n Result<\n\n ...
Rust
turbo-txpool/src/error.rs
quilt/turbo
d4efba95f82669d3976120295c50090b31c08428
pub(crate) mod decode_error { use snafu::{ResultExt, Snafu}; use ethereum_interfaces::txpool::ImportResult; #[derive(Debug, Snafu)] #[non_exhaustive] #[snafu(visibility = "pub(crate)")] pub enum DecodeError { RlpDecode { source: Box<dyn std::err...
pub(crate) mod decode_error { use snafu::{ResultExt, Snafu}; use ethereum_interfaces::txpool::ImportResult; #[derive(Debug, Snafu)] #[non_exhaustive] #[snafu(visibility = "pub(crate)")] pub enum DecodeError { RlpDecode { source: Box<dyn std::err...
} } pub(crate) mod import_error { use ethereum_types::{Address, H256, U256}; use snafu::Snafu; use ethereum_interfaces::txpool::ImportResult; #[derive(Debug, Snafu)] #[non_exhaustive] #[snafu(visibility = "pub(crate)")] pub enum ImportError { NonceUsed { ...
fn from(e: DecodeError) -> ImportResult { match e { DecodeError::RlpDecode { .. } => ImportResult::Invalid, DecodeError::IntegerOverflow => ImportResult::InternalError, } }
function_block-full_function
[ { "content": "#[async_trait]\n\npub trait Control {\n\n type BlockStream: futures_core::stream::Stream<\n\n Item = Result<BlockDiff, Status>,\n\n >;\n\n\n\n async fn block_stream(\n\n &mut self,\n\n request: BlockStreamRequest,\n\n ) -> Result<Self::BlockStream, Status>;\n\n\n\n...
Rust
src/world/chunk/chunkmanager.rs
Ducolnd/ludwig-world-3d
3eb034d5c14cc95a29be7dab5d564c47c8423daf
use std::collections::HashMap; use std::time::Instant; use crate::world::{ chunk::{chunk::Chunk, pos::*}, constants::*, block::blocks::BlockID, world::World, }; use crate::render::{ low::{ renderer::Renderer, context::Context, }, meshing::chunkmeshing::ChunkMesh, drawabl...
use std::collections::HashMap; use std::time::Instant; use crate::world::{ chunk::{chunk::Chunk, pos::*}, constants::*, block::blocks::BlockID, world::World, }; use crate::render::{ low::{ renderer::Renderer, context::Context, }, meshing::chunkmeshing::ChunkMesh, drawabl...
pub fn queue_chunk_load(&mut self, pos: ChunkPos) { self.load_queue.push(pos); } pub fn load_queue(&mut self, world: &World, renderer: &mut Renderer) { if self.load_queue.len() > 0 { for pos in self.load_queue.clone() { self.load_chunk(pos.clone(), wo...
4]{ [ self.get_chunk_option(center + ChunkPos::new(0, 0, 1)), self.get_chunk_option(center + ChunkPos::new(1, 0, 0)), self.get_chunk_option(center + ChunkPos::new(0, 0, -1)), self.get_chunk_option(center + ChunkPos::new(-1, 0, 0)), ] }
function_block-function_prefixed
[ { "content": "// Helper function\n\npub fn coords_to_float(coords: [u32; 2]) -> [f32; 2] {\n\n [\n\n coords[0] as f32 / TEXTURE_IMAGE_WIDTH as f32,\n\n coords[1] as f32 / TEXTURE_IMAGE_HEIGHT as f32,\n\n ]\n\n}\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TextureTile {\n\n pub coord...
Rust
src/engine/obj.rs
PistonDevelopers/dyon_asteroids
51f944cac511e26b4d772c57e1ea245ffab280a1
use wavefront_obj::mtl::MtlSet; use wavefront_obj::obj::{self, ObjSet}; use std::sync::Arc; use current::Current; use dyon::*; use dyon::embed::{PushVariable, PopVariable}; pub type Materials = Vec<(Arc<String>, MtlSet)>; pub type ObjSets = Vec<(Arc<String>, ObjSet)>; pub fn register_obj(module: &mut Module) { mo...
use wavefront_obj::mtl::MtlSet; use wavefront_obj::obj::{self, ObjSet}; use std::sync::Arc; use current::Current; use dyon::*; use dyon::embed::{PushVariable, PopVariable}; pub type Materials = Vec<(Arc<String>, MtlSet)>; pub type ObjSets = Vec<(Arc<String>, ObjSet)>; pub fn register_obj(module: &mut Module) { mo...
try!(rt.var(&arr[2])))) } _ => return Err(rt.expected(var, "array of length 1, 2, 3")) }) } else { Err(rt.expected(var, "array")) } } } impl PushVariable for Shape { fn push_var(&self) -> Variable...
Ok(match arr.len() { 1 => { Shape(obj::Shape::Point(try!(rt.var(&arr[0])))) } 2 => { Shape(obj::Shape::Line(try!(rt.var(&arr[0])), try!(rt.var(&arr[1])))) } ...
function_block-random_span
[ { "content": "pub fn register_shader(module: &mut Module) {\n\n module.add(Arc::new(\"load_program__name_vshader_fshader\".into()),\n\n load_program__name_vshader_fshader, PreludeFunction {\n\n lts: vec![Lt::Default; 3],\n\n tys: vec![Type::Text; 3],\n\n ret: Type::Res...
Rust
src/text.rs
zyxw59/conlang_fmt
2c74dd805de38fff5b28c644517c3347ba93d3a5
use std::io::{Result as IoResult, Write}; use crate::blocks::{BlockCommon, BlockType, Parameter, UpdateParam}; use crate::document::Document; use crate::errors::Result as EResult; use crate::html; type OResult<T> = EResult<Option<T>>; pub trait Referenceable { fn reference_text(&self) -> Text; } #[derive(C...
use std::io::{Result as IoResult, Write}; use crate::blocks::{BlockCommon, BlockType, Parameter, UpdateParam}; use crate::document::Document; use crate::errors::Result as EResult; use crate::html; type OResult<T> = EResult<Option<T>>; pub trait Referenceable { fn reference_text(&self) -> Text; } #[derive(C...
} pub fn starts_with(&self, c: char) -> bool { match self.0.first() { Some(inline) => inline.kind.starts_with(c), None => false, } } pub fn ends_with(&self, c: char) -> bool { match self.0.last() { Some(inline) => inline.kind.ends_with(c), ...
rite_inline_plain(&self, w: &mut dyn Write, document: &Document) -> IoResult<()> { for t in &self.0 { t.kind.write_plain(w, document)?; } Ok(())
function_block-random_span
[ { "content": "pub trait BlockType: Debug {\n\n /// Outputs the block.\n\n fn write(&self, w: &mut dyn Write, common: &BlockCommon, document: &Document) -> IoResult<()>;\n\n\n\n /// Updates with the given parameter. If the parameter was not updated, returns the parameter.\n\n fn update_param(&mut sel...
Rust
rustracts/src/contracts/option.rs
JOE1994/rustracts
c15541d7968aea40d06dadd5e2c5cb57b4d6d341
use std::sync::Mutex; use std::time::Duration; use crate::context::{ContextError, ContextErrorKind, ContractContext}; use crate::park::{WaitMessage, WaitThread}; use crate::time::Timer; use crate::{Contract, ContractExt, Status}; use futures::{ future::{FusedFuture, Future}, task::{Context, Poll}, }; use parc...
use std::sync::Mutex; use std::time::Duration; use crate::context::{ContextError, ContextErrorKind, ContractContext}; use crate::park::{WaitMessage, WaitThread}; use crate::time::Timer; use crate::{Contract, ContractExt, Status}; use futures::{ future::{FusedFuture, Future}, task::{Context, Poll}, }; use parc...
#[test] fn noprod_option_contract() { let vcontext = EqContext(2, 2); let pcontext = EqContext(2, 2); let c = OptionContract::new( Duration::new(1, 0), vcontext, pcontext, |(vcon, pcon)| -> usize { vcon.0 + pcon.0 + 1 }, ); ...
fn void_option_contract() { let vcontext = EqContext(2, 2); let pcontext = EqContext(2, 2); let c = OptionContract::new( Duration::new(1, 0), vcontext, pcontext, |(vcon, pcon)| -> usize { vcon.0 + pcon.0 + 1 }, ); let handle = s...
function_block-full_function
[]
Rust
src/protocol/flv.rs
nintha/river
56a63312dd7fef48f73dbd3985022604c739ba40
use byteorder::{BigEndian, ByteOrder}; use crate::protocol::rtmp::{ChunkMessageType, RtmpMessage}; use crate::util::spawn_and_log_error; use smol::channel::Receiver; use std::convert::TryFrom; use crate::rtmp_server::eventbus_map; use chrono::Local; use smol::io::AsyncWriteExt; use std::time::{Duration, Instant}; pu...
use byteorder::{BigEndian, ByteOrder}; use crate::protocol::rtmp::{ChunkMessageType, RtmpMessage}; use crate::util::spawn_and_log_error; use smol::channel::Receiver; use std::convert::TryFrom; use crate::rtmp_server::eventbus_map; use chrono::Local; use smol::io::AsyncWriteExt; use std::time::{Duration, Instant}; pu...
file.write_all(&FLV_HEADER_WITH_TAG0).await?; let ctx_begin_timestamp = Local::now().timestamp_millis(); let mut last_flush_time = Instant::now(); let min_flush_duration = Duration::from_secs(2); while let Ok(mut msg) = flv_rx.recv().await { msg.header.timestamp = (Local::now().timestamp_m...
pub fn data_size(&self) -> u32 { BigEndian::read_u24(&self.raw_data[1..4]) } pub fn timestamp(&self) -> u32 { let timestamp_u24 = BigEndian::read_u24(&self.raw_data[4..7]); timestamp_u24 | (self.raw_data[7] as u32) << 24 } pub fn body(&self) -> &[u8] { ...
random
[ { "content": "pub fn print_hex(bytes: &[u8]) {\n\n println!(\"{}\", bytes_hex_format(bytes));\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 112056.65758520142 }, { "content": "pub fn bytes_hex_format(bytes: &[u8]) -> String {\n\n const COLUMN: usize = 16;\n\n const CO...
Rust
src/third_party/alga/alga_transform.rs
dfarnham/nalgebra
79ef862fe9bd5f6d97a864c36274e0eb69468025
use alga::general::{ AbstractGroup, AbstractLoop, AbstractMagma, AbstractMonoid, AbstractQuasigroup, AbstractSemigroup, Identity, Multiplicative, RealField, TwoSidedInverse, }; use alga::linear::{ProjectiveTransformation, Transformation}; use crate::base::allocator::Allocator; use crate::base::dimension::{DimN...
use alga::general::{ AbstractGroup, AbstractLoop, AbstractMagma, AbstractMonoid, AbstractQuasigroup, AbstractSemigroup, Identity, Multiplicative, RealField, TwoSidedInverse, }; use alga::linear::{ProjectiveTransformation, Transformation}; use crate::base::allocator::Allocator; use crate::base::dimension::{DimN...
SVector<T, D> { self.transform_vector(v) } } impl<T, C, const D: usize> ProjectiveTransformation<Point<T, D>> for Transform<T, C, D> where Const<D>: DimNameAdd<U1>, T: RealField + simba::scalar::RealField, C: SubTCategoryOf<TProjective>, DefaultAllocator: Allocator<T, DimNameSum<Const<D>, ...
rm<T, C, D> where Const<D>: DimNameAdd<U1>, C: TCategory, DefaultAllocator: Allocator<T, DimNameSum<Const<D>, U1>, DimNameSum<Const<D>, U1>>, { #[inline] fn operate(&self, rhs: &Self) -> Self { self * rhs } } macro_rules! impl_multiplicative_structures( ($($marker: ident<$operator: ...
random
[]
Rust
src/ais/vdm_t14.rs
johann2/nmea-parser
0dd55af67546526399bbc026067e51da8ea3fdc1
/* Copyright 2020 Timo Saarinen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...
/* Copyright 2020 Timo Saarinen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...
#[cfg(test)] mod test { use super::*; #[test] fn test_parse_vdm_type14() { let mut p = NmeaParser::new(); match p.parse_sentence("!AIVDM,1,1,,A,>5?Per18=HB1U:1@E=B0m<L,2*51") { Ok(ps) => { match ps { ParsedMess...
pub(crate) fn handle( bv: &BitVec, station: Station, own_vessel: bool, ) -> Result<ParsedMessage, ParseError> { Ok(ParsedMessage::SafetyRelatedBroadcastMessage( SafetyRelatedBroadcastMessage { own_vessel: { own_vessel }, station: { station }, mmsi: { pick_u64(...
function_block-full_function
[ { "content": "/// Make key for store\n\nfn make_gsv_key(sentence_type: &str, msg_count: u32, msg_num: u32) -> String {\n\n format!(\"{},{},{}\", sentence_type, msg_count, msg_num)\n\n}\n\n\n\n// -------------------------------------------------------------------------------------------------\n\n\n\n#[cfg(tes...
Rust
sourcemap/src/types.rs
jaspervandenberg/symbolic
c420a47d67a4b17cbdc48de5b5900e8e2e7fa62f
use std::mem; use std::borrow::Cow; use sourcemap; use symbolic_common::Result; pub struct SourceView<'a> { sv: sourcemap::SourceView<'a>, } pub struct SourceMapView { sm: sourcemap::SourceMap, } pub struct TokenMatch<'a> { pub src_line: u32, pub src_col: u32, pub dst_line: u32, pub dst_col...
use std::mem; use std::borrow::Cow; use sourcemap; use symbolic_common::Result; pub struct SourceView<'a> { sv: sourcemap::SourceView<'a>, } pub struct SourceMapView { sm: sourcemap::SourceMap, } pub struct TokenMatch<'a> { pub src_line: u32, pub src_col: u32, pub dst_line: u32, pub dst_col...
self.sm.get_source_count() } pub fn lookup_token_with_function_name<'a, 'b>( &'a self, line: u32, col: u32, minified_name: &str, source: &SourceView<'b>, ) -> Option<TokenMatch<'a>> { self.sm.lookup_token(line, col).map(...
pub function_name: Option<String>, } impl<'a> SourceView<'a> { pub fn new(source: &'a str) -> SourceView<'a> { SourceView { sv: sourcemap::SourceView::new(source), } } pub fn from_string(source: String) -> SourceView<'static> { SourceView { sv...
random
[ { "content": "/// Checks whether an ELF binary contains a section.\n\n///\n\n/// This is useful to determine whether the binary contains certain information\n\n/// without loading its section data.\n\npub fn has_elf_section(elf: &elf::Elf, sh_type: u32, name: &str) -> bool {\n\n for header in &elf.section_he...
Rust
arch/x86/cpu/idt.rs
mvdnes/element76
87e0206b022bda177dd1ca8fb6e2989429c2c8bf
/* * This file contains code for the Interrupt Descriptor Table * * See: http://www.jamesmolloy.co.uk/tutorial_html/4.-The%20GDT%20and%20IDT.html */ use core::marker::Copy; use core::clone::Clone; const IDT_COUNT: usize = 256; static mut IDT_ENTRIES: [IDTEntry; IDT_COUNT] = [IDTEntry { base_low: 0, selector: 0, z...
/* * This file contains code for the Interrupt Descriptor Table * * See: http://www.jamesmolloy.co.uk/tutorial_html/4.-The%20GDT%20and%20IDT.html */ use core::marker::Copy; use core::clone::Clone; const IDT_COUNT: usize = 256; static mut IDT_ENTRIES: [IDTEntry; IDT_COUNT] = [IDTEntry { base_low: 0, selector: 0, z...
, 0x08, 0x8E); idt_set_gate(44, irq12 as usize, 0x08, 0x8E); idt_set_gate(45, irq13 as usize, 0x08, 0x8E); idt_set_gate(46, irq14 as usize, 0x08, 0x8E); idt_set_gate(47, irq15 as usize, 0x08, 0x8E); idt_flush(&IDT_PTR as *const IDTPointer as u32); } } unsafe fn idt_set_gate(n: usize, base: usize, sel: u16,...
8, 0x8E); idt_set_gate(20, isr20 as usize, 0x08, 0x8E); idt_set_gate(21, isr21 as usize, 0x08, 0x8E); idt_set_gate(22, isr22 as usize, 0x08, 0x8E); idt_set_gate(23, isr23 as usize, 0x08, 0x8E); idt_set_gate(24, isr24 as usize, 0x08, 0x8E); idt_set_gate(25, isr25 as usize, 0x08, 0x8E); idt_set_gate(26, isr...
random
[ { "content": "fn parse_keycode(code: u8) -> KeyboardKey\n\n{\n\n\tmatch code\n\n\t{\n\n\t\t1 => KeyboardKey::Escape,\n\n\t\t2 => KeyboardKey::Printable('1', '!'),\n\n\t\t3 => KeyboardKey::Printable('2', '@'),\n\n\t\t4 => KeyboardKey::Printable('3', '#'),\n\n\t\t5 => KeyboardKey::Printable('4', '$'),\n\n\t\t6 =>...
Rust
src/bdd.rs
tangentstorm/bex
c2dea80e284de3fd577fda892577edc829c07bf7
use std::collections::HashMap; use std::collections::HashSet; use std::cell::RefCell; extern crate num_cpus; use bincode; use base::{Base}; use io; use reg::Reg; use {vhl, vhl::{HiLo, Walkable}}; use nid::{NID,O,I}; use vid::{VID,VidOrdering,topmost_of3}; mod bdd_sols; mod bdd_swarm; use self::bdd_swarm::*; pub ty...
use std::collections::HashMap; use std::collections::HashSet; use std::cell::RefCell; extern crate num_cpus; use bincode; use base::{Base}; use io; use reg::Reg; use {vhl, vhl::{HiLo, Walkable}}; use nid::{NID,O,I}; use vid::{VID,VidOrdering,topmost_of3}; mod bdd_sols; mod bdd_swarm; use self::bdd_swarm::*; pub ty...
} impl Base for BDDBase { fn new()->BDDBase { BDDBase{swarm: BddSwarm::new(), tags:HashMap::new()}} fn when_hi(&mut self, x:VID, y:NID)->NID { let yv = y.vid(); match x.cmp_depth(&yv) { VidOrdering::Level => self.tup(y).0, VidOrdering::Above => y, VidOrdering::Be...
pub fn tt(&mut self, n0:NID, num_vars:u32)->Vec<u8> { if !n0.vid().is_var() { todo!("tt only works for actual variables. got {:?}", n0); } if num_vars > 16 { panic!("refusing to generate a truth table of 2^{} bytes", num_vars) } if num_vars == 0 { panic!("num_vars should be > 0")} let mut res = vec...
function_block-full_function
[ { "content": "#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]\n\nstruct XHiLo { pub hi: XID, pub lo: XID }\n\nimpl std::ops::Not for XHiLo { type Output = XHiLo; fn not(self)->XHiLo { XHiLo { hi:!self.hi, lo:!self.lo }}}\n\nimpl XHiLo { fn as_tup(&self)->(XID,XID) { (self.hi, self.lo) }}\n\n\n\n#[derive(Debu...
Rust
crates/tools/src/setup.rs
RetricSu/godwoken
88df30ffad824b3b3b2980d67ece79ca31ab0b47
use crate::deploy_genesis::deploy_genesis; use crate::deploy_scripts::deploy_scripts; use crate::generate_config::generate_config; use crate::prepare_scripts::{self, prepare_scripts, ScriptsBuildMode}; use crate::utils; use ckb_types::{ core::ScriptHashType, packed as ckb_packed, prelude::Builder as CKBBuilder, ...
use crate::deploy_genesis::deploy_genesis; use crate::deploy_scripts::deploy_scripts; use crate::generate_config::generate_config; use crate::prepare_scripts::{self, prepare_scripts, ScriptsBuildMode}; use crate::utils; use ckb_types::{ core::ScriptHashType, packed as ckb_packed, prelude::Builder as CKBBuilder, ...
) } fn transfer_ckb(node_wallet: &NodeWalletInfo, payer_privkey_path: &Path, capacity: u32) { utils::run( "ckb-cli", vec![ "wallet", "transfer", "--to-address", &node_wallet.testnet_address, "--capacity", &capacity.to_string(),...
tils::make_path(&node_dir, vec!["pk"]); let privkey = fs::read_to_string(&privkey_file) .map(|s| s.trim().into()) .unwrap_or_else(|_| Vec::new()); if !privkey.starts_with(b"0x") || privkey.len() != 66 || hex::decode(&privkey[2..]).i...
random
[ { "content": "pub fn hex(raw: &[u8]) -> Result<String> {\n\n Ok(format!(\"0x{}\", faster_hex::hex_string(raw)?))\n\n}\n", "file_path": "crates/web3-indexer/src/helper.rs", "rank": 4, "score": 274876.3472011481 }, { "content": "fn prepare_scripts_in_copy_mode(prebuild_image: &PathBuf, scri...
Rust
src/rule_finder.rs
ciphergoth/rerast
2abd359242dee27ab09919259154274cca612bb5
use std::marker; use syntax::ast::NodeId; use syntax::symbol::Symbol; use syntax::ext::quote::rt::Span; use std::vec::Vec; use rustc::hir::{self, intravisit}; use rustc::ty::{self, TyCtxt}; use definitions::RerastDefinitions; use rule_matcher::{Matchable, OperatorPrecedence}; use rules::{Rule, Rules}; use errors::Err...
use std::marker; use syntax::ast::NodeId; use syntax::symbol::Symbol; use syntax::ext::quote::rt::Span; use std::vec::Vec; use rustc::hir::{self, intravisit}; use rustc::ty::{self, TyCtxt}; use definitions::RerastDefinitions; use rule_matcher::{Matchable, OperatorPrecedence}; use rules::{Rule, Rules}; use errors::Err...
intravisit::walk_crate(&mut rule_finder, krate); if rule_finder.errors.is_empty() { Ok(rule_finder.rules) } else { Err(rule_finder.errors) } } fn maybe_add_rule( &mut self, arg_ty: ty::Ty<'gcx>, arms: &'gcx [hir::Arm], ...
let mut rule_finder = RuleFinder { tcx, rerast_definitions, rules_mod_symbol: Symbol::intern(super::RULES_MOD_NAME), rules: Rules::new(), body_id: None, in_rules_module: false, errors: Vec::new(), };
assignment_statement
[ { "content": "struct Placeholder<'gcx> {\n\n expr: &'gcx hir::Expr,\n\n uses: Vec<Span>,\n\n}\n\n\n", "file_path": "src/change_to_rule.rs", "rank": 0, "score": 126178.62619493643 }, { "content": "struct RuleFinder<'a, 'gcx: 'a> {\n\n tcx: TyCtxt<'a, 'gcx, 'gcx>,\n\n changed_span:...
Rust
kernel/env/mod.rs
pwoolcoc/redox
87f5ea23d26502494439cbf2a094bb5102f989b8
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use arch::context::ContextManager; use common::event::Event; use common::time::Duration; use disk::Disk; use network::Nic; use fs::{KScheme, Resource, Scheme, VecResource, Url}; use sync::WaitQu...
use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use arch::context::ContextManager; use common::event::Event; use common::time::Duration; use disk::Disk; use network::Nic; use fs::{KScheme, Resource, Scheme, VecResource, Url}; use sync::WaitQu...
} } else { for mut scheme in unsafe { &mut *self.schemes.get() }.iter_mut() { if scheme.scheme() == url_scheme { return scheme.open(url, flags); } } Err(Error::new(ENOENT)) } } pub fn mkdir(&self, url...
pub interrupts: UnsafeCell<[u64; 256]>, } impl Environment { pub fn new() -> Box<Environment> { box Environment { contexts: UnsafeCell::new(ContextManager::new()), clock_realtime: UnsafeCell::new(Duration::new(0, 0)), clock_monotonic: UnsafeCell::new(Duration::new(...
random
[ { "content": "pub trait Disk {\n\n fn name(&self) -> String;\n\n fn on_irq(&mut self, irq: u8);\n\n fn size(&self) -> u64;\n\n fn read(&mut self, block: u64, buffer: &mut [u8]) -> Result<usize>;\n\n fn write(&mut self, block: u64, buffer: &[u8]) -> Result<usize>;\n\n}\n", "file_path": "kernel...
Rust
src/lib.rs
antoyo/password-store-rs
b2615c12fec5d8957798fa8a745bdec1f1274719
/* * Copyright (c) 2016-2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
/* * Copyright (c) 2016-2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
=> "invalid output".to_string(), Pass(ref error) => error.clone(), Utf8(ref error) => error.to_string(), }; write!(formatter, "{}", string) } } impl error::Error for Error { fn description(&self) -> &str { match *self { FromUtf8(ref error)...
rmatter: &mut Formatter) -> fmt::Result { let string = match *self { FromUtf8(ref error) => error.to_string(), Json(ref error) => error.to_string(), Io(ref error) => error.to_string(), InvalidInput => "invalid input".to_string(), ...
function_block-random_span
[ { "content": "pub trait Chomp {\n\n fn chomp(&mut self);\n\n}\n\n\n\nimpl Chomp for String {\n\n fn chomp(&mut self) {\n\n if self.chars().last() == Some('\\n') {\n\n self.pop();\n\n }\n\n }\n\n}\n", "file_path": "src/chomp.rs", "rank": 0, "score": 50258.44084005050...
Rust
gstreamer-app/src/app_src.rs
kad3nce/gstreamer-rs
fcc361f920c9c4d0926cc90de997a0293a21b0b1
use glib::translate::*; use glib_sys::{gboolean, gpointer}; use gst; use gst_app_sys; use std::cell::RefCell; use std::mem; use std::ptr; use AppSrc; #[allow(clippy::type_complexity)] pub struct AppSrcCallbacks { need_data: Option<RefCell<Box<dyn FnMut(&AppSrc, u32) + Send + 'static>>>, enough_data: Option<B...
use glib::translate::*; use glib_sys::{gboolean, gpointer}; use gst; use gst_app_sys; use std::cell::RefCell; use std::mem; use std::ptr; use AppSrc; #[allow(clippy::type_complexity)] pub struct AppSrcCallbacks { need_data: Option<RefCell<Box<dyn FnMut(&AppSrc, u32) + Send + 'static>>>, enough_data: Option<B...
pub fn seek_data<F: Fn(&AppSrc, u64) -> bool + Send + Sync + 'static>( self, seek_data: F, ) -> Self { Self { seek_data: Some(Box::new(seek_data)), ..self } } pub fn build(self) -> AppSrcCallbacks { let have_need_data = self.need_data.is...
pub fn enough_data<F: Fn(&AppSrc) + Send + Sync + 'static>(self, enough_data: F) -> Self { Self { enough_data: Some(Box::new(enough_data)), ..self } }
function_block-full_function
[ { "content": "fn into_raw_pad_task<F: FnMut() + Send + 'static>(func: F) -> gpointer {\n\n #[allow(clippy::type_complexity)]\n\n let func: Box<RefCell<F>> = Box::new(RefCell::new(func));\n\n Box::into_raw(func) as gpointer\n\n}\n\n\n\nunsafe extern \"C\" fn destroy_closure_pad_task<F>(ptr: gpointer) {\...
Rust
tests/sweep.rs
hellow554/flo_curves
8807b446271f0d2212d3f27d86741beeab5abebb
use flo_curves::geo::{ sweep_against, sweep_self, BoundingBox, Bounds, Coord2, Coordinate, Coordinate2D, Coordinate3D, }; use rand::prelude::*; use std::cmp::Ordering; #[test] fn sweep_self_single_overlap() { let mut bounds = vec![ Bounds::from_min_max(Coord2(100.0, 200.0), Coord2(200.0, 300.0)), ...
use flo_curves::geo::{ sweep_against, sweep_self, BoundingBox, Bounds, Coord2, Coordinate, Coordinate2D, Coordinate3D, }; use rand::prelude::*; use std::cmp::Ordering; #[test] fn sweep_self_single_overlap() { let mut bounds = vec![ Bounds::from_min_max(Coord2(100.0, 200.0), Coord2(200.0, 300.0)), ...
#[test] fn sweep_self_1000_random() { let mut rng = StdRng::from_seed([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, ]); let mut bounds = (0..1000) .into_iter() .map(|_| { let x = rng.gen::...
fn sweep_against_quad_overlap() { let mut bounds1 = vec![ Bounds::from_min_max(Coord2(100.0, 200.0), Coord2(200.0, 300.0)), Bounds::from_min_max(Coord2(150.0, 250.0), Coord2(250.0, 350.0)), ]; let mut bounds2 = vec![ Bounds::from_min_max(Coord2(190.0, 290.0), Coord2(290.0, 390.0)), ...
function_block-full_function
[ { "content": "fn detect_collisions(mut graph_path: GraphPath<Coord2, ()>) {\n\n graph_path.self_collide(0.1);\n\n}\n\n\n", "file_path": "benches/sweep.rs", "rank": 0, "score": 169984.23598104744 }, { "content": "///\n\n/// Finds the upper and lower points in a cubic curve's bounding box\n...
Rust
crates/examples/src/readobj/mod.rs
sunfishcode/object
aaf312e51fc6e4511e19a32c05d4b2ddf248b5b6
use std::io::Write; use std::{fmt, str}; use object::read::archive::ArchiveFile; use object::read::macho::{FatArch, FatHeader}; use object::Endianness; pub fn print(w: &'_ mut dyn Write, e: &'_ mut dyn Write, file: &[u8]) { let mut printer = Printer::new(w, e); print_object(&mut printer, &*file); } struct Pr...
use std::io::Write; use std::{fmt, str}; use object::read::archive::ArchiveFile; use object::read::macho::{FatArch, FatHeader}; use object::Endianness; pub fn print(w: &'_ mut dyn Write, e: &'_ mut dyn Write, file: &[u8]) { let mut printer = Printer::new(w, e); print_object(&mut printer, &*file); } struct Pr...
fn field<T: fmt::Display>(&mut self, name: &str, value: T) { self.field_name(name); writeln!(self.w, "{}", value).unwrap(); } fn field_hex<T: fmt::UpperHex>(&mut self, name: &str, value: T) { self.field_name(name); writeln!(self.w, "0x{:X}", value).unwrap(); } fn ...
fn field_name(&mut self, name: &str) { self.print_indent(); if !name.is_empty() { write!(self.w, "{}: ", name).unwrap(); } }
function_block-full_function
[ { "content": "fn dump_parsed_object<W: Write, E: Write>(w: &mut W, e: &mut E, file: &object::File) -> Result<()> {\n\n writeln!(\n\n w,\n\n \"Format: {:?} {:?}-endian {}-bit\",\n\n file.format(),\n\n file.endianness(),\n\n if file.is_64() { \"64\" } else { \"32\" }\n\n )...
Rust
src/move_table.rs
lePerdu/twisted
6f3330fbb594beb9f06d8bfeb307cb60ca8035b9
use std::marker::PhantomData; use crate::coord::{CompositeCoord, Coord}; use crate::puzzle::{PuzzleMove, PuzzlePerm}; use crate::symmetry::{SymCoord, Symmetry}; use crate::util::{EnumCount, IntoEnumIterator}; pub trait MoveTable { type Puzzle: PuzzlePerm; type Coord: Coord<Self::Puzzle>; type Move: Puzz...
use std::marker::PhantomData; use crate::coord::{CompositeCoord, Coord}; use crate::puzzle::{PuzzleMove, PuzzlePerm}; use crate::symmetry::{SymCoord, Symmetry}; use crate::util::{EnumCount, IntoEnumIterator}; pub trait MoveTable { type Puzzle: PuzzlePerm; type Coord: Coord<Self::Puzzle>; type Move: Puzz...
ble_coord = table.get_move(orig_coord, turn); let perm_coord = C::from(&perm); assert_eq!(table_coord, perm_coord); } } // Do the tests for each coordinate macro_rules! make_tests { ($name:ident, $coord:ty) => { pub mod $name { use super...
let transformed = perm.sequence(sym.permutation()); if let Some(transformed_move) = M::iter().find(|m| *m.permutation() == transformed) { move_table.push(transformed_move); } else { panic!("Transforme...
random
[ { "content": "/// Symmetry-reduced coordinate, constructed from a regular coordinate and a symmetry.\n\npub trait SymCoord<P: PuzzlePerm>: EnumIndex {\n\n type BaseCoord: Coord<P>;\n\n type Symmetry: Symmetry<Puzzle = P>;\n\n type EquivClass: EnumIndex;\n\n\n\n fn from_sym_and_class(sym: Self::Symme...
Rust
compiler/src/llvm.rs
kowaalczyk/instant
95ae0bcb58ec829828e68bc8b09016514c6e08f5
use instant_parser::ast; use crate::common::CompilationError; use std::collections::HashSet; use instant_parser::ast::Stmt; pub trait FormatLLVM { fn format_llvm(&self) -> String; } enum CompilationResult { Register { id: u32 }, Constant { val: i32 }, None, } impl FormatLLVM for CompilationResult { ...
use instant_parser::ast; use crate::common::CompilationError; use std::collections::HashSet; use instant_parser::ast::Stmt; pub trait FormatLLVM { fn format_llvm(&self) -> String; } enum CompilationResult { Register { id: u32 }, Constant { val: i32 }, None, } impl FormatLLVM for CompilationResult { ...
} impl CompileLLVM for ast::Stmt { fn compile_llvm( &self, available_reg: &mut u32, variables: &mut HashSet<String> ) -> Result<CompiledCode, CompilationError> { match self { Stmt::Expr { expr } => { let mut compiled_expr = expr.compile_llvm(availabl...
fn compile_llvm( &self, available_reg: &mut u32, variables: &mut HashSet<String> ) -> Result<CompiledCode, CompilationError> { let mut instructions: Vec<String> = vec![]; for stmt in self.stmts.iter() { let mut compiled_stmt = stmt.compile_llvm( av...
function_block-full_function
[ { "content": "pub fn parse_arg() -> String {\n\n let args: Vec<String> = env::args().collect();\n\n match args.get(1) {\n\n Some(input_filename) => {\n\n String::from(input_filename)\n\n },\n\n None => {\n\n println!(\"Usage: {} {}\", &args[0], \"[input_filename]...
Rust
testsuite/cluster-test/src/experiments/client_compatibility_test.rs
chouette254/libra
1eaefa60d29e1df72ba6c4f9cf1867964821b586
#![forbid(unsafe_code)] use crate::{ cluster::Cluster, cluster_swarm::cluster_swarm_kube::CFG_SEED, experiments::{Context, Experiment, ExperimentParam}, instance::Instance, }; use async_trait::async_trait; use libra_logger::prelude::*; use libra_types::chain_id::ChainId; use std::{collections::HashSe...
#![forbid(unsafe_code)] use crate::{ cluster::Cluster, cluster_swarm::cluster_swarm_kube::CFG_SEED, experiments::{Context, Experiment, ExperimentParam}, instance::Instance, }; use async_trait::async_trait; use libra_logger::prelude::*; use libra_types::chain_id::ChainId; use std::{collections::HashSe...
self.faucet_node.peer_name(), full_faucet_cmd ); info!("Waiting for faucet job to spin up completely"); time::delay_for(Duration::from_secs(20)).await; let run_cli_cmd = format!( "/opt/libra/bin/cli --url {fn_url} --chain-id {chain_id} -f h...
let faucet_job_name = self .faucet_node .spawn_job(&test_image, &full_faucet_cmd, "run-faucet") .await .map_err(|err| anyhow::format_err!("Failed to spawn faucet job: {}", err))?; info!( "Job {} started for node {}:{} faucet command: {}", ...
random
[ { "content": "pub fn get_instance_list_str(batch: &[Instance]) -> String {\n\n let mut nodes_list = String::from(\"\");\n\n for instance in batch.iter() {\n\n nodes_list.push_str(&instance.to_string());\n\n nodes_list.push_str(\", \")\n\n }\n\n nodes_list\n\n}\n\n\n\n#[derive(StructOpt...
Rust
src/unwrap.rs
jkfritcher/aes-keywrap-rs
76abb49644769a8a48228227ff3ebd56336f6ddf
use crate::{ types::{Aes128Ecb, Aes192Ecb, Aes256Ecb, AES_BLOCK_LEN, BLOCK_LEN}, }; use block_modes::BlockMode; use thiserror::Error; #[derive(Error, Debug)] pub enum UnwrapKeyError { #[error("Key length must be 16, 24 or 32 octets")] KeyLengthInvalid, #[error("Ciphertext length must be a multiple o...
use crate::{ types::{Aes128Ecb, Aes192Ecb, Aes256Ecb, AES_BLOCK_LEN, BLOCK_LEN}, }; use block_modes::BlockMode; use thiserror::Error; #[derive(Error, Debug)] pub enum UnwrapKeyError { #[error("Key length must be 16, 24 or 32 octets")] KeyLengthInvalid, #[error("Ciphertext length must be a multiple o...
#[test] fn test_unwrap_nopad_32_byte_key_24_byte_data() { let ct = hex!("A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1").to_vec(); let key = hex!("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F").to_vec(); let pt = aes_unwrap_with_nopadding(&ct, &ke...
EDCE1C6C7DDEE725A936BA814915C6762D2").to_vec(); let key = hex!("000102030405060708090A0B0C0D0E0F1011121314151617").to_vec(); let pt = aes_unwrap_with_nopadding(&ct, &key); assert!(pt.is_ok(), "Test unexpectantly failed: {:?}", pt); assert_eq!( pt.unwrap(), hex!("0...
function_block-function_prefixed
[ { "content": "fn wrap_core<AesEcb>(key: &[u8], n: usize, ct: &mut [u8], aes_ecb_encrypt: AesEcb)\n\nwhere\n\n AesEcb: Fn(&[u8], &mut [u8]),\n\n{\n\n if ct.len() > AES_BLOCK_LEN {\n\n // Allocate buffer for operations in loop\n\n // tmp = A | R[i]\n\n let mut tmp: Vec<u8> = vec![0u8; A...
Rust
lang/src/compiler/path.rs
leops/hatchet
4f788737551b3cf74c06c8fae24b5b20be420ef4
use std::collections::VecDeque; use std::borrow::Borrow; use hct::ast::Path; use super::builder::*; use super::function::*; use super::scope::Scope; use super::types::*; use atom::*; pub fn resolve_path<'a, P: Borrow<Path>>(path: P, scope: &Scope<'a>, builder: &mut Builder) -> ValueRef { let path = path.borrow();...
use std::collections::VecDeque; use std::borrow::Borrow; use hct::ast::Path; use super::builder::*; use super::function::*; use super::scope::Scope; use super::types::*; use atom::*; pub fn resolve_path<'a, P: Borrow<Path>>(path: P, scope: &Scope<'a>, builder: &mut Builder) -> ValueRef { let path = path.borrow();...
, Path::Instance(pat) => (Some(resolve_path(pat, scope, builder)), None, None), Path::Binding(_) => (None, Some(resolve_path(&path, scope, builder)), None), } } pub fn event<'a>(path: Path, scope: &Scope<'a>, builder: &mut Builder) -> (ValueRef, ValueRef) { match break_trigger(path, scope, buil...
match break_trigger(*obj, scope, builder) { (a, Some(b), None) => (a, Some(b), Some(prop)), (a, None, None) => (a, Some(builder.build_const_entity(prop)), None), path => panic!("invalid path {:?}", path), }
if_condition
[ { "content": "/// Create a call to an STL function\n\npub fn call_stl<'a, A>(builder: &mut Builder, name: Atom, args: A) -> ValueRef\n\n where A: IntoIterator<Item=&'a ValueRef>, Type: 'a, Value: 'a {\n\n let mut args = args.into_iter().peekable();\n\n\n\n match name {\n\n hct_atom!(\"length\") ...
Rust
src/day21.rs
codedstructure/aoc2021
27e151e4c8cbcda78b29fe734df6733818783461
use std::collections::HashMap; #[derive(Default, Debug, Clone)] struct DetDie { state: i32, roll_count: i32, } impl Iterator for DetDie { type Item = i32; fn next(&mut self) -> Option<i32> { self.roll_count += 1; let value = self.state + 1; self.state = (self.state + 1) % 10...
use std::collections::HashMap; #[derive(Default, Debug, Clone)] struct DetDie { state: i32, roll_count: i32, } impl Iterator for DetDie { type Item = i32; fn next(&mut self) -> Option<i32> { self.roll_count += 1; let value = self.state + 1; self.state = (self.state + 1) % 10...
throw_count + 1, throw_way_map, ); } return new_ways; } *throw_way_map.entry(throw_count).or_insert(0) += ways; ways } pub fn step2() { let mut p1_throw_ways = HashMap::new(); let p1_complete = run_game(21, 8, 1, 0, &mut p...
, i128>, ) -> i128 { let roll_dist: HashMap<i32, i128> = HashMap::from_iter([(3, 1), (4, 3), (5, 6), (6, 7), (7, 6), (8, 3), (9, 1)]); if remain > 0 { let mut new_ways = 0; for roll_sum in 3..=9 { let possibilities = roll_dist.get(&roll_sum).unwrap(); let new_pos...
function_block-random_span
[ { "content": "pub fn step1() {\n\n let hm = HeightMap::new(\"inputs/day09.txt\");\n\n\n\n println!(\"{}\", hm.risk_level());\n\n}\n\n\n", "file_path": "src/day09.rs", "rank": 0, "score": 153179.67823020153 }, { "content": "pub fn step1() {\n\n let mut game = Game::new(\"inputs/day04...
Rust
src/types.rs
pitkley/i3nator
c79dc059d7f174ac0ef4823769149dec537ed063
use crate::{configfiles::ConfigFile, layouts::Layout as ManagedLayout, shlex}; use serde::{ de::{self, Deserializer}, Deserialize, }; #[cfg(unix)] use std::os::unix::ffi::OsStrExt; use std::{ borrow::Cow, ffi::{OsStr, OsString}, fmt, marker::PhantomData, path::{Path, PathBuf}, time::Du...
use crate::{configfiles::ConfigFile, layouts::Layout as ManagedLayout, shlex}; use serde::{ de::{self, Deserializer}, Deserialize, }; #[cfg(unix)] use std::os::unix::ffi::OsStrExt; use std::{ borrow::Cow, ffi::{OsStr, OsString}, fmt, marker::PhantomData, path::{Path, PathBuf}, time::Du...
fn deserialize_exec<'de, D>(deserializer: D) -> Result<Exec, D::Error> where D: Deserializer<'de>, { impl<'de> de::Visitor<'de> for Phantom<Exec> { type Value = Exec; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("string, sequence of stri...
fn deserialize_duration<'de, D>(deserializer: D) -> Result<Duration, D::Error> where D: Deserializer<'de>, { impl<'de> de::Visitor<'de> for Phantom<Duration> { type Value = Duration; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("integer or...
function_block-full_function
[ { "content": "fn exec_text(base_parameters: &[&str], text: &str, timeout: Duration) -> Result<()> {\n\n let args = &[base_parameters, &[\"type\", \"--window\", \"%1\", text]].concat();\n\n let mut child = Command::new(\"xdotool\")\n\n .args(args)\n\n .stdin(Stdio::null())\n\n .stdout(...
Rust
snapshot/src/logic.rs
AllSafeCybercurity/RClient
88aa5fe784621041b05038ae62139398a34b74bc
use sodiumoxide::crypto::{ hash, pwhash, secretstream::{self, Header, Key, Pull, Push, Stream, Tag}, }; use std::{ fs::File, io::{Read, Write}, }; const CHUNK_SIZE: usize = 4096; const SIGN: [u8; 5] = [0x50, 0x41, 0x52, 0x54, 0x49]; const VERSION: [u8; 2] = [0x1, 0x0]; fn generate_salt() -> crate...
use sodiumoxide::crypto::{ hash, pwhash, secretstream::{self, Header, Key, Pull, Push, Stream, Tag}, }; use std::{ fs::File, io::{Read, Write}, }; const CHUNK_SIZE: usize = 4096; const SIGN: [u8; 5] = [0x50, 0x41, 0x52, 0x54, 0x49]; const VERSION: [u8; 2] = [0x1, 0x0]; fn generate_salt() -> crate...
=> return Err(crate::Error::SnapshotError("Incorrect Password".into())), _ => return Err(crate::Error::SnapshotError("Decryption failed... ".into())), } } Ok(()) } fn check_file_len(input: &mut File) -> crate::Result<()> { if input.metadata()?.len() <= (pwhash::SALTBYTES + secretstrea...
assword, &salt)?; let mut buf = [0u8; CHUNK_SIZE + secretstream::ABYTES]; let mut stream = pull_stream(&header, &key)?; while stream.is_not_finalized() { match input.read(&mut buf) { Ok(bytes_read) if bytes_read > 0 => { let (dec...
function_block-random_span
[ { "content": "/// HChaCha20 implementation\n\npub fn h_chacha20_hash(key: &[u8], nonce: &[u8], buf: &mut [u8]) {\n\n // initialize state\n\n let mut state = vec![0u32; 16];\n\n (0..4).for_each(|i| state[i] = BASIS[i]);\n\n (4..12).for_each(|i| state[i] = read32_little_endian!(&key[(i - 4) * 4..]));\...
Rust
aoc2020/src/main.rs
kylewillmon/advent-of-code-rs
f6d37627eabe4b39f87329159b11aedf59362b73
use std::io::{self, Read}; use std::fs; use clap::{App, Arg}; use aoclib::{self, AOC, Day}; pub(crate) mod parse; pub(crate) mod error; mod day1; mod day2; mod day3; mod day4; mod day6; mod day7; mod day8; mod day9; mod day10; mod day11; mod day12; mod day13; mod day14; mod day15; mod day16; mod day17; mod day18; mod ...
use std::io::{self, Read}; use std::fs; use clap::{App, Arg}; use aoclib::{self, AOC, Day}; pub(crate) mod parse; pub(crate) mod error; mod day1; mod day2; mod day3; mod day4; mod day6; mod day7; mod day8; mod day9; mod day10; mod day11; mod day12; mod day13; mod day14; mod day15; mod day16; mod day17; mod day18; mod ...
et_input<P: AsRef<str>>(filename: P) -> io::Result<String> { if filename.as_ref() == "-" { let mut data = String::new(); return io::stdin().read_to_string(&mut data).map(move |_| data); } fs::read_to_string(filename.as_ref()) }
ew(8) .part(1, day8::part1) .part(2, day8::part2)) .day(Day::new(9) .part(1, day9::part1) .part(2, day9::part2)) .day(Day::new(10) .part(1, day10::part1) .part(2, day10::part2)) .day(Day::new(11) .part(1, day11::...
random
[ { "content": "pub fn part2(input: String) -> Result<usize, AocError> {\n\n let mut total = 0;\n\n for entry in input.split(\"\\n\\n\") {\n\n let cf = entry.parse::<CustomsForm>()?;\n\n total += cf.everyone_yes_count();\n\n }\n\n Ok(total)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n u...
Rust
verifier/src/verify_merkle.rs
patrickbiel01/Cairo_Verifier
c174b5d5bc906cb64c832534ffac74268bd9b308
use num256::uint256::Uint256 as Uint256; use crate::uint256_ops; pub fn get_hash_mask() -> Uint256 { return uint256_ops::get_uint256("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000"); } /* Verifies a Merkle tree decommitment for n leaves in a Merkle tree with N leaves. The inputs da...
use num256::uint256::Uint256 as Uint256; use crate::uint256_ops; pub fn get_hash_mask() -> Uint256 { return uint256_ops::get_uint256("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000"); } /* Verifies a Merkle tree decommitment for n leaves in a Merkle tree with N leaves. The inputs da...
x % 2; sibling_data[1 ^ sibling_offset] = uint256_ops::to_fixed_bytes( &ctx[rd_idx + hashes_index] ); rd_idx = ( rd_idx + slot_size ) % queue_size; let mut new_hash_index = proof_idx; proof_idx += 1; ...
function_block-function_prefixed
[ { "content": "pub fn read_hash(channel_idx: usize, mix: bool, ctx: &mut Vec<Uint256>) -> Uint256 {\n\n\tlet val = read_bytes(channel_idx, mix, ctx);\n\n\treturn val;\n\n}\n\n\n\n\n\n\n\n\n", "file_path": "verifier/src/verifier_channel.rs", "rank": 0, "score": 340848.0792643196 }, { "content"...
Rust
src/watcher.rs
rakaly/desktop
4d16ef506704109c4300410a2f6fc12d2fef51e7
use anyhow::{anyhow, Context}; use flate2::bufread::GzEncoder; use flate2::Compression; use log::{debug, info, warn}; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher}; use std::fs::File; use std::io::{BufReader, Read}; use std::path::Path; use std::sync::mpsc::channel; use std::time::Duration; pub struct ...
use anyhow::{anyhow, Context}; use flate2::bufread::GzEncoder; use flate2::Compression; use log::{debug, info, warn}; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher}; use std::fs::File; use std::io::{BufReader, Read}; use std::path::Path; use std::sync::mpsc::channel; use std::time::Duration; pub struct ...
fn upload_txt(&self, path: &Path) -> anyhow::Result<()> { let file = File::open(path).context("unable to open")?; let reader = BufReader::new(file); let mut buffer = Vec::new(); let mut gz = GzEncoder::new(reader, Compression::new(4)); gz.read_to_end(&mut buffer).context("u...
g() .context("unable to interpret eror server response")?; Err(anyhow!("server responded with an error: {}", err)) } }
function_block-function_prefixed
[ { "content": "pub fn write_minimal_config<P: AsRef<Path>>(\n\n input: &UserInputConfig,\n\n destination: P,\n\n) -> anyhow::Result<UploaderConfig> {\n\n let path = destination.as_ref();\n\n let config_data =\n\n toml::ser::to_vec(&input).context(\"unable to serialize user input to a config\")...
Rust
src/compile.rs
shino16/cargo-auto-bundle
1cbd9fe1a3a8ea7f6ca499372a6d9eb7ca0edd8a
use super::ModPath; use anyhow::Result; use itertools::Itertools; use proc_macro2::{Ident, Span}; use quote::ToTokens; use std::{ collections::BTreeMap, path::{Path, PathBuf}, }; pub fn compile( crate_name: &str, paths: &[ModPath], file_paths: &[PathBuf], mod_visibility: BTreeMap<ModPath, Strin...
use super::ModPath; use anyhow::Result; use itertools::Itertools; use proc_macro2::{Ident, Span}; use quote::ToTokens; use std::{ collections::BTreeMap, path::{Path, PathBuf}, }; pub fn compile( crate_name: &str, paths: &[ModPath], file_paths: &[PathBuf], mod_visibility: BTreeMap<ModPath, Strin...
fn visit_item_mod(&mut self, item: &'ast syn::ItemMod) { if item.semi.is_some() { let mut iter = item.to_token_stream().into_iter(); let start = iter.next().unwrap().span(); let end = iter.last().unwrap().span(); self.remove_spans.push((start, ...
function_block-function_prefix_line
[ { "content": "fn visit_use_file(path: &Path) -> Result<Vec<ModPath>> {\n\n use syn::UseTree::{self, *};\n\n fn dfs(tree: &UseTree, prefix: &mut ModPath, buf: &mut Vec<ModPath>) {\n\n match tree {\n\n Path(path) => {\n\n prefix.push(path.ident.to_string());\n\n ...
Rust
fabric_contract/src/dataapi/wirebuffer.rs
wtllc/fabric-contract-api-rust
6cf261d7795f1e26169934757422bf13772c9589
/* * SPDX-License-Identifier: Apache-2.0 */ use super::TypeSchema; use std::fmt::Debug; pub struct WireBuffer { pub buffer: Option<Vec<u8>>, pub schema: TypeSchema, } impl WireBuffer { pub fn new( buffer: Vec<u8>, schema: TypeSchema, /*, converter: Box<dyn Converter>*/ ) -> Self...
/* * SPDX-License-Identifier: Apache-2.0 */ use super::TypeSchema; use std::fmt::Debug; pub struct WireBuffer { pub buffer: Option<Vec<u8>>, pub schema: TypeSchema, } impl WireBuffer { pub fn new( buffer: Vec<u8>, schema: TypeSchema, /*, converter: Box<dyn Converter>*/ ) -> Self...
} impl WireBufferFromReturnType<i8> for WireBuffer { fn from_rt(self: &mut Self, s: i8) { self.buffer = Some(s.to_string().into_bytes()); } } impl WireBufferFromReturnType<i16> for WireBuffer { fn from_rt(self: &mut Self, s: i16) { self.buffer = Some(s.to_string().into_b...
fn from_rt(self: &mut Self, b: bool) { self.buffer = match b { true => Some(b"true".to_vec()), false => Some(b"false".to_vec()), }; }
function_block-full_function
[ { "content": "pub trait Converter {\n\n fn into_string(&self, buffer: &[u8], ts: &TypeSchema) -> String;\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\npub struct JSONConverter {}\n\n\n\nimpl Converter for JSONConverter {\n\n // straight conversion\n\n fn into_string(&self, buffer: &[u8], ts: &TypeSchema...
Rust
src/imapw.rs
mordak/runt
03ac329c54d61a05d2390f28c963f2a7d8c9a590
use crate::config::Account; use imap::extensions::idle; use imap::types::{Fetch, Flag, Mailbox, Name, Uid, UnsolicitedResponse, ZeroCopy}; use imap::Session; use imap::{Client, ClientBuilder}; use rustls_connector::TlsStream as RustlsStream; use std::convert::From; use std::net::TcpStream; use std::ops::Deref; use std:...
use crate::config::Account; use imap::extensions::idle; use imap::types::{Fetch, Flag, Mailbox, Name, Uid, UnsolicitedResponse, ZeroCopy}; use imap::Session; use imap::{Client, ClientBuilder}; use rustls_connector::TlsStream as RustlsStream; use std::convert::From; use std::net::TcpStream; use std::ops::Deref; use std:...
last.unwrap())), }; let qresync = match changedsince { None => "".to_string(), Some(n) => format!(" (CHANGEDSINCE {} VANISHED)", n), }; self.session .uid_fetch( range, format!("(UID RFC822.SIZE INTERNALDATE FLAGS){}",...
le(idle::stop_on_any) .map_err(|e| format!("{}", e)) .map(|_| ()) */ self.session .idle() .map_err(|e| format!("{}", e)) .and_then(|mut i| { i.set_keepalive(Duration::from_secs(10 * 60)); i.wait_keepalive_while(i...
random
[ { "content": "// FIXME: Move this to imapw?\n\n/// Convert imap flags to maildir flags\n\npub fn maildir_flags_from_imap(inflags: &[Flag]) -> String {\n\n let syncflags = SyncFlags::from(inflags);\n\n syncflags.to_string()\n\n}\n\n\n", "file_path": "src/cache/mod.rs", "rank": 0, "score": 12506...
Rust
src/drivers/keyboard.rs
arbel03/os
ba061f795cc6e492dd752344e43d4d8e4896d5f3
use drivers::utils::inb; #[derive(Copy, Clone, PartialEq, Eq)] pub enum ScanCodeType { Digit(u8), Character(char), Shift, Backspace, Enter, Space, Quote, } pub struct ScanCode { pub released: bool, pub scan_code_type: ScanCodeType, } #[derive(PartialEq)] pub enum ScanCodeError { ...
use drivers::utils::inb; #[derive(Copy, Clone, PartialEq, Eq)] pub enum ScanCodeType { Digit(u8), Character(char), Shift, Backspace, Enter, Space, Quote, } pub struct ScanCode { pub released: bool, pub scan_code_type: ScanCodeType, } #[derive(PartialEq)] pub enum ScanCodeError { ...
} } } }
match c.get_char() { Ok(character) => return character as usize, Err(scan_code_error) => { if scan_code_error == ScanCodeError::BackspaceScancode { return 0xffffffff; } } ...
if_condition
[ { "content": "pub fn proc_info(info_struct_ptr: *mut u8, proc_number: usize) -> usize {\n\n #[repr(packed)]\n\n #[derive(Debug)]\n\n pub struct ProcInfo {\n\n pub process_index: u32,\n\n pub process_name_length: u32,\n\n pub process_base: u32,\n\n pub process_total_size: u32...
Rust
benches/hash.rs
flier/rust-t1ha
163460ad90b424e75a5480cfe3c94edafc4883ef
#![allow(deprecated)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate criterion; use std::collections::hash_map::DefaultHasher; use std::hash::{Hasher, BuildHasher}; use std::hash::SipHasher; use std::io::BufReader; use std::mem; use std::slice; use criterion::{black_box, Criterion, ParameterizedBen...
#![allow(deprecated)] #[macro_use] extern crate lazy_static; #[macro_use] extern crate criterion; use std::collections::hash_map::DefaultHasher; use std::hash::{Hasher, BuildHasher}; use std::hash::SipHasher; use std::io::BufReader; use std::mem; use std::slice; use criterion::{black_box, Criterion, ParameterizedBen...
fn bench_hash32(c: &mut Criterion) { c.bench( "hash32", ParameterizedBenchmark::new( "t1ha0_32", move |b, &&size| { b.iter(|| t1ha0_32(&DATA[..size], SEED)); }, &PARAMS, ) .with_function("murmur3_32", move |b, &&size| ...
fn bench_memory(c: &mut Criterion) { c.bench( "memory", ParameterizedBenchmark::new( "sum", move |b, &&size| { let s = unsafe { slice::from_raw_parts(DATA.as_ptr() as *mut u32, size / mem::size_of::<u32>()) }; ...
function_block-full_function
[ { "content": "#[cfg(not(feature = \"unaligned_access\"))]\n\npub fn t1ha1_be(data: &[u8], seed: u64) -> u64 {\n\n if !aligned_to::<u64, _>(data.as_ptr()) {\n\n unsafe { t1h1_body::<BigEndianUnaligned<u64>>(data, seed) }\n\n } else {\n\n unsafe { t1h1_body::<BigEndianAligned<u64>>(data, seed)...
Rust
src/style/builder.rs
vinaychandra/embedded-text
71c5e8abbb940deff1fcbab0c06c2c2fced5de10
use crate::{ alignment::{HorizontalTextAlignment, LeftAligned, TopAligned, VerticalTextAlignment}, style::{ height_mode::{Exact, HeightMode}, vertical_overdraw::FullRowsOnly, TabSize, TextBoxStyle, }, }; use embedded_graphics::{ prelude::*, style::{TextStyle, TextStyleBuilde...
use crate::{ alignment::{HorizontalTextAlignment, LeftAligned, TopAligned, VerticalTextAlignment}, style::{ height_mode::{Exact, HeightMode}, vertical_overdraw::FullRowsOnly, TabSize, TextBoxStyle, }, }; use embedded_graphics::{ prelude::*, style::{TextStyle, TextStyleBuilde...
Self { text_style_builder, ..self } } #[inline] #[must_use] pub fn alignment<TA: HorizontalTextAlignment>( self, alignment: TA, ) -> TextBoxStyleBuilder<C, F, TA, V, H> { TextBoxStyleBuilder { text_style_builder: sel...
if let Some(color) = text_style.text_color { text_style_builder = text_style_builder.text_color(color); }
if_condition
[ { "content": "fn demo_loop<V>(window: &mut Window, bounds: &mut Rectangle, alignment: V) -> bool\n\nwhere\n\n V: VerticalTextAlignment + std::fmt::Debug,\n\n for<'a> &'a StyledTextBox<'a, BinaryColor, Font6x8, LeftAligned, TopAligned, Exact<FullRowsOnly>>:\n\n Drawable<BinaryColor>,\n\n{\n\n let...
Rust
crates/apps/plugin-host/plugin-host-lib/src/commands/options/mod.rs
yamadapc/augmented-audio
2f662cd8aa1a0ba46445f8f41c8483ae2dc552d3
use clap::{App, ArgMatches}; #[derive(Clone)] pub struct RunOptions { plugin_path: String, input_audio: Option<String>, output_audio: Option<String>, open_editor: bool, watch: bool, audio_host_id: Option<String>, output_device_id: Option<String>, buffer_size: Option<usize>, sample_r...
use clap::{App, ArgMatches}; #[derive(Clone)] pub struct RunOptions { plugin_path: String, input_audio: Option<String>, output_audio: Option<String>, open_editor: bool, watch: bool, audio_host_id: Option<String>, output_device_id: Option<String>, buffer_size: Option<usize>, sample_r...
") .map(|value| value.parse().expect("Invalid buffer size")); let sample_rate = matches .value_of("sample-rate") .map(|value| value.parse().expect("Invalid sample rate")); let input_device_id = matches .value_of("input-device-id") .map(|value| value.to_string()); let ...
ze> { self.sample_rate } pub fn input_device_id(&self) -> &Option<String> { &self.input_device_id } pub fn use_default_input_device(&self) -> bool { self.use_default_input_device } pub fn use_mono_input(&self) -> Option<usize> { self.use_mono_input } } pub...
random
[ { "content": "/// Check if there's a non-null CFBundle with this identifier.\n\npub fn has_bundle(bundle_identifier: &str) -> bool {\n\n unsafe {\n\n let bundle_identifier = make_cfstring(bundle_identifier);\n\n if let Some(bundle_identifier) = bundle_identifier {\n\n let bundle = CF...
Rust
kaylee/src/instructions/math.rs
electricjones/kaylee
6cdc7e67ae8a3d9a989d8d18def496c9ceecab40
use std::fmt::Error; use kaylee_derive::Instruction; use crate::instructions; use crate::instructions::{display_instruction_with_values, Executable, Instruction, InstructionDocumentation, InstructionSignature, OperandType, OperandValues}; use crate::vm::{ExecutionResult, Kaylee, RegisterValue}; #[derive(Instructio...
use std::fmt::Error; use kaylee_derive::Instruction; use crate::instructions; use crate::instructions::{display_instruction_with_values, Executable, Instruction, InstructionDocumentation, InstructionSignature, OperandType, OperandValues}; use crate::vm::{ExecutionResult, Kaylee, RegisterValue}; #[derive(Instructio...
}
c![ Add::OPCODE, 29, 0, 2, Add::OPCODE, 30, 29, 2, Subtract::OPCODE, 30, 29, 1, Add::OPCODE, 28, 3, 4, Multiply::OPCODE, 31, 3, 2, Divide::OPCODE, 3, 29, 30, Subtract::OPCODE, 4, 2, 30, Add::OPCODE, 0, 3, 28, Mul...
function_block-function_prefixed
[ { "content": "/// Decodes the operand values from the Instruction Stream\n\npub fn consume_and_parse_values(signature: InstructionSignature, instructions: &Program, program_counter: &mut usize) -> Result<OperandValues, InstructionDecodeError> {\n\n let mut operand_values: OperandValues = [OperandValue::None,...
Rust
mgl_resource_derive/src/lib.rs
fcard/MGL
9d41d30ce58451b80aa6e0d255b0c398c679b86b
#![feature(box_patterns)] extern crate proc_macro; use proc_macro2::{TokenStream, Span}; use syn::*; use quote::*; macro_rules! ident { ($name: ident) => { Ident::new(stringify!($name), Span::call_site()) } } #[proc_macro_derive(Resource, attributes(array_field, sub_resource, ignore_field))] pub fn derive_resou...
#![feature(box_patterns)] extern crate proc_macro; use proc_macro2::{TokenStream, Span}; use syn::*; use quote::*; macro_rules! ident { ($name: ident) => { Ident::new(stringify!($name), Span::call_site()) } } #[proc_macro_derive(Resource, attributes(array_field, sub_resource, ignore_field))] pub fn derive_resou...
else if attr.path.is_ident(&ident!(array_field)) { attributes.array = true; } else if attr.path.is_ident(&ident!(ignore_field)) { attributes.ignore = true; } } attributes }
function_block-function_prefix_line
[ { "content": "pub fn parse_key(mut tks: InnerTokens) -> Key {\n\n let name = tks.next().unwrap().as_str();\n\n let mut key = Key::name(name);\n\n\n\n while let Some(rule) = tks.peek().map(|p| p.as_rule()) {\n\n match rule {\n\n Rule::name => {\n\n let right = parse_key(tks);\n\n key = K...
Rust
sdks/rust/src/sdk.rs
xxtanisxx/agones
3f00aa67518a8f3e43b02415c228808f1511d3cb
use std::{env, time::Duration}; use tonic::transport::Channel; mod api { tonic::include_proto!("agones.dev.sdk"); } use api::sdk_client::SdkClient; pub use api::GameServer; pub type WatchStream = tonic::Streaming<GameServer>; use crate::{alpha::Alpha, errors::Result}; #[inline] fn empty() -> api::Empty { ...
use std::{env, time::Duration}; use tonic::transport::Channel; mod api { tonic::include_proto!("agones.dev.sdk"); } use api::sdk_client::SdkClient; pub use api::GameServer; pub type WatchStream = tonic::Streaming<GameServer>; use crate::{alpha::Alpha, errors::Result}; #[inline] fn empty() -> api::Empty { ...
#[inline] pub fn alpha(&self) -> &Alpha { &self.alpha } pub async fn ready(&mut self) -> Result<()> { Ok(self.client.ready(empty()).await.map(|_| ())?) } pub async fn allocate(&mut self) -> Result<()> { Ok(self.client.allocate(empty()).await.map(|_| ())...
pub async fn new(port: Option<u16>, keep_alive: Option<Duration>) -> Result<Self> { let addr: http::Uri = format!( "http://localhost:{}", port.unwrap_or_else(|| { env::var("AGONES_SDK_GRPC_PORT") .ok() .and_then(|s| s.parse().ok()) ...
function_block-full_function
[ { "content": "struct SDK::SDKImpl {\n\n std::string host_;\n\n std::shared_ptr<grpc::Channel> channel_;\n\n std::unique_ptr<agones::dev::sdk::SDK::Stub> stub_;\n\n std::unique_ptr<grpc::ClientWriter<agones::dev::sdk::Empty>> health_;\n\n std::unique_ptr<grpc::ClientContext> health_context_;\n\n};\n\n\n\nSD...
Rust
athena-coreserver/src/services/unit_service.rs
athena-intelli/athena-rs
7546137e14c3248fe20c2a68626beffc0c9ab7d3
use tokio_stream::wrappers::ReceiverStream; use tonic::{Request, Response, Status}; use athena_api::pb::structures::{ChangePriorityRequest, Unit}; use athena_api::pb::unit_service::*; use athena_api::pb::unit_service::unit_service_server::UnitService; #[derive(Default)] pub struct UnitServiceImpl; #[tonic::async_trai...
use tokio_stream::wrappers::ReceiverStream; use tonic::{Request, Response, Status}; use athena_api::pb::structures::{ChangePriorityRequest, Unit}; use athena_api::pb::unit_service::*; use athena_api::pb::unit_service::unit_service_server::UnitService; #[derive(Default)] pub struct UnitServiceImpl; #[tonic::async_trai...
, Status> { todo!() } async fn complete_at_route_step(&self, request: Request<UnitCompleteAtRouteStepRequest>) -> Result<Response<Unit>, Status> { todo!() } async fn start_at_route_step(&self, request: Request<UnitStartAtRouteStepRequest>) -> Result<Response<Unit>, Status> { to...
nse<Unit>, Status> { todo!() } async fn undo_finish(&self, request: Request<TransitionUnitRequest>) -> Result<Response<Unit>, Status> { todo!() } async fn undo_scrap(&self, request: Request<TransitionUnitRequest>) -> Result<Response<Unit>, Status> { todo!() } async fn ...
random
[ { "content": " #[doc = \"Generated trait containing gRPC methods that should be implemented for use with UnitServiceServer.\"]\n\n #[async_trait]\n\n pub trait UnitService: Send + Sync + 'static {\n\n async fn add_to_queue(\n\n &self,\n\n request: tonic::Request<super::AddU...
Rust
layer_core/src/entry.rs
Sorenon/sorenon_openxr_layer
f32597269ac70ac63b7eb7ec9c6300cd8e6eca64
use std::ops::Deref; use std::sync::atomic::AtomicBool; use std::{ffi::CStr, sync::Arc}; use crate::loader_interfaces::*; use crate::wrappers::instance::{InnerInstance, InstanceWrapper, Runtime}; use crate::wrappers::XrHandle; use crate::ToResult; use log::{debug, error, info}; use openxr::sys as xr; use openxr::{Ex...
use std::ops::Deref; use std::sync::atomic::AtomicBool; use std::{ffi::CStr, sync::Arc}; use crate::loader_interfaces::*; use crate::wrappers::instance::{InnerInstance, InstanceWrapper, Runtime}; use crate::wrappers::XrHandle; use crate::ToResult; use log::{debug, error, info}; use openxr::sys as xr; use openxr::{Ex...
dows Mixed Reality Runtime" => Runtime::WMR, "Monado(XRT) by Collabora et al" => Runtime::Monado, _ => Runtime::Other(runtime_name.to_string()), }; let wrapper = InstanceWrapper { handle: *instance, inner: Arc::new(inner), systems: Default::default(), sessions: D...
ult> { let next_info = &unsafe { *layer_info.next_info }; if unsafe { CStr::from_ptr(std::mem::transmute(next_info.layer_name.as_ptr())) } .to_string_lossy() != crate::LAYER_NAME { error!( "Crate instance failed: Incorrect layer_name `{}`", unsafe { CStr::fro...
random
[ { "content": "type Func<H, T> = unsafe extern \"system\" fn(\n\n handle: H,\n\n format_capacity_input: u32,\n\n format_count_output: *mut u32,\n\n out: *mut T,\n\n) -> xr::Result;\n\n\n\npub unsafe fn call_enumerate<H: Copy, T: Copy>(\n\n handle: H,\n\n f: Func<H, T>,\n\n default: T,\n\n) -...
Rust
src/handlers/common/global.rs
ALinuxPerson/try-drop
1b2ac32ba746747f3af51278a689d19a94261691
pub(crate) mod imports {} use crate::handlers::common::Handler; use crate::handlers::UninitializedError; use parking_lot::{ MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLock, RwLockReadGuard, RwLockWriteGuard, }; use std::marker::PhantomData; pub trait GlobalDefinition: Handler { const UNINITIALIZED_ERROR...
pub(crate) mod imports {} use crate::handlers::common::Handler; use crate::handlers::UninitializedError; use parking_lot::{ MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLock, RwLockReadGuard, RwLockWriteGuard, }; use std::marker::PhantomData; pub trait GlobalDefinition: Handler { const UNINITIALIZED_ERROR...
pub fn write() -> MappedRwLockWriteGuard<'static, T::Global> { Self::try_write().expect(T::UNINITIALIZED_ERROR) } pub fn uninstall() { *T::global().write() = None } } impl<T: DefaultGlobalDefinition> Global<T> { pub fn read_or_default() -> MappedRwLockReadGuard<'static, T::Global...
bal.is_some() { Ok(RwLockWriteGuard::map(global, |global| { global.as_mut().unwrap() })) } else { Err(UninitializedError(())) } }
function_block-function_prefixed
[ { "content": "pub trait Handler: private::Sealed {}\n\n\n\npub enum Primary {}\n\nimpl private::Sealed for Primary {}\n\nimpl Handler for Primary {}\n\n\n\npub enum Fallback {}\n\nimpl private::Sealed for Fallback {}\n\nimpl Handler for Fallback {}\n\n\n", "file_path": "src/handlers/common/mod.rs", "ran...
Rust
crates/taplo-cli/src/commands/toml_test.rs
koalp/taplo
03044c5d4fd2ab64656d371ad2043ccd0146325b
use crate::Taplo; use anyhow::anyhow; use serde::{ ser::{SerializeMap, SerializeSeq}, Serialize, }; use taplo::dom::{ node::{DateTimeValue, DomNode}, Node, }; use taplo_common::environment::Environment; use tokio::io::AsyncReadExt; impl<E: Environment> Taplo<E> { pub async fn execute_toml_test(&sel...
use crate::Taplo; use anyhow::anyhow; use serde::{ ser::{SerializeMap, SerializeSeq}, Serialize, }; use taplo::dom::{ node::{DateTimeValue, DomNode}, Node, }; use taplo_common::environment::Environment; use tokio::io::AsyncReadExt; impl<E: Environment> Taplo<E> { pub async fn execute_toml_test(&sel...
Node::Float(f) if f.value().is_nan() => String::from("nan"), Node::Float(f) if f.value().is_infinite() => f.syntax().unwrap().to_string(), _ => serde_json::to_string(&self.node).map_err(serde::ser::Error::custom)?, }, )?; map.end()...
r> where S: serde::Serializer, { if let Some(ty) = self.r#type { let mut map = serializer.serialize_map(Some(2))?; map.serialize_entry("type", &ty)?; map.serialize_entry( "value", &match self.node { Node::Str...
random
[ { "content": "fn extract_value(node: &Node) -> Result<String, anyhow::Error> {\n\n Ok(match node {\n\n Node::Table(_) => {\n\n return Err(anyhow!(\n\n r#\"cannot print tables with the given output format, specify a different output format (e.g. with `-o json`) \"#\n\n ...
Rust
midi/src/message/system_common.rs
alisomay/koto_midi
7cf4579bb8d3c6c8bd4f29d7b101b4d2e8501a08
use crate::impl_midi_message; use crate::Category; use crate::MidiMessage; #[derive(Debug)] pub struct SystemExclusive { bytes: Vec<u8>, pub manufacturer_id: Vec<u8>, pub category: Category, } impl SystemExclusive { pub fn new(manufacturer_id: &[u8], message_content: &[u8]) -> Self { let mut me...
use crate::impl_midi_message; use crate::Category; use crate::MidiMessage; #[derive(Debug)] pub struct SystemExclusive { bytes: Vec<u8>, pub manufacturer_id: Vec<u8>, pub category: Category, } impl SystemExclusive { pub fn new(manufacturer_id: &[u8], message_content: &[u8]) -> Self { let mut me...
} impl_midi_message!(SystemExclusive); impl_midi_message!(TimeCodeQuarterFrame); impl_midi_message!(SongPosition); impl_midi_message!(SongSelect); impl_midi_message!(TuneRequest); impl_midi_message!(EndOfExclusive);
fn from(raw_bytes: &[u8]) -> Self { EndOfExclusive { bytes: [raw_bytes[0]], category: Category::SystemCommon, } }
function_block-full_function
[ { "content": "// TODO: Solve unnecessary repetition of list collectors for different types ot cases if there is.\n\npub fn collect_list_of_midi_bytes_as_u8(\n\n message: &ValueList,\n\n error: &str,\n\n) -> std::result::Result<Vec<u8>, RuntimeError> {\n\n let arguments = message\n\n .data()\n\n ...
Rust
avr-hal-generic/src/wdt.rs
IamTheCarl/avr-hal
10d311ba74a07289d0ad3afa05f4b22800a2ec7a
use core::marker::PhantomData; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Timeout { Ms16, Ms32, Ms64, Ms125, Ms250, Ms500, Ms1000, Ms2000, Ms4000, Ms8000, } pub trait WdtOps<H> { type MCUSR; ...
use core::marker::PhantomData; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Timeout { Ms16, Ms32, Ms64, Ms125, Ms250, Ms500, Ms1000, Ms2000, Ms4000, Ms8000, } pub trait WdtOps<H> { type MCUSR; ...
$crate::avr_device::interrupt::free(|_| { self.raw_feed(); self.wdtcsr .modify(|_, w| w.wdce().set_b...
timeout: |$to:ident, $w:ident| $to_match:expr, ) => { impl $crate::wdt::WdtOps<$HAL> for $WDT { type MCUSR = $MCUSR; #[inline] fn raw_init(&mut self, m: &Self::MCUSR) { m.modify(|_, w| w.wdrf().clear_bit()); ...
random
[ { "content": " pub trait Sealed {}\n\n}\n\npub(crate) use sealed::Sealed;\n", "file_path": "avr-hal-generic/src/lib.rs", "rank": 1, "score": 114647.06503214789 }, { "content": "/// A clock speed\n\npub trait Clock {\n\n /// Frequency of this clock in Hz\n\n const FREQ: u32;\n\n}\n\n...
Rust
src/main.rs
hardcorebadger/rustchain
e03bbf952726bf4e424f6be0331d8d9a8b16cef2
#[macro_use] extern crate lazy_static; #[macro_use] extern crate mime; #[macro_use] extern crate serde_derive; extern crate iron; extern crate router; extern crate serde; extern crate serde_json; extern crate uuid; extern crate bodyparser; use iron::prelude::*; use iron::status; use router::Router; use std::sync::{Arc...
#[macro_use] extern crate lazy_static; #[macro_use] extern crate mime; #[macro_use] extern crate serde_derive; extern crate iron; extern crate router; extern crate serde; extern crate serde_json; extern crate uuid; extern crate bodyparser; use iron::prelude::*; use iron::status; use router::Router; use std::sync::{Arc...
fn get_hello(_request: &mut Request) -> IronResult<Response> { let mut response = Response::new(); response.set_mut(status::Ok); response.set_mut(mime!(Text/Html; Charset=Utf8)); response.set_mut("Hey! I'm Rustchain, welcome to the future.\n"); Ok(response) } fn get_mine(_request: &mut Request, _chain: Arc<RwL...
fn main() { lazy_static! { static ref CHAIN: Arc<RwLock<Blockchain>> = { let mut chain: Arc<RwLock<Blockchain>> = Arc::new(RwLock::new(Blockchain::new())); chain }; } println!("Serving on http://localhost:3000...");...
function_block-full_function
[ { "content": "use std::fmt;\n\nuse transaction::Transaction;\n\n\n\n#[derive(Clone, Serialize, Deserialize)]\n\npub struct Block {\n\n\tpub index: i64,\n\n\tpub timestamp: i64,\n\n\tpub transactions: Vec<Transaction>,\n\n\tpub proof: i64,\n\n\tpub previous_hash: String\n\n\t//pub previous_hash: GenericArray<u8,...
Rust
src/lib.rs
mov-rax/smart_buffer
1ab3f45f1c2021d0cd5e87f25852a24dc569e40c
#![no_std] #![feature(min_const_generics)] #[macro_use] extern crate alloc; #[doc(hidden)] pub extern crate core as __core; use alloc::alloc::{alloc, dealloc, Layout}; use alloc::vec::Vec; use core::mem::size_of; use crate::iter::SmartBufferIterRef; use alloc::boxed::Box; use crate::__core::fmt::{Debug, Formatter}; ...
#![no_std] #![feature(min_const_generics)] #[macro_use] extern crate alloc; #[doc(hidden)] pub extern crate core as __core; use alloc::alloc::{alloc, dealloc, Layout}; use alloc::vec::Vec; use core::mem::size_of; use crate::iter::SmartBufferIterRef; use alloc::boxed::Box; use crate::__core::fmt::{Debug, Formatter}; ...
} pub fn new(value: T, len:usize) -> Self where T: Copy + Clone { let mut buf = Self{ s_buf: [value; N], d_buf: None, layout: None, size: 0, capacity: N, default: value, cursor: 0, }; if N ...
if let Ok(layout) = layout{ let ptr = unsafe {alloc(layout) as *mut T}; self.capacity += layout.size()/size_of::<T>(); self.layout = Some(layout); self.d_buf = Some(ptr); }
if_condition
[ { "content": "use crate::SmartBuffer;\n\nuse core::ops::Index;\n\nuse core::ops::IndexMut;\n\n\n\n\n\nimpl<T, const N:usize> Index<usize> for &SmartBuffer<T,N>\n\n where T: Clone\n\n{\n\n type Output = T;\n\n\n\n fn index(&self, index: usize) -> &Self::Output {\n\n unsafe {self.get_unchecked(ind...
Rust
src/sys/component_manager/src/model/events/source.rs
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
use { crate::{ capability::{CapabilityProvider, CapabilitySource, FrameworkCapability}, model::{ error::ModelError, events::{ event::SyncMode, registry::{EventRegistry, RoutedEvent}, serve::serve_event_source_sync, ...
use { crate::{ capability::{CapabilityProvider, CapabilitySource, FrameworkCapability}, model::{ error::ModelError, events::{ event::SyncMode, registry::{EventRegistry, RoutedEvent}, serve::serve_event_source_sync, ...
.into_iter() .filter(|event| !route_result.contains_event(&event)) .collect(); return Err(EventsError::NotAvailable { names }); } route_result.to_vec() }; if let Some(registry) = self.registry.upgrade() { ...
ption {:?}", names)] NotAvailable { names: Vec<CapabilityName> }, #[error("Routing failed")] RoutingFailed(#[source] ModelError), } struct RouteEventsResult { mapping: HashMap<CapabilityName, HashSet<AbsoluteMoniker>>, } impl RouteEventsResult { fn new() -> Self { Self { mapping...
random
[]
Rust
src/message.rs
media-cloud-ai/rs_http_worker
0848d1dec046ea13be1b3e75e90be73d698cd855
use amqp_worker::*; use amqp_worker::job::*; use reqwest; use reqwest::StatusCode; use std::fs::File; use std::io::prelude::*; pub fn process(message: &str) -> Result<JobResult, MessageError> { let job = Job::new(message)?; debug!("reveived message: {:?}", job); match job.check_requirements() { Ok...
use amqp_worker::*; use amqp_worker::job::*; use reqwest; use reqwest::StatusCode; use std::fs::File; use std::io::prelude::*; pub fn process(message: &str) -> Result<JobResult, MessageError> { let job = Job::new(message)?; debug!("reveived message: {:?}", job);
let source_path = job.get_string_parameter("source_path"); let destination_path = job.get_string_parameter("destination_path"); if source_path.is_none() { let result = JobResult::new(job.job_id, JobStatus::Error, vec![]) .with_message("missing source path parameter".to_string()); ...
match job.check_requirements() { Ok(_) => {} Err(message) => { return Err(message); } }
if_condition
[ { "content": "fn main() {\n\n println!(\"HTTP Worker (version {}) started \", env::var(\"VERSION\").expect(\"missing softwareversion\"));\n\n if env::var(\"VERBOSE\").is_ok() {\n\n simple_logger::init_with_level(Level::Debug).unwrap();\n\n } else {\n\n simple_logger::init_with_level(Level::Warn).unwrap...
Rust
code/src/example_catalog.rs
cloudfuse-io/buzz-rust
7199662d40de5da138b53a3c8e62aeaf69545848
use std::sync::Arc; use crate::datasource::{CatalogFile, CatalogTable, StaticCatalogTable}; use arrow::datatypes::{DataType, Field, Schema, TimeUnit}; pub fn nyc_taxi_cloudfuse_sample() -> CatalogTable { CatalogTable::new(Box::new(StaticCatalogTable::new( nyc_taxi_v1_schema(TimeUnit::Microsecond), ...
use std::sync::Arc; use crate::datasource::{CatalogFile, CatalogTable, StaticCatalogTable}; use arrow::datatypes::{DataType, Field, Schema, TimeUnit}; pub fn nyc_taxi_cloudfuse_sample() -> CatalogTable { CatalogTable::new(Box::new(StaticCatalogTable::new( nyc_taxi_v1_schema(TimeUnit::Microsecond), ...
474795751, vec!["2009/03".to_owned()], ), CatalogFile::new( "2009/04/data.parquet", 470914229, vec!["2009/04".to_owned()], ), CatalogFile::new( "2009/05/data.parquet", 489248...
388070114, vec!["2009/01".to_owned()], ), CatalogFile::new( "raw_5M/2009/02/data.parquet", 368127982, vec!["2009/02".to_owned()], ), CatalogFile::new( "raw_5M/2009/03/data.parquet...
random
[ { "content": "pub fn catalog_schema(partition_names: &[String]) -> Arc<Schema> {\n\n let mut fields = vec![\n\n Field::new(\"key\", DataType::Utf8, false),\n\n Field::new(\"length\", DataType::UInt64, false),\n\n ];\n\n for col in partition_names {\n\n fields.push(Field::new(col, D...
Rust
src/main.rs
jonathanmorley/rpg-cli
93a816e875287a884b5045c430dffbb4e2a4ce27
use game::Game; mod character; mod game; mod item; mod location; mod log; mod randomizer; use crate::location::Location; use clap::Clap; #[derive(Clap)] struct Opts { destination: Option<String>, #[clap(long)] pwd: bool, #[clap(long)] reset: bool, #[clap(long)] ...
use game::Game; mod character; mod game; mod item; mod location; mod log; mod randomizer; use crate::location::Location; use clap::Clap; #[derive(Clap)] struct Opts { destination: Option<String>, #[clap(long)] pwd: bool, #[clap(long)] reset: bool, #[clap(long)] ...
n => n, }; name.to_string() }
r) = game.go_to(&dest, run, bribe) { game.reset(); } } else { println!("No such file or directory"); std::process::exit(1); } } fn shop(game: &mut Game, item_name: &Option<String>) { if game.location.is_home() { if let Some(item_name) = item_name { le...
random
[]
Rust
crates/apollo-smith/src/input_value.rs
isabella232/apollo-rs
963b3552deaf7ba3a7eb5a698a90f20d0fc08242
use crate::{description::Description, directive::Directive, name::Name, ty::Ty, DocumentBuilder}; use arbitrary::Result; #[derive(Debug, Clone, PartialEq)] pub enum InputValue { Variable(Name), Int(i64), Float(f64), String(String), Boolean(bool), Null, Enum(Name), List(Vec<InputValue>)...
use crate::{description::Description, directive::Directive, name::Name, ty::Ty, DocumentBuilder}; use arbitrary::Result; #[derive(Debug, Clone, PartialEq)] pub enum InputValue { Variable(Name), Int(i64), Float(f64), String(String), Boolean(bool), Null, Enum(Name), List(Vec<InputValue>)...
} impl From<InputValue> for String { fn from(input_val: InputValue) -> Self { match input_val { InputValue::Variable(v) => format!("${}", String::from(v)), InputValue::Int(i) => format!("{i}"), InputValue::Float(f) => format!("{f}"), InputValue::String(s) =>...
fn from(input_value: InputValue) -> Self { match input_value { InputValue::Variable(v) => Self::Variable(v.into()), InputValue::Int(i) => Self::Int(i), InputValue::Float(f) => Self::Float(f), InputValue::String(s) => Self::String(s), InputValue::Boolea...
function_block-full_function
[ { "content": "enum NapSpots @testDirective(first: \"one\") {\n\n \"Top bunk of a cat tree.\"\n\n CAT_TREE\n\n BED\n\n CARDBOARD_BOX @deprecated(reason: \"Box was recycled.\")\n\n}\n\n\"#\n\n );\n\n }\n\n\n\n #[test]\n\n fn it_encodes_enum_extension() {\n\n let mut enum_ty_1 = EnumValu...
Rust
crates/store/src/state/mem_pool_state_db.rs
driftluo/godwoken
667a4bc435a9894b131cd804daf6403fd5cd4026
use crate::mem_pool_store::{ Value, MEM_POOL_COL_DATA, MEM_POOL_COL_SCRIPT, MEM_POOL_COL_SCRIPT_PREFIX, }; use crate::smt::mem_pool_smt_store::MemPoolSMTStore; use crate::{traits::KVStore, transaction::StoreTransaction}; use anyhow::Result; use gw_common::{error::Error as StateError, smt::SMT, state::State, H256}...
use crate::mem_pool_store::{ Value, MEM_POOL_COL_DATA, MEM_POOL_COL_SCRIPT, MEM_POOL_COL_SCRIPT_PREFIX, }; use crate::smt::mem_pool_smt_store::MemPoolSMTStore; use crate::{traits::KVStore, transaction::StoreTransaction}; use anyhow::Result; use gw_common::{error::Error as StateError, smt::SMT, state::State, H256}...
fn get_script_hash_by_short_address(&self, script_hash_prefix: &[u8]) -> Option<H256> { let mem_pool_store = self.db().mem_pool.load(); match mem_pool_store .get(MEM_POOL_COL_SCRIPT_PREFIX, script_hash_prefix) .and_then(|v| v.to_opt()) .or_else(|| { ...
fn get_script(&self, script_hash: &H256) -> Option<packed::Script> { let mem_pool_store = self.db().mem_pool.load(); mem_pool_store .get(MEM_POOL_COL_SCRIPT, script_hash.as_slice()) .and_then(|v| v.to_opt()) .or_else(|| { self.db() ...
function_block-full_function
[ { "content": "// Calculate compacted account root\n\npub fn calculate_state_checkpoint(root: &H256, count: u32) -> H256 {\n\n let mut hash = [0u8; 32];\n\n let mut hasher = new_blake2b();\n\n hasher.update(root.as_slice());\n\n hasher.update(&count.to_le_bytes());\n\n hasher.finalize(&mut hash);\...
Rust
src/lib.rs
SilverBzH/wasm-sorter
303cb7c16e764025d5b3d1eedeef219365892830
mod utils; use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SortType { Bubble, BubbleOptimizied, QuickSort, } #[wasm_bindgen] pu...
mod utils; use wasm_bindgen::prelude::*; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SortType { Bubble, BubbleOptimizied, QuickSort, } #[wasm_bindgen] pu...
#[test] fn bubble_optimized() { let mut data = vec![0,5,2,3,6,9,4,2,5,7,8,1,5,6]; let mut sorter = Sorter::new(data.clone()); sorter.run(SortType::BubbleOptimizied); data.sort(); let sucess = if data == sorter.get_data() {true} else {false}; assert_eq!(sucess, t...
let mut sorter = Sorter::new(data.clone()); sorter.run(SortType::Bubble); data.sort(); let sucess = if data == sorter.get_data() {true} else {false}; assert_eq!(sucess, true); }
function_block-function_prefix_line
[ { "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 least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
tests/test_casbin.rs
smrpn/actix-casbin
c4e91e518e3414ae9c3542f47ba04c358e38e1b1
use actix_casbin::{CasbinActor, CasbinCmd, CasbinResult}; use casbin::prelude::*; #[actix_rt::test] async fn test_enforcer() { let m = DefaultModel::from_file("examples/rbac_model.conf") .await .unwrap(); let a = FileAdapter::new("examples/rbac_policy.csv"); let addr = CasbinActor::<Enforce...
use actix_casbin::{CasbinActor, CasbinCmd, CasbinResult}; use casbin::prelude::*; #[actix_rt::test] async fn test_enforcer() { let m = DefaultModel::from_file("
, vec!["data1_admin", "data2_admin"] .iter() .map(|s| s.to_string()) .collect(), None, )) .await .unwrap() .unwrap() { assert_eq!(true, add_roles_for_user); } if let CasbinResult::DeleteRoleForUs...
examples/rbac_model.conf") .await .unwrap(); let a = FileAdapter::new("examples/rbac_policy.csv"); let addr = CasbinActor::<Enforcer>::new(m, a).await.unwrap(); if let CasbinResult::Enforce(test_enforce) = addr .send(CasbinCmd::Enforce( vec!["alice", "data1", "read"] ...
random
[ { "content": "use actix_casbin_auth::CasbinService;\n\n\n\n#[actix_rt::main]\n\nasync fn main() -> Result<()> {\n\n let m = DefaultModel::from_file(\"examples/rbac_model.conf\")\n\n .await?;\n\n let a = FileAdapter::new(\"examples/rbac_policy.csv\");\n\n\n\n let mut casbin_middleware = CasbinSer...
Rust
examples/iam/src/bin/iam-getting-started.rs
eduardomourar/aws-sdk-rust
58569c863afbe7bc442da8254df6c3970111de38
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. Purpose Shows how to use the AWS SDK for PHP (v3) to get started using AWS Identity and Access Management (IAM). Create an IAM user, assume a role, and perform AWS actions. 1. Create a user that has no per...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. Purpose Shows how to use the AWS SDK for PHP (v3) to get started using AWS Identity and Access Management (IAM). Create an IAM user, assume a role, and perform AWS actions. 1. Create a user that has no per...
y).await?; iam_service::delete_role(&client, &assume_role_role).await?; println!( "Deleted role {}", assume_role_role.role_name.as_ref().unwrap() ); iam_service::delete_access_key(&client, &user, &key).await?; println!("Deleted key for {}", key.user_name.as_ref().unwrap()); iam_s...
olicy: {}", list_all_buckets_policy.policy_name.as_ref().unwrap() ); let attach_role_policy_result = iam_service::attach_role_policy(&client, &assume_role_role, &list_all_buckets_policy) .await?; println!( "Attached the policy to the role: {:?}", attach...
random
[]
Rust
src/mdbook/fenced_blocks.rs
FifthTry/ft-cli
155c0765bc2e74d5d6dada52b95f8c4422d0e0a3
pub(crate) fn fenced_to_code(content: &str, img_src: &std::path::Path) -> String { #[derive(PartialEq)] enum ParsingState { WaitingForBackTick, WaitingForEndBackTick, } struct State { state: ParsingState, sections: Vec<String>, } let mut state = State { ...
pub(crate) fn fenced_to_code(content: &str, img_src: &std::path::Path) -> String { #[derive(PartialEq)] enum ParsingState { WaitingForBackTick, WaitingForEndBackTick, } struct State { state: ParsingState, sections: Vec<String>, } let mut state = State { ...
ftd::Markdown::from_body(&content).to_p1().to_string() } else { content }; state.sections.push(section); } } state.state = ParsingState::WaitingForEndBackTick; buffer = format!( ...
if let Some(html_parser::Node::Element(e)) = dom.children.get(0) { if let Some(html_parser::Node::Text(text)) = e.children.get(0) { let text = if text.contains(':') { match text.split(':').collect::<Vec<_>>().last() { Some(s)...
random
[ { "content": "fn content_with_extract_title(content: &str) -> (String, Option<String>) {\n\n let lines = content.lines().into_iter().collect::<Vec<_>>();\n\n let mut title_line = None;\n\n for line in lines.iter() {\n\n if line.trim().starts_with('#') {\n\n title_line = Some(line.to_s...
Rust
path_tracing/src/utilities.rs
sansumbrella/path-tracer-rs
9de8797bfa957b82393d1757b84c24357ddc0f02
use super::vector::*; use rand::distributions::{Distribution, UnitSphereSurface}; use rand::prelude::*; use std::borrow::Borrow; use std::ops::{Add, Mul, Sub}; pub fn mix<T, U>(a: T, b: T, t: U) -> T where T: Copy + Add<T, Output = T> + Sub<T, Output = T> + Mul<U, Output = T>, { a + (b - a) * t } pub fn rando...
use super::vector::*; use rand::distributions::{Distribution, UnitSphereSurface}; use rand::prelude::*; use std::borrow::Borrow; use std::ops::{Add, Mul, Sub}; pub fn mix<T, U>(a: T, b: T, t: U) -> T where T: Copy + Add<T, Output = T> + Sub<T, Output = T> + Mul<U, Output = T>, { a + (b - a) * t } pub fn rando...
pub fn cross<T, U>(a: T, b: U) -> Vec3 where T: Borrow<Vec3>, U: Borrow<Vec3>, { let &[ax, ay, az] = &a.borrow().0; let &[bx, by, bz] = &b.borrow().0; Vec3::new(ay * bz - az * by, -(ax * bz - az * bx), ax * by - ay * bx) } pub fn reflect<T, U>(vector: T, normal: U) -> Vec3 where T: Borrow<Ve...
pub fn dot<T, U>(a: T, b: U) -> f64 where T: Borrow<Vec3>, U: Borrow<Vec3>, { let &[ax, ay, az] = &a.borrow().0; let &[bx, by, bz] = &b.borrow().0; ax * bx + ay * by + az * bz }
function_block-full_function
[ { "content": "pub fn trace_scene(\n\n world: &World,\n\n camera: &Camera,\n\n rows: u32,\n\n columns: u32,\n\n num_samples: u32,\n\n) -> Vec<Vec3> {\n\n let colors: Vec<Vec3> = (0..(rows * columns))\n\n .into_par_iter()\n\n .map(|index| {\n\n let x = index % columns;\n...
Rust
rust/xaynet-server/src/state_machine/phases/sum2.rs
little-dude/xain-fl
9c421c03bf1b98c7717593c0856fe856b6f338f7
use xaynet_core::{ mask::{Aggregation, MaskObject}, SumDict, SumParticipantPublicKey, }; use crate::state_machine::{ coordinator::MaskDict, phases::{Handler, Phase, PhaseName, PhaseState, Shared, StateError, Unmask}, requests::{StateMachineRequest, Sum2Request}, StateMachine, StateMachi...
use xaynet_core::{ mask::{Aggregation, MaskObject}, SumDict, SumParticipantPublicKey, }; use crate::state_machine::{ coordinator::MaskDict, phases::{Handler, Phase, PhaseName, PhaseState, Shared, StateError, Unmask}, requests::{StateMachineRequest, Sum2Request}, StateMachine, StateMachi...
} } impl PhaseState<Sum2> { pub fn new( shared: Shared, sum_dict: SumDict, model_agg: Aggregation, scalar_agg: Aggregation, ) -> Self { info!("state transition"); Self { inner: Sum2 { sum_dict, model_agg, ...
match req { StateMachineRequest::Sum2(sum2_req) => { metrics!( self.shared.io.metrics_tx, metrics::message::sum2::increment(self.shared.state.round_id, Self::NAME) ); self.handle_sum2(sum2_req) } ...
if_condition
[ { "content": "/// A trait that must be implemented by a state to handle a request.\n\npub trait Handler {\n\n /// Handles a request.\n\n fn handle_request(&mut self, req: StateMachineRequest) -> Result<(), StateMachineError>;\n\n}\n\n\n\n/// I/O interfaces.\n\n#[derive(Debug)]\n\npub struct IO {\n\n //...
Rust
src/ppu/ppu_memory.rs
bheisler/Corrosion
5ca2b3a03825c3d58623df774a8596de32b46812
use super::Color; use super::TilePattern; use cart::Cart; use memory::MemSegment; use std::cell::UnsafeCell; use std::rc::Rc; pub struct PPUMemory { cart: Rc<UnsafeCell<Cart>>, vram: Box<[u8; 0x0F00]>, palette: [Color; 0x20], } impl PPUMemory { pub fn new(cart: Rc<UnsafeCell<Cart>>) -> ...
use super::Color; use super::TilePattern; use cart::Cart; use memory::MemSegment; use std::cell::UnsafeCell; use std::rc::Rc; pub struct PPUMemory { cart: Rc<UnsafeCell<Cart>>, vram: Box<[u8; 0x0F00]>, palette: [Color; 0x20], } impl PPUMemory { pub fn new(cart: Rc<UnsafeCell<Cart>>) -> ...
#[test] fn horizontal_mirroring_mirrors_horizontally() { let mut ppu = create_test_ppu_with_mirroring(ScreenMode::Horizontal); assert_mirrored(&mut ppu, 0, 1); assert_mirrored(&mut ppu, 2, 3); assert_not_mirrored(&mut ppu, 0, 2); assert_not_mirrored(&mut ppu, ...
fn four_screen_mirroring_mirrors_both_ways() { let mut ppu = create_test_ppu_with_mirroring(ScreenMode::FourScreen); assert_not_mirrored(&mut ppu, 0, 1); assert_not_mirrored(&mut ppu, 1, 2); assert_not_mirrored(&mut ppu, 2, 3); }
function_block-full_function
[ { "content": "#[test]\n\nfn blargg_ppu_test_vram_access() {\n\n let mut hashes: HashMap<u32, &'static str> = HashMap::new();\n\n let commands: HashMap<u32, &'static str> = HashMap::new();\n\n\n\n hashes.insert(18, \"cb15f68f631c1d409beefb775bcff990286096fb\");\n\n\n\n run_system_test(\n\n 19,...
Rust
lib/src/api/tests.rs
untoldwind/t-rust-less
e4ecd17b624e303626b55350b06319e1632a5743
use crate::{ api::{ Identity, PasswordStrength, Secret, SecretAttachment, SecretEntry, SecretEntryMatch, SecretList, SecretListFilter, SecretProperties, SecretType, SecretVersion, SecretVersionRef, Status, ZeroizeDateTime, }, memguard::SecretBytes, }; use chrono::{TimeZone, Utc}; use quickcheck::{quickche...
use crate::{ api::{ Identity, PasswordStrength, Secret, SecretAttachment, SecretEntry, SecretEntryMatch, SecretList, SecretListFilter, SecretProperties, SecretType, SecretVersion, SecretVersionRef, Status, ZeroizeDateTime, }, memguard::SecretBytes, }; use chrono::{TimeZone, Utc}; use quickcheck::{quickche...
} } impl Arbitrary for SecretListFilter { fn arbitrary(g: &mut Gen) -> Self { SecretListFilter { url: Option::arbitrary(g), tag: Option::arbitrary(g), secret_type: Option::arbitrary(g), name: Option::arbitrary(g), deleted: bool::arbitrary(g), } } } impl Arbitrary for Secre...
match g.choose(&[0, 1, 2, 3, 4, 5]).unwrap() { 0 => SecretType::Login, 1 => SecretType::Note, 2 => SecretType::Licence, 3 => SecretType::Wlan, 4 => SecretType::Password, _ => SecretType::Other, }
if_condition
[ { "content": "fn secret_to_clipboard(properties: &'static [&'static str]) -> impl Fn(&mut Cursive) {\n\n move |s: &mut Cursive| {\n\n let maybe_secret = {\n\n let secret_view = s.find_name::<SecretView>(\"secret_view\").unwrap();\n\n secret_view.current_secret()\n\n };\n\n let state = s.user...