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
examples/adc.rs
stm32-rs/stm32f072b-disco
8f9af0195f889c2b326a22f9144cef543d9fce86
#![no_main] #![no_std] #[allow(unused)] use panic_halt; use stm32f072b_disco as board; use board::hal::{adc, prelude::*, serial, stm32}; use cortex_m::{interrupt::Mutex, peripheral::syst::SystClkSource::Core, peripheral::Peripherals}; use cortex_m_rt::{entry, exception}; use core::{cell::RefCell, fmt::Write, ptr};...
#![no_main] #![no_std] #[allow(unused)] use panic_halt; use stm32f072b_disco as board; use board::hal::{adc, prelude::*, serial, stm32}; use cortex_m::{interrupt::Mutex, peripheral::syst::SystClkSource::Core, peripheral::Peripherals}; use cortex_m_rt::{entry, exception}; use core::{cell::RefCell, fmt::Write, ptr};...
ut shared) = SHARED.borrow(cs).borrow_mut().deref_mut() { let t: Result<u16, _> = shared.adc.read(&mut shared.temp); if let Ok(t) = t { writeln!(shared.tx, "Temperature {}\r", calculate_temperature(t)).ok(); } else { share...
dc::VTemp::new(); let mut reference = adc::VRef::new(); temp.enable(&mut adc); reference.enable(&mut adc); tx.write_str("\n\rThis ADC example will read various values using the ADC and print them out to the serial terminal\r\n").o...
random
[ { "content": "#[entry]\n\nfn main() -> ! {\n\n if let Some(mut p) = stm32::Peripherals::take() {\n\n cortex_m::interrupt::free(|cs| {\n\n let mut rcc = p.RCC.configure().sysclk(48.mhz()).freeze(&mut p.FLASH);\n\n let gpioa = p.GPIOA.split(&mut rcc);\n\n\n\n // USART1 a...
Rust
src/lib/input.rs
CoBrooks/hephaestus-rs
56ffb62ecd00113de2501f28938fb7ca388d4714
use std::collections::{ HashSet, HashMap }; use winit::event::{ VirtualKeyCode, ElementState, DeviceEvent, ButtonId, MouseScrollDelta }; pub struct Input { keyboard: HashSet<u32>, keyboard_prev: HashSet<u32>, buttons: HashSet<u32>, buttons_prev: HashSet<u32>, axes: HashMap<String, f32>, mouse_p...
use std::collections::{ HashSet, HashMap }; use winit::event::{ VirtualKeyCode, ElementState, DeviceEvent, ButtonId, MouseScrollDelta }; pub struct Input { keyboard: HashSet<u32>, keyboard_prev: HashSet<u32>, buttons: HashSet<u32>, buttons_prev: HashSet<u32>, axes: HashMap<String, f32>, mouse_p...
pub fn update(&mut self) { self.keyboard_prev = self.keyboard.clone(); self.buttons_prev = self.buttons.clone(); self.mouse_delta = (0.0, 0.0); self.scroll_wheel = 0.0; if self.get_key(VirtualKeyCode::W) || self.get_key(VirtualKeyCode::Up) { *self.axes.get_mut(...
w(); axes.insert("horizontal".into(), 0.0); axes.insert("vertical".into(), 0.0); Self { keyboard: HashSet::new(), keyboard_prev: HashSet::new(), buttons: HashSet::new(), buttons_prev: HashSet::new(), axes, mouse_pos: (windo...
function_block-function_prefixed
[ { "content": "#[proc_macro_derive(Component)]\n\npub fn component_derive(input: TokenStream) -> TokenStream {\n\n let ast: syn::DeriveInput = syn::parse(input).unwrap();\n\n\n\n let name = &ast.ident;\n\n let gen = quote! {\n\n impl Component for #name {\n\n fn get_id(&self) -> usize ...
Rust
src/shard_ctrler/server.rs
gloriallluo/MadRaft
8c2b480b431445f5182791bdbd69b9528e69a021
use std::collections::HashMap; use crate::{ shard_ctrler::{msg::*, N_SHARDS}, kvraft::{server::Server, state::State}, }; use serde::{Deserialize, Serialize}; pub type ShardCtrler = Server<ShardInfo>; #[derive(Debug, Serialize, Deserialize)] pub struct ShardInfo { configs: Vec<Config>, } impl Default for ...
use std::collections::HashMap; use crate::{ shard_ctrler::{msg::*, N_SHARDS}, kvraft::{server::Server, state::State}, }; use serde::{Deserialize, Serialize}; pub type ShardCtrler = Server<ShardInfo>; #[derive(Debug, Serialize, Deserialize)] pub struct ShardInfo { configs: Vec<Config>, } impl Default for ...
.iter() .enumerate() .for_each(|(i, gid)| { let c = if i < r { opt + 1 } else { opt }; for _ in 0..c { self.shards[re_alloc_shards.pop().unwrap()] = *gid; } }); } fn balance_leave(&mut self, ...
ps.insert(g.0, g.1); }); new_config.balance_join(ng); self.configs.push(new_config.clone()); Some(new_config) }, Op::Leave { gids } => { let mut new_config = self.new_config(); gids ...
random
[ { "content": "pub trait State: net::Message + Default {\n\n type Command: net::Message + Clone;\n\n type Output: net::Message + Clone;\n\n fn apply(&mut self, cmd: Self::Command) -> Self::Output;\n\n}\n\n\n\n\n\n#[derive(Debug, Default, Serialize, Deserialize)]\n\npub struct Kv {\n\n data: HashMap<S...
Rust
core/src/ops/cnn/conv/depth_wise.rs
mithril-security/tract-sgx-xargo
ea0d7cc5a81f413250dbfca89d5d876e76746b89
use crate::internal::*; use crate::ops::cnn::patches::{Zone, ZoneScanner}; use crate::ops::cnn::Patch; use crate::ops::nn::DataShape; #[derive(Debug, Clone, new, Hash)] pub struct DepthWise { patch: Patch, input_shape: DataShape, output_shape: DataShape, kernel_chw: Arc<Tensor>, bias: Arc<Tensor>, ...
use crate::internal::*; use crate::ops::cnn::patches::{Zone, ZoneScanner}; use crate::ops::cnn::Patch; use crate::ops::nn::DataShape; #[derive(Debug, Clone, new, Hash)] pub struct DepthWise { patch: Patch, input_shape: DataShape, output_shape: DataShape, kernel_chw: Arc<Tensor>, bias: Arc<Tensor>, ...
#[inline(never)] unsafe fn process_zone_4<T: Datum + Copy + ndarray::LinalgScalar>( &self, zone: &Zone, c_stride_i: isize, c_stride_o: isize, k_stride_i: isize, iptr: *const T, kptr: *const T, bias: *const T, optr: *mut T, ) { ...
process_zone_4(zone, c_stride_i, c_stride_o, k_stride_i, iptr, kptr, bias, optr) } else { zone.visit_output(&self.patch, |visitor| { for c in 0..*self.input_shape.c() as isize { let iptr = iptr.offset(c_stride_i * c); let optr = optr.offset(c_s...
function_block-function_prefixed
[ { "content": "pub fn output_type(input: DatumType) -> DatumType {\n\n if input.is_float() {\n\n input\n\n } else {\n\n i32::datum_type()\n\n }\n\n}\n\n\n\npub(super) fn eval(\n\n a: &Tensor,\n\n b: &Tensor,\n\n a_trans: bool,\n\n b_trans: bool,\n\n c_trans: bool,\n\n) -> Tr...
Rust
cglue-gen/src/util.rs
ko1N/cglue
040074eed961d4783a4c9c8a1c084441c0dcb301
use proc_macro2::TokenStream; use proc_macro_crate::{crate_name, FoundCrate}; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::token::Colon2; use syn::token::Comma; use syn::*; pub fn crate_path() -> TokenStream { let (col, ident) = crate_path_ident(...
use proc_macro2::TokenStream; use proc_macro_crate::{crate_name, FoundCrate}; use quote::{format_ident, quote}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::token::Colon2; use syn::token::Comma; use syn::*; pub fn crate_path() -> TokenStream { let (col, ident) = crate_path_ident(...
} x => x, }; Some(ret) } pub fn parse_maybe_braced<T: Parse>(input: ParseStream) -> Result<Vec<T>> { let mut ret = vec![]; if let Ok(braces) = syn::group::parse_braces(&input) { let content = braces.content; while !content.is_empty() { let val = content.p...
if has_doc_env { FoundCrate::Name("cglue".to_string()) } else { FoundCrate::Itself }
if_condition
[ { "content": "pub fn gen_trait(mut tr: ItemTrait, ext_name: Option<&Ident>) -> TokenStream {\n\n // Path to trait group import.\n\n let crate_path = crate::util::crate_path();\n\n let trg_path: TokenStream = quote!(#crate_path::trait_group);\n\n\n\n // Need to preserve the same visibility as the tra...
Rust
hfo2/src/init.rs
Dongjoo-Kim/hafnium-verification
6071eff162148e4d25a0fedaea003addac242ace
/* * Copyright 2019 Sanguk Park * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
/* * Copyright 2019 Sanguk Park * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
pub fn hypervisor() -> &'static Hypervisor { unsafe { HYPERVISOR.get_ref() } } #[no_mangle] pub unsafe extern "C" fn cpu_main(c: *const Cpu) -> *const VCpu { if hypervisor().cpu_manager.index_of(c) != 0 { hypervisor().memory_manager.cpu_init(); } let primary = hypervisor().vm_manager.get_pri...
for i in 0..params.mem_ranges_count { dlog!( "Memory range: {:#x} - {:#x}\n", pa_addr(params.mem_ranges[i].begin), pa_addr(params.mem_ranges[i].end) - 1 ); } dlog!( "Ramdisk range: {:#x} - {:#x}\n", pa_addr(params.initrd_begin), pa_add...
function_block-function_prefix_line
[ { "content": "/// Helper method for parsing 32/64-bit units from FDT data.\n\npub fn fdt_parse_number(data: &[u8]) -> Option<u64> {\n\n #[repr(C, align(8))]\n\n struct T {\n\n a: [u8; 8],\n\n }\n\n\n\n // FDT values should be aligned to 32-bit boundary.\n\n assert!(is_aligned(data.as_ptr()...
Rust
src/diff.rs
cysp/git2-rs
78759d028e815954bf750279472d890d14104c93
use std::kinds::marker; use std::str; use {raw, StatusEntry, Delta, Oid}; pub struct DiffDelta<'a> { raw: *mut raw::git_diff_delta, marker1: marker::ContravariantLifetime<'a>, marker2: marker::NoSend, marker3: marker::NoSync, } pub struct DiffFile<'a> { raw: *const raw::git_diff_file, marker1...
use std::kinds::marker; use std::str; use {raw, StatusEntry, Delta, Oid}; pub struct DiffDelta<'a> { raw: *mut raw::git_diff_delta, marker1: marker::ContravariantLifetime<'a>, marker2: marker::NoSend, marker3: marker::NoSync, } pub struct DiffFile<'a> { raw: *const raw::git_diff_file, marker1...
} pub fn old_file(&self) -> DiffFile { unsafe { DiffFile::from_raw(self, &(*self.raw).old_file) } } pub fn new_file(&self) -> DiffFile { unsafe { DiffFile::from_raw(self, &(*self.raw).new_file) } } } impl<'a> DiffFile<'a> { ...
match unsafe { (*self.raw).status } { raw::GIT_DELTA_UNMODIFIED => Delta::Unmodified, raw::GIT_DELTA_ADDED => Delta::Added, raw::GIT_DELTA_DELETED => Delta::Deleted, raw::GIT_DELTA_MODIFIED => Delta::Modified, raw::GIT_DELTA_RENAMED => Delta::Renamed, ...
if_condition
[ { "content": "#[cfg(windows)]\n\npub fn openssl_init() {}\n\n\n\nextern {\n\n // threads\n\n pub fn git_libgit2_init() -> c_int;\n\n pub fn git_libgit2_shutdown();\n\n\n\n // repository\n\n pub fn git_repository_free(repo: *mut git_repository);\n\n pub fn git_repository_open(repo: *mut *mut gi...
Rust
src/lib.rs
bugagashenkj/rust-salsa20
07d50a6997af0fe455d0ee505d6f4cb7ed870e01
#![no_std] mod utils; use core::fmt; use crate::utils::{u8_to_u32, xor_from_slice}; fn quarterround(y0: u32, y1: u32, y2: u32, y3: u32) -> [u32; 4] { let y1 = y1 ^ y0.wrapping_add(y3).rotate_left(7); let y2 = y2 ^ y1.wrapping_add(y0).rotate_left(9); let y3 = y3 ^ y2.wrapping_add(y1).rotate_left(13); ...
#![no_std] mod utils; use core::fmt; use crate::utils::{u8_to_u32, xor_from_slice}; fn quarterround(y0: u32, y1: u32, y2: u32, y3: u32) -> [u32; 4] { let y1 = y1 ^ y0.wrapping_add(y3).rotate_left(7); let y2 = y2 ^ y1.wrapping_add(y0).rotate_left(9); let y3 = y3 ^ y2.wrapping_add(y1).rotate_left(13); ...
#[test] fn doubleround_test() { test([ 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 ], [ ...
0, 0x00000000 ]); test([ 0x08521bd6, 0x1fe88837, 0xbb2aa576, 0x3aa26365, 0xc54c6a5b, 0x2fc74c2f, 0x6dd39cc3, 0xda0a64f6, 0x90a2f23d, 0x067f95a6, 0x06b35f61, 0x41e4732e, 0xe859c100, 0xea4d84b7, 0x0f619bff, 0xbc6e965a ], [ 0x8c9d190a, 0x...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn generate_test() {\n\n test(\n\n 0x00000fff,\n\n vec![\n\n 134, 70, 88, 94, 194, 104, 117, 219, 33, 198, 116, 85, 32, 52, 54,\n\n 214, 98, 231, 58, 191, 69, 243, 75, 142, 233, 245, 119, 223, 113,\n\n 31, 50, 172, 218, 9, 93, 192, 217, ...
Rust
querier/src/namespace/mod.rs
r4ntix/influxdb_iox
5ff874925101e2afbafa6853385260a2ba044394
use crate::{ cache::CatalogCache, chunk::ChunkAdapter, ingester::IngesterConnection, query_log::QueryLog, table::QuerierTable, }; use data_types::{NamespaceId, NamespaceSchema}; use iox_query::exec::Executor; use parquet_file::storage::ParquetStorage; use schema::Schema; use std::{collections::HashMap, sync::...
use crate::{ cache::CatalogCache, chunk::ChunkAdapter, ingester::IngesterConnection, query_log::QueryLog, table::QuerierTable, }; use data_types::{Nam
await; let expected_schema = SchemaBuilder::new().build().unwrap(); let actual_schema = schema(&qns, "table"); assert_eq!(actual_schema.as_ref(), &expected_schema,); table.create_column("col1", ColumnType::I64).await; table.create_column("col2", ColumnType::Bool).await; ...
espaceId, NamespaceSchema}; use iox_query::exec::Executor; use parquet_file::storage::ParquetStorage; use schema::Schema; use std::{collections::HashMap, sync::Arc}; mod query_access; #[cfg(test)] mod test_util; #[derive(Debug)] pub struct QuerierNamespace { id: NamespaceId, name: Arc<str>, ...
random
[ { "content": "//! Code for defining values and tag sets with tags that are dependent on other tags.\n\n\n\nuse crate::now_ns;\n\nuse crate::specification::{DataSpec, ValuesSpec};\n\nuse crate::substitution::new_handlebars_registry;\n\nuse crate::tag_pair::StaticTagPair;\n\nuse handlebars::Handlebars;\n\nuse ite...
Rust
ruzzt_engine/src/tests/world_tester.rs
yokljo/ruzzt
e76b28d5f78e8f51ba78e557c82f5f172523a1c5
pub use crate::engine::RuzztEngine; pub use crate::event::Event; pub use crate::board_simulator::*; pub use zzt_file_format::*; pub use zzt_file_format::dosstring::*; use std::collections::HashMap; #[derive(Clone)] pub struct TestWorld { pub engine: RuzztEngine, pub event: Event, } impl TestWorld { pub fn new() -...
pub use crate::engine::RuzztEngine; pub use crate::event::Event; pub use crate::board_simulator::*; pub use zzt_file_format::*; pub use zzt_file_format::dosstring::*; use std::collections::HashMap; #[derive(Clone)] pub struct TestWorld { pub engine: RuzztEngine, pub event: Event, } impl TestWorld { pub fn new() -...
al: {:?}", selfsim.status_elements); println!("Expected: {:?}", othersim.status_elements); result = false; } result = result && self.current_board_tiles_equals(expected_world); result } pub fn current_board_tiles_equals(&self, expected_world: TestWorld) -> bool { let selfsim = &self.engine.board...
orld = World::parse(&mut cursor).unwrap(); world.boards[1].status_elements.clear(); world.boards[1].tiles[29 + 11*BOARD_WIDTH] = BoardTile::new(ElementType::Empty, 0); let mut engine = RuzztEngine::new(); engine.load_world(world, None); engine.set_in_title_screen(false); engine.is_paused = false; T...
random
[ { "content": "pub fn load_zzt_behaviours(sim: &mut BoardSimulator) {\n\n\tsim.set_behaviour(ElementType::Player, Box::new(items::PlayerBehaviour));\n\n\tsim.set_behaviour(ElementType::Ammo, Box::new(items::AmmoBehaviour));\n\n\tsim.set_behaviour(ElementType::Torch, Box::new(items::TorchBehaviour));\n\n\tsim.set...
Rust
src/config/file.rs
lachesis/roughenough
a5e29a47646cc57bdd8e3603818cc9bd46f81bfc
use std::fs::File; use std::io::Read; use std::time::Duration; use data_encoding::{Encoding, HEXLOWER_PERMISSIVE}; use yaml_rust::YamlLoader; use crate::config::{DEFAULT_BATCH_SIZE, DEFAULT_STATUS_INTERVAL}; use crate::config::ServerConfig; use crate::Error; use crate::key::KmsProtection; const HEX: Encoding = HEX...
use std::fs::File; use std::io::Read; use std::time::Duration; use data_encoding::{Encoding, HEXLOWER_PERMISSIVE}; use yaml_rust::YamlLoader; use crate::config::{DEFAULT_BATCH_SIZE, DEFAULT_STATUS_INTERVAL}; use crate::config::ServerConfig; use crate::Error; use crate::key::KmsProtection; const HEX: Encoding = HEX...
} impl ServerConfig for FileConfig { fn interface(&self) -> &str { self.interface.as_ref() } fn port(&self) -> u16 { self.port } fn seed(&self) -> Vec<u8> { self.seed.clone() } fn batch_size(&self) -> u8 { self.batch_size } fn status_interval(&se...
4) } "kms_protection" => { let val = value.as_str().unwrap().parse().unwrap_or_else(|_| { panic!("invalid kms_protection value: {:?}", value) }); config.kms_protection = va...
function_block-function_prefixed
[ { "content": "#[allow(clippy::useless_let_if_seq)]\n\npub fn is_valid_config(cfg: &dyn ServerConfig) -> bool {\n\n let mut is_valid = true;\n\n\n\n if cfg.port() == 0 {\n\n error!(\"server port not set: {}\", cfg.port());\n\n is_valid = false;\n\n }\n\n\n\n if cfg.interface().is_empty(...
Rust
source-code/parser.rs
adrianbielsa1/nabe
3355ecb7b5ba8e21a1db256144935af46f506eca
use crate::token::Token; use crate::statement::*; struct Parser<'a> { tokens: &'a Vec<Token>, tokens_position: usize, } impl<'a> Parser<'a> { pub fn new(tokens: &'a Vec<Token>) -> Parser { return Parser { tokens: tokens, tokens_position: 0, }; } pub fn pars...
use crate::token::Token; use crate::statement::*; struct Parser<'a> { tokens: &'a Vec<Token>, tokens_position: usize, } impl<'a> Parser<'a> { pub fn new(tokens: &'a Vec<Token>) -> Parser { return Parser { tokens: tokens, tokens_position: 0, }; } pub fn pars...
fn parse_enum_attribute(&mut self) -> Option<Statement> { let name = self.consume(Token::Identifier(vec!()))?; let value = match self.consume(Token::Assignment) { Some(_) => Some(self.consume(Token::Number(vec!()))?), None => None, }; return Some(...
e); } let _ = self.consume(Token::End)?; let _ = self.consume(Token::Enum)?; return Some(Statement::Enum(EnumStatement { scope: scope, name: name, attributes: attributes, })); }
function_block-function_prefixed
[ { "content": "// TODO: Handle multiline comments (through the underscore character).\n\n// Or is it a parser matter?\n\nfn lex_comment(characters: &Vec<u8>, position: &mut usize, _tokens: &mut Vec<Token>) -> bool {\n\n let mut character = characters[*position] as char;\n\n\n\n if character != '\\'' { retu...
Rust
evolvim-lib/src/lib/neat/mod.rs
splintah/evolvim
13e95441e617f5931441995a3fd041447c40a77e
mod genome; mod input; mod output; mod phenotype; pub use genome::Genome; pub use phenotype::NeuralNet; #[derive(Debug)] pub struct NeatBrain { genome: Genome, net: NeuralNet, } impl From<Genome> for NeatBrain { fn from(genome: Genome) -> Self { let net = (&genome).into(); NeatBrain { ge...
mod genome; mod input; mod output; mod phenotype; pub use genome::Genome; pub use phenotype::NeuralNet; #[derive(Debug)] pub struct NeatBrain { genome: Genome, net: NeuralNet, } impl From<Genome> for NeatBrain { fn from(genome: Genome) -> Self { let net = (&genome).into(); NeatBrain { ge...
} impl<'de> serde::Deserialize<'de> for NeatBrain { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<NeatBrain, D::Error> { use serde::de::*; struct BrainVisitor; impl<'de> Visitor<'de> for BrainVisitor { type Value = NeatBrain; fn expecting...
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { use serde::ser::SerializeStruct; let mut state = serializer.serialize_struct("NeatBrain", 1)?; state.serialize_field("genome", &self.genome)?; state.end() }
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nstruct Output {\n\n node_index: usize,\n\n value: f64,\n\n output_type: OutputType,\n\n}\n\n\n\nimpl Output {\n\n fn use_output(&self, env: &mut crate::brain::EnvironmentMut<super::NeatBrain>, time_step: f64) {\n\n self.output_type.use_output(self.value, env,...
Rust
research/gaia/pegasus/pegasus/src/communication/channel.rs
tianliplus/GraphScope
0226e00c106d5959d6fdc1637fe1646b16b26136
use crate::api::function::{MultiRouteFunction, RouteFunction}; use crate::channel_id::{ChannelId, SubChannelId}; use crate::communication::decorator::{count::CountedPush, exchange::ExchangePush, DataPush}; use crate::data::{Data, DataSet}; use crate::data_plane::{GeneralPull, GeneralPush, Push}; use crate::dataflow::...
use crate::api::function::{MultiRouteFunction, RouteFunction}; use crate::channel_id::{ChannelId, SubChannelId}; use crate::communication::decorator::{count::CountedPush, exchange::ExchangePush, DataPush}; use crate::data::{Data, DataSet}; use crate::data_plane::{GeneralPull, GeneralPush, Push}; use crate::dataflow::...
; Ok(MaterializedChannel { meta, push: DataPush::Exchange(push), pull: pull.into() }) } ChannelKind::Aggregate(id) => { let (mut raw, pull) = super::build_channel::<DataSet<T>>(index, &dfb.config)?.take(); let meta = ChannelMeta...
if let Some(r) = r { ExchangePush::exchange_to_some(dfb.config.batch_size as usize, ch_id, pushes, r) } else { ExchangePush::broadcast(dfb.config.batch_size as usize, ch_id, pushes) }
if_condition
[ { "content": "pub fn pipeline<T>(id: SubChannelId) -> (ThreadPush<T>, ThreadPull<T>) {\n\n let queue = Box::new(VecDeque::new());\n\n let ptr =\n\n NonNull::new(Box::into_raw(queue)).expect(\"inter thread communication_old init failure;\");\n\n let exhaust = Arc::new(CachePadded::new(AtomicBool:...
Rust
neqo-transport/src/connection/tests/resumption.rs
hawkinsw/neqo
197c69b613cae40283c801fc2eb338f5482f3808
use super::{ connect, connect_with_rtt, default_client, default_server, exchange_ticket, get_tokens, send_something, AT_LEAST_PTO, }; use crate::addr_valid::{AddressValidation, ValidateAddress}; use std::cell::RefCell; use std::rc::Rc; use std::time::Duration; use test_fixture::{self, assertions, now}; #[te...
use super::{ connect, connect_with_rtt, default_client, default_server, exchange_ticket, get_tokens, send_something, AT_LEAST_PTO, }; use crate::addr_valid::{AddressValidation, ValidateAddress}; use std::cell::RefCell; use std::rc::Rc; use std::time::Duration; use test_fixture::{self, assertions, now}; #[te...
fn take_token() { let mut client = default_client(); let mut server = default_server(); connect(&mut client, &mut server); server.send_ticket(now(), &[]).unwrap(); let dgram = server.process(None, now()).dgram(); client.process_input(dgram.unwrap(), now()); let tokens = get_tokens(&mu...
function_block-full_function
[ { "content": "/// Connect with an RTT and then force both peers to be idle.\n\nfn connect_rtt_idle(client: &mut Connection, server: &mut Connection, rtt: Duration) -> Instant {\n\n let now = connect_with_rtt(client, server, now(), rtt);\n\n let now = force_idle(client, server, rtt, now);\n\n // Drain e...
Rust
demo-kitferret/src/st7735.rs
GuiAmPm/kit-ferret-rs
51e042dd591095ce51d18d8b4c31c93c47ac0efd
pub mod instruction; use crate::spi_controller::SpiController; use ferret_rs::system::ScreenTrait; use crate::st7735::instruction::Instruction; use embedded_hal::blocking::delay::DelayMs; use embedded_hal::digital::v2::OutputPin; pub struct ST7735<'a, SPI, DC, RST> where SPI: SpiController, DC: OutputPin, ...
pub mod instruction; use crate::spi_controller::SpiController; use ferret_rs::system::ScreenTrait; use crate::st7735::instruction::Instruction; use embedded_hal::blocking::delay::DelayMs; use embedded_hal::digital::v2::OutputPin; pub struct ST7735<'a, SPI, DC, RST> where SPI: SpiController, DC: OutputPin, ...
fn update_screen_interlace(&mut self) -> Result<(), ()> { if self.buffer != None { let width = self.width; let height = self.height; let even = self.interlace_even; let start = if even { 0 } else { 1 }; for y in (start..height).step_by(2) { ...
fn update_entire_screen(&mut self) -> Result<(), ()> { if self.buffer != None { self.write_command(Instruction::RAMWR, &[])?; self.start_data()?; let buffer = self.buffer.as_ref().unwrap(); self.spi.write(&buffer); Ok(()) } else { ...
function_block-full_function
[ { "content": "// ported from: https://www.geeksforgeeks.org/implement-itoa/\n\npub fn integer_to_string<T>(mut num: T, buffer: &mut [char], base: u8)\n\nwhere T: IntegerType {\n\n let mut index = 0;\n\n let mut is_negative = false;\n\n\n\n if num.is_zero() {\n\n buffer[index] = '0';\n\n b...
Rust
macros/src/command/slash.rs
noituri/poise
45f27a86990a9443077c0cb457bd7600af625b3b
use syn::spanned::Spanned as _; use super::{extract_option_type, extract_vec_type, Invocation}; fn generate_options(inv: &Invocation) -> proc_macro2::TokenStream { let check = match &inv.more.check { Some(check) => { quote::quote! { Some(|ctx| Box::pin(#check(ctx.into()))) } } ...
use syn::spanned::Spanned as _; use super::{extract_option_type, extract_vec_type, Invocation}; fn generate_options(inv: &Invocation) -> proc_macro2::TokenStream { let check = match &inv.more.check { Some(check) => { quote::quote! { Some(|ctx| Box::pin(#check(ctx.into()))) } } ...
}
Ok(quote::quote! { ::poise::ContextMenuCommand { name: #name, action: <#param_type as ::poise::ContextMenuParameter<_, _>>::to_action(|ctx, value| { Box::pin(async move { inner(ctx.into(), value).await }) }), id: std::sync::Arc::clone(&command_id),...
call_expression
[ { "content": "/// Implemented for all types that can be used in a context menu command\n\npub trait ContextMenuParameter<U, E> {\n\n /// Convert an action function pointer that takes Self as an argument into the appropriate\n\n /// [`crate::ContextMenuCommandAction`] variant.\n\n fn to_action(\n\n ...
Rust
src/tokenizer.rs
quail-lang/quail
696b6f11b65776843320468fdad0acc9dfad1312
use std::fmt; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq, Clone)] pub enum Token { Ident(Loc, String), Hole(Loc, Option<String>, Option<String>), Lambda(Loc), Let(Loc), Def(Loc), Equals(Loc), In(Loc), Arrow(Loc), FatArrow(Loc), LeftParen(Loc), RightParen(Lo...
use std::fmt; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq, Clone)] pub enum Token { Ident(Loc, String), Hole(Loc, Option<String>, Option<String>), Lambda(Loc), Let(Loc), Def(Loc), Equals(Loc), In(Loc), Arrow(Loc), FatArrow(Loc), LeftParen(Loc), RightParen(Lo...
ng(), Token::With(self.loc.clone())), ("import".to_string(), Token::Import(self.loc.clone())), ("as".to_string(), Token::As(self.loc.clone())), ].iter().cloned().collect(); let loc = self.loc.clone(); let mut first_char = '\0'; match self.peek() { So...
loc, Arrow(loc) => loc, FatArrow(loc) => loc, LeftParen(loc) => loc, RightParen(loc) => loc, LeftCurly(loc) => loc, RightCurly(loc) => loc, Match(loc) => loc, With(loc) => loc, Import(loc) => loc, Col...
random
[ { "content": "pub fn parse_import(source: Option<String>, input: &str) -> Result<Import, ParseErr> {\n\n let mut toker = Tokenizer::new(source, input);\n\n let tokens = toker.tokenize()?;\n\n\n\n let mut parser = Parser::new(tokens);\n\n parser.parse_import()\n\n}\n\n\n", "file_path": "src/parse...
Rust
src/structs.rs
th0rex/pe_load
edf8caf2a2ae97f48c711398894d5e92a4b1a09b
use std::marker::PhantomData; use std::mem::size_of; use std::os::raw::{c_char, c_void}; use std::slice; use super::rva::{Pointer, RVA}; #[repr(u16)] pub enum Machine { X64 = 0x8864, I386 = 0x14c, } #[repr(u16)] pub enum OptionalHeaderSignature { X64 = 523, X86 = 267, ROM = 263, } #[repr(u32)] ...
use std::marker::PhantomData; use std::mem::size_of; use std::os::raw::{c_char, c_void}; use std::slice; use super::rva::{Pointer, RVA}; #[repr(u16)] pub enum Machine { X64 = 0x8864, I386 = 0x14c, } #[repr(u16)] pub enum OptionalHeaderSignature { X64 = 523, X86 = 267, ROM = 263, } #[repr(u32)] ...
[c_char; 2], pub not_needed: [c_char; 58], pub offset_to_pe_header: u32, } impl DosHeader { pub fn get_pe_header(&self) -> &PeHeader { unsafe { let self_ptr = self as *const _ as *const c_char; &*(self_ptr.offset(self.offset_to_pe_header as _) as *const _) } } ...
ion_alignment: u32, pub file_alignment: u32, pub major_os_version: u16, pub minor_os_version: u16, pub major_image_version: u16, pub minor_image_version: u16, pub major_subsystem_version: u16, pub minor_subsystem_version: u16, pub win32_version: u32, pub size_of_image: u32, pub s...
random
[ { "content": "pub fn wrapped_dll_main(ep: extern \"C\" fn()) -> impl FnOnce() -> () {\n\n let x: extern \"stdcall\" fn(HINSTANCE, u32, *mut c_void) = unsafe { mem::transmute(ep) };\n\n let y = move || {\n\n // TODO: Use the mapped address as the HMODULE parameter (i.e. loader.image_base)\n\n ...
Rust
src/invoker/src/controller.rs
MikailBag/jjs
bf00423f70f8a6ed508bbcb8b38840225e43cc73
mod notify; mod task_loading; mod toolchains; use crate::{ scheduler::Scheduler, worker::{JudgeOutcome, Request, Response}, }; use anyhow::Context; use notify::Notifier; use std::{ path::{Path, PathBuf}, sync::Arc, }; use tracing::{debug, info, instrument}; use uuid::Uuid; #[derive(Debug)] struct Lo...
mod notify; mod task_loading; mod toolchains; use crate::{ scheduler::Scheduler, worker::{JudgeOutcome, Request, Response}, }; use anyhow::Context; use notify::Notifier; use std::{ path::{Path, PathBuf}, sync::Arc, }; use tracing::{debug, info, instrument}; use uuid::Uuid; #[derive(Debug)] struct Lo...
} #[async_trait::async_trait] pub trait JudgeResponseCallbacks: Send + Sync { async fn set_finished( &self, invocation_id: Uuid, reason: InvocationFinishReason, ) -> anyhow::Result<()>; async fn add_outcome_header( &self, invocation_id: Uuid, head...
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("JudgeRequestAndCallbacks") .field("request", &self.request) .field("handler", &"..") .finish() }
function_block-function_prefix_line
[ { "content": " /// HTTP Request.\n\n pub trait Request {\n\n type Form: Form;\n\n\n\n /// Sets the header with the given key and value.\n\n fn header(self, name: &'static str, value: &str) -> Self;\n\n\n\n /// Sets body using the given vector of bytes.\n\n ///\n\n ...
Rust
src/lib.rs
Thog/blz-nx-rs
3b7a3fc587f064ab5c86da0aaff8e7decea26be1
#![no_std] use byteorder::ByteOrder; use byteorder::LittleEndian; #[derive(Debug)] pub enum Error { Unknown, InvalidBlz, DecompressionBufferTooSmall, CompressionBufferTooSmall, } const BLZ_SHIFT: u8 = 1; const BLZ_MASK: u8 = 0x80; const BLZ_THRESHOLD: usize = 2; const BLZ_MAX_OFFSET: usize = 0x1002; ...
#![no_std] use byteorder::ByteOrder; use byteorder::LittleEndian; #[derive(Debug)] pub enum Error { Unknown, InvalidBlz, DecompressionBufferTooSmall, CompressionBufferTooSmall, } const BLZ_SHIFT: u8 = 1; const BLZ_MASK: u8 = 0x80; const BLZ_THRESHOLD: usize = 2; const BLZ_MAX_OFFSET: usize = 0x1002; ...
(compressed_len + header_size) as u32, ); LittleEndian::write_u32( &mut compression_buffer[compressed_pos + 4..], header_size as u32, ); LittleEndian::write_u32( &mut compression_buffer[compressed_pos + 8..], (inc_len - header_size) as u32...
et mut bottom_position = data.len() - 1; while top_position < bottom_position { let tmp = data[top_position]; data[top_position] = data[bottom_position]; data[bottom_position] = tmp; bottom_position -= 1; top_position += 1; } } fn compression_search(data: &[u8], current...
random
[ { "content": "# blz-nx-rs\n\n\n\n[![Travis Build](https://img.shields.io/travis/com/Thog/blz-nx-rs.svg?logo=travis)](https://travis-ci.com/Thog/blz-nx-rs) [![Dependabot Status](https://api.dependabot.com/badges/status?host=github&repo=Thog/blz-nx-rs)](https://dependabot.com)\n\n\n\nAn implementation of the Bott...
Rust
tests/substrate_tests/function_types.rs
reeftotem/solang
56047c48da5f836a23661c092b35a55713346871
use crate::build_solidity; use parity_scale_codec::Encode; use parity_scale_codec_derive::{Decode, Encode}; #[test] fn simple_test() { #[derive(Debug, PartialEq, Encode, Decode)] struct Args(bool, u32, u32); let mut runtime = build_solidity( r##" contract ft { function mul(int3...
use crate::build_solidity; use parity_scale_codec::Encode; use parity_scale_codec_derive::{Decode, Encode}; #[test] fn simple_test() { #[derive(Debug, PartialEq, Encode, Decode)] struct Args(bool, u32, u32); let mut runtime = build_solidity( r##" contract ft { function mul(int3...
runtime.function("test", Vec::new()); let mut runtime = build_solidity( r##" contract ft { function test() public { function(int32) external returns (uint64) func = this.foo; bar(func); } function foo(int32) public returns ...
let mut runtime = build_solidity( r##" contract ft { function test() public { function(int32) external returns (uint64) func = this.foo; bar(func); } function foo(int32) public returns (uint64) { return 0xabbaabba; ...
assignment_statement
[]
Rust
cli/src/workflow/render/producer/typescript/render_static.rs
DmitryAstafyev/clibri
9cf501e0274d5cc1aae13fcf8cb50ed7820f8503
use super::{helpers, workflow::event::Event}; use std::include_str; use std::{ fs, path::{Path, PathBuf}, }; #[allow(non_upper_case_globals)] mod paths { pub mod events { pub const connected: &str = "connected.ts"; pub const disconnected: &str = "disconnected.ts"; pub const error: &...
use super::{helpers, workflow::event::Event}; use std::include_str; use std::{ fs, path::{Path, PathBuf}, }; #[allow(non_upper_case_globals)] mod paths
helpers::fs::write( self.get_dest_file(base, paths::events::dest, paths::events::ready)?, include_str!("./static/events/ready.ts").to_owned(), true, )?; } if !self .get_dest_file(base, paths::events::dest, paths::events::shutdown...
{ pub mod events { pub const connected: &str = "connected.ts"; pub const disconnected: &str = "disconnected.ts"; pub const error: &str = "error.ts"; pub const ready: &str = "ready.ts"; pub const shutdown: &str = "shutdown.ts"; pub const dest: &str = "events"; } ...
random
[ { "content": "pub fn write(filename: PathBuf, content: String, overwrite: bool) -> Result<(), String> {\n\n if filename.exists() && overwrite {\n\n if let Err(e) = remove_file(filename.clone()) {\n\n return Err(e.to_string());\n\n }\n\n } else if filename.exists() && !overwrite {\...
Rust
lib/oxrdf/src/interning.rs
etiennept/oxigraph
cbccdfba867204ce4b20b6fc16e37a30719f90eb
use crate::*; use lasso::{Key, Rodeo, Spur}; use std::collections::HashMap; #[derive(Debug, Default)] pub struct Interner { strings: Rodeo, #[cfg(feature = "rdf-star")] triples: HashMap<InternedTriple, Triple>, } #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Copy, Hash)] pub struct InternedName...
use crate::*; use lasso::{Key, Rodeo, Spur}; use std::collections::HashMap; #[derive(Debug, Default)] pub struct Interner { strings: Rodeo, #[cfg(feature = "rdf-star")] triples: HashMap<InternedTriple, Triple>, } #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Copy, Hash)] pub struct InternedName...
interner, ))), } } pub fn encoded_from(term: TermRef<'_>, interner: &Interner) -> Option<Self> { Some(match term { TermRef::NamedNode(term) => { Self::NamedNode(InternedNamedNode::encoded_from(term, interner)?) } TermRef::Bl...
), Self::BlankNode(node) => Self::BlankNode(node.next()), } } pub fn impossible() -> Self { Self::NamedNode(InternedNamedNode::impossible()) } } #[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Hash)] pub enum InternedTerm { NamedNode(InternedNamedNode), BlankNode...
random
[ { "content": "fn named_node_repr(node: NamedNodeRef<'_>, buffer: &mut String) {\n\n buffer.push_str(\"<NamedNode value=\");\n\n buffer.push_str(node.as_str());\n\n buffer.push('>');\n\n}\n\n\n", "file_path": "python/src/model.rs", "rank": 1, "score": 289960.8145970217 }, { "content"...
Rust
src/media/audio/lib/test/hermetic_audio_environment/rust/src/lib.rs
mehulagg/fuchsia
3f56175ee594da6b287d5fb19f2f0eccea2897f0
pub mod virtual_audio; pub mod prelude { pub use fidl; pub use fidl_fuchsia_virtualaudio::*; pub use fuchsia_async as fasync; pub type Result<T> = std::result::Result<T, failure::Error>; pub use crate::Environment; pub use fidl_fuchsia_media::*; pub use fuchsia_component::client; pub u...
pub mod virtual_audio; pub mod prelude { pub use fidl; pub use fidl_fuchsia_virtualaudio::*; pub use fuchsia_async as fasync; pub type Result<T> = std::result::Result<T, failure::Error>; pub use crate::Environment; pub use fidl_fuchsia_media::*; pub use fuchsia_component::client; pub u...
pub fn connect_to_service<S: DiscoverableService>(&self) -> Result<S::Proxy> { self.env.connect_to_service::<S>() } }
pub fn new() -> Result<Self> { use fidl_fuchsia_logger::LogSinkMarker; let mut fs = ServiceFs::new(); register_services(&mut fs); fs.add_proxy_service::<LogSinkMarker, ConnectRequest>(); let env = fs.create_salted_nested_environment("environment")?; let launched_compone...
function_block-full_function
[]
Rust
hsp3-analyzer-mini/ham-core/src/analysis/preproc.rs
honobonosun/hsp3-ginger
d2788085d71c8d8fdf31e445a8e262c08e18fba8
use super::{a_scope::*, a_symbol::*}; use crate::{parse::*, source::DocId}; use std::{collections::HashMap, mem::replace}; #[derive(Default)] struct Ctx { doc: DocId, symbols: Vec<ASymbolData>, scope: ALocalScope, modules: HashMap<AModule, AModuleData>, module_len: usize, deffunc_len: usize, ...
use super::{a_scope::*, a_symbol::*}; use crate::{parse::*, source::DocId}; use std::{collections::HashMap, mem::replace}; #[derive(Default)] struct Ctx { doc: DocId, symbols: Vec<ASymbolData>, scope: ALocalScope, modules: HashMap<AModule, AModuleData>, module_len: usize, deffunc_len: usize, ...
t { let mut ctx = Ctx::default(); ctx.doc = doc; for stmt in &root.stmts { on_stmt(stmt, &mut ctx); } let Ctx { symbols, modules, .. } = ctx; PreprocAnalysisResult { symbols, modules } }
function_block-function_prefixed
[ { "content": "fn add_symbol(kind: ASymbolKind, name: &PToken, def_site: bool, ctx: &mut Ctx) {\n\n // 新しいシンボルを登録する。\n\n let symbol = ASymbol::new(ctx.symbols.len());\n\n\n\n let mut symbol_data = ASymbolData {\n\n kind,\n\n name: name.body.text.clone(),\n\n def_sites: vec![],\n\n ...
Rust
src/history.rs
nuta/nsh
4e90833e8d205d5311fbb118076568b810557c84
use crate::fuzzy::FuzzyVec; use crate::theme::ThemeColor; use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; pub struct History { path: PathBuf, history: FuzzyVec, path2cwd: HashMap<String, PathBuf>, } impl History { ...
use crate::fuzzy::FuzzyVec; use crate::theme::ThemeColor; use std::collections::HashMap; use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; pub struct History { path: PathBuf, history: FuzzyVec, path2cwd: HashMap<String, PathBuf>, } impl History { ...
pub fn reset(&mut self) { self.offset = 0; } pub fn current(&self, history: &History) -> String { if self.offset == 0 { self.input.clone() } else { history.nth_last(self.offset - 1).unwrap() } } pub fn prev(&mut ...
pub fn new() -> HistorySelector { HistorySelector { offset: 0, input: String::new(), } }
function_block-full_function
[ { "content": "fn path_completion(pattern: &str, only_dirs: bool) -> FuzzyVec {\n\n let home_dir = dirs::home_dir().unwrap();\n\n let current_dir = std::env::current_dir().unwrap();\n\n let mut dir = if pattern.is_empty() {\n\n current_dir.clone()\n\n } else if let Some(pattern) = pattern.stri...
Rust
shell_automaton/src/peer/message/write/peer_message_write_effects.rs
simplestaking/tezos-rs
d859dff0a8db4f5adb4885e4885217d5284f7861
use std::net::SocketAddr; use tezos_encoding::binary_writer::BinaryWriterError; use tezos_messages::p2p::binary_message::BinaryWrite; use tezos_messages::p2p::encoding::peer::{PeerMessage, PeerMessageResponse}; use crate::peer::binary_message::write::{ PeerBinaryMessageWriteSetContentAction, PeerBinaryMessageWr...
use std::net::SocketAddr; use tezos_encoding::binary_writer::BinaryWriterError; use tezos_messages::p2p::binary_message::BinaryWrite; use tezos_messages::p2p::encoding::peer::{PeerMessage, PeerMessageResponse}; use crate::peer::binary_message::write::{ PeerBinaryMessageWriteSetContentAction, PeerBinaryMessageWr...
; } } } Action::PeerMessageWriteInit(content) => { let peer = match store.state.get().peers.get(&content.address) { Some(peer) => match peer.status.as_handshaked() { Some(v) => v, None => return, ...
binary_message_write_init( store, content.address, &next_message, message_encode_result, )
call_expression
[ { "content": "pub fn peer_message_read_reducer(state: &mut State, action: &ActionWithMeta) {\n\n match &action.action {\n\n Action::PeerMessageReadInit(content) => {\n\n let peer = match state\n\n .peers\n\n .list\n\n .get_mut(&content.address)\n...
Rust
src/uu/seq/src/extendedbigdecimal.rs
353fc443/coreutils
ec386fa460e4fe4dfb7e6a0ec0ddcfabe0c41985
use std::cmp::Ordering; use std::fmt::Display; use std::ops::Add; use bigdecimal::BigDecimal; use num_bigint::BigInt; use num_bigint::ToBigInt; use num_traits::One; use num_traits::Zero; use crate::extendedbigint::ExtendedBigInt; #[derive(Debug, Clone)] pub enum ExtendedBigDecimal { BigDecimal(BigDecimal)...
use std::cmp::Ordering; use std::fmt::Display; use std::ops::Add; use bigdecimal::BigDecimal; use num_bigint::BigInt; use num_bigint::ToBigInt; use num_traits::One; use num_traits::Zero; use crate::extendedbigint::ExtendedBigInt; #[derive(Debug, Clone)] pub enum ExtendedBigDecimal { BigDecimal(BigDecimal)...
} impl Add for ExtendedBigDecimal { type Output = Self; fn add(self, other: Self) -> Self { match (self, other) { (Self::BigDecimal(m), Self::BigDecimal(n)) => Self::BigDecimal(m.add(n)), (Self::BigDecimal(_), Self::MinusInfinity) => Self::MinusInfinity, (Self::Big...
fn is_zero(&self) -> bool { match self { Self::BigDecimal(n) => n.is_zero(), Self::MinusZero => true, _ => false, } }
function_block-full_function
[ { "content": "#[uucore_procs::gen_uumain]\n\npub fn uumain(mut args: impl uucore::Args) -> UResult<()> {\n\n let program = args.next().unwrap_or_else(|| OsString::from(\"test\"));\n\n let binary_name = uucore::util_name();\n\n let mut args: Vec<_> = args.collect();\n\n\n\n if binary_name.ends_with('...
Rust
gears_core/src/gear/mod.rs
XBagon/gears
5c42708dece4f0a288b2415a8efa23d3a35a5964
use crate::gear::special::GearSpecial; use crate::gear::{ command::{GearCommand, GearGenericCommand}, compound::GearCompound, internal::GearInternal, special::{io::Input, io::Output, literal::Literal}, }; use crate::ty::*; use crate::util::LiftSlotMap; use enum_dispatch::enum_dispatch; use slotmap::{new...
use crate::gear::special::GearSpecial; use crate::gear::{ command::{GearCommand, GearGenericCommand}, compound::GearCompound, internal::GearInternal, special::{io::Input, io::Output, literal::Literal}, }; use crate::ty::*; use crate::util::LiftSlotMap; use enum_dispatch::enum_dispatch; use slotmap::{new...
pub fn register(&mut self, gear: Gear) -> GearId { self.gears.insert(gear) } pub fn register_template(&mut self, gear: Gear) -> TemplateGearId { self.template_gears.insert(gear) } pub fn duplicate(&mut self, gear_id: GearId) -> GearId { let clone = self.gears[gear_id].clo...
pub fn init() -> Self { let mut template_gears = SlotMap::with_key(); Self { internal: internal::Gears::init(&mut template_gears), special: special::Gears::init(&mut template_gears), command: command::Gears::init(&mut template_gears), gears: LiftSlotMap::w...
function_block-function_prefix_line
[ { "content": "use super::*;\n\n\n\npub mod io;\n\npub mod literal;\n\n\n\npub struct Gears {\n\n pub io: io::Gears,\n\n}\n\n\n\nimpl Gears {\n\n pub fn init(template_gears: &mut TemplateGearMap) -> Self {\n\n Self {\n\n io: io::Gears::init(template_gears),\n\n }\n\n }\n\n}\n\n\...
Rust
atomics/src/atomic_primitive/atomic_f32.rs
BrianMcDonaldWS/rpc-perf
e36466ce611d151757cf4e8dcfebb1f7f32263d7
use crate::{AtomicPrimitive, Ordering}; #[cfg(feature = "serde")] use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; pub struct AtomicF32 { pub(crate) inner: core::sync::atomic::AtomicU32, } impl AtomicPrimitive for AtomicF32 { type Primitive = f32; fn new(value: Self::Primiti...
use crate::{AtomicPrimitive, Ordering}; #[cfg(feature = "serde")] use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; pub struct AtomicF32 { pub(crate) inner: core::sync::atomic::AtomicU32, } impl AtomicPrimitive for AtomicF32 { type Primitive = f32; fn new(value: Self::Primiti...
} fn visit_u8<E>(self, value: u8) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(Self::Value::new(f32::from(value))) } fn visit_u16<E>(self, value: u16) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(Self::Value::new(f32::from(valu...
if let Ok(value) = i16::try_from(value).map(f32::from) { Ok(Self::Value::new(value)) } else { Err(E::custom(format!("f32 is out of range: {}", value))) }
if_condition
[ { "content": "/// Counter primitives are capable of saturating addition and subtraction\n\npub trait CounterPrimitive: PartialEq + Copy + Default {\n\n /// Perform saturating addition on this `CounterPrimitive`\n\n fn saturating_add(self, rhs: Self) -> Self;\n\n /// Perform saturating subtraction on th...
Rust
rita/src/rita_exit/database/sms.rs
darkdrgn2k/althea_rs
a331a1b73339f770c1d2baa1c1e75e825493ed8f
use crate::rita_exit::database::database_tools::text_sent; use crate::rita_exit::database::database_tools::verify_client; use crate::rita_exit::database::get_exit_info; use crate::rita_exit::database::struct_tools::texts_sent; use althea_types::{ExitClientDetails, ExitClientIdentity, ExitState}; use diesel; use diesel:...
use crate::rita_exit::database::database_tools::text_sent; use crate::rita_exit::database::database_tools::verify_client; use crate::rita_exit::database::get_exit_info; use crate::rita_exit::database::struct_tools::texts_sent; use althea_types::{ExitClientDetails, ExitClientIdentity, ExitState}; use diesel; use diesel:...
build()?; let res = client .post(&url) .basic_auth(phone.twillio_account_id, Some(phone.twillio_auth_token)) .form(&SmsNotification { to: number.to_string(), from: phone.notification_number, body: phone.balance_notification_body, }) .send()...
function_block-function_prefix_line
[]
Rust
src/stm32f407.rs
SweGecko/vectrex-cart
8f24cfab5c53c418487d872878d98afc0fdbe5ec
/* * Custom wrappers for some CPU registers */ use volatile_register::{RO, RW, WO}; #[repr(C)] pub struct Syscfg { _fsmc: u32, _pmc: u32, pub exticr1: RW<u16>, _reserved: u16, } const SYSCFG_ADDR: u32 = 0x4001_3800; impl Syscfg { pub fn syscfg() -> &'static mut Syscfg { unsafe { &mut ...
/* * Custom wrappers for some CPU registers */ use volatile_register::{RO, RW, WO}; #[repr(C)] pub struct Syscfg { _fsmc: u32, _pmc: u32, pub exticr1: RW<u16>, _reserved: u16, } const SYSCFG_ADDR: u32 = 0x4001_3800; impl Syscfg { pub fn syscfg() -> &'static mut Syscfg { unsafe { &mut ...
<= 10, 0 <= m <= 10) ( $n:tt; $m:tt ) => { rpt!($n; $m; { asm::nop() }) }; } */
=> {}; ( 1; $x:block ) => { $x; }; ( 2; $x:block ) => { $x; $x; }; ( 3; $x:block ) => { rpt!(2; $x); $x; }; ( 4; $x:block) => { rpt!(2; $x); rpt!(2; $x); }; ( 5; $x:block ) => { rpt!(4; $x); $x; }; ( 6 ; ...
random
[ { "content": "#[derive(Debug, PartialEq, PartialOrd, Eq, Ord)]\n\nstruct CartHdr {\n\n name: Vec<u8>,\n\n year: u32,\n\n path: PathBuf,\n\n}\n\n\n", "file_path": "build.rs", "rank": 0, "score": 29200.684055384212 }, { "content": "fn main() {\n\n // Put the linker script somewhere...
Rust
src/api/context/propagation/composite_propagator.rs
bnjjj/opentelemetry-rust
8a828a81b3c9750ce4ccebe47d104e69929e8ee6
use crate::api::{self, HttpTextFormat}; use std::fmt::Debug; #[derive(Debug)] pub struct HttpTextCompositePropagator { propagators: Vec<Box<dyn HttpTextFormat + Send + Sync>>, } impl HttpTextCompositePropagator { pub fn new(propagators: Vec<Box<dyn HttpTextFormat + Send + Sync>>) -> Self { ...
use crate::api::{self, HttpTextFormat}; use std::fmt::Debug; #[derive(Debug)] pub struct HttpTextCompositePropagator { propagators: Vec<Box<dyn HttpTextFormat + Send + Sync>>, } impl HttpTextCompositePropagator { pub fn new(propagators: Vec<Box<dyn HttpTextFormat + Send + Sync>>) -> Self { ...
ace_context = TraceContextPropagator::new(); let composite_propagator = HttpTextCompositePropagator { propagators: vec![Box::new(b3), Box::new(trace_context)], }; for (header_name, header_value) in test_data() { let mut carrier = HashMap::new(); carrier.inser...
r = HttpTextCompositePropagator { propagators: vec![Box::new(b3), Box::new(trace_context)], }; let cx = Context::default().with_span(TestSpan(SpanContext::new( TraceId::from_u128(1), SpanId::from_u64(1), 0, false, ))); let mut ...
random
[ { "content": "/// Sets the given [`HttpTextFormat`] propagator as the current global propagator.\n\n///\n\n/// [`HttpTextFormat`]: ../api/context/propagation/trait.HttpTextFormat.html\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use opentelemetry::{api, global};\n\n///\n\n/// // create your http text propa...
Rust
src/hubris/elaborate/pattern_matching/mod.rs
jroesch/hubris
0333d4d26b7d66924acfe065c94d914e0ba011e4
use super::super::ast::{self}; use super::super::core::{self, Term}; use super::{LocalElabCx, Error}; use std::collections::HashMap; struct PatternMatchCx<'ecx, 'cx: 'ecx> { elab_cx: &'ecx mut LocalElabCx<'cx>, } mod renamer; mod simplify; use self::simplify::*; impl<'ecx, 'cx: 'ecx>PatternMatchCx<'ecx, 'cx> {...
use super::super::ast::{self}; use super::super::core::{self, Term}; use super::{LocalElabCx, Error}; use std::collections::HashMap; struct PatternMatchCx<'ecx, 'cx: 'ecx> { elab_cx: &'ecx mut LocalElabCx<'cx>, } mod renamer; mod simplify; use self::simplify::*; impl<'ecx, 'cx: 'ecx>PatternMatchCx<'ecx, 'cx> {...
fn elaborate_simple_case(&mut self, simple_case: SimpleCase, scrutinee_ty: &core::Term, ctor_map: &HashMap<core::Name, core::Term>) -> Result<core::Term, Error> { let SimpleCase { pattern, rhs, ...
map(|(t, n)| { (n, t.clone()) }).collect(); return Ok(binders); } } } } }
function_block-function_prefix_line
[ { "content": "pub fn simplify_match(scrutinee: ast::Term, cases: Vec<ast::Case>) -> SimpleMatch {\n\n let mut simple_cases = vec![];\n\n\n\n for case in cases {\n\n let rhs = SimpleMatchArm::Term(case.rhs);\n\n simple_cases.push(simplify_pattern(case.pattern, rhs));\n\n }\n\n\n\n let s...
Rust
src/model/category_lookup.rs
creinig/naday
975eb02a0e2e71bfe63ed8efd29141ddc5d77f7d
use super::Category; use anyhow::{bail, Result}; use std::collections::HashMap; use std::rc::Rc; #[derive(Debug)] pub struct CategoryLookup { categories: HashMap<String, Rc<Category>>, by_name_or_alias: HashMap<String, Rc<Category>>, } impl CategoryLookup { pub fn new() -> CategoryLookup { Categor...
use super::Category; use anyhow::{bail, Result}; use std::collections::HashMap; use std::rc::Rc; #[derive(Debug)] pub struct CategoryLookup { categories: HashMap<String, Rc<Category>>, by_name_or_alias: HashMap<String, Rc<Category>>, } impl CategoryLookup { pub fn new() -> CategoryLookup { Categor...
nwrap(); lookup .add(Category::new("Pushdowns", 1.0, vec!["pd", "push"])) .expect_err("Should return an error for duplicate key"); } }
ercase(), cat_rc.clone()); } Ok(()) } pub fn find<S: AsRef<str>>(&self, alias_or_name: S) -> Option<Rc<Category>> { let lc = alias_or_name.as_ref().to_lowercase(); match self.by_name_or_alias.get(&lc) { Some(cat) => Some(cat.clone()), None => None, ...
random
[ { "content": "/// Read all categories and return a populated lookup structure\n\npub fn read_categories(cfg: &Config) -> Result<CategoryLookup> {\n\n let categories = category::read_categories(cfg)?;\n\n let mut lookup = CategoryLookup::new();\n\n\n\n for category in categories {\n\n lookup.add(...
Rust
program/src/orderbook.rs
solindex/orderbook
ed5e4246aa8ec5b5eef84aa0982bc50622cb9b5d
use crate::{ critbit::{LeafNode, Node, NodeHandle, Slab}, error::AoError, processor::new_order, state::{Event, EventQueue, SelfTradeBehavior, Side}, utils::{fp32_div, fp32_mul}, }; use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{account_info::AccountInfo, msg, program_error::Prog...
use crate::{ critbit::{LeafNode, Node, NodeHandle, Slab}, error::AoError, processor::new_order, state::{Event, EventQueue, SelfTradeBehavior, Side}, utils::{fp32_div, fp32_mul}, }; use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{account_info::AccountInfo, msg, program_error::Prog...
; if post_only || !crossed { break; } let offer_size = best_bo_ref.base_quantity; let base_trade_qty = offer_size .min(base_qty_remaining) .min(fp32_div(quote_qty_remaining, best_bo_ref.price())); if base_trad...
match side { Side::Bid => limit_price >= trade_price, Side::Ask => limit_price <= trade_price, }
if_condition
[ { "content": "#[wasm_bindgen]\n\npub fn find_max(data: &mut [u8], callback_info_len: u64, slot_size: u64) -> Option<u32> {\n\n let slab = Slab::new(\n\n Rc::new(RefCell::new(data)),\n\n callback_info_len as usize,\n\n slot_size as usize,\n\n );\n\n slab.find_max()\n\n}\n\n\n", ...
Rust
glib/src/char.rs
YaLTeR/gtk-rs
b10a29d60458d33642c05421b0ece8d67582229e
use crate::translate::FromGlib; use crate::translate::ToGlib; use libc::{c_char, c_uchar}; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Char(pub c_char); impl Char { pub fn new(c: char) -> Option<Char> { if c as u32 > 255 { ...
use crate::translate::FromGlib; use crate::translate::ToGlib; use libc::{c_char, c_uchar}; #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct Char(pub c_char); impl Char { pub fn new(c: char) -> Option<Char> { if c as u32 > 255 { ...
har) -> char { c.0 as char } } #[doc(hidden)] impl FromGlib<c_uchar> for UChar { unsafe fn from_glib(value: c_uchar) -> Self { UChar(value) } } #[doc(hidden)] impl ToGlib for UChar { type GlibType = c_uchar; fn to_glib(&self) -> c_uchar { self.0 } } #[cfg(test)] mod t...
} else { Some(Char(c as c_char)) } } } impl From<Char> for char { fn from(c: Char) -> char { c.0 as u8 as char } } #[doc(hidden)] impl FromGlib<c_char> for Char { unsafe fn from_glib(value: c_char) -> Self { Char(value) } } #[doc(hidden)] impl ToGlib for Char {...
random
[ { "content": "#[doc(alias = \"gdk_keyval_convert_case\")]\n\npub fn keyval_convert_case(symbol: u32) -> (u32, u32) {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n let mut lower = mem::MaybeUninit::uninit();\n\n let mut upper = mem::MaybeUninit::uninit();\n\n ffi::gdk_keyval_...
Rust
iota-conversion/unit_converter.rs
zesterer/bee-p
375357bdfe8f670e4d26b62a7683d97f339f056f
use super::iota_units::IotaUnits; pub fn convert_units(amount: u64, from: IotaUnits, to: IotaUnits) -> u64 { let amount_in_source = amount * 10_u64.pow(u32::from(from.value())); convert_units_helper(amount_in_source, to) } fn convert_units_helper(amount: u64, to: IotaUnits) -> u64 { amount / 10_u64.pow(u3...
use super::iota_units::IotaUnits; pub fn convert_units(amount: u64, from: IotaUnits, to: IotaUnits) -> u64 { let amount_in_source = amount * 10_u64.pow(u32::from(from.value())); convert_units_helper(amount_in_source, to) } fn convert_units_helper(amount: u64, to: IotaUnits) -> u64 { amount / 10_u64.pow(u3...
_display_text(1000000000000, false), "1.00 Ti" ); assert_eq!( convert_raw_iota_amount_to_display_text(1000000000000000, false), "1.00 Pi" ); assert_eq!( convert_raw_iota_amount_to_display_text(1900000000000002, true), "1.9000000...
t] fn test_find_optimize_unit_to_display() { assert_eq!(find_optimal_iota_unit_to_display(1), IotaUnits::Iota); assert_eq!(find_optimal_iota_unit_to_display(1000), IotaUnits::KiloIota); assert_eq!( find_optimal_iota_unit_to_display(1000000), IotaUnits::MegaIota ...
random
[ { "content": "/// Converts a tryte-encoded string into a UTF-8 string containing ascii characters\n\npub fn to_string(input_trytes: &str) -> Result<String> {\n\n ensure!(\n\n input_trytes.len() % 2 == 0,\n\n iota_constants::INVALID_TRYTES_INPUT_ERROR\n\n );\n\n let mut tmp = String::new()...
Rust
src/core/string.rs
phR0ze/rs
33573ef35ec6964f4aa15340941636fb1a77f6ed
use crate::errors::*; use std::{ffi::OsStr, path::Path, str}; pub trait StringExt { fn size(&self) -> usize; fn trim_suffix<T: Into<String>>(&self, suffix: T) -> String; } impl StringExt for str { fn size(&self...
use crate::errors::*; use std::{ffi::OsStr, path::Path, str}; pub trait StringExt { fn size(&self) -> usize; fn trim_suffix<T: Into<String>>(&self, suffix: T) -> String; } impl StringExt for str { fn size(&self...
} } impl StringExt for String { fn size(&self) -> usize { self.chars().count() } fn trim_suffix<T: Into<String>>(&self, suffix: T) -> String { let target = suffix.into(); match self.ends_with(&target) { true => self[..self.len() - target.len()].to_owned(), ...
match self.ends_with(&target) { true => self[..self.len() - target.len()].to_owned(), _ => self.to_owned(), }
if_condition
[ { "content": "/// Set the timezone from the given value\n\npub fn set_timezone(tz: &str) {\n\n env::set_var(\"TZ\", tz);\n\n unsafe {\n\n c::tzset();\n\n }\n\n}\n\n\n\n// libc types specific to `time` not exposed by base libc crate\n\nmod c {\n\n extern \"C\" {\n\n // `gmtime_r` conver...
Rust
cranelift/native/src/lib.rs
yuyang-ok/wasmtime
67c0d55fbb1f86af0595815e3a9c7f39593f3bd0
#![deny( missing_docs, trivial_numeric_casts, unused_extern_crates, )] /* riscv64gc backend have to use is_riscv_feature_detected which is unstable. */ #![feature(stdsimd)] #![warn(unused_import_braces)] #![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))] #![cfg_att...
#![deny( missing_docs, trivial_numeric_casts, unused_extern_crates, )] /* riscv64gc backend have to use is_riscv_feature_detected which is unstable. */ #![feature(stdsimd)] #![warn(unused_import_braces)] #![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))] #![cfg_att...
if !infer_native_flags { return Ok(isa_builder); } let v = unsafe { libc::getauxval(libc::AT_HWCAP) }; const HWCAP_S390X_VXRS_EXT2: libc::c_ulong = 32768; if (v & HWCAP_S390X_VXRS_EXT2) != 0 { isa_builder.enable("has_vxrs_ext2").unwrap(); ...
isa_builder.enable("has_avx512dq").unwrap(); } if std::is_x86_feature_detected!("avx512f") { isa_builder.enable("has_avx512f").unwrap(); } if std::is_x86_feature_detected!("avx512vl") { isa_builder.enable("has_avx512vl").unwrap(); } if ...
random
[ { "content": "// Configure the test suite environment.\n\n// Test programs use these environment variables to determine what behavior\n\n// is expected: different errnos are expected on windows, mac, and other unixes,\n\n// and other filesystem operations are supported or not.\n\npub fn test_suite_environment()...
Rust
x86_64/src/smbios.rs
Gnurou/crosvm
307168a1eb35dda5b71cdef1d534882c893ef686
use std::mem; use std::result; use std::slice; use std::fs::OpenOptions; use std::io::prelude::*; use std::path::{Path, PathBuf}; use data_model::DataInit; use remain::sorted; use thiserror::Error; use vm_memory::{GuestAddress, GuestMemory}; #[sorted] #[derive(Error, Debug)] pub enum Error { #[error("The ...
use std::mem; use std::result; use std::slice; use std::fs::OpenOptions; use std::io::prelude::*; use std::path::{Path, PathBuf}; use data_model::DataInit; use remain::sorted; use thiserror::Error; use vm_memory::{GuestAddress, GuestMemory}; #[sorted] #[derive(Error, Debug)] pub enum Error { #[error("The ...
fn write_string(mem: &GuestMemory, val: &str, mut curptr: GuestAddress) -> Result<GuestAddress> { for c in val.as_bytes().iter() { curptr = write_and_incr(mem, *c, curptr)?; } curptr = write_and_incr(mem, 0_u8, curptr)?; Ok(curptr) } fn setup_smbios_from_file(mem: &GuestMemory, path: &Path) -...
r) .map_err(|_| Error::WriteData)?; curptr = curptr .checked_add(mem::size_of::<T>() as u64) .ok_or(Error::NotEnoughMemory)?; Ok(curptr) }
function_block-function_prefixed
[ { "content": "/// Write a protective MBR for a disk of the given total size (in bytes).\n\n///\n\n/// This should be written at the start of the disk, before the GPT header. It is one `SECTOR_SIZE`\n\n/// long.\n\npub fn write_protective_mbr(file: &mut impl Write, disk_size: u64) -> Result<(), Error> {\n\n /...
Rust
sulis_core/src/util.rs
ThyWoof/sulis
e89eda94a1a72228224e1926d307aa4c9228bdcb
mod point; pub use self::point::{Offset, Point, Rect, Scale}; pub mod size; pub use self::size::Size; use std::cmp::Ordering; use std::f32; use std::fmt; use std::fs; use std::io::{Error, ErrorKind}; use std::ops::*; use std::panic; use std::path::PathBuf; use std::time::Duration; use backtrace::Backtrace; use log...
mod point; pub use self::point::{Offset, Point, Rect, Scale}; pub mod size; pub use self::size::Size; use std::cmp::Ordering; use std::f32; use std::fmt; use std::fs; use std::io::{Error, ErrorKind}; use std::ops::*; use std::panic; use std::path::PathBuf; use std::time::Duration; use backtrace::Backtrace; use log...
pub fn is_zero(self) -> bool { match self { ExtInt::Int(amount) => amount == 0, ExtInt::Infinity => false, } } pub fn is_infinite(self) -> bool { match self { ExtInt::Int(_) => false, ExtInt::Infinity => true, } } pu...
t) => match other { ExtInt::Int(other_amount) => amount as f32 / other_amount as f32, ExtInt::Infinity => 0.0, }, ExtInt::Infinity => match other { ExtInt::Int(_) => 0.0, ExtInt::Infinity => 1.0, }, } }
function_block-function_prefixed
[]
Rust
utils/global-state-update-gen/src/auction_utils.rs
rafal-ch/casper-node
10ed44340c42dbfd861eefa921144ef6d759410b
use std::collections::{BTreeMap, BTreeSet}; use casper_engine_test_support::internal::LmdbWasmTestBuilder; use casper_execution_engine::shared::stored_value::StoredValue; use casper_types::{ system::auction::{ Bid, SeigniorageRecipient, SeigniorageRecipientsSnapshot, SEIGNIORAGE_RECIPIENTS_SNAPSHOT...
use std::collections::{BTreeMap, BTreeSet}; use casper_engine_test_support::internal::LmdbWasmTestBuilder; use casper_execution_engine::shared::stored_value::StoredValue; use casper_types::{ system::auction::{ Bid, SeigniorageRecipient, SeigniorageRecipientsSnapshot, SEIGNIORAGE_RECIPIENTS_SNAPSHOT...
pkey| { let amount = *new_snapshot .values() .next() .unwrap() .get(pkey) .unwrap() .stake(); let account_hash = pkey.to_account_hash(); let account = builder.get_account(account_hash).unw...
_hash = protocol_data.auction(); let validators_key = builder .get_contract(auction_contract_hash) .expect("auction should exist") .named_keys()[SEIGNIORAGE_RECIPIENTS_SNAPSHOT_KEY]; let stored_value = builder .query(None, validators_key, &[]) .expect("should ...
random
[ { "content": "fn withdraw_bid(public_key: PublicKey, unbond_amount: U512) -> U512 {\n\n let contract_hash = system::get_auction();\n\n let args = runtime_args! {\n\n auction::ARG_AMOUNT => unbond_amount,\n\n auction::ARG_PUBLIC_KEY => public_key,\n\n };\n\n runtime::call_contract(contr...
Rust
tests/do_nestest.rs
Lokathor/terbium
382ce827aeda58e0a66449a1cfafc7da48f9e65b
#![allow(unused)] use std::{fs::File, io::prelude::*, path::Path}; use terbium::*; #[test] fn run_through_nestest() { main(); } fn main() { let rom_path = Path::new("roms").join("nestest.nes"); let mut file = File::open(rom_path).expect("couldn't open ROM file"); let mut contents = Vec::new(); file ...
#![allow(unused)] use std::{fs::File, io::prelude::*, path::Path}; use terbium::*; #[test] fn run_through_nestest() { main(); } fn main() { let rom_path = Path::new("roms").join("nestest.nes"); let mut file = File::open(rom_path).expect("couldn't open ROM file"); let mut contents = Vec::new(); file ...
n!("previous operation was:"); println!("{}", &official_log.lines().nth(n - 2).unwrap()[16..48]); std::process::exit(1); }; if log_s != system.cpu.s { panic!( "S error, line {}, expected {:02X}, got {:02X}", n, log_s, system.cpu.s ) }; while syste...
hable!(), }; if log_instruction != instruction { panic!( "Instruction error, line {}, expected '{}', got '{}'", n, log_instruction, instruction ) }; if log_a != system.cpu.a { println!( "A error, line {} expected state:\n{}\n> expected A:{:02X}, have {:02X...
random
[]
Rust
digest/src/mac.rs
tesaguri/RustCrypto-traits
e5b99207535ed36964ddfc454d1ea46fb1425a07
use crate::{FixedOutput, FixedOutputReset, Update}; use crypto_common::{InvalidLength, Key, KeyInit, KeySizeUser, Output, OutputSizeUser, Reset}; #[cfg(feature = "rand_core")] use crate::rand_core::{CryptoRng, RngCore}; use core::fmt; use generic_array::typenum::Unsigned; use subtle::{Choice, ConstantTimeEq}; #[cfg_a...
use crate::{FixedOutput, FixedOutputReset, Update}; use crypto_common::{InvalidLength, Key, KeyInit, KeySizeUser, Output, OutputSizeUser, Reset}; #[cfg(feature = "rand_core")] use crate::rand_core::{CryptoRng, RngCore}; use core::fmt; use generic_array::typenum::Unsigned; use subtle::{Choice, ConstantTimeEq}; #[cfg_a...
#[inline] fn reset(&mut self) where Self: Reset, { Reset::reset(self) } #[inline] fn verify(self, tag: &Output<Self>) -> Result<(), MacError> { if self.finalize() == tag.into() { Ok(()) } else { Err(MacError) } } #[i...
fn finalize_reset(&mut self) -> CtOutput<Self> where Self: FixedOutputReset, { CtOutput::new(self.finalize_fixed_reset()) }
function_block-full_function
[ { "content": "/// Trait for hash functions with fixed-size output able to reset themselves.\n\npub trait FixedOutputReset: FixedOutput + Reset {\n\n /// Write result into provided array and reset the hasher state.\n\n fn finalize_into_reset(&mut self, out: &mut Output<Self>);\n\n\n\n /// Retrieve resul...
Rust
rafx-api/src/queue.rs
DavidVonDerau/rafx
5d42caed4bd7fcb5d32e3e26021669cf60071abd
#[cfg(any( feature = "rafx-empty", not(any(feature = "rafx-metal", feature = "rafx-vulkan")) ))] use crate::empty::RafxQueueEmpty; #[cfg(feature = "rafx-metal")] use crate::metal::RafxQueueMetal; #[cfg(feature = "rafx-vulkan")] use crate::vulkan::RafxQueueVulkan; use crate::{ RafxCommandBuffer, RafxCommandP...
#[cfg(any( feature = "rafx-empty", not(any(feature = "rafx-metal", feature = "rafx-vulkan")) ))] use crate::empty::RafxQueueEmpty; #[cfg(feature = "rafx-metal")] use crate::metal::RafxQueueMetal; #[cfg(feature = "rafx-vulkan")] use crate::vulkan::RafxQueueVulkan; use crate::{ RafxCommandBuffer, RafxCommandP...
afx-empty", not(any(feature = "rafx-metal", feature = "rafx-vulkan")) ))] RafxQueue::Empty(inner) => inner.queue_type(), } } pub fn create_command_pool( &self, command_pool_def: &RafxCommandPoolDef, ) -> RafxResult<RafxCommandPool> { ...
&self) -> RafxQueueType { match self { #[cfg(feature = "rafx-vulkan")] RafxQueue::Vk(inner) => inner.queue_type(), #[cfg(feature = "rafx-metal")] RafxQueue::Metal(inner) => inner.queue_type(), #[cfg(any( feature = "r
function_block-random_span
[ { "content": "pub fn draw_skybox(\n\n resource_context: &ResourceContext,\n\n skybox_material: &ResourceArc<MaterialPassResource>,\n\n skybox_texture: &ResourceArc<ImageViewResource>,\n\n main_view: &RenderView,\n\n render_target_meta: &GraphicsPipelineRenderTargetMeta,\n\n command_buffer: &Ra...
Rust
elasticsearch/examples/index_questions_answers/main.rs
yaanhyy/elasticsearch-rs
740c3ebd41b391f954e9cf008209b39d89a75231
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not u...
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not u...
fn running_proxy() -> bool { let system = sysinfo::System::new(); !system.get_process_by_name("Fiddler").is_empty() } let mut url = Url::parse(cluster_addr().as_ref()).unwrap(); let credentials = if url.scheme() == "https" { let username = if !url.username().is_empt...
td::env::var("ELASTICSEARCH_URL") { Ok(server) => server, Err(_) => DEFAULT_ADDRESS.into(), } }
function_block-function_prefixed
[ { "content": "fn create_client() -> Result<Elasticsearch, Error> {\n\n fn cluster_addr() -> String {\n\n match std::env::var(\"ELASTICSEARCH_URL\") {\n\n Ok(server) => server,\n\n Err(_) => DEFAULT_ADDRESS.into(),\n\n }\n\n }\n\n\n\n /// Determines if Fiddler.exe pro...
Rust
src/lib.rs
Lantern-chat/mime_db
a197b8e9e608872b8a042a254d4e86fa6cf21ce0
use unicase::UniCase; #[derive(Debug, Clone, Copy)] pub struct MimeEntry { compressible: bool, extensions: &'static [&'static str], } #[derive(Debug, Clone, Copy)] pub struct ExtEntry { types: &'static [&'static str], } include!(concat!(env!("OUT_DIR"), "/mime_db.rs")); pub fn lookup_ext(ext: &str) -> O...
use unicase::UniCase; #[derive(Debug, Clone, Copy)] pub struct MimeEntry { compressible: bool, extensions: &'static [&'static str], } #[derive(Debug, Clone, Copy)] pub struct ExtEntry { types: &'static [&'static str], } include!(concat!(env!("OUT_DIR"), "/mime_db.rs")); pub fn lookup_ext(ext: &str) -> O...
0, &[ 0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C, ], "video/x-ms-wmv", ), ( 0, &[ 0x53, 0x49, 0x4D, 0x50, 0x4C, 0x45, 0x20, 0x20, 0x3D, 0x20, ...
0, &[0x78, 0x9C], "application/z-lib"), (0, &[0x78, 0xDA], "application/z-lib"), (0, &[0x78, 0x20], "application/z-lib"), (0, &[0x78, 0x7D], "application/z-lib"), (0, &[0x78, 0xBB], "application/z-lib"), (0, &[0x78, 0xF9], "application/z-lib"), ( 0, ...
random
[ { "content": "#[derive(Debug, serde::Deserialize)]\n\nstruct MimeEntry {\n\n #[serde(default)]\n\n pub compressible: bool,\n\n\n\n #[serde(default)]\n\n pub extensions: Vec<String>,\n\n\n\n #[serde(default)]\n\n pub source: Source,\n\n}\n\n\n", "file_path": "build.rs", "rank": 4, "...
Rust
src/connectivity/overnet/overnetstack/src/main.rs
mehulagg/fuchsia
3f56175ee594da6b287d5fb19f2f0eccea2897f0
#![deny(missing_docs)] mod mdns; use failure::{Error, ResultExt}; use fidl_fuchsia_overnet::{ MeshControllerRequest, MeshControllerRequestStream, OvernetListPeersResponder, OvernetRequest, OvernetRequestStream, ServiceConsumerListPeersResponder, ServiceConsumerRequest, ServiceConsumerRequestStream, Serv...
#![deny(missing_docs)] mod mdns; use failure::{Error, ResultExt}; use fidl_fuchsia_overnet::{ MeshControllerRequest, MeshControllerRequestStream, OvernetListPeersResponder, OvernetRequest, OvernetRequestStream, ServiceConsumerListPeersResponder, ServiceConsumerRequest, ServiceConsumerRequestStream, Serv...
fn send_on_link(&mut self, id: Self::LinkId, packet: &mut [u8]) -> Result<(), Error> { match id { AppLinkId::Udp(addr) => { println!("UDP_SEND to:{} len:{}", addr, packet.len()); let sock = with_app_mut(|app| -> Result<_, Error> { Ok(app ...
ppLinkId) -> LinkId<overnet_core::PhysLinkId<AppLinkId>> { with_app_mut(|app| match id { AppLinkId::Udp(addr) => { app.udp_link_ids.get(&addr).copied().unwrap_or(LinkId::invalid()) } }) }
function_block-function_prefixed
[]
Rust
src/fmtstr.rs
MikaelSmith/strfmt
4ad7c2240203df3eec954fb00a31e87d74812339
use std::fmt::Write; use std::string::String; use types::*; use formatter::Formatter; fn write_char(f: &mut Formatter, c: char, n: usize) { for _ in 0..n { f.write_char(c).unwrap(); } } #[test] fn test_write_char() { let mut s = String::new(); s.write_str("h ").unwrap(); { let mut...
use std::fmt::Write; use std::string::String; use types::*; use formatter::Formatter; fn write_char(f: &mut Formatter, c: char, n: usize) { for _ in 0..n { f.write_char(c).unwrap(); } } #[test] fn test_write_char() { let mut s = String::new(); s.write_str("h ").unwrap(); { let mut...
pub fn str_unchecked(&mut self, s: &str) -> Result<()> { let fill = self.fill(); let width = self.width(); let precision = self.precision(); let len = match precision { Some(p) => if p < s.len() { p ...
pub fn str(&mut self, s: &str) -> Result<()> { if !(self.ty() == None || self.ty() == Some('s')) { let mut msg = String::new(); write!(msg, "Unknown format code {:?} for object of type 'str'", self.ty()).unwrap(); return Err(FmtError::TypeError(msg)); } else if self.a...
function_block-full_function
[ { "content": "fn is_type_element(c: char) -> bool {\n\n match c {\n\n 'b' |\n\n 'o' |\n\n 'x' |\n\n 'X' |\n\n 'e' |\n\n 'E' |\n\n 'f' |\n\n 'F' |\n\n '%' |\n\n 's' |\n\n '?' => true,\n\n _ => false,\n\n }\n\n}\n\n\n", ...
Rust
src/eval.rs
edre/nokamute
ace46abe0cb2a4056e0e97c4377deb2746bcbae0
use crate::board::*; pub struct DumbEvaluator; impl minimax::Evaluator for DumbEvaluator { type G = Rules; fn evaluate(&self, _: &Board) -> minimax::Evaluation { 0 } } pub struct BasicEvaluator { queen_factor: i32, movable_bug_factor: i32, unplayed_bug_factor: i32, } impl Default for...
use crate::board::*; pub struct DumbEvaluator; impl minimax::Evaluator for DumbEvaluator { type G = Rules; fn evaluate(&self, _: &Board) -> minimax::Evaluation { 0 } } pub struct BasicEvaluator { queen_factor: i32, movable_bug_factor: i32, unplayed_bug_factor: i32, } impl Default for...
if board.slidable_adjacent(id, id).next().is_none() { continue; } } bug_score *= self.movable_bug_factor; if tile.color != board.to_move() { bug_score = -bug_score; } ...
continue; } if tile.bug == Bug::Mosquito { if tile.underneath.is_some() { bug_score = value(Bug::Beetle); } else { bug_score = node .adj ...
random
[ { "content": "fn perft_recurse(b: &mut Board, depth: usize) -> u64 {\n\n if depth == 0 {\n\n return 1;\n\n }\n\n if Rules::get_winner(b).is_some() {\n\n // Apparently perft rules only count positions at the target depth.\n\n return 0;\n\n }\n\n let mut moves = Vec::new();\n\n...
Rust
src/canary_update.rs
The-Emperor10/oofbot
e20a399eafbe9a6c7449680108690013a7a2c1ac
use crate::logger::get_guild_members; use crate::{permissions::SqlHandler, LogResult}; use serenity::framework::standard::macros::check; use serenity::{ framework::standard::{ macros::{command, group}, *, }, model::prelude::*, prelude::*, utils::MessageBuilder, }; use sqlite::*; use std::{ ops::Deref, sync::...
use crate::logger::get_guild_members; use crate::{permissions::SqlHandler, LogResult}; use serenity::framework::standard::macros::check; use serenity::{ framework::standard::{ macros::{command, group}, *, }, model::prelude::*, prelude::*, utils::MessageBuilder, }; use sqlite::*; use std::{ ops::Deref, sync::...
#[command] #[checks(Manage)] #[description = "Unsets the channel for updates"] #[only_in(guilds)] async fn unsetupdatechannel(ctx: &Context, msg: &Message) -> CommandResult { if let Some(guild_id) = msg.guild_id { let clock = ctx.data.read().await; let canary = clock.get::<CanaryUpdateHandler>().unwrap(); let ...
async fn getupdatechannel(ctx: &Context, msg: &Message) -> CommandResult { if let Some(guild_id) = msg.guild_id { let clock = ctx.data.read().await; let canary = clock.get::<CanaryUpdateHandler>().unwrap(); let lock = canary.lock().await; let res = lock.get_update_channel(&guild_id).await; if let Some(id) =...
function_block-full_function
[ { "content": "pub fn do_framework(_framework: &mut StandardFramework) {}\n\n\n\nimpl SqlHandler {\n\n\tpub fn new() -> Arc<Self> {\n\n\t\tlet sql_connection = Mutex::new(Connection::open(\"oofbot.db\").unwrap());\n\n\t\tArc::new(Self { sql_connection })\n\n\t}\n\n\t/// Creates the sqlite canary update table\n\n...
Rust
src/main.rs
andersk/prime-summer
060f1167a56cab1fff687e52a13af5815d2508ad
use primesieve_sys::{ primesieve_free, primesieve_free_iterator, primesieve_generate_primes, primesieve_init, primesieve_iterator, primesieve_next_prime, primesieve_prev_prime, primesieve_skipto, UINT64_PRIMES, }; use rug::ops::Pow; use rug::Integer; use std::collections::VecDeque; use std::env; use std::er...
use primesieve_sys::{ primesieve_free, primesieve_free_iterator, primesieve_generate_primes, primesieve_init, primesieve_iterator, primesieve_next_prime, primesieve_prev_prime, primesieve_skipto, UINT64_PRIMES, }; use rug::ops::Pow; use rug::Integer; use std::collections::VecDeque; use std::env; use std::er...
eq!( sum_primes_squared(15485863), "76304519151822049179".parse::<Integer>().unwrap() ); assert_eq!( sum_primes_squared(179424673), "103158861357874372432083".parse::<Integer>().unwrap() ); assert_eq!( sum_primes_squared(2038074743), "133759354162117403400...
function_block-function_prefixed
[ { "content": "# prime-summer\n\n\n\nThe easiest way to try this is via Docker:\n\n\n\n```console\n\n$ docker run --rm anderskaseorg/prime-summer prime-summer 100\n\nSum of squares of primes ≤ 100 is 65796\n\n$ docker run --rm anderskaseorg/prime-summer prime-summer 10000000000000\n\nSum of squares of primes ≤ 1...
Rust
src/vmm/src/memory_snapshot.rs
HQ01/firecracker
a08be39fb621b17494e0a964ad5d434c65a8e737
#![cfg(target_arch = "x86_64")] use std::fmt::{Display, Formatter}; use std::fs::File; use std::io::SeekFrom; use versionize::{VersionMap, Versionize, VersionizeResult}; use versionize_derive::Versionize; use vm_memory::{ Bytes, FileOffset, GuestAddress, GuestMemory, GuestMemoryError, GuestMemoryMmap, Guest...
#![cfg(target_arch = "x86_64")] use std::fmt::{Display, Formatter}; use std::fs::File; use std::io::SeekFrom; use versionize::{VersionMap, Versionize, VersionizeResult}; use versionize_derive::Versionize; use vm_memory::{ Bytes, FileOffset, GuestAddress, GuestMemory, GuestMemoryError, GuestMemoryMmap, Guest...
#[test] fn test_restore_memory() { let page_size: usize = sysconf::page::pagesize(); let mem_regions = [ (GuestAddress(0), page_size * 2), (GuestAddress(page_size as u64 * 3), page_size * 2), ]; let guest_memory = GuestMemoryMmap::from_ranges_w...
s: vec![ GuestMemoryRegionState { base_address: 0, size: page_size, offset: 0, }, GuestMemoryRegionState { base_address: page_size as u64 * 2, size: page_size, ...
function_block-function_prefixed
[ { "content": "/// Returns a Vec of the valid memory addresses.\n\n/// These should be used to configure the GuestMemoryMmap structure for the platform.\n\n/// For x86_64 all addresses are valid from the start of the kernel except a\n\n/// carve out at the end of 32bit address space.\n\npub fn arch_memory_region...
Rust
liblumen_alloc/src/erts/term/arch/repr.rs
bitwalker/lumen
7d286b93d1a839aa7de5fed7020bafc1bc39f300
use core::fmt::{self, Debug, Display}; use core::hash::Hash; use alloc::sync::Arc; use std::backtrace::Backtrace; use crate::erts::term::prelude::*; use super::Tag; pub trait Repr: Sized + Copy + Debug + Display + PartialEq<Self> + Eq + PartialOrd<Self> + Ord + Hash + Send { type Word: Clone + Copy + Parti...
use core::fmt::{self, Debug, Display}; use core::hash::Hash; use alloc::sync::Arc; use std::backtrace::Backtrace; use crate::erts::term::prelude::*; use super::Tag; pub trait Repr: Sized + Copy + Debug + Display + PartialEq<Self> + Eq + PartialOrd<Self> + Ord + Hash + Send { type Word: Clone + Copy + Parti...
se { Ok(TypedTerm::ProcBin(ptr.cast::<ProcBin>())) } } }, Tag::SubBinary => Ok(TypedTerm::SubBinary(ptr.cast::<SubBinary>())), Tag::MatchContext => Ok(TypedTerm::MatchContext(ptr.cast::<MatchContext>())), Tag::Ex...
=> Ok(TypedTerm::ProcBin(ptr.cast::<ProcBin>())), Some(true) => Ok(TypedTerm::BinaryLiteral(ptr.cast::<BinaryLiteral>())), None => { let offset = BinaryLiteral::flags_offset(); debug_assert_eq!(offset, ProcBin::inner_offset()); ...
random
[ { "content": "#[inline]\n\npub fn in_area<T, U>(ptr: *const T, start: *const U, end: *const U) -> bool\n\nwhere\n\n T: ?Sized,\n\n U: ?Sized,\n\n{\n\n // If any pointers are null, the only sensible answer is false\n\n if ptr.is_null() || start.is_null() || end.is_null() {\n\n false\n\n } e...
Rust
wayland-commons/src/map.rs
atouchet/wayland-rs
de9eac07cb9d295333a33ee45dae4342341bc26e
use crate::{Interface, MessageGroup, NoMessage}; use std::cmp::Ordering; pub const SERVER_ID_LIMIT: u32 = 0xFF00_0000; pub trait ObjectMetadata: Clone { fn child(&self) -> Self; } impl ObjectMetadata for () { fn child(&self) {} } #[derive(Clone)] pub struct Object<Meta: ObjectMetadata> { ...
use crate::{Interface, MessageGroup, NoMessage}; use std::cmp::Ordering; pub const SERVER_ID_LIMIT: u32 = 0xFF00_0000; pub trait ObjectMetadata: Clone { fn child(&self) -> Self; } impl ObjectMetadata for () { fn child(&self) {} } #[derive(Clone)] pub struct Object<Meta: ObjectMetadata> { ...
#[allow(clippy::result_unit_err)] pub fn insert_at(&mut self, id: u32, object: Object<Meta>) -> Result<(), ()> { if id == 0 { Err(()) } else if id >= SERVER_ID_LIMIT { insert_in_at(&mut self.server_objects, (id - SERVER_ID_LIMIT) as usize, objec...
place = None; } } else if let Some(place) = self.client_objects.get_mut((id - 1) as usize) { *place = None; } }
function_block-function_prefix_line
[ { "content": "fn display_req_child(opcode: u16, _: u32, meta: &ObjectMeta) -> Option<Object<ObjectMeta>> {\n\n match opcode {\n\n // sync\n\n 0 => Some(Object::from_interface::<crate::protocol::wl_callback::WlCallback>(\n\n 1,\n\n meta.child(),\n\n )),\n\n //...
Rust
mem6/src/fetch_mod.rs
bestia-dev/mem6_game
9bd5ccab9f66fc884dd7ed2ea774f35520e124eb
use crate::*; use unwrap::unwrap; use wasm_bindgen_futures::spawn_local; use dodrio::VdomWeak; pub fn async_fetch_game_config_and_update(rrc: &mut RootRenderingComponent, vdom: VdomWeak) { let url_config = format!( "{}/content/{}/game_config.json", rrc.web_data.href, rrc.game_data.game_name )...
use crate::*; use unwrap::unwrap; use wasm_bindgen_futures::spawn_local; use dodrio::VdomWeak; pub fn async_fetch_game_config_and_update(rrc: &mut RootRenderingComponent, vdom: VdomWeak) { let url_config = format!( "{}/content/{}/game_config.json", rrc.web_data.href, rrc.game_data.game_name )...
pub fn fetch_videos_and_update(href: &str, vdom: VdomWeak) { let url = format!("{}/content/videos.json", href); spawn_local({ let vdom_on_next_tick = vdom.clone(); async move { let respbody = websysmod::fetch_response(url).await; let vid_json: game_data_mod::Videos = un...
pub fn fetch_games_metadata_and_update(href: &str, vdom: VdomWeak) { let url_config = format!("{}/content/gamesmetadata.json", href); spawn_local({ let vdom_on_next_tick = vdom.clone(); async move { let respbody = websysmod::fetch_response(url_config).await; ...
function_block-full_function
[ { "content": "/// on click\n\npub fn on_click_take_turn(rrc: &mut RootRenderingComponent, vdom: &VdomWeak) {\n\n // websysmod::debug_write(&format!(\"on_click_take_turn {}\", \"\"));\n\n\n\n let msg_id = ackmsgmod::prepare_for_ack_msg_waiting(rrc, vdom);\n\n\n\n let msg = websocketmod::WsMessageForRece...
Rust
src/network/tests.rs
ambaxter/expert-rs
5d5070f4c8842a0b4f53c6ebc277ea0444fedb58
use std::hash::{Hash, Hasher}; use std::fmt; use std::fmt::Debug; use traits::Fact; use ordered_float::NotNaN; use runtime::memory::SymbolId; use num::Float; #[derive(Clone, Hash, Eq, PartialEq)] pub enum CLimits<T: Hash + Eq + Ord + Clone> { S(T), D(T, T) } #[derive(Clone)] pub enum OrdData<T: Fact>{ I8(...
use std::hash::{Hash, Hasher}; use std::fmt; use std::fmt::Debug; use traits::Fact; use ordered_float::NotNaN; use runtime::memory::SymbolId; use num::Float; #[derive(Clone, Hash, Eq, PartialEq)] pub enum CLimits<T: Hash + Eq + Ord + Clone> { S(T), D(T, T) } #[derive(Clone)] pub enum OrdData<T: Fact>{ I8(...
&F64(accessor, ref limits) => { Self::hash_self(1, accessor as usize, limits, state); }, } } } impl<T: Fact> PartialEq for FlData<T> { fn eq(&self, other: &Self) -> bool { use self::FlData::*; match (self, other) { (&F32(accessor1, ref limits1...
limits, state); }, &I32(accessor, ref limits) => { Self::hash_self(2, accessor as usize, limits, state); }, &I64(accessor, ref limits) => { Self::hash_self(3, accessor as usize, limits, state); }, &U8(accessor, ref ...
random
[ { "content": "pub trait Fact: Introspect + Eq + Hash\n\n where Self: std::marker::Sized {\n\n type HashEq: Hash + Eq + Clone + Debug;\n\n fn create_hash_eq(conditions: &Vec<StatementConditions>, cache: &StringCache) -> Self::HashEq;\n\n fn new_from_fields(fields: &[FieldValue], cache: &StringCache) ...
Rust
src/can1/mir1_arb.rs
crawford/efm32gg11b820
390142de0a68b55a142bb16d31634cebf2289209
#[doc = "Reader of register MIR1_ARB"] pub type R = crate::R<u32, super::MIR1_ARB>; #[doc = "Writer for register MIR1_ARB"] pub type W = crate::W<u32, super::MIR1_ARB>; #[doc = "Register MIR1_ARB `reset()`'s with value 0"] impl crate::ResetValue for super::MIR1_ARB { type Type = u32; #[inline(always)] fn re...
#[doc = "Reader of register MIR1_ARB"] pub type R = crate::R<u32, super::MIR1_ARB>; #[doc = "Writer for register MIR1_ARB"] pub type W = crate::W<u32, super::MIR1_ARB>; #[doc = "Register MIR1_ARB `reset()`'s with value 0"] impl crate::ResetValue for super::MIR1_ARB { type Type = u32; #[inline(always)] fn re...
self.w } } #[doc = "Reader of field `MSGVAL`"] pub type MSGVAL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MSGVAL`"] pub struct MSGVAL_W<'a> { w: &'a mut W, } impl<'a> MSGVAL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { se...
t_value() -> Self::Type { 0 } } #[doc = "Reader of field `ID`"] pub type ID_R = crate::R<u32, u32>; #[doc = "Write proxy for field `ID`"] pub struct ID_W<'a> { w: &'a mut W, } impl<'a> ID_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) ...
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
crates/core/plugin_sm/tests/plugin_manager.rs
PradeepKiruvale/localworkflow
b5f3c97c835cb36ae87f14b8697bedcca5d22619
#[cfg(test)] mod tests { use plugin_sm::plugin_manager::{ExternalPlugins, Plugins}; use std::{fs::File, path::PathBuf, str::FromStr}; use tempfile::NamedTempFile; #[test] fn plugin_manager_load_plugins_empty() { let temp_dir = tempfile::tempdir().unwrap(); let plugin_dir =...
#[cfg(test)] mod tests { use plugin_sm::plugin_manager::{ExternalPlugins, Plugins}; use std::{fs::File, path::PathBuf, str::FromStr}; use tempfile::NamedTempFile; #[test] fn plugin_manager_load_plugins_empty() { let temp_dir = tempfile::tempdir().unwrap(); let plugin_dir =...
fn create_some_plugin_in(dir: &tempfile::TempDir) -> NamedTempFile { tempfile::Builder::new() .suffix(".0") .tempfile_in(dir) .unwrap() } fn get_dummy_plugin_path() -> PathBuf { let package_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); ...
p(); let result = ExternalPlugins::open(plugin_dir.into_path(), Some("dummy".into()), None)?; assert!(result.empty()); assert!(result.default().is_none()); Ok(()) }
function_block-function_prefixed
[ { "content": "fn get_project_name(tedge_apama_project_path: &Path) -> String {\n\n let tedge_apama_project_descriptor_path = tedge_apama_project_path.join(\".project\");\n\n if tedge_apama_project_descriptor_path.exists() {\n\n if let Ok(xml_content) = fs::read_to_string(tedge_apama_project_descrip...
Rust
xtask/src/main.rs
YruamaLairba/rust-lv2-more-examples
0d19fd3e120ec3563ad7e7cd471e1396cbf8e512
#![allow(clippy::try_err)] extern crate getopts; use getopts::Options; use std::env; use std::fs; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Write; use std::iter::Iterator; use std::path::{Path, PathBuf}; use std::process::Command; type DynError = Box<dyn std:...
#![allow(clippy::try_err)] extern crate getopts; use getopts::Options; use std::env; use std::fs; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Write; use std::iter::Iterator; use std::path::{Path, PathBuf}; use std::process::Command; type DynError = Box<dyn std:...
; String::from(prefix) } fn lib_suffix(&self) -> String { let suffix = if self.target.contains("apple") { ".dylib" } else if self.target.contains("windows") { ".dll" } else if cfg!(target_vendor = "apple") { ".dylib" } else if cfg!(tar...
if self.target.contains("windows") { "" } else if cfg!(target_vendor = "apple") { "lib" } else if cfg!(target_os = "windows") { "" } else { "lib" }
if_condition
[ { "content": "#[derive(PortCollection)]\n\nstruct Ports {\n\n trigger_task: InputPort<Control>,\n\n}\n\n\n\n/// Requested features\n", "file_path": "eg-worker-rs/src/lib.rs", "rank": 9, "score": 48153.91537814452 }, { "content": "#[derive(PortCollection)]\n\nstruct Ports {\n\n _param1:...
Rust
src/view/mod.rs
matthias-t/Smith
e89ded89a4ce2147ca3c8be6ed065a8f1a808fff
mod screen; use self::screen::Screen; use data::{Editable, Named, Selectable}; use std::{cmp, iter}; use termion::{color, style, terminal_size}; pub struct View { message: Option<String>, is_prompt: bool, line_offset: usize, screen: Screen, } const TAB_LENGTH: usize = 4; impl View { pub fn new()...
mod screen; use self::screen::Screen; use data::{Editable, Named, Selectable}; use std::{cmp, iter}; use termion::{color, style, terminal_size}; pub struct View { message: Option<String>, is_prompt: bool, line_offset: usize, screen: Screen, } const TAB_LENGTH: usize = 4; impl View { pub fn new()...
fn cursor_pos<T: Editable>(&self, content: &T) -> (usize, usize) { let line = content.line(); let first_line = self.line_offset; let y = line - first_line as usize; let visual_col = content.col(); let column: usize = content .iter_line(line) ...
fn paint_lines<T>(&self, content: &T) where T: Editable + Selectable, { let line_offset = self.line_offset as usize; let lines_height = self.lines_height() as usize; let lines_width = self.lines_width(content.line_count()) as usize; let line_count = content.line_count(); ...
function_block-full_function
[]
Rust
liblz4stego/src/compressor.rs
m4tx/lz4stego
5e53272900a74c1c88b993f92087ae7e588130b8
use std::cmp::min; use log::debug; use xxhash_rust::xxh32::{xxh32, Xxh32}; use crate::constants::{ END_LITERAL_NUM, LZ4_MAGIC_NUMBER, MATCH_LENGTH_OFFSET, MAX_BLOCK_SIZE, MIN_COMPRESS_LENGTH, TOKEN_MAX_VAL, }; use crate::descriptors::{BdByte, BlockSize, FlgByte, Token}; use crate::numeral_coding; use crate::o...
use std::cmp::min; use log::debug; use xxhash_rust::xxh32::{xxh32, Xxh32}; use crate::constants::{ END_LITERAL_NUM, LZ4_MAGIC_NUMBER, MATCH_LENGTH_OFFSET, MAX_BLOCK_SIZE, MIN_COMPRESS_LENGTH, TOKEN_MAX_VAL, }; use crate::descriptors::{BdByte, BlockSize, FlgByte, Token}; use crate::numeral_coding; use crate::o...
pub fn new(writer: W) -> Result<Self, std::io::Error> { let mut compressor = Self { output_write: writer, buffer: VecDeque::new(), hash: Xxh32::new(0), hidden_data_encoder: numeral_coding::Decoder::new(b""), prefer_hidden: false, }; ...
Result<Self, std::io::Error> { let mut compressor = Self { output_write: writer, buffer: VecDeque::new(), hash: Xxh32::new(0), hidden_data_encoder: numeral_coding::Decoder::new(hidden_data), prefer_hidden, }; compressor.init()?; ...
function_block-function_prefixed
[ { "content": "fn compress(data: &[u8]) -> Vec<u8> {\n\n let mut output = Vec::new();\n\n let mut compressor = Compressor::new(&mut output).unwrap();\n\n compressor.write(data).unwrap();\n\n compressor.finish().unwrap();\n\n\n\n output\n\n}\n\n\n", "file_path": "liblz4stego/src/tests/compresso...
Rust
qlib/buddyallocator.rs
CentaurusInfra/Quark
1079b36efa7e537f8fec39f037ee5ccc71977e7d
use super::mutex::*; use alloc::slice; use alloc::vec::Vec; use core::ops::Deref; use super::addr::*; use super::common::*; pub fn ZeroPage(pageStart: u64) { unsafe { let arr = slice::from_raw_parts_mut(pageStart as *mut u64, 512); for i in 0..512 { arr[i] = 0 } } } #[de...
use super::mutex::*; use alloc::slice; use alloc::vec::Vec; use core::ops::Deref; use super::addr::*; use super::common::*; pub fn ZeroPage(pageStart: u64) { unsafe { let arr = slice::from_raw_parts_mut(pageStart as *mut u64, 512); for i in 0..512 { arr[i] = 0 } } } #[de...
} pub struct MemAllocator(QMutex<MemAllocatorInternal>); impl Deref for MemAllocator { type Target = QMutex<MemAllocatorInternal>; fn deref(&self) -> &QMutex<MemAllocatorInternal> { &self.0 } } impl RefMgr for MemAllocator { fn Ref(&self, _addr: u64) -> Result<u64> { return Ok(1); ...
pub fn Free(&mut self, addr: u64, pages: u64) -> Result<()> { let pageOff = (addr - self.baseAddr) as u64 >> PAGE_SHIFT; let ret = self.ba.free(pageOff, pages); if ret { Ok(()) } else { Err(Error::InvalidInput) } }
function_block-full_function
[ { "content": "#[inline(always)]\n\npub fn CmpExchg(addr: u64, old: u64, new: u64) -> u64 {\n\n let mut ret: u64;\n\n unsafe {\n\n llvm_asm!(\"\n\n lock cmpxchgq $2, ($3)\n\n \"\n\n : \"={rax}\"(ret)\n\n : \"{rax}\"(old), \"{rdx}\"(new), \"{rcx}\"(addr)\...
Rust
crates/plugins/physics-rapier/src/lib.rs
Hihaheho-Studios/desk
7f8ad48a3b9a5439e566d07aecab6185c2d95012
use core::DeskSystem; use bevy::prelude::*; use bevy_rapier2d::prelude::*; use physics::{shape::Shape, widget::WidgetId, DragState, Velocity}; pub struct PhysicsPlugin; const LINEAR_DAMPING: f32 = 8.0; impl Plugin for PhysicsPlugin { fn build(&self, app: &mut bevy::app::AppBuilder) { app.add_plugin(Rapi...
use core::DeskSystem; use bevy::prelude::*; use bevy_rapier2d::prelude::*; use physics::{shape::Shape, widget::WidgetId, DragState, Velocity}; pub struct PhysicsPlugin; const LINEAR_DAMPING: f32 = 8.0; impl Plugin for PhysicsPlugin { fn build(&self, app: &mut bevy::app::AppBuilder) { app.add_plugin(Rapi...
ping, &DragState), Changed<DragState>>) { for (mut damping, drag_state) in query.iter_mut() { use DragState::*; match drag_state { Dragging => { damping.linear_damping = 0.0; } NotDragging => { damping.linear_damping = LINEAR_DAMPIN...
function_block-function_prefixed
[ { "content": "fn reset_velocity(mut query: Query<&mut Velocity>) {\n\n for mut velocity in query.iter_mut() {\n\n velocity.0 = Vec2::ZERO;\n\n }\n\n}\n\n\n", "file_path": "crates/plugins/shell/src/lib.rs", "rank": 0, "score": 207939.65898868084 }, { "content": "fn translate_posi...
Rust
crypto-msg-parser/src/exchanges/binance/binance_all.rs
CPT-Jack-A-Castle/crypto-crawler-rs
e7b8a2d51989e69779c69e3e7755351fe5fcb3bb
use crypto_market_type::MarketType; use crate::{FundingRateMsg, MessageType, Order, OrderBookMsg, TradeMsg, TradeSide}; use super::super::utils::calc_quantity_and_volume; use serde::{Deserialize, Serialize}; use serde_json::{Result, Value}; use std::collections::HashMap; const EXCHANGE_NAME: &str = "binance"; #[der...
use crypto_market_type::MarketType; use crate::{FundingRateMsg, MessageType, Order, OrderBookMsg, TradeMsg, TradeSide}; use super::super::utils::calc_quantity_and_volume; use serde::{Deserialize, Serialize}; use serde_json::{Result, Value}; use std::collections::HashMap; const EXCHANGE_NAME: &str = "binance"; #[der...
, asks: ws_msg .data .a .iter() .map(|raw_order| parse_order(raw_order)) .collect::<Vec<Order>>(), bids: ws_msg .data .b .iter() .map(|raw_order| parse_order(raw_order)) .collect::<Vec...
if market_type == MarketType::Spot { ws_msg.data.E } else { ws_msg.data.T.unwrap() }
if_condition
[ { "content": "pub fn check_trade_fields(exchange: &str, market_type: MarketType, pair: String, trade: &TradeMsg) {\n\n assert_eq!(trade.exchange, exchange);\n\n assert_eq!(trade.market_type, market_type);\n\n assert_eq!(trade.pair, pair);\n\n assert_eq!(trade.msg_type, MessageType::Trade);\n\n as...
Rust
lapce-data/src/rich_text.rs
mirchandani-mohnish/lapce
d20ddbee3bd39c03aae6d59e7bd1c61eb3c45e9f
use std::{ ops::{Range, RangeBounds}, sync::Arc, }; use druid::{ piet::TextStorage as PietTextStorage, piet::{PietTextLayoutBuilder, TextLayoutBuilder}, text::{Attribute, AttributeSpans, Link}, text::{EnvUpdateCtx, TextStorage}, ArcStr, Color, Command, Data, Env, FontDescriptor, FontFamily,...
use std::{ ops::{Range, RangeBounds}, sync::Arc, }; use druid::{ piet::TextStorage as PietTextStorage, piet::{PietTextLayoutBuilder, TextLayoutBuilder}, text::{Attribute, AttributeSpans, Link}, text::{EnvUpdateCtx, TextStorage}, ArcStr, Color, Command, Data, Env, FontDescriptor, FontFamily,...
t_family(&mut self, family: FontFamily) -> &mut Self { self.add_attr(Attribute::font_family(family)); self } pub fn weight(&mut self, weight: FontWeight) -> &mut Self { self.add_attr(Attribute::weight(weight)); self } pub fn style(&mut self, style: FontStyle) ...
new() -> Self { Self::default() } pub fn push(&mut self, string: &str) -> AttributesAdder { let range = self.buffer.len()..(self.buffer.len() + string.len()); self.buffer.push_str(string); self.add_attributes_for_range(range) } pub fn set_line_heigh...
random
[]
Rust
src/proc/bin/starnix/fs/fuchsia/remote.rs
dahliaOS/fuchsia-pi4
5b534fccefd918b5f03205393c1fe5fddf8031d0
use fidl_fuchsia_io as fio; use fidl_fuchsia_kernel as fkernel; use fuchsia_component::client::connect_channel_to_protocol; use fuchsia_zircon as zx; use lazy_static::lazy_static; use log::info; use crate::fd_impl_seekable; use crate::fs::*; use crate::task::*; use crate::types::*; lazy_static! { static ref VME...
use fidl_fuchsia_io as fio; use fidl_fuchsia_kernel as fkernel; use fuchsia_component::client::connect_channel_to_protocol; use fuchsia_zircon as zx; use lazy_static::lazy_static; use log::info; use crate::fd_impl_seekable; use crate::fs::*; use crate::task::*; use crate::types::*; lazy_static! { static ref VME...
s, buffer) = match self.node { RemoteNode::File(ref n) => { n.get_buffer(prot.bits(), zx::Time::INFINITE).map_err(fidl_error) } _ => Err(ENODEV), }?; zx::Status::ok(status).map_err(fio_error)?; let mut vmo = buffer.unwrap().vmo; if has_...
.expect("couldn't connect to fuchsia.kernel.VmexResource"); let service = fkernel::VmexResourceSynchronousProxy::new(client_end); service.get(zx::Time::INFINITE).expect("couldn't talk to fuchsia.kernel.VmexResource") }; } pub struct RemoteFile { node: RemoteNode, } enum RemoteNode { ...
random
[]
Rust
policy-test/tests/e2e_authorization_policy.rs
giantswarm/linkerd2
9d868c097d6c01f63d371578b960ff5d844303cf
use linkerd_policy_controller_k8s_api::{ self as k8s, policy::{LocalTargetRef, NamespacedTargetRef}, }; use linkerd_policy_test::{create, create_ready_pod, curl, nginx, with_temp_ns, LinkerdInject}; #[tokio::test(flavor = "current_thread")] async fn meshtls() { with_temp_ns(|client, ns| async move { ...
use linkerd_policy_controller_k8s_api::{ self as k8s, policy::{LocalTargetRef, NamespacedTargetRef}, }; use linkerd_policy_test::{create, create_ready_pod, curl, nginx, with_temp_ns, LinkerdInject}; #[tokio::test(flavor = "current_thread")] async fn meshtls() { with_temp_ns(|client, ns| async move { ...
fn all_authenticated(ns: &str) -> k8s::policy::MeshTLSAuthentication { k8s::policy::MeshTLSAuthentication { metadata: k8s::ObjectMeta { namespace: Some(ns.to_string()), name: Some("all-authenticated".to_string()), ..Default::default() }, spec: k8s::polic...
fn authz_policy( ns: &str, name: &str, target: LocalTargetRef, authns: impl IntoIterator<Item = NamespacedTargetRef>, ) -> k8s::policy::AuthorizationPolicy { k8s::policy::AuthorizationPolicy { metadata: k8s::ObjectMeta { namespace: Some(ns.to_string()), name: Some(nam...
function_block-full_function
[ { "content": "pub fn pod(ns: &str) -> k8s::Pod {\n\n k8s::Pod {\n\n metadata: k8s::ObjectMeta {\n\n namespace: Some(ns.to_string()),\n\n name: Some(\"nginx\".to_string()),\n\n annotations: Some(convert_args!(btreemap!(\n\n \"linkerd.io/inject\" => \"enab...
Rust
modules/fdb/src/ro/mod.rs
enteryournamehere/assembly_rs
dd5250abb586e135b59bf574543c386a4c89cbd9
use std::{ops::Deref, sync::Arc}; use assembly_core::buffer::{CastError, MinimallyAligned, Repr}; use self::buffer::Buffer; use super::file::ArrayHeader; pub mod buffer; pub mod handle; pub mod slice; pub type ArcHandle<B, T> = BaseHandle<Arc<B>, T>; impl<B: AsRef<[u8]>> ArcHandle<B, ()> { pub fn new_a...
use std::{ops::Deref, sync::Arc}; use assembly_core::buffer::{CastError, MinimallyAligned, Repr}; use self::buffer::Buffer; use super::file::ArrayHeader; pub mod buffer; pub mod handle; pub mod slice; pub type ArcHandle<B, T> = BaseHandle<Arc<B>, T>; impl<B: AsRef<[u8]>> ArcHandle<B, ()> { pub fn new_a...
} #[derive(Clone, Debug)] pub struct BaseHandle<P: Deref, T> where <P as Deref>::Target: AsRef<[u8]>, { pub(super) mem: P, pub(super) raw: T, } impl<P, T> Copy for BaseHandle<P, T> where P: Deref + Copy, T: Copy, <P as Deref>::Target: AsRef<[u8]>, { } impl<P: Deref> BaseHandle<P, (...
n as_bytes_handle(&self) -> Handle<T> { BaseHandle { mem: Buffer::new(self.mem.as_ref().as_ref()), raw: self.raw, } }
function_block-function_prefixed
[ { "content": "/// Expect an opening tag `<{key}>`\n\npub fn expect_elem<B: BufRead>(\n\n xml: &mut Reader<B>,\n\n buf: &mut Vec<u8>,\n\n key: &'static str,\n\n) -> Result<()> {\n\n if let Event::Start(start) = xml.read_event(buf)? {\n\n if start.name() == key.as_bytes() {\n\n buf.c...
Rust
src/main.rs
cspital/lsplit
dcab20d5aef4ff8ec4a35e57e28adbc18d3240b7
extern crate clap; use clap::{App, Arg, ArgMatches}; use std::env; use std::error; use std::error::Error; use std::fmt; use std::fs; use std::fs::File; use std::io; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::PathBuf; use std::str::FromStr; use std::sync::mpsc::{channel, Receiver, RecvError, Sen...
extern crate clap; use clap::{App, Arg, ArgMatches}; use std::env; use std::error; use std::error::Error; use std::fmt; use std::fs; use std::fs::File; use std::io; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::path::PathBuf; use std::str::FromStr; use std::sync::mpsc::{channel, Receiver, RecvError, Sen...
} fn new_writer(file_num: i32, splitter: &Splitter) -> Result<BufWriter<File>, SplitterError> { if let Some(new_path) = derive_new_path(file_num, splitter) { let new_file = File::create(new_path)?; return Ok(BufWriter::new(new_file)); } Err(SplitterError::Temp("Invalid filename.".to_string...
fn stream(&self, receiver: Receiver<Line>) -> SplitterResult { if let Ok(mut line) = receiver.recv() { let mut progress = 0; let mut file_num = 1; fs::create_dir_all(&self.splitter.write_dir)?; let mut writer = new_writer(file_num, self.splitter)?; whi...
function_block-full_function
[ { "content": "Split a file into byte sized chunks by line.\n\n\n", "file_path": "README.md", "rank": 24, "score": 11.377523898280417 } ]
Rust
clef/src/math/fraction.rs
dukguru/clef
edd54db5cd36ce41218453cd6c4d13e08da76310
use crate::math; use contracts::requires; use std::cmp::Ordering; use std::fmt; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}; #[derive(Clone, Copy, Debug, Eq, Ord)] pub struct Fraction { numerator: i32, denominator: i32, } impl Fraction { pub const ZERO: Fraction = F...
use crate::math; use contracts::requires; use std::cmp::Ordering; use std::fmt; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}; #[derive(Clone, Copy, Debug, Eq, Ord)] pub struct Fraction { numerator: i32, denominator: i32, } impl Fraction { pub const ZERO: Fraction = F...
}
2)); assert_eq!(-Fraction::new(5, -10), Fraction::new(1, 2)); assert_eq!(-Fraction::new(-5, -10), Fraction::new(-1, 2)); }
function_block-function_prefixed
[ { "content": "pub fn gcd(a: i32, b: i32) -> i32 {\n\n let mut a = a.abs();\n\n let mut b = b.abs();\n\n\n\n while a != 0 && b != 0 {\n\n if a > b {\n\n a %= b;\n\n } else {\n\n b %= a;\n\n }\n\n }\n\n\n\n cmp::max(a, b)\n\n}\n\n\n", "file_path": "cle...
Rust
src/arena.rs
scottjmaddox/rust-memory-arena
66dfdf6a683cd2d0066ab1742100ade8256d3a7b
use core::cell::Cell; use arena_box::ArenaBox; pub struct Arena { size: usize, used: Cell<usize>, mem: *mut u8, } impl Arena { pub fn new(size: usize, alignment: usize) -> Result<Self, ::alloc::AllocError> { if size == 0 { Ok(Self { size: size, use...
use core::cell::Cell; use arena_box::ArenaBox; pub struct Arena { size: usize, used: Cell<usize>, mem: *mut u8, } impl Arena { pub fn new(size: usize, alignment: usize) -> Result<Self, ::alloc::AllocError> { if size == 0 { Ok(Self { size: size, use...
fn alloc<T>(&self) -> Option<*mut T> { let size = ::core::mem::size_of::<T>(); if size == 0 { return Some(::core::mem::align_of::<T>() as *mut T); } let alignment = ::core::mem::align_of::<T>(); match self.aligned_alloc(size, alignment) { None => Non...
assert!(alignment.count_ones() == 1); let unaligned_p = self.mem as usize + self.used.get(); let aligned_p = (unaligned_p + alignment - 1) & !(alignment - 1); let offset = aligned_p - unaligned_p; if self.used.get() + size + offset > self.size { return None; } ...
function_block-function_prefix_line
[ { "content": "/// Types that can be \"unsized\" to a dynamically-sized type.\n\n///\n\n/// For example, the sized array type `[i8; 2]` implements `Unsize<[i8]>` and\n\n/// `Unsize<fmt::Debug>`.\n\n///\n\n/// All implementations of `Unsize` are provided automatically by the compiler.\n\n///\n\n/// `Unsize` is im...
Rust
src/bin/server.rs
srgsrg/machiavelli
ebbaae04e4867a123c652f5cad6292a176034a06
use std::process; use std::fs::File; use std::thread; use std::env; use rand::{ thread_rng, Rng }; use machiavelli::lib_server::*; const SAVE_EXTENSION: &str = ".sav"; fn get_port() -> usize { println!("Which port should I use?"); loop { match get_input() { Ok(s) => match s.trim().parse:...
use std::process; use std::fs::File; use std::thread; use std::env; use rand::{ thread_rng, Rng }; use machiavelli::lib_server::*; const SAVE_EXTENSION: &str = ".sav"; fn get_port() -> usize { println!("Which port should I use?"); loop { match get_input() { Ok(s) => match s.trim().parse:...
let mut savefile = "machiavelli_save".to_string(); if !load { match get_config_from_file(&"Config/config.dat") { Ok(conf) => { config = conf.0; savefile = conf.1; }, Err(_) => { println!("Could not read...
let mut config = Config { n_decks: 0, n_jokers: 0, n_cards_to_start: 0, custom_rule_jokers: false, n_players: 0 };
assignment_statement
[ { "content": "/// wait for a player to reconnect\n\npub fn wait_for_reconnection(stream: &mut TcpStream, name: &str, port: usize) \n\n -> Result<(), StreamError>\n\n{\n\n\n\n // wait for a connection\n\n\n\n // set-up the tcp listener\n\n let listener = TcpListener::bind(format!(\"0.0.0.0:{}\", port...
Rust
src/lib.rs
tstellanova/ist8310
851f9767759073520eb538fe6987e51c12b53c1b
/* Copyright (c) 2020 Todd Stellanova LICENSE: BSD3 (see LICENSE file) */ #![no_std] use embedded_hal as hal; use hal::blocking::delay::DelayMs; #[derive(Debug)] pub enum Error<CommE> { Comm(CommE), OutOfRange, Configuration, UnknownChipId, } pub const ADDR_0_0_7BIT:u8 = 0x0C;...
/* Copyright (c) 2020 Todd Stellanova LICENSE: BSD3 (see LICENSE file) */ #![no_std] use embedded_hal as hal; use hal::blocking::delay::DelayMs; #[derive(Debug)] pub enum Error<CommE> { Comm(CommE), OutOfRange, Configuration, UnknownChipId, } pub const ADDR_0_0_7BIT:u8 = 0x0C;...
}
pub fn get_mag_vector(&mut self, delay_source: &mut impl DelayMs<u8>) -> Result<[i16; 3], Error<CommE>> { const SINGLE_MEASURE_MODE: u8 = 0x01; const XYZ_DATA_LEN: usize = 6; self.write_reg(REG_CTRL1, SINGLE_MEASURE_MODE)?; delay_source.delay_ms(6); s...
function_block-full_function
[ { "content": "#[test]\n\nfn test_init() {\n\n const SRST_POR_FLAG: u8 = 0x01 << 0;\n\n const SRPD_MODE_LOW_POWER: u8 = 0xC0;\n\n const AVG_CTRL_16X: u8 = 0x24;\n\n\n\n let addr = ist8310::DEFAULT_ADDRESS;\n\n\n\n // Configure expectations\n\n let expectations = [\n\n I2cTransaction::wri...
Rust
src/server/rpc/client.rs
gavento/rain
9372c66d82180ecae12af065a81631565c0d40dc
use capnp::capability::Promise; use std::net::SocketAddr; use futures::{future, Future}; use common::resources::Resources; use common::id::{DataObjectId, SId, TaskId}; use common::convert::{FromCapnp, ToCapnp}; use client_capnp::client_service; use server::state::StateRef; use server::graph::{ClientRef, DataObjectRef,...
use capnp::capability::Promise; use std::net::SocketAddr; use futures::{future, Future}; use common::resources::Resources; use common::id::{DataObjectId, SId, TaskId}; use common::convert::{FromCapnp, ToCapnp}; use client_capnp::client_service; use server::state::StateRef; use server::graph::{ClientRef, DataObjectRef,...
} impl client_service::Server for ClientServiceImpl { fn get_server_info( &mut self, _: client_service::GetServerInfoParams, mut results: client_service::GetServerInfoResults, ) -> Promise<(), ::capnp::Error> { debug!("Client asked for info"); let s = self.state.get(); ...
fn drop(&mut self) { let mut s = self.state.get_mut(); info!("Client {} disconnected", self.client.get_id()); s.remove_client(&self.client) .expect("client connection drop"); }
function_block-function_prefixed
[ { "content": "pub fn task_run(state: &mut State, task_ref: TaskRef) -> TaskResult {\n\n let state_ref = state.self_ref();\n\n let config: RunConfig = task_ref.get().attributes.get(\"config\")?;\n\n\n\n let (dir, future, stderr_path) = {\n\n // Parse arguments\n\n let name = config.args.ge...
Rust
src/hierarchies.rs
esrlabs/cgroups-rs
556dea62b963fb75c3b1234f9cab6164706fc594
use std::fs; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use crate::blkio::BlkIoController; use crate::cpu::CpuController; use crate::cpuacct::CpuAcctController; use crate::cpuset::CpuSetController; use crate::devices::DevicesController; use crate::freezer::FreezerController; use cr...
use std::fs; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use crate::blkio::BlkIoController; use crate::cpu::CpuController; use crate::cpuacct::CpuAcctController; use crate::cpuset::CpuSetController; use crate::devices::DevicesController; use crate::freezer::FreezerController; use cr...
pub fn auto() -> Box<dyn Hierarchy> { if is_cgroup2_unified_mode() { Box::new(V2::new()) } else { Box::new(V1::new()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_mount() { let mountinfo = vec![ ("29 26 0:26 / /sys/fs/cgroup/cpuset,cpu,...
pub fn is_cgroup2_unified_mode() -> bool { let lines = fs::read_to_string(INIT_CGROUP_PATHS); if lines.is_err() { return false; } for line in lines.unwrap().lines() { let fields: Vec<&str> = line.split(':').collect(); if fields.len() != 3 { continue; } ...
function_block-full_function
[]
Rust
stake-pool/program/tests/set_fee.rs
honeydefi/NFT-farm
dc97a5439c6ab85e7b0ed4c86f3f5c6939d07c99
#![cfg(feature = "test-bpf")] mod helpers; use { helpers::*, solana_program_test::*, solana_sdk::{ borsh::try_from_slice_unchecked, instruction::InstructionError, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, }, spl_stake_p...
#![cfg(feature = "test-bpf")] mod helpers; use { helpers::*, solana_program_test::*, solana_sdk::{ borsh::try_from_slice_unchecked, instruction::InstructionError, signature::{Keypair, Signer}, transaction::{Transaction, TransactionError}, }, spl_stake_p...
#[tokio::test] async fn fail_high_fee() { let (mut context, stake_pool_accounts, _new_fee) = setup().await; let new_fee = Fee { numerator: 11, denominator: 10, }; let transaction = Transaction::new_signed_with_payer( &[instruction::set_fee( &id(), ...
unts, new_fee) = setup().await; let wrong_manager = Keypair::new(); let transaction = Transaction::new_signed_with_payer( &[instruction::set_fee( &id(), &stake_pool_accounts.stake_pool.pubkey(), &wrong_manager.pubkey(), FeeType::Epoch(new_fee), ...
function_block-function_prefixed
[ { "content": "fn validate_fraction(numerator: u64, denominator: u64) -> Result<(), SwapError> {\n\n if denominator == 0 && numerator == 0 {\n\n Ok(())\n\n } else if numerator >= denominator {\n\n Err(SwapError::InvalidFee)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Fees {\n\...
Rust
samples/d3d12-hello-world/d3d12-hello-window/src/main.rs
damyanp/directx-graphics-samples-rs
d1b04382984b3ad1facf5f52ffd7901cc6d00488
use d3dx12::*; use dxsample::*; use windows::{ core::*, Win32::{ Foundation::*, Graphics::{Direct3D12::*, Dxgi::Common::*, Dxgi::*}, }, }; mod d3d12_hello_window { use std::convert::TryInto; use super::*; const FRAME_COUNT: usize = 2; pub struct Sample { dxgi_fact...
use d3dx12::*; use dxsample::*; use windows::{ core::*, Win32::{ Foundation::*, Graphics::{Direct3D12::*, Dxgi::Common::*, Dxgi::*}, }, }; mod d3d12_hello_wi
}); Ok(()) } fn title(&self) -> String { "D3D12 Hello Window".into() } fn window_size(&self) -> (i32, i32) { (1280, 720) } fn render(&mut self) { let resources = match &mut self.resources { Some(i...
ndow { use std::convert::TryInto; use super::*; const FRAME_COUNT: usize = 2; pub struct Sample { dxgi_factory: IDXGIFactory4, device: ID3D12Device, resources: Option<Resources>, } struct Resources { command_queue: SynchronizedCommandQueue, swap_chain:...
random
[ { "content": "use windows::Win32::Graphics::{Direct3D12::*, Dxgi::Common::*};\n\n\n\nmod descriptor_heaps;\n\npub use descriptor_heaps::*;\n\n\n\nmod pipeline_states;\n\npub use pipeline_states::*;\n\n\n\npub mod build;\n\n\n", "file_path": "d3dx12/src/lib.rs", "rank": 0, "score": 34164.99046050119 ...
Rust
src/device/vga/crt.rs
shift-crops/x64emu
18f661a9a64bfbfce76c15dc7039abee73e4e128
use packed_struct::prelude::*; #[derive(Debug, Default)] pub(super) struct CRT { pub ccir: CRTCtrlIndex, htr: u8, pub hdeer: u8, hbsr: u8, hber: HorBlnkEnd, hssr: u8, hser: HorSyncEnd, vtr: u8, ofr: Overflow, prsr: PresetRowScan, mslr: MaxScanLine, tcsr: Te...
use packed_struct::prelude::*; #[derive(Debug, Default)] pub(super) struct CRT { pub ccir: CRTCtrlIndex, htr: u8, pub hdeer: u8, hbsr: u8, hber: HorBlnkEnd, hssr: u8, hser: HorSyncEnd, vtr: u8, ofr: Overflow, prsr: PresetRowScan, mslr: MaxScanLine, tcsr: Te...
: u8, } #[derive(Debug, Default, PackedStruct)] #[packed_struct(bit_numbering="lsb0", size_bytes="1")] pub struct UnderLocate { #[packed_field(bits="0:4")] location: u8, #[packed_field(bits="5")] count: u8, #[packed_field(bits="6")] dword: u8, } #[derive(Debug, Default, PackedStruct)] #[packed_s...
u8, #[packed_field(bits="7")] dbl_scan: u8, } #[derive(Debug, Default, PackedStruct)] #[packed_struct(bit_numbering="lsb0", size_bytes="1")] pub struct TextCurStart { #[packed_field(bits="0:4")] cur_srt: u8, #[packed_field(bits="5")] cur_off: bool, } #[derive(Debug, Default, PackedStruct)] #[packed_...
random
[ { "content": "pub fn wait_for_tcp(port: u16) -> DynResult<TcpStream> {\n\n let sockaddr = format!(\"127.0.0.1:{}\", port);\n\n eprintln!(\"Waiting for a GDB connection on {:?}...\", sockaddr);\n\n\n\n let sock = TcpListener::bind(sockaddr)?;\n\n let (stream, addr) = sock.accept()?;\n\n eprintln!(...
Rust
src/photosdir.rs
kaj/rphotos
640dc328eb6338368b66831061530d8c894722f6
use crate::models::Photo; use crate::myexif::ExifData; use image::imageops::FilterType; use image::{self, GenericImageView, ImageError, ImageFormat}; use log::{debug, info, warn}; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::{fs, io}; use tokio::task::{spawn_blocking, JoinError}; pub struct PhotosDir ...
use crate::models::Photo; use crate::myexif::ExifData; use image::imageops::FilterType; use image::{self, GenericImageView, ImageError, ImageFormat}; use log::{debug, info, warn}; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::{fs, io}; use tokio::task::{spawn_blocking, JoinError}; pub struct PhotosDir ...
} fn load_meta(path: &Path) -> Option<ExifData> { if let Ok(mut exif) = ExifData::read_from(&path) { if exif.width.is_none() || exif.height.is_none() { if let Ok((width, height)) = actual_image_size(&path) { exif.width = Some(width); exif.height = Some(height); ...
lt<&'a str, io::Error> { let path = fullpath .strip_prefix(&self.basedir) .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; path.to_str().ok_or_else(|| { io::Error::new( io::ErrorKind::InvalidInput, format!("Non-utf8 path {...
function_block-function_prefixed
[ { "content": "pub fn to_dir(dir: &str) -> Result<(), Error> {\n\n let dir: &Path = dir.as_ref();\n\n for s in STATICS {\n\n // s.name may contain directory components.\n\n if let Some(parent) = dir.join(s.name).parent() {\n\n create_dir_all(parent)?;\n\n }\n\n File::...
Rust
src/main.rs
Masorubka1/rs_graph_system
ac51d9ccdbd7f60996804287e527d9633fa5d4e9
use std::collections::HashSet; use std::thread::sleep_ms; use std::collections::HashMap; use rs_graph_system::ThreadPool; use petgraph::Graph; use petgraph::adj::NodeIndex; use petgraph::adj::IndexType; use std::collections::VecDeque; #[derive(Copy, Clone)] pub struct Xz { Xz: usize } impl Xz { fn new(num: us...
use std::collections::HashSet; use std::thread::sleep_ms; use std::collections::HashMap; use rs_graph_system::ThreadPool; use petgraph::Graph; use petgraph::adj::NodeIndex; use petgraph::adj::IndexType; use std::collections::VecDeque; #[derive(Copy, Clone)] pub struct Xz { Xz: usize } impl Xz { fn new(num: us...
); let third = InfoNode::new(do_smth_2, third_h); let fourth = InfoNode::new(do_smth_2, fourth_h); let thith = InfoNode::new(do_smth_2, thith_h); let arr = vec![first, second, third, fourth, thith]; let mut list_nodes = HashMap::<usize, NodeIndex>::new(); let mut tmp_cnt = 0; for i in ...
{ let mut first_h = HashMap::new(); first_h.insert("name", 1); let mut second_h = HashMap::new(); second_h.insert("name", 2); let mut third_h = HashMap::new(); third_h.insert("name", 3); let mut fourth_h = HashMap::new(); fourth_h.insert("name", 4); let mut thith_h = HashMap::new(); ...
random
[ { "content": "struct Worker {\n\n id: usize,\n\n thread: Option<thread::JoinHandle<()>>,\n\n}\n\n\n\nimpl Worker {\n\n fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker {\n\n let thread = thread::spawn(move || loop {\n\n let message = receiver.lock().unwrap()....
Rust
src/colln_paint/mod.rs
pwil3058/rs_epaint
abde42728f65fc166df6416df8b3c3067faf51ed
use std::cell::RefCell; use std::cmp::Ordering; use std::fmt; use std::fmt::Debug; use std::fs::File; use std::hash::*; use std::io::Read; use std::marker::PhantomData; use std::path::Path; use std::rc::Rc; use std::str::FromStr; use pw_gix::{ gtk::{self, prelude::*}, wrapper::*, }; pub mod binder; pub mod ...
use std::cell::RefCell; use std::cmp::Ordering; use std::fmt; use std::fmt::Debug; use std::fs::File; use std::hash::*; use std::io::Read; use std::marker::PhantomData; use std::path::Path; use std::rc::Rc; use std::str::FromStr; use pw_gix::{ gtk::{self, prelude::*}, wrapper::*, }; pub mod binder; pub mod ...
} impl<C, CID> fmt::Display for PaintCollnSpec<C, CID> where C: CharacteristicsInterface, CID: CollnIdInterface, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{} {}\n", CID::colln_name_label(), self.colln_id.colln_name() ...
if colln_name.len() == 0 || colln_owner.len() == 0 { return Err(PaintErrorType::MalformedText(string.to_string()).into()); }; let colln_id = Rc::new(CID::new(colln_name, colln_owner)); let mut paint_specs: Vec<BasicPaintSpec<C>> = Vec::new(); for line in lines { l...
function_block-function_prefix_line
[ { "content": "pub trait BasicPaintInterface<C>: Clone + PartialEq + Ord + Debug + ColouredItemInterface\n\nwhere\n\n C: CharacteristicsInterface,\n\n{\n\n fn name(&self) -> String;\n\n fn notes(&self) -> String;\n\n fn tooltip_text(&self) -> String;\n\n fn characteristics(&self) -> C;\n\n\n\n ...
Rust
rounded-svg/src/main.rs
Ar37-rs/demos
b77283496f4076863cc16c059f1e1721932d3ea1
use fltk::{enums::*, prelude::*, *}; use std::cell::RefCell; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use svg::node::element::Rectangle; use svg::Document; struct RoundedImageDisplay { frame_: frame::Frame, bordercolor_: Rc<RefCell<[u8; 3]>>, radius_: Rc<RefCell<i32>>, } impl RoundedImageDis...
use fltk::{enums::*, prelude::*, *}; use std::cell::RefCell; use std::ops::{Deref, DerefMut}; use std::rc::Rc; use svg::node::element::Rectangle; use svg::Document; struct RoundedImageDisplay { frame_: frame::Frame, bordercolor_: Rc<RefCell<[u8; 3]>>, radius_: Rc<RefCell<i32>>, } impl RoundedImageDis...
1.5) as u8, (border[2] as f64 / 1.5) as u8, )); slider.set_callback(move |s| { rimage.radius(s.value() as i32); }); win.end(); win.show(); a.run().unwrap(); }
function_block-function_prefixed
[ { "content": "pub fn get_proc_address(win: &window::GlWindow, name: &str) -> *mut c_void {\n\n win.get_proc_address(name) as _\n\n}\n\n\n", "file_path": "libmpv/src/main.rs", "rank": 0, "score": 225561.0756709798 }, { "content": "// draw header with day names\n\nfn draw_header(txt: &str, ...
Rust
build/sdk/meta/src/product_bundle_container.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { crate::{ common::{ElementType, Envelope}, json::{schema, JsonObject}, metadata::Metadata, ProductBundleV1, }, serde::{Deserialize, Serialize}, }; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct WorkaroundProductBund...
use { crate::{ common::{ElementType, Envelope}, json::{schema, JsonObject}, metadata::Metadata, ProductBundleV1, }, serde::{Deserialize, Serialize}, }; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct WorkaroundProductBund...
opment/0.20201216.2.1/packages/generic-x64.tar.gz" }] }, "schema_id": "product_bundle-6320eef1.json#/definitions/product_bundle" } ] } } "#, valid = true, } test_v...
#[serde(rename = "type")] pub kind: ElementType, pub bundles: Vec<WorkaroundProductBundleWrapper>, } impl JsonObject for Envelope<ProductBundleContainerV1> { fn get_schema() -> &'static str { include_str!("../product_bundle_container-76a5c104.json") } fn get_referenced_schemat...
random
[]
Rust
src/lib.rs
Uriopass/inline_tweak
8ef340ea259854e21edfe2374c1237d1bf07a5e5
pub trait Tweakable: Sized { fn parse(x: &str) -> Option<Self>; } #[cfg(any(debug_assertions, feature = "release_tweak"))] mod itweak { use super::Tweakable; use lazy_static::*; use std::any::Any; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{BufRead, BufReade...
pub trait Tweakable: Sized { fn parse(x: &str) -> Option<Self>; } #[cfg(any(debug_assertions, feature = "release_tweak"))] mod itweak { use super::Tweakable; use lazy_static::*; use std::any::Any; use std::collections::{HashMap, HashSet}; use std::fs::File; use std::io::{BufRead, BufReade...
{ let mut tweaks_seen = 0; let line_str = BufReader::new(&file) .lines() .filter_map(|line| line.ok()) .find(|line| { tweaks_seen += line.matches("tweak!(").count(); tweaks_seen > tweak.position ...
tweaks_seen += 1; } } fileinfos.insert(fpath); } Some(()) } fn update_tweak<T: 'static + Tweakable + Clone + Send>( tweak: &mut TweakValue, fpath: &'static str, ) -> Option<()> { let file = try_open(fpath).ok()?; let ...
random
[ { "content": "fn do_fn(item: TokenStream, release_tweak: bool) -> TokenStream {\n\n let mut v: syn::ItemFn = parse_macro_input!(item as syn::ItemFn);\n\n\n\n let fname = v.sig.ident.clone();\n\n\n\n LiteralReplacer {\n\n nth: 0,\n\n fname,\n\n release_tweak,\n\n }\n\n .visit_...
Rust
contract/ft-transfer-receiver-mock/src/lib.rs
evgenykuzyakov/oysterpack-near-stake-token
86a01e80f57780fa755bbc09e55b91714c0751d4
use near_sdk::serde::export::TryFrom; use near_sdk::{ borsh::{self, BorshDeserialize, BorshSerialize}, env, json_types::{ValidAccountId, U128}, log, near_bindgen, serde::{Deserialize, Serialize}, serde_json::{self, json}, wee_alloc, AccountId, Promise, PromiseOrValue, }; use std::{ cmp::...
use near_sdk::serde::export::TryFrom; use near_sdk::{ borsh::{self, BorshDeserialize, BorshSerialize}, env, json_types::{ValidAccountId, U128}, log, near_bindgen, serde::{Deserialize, Serialize}, serde_json::{self, json}, wee_alloc, AccountId, Promise, PromiseOrValue, }; use std::{ cmp::...
refund_percent, transfer_relay, } => { println!( "refund_percent={}% transfer_relay={:?}", refund_percent, transfer_relay ) } Message::Panic => panic!("expected Accept message type"), ...
"refund_percent": 0, "transfer_relay": {"account_id": "account.near", "percent": 50} } }); let json = serde_json::to_string(&json).unwrap(); println!("{}", json); let msg: Message = serde_json::from_str(&json).unwrap(); match msg { Me...
random
[ { "content": "pub fn deserialize_receipts() -> Vec<Receipt> {\n\n get_created_receipts()\n\n .iter()\n\n .map(|receipt| {\n\n let json = serde_json::to_string_pretty(receipt).unwrap();\n\n println!(\"{}\", json);\n\n let receipt: Receipt = serde_json::from_str(&...
Rust
src/articles/library.rs
tiagoamaro/pickpocket-rust
fc95d1152da1e6526e4d357896a323b3294293d8
use crate::articles::api::API; use crate::articles::article::Article; use crate::articles::inventory::Inventory; use crate::configuration::Configuration; use crate::logger; use rand::seq::SliceRandom; use serde::{Deserialize, Serialize}; use serde_yaml; use std::collections::HashMap; use std::fs::File; use std::path::P...
use crate::articles::api::API; use crate::articles::article::Article; use crate::articles::inventory::Inventory; use crate::configuration::Configuration; use crate::logger; use rand::seq::SliceRandom; use serde::{Deserialize, Serialize}; use serde_yaml; use std::collections::HashMap; use std::fs::File; use std::path::P...
pub fn status() { let library = Library::load(); logger::log(&format!( "You have {} read articles", &library.read.articles.len() )); logger::log(&format!( "You have {} unread articles", &library.unread.articles.len() )); ...
fn move_to_read(article_id: String) { let mut library = Library::load(); match library.unread.articles.remove(&article_id) { Some(read_article) => { library .read .articles .insert(read_article.id.to_owned(), read_a...
function_block-full_function
[ { "content": "pub fn log(message: &str) -> &str {\n\n println!(\"[Pickpocket] {}\", message);\n\n message\n\n}\n", "file_path": "src/logger.rs", "rank": 0, "score": 50771.27213072561 }, { "content": "use crate::articles::article::Article;\n\nuse serde::{Deserialize, Serialize};\n\nuse ...
Rust
src/event.rs
vstojkovic/sapi-lite
202e96fd1cca47863f5eca2c9b5b82b7ea390d88
use windows as Windows; use Windows::core::{implement, IUnknown}; use Windows::Win32::Foundation::PWSTR; use Windows::Win32::Media::Speech::{ ISpEventSource, ISpNotifySink, ISpObjectToken, ISpRecoResult, SPEI_END_INPUT_STREAM, SPEI_RECOGNITION, SPEI_RESERVED1, SPEI_RESERVED2, SPET_LPARAM_IS_OBJECT, SPET_LPA...
use windows as Windows; use Windows::core::{implement, IUnknown}; use Windows::Win32::Fo
{ source, handler: Box::new(handler), } } pub(crate) fn install(self, interest: Option<&[SPEVENTENUM]>) -> Result<()> { use windows::core::ToImpl; let src_intf = self.source.intf.clone(); let sink_intf: ISpNotifySink = self.into(); unsafe { src_...
undation::PWSTR; use Windows::Win32::Media::Speech::{ ISpEventSource, ISpNotifySink, ISpObjectToken, ISpRecoResult, SPEI_END_INPUT_STREAM, SPEI_RECOGNITION, SPEI_RESERVED1, SPEI_RESERVED2, SPET_LPARAM_IS_OBJECT, SPET_LPARAM_IS_POINTER, SPET_LPARAM_IS_STRING, SPET_LPARAM_IS_TOKEN, SPET_LPARAM_IS_UNDEFINED, ...
random
[ { "content": "use std::ops::Deref;\n\n\n\nuse windows as Windows;\n\nuse Windows::core::Interface;\n\nuse Windows::Win32::Media::Speech::{SPEI_END_INPUT_STREAM, SPF_ASYNC};\n\n\n\nuse crate::event::{Event, EventSink, EventSource};\n\nuse crate::tts::Speech;\n\nuse crate::Result;\n\n\n\nuse super::Synthesizer;\n...
Rust
src/udp_mux/mod.rs
webrtc-rs/ice
ebdf3e3b6f431f0e5e59ca0be9f61d563743fb45
use std::{collections::HashMap, io::ErrorKind, net::SocketAddr, sync::Arc}; use util::{sync::RwLock, Conn, Error}; use async_trait::async_trait; use tokio::sync::{watch, Mutex}; mod udp_mux_conn; use udp_mux_conn::{UDPMuxConn, UDPMuxConnParams}; #[cfg(test)] mod udp_mux_test; mod socket_addr_ext; use stun::{ ...
use std::{collections::HashMap, io::ErrorKind, net::SocketAddr, sync::Arc}; use util::{sync::RwLock, Conn, Error}; use async_trait::async_trait; use tokio::sync::{watch, Mutex}; mod udp_mux_conn; use udp_mux_conn::{UDPMuxConn, UDPMuxConnParams}; #[cfg(test)] mod udp_mux_test; mod socket_addr_ext; use stun::{ ...
async fn get_conn(self: Arc<Self>, ufrag: &str) -> Result<Arc<dyn Conn + Send + Sync>, Error> { if self.is_closed().await { return Err(Error::ErrUseClosedNetworkConn); } { let mut conns = self.conns.lock().await; if let Some(conn) = conns.get(ufrag) { ...
for (_, conn) in old_conns.into_iter() { conn.close(); } { let mut address_map = self.address_map.write(); let _ = std::mem::take(&mut (*address_map)); } } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn assert_inbound_message_integrity(m: &mut Message, key: &[u8]) -> Result<()> {\n\n let message_integrity_attr = MessageIntegrity(key.to_vec());\n\n Ok(message_integrity_attr.check(m)?)\n\n}\n\n\n\n/// Initiates a stun requests to `server_addr` using conn, reads the response and returns...
Rust
src/header.rs
ssands1/elf2tab
9ba7a8dd3832d4edd1e323ee62a660313ccdf8e0
use std::fmt; use std::io; use std::io::{Read, Seek, SeekFrom, Write}; use std::mem; use std::vec; use util; #[repr(u16)] #[derive(Clone, Copy, Debug)] #[allow(dead_code)] enum TbfHeaderTypes { Main = 1, WriteableFlashRegions = 2, PackageName = 3, PicOption1 = 4, } #[repr(C)] #[derive(Clone, Copy, Deb...
use std::fmt; use std::io; use std::io::{Read, Seek, SeekFrom, Write}; use std::mem; use std::vec; use util; #[repr(u16)] #[derive(Clone, Copy, Debug)] #[allow(dead_code)] enum TbfHeaderTypes { Main = 1, WriteableFlashRegions = 2, PackageName = 3, PicOption1 = 4, } #[repr(C)] #[derive(Clone, Copy, Deb...
pub fn set_protected_size(&mut self, protected_size: u32) { self.hdr_main.protected_size = protected_size; } pub fn set_total_size(&mut self, total_size: u32) { self.hdr_base.total_size = total_size; } pub fn set_init_fn_offset(&mut self, init_fn_offset: ...
header_length += mem::size_of::<TbfHeaderWriteableFlashRegion>() * writeable_flash_regions; let flags = 0x0000_0001; self.hdr_base.header_size = header_length as u16; self.hdr_base.flags = flags; self.hdr_main.minimum_ram_size = minimum_ram_size; sel...
function_block-function_prefix_line
[ { "content": "pub fn do_pad(output: &mut io::Write, length: usize) -> io::Result<()> {\n\n let mut pad = length;\n\n let zero_buf = [0_u8; 512];\n\n while pad > 0 {\n\n let amount_to_write = cmp::min(zero_buf.len(), pad);\n\n pad -= output.write(&zero_buf[..amount_to_write])?;\n\n }\n\...
Rust
src/solution/string/str_str.rs
smallswan/leetcode-rust
9b8bb3f91bec613de61f1cfdd203dd9eeda23ebe
pub fn str_str(haystack: String, needle: String) -> i32 { let source = haystack.as_bytes(); let target = needle.as_bytes(); let source_offset = 0usize; let source_count = source.len(); let target_offset = 0usize; let target_count = target.len(); let from_index = 0usize; if target...
pub fn str_str(haystack: String, needle: String) -> i32 { let source = haystack.as_bytes(); let target = needle.as_bytes(); let source_offset = 0usize; let source_count = source.len(); let target_offset = 0usize; let target_count = target.len(); let from_index = 0usize; if target...
pub fn rabin_karp(target: String, pattern: String) -> Vec<usize> { if target.is_empty() || pattern.is_empty() || pattern.len() > target.len() { return vec![]; } let string: String = (&pattern[0..pattern.len()]).to_string(); let hash_pattern = hash(string.clone()); let mut ret = vec![...
is_empty() { return vec![]; } let string = st.into_bytes(); let pattern = pat.into_bytes(); let mut partial = vec![0]; for i in 1..pattern.len() { let mut j = partial[i - 1]; while j > 0 && pattern[j] != pattern[i] { j = partial[j - 1]; } pa...
function_block-function_prefixed
[ { "content": "/// 剑指 Offer 58 - II. 左旋转字符串 https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/\n\npub fn reverse_left_words(s: String, n: i32) -> String {\n\n let mut chars: Vec<char> = s.chars().collect();\n\n chars.rotate_left(n as usize);\n\n chars.iter().collect()\n\n}\n\n\n\nuse std:...
Rust
src/enclave_proc/socket.rs
bercarug/aws-nitro-enclaves-cli-1
ab4e03bc37fc7fcf6f98c42d416612976299989a
#![deny(missing_docs)] #![deny(warnings)] use inotify::{EventMask, Inotify, WatchMask}; use log::{debug, warn}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread::{self, JoinHandle}; use crate::common::get_socket_path; use crate::common::{ExitGraceful...
#![deny(missing_docs)] #![deny(warnings)] use inotify::{EventMask, Inotify, WatchMask}; use log::{debug, warn}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread::{self, JoinHandle}; use crate::common::get_socket_path; use crate::common::{ExitGraceful...
#[cfg(test)] mod tests { use super::*; use std::os::unix::net::UnixListener; use std::process::Command; const DUMMY_ENCLAVE_ID: &str = "i-0000000000000000-enc0123456789012345"; const THREADS_STR: &str = "Threads:"; const WAIT_REMOVE_MILLIS: u64 = 10; fn get_num_threads_fr...
fn socket_removal_listener( socket_path: PathBuf, requested_remove: Arc<AtomicBool>, mut socket_inotify: Inotify, exit_on_delete: bool, ) { let mut buffer = [0u8; 4096]; let mut done = false; debug!("Socket file event listener started for {:?}.", socket_path); while !done { ...
function_block-full_function
[ { "content": "/// Get the path to the Unix socket owned by an enclave process which also owns the enclave with the given ID.\n\npub fn get_socket_path(enclave_id: &str) -> NitroCliResult<PathBuf> {\n\n // The full enclave ID is \"i-(...)-enc<enc_id>\" and we want to extract only <enc_id>.\n\n let tokens: ...
Rust
src/component/sum_of_best.rs
AntyMew/livesplit-core
b59a45ddd85c914121d279df38ad5b0e581bd512
use Timer; use time::formatter::{Accuracy, Regular, TimeFormatter}; use serde_json::{to_writer, Result}; use analysis::sum_of_segments::calculate_best; use std::io::Write; use std::borrow::Cow; use settings::{Color, Field, Gradient, SettingsDescription, Value}; use super::DEFAULT_INFO_TEXT_GRADIENT; #[derive(Default...
use Timer; use time::formatter::{Accuracy, Regular, TimeFormatter}; use serde_json::{to_writer, Result}; use analysis::sum_of_segments::calculate_best; use std::io::Write; use std::borrow::Cow; use settings::{Color, Field, Gradient, SettingsDescription, Value}; use super::DEFAULT_INFO_TEXT_GRADIENT; #[derive(Default...
; State { background: self.settings.background, label_color: self.settings.label_color, value_color: self.settings.value_color, text: String::from("Sum of Best Segments"), time: Regular::with_accuracy(self.settings.accuracy) .format(ti...
calculate_best( timer.run().segments(), false, true, timer.current_timing_method(), )
call_expression
[ { "content": "pub fn write<W: Write>(mut writer: W, classes: &BTreeMap<String, Class>) -> Result<()> {\n\n write!(\n\n writer,\n\n \"{}\",\n\n r#\"#ifndef LIVESPLIT_CORE_H\n\n#define LIVESPLIT_CORE_H\n\n\n\n#ifdef __cplusplus\n\n#define restrict __restrict\n\nnamespace LiveSplit {\n\next...
Rust
weight-gen/src/main.rs
ImbueNetwork/open-runtime-module-library
c439a50e01944aedeef33231e0824a17ed1813bc
use clap::{App, Arg}; use serde::{Deserialize, Serialize}; use std::io::Read; #[derive(Serialize, Deserialize, Default, Debug, Clone)] pub struct BenchData { pub name: String, pub weight: u64, pub reads: u32, pub writes: u32, pub comments: Vec<String>, } #[derive(Serialize, Default, Debug, Clone)] struct Templat...
use clap::{App, Arg}; use serde::{Deserialize, Serialize}; use std::io::Read; #[derive(Serialize, Deserialize, Default, Debug, Clone)] pub struct BenchData { pub name: String, pub weight: u64, pub reads: u32, pub writes: u32, pub comments: Vec<String>, } #[derive(Serialize, Default, Debug, Clone)] struct Templat...
} fn parse_stdio() -> Option<Vec<BenchData>> { let mut buffer = String::new(); std::io::stdin() .read_to_string(&mut buffer) .expect("Unable to read from stdin"); let file_path = buffer .split_ascii_whitespace() .last() .expect("Last line must be JOSN file path."); let reader = std::fs::File::open(std:...
fn call<'reg: 'rc, 'rc>( &self, h: &handlebars::Helper, _: &handlebars::Handlebars, _: &handlebars::Context, _rc: &mut handlebars::RenderContext, out: &mut dyn handlebars::Output, ) -> handlebars::HelperResult { use handlebars::JsonRender; let param = h.param(0).expect("Unable to retrieve param from ha...
function_block-full_function
[ { "content": "/// Increment used weight\n\npub fn using(weight: Weight) {\n\n\tMETER.with(|v| {\n\n\t\tlet mut meter = v.borrow_mut();\n\n\t\tmeter.used_weight = meter.used_weight.saturating_add(weight);\n\n\t})\n\n}\n\n\n", "file_path": "weight-meter/src/meter_std.rs", "rank": 0, "score": 271039.88...
Rust
src/lib.rs
kneasle/goldilocks-json-fmt
41a84437e933c67365e874b73405d4d1fc935849
/*! [![crates.io](https://img.shields.io/crates/v/goldilocks-json-fmt.svg)](https://crates.io/crates/goldilocks-json-fmt) A simple, portable, fast, pretty JSON formatter. No dependencies or unsafe code. The resulting JSON strikes a balance between 'too wide' (i.e. minified, all on one line) and 'too tall' (e.g. `ser...
/*! [![crates.io](https://img.shields.io/crates/v/goldilocks-json-fmt.svg)](https://crates.io/crates/goldilocks-json-fmt) A simple, portable, fast, pretty JSON formatter. No dependencies or unsafe code. The resulting JSON strikes a balance between 'too wide' (i.e. minified, all on one line) and 'too tall' (e.g. `ser...
py, PartialEq, Eq)] pub enum Expected { Key, Value, Char(char), Digit, } impl Error { fn expected_xs_found( item: Item, expected: &'static [Expected], v: Option<(usize, char)>, ) -> Self { match v { Some((idx, c)) => Erro...
ing(usize, char), /* Number parsing */ LeadingZero(usize), SecondDecimalPoint(usize), InvalidCharInExponent(usize, char), EmptyExponent(usize), } pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Item { TopLevelValue, Liter...
random
[ { "content": "/// Attempt to parse the chars in `iter` as an string, **assuming that the initial `\"` has\n\n/// been consumed**. This returns a string slice **from the JSON source code**, i.e. the fully\n\n/// escaped string complete with the enclosing `\"`s. We do not attempt to decode the string, we\n\n///...
Rust
crates/wasi-common/cap-std-sync/src/dir.rs
dheaton-arm/wasmtime
86611d3bbc92b781ed136dcda7cdba9ec2c1cbee
use crate::file::{filetype_from, File}; use cap_fs_ext::{DirEntryExt, DirExt, MetadataExt, SystemTimeSpec}; use std::any::Any; use std::path::{Path, PathBuf}; use system_interface::fs::GetSetFdFlags; use wasi_common::{ dir::{ReaddirCursor, ReaddirEntity, WasiDir}, file::{FdFlags, FileType, Filestat, OFlags, Was...
use crate::file::{filetype_from, File}; use cap_fs_ext::{DirEntryExt, DirExt, MetadataExt, SystemTimeSpec}; use std::any::Any; use std::path::{Path, PathBuf}; use system_interface::fs::GetSetFdFlags; use wasi_common::{ dir::{ReaddirCursor, ReaddirEntity, WasiDir}, file::{FdFlags, FileType, Filestat, OFlags, Was...
} async fn rename( &self, src_path: &str, dest_dir: &dyn WasiDir, dest_path: &str, ) -> Result<(), Error> { let dest_dir = dest_dir .as_any() .downcast_ref::<Self>() .ok_or(Error::badf().context("failed downcast to cap-std Dir"))?;...
Ok(Filestat { device_id: meta.dev(), inode: meta.ino(), filetype: filetype_from(&meta.file_type()), nlink: meta.nlink(), size: meta.len(), atim: meta.accessed().map(|t| Some(t.into_std())).unwrap_or(None), mtim: meta.modified().map(|t| ...
call_expression
[ { "content": "/// Generates all the Rust source files used in Cranelift from the meta-language.\n\npub fn generate(isas: &[isa::Isa], out_dir: &str, crate_dir: &Path) -> Result<(), error::Error> {\n\n // Create all the definitions:\n\n // - common definitions.\n\n let mut shared_defs = shared::define()...
Rust
src/format/stm/load.rs
cmatsuoka/oxdz
0b7371bf63967819315316a58629881b2169f570
use format::{ProbeInfo, Format, Loader}; use format::stm::{StmData, StmPatterns, StmInstrument}; use module::{Module, Sample}; use module::sample::SampleType; use util::BinaryRead; use ::*; pub struct StmLoader; impl Loader for StmLoader { fn name(&self) -> &'static str { "Scream Tracker 2" } fn ...
use format::{ProbeInfo, Format, Loader}; use format::stm::{StmData, StmPatterns, StmInstrument}; use module::{Module, Sample}; use module::sample::SampleType; use util::BinaryRead; use ::*; pub struct StmLoader; impl Loader for StmLoader { fn name(&self) -> &'static str { "Scream Tracker 2" } fn ...
mPatterns::from_slice(num_patterns as usize, b.slice(1168, 1024*num_patterns as usize)?)?; let mut ofs = 1168 + 1024*num_patterns as usize; for i in 0..31 { let size = instruments[i].size as usize; let smp = load_sample(b.slice(ofs, size)?, ofs, i, &instruments[i]); ...
let version_minor = b.read8(31)?; if version_major != 2 || version_minor < 21 { return Err(Error::Format(format!("unsupported version {}.{}", version_major, version_minor))); } let speed = b.read8(32)?; let num_patterns = b.read8(33)?; let global_vol = b.read8...
function_block-random_span
[ { "content": "pub fn load(b: &[u8], player_id: &str) -> Result<Module, Error> {\n\n\n\n for f in loader_list() {\n\n debug!(\"Probing format: {}\", f.name());\n\n\n\n let info = match f.probe(b, player_id) {\n\n Ok(val) => val,\n\n Err(_) => continue,\n\n };\n\n\n\...
Rust
common/rs/src/mtc/battle/organizer.rs
OpenEmojiBattler/open-emoji-battler
c5054753525d2880602cd406837f01a8a82c7577
use crate::{ codec_types::*, mtc::battle::{common::BattleEmo, march::march}, }; use anyhow::{anyhow, ensure, Result}; use rand::{seq::SliceRandom, SeedableRng}; use rand_pcg::Pcg64Mcg; use sp_std::{cmp, prelude::*}; pub fn battle_all( board: &mtc::Board, health: &mut u8, ghost_states: &mut [mtc::Gh...
use crate::{ codec_types::*, mtc::battle::{common::BattleEmo, march::march}, }; use anyhow::{anyhow, ensure, Result}; use rand::{seq::SliceRandom, SeedableRng}; use rand_pcg::Pcg64Mcg; use sp_std::{cmp, prelude::*}; pub fn battle_all( board: &mtc::Board, health: &mut u8, ghost_states: &mut [mtc::Gh...
fn battle_gvg( ghost0_state: &mut mtc::GhostState, ghost0_history: &[mtc::GradeAndGhostBoard], ghost1_state: &mut mtc::GhostState, ghost1_history: &[mtc::GradeAndGhostBoard], turn: u8, seed: u64, emo_bases: &emo::Bases, ) -> Result<()> { let ghost0_grade_and_ghost_board = get_g...
turn: u8, seed: u64, emo_bases: &emo::Bases, ) -> Result<()> { let ghost_grade_and_ghost_board = get_grade_and_ghost_board(ghost_history, ghost_state, turn); let (player_board_grade, ghost_board_grade, _) = march_pvg(board, &ghost_grade_and_ghost_board.board, seed, emo_bases)?; damage_ghos...
function_block-function_prefix_line
[ { "content": "#[wasm_bindgen]\n\npub fn march_pvg(board: &[u8], ghost_board: &[u8], seed: &str, emo_bases: &[u8]) -> Vec<u8> {\n\n mtc::battle::organizer::march_pvg(\n\n &mtc::decoders::decode_board(board),\n\n &mtc::decoders::decode_ghost_board(ghost_board),\n\n seed.parse().unwrap(),\n...