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
lib_gbemulation/src/cpu/instructions/cb_instructions.rs
p4ddy1/gbemulator
1fed41d25fbbfb3e73c616612b5ccf338f6fed39
use crate::cpu::cpu::Cpu; use crate::cpu::instructions::{ functions, read_hl_addr, write_hl_addr, ExecutionType, Instruction, }; use crate::memory::mmu::{Mmu, Opcode}; use crate::util::binary::{reset_bit_in_byte, set_bit_in_byte}; macro_rules! bit { ($bit: expr) => { Some(&Instruction { len...
use crate::cpu::cpu::Cpu; use crate::cpu::instructions::{ functions, read_hl_addr, write_hl_addr, ExecutionType, Instruction, }; use crate::memory::mmu::{Mmu, Opcode}; use crate::util::binary::{reset_bit_in_byte, set_bit_in_byte}; macro_rules! bit { ($bit: expr) => { Some(&Instruction { len...
pcode| { let result = set_bit_in_byte(read_hl_addr(cpu, mmu), $bit); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }) }; } pub fn get_instruction(op_code: &u8) -> Option<&Instruction> { match op_code { 0x00..=0x05 | 0x07 => S...
code: &Opcode| { let result = set_bit_in_byte(read_by_opcode(op_code, cpu), $bit); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }) }; } macro_rules! set_hl { ($bit: expr) => { Some(&Instruction { length: 2,...
random
[ { "content": "pub fn call(cpu: &mut Cpu, mmu: &mut Mmu) {\n\n //Put address of next instruction onto stack and jump to aa\n\n cpu.registers.sp = cpu.registers.sp.wrapping_sub(2);\n\n mmu.write_word(cpu.registers.sp, cpu.registers.pc + 3);\n\n cpu.registers.pc = bytes_to_word(get_argument(cpu, mmu, 1...
Rust
fhir-bench-orchestrator/src/servers/mod.rs
karlmdavis/fhir-benchmarks
e1af68545f202c40d68fed623891898c78fdbf31
use crate::{ config::AppConfig, sample_data::SampleResource, servers::docker_compose::DockerComposeServerPlugin, AppState, }; use async_trait::async_trait; use eyre::Result; use serde::{Deserialize, Serialize}; use tracing::info; use url::Url; mod docker_compose; #[derive(Debug, PartialEq, Clone, Deserializ...
use crate::{ config::AppConfig, sample_data::SampleResource, servers::docker_compose::DockerComposeServerPlugin, AppState, }; use async_trait::async_trait; use eyre::Result; use serde::{Deserialize, Serialize}; use tracing::info; use url::Url; mod docker_compose; #[derive(Debug, PartialEq, Clone, Deserializ...
} async fn launch(&self, app_state: &AppState) -> Result<Box<dyn ServerHandle>> { match self { ServerPluginWrapper::DockerComposeServerPlugin(server_plugin) => { server_plugin.launch(app_state).await } } } } pub fn create_server_plugins(config: &App...
match self { ServerPluginWrapper::DockerComposeServerPlugin(server_plugin) => { server_plugin.server_name() } }
if_condition
[ { "content": "/// Converts [Duration] instances to ISO-8601 string values, for use in JSON.\n\n///\n\n/// Parameters:\n\n/// * `duration`: the [Duration] instance to be serialized\n\n/// * `serializer`: the Serde [Serializer] to use\n\n///\n\n/// Returns the [Serializer] result.\n\npub fn serialize<S>(duration:...
Rust
lib.rs
Lesterrry/Ferret-Interface
95026ad1798c992c5952133039a5b7b39c9b114e
extern crate termion; use std::io::{Write, stdout}; use termion::{terminal_size, color, style, raw::IntoRawMode, input::TermRead}; use std::{thread, time}; pub struct Misc; impl Misc { #[allow(dead_code)] fn overwrite(){ let stdout = stdout(); let mut stdout = stdout.lock().into_raw_mode().unwrap(); write!(std...
extern crate termion; use std::io::{Write, stdout}; use termion::{terminal_size, color, style, raw::IntoRawMode, input::TermRead}; use std::{thread, time}; pub struct Misc; impl Misc { #[allow(dead_code)] fn overwrite(){ let stdout = stdout(); let mut stdout = stdout.lock().into_raw_mode().unwrap(); write!(std...
fn invoke(&mut self){ ProgressBar::draw(self.message.clone(), self.progression.to_string() + "/" + &self.max.to_string(), self.progression / 27, self.color.clone()); } fn increase(&mut self){ self.progression += 1; ProgressBar::invoke(self); } fn draw(message: String, description: String, position: usize, c...
fn new(message: String, max: usize, color: FerretColor) -> Self{ ProgressBar{ max, progression: 0, message, color } }
function_block-full_function
[ { "content": "fn main() {\n\n\tMisc::overwrite();\n\n\tloop{\n\n\t\tlet mut progress_bar = ProgressBar::new(\"LOADING...\".to_string(), 800, FerretColor::Blue);\n\n\t\tfor _i in 0..800{\n\n\t\t\tthread::sleep(time::Duration::from_millis(10));\n\n\t\t\tprogress_bar.increase();\n\n\t\t}\n\n\t\tmatch Alert::invoke...
Rust
algebra/src/curves/mod.rs
knarz/zexe
e094e2127430521b7a882b0773bf1dc6852237b4
use crate::{ bytes::{FromBytes, ToBytes}, fields::{Field, PrimeField, SquareRootField}, groups::Group, }; use crate::UniformRand; use std::{ fmt::{Debug, Display}, hash::Hash, ops::{Add, AddAssign, Neg, Sub, SubAssign}, }; pub mod bls12_377; pub mod bls12_381; pub mod edwards_bls12; pub mod edw...
use crate::{ bytes::{FromBytes, ToBytes}, fields::{Field, PrimeField, SquareRootField}, groups::Group, }; use crate::UniformRand; use std::{ fmt::{Debug, Display}, hash::Hash, ops::{Add, AddAssign, Neg, Sub, SubAssign}, }; pub mod bls12_377; pub mod bls12_381; pub mod edwards_bls12; pub mod edw...
} pub trait ProjectiveCurve: Eq + Sized + ToBytes + FromBytes + Copy + Clone + Default + Send + Sync + Hash + Debug + Display + UniformRand + 'static + Neg<Output = Self> + for<'a> Add<&'a Self, Output = Self> + for<'a> Sub<&'a Self, Output = Self> ...
fn pairing<G1, G2>(p: G1, q: G2) -> Self::Fqk where G1: Into<Self::G1Affine>, G2: Into<Self::G2Affine>, { Self::final_exponentiation(&Self::miller_loop( [(&(p.into().prepare()), &(q.into().prepare()))].iter(), )) .unwrap() }
function_block-full_function
[ { "content": "/// A trait that defines parameters for a prime field.\n\npub trait FpParameters: 'static + Send + Sync + Sized {\n\n type BigInt: BigInteger;\n\n\n\n /// The modulus of the field.\n\n const MODULUS: Self::BigInt;\n\n\n\n /// The number of bits needed to represent the `Self::MODULUS`.\...
Rust
old/marker.rs
Cognoscan/fog_pack
7b3af246faa851bfc2aa09cc186ff2332124e791
#[derive(Clone, Copy, Debug, PartialEq)] pub enum Marker { PosFixInt(u8), FixMap(u8), FixArray(u8), FixStr(u8), Nil, Reserved, False, True, Bin8, Bin16, Bin32, Ext8, Ext16, Ext32, F32, F64, UInt8, UInt16, UInt32, UInt64, Int8, Int1...
#[derive(Clone, Copy, Debug, PartialEq)] pub enum Marker { PosFixInt(u8), FixMap(u8), FixArray(u8), FixStr(u8), Nil, Reserved, False, True, Bin8, Bin16, Bin32, Ext8, Ext16, Ext32, F32, F64, UInt8, UInt16, UInt32, UInt64, Int8, Int1...
} impl From<u8> for Marker { fn from(val: u8) -> Marker { Marker::from_u8(val) } } impl From<Marker> for u8 { fn from(val: Marker) -> u8 { val.into_u8() } } #[derive(Debug,PartialEq,Eq)] pub enum ExtType { Timestamp, Hash, Identity, Lockbox, } impl ExtType { ...
pub fn into_u8(self) -> u8 { match self { Marker::PosFixInt(val) => val, Marker::FixMap(len) => 0x80 | len, Marker::FixArray(len) => 0x90 | len, Marker::FixStr(len) => 0xa0 | len, Marker::Nil => 0xc0, Marker::Reserved ...
function_block-full_function
[ { "content": "/// Attempt to read a F32 from a fogpack data structure. Fails if invalid F64 retrieved.\n\npub fn read_f64(buf: &mut &[u8]) -> crate::Result<f64> {\n\n let fail_len = buf.len();\n\n let marker = read_marker(buf)?;\n\n if let MarkerType::F64 = marker {\n\n Ok(buf.read_f64::<BigEndi...
Rust
src/viewed_date.rs
tommket/chrono-datepicker-core
392903f18fc33bfa1f4e75cf866867d9835c5ac6
use std::ops::RangeInclusive; use chrono::{Datelike, NaiveDate}; use crate::dialog_view_type::DialogViewType; pub const YEARS_IN_YEAR_SELECTION: i32 = 20; pub type YearNumber = i32; pub type MonthNumber = u32; pub type DayNumber = u32; pub trait ViewedDate { fn previous_month(&self) -> NaiveDate; ...
use std::ops::RangeInclusive; use chrono::{Datelike, NaiveDate}; use crate::dialog_view_type::DialogViewType; pub const YEARS_IN_YEAR_SELECTION: i32 = 20; pub type YearNumber = i32; pub type MonthNumber = u32; pub type DayNumber = u32; pub trait ViewedDate { fn previous_month(&self) -> NaiveDate; ...
} pub fn year_group_start(year: YearNumber) -> YearNumber { year - (year % YEARS_IN_YEAR_SELECTION) } pub fn year_group_end(year: YearNumber) -> YearNumber { year_group_start(year) + (YEARS_IN_YEAR_SELECTION - 1) } pub fn year_group_range(year: YearNumber) -> RangeInclusive<YearNumber> { year_group_star...
match dialog_view_type { DialogViewType::Years => self.year() == date.year(), DialogViewType::Months => self.year() == date.year() && self.month() == date.month(), DialogViewType::Days => self == date, } }
function_block-function_prefix_line
[ { "content": "#[fixture(year = 1990, month = 1, day = 1)]\n\npub fn create_date(year: YearNumber, month: MonthNumber, day: DayNumber) -> NaiveDate {\n\n NaiveDate::from_ymd(year, month, day)\n\n}\n", "file_path": "src/rstest_utils.rs", "rank": 0, "score": 126217.50530730654 }, { "content"...
Rust
src/server/route.rs
fairingrey/tide
dd9d42d4c8e01299a1c7f69e0f56b8f06cc47b8f
use crate::utils::BoxFuture; use crate::{router::Router, Endpoint, Response}; #[allow(missing_debug_implementations)] pub struct Route<'a, State> { router: &'a mut Router<State>, path: String, prefix: bool, } impl<'a, State: 'static> Route<'a, State> { pub(crate) fn new(router: &'a...
use crate::utils::BoxFuture; use crate::{router::Router, Endpoint, Response}; #[allow(missing_debug_implementations)] pub struct Route<'a, State> { router: &'a mut Router<State>, path: String, prefix: bool, } impl<'a, State: 'static> Route<'a, State> { pub(crate) fn new(router: &'a...
rity_part() { new_uri.authority(authority.clone()); } new_uri.path_and_query(path_and_query.as_str()); let new_uri = new_uri.build().unwrap(); *req.request.uri_mut() = new_uri; self.0.call(req) } }
; if let Some(query) = uri.query() { path_and_query.push('?'); path_and_query.push_str(query); } let mut new_uri = http::Uri::builder(); if let Some(scheme) = uri.scheme_part() { new_uri.scheme(scheme.clone()); } if let Some(authority) ...
function_block-random_span
[ { "content": "/// An HTTP request handler.\n\n///\n\n/// This trait is automatically implemented for `Fn` types, and so is rarely implemented\n\n/// directly by Tide users.\n\n///\n\n/// In practice, endpoints are functions that take a `Request<State>` as an argument and\n\n/// return a type `T` that implements...
Rust
src/lib.rs
jdisanti/hassel_wasm_dbg
9b3804d4f42d2310151007e2e10a15c06c3954c0
extern crate hassel_emu; mod debug; use debug::{DebuggingEmulator, StepResult}; use std::os::raw::c_void; use std::mem; #[no_mangle] pub fn alloc(len: usize) -> *mut c_void { let mut memory = Vec::with_capacity(len); let ptr = memory.as_mut_ptr(); mem::forget(memory); ptr as *mut c_void } #[no_man...
extern crate hassel_emu; mod debug; use debug::{DebuggingEmulator, StepResult}; use std::os::raw::c_void; use std::mem; #[no_mangle] pub fn alloc(len: usize) -> *mut c_void { let mut memory = Vec::with_capacity(len); let ptr = memory.as_mut_ptr(); mem::forget(memory); ptr as *mut c_void } #[no_man...
Vec::from_raw_parts(buffer_ptr, buffer_size, buffer_size) }; { let debug_read = emulator.cpu().memory().debug_read(); for i in 0..buffer_size { buffer[i] = debug_read.byte(i as u16); } } mem::forget(buffer); mem::forget(emulator); } #[no_mangle] pub fn emulator_get...
} } cycles_run }) } #[no_mangle] pub fn emulator_reg_a(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().a }) } #[no_mangle] pub fn emulator_reg_x(emulator_ptr: *mut DebuggingEmulator) -> u...
random
[ { "content": " public getMemorySlice(start: number, end: number): number[] {\n\n let memory: number[] = [];\n\n if (start < end) {\n\n this.assembly_exports.emulator_get_memory(this.emulator, this.memoryPtr);\n\n let memoryView = new Uint8Array(this.assembly_instance.expor...
Rust
src/tests.rs
duncanrhamill/cell-map
27979d40088f0459c930fa38f2638106b8191005
use nalgebra::{Point2, Vector2}; use super::*; use crate::{cell_map::Bounds, test_utils::TestLayers}; #[test] fn get_cell_positions() { let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(1.0, 1.0), ....
use nalgebra::{Point2, Vector2}; use super::*; use crate::{cell_map::Bounds, test_utils::TestLayers}; #[test] fn get_cell_positions() { let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(1.0, 1.0), ....
let mut last_y = 0; print!("\nA + B:\n "); for ((_, idx), val) in map_a.iter().layer(TestLayers::Layer0).indexed() { if last_y != idx.y { last_y = idx.y; print!("\n "); } print!("{} ", val); } println!(); }
for ((_, idx), &val) in map.iter().indexed().layer(TestLayers::Layer0) { if idx.x >= 2 || idx.y < 5 || idx.y >= 15 { assert_eq!(val, None); } else { assert_eq!(val, Some(1)); } } } #[test] fn test_merge() { let mut map_a = CellMap::<TestLayers, i32>::new_from_ele...
random
[ { "content": "#[test]\n\nfn tests() {\n\n let t = trybuild::TestCases::new();\n\n t.pass(\"tests/layer-pass.rs\");\n\n t.compile_fail(\"tests/layer-fail.rs\");\n\n}\n", "file_path": "cell-map-macro/tests/all.rs", "rank": 0, "score": 106619.28868823935 }, { "content": "#[test]\n\nfn ...
Rust
server/src/main.rs
bigbass1997/remote64
8355a3b956b3f8139a913944db9e16781c97503e
extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use clap::{AppSettings, Arg, Command}; use crossbeam_queue::SegQueue; use log::LevelFilter; use minifb::{Key, Window, WindowOptions}; use minifb::{Scale, ScaleMode}; use portaudio::DeviceIndex; ...
extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use clap::{AppSettings, Arg, Command}; use crossbeam_queue::SegQueue; use log::LevelFilter; use minifb::{Key, Window, WindowOptions}; use minifb::{Scale, ScaleMode}; use portaudio::DeviceIndex; ...
fn main() { let matches = Command::new("remote64-server") .version(clap::crate_version!()) .arg(Arg::new("features") .short('f') .long("feature") .takes_value(true) .multiple_occurrences(true) .possible_values(["LivePlayback", "AudioRe...
function_block-full_function
[ { "content": " }\n\n \n\n /// Attempts to resize the resolution of the captured video.\n\n /// \n\n /// Returns the resulting format.\n\n pub fn resize(&mut self, width: u32, height: u32) -> Format {\n\n let mut fmt = self.dev.format().unwrap();\n\n fmt.width = width;\n\n ...
Rust
server/entity/src/object/falling_block.rs
nobbele/feather
5599851800624086fd1b049bdd1894b2aa637a03
use feather_core::blocks::{BlockId, SimplifiedBlockKind}; use feather_core::entitymeta::{EntityMetadata, META_INDEX_FALLING_BLOCK_SPAWN_POSITION}; use feather_core::network::packets::{Effect, SpawnObject}; use feather_core::network::Packet; use feather_core::util::{BlockPosition, Position}; use feather_server_types::...
use feather_core::blocks::{BlockId, SimplifiedBlockKind}; use feather_core::entitymeta::{EntityMetadata, META_INDEX_FALLING_BLOCK_SPAWN_POSITION}; use feather_core::network::packets::{Effect, SpawnObject}; use feather_core::network::Packet; use feather_core::util::{BlockPosition, Position}; use feather_server_types::...
fn create_spawn_packet(accessor: &EntityRef) -> Box<dyn Packet> { let data = i32::from(accessor.get::<FallingBlockType>().0.vanilla_id()); let position = accessor.get::<Position>(); let entity_id = accessor.get::<NetworkId>().0; let velocity = accessor.get::<Velocity>().0; let (velocity_x, veloc...
EntityMetadata::entity_base().with(META_INDEX_FALLING_BLOCK_SPAWN_POSITION, spawn_pos); crate::base() .with(FallingBlock) .with(FallingBlockType(ty)) .with(SpawnPacketCreator(&create_spawn_packet)) .with( PhysicsBuilder::new() .bbox(0.98, 0.98, 0.98) ...
function_block-function_prefix_line
[ { "content": "#[fecs::event_handler]\n\npub fn on_block_break_drop_loot(event: &BlockUpdateEvent, game: &mut Game, world: &mut World) {\n\n if event.old.is_air() || !event.new.is_air() {\n\n return;\n\n }\n\n\n\n let item = match event.cause {\n\n feather_server_types::BlockUpdateCause::E...
Rust
src/storage/src/range_map.rs
vinimin/fluvio
142c050a2f1aaa83aeda19705fedd670fffaf1a1
use std::cmp::max; use std::cmp::min; use std::collections::BTreeMap; use std::ops::Bound::Excluded; use std::ops::Bound::Included; use std::ffi::OsStr; use log::debug; use log::trace; use log::error; use kf_protocol::api::Offset; use crate::segment::ReadSegment; use crate::StorageError; use crate::ConfigOption; use...
use std::cmp::max; use std::cmp::min; use std::collections::BTreeMap; use std::ops::Bound::Excluded; use std::ops::Bound::Included; use std::ffi::OsStr; use log::debug; use log::trace; use log::error; use kf_protocol::api::Offset; use crate::segment::ReadSegment; use crate::StorageError; use crate::ConfigOption; use...
ult<(), StorageError> { let rep_dir = temp_dir().join(TEST_EMPTY_DIR); ensure_new_dir(&rep_dir)?; let option = default_option(rep_dir); let (segments, last_segment) = SegmentList::from_dir(&option).await?; assert_eq!(segments.len(), 0); assert!(last_segment.is_none());...
ment(create_segment(&option, 3000, 2000).await?); let index = list.find_segment(1500); assert!(index.is_some()); let (pos, _) = index.unwrap(); assert_eq!(*pos, 500); Ok(()) } const TEST_READ_DIR: &str = "segmentlist-read-many"; #[test_async] async fn test_se...
random
[ { "content": "/// given parent directory, base offset, extension, generate path\n\npub fn generate_file_name<P>(parent_dir: P, base_offset: Offset, extension: &str) -> PathBuf\n\n where P: AsRef<Path>\n\n {\n\n\n\n let mut file = parent_dir.as_ref().join(format!(\"{:020}\",base_offset));\n\n file.set_e...
Rust
src/dfinity.rs
Zondax/ledger-dfinity-rs
af9f87cade48b3c5ad03e35ef319b9d0e42d5f04
/******************************************************************************* * (c) 2020 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/lic...
/******************************************************************************* * (c) 2020 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/lic...
it as u8, p2: 0x00, data: serialized_path, }; let response = ledger_zondax_generic::send_chunks(&self.apdu_transport, &start_command, &message) .await?; if response.data.is_empty() && response.retcode == APDUErrorCodes::NoError as u16 { ...
pub rs: [u8; SIG_LEN], } impl DfinityApp { pub fn new(apdu_transport: APDUTransport) -> Self { DfinityApp { apdu_transport, cla: CLA_DFINITY, } } pub async fn get_version(&self) -> Result<Version, LedgerAppError> { ledger_zondax_generic::ge...
random
[ { "content": "/// Create a new connection to a dfinity app\n\npub fn new_dfinity_app(apdu_transport: APDUTransport) -> DfinityApp {\n\n DfinityApp::new(apdu_transport)\n\n}\n", "file_path": "src/lib.rs", "rank": 3, "score": 34796.735529721744 }, { "content": "/****************************...
Rust
src/connectivity/network/ping3/src/tests/mod.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
mod integration_tests; use fidl::endpoints::DiscoverableProtocolMarker as _; use fidl_fuchsia_net as fnet; use fidl_fuchsia_net_icmp as fnet_icmp; use fidl_fuchsia_net_stack as fnet_stack; use fidl_fuchsia_net_stack_ext::FidlReturn as _; use fidl_fuchsia_netemul_environment as netemul_environment; use fuchsia_zircon...
mod integration_tests; use fidl::endpoints::DiscoverableProtocolMarker as _; use fidl_fuchsia_net as fnet; use fidl_fuchsia_net_icmp as fnet_icmp; use fidl_fuchsia_net_stack as fnet_stack; use fidl_fuchsia_net_stack_ext::FidlReturn as _; use fidl_fuchsia_netemul_environment as netemul_environment; use fuchsia_zircon...
let sleep_ms = 500; eprintln!("address not ready, waiting {}ms...", sleep_ms); let () = zx::Duration::from_millis(sleep_ms).sleep(); } let stack = env.connect_to_service::<fnet_stack::StackMarker>().context("connect to net stack")?; let () = stack ...
waiting {}ms...", sleep_ms); let () = zx::Duration::from_millis(sleep_ms).sleep(); } let () = iface.add_ip_addr(config.static_ip).await.context("add ip addr")?; loop { if iface.get_addrs().await.context("ge...
random
[]
Rust
src/ui/presenter/state/split.rs
MattWindsor91/zombiesplit
9040ac14e1c2a479dbb48f4e80d3c3b49ea9f7ec
use super::super::cursor::SplitPosition; use std::fmt::Display; use crate::model::{ aggregate, attempt::observer::{split, time}, comparison::pace::{self, PacedTime}, short, }; #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Set { short_map: short::Map<usize>, vec: Vec<Split>, } im...
use super::super::cursor::SplitPosition; use std::fmt::Display; use crate::model::{ aggregate, attempt::observer::{split, time}, comparison::pace::{self, PacedTime}, short, }; #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Set { short_map: short::Map<usize>, vec: Vec<Split>, } im...
}
pub fn set_editor(&mut self, editor: Option<&super::super::mode::Editor>) { self.editor = editor.map(|e| { let mut out = super::Editor { hours: e.time.hours.to_string(), mins: e.time.mins.to_string(), secs: e.time.secs.to_string(), msec...
function_block-full_function
[ { "content": "fn make_cache(from: &[Split]) -> short::Map<usize> {\n\n from.iter()\n\n .enumerate()\n\n .map(|(i, s)| (s.info.short, i))\n\n .collect()\n\n}\n\n\n", "file_path": "src/model/attempt/split/set.rs", "rank": 0, "score": 242006.49281943368 }, { "content": "...
Rust
execution-engine/engine-tests/src/test/contract_api/create_purse.rs
flowstake/CasperLabs
761910a5957dffb281242d59d11dc017dcaa4104
use crate::support::test_support::{ExecuteRequestBuilder, WasmTestBuilder}; use contract_ffi::base16; use contract_ffi::key::Key; use contract_ffi::value::account::PurseId; use contract_ffi::value::U512; use engine_shared::transform::Transform; use crate::test::{DEFAULT_ACCOUNT_ADDR, DEFAULT_GENESIS_CONFIG, DEFAULT_P...
use crate::support::test_support::{ExecuteRequestBuilder, WasmTestBuilder}; use contract_ffi::base16; use contract_ffi::key::Key; use contract_ffi::value::account::PurseId; use contract_ffi::value::U512; use engine_shared::transform::Transform; use crate::test::{DEFAULT_ACCOUNT_ADDR, DEFAULT_GENESIS_CONFIG, DEFAULT_P...
#[ignore] #[test] fn should_insert_account_into_named_keys() { let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_TRANSFER_PURSE_TO_ACCOUNT, (ACCOUNT_1_ADDR, *ACCOUNT_1_INITIAL_BALANCE), ) .build(); let exec_request_2 = ExecuteRequestBuilder::...
fn should_insert_mint_add_keys_transform() { let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_TRANSFER_PURSE_TO_ACCOUNT, (ACCOUNT_1_ADDR, *ACCOUNT_1_INITIAL_BALANCE), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( ACC...
function_block-full_function
[ { "content": "fn get_uref(key: Key) -> URef {\n\n match key {\n\n Key::URef(uref) => uref,\n\n _ => panic!(\"Key {:?} is not an URef\", key),\n\n }\n\n}\n\n\n", "file_path": "execution-engine/engine-tests/src/test/regression/ee_441.rs", "rank": 1, "score": 413384.2920016523 }, ...
Rust
src/http/mod.rs
ml85/iexc-rs
7a97fa89c4a5d4d9ac680c71395594e0c75a9a71
use std::error; use std::io; use std::io::prelude::*; use std::net::TcpStream; use std::sync::Arc; type Result<T> = std::result::Result<T, Box<dyn error::Error>>; pub struct Response { pub protocol_version: String, pub status_code: u16, pub status_message: String, pub headers: Vec<(String, String)>, ...
use std::error; use std::io; use std::io::prelude::*; use std::net::TcpStream; use std::sync::Arc; type Result<T> = std::result::Result<T, Box<dyn error::Error>>; pub struct Response { pub protocol_version: String, pub status_code: u16, pub status_message: String, pub headers: Vec<(String, String)>, ...
} else { let mut config = rustls::ClientConfig::new(); config .root_store .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS); let dns_name = webpki::DNSNameRef::try_from_ascii_str(self.domain.as_str())?; let session = rustl...
match TcpStream::connect(format!("{}:{}", self.domain, self.port)) { Ok(stream) => Ok(Box::new(stream)), Err(e) => Err(Box::new(e)), }
if_condition
[ { "content": "type Result<T> = std::result::Result<T, Box<dyn error::Error>>;\n\n\n\npub enum Endpoint {\n\n Production,\n\n Sandbox,\n\n}\n\n\n\npub struct Client {\n\n http_client: http::Client,\n\n api_token: String,\n\n}\n\n\n\nimpl Client {\n\n pub fn new(endpoint: Endpoint, api_token: Strin...
Rust
edgelet/edgelet-http/src/util/mod.rs
jongio/iotedge
07a7b2071e6d64c934ebf55589416da0c4725093
use std::fmt; use std::io::{self, Read, Write}; use std::net::SocketAddr; #[cfg(unix)] use std::os::unix::net::SocketAddr as UnixSocketAddr; use bytes::{Buf, BufMut}; use edgelet_core::pid::Pid; use futures::Poll; use tokio_core::net::TcpStream; use tokio_io::{AsyncRead, AsyncWrite}; #[cfg(windows)] use tokio_named_...
use std::fmt; use std::io::{self, Read, Write}; use std::net::SocketAddr; #[cfg(unix)] use std::os::unix::net::SocketAddr as UnixSocketAddr; use bytes::{Buf, BufMut}; use edgelet_core::pid::Pid; use futures::Poll; use tokio_core::net::TcpStream; use tokio_io::{AsyncRead, AsyncWrite}; #[cfg(windows)] use tokio_named_...
[u8]) -> bool { match *self { StreamSelector::Tcp(ref stream) => stream.prepare_uninitialized_buffer(buf), #[cfg(windows)] StreamSelector::Pipe(ref stream) => stream.prepare_uninitialized_buffer(buf), #[cfg(unix)] StreamSelector::Unix(ref stream) => s...
ixStream), } impl StreamSelector { pub fn pid(&self) -> io::Result<Pid> { match *self { StreamSelector::Tcp(_) => Ok(Pid::Any), #[cfg(windows)] StreamSelector::Pipe(_) => Ok(Pid::Any), #[cfg(unix)] StreamSelector::Unix(ref stream) => stream.pid(),...
random
[ { "content": "pub trait Recognizer {\n\n type Parameters: 'static;\n\n\n\n fn recognize(\n\n &self,\n\n method: &Method,\n\n path: &str,\n\n ) -> Result<HandlerParamsPair<Self::Parameters>, StatusCode>;\n\n}\n\n\n", "file_path": "edgelet/edgelet-http/src/route/mod.rs", "ran...
Rust
bee-api/bee-rest-api/src/endpoints/routes/api/plugins/debug/white_flag.rs
fossabot/bee-1
15329cb8a0b3bc5512fff2bd782db7e47ccb0ff0
use crate::{ endpoints::{ config::{RestApiConfig, ROUTE_WHITE_FLAG}, filters::{ with_bus, with_message_requester, with_requested_messages, with_rest_api_config, with_storage, with_tangle, }, permission::has_permission, rejection::CustomRejection, storage...
use crate::{ endpoints::{ config::{RestApiConfig, ROUTE_WHITE_FLAG}, filters::{ with_bus, with_message_requester, with_requested_messages, with_rest_api_config, with_storage, with_tangle, }, permission::has_permission, rejection::CustomRejection, storage...
pub(crate) async fn white_flag<B: StorageBackend>( body: JsonValue, storage: ResourceHandle<B>, tangle: ResourceHandle<MsTangle<B>>, bus: ResourceHandle<Bus<'static>>, message_requester: MessageRequesterWorker, requested_messages: ResourceHandle<RequestedMessages>, rest_api_config: RestApi...
bus: ResourceHandle<Bus<'static>>, message_requester: MessageRequesterWorker, requested_messages: ResourceHandle<RequestedMessages>, rest_api_config: RestApiConfig, ) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone { self::path() .and(warp::post()) .and(has_permission(ROU...
function_block-function_prefix_line
[ { "content": "fn path() -> impl Filter<Extract = (MessageId,), Error = Rejection> + Clone {\n\n super::path()\n\n .and(warp::path(\"messages\"))\n\n .and(message_id())\n\n .and(warp::path::end())\n\n}\n\n\n\npub(crate) fn filter<B: StorageBackend>(\n\n public_routes: Box<[String]>,\n\...
Rust
azure_sdk_storage_blob/src/blob/requests/get_blob_builder.rs
imp/AzureSDKForRust
964b95e4a32c457a0a4fa45e9e16064e35f863be
use crate::blob::responses::GetBlobResponse; use crate::blob::{generate_blob_uri, Blob}; use azure_sdk_core::errors::{check_status_extract_headers_and_body, AzureError}; use azure_sdk_core::headers::RANGE_GET_CONTENT_MD5; use azure_sdk_core::lease::LeaseId; use azure_sdk_core::range::Range; use azure_sdk_core::util::Re...
use crate::blob::responses::GetBlobResponse; use crate::blob::{generate_blob_uri, Blob}; use azure_sdk_core::errors::{check_status_extract_headers_and_body, AzureError}; use azure_sdk_core::headers::RANGE_GET_CONTENT_MD5; use azure_sdk_core::lease::LeaseId; use azure_sdk_core::range::Range; use azure_sdk_core::util::Re...
if let Some(timeout) = TimeoutOption::to_uri_parameter(&self) { uri = format!("{}{}{}", uri, if f_first { "?" } else { "&" }, timeout); } trace!("uri == {:?}", uri); let future_response = self.client().perform_request( &uri, &Method::GET, ...
inerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn lease_id(&self) -> Option<&'a LeaseId> { self.lease_id } } impl<'a, ContainerNameSet, BlobNameSet> ClientRequestIdOption<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ...
random
[ { "content": "pub fn initialize() -> Result<Client<impl CosmosUriBuilder + Clone>, AzureError> {\n\n let account = std::env::var(\"COSMOS_ACCOUNT\").expect(\"Set env variable COSMOS_ACCOUNT first!\");\n\n let key = std::env::var(\"COSMOS_MASTER_KEY\").expect(\"Set env variable COSMOS_KEY first!\");\n\n\n\...
Rust
libafl_frida/src/cmplog_rt.rs
AdrianoPi/LibAFL
cf5b4dfb180d65cb267ec1297df5cb52acbdcfef
use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; use libafl_targets::CMPLOG_MAP_W; use std::ffi::c_void; extern crate libafl_targets; extern "C" { pub fn __libafl_targets_cmplog_instructions(k: u64, shape: u8, arg1: u64, arg2: u64); } pub struct CmpLogRuntime { ops_save_register_and_blr_to_populate: Option<...
use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; use libafl_targets::CMPLOG_MAP_W; use std::ffi::c_void; extern crate libafl_targets; extern "C" { pub fn __libafl_targets_cmplog_instructions(k: u64, shape: u8, arg1: u64, arg2: u64); } pub struct CmpLogRuntime { ops_save_register_and_blr_to_populate: Option<...
; self.ops_save_register_and_blr_to_populate = Some( ops_save_register_and_blr_to_populate .finalize() .unwrap() .into_boxed_slice(), ); } pub fn init(&mut self) { self.generate_instrumentation_blobs(); } #[inline...
Some( ops_handle_tbnz_masking .finalize() .unwrap() .into_boxed_slice(), )
call_expression
[ { "content": "pub fn set_exec_cmp1_hook(hook: extern \"C\" fn(id: u64, v0: u8, v1: u8)) {\n\n unsafe {\n\n libafl_exec_cmp_hook1 = hook;\n\n }\n\n}\n\n\n", "file_path": "libafl_qemu/src/emu.rs", "rank": 0, "score": 394177.4333775672 }, { "content": "pub fn set_hook(addr: u64, ca...
Rust
12_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs
tantara/rust-raspberrypi-OS-tutorials
6eafd7c81e41cdfcac131eaaf722e274c8b1bcff
use core::{cell::UnsafeCell, fmt}; use cortex_a::{asm, barrier, regs::*}; use register::InMemoryRegister; global_asm!(include_str!("exception.S")); #[repr(transparent)] struct SpsrEL1(InMemoryRegister<u64, SPSR_EL1::Register>); #[repr(C)] struct ExceptionContext { gpr: [u64; 30], lr: u64, ...
use core::{cell::UnsafeCell, fmt}; use cortex_a::{asm, barrier, regs::*}; use register::InMemoryRegister; global_asm!(include_str!("exception.S")); #[repr(transparent)] struct SpsrEL1(InMemoryRegister<u64, SPSR_EL1::Register>); #[repr(C)] struct ExceptionContext { gpr: [u64; 30], lr: u64, ...
} #[rustfmt::skip] impl fmt::Display for SpsrEL1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; let to_flag_str = |x| -> _ { if x { "Set" } else { "Not set" } }; writeln!(f, " Flags:")?; ...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let esr_el1 = ESR_EL1.extract(); writeln!(f, "ESR_EL1: {:#010x}", esr_el1.get())?; write!(f, " Exception Class (EC) : {:#x}", esr_el1.read(ESR_EL1::EC))?; let ec_translation = match esr_el1....
function_block-full_function
[ { "content": "/// Return the inclusive range spanning the .bss section.\n\n///\n\n/// # Safety\n\n///\n\n/// - Values are provided by the linker script and must be trusted as-is.\n\n/// - The linker-provided addresses must be u64 aligned.\n\npub fn bss_range_inclusive() -> RangeInclusive<*mut u64> {\n\n let ...
Rust
src/errno.rs
allisonrandal/vmm-sys-util
26e085b93c0e6342447d82ef21ddb3846c4edad4
use std::fmt::{Display, Formatter}; use std::io; use std::result; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Error(i32); pub type Result<T> = result::Result<T, Error>; impl Error { pub fn new(errno: i32) -> Error { ...
use std::fmt::{Display, Formatter}; use std::io; use std::result; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Error(i32); pub type Result<T> = result::Result<T, Error>; impl Error { pub fn new(errno: i32) -> Error { ...
let mut buf: Vec<u8> = Vec::new(); assert!(file.read_to_end(&mut buf).is_err()); let last_err = errno_result::<i32>().unwrap_err(); assert_eq!(last_err, Error::new(expected_errno)); assert_eq!(last_err.errno(), expected_errno); assert!(last_err.source...
let mut file = OpenOptions::new() .read(false) .write(true) .create(true) .truncate(true) .open(path) .unwrap();
assignment_statement
[ { "content": "fn modify_mode<F: FnOnce(&mut termios)>(fd: RawFd, f: F) -> Result<()> {\n\n // Safe because we check the return value of isatty.\n\n if unsafe { isatty(fd) } != 1 {\n\n return Ok(());\n\n }\n\n\n\n // The following pair are safe because termios gets totally overwritten by tcget...
Rust
crates/ra_ide/src/references/search_scope.rs
iTZAvishay/rust-analyzer
074474fe00a08d394cbdcac2a136bca825d93377
use std::mem; use hir::{DefWithBody, HasSource, ModuleSource}; use ra_db::{FileId, SourceDatabaseExt}; use ra_prof::profile; use ra_syntax::{AstNode, TextRange}; use rustc_hash::FxHashMap; use ra_ide_db::RootDatabase; use super::Definition; pub struct SearchScope { entries: FxHashMap<FileId, Option<TextRange>...
use std::mem; use hir::{DefWithBody, HasSource, ModuleSource}; use ra_db::{FileId, SourceDatabaseExt}; use ra_prof::profile; use ra_syntax::{AstNode, TextRange}; use rustc_hash::FxHashMap; use ra_ide_db::RootDatabase; use super::Definition; pub struct SearchScope { entries: FxHashMap<FileId, Option<TextRange>...
parent_module.definition_source(db); let file_id = parent_src.file_id.original_file(db); match parent_src.value { ModuleSource::Module(m) => { let range = Some(m.syntax().text_range()); res.insert(file_id, range); ...
(db).value.syntax().text_range(), DefWithBody::Const(c) => c.source(db).value.syntax().text_range(), DefWithBody::Static(s) => s.source(db).value.syntax().text_range(), }; let mut res = FxHashMap::default(); res.insert(file_id, Some(range)); ...
random
[ { "content": "/// Build the signature of a callable item (function, struct or enum variant).\n\npub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> PolyFnSig {\n\n match def {\n\n CallableDef::FunctionId(f) => fn_sig_for_fn(db, f),\n\n CallableDef::StructId(s) => fn_sig_for_str...
Rust
src/developer/ffx/lib/doctor_utils/src/recorder.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { anyhow::{anyhow, Result}, chrono::prelude::*, std::{ collections::HashMap, fs::File, io::{copy, Seek, SeekFrom, Write}, path::PathBuf, }, zip::{ write::{FileOptions, ZipWriter}, CompressionMethod, }, }; const FILE_MAX_BYTES: i64 = 4_000_00...
use { anyhow::{anyhow, Result}, chrono::prelude::*, std::{ collections::HashMap, fs::File, io::{copy, Seek, SeekFrom, Write}, path::PathBuf, }, zip::{ write::{FileOptions, ZipWriter}, CompressionMethod, }, }; const FILE_MAX_BYTES: i64 = 4_000_00...
} #[cfg(test)] mod test { use { super::*, fuchsia_async as fasync, std::{ collections::HashSet, fs::File, io::{Read, Write}, }, tempfile::tempdir, zip::read::ZipArchive, }; const FAKE_OUTPUT: &str = "doctor doctor"; c...
fn generate(&self, output_dir: PathBuf) -> Result<PathBuf> { let fname = format!("ffx-record-{}.zip", Local::now().format("%Y%m%d-%H%M%S")); let mut output_path = output_dir.clone(); output_path.push(fname); let file = File::create(output_path.clone())?; let mut zip = ZipWriter:...
function_block-full_function
[]
Rust
src/tools/clippy/clippy_lints/src/needless_for_each.rs
stevepentland/rust
57d8747cca741de84918800dca13da0c821e33e0
use rustc_errors::Applicability; use rustc_hir::{ intravisit::{walk_expr, NestedVisitorMap, Visitor}, Expr, ExprKind, Stmt, StmtKind, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{source_map::Span, sym...
use rustc_errors::Applicability; use rustc_hir::{ intravisit::{walk_expr, NestedVisitorMap, Visitor}, Expr, ExprKind, Stmt, StmtKind, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{source_map::Span, sym...
} #[derive(Default)] struct RetCollector { spans: Vec<Span>, ret_in_loop: bool, loop_depth: u16, } impl<'tcx> Visitor<'tcx> for RetCollector { type Map = Map<'tcx>; fn visit_expr(&mut self, expr: &Expr<'_>) { match expr.kind { ExprKind::Ret(..) => { if self.lo...
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { let expr = match stmt.kind { StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr, _ => return, }; if_chain! { if let ExprKind::MethodCall(method_name, _, [for_each_recv, for...
function_block-full_function
[]
Rust
src/binding_layout_tests.rs
nervosnetwork/blake2b-rs
1ecc3d2986977ea2ac8fb04fd0566332465d349a
use crate::binding::*; #[test] fn bindgen_test_layout_max_align_t() { assert_eq!( ::core::mem::size_of::<max_align_t>(), 32usize, concat!("Size of: ", stringify!(max_align_t)) ); assert_eq!( ::core::mem::align_of::<max_align_t>(), 16usize, concat!("Alignment ...
use crate::binding::*; #[test] fn bindgen_test_layout_max_align_t() { assert_eq!( ::core::mem::size_of::<max_align_t>(), 32usize, concat!("Size of: ", stringify!(max_align_t)) ); assert_eq!( ::core::mem::align_of::<max_align_t>(), 16usize, concat!("Alignment ...
#[test] fn bindgen_test_layout_blake2b_state__() { assert_eq!( ::core::mem::size_of::<blake2b_state__>(), 248usize, concat!("Size of: ", stringify!(blake2b_state__)) ); assert_eq!( ::core::mem::align_of::<blake2b_state__>(), 8usize, concat!("Alignment of ", ...
fn bindgen_test_layout___fsid_t() { assert_eq!( ::core::mem::size_of::<__fsid_t>(), 8usize, concat!("Size of: ", stringify!(__fsid_t)) ); assert_eq!( ::core::mem::align_of::<__fsid_t>(), 4usize, concat!("Alignment of ", stringify!(__fsid_t)) ); assert_...
function_block-full_function
[ { "content": "fn main() {\n\n // Some target(e.g. wasm32-unknown-unknown) won't have this flag\n\n // defined since it has not features.\n\n let features = std::env::var(\"CARGO_CFG_TARGET_FEATURE\").unwrap_or_default();\n\n if features.contains(\"sse4.1\") || features.contains(\"sse2\") {\n\n ...
Rust
src/rules/no_regex_spaces.rs
hugo-paul/deno_lint
d46a89fe4569f8ab0596996bb0a98a70b4a34b05
use super::Context; use super::LintRule; use crate::scopes::{ScopeManager, ScopeVisitor}; use swc_ecma_ast::{CallExpr, Expr, ExprOrSuper, Lit, NewExpr, Regex}; use swc_ecma_visit::Node; use swc_ecma_visit::Visit; pub struct NoRegexSpaces; impl LintRule for NoRegexSpaces { fn new() -> Box<Self> { Box::new(NoReg...
use super::Context; use super::LintRule; use crate::scopes::{ScopeManager, ScopeVisitor}; use swc_ecma_ast::{CallExpr, Expr, ExprOrSuper, Lit, NewExpr, Regex}; use swc_ecma_visit::Node; use swc_ecma_visit::Visit; pub struct NoRegexSpaces; impl LintRule for NoRegexSpaces { fn new() -> Box<Self> { Box::new(NoReg...
} pub struct NoRegexSpacesVisitor { context: Context, scope_manager: ScopeManager, } impl NoRegexSpacesVisitor { pub fn new(context: Context, scope_manager: ScopeManager) -> Self { Self { context, scope_manager, } } fn check_regex(&self, regex: &str) -> bool { lazy_static! { ...
fn lint_module(&self, context: Context, module: swc_ecma_ast::Module) { let mut scope_visitor = ScopeVisitor::new(); scope_visitor.visit_module(&module, &module); let scope_manager = scope_visitor.consume(); let mut visitor = NoRegexSpacesVisitor::new(context, scope_manager); visitor.visit_module(&m...
function_block-full_function
[ { "content": "pub fn assert_lint_ok<T: LintRule + 'static>(source: &str) {\n\n let rule = T::new();\n\n let diagnostics = lint(rule, source);\n\n if !diagnostics.is_empty() {\n\n panic!(\"Unexpected diagnostics: {:#?}\", diagnostics);\n\n }\n\n}\n\n\n", "file_path": "src/test_util.rs", "rank": 0,...
Rust
src/prolog/heap_iter.rs
GavinMendelGleason/scryer-prolog
9e54b1406c9982258f43234401ea29c8b45f44eb
use crate::prolog::machine::machine_indices::*; use crate::prolog::machine::machine_state::*; use indexmap::IndexSet; use std::cmp::Ordering; use std::ops::Deref; use std::vec::Vec; pub struct HCPreOrderIterator<'a> { pub machine_st: &'a MachineState, pub state_stack: Vec<Addr>, } impl<'a> HCPreOrderIterato...
use crate::prolog::machine::machine_indices::*; use crate::prolog::machine::machine_state::*; use indexmap::IndexSet; use std::cmp::Ordering; use std::ops::Deref; use std::vec::Vec; pub struct HCPreOrderIterator<'a> { pub machine_st: &'a MachineState, pub state_stack: Vec<Addr>, } impl<'a> HCPreOrderIterato...
; } } Addr::Con(h) } da => { da } } } } impl<'a> Iterator for HCPreOrderIterator<'a> { type Item = Addr; fn next(&mut self) -> Option<Self::Item> { self.state_stack.pop().map(|a| self.f...
if has_tail { self.follow(Addr::HeapCell(h + 1)) } else { Addr::EmptyList }
if_condition
[ { "content": "#[inline]\n\nfn functor_location(addr: &Addr) -> Option<usize> {\n\n Some(match addr {\n\n &Addr::Lis(l) => l,\n\n &Addr::Str(s) => s,\n\n &Addr::PStrLocation(h, _) => h,\n\n _ => {\n\n return None;\n\n }\n\n })\n\n}\n\n\n\nimpl<'a, Outputter: HC...
Rust
winapi-perf-wrapper/src/lib.rs
zaphar/win-utils
8215fc3b56cd083c7f4575e663f0469d51eb9e2d
use winapi::shared::minwindef::{DWORD, FALSE, TRUE}; use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::pdh::{ PDH_FMT_COUNTERVALUE_u, PdhAddCounterW, PdhCloseQuery, PdhCollectQueryData, PdhEnumObjectItemsW, PdhEnumObjectsW, PdhExpandCounterPathW, PdhGetFormattedCounterValue, PdhOpenQueryW, PdhR...
use winapi::shared::minwindef::{DWORD, FALSE, TRUE}; use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::pdh::{ PDH_FMT_COUNTERVALUE_u, PdhAddCounterW, PdhCloseQuery, PdhCollectQueryData, PdhEnumObjectItemsW, PdhEnumObjectsW, PdhExpandCounterPathW, PdhGetFormattedCounterValue, PdhOpenQueryW, PdhR...
unters(&mut self) -> Result<Vec<String>, PDHStatus> { let mut counter_path_vec = Vec::new(); let path_prefix = if let Some(ref machine_name) = self.machine_name { format!("\\\\{}", String::from_utf16_lossy(machine_name.as_slice())) } else { String::new() ...
utf16_lossy(v.as_slice())) .collect(), insts .drain(0..) .map(|v| String::from_utf16_lossy(v.as_slice())) .collect(), ) }) } pub fn enumerate_items_utf16( ...
random
[ { "content": "pub fn print_object_counters(pdh: &mut PDH, obj: &str) -> anyhow::Result<()> {\n\n println!(\"Counters for {}:\", obj);\n\n let (counters, instances) = pdh\n\n .enumerate_items_string(obj)\n\n .map_err(|s| constants::pdh_status_friendly_name(s))\n\n .unwrap();\n\n for...
Rust
a_2sat/src/lib.rs
Ninjani/rosalind
e22ecf2c9f0935d970b137684029957c0850d63f
use std::collections::{btree_map::BTreeMap, HashMap, HashSet}; use failure::Error; use utility; pub fn rosalind_2sat(filename: &str) -> Result<Vec<Option<Vec<isize>>>, Error> { let input = utility::io::input_from_file(filename)?; let mut lines = input .split('\n') .filter(|s| !s.trim().is_emp...
use std::collections::{btree_map::BTreeMap, HashMap, HashSet}; use failure::Error; use utility; pub fn rosalind_2sat(filename: &str) -> Result<Vec<Option<Vec<isize>>>, Error> { let input = utility::io::input_from_file(filename)?; let mut lines = input .split('\n') .filter(|s| !s.trim().is_emp...
for node_index in node_order { if !seen.contains(&graph.nodes[node_index]) { for c_node in &component_to_nodes[&graph.connected_components[node_index]] { if !seen.contains(c_node) { n_node = get_negated_node(*c_node); seen....
nected_components.iter().enumerate() { component_to_nodes .entry(component) .or_insert_with(Vec::new) .push(graph.nodes[i]); } let mut seen = HashSet::with_capacity(graph.num_nodes); let mut assignment = (0..graph.num_nodes).map(|_| fal...
random
[ { "content": "/// Read set of form:\n\n/// {n1, n2, n3, ... }\n\npub fn read_set(line: &str) -> Result<HashSet<usize>, Error> {\n\n let chars: Vec<_> = line.chars().collect();\n\n let line: String = chars[1..(line.len() - 1)].iter().collect();\n\n Ok(HashSet::from_iter(\n\n line.split(\", \")\n\...
Rust
src/font/hbwrap.rs
TimeToogo/wezterm
d36afd90ceb5c17e425f94e7a4d893df33a0cb62
#![allow(dead_code)] #[cfg(target_os = "macos")] use core_text::font::{CTFont, CTFontRef}; use freetype; pub use harfbuzz::*; use anyhow::{ensure, Error}; use std::mem; use std::ptr; use std::slice; extern "C" { fn hb_ft_font_set_load_flags(font: *mut hb_font_t, load_flags: i32); } #[cfg(windows)] extern "C" { ...
#![allow(dead_code)] #[cfg(target_os = "macos")] use core_text::font::{CTFont, CTFontRef}; use freetype; pub use harfbuzz::*; use anyhow::{ensure, Error}; use std::mem; use std::ptr; use std::slice; extern "C" { fn hb_ft_font_set_load_flags(font: *mut hb_font_t, load_flags: i32); } #[cfg(windows)] extern "C" { ...
}
pub fn glyph_positions(&self) -> &[hb_glyph_position_t] { unsafe { let mut len: u32 = 0; let pos = hb_buffer_get_glyph_positions(self.buf, &mut len as *mut _); slice::from_raw_parts(pos, len as usize) } }
function_block-full_function
[ { "content": "/// A convenience function that wraps Base91Decoder; it decodes a slice of data\n\n/// and returns a vector holding the unencoded binary data.\n\npub fn decode(buf: &[u8]) -> Vec<u8> {\n\n let mut result = Vec::with_capacity(buf.len());\n\n {\n\n let mut writer = Base91Decoder::new(&m...
Rust
crates/swc_ecma_transforms_optimization/src/simplify/const_propgation.rs
maxxcs/swc
a2a0b63c6297de039a5703a549eae62ae20b48c8
use swc_common::{collections::AHashMap, util::take::Take}; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, Id}; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; pub fn constant_propagation() -> impl 'static + Fold + VisitMut { as_folder(ConstPropagation::default()) } ...
use swc_common::{collections::AHashMap, util::take::Take}; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, Id}; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; pub fn constant_propagation() -> impl 'static + Fold + VisitMut { as_folder(ConstPropagation::default()) } ...
} impl VisitMut for ConstPropagation<'_> { noop_visit_mut_type!(); fn visit_mut_function(&mut self, n: &mut Function) { let scope = Scope::new(&self.scope); let mut v = ConstPropagation { scope }; n.visit_mut_children_with(&mut v); } fn visit_mut...
self, id: &Id) -> Option<&Box<Expr>> { if let Some(v) = self.vars.get(id) { return Some(v); } self.parent.and_then(|parent| parent.find_var(id)) }
function_block-function_prefixed
[]
Rust
mayastor/tests/yaml_config.rs
whoan/Mayastor
a541eebfd021d937d374b41f2b297224014ffe3b
use std::{fs::metadata, sync::Mutex, time::Duration}; use common::ms_exec::run_test; use mayastor::{subsys, subsys::Config}; pub mod common; #[test] fn yaml_default() { let args = vec!["-s".into(), "128".into()]; run_test(Box::from(args), |ms| { let out = ms .rpc_call("rpc_get_m...
use std::{fs::metadata, sync::Mutex, time::Duration}; use common::ms_exec::run_test; use mayastor::{subsys, subsys::Config}; pub mod common; #[test] fn yaml_default() { let args = vec!["-s".into(), "128".into()]; run_test(Box::from(args), |ms| { let out = ms .rpc_call("rpc_get_m...
#[test] fn yaml_load_from_existing() { let mut cfg = Config::default(); common::truncate_file("/tmp/disk1.img", 1024 * 64); let bdev = subsys::BaseBdev { uri: "aio:///tmp/disk1.img?blk_size=512&uuid=3dbbaeb0-ec02-4962-99c5-4e8f67c6b80c".to_string(), }; cfg.source = Some("/tmp/loadme.yam...
fn yaml_not_exist() { let args = vec![ "-s".to_string(), "128".into(), "-y".into(), "/tmp/test.yaml".into(), ]; common::delete_file(&["/tmp/test.yaml".into()]); run_test(Box::from(args), |ms| { let out = ms .rpc_call("mayastor_config_export", se...
function_block-full_function
[ { "content": "/// start mayastor as a separate process and run the closure. By wrapping the\n\n/// test closure, we can catch errors but still kill mayastor to avoid dangling\n\n/// process.\n\npub fn run_test<T>(args: Box<[String]>, test: T)\n\nwhere\n\n T: FnOnce(&MayastorProcess) + panic::UnwindSafe,\n\n{...
Rust
tests/integration_test.rs
Baawa/chiselstore
b1ab1dba568ab4aafe9f3e199a94f3f562560ed3
use chiselstore::rpc::proto::rpc_server::RpcServer; use chiselstore::{ rpc::{RpcService, RpcTransport}, StoreServer, }; use std::sync::Arc; use tonic::transport::Server; extern crate futures; use crate::futures::FutureExt; pub mod proto { tonic::include_proto!("proto"); } use proto::rpc_client::RpcClient; u...
use chiselstore::rpc::proto::rpc_server::RpcServer; use chiselstore::{ rpc::{RpcService, RpcTransport}, StoreServer, }; use std::sync::Arc; use tonic::transport::Server; extern crate futures; use crate::futures::FutureExt; pub mod proto { tonic::include_proto!("proto"); } use proto::rpc_client::RpcClient; u...
let mut replicas = setup_replicas(3).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test_follower_drop (id integer PRIMARY KEY)")).await.unwrap(); }).await.unwrap(); let mut follower_idx = 0; for (i, r) in replicas.iter()....
replicas = setup_replicas(3).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test_leader_drop (id integer PRIMARY KEY)")).await.unwrap(); }).await.unwrap(); let mut leader_idx = 0; for (i, r) in replicas.iter().enumerate() { if ...
random
[ { "content": "pub fn log(s: String) {\n\n let mut builder = TerminalLoggerBuilder::new();\n\n builder.level(Severity::Debug);\n\n builder.destination(Destination::Stderr);\n\n\n\n let logger = builder.build().unwrap();\n\n info!(logger, \"{}\", s);\n\n}\n", "file_path": "src/util/log.rs", ...
Rust
lib/tests/diff.rs
austinjones/texture-synthesis
52625c803523b659114d03ba0192bfb5c2905c07
use img_hash::{HashType, ImageHash}; use texture_synthesis as ts; use image::{imageops, DynamicImage, FilterType, GenericImageView, GrayImage, Pixel, RgbaImage}; use img_hash::HashImage; const FILTER_TYPE: FilterType = FilterType::Nearest; struct MyPrecious<T>(T); impl HashImage for MyPrecious<DynamicImage> { ty...
use img_hash::{HashType, ImageHash}; use texture_synthesis as ts; use image::{imageops, DynamicImage, FilterType, GenericImageView, GrayImage, Pixel, RgbaImage}; use img_hash::HashImage; const FILTER_TYPE: FilterType = FilterType::Nearest; struct MyPrecious<T>(T); impl HashImage for MyPrecious<DynamicImage> { ty...
.random_init(10) .seed(211) .output_size(100, 100) }); diff_hash!(guided, "JBQFEgoXm5KCiWZUfHHBhyYK", { ts::Session::builder() .add_example( ts::Example::builder(&"../imgs/2.jpg").with_guide(&"../imgs/masks/2_example.jpg"), ) .load_target_guide(&"../imgs/mask...
ld() .unwrap() .run(None); let gen_img = generated.into_image(); let gen_hash = ImageHash::hash(&MyPrecious(gen_img), 8, HashType::DoubleGradient); if gen_hash != expected_hash { let distance = expected_hash.dist_ratio(&gen_hash); ...
random
[ { "content": "#[derive(Clone, Copy, Debug, Default)]\n\nstruct PatchId(u32);\n", "file_path": "lib/src/multires_stochastic_texture_synthesis.rs", "rank": 0, "score": 78339.35903847126 }, { "content": "#[derive(Clone, Copy, Debug)]\n\nstruct CoordFlat(u32);\n\n\n\nimpl CoordFlat {\n\n fn t...
Rust
xtask/src/docgen/extract.rs
zaida04/RSLint
05c9939d16aa45b24c3acd222e31917d49ad301a
use proc_macro2::TokenStream; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::*; use unindent::unindent; pub fn parse_group_mod(file: &str) -> Result<Group> { let file = parse_file(file)?; for item in file.items.iter() { if let Item::Macro(macro_call) = item { ...
use proc_macro2::TokenStream; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::*; use unindent::unindent; pub fn parse_group_mod(file: &str) -> Result<Group> { let file = parse_file(file)?; for item in file.items.iter() { if let Item::Macro(macro_call) = item { ...
ests: Option<RuleTests>, } #[derive(Clone)] pub struct LintDeclaration { pub name: String, pub docstring: Option<String>, pub config_fields: Vec<ConfigField>, } #[derive(Clone)] pub struct ConfigField { pub docstring: Option<String>, pub field: Field, } impl Parse for LintDeclaration { fn par...
call.tokens); declaration = Some(res?); } else if call .path .segments .last() .map_or(false, |x| x.ident == "rule_tests") && tests.is_none() { tests = Some(parse2::<RuleTests>(call.to...
random
[]
Rust
cio/src/certs.rs
borisfaure/cio
b6eeb20b5b4bc8c3f3b7a3f6b679348c1a939481
use std::env; use std::fs; use std::path::{Path, PathBuf}; use std::str::from_utf8; use std::thread; use std::time; use acme_lib::create_p384_key; use acme_lib::persist::FilePersist; use acme_lib::{Directory, DirectoryUrl}; use async_trait::async_trait; use chrono::NaiveDate; use chrono::{DateTime, TimeZone, Utc}; use...
use std::env; use std::fs; use std::path::{Path, PathBuf}; use std::str::from_utf8; use std::thread; use std::time; use acme_lib::create_p384_key; use acme_lib::persist::FilePersist; use acme_lib::{Directory, DirectoryUrl}; use async_trait::async_trait; use chrono::NaiveDate; use chrono::{DateTime, TimeZone, Utc}; use...
#[instrument] #[inline] fn get_path(&self, dir: &str) -> PathBuf { Path::new(dir).join(self.domain.replace("*.", "wildcard.")) } #[instrument] #[inline] pub fn save_to_directory(&self, dir: &str) { let path = self.get_path(dir); fs::create_dir_all(pa...
let exp_date = self.expiration_date(); self.expiration_date = exp_date.date().naive_utc(); self.valid_days_left = self.valid_days_left(); } }
function_block-function_prefix_line
[]
Rust
capsules/src/ninedof.rs
x37v/tock
683d545b408864d58c6e84ae0536ac416dafa6d3
use core::cell::Cell; use kernel::{AppId, Callback, Container, Driver}; use kernel::ReturnCode; use kernel::hil; use kernel::process::Error; #[derive(Clone,Copy,PartialEq)] pub enum NineDofCommand { Exists, ReadAccelerometer, ReadMagnetometer, ReadGyroscope, } pub struct App { callback: Option<C...
use core::cell::Cell; use kernel::{AppId, Callback, Container, Driver}; use kernel::ReturnCode; use kernel::hil; use kernel::process::Error; #[derive(Clone,Copy,PartialEq)] pub enum NineDofCommand { Exists, ReadAccelerometer, ReadMagnetometer, ReadGyroscope, } pub struct App { callback: Option<C...
ReturnCode::SUCCESS, 1 => self.enqueue_command(NineDofCommand::ReadAccelerometer, arg1, appid), 100 => self.enqueue_command(NineDofCommand::ReadMagnetometer, arg1, appid), 200 => self.enqueue_command(NineDofCommand::ReadGyroscope, arg1, appi...
usize) -> ReturnCode { match command { NineDofCommand::ReadAccelerometer => self.driver.read_accelerometer(), NineDofCommand::ReadMagnetometer => self.driver.read_magnetometer(), NineDofCommand::ReadGyroscope => self.driver.read_gyroscope(), _ => ReturnCode::ENOSU...
random
[ { "content": "pub fn schedule(callback: FunctionCall, appid: AppId) -> bool {\n\n let procs = unsafe { &mut PROCS };\n\n let idx = appid.idx();\n\n if idx >= procs.len() {\n\n return false;\n\n }\n\n\n\n match procs[idx] {\n\n None => false,\n\n Some(ref mut p) => {\n\n ...
Rust
src/domain/runtime/type/remote_object/mod.rs
cloudflare/chrome-devtools-rs
d8fdf820d5337df1586fa0ff89b2bf420172522f
use std::fmt; pub mod r#type; use r#type::object::{ObjectPreview, Subtype}; use r#type::Type; use serde::{Deserialize, Serialize}; use unescape::unescape; use console::style; #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct RemoteObject { pub r#type: Type, pub s...
use std::fmt; pub mod r#type; use r#type::object::{ObjectPreview, Subtype}; use r#type::Type; use serde::{Deserialize, Serialize}; use unescape::unescape; use console::style; #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct RemoteObject { pub r#type: Type, pub s...
} impl fmt::Display for RemoteObject { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let formatted = match &self.r#type { Type::Undefined => { let mut disp = "undefined".to_string(); if cfg!(feature = "color") { disp = format!("{}", ...
fn display_object(&self) -> String { if let Some(preview) = &self.preview { preview.to_string() } else if let Some(subtype) = &self.subtype { if subtype.to_string() == "null" { let mut null = "null".to_string(); if cfg!(feature = "color") { ...
function_block-full_function
[ { "content": "use std::fmt;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\n/// Object subtype hint. Specified for the `object` [Type][crate::domain::runtime::type::remote_object::type::Type] values only\n\n#[derive(Debug, Serialize, Deserialize, Clone)]\n\n#[serde(rename_all = \"lowercase\")]\n\npub enum Su...
Rust
vendor/unicode-segmentation/src/sentence.rs
yilinhan/crates-io
eb259811db1316ec63d9dd01cda3d87e3b860ca0
use core::cmp; use core::iter::Filter; mod fwd { use tables::sentence::SentenceCat; use core::cmp; #[derive(Clone, Copy, PartialEq, Eq)] enum StatePart { Sot, Eot, Other, CR, LF, Sep, ATerm, UpperLower, ClosePlus, ...
use core::cmp; use core::iter::Filter; mod fwd { use tables::sentence::SentenceCat; use core::cmp; #[derive(Clone, Copy, PartialEq, Eq)] enum StatePart { Sot, Eot, Other, CR, LF, Sep, ATerm, UpperLower, ClosePlus, ...
eaks<'a>(source: &'a str) -> SentenceBreaks<'a> { SentenceBreaks { string: source, pos: 0, state: INITIAL_STATE } } } #[derive(Clone)] pub struct UnicodeSentences<'a> { inner: Filter<USentenceBounds<'a>, fn(&&str) -> bool>, } #[derive(Clone)] pub struct USentenceBounds<'a> { iter: fwd::SentenceBr...
match1(StatePart::Sot) { None } else if self.state.match1(StatePart::Eot) { None } else { self.state = self.state.end(); Some(self.pos) } } } pub fn new_sentence_br
random
[]
Rust
parallel-processor-rs/src/debug_allocator.rs
Guilucand/genome-assembly
a18ce27eab733a95de40276348f22277e83a565a
use dashmap::DashMap; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serde_json::to_string_pretty; use std::alloc::{GlobalAlloc, Layout, System}; use std::fs::File; use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::Duration; pub ...
use dashmap::DashMap; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serde_json::to_string_pretty; use std::alloc::{GlobalAlloc, Layout, System}; use std::fs::File; use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::Duration; pub ...
fn update_backtrace(ptr: *mut u8, new_ptr: *mut u8, diff: isize) { let (_, bt) = ADDRESSES_BACKTRACE.remove(&(ptr as usize)).unwrap(); let aref = ALLOCATION_INFOS.get(&bt).unwrap(); if diff > 0 { aref.current_size .fetch_add(diff as usize, Ordering::Relaxed); aref.max_size ...
Relaxed); info.current_size.fetch_add(size, Ordering::Relaxed); info.total_count.fetch_add(1, Ordering::Relaxed); info.max_size .fetch_max(info.current_size.load(Ordering::Relaxed), Ordering::Relaxed); }
function_block-function_prefixed
[ { "content": "#[inline(always)]\n\npub fn decode_varint(mut read_byte: impl FnMut() -> Option<u8>) -> Option<u64> {\n\n let mut result = 0;\n\n let mut offset = 0u32;\n\n loop {\n\n let value = read_byte()?;\n\n let next = (value & 0b10000000) != 0;\n\n result |= ((value & 0b111111...
Rust
crates/eosio_macros_internal/src/internal.rs
adsorptionenthalpy/eosio-rust
f21a1ce86c6d7456bd05b3106c5a89ae593a487d
use proc_macro2::{Span, TokenStream}; use quote::ToTokens; use std::fmt::{self, Display}; use syn::{ parse::{Error as ParseError, Result as ParseResult}, Attribute, Ident, Lit, LitStr, Meta, Meta::List, NestedMeta, Path, }; #[derive(Copy, Clone)] pub struct Symbol(&'static str); pub const EOSIO: Symbo...
use proc_macro2::{Span, TokenStream}; use quote::ToTokens; use std::fmt::{self, Display}; use syn::{ parse::{Error as ParseError, Result as ParseResult}, Attribute, Ident, Lit, LitStr, Meta, Meta::List, NestedMeta, Path, }; #[derive(Copy, Clone)] pub struct Symbol(&'static str); pub const EOSIO: Symbo...
pub struct Attr<T> { name: Symbol, tokens: TokenStream, value: Option<T>, } impl<T> Attr<T> { pub fn none(name: Symbol) -> Self { Self { name, tokens: TokenStream::new(), value: None, } } pub fn set<A: ToTokens>(&mut self, obj: A, value: T)...
pub fn get_root_path(attrs: &[Attribute]) -> Path { for meta_item in attrs.iter().flat_map(get_eosio_meta_items).flatten() { match meta_item { NestedMeta::Meta(Meta::NameValue(m)) if m.path == CRATE_PATH => { match m.lit { Lit::Str(string) => { ...
function_block-full_function
[ { "content": "pub fn set_abi(account: impl AsRef<str>, abi_path: impl AsRef<str>) {\n\n let account = account.as_ref();\n\n let abi_path = abi_path.as_ref();\n\n println!(\"set abi {} {}\", account, abi_path);\n\n cleos()\n\n .arg(\"set\")\n\n .arg(\"abi\")\n\n .arg(account)\n\n...
Rust
src/wand/macros.rs
Atul9/magick-rust
65ae47fbf83182257bd69a6e38ade3d29412361d
/* * Copyright 2016 Mattis Marjak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
/* * Copyright 2016 Mattis Marjak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
"null ptr returned by", stringify!($wand), "get_exception" )) } else { let c_str = unsafe { CStr::from_ptr(ptr) }; Ok((c_str.to_string_lossy().into_owned(), severity)) ...
::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!("failed to clear", stringify!($wand), "exception")), } } pub fn get_exception_type(&self) -> ::bindings::ExceptionType { unsafe { ::bindings::$get_exc_type(self.wand) } } ...
random
[ { "content": "pub fn magick_query_fonts(pattern: &str) -> Result<Vec<String>, &'static str> {\n\n let mut number_fonts: size_t = 0;\n\n let c_string =\n\n try!(::std::ffi::CString::new(pattern).map_err(|_| \"could not convert to cstring\"));\n\n let ptr =\n\n unsafe { bindings::MagickQuer...
Rust
program/src/state.rs
0xNico/noir-pay
8ef1e219c75ce96d900247497885efae3235f626
use arrayref::{array_mut_ref, array_ref, array_refs, mut_array_refs}; use solana_program::{ program_error::ProgramError, program_pack::{IsInitialized, Pack, Sealed}, pubkey::Pubkey, }; use std::convert::TryInto; #[derive(Clone)] pub struct ChecksAndTransferState { is_initialized: bool, pub found_ro...
use arrayref::{array_mut_ref, array_ref, array_refs, mut_array_refs}; use solana_program::{ program_error::ProgramError, program_pack::{IsInitialized, Pack, Sealed}, pubkey::Pubkey, }; use std::convert::TryInto; #[derive(Clone)] pub struct ChecksAndTransferState { is_initialized: bool, pub found_ro...
} } fn pack_into_slice(&self, _dst: &mut [u8]) {} }
Ok(InstructionIndex { is_initialized: true, signer_pubkey: solana_program::pubkey::Pubkey::new(signer_pubkey), current_instruction_index: usize::from_le_bytes(*current_instruction_index), })
call_expression
[]
Rust
src/lib.rs
Ekranos/simple-async-pipe
422347782b362beed5d6da1e52d2015312d632cd
use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TrySendError; pub struct PipeWrite { sender: mpsc::Sender<Vec<u8>>, shared: Arc<Mutex<PipeShared>>, } pub struct PipeR...
use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TrySendError; pub struct PipeWrite { sender: mpsc::Sender<Vec<u8>>, shared: Arc<Mutex<PipeShared>>, } pub struct PipeR...
if self.read_remaining.len() > 0 { self.read_remaining = write_to_buf(&mut self.read_remaining); return Poll::Ready(Ok(())); } match self.receiver.poll_recv(cx) { Poll::Ready(v) => match v { None => Poll::Ready(Err(std::io::Error::new( ...
let mut write_to_buf = |vec: &[u8]| -> Vec<u8> { let end = std::cmp::min(buf.remaining(), vec.len()); let slice_to_write = &vec[0..end]; buf.put_slice(slice_to_write); let rest_of_vec = &vec[end..]; rest_of_vec.to_vec() };
assignment_statement
[ { "content": "# simple-async-pipe\n\n\n\nAims to provide a simple pipe-like functionality for async code. Created to be used in\n\ntests. No performance optimization done.\n\n\n\n[Documentation](https://docs.rs/simple_async_pipe/)\n\n\n\n## License\n\n\n\nThis project is licensed under either of\n\n\n\n* Apache...
Rust
clippy_lints/src/copies.rs
g-bartoszek/rust-clippy
cefddf784373392768b84ebec7be4c697d0b029a
use crate::utils::{get_parent_expr, higher, in_macro_or_desugar, snippet, span_lint_and_then, span_note_and_lint}; use crate::utils::{SpanlessEq, SpanlessHash}; use rustc::hir::*; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; use rustc::ty::Ty; use rustc::{declare_lint_pass, declare_tool_lint}; use...
use crate::utils::{get_parent_expr, higher, in_macro_or_desugar, snippet, span_lint_and_then, span_note_and_lint}; use crate::utils::{SpanlessEq, SpanlessHash}; use rustc::hir::*; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; use rustc::ty::Ty; use rustc::{declare_lint_pass, declare_tool_lint}; use...
:default(); bindings_impl(cx, pat, &mut result); result } fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)> where Eq: Fn(&T, &T) -> bool, { for win in exprs.windows(2) { if eq(&win[0], &win[1]) { return Some((&win[0], &win[1])); } } None } fn ...
db.span_note( i.body.span, &format!( "`{}` has the same arm body as the `_` wildcard, consider removing it`", lhs ), ...
random
[ { "content": "fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {\n\n if arms.len() == 2\n\n && arms[0].pats.len() == 1\n\n && arms[0].guard.is_none()\n\n && arms[1].pats.len() == 1\n\n && arms[1].guard.is_none()\n\n {\n\n let arm_ref:...
Rust
types/src/unit_tests/canonical_serialization_examples.rs
egabrielsen/libra
773b9142b12504eabd28ce135dd2de4ee7e54126
use crate::{ access_path::AccessPath, account_address::AccountAddress, account_config::lbr_type_tag, transaction::{ChangeSet, RawTransaction, Script, TransactionArgument, TransactionPayload}, write_set::{WriteOp, WriteSet, WriteSetMut}, }; use lcs::to_bytes; use std::time::Duration; #[test] fn te...
use crate::{ access_path::AccessPath, account_address::AccountAddress, account_config::lbr_type_tag, transaction::{ChangeSet, RawTransaction, Script, TransactionArgument, TransactionPayload}, write_set::{WriteOp, WriteSet, WriteSetMut}, }; use lcs::to_bytes; use std::time::Duration; #[test] fn te...
#[test] fn test_write_set_canonical_serialization_example() { let input = get_common_write_set(); let expected_output = vec![ 0x02, 0xA7, 0x1D, 0x76, 0xFA, 0xA2, 0xD2, 0xD5, 0xC3, 0x22, 0x4E, 0xC3, 0xD4, 0x1D, 0xEB, 0x29, 0x39, 0x21, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x25,...
fn test_write_op_value_canonical_serialization_example() { let input = WriteOp::Value(vec![0xca, 0xfe, 0xd0, 0x0d]); let expected_output = vec![0x01, 0x04, 0xCA, 0xFE, 0xD0, 0x0D]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); }
function_block-full_function
[ { "content": "fn test_save_blocks_impl(input: Vec<(Vec<TransactionToCommit>, LedgerInfoWithSignatures)>) {\n\n let tmp_dir = TempPath::new();\n\n let db = LibraDB::new(&tmp_dir);\n\n\n\n let num_batches = input.len();\n\n let mut cur_ver = 0;\n\n for (batch_idx, (txns_to_commit, ledger_info_with_...
Rust
tokio-tls/src/lib.rs
swarmer/tokio
c15e01a09bd2a3f9ac8e720069ee4ecfc8a4815a
#![doc(html_root_url = "https://docs.rs/tokio-tls/0.3.0-alpha.6")] #![warn( missing_debug_implementations, missing_docs, rust_2018_idioms, unreachable_pub )] #![deny(intra_doc_link_resolution_failure)] #![doc(test( no_crate_inject, attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_v...
#![doc(html_root_url = "https://docs.rs/tokio-tls/0.3.0-alpha.6")] #![warn( missing_debug_implementations, missing_docs, rust_2018_idioms, unreachable_pub )] #![deny(intra_doc_link_resolution_failure)] #![doc(test( no_crate_inject, attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_v...
pub fn get_ref(&self) -> &S where S: AsyncRead + AsyncWrite + Unpin, { &self.0.get_ref().inner } pub fn get_mut(&mut self) -> &mut S where S: AsyncRead + AsyncWrite + Unpin, { &mut self.0.get_mut().inner } } impl<S> AsyncRead for TlsStream<S>...
x: &mut Context<'_>, f: F) -> R where F: FnOnce(&mut native_tls::TlsStream<AllowStd<S>>) -> R, AllowStd<S>: Read + Write, { self.0.get_mut().context = ctx as *mut _ as *mut (); let g = Guard(self); f(&mut (g.0).0) }
function_block-function_prefixed
[ { "content": "/// Run the provided closure with a `MockClock` that starts at the current time.\n\npub fn mock<F, R>(f: F) -> R\n\nwhere\n\n F: FnOnce(&mut Handle) -> R,\n\n{\n\n let mut mock = MockClock::new();\n\n mock.enter(f)\n\n}\n\n\n", "file_path": "tokio-test/src/clock.rs", "rank": 0, ...
Rust
near/oysterpack-smart-near/src/data/object.rs
oysterpack/oysterpack-smart
f2985636d7c035de06e319f7ac8bec92e1293362
use near_sdk::{ borsh::{BorshDeserialize, BorshSerialize}, env, }; use std::ops::{Deref, DerefMut}; use std::{fmt::Debug, hash::Hash}; #[derive(Clone, Debug, PartialEq)] pub struct Object<K, V>(K, V) where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + Bo...
use near_sdk::{ borsh::{BorshDeserialize, BorshSerialize}, env, }; use std::ops::{Deref, DerefMut}; use std::{fmt::Debug, hash::Hash}; #[derive(Clone, Debug, PartialEq)] pub struct Object<K, V>(K, V) where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + Bo...
}
fn crud() { let context = new_context("bob"); testing_env!(context); let data = Data::new(1, 2); assert!(!object_exists(data.key())); data.save(); assert!(object_exists(data.key())); let mut data2 = Data::load(data.key()).unwrap(); ...
function_block-full_function
[]
Rust
src/events/mod.rs
nthorne/rssnek
f877f5d1f4cc38ec22df1690e51d0566d57837c3
extern crate slog; use std::fmt::Debug; use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc; use slog::Logger; #[allow(dead_code)] pub struct Dispatcher<T> { channels: Vec<Sender<T>>, logger: slog::Logger, pub msg_tx: Sender<T>, msg_rx: Receiver<T>, } impl <T>Dispatcher<T> where ...
extern crate slog; use std::fmt::Debug; use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc; use slog::Logger; #[allow(dead_code)] pub struct Dispatcher<T> { channels: Vec<Sender<T>>, logger: slog::Logger, pub msg_tx: Sender<T>, msg_rx: Receiver<T>, } impl <T>Dispatcher<T> where ...
} } pub fn subscribe(&mut self, channel: Sender<T>) { info!(self.logger, "Adding subscriber"; "channel" => format!("{:?}", channel)); self.channels.push(channel); } } #[allow(unused_variables)] #[allow(dead_code)] #[cfg(test)] mod tests { extern crate slog; extern cr...
if let Ok(msg) = self.msg_rx.recv() { info!(self.logger, "Got message"; "msg" => format!("{:?}", msg)); let current_channels = self.channels.clone(); self.channels.clear(); for c in current_channels { if let Ok(_) = c.send(msg.clone()...
if_condition
[ { "content": "pub fn setup() -> slog::Logger {\n\n let file = File::create(\"rssnek.log\").expect(\"Could not open log file.\");\n\n let file_drain = slog_stream::stream(file, slog_json::default()).fuse();\n\n //let drain = slog_term::streamer().compact().build().fuse();\n\n Logger::root(file_drain,...
Rust
src/usbphy/rx_set.rs
conorpp/lpc55-pac
eb30d633de05113362de01095123d70c54e63ef4
#[doc = "Reader of register RX_SET"] pub type R = crate::R<u32, super::RX_SET>; #[doc = "Writer for register RX_SET"] pub type W = crate::W<u32, super::RX_SET>; #[doc = "Register RX_SET `reset()`'s with value 0"] impl crate::ResetValue for super::RX_SET { type Type = u32; #[inline(always)] fn reset_value() ...
#[doc = "Reader of register RX_SET"] pub type R = crate::R<u32, super::RX_SET>; #[doc = "Writer for register RX_SET"] pub type W = crate::W<u32, super::RX_SET>; #[doc = "Register RX_SET `reset()`'s with value 0"] impl crate::ResetValue for super::RX_SET { type Type = u32; #[inline(always)] fn reset_value() ...
#[doc = "Checks if the value of the field is `VALUE0`"] #[inline(always)] pub fn is_value0(&self) -> bool { *self == ENVADJ_A::VALUE0 } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { *self == ENVADJ_A::VALUE1 }...
1), 2 => Val(ENVADJ_A::VALUE2), 3 => Val(ENVADJ_A::VALUE3), i => Res(i), } }
function_block-function_prefixed
[]
Rust
core/tests/rocket.rs
CugeDe/rocket-config
23083728ea17e9b82d73807dbd98885899e99fb5
#![feature(decl_macro, proc_macro_hygiene)] #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_config; #[macro_use] extern crate serde_json; extern crate tempfile; use rocket::local::Client; use rocket_config::Factory as ConfigurationsFairing; use std::env; use std::fs::OpenOptions; use std::io::Resu...
#![feature(decl_macro, proc_macro_hygiene)] #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_config; #[macro_use] extern crate serde_json; extern crate tempfile; use rocket::local::Client; use rocket_config::Factory as ConfigurationsFairing; use std::env; use std::fs::OpenOptions; use std::io::Resu...
elete_temporary_file(temp_file: tempfile::NamedTempFile) { let _ = temp_file.close(); } fn create_temporary_directory(prefix: &str, suffix: &str, rand_bytes: usize, dest: &Path) -> Result<tempfile::TempDir> { tempfile::Builder::new() .prefix(prefix) .suffix(suffix) .rand_bytes(rand_...
tion!("diesel"); fn create_temporary_file(prefix: &str, suffix: &str, rand_bytes: usize, dest: &Path) -> Result<tempfile::NamedTempFile> { tempfile::Builder::new() .prefix(prefix) .suffix(suffix) .rand_bytes(rand_bytes) .tempfile_in(dest) } fn d
random
[ { "content": "# rocket-config\n\n\n\nrocket-config is a [Fairing](https://api.rocket.rs/v0.4/rocket/fairing/trait.Fairing.html)\n\ndesigned for Rocket, a web framework for Rust (nightly).\n\n\n\n```rust\n\n#![feature(proc_macro_hygiene)]\n\n\n\n#[macro_use] extern crate rocket;\n\nextern crate rocket_config;\n\...
Rust
src/structs/drawing/charts/legend.rs
MathNya/umya-spreadsheet
d9c8bb9919fe0b42733269fca5a81866a139fbcc
use super::LegendPosition; use super::Layout; use super::Overlay; use super::TextProperties; use writer::driver::*; use quick_xml::Reader; use quick_xml::events::{Event, BytesStart}; use quick_xml::Writer; use std::io::Cursor; #[derive(Default, Debug)] pub struct Legend { legend_position: LegendPosition, layou...
use super::LegendPosition; use super::Layout; use super::Overlay; use super::TextProperties; use writer::driver::*; use quick_xml::Reader; use quick_xml::events::{Event, BytesStart}; use quick_xml::Writer; use std::io::Cursor; #[derive(Default, Debug)] pub struct Legend { legend_position: LegendPosition, layou...
[], false); &self.legend_position.write_to(writer); match &self.layout { Some(v) => {v.write_to(writer);}, None => {} } &self.overlay.write_to(writer); match &self.text_properties { Some(v) => {v.write_to...
y: Overlay, text_properties: Option<TextProperties>, } impl Legend { pub fn get_legend_position(&self)-> &LegendPosition { &self.legend_position } pub fn get_legend_position_mut(&mut self)-> &mut LegendPosition { &mut self.legend_position } pub fn set_legend_position(&mut self...
random
[ { "content": "pub trait EnumTrait{\n\n fn get_value_string(&self)->&str;\n\n}\n", "file_path": "src/structs/enum_trait.rs", "rank": 0, "score": 100229.84228063838 }, { "content": "/// create new spreadsheet file.\n\n/// # Arguments\n\n/// # Return value\n\n/// * Spreadsheet structs object...
Rust
src/markdown/compound.rs
Canop/minimad
09b34e8f0173a777ec721bad1827f76b11e90ae0
use std::fmt::{self, Write}; #[derive(Clone, PartialEq, Eq, Hash)] pub struct Compound<'s> { pub src: &'s str, pub bold: bool, pub italic: bool, pub code: bool, pub strikeout: bool, } impl<'s> Compound<'s> { #[inline(always)] pub fn raw_str(src: &'s str) -> Compound<'s> { ...
use std::fmt::{self, Write}; #[derive(Clone, PartialEq, Eq, Hash)] pub struct Compound<'s> { pub src: &'s str, pub bold: bool, pub italic: bool, pub code: bool, pub strikeout: bool, } impl<'s> Compound<'s> { #[inline(always)] pub fn raw_str(src: &'s str) -> Compound<'s> { ...
italic: self.italic, code: self.code, strikeout: self.strikeout, }; self.src = &self.src[0..cut]; tail } #[inline(always)] pub fn raw_part(src: &'s str, start: usize, end: usize) -> Compound<'s> { Compound { src: &src[start..e...
elf.strikeout, } } #[inline(always)] pub fn sub_chars(&self, r_start: usize, r_end: usize) -> Compound<'s> { let mut rb_start = 0; let mut rb_end = 0; for (char_idx, (byte_idx, _)) in self.as_str().char_indices().enumerate() { if char...
random
[ { "content": "pub fn is_blank(s: &str) -> bool {\n\n s.chars().all(char::is_whitespace)\n\n}\n\n\n", "file_path": "src/clean.rs", "rank": 0, "score": 134340.7432941864 }, { "content": "/// count the number of '#' at start. Return 0 if they're\n\n/// not followed by a ' ' or if they're too...
Rust
src/sodium.rs
bob3000/thevault
8a60dc3a9aa892f1e16c820477bce97fb46c2c7a
use secstr::SecVec; use sodiumoxide::crypto::{pwhash, secretbox}; use std::io; use thiserror::Error; pub const HEADER_LEN: usize = 56; #[derive(Debug, Clone)] pub struct Crypto { key: secretbox::Key, nonce: secretbox::Nonce, salt: pwhash::Salt, } impl Crypto { pub async fn new_encrypter(password: &Se...
use secstr::SecVec; use sodiumoxide::crypto::{pwhash, secretbox}; use std::io; use thiserror::Error; pub const HEADER_LEN: usize = 56; #[derive(Debug, Clone)] pub struct Crypto { key: secretbox::Key, nonce: secretbox::Nonce, salt: pwhash::Salt, } impl Crypto { pub async fn new_encrypter(password: &Se...
}
let c = Crypto::new_encrypter(&password) .await .expect("error creating encrypter"); cipher_package.write_all(&c.header()).await.unwrap(); let ciphertext = c.encrypt(message.clone()).await; assert_ne!(&message.unsecure()[..], &ciphertext[..]); cipher_package ...
function_block-function_prefix_line
[ { "content": "// This function is searches for the encryption / decryption password on\n\n// different places in the following order:\n\n// 1. command line argument or environment variable\n\n// 2. password file\n\n// 3. read from TTY\n\npub fn get_password(\n\n password: &mut Option<String>,\n\n password...
Rust
src/fixed_heap.rs
rust-photogrammetry/hamming-queue
c7b7165ee000651a5323741fe7ec7d9a0192f766
#[derive(Clone, Debug)] pub struct FixedHammingHeap<T> { cap: usize, size: usize, worst: u32, distances: Vec<Vec<T>>, } impl<T> FixedHammingHeap<T> { pub fn new() -> Self { Self::default() } pub fn new_distances(distances: usize) -> Self { let mut s = Self::new(); ...
#[derive(Clone, Debug)] pub struct FixedHammingHeap<T> { cap: usize, size: usize, worst: u32, distances: Vec<Vec<T>>, } impl<T> FixedHammingHeap<T> { pub fn new() -> Self { Self::default() } pub fn new_distances(distances: usize) -> Self { let mut s = Self::new(); ...
} fn end(&self) -> usize { if self.at_cap() { self.worst as usize } else { self.distances.len() - 1 } } fn update_worst(&mut self) { self.worst = self.distances[0..=self.worst as usize] .iter() .rev() ...
if distance < self.worst { self.distances[distance as usize].push(item); self.remove_worst(); true } else { false }
if_condition
[ { "content": "/// ```\n\n/// use hamming_heap::HammingHeap;\n\n/// let mut candidates = HammingHeap::new_distances(129);\n\n/// candidates.push((0u128 ^ !0u128).count_ones(), ());\n\n/// ```\n\n#[derive(Clone, Debug)]\n\npub struct HammingHeap<T> {\n\n distances: Vec<Vec<T>>,\n\n best: u32,\n\n}\n\n\n\nim...
Rust
explorer/src/pages/mod.rs
trustfractal/protocol
f6ccaeddc88e6fd2edb33aa522efe0526dce952a
use actix_web::{error::*, *}; use block_pool::Pool; use ramhorns::{Content, Ramhorns}; use std::collections::BTreeMap; use crate::data::*; pub fn resources() -> Vec<Resource> { vec![ web::resource("/").to(home), web::resource("/metrics/identities").to(metrics_identities), ] } pub fn templates...
use actix_web::{error::*, *}; use block_pool::Pool; use ramhorns::{Content, Ramhorns}; use std::collections::BTreeMap; use crate::data::*; pub fn resources() -> Vec<Resource> { vec![ web::resource("/").to(home), web::resource("/metrics/identities").to(metrics_identities), ] } pub fn templates...
fn get_home_data(pg: &mut postgres::Client) -> anyhow::Result<HomeData> { let blocks = pg .query( "SELECT json FROM block_json ORDER BY number DESC LIMIT 20", &[], )? .into_iter() .map(|row| serde_json::from_str(row.get(&"json"))) .collect::<Result<_, ...
function_block-full_function
[ { "content": "fn get_key(key: impl AsRef<str>, pg: &mut Client) -> anyhow::Result<Option<String>> {\n\n Ok(pg\n\n .query_opt(\n\n \"SELECT value FROM key_values WHERE key = $1\",\n\n &[&key.as_ref()],\n\n )?\n\n .map(|row| row.get::<_, &str>(&\"value\").to_string())...
Rust
core/src/parse/error.rs
bharadwaj1098/yatima
639e17d9644b89d27fd75be98ecb7dac91bb9e3b
use crate::{ name::Name, parse::{ base, span::Span, }, term::{ LitType, Literal, }, }; use nom::{ error::ErrorKind, AsBytes, Err, IResult, InputLength, }; #[cfg(feature = "std")] use std::{ cmp::Ordering, fmt, fmt::Write, num::ParseIntError, vec::Vec, }; #[cfg(not(feature...
use crate::{ name::Name, parse::{ base, span::Span, }, term::{ LitType, Literal, }, }; use nom::{ error::ErrorKind, AsBytes, Err, IResult, InputLength, }; #[cfg(feature = "std")] use std::{ cmp::Ordering, fmt, fmt::Write, num::ParseIntError, vec::Vec, }; #[cfg(not(feature...
I>> { match x { Ok(res) => Ok(res), Err(Err::Incomplete(n)) => Err(Err::Incomplete(n)), Err(Err::Error(e)) => Err(Err::Error(f(e))), Err(Err::Failure(e)) => Err(Err::Failure(f(e))), } }
function_block-function_prefixed
[ { "content": "pub fn is_valid_symbol_string(s: &str) -> bool {\n\n let invalid_chars = s.starts_with('\"')\n\n || s.starts_with('\\'')\n\n || s.starts_with('#')\n\n || s.chars().any(|x| !is_valid_symbol_char(x));\n\n !s.is_empty() && !invalid_chars\n\n}\n\n\n", "file_path": "core/src/parse/term.r...
Rust
lib/tracing-metrics/examples/echo.rs
sudharsh/vector
8b61656965f630582187a18e04d0812484ad9196
extern crate futures; extern crate hyper; #[macro_use] extern crate tracing; extern crate tokio; extern crate tracing_fmt; extern crate tracing_futures; use futures::future; use hyper::rt::{Future, Stream}; use hyper::server::conn::Http; use hyper::service::service_fn; use hyper::{Body, Method, Request, Response, Stat...
extern crate futures; extern crate hyper; #[macro_use] extern crate tracing; extern crate tokio; extern crate tracing_fmt; extern crate tracing_futures; use futures::future; use hyper::rt::{Future, Stream}; use hyper::server::conn::Http; use hyper::service::service_fn; use hyper::{Body, Method, Request, Response, Stat...
fn main() { use hotmic::Receiver; let mut receiver = Receiver::builder().build(); let sink = receiver.get_sink(); let controller = receiver.get_controller(); std::thread::spawn(move || { receiver.run(); }); std::thread::spawn(move || loop { std::thread::sleep(std::time::D...
fn echo(req: Request<Body>) -> Instrumented<BoxFut> { trace_span!( "request", method = &field::debug(req.method()), uri = &field::debug(req.uri()), headers = &field::debug(req.headers()) ) .in_scope(|| { info!("received request"); let mut response = Response::...
function_block-full_function
[ { "content": "type Error = Box<std::error::Error + 'static + Send + Sync>;\n\n\n\nimpl<T, S, B> Sink for BatchServiceSink<T, S, B>\n\nwhere\n\n S: Service<T>,\n\n S::Error: Into<Error>,\n\n S::Response: std::fmt::Debug,\n\n B: Batch<Output = T>,\n\n{\n\n type SinkItem = B;\n\n type SinkError =...
Rust
aorist_core/src/driver/python.rs
scie-nz/aorist
ac1e31251af7d851c4491a310b417de880b79d09
use abi_stable::std_types::ROption; use aorist_primitives::AOption; use crate::constraint::TConstraintEnum; use crate::constraint::{OuterConstraint, TBuilder}; use crate::constraint_state::ConstraintState; use aorist_primitives::Dialect; use crate::driver::{ConstraintsBlockMap, Driver}; use crate::flow::{ETLFlow, Flow...
use abi_stable::std_types::ROption; use aorist_primitives::AOption; use crate::constraint::TConstraintEnum; use crate::constraint::{OuterConstraint, TBuilder}; use crate::constraint_state::ConstraintState; use aorist_primitives::Dialect; use crate::driver::{ConstraintsBlockMap, Driver}; use crate::flow::{ETLFlow, Flow...
) .filter(|x| x.is_some()) .map(|x| x.unwrap().into_iter()) .flatten() .collect::<BTreeSet<AString>>() .into_iter() .collect() } fn _new( concepts: RArc<RRwLock<HashMap<(AUuid, AString), C>>>, constraints: LinkedHashMap<(AUu...
match x.read().get_dialect() { AOption(ROption::RSome(Dialect::Python(x))) => { AOption(ROption::RSome(x.get_pip_requirements())) } _ => AOption(ROption::RNone), }
if_condition
[ { "content": "pub trait Driver<'a, B, D, U, C, A, P>\n\nwhere\n\n U: AoristConcept + AoristUniverse,\n\n B: TBuilder<'a, TEnum = C, TAncestry = A>,\n\n D: FlowBuilderBase<U>,\n\n D: FlowBuilderMaterialize<\n\n U,\n\n BuilderInputType = <Self::CB as ConstraintBlock<\n\n 'a,\n...
Rust
examples/modbus-rtu.rs
slowtec/truebner-smt100
d74864043564c907ba581f8e8d1bc6878f955203
#[cfg(feature = "modbus-rtu")] pub fn main() { use chrono::{DateTime, Utc}; use env_logger::Builder as LoggerBuilder; use futures::{future::Either, Future, Stream}; use std::{cell::RefCell, env, io::Error, rc::Rc, time::Duration}; use stream_cancel::{StreamExt, Tripwire}; use tokio::timer::Inter...
#[cfg(feature = "modbus-rtu")] pub fn main() { use chrono::{DateTime, Utc}; use env_logger::Builder as LoggerBuilder; use futures::{future::Either, Future, Stream}; use std::{cell::RefCell, env, io::Error, rc::Rc, time::Duration}; use stream_cancel::{StreamExt, Tripwire}; use tokio::timer::Inter...
pub fn broadcast_slave(&self) -> impl Future<Item = (), Error = Error> { self.proxy.broadcast_slave() } } log::info!("Connecting: {:?}", context_config); let ctrl_loop = ControlLoop::new(slave_config, Box::new(context_config)); core.run(ctrl_loop.reconnect()).unwrap(); ...
pub fn recover_after_error(&self, err: &Error) -> impl Future<Item = (), Error = ()> { log::warn!( "Reconnecting after error: {}", err ); self.reconnect().or_else(|err| { log::error!( "Failed to reconnect: {}", ...
function_block-function_prefix_line
[ { "content": "pub fn read_permittivity_with_timeout(\n\n context: &mut client::Context,\n\n timeout: Duration,\n\n) -> impl Future<Item = RelativePermittivity, Error = Error> {\n\n read_permittivity(context)\n\n .timeout(timeout)\n\n .map_err(move |err| {\n\n err.into_inner().u...
Rust
src/mutable_linked_list.rs
marcianx/data-structures-rs
767cdc5827bbb91b6e225e292d8ac17dbc9c1f56
use std::iter::IntoIterator; pub struct List<T> { head: Link<T>, } type Link<T> = Option<Box<Node<T>>>; struct Node<T> { elem: T, next: Link<T>, } impl<T> List<T> { pub fn new() -> Self { List { head: None } } pub fn push(&mut self, elem: T) { self.head = Some(Box::new(...
use std::iter::IntoIterator; pub struct List<T> { head: Link<T>, } type Link<T> = Option<Box<Node<T>>>; struct Node<T> { elem: T, next: Link<T>, } impl<T> List<T> { pub fn new() -> Self { List { head: None } } pub fn push(&mut self, elem: T) { self.head = Some(Box::new(...
ntoIter = IterMut<'a, T>; fn into_iter(self) -> IterMut<'a, T> { self.iter_mut() } } #[cfg(test)] mod test { use super::List; #[test] fn test_push_pop() { let mut list = List::new(); list.push(1); assert_eq!(Some(&1), list.peek()); list.push(2); ass...
> { ListIntoIterator { list: self } } } impl<'a, T> IntoIterator for &'a List<T> { type Item = &'a T; type IntoIter = Iter<'a, T>; fn into_iter(self) -> Iter<'a, T> { self.iter() } } impl<'a, T> IntoIterator for &'a mut List<T> { type Item = &'a mut T; type I
random
[ { "content": "struct Node<T> {\n\n elem: T,\n\n next: Link<T>,\n\n}\n\n\n\nimpl<T> List<T> {\n\n pub fn new() -> Self {\n\n List { head: None }\n\n }\n\n\n\n pub fn prepend(&self, elem: T) -> List<T> {\n\n List { head: Some(Rc::new(Node { elem: elem, next: self.head.clone() })) }\n\...
Rust
crates/core_text/src/rasterizer.rs
ericrobolson/realtime-cpu-raytracer
3d759f2b8a00bf876ab24d2375716c63f5ed0134
use core_img::Rgba8Image; use core_fs::load; use rusttype::{point, Font, Scale, VMetrics}; use std::{borrow::Borrow, collections::HashMap}; pub struct TextRasterizer<'a> { fonts: HashMap<(&'static str, u32), FontRecord<'a>>, debug_save_rasters: bool, } struct FontRecord<'a> { font: Font<'a>, font_siz...
use core_img::Rgba8Image; use core_fs::load; use rusttype::{point, Font, Scale, VMetrics}; use std::{borrow::Borrow, collections::HashMap}; pub struct TextRasterizer<'a> { fonts: HashMap<(&'static str, u32), FontRecord<'a>>, debug_save_rasters: bool, } struct FontRecord<'a> { font: Font<'a>, font_siz...
.ascent)); let height = font_record.glyph_height; let mut min_x = u32::MAX; let mut max_x = 0; let mut min_y = u32::MAX; let mut max_y = 0; let (img_width, img_height) = (font_size, height); let is_whitespace = c.is_whitespace() || match glyph.pixe...
PartialEq)] pub struct CharacterRecord { pub c: char, pub width: u32, pub height: u32, } impl<'a> TextRasterizer<'a> { pub fn new(debug_save_rasters: bool) -> Self { Self { debug_save_rasters, fonts: HashMap::new(), } } pub fn load_font(&mut self, font_...
random
[ { "content": "pub fn build<Sim, Cfg, Msg>(title: &'static str, w: u32, h: u32) -> impl WinGfx<Sim, Cfg, Msg>\n\nwhere\n\n Sim: Simulation<Cfg, Msg> + 'static,\n\n Cfg: 'static,\n\n Msg: 'static,\n\n{\n\n OpenGlWindow::new(title, w, h)\n\n}\n", "file_path": "crates/core_wingfx/src/wingfx.rs", ...
Rust
src/spriteanimationloader.rs
neosam/sprite-game
5d261eb538824ebb133833a4f4fe4f162aa3445c
use amethyst::{ assets::{AssetStorage, Loader}, config::Config, prelude::*, renderer::{ImageFormat, Sprite, SpriteSheet, /*SpriteSheetHandle,*/ Texture, /*TextureMetadata*/ sprite::SpriteSheetHandle, SpriteRender, }, }; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collec...
use amethyst::{ assets::{AssetStorage, Loader}, config::Config, prelude::*, renderer::{ImageFormat, Sprite, SpriteSheet, /*SpriteSheetHandle,*/ Texture, /*TextureMetadata*/ sprite::SpriteSheetHandle, SpriteRender, }, }; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collec...
} pub struct SpriteAnimationStore { pub sprite_sheet_handle: SpriteSheetHandle, pub animations: BTreeMap<String, Vec<usize>>, pub images: BTreeMap<String, usize>, } impl SpriteAnimationStore { pub fn get_sprite_render(&self, name: &str) -> Option<SpriteRender> { self.images.get(name) ...
ure_path: String::new(), texture_width: 0, texture_height: 0, sprites: Vec::new(), animations: BTreeMap::new(), images: BTreeMap::new(), } }
function_block-function_prefixed
[ { "content": "fn build_map(width: usize, height: usize) -> map::Map<room::Room> {\n\n /*let mut map = map::Map::new();\n\n\n\n let mut room_generation1 = room::RoomGeneration::default();\n\n room_generation1.width = width;\n\n room_generation1.height = height;\n\n room_generation1.exit_east = tru...
Rust
memeroute-gui/src/pcb/pcb_view.rs
Edgeworth/memeroute
97e3443ab8e450150bcd84d6af96d70d224ba12c
use std::lazy::SyncLazy; use eframe::egui::epaint::{Mesh, TessellationOptions, Tessellator}; use eframe::egui::{epaint, Color32, Context, PointerButton, Response, Sense, Ui, Widget}; use memegeom::primitive::point::Pt; use memegeom::primitive::rect::Rt; use memegeom::primitive::shape::Shape; use memegeom::primitive::{...
use std::lazy::SyncLazy; use eframe::egui::epaint::{Mesh, TessellationOptions, Tessellator}; use eframe::egui::{epaint, Color32, Context, PointerButton, Response, Sense, Ui, Widget}; use memegeom::primitive::point::Pt; use memegeom::primitive::rect::Rt; use memegeom::primitive::shape::Shape; use memegeom::primitive::{...
let tf = tf * v.tf(); for outline in &v.outlines { let idx = outline.layers.first().unwrap(); shapes.extend(Self::draw_shape(&tf, outline, OUTLINE[idx])); } for keepout in &v.keepouts { shapes.extend(Self::draw_keepout(&tf, keepout, *KEEPOUT)); ...
: Rt, local_area: Rt, offset: Pt, zoom: f64, dirty: bool, mesh: Mesh, } impl Widget for &mut PcbView { fn ui(self, ui: &mut Ui) -> Response { let (response, painter) = ui.allocate_painter(ui.available_size_before_wrap(), Sense::click_and_drag()); if response.dragged...
random
[ { "content": "#[must_use]\n\npub fn to_pt(p: Pos2) -> Pt {\n\n pt(p.x as f64, p.y as f64)\n\n}\n\n\n", "file_path": "memeroute-gui/src/pcb/mod.rs", "rank": 0, "score": 104123.93811878798 }, { "content": "pub fn fill_polygon(tf: &Tf, pts: &[Pt], tris: &[u32], col: Color32) -> epaint::Shape...
Rust
spotify_player/src/state/ui.rs
aome510/spotify-player
15a8e2d88d06c0f96f54cec864ccfd9a4f889b06
use super::model::*; use crate::{config, key, utils}; use tui::widgets::*; pub type UIStateGuard<'a> = parking_lot::MutexGuard<'a, UIState>; #[derive(Debug)] pub struct UIState { pub is_running: bool, pub theme: config::Theme, pub input_key_sequence: key::KeySequence, pub history: Vec<PageState>, ...
use super::model::*; use crate::{config, key, utils}; use tui::widgets::*; pub type UIStateGuard<'a> = parking_lot::MutexGuard<'a, UIState>; #[derive(Debug)] pub struct UIState { pub is_running: bool, pub theme: config::Theme, pub input_key_sequence: key::KeySequence, pub history: Vec<PageState>, ...
pub fn list_state_mut(&mut self) -> Option<&mut ListState> { match self { Self::DeviceList(list_state) => Some(list_state), Self::UserPlaylistList(.., list_state) => Some(list_state), Self::UserFollowedArtistList(list_state) => Some(list_state), Self::U...
e), Self::UserPlaylistList(.., list_state) => Some(list_state), Self::UserFollowedArtistList(list_state) => Some(list_state), Self::UserSavedAlbumList(list_state) => Some(list_state), Self::ArtistList(.., list_state) => Some(list_state), Self::ThemeList(.., li...
function_block-function_prefixed
[ { "content": "/// truncates a string whose length exceeds a given `max_len` length.\n\n/// Such string will be appended with `...` at the end.\n\npub fn truncate_string(s: String, max_len: usize) -> String {\n\n let len = UnicodeWidthStr::width(s.as_str());\n\n if len > max_len {\n\n // get the lon...
Rust
src/main.rs
sambuc/mercator_data_generator
67d20946525542eba29ad4eca36dc808b7363ce8
#![forbid(unsafe_code)] use std::fs::File; use std::io::BufWriter; use mercator_db::storage::model::v1::Shape; use mercator_db::storage::model::*; use rand::distributions::Distribution; use rand::distributions::Uniform; use rand::prelude::ThreadRng; use serde::Serialize; use structopt::StructOpt; const POSITIONS_PER...
#![forbid(unsafe_code)] use std::fs::File; use std::io::BufWriter; use mercator_db::storage::model::v1::Shape; use mercator_db::storage::model::*; use rand::distributions::Distribution; use rand::distributions::Uniform; use rand::prelude::ThreadRng; use serde::Serialize; use structopt::StructOpt; const POSITIONS_PER...
#[derive(StructOpt, Debug)] struct Opt { #[structopt(long, short)] factor: Option<usize>, datasets: Vec<usize>, } fn main() { let opt = Opt::from_args(); let factor = match opt.factor { None => 1, Some(val) => val, }; let mut rng = rand::thread_rng(); let ...
e(), ); for _ in 0..nb_points { objects.append(&mut generate_points(factor, &space_name, rng, &die)); } store(format!("{}k.objects", nb_points).as_str(), objects); }
function_block-function_prefixed
[ { "content": "# Mercator Test data generator\n\n\n\nTool to generate test data for Mercator, a spatial index.\n\n\n\n## Mercator: Spatial Index\n\n\n\n**Mercator** is a spatial *volumetric* index for the [Human Brain Project](http://www.humanbrainproject.eu). It is a component of the [Knowledge Graph](http://ww...
Rust
src/ws.rs
jnicholls/binance-api
0093f8dd053c91de988c33597e485093f70d3db2
use std::collections::BTreeMap; use std::marker::{PhantomData, Unpin}; use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use std::time::Duration; use async_tungstenite::{ tokio::{connect_async, ConnectStream}, tungstenite::Message, WebSocketStream, }; use futures::{ future...
use std::collections::BTreeMap; use std::marker::{PhantomData, Unpin}; use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use std::time::Duration; use async_tungstenite::{ tokio::{connect_async, ConnectStream}, tungstenite::Message, WebSocketStream, }; use futures::{ future...
} async fn send_request(&self, mut req: WSRequest) -> Result<WSResponse, WSApiCode> { let timeout = req.timeout; let (tx, rx) = oneshot::channel(); { let mut state = self.state.lock().unwrap(); if state.is_closed { return Err(Error::WebsocketClos...
Ok(( Self { close_tx, request_tx, state, _marker: PhantomData, }, WSClientStream(event_rx), ))
call_expression
[ { "content": "pub trait TradeApi {\n\n type OrderRequestDetails: Serialize;\n\n type OrderDetails: DeserializeOwned;\n\n type OrderType: DeserializeOwned + Serialize;\n\n\n\n fn all_orders() -> &'static str;\n\n fn all_open_orders() -> &'static str;\n\n fn auto_cancel_all() -> &'static str;\n\...
Rust
src/days/aoc_2022.rs
Measter/AdventOfCode2020
e5c3f7f368b5df9f536a5c8740be0ea004b8ee7e
use std::{ collections::{HashSet, VecDeque}, num::ParseIntError, }; use aoc_lib::{day, parsers::split_pair, Bench, BenchResult, UserError}; use color_eyre::{eyre::Result, Report}; day! { day 22: "Crab Combat" 1: run_part1 2: run_part2 } fn run_part1(input: &str, b: Bench) -> BenchResult { let...
use std::{ collections::{HashSet, VecDeque}, num::ParseIntError, }; use aoc_lib::{day, parsers::split_pair, Bench, BenchResult, UserError}; use color_eyre::{eyre::Result, Report}; day! { day 22: "Crab Combat" 1: run_part1 2: run_part2 } fn run_part1(input: &str, b: Bench) -> BenchResult { let...
#[cfg(test)] mod tests_2022 { use aoc_lib::Example; use super::*; #[test] fn part1_example() { let input = aoc_lib::input(2020, 22) .example(Example::Part1, 1) .open() .unwrap(); let (player1, player2) = parse_input(&input).unwrap(); let e...
deck.len() && p2_card as usize <= p2_deck.len() { let p1_new_deck = p1_deck.iter().copied().take(p1_card as usize).collect(); let p2_new_deck = p2_deck.iter().copied().take(p2_card as usize).collect(); play_part2(p1_new_deck, p2_new_deck)?.0 } else if p1_card >= p2_card { ...
function_block-function_prefixed
[ { "content": "fn run_part2(input: &str, b: Bench) -> BenchResult {\n\n let floor = WaitingArea::parse(input).map_err(UserError)?;\n\n\n\n b.bench(|| {\n\n let mut floor = floor.clone();\n\n floor.run(WaitingArea::count_neighbours_part2, 5);\n\n Ok::<_, NoError>(floor.occupied_seats())...
Rust
src/day_7.rs
jacobguenther/advent_of_code_2020
c1e4ea46e106b9845b9a30ec9240c7527ec5fd11
/* Copyright 2020 Jacob Guenther Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, su...
/* Copyright 2020 Jacob Guenther Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, su...
fn count_bags_in(current: &str, bags: &HashMap<&str, Vec<(&str, u32)>>) -> u32 { let mut count = 0; for (bag_color, bags_in_bag) in bags.get(current).unwrap() { count += bags_in_bag + bags_in_bag * count_bags_in(&bag_color, bags); } count } #[cfg(test)] mod tests { use super::Challenge; use crate::common::Cha...
e == "shiny gold"); if current_contains_gold { true } else { for (bag, _) in current_info { if contains_gold(*bag, bags, cache) { cache.insert(*bag, true); return true; } else { cache.insert(*bag, false); } } false } }
function_block-function_prefixed
[ { "content": "fn parse_line(line: &str) -> (u16, u16, u8, &str) {\n\n\tlet mut min: u16 = 0;\n\n\tlet mut max: u16 = 0;\n\n\tlet mut letter = b' ';\n\n\tlet mut password = \"\";\n\n\tline.split(&['-', ' '][..])\n\n\t\t.enumerate()\n\n\t\t.for_each(|(i, s)| match i {\n\n\t\t\t0 => min = s.parse().unwrap(),\n\n\t...
Rust
crates/stun-types/src/parse.rs
kbalt/ezk
6886981a5d13954fb8536cf69d83b147551fd55c
use crate::attributes::{Attribute, Fingerprint, MessageIntegrity, MessageIntegritySha256}; use crate::header::{Class, MessageHead, MessageId, Method}; use crate::{padding_usize, Error, COOKIE, NE}; use byteorder::ReadBytesExt; use bytes::Buf; use std::convert::TryFrom; use std::io::Cursor; #[derive(Debug, Clone, Copy)...
use crate::attributes::{Attribute, Fingerprint, MessageIntegrity, MessageIntegritySha256}; use crate::header::{Class, MessageHead, MessageId, Method}; use crate::{padding_usize, Error, COOKIE, NE}; use byteorder::ReadBytesExt; use bytes::Buf; use std::convert::TryFrom; use std::io::Cursor; #[derive(Debug, Clone, Copy)...
fn set_msg_len(&mut self, len: u16) { self.head.set_len(len); let [b0, b1, b2, b3] = u32::to_ne_bytes(self.head.0); self.buffer[0] = b3; self.buffer[1] = b2; self.buffer[2] = b1; self.buffer[3] = b0; } pub fn with_msg_len<F, R>(&mut self, len: u16, f: F) ...
ha256::TYPE | Fingerprint::TYPE) { return None; } if attr.typ == A::TYPE { return Some(A::decode(ctx, self, attr)); } else if matches!( attr.typ, MessageIntegrity::TYPE | Me...
function_block-function_prefixed
[ { "content": "fn encode_addr(addr: SocketAddr, buf: &mut Vec<u8>, xor16: u16, xor32: u32, xor128: u128) {\n\n buf.put_u8(0);\n\n\n\n match addr {\n\n SocketAddr::V4(addr) => {\n\n buf.put_u8(1);\n\n buf.put_u16(addr.port() ^ xor16);\n\n\n\n let ip = u32::from_ne_byt...
Rust
src/components/axis.rs
HaKr/rustplotlib
09d907976a5930b44ba2cc9cc941500c088d765c
use svg::node::element::{Group, Line}; use svg::node::Text as TextNode; use svg::node::element::Text; use svg::Node; use format_num::NumberFormat; use crate::axis::AxisPosition; pub(crate) struct AxisLine { x1: f32, y1: f32, x2: f32, y2: f32, } impl AxisLine { pub fn new(x1: f32, y1: f32, x2:...
use svg::node::element::{Group, Line}; use svg::node::Text as TextNode; use svg::node::element::Text; use svg::Node; use format_num::NumberFormat; use crate::axis::AxisPosition; pub(crate) struct AxisLine { x1: f32, y1: f32, x2: f32, y2: f32, } impl AxisLine { pub fn new(x1: f32, y1: f32, x2:...
} pub struct AxisTick { axis_position: AxisPosition, label_offset: usize, label_rotation: isize, tick_offset: f32, label: String, label_format: Option<String> } impl AxisTick { pub fn new(tick_offset: f32, label_offset: usize, label_rotation: isize, label: String, axis_position: Axis...
pub fn to_svg(&self) -> Result<Line, String> { let line = Line::new() .set("x1", self.x1) .set("y1", self.y1) .set("x2", self.x2) .set("y2", self.y2) .set("shape-rendering", "crispEdges") .set("stroke-width", 1) .set("stroke", "...
function_block-full_function
[ { "content": "#[derive(Default)]\n\nstruct BarLabel {\n\n key: usize,\n\n label: String,\n\n}\n\n\n\nimpl From<usize> for BarLabel {\n\n fn from(key: usize) -> Self {\n\n BarLabel {\n\n key,\n\n label: format!(\"{}\", key),\n\n }\n\n }\n\n}\n\n\n\nimpl<D: Display>...
Rust
src/simples3/s3.rs
kingli-crypto/sccache
549cfd405b8bc23a128ccb2a0e9df1b3c13a092b
#[allow(unused_imports, deprecated)] use std::ascii::AsciiExt; use std::fmt; use crate::simples3::credential::*; use futures::{Future, Stream}; use hmac::{Hmac, Mac, NewMac}; use hyper::header::HeaderValue; use hyper::Method; use hyperx::header; use reqwest::r#async::{Client, Request}; use sha1::Sha1; use crate::er...
#[allow(unused_imports, deprecated)] use std::ascii::AsciiExt; use std::fmt; use crate::simples3::credential::*; use futures::{Future, Stream}; use hmac::{Hmac, Mac, NewMac}; use hyper::header::HeaderValue; use hyper::Method; use hyperx::header; use reqwest::r#async::{Client, Request}; use sha1::Sha1; use crate::er...
now().to_rfc7231(); let auth = self.auth("GET", &date, key, "", &canonical_headers, "", creds); request.headers_mut().insert( "Date", HeaderValue::from_str(&date).expect("Invalid date header"), ); request.headers_mut().insert( ...
o_vec() } fn signature(string_to_sign: &str, signing_key: &str) -> String { let s = hmac(signing_key.as_bytes(), string_to_sign.as_bytes()); base64::encode_config(&s, base64::STANDARD) } pub struct Bucket { name: String, base_url: String, client: Client, } impl fmt::Display for Bucket { fn fm...
random
[ { "content": "fn hmac(data: &[u8], secret: &[u8]) -> Vec<u8> {\n\n let mut hmac = Hmac::<Sha256>::new_varkey(secret).expect(\"HMAC can take key of any size\");\n\n hmac.update(data);\n\n hmac.finalize().into_bytes().as_slice().to_vec()\n\n}\n\n\n", "file_path": "src/azure/blobstore.rs", "rank":...
Rust
src/client.rs
jakalope/vixi
b0f39dc92c3eca21ccac17e1b54050569f72575e
use xrl; use xrl::{ClientResult, ViewId}; use serde_json::Value; use futures::future::ok; pub trait Client { fn notify(&mut self, method: &str, params: Value) -> ClientResult<()>; fn request(&mut self, method: &str, params: Value) -> ClientResult<Value>; fn edit(&mut self, view_id: ViewId, method: &str, pa...
use xrl; use xrl::{ClientResult, ViewId}; use serde_json::Value; use futures::future::ok; pub trait Client { fn notify(&mut self, method: &str, params: Value) -> ClientResult<()>; fn request(&mut self, method: &str, params: Value) -> ClientResult<Value>; fn edit(&mut self, view_id: ViewId, method: &str, pa...
rams) } } #[derive(Clone)] pub struct DummyClient; impl DummyClient { pub fn new() -> Self { DummyClient {} } } impl Client for DummyClient { fn notify(&mut self, method: &str, params: Value) -> ClientResult<()> { Box::new(ok(())) } fn request(&mut self, method: &str, params: ...
lugin: &str, method: &str, params: Value, ) -> ClientResult<()> { self.client.notify_plugin(view_id, plugin, method, &pa
function_block-random_span
[ { "content": "pub fn parse_any(buffer: &str) -> Option<Key> {\n\n parse_angle(buffer).or(parse_key(buffer))\n\n}\n\n\n\n#[macro_use]\n\npub mod parse {\n\n use super::*;\n\n use key::MultiKey::*;\n\n\n\n named!(\n\n shift<&str, MultiKey>,\n\n map_opt!(\n\n delimited!(tag_no_...
Rust
crates/bevy_asset/src/io/file_asset_io.rs
BoxyUwU/bevy
5d3d9723d15ae4ad12ffe50db4893531887c92c6
use crate::{filesystem_watcher::FilesystemWatcher, AssetIo, AssetIoError, AssetServer}; use anyhow::Result; use bevy_ecs::{bevy_utils::BoxedFuture, Res}; use bevy_utils::HashSet; use crossbeam_channel::TryRecvError; use fs::File; use io::Read; use parking_lot::RwLock; use std::{ env, fs, io, path::{Path, PathBu...
use crate::{filesystem_watcher::FilesystemWatcher, AssetIo, AssetIoError, AssetServer}; use anyhow::Result; use bevy_ecs::{bevy_utils::BoxedFuture, Res}; use bevy_utils::HashSet; use crossbeam_channel::TryRecvError; use fs::File; use io::Read; use parking_lot::RwLock; use std::{ env, fs, io, path::{Path, PathBu...
} fn watch_path_for_changes(&self, path: &Path) -> Result<(), AssetIoError> { #[cfg(feature = "filesystem_watcher")] { let path = self.root_path.join(path); let mut watcher = self.filesystem_watcher.write(); if let Some(ref mut watcher) = *watcher { ...
Ok(Box::new(fs::read_dir(root_path.join(path))?.map( move |entry| { let path = entry.unwrap().path(); path.strip_prefix(&root_path).unwrap().to_owned() }, )))
call_expression
[ { "content": "pub fn get_wgpu_render_system(resources: &mut Resources) -> impl FnMut(&mut World, &mut Resources) {\n\n let options = resources\n\n .get_cloned::<WgpuOptions>()\n\n .unwrap_or_else(WgpuOptions::default);\n\n let mut wgpu_renderer = future::block_on(WgpuRenderer::new(options));...
Rust
examples/flat_2d_across_nodes.rs
jrxb/ui-navigation
0f92dd0df092469d2fb8beb1f5ae0d9fb06d007d
use bevy::prelude::*; use bevy_ui_navigation::{ systems::{default_gamepad_input, default_keyboard_input, InputMapping}, Focusable, Focused, NavEvent, NavMenu, NavigationPlugin, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugin(NavigationPlugin) .init_resource::<But...
use bevy::prelude::*; use bevy_ui_navigation::{ systems::{default_gamepad_input, default_keyboard_input, InputMapping}, Focusable, Focused, NavEvent, NavMenu, NavigationPlugin, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugin(NavigationPlugin) .init_resource::<But...
} fn print_nav_events(mut events: EventReader<NavEvent>) { for event in events.iter() { println!("{:?}", event); } } fn button_system( button_materials: Res<ButtonMaterials>, mut interaction_query: Query<(Option<&Focused>, &mut Handle<ColorMaterial>), With<Button>>, ) { for (interaction, ...
fn from_world(world: &mut World) -> Self { let mut materials = world.get_resource_mut::<Assets<ColorMaterial>>().unwrap(); ButtonMaterials { normal: materials.add(Color::rgb(0.15, 0.15, 0.15).into()), focused: materials.add(Color::rgb(0.35, 0.75, 0.35).into()), pink: ...
function_block-full_function
[ { "content": "/// This example illustrates how to mark buttons as focusable and let\n\n/// NavigationPlugin figure out how to go from one to another.\n\nfn main() {\n\n App::new()\n\n .add_plugins(DefaultPlugins)\n\n // 1: Add the NavigationPlugin\n\n .add_plugin(NavigationPlugin)\n\n ...
Rust
src/error.rs
gnp/cusip-rs
f1f4bf8e244f30fd21e8347175e5da455de2b351
#![warn(missing_docs)] use std::error::Error; use std::fmt::Formatter; use std::fmt::{Debug, Display}; #[non_exhaustive] #[derive(Clone, PartialEq, Eq)] pub enum CUSIPError { InvalidCUSIPLength { was: usize, }, InvalidPayloadLength { was: usize, }, ...
#![warn(missing_docs)] use std::error::Error; use std::fmt::Formatter; use std::fmt::{Debug, Display}; #[non_exhaustive] #[derive(Clone, PartialEq, Eq)] pub enum CUSIPError { InvalidCUSIPLength { was: usize, }, InvalidPayloadLength { was: usize, }, ...
Digit { was } => { write!(f, "InvalidCheckDigit {{ was: {:?} }}", char::from(*was)) } CUSIPError::IncorrectCheckDigit { was, expected } => { write!( f, "IncorrectCheckDigit {{ was: {:?}, expected: {:?} }}", ...
write!(f, "InvalidIssuerNum {{ was: {:?} }}", s) } Err(_) => { write!(f, "InvalidIssuerNum {{ was: (invalid UTF-8) {:?} }}", was) } }, CUSIPError::InvalidIssueNum { was } => match std::str::from_utf8(was) { ...
function_block-random_span
[ { "content": "/// Compute the _checksum_ for a u8 array. No attempt is made to ensure the input string is in\n\n/// the CUSIP payload format or length.\n\n///\n\n/// The algorithm processes the input ASCII characters left-to-right, and counting from one, doubles\n\n/// the even ones and leaves the odd ones with...
Rust
src/sqllogictest/src/main.rs
priceloop/materialize
fa6d085455d94a2169d0df24805a5de76f2b3938
use std::cell::RefCell; use std::fmt; use std::fs::File; use std::io::{self, Write}; use std::path::PathBuf; use std::process; use chrono::Utc; use walkdir::WalkDir; use mz_sqllogictest::runner::{self, Outcomes, RunConfig, WriteFmt}; use mz_sqllogictest::util; #[derive(clap::Parser)] struct Args { ...
use std::cell::RefCell; use std::fmt; use std::fs::File; use std::io::{self, Write}; use std::path::PathBuf; use std::process; use chrono::Utc; use walkdir::WalkDir; use mz_sqllogictest::runner::{self, Outcomes, RunConfig, WriteFmt}; use mz_sqllogictest::util; #[derive(clap::Parser)] struct Args { ...
r: W, timestamps: bool) -> OutputStream<W> { OutputStream { inner: RefCell::new(inner), need_timestamp: RefCell::new(true), timestamps, } } fn emit_str(&self, s: &str) { self.inner.borrow_mut().write_all(s.as_bytes()).unwrap(); } } impl<W> WriteF...
=> match File::create(&filename) { Ok(file) => Some(file), Err(err) => { writeln!(config.stderr, "creating {}: {}", filename.display(), err); process::exit(1); } }, None => None, }; let mut bad_file = false; let mut outcomes...
random
[]
Rust
src/libstd/sync/mutex.rs
quornian/rust
dbc379a66eae8504b663b0032da518595335d872
#![allow(dead_code)] use core::prelude::*; use alloc::boxed::Box; use rustrt::mutex; pub const LOCKED: uint = 1 << 0; pub const BLOCKED: uint = 1 << 1; pub struct Mutex { lock: Box<StaticMutex>, } pub struct StaticMutex { lock: mutex::StaticNativeMutex, } #[must_use] pu...
#![allow(dead_code)] use core::prelude::*; use alloc::boxed::Box; use rustrt::mutex; pub const LOCKED: uint = 1 << 0; pub const BLOCKED: uint = 1 << 1; pub struct Mutex { lock: Box<StaticMutex>, } pub struct StaticMutex { lock: mutex::StaticNativeMutex, } #[must_use] pu...
let (tx, rx) = channel(); for _ in range(0, K) { let tx2 = tx.clone(); spawn(proc() { inc(); tx2.send(()); }); let tx2 = tx.clone(); spawn(proc() { inc(); tx2.send(()); }); } drop(tx); for _ in range(0, 2 * K) { rx.re...
for _ in range(0, J) { unsafe { let _g = M.lock(); CNT += 1; } } }
function_block-function_prefix_line
[ { "content": "pub fn main() { let _quux: Box<Vec<uint>> = box Vec::new(); }\n", "file_path": "src/test/run-pass/vector-no-ann-2.rs", "rank": 0, "score": 691504.1338730764 }, { "content": "#[rustc_move_fragments]\n\npub fn test_move_array_then_overwrite_elem2(mut a: [D, ..3], i: uint, j: uint...
Rust
types/src/deploy_info.rs
mcdee/casper-node
8cff3369480aaa7645bd7626ae0af19628873b2c
#![allow(clippy::field_reassign_with_default)] use alloc::vec::Vec; #[cfg(feature = "std")] use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{ account::AccountHash, bytesrepr::{self, FromBytes, ToBytes}, DeployHash, TransferAddr, URef, U512, }; #[derive(Debug, Clone, Ord, Parti...
#![allow(clippy::field_reassign_with_default)] use alloc::vec::Vec; #[cfg(feature = "std")] use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{ account::AccountHash, bytesrepr::{self, FromBytes, ToBytes}, DeployHash, TransferAddr, URef, U512, }; #[derive(Debug, Clone, Ord, Parti...
roundtrip(deploy_info in gens::deploy_info_arb()) { bytesrepr::test_serialization_roundtrip(&deploy_info) } } }
use alloc::vec::Vec; use proptest::{ array, collection::{self, SizeRange}, prelude::{Arbitrary, Strategy}, }; use crate::{ account::AccountHash, gens::{u512_arb, uref_arb}, DeployHash, DeployInfo, TransferAddr, }; pub fn deploy_hash_arb() -> impl ...
random
[ { "content": "/// Serializes `t` into a `Vec<u8>`.\n\npub fn serialize(t: impl ToBytes) -> Result<Vec<u8>, Error> {\n\n t.into_bytes()\n\n}\n\n\n\npub(crate) fn safe_split_at(bytes: &[u8], n: usize) -> Result<(&[u8], &[u8]), Error> {\n\n if n > bytes.len() {\n\n Err(Error::EarlyEndOfStream)\n\n ...
Rust
wiz/wizc/src/high_level_ir/type_resolver/name_environment.rs
ChanTsune/wiz
199d0f4698822a177ede8015bf8e04f190f39934
use crate::high_level_ir::declaration_id::DeclarationId; use crate::high_level_ir::type_resolver::arena::ResolverArena; use crate::high_level_ir::type_resolver::context::{EnvValue, ResolverStruct}; use crate::high_level_ir::type_resolver::declaration::DeclarationItemKind; use std::collections::{HashMap, HashSet}; use w...
use crate::high_level_ir::declaration_id::DeclarationId; use crate::high_level_ir::type_resolver::arena::ResolverArena; use crate::high_level_ir::type_resolver::context::{EnvValue, ResolverStruct}; use crate::high_level_ir::type_resolver::declaration::DeclarationItemKind; use std::collections::{HashMap, HashSet}; use w...
return Some(EnvValue::from(values)); } }; None } Some(t) => Some(t), } } else { let ids = self.values.get(&namespace[0].to_string())?; let ids = ids.iter().copied().collect...
lt(), arena, } } pub(crate) fn use_asterisk<T: ToString>(&mut self, namespace: &[T]) -> Option<()> { let ns_id = self.arena.resolve_declaration_id_from_root(namespace)?; let ns = self.arena.get_by_id(&ns_id).unwrap(); self.values.extend(ns.children().clone()); ...
random
[ { "content": "pub fn hlir2mlir<'arena>(\n\n target: TypedSourceSet,\n\n dependencies: &'arena [MLFile],\n\n arena: &'arena ResolverArena,\n\n) -> Result<MLFile> {\n\n let mut converter = HLIR2MLIR::new(arena);\n\n converter.load_dependencies(dependencies)?;\n\n Ok(converter.convert_from_source...
Rust
src/net/mod.rs
rusty-io/coio-rs
fc3e1270937175eff8dbe1e2606a413c80c7ec28
pub mod tcp; pub mod udp; #[cfg(unix)] pub mod unix; pub use self::tcp::{TcpListener, TcpStream, Shutdown}; pub use self::udp::UdpSocket; #[cfg(unix)] pub use self::unix::{UnixListener, UnixStream, UnixSocket}; use std::fmt::Debug; use std::io::{self, Read, Write}; use std::net::{SocketAddr, ToSocketAddrs}; use s...
pub mod tcp; pub mod udp; #[cfg(unix)] pub mod unix; pub use self::tcp::{TcpListener, TcpStream, Shutdown}; pub use self::udp::UdpSocket; #[cfg(unix)] pub use self::unix::{UnixListener, UnixStream, UnixSocket}; use std::fmt::Debug; use std::io::{self, Read, Write}; use std::net::{SocketAddr, ToSocketAddrs}; use s...
} #[cfg(unix)] impl<E: Evented + Debug + AsRawFd> AsRawFd for GenericEvented<E> { fn as_raw_fd(&self) -> RawFd { self.inner.as_raw_fd() } } struct SyncGuard(bool); impl SyncGuard { #[inline] pub fn new() -> SyncGuard { SyncGuard(true) } #[inline] pub fn disarm(&mut self)...
fn flush(&mut self) -> io::Result<()> { let mut sync_guard = SyncGuard::new(); loop { match self.inner.flush() { Ok(()) => { trace!("GenericEvented({:?}): write() => Ok(())", self.token); return Ok(()); } ...
function_block-full_function
[ { "content": "type RegisterCallback<'a> = &'a mut FnMut(&mut EventLoop<Scheduler>, Token, ReadyStates) -> bool;\n", "file_path": "src/scheduler.rs", "rank": 0, "score": 256797.86269830115 }, { "content": "type DeregisterCallback<'a> = &'a mut FnMut(&mut EventLoop<Scheduler>);\n\n\n\n#[doc(hi...
Rust
relay-general/src/protocol/exception.rs
rhcarvalho/relay
6f1e81115f1dd82aaf63d242d4e4db754c393a5e
use crate::protocol::{JsonLenientString, Mechanism, RawStacktrace, Stacktrace, ThreadId}; use crate::types::{Annotated, Object, Value}; #[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, ToValue, ProcessValue)] #[metastructure(process_func = "process_exception", value_type = "Exception")] pub struct Exceptio...
use crate::protocol::{JsonLenientString, Mechanism, RawStacktrace, Stacktrace, ThreadId}; use crate::types::{Annotated, Object, Value}; #[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, ToValue, ProcessValue)] #[metastructure(process_func = "process_exception", value_type = "Exception")] pub struct Exceptio...
#[test] fn test_explicit_none() { let json = r#"{ "value": null, "type": "ZeroDivisionError" }"#; let exception = Annotated::new(Exception { ty: Annotated::new("ZeroDivisionError".to_string()), ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(json).unwrap()...
assert_eq_dbg!(exception, Annotated::from_json(input).unwrap()); assert_eq_str!(output, exception.to_json().unwrap()); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_debug_image_symbolic_default_values() {\n\n let json = r#\"{\n\n \"code_file\": \"CoreFoundation\",\n\n \"debug_id\": \"494f3aea-88fa-4296-9644-fa8ef5d139b6-1234\",\n\n \"image_addr\": \"0x0\",\n\n \"image_size\": 4096,\n\n \"type\": \"symbolic\"\n\n}\"#;\n\n\n\n let ...
Rust
chain-impl-mockchain/benches/tally.rs
bernardoaraujor/chain-libs
715644b517be119eb856ca06893e01edbd777995
use chain_crypto::testing::TestCryptoRng; use chain_impl_mockchain::testing::scenario::template::WalletTemplateBuilder; use chain_impl_mockchain::{ certificate::{ DecryptedPrivateTally, DecryptedPrivateTallyProposal, EncryptedVoteTally, VoteCast, VotePlan, VoteTally, }, fee::LinearFee, h...
use chain_crypto::testing::TestCryptoRng; use chain_impl_mockchain::testing::scenario::template::WalletTemplateBuilder; use chain_impl_mockchain::{ certificate::{ DecryptedPrivateTally, DecryptedPrivateTallyProposal, EncryptedVoteTally, VoteCast, VotePlan, VoteTally, }, fee::LinearFee, h...
edger .apply_fragment(&parameters, &fragment, date) .unwrap(); }) }); ledger.apply_fragment(&fragment, ledger.date()).unwrap(); alice.confirm_transaction(); let vote_plans = ledger.ledger.active_vote_plans(); let vote_plan_status = vote_plans ...
} res }; let mut vote_casting_bench = c.benchmark_group("vote_casting"); vote_casting_bench.sample_size(10); vote_casting_bench.bench_function(&format!("vote_cast_{}", benchmark_name), |b| { b.iter(|| { let mut ledger = ledger.clone(); for vote ...
random
[]
Rust
src/resp2/encode.rs
marius-meissner/redis-protocol.rs
e68cee7ca0b74666e0cdbd91fce32087caeed84e
use crate::resp2::types::*; use crate::resp2::utils::{self as resp2_utils}; use crate::types::{RedisProtocolError, CRLF}; use crate::utils; use crate::alloc::string::ToString; use alloc::vec::Vec; use bytes::BytesMut; use cookie_factory::GenError; fn gen_simplestring<'a>(x: (&'a mut [u8], usize), data: &[u8]) -> Res...
use crate::resp2::types::*; use crate::resp2::utils::{self as resp2_utils}; use crate::types::{RedisProtocolError, CRLF}; use crate::utils; use crate::alloc::string::ToString; use alloc::vec::Vec; use bytes::BytesMut; use cookie_factory::GenError; fn gen_simplestring<'a>(x: (&'a mut [u8], usize), data: &[u8]) -> Res...
#[test] fn should_encode_raw_incr_req_example() { let expected = "*2\r\n$4\r\nINCR\r\n$5\r\nmykey\r\n"; let input = Frame::Array(vec![ Frame::BulkString("INCR".into()), Frame::BulkString("mykey".into()), ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_enc...
d = "*2\r\n$4\r\nLLEN\r\n$6\r\nmylist\r\n"; let input = Frame::Array(vec![ Frame::BulkString("LLEN".into()), Frame::BulkString("mylist".into()), ]); encode_raw_and_verify_empty(&input, expected); }
function_block-function_prefixed
[ { "content": "fn attempt_encoding<'a>(buf: &'a mut [u8], offset: usize, frame: &Frame) -> Result<(&'a mut [u8], usize), GenError> {\n\n use crate::resp3::types::Frame::*;\n\n\n\n let x = (buf, offset);\n\n let total_size = resp3_utils::encode_len(frame)?;\n\n trace!(\"Attempting to encode {:?} with total si...
Rust
src/bin/run.rs
Pilyushkin/onnxruntime-rs
72da91d9ec56fb80e1528520e74a04ec3a4d2274
use std::ffi::CStr; use std::time::{Duration, Instant}; use onnxruntime::*; use structopt::{clap, StructOpt}; #[structopt( name = "run", about = "Run a benchmark on an onnx model. Each worker runs the model in a loop in its own thead. Once done it will print the average time to run the model.", settin...
use std::ffi::CStr; use std::time::{Duration, Instant}; use onnxruntime::*; use structopt::{clap, StructOpt}; #[structopt( name = "run", about = "Run a benchmark on an onnx model. Each worker runs the model in a loop in its own thead. Once done it will print the average time to run the model.", settin...
fn tensor_mut(elem_type: OnnxTensorElementDataType, dims: &[usize]) -> Box<dyn AsMut<Val>> { use OnnxTensorElementDataType::*; match elem_type { Float => Box::new(Tensor::<f32>::init(dims, 0.0).unwrap()), Int64 => Box::new(Tensor::<i64>::init(dims, 0).unwrap()), Int32 => Box::new(Tenso...
1); 1 }) } SymbolicDim::Fixed(x) => x, }) .collect(); (info.elem_type(), dims) }
function_block-function_prefixed
[ { "content": "fn key_val_parse(str: &str) -> HashMap<String, usize> {\n\n let mut map = HashMap::new();\n\n if str.is_empty() {\n\n return map;\n\n }\n\n for key_val in str.split(',') {\n\n let mut iter = key_val.split('=');\n\n let key = iter.next().expect(\"no =\");\n\n ...
Rust
rups/src/blocking/mod.rs
aramperes/nut-rs
35d40d31116b745967927fbc944a18232dbf8fb1
use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpStream}; use crate::blocking::stream::ConnectionStream; use crate::cmd::{Command, Response}; use crate::{ClientError, Config, Host, NutError}; mod stream; pub enum Connection { Tcp(TcpConnection), } impl Connection { pub fn ne...
use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpStream}; use crate::blocking::stream::ConnectionStream; use crate::cmd::{Command, Response}; use crate::{ClientError, Config, Host, NutError}; mod stream; pub enum Connection { Tcp(TcpConnection), } impl Connection { pub fn ne...
eprint!("DEBUG -> {}", line); } self.stream.write_all(line.as_bytes())?; self.stream.flush()?; Ok(()) } fn parse_line( reader: &mut BufReader<&mut ConnectionStream>, debug: bool, ) -> crate::Result<Vec<String>> { let mut raw = String::new(); ...
InvalidHostname))?; let dns_name = webpki::DNSNameRef::try_from_ascii_str(&hostname) .map_err(|_| ClientError::Nut(NutError::SslInvalidHostname))?; ssl_config .root_store .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROO...
random
[ { "content": "fn connect(config: Config) -> anyhow::Result<Connection> {\n\n Connection::new(&config).with_context(|| format!(\"Failed to connect to upsd: {:?}\", &config))\n\n}\n\n\n", "file_path": "rupsc/src/cmd.rs", "rank": 0, "score": 117285.13075444756 }, { "content": "/// Lists each...
Rust
src/cargo/util/rustc.rs
xobs/cargo
ab64d1393b5b77c66b6534ef5023a1b89ee7bf64
use std::collections::hash_map::HashMap; use std::env; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use log::{debug, info, warn}; use serde::{Deserialize, Serialize}; use crate::util::interning::InternedString; use crate::util::paths; use crate::util::{self, profile, CargoResul...
use std::collections::hash_map::HashMap; use std::env; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use log::{debug, info, warn}; use serde::{Deserialize, Serialize}; use crate::util::interning::InternedString; use crate::util::paths; use crate::util::{self, profile, CargoResul...
host, cache: Mutex::new(cache), }) } pub fn process(&self) -> ProcessBuilder { util::process(self.path.as_path()).wrapped(self.wrapper.as_ref()) } pub fn workspace_process(&self) -> ProcessBuilder { util::process(self.path.as_path()) ...
extract = |field: &str| -> CargoResult<&str> { verbose_version .lines() .find(|l| l.starts_with(field)) .map(|l| &l[field.len()..]) .ok_or_else(|| { anyhow::format_err!( "`rustc -vV` didn't have a lin...
random
[ { "content": "pub fn read(path: &Path) -> CargoResult<String> {\n\n match String::from_utf8(read_bytes(path)?) {\n\n Ok(s) => Ok(s),\n\n Err(_) => anyhow::bail!(\"path at `{}` was not valid utf-8\", path.display()),\n\n }\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 0...
Rust
associated-token-account/program/tests/create_idempotent.rs
biw/solana-program-library
5611ad8bd595d9e3666f8b115cd28f8116038645
#![cfg(feature = "test-bpf")] mod program_test; use { program_test::program_test_2022, solana_program::{instruction::*, pubkey::Pubkey}, solana_program_test::*, solana_sdk::{ account::Account as SolanaAccount, program_option::COption, program_pack::Pack, signature::Sign...
#![cfg(feature = "test-bpf")] mod program_test; use { program_test::program_test_2022, solana_program::{instruction::*, pubkey::Pubkey}, solana_program_test::*, solana_sdk::{ account::Account as SolanaAccount, program_option::COption, program_pack::Pack, signature::Sign...
ta() { let token_mint_address = Pubkey::new_unique(); let (mut banks_client, payer, recent_blockhash) = program_test_2022(token_mint_address, true).start().await; let rent = banks_client.get_rent().await.unwrap(); let token_account_len = ExtensionType::get_account_len::<Account>(&[Exten...
); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError( 0, InstructionError::Custom(AssociatedTokenAccountError::InvalidOwner as u32) ) )...
random
[ { "content": "/// Determine if a memo is required for transfers into this account\n\npub fn memo_required(account_state: &StateWithExtensionsMut<Account>) -> bool {\n\n if let Ok(extension) = account_state.get_extension::<MemoTransfer>() {\n\n return extension.require_incoming_transfer_memos.into();\n...
Rust
src/parsers/elements_section.rs
w1th0utnam3/mshio
53f0d1d4c4cd0bbd50387c4a45aa5b666a9bf9ed
use std::collections::HashMap; use nom::IResult; use num::traits::FromPrimitive; use crate::error::{ always_error, context, make_error, MapMshError, MshParserError, MshParserErrorKind, }; use crate::mshfile::{Element, ElementBlock, ElementType, Elements, MshIntT, MshUsizeT}; use crate::parsers::num_parser_traits:...
use std::collections::HashMap; use nom::IResult; use num::traits::FromPrimitive; use crate::error::{ always_error, context, make_error, MapMshError, MshParserError, MshParserErrorKind, }; use crate::mshfile::{Element, ElementBlock, ElementType, Elements, MshIntT, MshUsizeT}; use crate::parsers::num_parser_traits:...
ement_type = ElementType::from_i32(element_type_raw).ok_or_else(|| { make_error(input, MshParserErrorKind::UnknownElement) .with_context_from(input, || format!("value {}", element_type_raw)) })?; Ok((input_new, element_type)) } fn parse_element<'a, U>( parser: impl ParsesSizeT<U>, ...
input: &'a [u8], ) -> IResult<&'a [u8], ElementSectionHeader<U>, MshParserError<&'a [u8]>> { let size_t_parser = size_t_parser(&parser); let usize_parser = usize_parser(&parser); let (input, num_entity_blocks) = context("number of element entity blocks", usize_parser)(input)?; let (input, num...
random
[ { "content": "fn parse_entity_section_header<'a, U: MshUsizeT>(\n\n parser: impl ParsesSizeT<U>,\n\n input: &'a [u8],\n\n) -> IResult<&'a [u8], EntitySectionHeader, MshParserError<&'a [u8]>> {\n\n let usize_parser = usize_parser(&parser);\n\n\n\n let (input, num_points) = context(\"number of point e...
Rust
src/pg/numeric.rs
shenhunluo/rustorm
cb7c7b203c718a71b76dc93d51017af57e55003f
use byteorder::{ NetworkEndian, ReadBytesExt, WriteBytesExt, }; use std::error::Error; use postgres::types::{ self, FromSql, IsNull, ToSql, Type, }; use bigdecimal::BigDecimal; use num_bigint::{ BigInt, BigUint, Sign, }; use num_integer::Integer; use num_traits::{ Si...
use byteorder::{ NetworkEndian, ReadBytesExt, WriteBytesExt, }; use std::error::Error; use postgres::types::{ self, FromSql, IsNull, ToSql, Type, }; use bigdecimal::BigDecimal; use num_bigint::{ BigInt, BigUint, Sign, }; use num_integer::Integer; use num_traits::{ Si...
let relevant_digits = digits.len() - unnecessary_zeroes; digits.truncate(relevant_digits); match decimal.sign() { Sign::Plus => { PgNumeric::Positive { digits, scale, weight, } ...
let unnecessary_zeroes = if weight >= 0 { let index_of_decimal = (weight + 1) as usize; digits .get(index_of_decimal..) .expect("enough digits exist") .iter() .rev() .take_while(|i| i.is_zero()) .coun...
assignment_statement
[ { "content": "pub fn eval_f64(expr: &str) -> Result<f64, meval::Error> { meval::eval_str(expr) }\n", "file_path": "src/util.rs", "rank": 1, "score": 149008.67453994806 }, { "content": "pub fn maybe_trim_parenthesis(arg: &str) -> &str {\n\n if arg.starts_with('(') && arg.ends_with(')') {\n...
Rust
api/src/models/image.rs
jpommerening/PREvant
856102242987cb6b39cc6d5096e325ff817bbb3a
/*- * ========================LICENSE_START================================= * PREvant REST API * %% * Copyright (C) 2018 - 2019 aixigo AG * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the ...
/*- * ========================LICENSE_START================================= * PREvant REST API * %% * Copyright (C) 2018 - 2019 aixigo AG * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the ...
#[test] fn should_parse_image_id() { let image = Image::from_str("9895c9b90b58").unwrap(); assert_eq!(&image.to_string(), "9895c9b90b58"); assert_eq!(image.name(), None); assert_eq!(image.tag(), None); } #[test] fn should_parse_image_with_repo_and_user() { ...
image.to_string(), "sha256:9895c9b90b58c9490471b877f6bb6a90e6bdc154da7fbb526a0322ea242fc913" ); }
function_block-function_prefix_line
[ { "content": "pub fn docker() -> Cli {\n\n if INIT_LOGGER.compare_and_swap(true, false, Ordering::Relaxed) {\n\n env_logger::from_env(env_logger::Env::default().default_filter_or(\"info\")).init();\n\n }\n\n\n\n Cli::default()\n\n}\n", "file_path": "api-tests/tests/common/mod.rs", "rank"...
Rust
rs/bitcoin/canister/src/main.rs
paulyoung/ic
661ae3e3472c6ac7c455c1b75fad3e2eebf8e86f
use bitcoin::{ blockdata::constants::genesis_block, util::psbt::serialize::Deserialize, Address, Network, Transaction, }; use candid::candid_method; use ic_btc_canister::{ proto::{GetSuccessorsRequest, GetSuccessorsResponse}, store::State, }; use ic_btc_types::{ GetBalanceError, GetBalanceRequest, G...
use bitcoin::{ blockdata::constants::genesis_block, util::psbt::serialize::Deserialize, Address, Network, Transaction, }; use candid::candid_method; use ic_btc_canister::{ proto::{GetSuccessorsRequest, GetSuccessorsResponse}, store::State, }; use ic_btc_types::{ GetBalanceError, GetBalanceRequest, G...
#[test] fn malformed_transaction() { assert_eq!( send_transaction(SendTransactionRequest { transaction: vec![1, 2, 3], }), Err(SendTransactionError::MalformedTransaction) ); } }
ock_0 = BlockBuilder::genesis() .with_transaction(coinbase_tx.clone()) .build(); let tx = TransactionBuilder::with_input(bitcoin::OutPoint::new(coinbase_tx.txid(), 0)) .with_output(&address_2, 1000) .build(); let block_1 = BlockBuil...
function_block-function_prefixed
[ { "content": "fn main() -> Result<()> {\n\n prost_build::compile_protos(&[\"src/proto.proto\"], &[\"src/\"])?;\n\n #[cfg(feature = \"tonic-build\")]\n\n tonic_build::compile_protos(\"src/proto.proto\")?;\n\n Ok(())\n\n}\n", "file_path": "rs/bitcoin/canister/build.rs", "rank": 3, "score":...
Rust
src/ast.rs
namachan10777/jubilant-octo-telegram
1978e5694a0e86d995f56e548095ff23bdcc3e10
use std::collections::HashMap; use yaml_rust::Yaml; #[derive(Debug, Clone, PartialEq)] pub enum Value { Int(i64), Real(f64), Str(String), Bool(bool), Array(Vec<Value>), Hash(HashMap<String, Value>), } #[derive(Debug)] pub enum ConvError { YamlAlias, YamlBadValue, Ya...
use std::collections::HashMap; use yaml_rust::Yaml; #[derive(Debug, Clone, PartialEq)] pub enum Value { Int(i64), Real(f64), Str(String), Bool(bool), Array(Vec<Value>), Hash(HashMap<String, Value>), } #[derive(Debug)] pub enum ConvError { YamlAlias, YamlBadValue, Ya...
}
fn test_not_allowed_member() { let map = hashmap! { "a" => 1, "b" => 2, "c" => 3, "d" => 4, }; let mut not_allowed = not_allowed_member(&map, &[&"a", &"c"]); not_allowed.sort_by(|(k1, _), (k2, _)| k1.cmp(&k2)); assert_eq!(not_allow...
function_block-full_function
[ { "content": "fn yaml_to_str(yaml: &crate::ast::Value) -> Result<Option<String>, crate::Error> {\n\n match &yaml {\n\n crate::ast::Value::Str(s) => Ok(Some(s.clone())),\n\n crate::ast::Value::Real(r) => Ok(Some(r.to_string())),\n\n crate::ast::Value::Int(i) => Ok(Some(i.to_string())),\n\...
Rust
src/sys/pkg/bin/omaha-client/src/storage/stash.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use omaha_client::storage::Storage; use fidl::endpoints::create_proxy; use fidl_fuchsia_stash::{Store2Marker, StoreAccessorMarker, StoreAccessorProxy, Value}; use futures::future::BoxFuture; use futures::prelude::*; use log::{error, warn}; use thiserror::Error; type Result<T> = std::result::Result<T, StashError>; ...
use omaha_client::storage::Storage; use fidl::endpoints::create_proxy; use fidl_fuchsia_stash::{Store2Marker, StoreAccessorMarker, StoreAccessorProxy, Value}; use futures::future::BoxFuture; use futures::prelude::*; use log::{error, warn}; use thiserror::Error; type Result<T> = std::result::Result<T, StashError>; ...
fn commit(&mut self) -> BoxFuture<'_, Result<()>> { future::ready(match &self.proxy { Some(proxy) => match proxy.commit() { Ok(_) => Ok(()), Err(e) => { error!("Unable to commit changes to stash! {}", e); Err(e.into()) ...
fn remove<'a>(&'a mut self, key: &'a str) -> BoxFuture<'_, Result<()>> { future::ready(match &self.proxy { Some(proxy) => match proxy.delete_value(key) { Ok(_) => Ok(()), Err(e) => { error!("Unable to write to stash for key: {}; {}", key, e); ...
function_block-full_function
[]
Rust
src/process/process_group.rs
krhancoc/fastfreeze
71435e7f2d7c01d81ce54aa28b5b28ccadeed748
use anyhow::{Result, Context}; use std::{ os::unix::io::AsRawFd, io::{ErrorKind, Read}, time::{Duration, Instant}, fs, iter, }; use nix::{ poll::{PollFd, PollFlags}, fcntl::OFlag, sys::signal, }; use crate::{ consts::*, util::{poll_nointr, Pipe}, }; use super::{Process, ProcessErro...
use anyhow::{Result, Context}; use std::{ os::unix::io::AsRawFd, io::{ErrorKind, Read}, time::{Duration, Instant}, fs, iter, }; use nix::{ poll::{PollFd, PollFlags}, fcntl::OFlag, sys::signal, }; use crate::{ consts::*, util::{poll_nointr, Pipe}, }; use super::{Process, ProcessErro...
} pub fn add(&mut self, proc: impl Into<ProcessMembership>) -> ProcessHandle { self.children.push(proc.into()); ProcessHandle(self.children.len() - 1) } pub fn get_mut(&mut self, id: ProcessHandle) -> &mut Process { &mut self.children[id.0].inner } fn drain_sigchld_pi...
Ok(Self { sigchld_pipe: pipe.read, children: Vec::new(), kill_grace_period, sig_hook_id, })
call_expression
[ { "content": "/// Kill an entire process group. It is not atomic.\n\n/// Tasks may appear while we are traversing the tree.\n\n/// This is mostly used to SIGSTOP/SIGCONT the entire application.\n\n/// TODO We could use the cgroup freezer if we have access to it.\n\npub fn kill_process_tree(root_pid: Pid, signal...
Rust
src/aggregation/segment_agg_result.rs
StyMaar/tantivy
458ed29a31d4a8929193ba4f41b83cd69eaac5f9
use std::fmt::Debug; use super::agg_req::MetricAggregation; use super::agg_req_with_accessor::{ AggregationsWithAccessor, BucketAggregationWithAccessor, MetricAggregationWithAccessor, }; use super::bucket::SegmentRangeCollector; use super::metric::{ AverageAggregation, SegmentAverageCollector, SegmentStatsCo...
use std::fmt::Debug; use super::agg_req::MetricAggregation; use super::agg_req_with_accessor::{ AggregationsWithAccessor, BucketAggregationWithAccessor, MetricAggregationWithAccessor, }; use super::bucket::SegmentRangeCollector; use super::metric::{ AverageAggregation, SegmentAverageCollector, SegmentStatsCo...
ketResultCollector::Range(range) => { range.collect_block(doc, bucket_with_accessor, force_flush); } } } } #[derive(Clone, PartialEq)] pub(crate) struct SegmentRangeBucketEntry { pub key: Key, pub doc_count: u64, pub sub_aggregation: Option<SegmentAggregationResultsC...
(crate) enum SegmentBucketResultCollector { Range(SegmentRangeCollector), } impl SegmentBucketResultCollector { pub fn from_req_and_validate(req: &BucketAggregationWithAccessor) -> crate::Result<Self> { match &req.bucket_agg { BucketAggregationType::Range(range_req) => { Ok(...
random
[ { "content": "#[inline]\n\nfn is_within<TDocSetExclude: DocSet>(docset: &mut TDocSetExclude, doc: DocId) -> bool {\n\n docset.doc() <= doc && docset.seek(doc) == doc\n\n}\n\n\n\n/// Filters a given `DocSet` by removing the docs from a given `DocSet`.\n\n///\n\n/// The excluding docset has no impact on scorin...
Rust
src/devices/src/virtio/block/device.rs
lyuyuan/vmm-reference
6275fc099022c7fb6d62022a87c5686b2fbe0ba2
use std::borrow::{Borrow, BorrowMut}; use std::fs::OpenOptions; use std::ops::DerefMut; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use vm_device::bus::MmioAddress; use vm_device::device_manager::MmioManager; use vm_device::{DeviceMmio, MutDeviceMmio}; use vm_memory::GuestAddressSpace; use vm_virtio::block:...
use std::borrow::{Borrow, BorrowMut}; use std::fs::OpenOptions; use std::ops::DerefMut; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use vm_device::bus::MmioAddress; use vm_device::device_manager::MmioManager; use vm_device::{DeviceMmio, MutDeviceMmio}; use vm_memory::GuestAddressSpace; use vm_virtio::block:...
}
fn test_device() { let tmp = TempFile::new().unwrap(); let mut mock = EnvMock::new(); let mut env = mock.env(); let args = BlockArgs { file_path: tmp.as_path().to_path_buf(), read_only: true, root_device: true, advertise_flush: true, ...
function_block-full_function
[ { "content": "pub fn get_type(entry: u64) -> u8 {\n\n ((entry & 0x0000_0F00_0000_0000) >> 40) as u8\n\n}\n\n\n", "file_path": "src/vm-vcpu/src/vcpu/gdt.rs", "rank": 0, "score": 194121.65583323193 }, { "content": "type Result<T> = std::result::Result<T, Error>;\n\npub type Subscriber = Arc...
Rust
src/fonts/manifest/src/v2.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { crate::serde_ext::*, anyhow::{ensure, Error}, char_set::CharSet, fidl_fuchsia_fonts::{GenericFontFamily, Slant, Width, WEIGHT_NORMAL}, fuchsia_url::pkg_url::PkgUrl, itertools::Itertools, offset_string::OffsetString, serde::{ de::{Deserializer, Error as DeError}, s...
use { crate::serde_ext::*, anyhow::{ensure, Error}, char_set::CharSet, fidl_fuchsia_fonts::{GenericFontFamily, Slant, Width, WEIGHT_NORMAL}, fuchsia_url::pkg_url::PkgUrl, itertools::Itertools, offset_string::OffsetString, serde::{ de::{Deserializer, Error as DeError}, s...
} impl Style { fn default_slant() -> Slant { Slant::Upright } fn default_weight() -> u16 { WEIGHT_NORMAL } fn default_width() -> Width { Width::Normal } }
nt: Style::default_slant(), weight: Style::default_weight(), width: Style::default_width(), } }
function_block-function_prefixed
[]