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
contracts/tests/sim/test_storage.rs
alexkeating/moloch
bf11f8e03de63a000706bb1c711cec16410dbe09
use crate::utils::init_moloch; use near_sdk_sim::{call, to_yocto}; use std::convert::TryInto; #[test] fn simulate_storage_deposit_exact() { let (_, moloch, _fdai, _alice, bob, _deposit_amount) = init_moloch(); let start_amount = bob.account().unwrap().amount; let min_deposit = to_yocto("7"); println!(...
use crate::utils::init_moloch; use near_sdk_sim::{call, to_yocto}; use std::convert::TryInto; #[test] fn simulate_storage_deposit_exact() { let (_, moloch, _fdai, _alice, bob, _deposit_amount) = init_moloch(); let start_amount = bob.account().unwrap().amount; let min_deposit = to_yocto("7"); println!(...
#[test] fn simulate_storage_deposit_already_registered() { let (_, moloch, _, _, bob, _) = init_moloch(); let deposit = to_yocto("9"); call!( bob, moloch.storage_deposit( Some(bob.account_id.to_string().try_into().unwrap()), Some(false) ), deposit, ...
fn simulate_storage_deposit_transfer_back() { let (_, moloch, _fdai, _alice, bob, _deposit_amount) = init_moloch(); let start_amount = &bob.account().unwrap().amount; let deposit = 828593677552200000000; println!("Here {:?} 23", start_amount); call!( bob, moloch.storage_deposit( ...
function_block-full_function
[ { "content": "#[test]\n\nfn simulate_submit_proposal() {\n\n let (_root, moloch, fdai, alice, bob, deposit_amount) = init_moloch();\n\n register_user_moloch(&alice, &moloch);\n\n register_user_moloch(&bob, &moloch);\n\n call!(\n\n bob,\n\n fdai.ft_transfer_call(\n\n moloch.u...
Rust
src/uucore/src/lib/macros.rs
E3uka/coreutils
c7f7a222b9a2e86a68b204b417fbe23e7df01e3f
use std::sync::atomic::AtomicBool; pub static UTILITY_IS_SECOND_ARG: AtomicBool = AtomicBool::new(false); #[macro_export] macro_rules! show( ($err:expr) => ({ let e = $err; $crate::error::set_exit_code(e.code()); eprintln!("{}: {}", $crate::util_name(), e); }) ); #[macro_export] mac...
use std::sync::atomic::AtomicBool; pub static UTILITY_IS_SECOND_ARG: AtomicBool = AtomicBool::new(false); #[macro_export] macro_rules! show( ($err:expr) => ({ let e = $err; $crate::error::set_exit_code(e.code()); eprintln!("{}: {}", $crate::util_name(), e); }) ); #[macro_export] mac...
expr, $short_flag:expr) => { $crate::msg_invalid_opt_use!( format!("only usable if {}", $clause), $long_flag, $short_flag ) }; } #[macro_export] macro_rules! msg_opt_invalid_should_be { ($expects:expr, $received:expr, $flag:expr) => { $crate::msg_inva...
(m) => m, Err(f) => { $crate::show_error!("{}", f); return $exit_code; } } ) ); #[macro_export] macro_rules! safe_writeln( ($fd:expr, $($args:tt)+) => ( match writeln!($fd, $($args)+) { Ok(_) => {} Err(f) => panic!(...
random
[ { "content": "pub fn uu_app() -> App<'static, 'static> {\n\n App::new(uucore::util_name())\n\n .about(\"A file perusal filter for CRT viewing.\")\n\n .version(crate_version!())\n\n .arg(\n\n Arg::with_name(options::SILENT)\n\n .short(\"d\")\n\n .l...
Rust
src/io.rs
finalfusion/finalfusion-utils
d37a5d7f17515bcd0d6ba56a2e4dcec5914bf07a
use std::convert::TryFrom; use std::fmt; use std::fs::File; use std::io::{BufReader, BufWriter}; use anyhow::{anyhow, bail, Context, Error, Result}; use finalfusion::compat::floret::ReadFloretText; use finalfusion::compat::text::{WriteText, WriteTextDims}; use finalfusion::compat::word2vec::WriteWord2Vec; use finalfu...
use std::convert::TryFrom; use std::fmt; use std::fs::File; use std::io::{BufReader, BufWriter}; use anyhow::{anyhow, bail, Context, Error, Result}; use finalfusion::compat::floret::ReadFloretText; use finalfusion::compat::text::{WriteText, WriteTextDims}; use finalfusion::compat::word2vec::WriteWord2Vec; use finalfu...
} impl fmt::Display for EmbeddingFormat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use EmbeddingFormat::*; let s = match self { FastText => "fasttext", FinalFusion => "finalfusion", FinalFusionMmap => "finalfusion_mmap", Floret => "...
format { "fasttext" => Ok(FastText), "finalfusion" => Ok(FinalFusion), "finalfusion_mmap" => Ok(FinalFusionMmap), "floret" => Ok(Floret), "word2vec" => Ok(Word2Vec), "text" => Ok(Text), "textdims" => Ok(TextDims), unknown =>...
function_block-function_prefixed
[ { "content": "fn read_metadata(filename: impl AsRef<str>) -> Result<Value> {\n\n let f = File::open(filename.as_ref())\n\n .context(format!(\"Cannot open metadata file: {}\", filename.as_ref()))?;\n\n let mut reader = BufReader::new(f);\n\n let mut buf = String::new();\n\n reader\n\n ....
Rust
src/agent/coverage/src/cobertura.rs
tonybaloney/onefuzz
e0f2e9ed5aae006e0054387de7a0ff8c83c8f722
use crate::source::SourceCoverage; use crate::source::SourceCoverageLocation; use crate::source::SourceFileCoverage; use anyhow::Context; use anyhow::Error; use anyhow::Result; use std::time::{SystemTime, UNIX_EPOCH}; use xml::writer::{EmitterConfig, XmlEvent}; pub fn cobertura(source_coverage: SourceCoverage) -> Resu...
use crate::source::SourceCoverage; use crate::source::SourceCoverageLocation; use crate::source::SourceFileCoverage; use anyhow::Context; use anyhow::Error; use anyhow::Result; use std::time::{SystemTime, UNIX_EPOCH}; use xml::writer::{EmitterConfig, XmlEvent};
#[cfg(test)] mod tests { use super::*; use anyhow::Result; #[test] fn test_source_to_cobertura() -> Result<()> { let mut coverage_locations_vec1: Vec<SourceCoverageLocation> = Vec::new(); coverage_locations_vec1.push(SourceCoverageLocation { line: 5, column: N...
pub fn cobertura(source_coverage: SourceCoverage) -> Result<String, Error> { let mut backing: Vec<u8> = Vec::new(); let mut emitter = EmitterConfig::new() .perform_indent(true) .create_writer(&mut backing); let unixtime = SystemTime::now() .duration_since(UNIX_EPOCH) .contex...
function_block-full_function
[ { "content": " def is_used(self) -> bool:\n\n if len(self.get_forwards()) == 0:\n\n logging.info(PROXY_LOG_PREFIX + \"no forwards: %s\", self.region)\n\n return False\n", "file_path": "src/api-service/__app__/onefuzzlib/proxy.py", "rank": 0, "score": 51893.43127703405...
Rust
gui/src/app/root_stack/oc_page/stats_grid.rs
ashleysmithgpu/LACT
0bfc6c5acdd800d33ce92527328a9477c215b180
use daemon::gpu_controller::GpuStats; use gtk::*; #[derive(Clone)] pub struct StatsGrid { pub container: Grid, vram_usage_bar: LevelBar, vram_usage_label: Label, gpu_clock_label: Label, vram_clock_label: Label, gpu_voltage_label: Label, power_usage_label: Label, gpu_temperature_label: L...
use daemon::gpu_controller::GpuStats; use gtk::*; #[derive(Clone)] pub struct StatsGrid { pub container: Grid, vram_usage_bar: LevelBar, vram_usage_label: Label, gpu_clock_label: Label, vram_clock_label: Label, gpu_voltage_label: Label, power_usage_label: Label, gpu_temperature_label: L...
}
stats.power_cap.unwrap_or_else(|| 0) )); self.gpu_temperature_label .set_markup(&format!("<b>{}°C</b>", stats.gpu_temp.unwrap_or_default())); self.gpu_usage_label .set_markup(&format!("<b>{}%</b>", stats.gpu_usage.unwrap_or_default())); }
function_block-function_prefix_line
[ { "content": "fn print_stats(d: &DaemonConnection, gpu_id: u32) {\n\n let gpu_stats = d.get_gpu_stats(gpu_id).unwrap();\n\n println!(\n\n \"{} {}/{}{}\",\n\n \"VRAM Usage:\".green(),\n\n gpu_stats.mem_used.unwrap_or_default().to_string().bold(),\n\n gpu_stats.mem_total.unwrap_o...
Rust
src/lib.rs
aldanor/pod-typeinfo
9118046ce2a8e9b4e6cc523d18d7eace8fdaf0f1
#![cfg_attr(feature = "unstable", feature(plugin))] #![cfg_attr(feature = "unstable", plugin(clippy))] #[derive(Clone, PartialEq, Debug)] pub enum Type { Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64,...
#![cfg_attr(feature = "unstable", feature(plugin))] #![cfg_attr(feature = "unstable", plugin(clippy))] #[derive(Clone, PartialEq, Debug)] pub enum Type { Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64,...
} pub trait TypeInfo: Copy { fn type_info() -> Type; } macro_rules! impl_scalar { ($t:ty, $i:ident) => ( impl $crate::TypeInfo for $t { #[inline(always)] fn type_info() -> $crate::Type { $crate::Type::$i } } ) } impl_scalar!(i8, In...
pub fn new<S: Into<String>>(ty: &Type, name: S, offset: usize) -> Field { Field { ty: ty.clone(), name: name.into(), offset: offset } }
function_block-full_function
[ { "content": "#[test]\n\n#[allow(unused_variables, unused_imports)]\n\nfn test_pub_structs_fields() {\n\n use module::{A, B};\n\n use module::multiple::{E, F, G, H};\n\n let b = B { x: 1, y: 2 };\n\n}\n", "file_path": "tests/test.rs", "rank": 0, "score": 65230.86850490266 }, { "cont...
Rust
src/main.rs
sonald/redis-cli-rs
5de760421f4d052d4a28001d1274ab90688d0fd3
use structopt::StructOpt; use tokio::prelude::*; use tokio::net::TcpStream; use rustyline::{Editor, error::ReadlineError}; use std::error::Error; use log::*; use std::io::Write; mod redis; use self::redis::*; #[derive(Debug, StructOpt)] struct Opt { #[structopt(short, long)] pub debug: bool, #[structopt(...
use structopt::StructOpt; use tokio::prelude::*; use tokio::net::TcpStream; use rustyline::{Editor, error::ReadlineError}; use std::error::Error; use log::*; use std::io::Write; mod redis; use self::redis::*; #[derive(Debug, StructOpt)] struct Opt { #[structopt(short, long)] pub debug: bool, #[structopt(...
_ => { let res = read_redis_output(cli).await?; print!("{}", RedisValue::deserialize(&res).expect("").0); } } }, Err(ReadlineError::Interrupted) => { info!("CTRL-C"); break ...
"monitor" | "subscribe" => loop { consume_all_output(cli).await? },
function_block-random_span
[ { "content": "# cedis\n\n\n\na simple redis-cli replacement written in pure rust\n", "file_path": "README.md", "rank": 2, "score": 13893.999718397194 }, { "content": "use std::fmt;\n\nuse std::error::Error;\n\nuse bytes::Bytes;\n\n\n\n#[derive(Debug)]\n\npub enum RedisValue {\n\n Str(Stri...
Rust
runtime_v4/src/runtime.rs
MatchaChoco010/game_loop_async_runtime
4ccd2e4c642cdf793f83c8764d8b408fbfe17b05
use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Debug; use std::future::Future; use std::hash::Hash; use std::pin::Pin; use std::rc::Rc; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use futures::task::ArcWake; struct Task { future: Pin<Box<dyn Future<Output = ()> + 'sta...
use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Debug; use std::future::Future; use std::hash::Hash; use std::pin::Pin; use std::rc::Rc; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use futures::task::ArcWake; struct Task { future: Pin<Box<dyn Future<Output = ()> + 'sta...
c<RefCell<HashMap<T, Vec<Task>>>>, activated_phase: Rc<RefCell<HashMap<u16, T>>>, } impl<T: Eq + Hash + Clone + Debug> Runtime<T> { pub fn new() -> Self { Self { frame_counter: 0, tasks: Rc::new(RefCell::new(HashMap::new())), wait_tasks: Rc::new(RefCell::new(Hash...
NotDone, } #[derive(Clone)] pub struct Runtime<T: Eq + Hash + Clone + Debug> { frame_counter: u64, tasks: Rc<RefCell<HashMap<T, Vec<Task>>>>, wait_tasks: R
random
[ { "content": "#[derive(Clone)]\n\nstruct WakeFlagWaker {\n\n flag: WakeFlag,\n\n}\n\nimpl WakeFlagWaker {\n\n fn waker(flag: WakeFlag) -> Waker {\n\n futures::task::waker(Arc::new(Self { flag }))\n\n }\n\n}\n\nimpl ArcWake for WakeFlagWaker {\n\n fn wake_by_ref(arc_self: &Arc<Self>) {\n\n ...
Rust
src/prng/chacha.rs
TheIronBorn/rand
e1b60350d0936e6f17c7fd017ed18f3151006f43
use core::fmt; use rand_core::{BlockRngCore, CryptoRng, RngCore, SeedableRng, Error, le}; use rand_core::impls::BlockRng; const SEED_WORDS: usize = 8; const STATE_WORDS: usize = 16; #[derive(Clone, Debug)] pub struct ChaChaRng(BlockRng<ChaChaCore>); impl RngCore for ChaChaRng { #[inline] fn next_u32(&mut ...
use core::fmt; use rand_core::{BlockRngCore, CryptoRng, RngCore, SeedableRng, Error, le}; use rand_core::impls::BlockRng; const SEED_WORDS: usize = 8; const STATE_WORDS: usize = 16; #[derive(Clone, Debug)] pub struct ChaChaRng(BlockRng<ChaChaCore>); impl RngCore for ChaChaRng { #[inline] fn next_u32(&mut ...
#[test] fn test_chacha_set_counter() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); rng.set_counter(0, 2u64 << 56); let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); } let exp...
fn test_chacha_true_bytes() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); let mut results = [0u8; 32]; rng.fill_bytes(&mut results); let expected = [118, 184, 224, 173, 160, 241, 61, 144, 64, 93, 106, 229, 83, 134, 189, 40, ...
function_block-full_function
[ { "content": "/// Implement `fill_bytes` via `next_u64`, little-endian order.\n\npub fn fill_bytes_via_u64<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) {\n\n fill_bytes_via!(rng, next_u64, 8, dest)\n\n}\n\n\n\nmacro_rules! impl_uint_from_fill {\n\n ($rng:expr, $ty:ty, $N:expr) => ({\n\n debug...
Rust
src/main.rs
harksin/noria-mysql
7ece4f4107d453c922b452cbf0d824be7625a8e4
#![feature(box_syntax, box_patterns)] #![feature(nll)] #![feature(try_from)] extern crate arccstr; extern crate chrono; #[macro_use] extern crate clap; extern crate noria; extern crate msql_srv; extern crate nom_sql; #[macro_use] extern crate lazy_static; #[macro_use] extern crate slog; extern crate slog_term; exter...
#![feature(box_syntax, box_patterns)] #![feature(nll)] #![feature(try_from)] extern crate arccstr; extern crate chrono; #[macro_use] extern crate clap; extern crate noria; extern crate msql_srv; extern crate nom_sql; #[macro_use] extern crate lazy_static; #[macro_use] extern crate slog; extern crate slog_term; exter...
e"); let static_responses = !matches.is_present("no-static-responses"); let listener = net::TcpListener::bind(format!("127.0.0.1:{}", port)).unwrap(); let log = logger_pls(); info!(log, "listening on port {}", port); let query_counter = Arc::new(AtomicUsize::new(0)); let schemas: Arc<RwLock<...
function_block-function_prefixed
[ { "content": "fn collapse_where_in_recursive(\n\n leftmost_param_index: &mut usize,\n\n expr: &mut ConditionExpression,\n\n rewrite_literals: bool,\n\n) -> Option<(usize, Vec<Literal>)> {\n\n match *expr {\n\n ConditionExpression::Base(ConditionBase::Literal(Literal::Placeholder)) => {\n\n ...
Rust
crates/tako/benches/benchmarks/worker.rs
User3574/hyperqueue
d4dea5a805925cb624eb81da65840d5a8226d4a9
use std::time::Duration; use criterion::measurement::WallTime; use criterion::{BatchSize, BenchmarkGroup, BenchmarkId, Criterion}; use tako::common::index::{AsIdVec, ItemId}; use tako::common::resources::descriptor::GenericResourceKindIndices; use tako::common::resources::map::ResourceMap; use tako::common::resources:...
use std::time::Duration; use criterion::measurement::WallTime; use criterion::{BatchSize, BenchmarkGroup, BenchmarkId, Criterion}; use tako::common::index::{AsIdVec, ItemId}; use tako::common::resources::descriptor::GenericResourceKindIndices; use tako::common::resources::map::ResourceMap; use tako::common::resources:...
}, &ResourceMap::from_vec(vec!["GPU".to_string()]), ) } fn bench_resource_queue_add_task(c: &mut BenchmarkGroup<WallTime>) { c.bench_function("add task to resource queue", |b| { b.iter_batched_ref( || (create_resource_queue(64), create_worker_task(0)), |(queue, t...
} let task = create_worker_task(task_count); let duration = measure_time!({ state.add_task(task); }); total += duration; } total ...
random
[ { "content": "pub fn task_transfer_cost(taskmap: &TaskMap, task: &Task, worker_id: WorkerId) -> u64 {\n\n // TODO: For large number of inputs, only sample inputs\n\n task.inputs\n\n .iter()\n\n .take(512)\n\n .map(|ti| {\n\n let t = taskmap.get_task(ti.task());\n\n ...
Rust
src/ops/list.rs
wellinthatcase/fast-redis
b8b806989290d7c658884379975f59bfecaa84a5
use crate::*; #[pymethods] impl RedisClient { #[args(elements="*", no_overwrite="**")] #[text_signature = "($self, key, elements, *, no_overwrite)"] pub fn rpush(&mu...
use crate::*; #[pymethods] impl RedisClient { #[args(elements="*", no_overwrite="**")] #[text_signature = "($self, key, elements, *, no_overwrite)"] pub fn rpush(&mu...
#[text_signature = "($self, key, index, /)"] pub fn lindex(&mut self, key: &str, index: isize) -> PyResult<String> { let ind = index.to_string(); Ok(route_command(self, "LINDEX", Some(...
X", no_overwrite); let mut args = construct_vector(elements.len() + 1, Cow::from(&elements))?; args.insert(0, key); Ok(route_command(self, &command, Some(args))?) }
function_block-function_prefixed
[ { "content": "#[inline]\n\nfn route_command<Args, ReturnType>(inst: &mut RedisClient, cmd: &str, args: Option<Args>) -> PyResult<ReturnType>\n\nwhere \n\n Args: ToRedisArgs,\n\n ReturnType: FromRedisValue\n\n{\n\n let mut call = redis::cmd(cmd);\n\n call.arg(args);\n\n\n\n match call.query(&mut i...
Rust
actions/balance-notification-registration/src/lib.rs
HugoByte/aurras
fcc03684f4ed56ce949c5a1db8764508e0feb3f9
extern crate serde_json; use actions_common::Context; use chesterfield::sync::{Client, Database}; use serde_derive::{Deserialize, Serialize}; use serde_json::{Error, Value}; mod types; use std::collections::HashMap; use types::{Address, Response, Topic}; #[cfg(test)] use actions_common::Config; #[derive(Debug, Clone,...
extern crate serde_json; use actions_common::Context; use chesterfield::sync::{Client, Database}; use serde_derive::{Deserialize, Serialize}; use serde_json::{Error, Value}; mod types; use std::collections::HashMap; use types::{Address, Response, Topic}; #[cfg(test)] use actions_common::Config; #[derive(Debug, Clone,...
#[cfg(test)] mod tests { use super::*; use actions_common::mock_containers::CouchDB; use tokio; use tokio::time::{sleep, Duration}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Source { name: String, trigger: String, } impl Source { pub ...
ue) -> Result<Value, Error> { let input = serde_json::from_value::<Input>(args)?; let mut action = Action::new(input); #[cfg(not(test))] action.init(); match action.method().as_ref() { "post" => { let id = action.add_address( &action.params.token, ...
function_block-function_prefixed
[ { "content": "pub fn main(args: Value) -> Result<Value, Error> {\n\n let input = serde_json::from_value::<Input>(args)?;\n\n let mut action = Action::new(input);\n\n\n\n // TODO: Fix\n\n #[cfg(not(test))]\n\n action.init();\n\n\n\n let filtered_topics = action.filter_topics();\n\n let filte...
Rust
src/async/bufwriter.rs
kimhyunkang/rssh
046275ccdee7962230d5598b175e8f9815db605c
use super::buf::AsyncBuf; use super::DEFAULT_BUFSIZE; use std::{cmp, io}; use std::io::Write; use futures::{Async, Poll}; #[derive(Debug)] pub struct AsyncBufWriter<W: Write> { inner: Option<W>, buf: AsyncBuf, panicked: bool } #[derive(Debug)] pub struct IntoInnerError<W>(W, io::Error); impl <W: Write>...
use super::buf::AsyncBuf; use super::DEFAULT_BUFSIZE; use std::{cmp, io}; use std::io::Write; use futures::{Async, Poll}; #[derive(Debug)] pub struct AsyncBufWriter<W: Write> { inner: Option<W>, buf: AsyncBuf, panicked: bool } #[derive(Debug)] pub struct IntoInnerError<W>(W, io::Error); impl <W: Write>...
#[test] fn nb_write_exact_larger_than_buf() { let writer = { let buf = vec![0u8; 16]; let writer = Cursor::new(buf); let mut bufwriter = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"Hello, ").expect("...
writer = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"Hell").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"o, ").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"wor").expect(...
function_block-function_prefixed
[ { "content": "pub fn ntoh(buf: &[u8]) -> u32 {\n\n ((buf[0] as u32) << 24) + ((buf[1] as u32) << 16) + ((buf[2] as u32) << 8) + (buf[3] as u32)\n\n}\n\n\n", "file_path": "src/transport.rs", "rank": 0, "score": 151752.52172682478 }, { "content": "pub fn compute_pad_len<R: Rng>(payload_len:...
Rust
src/tokenizer.rs
crowlKats/rust-urlpattern
1dc0054b693ec652c8e4702a0edffc243ef5cd2c
use derive_more::Display; use crate::error::TokenizerError; use crate::Error; #[derive(Debug, Display, Clone, Eq, PartialEq)] pub enum TokenType { Open, Close, Regexp, Name, Char, EscapedChar, OtherModifier, Asterisk, End, InvalidChar, } #[derive(Debug, Clone)] pub struct Token { pub kind: To...
use derive_more::Display; use crate::error::TokenizerError; use crate::Error; #[derive(Debug, Display, Clone, Eq, PartialEq)] pub enum TokenType { Open, Close, Regexp, Name, Char, EscapedChar, OtherModifier, Asterisk, End, InvalidChar, } #[derive(Debug, Clone)] pub struct Token { pub kind: To...
fn process_tokenizing_error( &mut self, next_pos: usize, value_pos: usize, error: TokenizerError, ) -> Result<(), Error> { if self.policy == TokenizePolicy::Strict { Err(Error::Tokenizer(error, value_pos)) } else { self.add_token_with_default_len( TokenType::InvalidC...
fn add_token( &mut self, kind: TokenType, next_pos: usize, value_pos: usize, value_len: usize, ) { let range = value_pos..(value_pos + value_len); let value = self.input[range].iter().collect::<String>(); self.token_list.push(Token { kind, index: self.index, value, ...
function_block-full_function
[ { "content": "// Ref: https://wicg.github.io/urlpattern/#escape-a-pattern-string\n\nfn escape_pattern_string(input: &str) -> String {\n\n assert!(input.is_ascii());\n\n let mut result = String::new();\n\n for char in input.chars() {\n\n if matches!(char, '+' | '*' | '?' | ':' | '{' | '}' | '(' | ')' | '\\...
Rust
src/main.rs
Cxarli/minecrab
ddff0ab35c234c4413b2638c2615a2767c37c9ff
mod aabb; mod camera; mod geometry; mod geometry_buffers; mod hud; mod player; mod render_context; mod state; mod text_renderer; mod texture; mod time; mod utils; mod vertex; mod view; mod world; use std::time::{Duration, Instant}; use winit::{ dpi::{PhysicalSize, Size}, event::{ElementState, Event, KeyboardIn...
mod aabb; mod camera; mod geometry; mod geometry_buffers; mod hud; mod player; mod render_context; mod state; mod text_renderer; mod texture; mod time; mod utils; mod vertex; mod view; mod world; use std::time::{Duration, Instant}; use winit::{ dpi::{PhysicalSize, Size}, event::{ElementState, Event, KeyboardIn...
print!( "fps avg={:>5} min={:>5} max={:>5} | ", fps, fps_min, fps_max ); println!( "{:>8} tris | {:>5} chunks", triangle_count, state.world.chunks.len() ...
function_block-function_prefix_line
[ { "content": "use wgpu::{CommandEncoder, RenderPipeline};\n\n\n\nuse crate::{\n\n render_context::RenderContext,\n\n vertex::{HudVertex, Vertex},\n\n world::block::BlockType,\n\n};\n\n\n\nuse self::{debug_hud::DebugHud, hotbar_hud::HotbarHud, widgets_hud::WidgetsHud};\n\n\n\nuse std::borrow::Cow;\n\n\n...
Rust
src/serial.rs
IamfromSpace/stm32f3xx-hal
c68c36c03e0e33699b3b0c9acc3f8d80f5a25cd4
use crate::{ gpio::{gpioa, gpiob, gpioc, AF7}, hal::{blocking, serial}, pac::{USART1, USART2, USART3}, rcc::{Clocks, APB1, APB2}, time::Bps, }; use cfg_if::cfg_if; use core::{convert::Infallible, marker::PhantomData, ptr}; cfg_if! { if #[cfg(any(feature = "stm32f302", feature = "stm32f303"))]...
use crate::{ gpio::{gpioa, gpiob, gpioc, AF7}, hal::{blocking, serial}, pac::{USART1, USART2, USART3}, rcc::{Clocks, APB1, APB2}, time::Bps, }; use cfg_if::cfg_if; use core::{convert::Infallible, marker::PhantomData, ptr}; cfg_if! { if #[cfg(any(feature = "stm32f302", feature = "stm32f303"))]...
self.usart.cr1.modify(|_, w| w.rxneie().set_bit()) }, Event::Txe => { self.usart.cr1.modify(|_, w| w.txeie().set_bit()) }, } } ...
} pub fn listen(&mut self, event: Event) { match event { Event::Rxne => {
random
[ { "content": "fn unlock(apb1: &mut APB1, pwr: &mut PWR) {\n\n apb1.enr().modify(|_, w| {\n\n w\n\n // Enable the backup interface by setting PWREN\n\n .pwren()\n\n .set_bit()\n\n });\n\n pwr.cr.modify(|_, w| {\n\n w\n\n // Enable access to the b...
Rust
src/processor/mod.rs
gluwa/Sawtooth-SDK-Rust
8a3d99fa2c82eb3131148931a819ffca46d78c66
/* * Copyright 2017 Bitwise IO, Inc. * * 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 agree...
/* * Copyright 2017 Bitwise IO, Inc. * * 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 agree...
fn unregister(&mut self, sender: &ZmqMessageSender) { let request = TpUnregisterRequest::new(); info!("sending TpUnregisterRequest"); let serialized = match request.write_to_bytes() { Ok(serialized) => serialized, Err(err) => { error!("Serialization ...
fn register(&mut self, sender: &ZmqMessageSender, unregister: &Arc<AtomicBool>) -> bool { for handler in &self.handlers { for version in handler.family_versions() { let mut request = TpRegisterRequest::new(); request.set_family(handler.family_name().clone()); ...
function_block-full_function
[ { "content": "pub fn create_context(algorithm_name: &str) -> Result<Box<dyn Context>, Error> {\n\n match algorithm_name {\n\n \"secp256k1\" => Ok(Box::new(secp256k1::Secp256k1Context::new())),\n\n _ => Err(Error::NoSuchAlgorithm(format!(\n\n \"no such algorithm: {}\",\n\n ...
Rust
client/telemetry/src/transport.rs
cruz101-hub/substrate
6e45ffaa4d2a2aa62405194890477985b94747cd
use futures::{ executor::block_on, prelude::*, ready, task::{Context, Poll}, }; use libp2p::{ core::transport::{timeout::TransportTimeout, OptionalTransport}, wasm_ext, Transport, }; use std::io; use std::pin::Pin; use std::time::Duration; const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); pub(crate) ...
use futures::{ executor::block_on, prelude::*, ready, task::{Context, Poll}, }; use libp2p::{ core::transport::{timeout::TransportTimeout, OptionalTransport}, wasm_ext, Transport, }; use std::io; use std::pin::Pin; use std::time::Duration; const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); pub(crate) ...
} pub(crate) trait StreamAndSink<I>: Stream + Sink<I> {} impl<T: ?Sized + Stream + Sink<I>, I> StreamAndSink<I> for T {} pub(crate) type WsTrans = libp2p::core::transport::Boxed< Pin< Box< dyn StreamAndSink<Vec<u8>, Item = Result<Vec<u8>, io::Error>, Error = io::Error> + Send, >, >, >; #[pin_project::pin_p...
Ok(TransportTimeout::new( transport.map(|out, _| { let out = out .map_err(|err| io::Error::new(io::ErrorKind::Other, err)) .sink_map_err(|err| io::Error::new(io::ErrorKind::Other, err)); Box::pin(out) as Pin<Box<_>> }), CONNECT_TIMEOUT, ) .boxed())
call_expression
[ { "content": "fn decl_runtime_version_impl_inner(item: ItemConst) -> Result<TokenStream> {\n\n\tlet runtime_version = ParseRuntimeVersion::parse_expr(&*item.expr)?.build(item.expr.span())?;\n\n\tlet link_section =\n\n\t\tgenerate_emit_link_section_decl(&runtime_version.encode(), \"runtime_version\");\n\n\n\n\tO...
Rust
tests/baking_mod/macros_baking/macro_choice.rs
julien-lange/mpst_rust_github
ca10d860f06d3bc4b6d1a9df290d2812235b456f
use either::Either; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthree::role::end::RoleEnd; use mpstthree::role::Role; use std::error::Error; use rand::{thread_rng, Rng}; use mpstthree::bundle_impl; bundle_impl!(MeshedChannels, A, B, C); type OfferMpst<S0, S1, S...
use either::Either; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthree::role::end::RoleEnd; use mpstthree::role::Role; use std::error::Error; use rand::{thread_rng, Rng}; use mpstthree::bundle_impl; bundle_impl!(MeshedChannels, A, B, C); type OfferMpst<S0, S1, S...
tackAEnd, RoleA<RoleEnd>>; type OfferA<N> = OfferMpst< AtoBVideo<N>, AtoCVideo<N>, AtoBClose, AtoCClose, StackAVideo, StackAEnd, RoleA<RoleEnd>, >; type InitA<N> = Recv<N, Send<N, OfferA<N>>>; type EndpointAFull<N> = MeshedChannels<End, InitA<N>, StackAFull, RoleA<RoleEnd>>; type EndpointB...
ype StackAVideo = RoleC<RoleB<RoleB<RoleC<RoleEnd>>>>; type StackAVideoDual = <StackAVideo as Role>::Dual; type StackAFull = RoleC<RoleC<RoleAlltoC<RoleEnd, RoleEnd>>>; type StackBEnd = RoleEnd; type StackBVideo = RoleA<RoleA<RoleEnd>>; type StackBVideoDual = <StackBVideo as Role>::Dual; type StackBFull = RoleAlltoC<R...
random
[ { "content": "type ChooseMpstThree<S0, S1, S2, S3, R0, R1, N0> = Send<\n\n Either<\n\n MeshedChannels<\n\n <S0 as Session>::Dual,\n\n <S1 as Session>::Dual,\n\n <R0 as Role>::Dual,\n\n <N0 as Role>::Dual,\n\n >,\n\n MeshedChannels<\n\n ...
Rust
src/managers/memory.rs
aajtodd/riam
2b72f7d2eb5bac184631c2926f41629a44de6fd5
use crate::{Policy, PolicyManager, Result, RiamError}; use std::collections::HashMap; use std::collections::HashSet; use uuid::Uuid; pub struct MemoryManager { by_principal: HashMap<String, HashSet<Uuid>>, by_id: HashMap<Uuid, Policy>, } impl MemoryManager { pub fn new() -> Self { ...
use crate::{Policy, PolicyManager, Result, RiamError}; use std::collections::HashMap; use std::collections::HashSet; use uuid::Uuid; pub struct MemoryManager { by_principal: HashMap<String, HashSet<Uuid>>, by_id: HashMap<Uuid, Policy>, } impl MemoryManager { pub fn new() -> Self { ...
fn list(&self) -> Result<Vec<Policy>> { Ok(Vec::new()) } fn get_policies_for_principal(&self, principal: &str) -> Result<Option<Vec<Policy>>> { if let Some(policy_ids) = self.by_principal.get(principal) { let mut policies: Vec<Policy> = Vec::with_capacity(policy_ids....
ove(&id) { self.by_principal.retain(|_principal, pset| { pset.remove(&id); return pset.len() > 0; }) } else { return Err(RiamError::UnknownPolicy); } Ok(()) }
function_block-function_prefixed
[ { "content": "// custom serialize for Vec<String> for policy statements. If the vec length is\n\n// 1 the output will be flattened to just that single string. Otherwise it will\n\n// serialize normally to a sequence\n\n// e.g.\n\n// vec![\"actions:list\"] -> \"actions:list\"\n\n// vec![\"actions:list\", \"actio...
Rust
src/hir/constructor2enum.rs
KeenS/webml
60f4d899d623d5872c325412054bd0d77e37c4aa
use crate::config::Config; use crate::hir::util::Transform; use crate::hir::*; use crate::pass::Pass; use std::collections::{HashMap, HashSet}; pub struct ConstructorToEnumPass { enum_likes: HashSet<Symbol>, symbol_table: SymbolTable, } fn rewrite_ty(enum_likes: &HashSet<Symbol>, ty: HTy) -> HTy { use HTy...
use crate::config::Config; use crate::hir::util::Transform; use crate::hir::*; use crate::pass::Pass; use std::collections::{HashMap, HashSet}; pub struct ConstructorToEnumPass { enum_likes: HashSet<Symbol>, symbol_table: SymbolTable, } fn rewrite_ty(enum_likes: &HashSet<Symbol>, ty: HTy) -> HTy { use HTy...
, Var { name, ty } => Var { name, ty: self.rewrite_ty(ty), }, }; (pat, expr) }) .collect(); Expr::Case { ty, expr: Box::new(self.transform_expr(...
match ty { HTy::Datatype(name) if self.is_enum_like(&name) => Constant { ty: HTy::Int, value: descriminant as i64, }, ty => Constructor { descriminant, ...
if_condition
[ { "content": "fn take_binds(expr: Expr) -> (Expr, Vec<Val>) {\n\n use crate::hir::Expr::*;\n\n match expr {\n\n Let { bind, ret, .. } => {\n\n let (expr, mut binds) = take_binds(*ret);\n\n binds.insert(0, *bind);\n\n (expr, binds)\n\n }\n\n BuiltinCall...
Rust
tests/delete_component.rs
colelawrence/shipyard
bd535706a4ec53f5162e4aae6b8c9480e5f8bc75
use core::any::type_name; use shipyard::error; use shipyard::internal::iterators; use shipyard::prelude::*; #[test] fn no_pack() { let world = World::new(); let (mut entities, mut usizes, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u32)>(); let entity1 = entities.add_entity((&mut usi...
use core::any::type_name; use shipyard::error; use shipyard::internal::iterators; use shipyard::prelude::*; #[test] fn no_pack() { let world = World::new(); let (mut entities, mut usizes, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u32)>(); let entity1 = entities.add_entity((&mut usi...
#[test] fn loose() { let world = World::new(); let (mut entities, mut usizes, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u32)>(); (&mut usizes, &mut u32s).loose_pack(); let entity1 = entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32)); let entity2 = entities.add_e...
assert_eq!( (&mut usizes).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!((&mut u32s).get(entity1), Ok(&mut 1)); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(u32s.get(entity2), Ok(&3)); let i...
function_block-function_prefix_line
[ { "content": "#[system(Test3)]\n\nfn run(_: &mut Entities, _: &mut u32) {}\n\n\n", "file_path": "tests/derive/good.rs", "rank": 0, "score": 274503.01059633156 }, { "content": "#[system(Test1)]\n\nfn run(_: &usize, _: &mut i32, _: &Entities, _: Unique<&u32>, _: Entities) {}\n\n\n", "file_...
Rust
solo-machine/src/server/ibc.rs
devashishdxt/ibc-solo-machine
76cb11d81e4777e96d4babbfb81381e50a48d57e
tonic::include_proto!("ibc"); use std::time::SystemTime; use k256::ecdsa::VerifyingKey; use solo_machine_core::{ cosmos::crypto::{PublicKey, PublicKeyAlgo}, ibc::core::ics24_host::identifier::ChainId, service::IbcService as CoreIbcService, DbPool, Event, Signer, }; use tokio::sync::mpsc::UnboundedSend...
tonic::include_proto!("ibc"); use std::time::SystemTime; use k256::ecdsa::VerifyingKey; use solo_machine_core::{ cosmos::crypto::{PublicKey, PublicKeyAlgo}, ibc::core::ics24_host::identifier::ChainId, service::IbcService as CoreIbcService, DbPool, Event, Signer, }; use tokio::sync::mpsc::UnboundedSend...
async fn mint(&self, request: Request<MintRequest>) -> Result<Response<MintResponse>, Status> { let request = request.into_inner(); let chain_id = request .chain_id .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let ...
let request_id = request.request_id; let force = request.force; self.core_service .connect(&self.signer, chain_id, request_id, memo, force) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) }...
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\npub trait Signer: ToPublicKey + Send + Sync {\n\n /// Signs the given message\n\n async fn sign(&self, request_id: Option<&str>, message: Message<'_>) -> Result<Vec<u8>>;\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Signer> Signer for &T {\n\n async fn sign(&self, request_id: O...
Rust
src/kernel/src/syscall/sync.rs
ariadiamond/twizzler-Rust
5f5d01bac9127ca1d64bb8aa472a04f6634fc3a9
use core::time::Duration; use alloc::{collections::BTreeMap, vec::Vec}; use twizzler_abi::syscall::{ ThreadSync, ThreadSyncError, ThreadSyncReference, ThreadSyncSleep, ThreadSyncWake, }; use x86_64::VirtAddr; use crate::{ obj::{LookupFlags, ObjectRef}, once::Once, spinlock::Spinlock, thread::{curr...
use core::time::Duration; use alloc::{collections::BTreeMap, vec::Vec}; use twizzler_abi::syscall::{ ThreadSync, ThreadSyncError, ThreadSyncReference, ThreadSyncSleep, ThreadSyncWake, }; use x86_64::VirtAddr; use crate::{ obj::{LookupFlags, ObjectRef}, once::Once, spinlock::Spinlock, thread::{curr...
fn undo_sleep(sleep: SleepEvent) { sleep.obj.remove_from_sleep_word(sleep.offset); } fn wakeup(wake: &ThreadSyncWake) -> Result<usize, ThreadSyncError> { let (obj, offset) = get_obj(wake.reference)?; Ok(obj.wakeup_word(offset, wake.count)) } fn thread_sync_cb_timeout(thread: ThreadRef) { if thread.r...
e)?; /* logln!( "{} sleep {} {:x}", current_thread_ref().unwrap().id(), obj.id(), offset ); if let ThreadSyncReference::Virtual(p) = &sleep.reference { logln!(" => {:p} {}", *p, unsafe { (**p).load(core::sync::atomic::Ordering::SeqCst) }); ...
function_block-function_prefixed
[]
Rust
src/render.rs
JorgenPo/rust-text-rpg
5e8f489741628062503ff1814535384b1692929f
use termion::terminal_size; use termion::{color, cursor, clear, style}; use std::io::{Error, Write, Stdout, StdoutLock}; use termion::raw::{IntoRawMode, RawTerminal}; use std::cmp::max; #[doc(hidden)] pub fn _print(args: ::core::fmt::Arguments) { use core::fmt::Write; std::io::stdout().write_fmt(args).expect(...
use termion::terminal_size; use termion::{color, cursor, clear, style}; use std::io::{Error, Write, Stdout, StdoutLock}; use termion::raw::{IntoRawMode, RawTerminal}; use std::cmp::max; #[doc(hidden)] pub fn _print(args: ::core::fmt::Arguments) { use core::fmt::Write; std::io::stdout().write_fmt(args).expect(...
pub fn draw_raw(&mut self, string: &str) { render!("{}", string); } pub fn flash(&self) { std::io::stdout().flush().unwrap(); } } impl Drop for Render { fn drop(&mut self) { print!("{}{}{}{}", clear::All, style::Reset, cursor::Show, cursor::Goto(1, 1)); } }
pub fn draw<T: Drawable>(&mut self, drawable: &T) { let position = drawable.get_position(); let x = match position.x { Coordinate::Absolute(x) => max(x, 1), Coordinate::Centered => self.get_middle_x(drawable), Coordinate::Percent(percent) => max(self.term_size.width,...
function_block-full_function
[ { "content": "pub trait Logger {\n\n fn info(&mut self, message: &str);\n\n fn warn(&mut self, message: &str);\n\n}", "file_path": "src/game/loggers.rs", "rank": 2, "score": 61792.36740350007 }, { "content": "fn lerp_color(start: color::Rgb, end: color::Rgb, k: f32) -> color::Rgb {\n\n...
Rust
scheduler/crates/api/src/calendar/update_calendar.rs
omid/nettu-scheduler
27a2728882842222085ee4e17c952ec215fd683e
use crate::shared::{ auth::{ account_can_modify_calendar, account_can_modify_user, protect_account_route, Permission, }, usecase::{execute, execute_with_policy, PermissionBoundary, UseCase}, }; use crate::{error::NettuError, shared::auth::protect_route}; use actix_web::{web, HttpResponse}; use nettu...
use crate::shared::{ auth::{ account_can_modify_calendar, account_can_modify_user, protect_account_route, Permission, }, usecase::{execute, execute_with_policy, PermissionBoundary, UseCase}, }; use crate::{error::NettuError, shared::auth::protect_route}; use actix_web::{web, HttpResponse}; use nettu...
; } } if let Some(metadata) = &self.metadata { calendar.metadata = metadata.clone(); } ctx.repos .calendars .save(&calendar) .await .map(|_| calendar) .map_err(|_| UseCaseError::StorageError) } } i...
Err(UseCaseError::InvalidSettings(format!( "Invalid timezone: {}, must be a valid IANA Timezone string", timezone )))
call_expression
[]
Rust
tower-balance/src/p2c/service.rs
JeanMertz/tower
7e55b7fa0b2db4ff36fd90f3700bd628c89951b6
use crate::error; use futures::{future, Async, Future, Poll}; use rand::{rngs::SmallRng, SeedableRng}; use tower_discover::{Change, Discover}; use tower_load::Load; use tower_ready_cache::{error::Failed, ReadyCache}; use tower_service::Service; use tracing::{debug, trace}; #[derive(Debug)] pub struct Balance<D: Discov...
use crate::error; use futures::{future, Async, Future, Poll}; use rand::{rngs::SmallRng, SeedableRng}; use tower_discover::{Change, Discover}; use tower_load::Load; use tower_ready_cache::{error::Failed, ReadyCache}; use tower_service::Service; use tracing::{debug, trace}; #[derive(Debug)] pub struct Balance<D: Discov...
} } self.ready_index = self.p2c_ready_index(); if self.ready_index.is_none() { debug_assert_eq!(self.services.ready_len(), 0); return Ok(Async::NotReady); } } } ...
self.ready_index = Some(index); return Ok(Async::Ready(())); } Ok(false) => { trace!("ready service became unavailable"); } Err(Failed(...
function_block-random_span
[ { "content": "fn new_service<P: Policy<Req, Res, Error> + Clone>(\n\n policy: P,\n\n) -> (tower_retry::Retry<P, Mock>, Handle) {\n\n let (service, handle) = mock::pair();\n\n let service = tower_retry::Retry::new(policy, service);\n\n (service, handle)\n\n}\n\n\n", "file_path": "tower-retry/test...
Rust
src/views/krate_publish.rs
vignesh-sankaran/crates.io
387ae4f2e9f6e653804bb063ae30cadd8c3382be
use std::collections::HashMap; use semver; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use models::krate::MAX_NAME_LENGTH; use models::Crate; use models::DependencyKind; use models::Keyword as CrateKeyword; #[derive(Deserialize, Serialize, Debug)] pub struct EncodableCrateUpload { pub n...
use std::collections::HashMap; use semver; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use models::krate::MAX_NAME_LENGTH; use models::Crate; use models::DependencyKind; use models::Keyword as CrateKeyword; #[derive(Deserialize, Serialize, Debug)] pub struct EncodableCrateUpload { pub n...
} impl<'de> Deserialize<'de> for EncodableFeature { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableFeature, D::Error> { let s = String::deserialize(d)?; if !Crate::valid_feature(&s) { let value = de::Unexpected::Str(&s); let expected = "a valid feature name";...
let expected = "a valid feature name containing only letters, \ numbers, hyphens, or underscores"; Err(de::Error::invalid_value(value, &expected)) } else { Ok(EncodableFeatureName(s)) } }
function_block-function_prefix_line
[]
Rust
programs/vote/src/vote_processor.rs
Flawm/solana
551c24da5792f4452c3c555e562809e8c9e742e5
use { crate::{id, vote_instruction::VoteInstruction, vote_state}, log::*, solana_metrics::inc_new_counter_info, solana_program_runtime::{ invoke_context::InvokeContext, sysvar_cache::get_sysvar_with_account_check, }, solana_sdk::{ feature_set, instruction::InstructionEr...
use { crate::{id, vote_instruction::VoteInstruction, vote_state}, log::*, solana_metrics::inc_new_counter_info, solana_program_runtime::{ invoke_context::InvokeContext, sysvar_cache::get_sysvar_with_account_check, }, solana_sdk::{ feature_set, instruction::InstructionEr...
#[test] fn test_spoofed_vote() { process_instruction_as_one_arg( &vote( &invalid_vote_state_pubkey(), &Pubkey::new_unique(), Vote::default(), ), Err(InstructionError::InvalidAccountOwner), ); process_in...
fn test_vote_process_instruction_decode_bail() { process_instruction( &[], Vec::new(), Vec::new(), Err(InstructionError::NotEnoughAccountKeys), ); }
function_block-full_function
[ { "content": "pub fn read_pubkey(current: &mut usize, data: &[u8]) -> Result<Pubkey, SanitizeError> {\n\n let len = std::mem::size_of::<Pubkey>();\n\n if data.len() < *current + len {\n\n return Err(SanitizeError::IndexOutOfBounds);\n\n }\n\n let e = Pubkey::new(&data[*current..*current + len...
Rust
src/widgets/image_widget.rs
alexislozano/rust-pushrod
57f4129861a2e22608cbc9cb0aa151b5fb424c62
use crate::render::callbacks::CallbackRegistry; use crate::render::widget::*; use crate::render::widget_cache::WidgetContainer; use crate::render::widget_config::{ CompassPosition, Config, WidgetConfig, CONFIG_COLOR_BASE, CONFIG_IMAGE_POSITION, CONFIG_SIZE, }; use crate::render::Points; use sdl2::image::LoadText...
use crate::render::callbacks::CallbackRegistry; use crate::render::widget::*; use crate::render::widget_cache::WidgetContainer; use crate::render::widget_config::{ CompassPosition, Config, WidgetConfig, CONFIG_COLOR_BASE, CONFIG_IMAGE_POSITION, CONFIG_SIZE, }; use crate::render::Points; use sdl2::image::LoadText...
; let texture_y = match self.get_compass(CONFIG_IMAGE_POSITION) { CompassPosition::NW | CompassPosition::N | CompassPosition::NE => { self.get_config().to_y(0) } CompassPosition::W | CompassPosition::Center | CompassPosition::E => { self.get_...
match self.get_compass(CONFIG_IMAGE_POSITION) { CompassPosition::NW | CompassPosition::W | CompassPosition::SW => { self.get_config().to_x(0) } CompassPosition::N | CompassPosition::Center | CompassPosition::S => { self.get_config().to_x((widget_w - w...
if_condition
[ { "content": "pub fn widget_id_for_name(widgets: &[WidgetContainer], name: String) -> usize {\n\n match widgets.iter().find(|x| x.get_widget_name() == name.clone()) {\n\n Some(x) => x.get_widget_id() as usize,\n\n None => 0 as usize,\n\n }\n\n}\n", "file_path": "src/render/callbacks.rs",...
Rust
src/nfa.rs
MarioJim/finite-automata-tui
c22e9c0de28a199efbdfcabda7e8184fecaf1a20
use multimap::MultiMap; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::fmt; #[derive(Debug)] pub struct NFA { pub alphabet: HashSet<String>, initial_state: String, states: HashMap<String, NFAState>, } #[derive(Debug)] struct NFAState { is_final: bool, transitions: Mu...
use multimap::MultiMap; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::fmt; #[derive(Debug)] pub struct NFA { pub alphabet: HashSet<String>, initial_state: String, states: HashMap<String, NFAState>, } #[derive(Debug)] struct NFAState { is_final: bool, transitions: Mu...
; let from_state = match from_symbol.get(0) { Some(&s) => match states.contains_key(s) { true => s, false => { return Err("Couldn't find a transition's starting state in defined states") } }, ...
match line_iter.next() { Some(s) => s.split(',').collect(), None => return Err("Transition line is empty"), }
if_condition
[ { "content": "pub fn show_tui(automata_struct: nfa::NFA) {\n\n let instructions = \"Write the symbols separated by a space, press Esc or Ctrl+C to quit\";\n\n let mut input_f = input_field::InputField::new();\n\n let term = Term::with_height(TermHeight::Fixed(4)).unwrap();\n\n while let Ok(ev) = ter...
Rust
src/middle/builder.rs
reitermarkus/libffi-rs
693182bf1fb16da2c00ace0cc13920a98845c9a3
use std::any::Any; use super::types::Type; #[derive(Clone, Debug)] pub struct Builder { args: Vec<Type>, res: Type, abi: super::FfiAbi, } impl Default for Builder { fn default() -> Self { Builder::new() } } impl Builder { pub fn new() -> Self { Builder { args...
use std::any::Any; use super::types::Type; #[derive(Clone, Debug)] pub struct Builder { args: Vec<Type>, res: Type, abi: super::FfiAbi, } impl Default for Builder { fn default() -> Self { Builder::new() } } impl Builder { pub fn new() -> Self { Builder { args...
pub fn res(mut self, type_: Type) -> Self { self.res = type_; self } pub fn abi(mut self, abi: super::FfiAbi) -> Self { self.abi = abi; self } pub fn into_cif(self) -> super::Cif { let mut result = super::Cif::new(self.args, self.res); ...
pub fn args<I>(mut self, types: I) -> Self where I: IntoIterator<Item=Type> { self.args.extend(types.into_iter()); self }
function_block-full_function
[ { "content": "/// Constructs an [`Arg`](struct.Arg.html) for passing to\n\n/// [`call`](fn.call.html).\n\npub fn arg<T: super::CType>(arg: &T) -> Arg {\n\n Arg::new(arg)\n\n}\n\n\n\n/// Performs a dynamic call to a C function.\n\n///\n\n/// To reduce boilerplate, see [`ffi_call!`](../../macro.ffi_call!.html)...
Rust
baustelle/src/containerfile.rs
akhramov/knast
8c9f5f481a467a22c7cc47f11a28fe52536f9950
use std::{convert::TryFrom, fs, io::Read, path::PathBuf}; use anyhow::{Context, Error}; use dockerfile_parser::{ Dockerfile as Containerfile, FromInstruction, Instruction::{self, *}, }; use futures::{ channel::mpsc::{unbounded, SendError, UnboundedSender}, future::{self, Future}, stream::Stream, ...
use std::{convert::TryFrom, fs, io::Read, path::PathBuf}; use anyhow::{Context, Error}; use dockerfile_parser::{ Dockerfile as Containerfile, FromInstruction, Instruction::{self, *}, }; use futures::{ channel::mpsc::{unbounded, SendError, UnboundedSender}, future::{self, Future}, stream::Stream, ...
#[fehler::throws] async fn execute_from_instruction( &self, instruction: FromInstruction, sender: UnboundedSender<EvaluationUpdate>, ) { let image = &instruction.image_parsed; let sender = sender.with(|val| { future::ok::<_, SendError>(EvaluationUpdate:...
nder: UnboundedSender<EvaluationUpdate>, ) { match instruction { From(instruction) => { self.execute_from_instruction(instruction, sender).await?; } _ => { log::warn!( "Unhandled containerfile instruction {:?}", ...
function_block-function_prefixed
[ { "content": "#[fehler::throws]\n\npub fn teardown(storage: &Storage<impl StorageEngine>, key: impl AsRef<str>) {\n\n let cache: ContainerAddressStorage = storage\n\n .get(NETWORK_STATE_STORAGE_KEY, CONTAINER_ADDRESS_STORAGE_KEY)?\n\n .ok_or_else(|| anyhow::anyhow!(\"Failed to read network stat...
Rust
src/room.rs
neosam/sprite-game
5d261eb538824ebb133833a4f4fe4f162aa3445c
use rand::Rng; #[derive(Copy, Clone)] pub enum DestRoom { Relative(isize, isize, i32, i32,), Absolute(isize, isize, i32, i32,), } impl DestRoom { pub fn to_absolute_coordinates(&self, (x, y): (i32, i32)) -> (i32, i32) { match self { DestRoom::Relative(rel_x, rel_y, _, _) => (x + *rel_x...
use rand::Rng; #[derive(Copy, Clone)] pub enum DestRoom { Relative(isize, isize, i32, i32,), Absolute(isize, isize, i32, i32,), } impl DestRoom { pub fn to_absolute_coordinates(&self, (x, y): (i32, i32)) -> (i32, i32) { match self { DestRoom::Relative(rel_x, rel_y, _, _) => (x + *rel_x...
if self.exit_west { room.set_field(0, self.height / 2, RoomField::Exit(DestRoom::Relative(-1, 0, self.width as i32 - 2, self.height as i32 / 2))); } /* Draw 5-7 random stones */ for _ in 0..rng.gen_range(5, 8) { let x = rng.gen_range(2, self.widt...
if self.exit_east { room.set_field(self.width - 1, self.height / 2, RoomField::Exit(DestRoom::Relative(1, 0, 1, self.height as i32 / 2))); }
if_condition
[ { "content": "fn generate_corridor(map: &mut Map<RoomGeneration>, rng: &mut impl Rng, width: usize, height: usize, corridor_length: u32, mut coordinate: (i32, i32)) -> Vec<(i32,i32)> {\n\n let mut coordinate_stack = Vec::new();\n\n for _ in 0..corridor_length {\n\n let choice = {\n\n let...
Rust
part_8/src/render.rs
CroPo/roguelike-tutorial-2018
6ceceb445087ef42ed988574ef5ac04e341d9889
use tcod::console::{Console, Root, blit, Offscreen}; use map_objects::map::GameMap; use tcod::Map; use ecs::Ecs; use ecs::component::Position; use ecs::component::Render; use ecs::id::EntityId; use tcod::Color; use tcod::colors; use tcod::BackgroundFlag; use tcod::TextAlignment; use ecs::component::Actor; use message:...
use tcod::console::{Console, Root, blit, Offscreen}; use map_objects::map::GameMap; use tcod::Map; use ecs::Ecs; use ecs::component::Position; use ecs::component::Render; use ecs::id::EntityId; use tcod::Color; use tcod::colors; use tcod::BackgroundFlag; use tcod::TextAlignment; use ecs::component::Actor; use message:...
pub fn inventory_menu(console: &mut Root, ecs: &Ecs, title: &str, width: i32, screen_width: i32, screen_height: i32) { if let Some(inventory) = ecs.get_component::<Inventory>(ecs.player_entity_id) { let items = if inventory.items.len() == 0 { vec!["Inventory is empty".to_string()] } ...
t!("({}) {}", letter_index as char, option); menu_panel.print_ex(0, y, BackgroundFlag::None, TextAlignment::Left, text); y+=1; letter_index+=1; } let x = screen_width / 2 - width / 2; let y = screen_height / 2 - height / 2; blit(&menu_panel, (0, 0), (width, height), ...
function_block-function_prefixed
[ { "content": "/// Display a selection menu of various options\n\npub fn selection_menu(console: &mut Root, title: &str, options: Vec<String>, width: i32, screen_width: i32, screen_height: i32) {\n\n let header_height = console.get_height_rect(0, 0, width, screen_height, title);\n\n let height = header_hei...
Rust
clinkv2/src/kzg10/prover.rs
sunhuachuang/ckb-zkp
4031a458a301a87cfdea9f6c662cc8a837d6ae51
use ark_ec::PairingEngine; use ark_ff::{Field, One, ToBytes, UniformRand, Zero}; use ark_poly::polynomial::univariate::DensePolynomial; use ark_poly::{EvaluationDomain, GeneralEvaluationDomain, Polynomial, UVPolynomial}; use ark_std::{cfg_iter, cfg_iter_mut}; use merlin::Transcript; use rand::Rng; #[cfg(feature = "par...
use ark_ec::PairingEngine; use ark_ff::{Field, One, ToBytes, UniformRand, Zero}; use ark_poly::polynomial::univariate::DensePolynomial; use ark_poly::{EvaluationDomain, GeneralEvaluationDomain, Polynomial, UVPolynomial}; use ark_std::{cfg_iter, cfg_iter_mut}; use merlin::Transcript; use rand::Rng; #[cfg(feature = "par...
pub fn create_random_proof<E: PairingEngine, R: Rng>( circuit: &ProveAssignment<E>, kzg10_ck: &ProveKey<'_, E>, rng: &mut R, ) -> Result<Proof<E>, SynthesisError> { let m_io = circuit.input_assignment.len(); let m_mid = circuit.aux_assignment.len(); let n = circuit.input...
function_block-full_function
[ { "content": "type Kzg10Proof<E> = kzg10::Proof<E>;\n", "file_path": "clinkv2/src/kzg10/mod.rs", "rank": 0, "score": 123476.63471316447 }, { "content": "fn skip_leading_zeros_and_convert_to_bigints<F: PrimeField>(\n\n p: &DensePolynomial<F>,\n\n) -> (usize, Vec<F::BigInt>) {\n\n let mu...
Rust
examples/simple/main.rs
Vollkornaffe/VRV
8e71b9c728dbe91d41d563e32bcbf432952fe828
use std::{ collections::HashSet, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::Instant, }; use ash::vk::{DynamicState, Extent2D}; use cgmath::{perspective, Deg, EuclideanSpace, Matrix4, Point3, SquareMatrix, Vector3}; use openxr::{EventDataBuffer, SessionState, ViewConfiguration...
use std::{ collections::HashSet, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::Instant, }; use ash::vk::{DynamicState, Extent2D}; use cgmath::{perspective, Deg, EuclideanSpace, Matrix4, Point3, SquareMatrix, Vector3}; use openxr::{EventDataBuffer, SessionState, ViewConfiguration...
use openxr::Event::*; match event { SessionStateChanged(e) => { log::warn!("entered state {:?}", e.state()); xr_focused = false; match e.state() { ...
function_block-function_prefixed
[ { "content": "// there are 4 angles to consider instead of one\n\npub fn fov_to_projection(fov: Fovf) -> Matrix4<f32> {\n\n let tan_left = fov.angle_left.tan();\n\n let tan_right = fov.angle_right.tan();\n\n let tan_down = fov.angle_down.tan();\n\n let tan_up = fov.angle_up.tan();\n\n let near = ...
Rust
crates/nu-parser/src/hir.rs
jkatzmewing/nushell
7061af712e3eec7e2bb68bf7ca31e67d6b8b3ae8
pub(crate) mod baseline_parse; pub(crate) mod binary; pub(crate) mod expand_external_tokens; pub(crate) mod external_command; pub(crate) mod named; pub(crate) mod path; pub(crate) mod range; pub mod syntax_shape; pub(crate) mod tokens_iterator; use crate::hir::syntax_shape::Member; use crate::parse::operator::CompareO...
pub(crate) mod baseline_parse; pub(crate) mod binary; pub(crate) mod expand_external_tokens; pub(crate) mod external_command; pub(crate) mod named; pub(crate) mod path; pub(crate) mod range; pub mod syntax_shape; pub(crate) mod tokens_iterator; use crate::hir::syntax_shape::Member; use crate::parse::operator::CompareO...
fn pretty_debug(&self, source: &str) -> DebugDocBuilder { b::typed( "call", self.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source), ) } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Expression { Lite...
e(), ) }), ) + b::preceded_option( Some(b::space()), self.named.as_ref().map(|named| { named.refined_pretty_debug(PrettyDebugRefineKind::WithContext, so...
function_block-function_prefixed
[ { "content": "pub fn files_exist_at(files: Vec<impl AsRef<Path>>, path: impl AsRef<Path>) -> bool {\n\n files.iter().all(|f| {\n\n let mut loc = PathBuf::from(path.as_ref());\n\n loc.push(f);\n\n loc.exists()\n\n })\n\n}\n\n\n", "file_path": "crates/nu-test-support/src/fs.rs", ...
Rust
src/token.rs
illumination-k/rs9cc
6c2570e5d250435267a331b0a4d66ca052cb477d
use std::iter::Peekable; use std::collections::HashSet; #[derive(Debug, Clone)] struct OpWords { op_words: HashSet<String>, max_length: usize, } impl OpWords { fn new(op_words: Vec<&str>) -> Self { let max_length = op_words.iter().map(|x| x.len()).max().unwrap(); Self { op_word...
use std::iter::Peekable; use std::collections::HashSet; #[derive(Debug, Clone)] struct OpWords { op_words: HashSet<String>, max_length: usize, } impl OpWords { fn new(op_words: Vec<&str>) -> Self { let max_length = op_words.iter().map(|x| x.len()).max().unwrap(); Self { op_word...
&v in val[now_length..].iter().rev() { bytes.push_front(v) } val = val[..now_length].to_vec(); break; } } now_length -= 1; ...
if bytes[0].is_ascii_digit() { TokenKind::TkNum } else { TokenKind::TkReserved }; match token_kind { TokenKind::TkNum => { while let Some(byte) = bytes.pop_front() { if byte.is_ascii_digit() { val.p...
function_block-random_span
[ { "content": "pub fn primary(tokenizer: &mut Peekable<TokenIter>) -> Box<Node> {\n\n if consume(\"(\", tokenizer) {\n\n let node = expr(tokenizer);\n\n let _expect = consume(\")\", tokenizer);\n\n return node \n\n }\n\n\n\n match tokenizer.peek() {\n\n Some(t) => {\n\n ...
Rust
beacon_node/store/src/block_at_slot.rs
JustinDrake/lighthouse
0694d1d0ec488d2d9f448a2bf5c6f742e1c5a5ed
use super::*; use ssz::{Decode, DecodeError}; fn get_block_bytes<T: Store<E>, E: EthSpec>( store: &T, root: Hash256, ) -> Result<Option<Vec<u8>>, Error> { store.get_bytes(BeaconBlock::<E>::db_column().into(), &root[..]) } fn read_slot_from_block_bytes(bytes: &[u8]) -> Result<Slot, DecodeError> { let e...
use super::*; use ssz::{Decode, DecodeError}; fn get_block_bytes<T: Store<E>, E: EthSpec>( store: &T, root: Hash256, ) -> Result<Option<Vec<u8>>, Error> { store.get_bytes(BeaconBlock::<E>::db_column().into(), &root[..]) } fn read_slot_from_block_bytes(bytes: &[u8]) -> Result<Slot, DecodeError> { let e...
pub fn get_block_at_preceeding_slot<T: Store<E>, E: EthSpec>( store: &T, slot: Slot, start_root: Hash256, ) -> Result<Option<(Hash256, BeaconBlock<E>)>, Error> { Ok( match get_at_preceeding_slot::<_, E>(store, slot, start_root)? { Some((hash, bytes)) => Some((hash, BeaconBlock::<E>...
s(bytes: &[u8]) -> Result<Hash256, DecodeError> { let previous_bytes = Slot::ssz_fixed_len(); let slice = bytes .get(previous_bytes..previous_bytes + Hash256::ssz_fixed_len()) .ok_or_else(|| DecodeError::BytesInvalid("Not enough bytes.".to_string()))?; Hash256::from_ssz_bytes(slice) }
function_block-function_prefixed
[ { "content": "/// Fetch the next state to use whilst backtracking in `*RootsIterator`.\n\nfn next_historical_root_backtrack_state<E: EthSpec, S: Store<E>>(\n\n store: &S,\n\n current_state: &BeaconState<E>,\n\n) -> Option<BeaconState<E>> {\n\n // For compatibility with the freezer database's restore po...
Rust
src/protocol/spdm/get_caps.rs
capoferro/manticore
64a4fb3089133d1543849bfdc44ccb8855ba0b7e
use core::mem; use core::time::Duration; use enumflags2::bitflags; use enumflags2::BitFlags; use crate::io::ReadInt as _; use crate::protocol::spdm; use crate::protocol::spdm::CommandType; protocol_struct! { type GetCaps; const TYPE: CommandType = GetCaps; #![fuzz_derives_if = any()] ...
use core::mem; use core::time::Duration; use enumflags2::bitflags; use enumflags2::BitFlags; use crate::io::ReadInt as _; use crate::protocol::spdm; use crate::protocol::spdm::CommandType; protocol_struct! { type GetCaps; const TYPE: CommandType = GetCaps; #![fuzz_derives_if = any()] ...
(size, Some(size)) } } #[cfg(feature = "arbitrary-derive")] impl Arbitrary for GetCapsResponse { fn arbitrary(u: &mut Unstructured) -> arbitrary::Result<Self> { Ok(Self { crypto_timeout: u.arbitrary()?, caps: arbitrary_bitflags(u)?, max_packet_size: u.arbitr...
let size = mem::size_of::<Duration>() + mem::size_of::<BitFlags<Caps>>() + mem::size_of::<u32>() * 2;
assignment_statement
[ { "content": "/// No-std helper for using as a `write!()` target.\n\nstruct ArrayBuf<const N: usize>([u8; N], usize);\n\n\n\nimpl<const N: usize> AsRef<str> for ArrayBuf<N> {\n\n fn as_ref(&self) -> &str {\n\n core::str::from_utf8(&self.0[..self.1]).unwrap()\n\n }\n\n}\n\n\n\nimpl<const N: usize> D...
Rust
kernel/src/allocator/tests.rs
rrybarczyk/osy
3328c26343d47c31e615df080d4769821567df15
mod align_util { use allocator::util::{align_up, align_down}; #[test] fn test_align_down() { assert_eq!(align_down(0, 2), 0); assert_eq!(align_down(0, 8), 0); assert_eq!(align_down(0, 1 << 5), 0); assert_eq!(align_down(1 << 10, 1 << 10), 1 << 10); assert_eq!(align_d...
mod align_util { use allocator::util::{align_up, align_down}; #[test] fn test_align_down() { a
12), 0xAF000); assert_eq!(align_down(0xAFFFF, 1 << 16), 0xA0000); } #[test] fn test_align_up() { assert_eq!(align_up(0, 2), 0); assert_eq!(align_up(0, 8), 0); assert_eq!(align_up(0, 1 << 5), 0); assert_eq!(align_up(1 << 10, 1 << 10), 1 << 10); assert_eq!(al...
ssert_eq!(align_down(0, 2), 0); assert_eq!(align_down(0, 8), 0); assert_eq!(align_down(0, 1 << 5), 0); assert_eq!(align_down(1 << 10, 1 << 10), 1 << 10); assert_eq!(align_down(1 << 20, 1 << 10), 1 << 20); assert_eq!(align_down(1 << 23, 1 << 4), 1 << 23); assert_eq!(alig...
function_block-random_span
[ { "content": "pub fn next_test_ip4() -> SocketAddr {\n\n let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port();\n\n SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))\n\n}\n\n\n", "file_path": "std/src/net/test.rs", "rank": 0, "score": 132764.1280292329 }, {...
Rust
src/types/fetch_attributes.rs
FelixPodint/imap-codec
48019304520dcaade13fc94a5f359d0a450b7a79
use std::num::NonZeroU32; #[cfg(feature = "arbitrary")] use arbitrary::Arbitrary; #[cfg(feature = "serdex")] use serde::{Deserialize, Serialize}; use crate::types::{ body::BodyStructure, core::NString, datetime::MyDateTime, envelope::Envelope, flag::Flag, section::Section, }; #[cfg_attr(feature = "arbitrary"...
use std::num::NonZeroU32; #[cfg(feature = "arbitrary")] use arbitrary::Arbitrary; #[cfg(feature = "serdex")] use serde::{Deserialize, Serialize}; use crate::types::{ body::BodyStructure, core::NString, datetime::MyDateTime, envelope::Envelope, flag::Flag, section::Section, }; #[cfg_attr(feature = "arbitrary"...
} #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum MacroOrFetchAttributes { Macro(Macro), FetchAttributes(Vec<FetchAttribute>), } impl From<Macro> for MacroOrFetchAttributes { fn fro...
e::*; match self { Self::All => vec![Flags, InternalDate, Rfc822Size, Envelope], Self::Fast => vec![Flags, InternalDate, Rfc822Size], Self::Full => vec![Flags, InternalDate, Rfc822Size, Envelope, Body], } }
function_block-function_prefixed
[ { "content": "/// body = \"(\" (body-type-1part / body-type-mpart) \")\"\n\n///\n\n/// Note: This parser is recursively defined. Thus, in order to not overflow the stack,\n\n/// it is needed to limit how may recursions are allowed. (8 should suffice).\n\npub fn body(remaining_recursions: usize) -> impl Fn(&[u8]...
Rust
rsocket/src/frame/setup.rs
sofkyle/rsocket-rust
136fbc70c006c53ee3e3839aa16e97eb7cf845da
use super::{Body, Frame, PayloadSupport, Version, FLAG_METADATA, FLAG_RESUME}; use crate::utils::{RSocketResult, Writeable, DEFAULT_MIME_TYPE}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::time::Duration; #[derive(Debug, PartialEq)] pub struct Setup { version: Version, keepalive: u32, lifetime: u32,...
use super::{Body, Frame, PayloadSupport, Version, FLAG_METADATA, FLAG_RESUME}; use crate::utils::{RSocketResult, Writeable, DEFAULT_MIME_TYPE}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::time::Duration; #[derive(Debug, PartialEq)] pub struct Setup { version: Version, keepalive: u32, lifetime: u32,...
} pub fn builder(stream_id: u32, flag: u16) -> SetupBuilder { SetupBuilder::new(stream_id, flag) } pub fn get_version(&self) -> Version { self.version } pub fn get_keepalive(&self) -> Duration { Duration::from_millis(u64::from(self.keepalive)) } pub fn get_li...
Ok(Setup { version: Version::new(major, minor), keepalive, lifetime, token, mime_metadata: String::from_utf8(mime_metadata.to_vec()).unwrap(), mime_data: String::from_utf8(mime_data.to_vec()).unwrap(), metadata, data, ...
call_expression
[ { "content": "#[inline]\n\nfn to_frame_type(body: &Body) -> u16 {\n\n match body {\n\n Body::Setup(_) => TYPE_SETUP,\n\n Body::Lease(_) => TYPE_LEASE,\n\n Body::Keepalive(_) => TYPE_KEEPALIVE,\n\n Body::RequestResponse(_) => TYPE_REQUEST_RESPONSE,\n\n Body::RequestFNF(_) =>...
Rust
src/pka/compare.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register COMPARE"] pub type R = crate::R<u32, super::COMPARE>; #[doc = "Writer for register COMPARE"] pub type W = crate::W<u32, super::COMPARE>; #[doc = "Register COMPARE `reset()`'s with value 0x01"] impl crate::ResetValue for super::COMPARE { type Type = u32; #[inline(always)] fn reset...
#[doc = "Reader of register COMPARE"] pub type R = crate::R<u32, super::COMPARE>; #[doc = "Writer for register COMPARE"] pub type W = crate::W<u32, super::COMPARE>; #[doc = "Register COMPARE `reset()`'s with value 0x01"] impl crate::ResetValue for super::COMPARE { type Type = u32; #[inline(always)] fn reset...
ls_b(&mut self) -> A_EQUALS_B_W { A_EQUALS_B_W { w: self } } }
mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bits 3:31 - 31:3\\] Ignore on read"] #[inline(always)] pub fn reserved3(&self) -> RESERVED3_R { RESERVED3_R::new(((self.bits >> 3) & 0x1fff_ffff) as u32) } #[doc = "Bit 2 -...
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/p2p/session.rs
placefortea/teatree
7a56755a428fe63ee753df67a7c71d8f668e17ec
use bytes::{BufMut, BytesMut}; use futures::stream::SplitSink; use futures::Sink; use std::collections::HashMap; use std::net::SocketAddr; use tokio::codec::BytesCodec; use tokio::net::UdpFramed; use crate::actor::prelude::*; use crate::primitives::functions::{try_resend_times, DEFAULT_TIMES}; use crate::traits::actor...
use bytes::{BufMut, BytesMut}; use futures::stream::SplitSink; use futures::Sink; use std::collections::HashMap; use std::net::SocketAddr; use tokio::codec::BytesCodec; use tokio::net::UdpFramed; use crate::actor::prelude::*; use crate::primitives::functions::{try_resend_times, DEFAULT_TIMES}; use crate::traits::actor...
} Err(_) => panic!("DEBUG: NETWORK HAVE ERROR"), } actor_ok(()) }) .wait(ctx); Some(()) }); } } impl<A: P2PBridgeActor> Actor for P2PSessionActor<A> { type Context = Con...
if !next.is_empty() { act.send_udp(next, self_sign, next_sign, socket, ctx); }
if_condition
[ { "content": "pub fn parse_http_body_json(bytes: &mut BytesMut) -> Result<Value, ()> {\n\n let mut vec: Vec<u8> = Vec::new();\n\n\n\n for (i, v) in (&bytes).iter().enumerate() {\n\n if v == &13 || v == &10 {\n\n vec.push(v.clone())\n\n } else {\n\n if vec == [13, 10, 13...
Rust
src/connector/mysql/conversion.rs
kyle-mccarthy/quaint
12b6d22014f4e1218e32760a91b7985205e02453
use crate::{ ast::Value, connector::{queryable::TakeRow, TypeIdentifier}, error::{Error, ErrorKind}, }; #[cfg(feature = "chrono")] use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc}; use mysql_async::{ self as my, consts::{ColumnFlags, ColumnType}, }; use std::conve...
use crate::{ ast::Value, connector::{queryable::TakeRow, TypeIdentifier}, error::{Error, ErrorKind}, }; #[cfg(feature = "chrono")] use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc}; use mysql_async::{ self as my, consts::{ColumnFlags, ColumnType}, }; use std::conve...
let mut row = Vec::with_capacity(self.len()); for i in 0..self.len() { row.push(convert(self, i)?); } Ok(row) } }
fn convert(row: &mut my::Row, i: usize) -> crate::Result<Value<'static>> { let value = row.take(i).ok_or_else(|| { let msg = "Index out of bounds"; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })?; let column = ...
function_block-full_function
[ { "content": "#[tracing::instrument(skip(params))]\n\npub fn conv_params<'a>(params: &'a [Value<'a>]) -> crate::Result<Vec<&'a dyn ToSql>> {\n\n let mut converted = Vec::with_capacity(params.len());\n\n\n\n for param in params.iter() {\n\n converted.push(param as &dyn ToSql)\n\n }\n\n\n\n Ok(...
Rust
src/services/filler/processor.rs
Emulator000/pdfiller
89df98bbdb95147269ba9161f619ae59a30a43ce
use std::collections::BTreeMap; use std::str; use async_std::sync::Arc; use log::error; use lopdf::{Dictionary, Document as PdfDocument, Object, ObjectId}; use crate::file::FileProvider; use crate::mongo::models::document::Document; const PDF_VERSION: &str = "1.5"; pub struct DocumentObjects { pub objects: BTre...
use std::collections::BTreeMap; use std::str; use async_std::sync::Arc; use log::error; use lopdf::{Dictionary, Document as PdfDocument, Object, ObjectId}; use crate::file::FileProvider; use crate::mongo::models::document::Document; const PDF_VERSION: &str = "1.5"; pub struct DocumentObjects { pub objects: BTre...
; } "Pages" => { if let Some(dictionary) = upsert_dictionary(&object, pages_object.as_ref().map(|(_, object)| object)) { pages_object = Some(( if let Some((id, _)) = pages_object { ...
Some(( if let Some((id, _)) = catalog_object { id } else { *object_id }, object.clone(), ))
call_expression
[ { "content": "fn get_document_buffer(document: &mut PdfDocument) -> ExportCompilerResult<Vec<u8>> {\n\n let buf = Vec::<u8>::new();\n\n let mut cursor = Cursor::new(buf);\n\n\n\n match document.save_to(&mut cursor) {\n\n Ok(_) => {\n\n let _ = cursor.seek(SeekFrom::Start(0));\n\n\n\n ...
Rust
openethereum/rpc/src/v1/helpers/subscribers.rs
snuspl/fluffy
d17e1fb3cda259d6f2c244ef67ee3a4bdf83261b
use std::{ops, str}; use std::collections::HashMap; use jsonrpc_pubsub::{typed::{Subscriber, Sink}, SubscriptionId}; use ethereum_types::H64; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct Id(H64); impl str::FromStr for Id { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.sta...
use std::{ops, str}; use std::collections::HashMap; use jsonrpc_pubsub::{typed::{Subscriber, Sink}, SubscriptionId}; use ethereum_types::H64; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct Id(H64); impl str::FromStr for Id { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.sta...
} impl<T> Subscribers<Sink<T>> { pub fn push(&mut self, sub: Subscriber<T>) { let id = self.next_id(); if let Ok(sink) = sub.assign_id(SubscriptionId::String(id.as_string())) { debug!(target: "pubsub", "Adding subscription id={:?}", id); self.subscriptions.insert(id, sink); } } } impl<T, V> Subscribe...
pub fn remove(&mut self, id: &SubscriptionId) -> Option<T> { trace!(target: "pubsub", "Removing subscription id={:?}", id); match *id { SubscriptionId::String(ref id) => match id.parse() { Ok(id) => self.subscriptions.remove(&id), Err(_) => None, }, _ => None, } }
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\npub fn json_chain_test<H: FnMut(&str, HookType)>(path: &Path, json_data: &[u8], start_stop_hook: &mut H) -> Vec<String> {\n\n\tlet _ = ::env_logger::try_init();\n\n\tlet tests = ethjson::test_helpers::state::Test::load(json_data)\n\n\t\t.expect(&format!(\"Could not parse JSO...
Rust
src/refmanager.rs
WilsonGramer/ref_thread_local.rs
52cd3d9641d1b776ebd1586bdc914dd889a9f9de
extern crate std; use super::RefThreadLocal; use std::cell::Cell; use std::fmt::{Debug, Display, Formatter}; use std::ops::{Deref, DerefMut}; use std::ptr::{null, null_mut}; use std::thread::LocalKey; struct RefManagerInnerData<T> { borrow_count: Cell<isize>, value: T, } pub struct RefManagerPeekData<T> { ...
extern crate std; use super::RefThreadLocal; use std::cell::Cell; use std::fmt::{Debug, Display, Formatter}; use std::ops::{Deref, DerefMut}; use std::ptr::{null, null_mut}; use std::thread::LocalKey; struct RefManagerInnerData<T> { borrow_count: Cell<isize>, value: T, } pub struct RefManagerPeekData<T> { ...
} impl<'a, T: Debug> Debug for Ref<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { Debug::fmt(&**self, f) } } impl<'a, T: Display> Display for Ref<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { self.value.fmt(f) } } impl<'a, T: ?Sized> Drop for RefMut...
pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'a, T>, f: F) -> (Ref<'a, U>, Ref<'a, V>) where F: FnOnce(&T) -> (&U, &V), { let borrow_count = orig.borrow_count; let value = orig.value; std::mem::forget(orig); let (a, b) = f(value); borrow_count.set(borrow_co...
function_block-full_function
[ { "content": "fn __static_ref_initialize() -> X {\n\n X\n\n}\n", "file_path": "tests/test.rs", "rank": 0, "score": 76498.62253932712 }, { "content": "#[test]\n\nfn test_borrow_mut_after_borrow() {\n\n let _a = NUMBER.try_borrow();\n\n let _b = NUMBER.try_borrow_mut();\n\n _a.expe...
Rust
src/parser/combinators.rs
ireina7/abyss.rs
2c374996d68a6940a6100ff41e1912d3daca9db9
use super::core::*; #[allow(dead_code)] pub fn wrap<P: Parser>(p: P) -> Wrapper<P> { Wrapper::new(p) } #[allow(dead_code)] pub fn pure<A: Clone>(x: A) -> Pure<A> { Pure::new(x) } #[allow(dead_code)] pub fn satisfy<F>(f: F) -> Satisfy<F> where F: Fn(&char) -> bool { Satisfy::new(f) } #[allow(dead_co...
use super::core::*; #[allow(dead_code)] pub fn wrap<P: Parser>(p: P) -> Wrapper<P> { Wrapper::new(p) } #[allow(dead_code)] pub fn pure<A: Clone>(x: A) -> Pure<A> { Pure::new(x) } #[allow(dead_code)] pub fn satisfy<F>(f: F) -> Satisfy<F> where F: Fn(&char) -> bool { Satisfy::new(f) } #[allow(dead_co...
.parse(&mut src), Ok('c')); }*/ #[test] fn test_parser_many() { let mut src = ParseState::new("aa0bcdefghijklmn"); let parser = many(char('a')); assert_eq!(parser.parse(&mut src), Ok(vec!['a', 'a'])); } #[test] fn test_parser_many1() { let mut src = ParseState::...
.info(&format!("Parsing char of one of {}", cs)) } #[allow(dead_code)] pub fn except(cs: &str) -> Wrapper<impl Parser<Output=char> + Clone> { let ss = cs.to_string(); satisfy(move |&c| !ss.chars().any(|x| x == c)) .info(&format!("Parsing char except one of {}", cs)) } #[allow(dead_code)] pub fn i...
random
[ { "content": "/// Check if variable is atom (normal form)\n\nfn is_atom(s: &str) -> bool {\n\n let atoms = [\"True\", \"False\"];\n\n atoms.iter().any(|&x| x == s)\n\n}\n\n\n", "file_path": "src/abyss/eval/strict.rs", "rank": 18, "score": 143964.6489613122 }, { "content": "/// Test if ...
Rust
src/entities.rs
JoshMcguigan/amethyst-2d-platformer-demo
fa4c53621e4af22e6e7f0657e83bfa13f50bf341
use amethyst::{ assets::{AssetStorage, Loader}, core::{Transform}, ecs::{Entity}, prelude::*, renderer::{ Camera, PngFormat, Projection, Sprite, SpriteRender, SpriteSheet, SpriteSheetHandle, Texture, TextureMetadata, SpriteSheetFormat, Transparent }, }; use crate::{ DISPLAY_W...
use amethyst::{ assets::{AssetStorage, Loader}, core::{Transform}, ecs::{Entity}, prelude::*, renderer::{ Camera, PngFormat, Projection, Sprite, SpriteRender, SpriteSheet, SpriteSheetHandle, Texture, TextureMetadata, SpriteSheetFormat, Transparent }, }; use crate::{ DISPLAY_W...
fn init_crate_sprite(world: &mut World, sprite_sheet: &SpriteSheetHandle, left: f32, bottom: f32) -> Entity { let mut transform = Transform::default(); transform.set_z(-9.); let sprite = SpriteRender { sprite_sheet: sprite_sheet.clone(), sprite_number: 0, }; let mut two_dim_object...
world.create_entity() .with(transform) .with(two_dim_object) .with(sprite) .with(Transparent) .build() }
function_block-function_prefix_line
[ { "content": "fn main() -> amethyst::Result<()> {\n\n amethyst::start_logger(Default::default());\n\n let config = DisplayConfig::load(\"./resources/display_config.ron\");\n\n let pipe = Pipeline::build().with_stage(\n\n Stage::with_backbuffer()\n\n .clear_target([0.1, 0.1, 0.2, 1.0],...
Rust
src/lib.rs
psFried/pgen
008a4c680cd3651da5442780076523df1e8df86e
#[macro_use] extern crate failure; #[macro_use] extern crate lazy_static; extern crate byteorder; extern crate encoding; extern crate itertools; extern crate lalrpop_util; extern crate rand; extern crate regex; extern crate rustyline; extern crate string_cache; mod arguments; pub(crate) mod builtins; mod context; pub...
#[macro_use] extern crate failure; #[macro_use] extern crate lazy_static; extern crate byteorder; extern crate encoding; extern crate itertools; extern crate lalrpop_util; extern crate rand; extern crate regex; extern crate rustyline; extern crate string_cache; mod arguments; pub(crate) mod builtins; mod context; pub...
pub fn write_value( &self, context: &mut ProgramContext, output: &mut DataGenOutput, ) -> Result<(), Error> { match *self { AnyFunction::String(ref fun) => fun.write_value(context, output), AnyFunction::Uint(ref fun) => fun.write_value(context, output), ...
pub fn get_type(&self) -> GenType { match *self { AnyFunction::String(_) => GenType::String, AnyFunction::Uint(_) => GenType::Uint, AnyFunction::Int(_) => GenType::Int, AnyFunction::Decimal(_) => GenType::Decimal, AnyFunction::Boolean(_) => GenType::Bo...
function_block-full_function
[ { "content": "fn execute_fn(function: AnyFunction, context: &mut ProgramContext) -> Result<(), Error> {\n\n let out = io::stdout();\n\n let mut lock = out.lock();\n\n\n\n let result = {\n\n let mut dgen_out = DataGenOutput::new(&mut lock);\n\n function.write_value(context, &mut dgen_out)....
Rust
src/resolution/constraint/contact_equation.rs
BenBergman/nphysics
11ca4d6f967c35e7f51e65295174c5b0395cbd93
use na::Bounded; use na; use num::Float; use ncollide::geometry::Contact; use volumetric::InertiaTensor; use resolution::constraint::velocity_constraint::VelocityConstraint; use object::RigidBody; use math::{Scalar, Point, Vect, Orientation}; pub enum CorrectionMode { Velocity(Scalar), VelocityAndPos...
use na::Bounded; use na; use num::Float; use ncollide::geometry::Contact; use volumetric::InertiaTensor; use resolution::constraint::velocity_constraint::VelocityConstraint; use object::RigidBody; use math::{Scalar, Point, Vect, Orientation}; pub enum CorrectionMode { Velocity(Scalar), VelocityAndPos...
e::VelocityAndPositionThresold(_, ref p, _) => p.clone(), CorrectionMode::Velocity(_) => na::zero() } } #[inline] pub fn min_depth_for_pos_corr(&self) -> Scalar { match *self { CorrectionMode::VelocityAndPosition(_, _, ref t) ...
orr_factor(&self) -> Scalar { match *self { CorrectionMode::VelocityAndPosition(_, ref p, _) => p.clone(), CorrectionMod
function_block-random_span
[]
Rust
src/hs_types.rs
a-mackay/raystack
26837f3c148f0e21ba529f40925828e3f291c333
use chrono::{NaiveDate, NaiveTime}; use chrono_tz::Tz; use raystack_core::{FromHaysonError, Hayson}; use serde_json::{json, Value}; use std::convert::From; const KIND: &str = "_kind"; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Date(NaiveDate); impl Date { pub fn new(naive_date: NaiveDate) -> Self { ...
use chrono::{NaiveDate, NaiveTime}; use chrono_tz::Tz; use raystack_core::{FromHaysonError, Hayson}; use serde_json::{json, Value}; use std::convert::From; const KIND: &str = "_kind"; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Date(NaiveDate); impl Date { pub fn new(naive_date: NaiveDate) -> Self { ...
let tz_value = obj.get("tz"); let mut tz_str = default_tz.to_owned(); if let Some(value) = tz_value { match value { Value::Null => { tz_str = default_tz.to_owned(); } ...
if let Some(kind_err) = hayson_check_kind("dateTime", value) { return Err(kind_err); }
if_condition
[ { "content": "/// Convert a `DateTime` into a string which can be used in ZINC files.\n\nfn to_zinc_encoded_string(date_time: &DateTime) -> String {\n\n let time_zone_name = date_time.short_time_zone();\n\n format!(\n\n \"{} {}\",\n\n date_time\n\n .date_time()\n\n .to_...
Rust
src/timestamp.rs
Cognoscan/fog_pack
7b3af246faa851bfc2aa09cc186ff2332124e791
use std::cmp; use std::convert::TryFrom; use std::fmt; use std::ops; use std::time; use byteorder::{LittleEndian, ReadBytesExt}; use fog_crypto::serde::{ CryptoEnum, FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_INDEX, FOG_TYPE_ENUM_TIME_NAME, }; use serde::{ de::{Deserialize, Deserializer, EnumAccess, Error, Unexpected...
use std::cmp; use std::convert::TryFrom; use std::fmt; use std::ops; use std::time; use byteorder::{LittleEndian, ReadBytesExt}; use fog_crypto::serde::{ CryptoEnum, FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_INDEX, FOG_TYPE_ENUM_TIME_NAME, }; use serde::{ de::{Deserialize, Deserializer, EnumAccess, Error, Unexpected...
pub fn size(&self) -> usize { if self.nano != 0 { 1 + 8 + 4 } else if (self.sec <= u32::MAX as i64) && (self.sec >= 0) { 1 + 4 } else { 1 + 8 } } pub fn now() -> Option<Timestamp> { match time::SystemTime::now().du...
vec.push(self.standard); vec.extend_from_slice(&self.sec.to_le_bytes()); vec.extend_from_slice(&self.nano.to_le_bytes()); } else if (self.sec <= u32::MAX as i64) && (self.sec >= 0) { vec.reserve(1 + 4); vec.push(self.standard); vec.extend_from_slice(&(...
function_block-function_prefix_line
[ { "content": "/// Serialize an element onto a byte vector. Doesn't check if Array & Map structures make\n\n/// sense, just writes elements out.\n\npub fn serialize_elem(buf: &mut Vec<u8>, elem: Element) {\n\n use self::Element::*;\n\n match elem {\n\n Null => buf.push(Marker::Null.into()),\n\n ...
Rust
src/main.rs
thehamsterjam/better_aws_sso
4a2fbee508c549dbba65fe17e7557fdb844581d3
use clap::{App, Arg}; use ini::Ini; use serde::Deserialize; use std::{thread, time}; use ureq::Response; use webbrowser; extern crate dirs; use std::time::{SystemTime, UNIX_EPOCH}; const GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code"; #[derive(Debug)] #[allow(non_snake_case)] struct SsoProfile { ...
use clap::{App, Arg}; use ini::Ini; use serde::Deserialize; use std::{thread, time}; use ureq::Response; use webbrowser; extern crate dirs; use std::time::{SystemTime, UNIX_EPOCH}; const GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code"; #[derive(Debug)] #[allow(non_snake_case)] struct SsoProfile { ...
fn _list_accounts(sso_url: String, access_token: String) -> Response { ureq::get(format!("{}{}", sso_url, "/assignment/accounts").as_str()) .query("max_result", "100") .set( "x-amz-sso_bearer_token", format!("{}", access_token).as_str(), ) .call() }
f save_as_profile_name { format!("{}_", profile) } else { format!("{}_{}", sso_account_id, sso_role_name) }; let mut aws_creds = Ini::load_from_file(format!("{}{}", home_dir, "/.aws/credentials")).unwrap(); if verbose { println!("Section name : {}", section_name); }...
function_block-function_prefixed
[ { "content": "fn get_latest_version() -> String {\n\n let api_url = \"https://api.github.com/repos/thehamsterjam/better_aws_sso/releases/latest\";\n\n let resp = ureq::get(api_url)\n\n .call()\n\n .into_json()\n\n .unwrap();\n\n resp[\"tag_name\"].to_string()\n\n}", "file_path"...
Rust
src/sol.rs
Aehmlo/sudoku
d2cb746ff47d427128f53f593efc555212cf32b5
use crate::sudoku::Grid; use crate::Element; use crate::Point; use crate::Sudoku; use crate::DIMENSIONS; use std::ops::{Index, IndexMut}; #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] pub enum Difficulty { #[doc(hidden)] Unplayable, Beginner, Easy, Intermediate, ...
use crate::sudoku::Grid; use crate::Element; use crate::Point; use crate::Sudoku; use crate::DIMENSIONS; use std::ops::{Index, IndexMut}; #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] pub enum Difficulty { #[doc(hidden)] Unplayable, Beginner, Easy, Intermediate, ...
pub fn eliminate(&mut self, index: Point, value: usize) { self[index] = self[index].and_then(|e| e.eliminate(value)); } pub fn next(&self) -> (Option<Point>, Option<PossibilitySet>) { let mut best = None; let mut best_index = None; let mut best_sco...
f { Self { possibilities: vec![ Some(PossibilitySet::new(order)); (order as usize).pow(2 + DIMENSIONS as u32) ], order, parent: None, } }
function_block-function_prefixed
[ { "content": "/// Trait to generate a puzzle.\n\n///\n\n/// Requires that the puzzle be solvable (to ensure the desired difficulty is\n\n/// attained).\n\npub trait Generate: Score + Sized {\n\n /// Generates a puzzle of the desired order and difficulty.\n\n fn generate(order: u8, difficulty: Difficulty) ...
Rust
flow-rs/src/channel/storage.rs
ysh329/MegFlow
778a4361a88af43f499528f4509f6523515ce0ee
/** * \file flow-rs/src/channel/storage.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS I...
/** * \file flow-rs/src/channel/storage.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS I...
> ChannelStorage { ChannelStorage { storage: inner::bounded(cap), receiver_epoch: Arc::new(AtomicUsize::new(0)), sender_epoch: Arc::new(AtomicUsize::new(0)), sender_record: Arc::new(Mutex::new(HashMap::new())), rx_counter: Arc::new(AtomicUsize::new(0))...
queue.is_closed() } fn is_none(&self) -> bool { false } } impl ChannelStorage { pub fn bound(cap: usize) -
random
[ { "content": "pub fn ident(lit: impl AsRef<str>) -> Ident {\n\n Ident::new(lit.as_ref(), Span::call_site())\n\n}\n", "file_path": "flow-derive/src/lit.rs", "rank": 0, "score": 153767.02012632263 }, { "content": "pub fn match_last_ty(ty: &syn::Type, wrapper: &str) -> bool {\n\n match ty...
Rust
src/external_service/spread_sheet/token_manager.rs
tacogips/api-everywhere
02224c875afee72dc0ad82707e1ef1a0d7eff51a
use arc_swap::ArcSwap; use chrono::{Duration, Local}; use hyper; use log; use once_cell::sync::OnceCell; use std::path::PathBuf; use std::sync::Arc; use thiserror::Error; use tokio::sync::broadcast; use tokio::task::{JoinError, JoinHandle}; use tokio::time::timeout; use yup_oauth2::{ self as oauth, authenticato...
use arc_swap::ArcSwap; use chrono::{Duration, Local}; use hyper; use log; use once_cell::sync::OnceCell; use std::path::PathBuf; use std::sync::Arc; use thiserror::Error; use tokio::sync::broadcast; use tokio::task::{JoinError, JoinHandle}; use tokio::time::timeout; use yup_oauth2::{ self as oauth, authenticato...
})?; let authenticator = oauth::ServiceAccountAuthenticator::builder(sa_key) .build() .await .map_err(|e| { GoogleTokenManagerError::InvalidServiceAccountFileError(service_account_cred_file, e) })?; TokenManager::start( authenticator, scopes, ...
nt_token, token_refreshing_loop_jh, }; Ok(result) } async fn periodically_refreshing_token( authenticator: Arc<Authenticator<HttpConnector>>, shared_token: Arc<ArcSwap<AccessToken>>, scopes: &'static [&'static str], mut stop_refreshing_notifyer_rx: br...
random
[ { "content": "/// \"A\" -> 0\n\n/// \"Z\" -> 25\n\n/// \"AA\"-> 26\n\npub fn col_alphabet_to_num(n: &str) -> Result<usize> {\n\n let chars: Vec<char> = n.chars().into_iter().collect();\n\n let mut digit = chars.len();\n\n let mut result = 0usize;\n\n for each in chars {\n\n let num_at_digi...
Rust
2d-games/match-three/src/mgfw/ecs/entity.rs
Syn-Nine/rust-mini-games
b80fa60d524c8fb6749731cbc078a1a2526861ed
use super::*; use crate::mgfw::log; pub const ENTITY_SZ: usize = 256; #[derive(Copy, Clone)] pub struct EntityIdSpan { pub first: usize, pub last: usize, } struct Entity { components: u32, } pub struct EntityRegistry { data: *mut Entity, cursor: usize, span: EntityIdSpan, } #[allow(d...
use super::*; use crate::mgfw::log; pub const ENTITY_SZ: usize = 256; #[derive(Copy, Clone)] pub struct EntityIdSpan { pub first: usize, pub last: usize, } struct Entity { components: u32, } pub struct EntityRegistry { data: *mut Entity, cursor: usize, span: EntityIdSpan, } #[allow(d...
} } fn get_data_ref_mut(&self, idx: usize) -> &mut Entity { assert!(idx < ENTITY_SZ); unsafe { &mut *(self.data.offset(idx as isize)) } } fn get_data_ref(&self, idx: usize) -> &Entity { assert!(idx < ENTITY_SZ); unsafe { &*(self.data.offset(idx as isize)) } ...
if self.has_component(idx, COMPONENT_ACTIVE) { if idx < self.span.first { self.span.first = idx; } if idx > self.span.last { self.span.last = idx; } }
if_condition
[ { "content": "// update the entities for the cursor\n\npub fn update_cursor_entities(cache: &mut GameData, world: &mut mgfw::ecs::World) {\n\n let mut j: usize = 0;\n\n let loc = get_cursor_location(cache);\n\n let cx: f32 = loc.0 as f32 * 16.0 + 8.0;\n\n let cy: f32 = loc.1 as f32 * 16.0 + 56.0;\n\...
Rust
src/window/glutin.rs
jutuon/space-boss-battles
407d3fa1f057ea0ce9b05b6f695349be1f3a141f
use std::os::raw::c_void; use glutin::{EventsLoop, GlContext, WindowBuilder, ContextBuilder, GlWindow, GlRequest, Api, VirtualKeyCode}; use input::{InputManager, Key, Input}; use renderer::{Renderer, DEFAULT_SCREEN_HEIGHT, DEFAULT_SCREEN_WIDTH}; use settings::Settings; use gui::GUI; use logic::Logic; use utils::{Ti...
use std::os::raw::c_void; use glutin::{EventsLoop, GlContext, WindowBuilder, ContextBuilder, GlWindow, GlRequest, Api, VirtualKeyCode}; use input::{InputManager, Key, Input}; use renderer::{Renderer, DEFAULT_SCREEN_HEIGHT, DEFAULT_SCREEN_WIDTH}; use settings::Settings; use gui::GUI; use logic::Logic; use utils::{Ti...
} WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Released, virtual_keycode: Some(keycode), .. ...
if let Some(key) = virtual_keycode_to_key(keycode) { input_manager.update_key_down(key, time_manager.current_time()); }
if_condition
[ { "content": "/// Returns the value of boolean reference and sets\n\n/// references value to false.\n\nfn return_and_reset(value: &mut bool) -> bool {\n\n let original_value: bool = *value;\n\n *value = false;\n\n original_value\n\n}\n\n\n\nimpl Input for InputManager {\n\n fn up(&self) -> bool {...
Rust
crates/fluvio-test/src/tests/longevity/mod.rs
bohlmannc/fluvio
b5a3105600b6886c55d76707d369fa59f5d9673b
pub mod producer; pub mod consumer; use core::panic; use std::any::Any; use std::num::ParseIntError; use std::time::Duration; use structopt::StructOpt; use fluvio_test_derive::fluvio_test; use fluvio_test_util::test_meta::environment::EnvironmentSetup; use fluvio_test_util::test_meta::{TestOption, TestCase}; use fluv...
pub mod producer; pub mod consumer; use core::panic; use std::any::Any; use std::num::ParseIntError; use std::time::Duration; use structopt::StructOpt; use fluvio_test_derive::fluvio_test; use fluvio_test_util::test_meta::environment::EnvironmentSetup; use fluvio_test_util::test_meta::{TestOption, TestCase}; use fluv...
} #[derive(Debug, Clone, StructOpt, Default, PartialEq)] #[structopt(name = "Fluvio Longevity Test")] pub struct LongevityTestOption { #[structopt(long, parse(try_from_str = parse_seconds), default_value = "3600")] runtime_seconds: Duration, #[structopt(long, default_value = "1000")]...
e .option .as_any() .downcast_ref::<LongevityTestOption>() .expect("LongevityTestOption") .to_owned(); LongevityTestCase { environment: test_case.environment, option: longevity_option, } }
function_block-function_prefixed
[ { "content": "fn cluster_cleanup(option: EnvironmentSetup) {\n\n if option.cluster_delete() {\n\n let mut setup = TestCluster::new(option);\n\n\n\n let cluster_cleanup_wait = async_process!(async {\n\n setup.remove_cluster().await;\n\n });\n\n let _ = cluster_cleanup_wa...
Rust
src/octez/node.rs
tzConnectBerlin/que-pasa
c79769fbe7aa8d0ef3e1d104bb45f68bf63a7c7d
use crate::octez::block::{Block, LevelMeta}; use anyhow::{anyhow, Context, Result}; use backoff::{retry, Error, ExponentialBackoff}; use chrono::{DateTime, Utc}; use curl::easy::Easy; use serde::Deserialize; use std::str::FromStr; use std::time::Duration; #[derive(Clone)] pub struct NodeClient { node_url: String, ...
use crate::octez::block::{Block, LevelMeta}; use anyhow::{anyhow, Context, Result}; use backoff::{retry, Error, ExponentialBackoff}; use chrono::{DateTime, Utc}; use curl::easy::Easy; use serde::Deserialize; use std::str::FromStr; use std::time::Duration; #[derive(Clone)] pub struct NodeClient { node_url: String, ...
pub(crate) fn get_contract_storage_definition( &self, contract_id: &str, level: Option<u32>, ) -> Result<serde_json::Value> { let level = match level { Some(x) => format!("{}", x), None => "head".to_string(), }; let (_, json) = self...
fn level_json_internal(&self, level: &str) -> Result<(LevelMeta, Block)> { let (body, _) = self .load_retry_on_nonjson(&format!("blocks/{}", level)) .with_context(|| { format!("failed to get level_json for level={}", level) })?; let mut deserializer =...
function_block-full_function
[ { "content": "fn is_implicit_active(level: u32, contract_address: &str) -> bool {\n\n // liquidity baking has 2 implicit contract creation events in the block prior to Granada's activation block\n\n level == LIQUIDITY_BAKING_LEVEL\n\n && (contract_address == LIQUIDITY_BAKING\n\n || contr...
Rust
benches/custom_benches.rs
IzumiRaine/libdeflater
3a90be5798fc9949e9a416efeaba4663ac7d4e25
extern crate flate2; extern crate libdeflater; use std::io::prelude::*; use std::fs; use std::fs::{File}; use std::path::Path; use criterion::{Criterion, black_box}; use flate2::{Compression, Compress, Decompress, FlushCompress, FlushDecompress}; use libdeflater::{Compressor, CompressionLvl, Decompressor}; struct F...
extern crate flate2; extern crate libdeflater; use std::io::prelude::*; use std::fs; use std::fs::{File}; use std::path::Path; use crit
inish(); } }
erion::{Criterion, black_box}; use flate2::{Compression, Compress, Decompress, FlushCompress, FlushDecompress}; use libdeflater::{Compressor, CompressionLvl, Decompressor}; struct Flate2Encoder { compress: Compress, } impl Flate2Encoder { fn new() -> Flate2Encoder { Flate2Encoder{ compress: Compress:...
random
[ { "content": "#[test]\n\nfn test_use_crc32_convenience_method_returns_same_crc32_as_flate2() {\n\n // This assumes that flate2's crc32 implementation returns a\n\n // correct value, which is a pretty safe assumption.\n\n\n\n let input_data = read_fixture_content();\n\n\n\n let flate2_crc32 = {\n\n ...
Rust
aoc13/src/main.rs
jadeaffenjaeger/rust_aoc19
4f3f4160377cbfdb76207ab942afc8306b201b2d
use intcomputer::*; use display::*; use std::env; use std::fs; use num_enum::TryFromPrimitive; use std::convert::TryFrom; const WIDTH: usize = 44; const HEIGHT: usize = 20; const SCALE: usize = 25; #[derive(Debug, Clone, Copy, PartialEq, TryFromPrimitive)] #[repr(i64)] enum Tile { Empty = 0, Wall = 1, B...
use intcomputer::*; use display::*; use std::env; use std::fs; use num_enum::TryFromPrimitive; use std::convert::TryFrom; const WIDTH: usize = 44; const HEIGHT: usize = 20; const SCALE: usize = 25; #[derive(Debug, Clone, Copy, PartialEq, TryFromPrimitive)] #[repr(i64)] enum Tile { Empty = 0, Wall = 1, B...
pub fn left(&mut self) { self.computer.input.push_back(-1); } pub fn right(&mut self) { self.computer.input.push_back(1); } pub fn neutral(&mut self) { self.computer.input.push_back(0); } pub fn consume_output(&mut self) { while self.computer.output.len()...
p { self.computer.run(); match self.computer.state { ProgramState::Finished => break, ProgramState::Running => continue, ProgramState::WaitingForInput => { self.consume_output(); break; } ...
function_block-function_prefixed
[ { "content": "fn combine_layers(layer: &[u32], image: &mut [u32]) {\n\n let combine_pixels = |top, bottom| match top {\n\n 2 => bottom,\n\n _ => top,\n\n };\n\n\n\n for (p1, p2) in image.iter_mut().zip(layer.iter()) {\n\n *p1 = combine_pixels(*p1, *p2);\n\n }\n\n}\n\n\n", "f...
Rust
textures/src/imagemap.rs
hackmad/pbr_rust
b7ae75564bf71c4dfea8b20f49d05ac1b89e6734
use super::*; use core::geometry::*; use core::interaction::*; use core::mipmap::*; use core::pbrt::*; use core::spectrum::*; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign}; #[derive(Clone)] pub struct ImageTexture<Tmemory> where Tmemory: Copy + Default + Mul<Float, Output = Tmemo...
use super::*; use core::geometry::*; use core::interaction::*; use core::mipmap::*; use core::pbrt::*; use core::spectrum::*; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign}; #[derive(Clone)] pub struct ImageTexture<Tmemory> where Tmemory: Copy + Default + Mul<Float, Output = Tmemo...
let mem = self.mipmap.lookup(&st, &dstdx, &dstdy); let rgb = mem.to_rgb(); Spectrum::from_rgb(&rgb, None) } } impl Texture<Float> for ImageTexture<Float> { fn evaluate(&self, hit: &Hit, uv: &Point2f, der: &Derivatives) -> Float { let...
let TextureMap2DResult { p: st, dstdx, dstdy, } = self.mapping.map(hit, uv, der);
assignment_statement
[]
Rust
imxrt1062-pac/imxrt1062-ocotp/src/crc_addr.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register CRC_ADDR"] pub type R = crate::R<u32, super::CRC_ADDR>; #[doc = "Writer for register CRC_ADDR"] pub type W = crate::W<u32, super::CRC_ADDR>; #[doc = "Register CRC_ADDR `reset()`'s with value 0"] impl crate::ResetValue for super::CRC_ADDR { type Type = u32; #[inline(always)] fn re...
#[doc = "Reader of register CRC_ADDR"] pub type R = crate::R<u32, super::CRC_ADDR>; #[doc = "Writer for register CRC_ADDR"] pub type W = crate::W<u32, super::CRC_ADDR>; #[doc = "Register CRC_ADDR `reset()`'s with value 0"] impl crate::ResetValue for super::CRC_ADDR { type Type = u32; #[inline(always)] fn re...
{ OTPMK_CRC_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bits 25:31 - RSVD0"] #[inline(always)] pub fn rsvd0(&self) -> RSVD0_R { RSVD0_R::new(((self.bits >> 25) & 0x7f) as u8) } } impl W { #[doc = "Bits 0:7 - DATA_START_ADDR"] #[inline(always)] pub fn data_start_add...
field `CRC_ADDR`"] pub type CRC_ADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CRC_ADDR`"] pub struct CRC_ADDR_W<'a> { w: &'a mut W, } impl<'a> CRC_ADDR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits =...
random
[]
Rust
src/transaction.rs
tiagolobocastro/heath
4faedf8f37acba0ac183273cfc0cd00286526ded
use crate::{ client::ClientId, csv::transaction::{TransactionId, TransactionLogCsv, TransactionType}, transactions::TransactionInfo, }; use serde::{Deserialize, Serialize}; impl TransactionInfo for TransactionLog { fn transaction_type(&self) -> TransactionType { match self { Self::D...
use crate::{ client::ClientId, csv::transaction::{TransactionId, TransactionLogCsv, TransactionType}, transactions::TransactionInfo, }; use serde::{Deserialize, Serialize}; impl TransactionInfo for TransactionLog { fn transaction_type(&self) -> TransactionType { match self { Self::D...
match tx.transaction_type() { TransactionType::Deposit => Self::Deposit { common, amount: tx.amount().expect("Deposit should contain the amount"), }, TransactionType::Withdrawal => Self::Withdrawal { common, amo...
let common = TransactionLogCommon { client_id: tx.client_id(), tx_id: tx.transaction_id(), };
assignment_statement
[ { "content": " account: BankAccount,\n\n disputed_tx: Option<TransactionLog>,\n\n}\n\nimpl Dispute {\n\n pub(crate) fn new(account: BankAccount, disputed_tx: Option<TransactionLog>) -> Self {\n\n Self {\n\n account,\n\n disputed_tx,\n\n }\n\n }\n\n}\n\nimpl Transa...
Rust
src/terminal/winapi_terminal.rs
Rukenshia/crossterm
caa7579ef6102f966a7436f55c2dfda2e30efb5a
use {Construct}; use cursor::cursor; use super::{ClearType, ITerminal}; use winapi::um::wincon::{SMALL_RECT, COORD, CONSOLE_SCREEN_BUFFER_INFO,}; use kernel::windows_kernel::{kernel, terminal}; pub struct WinApiTerminal; impl Construct for WinApiTerminal { fn new() -> Box<WinApiTerminal> { Box::from(Win...
use {Construct}; use cursor::cursor; use super::{ClearType, ITerminal}; use winapi::um::wincon::{SMALL_RECT, COORD, CONSOLE_SCREEN_BUFFER_INFO,}; use kernel::windows_kernel::{kernel, terminal}; pub struct WinApiTerminal; impl Construct for WinApiTerminal { fn new() -> Box<WinApiTerminal> { Box::from(Win...
pub fn clear_entire_screen(csbi: CONSOLE_SCREEN_BUFFER_INFO) { let x = 0; let y = 0; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = csbi.dwSize.X as u32 * csbi.dwSize.Y as u32; clear( start_location, cells_to_write); cursor().goto(0,...
pub fn clear_before_cursor(pos: (u16,u16), csbi: CONSOLE_SCREEN_BUFFER_INFO) { let (xpos,ypos) = pos; let x = 0; let y = 0; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = (csbi.dwSize.X as u32 * ypos as u32) + (xpos as u32 + 1); clear(start...
function_block-full_function
[ { "content": "pub fn set_console_screen_buffer_size( size: COORD) -> bool\n\n{\n\n let output_handle = get_output_handle();\n\n\n\n unsafe\n\n {\n\n let success = SetConsoleScreenBufferSize(output_handle, size);\n\n is_true(success)\n\n }\n\n}\n\n\n", "file_path": ...
Rust
src/skelly.rs
lain-dono/skelly
f161e4d3641c22fb764936bf441dac8434c3f9d1
use na::{Isometry3, Point3, RealField, Scalar, Translation3, UnitQuaternion}; pub struct Skelly<T: Scalar, D = ()> { bones: Vec<Bone<T, D>>, } struct Bone<T: Scalar, D> { isometry: Isometry3<T>, parent: Option<usize>, userdata: D, } impl<T> Skelly<T> where T: Scalar, { pub fn add_ro...
use na::{Isometry3, Point3, RealField, Scalar, Translation3, UnitQuaternion}; pub struct Skelly<T: Scalar, D = ()> { bones: Vec<Bone<T, D>>, } struct Bone<T: Scalar, D> { isometry: Isometry3<T>, parent: Option<usize>, userdata: D, } impl<T> Skelly<T> where T: Scalar, { pub fn add_ro...
mut self, bone: usize) -> &mut D { &mut self.bones[bone].userdata } pub fn get_parent(&self, bone: usize) -> Option<usize> { self.bones[bone].parent } pub fn len(&self) -> usize { self.bones.len() } pub fn write_globals(&self, globals: &mut [Isometry3<T>...
ttach(&mut self, relative_position: Point3<T>, parent: usize) -> usize where T: RealField, { self.attach_with(relative_position, parent, ()) } } impl<T, D> Skelly<T, D> where T: Scalar, { pub fn new() -> Self { Skelly { bones: Vec::new() } } pub fn ad...
random
[ { "content": "fn enque<T>(queue: &mut Vec<QueueItem<T>>, bone: usize, tip: Point3<T>, goal: Point3<T>)\n\nwhere\n\n T: Scalar,\n\n{\n\n let index = queue\n\n .binary_search_by(|item| item.bone.cmp(&bone))\n\n .unwrap_or_else(|x| x);\n\n\n\n queue.insert(index, QueueItem { bone, tip, goal ...
Rust
benches/spmc_mt_read_write_bench.rs
tower120/lockless_event_queue
aa55039161736c88b103a520f83ce8f8ab66288f
use rc_event_queue::spmc::{EventQueue, EventReader, Settings}; use criterion::{Criterion, black_box, criterion_main, criterion_group, BenchmarkId}; use std::time::{Duration, Instant}; use std::thread; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::pin::Pin; use rc_event_queue::{CleanupMode,...
use rc_event_queue::spmc::{EventQueue, EventReader, Settings}; use criterion::{Criterion, black_box, criterion_main, criterion_group, BenchmarkId}; use std::time::{Duration, Instant}; use std::thread; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::pin::Pin; use rc_event_queue::{CleanupMode,...
let thread = Box::new(thread::spawn(move || { let mut local_sum0: usize = 0; loop{ let stop = readers_stop.load(Ordering::Acquire); let mut iter = reader.iter(); while let Some(i) = iter.next()...
+ Send + 'static + Clone { let mut total = Duration::ZERO; let readers_thread_count = 4; for _ in 0..iters { let mut event = Event::new(); let mut readers = Vec::new(); for _ in 0..readers_thread_count{ readers.push(EventReader::new(&mut event)); } ...
function_block-random_span
[ { "content": "/// We test high-contention read-write case.\n\nfn bench_event_read_write<F>(iters: u64, writer_fn: F) -> Duration\n\n where F: Fn(&ArcEvent, usize, usize) -> () + Send + 'static + Clone\n\n{\n\n let mut total = Duration::ZERO;\n\n\n\n let writers_thread_count = 2;\n\n let readers_thre...
Rust
eval/src/values/mod.rs
slowli/arithmetic-parser
3e01a6069ddea36740126c40386deea0b6dfaee7
use hashbrown::HashMap; use core::{ any::{type_name, Any}, fmt, }; use crate::{ alloc::{vec, Rc, String, Vec}, fns, }; use arithmetic_parser::{MaybeSpanned, StripCode}; mod env; mod function; mod ops; mod variable_map; pub use self::{ env::Environment, function::{CallContext, Function, Int...
use hashbrown::HashMap; use core::{ any::{type_name, Any}, fmt, }; use crate::{ alloc::{vec, Rc, String, Vec}, fns, }; use arithmetic_parser::{MaybeSpanned, StripCode}; mod env; mod function; mod ops; mod variable_map; pub use self::{ env::Environment, function::{CallContext, Function, Int...
his == other, _ => false, } } } impl<T: fmt::Display> fmt::Display for Value<'_, T> { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Prim(value) => fmt::Display::fmt(value, formatter), Self::Bool(true) => formatter.write...
other, (Self::Tuple(this), Self::Tuple(other)) => this == other, (Self::Object(this), Self::Object(other)) => this == other, (Self::Function(this), Self::Function(other)) => this.is_same_function(other), (Self::Ref(this), Self::Ref(other)) => t
function_block-random_span
[ { "content": "/// Default implementation of [`VisitMut::visit_function_mut()`].\n\npub fn visit_function_mut<Prim, V>(visitor: &mut V, function: &mut Function<Prim>)\n\nwhere\n\n Prim: PrimitiveType,\n\n V: VisitMut<Prim> + ?Sized,\n\n{\n\n visitor.visit_tuple_mut(&mut function.args);\n\n visitor.vi...
Rust
starlark/src/syntax/validate.rs
creativemindplus/starlark-rust
4fc26687df9a975eeb26f6b3d6f995d188fd00ba
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://www.apache.org/lic...
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://www.apache.org/lic...
pub fn check_assign(codemap: &CodeMap, x: AstExpr) -> anyhow::Result<AstAssign> { Ok(Spanned { span: x.span, node: match x.node { Expr::Tuple(xs) | Expr::List(xs) => { Assign::Tuple(xs.into_try_map(|x| Self::check_assign(codemap, x))?) ...
pub fn check_def( name: AstString, parameters: Vec<AstParameter>, return_type: Option<Box<AstExpr>>, stmts: AstStmt, codemap: &CodeMap, ) -> anyhow::Result<Stmt> { check_parameters(&parameters, codemap)?; let name = name.into_map(|s| AssignIdentP(s, ())); ...
function_block-full_function
[ { "content": "fn require_return_expression(ret_type: &Option<Box<AstExpr>>) -> Option<Span> {\n\n match ret_type {\n\n None => None,\n\n Some(x) => match &***x {\n\n Expr::Identifier(x, _) if x.node == \"None\" => None,\n\n _ => Some(x.span),\n\n },\n\n }\n\n}\n\...
Rust
src/utils.rs
rustbunker/youki
2f3d8062ec006057e04b13c6697ebabf7cd5f9bd
use std::env; use std::ffi::CString; use std::fs; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::Context; use anyhow::{bail, Result}; use nix::unistd; pub trait PathBufExt { fn as_in_container(&self) -> Result<PathBuf>; fn join_absolute_path(&self, p: &Path) -> Res...
use std::env; use std::ffi::CString; use std::fs; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::Context; use anyhow::{bail, Result}; use nix::unistd; pub trait PathBufExt { fn as_in_container(&self) -> Result<PathBuf>; fn join_absolute_path(&self, p: &Path) -> Res...
.unwrap(), PathBuf::from("sample/a/b") ); } #[test] fn test_join_absolute_path_error() { assert_eq!( PathBuf::from("sample/a/") .join_absolute_path(&PathBuf::from("b/c")) .is_err(), true ); } ...
iner(&self) -> Result<PathBuf> { if self.is_relative() { bail!("Relative path cannot be converted to the path in the container.") } else { let path_string = self.to_string_lossy().into_owned(); Ok(PathBuf::from(path_string[1..].to_string())) } } fn jo...
random
[ { "content": "#[inline]\n\npub fn write_cgroup_file_str<P: AsRef<Path>>(path: P, data: &str) -> Result<()> {\n\n fs::OpenOptions::new()\n\n .create(false)\n\n .write(true)\n\n .truncate(false)\n\n .open(path.as_ref())\n\n .with_context(|| format!(\"failed to open {:?}\", pa...
Rust
cli/src/command/export/export.rs
bennyboer/worklog
bce3c3954c3a14cca7c029caf2641ec1f5af4478
use crate::command::command::Command; use crate::command::list; use cmd_args::{arg, option, Group}; use persistence::calc::event::EventType; use persistence::calc::WorkItem; use std::collections::HashMap; use std::fs; pub struct ExportCommand {} impl Command for ExportCommand { fn build(&self) -> Group { ...
use crate::command::command::Command; use crate::command::list; use cmd_args::{arg, option, Group}; use persistence::calc::event::EventType; use persistence::calc::WorkItem; use std::collections::HashMap; use std::fs; pub struct ExportCommand {} impl Command for ExportCommand { fn build(&self) -> Group { ...
::time::format_duration((total_work_time_ms / 1000) as u32) }; let start_time = shared::time::get_local_date_time(find_earliest_work_item(&items).created_timestamp()) .format("%H:%M") .to_string(); let end_time = shared::time::get_local_date_time(find_latest_work_item...
) -> Option<Vec<&str>> { None } fn name(&self) -> &str { "export" } } fn execute(args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) { let export_type = args[0].str().unwrap(); if export_type.trim().to_lowercase() == "markdown" { export_to_markdown( ...
random
[ { "content": "/// Execute the log command.\n\nfn execute(args: &Vec<arg::Value>, _options: &HashMap<&str, option::Value>) {\n\n let description = args[0].str().unwrap();\n\n let tags_str = args[1].str().unwrap();\n\n let time_taken_str = args[2].str().unwrap();\n\n\n\n let tags: Vec<String> = tags_s...
Rust
src/client/general.rs
stuck-overflow/obws
6b71ed39bfacb66bbb3050b300e97ac2be2efa44
use serde::Serialize; use super::Client; use crate::requests::{KeyModifier, Projector, ProjectorInternal, QtGeometry, RequestType}; use crate::responses; use crate::{Error, Result}; pub struct General<'a> { pub(super) client: &'a Client, } impl<'a> General<'a> { pub async fn get_version(&self) -> Result...
use serde::Serialize; use super::Client; use crate::requests::{KeyModifier, Projector, ProjectorInternal, QtGeometry, RequestType}; use crate::responses; use crate::{Error, Result}; pub struct General<'a> { pub(super) client: &'a Client, } impl<'a> General<'a> { pub async fn get_version(&self) -> Result...
pub async fn broadcast_custom_message<T>(&self, realm: &str, data: &T) -> Result<()> where T: Serialize, { self.client .send_message(RequestType::BroadcastCustomMessage { realm, data: &serde_json::to_value(data).map_err(Error:...
pub async fn get_stats(&self) -> Result<responses::ObsStats> { self.client .send_message::<responses::Stats>(RequestType::GetStats) .await .map(|s| s.stats) }
function_block-full_function
[ { "content": "pub fn duration_millis<'de, D>(deserializer: D) -> Result<Duration, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n deserializer.deserialize_i64(DurationMillisVisitor)\n\n}\n\n\n", "file_path": "src/de.rs", "rank": 0, "score": 109560.20084211772 }, { "content": "pub...
Rust
src/liboak/back/context.rs
ptal/oak
667c625096540600b6c6ac0943126ca092a9f80e
pub use back::continuation::*; use back::name_factory::*; use back::compiler::ExprCompilerFn; use back::compiler::rtype::*; use back::compiler::{recognizer_compiler, parser_compiler}; use back::compiler::value::*; use quote::quote; use syn::parse_quote; pub struct Context<'a> { grammar: &'a TGrammar, closures: ...
pub use back::continuation::*; use back::name_factory::*; use back::compiler::ExprCompilerFn; use back::compiler::rtype::*; use back::compiler::{recognizer_compiler, parser_compiler}; use back::compiler::value::*; use quote::quote; use syn::parse_quote; pub struct Context<'a> { grammar: &'a TGrammar, closures: ...
pub fn do_not_duplicate_success(&self) -> bool { self.num_combinators_compiled > 0 } pub fn success_as_closure(&mut self, continuation: Continuation) -> Continuation { if self.do_not_duplicate_success() { self.num_combinators_compiled = 0; let closure_name = self.name_factory.next_closure_n...
self.push_mut_ref_fv(result_var.clone(), value_ty); let result_value = tuple_value(self.free_variables()); let body = Continuation::new( value_constructor(result_var.clone(), result_value), parse_quote!(state.failure()) ) .compile_success(self, parser_compiler, expr_idx) ...
function_block-function_prefix_line
[ { "content": "pub fn recognizer_compiler(grammar: &TGrammar, idx: usize) -> Box<dyn CompileExpr> {\n\n match grammar.expr_by_index(idx) {\n\n StrLiteral(lit) => Box::new(StrLiteralCompiler::recognizer(lit)),\n\n CharacterClass(classes) => Box::new(CharacterClassCompiler::recognizer(classes)),\n\n AnyS...
Rust
dpx/src/dpx_dpxconf.rs
mulimoen/tectonic
bea4516e2c7b253bc92dbd0b744a233635db7b0b
/* This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks. Copyright (C) 2002-2016 by Jin-Hwan Cho and Shunsaku Hirata, the dvipdfmx project team. Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu> This program is free software; you can redistribute it and/or modify it un...
/* This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks. Copyright (C) 2002-2016 by Jin-Hwan Cho and Shunsaku Hirata, the dvipdfmx project team. Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu> This program is free software; you can redistribute it and/or modify it un...
.is_null() { if streq_ptr(ppformat, (*ppinfo).name) { break; } ppinfo = if !ppinfo.offset(1).is_null() && !(*ppinfo.offset(1)).name.is_null() { ppinfo.offset(1) } else { 0 as *const paper } } return if !ppinfo.is_null() ...
*const i8, pswidth: 595.276f64, psheight: 841.890f64, }; init }, { let mut init = paper { name: b"a3\x00" as *const u8 as *const i8, pswidth: 841.890f64, psheight: 1190.550f64, }; init }, { let mu...
random
[ { "content": "pub fn hex_to_bytes(text: &str, dest: &mut [u8]) -> Result<()> {\n\n let n = dest.len();\n\n let text_len = text.len();\n\n\n\n if text_len != 2 * n {\n\n return Err(ErrorKind::BadLength(2 * n, text_len).into());\n\n }\n\n\n\n for i in 0..n {\n\n dest[i] = u8::from_str...
Rust
src/nal/sei/buffering_period.rs
fkaa/h264-reader
24bc61f62599ee3d3fe4df7f725a00002ac8d484
use super::SeiCompletePayloadReader; use std::marker; use crate::nal::{sps, pps}; use crate::rbsp::RbspBitReader; use crate::Context; use crate::nal::sei::HeaderType; use crate::rbsp::RbspBitReaderError; use log::*; #[derive(Debug)] enum BufferingPeriodError { ReaderError(RbspBitReaderError), UndefinedSeqParam...
use super::SeiCompletePayloadReader; use std::marker; use crate::nal::{sps, pps}; use crate::rbsp::RbspBitReader; use crate::Context; use crate::nal::sei::HeaderType; use crate::rbsp::RbspBitReaderError; use log::*; #[derive(Debug)] enum BufferingPeriodError { ReaderError(RbspBitReaderError), UndefinedSeqParam...
} } #[cfg(test)] mod test { use hex_literal::hex; use super::*; #[test] fn parse() { let mut ctx = Context::default(); let sps_rbsp = hex!(" 4d 60 15 8d 8d 28 58 9d 08 00 00 0f a0 00 07 53 07 00 00 00 92 7c 00 00 12 4f 80 fb dc 18 00 00 ...
match BufferingPeriod::read(ctx, buf) { Err(e) => error!("Failure reading buffering_period: {:?}", e), Ok(buffering_period) => { info!("TODO: expose buffering_period {:#?}", buffering_period); } }
if_condition
[ { "content": "fn count_zero_bits<R: BitRead>(r: &mut R, name: &'static str) -> Result<u8, RbspBitReaderError> {\n\n let mut count = 0;\n\n while !r.read_bit()? {\n\n count += 1;\n\n if count > 31 {\n\n return Err(RbspBitReaderError::ExpGolombTooLarge(name));\n\n }\n\n }\...
Rust
src/main.rs
gfarrell/netctl-tray
58b7ad1684bc9f949839fb2dd08cd9ef2ad0bc74
#![feature(exclusive_range_pattern)] mod state; use notify_rust::{Notification, Timeout}; use qt_gui::QIcon; use qt_widgets::cpp_utils::{CppBox, MutPtr}; use qt_widgets::qt_core::{QString, QTimer, Slot}; use qt_widgets::{QActionGroup, QApplication, QMenu, QSystemTrayIcon, SlotOfActivationReason}; use state::{inotify_...
#![feature(exclusive_range_pattern)] mod state; use notify_rust::{Notification, Timeout}; use qt_gui::QIcon; use qt_widgets::cpp_utils::{CppBox, MutPtr}; use qt_widgets::qt_core::{QString, QTimer, Slot}; use qt_widgets::{QActionGroup, QApplication, QMenu, QSystemTrayIcon, SlotOfActivationReason}; use state::{inotify_...
fn profile_notification( state: &mut State, old_active_profile: Option<String>, ) -> Result<(), notify_rust::error::Error> { let text = match (&old_active_profile, &state.active_profile) { (None, Some(new)) => { format!("Profile <b>{}</b> started.", new) } ...
unsafe fn gen_profile_submenu( state_ptr: *mut State, mut profiles_submenu: MutPtr<QMenu>, profile_actions_group: &mut CppBox<QActionGroup>, click: &Slot, ) { profiles_submenu.clear(); for profile in &(*(*state_ptr).all_profiles.lock().unwrap()) { let mut item = profiles_subm...
function_block-full_function
[ { "content": "// Updates the netctl-tray state: ping, quality and current active profile\n\npub fn update_state(state: &mut State, args: &Opt) -> Result<(), std::io::Error> {\n\n // get the current active profile\n\n #[cfg(not(feature = \"auto\"))]\n\n let raw_profiles = Command::new(\"netctl\").arg(\"...
Rust
examples/rpg_engine/src/character.rs
arn-the-long-beard/ntnu_rust_lecture
1c7d6aba84e9e5ea99f18a5e46a11a674a08aa34
use crate::dice::SkillDice; use crate::item::Weapon; use crate::item::*; use crate::stuff::{Stuff, StuffConfig}; use colored::*; #[derive(Clone)] pub struct Character { name: String, health: f32, max_health: f32, stuff: Stuff, } #[allow(unused)] impl Character { pub fn name(&self) -> &str { ...
use crate::dice::SkillDice; use crate::item::Weapon; use crate::item::*; use crate::stuff::{Stuff, StuffConfig}; use colored::*; #[derive(Clone)] pub struct Character { name: String, health: f32, max_health: f32, stuff: Stuff, } #[allow(unused)] impl Character { pub fn name(&self) -> &str { ...
fn update_health_from_taken_damage(&mut self, damages: &RawDamages) { self.health -= *damages; if self.health < 0.0 { self.health = 0.0 } } #[deprecated] pub fn get_attacked_by(&mut self, damages: RawDamages, attack_dice: u8, def_dice: Option<u8>) { ...
elf, raw_damages: RawDamages) -> RawDamages { let mut damage_taken = raw_damages - self.get_armor(); if damage_taken < 0.0 { damage_taken = raw_damages * 0.1; } self.update_health_from_taken_damage(&damage_taken); damage_taken }
function_block-function_prefixed
[ { "content": "pub fn roll_dice(actor: &str, dices: &str, action: &str) -> i64 {\n\n let result = Roller::new(&format!(\"{} : {} \", dices, action))\n\n .unwrap()\n\n .roll()\n\n .unwrap();\n\n println!(\n\n \"{} rolls {} for {} \",\n\n actor.bold(),\n\n dices.unde...
Rust
src/bin/roughenough-kms.rs
lachesis/roughenough
a5e29a47646cc57bdd8e3603818cc9bd46f81bfc
#[macro_use] extern crate log; use clap::{App, Arg}; use data_encoding::{Encoding, HEXLOWER_PERMISSIVE}; use log::LevelFilter; use simple_logger::SimpleLogger; #[allow(unused_imports)] use roughenough::kms::{EnvelopeEncryption, KmsProvider}; use roughenough::roughenough_version; const HEX: Encoding = HEXLOWER_PERM...
#[macro_use] extern crate log; use clap::{App, Arg}; use data_encoding::{Encoding, HEXLOWER_PERMISSIVE}; use log::LevelFilter; use simple_logger::SimpleLogger; #[allow(unused_imports)] use roughenough::kms::{EnvelopeEncryption, KmsProvider}; use roughenough::roughenough_version; const HEX: Encoding = HEXLOWER_PERM...
let kms_key = matches.value_of("KEY_ID").expect("Invalid KMS key id"); if matches.is_present("SEED") { let hex_seed = matches.value_of("SEED").expect("Invalid seed value"); encrypt_seed(kms_key, hex_seed); } else if matches.is_present("DECRYPT") { let hex_blob = matches.value_of("...
let matches = App::new("roughenough-kms") .version(roughenough_version().as_ref()) .long_about("Encrypt and decrypt Roughenough long-term server seeds using a KMS") .arg( Arg::with_name("KEY_ID") .short("k") .long("kms-key") .takes_valu...
assignment_statement
[ { "content": "/// Factory function to create a `ServerConfig` _trait object_ based on the value\n\n/// of the provided `arg`.\n\n///\n\n/// * `ENV` will return an [`EnvironmentConfig`](struct.EnvironmentConfig.html)\n\n/// * any other value returns a [`FileConfig`](struct.FileConfig.html)\n\n///\n\npub fn m...
Rust
src/read/elf/hash.rs
sunfishcode/object
aaf312e51fc6e4511e19a32c05d4b2ddf248b5b6
use core::mem; use crate::elf; use crate::read::{ReadError, ReadRef, Result}; use crate::{U32, U64}; use super::{FileHeader, Sym, SymbolTable, Version, VersionTable}; #[derive(Debug)] pub struct HashTable<'data, Elf: FileHeader> { buckets: &'data [U32<Elf::Endian>], chains: &'data [U32<Elf::Endian>], } impl...
use core::mem; use crate::elf; use crate::read::{ReadError, ReadRef, Result}; use crate::{U32, U64}; use super::{FileHeader, Sym, SymbolTable, Version, VersionTable}; #[derive(Debug)] pub struct HashTable<'data, Elf: FileHeader> { buckets: &'data [U32<Elf::Endian>], chains: &'data [U32<Elf::Endian>], } impl...
l); } } None } pub fn find<R: ReadRef<'data>>( &self, endian: Elf::Endian, name: &[u8], hash: u32, version: Option<&Version>, symbols: &SymbolTable<'data, Elf, R>, versions: &VersionTable<'data, Elf>, ) -> Option<(usi...
bucket { max_symbol = bucket; } } for value in self .values .get(max_symbol.checked_sub(self.symbol_base)? as usize..)? { max_symbol += 1; if value.get(endian) & 1 != 0 { return Some(max_symbo
function_block-random_span
[ { "content": "/// Calculate the GNU hash for a symbol name.\n\n///\n\n/// Used for `SHT_GNU_HASH`.\n\npub fn gnu_hash(name: &[u8]) -> u32 {\n\n let mut hash = 5381u32;\n\n for byte in name {\n\n hash = hash.wrapping_mul(33).wrapping_add(u32::from(*byte));\n\n }\n\n hash\n\n}\n\n\n\n// Motorol...
Rust
gstreamer/src/buffer_pool.rs
heftig/gstreamer-rs
03c3580c224a10c86e89b34380215a551e1f7bff
use BufferPool; use Structure; use glib; use glib::translate::{from_glib, from_glib_full, from_glib_none, ToGlib, ToGlibPtr, ToGlibPtrMut}; use glib::IsA; use ffi; use std::mem; use std::ops; use std::ptr; #[derive(Debug, PartialEq, Eq)] pub struct BufferPoolConfig(Structure); impl ops::Deref for BufferPoolConfi...
use BufferPool; use Structure; use glib; use glib::translate::{from_glib, from_glib_full, from_glib_none, ToGlib, ToGlibPtr, ToGlibPtrMut}; use glib::IsA; use ffi; use std::mem; use std::ops; use std::ptr; #[derive(Debug, PartialEq, Eq)] pub struct BufferPoolConfig(Structure); impl ops::Deref for BufferPoolConfi...
fn release_buffer(&self, buffer: ::Buffer) { unsafe { ffi::gst_buffer_pool_release_buffer(self.to_glib_none().0, buffer.into_ptr()); } } } #[cfg(test)] mod tests { use super::*; use prelude::*; #[test] fn test_pool() { ::init().unwrap(); let pool ...
fn acquire_buffer<'a, P: Into<Option<&'a BufferPoolAcquireParams>>>( &self, params: P, ) -> Result<::Buffer, ::FlowReturn> { let params = params.into(); let params_ptr = match params { Some(params) => &params.0 as *const _ as *mut _, None => ptr::null_mut(), ...
function_block-full_function
[ { "content": "pub fn type_find_helper<P: IsA<gst::Pad>>(src: &P, size: u64) -> Option<gst::Caps> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n from_glib_full(ffi::gst_type_find_helper(src.to_glib_none().0, size))\n\n }\n\n}\n\n\n", "file_path": "gstreamer-base/src/auto/functions....
Rust
src/io/obj.rs
cpheinrich/web-geo-viewer
e835b0667e57697e0b8005c08c9dcd36222811ee
/* Copyright 2020 Martin Buck 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, copy, modify, merge, publish, distribute, sublice...
/* Copyright 2020 Martin Buck 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, copy, modify, merge, publish, distribute, sublice...
} } } } Ok(()) } pub fn load_obj_points<IP, P, R>(read: &mut R, ip: &mut IP) -> ObjResult<()> where IP: IsPushable<P>, P: IsBuildable3D, R: BufRead, { let mut line_buffer = Vec::new(); let mut i_line = 0; while let Ok(line) = fetch_line(read, &mut line_buffer) ...
if let Some(d) = maybe_d { let face = Face3 { a: VId { val: a - 1 }, b: VId { val: c - 1 }, c: VId { val: d - 1 }, }; materi...
random
[ { "content": "/// Loads an IsMesh3D from the off file format\n\npub fn load_off_mesh<EM, P, R>(read: &mut R, mesh: &mut EM) -> OffResult<()>\n\nwhere\n\n EM: IsFaceEditableMesh<P, Face3> + IsVertexEditableMesh<P, Face3>,\n\n P: IsBuildable3D + Clone,\n\n R: BufRead,\n\n{\n\n let mut line_buffer = Ve...
Rust
step09/src/virtio.rs
13696652781/RSCV
f07db4aad2a5758ceae92fd41cd6e8520d117ace
use crate::bus::*; use crate::cpu::*; use crate::trap::*; pub const VIRTIO_IRQ: u64 = 1; const VRING_DESC_SIZE: u64 = 16; const DESC_NUM: u64 = 8; pub const VIRTIO_MAGIC: u64 = VIRTIO_BASE + 0x000; pub const VIRTIO_VERSION: u64 = VIRTIO_BASE + 0x004; pub const VIRTIO_DEVICE_ID: u64 = VIRTIO_BASE + 0x008; pub c...
use crate::bus::*; use crate::cpu::*; use crate::trap::*; pub const VIRTIO_IRQ: u64 = 1; const VRING_DESC_SIZE: u64 = 16; const DESC_NUM: u64 = 8; pub const VIRTIO_MAGIC: u64 = VIRTIO_BASE + 0x000; pub const VIRTIO_VERSION: u64 = VIRTIO_BASE + 0x004; pub const VIRTIO_DEVICE_ID: u64 = VIRTIO_BASE + 0x008; pub c...
} } impl Virtio { pub fn new(disk_image: Vec<u8>) -> Self { let mut disk = Vec::new(); disk.extend(disk_image.iter().cloned()); Self { id: 0, driver_features: 0, page_size: 0, queue_sel: 0, queue_num: 0, queu...
match size { 32 => Ok(self.store32(addr, value)), _ => Err(Exception::StoreAMOAccessFault), }
if_condition
[ { "content": "fn main() -> io::Result<()> {\n\n let args: Vec<String> = env::args().collect();\n\n\n\n if args.len() != 2 {\n\n panic!(\"Usage: rvemu-for-book <filename>\");\n\n }\n\n let mut file = File::open(&args[1])?;\n\n let mut binary = Vec::new();\n\n file.read_to_end(&mut binary...
Rust
descriptor/src/ranges.rs
Moxinilian/rendy
c521b6d97d8154042bcc2215c7d7906cc70d7282
use std::{ cmp::Ordering, ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign}, }; pub use gfx_hal::pso::{DescriptorRangeDesc, DescriptorSetLayoutBinding, DescriptorType}; const DESCPTOR_TYPES_COUNT: usize = 11; const DESCRIPTOR_TYPES: [DescriptorType; DESCPTOR_TYPES_COUNT] = [ DescriptorType::Sampler, ...
use std::{ cmp::Ordering, ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign}, }; pub use gfx_hal::pso::{DescriptorRangeDesc, DescriptorSetLayoutBinding, DescriptorType}; const DESCPTOR_TYPES_COUNT: usize = 11; const DESCRIPTOR_TYPES: [DescriptorType; DESCPTOR_TYPES_COUNT] = [ DescriptorType::Sampler, ...
; } } } } }
Some(DescriptorRangeDesc { count: self.counts[index] as usize, ty: DESCRIPTOR_TYPES[index], })
call_expression
[ { "content": "/// Trait for vertex attributes to implement\n\npub trait AsAttribute: Debug + PartialEq + PartialOrd + Copy + Send + Sync + 'static {\n\n /// Name of the attribute\n\n const NAME: &'static str;\n\n /// Attribute format.\n\n const FORMAT: Format;\n\n}\n\n\n\n/// A unique identifier for...
Rust
src/rust/storage/seg/src/ttl_buckets/ttl_bucket.rs
wandaitzuchen/pelikan
7421cdedbd5cf5c9814d244ae02eef5ec05904bf
use super::{SEGMENT_CLEAR, SEGMENT_EXPIRE}; use crate::*; use core::num::NonZeroU32; pub struct TtlBucket { head: Option<NonZeroU32>, tail: Option<NonZeroU32>, ttl: i32, nseg: i32, next_to_merge: Option<NonZeroU32>, _pad: [u8; 44], } impl TtlBucket { pub(super) fn new(ttl: i32) -> S...
use super::{SEGMENT_CLEAR, SEGMENT_EXPIRE}; use crate::*; use core::num::NonZeroU32; pub struct TtlBucket { head: Option<NonZeroU32>, tail: Option<NonZeroU32>, ttl: i32, nseg: i32, next_to_merge: Option<NonZeroU32>, _pad: [u8; 44], } impl TtlBucket { pub(super) fn new(ttl: i32) -> S...
ired += 1; } else { return expired; } } else { return expired; } } } pub(super) fn clear(&mut self, hashtable: &mut HashTable, segments: &mut Segments) -> usize { if self.head.is_none() { ...
self.head = None; self.tail = None; } let _ = segment.clear(hashtable, true); segments.push_free(seg_id); SEGMENT_EXPIRE.increment(); exp
random
[ { "content": "#[inline]\n\nfn copy_slice(dst: &mut [u8], src: &[u8]) -> usize {\n\n let n = cmp::min(dst.len(), src.len());\n\n dst[0..n].copy_from_slice(&src[0..n]);\n\n n\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use tempfile::NamedTempFile;\n\n\n\n fn kvs() -> Vec<(Strin...
Rust
oxide-7/src/video/mod.rs
coopersimon/oxide-7
538a2946fc32eef922749dcfe86490c1f09ca12e
mod ram; mod render; use std::sync::{ Arc, Mutex }; use bitflags::bitflags; use crate::{ common::Interrupt, constants::{ timing, screen }, }; use ram::VideoMem; pub use render::RenderTarget; type VRamRef = Arc<Mutex<VideoMem>>; bitflags! { #[derive(Default)] struct In...
mod ram; mod render; use std::sync::{ Arc, Mutex }; use bitflags::bitflags; use crate::{ common::Interrupt, constants::{ timing, screen }, }; use ram::VideoMem; pub use render::RenderTarget; type VRamRef = Arc<Mutex<VideoMem>>; bitflags! { #[derive(Default)] struct In...
= PPUState::VBlank; self.trigger_nmi() }, } } fn check_y_irq(&self) -> bool { let enabled = (self.int_enable & IntEnable::all_irq()) == IntEnable::ENABLE_IRQ_Y; enabled && (self.scanline == (self.v_timer as usize)) } fn chec...
ex::new(VideoMem::new())); PPU { state: PPUState::VBlank, mem: mem.clone(), cycle_count: 0, scanline: 0, int_enable: IntEnable::default(), status: PPUStatus::default(), nmi_flag: ...
random
[ { "content": "type CartMappingFn = fn(u8, u16) -> CartDevice;\n\n\n", "file_path": "oxide-7/src/mem/rom/mod.rs", "rank": 1, "score": 252137.86479187425 }, { "content": "fn map_hirom_bank(in_bank: u8, mapping: u8, lo_rom: bool, bank_addr: u16) -> u8 {\n\n let mapped_bank = map_bank(in_bank...
Rust
src/limit.rs
phip1611/spectrum-analyzer
8f8eb2cd91768222a7ede072c2c5353788238256
/* MIT License Copyright (c) 2021 Philipp Schuster 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, copy, modify, merge, publis...
/* MIT License Copyright (c) 2021 Philipp Schuster 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, copy, modify, merge, publis...
} #[derive(Debug)] pub enum FrequencyLimitError { ValueBelowMinimum(f32), ValueAboveNyquist(f32), InvalidRange(f32, f32), } #[cfg(test)] mod tests { use crate::FrequencyLimit; #[test] fn test_panic_min_below_minimum() { let _ = FrequencyLimit::Min(-1.0).verif...
Err(FrequencyLimitError::ValueBelowMinimum(*x)) } else if *x > max_detectable_frequency { Err(FrequencyLimitError::ValueAboveNyquist(*x)) } else { Ok(()) } } FrequencyLimit::Range(min, max) => { ...
function_block-function_prefix_line
[ { "content": "/// Creates a sine (sinus) wave function for a given frequency.\n\n/// Don't forget to scale up the value to the audio resolution.\n\n/// So far, amplitude is in interval `[-1; 1]`. The parameter\n\n/// of the returned function is the point in time in seconds.\n\n///\n\n/// * `frequency` is in Her...
Rust
predict/src/bin/build_driving_model.rs
ehsanul/brick
291c0783f3b062cf73887cb3581dd92342891165
extern crate bincode; extern crate flate2; extern crate predict; extern crate state; use bincode::serialize_into; use flate2::write::GzEncoder; use flate2::Compression; use predict::driving_model::{DrivingModel, PlayerTransformation, TransformationMap}; use predict::sample; use state::*; use std::collections::hash_map...
extern crate bincode; extern crate flate2; extern crate predict; extern crate state; use bincode::serialize_into; use flate2::write::GzEncoder; use flate2::Compression; use predict::driving_model::{DrivingModel, PlayerTransformation, TransformationMap}; use predict::sample; use state::*; use std::collections::hash_map...
let existing_delta = (existing_delta_x.powf(2.0) + existing_delta_y.powf(2.0)).sqrt(); let new_lv = sample[j].local_velocity(); let new_delta_x = (new_lv.x - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vx as f32).abs(); ...
let existing_delta_y = (existing_transformation.start_local_vy as f32 - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vy as f32) .abs();
assignment_statement
[ { "content": "fn percentile_value(numbers: &mut Vec<f32>, percentile: f32) -> f32 {\n\n numbers.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Less));\n\n let i = (percentile * numbers.len() as f32) as usize / 100;\n\n numbers[i]\n\n}\n\n\n", "file_path": "predict/tests/compare_with_sample_fil...
Rust
utoipa-gen/src/openapi.rs
juhaku/utoipa
070b00c13b41040e9605c62a0d7c3b5fcf04899c
use proc_macro2::Ident; use proc_macro_error::ResultExt; use syn::{ parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::{And, Comma}, Attribute, Error, ExprPath, GenericParam, Generics, Token, }; use proc_macro2::TokenStream; use quote::{format_ident, quote, quote_spanned, To...
use proc_macro2::Ident; use proc_macro_error::ResultExt; use syn::{ parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::{And, Comma}, Attribute, Error, ExprPath, GenericParam, Generics, Token, }; use proc_macro2::TokenStream; use quote::{format_ident, quote, quote_spanned, To...
} impl Parse for Component { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Component { ty: input.parse()?, generics: input.parse()?, }) } } #[cfg_attr(feature = "debug", derive(Debug))] struct Modifier { and: And, ident: Ident, } impl ToTokens for Mod...
fn has_lifetime_generics(&self) -> bool { self.generics .params .iter() .any(|generic| matches!(generic, GenericParam::Lifetime(_))) }
function_block-full_function
[]
Rust
src/main.rs
Drarig29/crypto-balance
b9f57923b4eb0c145ff7908c6d82425093225413
#[macro_use] extern crate rocket; extern crate chrono; extern crate dotenv; extern crate hex; extern crate hmac; extern crate mongodb; extern crate reqwest; extern crate serde; extern crate serde_json; extern crate sha2; mod aggregate; mod database; mod model; mod requests; mod utils; use chrono::{DateTime, Utc}; use...
#[macro_use] extern crate rocket; extern crate chrono; extern crate dotenv; extern crate hex; extern crate hmac; extern crate mongodb; extern crate reqwest; extern crate serde; extern crate serde_json; extern crate sha2; mod aggregate; mod database; mod model; mod requests; mod utils; use chrono::{DateTime, Utc}; use...
} #[get("/")] async fn index() -> Option<NamedFile> { NamedFile::open("static/index.html").await.ok() } #[get("/<file..>")] async fn files(file: PathBuf) -> Option<NamedFile> { NamedFile::open(Path::new("static/").join(file)).await.ok() } impl<'r> Responder<'r, 'r> for ApiResponse { fn respond_to(self, ...
Ok(Environment { app_password, binance_key, binance_secret, nomics_key, mongodb_host, mongodb_port, mongodb_username, mongodb_password, })
call_expression
[ { "content": "pub fn make_aggregate_query(start: DateTime<Utc>, end: DateTime<Utc>) -> Vec<bson::Document> {\n\n vec![\n\n doc! {\n\n \"$match\": {\n\n \"time\": {\n\n \"$gte\": start,\n\n \"$lte\": end\n\n }\n\n }\n\n },\n\n ...
Rust
src/tests/unit.rs
asomers/async-weighted-semaphore
2085026ab5f4a5b9b6bc8a724e7cdca75a212c32
use std::sync::{Arc, Barrier, Mutex}; use rand::{thread_rng, Rng, SeedableRng}; use std::sync::atomic::{AtomicIsize, AtomicBool}; use std::sync::atomic::Ordering::Relaxed; use std::task::{Context, Waker, Poll}; use std::future::Future; use std::{mem, thread, fmt}; use futures_test::task::{AwokenCount, new_count_wak...
use std::sync::{Arc, Barrier, Mutex}; use rand::{thread_rng, Rng, SeedableRng}; use std::sync::atomic::{AtomicIsize, AtomicBool}; use std::sync::atomic::Ordering::Relaxed; use std::task::{Context, Waker, Poll}; use std::future::Future; use std::{mem, thread, fmt}; use futures_test::task::{AwokenCount, new_count_wak...
#[test] fn test_parallel() { for i in 0..1000 { println!("iteration {:?}", i); test_parallel_impl(); } } fn test_parallel_impl() { let threads = 10; let semaphore = Arc::new(Semaphore::new(0)); let resource = Arc::new(AtomicIsize::new(0)); let barrier = Arc::new(Barrier::new(t...
ze, TestFuture>::new(); let mut rng = XorShiftRng::seed_from_u64(954360855); for _ in 0..100000 { if rng.gen_bool(0.1) && futures.len() < 5 { let amount = rng.gen_range(0, 10); let mut fut = TestFuture::new(&semaphore, amo...
function_block-function_prefixed
[ { "content": "struct SemMutex(Semaphore, UnsafeCell<usize>);\n\n\n\nunsafe impl Send for SemMutex {}\n\n\n\nunsafe impl Sync for SemMutex {}\n\n\n\nimpl Default for SemMutex {\n\n fn default() -> Self {\n\n SemMutex(Semaphore::new(1), UnsafeCell::new(0))\n\n }\n\n}\n\n\n\nimpl AtomicCounter for Sem...
Rust
src/indexer/mod.rs
sinhrks/brassfibre
86028eaf7271b2cd560ef064969ef1cbf47396d4
use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::hash::Hash; use std::iter::FromIterator; use std::slice; use std::vec; use nullvec::prelude::dev::algos::Indexing; use traits::{Slicer, IndexerIndex, Append}; mod convert; mod formatting; mod indexing; mod ops; mod ...
use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::hash::Hash; use std::iter::FromIterator; use std::slice; use std::vec; use nullvec::prelude::dev::algos::Indexing; use traits::{Slicer, IndexerIndex, Append}; mod convert; mod formatting; mod indexing; mod ops; mod ...
}
fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = U>, { let values: Vec<U> = iter.into_iter().collect(); Indexer::new(values) }
function_block-full_function
[ { "content": "/// Indexing methods for Indexer\n\npub trait IndexerIndex: Slicer {\n\n type Key;\n\n\n\n fn contains(&self, label: &Self::Key) -> bool;\n\n fn push(&mut self, label: Self::Key);\n\n fn get_loc(&self, label: &Self::Key) -> usize;\n\n fn get_locs(&self, labels: &[Self::Key]) -> Vec<...
Rust
src/overlay.rs
penumbra-zone/jellyfish-merkle
0f216e2dcd3219c58f1bc4a584c373416cbef5cd
use std::collections::HashMap; use anyhow::Result; use tracing::instrument; use crate::{ storage::{TreeReader, TreeWriter}, JellyfishMerkleTree, KeyHash, MissingRootError, OwnedValue, RootHash, Version, }; pub struct WriteOverlay<R> { reader: R, overlay: HashMap<KeyHash, OwnedValue>, version: Ver...
use std::collections::HashMap; use anyhow::Result; use tracing::instrument; use crate::{ storage::{TreeReader, TreeWriter}, JellyfishMerkleTree, KeyHash, MissingRootError, OwnedValue, RootHash, Version, }; pub struct WriteOverlay<R> { reader: R, overlay: HashMap<KeyHash, OwnedValue>, version: Ver...
} } #[instrument(name = "WriteOverlay::get_with_proof", skip(self, key))] pub async fn get_with_proof( &self, key: Vec<u8>, ) -> Result<(OwnedValue, ics23::ExistenceProof)> { if self.overlay.contains_key(&key.clone().into()) { return...
match self.tree().get(key, self.version).await { Ok(Some(value)) => { tracing::trace!(version = ?self.version, ?key, value = ?hex::encode(&value), "read from tree"); Ok(Some(value)) } Ok(None) => { tracing::trace...
if_condition
[ { "content": "/// Computes the key immediately after `key`.\n\npub fn plus_one(key: KeyHash) -> KeyHash {\n\n assert_ne!(key, KeyHash([0xff; 32]));\n\n\n\n let mut buf = key.0;\n\n for i in (0..32).rev() {\n\n if buf[i] == 255 {\n\n buf[i] = 0;\n\n } else {\n\n buf[i...
Rust
engine/src/types.rs
ivankabestwill/wirefilter
294292f53db18a5a3261118e93fad30bd9498b09
use lex::{expect, skip_space, Lex, LexResult, LexWith}; use rhs_types::{Bytes, IpRange, UninhabitedBool}; use serde::{Deserialize, Serialize}; use std::{ cmp::Ordering, fmt::{self, Debug, Formatter}, net::IpAddr, ops::RangeInclusive, }; use strict_partial_ord::StrictPartialOrd; fn lex_rhs_values<'i, T:...
use lex::{expect, skip_space, Lex, LexResult, LexWith}; use rhs_types::{Bytes, IpRange, UninhabitedBool}; use serde::{Deserialize, Serialize}; use std::{ cmp::Ordering, fmt::{self, Debug, Formatter}, net::IpAddr, ops::RangeInclusive, }; use strict_partial_ord::StrictPartialOrd; fn lex_rhs_values<'i, T:...
} } macro_rules! declare_types { ($(# $attrs:tt)* enum $name:ident $(<$lt:tt>)* { $($(# $vattrs:tt)* $variant:ident ( $ty:ty ) , )* }) => { $(# $attrs)* #[repr(u8)] pub enum $name $(<$lt>)* { $($(# $vattrs)* $variant($ty),)* } impl $(<$lt>)* GetType for $na...
if let Ok(rest) = expect(input, "}") { input = rest; return Ok((res, input)); } else { let (item, rest) = T::lex(input)?; res.push(item); input = rest; }
if_condition
[ { "content": "fn lex_digits(input: &str) -> LexResult<'_, &str> {\n\n // Lex any supported digits (up to radix 16) for better error locations.\n\n take_while(input, \"digit\", |c| c.is_digit(16))\n\n}\n\n\n", "file_path": "engine/src/rhs_types/int.rs", "rank": 0, "score": 184976.2941145299 }...
Rust
src/main.rs
jmccrae/simple-rust-web
88ac2fc0c0d5ca91c05d8b3543a9cc00a0e43bcd
extern crate clap; extern crate iron; extern crate handlebars; extern crate params; extern crate percent_encoding; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; mod renderer; mod templates; use clap::{Arg, App}; use handlebars::Handlebars; use iron::middleware::Handler; use iron...
extern crate clap; extern crate iron; extern crate handlebars; extern crate params; extern crate percent_encoding; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; mod renderer; mod templates; use clap::{Arg, App}; use handlebars::Handlebars; use iron::middleware::Handler; use iron...
static APP_TITLE : &'static str = "My App"; static VERSION : &'static str = "0.1"; static AUTHOR : &'static str = "John McCrae <john@mccr.ae>"; static ABOUT : &'static str = "Simple framework for making Rust Webapps"; struct TestTranslator; impl Translator<String> for TestTranslator { fn convert(&self,...
let mut server = Server::new(); init(&mut server); let iron = Iron::new(server); iron.http(("localhost",port)).unwrap(); }
function_block-function_prefix_line
[ { "content": "/// Render using `layout.hbs`\n\npub fn render_ok(hbars : &Handlebars, title : String, body : String) -> IronResult<Response> {\n\n Ok(Response::with(\n\n (iron::status::Ok,\n\n Header(ContentType::html()),\n\n hbars.render(\"layout\", &LayoutPage {\n\n ...