lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/scouty.rs
turboflakes/skipper
594a4b6212df530a64ddb4ad4d7a2ea296e0601c
use crate::config::{Config, CONFIG}; use crate::errors::ScoutyError; use crate::hooks::{ Hook, HOOK_DEMOCRACY_STARTED, HOOK_INIT, HOOK_NEW_ERA, HOOK_NEW_SESSION, HOOK_VALIDATOR_CHILLED, HOOK_VALIDATOR_OFFLINE, HOOK_VALIDATOR_SLASHED, HOOK_VALIDATOR_STARTS_ACTIVE_NEXT_ERA, HOOK_VALIDATOR_STARTS_INACTIVE_NE...
use crate::config::{Config, CONFIG}; use crate::errors::ScoutyError; use crate::hooks::{ Hook, HOOK_DEMOCRACY_STARTED, HOOK_INIT, HOOK_NEW_ERA, HOOK_NEW_SESSION, HOOK_VALIDATOR_CHILLED, HOOK_VALIDATOR_OFFLINE, HOOK_VALIDATOR_SLASHED, HOOK_VALIDATOR_STARTS_ACTIVE_NEXT_ERA, HOOK_VALIDATOR_STARTS_INACTIVE_NE...
} fn spawn_and_restart_subscription_on_error() { let t = task::spawn(async { let config = CONFIG.clone(); loop { let c: Scouty = Scouty::new().await; if let Err(e) = c.subscribe_on_chain_events().await { match e { ScoutyError::Subscriptio...
s(HOOK_VALIDATOR_SLASHED, &config.hook_validator_slashed_path); Hook::exists(HOOK_VALIDATOR_CHILLED, &config.hook_validator_chilled_path); Hook::exists(HOOK_VALIDATOR_OFFLINE, &config.hook_validator_offline_path); Hook::exists(HOOK_DEMOCRACY_STARTED, &config.hook_democracy_started_path); ...
function_block-function_prefixed
[ { "content": "#[derive(Deserialize, Debug)]\n\nstruct ErrorResponse {\n\n errcode: String,\n\n error: String,\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Matrix {\n\n pub client: reqwest::Client,\n\n access_token: Option<String>,\n\n chain: SupportedRuntime,\n\n private_room_id: String,\...
Rust
src/datetime.rs
taiki-e/bson-rust
d112672069e217b65633531e82944e54524b8ee4
use std::{ fmt::{self, Display}, time::{Duration, SystemTime}, }; use chrono::{LocalResult, TimeZone, Utc}; #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)] pub struct DateTime(i64); impl crate::DateTime { pub const MAX: Self = Self::from_millis(i64::MAX); pub const MIN: Self =...
use std::{ fmt::{self, Display}, time::{Duration, SystemTime}, }; use chrono::{LocalResult, TimeZone, Utc}; #[derive(Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)] pub struct DateTime(i64); impl crate::DateTime { pub const MAX: Self = Self::from_millis(i64::MAX); pub const MIN: Self =...
fn from(x: chrono::DateTime<T>) -> Self { Self::from_chrono(x) } }
Err(e) => { let millis = e.duration().as_millis(); if millis > i64::MAX as u128 { Self::MIN } else { Self::from_millis(-(millis as i64)) } } } } pub fn to_sy...
random
[ { "content": "#[test]\n\nfn from_impls() {\n\n let _guard = LOCK.run_concurrently();\n\n assert_eq!(Bson::from(1.5f32), Bson::Double(1.5));\n\n assert_eq!(Bson::from(2.25f64), Bson::Double(2.25));\n\n assert_eq!(Bson::from(\"data\"), Bson::String(String::from(\"data\")));\n\n assert_eq!(\n\n ...
Rust
what_web/src/request.rs
0x727/ObserverWard_0x727
fec0c366a55eb0e7675664c8d1266e4876fb5b87
use std::collections::HashMap; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use std::{fmt, process}; use cached::proc_macro::cached; use cached::SizedCache; use encoding_rs::{Encoding, UTF_8}; use md5::{Digest, Md5}; use mime::Mime; use regex::Regex; use reqwest::header::{HeaderMap, HeaderName, ...
use std::collections::HashMap; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use std::{fmt, process}; use cached::proc_macro::cached; use cached::SizedCache; use encoding_rs::{Encoding, UTF_8}; use md5::{Digest, Md5}; use mime::Mime; use regex::Regex; use reqwest::header::{HeaderMap, HeaderName, ...
}; }; } } } let favicon_url = base_url.join("/favicon.ico").unwrap(); if !link_tags.contains_key(&String::from(favicon_url.clone())) { if let Ok(favicon_md5) = get_favicon_hash(favicon_url.clone(), timeout, proxy).await { link_tags.insert(St...
rprint.request_headers.clone() { headers.insert( HeaderName::from_str(&k).unwrap(), HeaderValue::from_str(&v).unwrap(), ); } } if fingerprint.path != "/" { url.set_path(fingerprint.path.as_str()); } let client = reqwest::Client::bui...
random
[ { "content": "// 去重\n\npub fn strings_to_urls(domains: String) -> HashSet<String> {\n\n let target_list: Vec<String> = domains\n\n .split_terminator('\\n')\n\n .map(|s| s.to_string())\n\n .collect();\n\n HashSet::from_iter(target_list)\n\n}\n\n\n", "file_path": "what_web/src/lib.r...
Rust
src/jacobi/mod.rs
mxxo/gauss-quad
05807e184d259b4ca8d573e3568c986570c92535
use crate::DMatrixf64; use statrs::function::gamma::gamma; pub struct GaussJacobi { pub nodes: Vec<f64>, pub weights: Vec<f64>, } impl GaussJacobi { pub fn init(deg: usize, alpha: f64, beta: f64) -> GaussJacobi { let (nodes, weights) = GaussJacobi::nodes_and_weights(deg, alpha, beta); Gau...
use crate::DMatrixf64; use statrs::function::gamma::gamma; pub struct GaussJacobi { pub nodes: Vec<f64>, pub weights: Vec<f64>, } impl GaussJacobi { pub fn init(deg: usize, alpha: f64, beta: f64) -> GaussJacobi { let (nodes, weights) = GaussJacobi::nodes_and_weights(deg, alpha, beta); Gau...
assert_float_absolute_eq!(x_val, x[i]); } for (i, w_val) in w_should.iter().enumerate() { assert_float_absolute_eq!(w_val, w[i]); } } #[test] fn golub_welsch_5_alpha_0_beta_1() { let (x, w) = GaussJacobi::nodes_and_weights(5, 0.0, 1.0); println!("{:?}, {:...
igenvectors.row(0).map(|x| x.powi(2)) * scale_factor) .data .as_vec() .clone(); let mut both: Vec<_> = nodes.iter().zip(weights.iter()).collect(); both.sort_by(|a, b| a.0.partial_cmp(b.0).unwrap()); let (mut nodes, weights): (Vec<f64>, Vec<f64>) = both.iter()....
random
[ { "content": "use crate::hermite;\n\nuse crate::legendre;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::{GaussHermite, GaussLegendre, PI};\n\n\n\n #[test]\n\n fn integrate_linear_legendre() {\n\n let quad = GaussLegendre::init(5);\n\n let integral = quad.integrate...
Rust
fog/overseer/server/src/service.rs
iamalwaysuncomfortable/mobilecoin
9d7f88efe181ee498c07f62767ff56aed18a032c
use crate::{error::OverseerError, responses::GetIngestSummariesResponse, worker::OverseerWorker}; use mc_common::logger::{log, Logger}; use mc_fog_ingest_client::FogIngestGrpcClient; use mc_fog_recovery_db_iface::RecoveryDb; use mc_fog_types::ingest_common::IngestSummary; use mc_fog_uri::FogIngestUri; use prometheus:...
use crate::{error::OverseerError, responses::GetIngestSummariesResponse, worker::OverseerWorker}; use mc_common::logger::{log, Logger}; use mc_fog_ingest_client::FogIngestGrpcClient; use mc_fog_recovery_db_iface::RecoveryDb; use mc_fog_types::ingest_common::IngestSummary; use mc_fog_uri::FogIngestUri; use prometheus:...
; Ok(response_message.to_string()) } pub fn get_status(&self) -> Result<String, String> { let is_enabled: bool = self.is_enabled.load(Ordering::SeqCst); let response_message = match is_enabled { true => "Fog Overseer is enabled.", false => "Fog Overseer is ...
match was_enabled { true => "Fog Overseer was successfully disabled", false => "Fog Overseer was already disabled", }
if_condition
[ { "content": "struct DbFetcherThread<DB: RecoveryDb + Clone + Send + Sync + 'static> {\n\n db: DB,\n\n stop_requested: Arc<AtomicBool>,\n\n shared_state: Arc<Mutex<DbFetcherSharedState>>,\n\n block_tracker: BlockTracker,\n\n num_queued_records_limiter: Arc<(Mutex<usize>, Condvar)>,\n\n readine...
Rust
third_party/rust_crates/vendor/syn-0.15.26/src/buffer.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
#[cfg(all( not(all(target_arch = "wasm32", target_os = "unknown")), feature = "proc-macro" ))] use proc_macro as pm; use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; use std::marker::PhantomData; use std::ptr; use private; use Lifetime; enum Entry { ...
#[cfg(all( not(all(target_arch = "wasm32", target_os = "unknown")), feature = "proc-macro" ))] use proc_macro as pm; use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; use std::marker::PhantomData; use std::ptr; use private; use Lifetime; enum Entry { ...
}
pub fn close_span_of_group(cursor: Cursor) -> Span { match *cursor.entry() { Entry::Group(ref group, _) => group.span_close(), _ => cursor.span(), } }
function_block-full_function
[]
Rust
substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs
ndkazu/guessNumber-vs-Bot
6e756977ce849137c62edb0716df6926583da9b2
use crate::{ pallet::{parse::helper::get_doc_literals, Def}, COUNTER, }; use syn::{spanned::Spanned, Ident}; pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { let count = COUNTER.with(|counter| counter.borrow_mut().inc()); let (genesis_config, def_macro_ident, std_macro_ident) = if let...
use crate::{ pallet::{parse::helper::get_doc_literals, Def}, COUNTER, }; use syn::{spanned::Spanned, Ident}; pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { let count = COUNTER.with(|counter| counter.borrow_mut().inc()); let (genesis_config, def_macro_ident, std_macro_ident) = if let...
attrs.push(syn::parse_quote!( #[cfg(feature = "std")] )); attrs.push(syn::parse_quote!( #[derive(#frame_support::Serialize, #frame_support::Deserialize)] )); attrs.push(syn::parse_quote!( #[serde(rename_all = "camelCase")] )); attrs.push(syn::parse_quote!( #[serde(deny_unknown_fields)] )); attrs....
if get_doc_literals(&attrs).is_empty() { attrs.push(syn::parse_quote!( #[doc = r" Can be used to configure the [genesis state](https://substrate.dev/docs/en/knowledgebase/integrate/chain-spec#the-genesis-state) of this pallet. "] )); }
if_condition
[ { "content": "///\n\n/// * Generate default rust doc\n\npub fn expand_config(def: &mut Def) -> proc_macro2::TokenStream {\n\n\tlet config = &def.config;\n\n\tlet config_item = {\n\n\t\tlet item = &mut def.item.content.as_mut().expect(\"Checked by def parser\").1[config.index];\n\n\t\tif let syn::Item::Trait(ite...
Rust
client/src/handshake_manager.rs
TotalKrill/naia
8a7cfab42e3c605e07cd4ac21a820ee2dd255ca2
use std::time::Duration; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use naia_client_socket::Packet; pub use naia_shared::{ ConnectionConfig, ManagerType, Manifest, PacketReader, PacketType, ProtocolKindType, ProtocolType, ReplicateSafe, SequenceIterator, SharedConfig, StandardHeader, Timer, Tim...
use std::time::Duration; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use naia_client_socket::Packet; pub use naia_shared::{ ConnectionConfig, ManagerType, Manifest, PacketReader, PacketType, ProtocolKindType, ProtocolType, ReplicateSafe, SequenceIterator, SharedConfig, StandardHeader, Timer, Tim...
pub fn set_auth_message(&mut self, auth: P) { self.auth_message = Some(auth); } pub fn disconnect(&mut self) { self.pre_connection_timestamp = None; self.pre_connection_digest = None; self.connection_state = AwaitingChallengeResponse; } pub fn receive_packet( ...
nd_packet(&mut self, io: &mut Io) { if !self.handshake_timer.ringing() { return; } self.handshake_timer.reset(); match self.connection_state { ConnectionState::Connected => { } ConnectionState::AwaitingChallengeResponse =...
function_block-function_prefixed
[ { "content": "pub fn finish_connect(mut resource: ResMut<ClientResource>) {\n\n resource.connector.reset();\n\n}\n\n\n", "file_path": "adapters/bevy/client/src/systems.rs", "rank": 0, "score": 216650.65838096116 }, { "content": "pub fn sync(mut query: Query<(&Position, &mut Transform)>) {...
Rust
src/content/guard.rs
arn-the-long-beard/proto-seeder
37ca45e10681f10b97507f52806eac16a70e1586
use crate::{ content::{ get_scoped_field, module::templates::guard::_GUARD_TEMPLATE, view::{get_view_function, SeedView}, SeedRoute, }, parser::view::get_guard_attribute, }; use indexmap::map::IndexMap; use syn::{export::ToTokens, ItemEnum, ItemStruct}; #[derive(Debug, Clo...
use crate::{ content::{ get_scoped_field, module::templates::guard::_GUARD_TEMPLATE, view::{get_view_function, SeedView}, SeedRoute, }, parser::view::get_guard_attribute, }; use indexmap::map::IndexMap; use syn::{export::ToTokens, ItemEnum, ItemStruct}; #[derive(Debug, Clo...
}
let admin_guard = content.guards.get("admin_guard",).unwrap(); assert_eq!( admin_guard.routes[0], SeedRoute { name: "Admin".to_string(), nested: false, children: false, id_param: false, query: false, ...
function_block-function_prefix_line
[ { "content": "/// todo add Model extractor to match the scope\n\npub fn get_view_function(model_scope: &str, view: &str, model: &ItemStruct,) -> String {\n\n if model_scope.is_empty() {\n\n format!(\n\n \"fn {}(model : &Model) -> Node<Msg>{{div![\\\"{}\\\"]}}\",\n\n view, view\n\...
Rust
vg/src/font/ft_drivers.rs
Pctg-x8/peridot
bc8c53d4d7b8b70ff3676cf818ee52a4e8dd49b1
use freetype2::*; use freetype2::outline::*; use std::rc::Rc; use std::mem::MaybeUninit; use lyon_path::builder::{PathBuilder, FlatPathBuilder}; use std::cell::{Cell, RefCell, Ref}; use std::ffi::{CStr, CString}; pub struct UniqueSystem { ptr: FT_Library } #[derive(Clone)] pub struct System(Rc<UniqueSystem>); impl U...
use freetype2::*; use freetype2::outline::*; use std::rc::Rc; use std::mem::MaybeUninit; use lyon_path::builder::{PathBuilder, FlatPathBuilder}; use std::cell::{Cell, RefCell, Ref}; use std::ffi::{CStr, CString}; pub struct UniqueSystem { ptr: FT_Library } #[derive(Clone)] pub struct System(Rc<UniqueSystem>); impl U...
pub fn new_face_from_mem(&self, mem: &[u8], face_index: FT_Long) -> Result<Face, FT_Error> { let mut ptr = MaybeUninit::uninit(); unsafe { let r = FT_New_Memory_Face(self.0.ptr, mem.as_ptr(), mem.len() as _, face_index, ptr.as_mut_ptr()); if r != 0 { Err(r) } else { Ok(Face { _parent: self.clone(...
let mut ptr = MaybeUninit::uninit(); unsafe { FT_New_Face(self.0.ptr, path as _, face_index, ptr.as_mut_ptr()); Face { _parent: self.clone(), ptr: ptr.assume_init() } } }
function_block-function_prefix_line
[ { "content": "fn pathevent_to_point_mut(e: &mut PathEvent) -> &mut euclid::Point2D<f32> {\n\n match e {\n\n PathEvent::MoveTo(p) | PathEvent::LineTo(p) |\n\n PathEvent::QuadraticTo(_, p) | PathEvent::CubicTo(_, _, p) => p,\n\n PathEvent::Close => panic!(\"The destination point cannot be ...
Rust
src/language/language_type.tera.rs
MonliH/tokei
d083504bc8a4e7ad61f5c96f2fa52d837df45f57
use arbitrary::Arbitrary; #[derive(Deserialize, Serialize)] #[derive(Arbitrary, Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[non_exhaustive] #[allow(clippy::upper_case_acronyms)] pub enum LanguageType { {% for key, _ in languages -%} #[allow(missing_docs)] {{key}}, {% endfor %} } impl ...
use arbitrary::Arbitrary; #[derive(Deserialize, Serialize)] #[derive(Arbitrary, Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[non_exhaustive] #[allow(clippy::upper_case_acronyms)] pub enum LanguageType { {% for key, _ in languages -%} #[allow(missing_docs)] {{key}}, {% endfor %} } impl ...
} pub fn from_file_extension(extension: &str) -> Option<Self> { match extension { {% for key, value in languages -%} {%- if value.extensions -%} {%- for item in value.extensions %}| "{{item}}" {% endfor %}=> ...
match fsutils::get_extension(&entry) { Some(extension) => LanguageType::from_file_extension(extension.as_str()), None => LanguageType::from_shebang(&entry), }
if_condition
[]
Rust
compiler/rustc_serialize/src/leb128.rs
mbc-git/rust
2c7bc5e33c25e29058cbafefe680da8d5e9220e9
#![macro_use] macro_rules! max_leb128_len { ($int_ty:ty) => { (std::mem::size_of::<$int_ty>() * 8 + 6) / 7 }; } pub const fn max_leb128_len() -> usize { max_leb128_len!(u128) } macro_rules! impl_write_unsigned_leb128 { ($fn_name:ident, $int_ty:ty) => { #[inline] pub f...
#![macro_use] macro_rules! max_leb128_len { ($int_ty:ty) => { (std::mem::size_of::<$int_ty>() * 8 + 6) / 7 }; } pub const fn max_leb128_len() -> usize { max_leb128_len!(u128) } macro_rules! impl_write_unsigned_leb128 { ($fn_name:ident, $int_ty:ty) => { #[inline] pub f...
result, position) } }; } impl_read_signed_leb128!(read_i16_leb128, i16); impl_read_signed_leb128!(read_i32_leb128, i32); impl_read_signed_leb128!(read_i64_leb128, i64); impl_read_signed_leb128!(read_i128_leb128, i128); impl_read_signed_leb128!(read_isize_leb128, isize);
u8] { let mut i = 0; loop { let mut byte = (value as u8) & 0x7f; value >>= 7; let more = !(((value == 0) && ((byte & 0x40) == 0)) || ((value == -1) && ((byte & 0x40) != 0))); if more { byte ...
random
[]
Rust
teams/04-NFTMart/src/substrate/primitives/npos-elections/src/mock.rs
btspoony/hackathon-2021-spring
1d11e46c207a78526415f91c63df25e6ae12bb0b
#![cfg(test)] use crate::*; use sp_arithmetic::{ traits::{One, SaturatedConversion, Zero}, PerThing, }; use sp_runtime::assert_eq_error_rate; use sp_std::collections::btree_map::BTreeMap; #[derive(Default, Debug)] pub(crate) struct _Candidate<A> { who: A, score: f64, approval_stake: f64, elected: bool, } #[d...
#![cfg(test)] use crate::*; use sp_arithmetic::{ traits::{One, SaturatedConversion, Zero}, PerThing, }; use sp_runtime::assert_eq_error_rate; use sp_std::collections::btree_map::BTreeMap; #[derive(Default, Debug)] pub(crate) struct _Candidate<A> { who: A, score: f64, approval_stake: f64, elected: bool, } #[d...
_stake; difference = difference + budget - stake_used; if difference < tolerance { return difference; } } else { difference = budget; } elected_edges.iter_mut().for_each(|e| { if let Some(support) = support_map.get_mut(&e.0) { support.total = support.total - e.1; support.others.retain(|i_suppor...
> 0.0) .filter_map(|e| support_map.get(&e.0)) .map(|e| e.total) .collect::<Vec<f64>>(); let mut difference; if backing_backed_stake.len() > 0 { let max_stake = backing_backed_stake .iter() .max_by(|x, y| x.partial_cmp(&y).unwrap_or(sp_std::cmp::Ordering::Equal)) .expect("vector with positive length...
random
[ { "content": "fn iteration(mut candidate_count: usize, mut voter_count: usize, seed: u64) {\n\n\tlet rng = rand::rngs::SmallRng::seed_from_u64(seed);\n\n\tcandidate_count = to_range(candidate_count, MIN_CANDIDATES, MAX_CANDIDATES);\n\n\tvoter_count = to_range(voter_count, MIN_VOTERS, MAX_VOTERS);\n\n\n\n\tlet (...
Rust
src/security/kms/src/crypto_provider/optee_provider/boringssl_wrapper.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use boringssl_sys::{ BN_bin2bn, BN_bn2bin, BN_dup, BN_free, BN_new, BN_num_bytes, CBB_cleanup, CBB_finish, CBB_init, CBS_init, EC_GROUP_new_by_curve_name, EC_KEY_free, EC_KEY_get0_group, EC_KEY_get0_private_key, EC_KEY_get0_public_key, EC_KEY_new_by_curve_name, EC_KEY_parse_private_key, EC_KEY_set_pub...
use boringssl_sys::{ BN_bin2bn, BN_bn2bin, BN_dup, BN_free, BN_new, BN_num_bytes, CBB_cleanup, CBB_finish, CBB_init, CBS_init, EC_GROUP_new_by_curve_name, EC_KEY_free, EC_KEY_get0_group, EC_KEY_get0_private_key, EC_KEY_get0_public_key, EC_KEY_new_by_curve_name, EC_KEY_parse_private_key, EC_KEY_set_pub...
pub fn marshal_public_key(&mut self) -> Result<Vec<u8>, &'static str> { let mut evp_pkey = EvpPkey::new().ok_or("Failed to initialize EvpPkey!")?; let result = unsafe { EVP_PKEY_set1_RSA(evp_pkey.get_mut_ptr(), self.rsa as *mut RSA) }; if result == 0 { return ...
ublic_exponent_bn = BigNum::parse(public_exponent).ok_or("Public exponent is not a valid BigNum!")?; let rsa = unsafe { RSA_new().as_mut().ok_or("Failed to initialize Rsa!") }?; let result = unsafe { RSA_set0_key( rsa as *mut RSA, ...
function_block-function_prefixed
[]
Rust
src/main.rs
not-fl3/squarebug
be410715fbb333b229465459754304eaa2a16ec2
use miniquad::*; mod vertices0; mod vertices1; mod vertices2; mod indices0; mod indices1; mod indices2; #[derive(Debug)] #[repr(C)] pub struct Vertex { pub pos: [f32; 2], pub uv: [f32; 2], pub color: [u8; 4], } pub struct Painter { pipeline: Pipeline, bindings: Bindings, } impl Painter { pu...
use miniquad::*; mod vertices0; mod vertices1; mod vertices2; mod indices0; mod indices1; mod indices2; #[derive(Debug)] #[repr(C)] pub struct Vertex { pub pos: [f32; 2], pub uv: [f32; 2], pub color: [u8; 4], } pub struct Painter { pipeline: Pipeline, bindings: Bindings, } impl Painter { pu...
} struct Stage { painter: Painter, } impl Stage { fn new(ctx: &mut Context) -> Self { let mut painter = Painter::new(ctx); painter.rebuild_egui_texture(ctx); Self { painter } } } impl EventHandler for Stage { fn update(&mut self, _ctx: &mut Context) {} fn draw(&mut self,...
fn paint_job(&mut self, ctx: &mut Context, vertices: &[Vertex], indices: &[u16]) { let screen_size_in_pixels = ctx.screen_size(); let pixels_per_point = ctx.dpi_scale(); let vertices_size_bytes = vertices.len() * std::mem::size_of::<Vertex>(); if self.bindings.vertex_buffers[0].size() <...
function_block-full_function
[ { "content": "pub static INDICES: &[u16] = &[2, 0, 4, 4, 0, 6, 6, 0, 8, 8, 0, 10, 10, 0, 12, 12, 0, 14, 14, 0, 16, 16, 0, 18, 18, 0, 20, 20, 0, 22, 22, 0, 24, 24, 0, 26, 26, 0, 28, 28, 0, 30, 0, 30, 31, 31, 1, 0, 2, 0, 1, 1, 3, 2, 4, 2, 3, 3, 5, 4, 6, 4, 5, 5, 7, 6, 8, 6, 7, 7, 9, 8, 10, 8, 9, 9, 11, 10, 12, 10...
Rust
src/command_buffer.rs
All8Up/hecs
e2055123165439e236843736effa8783b70dcbbb
use core::any::TypeId; use core::ptr::{self, NonNull}; use crate::alloc::alloc::{alloc, dealloc, Layout}; use crate::alloc::vec::Vec; use crate::archetype::TypeInfo; use crate::World; use crate::{align, DynamicBundle}; use crate::{Bundle, Entity}; pub struct CommandBuffer { entities: Vec<EntityIndex>, remov...
use core::any::TypeId; use core::ptr::{self, NonNull}; use crate::alloc::alloc::{alloc, dealloc, Layout}; use crate::alloc::vec::Vec; use crate::archetype::TypeInfo; use crate::World; use crate::{align, DynamicBundle}; use crate::{Bundle, Entity}; pub struct CommandBuffer { entities: Vec<EntityIndex>, remov...
} struct ComponentInfo { ty: TypeInfo, offset: usize, } struct EntityIndex { entity: Option<Entity>, first_component: usize, } struct RemovedComps { remove: fn(&mut World, Entity), entity: Entity, } #[cfg(test)] mod tests { use super::*; #[test] fn populate_archetypes...
unsafe fn put(self, mut f: impl FnMut(*mut u8, TypeInfo)) { for info in self .cmd .components .drain(self.cmd.entities[self.index].first_component..) { let ptr = self.cmd.storage.as_ptr().add(info.offset); f(ptr, info.ty); } }
function_block-full_function
[ { "content": "/// Types that can be components, implemented automatically for all `Send + Sync + 'static` types\n\n///\n\n/// This is just a convenient shorthand for `Send + Sync + 'static`, and never needs to be\n\n/// implemented manually.\n\npub trait Component: Send + Sync + 'static {}\n\nimpl<T: Send + Syn...
Rust
crates/resolver/src/name_server/name_server_state.rs
makarchuk/trust-dns
98d84917aa74432fa33cd1daca20dc93072629ed
use std::cmp::Ordering; use std::sync::RwLock; use std::time::Instant; use proto::op::Edns; pub struct NameServerState(RwLock<NameServerStateInner>); #[derive(Debug)] enum NameServerStateInner { Init { send_edns: Option<Edns> }, Established { remote_edns: Option<Edns> }, ...
use std::cmp::Ordering; use std::sync::RwLock; use std::time::Instant; use proto::op::Edns; pub struct NameServerState(RwLock<NameServerStateInner>); #[derive(Debug)] enum NameServerStateInner { Init { send_edns: Option<Edns> }, Established { remote_edns: Option<Edns> }, ...
}
ng::Less); assert_eq!(init.cmp(&failed), Ordering::Greater); assert_eq!(established.cmp(&established), Ordering::Equal); assert_eq!(established.cmp(&failed), Ordering::Greater); assert_eq!(failed.cmp(&failed), Ordering::Equal); }
function_block-function_prefixed
[ { "content": "#[allow(dead_code)]\n\npub fn query_a<C: ClientHandle>(io_loop: &mut Runtime, client: &mut C) {\n\n let name = Name::from_str(\"www.example.com\").unwrap();\n\n let response = query_message(io_loop, client, name, RecordType::A);\n\n let record = &response.answers()[0];\n\n\n\n if let R...
Rust
contracts/treasury/dapps/vault/src/tests/integration_tests/instantiate.rs
White-Whale-Defi-Platform/contracts
c112d283057aff300a41499c687cfa88f5c4f7e3
use cosmwasm_std::{Addr, Coin, Decimal, Uint128}; use terra_multi_test::{App, ContractWrapper}; use crate::tests::integration_tests::common_integration::{mint_some_whale, store_token_code}; use terra_multi_test::Executor; use terraswap::asset::{Asset, AssetInfo}; use white_whale::dapps::vault::msg::{ExecuteMsg, Insta...
use cosmwasm_std::{Addr, Coin, Decimal, Uint128}; use terra_multi_test::{App, ContractWrapper}; use crate::tests::integration_tests::common_integration::{mint_some_whale, store_token_code}; use terra_multi_test::Executor; use terraswap::asset::{Asset, AssetInfo}; use white_whale::dapps::vault::msg::{ExecuteMsg, Insta...
e(), &MemoryMsg::ExecuteMsg::UpdateAssetAddresses { to_add: vec![ ( "whale".to_string(), AssetInfo::Token { contract_addr: base_contracts.whale.to_string(), }, ), ( ...
function_block-function_prefixed
[ { "content": "/// Instantiates the whale token contract\n\npub fn init_whale_contract(app: &mut App, initial_balances: Vec<Cw20Coin>) -> Addr {\n\n let owner = Addr::unchecked(TEST_CREATOR);\n\n\n\n // Instantiate WHALE Token Contract\n\n let cw20_token_contract = Box::new(ContractWrapper::new(\n\n ...
Rust
core/src/analyser/constants.rs
pruthvikar/tract
29eddfed22ee09f88580898c6eaa261957a42be9
use super::prelude::*; use TractResult; use model::OutletId; use std::collections::HashMap; use std::borrow::Borrow; use {Model, Node, Tensor}; #[derive(Debug)] pub enum Element { Node(usize), Edge(usize), } #[derive(Debug)] pub struct Component { pub elements: Vec<Element>, pub outputs: Vec<usize>, }...
use super::prelude::*; use TractResult; use model::OutletId; use std::collections::HashMap; use std::borrow::Borrow; use {Model, Node, Tensor}; #[derive(Debug)] pub enum Element { Node(usize), Edge(usize), } #[derive(Debug)] pub struct Component { pub elements: Vec<Element>, pub outputs: Vec<usize>, }...
pub fn propagate_constants<M: Borrow<Model>>(analyser: &mut Analyser<M>) -> TractResult<()> { let components: Vec<Component> = connected_components(analyser)?; info!("Detected {:?} connected components.", components.len()); let mut const_int_nodes = HashMap::new(); for component in components { ...
function_block-full_function
[ { "content": "pub fn all_precursors(model: &InferenceModel, id: usize) -> TractResult<BitSet> {\n\n let mut queue = vec![id];\n\n let mut visited = BitSet::with_capacity(model.nodes().len());\n\n visited.insert(id);\n\n while let Some(next) = queue.pop() {\n\n let node = model.node(next);\n\n...
Rust
services/mgmt/hybridcompute/src/package_2019_03/models.rs
fedonman/azure-sdk-for-rust
b100c451bc4fc6635f36efd99eaec7203ad6dfd9
#![doc = "generated by AutoRust"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorDetail { #[doc = "The error's code."] pub code: String, #[doc = "A human readable error message."] p...
#![doc = "generated by AutoRust"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorDetail { #[doc = "The error's code."] pub code: String, #[doc = "A human readable error message."] p...
} #[doc = "The Update Resource model definition."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct UpdateResource { #[doc = "Resource tags"] #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } impl UpdateResource { pub fn new(...
pub fn new(location: String) -> Self { Self { id: None, name: None, type_: None, location, tags: None, identity: None, } }
function_block-full_function
[]
Rust
crates/tools/src/prepare_scripts.rs
magicalne/godwoken
ebee4a430a3aee3af8d96752836745c4e1410125
use crate::{ types::{BuildScriptsResult, Programs}, utils, }; use anyhow::Result; use clap::arg_enum; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, fs, path::{Path, PathBuf}, }; use url::Url; pub const SCRIPT_BUILD_DIR_PATH: &str = "scripts-build/"; pub const SCRIPTS_DIR_PAT...
use crate::{ types::{BuildScriptsResult, Programs}, utils, }; use anyhow::Result; use clap::arg_enum; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, fs, path::{Path, PathBuf}, }; use url::Url; pub const SCRIPT_BUILD_DIR_PATH: &str = "scripts-build/"; pub const SCRIPTS_DIR_PAT...
} #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)] struct ReposUrl { godwoken_scripts: Url, godwoken_polyjuice: Url, clerkb: Url, } #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)] struct ScriptsInfo { #[serde(default)] source: PathBuf, #[serde(default)] alway...
fn default() -> Self { ScriptsBuildConfig { prebuild_image: PathBuf::from("nervos/godwoken-prebuilds:v0.6.7-rc1"), repos: ReposUrl { godwoken_scripts: Url::parse( "https://github.com/nervosnetwork/godwoken-scripts#v0.8.4-rc1", ) ...
function_block-full_function
[]
Rust
src/ast/id/subclasses.rs
althonos/fastobo
4057d4c92eb83273a9d166e1edef77be285ad5e8
use pest::iterators::Pair; use crate::ast::*; use crate::error::SyntaxError; use crate::parser::Cache; use crate::parser::FromPair; use crate::syntax::Rule; macro_rules! ident_subclass { (#[doc = $docstring:literal] $rule:expr => pub struct $name:ident) => { #[derive(Clone, Debug, PartialEq, Hash, Eq, Par...
use pest::iterators::Pair; use crate::ast::*; use crate::error::SyntaxError; use crate::parser::Cache; use crate::parser::FromPair; use crate::syntax::Rule; macro_rules! ident_subclass { (#[doc = $docstring:literal] $rule:expr => pub struct $name:ident) => { #[derive(Clone, Debug, PartialEq, Hash, Eq, Par...
e, ) -> Result<Self, SyntaxError> { Ident::from_pair_unchecked(pair.into_inner().next().unwrap(), cache).map(From::from) } } impl ::std::str::FromStr for $name { type Err = $crate::error::SyntaxError; fn from_str(s: &str) -> Result<Self, S...
fn from(id: Ident) -> Self { $name::new(id) } } impl From<UnprefixedIdent> for $name { fn from(id: UnprefixedIdent) -> Self { $name::new(Ident::from(id)) } } impl From<PrefixedIdent> for $name { fn from(i...
random
[ { "content": "#[inline]\n\npub fn to_writer<W: Write>(mut writer: W, doc: &OboDoc) -> Result<()> {\n\n write!(writer, \"{}\", doc.header())?;\n\n if !doc.header().is_empty() && !doc.entities().is_empty() {\n\n writeln!(writer)?;\n\n }\n\n\n\n let mut entities = doc.entities().iter().peekable(...
Rust
execution-engine/engine-tests/src/test/contract_api/transfer_purse_to_purse.rs
mpapierski/CasperLabs
1f8741f8ef28447f87f3844784b3c4291041df3b
use engine_shared::{stored_value::StoredValue, transform::Transform}; use types::{ApiError, Key, U512}; use engine_test_support::{ internal::{ ExecuteRequestBuilder, InMemoryWasmTestBuilder, DEFAULT_GENESIS_CONFIG, DEFAULT_PAYMENT, }, DEFAULT_ACCOUNT_ADDR, DEFAULT_ACCOUNT_INITIAL_BALANCE, }; const...
use engine_shared::{stored_value::StoredValue, transform::Transform}; use types::{ApiError, Key, U512}; use engine_test_support::{ internal::{ ExecuteRequestBuilder, InMemoryWasmTestBuilder, DEFAULT_GENESIS_CONFIG, DEFAULT_PAYMENT, }, DEFAULT_ACCOUNT
d be U512") } else { panic!("actual purse uref should be a Write of UInt512 type"); }; assert_eq!(purse_secondary_balance, U512::from(PURSE_TO_PURSE_AMOUNT)); assert_eq!( main_purse_balance, U512::from(DEFAULT_ACCOUNT_INITIAL_BALANCE) - *DEFAULT_PAYMENT - PURSE_...
_ADDR, DEFAULT_ACCOUNT_INITIAL_BALANCE, }; const CONTRACT_TRANSFER_PURSE_TO_PURSE: &str = "transfer_purse_to_purse.wasm"; const PURSE_TO_PURSE_AMOUNT: u64 = 42; #[ignore] #[test] fn should_run_purse_to_purse_transfer() { let source = "purse:main".to_string(); let target = "purse:secondary".to_string(); l...
random
[ { "content": "#[allow(clippy::implicit_hasher)]\n\npub fn get_account(transforms: &AdditiveMap<Key, Transform>, account: &Key) -> Option<Account> {\n\n transforms.get(account).and_then(|transform| {\n\n if let Transform::Write(StoredValue::Account(account)) = transform {\n\n Some(account.to...
Rust
src/volume/storage/zbox/transport/wasm.rs
mwatts/zbox
b967ddef0cd38bfbfaac8fdf2aed24d06a575810
use http::header::{HeaderMap, HeaderName, HeaderValue}; use http::status::StatusCode; use http::{Response as HttpResponse, Uri}; use std::io::{Cursor, Read}; use js_sys::Uint8Array; use web_sys::{XmlHttpRequest, XmlHttpRequestResponseType}; use super::{Response, Transport}; use error::{Error, Result}; const READY_ST...
use http::header::{HeaderMap, HeaderName, HeaderValue}; use http::status::StatusCode; use http::{Response as HttpResponse, Uri}; use std::io::{Cursor, Read}; use js_sys::Uint8Array; use web_sys::{XmlHttpRequest, XmlHttpRequestResponseType}; use super::{Response, Transport}; use error::{Error, Result}; const READY_ST...
pub struct WasmTransport { timeout: u32, } impl WasmTransport { pub fn new(timeout: u32) -> Result<Self> { Ok(WasmTransport { timeout: timeout * 1000, }) } fn create_xhr( &self, method: &str, uri: &Uri, headers: &HeaderMap, ) -> XmlHttp...
e); let headers_str = map_req_err!(xhr.get_all_response_headers())?; if !headers_str.is_empty() { headers_str.trim_end().split("\r\n").for_each(|ent| { let ent: Vec<&str> = ent.split(": ").collect(); let name = HeaderName::from_lowercase(ent[0].as_bytes()).unwrap(); ...
function_block-function_prefixed
[ { "content": "// parse uri\n\n// example: access_key@repo_id?cache_type=mem&cache_size=2mb[&base=path]\n\n// return: (\n\n// access_key: &str,\n\n// repo_id: &str,\n\n// cache_type: CacheType,\n\n// cache_size: usize,\n\n// base: PathBuf\n\n// )\n\nfn parse_uri(mut uri: &str) -> Result<(&str, &str, Ca...
Rust
src/graph/mod.rs
jameone/btree_graph
b438d61e6019b6c94a169647ee9a3d8d8d50ac51
mod api; mod test; use alloc::collections::{BTreeMap, BTreeSet}; use core::default::Default; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use crate::Error; pub use api::*; pub type Edge<V, E> = (E, (V, V)); #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Des...
mod api; mod test; use alloc::collections::{BTreeMap, BTreeSet}; use core::default::Default; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use crate::Error; pub use api::*; pub type Edge<V, E> = (E, (V, V)); #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Des...
}
fn connections(&self, v: V) -> Result<BTreeSet<&V>, Self::Error> { match self.vertices.get(&v) { Some(vertex) => Ok(vertex .iter() .map(|edge| -> &V { &self.edges.get(&edge).unwrap().1 }) .collect()), None => Err(Error::VertexDoesNotExist),...
function_block-full_function
[ { "content": "/// `RemoveEdge` removes the edge from the vertex x to the vertex y, if it is there. If the\n\n/// edge does not exist, an error will be raised.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use btree_graph::{BTreeGraph, AddVertex, AddEdge, Edges, RemoveEdge, GetVertexValue};\n\n/// let mut gra...
Rust
bindings/seshat/src/database/connection.rs
stumptownlabs/beeper-android-seshat
2de21b9002f72ac083a143629e0ad3d806fd63ce
use std::ops::{Deref, DerefMut}; use std::path::PathBuf; use fs_extra::dir; use r2d2::PooledConnection; use r2d2_sqlite::SqliteConnectionManager; use rusqlite::NO_PARAMS; use crate::{ config::LoadConfig, error::Result, events::{CrawlerCheckpoint, Profile, SerializedEvent}, Database, }; #[derive(Ser...
use std::ops::{Deref, DerefMut}; use std::path::PathBuf; use fs_extra::dir; use r2d2::PooledConnection; use r2d2_sqlite::SqliteConnectionManager; use rusqlite::NO_PARAMS; use crate::{ config::LoadConfig, error::Result, events::{CrawlerCheckpoint, Profile, SerializedEvent}, Database, }; #[derive(Ser...
})?; let mut checkpoints = Vec::new(); for row in rows { let checkpoint: CrawlerCheckpoint = row?; checkpoints.push(checkpoint); } Ok(checkpoints) } pub fn is_empty(&self) -> Result<bool> { let event_count: i64 = Database::get...
Ok(CrawlerCheckpoint { room_id: row.get(0)?, token: row.get(1)?, full_crawl: row.get(2)?, direction: row.get(3)?, })
call_expression
[ { "content": "pub fn recv_error_code() -> i32 {\n\n 10\n\n}\n\n\n\npub unsafe fn j_object_to_checkpoint_option(env: &JNIEnv, j_native_option_checkpoint: JObject) -> Option<CrawlerCheckpoint> {\n\n let has_new_checkpoint_j_value = env.call_method(j_native_option_checkpoint, \"hasSome\", \"()Z\", &[]).unwra...
Rust
benches/json-functions.rs
sdroege/cookie-factory
fdc7b9e0eabfd7908fd490ff57994e44fdfcf0ab
#![feature(test)] extern crate test; #[macro_use] extern crate cookie_factory; #[macro_use] extern crate maplit; use std::str; use std::collections::BTreeMap; use test::Bencher; use cookie_factory::*; #[derive(Clone, Debug, PartialEq)] pub enum JsonValue { Str(String), Boolean(bool), Num(f64), Array(Vec<Json...
#![feature(test)] extern crate test; #[macro_use] extern crate cookie_factory; #[macro_use] extern crate maplit; use std::str; use std::collections::BTreeMap; use test::Bencher; use cookie_factory::*; #[derive(Clone, Debug, PartialEq)] pub enum JsonValue { Str(String), Boolean(bool), Num(f64), Array(Vec<Json...
4).collect::<Vec<u8>>(); let pos = { let mut sr = gen_json_value(&value); let res = sr(&mut buffer).unwrap(); res.as_ptr() as usize }; let index = pos - buffer.as_ptr() as usize; println!("result:\n{}", str::from_utf8(&buffer[..index]).unwrap()); assert_eq!(str::from_utf8(&buffer[..index]).unwr...
[u8]> { move |out: &'a mut [u8]| { match g { JsonValue::Str(ref s) => gen_str(s)(out), JsonValue::Boolean(ref b) => gen_bool(*b)(out), JsonValue::Num(ref n) => gen_num(*n)(out), JsonValue::Array(ref v) => gen_array(v)(out), JsonValue::Object(ref o) => gen_object(o)(out), } } } ...
random
[ { "content": "#[inline(always)]\n\npub fn gen_bool<'a>(b: bool) -> impl SerializeFn<&'a mut [u8]> {\n\n if b {\n\n string(\"true\")\n\n } else {\n\n string(\"false\")\n\n }\n\n}\n\n\n", "file_path": "tests/json/mod.rs", "rank": 0, "score": 270283.2753512403 }, { "content": "#[inline...
Rust
src/remote_ref.rs
majecty/git-trim
fccb8e48f95a70bd680eed1b60547b025b2354d8
use anyhow::{Context, Result}; use git2::{BranchType, Config, Direction, Repository}; use log::*; use crate::config; use crate::config::ConfigValue; use crate::simple_glob::{expand_refspec, ExpansionSide}; pub fn get_fetch_remote_ref( repo: &Repository, config: &Config, branch: &str, ) -> Result<Option<St...
use anyhow::{Context, Result}; use git2::{BranchType, Config, Direction, Repository}; use log::*; use crate::config; use crate::config::ConfigValue; use crate::simple_glob::{expand_refspec, ExpansionSide}; pub fn get_fetch_remote_ref(
fn get_remote_ref( repo: &Repository, config: &Config, remote_name: &str, branch: &str, ) -> Result<Option<String>> { let remote = repo.find_remote(remote_name)?; let key = format!("branch.{}.merge", branch); let ref_on_remote: ConfigValue<String> = if let Some(ref_on_remote) = con...
repo: &Repository, config: &Config, branch: &str, ) -> Result<Option<String>> { let remote_name = config::get_remote(config, branch)?; get_remote_ref(repo, config, &remote_name, branch) }
function_block-function_prefix_line
[ { "content": "pub fn get_remote(config: &Config, branch: &str) -> Result<ConfigValue<String>> {\n\n Ok(get(config, &format!(\"branch.{}.remote\", branch))\n\n .with_default(&String::from(\"origin\"))\n\n .read()?\n\n .expect(\"has default\"))\n\n}\n", "file_path": "src/config.rs", ...
Rust
http/src/request/channel/stage/create_stage_instance.rs
tbnritzdoge/twilight
32cc07376ac8e1f116807d17b7707c9eafed9597
use crate::{ client::Client, request::{validate, Request}, response::{marker::EmptyBody, ResponseFuture}, routing::Route, }; use serde::Serialize; use std::{ error::Error, fmt::{Display, Formatter, Result as FmtResult}, }; use twilight_model::{channel::stage_instance::PrivacyLevel, id::ChannelId...
use crate::{ client::Client, request::{validate, Request}, response::{marker::EmptyBody, ResponseFuture}, routing::Route, }; use serde::Serialize; use std::{ error::Error, fmt::{Display, Formatter, Result as FmtResult}, }; use twilight_model::{channel::stage_instance::PrivacyLevel, id::ChannelId...
re::error(source), }; self.http.request(request.build()) } }
= Request::builder(&Route::CreateStageInstance); request = match request.json(&self.fields) { Ok(request) => request, Err(source) => return ResponseFutu
function_block-random_span
[ { "content": "pub fn stage_topic(value: impl AsRef<str>) -> bool {\n\n _stage_topic(value.as_ref())\n\n}\n\n\n", "file_path": "http/src/request/validate.rs", "rank": 0, "score": 424811.88222955196 }, { "content": "pub fn username(value: impl AsRef<str>) -> bool {\n\n // <https://discor...
Rust
src/tracing/field_line/basic.rs
lars-frogner/bifrost-rust
ae1b4e7adde92ec1c611259796ef593243f82a8d
use super::{ super::stepping::{Stepper3, StepperInstruction, SteppingSense}, FieldLinePath3, FieldLineSetProperties3, FieldLineTracer3, }; use crate::{ field::CachingScalarFieldProvider3, geometry::{ Dim3::{X, Y, Z}, Point3, Vec3, }, grid::Grid3, interpolation::Interpolator...
use super::{ super::stepping::{Stepper3, StepperInstruction, SteppingSense}, FieldLinePath3, FieldLineSetProperties3, FieldLineTracer3, }; use crate::{ field::CachingScalarFieldProvider3, geometry::{ Dim3::{X, Y, Z}, Point3, Vec3, }, grid::Grid3, interpolation::Interpolator...
} impl FieldLineTracingSense { pub fn same() -> Self { FieldLineTracingSense::One(SteppingSense::Same) } pub fn opposite() -> Self { FieldLineTracingSense::One(SteppingSense::Opposite) } } impl BasicFieldLineTracerConfig { pub const DEFAULT_TRACING_SENSE: FieldLineTracingSense = F...
w(); let varying_vector_values = HashMap::new(); fixed_scalar_values.insert( "x0".to_string(), paths_x.par_iter().map(|path_x| path_x[0]).collect(), ); fixed_scalar_values.insert( "y0".to_string(), paths_y.par_iter().map(|path_y| path_y[0]...
function_block-function_prefixed
[ { "content": "#[cfg(not(feature = \"pickle\"))]\n\npub fn run_slice_subcommand<G, P>(_: &ArgMatches, _: P, _: &Option<SnapNumInRange>, _: &[&str])\n\nwhere\n\n G: Grid3<fdt>,\n\n P: SnapshotProvider3<G>,\n\n{\n\n exit_with_error!(\n\n \"Error: Compile with pickle feature in order to write Pickle...
Rust
src/tests.rs
ParadoxSpiral/forecast-rs
09e0a2c5fda11ad6d57fcb830cc36abe258a0ee7
use super::{ForecastRequestBuilder, ForecastRequest, TimeMachineRequestBuilder, TimeMachineRequest, ExcludeBlock, Units, Lang, ExtendBy, FORECAST_URL, EXCLUDE, EXTEND, LANG, UNITS}; use serde::{Serialize, Deserialize}; use reqwest::Url; use std::vec::Vec; const LAT: f64 = 6.66; const LONG: f...
use super::{ForecastRequestBuilder, ForecastRequest, TimeMachineRequestBuilder, TimeMachineRequest, ExcludeBlock, Units, Lang, ExtendBy, FORECAST_URL, EXCLUDE, EXTEND, LANG, UNITS}; use serde::{Serialize, Deserialize}; use reqwest::Url; use std::vec::Vec; const LAT: f64 = 6.66; const LONG: f...
assert_eq!(expected, builder.build()); } #[test] fn test_norwegian_lang_serde() { #[derive(Serialize, Deserialize, PartialEq, Debug)] struct TestStruct { no: Lang, nb: Lang, en: Lang } let test_json = "{\"nb\":\"nb\",\"no\":\"no\",\"en\":\"en\"}"; let test_struct: T...
let expected = TimeMachineRequest::new( API_KEY, LAT, LONG, TIME, expected_url, vec![ ExcludeBlock::Hourly, ExcludeBlock::Daily, ExcludeBlock::Alerts ], Some(Lang::Arabic), Some(Units::Imperial) );
assignment_statement
[ { "content": "#[test]\n\n#[cfg(feature = \"integration\")]\n\nfn test_get_time_machine_request_full() {\n\n let api_key = env!(\"FORECAST_API_KEY\");\n\n\n\n let reqwest_client = Client::builder()\n\n .timeout(Duration::from_secs(TIMEOUT_SECS))\n\n .build()\n\n .unwrap();\n\n\n\n l...
Rust
ashpd-demo/src/application.rs
Cogitri/ashpd
d2e6253e4d3f1c295dbbf19ee12547d7cb4bb2b8
use std::{collections::HashMap, convert::TryFrom}; use ashpd::{ flatpak::{FlatpakProxy, SpawnFlags, SpawnOptions}, zbus, zvariant, }; use gio::ApplicationFlags; use glib::clone; use glib::WeakRef; use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::{gio, glib}; use gtk_macros::{action, stateful_action...
use std::{collections::HashMap, convert::TryFrom}; use ashpd::{ flatpak::{FlatpakProxy, SpawnFlags, SpawnOptions}, zbus, zvariant, }; use gio::ApplicationFlags; use glib::clone; use glib::WeakRef; use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::{gio, glib}; use gtk_macros::{action, stateful_action...
pub struct Params( String, Vec<zvariant::OwnedValue>, HashMap<String, zvariant::OwnedValue>, ); impl zvariant::Type for Params { fn signature() -> zvariant::Signature<'static> { zvariant::Signature::from_str_unchecked("(sava{sv})") ...
sult<()> { let bus = gio::bus_get_sync(gio::BusType::Session, gio::NONE_CANCELLABLE).unwrap(); gio::bus_watch_name_on_connection( &bus, config::APP_ID, gio::BusNameWatcherFlags::NONE, move |_bus, _, _| tracing::info!("Name owned"), move |_bus, ...
random
[ { "content": "pub fn is_empty(txt: gtk::glib::GString) -> Option<String> {\n\n if txt.is_empty() {\n\n None\n\n } else {\n\n Some(txt.to_string())\n\n }\n\n}\n\n\n", "file_path": "ashpd-demo/src/portals/mod.rs", "rank": 0, "score": 168682.52994785775 }, { "content": "/...
Rust
sdk/smithy-types/src/instant/format.rs
marcbowes/aws-sdk-rust
93c788ee7b4f10d6c7cbfd164e5131b4db4d6937
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ const NANOS_PER_SECOND: u32 = 1_000_000_000; #[non_exhaustive] #[derive(Debug, Eq, PartialEq)] pub enum DateParseError { Invalid(&'static str), IntParseError, } pub mod http_date { use std...
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ const NANOS_PER_SECOND: u32 = 1_000_000_000; #[non_exhaustive] #[derive(Debug, Eq, PartialEq)] pub enum DateParseError { Invalid(&'static str), IntParseError, } pub mod http_date { use std...
d(year, month, day); let datetime = NaiveDateTime::new(date, time); Ok(Instant::from_secs_and_nanos( datetime.timestamp(), datetime.timestamp_subsec_nanos(), )) } fn parse_slice<T>(ascii_slice: &[u8]) -> Result<T, DateParseError> where T: FromStr, ...
haped string")); } let nanos: u32 = match &s[25] { b'.' => { let fraction_slice = &s[26..s.len() - 4]; if fraction_slice.len() > 3 { return Err(DateParseError::Invalid("too much precisi...
function_block-random_span
[ { "content": "pub fn validate_query_string<B>(\n\n request: &Request<B>,\n\n expected_params: &[&str],\n\n) -> Result<(), ProtocolTestFailure> {\n\n let actual_params = extract_params(request.uri());\n\n for param in expected_params {\n\n if !actual_params.contains(param) {\n\n ret...
Rust
src/upload.rs
webern/coldsnap
b88291667eee1d2d4030209fdcaabc30f3ff0c66
/*! Upload Amazon EBS snapshots. */ use bytes::BytesMut; use futures::stream::{self, StreamExt}; use indicatif::ProgressBar; use rusoto_ebs::{CompleteSnapshotRequest, PutSnapshotBlockRequest, StartSnapshotRequest}; use rusoto_ebs::{Ebs, EbsClient}; use sha2::{Digest, Sha256}; use snafu::{ensure, OptionExt, ResultExt...
/*! Upload Amazon EBS snapshots. */ use bytes::BytesMut; use futures::stream::{self, StreamExt}; use indicatif::ProgressBar; use rusoto_ebs::{CompleteSnapshotRequest, PutSnapshotBlockRequest, StartSnapshotRequest}; use rusoto_ebs::{Ebs, EbsClient}; use sha2::{Digest, Sha256}; use snafu::{ensure, OptionExt, ResultExt...
to complete snapshot '{}': {}", snapshot_id, source))] CompleteSnapshot { snapshot_id: String, source: rusoto_core::RusotoError<rusoto_ebs::CompleteSnapshotError>, }, #[snafu(display("Failed to find snapshot ID"))] FindSnapshotId {}, #[snafu(display("Fa...
a_length = i64::try_from(data_length).with_context(|| error::ConvertNumber { what: "data length", number: data_length.to_string(), target: "i64", })?; let block_request = PutSnapshotBlockRequest { snapshot_id: snapshot_id.to_string(), block_in...
random
[ { "content": "/// Stores the context needed to download a snapshot block.\n\nstruct BlockContext {\n\n path: PathBuf,\n\n block_index: i64,\n\n block_token: String,\n\n block_size: i64,\n\n snapshot_id: String,\n\n block_errors: Arc<Mutex<BTreeMap<i64, Error>>>,\n\n progress_bar: Arc<Option...
Rust
src/builtins/systemio.rs
boustrophedon/extrasafe
c96e38c26a225597b58fb38c15dea4758eb17deb
use std::collections::{HashSet, HashMap}; use std::fs::File; use std::os::unix::io::AsRawFd; use libseccomp::*; use syscalls::Sysno; use crate::{RuleSet, Rule}; use super::YesReally; const IO_READ_SYSCALLS: &[Sysno] = &[Sysno::read, Sysno::readv, Sysno::preadv, Sysno::preadv2, Sysno::pread64, Sysno::lseek]; const ...
use std::collections::{HashSet, HashMap}; use std::fs::File; use std::os::unix::io::AsRawFd; use libseccomp::*; use syscalls::Sysno; use crate::{RuleSet, Rule}; use super::YesReally; const IO_READ_SYSCALLS: &[Sysno] = &[Sysno::read, Sysno::readv, Sysno::preadv, Sysno::preadv2, Sysno::pread64, Sysno::lseek]; const ...
#[must_use] pub fn allow_file_read(mut self, file: &File) -> SystemIO { let fd = file.as_raw_fd(); for &syscall in IO_READ_SYSCALLS { let rule = Rule::new(syscall) .and_condition(scmp_cmp!($arg0 == fd.try_into().expect("fd provided...
pub fn allow_stderr(mut self) -> SystemIO { let rule = Rule::new(Sysno::write) .and_condition(scmp_cmp!($arg0 == 2)); self.custom.entry(Sysno::write) .or_insert_with(Vec::new) .push(rule); self }
function_block-function_prefix_line
[ { "content": "/// A [`Rule`] labeled with the profile it originated from. Internal-only.\n\nstruct LabeledRule(pub &'static str, pub Rule);\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 144623.30350069335 }, { "content": "#[test]\n\nfn allow_only_specific_files() {\n\n // create ...
Rust
src/fs/mod.rs
Vaiz/wtool
2ac4872df3e97d594f3b7e63351e0f8fb1d6c036
use crate::common; use crate::fs::list_file_holders::ListFileHolders; mod list_file_holders; pub struct FileSystemDispatcher { m_disp: common::Dispatcher, } impl FileSystemDispatcher { fn new() -> FileSystemDispatcher { let mut fs = FileSystemDispatcher { m_disp: common::Dispatcher::new()...
use crate::common; use crate::fs::list_file_holders::ListFileHolders; mod list_file_holders; pub struct FileSystemDispatcher { m_disp: common::Dispatcher, } impl FileSystemDispatcher { fn new() -> FileSystemDispatcher { let mut fs = FileSystemDispatcher { m_disp: common::Dispatcher::new()...
h_back(std::path::PathBuf::from(path)); explorer.load_next()?; } else { explorer.m_files.push_back(FileInfo::new(path, attr)); } Ok(explorer) } fn eof(&self) -> bool { self.m_folders.is_empty() && self.m_files.is_empty() } fn next(&mut self) -> Re...
pp::new(Self::name()) .arg( clap::Arg::with_name("path") .required(true)); app.subcommand(sub_cmd) } fn run(&self, args: Option<&clap::ArgMatches>) -> Result<(), Box<dyn std::error::Error>> { let args = args.unwrap(); let path =...
random
[ { "content": "pub fn is_file_has_same_encoding(filepath: &str, e: &EncodingRef, bom_policy: &EBomPolicy) -> std::io::Result<bool> {\n\n let file_content = read_file(filepath);\n\n if file_content.is_err() {\n\n return Err(file_content.err().unwrap());\n\n }\n\n let file_content = file_content...
Rust
src/ioslave/iointctl.rs
jwinarske/rs-ambiq-apollo3
f262200039f7f4b9aeadcc70fc3e428f85a1ddd2
#[doc = "Reader of register IOINTCTL"] pub type R = crate::R<u32, super::IOINTCTL>; #[doc = "Writer for register IOINTCTL"] pub type W = crate::W<u32, super::IOINTCTL>; #[doc = "Register IOINTCTL `reset()`'s with value 0"] impl crate::ResetValue for super::IOINTCTL { type Type = u32; #[inline(always)] fn re...
#[doc = "Reader of register IOINTCTL"] pub type R = crate::R<u32, super::IOINTCTL>; #[doc = "Writer for register IOINTCTL"] pub type W = crate::W<u32, super::IOINTCTL>; #[doc = "Register IOINTCTL `reset()`'s with value 0"] impl crate::ResetValue for super::IOINTCTL { type Type = u32; #[inline(always)] fn re...
(((self.bits >> 24) & 0xff) as u8) } #[doc = "Bit 16 - This bit clears all of the IOINT interrupts when written with a 1."] #[inline(always)] pub fn iointclr(&self) -> IOINTCLR_R { IOINTCLR_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bits 8:15 - These bits read the IOINT interrupt...
.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `IOINT`"] pub type IOINT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IOINT`"] pub struct IOINT_W<'a> { w: &'a mut W, } impl<'a> IOINT_W<'a> { #[doc = r"Writes raw bits to the field"...
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/cmds/init.rs
davvid/garden
656121af4e903da86f8c644bee05cc8de8cfd6e2
use anyhow::Result; use yaml_rust::yaml::Hash as YamlHash; use yaml_rust::yaml::Yaml; use super::super::cmd; use super::super::config; use super::super::errors; use super::super::model; use super::super::path; struct InitOptions { pub dirname: std::path::PathBuf, pub filename: String, pub force: bool, ...
use anyhow::Result; use yaml_rust::yaml::Hash as YamlHash; use yaml_rust::yaml::Yaml; use super::super::cmd; use super::super::config; use super::super::errors; use super::super::model; use super::super::path; struct InitOptions { pub dirname: std::path::PathBuf, pub filename: String, pub force: bool, ...
let exists = config_path.exists(); let mut doc; if exists { doc = config::reader::read_yaml(&config_path)?; } else { doc = config::reader::empty_doc(); } { if let Yaml::Hash(ref mut doc_hash) = doc { let garden_key = Yaml::String("garden".in...
if !parent.exists() { if let Err(err) = std::fs::create_dir_all(&parent) { let error_message = format!("unable to create {:?}: {}", parent, err); return Err(errors::GardenError::OSError(error_message).into()); } }
if_condition
[ { "content": "/// Execute a command over every tree in the evaluated tree query.\n\npub fn inspect(config: &mut model::Configuration, verbose: bool, queries: &[String]) -> Result<()> {\n\n for query in queries {\n\n // Resolve the tree query into a vector of tree contexts.\n\n let contexts = qu...
Rust
lobsters/src/client.rs
xfbs/lobsters
54599167849653f2265471ab624bd102f034745e
mod http_client; use std::fs::{self, DirBuilder, File}; use std::io; use std::io::BufReader; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use cookie_store::CookieStore; use directories::ProjectDirs; use futures::{Future, IntoFuture, Stream}; use kuchiki::traits::TendrilSink; use log::debug; use reqwest::hea...
mod http_client; use std::fs::{self, DirBuilder, File}; use std::io; use std::io::BufReader; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use cookie_store::CookieStore; use directories::ProjectDirs; use futures::{Future, IntoFuture, Stream}; use kuchiki::traits::TendrilSink; use log::debug; use reqwest::hea...
pub fn base_url(&self) -> &Url { self.http.base_url() } fn extract_csrf_token(res: Response) -> impl Future<Item = String, Error = Error> { res.into_body() .concat2() .map_err(Error::from) .and_then(|body| { std::str::from_utf8(&bod...
pub fn save_cookies(&self) -> Result<(), Error> { let cookie_store_path = cookie_store_path()?; let cookie_store_tmp_path = cookie_store_path.with_extension("tmp"); let config_dir = cookie_store_path.parent().ok_or_else(|| { Error::Io(io::Error::new( io::Err...
function_block-full_function
[ { "content": "fn login(rt: &mut Runtime, client: Client, _options: Login) -> CommandResult {\n\n let stdout = stdout();\n\n let mut stdout = stdout.lock();\n\n let stdin = stdin();\n\n let mut stdin = stdin.lock();\n\n\n\n stdout.write_all(b\"username: \")?;\n\n stdout.flush()?;\n\n\n\n let...
Rust
src/murmur/murmur3_128_64.rs
NGnius/rust-highhash
340d22fda169e3bb782dfd1c1f32905cd8259c07
use std::hash::{BuildHasher, Hasher}; #[derive(Default)] pub struct Murmur3Hasher128x64 { buffer: Vec<u8>, } impl Hasher for Murmur3Hasher128x64 { fn write(&mut self, bytes: &[u8]) { self.buffer.extend(bytes) } fn finish(&self) -> u64 { hash128_x64(&self.buffer) as u64 } } #[deri...
use std::hash::{BuildHasher, Hasher}; #[derive(Default)] pub struct Murmur3Hasher128x64 { buffer: Vec<u8>, } impl Hasher for Murmur3Hasher128x64 { fn write(&mut self, bytes: &[u8]) { self.buffer.extend(bytes) } fn finish(&self) -> u64 { hash128_x64(&self.buffer) as u64 } } #[deri...
[tail_num] as u64; k1 = k1.wrapping_mul(C1); k1 = k1.rotate_left(31); k1 = k1.wrapping_mul(C2); h1 ^= k1; } _ => {} } } h1 ^= data.len() as u64; h2 ^= data.len() as u64; h1 = h1.wrapping_add(h2); ...
h2 = h2.wrapping_add(h1); h2 = (h2.wrapping_mul(5)).wrapping_add(D2 as u64); } let tail_num = n_blocks * 16; let mut k1 = 0; let mut k2 = 0; for i in (1..=data.len() & 15).rev() { match i { 15 => k2 ^= (data[tail_num + 14] as u64) << 48, 14 => ...
random
[ { "content": "/// MurmurHash3 32-bit implementation of the 128-bit hashing algorithm.\n\n/// This version allows you to specify a seed.\n\npub fn hash128_with_seed<T: AsRef<[u8]>>(v: T, seed: u32) -> u128 {\n\n let data = v.as_ref();\n\n let n_blocks = data.len() / 16;\n\n\n\n const C1: u32 = 0x239b961...
Rust
src/content.rs
imp/easystring-rs
f52f1e436cbb9b34cb8fdf3d49966338e33c8ee2
use std::borrow::Cow; use std::fmt; use std::ffi::{CStr, CString, OsStr, OsString}; use std::ops::{Index, Range, RangeFull}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; #[derive(Clone, Debug)] pub enum Content { String(String), OsString(OsString), CString(CString), PathBuf(PathBuf...
use std::borrow::Cow; use std::fmt; use std::ffi::{CStr, CString, OsStr, OsString}; use std::ops::{Index, Range, RangeFull}; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; #[derive(Clone, Debug)] pub enum Content { String(String), OsString(OsString), CString(CString), PathBuf(PathBuf...
lf[..].as_bytes().index(index)) } } impl<T> From<T> for Content where T: ToContent<T> { fn from(s: T) -> Self { s.to_content() } } impl fmt::Display for Content { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad(&format!("{}", self)) } } impl PartialEq for Content ...
Content::CString(ref s) => s.as_bytes().len(), Content::PathBuf(ref p) => p.as_os_str().len(), } } pub fn is_empty(&self) -> bool { match *self { Content::String(ref s) => s.is_empty(), Content::OsString(ref s) => s.is_empty(), Content::CS...
random
[ { "content": "extern crate easystring;\n\n\n\n#[cfg(test)]\n\nmod content {\n\n mod index {\n\n use easystring::Content;\n\n\n\n #[test]\n\n fn range_full() {\n\n let content = Content::from(\"abcde\");\n\n assert_eq!(&content[..], \"abcde\");\n\n }\n\n\n\n ...
Rust
tornado/engine_api_dto/src/config.rs
ufoscout/tornado
5c9f711a243ca2c7833fc0dd4085646c3a95defb
use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; use std::iter::Sum; use std::ops::Add; use tornado_engine_matcher::config::filter::Filter; use tornado_engine_matcher::config::rule::{Operator, Rule}; use tornado_engine_matcher::config::{Defaultable, MatcherConfig}; use typescri...
use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; use std::iter::Sum; use std::ops::Add; use tornado_engine_matcher::config::filter::Filter; use tornado_engine_matcher::config::rule::{Operator, Rule}; use tornado_engine_matcher::config::{Defaultable, MatcherConfig}; use typescri...
} #[derive(Debug, PartialEq, Clone, Serialize, Deserialize, TypeScriptify)] #[serde(tag = "type")] pub enum ProcessingTreeNodeDetailsDto { Filter { name: String, description: String, active: bool, filter: Option<OperatorDto> }, Ruleset { name: String, rules: Vec<RuleDetailsDto> }, } impl From<&MatcherConfig>...
figDto::Filter { name: name.to_owned(), rules_count: matcher_config_node.get_all_rules_count(), children_count: matcher_config_node.get_direct_child_nodes_count(), description: filter.to_owned().description, }, MatcherConfig::Rules...
function_block-function_prefixed
[ { "content": "fn path_to_node_filter(filters: &mut HashMap<String, NodeFilter>, path: &[String]) {\n\n if path.is_empty() {\n\n return;\n\n }\n\n\n\n let is_last = path.len() == 1;\n\n let name = path[0].to_owned();\n\n\n\n if is_last {\n\n filters.insert(name, NodeFilter::AllChildr...
Rust
sync/src/verified_rpc_client.rs
LemonHX/starcoin
d87dbbd8d9b03a93d97075913d35a2c99f216222
use anyhow::{format_err, Result}; use logger::prelude::*; use network_api::peer_score::{InverseScore, Score}; use network_api::PeerSelector; use starcoin_accumulator::node::AccumulatorStoreType; use starcoin_accumulator::AccumulatorNode; use starcoin_crypto::hash::HashValue; use starcoin_network_rpc_api::{ gen_cl...
use anyhow::{format_err, Result}; use logger::prelude::*; use network_api::peer_score::{InverseScore, Score}; use network_api::PeerSelector; use starcoin_accumulator::node::AccumulatorStoreType; use starcoin_accumulator::AccumulatorNode; use starcoin_crypto::hash::HashValue; use starcoin_network_rpc_api::{ gen_cl...
pub async fn get_block_infos(&self, hashes: Vec<HashValue>) -> Result<Vec<Option<BlockInfo>>> { self.get_block_infos_from_peer(None, hashes).await } pub async fn get_block_infos_from_peer( &self, peer_id: Option<PeerId>, req: Vec<HashValue>, ) -> Result<Vec<Option<Bloc...
pub async fn get_bodies_by_hash( &self, req: Vec<HashValue>, ) -> Result<(Vec<Option<BlockBody>>, PeerId)> { let peer_id = self.select_a_peer()?; debug!("rpc select peer {}", &peer_id); let resp: Vec<Option<BlockBody>> = self .client .get_bodies_by_has...
function_block-function_prefix_line
[ { "content": "/// A generic service for providing time related operations (e.g., returning the current time and\n\n/// sleeping).\n\npub trait TimeService: Send + Sync + Debug {\n\n ///Adjust local time by on chain time.\n\n fn adjust(&self, value: GlobalTimeOnChain);\n\n /// Returns the current time s...
Rust
src/uriparams.rs
xsvutils/xsvutils
27acec48e5e1c5af05a3b4a872626e8cc853c3cc
use lazy_static::lazy_static; use memchr::memchr; use regex::Regex; use std::io; use std::io::BufRead; use std::io::Write; use std::iter; use structopt::*; use url; #[derive(StructOpt, Debug, Default)] #[structopt(rename_all = "kebab-case")] pub struct Opt { #[structopt(long)] names: Option<String>, #[str...
use lazy_static::lazy_static; use memchr::memchr; use regex::Regex; use std::io; use std::io::BufRead; use std::io::Write; use std::iter; use structopt::*; use url; #[derive(StructOpt, Debug, Default)] #[structopt(rename_all = "kebab-case")] pub struct Opt { #[structopt(long)] names: Option<String>, #[str...
} else { buff.push_str("\t"); } buff.push_str(s); } return buff; } fn name_list_a(url: &[u8]) -> String { let mut buff = String::new(); let mut first = true; for (k, v) in parse(url) { if !v.is_empty() { if first { first = false; ...
f_vec = vec![String::new(); names.len()]; for (k, v) in parse(url) { let k = RE.replace_all(k.as_ref(), ""); if let Some(ix) = names.iter().position(|&x| x == k) { let v = &escape(v.as_ref()); buff_vec[ix].push_str(v); buff_vec[ix].push_str(";"); } } ...
function_block-random_span
[ { "content": "/// 入力からTSVを読み取り、指定した列のみを出力する\n\npub fn run(opt: Opt, input: &mut impl BufRead, output: &mut impl Write) -> Result<(), io::Error> {\n\n // 表示する列のインデックス\n\n let target_col_idx = {\n\n let mut buff = String::new();\n\n let len = input.read_line(&mut buff)?;\n\n if len == 0...
Rust
tools/infrasys/src/keys.rs
likewu/bottlerocket
3a93dd301b7b09ddfaf9acc827543e27f84d804f
use async_trait::async_trait; use pubsys_config::{KMSKeyConfig, SigningKeyConfig}; use rusoto_cloudformation::{CloudFormation, CloudFormationClient, CreateStackInput}; use rusoto_core::Region; use snafu::{OptionExt, ResultExt}; use std::fs; use std::str::FromStr; use super::{error, shared, Result}; pub async fn creat...
use async_trait::async_trait; use pubsys_config::{KMSKeyConfig, SigningKeyConfig}; use rusoto_cloudformation::{CloudFormation, CloudFormationClient, CreateStackInput}; use rusoto_core::Region; use snafu::{OptionExt, ResultExt}; use std::fs; use std::str::FromStr; use super::{error, shared, Result}; pub async fn creat...
let stack_arn = stack_result .clone() .stack_id .context(error::ParseResponse { what: "stack_id", resource_name: &stack_name, })?; let output_array = shared::get_stack_outputs(&cfn_client, ...
let stack_result = cfn_client .create_stack(CreateStackInput { parameters: Some(vec![shared::create_parameter( "Alias".to_string(), self.key_alias .as_ref() .context(error::KeyConf...
assignment_statement
[ { "content": "/// Signs root with available_keys under root_keys (will have a different tuftool command depending on key type)\n\npub fn sign_root(signing_key_config: &SigningKeyConfig, filepath: &str) -> Result<()> {\n\n match signing_key_config {\n\n SigningKeyConfig::file { .. } => (),\n\n S...
Rust
client/consensus/manual-seal/src/rpc.rs
SHA888/PolkaScanner
328887f05dd4548e8aa56f5f3ea5181b0c88b7d8
pub use self::gen_client::Client as ManualSealClient; use futures::{ channel::{mpsc, oneshot}, FutureExt, SinkExt, TryFutureExt, }; use jsonrpc_core::Error; use jsonrpc_derive::rpc; use serde::{Deserialize, Serialize}; use sp_consensus::ImportedAux; use sp_runtime::Justification; type FutureResult<T> = Box<d...
pub use self::gen_client::Client as ManualSealClient; use futures::{ channel::{mpsc, oneshot}, FutureExt, SinkExt, TryFutureExt, }; use jsonrpc_core::Error; use jsonrpc_derive::rpc; use serde::{Deserialize, Serialize}; use sp_consensus::ImportedAux; use sp_runtime::Justification; type FutureResult<T> = Box<d...
fn finalize_block( &self, hash: Hash, justification: Option<Justification>, ) -> FutureResult<bool> { let mut sink = self.import_block_channel.clone(); let future = async move { let (sender, receiver) = oneshot::channel(); sink.send(EngineCommand...
er, receiver) = oneshot::channel(); let command = EngineCommand::SealNewBlock { create_empty, finalize, parent_hash, sender: Some(sender), }; sink.send(command).await?; receiver.await? } .boxe...
function_block-function_prefixed
[ { "content": "#[rpc]\n\npub trait BarcodeScannerApi<BlockHash, Hash> {\n\n #[rpc(name = \"barcode_scanner_is_valid_barcode\")]\n\n fn is_valid_barcode(&self, encoded_hash: Hash, at: Option<BlockHash>) -> Result<bool>;\n\n}\n\n\n\n/// A struct that implements the `BarcodeScannerApi`.\n\npub struct BarcodeS...
Rust
renderer/src/descriptors.rs
AndrewS236/TheEndlessWorld
a14d21429efe7d3a6b2e236d0a19d3e296de8a3a
use ash::vk; use ash::version::DeviceV1_0; use std::ptr; use crate::device::DeviceMTXG; use crate::buffer::UniformBufferMTXG; use crate::CleanupVkObj; #[allow(dead_code)] #[derive(Copy, Clone)] pub struct SetBindingMTXG { ind: u32, typ: vk::DescriptorType, lyt: vk::DescriptorSetLayoutBinding, } impl S...
use ash::vk; use ash::version::DeviceV1_0; use std::ptr; use crate::device::DeviceMTXG; use crate::buffer::UniformBufferMTXG; use crate::CleanupVkObj; #[allow(dead_code)] #[derive(Copy, Clone)] pub struct SetBindingMTXG { ind: u32, typ: vk::DescriptorType, lyt: vk::DescriptorSetLayoutBinding, } impl S...
} impl CleanupVkObj for DescriptorSetsMTXG { unsafe fn cleanup(&self, device: &DeviceMTXG) { device.device.destroy_descriptor_pool(self.pool, None); device.device.destroy_descriptor_set_layout(self.set_layout, None); } unsafe fn cleanup_recreation(&self, device: &DeviceMTXG) { dev...
unsafe { self.device.device.update_descriptor_sets(&[dscrp_write], &[]) }; } } else { assert_eq!(1, image_views.len()); for i in 0..self.sets.len() { let image_info = vk::DescriptorImageInfo { image_layout: vk::ImageLayout::SHADER_READ_ONL...
function_block-function_prefix_line
[ { "content": "// mipmap-less sampler creation\n\npub fn create_sampler(device: &DeviceMTXG,\n\n mag_filter: vk::Filter,\n\n min_filter: vk::Filter,\n\n address_mode_u: vk::SamplerAddressMode,\n\n address_mode_v: vk::SamplerAddre...
Rust
src/synth/wt_oscillator.rs
icsga/Yazz
593103400a53008e61a66237ca8c05656b2ceffc
use super::Float; use wavetable::WavetableRef; use serde::{Serialize, Deserialize}; const MAX_VOICES: usize = 7; #[derive(Serialize, Deserialize, Clone, Copy, Debug, Default)] pub struct WtOscData { pub num_voices: i64, pub voice_spread: Float, pub wave_index: Float, pub wavetable: usize, } impl Wt...
use super::Float; use wavetable::WavetableRef; use serde::{Serialize, Deserialize}; const MAX_VOICES: usize = 7; #[derive(Serialize, Deserialize, Clone, Copy, Debug, Default)] pub struct WtOscData { pub num_voices: i64, pub voice_spread: Float, pub wave_index: Float, pub wavetable: usize, } impl Wt...
ast_pos[i] = 0.0; } } } #[cfg(test)] #[test] fn test_get_table_index() { assert_eq!(WtOsc::get_table_index(11, 10.0), 0); assert_eq!(WtOsc::get_table_index(11, 20.0), 1); assert_eq!(WtOsc::get_table_index(11, 40.0), 2); assert_eq!(WtOsc::get_table_index(11, 80.0), 3); assert_eq!(WtOsc:...
table[position + 1] } else if frac < 0.1 { table[position] } else { let value_left = table[position]; let value_right = table[position + 1]; WtOsc::interpolate(value_left, value_right, frac) } } pub fn get_sampl...
random
[ { "content": "pub fn get_int(value: &Value) -> i64 {\n\n if let Value::Int(x) = value { *x } else { panic!(\"Got value {:?}\", value) }\n\n}\n\n\n", "file_path": "src/tui/value.rs", "rank": 0, "score": 132210.16842045842 }, { "content": "pub fn get_float(value: &Value) -> f64 {\n\n if ...
Rust
src/platform/src/linux/mod.rs
mmstick/relibc
5f9170d861898cf5a0a4c88f15c386f59ee19f8e
use core::ptr; use errno; use types::*; const AT_FDCWD: c_int = -100; const AT_REMOVEDIR: c_int = 0x200; pub fn e(sys: usize) -> usize { if (sys as isize) < 0 && (sys as isize) >= -256 { unsafe { errno = -(sys as isize) as c_int; } !0 } else { sys } } pub fn b...
use core::ptr; use errno; use types::*; const AT_FDCWD: c_int = -100; const AT_REMOVEDIR: c_int = 0x200;
pub fn brk(addr: *const c_void) -> c_int { unsafe { let newbrk = syscall!(BRK, addr); if newbrk < addr as usize { -1 } else { 0 } } } pub fn chdir(path: *const c_char) -> c_int { e(unsafe { syscall!(CHDIR, path) }) as c_int } pub fn chown(path: *co...
pub fn e(sys: usize) -> usize { if (sys as isize) < 0 && (sys as isize) >= -256 { unsafe { errno = -(sys as isize) as c_int; } !0 } else { sys } }
function_block-full_function
[ { "content": "extern int errno;\n", "file_path": "include/bits/errno.h", "rank": 0, "score": 80015.32969618468 }, { "content": "pub fn link(path1: *const c_char, path2: *const c_char) -> c_int {\n\n let path1 = unsafe { c_str(path1) };\n\n let path2 = unsafe { c_str(path2) };\n\n e(...
Rust
crates/aingle_keystore/src/test_keystore.rs
Daironode/aingle
54bfcbe21f587699a4e66e6764fe879a348987c8
use crate::*; const PUB1: &[u8] = &[ 154, 185, 40, 0, 115, 213, 127, 247, 174, 124, 110, 222, 11, 151, 230, 233, 2, 171, 91, 154, 79, 50, 137, 45, 188, 110, 75, 56, 45, 18, 156, 158, ]; const SEC1: &[u8] = &[ 207, 84, 35, 155, 191, 10, 211, 240, 254, 92, 222, 153, 125, 241, 80, 102, 189, 217, 201, 140, ...
use crate::*; const PUB1: &[u8] = &[ 154, 185, 40, 0, 115, 213, 127, 247, 174, 124, 110, 222, 11, 151, 230, 233, 2, 171, 91, 154, 79, 50, 137, 45, 188, 110, 75, 56, 45, 18, 156, 158, ]; const SEC1: &[u8] = &[ 207, 84, 35, 155, 191, 10, 211, 240, 254, 92, 222, 153, 125, 241, 80, 102, 189, 217, 201, 140, ...
2.to_vec(), }, ], vec![], vec![ FixtureX25519Keypair { pub_key: X25519_PUB1.into(), priv_key: X25519_SEC1.into(), }, FixtureX25519Keypair { pub_key: X25519_PUB2.into(), priv_key: X2551...
83, 246, 74, 221, 3, 123, 54, 48, 160, 192, 179, 207, 115, 6, 19, 53, 233, 231, 167, 75, ]; const X25519_SEC2: [u8; 32] = [ 19, 195, 209, 22, 152, 172, 136, 179, 66, 40, 251, 5, 43, 170, 48, 164, 199, 79, 46, 241, 70, 51, 70, 218, 21, 43, 220, 65, 117, 102, 224, 133, ]; const X25519_PUB2: [u8; 32] = [ ...
random
[ { "content": "/// Simulate getting an encryption key from Lair.\n\nfn get_encryption_key_shim() -> [u8; 32] {\n\n [\n\n 26, 111, 7, 31, 52, 204, 156, 103, 203, 171, 156, 89, 98, 51, 158, 143, 57, 134, 93, 56,\n\n 199, 225, 53, 141, 39, 77, 145, 130, 136, 108, 96, 201,\n\n ]\n\n}\n\n\n\n/// S...
Rust
tests/response.rs
sunnyrust/poem-openapi
98c28d67aee280d3877f0946351e79a8b773dde9
mod request; use poem::{ http::{HeaderValue, StatusCode}, IntoResponse, }; use poem_openapi::{ payload::{Json, PlainText}, registry::{MetaHeader, MetaMediaType, MetaResponse, MetaResponses, MetaSchema, MetaSchemaRef}, Object, Response, }; use serde_json::Value; #[derive(Object)] struct BadRequestR...
mod request; use poem::{ http::{HeaderValue, StatusCode}, IntoResponse, }; use poem_openapi::{ payload::{Json, PlainText}, registry::{MetaHeader, MetaMediaType, MetaResponse, MetaResponses, MetaSchema, MetaSchemaRef}, Object, Response, }; use serde_json::Value; #[derive(Object)] struct BadRequestR...
), #[oai(status = 400)] C( Json<BadRequestResult>, #[oai(header = "MY-HEADER1")] i32, #[oai(header = "MY-HEADER2")] String, ), D( StatusCode, PlainText, #[oai(header = "MY-HEADER1")] i32, #[oai(he...
assert_eq!(resp.status(), StatusCode::OK); let mut resp = MyResponse::BadRequest(Json(BadRequestResult { error_code: 123, message: "abc".to_string(), })) .into_response(); assert_eq!( serde_json::from_slice::<Value>(&resp.take_body().into_bytes().await.unwrap()).unwrap(), ...
random
[ { "content": "fn get_meta<T: Type>() -> MetaSchema {\n\n let mut registry = Registry::new();\n\n T::register(&mut registry);\n\n registry.schemas.remove(&*T::NAME.to_string()).unwrap()\n\n}\n\n\n", "file_path": "tests/object.rs", "rank": 0, "score": 228375.44197632003 }, { "content"...
Rust
replman/src/lib.rs
Dzejkop/replman
bcc3642960fe2f038394ff636d12c5ba6019307c
use std::str::FromStr; use rustyline::Editor; pub mod prelude { pub use replman_derive::ReplCmd; pub use crate::{read_command, Repl, ReplCmd}; } pub struct Repl { editor: Editor<()>, } impl Repl { #[allow(clippy::new_without_default)] pub fn new() -> Self { Self { editor: Ed...
use std::str::FromStr; use rustyline::Editor; pub mod prelude { pub use replman_derive::ReplCmd; pub use crate::{read_command, Repl, ReplCmd}; } pub struct Repl { editor: Editor<()>, } impl Repl { #[allow(clippy::new_without_default)] pub fn new() -> Self { Self { editor: Ed...
_unescape(line.trim())) { Ok(cmd) => return Ok(cmd), Err(err) => eprintln!("Failed to parse command: {}", err), } } } fn split_string_unescape( mut s: &str, ) -> impl Iterator<Item = anyhow::Result<&str>> { std::iter::from_fn(move || { if s.is_empty() { r...
from_str!(std::num::NonZeroI32); impl_with_from_str!(std::num::NonZeroI64); impl_with_from_str!(std::num::NonZeroI128); impl_with_from_str!(std::num::NonZeroIsize); impl_with_from_str!(std::num::NonZeroU8); impl_with_from_str!(std::num::NonZeroU16); impl_with_from_str!(std::num::NonZeroU32); impl_with_from_str!(std::nu...
random
[ { "content": "#[allow(unused_must_use)] // for the results of write! and writeln!\n\npub fn derive_help_method(\n\n input: &DataEnum,\n\n attrs: &EnumAttributes,\n\n) -> syn::ImplItemMethod {\n\n let mut help_str = String::new();\n\n\n\n for variant in &input.variants {\n\n let mut help_line ...
Rust
src/mod_search/vortex_scanner.rs
divanvisagie/skyrim-save-parser
4b55ba34a6496c152d8e23b32c322f479aa303fd
use std::{env, fs, io::Error, path::PathBuf}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug)] pub struct Plugin { pub name: String, pub urls: Vec<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct PluginFileType { name: String, #[serde(skip_serializing_if = "Option::is_none"...
use std::{env, fs, io::Error, path::PathBuf}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug)] pub struct Plugin { pub name: String, pub urls: Vec<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct PluginFileType { name: String, #[serde(skip_serializing_if = "Option::is_none"...
#[cfg(test)] mod tests { use super::*; #[test] fn get_masterlist_data_test() { let plugins = get_masterlist_data("skyrimse"); println!("{:?}", plugins); } #[test] fn get_profile_data_test() { let p = get_installed_from_all_profiles("skyrimse"); println!("Strin...
pub fn parse_plugin(plugin_file_type: &PluginFileType) -> Plugin { let name = plugin_file_type.name.clone(); let mut urls = Vec::new(); if let Some(v) = &plugin_file_type.url { if let serde_yaml::Value::Sequence(seq) = v { for item in seq { if let serde_yaml::Value::Strin...
function_block-full_function
[ { "content": "fn label_line(ui: &mut Ui, name: &str, value: &str) {\n\n ui.label(name);\n\n ui.label(value);\n\n ui.end_row();\n\n}\n\n\n\nimpl epi::App for AppState {\n\n fn update(&mut self, ctx: &egui::CtxRef, _frame: &epi::Frame) {\n\n egui::TopBottomPanel::top(\"top-panel\").show(ctx, |u...
Rust
raytracer/src/renderer.rs
vhiribarren/raytracer-rust
a45527204287191721d168c07a29fce37b68ea90
/* MIT License Copyright (c) 2019, 2020 Vincent Hiribarren 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...
/* MIT License Copyright (c) 2019, 2020 Vincent Hiribarren 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...
area_y_current: area_y, } } pub fn with_full_area(scene: Scene, config: RenderConfiguration) -> AreaRenderIterator { let area_width = config.canvas_width; let area_height = config.canvas_height; Self::new(scene, config, 0, 0, area_width, area_height) } pub fn to...
rayon::scope(move |s| { for y in 0..config.canvas_height { for x in 0..config.canvas_width { let tx = tx.clone(); s.spawn(move |_| { let canvas_x = x as f64 / (config.canvas_width as f64); let can...
random
[ { "content": "#[test]\n\n#[should_panic]\n\nfn scene_without_lights_is_error() {\n\n let scene = Scene {\n\n lights: Vec::new(),\n\n ..samples::generate_test_scene()\n\n };\n\n let config = <RenderConfiguration as Default>::default();\n\n render_scene(scene, config, false).unwrap().cou...
Rust
src/runner/forward_backward.rs
jneem/automaton
8fe5430417d4c8178f88ced8ba5e49cdde54ceb3
use std::fmt::Debug; use dfa::PrefixPart; use itertools::Itertools; use memchr::memchr; use runner::Engine; use runner::program::TableInsts; #[derive(Clone, Debug)] pub struct ForwardBackwardEngine<Ret> { forward: TableInsts<(usize, u8)>, backward: TableInsts<Ret>, prefix: Prefix, } impl<Ret: Copy + De...
use std::fmt::Debug; use dfa::PrefixPart; use itertools::Itertools; use memchr::memchr; use runner::Engine; use runner::program::TableInsts; #[derive(Clone, Debug)] pub struct ForwardBackwardEngine<Ret> { forward: TableInsts<(usize, u8)>, backward: TableInsts<Ret>, prefix: Prefix, } impl<Ret: Copy + De...
), } } fn clone_box(&self) -> Box<Engine<Ret>> { Box::new(self.clone()) } } #[derive(Clone, Debug)] pub enum Prefix { Empty, ByteSet { bytes: Vec<bool>, offset: usize }, Byte { byte: u8, offset: usize }, } const MAX_BYTE_SET_S...
if pos + offset <= s.len() { memchr(byte, &input[(pos + offset)..]).map(|x| x + pos) } else { None }
if_condition
[ { "content": "pub trait Engine<Ret: Debug>: Debug {\n\n fn find(&self, s: &str) -> Option<(usize, usize, Ret)>;\n\n fn clone_box(&self) -> Box<Engine<Ret>>;\n\n}\n\n\n\npub mod anchored;\n\npub mod forward_backward;\n\npub mod program;\n", "file_path": "src/runner/mod.rs", "rank": 0, "score": ...
Rust
crates/machinery-generator/src/extensions.rs
celphase/machinery-rs
1015a1728fc1db2e99564d875715b51d6954c832
use std::{ collections::{HashMap, HashSet}, fs, path::{Path, PathBuf}, process::Command, }; use heck::{CamelCase, ShoutySnakeCase, SnakeCase}; use nom::{ bytes::complete::{tag, take_while1}, character::complete::{char, none_of, satisfy, space0, space1}, multi::fold_many1, sequence::deli...
use std::{ collections::{HashMap, HashSet}, fs, path::{Path, PathBuf}, process::Command, }; use heck::{CamelCase, ShoutySnakeCase, SnakeCase}; use nom::{ bytes::complete::{tag, take_while1}, character::complete::{char, none_of, satisfy, space0, space1}, multi::fold_many1, sequence::deli...
} } Item::Impl(item) => { rename_ty(&mut item.self_ty); for item in &mut item.items { if let ImplItem::Method(item) = item { for input in &mut item.sig.inputs { if let FnArg::Typed(ty) = input { ...
match item { ForeignItem::Fn(item) => { for input in &mut item.sig.inputs { if let FnArg::Typed(ty) = input { rename_ty(&mut ty.ty); } } if ...
if_condition
[ { "content": "pub fn generate_wrappers(ty_name: &Ident, item: &ItemImpl) -> Vec<(Ident, TokenStream)> {\n\n let mut wrappers = Vec::new();\n\n\n\n for item in &item.items {\n\n let method_item = if let ImplItem::Method(method_item) = item {\n\n method_item\n\n } else {\n\n ...
Rust
src/commands/roll.rs
Celeo/CoD_dice_roller
43bcf3ead95e48d967bef521f68427a815f1b658
use lazy_static::lazy_static; use log::debug; use rand::{ distributions::{Distribution, Uniform}, thread_rng, }; use regex::Regex; use serenity::{ client::Context, framework::standard::{Args, CommandResult, macros::command}, model::channel::Message, utils::MessageBuilder, }; use std::{collection...
use lazy_static::lazy_static; use log::debug; use rand::{ distributions::{Distribution, Uniform}, thread_rng, }; use regex::Regex; use serenity::{ client::Context, framework::standard::{Args, CommandResult, macros::command}, model::channel::Message, utils::MessageBuilder, }; use std::{collection...
#[test] fn test_roll_again() { assert!(!roll_again(10, &RollModifier::NoAgain)); assert!(roll_again(10, &RollModifier::Again10)); assert!(!roll_again(9, &RollModifier::Again10)); assert!(!roll_again(8, &RollModifier::Again10)); assert!(!roll_again(7, &RollModifier::Aga...
fn test_mod_for_str() { assert_eq!(mod_for_str(""), RollModifier::Again10); assert_eq!(mod_for_str("9again"), RollModifier::Again9); assert_eq!(mod_for_str("8again"), RollModifier::Again8); assert_eq!(mod_for_str("no10again"), RollModifier::NoAgain); }
function_block-full_function
[ { "content": "#[command]\n\npub fn stats(context: &mut Context, message: &Message, args: Args) -> CommandResult {\n\n let mut args = args;\n\n if args.is_empty() {\n\n debug!(\"No args supplied to stats command\");\n\n return Ok(());\n\n }\n\n let first_arg = args.single::<String>().un...
Rust
src/chipid.rs
atsam4e-rs/atsam4e16e_hal
2b46f90f90f0a3f50412f2e04966098a05cea251
use crate::pac::CHIPID; #[derive(Clone, Copy, Debug, defmt::Format)] pub enum EmbeddedProcessor { Arm946Es, Arm7Tdmi, CortexM3, Arm920T, Arm926Ejs, CortexA5, CortexM4, } #[derive(Clone, Copy, Debug, defmt::Format)] pub enum Family { AtSam4e, AtSam4n, AtSam4s, } #[derive(Clone,...
use crate::pac::CHIPID; #[derive(Clone, Copy, Debug, defmt::Format)] pub enum EmbeddedProcessor { Arm946Es, Arm7Tdmi, CortexM3, Arm920T, Arm926Ejs, CortexA5, CortexM4, } #[derive(Clone, Copy, Debug, defmt::Format)] pub enum Family { AtSam4e, AtSam4n, AtSam4s, } #[derive(Clone,...
fn decode_family_and_model(chip_id: &CHIPID) -> (Option<Family>, Option<Model>) { match chip_id.cidr.read().bits() { 0x288B_07E0 => (Some(Family::AtSam4s), Some(Model::AtSam4s2a)), 0x289B_07E0 => (Some(Family::AtSam4s), Some(Model::AtSam4s2b)), 0x28AB_07E0 => (Some(Fami...
4), 7 => Some(128 * 1024), 9 => Some(256 * 1024), 10 => Some(512 * 1024), 12 => Some(1024 * 1024), 14 => Some(2048 * 1024), _ => None, } }
function_block-function_prefixed
[ { "content": "fn get_flash_wait_states_for_clock_frequency(clock_frequency: Hertz) -> u8 {\n\n match clock_frequency {\n\n c if c < 20_u32.MHz::<1, 1>() => 0,\n\n c if c < 40_u32.MHz::<1, 1>() => 1,\n\n c if c < 60_u32.MHz::<1, 1>() => 2,\n\n c if c < 80_u32.MHz::<1, 1>() => 3,\n\...
Rust
src/multi/difference_by_key.rs
MarinPostma/sdset
3aa1e37d6a7069e7c8c81fb6699285522712a5fd
use std::cmp; use crate::set::{Set, vec_sets_into_slices}; use crate::{SetOperation, Collection, exponential_offset_ge_by_key}; #[derive(Clone)] pub struct DifferenceByKey<'a, T: 'a, U: 'a, F, G, K> where F: Fn(&T) -> K, G: Fn(&U) -> K, K: Ord, { base: &'a [T], others: Vec<&'a [U]>, f: F, g...
use std::cmp; use crate::set::{Set, vec_sets_into_slices}; use crate::{SetOperation, Collection, exponential_offset_ge_by_key}; #[derive(Clone)] pub struct DifferenceByKey<'a, T: 'a, U: 'a, F, G, K> where F: Fn(&T) -> K, G: Fn(&U) -> K, K: Ord, { base: &'a [T], others: Vec<&'a [U]>, f: F, g...
{ let op = DifferenceByKey { base: &a, others: vec![&b, &c], f: |x| x.a, g: |&x| x }; let res: SetBuf<Foo> = op.into_set_buf(); test::black_box(|| res); }); } #[bench] fn three_slices_big3(bench: &mut Bencher) { let a: Vec<_> = (0..100).map(Foo::new).coll...
{ let a: Vec<_> = (0..100).map(Foo::new).collect(); let b: Vec<_> = (34..134).collect(); let c: Vec<_> = (66..167).collect(); bench.iter(||
function_block-random_span
[ { "content": "#[inline]\n\npub fn exponential_search_by_key<T, B, F>(slice: &[T], b: &B, mut f: F) -> Result<usize, usize>\n\nwhere F: FnMut(&T) -> B,\n\n B: Ord\n\n{\n\n exponential_search_by(slice, |k| f(k).cmp(b))\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 187438.53624207...
Rust
futures-util/src/sink/buffer.rs
gferon/futures-rs
64529405aada4e209fe29995c5b80fc4e40f79ef
use futures_core::stream::Stream; use futures_core::task::{Context, Poll}; use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use core::pin::Pin; use alloc::collections::VecDeque; #[derive(Debug)] #[must_use = "sinks do nothing unless polled"] pub struct Buffer<Si: Sink<Item>, Item> { sink: S...
use futures_core::stream::Stream; use futures_core::task::{Context, Poll}; use futures_sink::Sink; use pin_utils::{unsafe_pinned, unsafe_unpinned}; use core::pin::Pin; use alloc::collections::VecDeque; #[derive(Debug)] #[must_use = "sinks do nothing unless polled"] pub struct Buffer<Si: Sink<Item>, Item> { sink: S...
fn start_send( mut self: Pin<&mut Self>, item: Item, ) -> Result<(), Self::Error> { if self.capacity == 0 { self.as_mut().sink().start_send(item) } else { self.as_mut().buf().push_back(item); Ok(()) } } fn poll_flush( ...
fn poll_ready( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>> { if self.capacity == 0 { return self.as_mut().sink().poll_ready(cx); } let _ = self.as_mut().try_empty_buffer(cx)?; if self.buf.len() >= self.capacity { ...
function_block-full_function
[ { "content": "#[doc(hidden)]\n\npub fn assert_is_unpin_stream<S: Stream + Unpin>(_: &mut S) {}\n\n\n\n/// Assert that the next poll to the provided stream will return\n\n/// [`Poll::Pending`](futures_core::task::Poll::Pending).\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// #![feature(async_await)]\n\n/// us...
Rust
src/clears.rs
gw2scratch/arcdps_clears
a5e21759f4391052d11d5edeb2474e9f93b94f5f
use serde::{Deserialize, Serialize}; use std::collections::HashMap; use chrono::{DateTime, Duration, TimeZone, Utc}; use uuid::Uuid; use crate::settings::ApiKey; pub struct ClearData { raids: Option<RaidWings>, state: HashMap<Uuid, RaidClearState>, } impl ClearData { pub fn new() -> Self { ClearD...
use serde::{Deserialize, Serialize}; use std::collections::HashMap; use chrono::{DateTime, Duration, TimeZone, Utc}; use uuid::Uuid; use crate::settings::ApiKey; pub struct ClearData { raids: Option<RaidWings>, state: HashMap<Uuid, RaidClearState>, } impl ClearData { pub fn new() -> Self { ClearD...
lf) -> DateTime<Utc> { self.last_check_time } pub fn last_api_update_time(&self) -> DateTime<Utc> { self.last_api_update_time } } #[allow(dead_code)] impl FinishedEncountersStore { pub fn is_finished(&self, encounter: &RaidEncounter) -> bool { self.finished_encounter_ids.iter()....
b struct RaidClearState { finished_encounters: FinishedEncountersStore, last_check_time: DateTime<Utc>, last_api_update_time: DateTime<Utc>, } impl RaidClearState { pub fn new(finished_encounters: FinishedEncountersStore, last_check_time: DateTime<Utc>, last_api_update_time: DateTime<Utc>) -> Self { ...
random
[ { "content": "pub fn get_key_name(key: usize) -> Option<&'static str> {\n\n match key {\n\n 8 => Some(\"BACKSPACE\"),\n\n 9 => Some(\"TAB\"),\n\n 12 => Some(\"CLEAR\"),\n\n 13 => Some(\"ENTER\"),\n\n 19 => Some(\"PAUSE\"),\n\n 20 => Some(\"CAPS LOCK\"),\n\n 27...
Rust
core/src/component/pool/interface.rs
BlockProject3D/regecs
83d76fa1db9c5672dccc0b8c7e8fda9e5a136c49
use std::ops::{Index, IndexMut}; use crate::component::{Component, ComponentRef}; use crate::object::ObjectRef; pub trait ComponentPool<T: Component>: Index<ComponentRef<T>, Output = T> + IndexMut<ComponentRef<T>> where Self: Sized { fn add(&mut self, comp...
use std::ops::{Index, IndexMut}; use crate::component::{Component, ComponentRef}; use crate::object::ObjectRef; pub trait ComponentPool<T: Component>: Index<ComponentRef<T>, Output = T> + IndexMut<ComponentRef<T>> where
fn clear(&mut self, entity: ObjectRef); fn get_first_mut(&mut self, entity: ObjectRef) -> Option<&mut T>; fn get_first(&self, entity: ObjectRef) -> Option<&T>; } pub trait ComponentManager<T: Component> { fn get(&self) -> &T::Pool; fn get_mut(&mut self) -> &mut T::Pool; fn get_compone...
Self: Sized { fn add(&mut self, comp: T) -> ComponentRef<T>; fn remove(&mut self, r: ComponentRef<T>); fn len(&self) -> usize; fn is_empty(&self) -> bool { self.len() == 0 } } pub trai...
random
[ { "content": "/// Represents a component\n\npub trait Component: Sized\n\n{\n\n /// The type of ComponentPool to use for storing instances of this component\n\n type Pool: ComponentPool<Self>;\n\n}\n\n\n\npub struct ComponentRef<T: Component>\n\n{\n\n pub index: usize,\n\n useless: std::marker::Phan...
Rust
quic/s2n-quic-core/src/packet/encoding.rs
czakian/s2n-quic
c3ab570d42377e4a10084c965628d71219b1c492
use crate::{ crypto::{HeaderKey, Key as CryptoKey, ProtectedPayload}, packet::{ number::{PacketNumber, PacketNumberLen}, stateless_reset, }, }; use s2n_codec::{Encoder, EncoderBuffer, EncoderLenEstimator, EncoderValue}; pub trait PacketPayloadLenCursor: EncoderValue { fn new() -> Self...
use crate::{ crypto::{HeaderKey, Key as CryptoKey, ProtectedPayload}, packet::{ number::{PacketNumber, PacketNumberLen}, stateless_reset, }, }; use s2n_codec::{Encoder, EncoderBuffer, EncoderLenEstimator, EncoderValue}; pub trait PacketPayloadLenCursor: EncoderValue { fn new() -> Self...
cket_number.len().bytesize() + header_key.sealing_sample_len(), ); let estimated_payload_len = self .payload() .encoding_size_hint(&estimator, minimum_payload_len); if estimated_payload_len == 0 { return Er...
rLen, encoder: &mut E); fn payload(&mut self) -> &mut Payload; fn packet_number(&self) -> PacketNumber; fn encode_packet<'a>( mut self, key: &K, header_key: &H, largest_acknowledged_packet_number: PacketNumber, min_packet_len: Option<usize>, ...
random
[]
Rust
wonnx/tests/matrix.rs
webonnx/wonnx
db471ec90768c3deb08ca5c2bae292de23be9a43
use std::{collections::HashMap, convert::TryInto}; use wonnx::utils::{attribute, graph, initializer, model, node, tensor}; mod common; #[test] fn test_matmul_square_matrix() { let n = 16; let mut input_data = HashMap::new(); let data_a = ndarray::Array2::eye(n); let mut data_b = ndarray::Array2::<f32>...
use std::{collections::HashMap, convert::TryInto}; use wonnx::utils::{attribute, graph, initializer, model, node, tensor}; mod common; #[test] fn test_matmul_square_matrix() { let n = 16; let mut input_data = HashMap::new(); let data_a = ndarray::Array2::eye(n); let mut data_b = ndarray::Array2::<f32>...
nwrap(), &test_y); let mut input_data = HashMap::new(); let data = (1..=4).map(|x| x as f32).collect::<Vec<f32>>(); input_data.insert("X".to_string(), data.as_slice().into()); let upsampling_model = model(graph( vec![tensor("X", &[1, 1, 2, 2])], vec![tensor("Y", &[1, 1, 4, 6])], ...
nspose", vec![attribute("perm", vec![2, 1, 0])], ), ], )); let session = pollster::block_on(wonnx::Session::from_model(model)).expect("session did not create"); let result = pollster::block_on(session.run(&input_data)).unwrap(); common::assert_eq_vector((&re...
random
[ { "content": "pub fn initializer_int64(name: &str, data: Vec<i64>, dimensions: Vec<i64>) -> onnx::TensorProto {\n\n let mut initializer = crate::onnx::TensorProto::new();\n\n debug_assert_eq!(\n\n dimensions.iter().cloned().product::<i64>() as usize,\n\n data.len()\n\n );\n\n initializ...
Rust
src/stash/runtime.rs
claudiosdc/rgb-node
058b37a86d34917baad632fcb85dd20107f3ffff
use std::path::PathBuf; use lnpbp::bitcoin::{Transaction, Txid}; use lnpbp::lnp::zmqsocket::ZmqType; use lnpbp::lnp::{ session, transport, CreateUnmarshaller, PlainTranscoder, Session, TypedEnum, Unmarshall, Unmarshaller, }; use lnpbp::rgb::{ validation, Anchor, Assignments, Consignment, ContractId, Gene...
use std::path::PathBuf; use lnpbp::bitcoin::{Transaction, Txid}; use lnpbp::lnp::zmqsocket::ZmqType; use lnpbp::lnp::{ session, transport, CreateUnmarshaller, PlainTranscoder, Session, TypedEnum, Unmarshall, Unmarshaller, }; use lnpbp::rgb::{ validation, Anchor, Assignments, Consignment, ContractId, Gene...
esis.schema_id()) .map_err(|err| ServiceErrorDomain::Storage(err.to_string()))?; let validation_status = consignment.validate(&schema, &self.electrum); self.storage.add_genesis(&consignment.genesis)?; match validation_status.validity() { Validity::Valid => Ok(...
debug!("API request processing complete"), Err(err) => { error!("Error processing API request: {}", err); Err(err)?; } } } } } impl Runtime { async fn run(&mut self) -> Result<(), RuntimeError> { trace!("Awaitin...
random
[ { "content": "pub trait Store {\n\n type Error: ::std::error::Error + Into<ServiceErrorDomain>;\n\n\n\n fn schema_ids(&self) -> Result<Vec<SchemaId>, Self::Error>;\n\n fn schema(&self, id: &SchemaId) -> Result<Schema, Self::Error>;\n\n fn has_schema(&self, id: &SchemaId) -> Result<bool, Self::Error>...
Rust
telebot/src/bot.rs
AkaEra/ubiquitous-broccoli
018183e29f451107a2db17bbf52e6f5e27c0aa82
use error::Error; use objects; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::rc::Rc; use std::str; use std::sync::{Arc, Mutex}; use std::time::Duration; use curl::easy::{Easy, List}; use futures::sync::mpsc; use futures::sync::mpsc::UnboundedSender; use futures::{stream, Future, IntoFuture...
use error::Error; use objects; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::rc::Rc; use std::str; use std::sync::{Arc, Mutex}; use std::time::Duration; use curl::easy::{Easy, List}; use futures::sync::mpsc; use futures::sync::mpsc::UnboundedSender; use futures::{stream, Future, IntoFuture...
if let Some(text) = message.text.clone() { let mut content = text.split_whitespace(); if let Some(cmd) = content.next() { let s: Vec<&str> = cmd.split("@").take(2).collect(); if s.len() > 0 && (s.len() < 2 || s[1] ==...
andle.clone()), username: String::new(), id: 0, } } pub fn fetch_json<'a, T: DeserializeOwned + 'a>( &self, func: &str, msg: &str, ) -> impl Future<Item = T, Error = Error> + 'a { debug!("Send JSON: {}", msg); let mut h...
random
[ { "content": "pub fn gen_ua(bot: &telebot::RcBot) -> String {\n\n format!(\n\n concat!(\n\n env!(\"CARGO_PKG_NAME\"),\n\n \"/\",\n\n env!(\"CARGO_PKG_VERSION\"),\n\n \" (+https://t.me/{})\"\n\n ),\n\n bot.inner.username\n\n )\n\n}\n", "f...
Rust
src/core/util/numeric.rs
unix1986/rucene
bf4de84dafb58eeedfc2b975556890ed3e5dc1f6
#[derive(Debug, Clone, Copy, Serialize)] pub enum Numeric { Null, Byte(i8), Short(i16), Int(i32), Long(i64), Float(f32), Double(f64), } impl Numeric { pub fn byte_value(&self) -> i8 { match *self { Numeric::Byte(v) => v, Numeric::Short(v) => v as i8, ...
#[derive(Debug, Clone, Copy, Serialize)] pub enum Numeric { Null, Byte(i8), Short(i16), Int(i32), Long(i64), Float(f32), Double(f64), } impl Numeric { pub fn byte_value(&self) -> i8 { match *self { Numeric::Byte(v) => v, Numeric::Short(v) => v as i8, ...
pub fn long2sortable_bytes(value: i64, result: &mut [u8]) { let value = (value as u64 ^ 0x8000_0000_0000_0000) as i64; result[0] = (value >> 56) as u8; result[1] = (value >> 48) as u8; result[2] = (value >> 40) as u8; result[3] = (value >> 32) as u8; result[4] = (value >> 24) as u8; result...
pub fn sortable_bytes2int(encoded: &[u8]) -> i32 { let x = ((i32::from(encoded[0]) & 0xff) << 24) | ((i32::from(encoded[1]) & 0xff) << 16) | ((i32::from(encoded[2]) & 0xff) << 8) | (i32::from(encoded[3]) & 0xff); (x as u32 ^ 0x8000_0000) as i32 }
function_block-full_function
[ { "content": "pub fn long_to_int_exact(val: i64) -> Result<i32> {\n\n let ans = val as i32;\n\n if i64::from(ans) != val {\n\n bail!(IllegalState(\"integer overflow\".to_owned()));\n\n }\n\n Ok(ans)\n\n}\n\n\n", "file_path": "src/core/util/math.rs", "rank": 3, "score": 390490.6409...
Rust
feather/plugin-host/src/context/wasm/bump.rs
leElvyn/feather
1e2427b4389fccb61201e10c09cc88545f8108b0
use std::{alloc::Layout, cell::Cell}; use anyhow::Context; use wasmer::{NativeFunc, WasmPtr}; const INITIAL_CHUNK_SIZE: usize = 2048; const CHUNK_ALIGN: usize = 16; fn round_up_to(n: usize, divisor: usize) -> Option<usize> { debug_assert!(divisor > 0); debug_assert!(divisor.is_power_of_two()); Some(n.ch...
use std::{alloc::Layout, cell::Cell}; use anyhow::Context; use wasmer::{NativeFunc, WasmPtr}; const INITIAL_CHUNK_SIZE: usize = 2048; const CHUNK_ALIGN: usize = 16; fn round_up_to(n: usize, divisor: usize) -> Option<usize> { debug_assert!(divisor > 0); debug_assert!(divisor.is_power_of_two()); Some(n.ch...
Ok(Chunk { start, layout, ptr: Cell::new(start + new_size as u32), }) } pub fn reset(&mut self) -> anyhow::Result<()> { for chunk in self.chunks.drain(..self.chunks.len()) { self.deallocate_function.call( c...
} assert_eq!(align % CHUNK_ALIGN, 0); assert_eq!(new_size % CHUNK_ALIGN, 0); let layout = Layout::from_size_align(new_size, align).context("size or align is 0")?; assert!(new_size >= previous_size.unwrap_or(0) * 2); let start = self .allocate_function .ca...
function_block-random_span
[ { "content": "#[fecs::system]\n\npub fn chunk_optimize(game: &mut Game) {\n\n // Only run every CHUNK_OPTIMIZE_INTERVAL ticks\n\n if game.tick_count % CHUNK_OPTIMIZE_INTERVAL != 0 {\n\n return;\n\n }\n\n\n\n log::debug!(\"Optimizing chunks\");\n\n\n\n let start_time = current_time_in_milli...
Rust
src/core/mod.rs
SylphieBot/sylph-verifier
b33bf410e90c3f45e6a5506324beb2409e9173ff
use commands::*; use database::Database; use errors::*; use parking_lot::RwLock; use std::mem::drop; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicU8, Ordering}; use std::thread; use std::time::{Duration, Instant}; mod config; mod delete_service; mod discord; mod permissions; mod place; mod...
use commands::*; use database::Database; use errors::*; use parking_lot::RwLock; use std::mem::drop; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicU8, Ordering}; use std::thread; use std::time::{Duration, Instant}; mod config; mod delete_service; mod discord; mod permissions; mod place; mod...
} fn cleanup(&self) -> Result<()> { debug!("Running garbage collection."); self.0.config.on_cleanup_tick(); self.0.discord.on_cleanup_tick(); self.0.permissions.on_cleanup_tick(); self.0.roles.on_cleanup_tick(); self.0.verify_channel.on_cleanup_tick(); s...
Ok(VerifierCore(Arc::new(VerifierCoreData { status: AtomicU8::new(STATUS_STOPPED), _database: database, _tasks: tasks, config, core_ref, terminal, verifier, discord, place, permissions, roles, verify_channel, })))
call_expression
[ { "content": "fn set_perms_for_scope(ctx: &CommandContext, scope: Scope, mut last_arg: usize) -> Result<()> {\n\n let mut add_perms = EnumSet::new();\n\n let mut sub_perms = EnumSet::new();\n\n\n\n while let Some(arg) = ctx.arg_opt(last_arg) {\n\n if arg.starts_with('+') {\n\n add_per...
Rust
src/oof/mod.rs
marcospb19/ouch-1
a16b7e1ff9d3dcc7e5dbec22c4c75cc8617eb4e4
mod error; mod flags; pub mod util; use std::{ collections::BTreeMap, ffi::{OsStr, OsString}, }; pub use error::OofError; pub use flags::{ArgFlag, Flag, FlagType, Flags}; use util::trim_double_hyphen; pub fn pop_subcommand<'a, T, I, II>(args: &mut Vec<T>, subcommands: I) -> Option<&'a II> where I: Into...
mod error; mod flags; pub mod util; use std::{ collections::BTreeMap, ffi::{OsStr, OsString}, }; pub use error::OofError; pub use flags::{ArgFlag, Flag, FlagType, Flags}; use util::trim_double_hyphen; pub fn pop_subcommand<'a, T, I, II>(args: &mut Vec<T>, subcommands: I) -> Option<&'a II> where I: Into...
ote"]; let mut args = gen_args("add a b c"); let result = pop_subcommand(&mut args, subcommands); assert_eq!(result, Some(&"add")); assert_eq!(args[0], "a"); let mut args = gen_args("a b c"); let result = pop_subcommand(&mut args, subcommands); assert...
.get(&letter).ok_or(OofError::UnknownShortFlag(letter))?; if !is_last_letter && flag_info.takes_value { return Err(OofError::MisplacedShortArgFlagError(letter)); } let flag_name: &'static...
random
[]
Rust
src/reminisce.rs
TomBebbington/reminisce
1dd6c5516cc7ca5831bfe9bb140a1f807f876576
extern crate libc; #[cfg(target_os = "linux")] extern crate inotify; #[cfg(target_os = "windows")] #[macro_use] extern crate rustc_bitflags; #[cfg(feature = "sdl")] extern crate sdl2; #[cfg(target_os = "linux")] extern crate glob; #[cfg(all(target_os = "linux", not(feature = "sdl")))] pub mod linux; #[cfg(all(tar...
extern crate libc; #[cfg(target_os = "linux")] extern crate inotify; #[cfg(target_os = "windows")] #[macro_use] extern crate rustc_bitflags; #[cfg(feature = "sdl")] extern crate sdl2; #[cfg(target_os = "linux")] extern crate glob; #[cfg(all(target_os = "linux", not(feature = "sdl")))] pub mod linux; #[cfg(all(tar...
32), HatMoved(JoystickIndex, Hat, HatPos) } pub trait Backend: Sized { type Joystick : Joystick; fn new() -> Self; fn num_joysticks(&self) -> usize { self.joysticks().len() } fn joysticks(&self) -> &[Self::Joystick]; fn poll(&mut self) -> Optio...
; pub use native::Native; const MAX_AXIS_VALUE:i16 = 32767; use std::borrow::Cow; use std::fmt::Debug; pub type Axis = u8; pub type Button = u8; pub type Hat = u8; #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum HatPos { Centered, Up, Right, Down, Left } pub type JoystickIndex = u8; #[...
random
[ { "content": "/// Scan for joysticks\n\npub fn scan() -> Vec<NativeJoystick> {\n\n\t(0..4).filter_map(|i| ::Joystick::open(i).ok()).collect()\n\n}\n\n\n\npub struct NativeJoystick {\n\n\tindex: u8,\n\n\tlast: Gamepad,\n\n\tlast_packet: i32,\n\n\tevents: VecDeque<::Event>\n\n}\n\nimpl ::Joystick for NativeJoysti...
Rust
chain-impl-mockchain/src/testing/data/address.rs
truchq-ibl/chain-libs
f0fe7d5998146a0203b26cd655e48fd6a4b6046e
use crate::{ account::{Identifier, SpendingCounter}, header::HeaderId, key::EitherEd25519SecretKey, testing::builders::make_witness, transaction::{Input, Output, TransactionAuthData, Witness}, utxo::Entry, value::Value, }; use chain_addr::{Address, AddressReadable, Discrimination, Kind, Kind...
use crate::{ account::{Identifier, SpendingCounter}, header::HeaderId, key::EitherEd25519SecretKey, testing::builders::make_witness, transaction::{Input, Output, TransactionAuthData, Witness}, utxo::Entry, value::Value, }; use chain_addr::{Address, AddressReadable, Discrimination, Kind, Kind...
ccount_with_spending_counter( discrimination: Discrimination, spending_counter: u32, value: Value, ) -> Self { let address_data = AddressData::account_with_spending_counter(discrimination, spending_counter); Self::new(address_data, value) } pub fn delegat...
!("wrong kind of address to to get delegation key"), } } pub fn confirm_transaction(&self) { self.spending_counter.map(|sp| sp.increment().unwrap()); } pub fn spending_counter(&self) -> Option<SpendingCounter> { self.spending_counter } pub fn private_key(&self) -> Eith...
random
[ { "content": "pub fn to_raw_pk(key: &PublicKey<Ed25519Bip32>) -> PublicKey<Ed25519> {\n\n PublicKey(Pub::from_xpub(&key.0))\n\n}\n\n\n", "file_path": "chain-crypto/src/derive.rs", "rank": 0, "score": 384650.97988019395 }, { "content": "pub fn derive_sk_ed25519(key: &SecretKey<Ed25519Bip32...
Rust
src/parse/message.rs
Murgeye/imap-codec
fb7b5fc2358902383fbdbccdbc22bfa408305d91
use crate::{ parse::{ body::body, core::{nstring, number, nz_number}, datetime::date_time, envelope::envelope, flag::flag_fetch, section::section, }, types::response::{Data, DataItemResponse}, }; use abnf_core::streaming::SP; use nom::{ branch::alt, by...
use crate::{ parse::{ body::body, core::{nstring, number, nz_number}, datetime::date_time, envelope::envelope, flag::flag_fetch, section::section, }, types::response::{Data, DataItemResponse}, }; use abnf_core::streaming::SP; use nom::{ branch::alt, by...
tuple((tag_no_case(b"RFC822.TEXT"), SP, nstring)), |(_, _, nstring)| DataItemResponse::Rfc822Text(nstring.to_owned()), ), map( tuple((tag_no_case(b"RFC822"), SP, nstring)), |(_, _, nstring)| DataItemResponse::Rfc822(nstring.to_owned()), ...
), ))(remaining) } fn msg_att(input: &[u8]) -> IResult<&[u8], Vec<DataItemResponse>> { delimited( tag(b"("), separated_nonempty_list(SP, alt((msg_att_dynamic, msg_att_static))), tag(b")"), )(input) } fn msg_att_dynamic(input: &[u8]) -> IResult<&[u8], DataItemResponse> { let ...
random
[ { "content": "/// enable-data = \"ENABLED\" *(SP capability)\n\nfn enable_data(input: &[u8]) -> IResult<&[u8], Data> {\n\n let parser = tuple((tag_no_case(b\"ENABLED\"), many1(preceded(SP, capability))));\n\n\n\n let (remaining, (_, capabilities)) = parser(input)?;\n\n\n\n Ok((remaining, { Data::Enable...
Rust
game/src/sandbox/dashboards/misc.rs
accelsao/abstreet
eca71d27c95abd74a96863ed20bbd92c7850cd33
use crate::app::App; use crate::common::Tab; use crate::game::{DrawBaselayer, State, Transition}; use crate::sandbox::dashboards::DashTab; use crate::sandbox::SandboxMode; use abstutil::{prettyprint_usize, Counter}; use ezgui::{ Autocomplete, Btn, Composite, EventCtx, GfxCtx, Line, LinePlot, Outcome, PlotOptions, S...
use crate::app::App; use crate::common::Tab; use crate::game::{DrawBaselayer, State, Transition}; use crate::sandbox::dashboards::DashTab; use crate::sandbox::SandboxMode; use abstutil::{prettyprint_usize, Counter}; use ezgui::{ Autocomplete, Btn, Composite, EventCtx, GfxCtx, Line, LinePlot, Outcome, PlotOptions, S...
} impl State for ActiveTraffic { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition { match self.composite.event(ctx) { Outcome::Clicked(x) => DashTab::TripSummaries.transition(ctx, app, &x), _ => Transition::Keep, } } fn draw_baselayer(&self) -> ...
pub fn new(ctx: &mut EventCtx, app: &App) -> Box<dyn State> { let mut active_agents = vec![Series { label: format!("After \"{}\"", app.primary.map.get_edits().edits_name), color: app.cs.after_changes, pts: app .primary .sim .get...
function_block-full_function
[ { "content": "/// Create a new widget by implementing this trait. You can instantiate your widget by calling\n\n/// `Widget::new(Box::new(instance of your new widget))`, which gives you the usual style options.\n\npub trait WidgetImpl: downcast_rs::Downcast {\n\n /// What width and height does the widget occ...
Rust
src/bits.rs
flier/rust-t1ha
163460ad90b424e75a5480cfe3c94edafc4883ef
use core::marker::PhantomData; use core::mem; use core::ptr; use num_traits::{PrimInt, WrappingShr, Zero}; use crate::nightly::likely; const PAGESIZE: usize = 4096; pub fn aligned_to<T, P>(p: *const P) -> bool { (p as usize) % mem::size_of::<T>() == 0 } pub const PRIME_0: u64 = 0xEC99_BF0D_8372_CAAB; pub const...
use core::marker::PhantomData; use core::mem; use core::ptr; use num_traits::{PrimInt, WrappingShr, Zero}; use crate::nightly::likely; const PAGESIZE: usize = 4096; pub fn aligned_to<T, P>(p: *const P) -> bool { (p as usize) % mem::size_of::<T>() == 0 } pub const PRIME_0: u64 = 0xEC99_BF0D_8372_CAAB; pub const...
} } impl<T> MemoryModel for BigEndianUnaligned<T> where T: PrimInt + Zero + WrappingShr, { type Item = T; #[inline(always)] unsafe fn fetch<P>(p: *const P) -> Self::Item { ptr::read_unaligned(p as *const Self::Item).to_be() } #[inline(always)] unsafe fn tail<P>(p: *const P, t...
if likely(can_read_underside(p, mem::size_of::<T>())) { Self::fetch(p.sub(offset as usize)).wrapping_shr(shift as u32) } else { Self::fetch(p) & ((!T::zero()).wrapping_shr(shift as u32)) }
if_condition
[ { "content": "fn t1ha2_atonce_body<T: MemoryModel<Item = u64>>(mut data: &[u8], seed: u64) -> u64 {\n\n let mut state = State::default();\n\n let len = data.len();\n\n\n\n state.init_ab(seed, len as u64);\n\n\n\n if unlikely(len > 32) {\n\n state.init_cd(seed, len as u64);\n\n unsafe {...
Rust
Bootloaders/uefi/main.rs
ids1024/rust_os
236dfdca5660372ea6d4c3f1eea463dbd2c2945d
#![feature(asm)] #![feature(proc_macro_hygiene)] #![feature(panic_info_message)] #![no_std] use uefi::boot_services::protocols; use core::mem::size_of; #[macro_use] extern crate uefi; extern crate utf16_literal; macro_rules! log { ($($v:tt)*) => { loge!( ::get_conout(), $($v)*) }; } #[path="../_common/elf.rs"] ...
#![feature(asm)] #![feature(proc_macro_hygiene)] #![feature(panic_info_message)] #![no_std] use uefi::boot_services::protocols; use core::mem::size_of; #[macro_use] extern crate uefi; extern crate utf16_literal; macro_rules! log { ($($v:tt)*) => { loge!( ::get_conout(), $($v)*) }; } #[path="../_common/elf.rs"] ...
} pub fn get_conout() -> &'static ::uefi::SimpleTextOutputInterface { unsafe { &*S_CONOUT } } #[no_mangle] pub extern "win64" fn efi_main(image_handle: ::uefi::Handle, system_table: &::uefi::SystemTable) -> ::uefi::Status { let conout = system_table.con_out(); unsafe { S_CONOUT = conout; S_IMAGE_HANDLE...
ys_vol.open_read(filename) { Ok(_cfg_file) => { panic!("TODO: Read config file (allocating strings with `bs`)"); }, Err(::uefi::status::NOT_FOUND) => { Ok(Configuration { kernel: ::uefi::CStr16::from_slice(PATH_FALLBACK_KERNEL).into(), }) }, Err(e) => Err(e), } }
function_block-function_prefixed
[ { "content": "fn read_u16(s: &mut &[u8]) -> u16 {\n\n\tuse kernel::lib::byteorder::{ReadBytesExt,LittleEndian};\n\n\ts.read_u16::<LittleEndian>().unwrap()\n\n}\n", "file_path": "Kernel/Modules/fs_fat/on_disk.rs", "rank": 1, "score": 273544.45622170717 }, { "content": "/// Validates that a bu...
Rust
src/engine.rs
creativcoder/brainfcuk
4d9f70d18b8008657359755077ff6dfbbcf9a2f3
use std::collections::HashMap; use std::ascii::AsciiExt; use std::io::Read; #[derive(Debug)] pub enum IR { Sym(Instruction, usize), CntSym(usize, Instruction, usize), Eof } #[derive(Debug)] pub enum Instruction { MoveLeft, MoveRight, IncCell, DecCell, LBrace, RBrace, Stdout, ...
use std::collections::HashMap; use std::ascii::AsciiExt; use std::io::Read; #[derive(Debug)] pub enum IR { Sym(Instruction, usize), CntSym(usize, Instruction, usize), Eof } #[derive(Debug)] pub enum Instruction { MoveLeft, MoveRight, IncCell, DecCell, LBrace, RBrace, Stdout, ...
} } else { encoded.extend((current_cnt.to_string() + &first_sym.to_string()).chars()); } first_sym = a; current_cnt = 1; } } else { if current_cnt <= 2 || first_sym...
if a == first_sym { current_cnt += 1; } else { if current_cnt <= 2 || first_sym == '[' || first_sym == ']' { for _ in 0..current_cnt { encoded.push(first_sym);
function_block-random_span
[ { "content": "fn main() {\n\n if let Some(src) = env::args().skip(1).take(1).next() {\n\n let program = if let Ok(f) = fs::metadata(&src) {\n\n if f.is_file() {\n\n let mut s = String::new();\n\n let mut f = OpenOptions::new().read(true).open(&src).unwrap();\n\...
Rust
wheel/src/worker/sstable_uploader.rs
MrCroxx/RunKV
0770ce449363a98814c80e343a4e6e6a029e5f6b
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; use runkv_common::channel_pool::ChannelPool; use runkv_common::coding::CompressionAlgorithm; use runkv_common::Worker; use runkv_proto::manifest::SstableInfo; use runkv_proto::rudder::rudder_service...
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; use runkv_common::channel_pool::ChannelPool; use runkv_common::coding::CompressionAlgorithm; use runkv_common::Worker; use runkv_proto::manifest::SstableInfo; use runkv_proto::rudder::rudder_service...
fn gen_sstable_id(&self) -> u64 { let sequential_id = self.sstable_sequential_id.fetch_add(1, Ordering::SeqCst); (self.raft_node << 32) | sequential_id } }
Error::ManifestError(ManifestError::VersionDiffIdNotMatch( old, new, ))) = self.version_manager.update(version_diff, true).await { warn!( "version diff id not match, skip: [old: {}] [new: {}]", old, new ...
function_block-function_prefixed
[ { "content": "fn verify_no_duplication(mut iter: core::slice::Iter<u64>) -> bool {\n\n let mut unique = HashSet::new();\n\n iter.all(|v| unique.insert(*v))\n\n}\n", "file_path": "rudder/src/worker/compaction_detector.rs", "rank": 0, "score": 265443.33038124285 }, { "content": "/// Key ...
Rust
headers/src/header_components/mailbox.rs
PeterW-LWL/mail
f05836f227b44e7106d1360c7052356cd41ba361
use soft_ascii_string::SoftAsciiChar; use error::ComponentCreationError; use internals::encoder::{EncodableInHeader, EncodingWriter}; use internals::error::EncodingError; use {HeaderTryFrom, HeaderTryInto}; use super::Email; use super::Phrase; pub struct NoDisplayName; #[derive(Debug, Hash, Eq, PartialEq, Clone)] p...
use soft_ascii_string::SoftAsciiChar; use error::ComponentCreationError; use internals::encoder::{EncodableInHeader, EncodingWriter}; use internals::error::EncodingError; use {HeaderTryFrom, HeaderTryInto}; use super::Email; use super::Phrase; pub struct NoDisplayName; #[derive(Debug, Hash, Eq, PartialEq, Clone)] p...
!( mailbox, Mailbox { display_name: Some(Phrase::try_from("ay ya").unwrap()), email: Email::try_from("ab@cd").unwrap(), } ); } #[test] fn can_decide_to_not_generate_a_name() { let mai...
ents::{Email, Phrase}; ec_test! { email_only, { let email = Email::try_from( "affen@haus" )?; Mailbox::from(email) } => ascii => [ Text "<", MarkFWS, Text "affen", MarkFWS, Text "@", MarkFWS, Text "haus", MarkFWS, Text ">" ...
random
[ { "content": "fn encode_list<'a, I>(list_iter: I, handle: &mut EncodingWriter) -> Result<(), EncodingError>\n\nwhere\n\n I: Iterator<Item = &'a Mailbox>,\n\n{\n\n sep_for! { mailbox in list_iter;\n\n sep {\n\n handle.write_char( SoftAsciiChar::from_unchecked(',') )?;\n\n handl...
Rust
src/bindings.rs
thomashk0/softp-sys
0a899208d9a5593267137c4071a8b5300e042399
/* automatically generated by rust-bindgen */ pub type __int32_t = ::std::os::raw::c_int; pub type __uint32_t = ::std::os::raw::c_uint; pub type __int64_t = ::std::os::raw::c_long; pub type __uint64_t = ::std::os::raw::c_ulong; pub type int128_t = i128; pub type uint128_t = u128; pub const RoundingModeEnum_RM_RNE: Rou...
/* automatically generated by rust-bindgen */ pub type __int32_t = ::std::os::raw::c_int; pub type __uint32_t = ::std::os::raw::c_uint; pub type __int64_t = ::std::os::raw::c_long; pub type __uint64_t = ::std::os::raw::c_ulong; pub type int128_t = i128; pub type uint128_t = u128; pub const RoundingModeEnum_RM_RNE: Rou...
"C" { pub fn cvt_i64_sf64(a: i64, rm: RoundingModeEnum, pfflags: *mut u32) -> sfloat64; } extern "C" { pub fn cvt_u64_sf64(a: u64, rm: RoundingModeEnum, pfflags: *mut u32) -> sfloat64; } extern "C" { pub fn cvt_i128_sf64(a: int128_t, rm: RoundingModeEnum, pfflags: *mut u32) -> sfloat64; } extern "C" { ...
t; } extern "C" { pub fn cvt_i32_sf32(a: i32, rm: RoundingModeEnum, pfflags: *mut u32) -> sfloat32; } extern "C" { pub fn cvt_u32_sf32(a: u32, rm: RoundingModeEnum, pfflags: *mut u32) -> sfloat32; } extern "C" { pub fn cvt_i64_sf32(a: i64, rm: RoundingModeEnum, pfflags: *mut u32) -> sfloat32; } extern "C" {...
random
[ { "content": "pub fn main() {\n\n cc::Build::new()\n\n .files(&[\"softfp/softfp.c\"])\n\n .compile(\"softfp\");\n\n}\n", "file_path": "build.rs", "rank": 0, "score": 82729.09492821223 }, { "content": "sfloat32 fma_sf32(sfloat32 a, sfloat32 b, sfloat32 c, RoundingModeEnum rm,...
Rust
src/main.rs
ima9rd/carballrs
ac3d30394bb0e207acf76c64b7ff68b6c9cd1ae9
#[macro_use] extern crate serde_derive; extern crate glob; extern crate reqwest; extern crate serde_json; extern crate serde; extern crate version_compare; extern crate protoc_rust; extern crate protobuf; mod rattletrap; use std::collections::HashMap; use glob::glob; use std::fs::File; use std::io::BufReader; use s...
#[macro_use] extern crate serde_derive; extern crate glob; extern crate reqwest; extern crate serde_json; extern crate serde; extern crate version_compare; extern crate protoc_rust; extern crate protobuf; mod rattletrap; use std::collections::HashMap; use glob::glob; use std::fs::File; use std::io::BufReader; use s...
} commands } fn generate_protobuf() { let files = [ "api/game.proto", "api/metadata/camera_settings.proto", "api/metadata/game_metadata.proto", "api/metadata/mutators.proto", "api/metadata/player_loadout.proto", "api/party.proto", "api/player.proto",...
if suffix.contains("windows") { commands.insert("windows".to_owned(), file.to_owned() as String); } else if suffix.contains("linux") { commands.insert("linux".to_owned(), file.to_owned() as String); } else if suffix.contains("osx") { commands.insert("osx".to_owned(), ...
if_condition
[ { "content": "pub fn scan_dir(s: &str, files: &mut Vec<String>) {\n\n let dir: String = s.to_owned() + \"*\";\n\n for entry in glob(&dir).unwrap() {\n\n match entry {\n\n Ok(path) => {\n\n if path.extension().unwrap() != \"rs\" {\n\n files.push(path.to_s...
Rust
src/gui/mod.rs
tarkah/ajour
7afa05953c7c7536e638b405f333e4398b74e432
mod element; mod style; mod update; use crate::{ addon::{Addon, AddonState}, config::{load_config, Config, Flavor}, curse_api, error::ClientError, tukui_api, wowinterface_api, Result, }; use iced::{ button, pick_list, scrollable, Application, Column, Command, Container, Element, Length, Set...
mod element; mod style; mod update; use crate::{ addon::{Addon, AddonState}, config::{load_config, Config, Flavor}, curse_api, error::ClientError, tukui_api, wowinterface_api, Result, }; use iced::{ button, pick_list, scrollable, Application, Column, Command, Container, Element, Length, Set...
let space = Space::new(Length::Fill, Length::Units(10)); content = content.push(settings_container).push(space); } content = content .push(addon_row_titles) .push(addons_scrollable) .push(bottom_space) ...
let settings_container = element::settings_container( &mut self.directory_button_state, &mut self.flavor_list_state, &self.config, );
assignment_statement
[ { "content": "pub fn handle_message(ajour: &mut Ajour, message: Message) -> Result<Command<Message>> {\n\n match message {\n\n Message::Parse(Ok(config)) => {\n\n // When we have the config, we parse the addon directory\n\n // which is provided by the config.\n\n ajour...
Rust
zluda/src/impl/mod.rs
Massendefekt/ZLUDA
897fbcbdb8acf7fbb4d9a42227fb7da0cf825eac
use crate::{ cuda::{CUctx_st, CUdevice, CUdeviceptr, CUfunc_st, CUmod_st, CUresult, CUstream_st}, r#impl::device::Device, }; use std::{ ffi::c_void, mem::{self, ManuallyDrop}, os::raw::c_int, ptr, sync::Mutex, sync::TryLockError, }; #[cfg(test)] #[macro_use] pub mod test; pub mod contex...
use crate::{ cuda::{CUctx_st, CUdevice, CUdeviceptr, CUfunc_st, CUmod_st, CUresult, CUstream_st}, r#impl::device::Device, }; use std::{ ffi::c_void, mem::{self, ManuallyDrop}, os::raw::c_int, ptr, sync::Mutex, sync::TryLockError, }; #[cfg(test)] #[macro_use] pub mod test; pub mod contex...
pub fn as_result(&self) -> Result<&T, CUresult> { if self.cookie == T::COOKIE { Ok(&self.data) } else { Err(T::LIVENESS_FAIL) } } pub fn as_result_mut(&mut self) -> Result<&mut T, CUresult> { if self.cookie == T::COOKIE { Ok(&mut self.da...
pub fn as_option_mut(&mut self) -> Option<&mut T> { if self.cookie == T::COOKIE { Some(&mut self.data) } else { None } }
function_block-full_function
[ { "content": "pub fn free_v2(ptr: *mut c_void) -> Result<(), CUresult> {\n\n GlobalState::lock_current_context(|ctx| {\n\n let dev = unsafe { &mut *ctx.device };\n\n Ok::<_, CUresult>(unsafe { dev.l0_context.mem_free(ptr) }?)\n\n })\n\n .map_err(|_| CUresult::CUDA_ERROR_INVALID_VALUE)?\n\...
Rust
src/powers/power.rs
victorinno/animeclashers
ce5c2d6fb87a1fa888236e074f081a06159bbaf8
use serde::{Deserialize, Serialize}; use std::cmp::Ordering; use wasm_bindgen::prelude::*; use web_sys::Storage; use web_sys::Window; #[wasm_bindgen] #[derive(Serialize, Deserialize, Debug, Clone, Eq)] pub enum PowerType { Normal, Precise, Brute, } impl PartialEq for PowerType { fn eq(&self, other: &S...
use serde::{Deserialize, Serialize}; use std::cmp::Ordering; use wasm_bindgen::prelude::*; use web_sys::Storage; use web_sys::Window; #[wasm_bindgen] #[derive(Serialize, Deserialize, Debug, Clone, Eq)] pub enum PowerType { Normal, Precise, Brute, } impl PartialEq for PowerType { fn eq(&self, other: &S...
#[wasm_bindgen(getter)] pub fn name(&self) -> String { self.name.clone() } #[wasm_bindgen(setter)] pub fn set_name(&mut self, name: String) { self.name = name; } #[wasm_bindgen(getter)] pub fn power_type(&self) -> PowerType { self.power_type.clone() } #...
pub fn create( name: String, level: usize, power_type: PowerType, power_action: PowerAction, clasher_id: String, ) -> Power { let power: Power = Power { name, level, potency: Power::define_potency(&power_type), precision...
function_block-function_prefixed
[ { "content": "#[wasm_bindgen]\n\npub fn greet() {\n\n alert(\"Hello, anime-clashers!\");\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 66742.84851784013 }, { "content": "#[wasm_bindgen]\n\npub fn init() {\n\n utils::set_panic_hook();\n\n}\n", "file_path": "src/lib.rs...
Rust
binary-oracle-pair/program/src/instruction.rs
biw/solana-program-library
5611ad8bd595d9e3666f8b115cd28f8116038645
use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ clock::Slot, instruction::{AccountMeta, Instruction}, program_error::ProgramError, pubkey::Pubkey, sysvar, }; #[repr(C)] #[derive(BorshSerialize, BorshDeserialize, PartialEq, Debug, Clone)] pub struct InitArgs { pub min...
use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ clock::Slot, instruction::{AccountMeta, Instruction}, program_error::ProgramError, pubkey::Pubkey, sysvar, }; #[repr(C)] #[derive(BorshSerialize, BorshDeserialize, PartialEq, Debug, Clone)] pub struct InitArgs { pub min...
#[allow(clippy::too_many_arguments)] pub fn deposit( program_id: &Pubkey, pool: &Pubkey, authority: &Pubkey, user_transfer_authority: &Pubkey, user_token_account: &Pubkey, pool_deposit_token_account: &Pubkey, token_pass_mint: &Pubkey, token_fail_mint: &Pubkey, token_pass_destinatio...
pub fn init_pool( program_id: &Pubkey, pool: &Pubkey, authority: &Pubkey, decider: &Pubkey, deposit_token_mint: &Pubkey, deposit_account: &Pubkey, token_pass_mint: &Pubkey, token_fail_mint: &Pubkey, token_program_id: &Pubkey, init_args: InitArgs, ) -> Result<Instruction, ProgramE...
function_block-full_function
[ { "content": "/// Instruction processor\n\npub fn process_instruction(\n\n _program_id: &Pubkey,\n\n accounts: &[AccountInfo],\n\n _instruction_data: &[u8],\n\n) -> ProgramResult {\n\n // Create in iterator to safety reference accounts in the slice\n\n let account_info_iter = &mut accounts.iter()...
Rust
kalloc/src/rawlist.rs
Tan-YiFan/plan
7a51a9cc38ce178fa83f16486a1f63c92571be36
#[derive(Copy, Clone, Debug)] #[repr(C)] pub struct Rawlist { pub prev: *mut Rawlist, pub next: *mut Rawlist, } impl Rawlist { pub unsafe fn init(p: *mut Self) { (*p).prev = p; (*p).next = p; } pub unsafe fn is_empty(head: *mut Self) -> bool { (*head).next == head } ...
#[derive(Copy, Clone, Debug)] #[repr(C)] pub struct Rawlist { pub prev: *mut Rawlist, pub next: *mut Rawlist, } impl Rawlist { pub unsafe fn init(p: *mut Self) { (*p).prev = p; (*p).next = p; } pub unsafe fn is_empty(head: *mut Self) -> bool { (*head).next == head } ...
ert_eq!(p, &mut item[N - 1 - i] as *mut Rawlist); } assert_eq!(Rawlist::is_empty(&mut head), true); } } }
false); assert_eq!(Rawlist::front(&mut head), &mut item[i] as *mut Rawlist); assert_eq!(Rawlist::back(&mut head), &mut item[0] as *mut Rawlist); } for i in 0..N { assert_eq!(Rawlist::is_empty(&mut head), false); assert_eq!( ...
random
[ { "content": "#[inline]\n\npub fn round_up(x: usize, n: usize) -> usize {\n\n round_down(x + n - 1, n)\n\n}\n\n\n\n/// Check if two ranges are intersect with each other.\n", "file_path": "kcore/src/utils.rs", "rank": 0, "score": 163562.34762216697 }, { "content": "#[inline]\n\npub fn roun...
Rust
day4/src/main.rs
ArcticPheenix/AOC2020
75d2625dc32a6fc521142c99f0566ac46941b879
use std::fs::File; use std::io::{BufRead, BufReader}; use regex::Regex; #[derive(Clone, Debug)] struct Passport { byr: String, iyr: String, eyr: String, hgt: String, hcl: String, ecl: String, pid: String, cid: String } impl Passport { fn is_valid(&self) -> bool { l...
use std::fs::File; use std::io::{BufRead, BufReader}; use regex::Regex; #[derive(Clone, Debug)] struct Passport { byr: String, iyr: String, eyr: String, hgt: String, hcl: String, ecl: String, pid: String, cid: String } impl Passport { fn is_valid(&self) -> bool { l...
fn new() -> Self { Passport { byr: "".to_string(), iyr: "".to_string(), eyr: "".to_string(), hgt: "".to_string(), hcl: "".to_string(), ecl: "".to_string(), pid: "".to_string(), cid: "".to_string() } ...
t.split("in").collect(); hgt_in = hgt[0].parse().unwrap(); } let mut byr_valid = { self.byr != "".to_string() && year_re.is_match(&self.byr) }; if byr_valid { let byr: i32 = self.byr.parse().unwrap(); if byr >= byr_min...
function_block-function_prefixed
[ { "content": "fn compare_new(min: i32, max: i32, character: String, password: String) -> bool {\n\n let mut c: char = '-';\n\n for ch in character.chars() {\n\n c = ch;\n\n }\n\n let min = min as usize;\n\n let max = max as usize;\n\n let password_min = password.chars().nth(min - 1).unw...
Rust
src/types/s2k.rs
adrianheine/rpgp
070196d00b5299d33bb2575fe1e6d765a5444cf7
use std::io; use nom::be_u8; use num_traits::FromPrimitive; use rand::{CryptoRng, Rng}; use crate::crypto::hash::HashAlgorithm; use crate::errors::Result; use crate::ser::Serialize; const EXPBIAS: u32 = 6; #[derive(Debug, Clone, PartialEq, Eq)] pub struct StringToKey { typ: StringToKeyType, hash: HashAlgori...
use std::io; use nom::be_u8; use num_traits::FromPrimitive; use rand::{CryptoRng, Rng}; use crate::crypto::hash::HashAlgorithm; use crate::errors::Result; use crate::ser::Serialize; const EXPBIAS: u32 = 6; #[derive(Debug, Clone, PartialEq, Eq)] pub struct StringToKey { typ: StringToKeyType, hash: HashAlgori...
} #[repr(u8)] #[derive(Debug, PartialEq, Eq, Copy, Clone, FromPrimitive)] pub enum StringToKeyType { Simple = 0, Salted = 1, Reserved = 2, IteratedAndSalted = 3, Private100 = 100, Private101 = 101, Private102 = 102, Private103 = 103, Private104 = 104, Private105 = 105, Priv...
pub fn derive_key(&self, passphrase: &str, key_size: usize) -> Result<Vec<u8>> { let digest_size = self.hash.digest_size(); let rounds = (key_size as f32 / digest_size as f32).ceil() as usize; let mut key = Vec::with_capacity(key_size); for round in 0..rounds { let mut hash...
function_block-full_function
[ { "content": "/// Generate an ECDH KeyPair.\n\n/// Currently only support ED25519.\n\npub fn generate_key<R: Rng + CryptoRng>(rng: &mut R) -> (PublicParams, PlainSecretParams) {\n\n let secret = StaticSecret::new(rng);\n\n let public = PublicKey::from(&secret);\n\n\n\n // public key\n\n let mut p = ...
Rust
air/src/execution_step/execution_context/context.rs
fluencelabs/aquamarine
18f4c0036fad9bbdc503e4da3e466fea54f7481d
/* * Copyright 2020 Fluence Labs Limited * * 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 a...
/* * Copyright 2020 Fluence Labs Limited * * 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 a...
pub(crate) fn last_error(&self) -> LastErrorWithTetraplet { match &self.last_error { Some(error_descriptor) => LastErrorWithTetraplet::from_error_descriptor(error_descriptor, self), None => <_>::default(), } } pub(crate) fn next_call_request_id(&mut self) -> u32 { ...
pub(crate) fn new( current_peer_id: String, init_peer_id: String, call_results: CallResults, last_call_request_id: u32, ) -> Self { let current_peer_id = Rc::new(current_peer_id); Self { current_peer_id, init_peer_id, subtree_compl...
function_block-full_function
[ { "content": "pub fn stream_string(result: impl Into<String>, generation: u32) -> ExecutedState {\n\n let result = JValue::String(result.into());\n\n let value = Rc::new(result);\n\n\n\n ExecutedState::Call(CallResult::executed_stream(value, generation))\n\n}\n\n\n", "file_path": "crates/air-lib/te...
Rust
src/kernel/algorithms/approximation.rs
WeirdConstructor/Fornjot
dff74745e4a329eed1fd0438001adb25c3ea8e0d
use std::collections::HashSet; use crate::{ kernel::topology::{ edges::{Cycle, Edge}, faces::Face, vertices::Vertex, }, math::{Point, Scalar, Segment}, }; #[derive(Debug, PartialEq)] pub struct Approximation { pub points: HashSet<Point<3>>, ...
use std::collections::HashSet; use crate::{ kernel::topology::{ edges::{Cycle, Edge}, faces::Face, vertices::Vertex, }, math::{Point, Scalar, Segment}, }; #[derive(Debug, PartialEq)] pub struct Approximation { pub points: HashSet<Point<3>>, ...
#[test] fn for_cycle() { let tolerance = Scalar::ONE; let mut shape = Shape::new(); let a = Point::from([1., 2., 3.]); let b = Point::from([2., 3., 5.]); let c = Point::from([3., 5., 8.]); let v1 = shape.vertices().create(a); let v2 = shape.vertices()...
Segment::from([b, c]), Segment::from([c, d]), ], } ); assert_eq!( approximate_edge(points, None), Approximation { points: set![b, c], segments: set![Segment::from([b, c]), Segment::from([c, ...
function_block-function_prefix_line
[ { "content": "type VerticesInner = KdTree<Scalar, HandleInner<Point<3>>, 3>;\n", "file_path": "src/kernel/shape/mod.rs", "rank": 0, "score": 184866.36835071034 }, { "content": "/// Create a new shape that is a transformed version of an existing one\n\n///\n\n/// # Implementation note\n\n///\...
Rust
src/collision.rs
several-unforgettable-devs/gg
467ea8fb7b4301bf66931ac073860288c0c920f4
use bevy::prelude::*; use crate::audio::*; use crate::cooldown::*; use crate::velocity::*; use crate::explosion::ExplosionEvent; pub use crate::EntityType; use crate::GameState; #[derive(Clone, Copy, PartialEq)] pub struct Collision { pub mass: f32, pub radius: f32, pub etype: EntityType, } const COLLISI...
use bevy::prelude::*; use crate::audio::*; use crate::cooldown::*; use crate::velocity::*; use crate::explosion::ExplosionEvent; pub use crate::EntityType; use crate::GameState; #[derive(Clone, Copy, PartialEq)] pub struct Collision { pub mass: f32, pub radius: f32, pub etype: EntityType, } const COLLISI...
} (EntityType::Alien, EntityType::Player) => { let relative_velocity = obj1.velocity - obj2.velocity; let relative_speed_squared = relative_velocity.length_squared(); if relative_speed_squared > LETHAL_RELATIVE_VELOCITY_OF_ASTEROID_SQUARED { play_sou...
if relative_speed_squared > LETHAL_RELATIVE_VELOCITY_OF_BULLET_SQUARED { play_sound(asset_server, audio, "audio/SpaceshipCrash2.mp3"); commands.despawn(obj1.entity); commands.despawn(obj2.entity); expl_events.send(ExplosionEvent::new(obj2.position, obj2.ve...
if_condition
[ { "content": "#[allow(dead_code)]\n\npub fn change_text_system(mut query: Query<(&mut Text, &TextChanges)>) {\n\n for (mut text, _text_changes) in query.iter_mut() {\n\n text.value = format!(\n\n \"This text changes in the bottom right {}\",\n\n rand::random::<u16>(),\n\n ...
Rust
lunch-list-backend/src/auth/claims.rs
Olavhaasie/lunch-list
308dee988d9a63bcc57f1197968f620f9eeaf7a7
use actix_web::{dev, http::HeaderMap, FromRequest, HttpRequest}; use chrono::{Duration, Utc}; use futures::future::{err, ok, Ready}; use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::errors::ServiceError; const TOKEN_ISSUER: &str = ...
use actix_web::{dev, http::HeaderMap, FromRequest, HttpRequest}; use chrono::{Duration, Utc}; use futures::future::{err, ok, Ready}; use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::errors::ServiceError; const TOKEN_ISSUER: &str = ...
}
fn from_request(req: &HttpRequest, _: &mut dev::Payload) -> Self::Future { let token = match get_bearer_token(req.headers()) { Ok(token) => token, Err(e) => return err(e), }; let config = match req .app_data::<Self::Config>() .ok_or(ServiceError::...
function_block-full_function
[ { "content": "/// Returns true when the username is a valid username, false otherwise.\n\nfn validate_username(username: &str) -> Result<(), ValidationError> {\n\n let valid = username.chars().all(|c| c.is_alphanumeric() || c == ' ');\n\n if valid {\n\n Ok(())\n\n } else {\n\n Err(Validat...
Rust
src/gui/edit_window.rs
rmed/receipt-keeper
f9bd9bcd747875257eebe3060fd3615668d35675
use std::cell::RefCell; use std::os::raw::{c_int, c_double}; use std::rc::Rc; use chrono::NaiveDate; use glib; use gtk; use gtk::prelude::*; use gtk::{ Application, ApplicationWindow, Builder, Box, ButtonsType, Dialog, DialogFlags, MessageType, Revealer, Window, WindowPosi...
use std::cell::RefCell; use std::os::raw::{c_int, c_double}; use std::rc::Rc; use chrono::NaiveDate; use glib; use gtk; use gtk::prelude::*; use gtk::{ Application, ApplicationWindow, Builder, Box, ButtonsType, Dialog, DialogFlags, MessageType, Revealer, Window, WindowPosi...
pub fn create_window(app: &Application, state: &Rc<RefCell<State>>, receipt_id: i32) -> ApplicationWindow { let mut title = ""; let mut is_modal = false; let receipt: Receipt; if receipt_id >= 0 { title = "Edit receipt"; receipt = db::get_receipt(state.borrow().db_...
function_block-full_function
[ { "content": "/// Refresh the receipt table\n\n///\n\n/// This is usually done when adding or editing a receipt\n\npub fn refresh_table() -> glib::Continue {\n\n REFRESH.with(move |r| {\n\n if let Some((ref builder, ref db_path)) = *r.borrow() {\n\n let store_table: ListStore = builder.get_...
Rust
rclrust/src/client/mod.rs
HarukiUchito/rclrust
a00c65daa837ff72e437f17516705725c807a8c3
use std::{ collections::HashMap, sync::{Arc, Mutex}, thread, time::Duration, }; use anyhow::Result; use futures::channel::{mpsc, oneshot}; use rclrust_msg::_core::{FFIToRust, ServiceResponseRaw, ServiceT}; use crate::{ internal::worker::{ReceiveWorker, WorkerMessage}, node::Node, qos::Qo...
use std::{ collections::HashMap, sync::{Arc, Mutex}, thread, time::Duration, }; use anyhow::Result; use futures::channel::{mpsc, oneshot}; use rclrust_msg::_core::{FFIToRust, ServiceResponseRaw, ServiceT}; use crate::{ internal::worker::{ReceiveWorker, WorkerMessage}, node::Node, qos::Qo...
pub fn is_valid(&self) -> bool { self.handle.is_valid() } pub fn service_is_available(&self) -> Result<bool> { self.handle.service_is_available() } ...
r: ReceiveWorker<ChannelMessage<Srv>>, pendings: Arc<Mutex<HashMap<i64, oneshot::Sender<Srv::Response>>>>, } impl<Srv> Client<Srv> where Srv: ServiceT, { pub(crate) fn new(node: &Node, service_name: &str, qos: &QoSProfile) -> Result<Self> { let handle = Arc::new(RclClient::new::<Srv>( n...
random
[ { "content": "type ChannelMessage<Srv> = (\n\n rcl_sys::rmw_request_id_t,\n\n <<Srv as ServiceT>::Request as MessageT>::Raw,\n\n);\n\n\n\n/// Service server\n\npub struct Service<Srv>\n\nwhere\n\n Srv: ServiceT,\n\n{\n\n handle: Arc<RclService>,\n\n worker: ReceiveWorker<ChannelMessage<Srv>>,\n\n...
Rust
src/libos/src/net/io_multiplexing/epoll.rs
yuhui790/occlum
ed7f83562a30689ac29c105dbc5d1334df5a7c76
use super::*; #[derive(Debug, Copy, Clone)] pub enum EpollCtlCmd { Add = 1, Del = 2, Mod = 3, } impl TryFrom<i32> for EpollCtlCmd { type Error = error::Error; fn try_from(op_num: i32) -> Result<Self> { match op_num { 1 => Ok(EpollCtlCmd::Add), 2 => O...
use super::*; #[derive(Debug, Copy, Clone)] pub enum EpollCtlCmd { Add = 1, Del = 2, Mod = 3, } impl TryFrom<i32> for EpollCtlCmd { type Error = error::Error; fn try_from(op_num: i32) -> Result<Self> { match op_num { 1 => Ok(EpollCtlCmd::Add), 2 => O...
let raw_epevent_ptr: *mut libc::epoll_event = match event { Some(epevent) => { &mut epevent.to_raw() } _ => std::ptr::null_mut(), }; try_libc!(libc::ocall::epoll...
let host_fd = { let fd_ref = current!().file(fd)?; if let Ok(socket) = fd_ref.as_socket() { socket.fd() } else if let Ok(eventfd) = fd_ref.as_event() { eventfd.get_host_fd() } else { return_errno!(EPERM, "unsupported file ty...
assignment_statement
[ { "content": "pub fn do_openat(dirfd: i32, path: *const i8, flags: u32, mode: u32) -> Result<isize> {\n\n let dirfd = DirFd::from_i32(dirfd)?;\n\n let path = from_user::clone_cstring_safely(path)?\n\n .to_string_lossy()\n\n .into_owned();\n\n let fd = file_ops::do_openat(dirfd, &path, fla...
Rust
day25/src/main.rs
lucaswerkmeister/advent-of-code-2020
3505da8b597854ada0998a0303c2a8053c25f3be
use std::error::Error; use std::fmt; use std::fs; use std::num::ParseIntError; #[derive(Clone, Debug, Eq, PartialEq)] enum ParseSystemError { NoFirstLine, BadFirstLine(ParseIntError), NoSecondLine, BadSecondLine(ParseIntError), ExtraLine, } impl fmt::Display for ParseSystemError { fn fmt(&self...
use std::error::Error; use std::fmt; use std::fs; use std::num::ParseIntError; #[derive(Clone, Debug, Eq, PartialEq)] enum ParseSystemError { NoFirstLine, BadFirstLine(ParseIntError), NoSecondLine, BadSecondLine(ParseIntError), ExtraLine, } impl fmt::Display for ParseSystemError { fn fmt(&self...
} panic!("could not find any matching private key"); } } impl PartialEq for System { fn eq(&self, other: &Self) -> bool { self.public_key_1 == other.public_key_1 && self.public_key_2 == other.public_key_2 && self.shared_key == other.shared_key && sel...
if public_key_1 as u32 == self.public_key_1 { let private_key_1 = private_key_1 as u32; return Self { private_key_1: Some(private_key_1), public_key_1: self.public_key_1, private_key_2: None, public_key_2: se...
if_condition
[ { "content": "fn part2(filename: &str) -> u64 {\n\n let input = fs::read_to_string(filename).expect(\"read input file\");\n\n let line2 = input.lines().skip(1).next().expect(\"get second line\");\n\n let mut departures_by_offset = HashMap::new();\n\n let mut offsets_by_departure = HashMap::new();\n\...
Rust
src/dispatcher.rs
presciense/actix-mqtt
8a82f3786e34a82c3f6d63aff5601ba9fffa8ea7
use std::future::Future; use std::marker::PhantomData; use std::pin::Pin; use std::rc::Rc; use std::task::{Context, Poll}; use std::time::Duration; use actix_ioframe as ioframe; use actix_service::{boxed, fn_factory_with_config, pipeline, Service, ServiceFactory}; use actix_utils::inflight::InFlightService; use actix_...
use std::future::Future; use std::marker::PhantomData; use std::pin::Pin; use std::rc::Rc; use std::task::{Context, Poll}; use std::time::Duration; use actix_ioframe as ioframe; use actix_service::{boxed, fn_factory_with_config, pipeline, Service, ServiceFactory}; use actix_utils::inflight::InFlightService; use actix_...
cket { mqtt::Packet::PingRequest => { Either::Left(Either::Left(ok(Some(mqtt::Packet::PingResponse)))) } mqtt::Packet::Disconnect => Either::Left(Either::Left(ok(None))), mqtt::Packet::Publish(publish) => { let packet_id = publish.packet_id...
:cell::Cell; use crate::error::MqttError; use crate::publish::Publish; use crate::sink::MqttSink; use crate::subs::{Subscribe, SubscribeResult, Unsubscribe}; pub(crate) struct MqttState<St> { inner: Cell<MqttStateInner<St>>, } struct MqttStateInner<St> { pub(crate) st: St, pub(crate) sink: MqttSink, } im...
random
[ { "content": "type HandlerService<S, E> = BoxService<Publish<S>, (), E>;\n\n\n\n/// Router - structure that follows the builder pattern\n\n/// for building publish packet router instances for mqtt server.\n\npub struct Router<S, E> {\n\n router: RouterBuilder<usize>,\n\n handlers: Vec<Handler<S, E>>,\n\n ...
Rust
rust/benches/car_benchmark.rs
xdmiodz/simple-binary-encoding
7f4af10bce63da68b4aad4980b222df0edc935d5
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use examples_uk_co_real_logic_sbe_benchmarks::*; const MANUFACTURER: &[u8] = b"MANUFACTURER"; const MODEL: &[u8] = b"MODEL"; struct State { buffer: Vec<u8>, } pub fn car_encode_benchmark(c: &mut Criterion) { let mut state = State { ...
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use examples_uk_co_real_logic_sbe_benchmarks::*; const MANUFACTURER: &[u8] = b"MANUFACTURER"; const MODEL: &[u8] = b"MODEL"; struct State { buffer: Vec<u8>, } pub fn car_encode_benchmark(c: &mut Criterion) { let mut state = State { ...
pub fn car_decode_benchmark(c: &mut Criterion) { let mut state = State { buffer: vec![0u8; 1024], }; let encoded_len = encode(&mut state).unwrap(); c.bench_function("decode car", |b| { b.iter(|| { let decoded_len = decode(black_box(&state)).unwrap(); assert_eq!...
fn encode(state: &mut State) -> SbeResult<usize> { let buffer = state.buffer.as_mut_slice(); let mut car = CarEncoder::default(); let mut fuel_figures = FuelFiguresEncoder::default(); let mut performance_figures = PerformanceFiguresEncoder::default(); let mut acceleration = AccelerationEncoder::defa...
function_block-full_function
[ { "content": "pub fn md_decode_benchmark(c: &mut Criterion) {\n\n let mut state = State {\n\n buffer: vec![0u8; 1024],\n\n };\n\n let encoded_len = encode_md(&mut state).unwrap();\n\n\n\n c.bench_function(\"decode md\", |b| {\n\n b.iter(|| {\n\n let decoded_len = decode_md(b...
Rust
src/compiler.rs
sollyucko/reflect
f513d632aa5511e003eb3d210a3ad2c3d336f5a4
use crate::ident::Ident; use crate::{ Function, GlobalBorrow, InvokeRef, MacroInvokeRef, Parent, Print, Receiver, SimplePath, TraitInferenceResult, TypeNode, ValueNode, ValueRef, INVOKES, MACROS, VALUES, }; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use ref_cast::RefCast; use std::colle...
use crate::ident::Ident; use crate::{ Function, GlobalBorrow, InvokeRef, MacroInvokeRef, Parent, Print, Receiver, SimplePath, TraitInferenceResult, TypeNode, ValueNode, ValueRef, INVOKES, MACROS, VALUES, }; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use ref_cast::RefCast; use std::colle...
} fn receiver_tokens(receiver: Receiver) -> Option<TokenStream> { match receiver { Receiver::NoSelf => None, Receiver::SelfByValue => Some(quote!(self)), Receiver::SelfByReference { is_mut, lifetime } if !is_mut => { let lifetime = lifetime .0 .a...
VALUES.with_borrow(|values| { let values = values_refs.iter().map(|value| match &values[value.0] { node if node.inlineable() => self.compile_value(*value), _ => value.binding().to_token_stream(), }); quote! { #(#values),* } }) }
function_block-function_prefix_line
[ { "content": "#[proc_macro]\n\npub fn library(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as Input);\n\n\n\n let modules = input.crates.iter().map(declare_mod);\n\n\n\n TokenStream::from(quote! {\n\n #[allow(non_snake_case)]\n\n mod RUNTIME {\n\n ...
Rust
examples/jezzball/main_layer.rs
Antonio-Bennett/scion
aeb6c6a70cb257bf8462e299af3bf9bf381c8888
use std::fmt::{Display, Formatter}; use rand::{thread_rng, Rng}; use scion::{ core::{ components::{ material::Material, maths::{ collider::{Collider, ColliderMask, ColliderType}, transform::Transform, }, tiles::{sprite::Sprite,...
use std::fmt::{Display, Formatter}; use rand::{thread_rng, Rng}; use scion::{ core::{ components::{ material::Material, maths::{ collider::{Collider, ColliderMask, ColliderType}, transform::Transform, }, tiles::{sprite::Sprite,...
fn add_border(world: &mut World) { world.push(( Transform::from_xy(2.0, 0.), Collider::new( ColliderMask::Custom("BORDER_TOP".to_string()), vec![ColliderMask::None], ColliderType::Rectangle(1104, 10), ), )); world.push(( Transform::from_xy...
function_block-full_function
[ { "content": "pub fn try_debug(world: &mut World, resources: &mut Resources) {\n\n resources.inputs().keyboard().on_key_pressed(KeyCode::P, || {\n\n let mut query = <Entity>::query();\n\n let v: Vec<Entity> = query.iter(world).map(|e| *e).collect();\n\n v.iter().for_each(|e| {\n\n ...