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
tests/test_no_warnings/build.rs
SimonSapin/gl-rs
036bdec1f42d34e81c9178d3a0be575a5882ca22
extern crate gl_generator; use gl_generator::*; use std::env; use std::fs::File; use std::io::prelude::*; use std::path::*; fn main() { let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&dest).join("test_no_warnings.rs")).unwrap(); let gl_registry = Registry::new(Api...
extern crate gl_generator; use gl_generator::*; use std::env; use std::fs::File; use std::io::prelude::*; use std::path::*; fn main() { let dest = env::var("OUT_DIR").unwrap(); let mut file = File::create(&Path::new(&dest).join("test_no_warnings.rs")).unwrap(); let gl_registry = Registry::new(Api...
(StaticStructGenerator, &mut file) .unwrap(); writeln!(&mut file, "}}").unwrap(); writeln!(&mut file, "mod egl_debug_struct {{ {}", build_egl_symbols()).unwrap(); egl_registry .write_bindings(DebugStructGenerator, &mut file) .unwrap(); writeln!(&mut file, "}}").unwrap(); } fn b...
nerator, &mut file) .unwrap(); writeln!(&mut file, "}}").unwrap(); writeln!(&mut file, "mod egl_static {{ {}", build_egl_symbols()).unwrap(); egl_registry .write_bindings(StaticGenerator, &mut file) .unwrap(); writeln!(&mut file, "}}").unwrap(); writeln!(&mut file, "mod egl...
function_block-random_span
[ { "content": "/// Creates one module for each GL command.\n\n///\n\n/// Each module contains `is_loaded` and `load_with` which interact with the `storage` module\n\n/// created by `write_ptrs`.\n\nfn write_fn_mods<W>(registry: &Registry, dest: &mut W) -> io::Result<()>\n\n where W: io::Write\n\n{\n\n for...
Rust
src/components.rs
cowboy8625/bevy_crossterm
9c9fe7c195e007b41e9b03bfecc22715dc329929
use bevy::prelude::*; use bevy::reflect::TypeUuid; use bevy::utils::{HashMap, HashSet}; use serde::{Deserialize, Serialize}; use std::default::Default; use unicode_segmentation::UnicodeSegmentation; pub use crossterm::style::Color; #[derive(Default)] pub(crate) struct PreviousEntityDetails(pub HashMap<Entity, (Previo...
use bevy::prelude::*; use bevy::reflect::TypeUuid; use bevy::utils::{HashMap, HashSet}; use serde::{Deserialize, Serialize}; use std::default::Default; use unicode_segmentation::UnicodeSegmentation; pub use crossterm::style::Color; #[derive(Default)] pub(crate) struct PreviousEntityDetails(pub HashMap<Entity, (Previo...
term::style::Attribute::Reset.into(), colors: Colors::default(), } } } #[derive(Default, Serialize, Deserialize, PartialEq, Eq, TypeUuid)] #[uuid = "a5418d12-e050-498a-a31e-37fd0b6c078d"] pub struct StyleMap { pub style: Style, pub map: Vec<Vec<Style>>, } impl StyleMap { pub fn new...
lizer.serialize_u32(attr_bits) } struct AttrVisitor; impl<'de> Visitor<'de> for AttrVisitor { type Value = crossterm::style::Attributes; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("expecting an u32") } fn...
random
[]
Rust
src/blockcipher/mod.rs
stevenhorsman/ocicrypt-rs
32dac715ff3d1cfbc817efba0904bdc5194c88d6
use anyhow::{anyhow, Result}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use std::collections::HashMap; use std::io::Read; extern crate base64; extern crate base64_serde; use base64_serde::base64_serde_type; pub mod aes_ctr; use aes_ctr::AESCTRBlockCipher; pub type LayerCipherType = String; ...
use anyhow::{anyhow, Result}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use std::collections::HashMap; use std::io::Read; extern crate base64; extern crate base64_serde; use base64_serde::base64_serde_type; pub mod aes_ctr; use aes_ctr::AESCTRBlockCipher; pub type LayerCipherType = String; ...
} pub trait LayerBlockCipher<R: Read> { fn generate_key(&self) -> Result<Vec<u8>>; fn encrypt(&mut self, input: R, opts: &mut LayerBlockCipherOptions) -> Result<()>; fn decrypt(&mut self, input: R, opts: &mut LayerBlockCipherOptions) -> Result<()>; } pub trait Finalizer { fn fin...
e .cipher_options .get(&key) .map(|value| value.to_vec()), } }
function_block-function_prefixed
[ { "content": "#[allow(clippy::borrowed_box)]\n\npub fn get_key_wrapper(scheme: &str) -> Result<&Box<dyn KeyWrapper>> {\n\n KEY_WRAPPERS\n\n .get(scheme)\n\n .ok_or_else(|| anyhow!(\"key wrapper not supported!\"))\n\n}\n\n\n", "file_path": "src/encryption.rs", "rank": 1, "score": 156...
Rust
pallets/xtransfer/src/assets_wrapper.rs
MSghais/khala-parachain
f456c273867e392bb4801680159e7ac074b177b0
pub use self::pallet::*; #[allow(unused_variables)] #[frame_support::pallet] pub mod pallet { use codec::{Decode, Encode}; use frame_support::{ dispatch::DispatchResult, pallet_prelude::*, traits::StorageVersion, transactional, }; use frame_system::pallet_prelude::*; use scale_info::TypeInfo; use sp_runtime::t...
pub use self::pallet::*; #[allow(unused_variables)] #[frame_support::pallet] pub mod pallet { use codec::{Decode, Encode}; use frame_support::{ dispatch::DispatchResult, pallet_prelude::*, traits::StorageVersion, transactional, }; use frame_system::pallet_prelude::*; use scale_info::TypeInfo; use sp_runtime::t...
) { info.enabled_bridges.remove(idx); } RegistryInfoByIds::<T>::insert(&asset_id, &info); Self::deposit_event(Event::ChainbridgeDisabled { asset_id, chain_id, resource_id, }); Ok(()) } } pub trait GetAssetRegistryInfo<AssetId> { fn id(asset: &XTransferAsset) -> Option<AssetId>; ...
match item.config { XBridgeConfig::ChainBridge { chain_id: cid, resource_id: rid, .. } => cid == chain_id && rid == resource_id, _ => false, }
if_condition
[ { "content": "// Checks events against the latest. A contiguous set of events must be provided. They must\n\n// include the most recent event, but do not have to include every past event.\n\npub fn assert_events(mut expected: Vec<Event>) {\n\n\tlet mut actual: Vec<Event> = system::Pallet::<Test>::events()\n\n\t...
Rust
netlink-packet-generic/src/ctrl/nlas/policy.rs
cathay4t/netlink
ee9bad4bfd4f63a69f433ecb1330c05f312c1282
use crate::constants::*; use anyhow::Context; use byteorder::{ByteOrder, NativeEndian}; use netlink_packet_utils::{ nla::{Nla, NlaBuffer, NlasIterator}, parsers::*, traits::*, DecodeError, }; use std::{ convert::TryFrom, mem::{size_of, size_of_val}, }; #[derive(Clone, Debug, PartialEq, Eq)] pub...
use crate::constants::*; use anyhow::Context; use byteorder::{ByteOrder, NativeEndian}; use netlink_packet_utils::{ nla::{Nla, NlaBuffer, NlasIterator}, parsers::*, traits::*, DecodeError, }; use std::{ convert::TryFrom, mem::{size_of, size_of_val}, }; #[derive(Clone, Debug, PartialEq, Eq)] pub...
} } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum NlaType { Flag, U8, U16, U32, U64, S8, S16, S32, S64, Binary, String, NulString, Nested, NestedArray, Bitfield32, } impl From<NlaType> for u32 { fn from(nlatype: NlaType) -> u32 { mat...
Ok(match buf.kind() { NL_POLICY_TYPE_ATTR_TYPE => { let value = parse_u32(payload).context("invalid NL_POLICY_TYPE_ATTR_TYPE value")?; Self::Type(NlaType::try_from(value)?) } NL_POLICY_TYPE_ATTR_MIN_VALUE_S => Self::MinValueSigned( pars...
call_expression
[ { "content": "pub fn parse_u16(payload: &[u8]) -> Result<u16, DecodeError> {\n\n if payload.len() != size_of::<u16>() {\n\n return Err(format!(\"invalid u16: {:?}\", payload).into());\n\n }\n\n Ok(NativeEndian::read_u16(payload))\n\n}\n\n\n", "file_path": "netlink-packet-utils/src/parsers.rs...
Rust
src/perf_event/perf_event.rs
pwang7/rust-bcc
15d64f21ff230ed1e3331f8853918afc7aac7541
use crate::core::BPF; use crate::error::BccError; use crate::perf_event::Event; use bcc_sys::bccapi::bpf_prog_type_BPF_PROG_TYPE_PERF_EVENT as BPF_PROG_TYPE_PERF_EVENT; #[derive(Default)] pub struct PerfEvent { handler: Option<String>, event: Option<Event>, sample_period: Option<u64>, sample_frequency...
use crate::core::BPF; use crate::error::BccError; use crate::perf_event::Event; use bcc_sys::bccapi::bpf_prog_type_BPF_PROG_TYPE_PERF_EVENT as BPF_PROG_TYPE_PERF_EVENT; #[derive(Default)] pub struct PerfEvent { handler: Option<String>, event: Option<Event>, sample_period: Option<u64>, sample_frequency...
}
pub fn attach(self, bpf: &mut BPF) -> Result<(), BccError> { if self.event.is_none() { return Err(BccError::InvalidPerfEvent { message: "event is required".to_string(), }); } if self.handler.is_none() { return Err(BccError::InvalidPerfEvent { ...
function_block-full_function
[ { "content": "pub fn get_kprobe_functions(event_re: &str) -> Result<Vec<String>, BccError> {\n\n let mut fns: Vec<String> = vec![];\n\n\n\n enum Section {\n\n Unmatched,\n\n Begin,\n\n End,\n\n }\n\n\n\n let mut in_init_section = Section::Unmatched;\n\n let mut in_irq_section...
Rust
roach-server/src/main.rs
wgreenberg/roach
a5fa7b28565b48e0c78afe3fa9db34bb26785287
use tokio; use warp::Filter; use hive::game_state::GameType; use tokio::sync::{RwLock}; use std::sync::{Arc}; use handlebars::Handlebars; use crate::matchmaker::Matchmaker; use crate::err_handler::handle_rejection; use crate::client::WebsocketClient; #[macro_use] extern crate diesel; use dotenv::dotenv; use pretty_env_...
use tokio; use warp::Filter; use hive::game_state::GameType; use tokio::sync::{RwLock}; use std::sync::{Arc}; use handlebars::Handlebars; use crate::matchmaker::Matchmaker; use crate::err_handler::handle_rejection; use crate::client::WebsocketClient; #[macro_use] extern crate diesel; use dotenv::dotenv; use pretty_env_...
#[tokio::main] async fn main() { let matchmaker = Arc::new(RwLock::new(Matchmaker::new(GameType::Base))); dotenv().ok(); pretty_env_logger::init(); let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let db_pool = db::create_db_pool(&db_url); let hb = Arc::new(initialize_...
templates"); hb.set_strict_mode(true); for name in expected_templates { if hb.get_template(name).is_none() { panic!("Couldn't find template \"{}.hbs\" in handlebars registry", name); } } hb }
function_block-function_prefixed
[ { "content": "pub fn with_player_auth(db: DBPool) -> impl Filter<Extract = (Player,), Error = Rejection> + Clone {\n\n warp::filters::header::header(\"x-player-auth\")\n\n .and(with(db))\n\n .and_then(|token: String, db: DBPool| async move {\n\n players::table\n\n .fil...
Rust
src/panels/panel.rs
narfit66/ncursesw-win-rs
629b36fd2d7be4027d3c6328bf90d2cc6c7403af
/* src/panels/panel.rs Copyright (c) 2019-2022 Stephen Whittle All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without lim...
/* src/panels/panel.rs Copyright (c) 2019-2022 Stephen Whittle All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without lim...
} } unsafe impl Send for Panel { } unsafe impl Sync for Panel { } impl PartialEq for Panel { fn eq(&self, rhs: &Self) -> bool { self.screen == rhs.screen && ptr::eq(self.handle, rhs.handle) } } impl Eq for Panel { } impl Hash for Panel { fn hash<H: Hasher>(&self, state: &mut H) { ...
if self.free_on_drop { if let Err(source) = panels::del_panel(self.handle) { panic!("{} @ ({:p})", source, self.handle) } }
if_condition
[ { "content": "pub fn mouse_trafo(origin: Origin, to_screen: bool) -> result!(OriginResult) {\n\n OriginResult::try_from(mouse::mouse_trafo(origin.try_into()?, to_screen))\n\n}\n", "file_path": "src/mouse/funcs.rs", "rank": 0, "score": 322473.059627309 }, { "content": "/// Return the forms...
Rust
src/exif/tags.rs
kernelmethod/libfixers
e1fc1f5e4e5e3df080f80f412529c932320fd53d
use crate::{exif::TIFFByteAlignment, parse}; use derive_try_from_primitive::TryFromPrimitive; use nom::error::context; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; #[derive(Debug, Clone, Copy, TryFromPrimitive, PartialEq, Eq, Serialize, Deserialize)] #[repr(u16)] pub enum IFDTag { Unknown...
use crate::{exif::TIFFByteAlignment, parse}; use derive_try_from_primitive::TryFromPrimitive; use nom::error::context; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; #[derive(Debug, Clone, Copy, TryFromPrimitive, PartialEq, Eq, Serialize, Deserialize)] #[repr(u16)] pub enum IFDTag { Unknown...
ErrorKind::Alt), ); context("IFDTag", parser)(i) } pub fn parse_unknown(i: parse::Input, alignment: TIFFByteAlignment) -> parse::Result<Self> { let (i, tag) = context("IFDTag", |x| alignment.parse_u16(x))(i)?; match Self::try_from(tag) { Ok(tag) => Ok((i, tag))...
-> parse::Result<Self> { use nom::{combinator::map_res, error::ErrorKind}; let parser = map_res( |x| alignment.parse_u16(x), |x| Self::try_from(x).map_err(|_|
random
[ { "content": "/// Takes errors generated by parsing and extracts all of their messages into a vector, ordered\n\n/// from higher-level contexts to lower-level contexts. In addition, the messages are modified to\n\n/// show where the error occurred in the file that was being parsed.\n\npub fn extract_error_messa...
Rust
rustorio-data-derive/src/lua.rs
jgraef/rustorio
d0a5235b57175d9989a236c6937fc19e4307f5aa
use darling::{FromDeriveInput, FromMeta, FromField}; use proc_macro2::{TokenStream, Literal}; use syn::{parse_str, DataStruct, DataEnum, Fields, Expr, Path, ext::IdentExt}; use quote::quote; use heck::KebabCase; #[derive(Debug, FromField)] #[darling(attributes(lua))] pub(crate) struct FieldAttributes { #[darling(d...
use darling::{FromDeriveInput, FromMeta, FromField}; use proc_macro2::{TokenStream, Literal}; use syn::{parse_str, DataStruct, DataEnum, Fields, Expr, Path, ext::IdentExt}; use quote::quote; use heck::KebabCase; #[derive(Debug, FromField)] #[darling(attributes(lua))] pub(crate) struct FieldAttributes { #[darling(d...
pub(crate) fn impl_from_lua_value_for_newtype_struct(data: DataStruct, options: DeriveOptions) -> TokenStream { let struct_ident = options.ident; match data.fields { Fields::Unnamed(fields) => { if fields.unnamed.len() != 1 { panic!("Can't derive FromLuaValue for new-type ...
pub(crate) fn impl_from_lua_table_for_struct(data: DataStruct, options: DeriveOptions) -> TokenStream { let struct_ident = options.ident; let struct_init = match data.fields { Fields::Named(fields) => { let mut field_inits = vec![]; for field in fields.named { l...
function_block-full_function
[ { "content": "pub fn run_file<P: AsRef<Path>>(lua: &mut Lua, path: P) -> Result<(), Error> {\n\n let path = path.as_ref();\n\n let name = path.as_os_str().to_str().unwrap();\n\n\n\n log::debug!(\"Running Lua: {}\", path.display());\n\n\n\n let mut reader = BufReader::new(File::open(path)?);\n\n l...
Rust
artichoke-backend/src/extn/core/regexp/trampoline.rs
youknowone/artichoke
dd7b51c716220ba20b6584ecb887b50ac4688ba2
use crate::extn::core::regexp::Regexp; use crate::extn::prelude::*; pub fn initialize( interp: &Artichoke, pattern: Value, options: Option<Value>, encoding: Option<Value>, into: Option<Value>, ) -> Result<Value, Exception> { Regexp::initialize(interp, pattern, options, encoding, into) } pub fn...
use crate::extn::core::regexp::Regexp; use crate::extn::prelude::*; pub fn initialize( interp: &Artichoke, pattern: Value, options: Option<Value>, encoding: Option<Value>, into: Option<Value>, ) -> Result<Value, Exception> { Regexp::initialize(interp, pattern, options, encoding, into) } pub fn...
egexp.borrow(); borrow.is_match(interp, pattern, pos) } pub fn match_( interp: &Artichoke, regexp: Value, pattern: Value, pos: Option<Value>, block: Option<Block>, ) -> Result<Value, Exception> { let regexp = unsafe { Regexp::try_from_ruby(interp, &regexp) }.map_err(|err| { if let A...
} else { Exception::from(Fatal::new( interp, "Unable to extract Rust Regexp from Ruby Regexp receiver", )) } })?; let borrow = r
function_block-random_span
[ { "content": "#[cfg(not(feature = \"artichoke-system-environ\"))]\n\npub fn initialize(interp: &Artichoke, into: Option<sys::mrb_value>) -> Result<Value, Exception> {\n\n let obj = Environ(Box::new(backend::memory::Memory::new()));\n\n let result = obj\n\n .try_into_ruby(&interp, into)\n\n ....
Rust
pkmnapi-db/src/db/type_name.rs
kevinselwyn/pkmnapi
170e6b6c9a74e85c377137bc086793898c415125
use crate::error::{self, Result}; use crate::patch::*; use crate::string::*; use crate::PkmnapiDB; use std::collections::HashMap; impl PkmnapiDB { pub fn get_type_name_all(&self, type_ids: &Vec<u8>) -> Result<HashMap<u8, TypeName>> { self.get_all(type_ids, |id| self.get_type_name(id)) } ...
use crate::error::{self, Result}; use crate::patch::*; use crate::string::*; use crate::PkmnapiDB; use std::collections::HashMap; impl PkmnapiDB { pub fn get_type_name_all(&self, type_ids: &Vec<u8>) -> Result<HashMap<u8, TypeName>> { self.get_all(type_ids, |id| self.get_type_name(id)) } ...
pub fn set_type_name(&self, type_id: &u8, type_name: &TypeName) -> Result<Patch> { let old_type_name = self.get_type_name(type_id)?; ...
pub fn get_type_name(&self, type_id: &u8) -> Result<TypeName> { let _max_id = self.type_id_validate(type_id)?; let offset_base = PkmnapiDB::ROM_PAGE * 0x08; let pointer_base = offset_base + 0x7DAE; let pointer_offset = pointer_base + ((*type_id as usize) * 2); let pointer = offs...
function_block-full_function
[ { "content": "pub fn get_etag(if_match: Result<IfMatch, IfMatchError>) -> Result<String, ResponseError> {\n\n match if_match {\n\n Ok(if_match) => Ok(if_match.into_inner()),\n\n Err(_) => Err(ETagErrorMissing::new()),\n\n }\n\n}\n\n\n", "file_path": "pkmnapi-api/src/utils.rs", "rank"...
Rust
src/tor/src/ext/rust/crates/rand_core-0.1.0/src/impls.rs
bitcointest527/tesbit12
71ab5ef78e2c5dc5cf57ce853e4d64930a05947e
use core::convert::AsRef; use core::intrinsics::transmute; use core::ptr::copy_nonoverlapping; use core::{fmt, slice}; use core::cmp::min; use core::mem::size_of; use {RngCore, BlockRngCore, CryptoRng, SeedableRng, Error}; #[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; pub fn next_u64_via_u32<R: RngC...
use core::convert::AsRef; use core::intrinsics::transmute; use core::ptr::copy_nonoverlapping; use core::{fmt, slice}; use core::cmp::min; use core::mem::size_of; use {RngCore, BlockRngCore, CryptoRng, SeedableRng, Error}; #[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; pub fn next_u64_via_u32<R: RngC...
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn fill_bytes(&mut self, dest: &mut [u8]) { let mut filled = 0; self.half_used = false; if self.index < self.results.as_ref().len() { let (consumed_u64, filled_u8) = fill_via_u...
e(&mut self.results); self.index = 0; } let value = self.results.as_ref()[self.index]; self.index += 1; self.half_used = false; value }
function_block-function_prefixed
[]
Rust
.cargo/registry/src/github.com-1ecc6299db9ec823/slog-stdlog-4.0.0/lib.rs
RangerStation/alexandrie-run
d2726ed6a00b2ef09f90a95a1c3781ba57798d82
#![warn(missing_docs)] extern crate log; use std::{fmt, io}; use slog::{Level, KV, b}; struct Logger; fn log_to_slog_level(level: log::Level) -> Level { match level { log::Level::Trace => Level::Trace, log::Level::Debug => Level::Debug, log::Level::Info => Level::Info, log::Lev...
#![warn(missing_docs)] extern crate log; use std::{fmt, io}; use slog::{Level, KV, b}; struct Logger; fn log_to_slog_level(level: log::Level) -> Level { match level { log::Level::Trace => Level::Trace, log::Level::Debug => Level::Debug, log::Level::Info => Level::Info, log::Lev...
self.logger_values .serialize(self.info, &mut ser) .map_err(|_| fmt::Error)?; self.info .kv() .serialize(self.info, &mut ser) .map_err(|_| fmt::Error)?; let values = ser.into_inner().into_inner(); write!(f, "{}", String::fro...
.unwrap_or("<unknown>"); let line = r.line().unwrap_or_default(); slog::RecordLocation { file, line, column: 0, function: "", module, } } impl log::Log for Logger { fn enabled(&self, _: &log::Metadata) -> bool { true } fn log(&self, r: &log::Rec...
random
[ { "content": "#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n\nstruct CrateMeta {\n\n pub name: String,\n\n pub vers: Version,\n\n pub deps: Vec<CrateMetaDependency>,\n\n pub features: HashMap<String, Vec<String>>,\n\n pub authors: Vec<String>,\n\n pub description: Option<String>,...
Rust
assembly/src/parsers/io_ops/adv_ops.rs
grjte/miden
a07da543291e1e6fab77a9d9ab80f7ed42865621
use super::{parse_int_param, validate_operation, AssemblyError, Operation, Token}; use vm_core::utils::PushMany; const ADVICE_READ_LIMIT: u32 = 16; pub fn parse_push_adv(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { validate_operation!(op, "push.adv", 1); let n = parse_i...
use super::{parse_int_param, validate_operation, AssemblyError, Operation, Token}; use vm_core::utils::PushMany; const ADVICE_READ_LIMIT: u32 = 16; pub fn parse_push_adv(span_ops: &mut Vec<Operation>, op: &Token) -> Result<(), AssemblyError> { validate_operation!(op, "push.adv", 1); let n = parse_i...
}
0; let mut span_ops: Vec<Operation> = Vec::new(); let pos = 0; let op_extra_val = Token::new("loadw.adv.0", pos); let expected = AssemblyError::extra_param(&op_extra_val); assert_eq!( parse_loadw(&mut span_ops, &op_extra_val, num_proc_locals).unwra...
function_block-function_prefixed
[ { "content": "/// Translates u32testw assembly instruction to VM operations.\n\n///\n\n/// Implemented by executing DUP U32SPLIT SWAP DROP EQZ on each element in the word\n\n/// and combining the results using AND operation (total of 23 VM cycles)\n\npub fn parse_u32testw(span_ops: &mut Vec<Operation>, op: &Tok...
Rust
src/graphics/lib/compute/mold/src/layer.rs
liexusong/fuchsia
81897680af92a1848a063e3c20ff3a4892ccff07
use std::mem; use surpass; use crate::Style; const IDENTITY: &[f32; 6] = &[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; const MAX_LAYER: usize = u16::MAX as usize; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct LayerId(pub(crate) u16); fn outer(index: usize) -> usize { index >> 6 } fn inne...
use std::mem; use surpass; use crate::Style; const IDENTITY: &[f32; 6] = &[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; const MAX_LAYER: usize = u16::MAX as usize; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct LayerId(pub(crate) u16); fn outer(index: usize) -> usize { index >> 6 } fn inne...
if self.inner.affine_transform != affine_transform { self.is_unchanged.clear(); self.inner.affine_transform = affine_transform; } self } #[inline] pub fn order(&self) -> u16 { self.inner.order.expect("Layers should always have orders") } #...
let affine_transform = if transform == IDENTITY { None } else { if transform[0] * transform[0] + transform[2] * transform[2] > 1.001 || transform[1] * transform[1] + transform[3] * transform[3] > 1.001 { panic!("Layer's scaling on each axis mus...
assignment_statement
[]
Rust
examples/demo_window.rs
locriacyber/imgui-glfw-support
86be855e6951536a038ca5642dbfa9bbc6f62c3a
use std::time::Instant; use futures::executor::block_on; fn main() { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).expect("GLFW failed to init"); glfw.window_hint(glfw::WindowHint::ClientApi(glfw::ClientApiHint::NoApi)); let (width, height) = (1600, 900); let (mut window, event_receiver) = glfw ...
use std::time::Instant; use futures::executor::block_on; fn main() { let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).expect("GLFW failed to init"); glfw.window_hint(glfw::WindowHint::ClientApi(glfw::ClientApiHint::NoApi)); let (width, height) = (1600, 900); let (mut window, event_receiver) = glfw ...
e( &wgpu::DeviceDescriptor { features: wgpu::Features::empty(), limits: wgpu::Limits::default(), shader_validation: false, }, None, )) .unwrap(); let mut swap_chain_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTAC...
; window.set_all_polling(true); let instance = wgpu::Instance::new(wgpu::BackendBit::all()); let surface = unsafe { instance.create_surface(&window) }; let adapter = block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ...
random
[ { "content": "fn main() {\n\n let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).expect(\"GLFW failed to init\");\n\n glfw.window_hint(glfw::WindowHint::ClientApi(glfw::ClientApiHint::NoApi));\n\n\n\n let (width, height) = (1600, 900);\n\n\n\n let (mut window, _event_receiver) = glfw\n\n .create...
Rust
src/session.rs
kvsari/dicey-dice
83f1ac233567bc28ff5cba6b4ab781d4cf2b3cd8
use std::num::NonZeroU8; use std::fmt; use derive_getters::Getters; use rand::{rngs, Rng}; use crate::game::{self, Tree, Board, Players, Player, Choice, Action, Consequence, Holding}; fn roll_d6s<T: Rng>(d6s: u8, random: &mut T) -> usize { (0..d6s) .fold(0, |sum, _| -> usize { sum + random.g...
use std::num::NonZeroU8; use std::fmt; use derive_getters::Getters; use rand::{rngs, Rng}; use crate::game::{self, Tree, Board, Players, Player, Choice, Action, Consequence, Holding}; fn roll_d6s<T: Rng>(d6s: u8, random: &mut T) -> usize { (0..d6s) .fold(0, |sum, _| -> usize { sum + random.g...
pub fn set_move_limit(&mut self, move_limit: NonZeroU8) -> &mut Self { self.move_limit = move_limit; self } pub fn set_board(&mut self, board: Board) -> &mut Self { self.players = *board.players(); self.board = Some(board); self } pub fn gen_boar...
pub fn set_players(&mut self, players: Players) -> &mut Self { if self.players != players { self.board = None; } self.players = players; self }
function_block-full_function
[ { "content": "/// Produces all legal attacking moves with the amount of dice they would capture.\n\nfn all_legal_attacks_from(grid: &Grid<u8>, player: &Player) -> Vec<Action> {\n\n grid.iter()\n\n .fold(Vec::new(), |mut moves, hex_tile| {\n\n //dbg!(hex_tile);\n\n let coordinate ...
Rust
devices/src/virtio/vhost/user/device/net.rs
google/crosvm
df929efce3261ca5383f66eea6c7041b3439eb77
pub mod sys; use std::sync::Arc; use anyhow::{anyhow, bail, Context}; use base::{error, Event}; use cros_async::{EventAsync, Executor, IntoAsync}; use data_model::DataInit; use futures::future::AbortHandle; use net_util::TapT; use once_cell::sync::OnceCell; use sync::Mutex; use vm_memory::GuestMemory; use vmm_vhost...
pub mod sys; use std::sync::Arc; use anyhow::{anyhow, bail, Context}; use base::{error, Event}; use cros_async::{EventAsync, Executor, IntoAsync}; use data_model::DataInit; use futures::future::AbortHandle; use net_util::TapT; use once_cell::sync::OnceCell; use sync::Mutex; use vm_memory::GuestMemory; use vmm_vhost...
{ error!("Failed to process ctrl queue: {}", e); break; } } } pub(crate) struct NetBackend<T: TapT + IntoAsync> { tap: T, avail_features: u64, acked_features: u64, acked_protocol_features: VhostUserProtocolFeatures, workers: [Option<AbortHandle>; MAX_QUEUE_NUM],...
process_ctrl( &doorbell, &mut queue, &mem, &mut tap, acked_features, vq_pairs, )
call_expression
[ { "content": "// Reads the next u16 from the file.\n\nfn read_u16_from_file(mut f: &File) -> Result<u16> {\n\n let mut value = [0u8; 2];\n\n (&mut f)\n\n .read_exact(&mut value)\n\n .map_err(Error::ReadingHeader)?;\n\n Ok(u16::from_be_bytes(value))\n\n}\n\n\n", "file_path": "disk/src/...
Rust
src/encoding/testutils.rs
jedisct1/rust-encoding
466d39a45a35303471a6990077aab42fb2ad38d9
#![macro_escape] macro_rules! assert_feed_ok( ($this:expr, $processed:expr, $unprocessed:expr, $output:expr) => ({ let processed = $processed; let processed = $this.test_norm_input(processed); let unprocessed = $unprocessed; let unprocessed = $this.test_norm_input(unprocessed); ...
#![macro_escape] macro_rules! assert_feed_ok( ($this:expr, $processed:expr, $unprocessed:expr, $output:expr) => ({ let processed = $processed; let processed = $this.test_norm_input(processed); let unprocessed = $unprocessed; let unprocessed = $this.test_norm_input(unprocessed); ...
xpr ) => ( mod tests { use super::{forward, backward, backward_remapped}; use test; multi_byte_tests!(make shared tests and benches with dups = $dups) static REMAP_MIN: u16 = $remap_min; static REMAP_MAX: u16 = $remap_max; #[test] ...
test::black_box(forward(i as u16)); } start += 0x80; }) } #[bench] fn bench_backward_sequential_128(bencher: &mut test::Bencher) { let mut start: u32 = 0; bencher.iter(|| { for i in range(start, start + 0x80) { ...
random
[ { "content": "#[inline]\n\npub fn backward(code: u32) -> u16 {\n\n let offset = (code >> 4) as uint;\n\n let offset = if offset < 12190 {BACKWARD_TABLE_UPPER[offset] as uint} else {0};\n\n BACKWARD_TABLE_LOWER[offset + ((code & 15) as uint)]\n\n}\n\n\n\n#[cfg(test)]\n\nmulti_byte_tests!(\n\n dups = ...
Rust
mk/src/render/sprite_atlas_grid.rs
AcrylicShrimp/mk
518bd804ff1b6f56b22163e94d758a0d5581a40a
use crate::render::{LuaRcSprite, LuaRcTexture, Sprite, SpriteChannel, TexelMapping, Texture}; use codegen::LuaRc; use image::{open as open_image, ColorType, GenericImageView, ImageError}; use mlua::prelude::*; use serde::Deserialize; use serde_json::{from_str, Error as JSONError}; use std::error::Error; use std::fmt::D...
use crate::render::{LuaRcSprite, LuaRcTexture, Sprite, SpriteChannel, TexelMapping, Texture}; use codegen::LuaRc; use image::{open as open_image, ColorType, GenericImageView, ImageError}; use mlua::prelude::*; use serde::Deserialize; use serde_json::{from_str, Error as JSONError}; use std::error::Error; use std::fmt::D...
while next_y <= height { while next_x <= width { sprites.push( Sprite::from_atlas( texture.clone(), TexelMapping::new((x, y), (next_x, next_y)), ) .into(), );...
let mut sprites = Vec::with_capacity( ((width / metadata.grid_width) * (height / metadata.grid_height)) as _, );
assignment_statement
[ { "content": "pub fn resize(width: u32, height: u32) {\n\n unsafe {\n\n gl33::Viewport(0, 0, width as _, height as _);\n\n }\n\n}\n", "file_path": "render/src/gl33/mod.rs", "rank": 0, "score": 274759.36155693186 }, { "content": "pub fn init(f: impl FnMut(&str) -> *const std::ffi...
Rust
core/src/test/skia/canvas.rs
ganita/akriti-core
49feb21138d36c4492d4a3c9072cc5ca190e8838
/* * Copyright 2017 Sreejith Krishnan R * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
/* * Copyright 2017 Sreejith Krishnan R * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed...
fn draw_rect_outline(&self, top_left: &Point, rect: &Rect, color: &Color, stroke_width: f32) { let mut paint = self.paint.borrow_mut(); paint.set_color(&SkiaColor { r: color.r(), g: color.g(), b: color.b(), a: color.a(), }); paint.set...
fn draw_rect(&self, top_left: &Point, rect: &Rect, color: &Color) { let mut paint = self.paint.borrow_mut(); paint.set_color(&SkiaColor { r: color.r(), g: color.g(), b: color.b(), a: color.a(), }); paint.set_antialias(true); paint.s...
function_block-full_function
[ { "content": "pub fn drawable<F>(width: i32, height: i32, draw_fn: F)\n\n where F: Fn(&DrawingArea, &Context) -> Inhibit + 'static {\n\n let window = gtk::Window::new(gtk::WindowType::Toplevel);\n\n let drawing_area = Box::new(DrawingArea::new)();\n\n\n\n drawing_area.connect_draw(draw_fn);\n\n\...
Rust
dagrs/src/task/yaml_task.rs
openeuler-mirror/opensource-intern
19cbd36ae72b105bcb0e9e1970e0a839ca3c185b
use super::{Inputval, Retval, RunScript, RunType, TaskTrait, TaskWrapper}; use crate::engine::{DagError, YamlFormatError, EnvVar}; use std::{cell::Cell, collections::HashMap, fs::File, io::Read}; use yaml_rust::{Yaml, YamlLoader}; #[derive(Debug)] struct YamlTaskInner { run: RunScript, } pub struct YamlTask...
use super::{Inputval, Retval, RunScript, RunType, TaskTrait, TaskWrapper}; use crate::engine::{DagError, YamlFormatError, EnvVar}; use std::{cell::Cell, collections::HashMap, fs::File, io::Read}; use yaml_rust::{Yaml, YamlLoader}; #[derive(Debug)] struct YamlTaskInner { run: RunScript, } pub struct YamlTask...
; let run_script = run["script"].as_str().ok_or(DagError::format_error( YamlFormatError::RunScriptError(id.into()), ))?; let mut afters = Vec::new(); if let Some(after_tasks) = info["after"].as_vec() { after_tasks .iter() ...
match run["type"].as_str().ok_or(DagError::format_error( YamlFormatError::RunScriptError(id.into()), ))? { "sh" => RunType::SH, "deno" => RunType::DENO, _ => { return Err(DagError::format_error(YamlFormatError::RunScriptError( i...
if_condition
[ { "content": "//Delete folder\n\npub fn rmdir(name:&String) {\n\n let mut path=String::from(\"/root/Cangku/\");\n\n let name_str:&str=&name[..];\n\n path.push_str(&name_str);\n\n fs::remove_dir_all(path);\n\n}\n", "file_path": "purl/purl/src/doc.rs", "rank": 0, "score": 238662.9237724669 }...
Rust
burnt-sushi/src/blocker.rs
OpenByteDev/spotify-ad-guard
8791a159adf03c9f6540108a5053894bb132e88d
use std::{mem, net::SocketAddrV4}; use dll_syringe::{ error::SyringeError, process::{OwnedProcessModule, Process}, Syringe, }; use log::{debug, error, info, warn}; use serde::Deserialize; use tokio::{runtime, task::LocalSet}; use crate::{ args::ARGS, resolver::{resolve_blocker, resolve_filter_conf...
use std::{mem, net::SocketAddrV4}; use dll_syringe::{ error::SyringeError, process::{OwnedProcessModule, Process}, Syringe, }; use log::{debug, error, info, warn}; use serde::Deserialize; use tokio::{runtime, task::LocalSet}; use crate::{ args::ARGS, resolver::{resolve_blocker, resolve_filter_conf...
} #[derive(Deserialize, Debug)] pub struct FilterConfig { pub allowlist: Vec<String>, pub denylist: Vec<String>, }
match result { Ok(_) | Err(SyringeError::ProcessInaccessible) | Err(SyringeError::ModuleInaccessible) => {} _ => todo!("{:#?}", result), }; *self = SpotifyHookState::Unhooked; }
function_block-function_prefix_line
[ { "content": "fn list_threads() -> io::Result<impl FallibleIterator<Item = THREADENTRY32, Error = io::Error>> {\n\n Toolhelp32ThreadIterator::new()\n\n}\n\n\n", "file_path": "burnt-sushi/src/spotify_process_scanner.rs", "rank": 0, "score": 195012.2295375033 }, { "content": "fn is_spotify_...
Rust
cincinnati/src/plugins/internal/graph_builder/release.rs
rwsu/cincinnati
c1e2b4eb6ae13f093875ae7de45acaa74937c848
use crate as cincinnati; use self::cincinnati::MapImpl; use itertools::Itertools; use log::trace; use semver::Version; use serde::{Deserialize, Serialize}; use std::fmt; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Release { pub source: String, pub metadata: Metadata, } impl Into<...
use crate as cincinnati; use self::cincinnati::MapImpl; use itertools::Itertools; use log::trace; use semver::Version; use serde::{Deserialize, Serialize}; use std::fmt; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Release { pub source: String, pub metadata: Metadata, } impl Into<...
} #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub struct Metadata { pub kind: MetadataKind, pub version: Version, #[serde(default)] pub previous: Vec<Version>, #[serde(default)] pub next: Vec<Version>, #[serde(default)] pub metadata: MapImpl<String, String>, } impl fmt...
version: self.metadata.version.to_string(), payload: self.source, metadata: self.metadata.metadata, }) }
function_block-function_prefix_line
[ { "content": "/// Deserialize path_prefix\n\npub fn de_path_prefix<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>\n\nwhere\n\n D: serde::Deserializer<'de>,\n\n{\n\n use serde::Deserialize;\n\n let path_prefix = String::deserialize(deserializer)?;\n\n Ok(Some(parse_path_prefix(path_pref...
Rust
super-metroid/src/graphics.rs
konkers/sm
03ab91ce00b034a2683984bbb7420b314473bc2d
use failure::{format_err, Error}; use super::{Color, Palette, RoomData, RoomMdb, TileTable, TileTableEntry, Tiles, PALETTE_ENTRIES}; pub const CRE_INDEX_START: u16 = 0x280; pub const TILE_H: usize = 8; pub const TILE_W: usize = 8; pub const BYTES_PER_TILE: usize = (TILE_H * TILE_W) / 2; fn get_pixel(data: &[u8], x: ...
use failure::{format_err, Error}; use super::{Color, Palette, RoomData, RoomMdb, TileTable, TileTableEntry, Tiles, PALETTE_ENTRIES}; pub const CRE_INDEX_START: u16 = 0x280; pub const TILE_H: usize = 8; pub const TILE_W: usize = 8; pub const BYTES_PER_TILE: usize = (TILE_H * TILE_W) / 2; fn get_pixel(data: &[u8], x: ...
#[cfg(feature = "render")] pub fn render_block( self: &Self, img: &mut image::RgbaImage, index: u16, x: usize, y: usize, flip_h: bool, flip_v: bool, ) -> Result<(), Error> { let block_data = self.get_block_data(index)?; ...
fn get_block_data(self: &Self, index: u16) -> Result<&[TileTableEntry], Error> { let tile_index = index as usize * 4; let cre_entries = self.cre_table.entries.len(); let sce_entries = self.sce_table.entries.len(); if tile_index < cre_entries { Ok(&self.cre_table.entries[tile_...
function_block-function_prefix_line
[ { "content": "pub fn decompress(data: &[u8]) -> Result<Vec<u8>, Error> {\n\n // Algorithm from http://patrickjohnston.org/ASM/ROM%20data/Super%20Metroid/decompress.py\n\n // and https://www.romhacking.net/documents/243/\n\n\n\n let mut r = Cursor::new(data);\n\n let mut out = Vec::new();\n\n\n\n ...
Rust
scheduler/crates/api/src/service/add_busy_calendar.rs
omid/nettu-scheduler
27a2728882842222085ee4e17c952ec215fd683e
use crate::error::NettuError; use crate::shared::{ auth::protect_account_route, usecase::{execute, UseCase}, }; use actix_web::{web, HttpRequest, HttpResponse}; use nettu_scheduler_api_structs::add_busy_calendar::*; use nettu_scheduler_domain::IntegrationProvider; use nettu_scheduler_domain::{ providers::{g...
use crate::error::NettuError; use crate::shared::{ auth::protect_account_route, usecase::{execute, UseCase}, }; use actix_web::{web, HttpRequest, HttpResponse}; use nettu_scheduler_api_structs::add_busy_calendar::*; use nettu_scheduler_domain::IntegrationProvider; use nettu_scheduler_domain::{ providers::{g...
} #[async_trait::async_trait(?Send)] impl UseCase for AddBusyCalendarUseCase { type Response = (); type Error = UseCaseError; const NAME: &'static str = "AddBusyCalendar"; async fn execute(&mut self, ctx: &NettuContext) -> Result<Self::Response, Self::Error> { let user = ctx .re...
fn from(e: UseCaseError) -> Self { match e { UseCaseError::StorageError => Self::InternalError, UseCaseError::CalendarNotFound => { Self::NotFound("The requested calendar was not found or user is missing permissions to read the calendar".into()) } ...
function_block-full_function
[]
Rust
src/http_request.rs
explodingcamera/rust-http-server-from-scratch
109fc07f42910f997fb032e5e81a8d31eb6032dd
use bytes::{Buf, Bytes}; use std::{ collections::{btree_map, BTreeMap}, convert::{TryFrom, TryInto}, fmt::{self, Debug}, }; use thiserror::Error; use crate::tokens; #[derive(Error, Debug)] pub enum RequestError { #[error("invalid method")] Method, #[error("invalid header name")] HeaderName...
use bytes::{Buf, Bytes}; use std::{ collections::{btree_map, BTreeMap}, convert::{TryFrom, TryInto}, fmt::{self, Debug}, }; use thiserror::Error; use crate::tokens; #[derive(Error, Debug)] pub enum RequestError { #[error("invalid method")] Method, #[error("invalid header name")] HeaderName...
Ok(()) } else { Err(RequestError::NewLine) } } b'\n' => Ok(()), _ => Err(RequestError::NewLine), } } pub fn parse_version(bytes: &mut Bytes) -> Result<u8, RequestError> { let res = match &bytes.slice(0.....
one, version: None, headers: Headers { headers: BTreeMap::new(), }, body: vec![], } } pub fn parse(&mut self, buf: Bytes) -> Result<(), RequestError> { let mut bytes = buf; self.method = Some( Request::parse_to...
random
[ { "content": "pub fn middleware_matches_request(request: &Request, route: &Route) -> Result<Option<RequestPath>> {\n\n let request_path = request.path.clone().unwrap_or_else(|| \"\".to_string());\n\n let request_segments = request_path.split('/').peekable();\n\n\n\n let route_path = &route.path;\n\n ...
Rust
src/chron_service.rs
canac/chron
30a156e0cf94188e1b1e52c4b35b8066e24510be
use crate::database::Database; use crate::http_server; use anyhow::{bail, Context, Result}; use chrono::{DateTime, TimeZone, Utc}; use cron::Schedule; use lazy_static::lazy_static; use regex::Regex; use std::collections::HashMap; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{self, ...
use crate::database::Database; use crate::http_server; use anyhow::{bail, Context, Result}; use chrono::{DateTime, TimeZone, Utc}; use cron::Schedule; use lazy_static::lazy_static; use regex::Regex; use std::collections::HashMap; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{self, ...
pub async fn start_server(&self) -> Result<(), std::io::Error> { http_server::start_server(self.state.clone()).await } pub fn run(&self) -> Result<()> { for command in self.state.commands.values() { let thread_state = self.state.clone(); let comm...
if !Self::validate_name(name) { bail!("Invalid command name {name}") } if self.state.commands.contains_key(name) { bail!("A job with the name {name} already exists") } let db = self.state.db.lock().unwrap(); let last_run_time = db .get_last_r...
function_block-function_prefix_line
[ { "content": "#[derive(Deserialize)]\n\nstruct ScheduledCommand {\n\n schedule: String,\n\n command: String,\n\n}\n\n\n\n#[derive(Deserialize)]\n\npub struct Chronfile {\n\n #[serde(rename = \"startup\", default)]\n\n startup_commands: HashMap<String, StartupCommand>,\n\n #[serde(rename = \"sched...
Rust
src/sttest/gpt.rs
pipex/cc2538
51ab96d8afed86bad1be5c4aee687d7909d98209
#[doc = "Reader of register GPT"] pub type R = crate::R<u32, super::GPT>; #[doc = "Writer for register GPT"] pub type W = crate::W<u32, super::GPT>; #[doc = "Register GPT `reset()`'s with value 0"] impl crate::ResetValue for super::GPT { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
#[doc = "Reader of register GPT"] pub type R = crate::R<u32, super::GPT>; #[doc = "Writer for register GPT"] pub type W = crate::W<u32, super::GPT>; #[doc = "Register GPT `reset()`'s with value 0"] impl crate::ResetValue for super::GPT { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
self.w } } #[doc = "Reader of field `GPTIDOV`"] pub type GPTIDOV_R = crate::R<u8, u8>; #[doc = "Write proxy for field `GPTIDOV`"] pub struct GPTIDOV_W<'a> { w: &'a mut W, } impl<'a> GPTIDOV_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a ...
> { w: &'a mut W, } impl<'a> RESERVED2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 5)) | (((value as u32) & 0x07) << 5);
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/video/vram/palette/dynamic.rs
super-rust-boy/super-rust-boy
53555c60278359877a3a6fe4bb7175f129e803e6
use bitflags::bitflags; use crate::{ mem::MemDevice, video::{ PaletteColours, Colour } }; const MAX_COLOUR: u16 = 0x1F; macro_rules! col15_to_col888 { ($rgb:expr) => { { let r_i = ($rgb & MAX_COLOUR) << 3; let g_i = (($rgb >> 5) & MAX_COLOUR) << 3; ...
use bitflags::bitflags; use crate::{ mem::MemDevice, video::{ PaletteColours, Colour } }; const MAX_COLOUR: u16 = 0x1F; macro_rules! col15_to_col888 { ($rgb:expr) => { { let r_i = ($rgb & MAX_COLOUR) << 3; let g_i = (($rgb >> 5) & MAX_COLOUR) << 3; ...
pub fn get_bg_colour(&self, which: usize, texel: u8) -> Colour { self.bg_palettes[which].colours[texel as usize] } pub fn get_obj_colour(&self, which: usize, texel: u8) -> Colour { self.obj_palettes[which].colours[texel as usize] } pub fn read_bg_index(&self) -> u8 { (sel...
DynamicPaletteMem { bg_palettes: vec![DynamicPalette::new(); 8], bg_palette_index: 0, bg_auto_inc: PaletteIndex::default(), obj_palettes: vec![DynamicPalette::new(); 8], obj_palette_index: 0, obj_auto_inc: PaletteIndex...
function_block-function_prefix_line
[ { "content": "#[inline]\n\nfn write_pixel(output: &mut [u8], colour: Colour) {\n\n output[0] = colour.r;\n\n output[1] = colour.g;\n\n output[2] = colour.b;\n\n}", "file_path": "src/video/vram/drawing.rs", "rank": 0, "score": 149450.73604155 }, { "content": "// CGB/SGB palette looku...
Rust
lib/src/io.rs
Ludea/speedupdate-rs
495bec821f902a8c43f55ee141913af23f2b40ec
pub use std::io::*; use std::path::Path; use std::{fmt, fs}; use sha1::{Digest, Sha1}; use crate::metadata::Sha1Hash; pub const BUFFER_SIZE: usize = 128 * 1024; pub trait ReadSlice { fn read_slice(&mut self, pos: SeekFrom, buf: &mut [u8]) -> Result<()>; } impl<T: Read + Seek> ReadSlic...
pub use std::io::*; use std::path::Path; use std::{fmt, fs}; use sha1::{Digest, Sha1}; use crate::metadata::Sha1Hash; pub const BUFFER_SIZE: usize = 128 * 1024; pub trait ReadSlice { fn read_slice(&mut self, pos: SeekFrom, buf: &mut [u8]) -> Result<()>; } impl<T: Read + Seek> ReadSlic...
pub struct Slice<T> { inner: T, offset: u64, size: u64, pos: u64, } impl<T: Seek> Slice<T> { pub fn new(mut inner: T, offset: u64, size: u64) -> Result<Self> { inner.seek(SeekFrom::Start(offset))?; Ok(Self { inner, offset, size, pos: 0 }) } fn seek_err(&self, pos: SeekFro...
d => assert_eq(false, expected_is_file, ctx), _ => Err(err), }, Ok(metadata) => assert_eq(metadata.is_file(), expected_is_file, ctx), } }
function_block-function_prefixed
[ { "content": "fn path_is_valid(path: &str) -> bool {\n\n let path = std::path::Path::new(path);\n\n let mut components = path.components().peekable();\n\n\n\n if let Some(first) = components.peek() {\n\n if !matches!(first, std::path::Component::Normal(_)) {\n\n return false;\n\n ...
Rust
arcon/arcon_state/src/backend/sled/vec_ops.rs
arxra/arcon
bfaa73394f9a1d0261bfd4e6eda5335e9aba9e42
use crate::{ data::{Metakey, Value}, error::*, handles::BoxedIteratorOfResult, serialization::{fixed_bytes, fixed_bytes::FixedBytes, protobuf}, sled::Sled, Handle, VecOps, VecState, }; #[cfg(feature = "metrics")] use crate::metrics_utils::*; use std::iter; impl VecOps for Sled { fn vec_cl...
use crate::{ data::{Metakey, Value}, error::*, handles::BoxedIteratorOfResult, serialization::{fixed_bytes, fixed_bytes::FixedBytes, protobuf}, sled::Sled, Handle, VecOps, VecState, }; #[cfg(feature = "metrics")] use crate::metrics_utils::*; use std::iter; impl VecOps for Sled { fn vec_cl...
result, &0usize) { eprintln!("length serialization error: {}", e); return None; } let mut len = 0usize; fn get_len(slice_ref: &mut &[u8]) -> Option<usize> { fixed_bytes::deserialize_from(slice_ref) .map_err(|e| { eprintln!("length deserializat...
as FixedBytes>::SIZE + existent.map(|x| x.len()).unwrap_or(0) + new.len(), ); if let Err(e) = fixed_bytes::serialize_into(&mut
function_block-random_span
[]
Rust
strict_encoding/derive/tests/tlv.rs
LNP-BP/client_side_validation
fc6d9279641909059eb0141493e362113dbc3e9f
#[macro_use] extern crate amplify; #[macro_use] extern crate strict_encoding_derive; #[macro_use] extern crate strict_encoding_test; mod common; use std::collections::BTreeMap; use common::{compile_test, Error, Result}; use strict_encoding::{strict_deserialize, StrictDecode}; use strict_encoding_test::test_encoding...
#[macro_use] extern crate amplify; #[macro_use] extern crate strict_encoding_derive; #[macro_use] extern crate strict_encoding_test; mod common; use std::collections::BTreeMap; use common::{compile_test, Error, Result}; use strict_encoding::{strict_deserialize, StrictDecode}; use strict_encoding_test::test_encoding...
let data1 = [0x00, 0x00, 0x00, 0x00]; let data2 = [ 0x03, 0x00, 0xB1, 0xB2, 0xB3, 0x00, 0x00, ]; let _: Tlv = strict_deserialize(&data1).unwrap(); let _: Tlv = strict_deserialize(&data2).unwrap(); test_encoding_roundtrip(&Tlv::default(), &data1)?; test_encoding_...
0xFE, 0xCA, 0xAD, 0xDE, ] }; } #[test] fn tlv_optional() -> Result { #[derive(Clone, PartialEq, Eq, Debug, Default)] #[derive(NetworkEncode, NetworkDecode)] #[network_encoding(use_tlv)] struct Tlv { fixed: u8, #[network_encoding(tlv = 0xBEEF)] ...
random
[ { "content": "#[derive(NetworkEncode, NetworkDecode)]\n\n#[network_encoding(use_tlv)]\n\nstruct Tlv {\n\n #[network_encoding(tlv = 0xCAFEBAD)]\n\n tlv: Option<u8>,\n\n}\n", "file_path": "strict_encoding/derive/tests/tlv-failures/tlv_non_u16_type/mod.rs", "rank": 1, "score": 232272.4955719504 ...
Rust
src/grid/a_star.rs
Elabajaba/hierarchical_pathfinding
96ad2c9fd6f8979179656f46d55017db94dd292d
use super::{HeuristicElement, Path}; use crate::{neighbors::Neighborhood, Point, PointMap}; use std::cmp::Ordering; use std::collections::BinaryHeap; pub fn a_star_search<N: Neighborhood>( neighborhood: &N, mut valid: impl FnMut(Point) -> bool, mut get_cost: impl FnMut(Point) -> isize, start: Point, ...
use super::{HeuristicElement, Path}; use crate::{neighbors::Neighborhood, Point, PointMap}; use std::cmp::Ordering; use std::collections::BinaryHeap; pub fn a_star_search<N: Neighborhood>( neighborhood: &N, mut valid: impl FnMut(Point) -> bool, mut get_cost: impl FnMut(Point) -> isize, start: Point, ...
); } } } if !visited.contains_key(&goal) { return None; } let steps = { let mut steps = vec![]; let mut current = goal; while current != start { steps.push(current); let (_, prev) = visited[&current]; current = pr...
HeuristicElement( other_id, other_cost, other_cost + heuristic, )
call_expression
[ { "content": "pub fn a_star_search<N: Neighborhood>(\n\n neighborhood: &N,\n\n mut valid: impl FnMut(Point) -> bool,\n\n mut get_cost: impl FnMut(Point) -> isize,\n\n start: Point,\n\n goal: Point,\n\n) -> Option<Vec<Point>> {\n\n if get_cost(start) < 0 {\n\n return None;\n\n }\n\n ...
Rust
cavalier_contours/src/polyline/pline_vertex.rs
jbuckmccready/cavalier_contours
dc17e19094081cffefb565d10612bb2b8b531d73
use std::fmt::Display; use crate::core::{math::Vector2, traits::Real}; #[derive(Debug, Copy, Clone, Default, PartialEq)] pub struct PlineVertex<T = f64> { pub x: T, pub y: T, pub bulge: T, } impl<T> Display for PlineVertex<T> where T: Display, { fn fmt(&self, f: &mut std::fmt::Form...
use std::fmt::Display; use crate::core::{math::Vector2, traits::Real}; #[derive(Debug, Copy, Clone, Default, PartialEq)] pub struct PlineVertex<T = f64> { pub x: T, pub y: T, pub bulge: T, } impl<T> Display for PlineVertex<T> where T: Display, { fn fmt(&self, f: &mut std::fmt::Form...
} } #[cfg(feature = "serde")] pub use serde_impl::*; impl<T> PlineVertex<T> where T: Real, { #[inline] pub fn new(x: T, y: T, bulge: T) -> Self { PlineVertex { x, y, bulge } } #[inline] pub fn from_slice(slice: &[T]) -> Option<Self> { if let [x, y, bulge] = ...
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let [x, y, bulge]: [T; 3] = Deserialize::deserialize(deserializer)?; Ok(PlineVertex { x, y, bulge }) }
function_block-full_function
[ { "content": "fn create_pline(vertexes: &[(f64, f64, f64)], is_closed: bool) -> *mut cavc_pline {\n\n let mut buffer = Vec::with_capacity(vertexes.len());\n\n for &(x, y, bulge) in vertexes {\n\n buffer.push(cavc_vertex::new(x, y, bulge));\n\n }\n\n\n\n let mut result = ptr::null();\n\n le...
Rust
src/github.rs
elba/elba-bot
06534c54f183e7602122c0f26537e2abf6568c27
use std::collections::HashMap; use std::time::Duration; use chrono::{DateTime, FixedOffset}; use reqwest::{ header::{self, HeaderMap}, Client, StatusCode, Url, }; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::json; use tokio::sync::RwLock; use tokio::time::delay_for; use crate::co...
use std::collections::HashMap; use std::time::Duration; use chrono::{DateTime, FixedOffset}; use reqwest::{ header::{self, HeaderMap}, Client, StatusCode, Url, }; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::json; use tokio::sync::RwLock; use tokio::time::delay_for; use crate::co...
}
g { format!( "https://api.github.com/repos/{}/issues/comments/{}", repo, comment_id ) }
function_block-function_prefixed
[ { "content": "fn github_repo_url(repo_name: &str) -> String {\n\n format!(\"https://github.com/{}.git\", repo_name)\n\n}\n", "file_path": "src/workspace/mod.rs", "rank": 0, "score": 169902.9705599253 }, { "content": "fn github_raw_url(head_hash: &str, manifest: &Manifest) -> String {\n\n ...
Rust
src/parse/fetch_attributes.rs
duesee/imap-codec
698b835cf1e0f3314f5a6d0ad0d7e86ae373a0e4
use std::num::NonZeroU32; use abnf_core::streaming::SP; use nom::{ branch::alt, bytes::streaming::{tag, tag_no_case}, combinator::{map, opt, value}, multi::separated_list1, sequence::{delimited, tuple}, IResult, }; use crate::{ parse::{ body::body, core::{nstring, number, n...
use std::num::NonZeroU32; use abnf_core::streaming::SP; use nom::{ branch::alt, bytes::streaming::{tag, tag_no_case}, combinator::{map, opt, value}, multi::separated_list1, sequence::{delimited, tuple}, IResult, }; use crate::{ parse::{ body::body, core::{nstring, number, n...
, )), |(_, section, byterange)| FetchAttribute::BodyExt { section, partial: byterange.map(|(start, _, end)| (start, end)), peek: true, }, ), map( tuple(( tag_no_case(b"BODY"), ...
opt(delimited( tag(b"<"), tuple((number, tag(b"."), nz_number)), tag(b">"), ))
call_expression
[ { "content": "/// section-spec = section-msgtext / (section-part [\".\" section-text])\n\nfn section_spec(input: &[u8]) -> IResult<&[u8], Section> {\n\n alt((\n\n map(section_msgtext, |part_specifier| match part_specifier {\n\n PartSpecifier::PartNumber(_) => unreachable!(),\n\n ...
Rust
kira-mp3/src/decoder.rs
Bombfuse/kira
d83d58bf37390b676e42741a534fc76ed598b130
use std::{ error::Error, fmt::{Display, Formatter}, fs::File, io::Seek, ops::Range, path::Path, }; use kira::Frame; #[derive(Debug)] pub enum DecoderError { UnsupportedChannelConfiguration, VariableSampleRate, UnknownSampleRate, IoError(std::io::Error), Mp3Error(minimp3::Error), } impl Display for Decoder...
use std::{ error::Error, fmt::{Display, Formatter}, fs::File, io::Seek, ops::Range, path::Path, }; use kira::Frame; #[derive(Debug)] pub enum DecoderError { UnsupportedChannelConfiguration, VariableSampleRate, UnknownSampleRate, IoError(std::io::Error), Mp3Error(minimp3::Error), } impl Display for Decoder...
{ self.ensure_packet().unwrap(); let CurrentPacket { packet, relative_frame_index } = self.current_packet.as_mut().expect( "ensure_packet should have either set self.current_packet to Some or returned an error" ); if frame_indices.contains(&self.frame_index) { frames.push(frame_from_packet(packet, ...
sample_rate { return Err(DecoderError::VariableSampleRate); } } else { sample_rate = Some(packet.sample_rate as u32); } if packet.channels > 2 { return Err(DecoderError::UnsupportedChannelConfiguration); } frame_count += packet.data.len() / packet.channels; } let sample_rate = sample...
random
[ { "content": "fn block_index_at_position(position: f64, sample_rate: u32) -> usize {\n\n\tlet frame_index = (position * sample_rate as f64) as usize;\n\n\tframe_index / BLOCK_SIZE\n\n}\n", "file_path": "kira/src/sound/streaming.rs", "rank": 2, "score": 179992.26660173768 }, { "content": "///...
Rust
main/rx/src/control_surface.rs
GavinRay97/reaper-rs
f2a999b98d1610d66c6ffe7c7de053ebea0f590b
use crate::{EventStreamSubject, ReactiveEvent}; use reaper_high::{AvailablePanValue, ChangeEvent, Fx, FxParameter, Project, Track, TrackRoute}; use reaper_medium::Pan; use rxrust::prelude::*; use std::cell::RefCell; use std::fmt; #[derive(Debug)] pub struct ControlSurfaceRxMiddleware { rx: ControlSurfaceRx, } imp...
use crate::{EventStreamSubject, ReactiveEvent}; use reaper_high::{AvailablePanValue, ChangeEvent, Fx, FxParameter, Project, Track, TrackRoute}; use reaper_medium::Pan; use rxrust::prelude::*; use std::cell::RefCell; use std::fmt; #[derive(Debug)] pub struct ControlSurfaceRxMiddleware { rx: ControlSurfaceRx, } imp...
pub fn project_switched(&self) -> impl ReactiveEvent<Project> { self.project_switched.borrow().clone() } pub fn global_automation_override_changed(&self) -> impl ReactiveEvent<()> { self.global_automation_override_changed.borrow().clone() } pub fn bookmarks_changed(&self) -> impl...
pub fn new() -> ControlSurfaceRx { fn default<T>() -> EventStreamSubject<T> { RefCell::new(LocalSubject::new()) } ControlSurfaceRx { main_thread_idle: default(), project_switched: default(), global_automation_override_changed: default(), ...
function_block-full_function
[ { "content": "pub fn get_track_fx_location(index: u32, is_input_fx: bool) -> TrackFxLocation {\n\n use TrackFxLocation::*;\n\n if is_input_fx {\n\n InputFxChain(index)\n\n } else {\n\n NormalFxChain(index)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug)]\n\npub struct FxInfo {\...
Rust
src/analyze/resolve/assign_parameterized_type.rs
noiz354/javaparser.rs
7165b63bd596e5ecfb1e1f16f21b0b9a6ce20650
use analyze::definition::{ Class, CompilationUnit, Decl, FieldDef, FieldGroup, MethodDef, Package, Root, }; use analyze::resolve::assign_type::{ resolve_and_replace_type, resolve_class_or_parameterized_type, resolve_type, }; use analyze::resolve::scope::Scope; use crossbeam_queue::SegQueue; use parse::tree::{Ty...
use analyze::definition::{ Class, CompilationUnit, Decl, FieldDef, FieldGroup, MethodDef, Package, Root, }; use analyze::resolve::assign_type::{ resolve_and_replace_type, resolve_class_or_parameterized_type, resolve_type, }; use analyze::resolve::scope::Scope; use crossbeam_queue::SegQueue; use parse::tree::{Ty...
else { new_extends.push(extend.clone()); } } type_param.extends.replace(new_extends); } scope.enter_class(class); for type_param in &class.type_params { scope.add_type_param(type_param); } for method in &class.methods { apply_method...
, scope: &mut Scope<'def, 'def_ref>) { match decl { Decl::Class(class) => apply_class(class, scope), Decl::Interface(interface) => (), } } fn apply_class<'def, 'def_ref>(class: &'def_ref Class<'def>, scope: &mut Scope<'def, 'def_ref>) { scope.enter(); for type_param in &class.type_param...
random
[ { "content": "pub fn apply(root: &mut Root) {\n\n let mut grapher = Grapher::new(root);\n\n grapher.collect();\n\n\n\n let queue = SegQueue::new();\n\n\n\n for &node_index in grapher.pool.iter() {\n\n queue.push(grapher.nodes.get(node_index).unwrap());\n\n }\n\n\n\n let mut threads = ve...
Rust
2020/src/day18.rs
Laguana/AdventOfCode
52c7049f5dab7f8631cdf172ac8a97dfa5c60202
#[test] fn part1_sample_works() { let input = parse_input("1 + 2 * 3 + 4 * 5 + 6"); let result = sum_exprs(&input); assert_eq!(result, 71); assert_eq!(evaluate(&parse_expr("2 * 3 + (4 * 5)")), 26); assert_eq!(evaluate(&parse_expr("5 + (8 * 3 + 9 + 3 * 4 * 3)")), 437); assert_eq!( evalua...
#[test] fn part1_sample_works() { let input = parse_input("1 + 2 * 3 + 4 * 5 + 6"); let result = sum_exprs(&input); assert_eq!(result, 71); assert_eq!(evaluate(&parse_expr("2 * 3 + (4 * 5)")), 26); assert_eq!(evaluate(&parse_expr("5 + (8 * 3 + 9 + 3 * 4 * 3)")), 437); assert_eq!( evalua...
fn parse_expr2_top(input: &[Token], i: usize) -> (usize, Expression) { let (j, e1) = parse_expr2_operand(input, i); parse_expr2_infix(input, j, e1) } fn parse_expr2(input: &str) -> Expression { let tokens = input.chars().filter(|c| *c != ' '); let tokens = tokens .map(|c| { if c >...
fn parse_expr2_operand(input: &[Token], i: usize) -> (usize, Expression) { match input[i] { Token::Char('(') => { let (j, e) = parse_expr2_top(input, i + 1); match input[j] { Token::Char(')') => (j + 1, e), _ => panic!("Unmatched paren"), }...
function_block-full_function
[ { "content": "pub fn part1() -> i32 {\n\n let input = parse_input(include_str!(\"inputs/day8.txt\"));\n\n return get_acc_when_looping(&input);\n\n}\n\n\n", "file_path": "2020/src/day8.rs", "rank": 4, "score": 253587.15589436181 }, { "content": "pub fn part1() -> usize {\n\n let inpu...
Rust
src/fuzz.rs
whentze/loom
5ec329bffb1d3091112b89dbf71b790d7b2d938d
use rt::{self, Execution, Scheduler}; use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, Instant}; const DEFAULT_MAX_THREADS: usize = 4; const DEFAULT_MAX_MEMORY: usize = 4096 << 14; const DEFAULT_MAX_BRANCHES: usize = 1_000; #[derive(Debug)] pub struct Builder { pub max_threads: usiz...
use rt::{self, Execution, Scheduler}; use std::path::PathBuf; use std::sync::Arc; use std::time::{Duration, Instant}; const DEFAULT_MAX_THREADS: usize = 4; const DEFAULT_MAX_MEMORY: usize = 4096 << 14; const DEFAULT_MAX_BRANCHES: usize = 1_000; #[derive(Debug)] pub struct Builder { pub max_threads: usiz...
) .map(|v| { let secs = v.parse().ok().expect("invalid value for `LOOM_MAX_DURATION`"); Duration::from_secs(secs) }) .ok(); let max_permutations = env::var("LOOM_MAX_PERMUTATIONS") .map(|v| { v.parse().ok().expect("...
untime = match &rt[..] { "thread" => Runtime::Thread, #[cfg(feature = "generator")] "generator" => Runtime::Generator, #[cfg(not(feature = "generator"))] "generator" => panic!("not compiled with `generator` feature"), #[cf...
function_block-random_span
[ { "content": "fn spawn_threads(n: usize) -> Vec<Thread> {\n\n (0..n).map(|_| {\n\n let stack = OsStack::new(STACK_SIZE).unwrap();\n\n\n\n let mut g: Thread = Generator::new(stack, move |yielder, _| {\n\n struct UnsetTls;\n\n\n\n impl Drop for UnsetTls {\n\n ...
Rust
src/chat/update.rs
mihai-dinculescu/slack-rust
ce011581bc7b4c5370d7c9c7b093a83007faf2ed
use crate::attachment::attachment::Attachment; use crate::block::blocks::Block; use crate::chat::message::Message; use crate::error::Error; use crate::http_client::{get_slack_url, ResponseMetadata, SlackWebAPIClient}; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; #[skip_serializing_none...
use crate::attachment::attachment::Attachment; use crate::block::blocks::Block; use crate::c
= UpdateResponse { ok: true, channel: Some("C024BE91L".to_string()), ts: Some("1401383885.000061".to_string()), text: Some("Updated text you carefully authored".to_string()), message: Some(Message { text: Some("Updated text you carefully author...
hat::message::Message; use crate::error::Error; use crate::http_client::{get_slack_url, ResponseMetadata, SlackWebAPIClient}; use serde::{Deserialize, Serialize}; use serde_with::skip_serializing_none; #[skip_serializing_none] #[derive(Deserialize, Serialize, Debug, Default, PartialEq)] pub struct UpdateRequest { ...
random
[ { "content": " use crate::http_client::{MockSlackWebAPIClient, SlackWebAPIClient};\n\n use crate::payloads::interactive::InteractiveEventType;\n\n use crate::socket::event::{\n\n DisconnectEvent, DisconnectReason, EventsAPI, HelloEvent, InteractiveEvent,\n\n SlashCommandsEvent,\n\n };\...
Rust
examples/1_trait_objects/interface/src/which_plugin.rs
h33p/abi_stable_crates
53ff4c222cd87db7b74f2224d62f1540fb7a4e8e
use crate::PluginId; use std::{ fmt::{self, Display}, str::FromStr, }; use arrayvec::ArrayVec; use abi_stable::{ std_types::{cow::BorrowingRCowStr, RCow, RString, RVec}, StableAbi, }; use core_extensions::{SelfOps, StringExt}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[repr(u...
use crate::PluginId; use std::{ fmt::{self, Display}, str::FromStr, }; use arrayvec::ArrayVec; use abi_stable::{ std_types::{cow::BorrowingRCowStr, RCow, RString, RVec}, StableAbi, }; use core_extensions::{SelfOps, StringExt}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[repr(u...
serde_() { let str_expected = new_str_expected(); for (_, elem) in str_expected { let str_ = serde_json::to_string(&elem).unwrap(); let other: WhichPlugin = serde_json::from_str(&str_).unwrap_or_else(|e| panic!("{}", e)); assert_eq!(other, elem); ...
map_err(de::Error::custom) } } impl Serialize for WhichPlugin { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.to_key().serialize(serializer) } } #[repr(transparent)] #[derive(Debug, Clone, StableAbi)] pub struct WhichPluginError(RStrin...
random
[ { "content": "/// Deserializes an `RCow<'a, str>` that borrows the string from the deserializer\n\n/// whenever possible.\n\n///\n\n///\n\n/// # Example\n\n///\n\n/// Defining a type containing an `RCow<'a, str>` which borrows from the deserializer.\n\n///\n\n/// ```\n\n/// use abi_stable::std_types::cow::{dese...
Rust
day14/src/main.rs
theonejb/advent-of-code-20
d0cbefd5ef88cae566df1260750c1c7d7a98a9ec
mod tests; use std::collections::HashMap; use regex; use std::path::Path; use std::fs::File; use std::io::{BufReader, BufRead}; /* We only keep the latest mask, and only store those memory locations which have been set to non-zero. This let's us not have to allocate ~68GB of memory for it. Seems like a good thing. *...
mod tests; use std::collections::HashMap; use regex; use std::path::Path; use std::fs::File; use std::io::{BufReader, BufRead}; /* We only keep the latest mask, and only store those memory locations which have been set to non-zero. This let's us not have to allocate ~68GB of memory for it. Seems like a good thing. *...
} pub fn compile_and_apply_instruction(&mut self, instruction: &str) { let instruction = DecoderChip::compile_instruction(instruction); self.apply_instruction(instruction); } pub fn compile_and_apply_instruction_v2(&mut self, instruction: &str) { let instruction = DecoderChip:...
match instruction { Instruction::SetMask(mask) => { self.mask = DecoderChip::compile_mask(&mask[..]); } Instruction::SetMemory(at, value) => { for memory_locations in self.mask.apply_mask_v2(at) { self.set_memory_locations.insert(me...
if_condition
[ { "content": "fn get_input(rules_filename: &str, data_filename: &str) -> (Vec<String>, Vec<String>) {\n\n let f = File::open(Path::new(rules_filename)).unwrap();\n\n let mut rules = vec![];\n\n for line in BufReader::new(f).lines() {\n\n rules.push(line.unwrap());\n\n }\n\n\n\n let f = Fil...
Rust
examples/pod_exec.rs
NAlexPear/kube-rs
3f0a5954db32edb247e987f70e77a0d5e6f6de30
#[macro_use] extern crate log; use futures::{StreamExt, TryStreamExt}; use k8s_openapi::api::core::v1::Pod; use kube::{ api::{Api, AttachParams, AttachedProcess, DeleteParams, ListParams, Meta, PostParams, WatchEvent}, Client, }; use tokio::io::AsyncWriteExt; #[tokio::main] async fn main() -> anyhow::Result<...
#[macro_use] extern crate log; use futures::{StreamExt, TryStreamExt}; use k8s_openapi::api::core::v1::Pod; use kube::{ api::{Api, AttachParams, AttachedProcess, DeleteParams, ListParams, Meta, PostParams, WatchEvent}, Client, }; use tokio::io::AsyncWriteExt; #[tokio::main] async fn main() -> anyhow::Result<...
} _ => {} } } { let attached = pods .exec( "example", vec!["sh", "-c", "for i in $(seq 1 3); do date; done"], &AttachParams::default().stderr(false), ) .await?; let output =...
if s.phase.clone().unwrap_or_default() == "Running" { info!("Ready to attach to {}", Meta::name(&o)); break; }
if_condition
[ { "content": "fn append_new_named<T, F>(base: &mut Vec<T>, next: Vec<T>, f: F)\n\nwhere\n\n F: Fn(&T) -> &String,\n\n{\n\n use std::collections::HashSet;\n\n base.extend({\n\n let existing = base.iter().map(|x| f(x)).collect::<HashSet<_>>();\n\n next.into_iter()\n\n .filter(|x|...
Rust
meilisearch-http/src/extractors/sequential_extractor.rs
Thearas/MeiliSearch
ae4e419db4da282c8301b807975c346e1953dbf4
#![allow(non_snake_case)] use std::{future::Future, pin::Pin, task::Poll}; use actix_web::{dev::Payload, FromRequest, Handler, HttpRequest}; use pin_project_lite::pin_project; #[derive(Clone)] pub struct SeqHandler<H>(pub H); pub struct SeqFromRequest<T>(T); macro_rules! gen_seq { ($ty:ident; $($T:ident)+) => {...
#![allow(non_snake_case)] use std::{future::Future, pin::Pin, task::Poll}; use actix_web::{dev::Payload, FromRequest, Handler, HttpRequest}; use pin_project_lite::pin_project; #[derive(Clone)] pub struct SeqH
quest(req, payload), }, )+ } } } impl<Han, $($T: FromRequest),+> Handler<SeqFromRequest<($($T),+)>> for SeqHandler<Han> where Han: Handler<($($T),+)>, { type Output = Han::Output; type Future = Han::Future; ...
andler<H>(pub H); pub struct SeqFromRequest<T>(T); macro_rules! gen_seq { ($ty:ident; $($T:ident)+) => { pin_project! { pub struct $ty<$($T: FromRequest), +> { $( #[pin] $T: ExtractFuture<$T::Future, $T, $T::Error>, )+ ...
random
[ { "content": "pub fn extract_user_agents(request: &HttpRequest) -> Vec<String> {\n\n request\n\n .headers()\n\n .get(USER_AGENT)\n\n .map(|header| header.to_str().ok())\n\n .flatten()\n\n .unwrap_or(\"unknown\")\n\n .split(';')\n\n .map(str::trim)\n\n ....
Rust
viewer/src/systems/follow_me.rs
arnodb/rhombus
3aefb1f6e789554978177111d53fce506221f9bf
use amethyst::{ core::{timing::Time, Transform}, derive::SystemDesc, ecs::prelude::*, }; use std::collections::{hash_map::Entry, HashMap}; pub struct FollowMeTag { pub target: Option<(Entity, f32)>, pub rotation_target: Option<(Entity, f32)>, } impl Component for FollowMeTag { type Storage = H...
use amethyst::{ core::{timing::Time, Transform}, derive::SystemDesc, ecs::prelude::*, }; use std::collections::{hash_map::Entry, HashMap}; pub struct FollowMeTag { pub target: Option<(Entity, f32)>, pub rotation_target: Option<(Entity, f32)>, } impl Component for FollowMeTag { type Storage = H...
}
fn run(&mut self, (mut transforms, follow_my_rotation_tags, time): Self::SystemData) { let delta_millis = { let duration = time.delta_time(); duration.as_secs() * 1000 + u64::from(duration.subsec_millis()) }; let mut target_transforms = HashMap::new(); for follow...
function_block-full_function
[ { "content": "#[test]\n\nfn test_rect_storage_should_have_entry_api() {\n\n #[derive(PartialEq, Eq, Debug)]\n\n struct Hex {\n\n value: usize,\n\n }\n\n let mut storage = RectStorage::new();\n\n\n\n // or_insert...\n\n // and_modify...\n\n assert_eq!(storage.get(3, 5), None);\n\n ...
Rust
src/math/division.rs
CmdrMoozy/euler
ae30dcaeb86b8442b5e7f95565f72175e6abeeb4
use crate::math::exp; use crate::math::prime; use crate::util::error::*; use std::ops::{Div, Rem}; pub fn divide<T: Copy + Div<Output = T> + Rem<Output = T>>(dividend: T, divisor: T) -> (T, T) { (dividend / divisor, dividend % divisor) } pub fn gcd(a: u64, b: u64) -> u64 { if a == 0 { return b; ...
use crate::math::exp; use crate::math::prime; use crate::util::error::*; use std::ops::{Div, Rem}; pub fn divide<T: Copy + Div<Output = T> + Rem<Output = T>>(dividend: T, divisor: T) -> (T, T) { (dividend / divisor, dividend % divisor) } pub fn gcd(a: u64, b: u64) -> u64 { if a == 0 { return b; ...
if u < v { v -= u; } else { let d = u - v; u = v; v = d; } v /= 2; } u << k } pub fn lcm(a: u64, b: u64) -> u64 { let gcd = gcd(a, b); match gcd { 0 => 0, _ => (a * b) / gcd, } } pub fn are_coprime(a: ...
while u % 2 == 0 { u /= 2; } while v != 0 { while v % 2 == 0 { v /= 2; }
random
[]
Rust
src/parser.rs
martin-olivier/ghfetch
0debc32b6836e012c4d64d66930f426087c1afaa
use colored::Colorize; use indexmap::IndexMap; use std::io::Read; fn help(bin: &str) { println!("USAGE:"); println!("\t{} [OPTIONS]\n", bin); println!("OPTIONS:"); println!("\t--help\t\tdisplay this help menu"); println!("\t--re\t\tremove the dependencies previously fetched and re-fetch them"); ...
use colored::Colorize; use indexmap::IndexMap; use std::io::Read; fn help(bin: &str) { println!("USAGE:"); println!("\t{} [OPTIONS]\n", bin); println!("OPTIONS:"); println!("\t--help\t\tdisplay this help menu"); println!("\t--re\t\tremove the dependencies previously fetched and re-fetch them"); ...
; let mut buff = String::new(); file.read_to_string(&mut buff).unwrap(); match toml::from_str(&buff) { Ok(val) => val, Err(err) => panic!("{} {} in \"{}\"", "Parsing error:".red().bold(), err, path) } } #[derive(serde::Deserialize)] struct DependencyParams { repo: Option<String>, ...
match std::fs::File::open(path) { Ok(f) => f, Err(_) => panic!("{} Could not load \"{}\"", "Missing config file:".red().bold(), path) }
if_condition
[]
Rust
src/raw/document_buf.rs
AaronErhardt/bson-rust
43f2fd664cd6f4a01889ba1e22b9efe5cf0ced02
use std::{ borrow::{Borrow, Cow}, convert::{TryFrom, TryInto}, iter::FromIterator, ops::Deref, }; use serde::{Deserialize, Serialize}; use crate::{ de::MIN_BSON_DOCUMENT_SIZE, spec::BinarySubtype, Document, RawBinaryRef, RawJavaScriptCodeWithScopeRef, }; use super::{ bson::Raw...
use std::{ borrow::{Borrow, Cow}, convert::{TryFrom, TryInto}, iter::FromIterator, ops::Deref, }; use serde::{Deserialize, Serialize}; use crate::{ de::MIN_BSON_DOCUMENT_SIZE, spec::BinarySubtype, Document, RawBinaryRef, RawJavaScriptCodeWithScopeRef, }; use super::{ bson::Raw...
pub fn iter(&self) -> Iter<'_> { self.into_iter() } pub fn into_bytes(self) -> Vec<u8> { self.data } ...
doc.to_writer(&mut data).map_err(|e| Error { key: None, kind: ErrorKind::MalformedValue { message: e.to_string(), }, })?; Ok(Self { data }) }
function_block-function_prefix_line
[ { "content": "fn append_test(expected: Document, append: impl FnOnce(&mut RawDocumentBuf)) {\n\n let bytes = crate::to_vec(&expected).unwrap();\n\n let mut buf = RawDocumentBuf::new();\n\n append(&mut buf);\n\n assert_eq!(buf.as_bytes(), bytes);\n\n}\n\n\n", "file_path": "src/raw/test/append.rs"...
Rust
rdftk_core/tests/language_tags.rs
johnstonskj/rust-rdftk
6741ddd9c14349ecdd0658058aa62cd7d8b81cd1
use rdftk_core::model::literal::LanguageTag; use std::str::FromStr; #[test] fn bcp_47_validator_01() { let result = LanguageTag::from_str("de"); assert!(result.is_ok()); if let Ok(LanguageTag::Tag(tag)) = result { println!("{:?}", tag); assert_eq!(tag.language(), &"de".to_string()); ...
use rdftk_core::model::literal::LanguageTag; use std::str::FromStr; #[test] fn bcp_47_validator_01() { let result = LanguageTag::from_str("de"); assert!(result.is_ok()); if let Ok(LanguageTag::Tag(tag)) = result { println!("{:?}", tag); assert_eq!(tag.language(), &"de".to_string()); ...
#[test] fn bcp_47_validator_13() { let result = LanguageTag::from_str("zh-TW"); assert!(result.is_ok()); if let Ok(LanguageTag::Tag(tag)) = result { println!("{:?}", tag); assert_eq!(tag.language(), &"zh".to_string()); assert!(tag.script().is_none()); assert_eq!(tag.region(...
assert_eq!(tag.region().unwrap(), &"IT".to_string()); assert_eq!( tag.variants().cloned().collect::<Vec<String>>(), vec!["arevela".to_string()] ); assert_eq!(tag.extensions().count(), 0); assert_eq!(tag.private_use().count(), 0); } else { panic!() ...
function_block-function_prefix_line
[ { "content": "fn lang_tag(input_pair: Pair<'_, Rule>) -> Result<Tag, Error> {\n\n if input_pair.as_rule() == Rule::lang_tag {\n\n let mut inner_pairs = input_pair.into_inner();\n\n let language = inner_pairs.next().unwrap().as_str().to_string();\n\n let mut script: Option<String> = None;...
Rust
src/lib.rs
ear7h/photos1
909e3696e36ab87c54e3bdc27a33525015914708
#![feature(crate_visibility_modifier)] mod double_buffer; pub use double_buffer::*; mod task_channel; use task_channel::TaskChannel; mod shaders; pub use shaders::{ Effects, EffectsShader, }; mod input; use input::Input; mod color; pub use color::*; mod utils; use utils::{ UniformsCons, create_dis...
#![feature(crate_visibility_modifier)] mod double_buffer; pub use double_buffer::*; mod task_channel; use task_channel::TaskChannel; mod shaders; pub use shaders::{ Effects, EffectsShader, }; mod input; use input::Input; mod color; pub use color::*; mod utils; use utils::{ UniformsCons, create_dis...
t { *control_flow = glutin::event_loop::ControlFlow::Poll; } egui_gl.paint(&display, &mut frame, shapes); frame.finish().unwrap(); }, (_, WindowEvent{ event, .. }) => { if egui_gl.is_quit_ev...
function_block-function_prefixed
[ { "content": "#[derive(Debug)]\n\nenum Msg {\n\n // Rename to OpenPhoto/OpenSingle/OpenEditor\n\n Open{\n\n path : PathBuf,\n\n },\n\n // TODO: when the database is implemented\n\n // this should be an enum:\n\n // enum PhotoSet {\n\n // Folder(String), // folder not in databas...
Rust
src/message_header.rs
murilobsd/calamp-rs
939f97340fb3d2b160fc1e3c2129d39ac474c50b
use nom::error::ErrorKind; use nom::number::streaming::{be_u16, be_u8}; use nom::IResult; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::fmt; #[derive(PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum MessageType { Null, AckNak, ...
use nom::error::ErrorKind; use nom::number::streaming::{be_u16, be_u8}; use nom::IResult; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::fmt; #[derive(PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum MessageType { Null, AckNak, ...
} impl fmt::Display for MessageType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { MessageType::Null => write!(f, "MessageType::Null"), MessageType::AckNak => write!(f, "MessageType::AckNak"), MessageType::EventReport => write!(f, "MessageTyp...
pub fn parse(input: &[u8]) -> IResult<&[u8], MessageType> { let (i, b): (&[u8], u8) = be_u8::<_, (_, ErrorKind)>(input).unwrap(); match b { 0 => Ok((i, MessageType::Null)), 1 => Ok((i, MessageType::AckNak)), 2 => Ok((i, MessageType::EventReport)), 3 => Ok...
function_block-full_function
[ { "content": "#[cfg(feature = \"serde\")]\n\nuse serde::{Deserialize, Serialize};\n\n\n\nconst OPTIONS_HEADER: u8 = 0x83;\n\n\n\n#[derive(Clone, PartialEq, Eq)]\n\n#[cfg_attr(feature = \"serde\", derive(Serialize, Deserialize))]\n\npub enum MobileIDType {\n\n Off,\n\n\n\n /// Electronic Serial Number (ESN...
Rust
src/node/parse.rs
yujixr/csvx
6934d876e3bde7d57d078867e88dcbcd355ade72
use super::*; pub fn parse(seq: &Vec<Token>) -> (Box<ThreadSafeNode>, Vec<(usize, usize)>) { if seq.first() == Some(&Token::ParenthesisEnd) && seq.last() == Some(&Token::ParenthesisBegin) { let inside_parentheses = &seq[1..seq.len() - 1]; let (_, has_depth_zero) = inside_parentheses ...
use super::*; pub fn parse(seq: &Vec<Token>) -> (Box<ThreadSafeNode>, Vec<(usize, usize)>) { if seq.first() == Some(&Token::ParenthesisEnd) && seq.last() == Some(&Token::ParenthesisBegin) { let inside_parentheses = &seq[1..seq.len() - 1]; let (_, has_depth_zero) = inside_parentheses ...
{ x } else if let Some(x) = parse_for_unary_operator( seq, &[(Token::Sub, minus::Node::new), (Token::Not, not::Node::new)], ) { x } else if let Some(x) = parse_for_function( seq, &[ (Token::FnRef, fn_ref::Node::new, 2), (Token::FnSum, ...
parse_for_binary_operator( seq, &[ (Token::Mul, mul::Node::new), (Token::Div, div::Node::new), (Token::Mod, modulo::Node::new), ], )
call_expression
[ { "content": "pub fn parse(primitive_tokens: Vec<PrimitiveToken>) -> Result<Vec<Token>, Box<dyn Error>> {\n\n let mut tokens = vec![];\n\n\n\n for token in primitive_tokens {\n\n tokens.push(match token {\n\n PrimitiveToken::Parsed(token) => token,\n\n PrimitiveToken::Raw(raw_...
Rust
src/entity.rs
dshomoye/rick-and-morty
3486187cdc1343a8d4aa7b9ce367fe258472048d
pub mod entity { use reqwest; pub use reqwest::Error; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; #[cfg(test)] use mockito; pub async fn get_url<T>(url: &str) -> Result<T, Error> where T: Deseriali...
pub mod entity { use reqwest; pub use reqwest::Error; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; #[cfg(test)] use mockito; pub async fn get_url<T>(url: &str) -> Result<T, Error> where T: Deseriali...
pub async fn get_all<T>(&self) -> Result<Vec<T>, Error> where T: DeserializeOwned, { let mut result: Vec<T> = vec![]; let mut url = self.base_url(); loop { let mut mr = get_url::<PageResponse<T>>(&url).await?; ...
serializeOwned, { let url = self.base_url() + "/" + &id.to_string(); let resp = get_url::<T>(&url).await?; Ok(resp) }
function_block-function_prefixed
[ { "content": "pub mod character;\n\npub mod episode;\n\npub mod location;\n", "file_path": "src/entities/mod.rs", "rank": 0, "score": 31420.715533834755 }, { "content": "use crate::entity::entity::*;\n\nuse crate::character::Character;\n\nuse serde::{Deserialize, Serialize};\n\nuse futures::...
Rust
rav1e-worker/src/server.rs
Luni-4/rav1e-by-gop
d87759676551f8075449677a43b9b04a4062e596
use crate::channels::SlotRequestSender; use crate::worker::SlotQueueItem; use crate::{ConnectedSocket, SwitchableStream}; use anyhow::Result; use bcrypt::{hash, verify, DEFAULT_COST}; use crossbeam_utils::thread::Scope; use http::StatusCode; use lazy_static::lazy_static; use log::{debug, error, info, warn}; use native_...
use crate::channels::SlotRequestSender; use crate::worker::SlotQueueItem; use crate::{ConnectedSocket, SwitchableStream}; use anyhow::Result; use bcrypt::{hash, verify, DEFAULT_COST}; use crossbeam_utils::thread::Scope; use http::StatusCode; use lazy_static::lazy_static; use log::{debug, error, info, warn}; use native_...
fn accept_callback(req: &Request, resp: Response) -> std::result::Result<Response, ErrorResponse> { let auth = req.headers().get("X-RAV1E-AUTH"); if let Some(password) = auth { if let Ok(password) = password.to_str() { if verify(password, &HASHED_SERVER_PASSWORD).unwrap() { ...
tem { connection, message, }) .unwrap(); return; } else { warn!( "Received unexpected binary-formatted message for connection {} whi...
function_block-function_prefixed
[ { "content": "fn wait_for_remote_data(mut connection: ConnectedSocket, slot_request: SlotRequestMessage) {\n\n loop {\n\n match connection.socket.read_message() {\n\n Ok(Message::Binary(data)) => {\n\n // This must be an encoder message, start the encode\n\n if...
Rust
advent2018/src/day17.rs
asoffer/advent-of-code-1
ca593f54c7be44196ce9431a34f5ba24023f0519
use std::collections::HashSet; use std::fs; use std::num::ParseIntError; use std::str::FromStr; pub fn run() { let (segs, a, b) = setup("inputs/17.txt"); let filled = fill_with_water(&segs, a, b); let num_filled = filled[segs.len()..].iter().map(|s| s.num_squares()).sum(); println!("Part 1: {}", part1(...
use std::collections::HashSet; use std::fs; use std::num::ParseIntError; use std::str::FromStr; pub fn run() { let (segs, a, b) = setup("inputs/17.txt"); let filled = fill_with_water(&segs, a, b); let num_filled = filled[segs.len()..].iter().map(|s| s.num_squares()).sum(); println!("Part 1: {}", part1(...
} return (None, left, right); } (None, None, None) } fn drop_down(xy: &(usize, usize), segments: &[LineSegment], max_y: usize) -> Option<usize> { let x = xy.0; let mut y = xy.1; while in_sand(x, y, &segments) { if y >= max_y { return None; } y +=...
x -= 1; } else { left = Some((x, y)); break; } } let x_min = x + 1; x = pt.0 + 1; while in_sand(x, y, &segments) { if in_clay(x, y + 1, &segments) { x += 1; } else { ...
random
[]
Rust
rust_impl/src/lib.rs
scimas/Hangman
54384c21e1e1ffd060cd3928546ac4e1a5830580
use std::fmt; #[derive(Debug, Clone)] struct Phrase { symbols: Vec<char>, visibility: Vec<bool>, visible_count: usize, } impl Phrase { fn new(s: &str) -> Self { let symbols: Vec<char> = s.chars().collect(); let mut visible_count = 0; let visibility = symbols .iter()...
use std::fmt; #[derive(Debug, Clone)] struct Phrase { symbols: Vec<char>, visibility: Vec<bool>, visible_count: usize, } impl Phrase { fn new(s: &str) -> Self { let symbols: Vec<char> = s.chars().collect(); let mut visible_count = 0; let visibility = symbols .iter()...
pub fn state(&self) -> GameState { self.state } pub fn guess_char(&mut self, guess: &char) -> GameState { match self.state { GameState::Lost | GameState::Won => (), GameState::PreStart | GameState::InProgress(_) => { if self.guesses.contains(guess) ...
let phrase = Phrase::new(phrase); let remaining_chances = 7; let state = GameState::PreStart; Self { phrase, guesses: vec![], remaining_chances, state, } }
function_block-function_prefix_line
[ { "content": "fn continue_game() -> bool {\n\n let mut input = get_input(\"Another game? [y]/n: \").expect(\"Error on std io\");\n\n while ![\"\", \"y\", \"n\"].contains(&input.trim()) {\n\n println!(\"Unrecognized option\");\n\n input = get_input(\"Another game? [y]/n: \").expect(\"Error on...
Rust
Engine/src/drawers/drawer_triangle.rs
nicolasgustafsson/3DMotorNicosKevin
2df776d11ba94ea326a5607ab0e9669231d8c2ea
use drawers::drawer_base::Drawer; use vulkano::buffer::BufferUsage; use vulkano::buffer::CpuAccessibleBuffer; use vulkano::device::Device; use vulkano::command_buffer::AutoCommandBufferBuilder; use vulkano::command_buffer::DynamicState; use vulkano::framebuffer::RenderPassAbstract; use vulkano::framebuffer::Subpass; u...
use drawers::drawer_base::Drawer; use vulkano::buffer::BufferUsage; use vulkano::buffer::CpuAccessibleBuffer; use vulkano::device::Device; use vulkano::command_buffer::AutoCommandBufferBuilder; use vulkano::command_buffer::DynamicState; use vulkano::framebuffer::RenderPassAbstract; use vulkano::framebuffer::Subpass; u...
TriangleDrawer { device, vertex_shader, fragment_shader, triangle_list : Vec::new() } } pub fn draw_triangle(&mut self, points : [[f32; 2]; 3]) { self.triangle_list.push(points); } } impl Drawer for TriangleDrawer { ...
let fragment_shader = fs::Shader::load(device.clone()).expect("Could not create fragment shader module for TriangleDrawer!");
assignment_statement
[ { "content": "fn main() {\n\n\n\n let mut event_loop = winit::EventsLoop::new();\n\n\n\n let mut instance = vulkano_instance::VulkanoInstance::new(&mut event_loop);\n\n\n\n let mut run = true;\n\n\n\n let bench_length = std::time::Duration::new(3, 0);\n\n\n\n let mut benchmarker = benchmarks::ben...
Rust
tests/number/evaluate.rs
rolandbernard/matheval
fb73a3b523fe71e30854a98bc14cde71bc55e055
use std::ops::Add; use std::str::FromStr; use matheval::Context; use matheval::Expr; use matheval::Number; use matheval::NumberContext; #[test] fn simple_integer_literal() { let parsed = Expr::parse("98765432109876543210") .expect("Failed parsing simple integer literal"); assert_eq!( Number::...
use std::ops::Add; use std::str::FromStr; use matheval::Context; use matheval::Expr; use matheval::Number; use matheval::NumberContext; #[test] fn simple_integer_literal() { let parsed = Expr::parse("98765432109876543210") .expect("Failed parsing simple integer literal"); assert_eq!( Number::...
on failed").to_string()); } #[test] fn context_variable() { let mut context = NumberContext::new(); context.set_variable("x", Number::from_str("12").expect("Failed parsing number")); let parsed = Expr::parse("42x") .expect("Failed parsing variable 'x'"); assert_eq!("504", parsed.eval_in(&contex...
'pi'"); assert_eq!("3.141592653589793", parsed.eval::<Number>().expect("Evaluation failed").to_string()); let parsed = Expr::parse("e ^ 2") .expect("Failed parsing constant 'e^2'"); assert_eq!("7.3890560989306495", parsed.eval::<Number>().expect("Evaluation failed").to_string()); let parsed = Ex...
function_block-random_span
[ { "content": "#[test]\n\nfn mixed_mul_div_pow() {\n\n let parsed = Expr::parse(\"5 / (6Hz)^4 + (41s^2)^2 / 2^13\")\n\n .expect(\"Failed parsing mixed mul/div/pow\");\n\n assert_eq!(\"138721/663552 s^4\", parsed.eval::<Quantity>().expect(\"Evaluation failed\").to_string());\n\n}\n\n\n", "file_pa...
Rust
dhall/src/phase/resolve.rs
FintanH/dhall-rust
bcaeab3b7b114d8782be9589ad673ab9ab8c59fd
use std::collections::HashMap; use std::path::{Path, PathBuf}; use crate::error::{Error, ImportError}; use crate::phase::{Normalized, NormalizedExpr, Parsed, Resolved}; type Import = dhall_syntax::Import<NormalizedExpr>; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum ImportRoot { LocalDir(PathBuf), } ty...
use std::collections::HashMap; use std::path::{Path, PathBuf}; use crate::error::{Error, ImportError}; use crate::phase::{Normalized, NormalizedExpr, Parsed, Resolved}; type Import = dhall_syntax::Import<NormalizedExpr>; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum ImportRoot { LocalDir(PathBuf), } ty...
fn do_resolve_expr( parsed: Parsed, import_cache: &mut ImportCache, import_stack: &ImportStack, ) -> Result<Resolved, ImportError> { let Parsed(mut expr, root) = parsed; let mut resolve = |import: Import| -> Result<Normalized, ImportError> { if import_stack.contains(&import) { ...
Ok( do_resolve_expr(Parsed::parse_file(f)?, import_cache, import_stack)? .typecheck()? .normalize(), ) }
function_block-function_prefix_line
[ { "content": "fn apply_special_attrs(f: &mut ParsedFn, rule_enum: &Ident) -> Result<()> {\n\n let function = &mut *f.function;\n\n let fn_name = &f.fn_name;\n\n let input_arg = &f.input_arg;\n\n\n\n *function = parse_quote!(\n\n #[allow(non_snake_case)]\n\n #function\n\n );\n\n\n\n ...
Rust
vrp-core/tests/unit/algorithms/clustering/dbscan_test.rs
PeakBI/ds-reinterpretcat-vrp
62428fdd5438812ddcf37583a14b9a26bdb43225
use super::*; use crate::algorithms::geometry::Point; use crate::helpers::construction::clustering::p; use rosomaxa::prelude::compare_floats; fn create_index(points: &Vec<Point>) -> HashMap<&Point, Vec<(&Point, f64)>> { points.iter().fold(HashMap::new(), |mut acc, point| { assert!(acc.get(point).is_none())...
use super::*; use crate::algorithms::geometry::Point; use crate::helpers::construction::clustering::p; use rosomaxa::prelude::compare_floats; fn create_index(points: &Vec<Point>) -> HashMap<&Point, Vec<(&Point, f64)>> { points.iter().fold(HashMap::new(), |mut acc, point| { assert!(acc.get(point).is_none())...
p(56.445776311447844, 45.162093662656844), p(57.36691949656233, 47.50097194337286), p(58.243626387557015, 46.114052729681134), p(56.27224595635198, 44.799080066150054), p(57.606924816500396, 46.94291057763621), p(30.18714230041951, 13.877149710431695), p(30.4494488106...
098873608, 33.92584423092194), p(73.9657889183145, 35.73191006924026), p(74.0074097183533, 36.81735596177168), p(73.41247541410848, 34.27314856695011), p(73.9156256353017, 36.83206791547127), p(74.81499205809087, 37.15682749846019), p(74.03144880081527, 37.57399178552441)...
random
[ { "content": "pub fn generate_matrix_distances_from_points(points: &[Point]) -> Vec<f64> {\n\n points.iter().cloned().flat_map(|p_a| points.iter().map(move |p_b| p_a.distance_to_point(p_b))).collect()\n\n}\n", "file_path": "vrp-core/tests/helpers/solver/mod.rs", "rank": 1, "score": 398687.8204957...
Rust
src/client_server/read_marker.rs
nekrondev/conduit_rockdb
f47d89eca32dd1237ddc4c460abd3d240a8ebb3c
use crate::{database::DatabaseGuard, ConduitResult, Error, Ruma}; use ruma::{ api::client::{ error::ErrorKind, r0::{read_marker::set_read_marker, receipt::create_receipt}, }, events::{AnyEphemeralRoomEvent, EventType}, receipt::ReceiptType, MilliSecondsSinceUnixEpoch, }; use std::col...
use crate::{database::DatabaseGuard, ConduitResult, Error, Ruma}; use ruma::{ api::client::{ error::ErrorKind, r0::{read_marker::set_read_marker, receipt::create_receipt}, }, events::{AnyEphemeralRoomEvent, EventType}, receipt::ReceiptType, MilliSecondsSinceUnixEpoc
om_id, AnyEphemeralRoomEvent::Receipt(ruma::events::receipt::ReceiptEvent { content: ruma::events::receipt::ReceiptEventContent(receipt_content), room_id: body.room_id.clone(), }), &db.globals, )?; } db.flush()?; Ok(set_read_marke...
h, }; use std::collections::BTreeMap; #[cfg(feature = "conduit_bin")] use rocket::post; #[cfg_attr( feature = "conduit_bin", post("/_matrix/client/r0/rooms/<_>/read_markers", data = "<body>") )] #[tracing::instrument(skip(db, body))] pub async fn set_read_marker_route( db: DatabaseGuard, body: Ruma<se...
random
[ { "content": "fn convert_error(error: heed::Error) -> Error {\n\n Error::HeedError {\n\n error: error.to_string(),\n\n }\n\n}\n\n\n\nimpl DatabaseEngine for Engine {\n\n fn open(config: &Config) -> Result<Arc<Self>> {\n\n let mut env_builder = heed::EnvOpenOptions::new();\n\n env_b...
Rust
src/sys/unix/console.rs
sl-sh-dev/sl-console
7da43882de1673e53326244f540f38f5b38dada6
use libc::{self, fd_set, suseconds_t, time_t, timeval}; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; use std::os::unix::fs::OpenOptionsExt; use std::os::unix::io::{AsRawFd, RawFd}; use std::time::Duration; use super::Termios; use crate::sys::attr::{get_terminal_attr_fd, raw_terminal_attr, set_...
use libc::{self, fd_set, suseconds_t, time_t, timeval}; use std::fs::{File, OpenOptions}; use std::io::{self, Read, Write}; use std::os::unix::fs::OpenOptionsExt; use std::os::unix::io::{AsRawFd, RawFd}; use std::time::Duration; use super::Termios; use crate::sys::attr::{get_terminal_attr_fd, raw_terminal_attr, set_...
pub(crate) fn read_block(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.poll(); self.read(buf) } } impl Read for SysConsoleIn { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.tty.read(buf) } } impl AsRawFd for SysConsoleOut { fn as_r...
pub fn poll_timeout(&mut self, timeout: Duration) -> bool { let tty_fd = self.tty.as_raw_fd(); let mut rfdset: fd_set = unsafe { std::mem::MaybeUninit::zeroed().assume_init() }; unsafe { libc::FD_ZERO(&mut rfdset); libc::FD_SET(tty_fd, &mut rfdset); } let ...
function_block-full_function
[ { "content": "/// Parse an Event from `item` and possibly subsequent bytes through `iter`.\n\npub fn parse_event<I>(item: u8, iter: &mut I) -> io::Result<Event>\n\nwhere\n\n I: Iterator<Item = io::Result<u8>>,\n\n{\n\n fn inner_parse_event<I>(item: u8, iter: &mut I) -> io::Result<Event>\n\n where\n\n ...
Rust
packages/wasm-game-of-life/src/lib.rs
CJSmith-0141/wasm-vite-svelte-monorepo
72524a6a7cfd634598c1ac9ca5dc874af2ca18ca
mod utils; extern crate web_sys; use wasm_bindgen::prelude::*; use nalgebra::geometry::Point2; use std::fmt; use js_sys::Uint8Array; use std::convert::TryInto; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] #[repr(u8)] #[derive(Clone, ...
mod utils; extern crate web_sys; use wasm_bindgen::prelude::*; use nalgebra::geometry::Point2; use std::fmt; use js_sys::Uint8Array; use std::convert::TryInto; #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] #[repr(u8)] #[derive(Clone, ...
} impl Cell { fn toggle(&mut self) { *self = match *self { Cell::Dead => Cell::Alive, Cell::Alive => Cell::Dead, }; } } macro_rules! log { ( $( $t:tt) *) => { web_sys::console::log_1(&format!( $( $t )* ).into()); } }
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for line in self.cells.as_slice().chunks(self.width as usize) { for &cell in line { let symbol = if cell == Cell::Dead { '◻' } else { '◼' }; write!(f, "{}", symbol)?; } write!(f, "\n")?; ...
function_block-full_function
[ { "content": "#[wasm_bindgen(js_name=\"helloWorld\")]\n\npub fn hello_world(name: Option<String>) {\n\n match name {\n\n Some(name) => alert(format!(\"Hello {}\", name)),\n\n None => alert(String::from(\"Hello world!\"))\n\n }\n\n}\n", "file_path": "packages/rust/src/lib.rs", "rank":...
Rust
akaze/src/evolution.rs
That1Guy007/cv
52f818ec5e5f6059dd5ffc4e221383287dec08a8
use crate::{fed_tau, Akaze, GrayFloatImage}; use log::*; #[derive(Debug)] #[allow(non_snake_case)] pub struct EvolutionStep { pub etime: f64, pub esigma: f64, pub octave: u32, pub sublevel: u32, pub sigma_size: u32, pub Lt: GrayFloatImage, pub Lsmooth: Gra...
use crate::{fed_tau, Akaze, GrayFloatImage}; use log::*; #[derive(Debug)] #[allow(non_snake_case)] pub struct EvolutionStep { pub etime: f64, pub esigma: f64, pub octave: u32, pub sublevel: u32, pub sigma_size: u32, pub Lt: GrayFloatImage, pub Lsmooth: Gra...
}) .flatten() .collect(); for i in 1..evolutions.len() { let ttime = evolutions[i].etime - evolutions[i - 1].etime; evolutions[i].fed_tau_steps = fed_tau::fed_tau_by_proce...
if smallest_dim < 40 { None } else { let sublevels = if smallest_dim < 80 { 1 } else { self.num_sublevels }; ...
if_condition
[ { "content": "pub fn export(mut writer: impl Write, points_and_colors: Vec<(Point3<f64>, [u8; 3])>) {\n\n // crete a ply objet\n\n let mut ply = Ply::<DefaultElement>::new();\n\n ply.header.encoding = Encoding::Ascii;\n\n ply.header\n\n .comments\n\n .push(\"Exported from rust-cv/vslam...
Rust
crates/apollo-encoder/src/object_def.rs
isabella232/apollo-rs
963b3552deaf7ba3a7eb5a698a90f20d0fc08242
use std::fmt; use crate::{Directive, FieldDefinition, StringValue}; #[derive(Debug)] pub struct ObjectDefinition { name: String, description: StringValue, interfaces: Vec<String>, fields: Vec<FieldDefinition>, directives: Vec<Directive>, extend: bool, } impl ObjectDef...
use std::fmt; use crate::{Directive, FieldDefinition, StringValue}; #[derive(Debug)] pub struct ObjectDefinition { name: String, description: StringValue, interfaces: Vec<String>, fields: Vec<FieldDefinition>, directives: Vec<Directive>, extend: bool, } impl ObjectDef...
#[test] fn it_encodes_object_with_block_string_description() { let ty_1 = Type_::NamedType { name: "String".to_string(), }; let mut field = FieldDefinition::new("name".to_string(), ty_1); field.description(Some("multiline\ndescription".to_string())); let m...
String::from("first"), Value::String("one".to_string()), )); let ty_2 = Type_::List { ty: Box::new(ty_1) }; let mut field = FieldDefinition::new("toys".to_string(), ty_2); let mut deprecated_directive = Directive::new(String::from("deprecated")); deprecated_directive....
function_block-function_prefix_line
[ { "content": "fn implements_interface(p: &mut Parser, is_interfaces: bool) {\n\n match p.peek() {\n\n Some(T![&]) => {\n\n p.bump(S![&]);\n\n implements_interface(p, is_interfaces)\n\n }\n\n Some(TokenKind::Name) => {\n\n ty::named_type(p);\n\n ...
Rust
src/graphics/buffer_drawer.rs
gifnksm/sabios
a0729dbdaafbbc318c6bc13636a3a17a842c782b
use crate::{ graphics::{Color, Draw, Offset, Point, Rectangle, ScreenInfo, Size}, prelude::*, }; use alloc::{vec, vec::Vec}; use bootloader::boot_info::{FrameBuffer, PixelFormat}; use core::{cmp::Ordering, convert::TryFrom, ptr}; use custom_debug_derive::Debug as CustomDebug; use derivative::Derivative; pub(cr...
use crate::{ graphics::{Color, Draw, Offset, Point, Rectangle, ScreenInfo, Size}, prelude::*, }; use alloc::{vec, vec::Vec}; use bootloader::boot_info::{FrameBuffer, PixelFormat}; use core::{cmp::Ordering, convert::TryFrom, ptr}; use custom_debug_derive::Debug as CustomDebug; use derivative::Derivative; pub(cr...
dx = self.pixel_index(dst.pos + dp)?; let src_idx = self.pixel_index(src.pos + dp)?; let dst_ptr = self.buffer.buffer_mut()[dst_idx..].as_mut_ptr(); let src_ptr = self.buffer.buffer()[src_idx..].as_ptr(); unsafe { ptr::copy(...
let dp = Point::new(0, dy); let dst_idx = self.pixel_index(dst.pos + dp)?; let src_idx = self.pixel_index(src.pos + dp)?; let dst_ptr = self.buffer.buffer_mut()[dst_idx..].as_mut_ptr(); let src_ptr = self.buffe...
random
[ { "content": "fn draw(drawer: &mut dyn Draw, size: Size<i32>) {\n\n drawer.fill_rect(\n\n Rectangle::new(Point::new(0, 0), Size::new(size.x, size.y - 50)),\n\n BG_COLOR,\n\n );\n\n drawer.fill_rect(\n\n Rectangle::new(Point::new(0, size.y - 50), Size::new(size.x, 50)),\n\n C...
Rust
examples/monitor/renderer.rs
lemunozm/torophy
790680c8084a38db043f70ed84f91c59f5074442
use glium::{implement_vertex, uniform, Display, Program, Frame, Surface}; #[derive(Copy, Clone)] pub struct Vertex { position: [f32; 2], } implement_vertex!(Vertex, position); impl Vertex { pub fn new(x: f32, y: f32) -> Vertex { Vertex { position: [x, y] } } } pub struct Color { data: [f32; ...
use glium::{implement_vertex, uniform, Display, Program, Frame, Surface}; #[derive(Copy, Clone)] pub struct Vertex { position: [f32; 2], } implement_vertex!(Vertex, position); impl Vertex { pub fn new(x: f32, y: f32) -> Vertex { Vertex { position: [x, y] } } } pub struct Color { data: [f32; ...
if limits_exceeded == 2 { draw(position.0 + self.dimension.0, position.1 + self.dimension.1); draw(position.0 + self.dimension.0, position.1 - self.dimension.1); draw(position.0 - self.dimension.0, position.1 + self.dimension.1); draw(position.0 - self.dimension...
if position.1 + radius > self.dimension.1 { draw(position.0, position.1 - self.dimension.1); limits_exceeded += 1; }
if_condition
[ { "content": "pub fn draw_space(renderer: &Renderer, target: &mut glium::Frame, space: &Space) {\n\n let mut rng = StdRng::seed_from_u64(1);\n\n for body in space.bodies() {\n\n let position = body.position();\n\n let color = Color::rgb(rng.gen_range(0.2, 0.8), rng.gen_range(0.2, 0.8), rng.g...
Rust
src/authority.rs
turboflakes/skipper
594a4b6212df530a64ddb4ad4d7a2ea296e0601c
use crate::config::CONFIG; use crate::errors::ScoutyError; use codec::Decode; use log::debug; use sp_consensus_babe::digests::PreDigest; use std::{collections::BTreeMap, convert::TryInto, result::Result, str::FromStr}; use subxt::{ rpc::ChainBlock, sp_runtime::{traits::Header, AccountId32, Digest, DigestItem}...
use crate::config::CONFIG; use crate::errors::ScoutyError; use codec::Decode; use log::debug; use sp_consensus_babe::digests::PreDigest; use std::{collections::BTreeMap, convert::TryInto, result::Result, str::FromStr}; use subxt::{ rpc::ChainBlock, sp_runtime::{traits::Header, AccountId32, Digest, DigestItem}...
*record, None => 0, } } pub fn previous_session_total(&self, stash: &AccountId32) -> u32 { let session_index = self.current_session_index - 1; let key = format!("{}:{}", session_index, stash); match self.records.get(&key) { Some(record) => *record, ...
ession_total(&self, stash: &AccountId32) -> u32 { let key = format!("{}:{}", self.current_session_index, stash); match self.records.get(&key) { Some(record) =>
function_block-random_span
[ { "content": "pub fn median(list: &mut Vec<u32>) -> u32 {\n\n if list.len() == 0 {\n\n return 0;\n\n }\n\n list.sort();\n\n let mid = list.len() / 2;\n\n list[mid]\n\n}\n\n\n", "file_path": "src/stats.rs", "rank": 0, "score": 146167.08948451563 }, { "content": "// Find ...
Rust
meilisearch-types/src/star_or.rs
meilisearch/meilisearch
4fc73195e6187101b3e24215997f61550674c381
use serde::de::Visitor; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt::{Display, Formatter}; use std::marker::PhantomData; use std::ops::Deref; use std::str::FromStr; #[derive(Debug)] pub enum StarOr<T> { Star, Other(T), } impl<T: FromStr> FromStr for StarOr<T> { type Err = T...
use serde::de::Visitor; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::fmt::{Display, Formatter}; use std::marker::PhantomData; use std::ops::Deref; use std::str::FromStr; #[derive(Debug)] pub enum StarOr<T> { Star, Other(T), } impl<T: FromStr> FromStr for StarOr<T> { type Err = T...
} impl<T> Serialize for StarOr<T> where T: Deref<Target = str>, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { StarOr::Star => serializer.serialize_str("*"), StarOr::Other(other) => serializer.serialize_str...
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct StarOrVisitor<T>(PhantomData<T>); impl<'de, T, FE> Visitor<'de> for StarOrVisitor<T> where T: FromStr<Err = FE>, ...
function_block-full_function
[ { "content": "#[rustfmt::skip]\n\nfn task_type_matches_content(type_: &TaskType, content: &TaskContent) -> bool {\n\n matches!((type_, content),\n\n (TaskType::IndexCreation, TaskContent::IndexCreation { .. })\n\n | (TaskType::IndexUpdate, TaskContent::IndexUpdate { .. })\n\n | (TaskTy...
Rust
src/address.rs
elmurci/xpring-rs
7bc1a03c62b75682035058e7c905c65369384de2
use crate::javascript::{JavaScript, JsCall}; use anyhow::Error; use fehler::throws; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize)] struct XAddressOptions { #[serde(skip_serializing_if = "Option::is_none")] classic_address: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] ...
use crate::javascript::{JavaScript, JsCall}; use anyhow::Error; use fehler::throws; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize)] struct XAddressOptions { #[serde(skip_serializing_if = "Option::is_none")] classic_address: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] ...
ontext, "xrp").unwrap_err(); assert_eq!( "Invalid Address", x_address.downcast_ref::<String>().unwrap() ); } #[throws(_)] #[test] fn test_is_valid_x_address_with_classic_address() { let out_dir = std::env::var("OUT_DIR").unwrap(); let mut jscontex...
t out_dir = std::env::var("OUT_DIR").unwrap(); let mut jscontext = JavaScript::new(format!("{}/xpring.js", out_dir))?; let x_address = decode_x_address(&mut jsc
function_block-random_span
[ { "content": "#[throws(_)]\n\npub fn is_valid_address(jscontext: &mut JavaScript, address: &str) -> bool {\n\n address::is_valid_address(jscontext, address)?\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 178717.09451076505 }, { "content": "#[throws(_)]\n\npub fn is_valid_x_...
Rust
src/days/day23.rs
RoccoDev/aoc-2021
22a0697b2055d56c50c1a28da0e6dc92d29bba08
use itertools::Itertools; use pathfinding::prelude::dijkstra; #[allow(clippy::ptr_arg)] fn calc_moves(grid: &Vec<Vec<u8>>) -> Vec<(Vec<Vec<u8>>, usize)> { let room_y_len = grid.len() - 2; let mut moves = Vec::with_capacity(25); let hallway = &grid[1]; for x in 0..hallway.len() { let (destinatio...
use itertools::Itertools; use pathfinding::prelude::dijkstra; #[allow(clippy::ptr_arg)] fn calc_moves(grid: &Vec<Vec<u8>>) -> Vec<(Vec<Vec<u8>>, usize)> { let room_y_len = grid.len() - 2; let mut moves = Vec::with_capacity(25); let hallway = &grid[1]; for x in 0..hallway.len() { let (destinatio...
part2(input: &[Vec<u8>]) -> usize { let mut input = input.to_owned(); input.insert(3, " #D#B#A#C#".bytes().collect()); input.insert(3, " #D#C#B#A#".bytes().collect()); find_path(&input) } #[cfg(test)] mod tests { use super::*; #[test] fn part1_example() { let input = r#"########...
ontains(&i) { continue; } let mut next_grid = grid.to_owned(); next_grid[1][i] = grid[y][x]; next_grid[y][x] = b'.'; moves.push((next_grid, (y - 1 + x - i) * cost)); } } moves } #[allow(clippy::ptr_arg)] fn find_path(maze: &Vec<Vec<u8>>) -> usize { di...
random
[ { "content": "fn run_game(scores: [usize; 2], positions: [usize; 2], cache: &mut FxHashMap<GameState, [usize; 2]>) -> [usize; 2] {\n\n if scores[0] >= 21 {\n\n return [1, 0]; // P0 won\n\n } else if scores[1] >= 21 {\n\n return [0, 1]; // P1 won\n\n }\n\n let game_state = GameState {\n...
Rust
src/file_management/seting.rs
rifqideveloper/indosanca
5cb2c5811884cf866712935091baeeb7788e4bc2
use std::path::Path; use std::io::prelude::*; use std::fs::File; use std::io::{ BufReader}; use serde_derive::Deserialize; #[derive(Deserialize)] struct Seting{ nama_app :String, versi :String, pembuat :Vec<String>, kompilasi:Vec<String>, turbo:bool, } #[derive(Deserialize)] struct dep{ } #[d...
use std::path::Path; use std::io::prelude::*; use std::fs::File; use std::io::{ BufReader}; use serde_derive::Deserialize; #[derive(Deserialize)] struct Seting{ nama_app :String, versi :String, pembuat :Vec<String>, kompilasi:Vec<String>, turbo:bool, } #[derive(Deserialize)] struct dep{ } #[d...
use futures::future; async fn buat_dir(path:String){ if let Err(_) = std::fs::create_dir_all(&path) { println!("tidak dapat membuat target direktori '{0}\\kode' ?",path); std::process::exit(1); } } async fn bangun_proyek(f:& String){ future::join4( buat_dir(format!("{}\\kode",f)), ...
fn buat_seting_file(f:& String){ match File::create(format!("{}\\seting.toml",f)) { Ok(mut o)=>{ if let Err(_) = o.write_all(b"\ [seting]\ \nnama_app = \"app\"\ \nversi = \"0.1.0\"\ \npembuat = [\"?\"]\ \nkompilasi = [\"wasm\"]\ ...
function_block-full_function
[ { "content": "#[derive(RustEmbed)]\n\n#[folder = \"asset/\"]\n\n#[prefix = \"prefix/\"]\n\nstruct Asset;\n", "file_path": "src/dok.rs", "rank": 5, "score": 49423.398405881606 }, { "content": "struct App {\n\n data:u32,\n\n window_:druid::WindowDesc<u32>\n\n}\n\nimpl App{\n\n //fn mo...
Rust
src/bitmap.rs
LucioFranco/BitMap-rs
534f1dc90b76e4e2aa0cc1f8df12245d742c927a
use std::io::{Write, Read, Seek, SeekFrom}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use super::image::{Image, Pixel}; use super::Error; #[derive(Debug, Clone, PartialEq, Eq)] #[allow(non_snake_case)] pub struct Header { pub bfSize: u32, pub zero: u32, pub bfOffBits: u32, pub biSi...
use std::io::{Write, Read, Seek, SeekFrom}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use super::image::{Image, Pixel}; use super::Error; #[derive(Debug, Clone, PartialEq, Eq)] #[allow(non_snake_case)] pub struct Header { pub bfSize: u32, pub zero: u32, pub bfOffBits: u32, pub biSi...
#[test] fn body_load_32bit() { let mut img = File::open("images/mountain.bmp").unwrap(); let mut header = Header::new(); assert!(header.load(&mut img).is_ok()); assert_eq!(header.biBitCount, 32u16); let mut body = Body::new(header); assert!(body.load(&mut img)...
fn header_save() { let mut header1 = Header::new(); header1.biWidth = 100; header1.biHeight = 200; let mut buf1 = File::create("target/test1.bmp").unwrap(); header1.save(&mut buf1); let mut header2 = Header::new(); let mut buf2 = File::open("target/test1.bmp").u...
function_block-full_function
[ { "content": "#[bench]\n\nfn detect_edges(b: &mut Bencher) {\n\n let mut buf = File::open(\"images/mountain.bmp\").unwrap();\n\n let mut bm = BitMap::load(&mut buf).unwrap();\n\n\n\n b.iter(|| {\n\n bm.apply_effect(EdgeDetection::default());\n\n });\n\n\n\n}\n", "file_path": "benches/edge...
Rust
src/arch/aarch64/context/scheduler.rs
Sh4d1/rustberry
207bdb8997ab444046fa2fb9da718aae051941b2
use super::process::{Id, Process, State}; use alloc::collections::vec_deque::VecDeque; use arch::exceptions::TrapFrame; use spin::Mutex; pub const TICK: u32 = 2 * 1000 * 1000; #[derive(Debug)] pub struct GlobalScheduler(Mutex<Option<Scheduler>>); impl GlobalScheduler { pub const fn uninitialized() -> GlobalSched...
use super::process::{Id, Process, State}; use alloc::collections::vec_deque::VecDeque; use arch::exceptions::TrapFrame; use spin::Mutex; pub const TICK: u32 = 2 * 1000 * 1000; #[derive(Debug)] pub struct GlobalScheduler(Mutex<Option<Scheduler>>); impl GlobalScheduler { pub const fn uninitialized() -> GlobalSched...
process.trap_frame.tpidr = self.last_id.unwrap(); self.processes.push_back(process); self.last_id } fn switch(&mut self, new_state: State, tf: &mut TrapFrame) -> Option<Id> { if self.processes.is_empty() { unsafe { asm!("wfi" :::: "volatile"); ...
-> Option<Id> { if self.last_id.is_none() { self.last_id = Some(0); self.current = Some(0); } else { self.last_id = Some(self.last_id.unwrap() + 1); }
function_block-random_span
[ { "content": "pub fn tick_in(us: u32) {\n\n GenericTimer::new().tick_in(us);\n\n}\n", "file_path": "src/io/generic_timer.rs", "rank": 0, "score": 137344.994271866 }, { "content": "pub fn handle_irq(interrupt: Interrupt, tf: &mut TrapFrame) {\n\n // kprintln!(\"{:?}\", interrupt);\n\...
Rust
crates/air-lib/trace-handler/src/merger/fold_merger/fold_lore_resolver.rs
fluencelabs/aquavm
6df4e470d37bdbfeb128e55815e73f7ab34fbaeb
/* * Copyright 2021 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 2021 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...
value_pos: 0, subtraces_desc: vec![SubTraceDesc::new(0, 3), SubTraceDesc::new(0, 3)], }, ]; let fold_result = FoldResult { lore }; let slider = TraceSlider::new(vec![ExecutedState::Ap(ApResult::new(vec![0]))]); let ctx = MergeCtx { sli...
ldResult, merge_ctx: &MergeCtx) -> MergeResult<ResolvedFold> { let (fold_states_count, lens) = compute_lens_convolution(fold, merge_ctx)?; let lore = fold.lore.iter().zip(lens).try_fold::<_, _, MergeResult<_>>( HashMap::with_capacity(fold.lore.len()), |mut resolved_lore, (lore, lens)| { ...
random
[ { "content": "pub fn fold(lore: FoldLore) -> ExecutedState {\n\n let result = FoldResult { lore };\n\n ExecutedState::Fold(result)\n\n}\n\n\n", "file_path": "crates/air-lib/test-utils/src/executed_state.rs", "rank": 0, "score": 205206.05594586604 }, { "content": "pub fn subtrace_lore(\...
Rust
software/fwupd-lib/src/usb/mod.rs
Gekkio/gb-cartpp
de1bc11c4ec055217a436eb049cb33c008631fdd
use libusb1_sys::constants::*; use libusb1_sys::*; use std::char; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::rc::Rc; use std::slice; mod bootloader; pub use crate::usb::bootloader::BootloaderMode; use crate::{DriverError, FirmwareVersion}; #[derive(Debug)] pub struct Usb...
use libusb1_sys::constants::*; use libusb1_sys::*; use std::char; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::rc::Rc; use std::slice; mod bootloader; pub use crate::usb::bootloader::BootloaderMode; use crate::{DriverError, FirmwareVersion}; #[derive(Debug)] pub struct Usb...
}; check_libusb(len as i32)?; let code_points = buffer[..(len as usize)] .chunks_exact(2) .skip(1) .filter_map(|chunk| match *chunk { [a, b] => Some(u16::from_le_bytes([a, b])), _ => None, }); Ok(char::decod...
libusb_get_string_descriptor( self.raw, index, 0x0000, buffer.as_mut_ptr(), buffer.len() as i32, )
call_expression
[ { "content": "pub fn format_device(dev: &UsbDevice<Unclaimed>) -> String {\n\n match dev.kind {\n\n UsbDeviceKind::Bootloader {\n\n bl_version,\n\n fw_version,\n\n } => format!(\n\n \"USB device {:03}: GB-CARTPP-XC v{} (bootloader v{})\",\n\n dev.usb_...
Rust
server/src/endpoints.rs
Co-Epi/coepi-backend-rust
d861389f02bc7d7823eef2244b1fd03ceb986a0d
use super::*; use chrono::*; pub mod report_new_symptoms { use super::*; #[derive(Serialize, Deserialize, Debug)] pub struct Req<'a> { #[serde(borrow)] symptoms: Vec<&'a str>, #[serde(borrow)] case_id: &'a str, } #[derive(Serialize, Deserialize, Debug)] pub str...
use super::*; use chrono::*; pub mod report_new_symptoms { use super::*; #[derive(Serialize, Deserialize, Debug)] pub struct Req<'a> { #[serde(borrow)] symptoms: Vec<&'a str>, #[serde(borrow)] case_id: &'a str, } #[derive(Serialize, Deserialize, Debug)] pub str...
d_duration_since(ts).num_hours(); (0..num_hours) .map(chrono::Duration::hours) .map(move |dur| time_key(ts + dur)) }
function_block-function_prefixed
[ { "content": "pub fn generate_cens_into(key: Key, start_unixtime: u64, buf: &mut [u8]) {\n\n let mut chacha = ChaCha8Rng::from_seed(key);\n\n\n\n let cen_number = start_unixtime / SECONDS_PER_INTERVAL * CEN_BYTES as u64;\n\n let word_pos = cen_number / 4; // word_pos is measured in 4 byte words\n\n ...
Rust
src/bounded.rs
alexcrichton/futures-spsc
c21f1c29331fab00e6b9836406f46a35f974c1ea
use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use futures::{Sink, Stream}; use futures::task::{self, Task}; use futures::{Poll, Async, StartSend, AsyncSink}; use SendError; use lock::Lock; pub fn channel<T>() -> (Sender<T>, Receiver<T>) { let inner = Arc::new(In...
use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use futures::{Sink, Stream}; use futures::task::{self, Task}; use futures::{Poll, Async, StartSend, AsyncSink}; use SendError; use lock::Lock; pub fn channel<T>() -> (Sender<T>, Receiver<T>) { let inner = Arc::new(In...
} impl<T> Receiver<T> { fn rx_task(&self) -> &Lock<Option<Task>> { if self.flag { &self.inner.rx_task1 } else { &self.inner.rx_task2 } } fn tx_task(&self) -> &Lock<Option<Task>> { if self.flag { &self.inner.tx_task1 ...
n), } if !data && self.inner.state.load(SeqCst) == EMPTY { return Ok(Async::NotReady) } let ret = Ok(self.inner.data.try_lock().unwrap().take().into()); drop(self.inner.state....
function_block-function_prefixed
[ { "content": "pub fn sassert_next<S: Stream>(s: &mut S, item: S::Item)\n\n where S::Item: Eq + fmt::Debug\n\n{\n\n match executor::spawn(s).poll_stream(unpark_panic()) {\n\n Ok(Async::Ready(None)) => panic!(\"stream is at its end\"),\n\n Ok(Async::Ready(Some(e))) => assert_eq!(e, item),\n\n ...
Rust
src/search.rs
ethcore/rust-igd
19741c4ccf895d1ba7741d13ac7ad80b4e4ef44a
use std::io; use std::net::{Ipv4Addr, SocketAddrV4}; use std::net::UdpSocket; use std::str; use std::fmt; use std::error; use std::time::Duration; use hyper; use regex::Regex; use xml::EventReader; use xml::common::Error as XmlError; use xml::reader::events::XmlEvent; use gateway::Gateway; const SEARCH_REQUEST: &'st...
use std::io; use std::net::{Ipv4Addr, SocketAddrV4}; use std::net::UdpSocket; use std::str; use std::fmt; use std::error; use std::time::Duration; use hyper; use regex::Regex; use xml::EventReader; use xml::common::Error as XmlError; use xml::reader::events::XmlEvent; use gateway::Gateway; const SEARCH_REQUEST: &'st...
st_parse_result() { let result = parse_result("location:http://0.0.0.0:0/control_url").unwrap(); assert_eq!(result.0.ip(), &Ipv4Addr::new(0,0,0,0)); assert_eq!(result.0.port(), 0); assert_eq!(&result.1[..], "/control_url"); }
function_block-function_prefixed
[ { "content": "pub fn send(url: &str, action: Action, body: &str) -> Result<String, Error> {\n\n let client = Client::new();\n\n let mut resp = try!(client.post(url)\n\n .header(action)\n\n .body(body)\n\n .send());\n\n\n\n let mut text = String::new();\n\n try!(resp.read_to_str...
Rust
src/lib.rs
stainless-steel/out123-sys
954854837280d5ad1f4b066dfa5cdc93afe7ae2c
#![allow(non_camel_case_types)] extern crate libc; extern crate mpg123_sys; use libc::{c_char, c_double, c_int, c_long, c_void, size_t}; use mpg123_sys::mpg123_fmt; pub enum out123_handle {} #[derive(Clone, Copy)] #[repr(C)] pub enum out123_flags { OUT123_HEADPHONES = 0x01, OUT123_INTERNAL_SPEAKER = 0x02,...
#![allow(non_camel_case_types)] extern crate libc; extern crate mpg123_sys; use libc::{c_char, c_double, c_int, c_long, c_void, size_t}; use mpg123_sys::mpg123_fmt; pub enum out123_handle {} #[derive(Clone, Copy)] #[repr(C)] pub enum out123_flags { OUT123_HEADPHONES = 0x01, OUT123_INTERNAL_SPEAKER = 0x02,...
har, ) -> c_int; pub fn out123_close(ao: *mut out123_handle); pub fn out123_encodings(ao: *mut out123_handle, rate: c_long, channels: c_int) -> c_int; pub fn out123_encsize(encoding: c_int) -> c_int; pub fn out123_formats( ao: *mut out123_handle, rates: *const c_long, ratecou...
c_long, ret_fvalue: *mut c_double, ret_svalue: *mut *mut c_char, ) -> c_int; pub fn out123_param_from(ao: *mut out123_handle, from_ao: *mut out123_handle) -> c_int; pub fn out123_drivers( ao: *mut out123_handle, names: *mut *mut *mut c_char, descr: *mut *mut *mut c_ch...
random
[ { "content": "fn main() {\n\n if pkg_config::find_library(\"out123\").is_ok() {\n\n return;\n\n }\n\n let dynamic = env::var(\"CARGO_FEATURE_STATIC\").is_err();\n\n let output = PathBuf::from(get!(\"DEP_MPG123_ROOT\"));\n\n println!(\n\n \"cargo:rustc-link-lib={}=out123\",\n\n ...
Rust
rlink/src/runtime/worker/runnable/source_runnable.rs
yorkart/rlink-rs
3bbbc049ac71c412f585d641328441bb830c898d
use crate::api::checkpoint::Checkpoint; use crate::api::element::Element; use crate::api::input::InputFormat; use crate::api::operator::{FunctionCreator, StreamOperator, TStreamOperator}; use crate::api::properties::SystemProperties; use crate::api::split::InputSplit; use crate::metrics::{register_counter, Tag}; use cr...
use crate::api::checkpoint::Checkpoint; use crate::api::element::Element; use crate::api::input::InputFormat; use crate::api::operator::{FunctionCreator, StreamOperator, TStreamOperator}; use crate::api::properties::SystemProperties; use crate::api::split::InputSplit; use crate::metrics::{register_counter, Tag}; use cr...
fn set_next_runnable(&mut self, next_runnable: Option<Box<dyn Runnable>>) { self.next_runnable = next_runnable; } fn checkpoint(&mut self, checkpoint_id: u64) { let context = { let context = self.context.as_ref().unwrap(); context.get_checkpoint_context(checkpoint_...
fn close(&mut self) { let source_func = self.stream_source.operator_fn.as_mut(); source_func.close(); self.next_runnable.as_mut().unwrap().close(); }
function_block-full_function
[ { "content": "pub fn get_net_receivers() -> HashMap<u32, Vec<ElementReceiver>> {\n\n let lock = NET_CHANNEL.lock().expect(\"lock failed\");\n\n let chain_channels = (&*lock).clone();\n\n\n\n let mut chain_receivers = HashMap::new();\n\n for (chain_id, channels) in chain_channels {\n\n let rec...
Rust
src/task_handler.rs
pipe-fun/pipe-core
d2bade633c3f4a7f9b85d12e93d7554698dfde78
use async_std::sync::Arc; use std::sync::Mutex; use std::collections::HashMap; use async_std::task::JoinHandle; use futures::{AsyncWriteExt, AsyncReadExt}; use web2core::protoc::{ExecuteInfo, OpResult}; use std::net::{TcpListener, ToSocketAddrs}; use async_std::net::TcpStream; use net2::TcpStreamExt; use std::time::Dur...
use async_std::sync::Arc; use std::sync::Mutex; use std::collections::HashMap; use async_std::task::JoinHandle; use futures::{AsyncWriteExt, AsyncReadExt}; use web2core::protoc::{ExecuteInfo, OpResult}; use std::net::{TcpListener, ToSocketAddrs}; use async_std::net::TcpStream; use net2::TcpStreamExt; use std::time::Dur...
if self.contains(token) { let mut s = self.get_socket(token).unwrap(); match s.close().await { Ok(_) => (), Err(e) => println!("{} close err {}", token, e.to_string()), } } self.tasks_run(token...
let token = match core::str::from_utf8(&buf[..len]) { Ok(t) => t.trim(), Err(_) => continue, };
assignment_statement
[ { "content": "pub fn put<T: Serialize>(url: &str, data: &T) {\n\n let url = format!(\"{}{}\", API_ROOT, url);\n\n let client = reqwest::blocking::ClientBuilder::new().build().unwrap();\n\n match client.put(&url).json(data).send() {\n\n Ok(_) => (),\n\n Err(_) => ()\n\n }\n\n}", "fi...
Rust
operators/src/opencl/typed_slice.rs
koerberm/geoengine
61e0ec7a0c1136b4360b0f9c6306c34198e8ac3a
use geoengine_datatypes::raster::RasterDataType; use ocl::{Buffer, OclPrm}; #[derive(Debug, Clone)] pub enum TypedSliceRef<'s> { U8(&'s [u8]), U16(&'s [u16]), U32(&'s [u32]), U64(&'s [u64]), I8(&'s [i8]), I16(&'s [i16]), I32(&'s [i32]), I64(&'s [i64]), F32(&'s [f32]), F64(&'s [f...
use geoengine_datatypes::raster::RasterDataType; use ocl::{Buffer, OclPrm}; #[derive(Debug, Clone)] pub enum TypedSliceRef<'s> { U8(&'s [u8]), U16(&'s [u16]),
nt_fn:expr, $($variant:tt),+ ) => { paste::paste! { match $input { $( $crate::opencl::SliceDataType::$variant => { type $var_type = [<$variant:lower>]; $variant_fn } )+ ...
U32(&'s [u32]), U64(&'s [u64]), I8(&'s [i8]), I16(&'s [i16]), I32(&'s [i32]), I64(&'s [i64]), F32(&'s [f32]), F64(&'s [f64]), } macro_rules! match_generic_slice_ref { ($input:expr, $var_name:ident => $variant_fn:expr) => { match $input { TypedSliceRef::U8($var_nam...
random
[ { "content": "pub trait UserInput: Clone {\n\n /// Validates user input and returns itself\n\n ///\n\n /// # Errors\n\n ///\n\n /// Fails if the user input is invalid\n\n ///\n\n fn validate(&self) -> Result<()>;\n\n\n\n /// Validates user input and returns itself\n\n ///\n\n /// #...
Rust
src/utils/cargo_contract.rs
kostekIV/ink-waterfall
b9da0d4a9f950d0c4b9c17f8d47c596f9a8cf02a
use regex::Regex; use std::{ path::PathBuf, process::Command, }; pub(crate) fn build(manifest_path: &PathBuf) -> Result<PathBuf, String> { let skip_build: String = std::env::var("WATERFALL_SKIP_CONTRACT_BUILD").unwrap_or(String::from("false")); if skip_build == "true" { log::info!("sk...
use regex::Regex; use std::{ path::PathBuf, process::Command, }; pub(crate) fn build(manifest_path: &PathBuf) -> Result<PathBuf, String> { let skip_build: String = std::env::var("WATERFALL_SKIP_CONTRACT_BUILD").unwrap_or(String::from("false")); if skip_build == "true" { log::info!("sk...
} } fn assert_wasm_opt_available() { assert!( which::which("wasm-opt").is_ok(), "ERROR: The `wasm-opt` binary cannot be found!\n\n\ Please check that it is installed and in your `PATH`.\n\n\ See the `cargo-contract` readme for instructions on how to install it:\n\ https...
Err(format!( "Failed with exit code: {:?} and '{:?}'", output.status.code(), stderr ))
call_expression
[ { "content": "/// Extracts the `source.hash` field from the contract bundle.\n\npub fn extract_hash_from_contract_bundle(path: &PathBuf) -> String {\n\n let file =\n\n File::open(path).expect(&format!(\"Contract file at {:?} does not exist\", path));\n\n let reader = BufReader::new(file);\n\n le...
Rust
src/chunks/norms.rs
bytesnake/finalfusion-rust
3c514923e6c80dfd3f10a0128a84984594bcb40d
use std::io::{Read, Seek, SeekFrom, Write}; use std::mem::size_of; use std::ops::Deref; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use ndarray::Array1; use super::io::{ChunkIdentifier, ReadChunk, TypeId, WriteChunk}; use crate::io::{ErrorKind, Result}; use crate::util::padding; #[derive(Clone, Deb...
use std::io::{Read, Seek, SeekFrom, Write}; use std::mem::size_of; use std::ops::Deref; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use ndarray::Array1; use super::io::{ChunkIdentifier, ReadChunk, TypeId, WriteChunk}; use crate::io::{ErrorKind, Result}; use crate::util::padding; #[derive(Clone, Deb...
} #[cfg(test)] mod tests { use std::io::{Cursor, Read, Seek, SeekFrom}; use byteorder::{LittleEndian, ReadBytesExt}; use ndarray::Array1; use super::NdNorms; use crate::chunks::io::{ReadChunk, WriteChunk}; const LEN: usize = 100; fn test_ndnorms() -> NdNorms { NdNorms::new(Arra...
write .write_u32::<LittleEndian>(ChunkIdentifier::NdNorms as u32) .map_err(|e| ErrorKind::io_error("Cannot write norms chunk identifier", e))?; let n_padding = padding::<f32>(write.seek(SeekFrom::Current(0)).map_err(|e| { ErrorKind::io_error("Cannot get file position for comp...
function_block-function_prefix_line
[ { "content": "fn read_ngrams_with_indices<R>(read: &mut R, len: usize) -> Result<Vec<(String, u64)>>\n\nwhere\n\n R: Read + Seek,\n\n{\n\n let mut ngrams = Vec::with_capacity(len);\n\n for _ in 0..len {\n\n let ngram_len = read\n\n .read_u32::<LittleEndian>()\n\n .map_err(|...
Rust
src/lib.rs
hlb8122/async-jsonrpc-rs
a47522ced920723664e0a30b924d0e8941bd2278
#[macro_use] extern crate serde; pub mod client; pub mod error; mod util; pub use client::Client; pub use error::Error; #[derive(Debug, Clone, PartialEq, Serialize)] pub struct Request<'a, 'b> { pub method: &'a str, pub params: &'b [serde_json::Value], pub id: serde_json::Value, pub jsonrpc: Optio...
#[macro_use] extern crate serde; pub mod client; pub mod error; mod util; pub use client::Client; pub use error::Error; #[derive(Debug, Clone, PartialEq, Serialize)] pub struct Request<'a, 'b> { pub method: &'a str, pub params: &'b [serde_json::Value], pub id: serde_json::Value, pub jsonrpc: Optio...
}
let s = r#"[ {"jsonrpc": "2.0", "result": 7, "id": "1"}, {"jsonrpc": "2.0", "result": 19, "id": "2"}, {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}, {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id"...
function_block-function_prefix_line
[ { "content": "/// Converts a Rust `Result` to a JSONRPC response object.\n\npub fn result_to_response(\n\n result: Result<serde_json::Value, RpcError>,\n\n id: serde_json::Value,\n\n) -> Response {\n\n match result {\n\n Ok(data) => Response {\n\n result: Some(data),\n\n er...
Rust
docker/src/docker/mod.rs
ethanshry/MS-Playground
b1dd23e5deb455a79fb359c0a9382d58ea0c6615
use bollard::image::ListImagesOptions; use bollard::{ container::{ Config, CreateContainerOptions, ListContainersOptions, PruneContainersOptions, StartContainerOptions, StopContainerOptions, }, image::{BuildImageOptions, PruneImagesOptions}, service::{HostConfig, PortBinding}, Docker...
use bollard::image::ListImagesOptions; use bollard::{ container::{ Config, CreateContainerOptions, ListContainersOptions, PruneContainersOptions, StartContainerOptions, StopContainerOptions, }, image::{BuildImageOptions, PruneImagesOptions}, service::{HostConfig, PortBinding}, Docker...
match build_result { Ok(_) => Ok(DockerImageBuildResult { log: log, image_id: container_guid.clone(), }), Err(e) => { error!("Error building container {}: {}", &container_...
let build_result: Result<(), String> = async { let mut file = File::open(format!("./tmp/containers/{}.tar.gz", &container_guid)) .expect("Could not find tarball"); let mut contents = Vec::new(); file.read_to_...
assignment_statement
[ { "content": "use std::fmt;\n\n/// This is a reduction of bollard's ContainerSummaryInner\n\npub struct DockerContainer {\n\n /// The ID of this container\n\n pub id: String,\n\n\n\n /// The names that this container has been given\n\n pub name: String,\n\n\n\n /// The name of the image used when...
Rust
sgtypes/src/channel_transaction.rs
fikgol/stargate
ae2b915575baed28115cf3475e2a773d5158ea42
use crate::channel_transaction_sigs::ChannelTransactionSigs; use crate::impl_hash; use anyhow::{Error, Result}; use bytes::IntoBuf; use libra_crypto::{ ed25519::{Ed25519PublicKey, Ed25519Signature}, hash::CryptoHash, HashValue, }; use libra_crypto_derive::CryptoHasher; use libra_prost_ext::MessageExt; use...
use crate::channel_transaction_sigs::ChannelTransactionSigs; use crate::impl_hash; use anyhow::{Error, Result}; use bytes::IntoBuf; use libra_crypto::{ ed25519::{Ed25519PublicKey, Ed25519Signature}, hash::CryptoHash, HashValue, }; use libra_crypto_derive::CryptoHasher; use libra_prost_ext::MessageExt; use...
} impl From<ChannelTransaction> for crate::proto::sgtypes::ChannelTransaction { fn from(value: ChannelTransaction) -> Self { Self { version: value.version.to_owned(), operator: Some(value.operator.into()), proposer: value.proposer.into(), sequence_number: va...
fn try_from(value: crate::proto::sgtypes::ChannelTransaction) -> Result<Self> { let version = value.version; let channel_address = AccountAddress::try_from(value.channel_address)?; let channel_sequence_number = value.channel_sequence_number; let proposer = AccountAddress::try_from(value....
function_block-full_function
[ { "content": "/// get preimage value from `args` which should be the args of `ChannelScript.receive_payment`\n\npub fn parse_htlc_preimage(args: &[TransactionArgument]) -> Result<HashValue> {\n\n ensure!(args.len() == 1, \"receive_payment should have 1 args\");\n\n match &args[0] {\n\n TransactionA...
Rust
src/datalog/symbol.rs
bastien-solutions/biscuit-rust
bab446420ce76539b4d44f015f60423a28dd669a
use chrono::{DateTime, NaiveDateTime, Utc}; pub type SymbolIndex = u64; use super::{Check, Fact, Predicate, Rule, Term, World}; #[derive(Clone, Debug, PartialEq, Default)] pub struct SymbolTable { pub symbols: Vec<String>, } impl SymbolTable { pub fn new() -> Self { SymbolTable::default() } ...
use chrono::{DateTime, NaiveDateTime, Utc}; pub type SymbolIndex = u64; use super::{Check, Fact, Predicate, Rule, Term, World}; #[derive(Clone, Debug, PartialEq, Default)] pub struct SymbolTable { pub symbols: Vec<String>, } impl SymbolTable { pub fn new() -> Self { SymbolTable::default() } ...
(self.symbols.len() - 1) as u64 } } } pub fn add(&mut self, s: &str) -> Term { let term = self.insert(s); Term::Str(term) } pub fn get(&self, s: &str) -> Option<SymbolIndex> { self.symbols .iter() .position(|sym| sym.as_str(...
self.symbols.iter().position(|sym| sym.as_str() == s) { Some(index) => index as u64, None => { self.symbols.push(s.to_string());
function_block-random_span
[ { "content": "/// creates a new fact\n\npub fn fact<I: AsRef<Term>>(name: &str, terms: &[I]) -> Fact {\n\n let pred = pred(name, terms);\n\n Fact::new(pred.name, pred.terms)\n\n}\n\n\n", "file_path": "src/token/builder.rs", "rank": 0, "score": 208671.38330416378 }, { "content": "pub fn...
Rust
common/src/web/api.rs
AzzOnFire/lumen
cefba99ce2a5c4d5ecd3252546bcb15080a333e2
use std::borrow::Cow; use log::*; use warp::{Filter, Reply, Rejection}; use crate::{db::DbStats}; use serde::Serialize; use super::SharedState; struct Md5([u8; 16]); impl std::str::FromStr for Md5 { type Err = &'static str; fn from_str(s: &str) -> Result<Md5, Self::Err> { let mut res = [0u...
use std::borrow::Cow; use log::*; use warp::{Filter, Reply, Rejection}; use crate::{db::DbStats}; use serde::Serialize; use super::SharedState; struct Md5([u8; 16]); impl std::str::FromStr for Md5 { type Err = &'static str; fn from_str(s: &str) -> Result<Md5, Self::Err> { let mut res = [0u...
; Result::<_, Rejection>::Ok(warp::reply::json(&Response { db_online: state.db.is_online().await, stats, })) }
match state.db.get_stats().await { Ok(stats) => DbStatus::Stats(stats), Err(err) => DbStatus::Error(format!("{}", err)), }
if_condition
[ { "content": "pub fn parse_metadata(mut data: &[u8]) -> Result<Vec<FunctionMetadata<'_>>, crate::rpc::Error> {\n\n let mut res = vec![];\n\n let mut bad_codes = HashSet::new();\n\n\n\n while !data.is_empty() {\n\n let (chunk, used) :(MetadataChunk, _) = from_slice(data)?;\n\n data = &data...
Rust
rita_client/src/dashboard/neighbors.rs
althea-mesh/althea_rs
a17329ccbf77a6c5f3c7c5c69511d0c1aa283e8d
use actix_web_async::http::StatusCode; use actix_web_async::{HttpRequest, HttpResponse}; use althea_types::Identity; use arrayvec::ArrayString; use babel_monitor::{ get_installed_route, get_route_via_neigh, open_babel_stream, parse_routes, Route as RouteLegacy, }; use num256::{Int256, Uint256}; use rita_common::de...
use actix_web_async::http::StatusCode; use actix_web_async::{HttpRequest, HttpResponse}; use althea_types::Identity; use arrayvec::ArrayString; use babel_monitor::{ get_installed_route, get_route_via_neigh, open_babel_stream, parse_routes, Route as RouteLegacy, }; use num256::{Int256, Uint256}; use rita_common::de...
let maybe_route = get_installed_route(&identity.mesh_ip, &route_table_sample); if maybe_route.is_err() { output.push(nonviable_node_info( nickname, u16::max_value(), identity.mesh_ip.to_string(), *identity, neig...
let nickname = match identity.nickname { Some(val) => val, None => ArrayString::<32>::from("No Nickname").unwrap(), };
assignment_statement
[ { "content": "pub fn get_local_fee(stream: &mut TcpStream) -> Result<u32, BabelMonitorError> {\n\n let output = run_command(stream, \"dump\");\n\n\n\n if let Err(e) = output {\n\n return Err(e);\n\n }\n\n let babel_output = output.unwrap();\n\n get_local_fee_sync(babel_output)\n\n}\n\n\n",...
Rust
examples/log-cpufeatures/src/main.rs
yoanlcq/android-cpufeatures-sys
8118c13e4c11682e767d4eadcb2693979ae7bb61
fn main() { main::main(); } #[cfg(not(target_os = "android"))] mod main { pub(super) fn main() { panic!("This example was written for Android"); } } #[cfg(target_os = "android")] mod main { extern crate android_cpufeatures_sys; extern crate android_glue; use self::android_cpufeatures_...
fn main() { main::main(); } #[cfg(not(target_os = "android"))] mod main { pub(super) fn main() { panic!("This example was written for Android"); } } #[cfg(target_os = "android")] mod main { extern crate android_cpufeatures_sys; extern crate android_glue; use self::android_cpufeatures_...
: u64, pub family: AndroidCpuFamily, #[cfg(target_arch="arm")] pub arm_cpuid: u32, } impl Default for Cpu { fn default() -> Self { unsafe { Self { count: android_getCpuCount(), features: android_getCpuFeatures()...
ormatter}; pub(super) fn main() { android_glue::write_log(&format!("{}", Cpu::default())); loop {} } #[derive(Debug)] pub struct Cpu { pub count: c_int, pub features
random
[ { "content": "fn main() {\n\n /*\n\n let ndk_path = env::var(\"NDK_HOME\").expect(\"Please set the path to the Android NDK with the \\\n\n $NDK_HOME environment variable.\");\n\n\n\n // let h_path = format!(\"{}/sources/android/cpufeatures/cpu-features.h\"...
Rust
src/pages/local.rs
TomBebbington/cargo-gui
ef0d2bb64887a1376ea4958665770af48b3c1406
use std::cell::RefCell; use std::rc::Rc; use gtk::prelude::*; use gtk::{Window, FileChooser, Button, Label, Dialog, SpinButton, Builder}; use cargo::util::config::Config; use cargo::ops::{self, CompileOptions, CompileMode}; use cargo::core::package::Package; use util::{Options, PreContext}; use pages::Page; fn upda...
use std::cell::RefCell; use std::rc::Rc; use gtk::prelude::*; use gtk::{Window, FileChooser, Button, Label, Dialog, SpinButton, Builder}; use cargo::util::config::Config; use cargo::ops::{self, CompileOptions, CompileMode}; use cargo::core::package::Package; use util::{Options, PreContext}; use pages::Page; fn upda...
; }, Err(error) => error!(Some(&self.window), "Failed to parse Cargo.toml: {:?}", error) } } } fn bind_listeners(&self) { self.bind_compile_button("build", &self.build, CompileMode::Build); self.bind_compile_button("test", &...
update_labels(&[ (&self.name, pack.name()), (&self.description, meta.description.as_ref().map(|v| v as &str).unwrap_or("")), (&self.author, meta.authors.get(0).as_ref().map(|v| v as &str).unwrap_or("")), (&self.version, &pac...
call_expression
[ { "content": "fn dialog(parent: Option<&Window>, ty: MessageType, text: &str) {\n\n let dialog = MessageDialog::new(parent, DIALOG_DESTROY_WITH_PARENT | DIALOG_MODAL, ty, ButtonsType::Close, text);\n\n dialog.connect_response(|dialog, _| {\n\n dialog.destroy();\n\n });\n\n dialog.set_icon_nam...
Rust
benches/predict.rs
tmpcnt/rav1e
e74206d0769eb3e1205d72fe2ee9f92977e22e1c
use criterion::*; use rand::{ChaChaRng, Rng, SeedableRng}; use rav1e::partition::BlockSize; use rav1e::predict::{Block4x4, Intra}; pub const BLOCK_SIZE: BlockSize = BlockSize::BLOCK_32X32; pub fn generate_block(rng: &mut ChaChaRng) -> (Vec<u16>, Vec<u16>, Vec<u16>) { let block = vec![0u16; BLOCK_SIZE.width() * BL...
use criterion::*; use rand::{ChaChaRng, Rng, SeedableRng}; use rav1e::partition::BlockSize; use rav1e::predict::{Block4x4, Intra}; pub const BLOCK_SIZE: BlockSize = BlockSize::BLOCK_32X32; pub fn generate_block(rng: &mut ChaChaRng) -> (Vec<u16>, Vec<u16>, Vec<u16>) { let block = vec![0u16; BLOCK_SIZE.width() * BL...
); } pub fn pred_bench(c: &mut Criterion) { bench_pred_fn(c, "intra_dc_4x4", intra_dc_4x4); bench_pred_fn(c, "intra_dc_128_4x4_u8", intra_dc_128_4x4_u8); bench_pred_fn(c, "intra_dc_left_4x4", intra_dc_left_4x4); bench_pred_fn(c, "intra_dc_top_4x4", intra_dc_top_4x4); bench_pred_fn(c, "intra_h_4x4", intra_...
if id.ends_with("_4x4_u8") { b.throughput(Throughput::Bytes(16)) } else if id.ends_with("_4x4") { b.throughput(Throughput::Bytes(32)) } else { b }
if_condition
[ { "content": "pub fn intra_cfl_4x4_aom(b: &mut Bencher) {\n\n let mut rng = ChaChaRng::from_seed([0; 32]);\n\n let (mut block, _above_context, _left_context) = generate_block(&mut rng);\n\n let ac: Vec<i16> = (0..(32 * 32)).map(|_| rng.gen()).collect();\n\n let alpha = -1 as i16;\n\n\n\n b.iter(|| unsafe {...
Rust
kernel/logger/src/lib.rs
jhutchins/Theseus
fe9edf60878c208116be824371c9992f9e1acb0f
#![no_std] extern crate serial_port; extern crate log; extern crate spin; extern crate irq_safety; use log::{Record, Level, SetLoggerError, Metadata, Log}; use core::fmt::{self, Write}; use spin::Once; use serial_port::SerialPort; use irq_safety::MutexIrqSafe; static LOGGER: Once<Logger> = Once::new(); const DEFA...
#![no_std] extern crate serial_port; extern crate log; extern crate spin; extern crate irq_safety; use log::{Record, Level, SetLoggerError, Metadata, Log}; use core::fmt::{self, Write}; use spin::Once; use serial_port::SerialPort; use irq_safety::MutexIrqSafe; static LOGGER: Once<Logger> = Once::new(); const DEFA...
} } pub fn mirror_to_vga(func: LogOutputFunc) { MIRROR_VGA_FUNC.call_once(|| func); } #[derive(Default)] struct Logger { serial_ports: [Option<MutexIrqSafe<SerialPort>>; 4], } impl Logger { fn write_fmt(&self, arguments: fmt::Arguments) -> fmt::Result { for serial_port in self.serial_po...
match *self { LogColor::Black => "\x1b[30m", LogColor::Red => "\x1b[31m", LogColor::Green => "\x1b[32m", LogColor::Yellow => "\x1b[33m", LogColor::Blue => "\x1b[34m", LogColor::Purple => "\x1b[35m", LogColor::Cyan => "\x1b[36m", LogColor::White ...
if_condition
[ { "content": "/// reset the mouse\n\npub fn reset_mouse() -> Result<(), &'static str> {\n\n if let Err(_e) = command_to_mouse(0xFF) {\n\n Err(\"reset mouse failled please try again\")\n\n } else {\n\n for _x in 0..14 {\n\n let more_bytes = ps2_read_data();\n\n if more_b...
Rust
src/creeps/gofer.rs
snorrwe/xenos
2b625daf8edea133949a70dcf1579dddc65a3668
use super::{move_to, pickup_energy, CreepState, LOADING, TARGET, TASK}; use crate::prelude::*; use num::FromPrimitive; use screeps::{ constants::ResourceType, game::{get_object_erased, get_object_typed}, objects::{ HasStore, StructureContainer, StructureExtension, StructureSpawn, StructureStorage,...
use super::{move_to, pickup_energy, CreepState, LOADING, TARGET, TASK}; use crate::prelude::*; use num::FromPrimitive; use screeps::{ constants::ResourceType, game::{get_object_erased, get_object_typed}, objects::{ HasStore, StructureContainer, StructureExtension, StructureSpawn, StructureStorage,...
debug!("couldn't withdraw: {:?}", r); Err("can't withdraw")?; } } else { move_to(creep, target)?; } Ok(()) } fn find_container<'a>(state: &mut CreepState) -> Option<StructureContainer> { read_target_container(state).or_else(|| { trace!("Finding new withdraw...
l() == 0 { Err("Target is empty")?; } let creep = state.creep(); if creep.pos().is_near_to(target) { let r = creep.withdraw_all(target, ResourceType::Energy); if r != ReturnCode::Ok {
function_block-random_span
[ { "content": "/// target_key is a memory entry key\n\npub fn approach_target_room(state: &mut CreepState, target_key: &str) -> ExecutionResult {\n\n let target = state.creep_memory_string(target_key).ok_or(\"no target\")?;\n\n\n\n let creep = state.creep();\n\n\n\n let room = creep.room();\n\n let r...