lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/manager/event.rs
cartoon-raccoon/toaruwm
612b6d8a4b3b58a7c52195a64eb7ea540f0dee46
use std::str::FromStr; use crate::x::{ XEvent, XWindowID, XConn, XError, event::{ ConfigureRequestData, ClientMessageEvent, ClientMessageData, PropertyEvent, PointerEvent, }, Atom, Property, WmHintsFlags, }; use crate::core::types::Point; use crate::keyb...
use std::str::FromStr; use crate::x::{ XEvent, XWindowID, XConn, XError, event::{ ConfigureRequestData, ClientMessageEvent, ClientMessageData, PropertyEvent, PointerEvent, }, Atom, Property, W
let atom = if let Ok(atom) = state.conn.lookup_atom(event.atom) { atom } else {return vec![]}; let hints = Atom::WmHints.as_ref(); if !event.deleted && atom == hints { let wmhints = if let Ok(Some(h)) = state.conn.get_prop(hints, event.id) { h } else {return vec![]}...
mHintsFlags, }; use crate::core::types::Point; use crate::keybinds::{Keybind, Mousebind}; use crate::manager::WMState; #[derive(Debug, Clone)] pub enum EventAction { ClientFocus(XWindowID), ClientUnfocus(XWindowID), ClientNameChange(XWindowID), ScreenReconfigure, ...
random
[ { "content": "//use std::convert::TryFrom;\n\nuse std::collections::HashMap;\n\nuse std::str::FromStr;\n\n\n\nuse thiserror::Error;\n\n\n\nuse strum::*;\n\nuse strum_macros::EnumIter;\n\n\n\nuse super::core::XAtom;\n\n\n\n// shamelessly stolen from:\n\n// https://github.com/sminez/penrose/blob/develop/src/core/...
Rust
src/yara/parser.rs
davbo/yara-rs
72f168eaa0b5335dd48942493c2eb34abae9d8c4
extern crate pom; use pom::parser::{call, list, none_of, one_of, seq, sym, empty, Parser}; use std::collections::HashMap; use std::fmt; const HEX: &'static [u8; 16] = b"0123456789ABCDEF"; #[derive(Debug, PartialEq, Hash, Eq, Clone)] pub enum YaraIdentifier { Str(String), } impl fmt::Display for YaraIdentifier { ...
extern crate pom; use pom::parser::{call, list, none_of, one_of, seq, sym, empty, Parser}; use std::collections::HashMap; use std::fmt; const HEX: &'static [u8; 16] = b"0123456789ABCDEF"; #[derive(Debug, PartialEq, Hash, Eq, Clone)] pub enum YaraIdentifier { Str(String), } impl fmt::Display for YaraIdentifier { ...
: $a = "foobar" nocase $b = { AB [0-2] ?D } private condition: $a or $b or $c } "#; let result = rule().parse(input); assert!( result.is_ok(), format!("Example failed to parse: {:#?}", result) ); } #[test] fn parse_regex() {...
} #[test] fn parse_apple_rules() { let apple_rules = fs::read("tests/rules.yara").expect("unable to open file"); let result = parse_rules(&apple_rules[..]); assert!( result.is_ok(), format!("Example failed to parse: {:#?}", result) ); } #[test] ...
random
[ { "content": "#[wasm_bindgen_test]\n\nfn fail() {\n\n assert_eq!(1, 2);\n\n}\n", "file_path": "tests/wasm.rs", "rank": 7, "score": 119138.49171164914 }, { "content": "#[wasm_bindgen]\n\npub fn yara_match(rules: &str, payload: &[u8]) -> bool {\n\n let rule = yara::parser::rule().parse(r...
Rust
src/bin/disasm.rs
MeFisto94/emul8
e06d06020a1ca944f156768684ffd80a8280b6ef
extern crate clap; extern crate emul8; use clap::{App, Arg}; use emul8::internals::opcode::Opcode; use emul8::internals::*; fn main() { let args = App::new("CHIP-8 Disassembler") .version("0.1") .author("Marc Streckfuß <marc.streckfuss@gmail.com>") .about("Disassembler for the CHIP-8 Binary...
extern crate clap; extern crate emul8; use clap::{App, Arg}; use emul8::internals::opcode::Opcode; use emul8::internals::*; fn main() { let args = App::new("CHIP-8 Disassembler") .version("0.1") .author("Marc Streckfuß <marc.streckfuss@gmail.com>") .about("Disassembler for the CHIP-8 Binary...
n!( "{:#X}\t\t\t{:#X} {:#X}\t{}", processor.memory.registers.pc, opcode.0, opcode.1, op ); } else { println!("{} ; {:#X}", op, processor.memory.registers.pc); } } } else if !ignore...
function_block-function_prefixed
[ { "content": "pub trait Opcode: fmt::Debug + fmt::Display + Downcast {\n\n fn execute(&self, processor: &mut Processor);\n\n fn modified_pc(&self) -> bool {\n\n false // The majority does not tamper with the PC\n\n }\n\n fn assemble(&self) -> (u8, u8) {\n\n (0x0, 0x0) // To easier migr...
Rust
tests/unit-tests.rs
diogo464/etherparse
dc9efc94c13310b4fb3d63f8566ad2fee39cb10d
extern crate etherparse; use etherparse::*; extern crate byteorder; #[macro_use] extern crate assert_matches; extern crate proptest; use std::io; mod errors; mod link; mod internet; mod transport; mod packet_builder; mod packet_filter; mod packet_slicing; mod proptest_generators; pub use crate::proptest_generators...
extern crate etherparse; use etherparse::*; extern crate byteorder; #[macro_use] extern crate assert_matches; extern crate proptest; use std::io; mod errors; mod link; mod internet; mod transport; mod packet_builder; mod packet_filter; mod packet_slicing; mod proptest_generators; pub use crate::proptest_generators...
expectedOuterTpid(2) ); } } mod write_error { #[test] fn value_error() { use super::*; assert_eq!( None, WriteError::IoError(std::io::Error::new(std::io::ErrorKind::Other, "oh no!")) .value_error() ); assert_eq!( Some(...
tches!( ReadError::UnexpectedEndOfSlice(2).add_slice_offset(3), ReadError::UnexpectedEndOfSlice(5) ); assert_matches!( ReadError::VlanDoubleTaggingUnexpectedOuterTpid(2).add_slice_offset(3), ReadError::VlanDoubleTaggingUn
random
[ { "content": "pub fn error_field_any() -> impl Strategy<Value = ErrorField> {\n\n use ErrorField::*;\n\n prop_oneof![\n\n Just(Ipv4PayloadLength),\n\n Just(Ipv4Dscp),\n\n Just(Ipv4Ecn),\n\n Just(Ipv4FragmentsOffset),\n\n Just(Ipv6FlowLabel),\n\n Just(VlanTagPriori...
Rust
iota-conversion/trinary.rs
wusyong/iota.rs
94ca611ec5d3f490d1b1871d159c4ab43760a694
use crate::Result; use iota_constants::{TRINARY_RADIX, TRITS_PER_BYTE, TRITS_PER_TRYTE}; lazy_static! { pub static ref BYTE_TO_TRITS_MAPPINGS: [[i8; TRITS_PER_BYTE]; 243] = { let mut trits: [i8; TRITS_PER_BYTE] = [0; TRITS_PER_BYTE]; let mut tmp = [[0; TRITS_PER_BYTE]; 243]; tmp.iter_m...
use crate::Result; use iota_constants::{TRINARY_RADIX, TRITS_PER_BYTE, TRITS_PER_TRYTE}; lazy_static! { pub static ref BYTE_TO_TRITS_MAPPINGS: [[i8; TRITS_PER_BYTE]; 243] = { let mut trits: [i8; TRITS_PER_BYTE] = [0; TRITS_PER_BYTE]; let mut tmp = [[0; TRITS_PER_BYTE]; 243]; tmp.iter_m...
}); tmp }; } pub trait Trinary { fn trits(&self) -> Vec<Trit>; fn trits_with_length(&self, length: usize) -> Vec<Trit>; fn trytes(&self) -> Result<Trytes>; } pub type Trit = i8; pub type Trytes = String; impl Trinary for i64 { fn trits(&self) -> Vec<Trit> { let ...
let mut trits: [i8; TRITS_PER_BYTE] = [0; TRITS_PER_BYTE]; let mut tmp = [[0; TRITS_PER_TRYTE]; 27]; tmp.iter_mut().for_each(|tmp_entry| { tmp_entry.copy_from_slice(&trits[0..TRITS_PER_TRYTE]); increment(&mut trits, TRITS_PER_TRYTE);
random
[ { "content": "/// Converts a slice of trits into a numeric value\n\npub fn value(trits: &[i8]) -> i8 {\n\n trits.iter().rev().fold(0, |acc, trit| acc * 3 + *trit)\n\n}\n\n\n", "file_path": "iota-conversion/lib.rs", "rank": 0, "score": 144049.02114393853 }, { "content": "/// Converts a sli...
Rust
app/gui/src/controller/ide/desktop.rs
cmarincia/enso
d59710c3cd9e356ce470edfa186c56cdca80f9d9
use crate::prelude::*; use crate::controller::ide::ManagingProjectAPI; use crate::controller::ide::Notification; use crate::controller::ide::StatusNotificationPublisher; use crate::controller::ide::API; use crate::ide::initializer; use crate::notification; use double_representation::identifier::ReferentName; use en...
use crate::prelude::*; use crate::controller::ide::ManagingProjectAPI; use crate::controller::ide::Notification; use crate::controller::ide::StatusNotificationPublisher; use crate::controller::ide::API; use crate::ide::initializer; use crate::notification; use double_representation::identifier::ReferentName; use en...
provided") }
ting_names: HashSet<_> = list.projects.into_iter().map(|p| p.name.into()).collect(); let name = template.clone().unwrap_or_else(|| UNNAMED_PROJECT_NAME.to_owned()); let name = choose_new_project_name(&existing_names, &name); let name = ProjectName::new_unchecked(name)...
random
[]
Rust
crates/storage/src/account/raw.rs
sudachen/svm
879e3d1f4cbfc6eba2b269d3da02c1cd4d949ecf
use std::collections::HashMap; use svm_types::State; use super::AccountKVStore; use crate::kv::StatefulKV; pub struct RawStorage { account_kv: AccountKVStore, kv_value_size: u32, } #[derive(Debug, Clone, PartialEq)] pub struct RawChange { pub offset: u32, pub data: Vec<u8>, } impl RawCha...
use std::collections::HashMap; use svm_types::State; use super::AccountKVStore; use crate::kv::StatefulKV; pub struct RawStorage { account_kv: AccountKVStore, kv_value_size: u32, } #[derive(Debug, Clone, PartialEq)] pub struct RawChange { pub offset: u32, pub data: Vec<u8>, } impl RawCha...
#[test] fn raw_storage_store() { let addr = Address::of("@Account"); let kv = testing::create_account_kv(addr); let var1 = RawChange { offset: 0, data: vec![0x10, 0x20, 0x30], }; let var2 = RawChange { offset: 3, data: v...
fn raw_storage_var_defaults_to_zeros() { let addr = Address::of("@Account"); let kv = testing::create_account_kv(addr); let off = 10; let len = 20; let storage = RawStorage::new(kv, KV_VALUE_SIZE); let bytes = storage.read(off, len); assert_eq!(bytes, vec![0; l...
function_block-full_function
[ { "content": "/// Given a WASM buffer memory offset in `offset` parameter,\n\n/// returns a '&mut [u8]' to its `Header` section.\n\npub fn wasm_buffer_mut<'a>(offset: usize) -> &'a mut [u8] {\n\n let len = wasm_buf_len(offset);\n\n let total_len = len + HEADER_SIZE;\n\n\n\n unsafe { std::slice::from_ra...
Rust
src/ppu/fetch.rs
goooosick/joy
09297bfd3debee39d649896e86d75bf663686e62
use super::{BgAttr, Ppu, Sprite, TileValue, LCDC}; use std::collections::VecDeque; pub enum FetchState { ReadTile, ReadData0, ReadData1, Push, } impl Default for FetchState { fn default() -> Self { FetchState::ReadTile } } #[derive(Default)] pub struct Fetcher { ticks: usize, ...
use super::{BgAttr, Ppu, Sprite, TileValue, LCDC}; use std::collections::VecDeque; pub enum FetchState { ReadTile, ReadData0, ReadData1, Push, } impl Default for FetchState { fn default() -> Self { FetchState::ReadTile } } #[derive(Default)] pub struct Fetcher { ticks: usize, ...
p_tile) } _ => bg_color, }; self.frame_buffer[self.fet.fb_offset..][0..3].copy_from_slice(&color); self.current_x += 1; self.fet.fb_offset += 3; } } } ...
(self.cgb && !self.lcdc.contains(LCDC::BG_ON)) || bg_tile == TileValue::B00; let color = match self.fet.sprite_fifo.pop_front() { None | Some((_, TileValue::B00)) => bg_color, Some((sp, sp_tile)) if sp_pri...
function_block-random_span
[ { "content": "pub fn load_cartridge<P: AsRef<std::path::Path>>(path: P) -> std::io::Result<Cartridge> {\n\n let rom = std::fs::read(path)?;\n\n let entry = 0x100;\n\n\n\n let title = std::str::from_utf8(\n\n rom[0x134..=0x142]\n\n .iter()\n\n .copied()\n\n .take_...
Rust
src/language_processor.rs
TNorbury/tyler-language
841597f6c46550daacd61aa82a5731d710597a13
use std::collections::HashMap; pub struct ProgramState { lists: HashMap<String, Vec<String>>, execs: HashMap<String, String>, command_history: Vec<String>, repeat_level: usize, } pub fn process(commands: Vec<&str>) { let mut state: ProgramState = ProgramState { lists: HashMap::new(), ...
use std::collections::HashMap; pub struct ProgramState { lists: HashMap<String, Vec<String>>, execs: HashMap<String, String>, command_history: Vec<String>, repeat_level: usize, } pub fn process(commands: Vec<&str>) { let mut state: ProgramState = ProgramState { lists: HashMap::new(), ...
if state.repeat_level > state.command_history.len() { can_not_repeat_panic(); } let mut tab_prefix: String = "".to_string(); for _i in 1..state.repeat_level { tab_prefix += "\t"; } if args.len() == 0 { match state .command_history ...
process_command(command, &mut state); } } } fn process_command(command: &str, state: &mut ProgramState) { let command_split: Vec<&str> = command.split(" ").collect(); let command_code = command_split[0]; let command_args = &command_split[1..command_split.len()]; m...
random
[ { "content": "fn main() {\n\n const TYLER_FILE_KEY: &str = \"FILE\";\n\n\n\n // Set up the command line arguments\n\n let cl_args = App::new(\"tyler\")\n\n .version(\"0.1.0\")\n\n .author(\"tnorbury\")\n\n .about(\"Interpreter for the tyler language\")\n\n .arg(\n\n ...
Rust
src/sound/frequency.rs
tiborgats/music
da1e23c411288757a53aface6c59a7680e82228e
use crate::sound::*; use std::cell::Cell; pub trait FrequencyFunction { fn get( &self, time_start: SampleCalc, base_frequency: Option<&[SampleCalc]>, result: &mut [SampleCalc], ) -> SoundResult<()>; } #[derive(Debug, Clone)] pub struct FrequencyConst { frequency: Cell<...
use crate::sound::*; use std::cell::Cell; pub trait FrequencyFunction { fn get( &self, time_start: SampleCalc, base_frequency: Option<&[SampleCalc]>, result: &mut [SampleCalc], ) -> SoundResult<()>; } #[derive(Debug, Clone)] pub struct FrequencyConst { frequency: Cell<...
pub fn set_phase(&mut self, phase: SampleCalc) -> SoundResult<()> { self.phase = phase % PI2; Ok(()) } } impl FrequencyModulator for Vibrato { fn get( &mut self, tempo: &[SampleCalc], base_frequency: &[SampleCalc], result: &mut [SampleCalc], ) -> S...
pub fn new( sample_rate: SampleCalc, note_value: NoteValue, extent_ratio: SampleCalc, ) -> SoundResult<Vibrato> { let sample_time = get_sample_time(sample_rate)?; if extent_ratio <= 0.0 { return Err(Error::FrequencyTooLow); } let phase_change = sam...
function_block-full_function
[ { "content": "/// Calculates the period of one sample for the given sample rate.\n\n/// Sample rates below 1.0 are considered to be invalid.\n\npub fn get_sample_time(sample_rate: SampleCalc) -> SoundResult<SampleCalc> {\n\n if sample_rate < 1.0 {\n\n Err(Error::SampleRateInvalid)\n\n } else {\n\n ...
Rust
src/main.rs
hendrikmaus/actions-digest
451e8116265e836f01696444c0d90b5accc9ac76
mod resolve; mod step; use crate::resolve::github::GitHub; use crate::step::Action; use clap::Parser; use rayon::prelude::*; use regex::Regex; use reqwest::header; use std::fs::read_to_string; use std::path::PathBuf; use std::str::FromStr; use std::time::Duration; #[derive(Parser, Debug)] #[clap( author, vers...
mod resolve; mod step; use crate::resolve::github::GitHub; use crate::step::Action; use clap::Parser; use rayon::prelude::*; use regex::Regex; use reqwest::header; use std::fs::read_to_string; use std::path::PathBuf; use std::str::FromStr; use std::time::Duration; #[derive(Parser, Debug)] #[clap( author, vers...
fn main() -> anyhow::Result<()> { let args = Args::parse(); let mut content = read_to_string(&args.file)?; let mut actions: Vec<Action> = content .lines() .filter_map(|line| { if !step::ACTION_USES_RE.is_match(line) { return None; } ...
function_block-full_function
[ { "content": "#[derive(Deserialize, Clone, Debug)]\n\nstruct Reference {\n\n #[serde(rename = \"ref\")]\n\n #[allow(dead_code)]\n\n git_ref: String,\n\n\n\n #[allow(dead_code)]\n\n node_id: String,\n\n\n\n #[allow(dead_code)]\n\n url: String,\n\n object: GitObject,\n\n}\n\n\n\npub struct...
Rust
src/import/dxf.rs
klotzambein/arch-intelligence
7b093d9879a220f240bc35d318a06b30298f021c
use std::collections::HashMap; use std::rc::Rc; use std::{cell::RefCell, path::Path}; use dxf::entities::{ Arc as DArc, Circle as DCircle, Ellipse as DEllipse, Entity, EntityType, Insert as DInsert, Line as DLine, LwPolyline as DLwPolyline, MText as DMText, Polyline as DPolyline, Spline as DSpline, Text ...
use std::collections::HashMap; use std::rc::Rc; use std::{cell::RefCell, path::Path}; use dxf::entities::{ Arc as DArc, Circle as DCircle, Ellipse as DEllipse, Entity, EntityType, Insert as DInsert, Line as DLine, LwPolyline as DLwPolyline, MText as DMText, Polyline as DPolyline, Spline as DSpline, Text ...
} impl DxfCanvasObject { pub fn iter_filtered<'a, F>( &'a self, filter: F, ) -> impl Iterator<Item = Point2D<f32, CanvasSpace>> + 'a where F: Fn(&DxfObject) -> bool + 'a, { self.block .objects .iter() .filter(move |x| filter(x)) ...
m, )?; let objects: &HashMap<String, Rc<DxfCanvasObject>> = ctx.get_generic()?; for (name, transform) in &self.block.children { let child = objects[name].clone(); ctx.with_model_transform(transform.then(&ctx.model_transform), |mut child_ctx| { child.draw(...
function_block-function_prefixed
[]
Rust
linkerd/stack/tracing/src/lib.rs
rahulmutt/linkerd2-proxy
d4f72c1aa4555f395007b628145b6b27707602c2
#![deny(warnings, rust_2018_idioms)] #![forbid(unsafe_code)] #![allow(clippy::inconsistent_struct_constructor)] use linkerd_stack::{layer, NewService, Proxy}; use pin_project::pin_project; use std::task::{Context, Poll}; use tracing::instrument::{Instrument as _, Instrumented}; use tracing::{trace, Span}; pub trait G...
#![deny(warnings, rust_2018_idioms)] #![forbid(unsafe_code)] #![allow(clippy::inconsistent_struct_constructor)] use linkerd_stack::{layer, NewService, Proxy}; use pin_project::pin_project; use std::task::{Context, Poll}; use tracing::instrument::{Instrument as _, Instrumented}; use tracing::{trace, Span}; pub trait G...
umentLayer::new(get_span) } } impl<T, G, N> NewService<T> for NewInstrument<G, N> where T: Clone, G: GetSpan<T> + Clone, N: NewService<T>, { type Service = Instrument<T, G, N::Service>; fn new_service(&mut self, target: T) -> Self::Service { let _span = self.get_span.get_span(&target)....
> { type Service = NewInstrument<G, N>; fn layer(&self, inner: N) -> Self::Service { NewInstrument { inner, get_span: self.get_span.clone(), } } } impl<G: Clone, N> NewInstrument<G, N> { pub fn layer(get_span: G) -> NewInstrumentLayer<G> { NewInstr
random
[ { "content": "pub fn layer<N, S, Req>() -> impl layer::Layer<N, Service = NewSplit<N, S, Req>> + Clone {\n\n // This RNG doesn't need to be cryptographically secure. Small and fast is\n\n // preferable.\n\n layer::mk(move |inner| NewSplit {\n\n inner,\n\n _service: PhantomData,\n\n })\...
Rust
rust/pact_matching_ffi/src/models/message_pact.rs
tonynguyenit18/pact-reference
44e7eb4d2a1c52c7077c08c4c2178246b11e022e
use crate::util::*; use crate::{as_mut, as_ref, ffi_fn, safe_str}; use anyhow::{anyhow, Context}; use libc::c_char; use std::iter::{self, Iterator}; use crate::models::message::Message; pub use pact_matching::models::message_pact::MessagePact; use pact_models::{Consumer, Provider}; ffi_fn! { ...
use crate::util::*; use crate::{as_mut, as_ref, ffi_fn, safe_str}; use anyhow::{anyhow, Context}; use libc::c_char; use std::iter::{self, Iterator}; use crate::models::message::Message; pub use pact_matching::models::message_pact::MessagePact; use pact_models::{Consumer, Provider}; ffi_fn! { ...
} impl Drop for MessagePactMetadataTriple { fn drop(&mut self) { string::string_delete(self.outer_key as *mut c_char); string::string_delete(self.inner_key as *mut c_char); string::string_delete(self.value as *mut c_char); } }
fn new( outer_key: &str, inner_key: &str, value: &str, ) -> anyhow::Result<MessagePactMetadataTriple> { Ok(MessagePactMetadataTriple { outer_key: string::to_c(outer_key)? as *const c_char, inner_key: string::to_c(inner_key)? as *const c_char, ...
function_block-full_function
[ { "content": "pub fn match_values<E, A>(path: &[&str], context: &MatchingContext, expected: E, actual: A) -> Result<(), Vec<String>>\n\n where E: Matches<A>, A: Clone {\n\n let matching_rules = context.select_best_matcher(path);\n\n match matching_rules {\n\n None => Err(vec![format!(\"No matche...
Rust
tests/tests.rs
fpruz/dbase-rs
7b2f350f5cd3775a3b0b63035461bdba9926a8b3
#[macro_use] extern crate dbase; use std::io::{Cursor, Read, Seek, Write}; use dbase::{ Date, DateTime, FieldIOError, FieldIterator, FieldName, FieldValue, FieldWriter, ReadableRecord, Reader, Record, TableWriterBuilder, Time, WritableRecord, }; use std::convert::{TryFrom, TryInto}; use std::fmt::Debug; cons...
#[macro_use] extern crate dbase; use std::io::{Cursor, Read, Seek, Write}; use dbase::{ Date, DateTime, FieldIOError, FieldIterator, FieldName, FieldValue, FieldWriter, ReadableRecord, Reader, Record, TableWriterBuilder, Time, WritableRecord, }; use std::convert::{TryFrom, TryInto}; use std::fmt::Debug; cons...
); } #[test] fn test_read_write_simple_file() { let mut expected_fields = Record::default(); expected_fields.insert( "name".to_owned(), dbase::FieldValue::Character(Some("linestring1".to_owned())), ); let mut reader = dbase::Reader::from_path(LINE_DBF).unwrap(); let records = reade...
s = Record::default(); expected_fields.insert( "name".to_owned(), dbase::FieldValue::Character(Some("linestring1".to_owned())), ); assert_eq!(records[0], expected_fields
function_block-random_span
[ { "content": "fn read_string_of_len<T: Read>(source: &mut T, len: u8) -> Result<String, std::io::Error> {\n\n let mut bytes = Vec::<u8>::new();\n\n bytes.resize(len as usize, 0u8);\n\n source.read_exact(&mut bytes)?;\n\n // Trims the null bytes: string cannot be properly trimmed otherwise\n\n let...
Rust
lab-06-division/src/main.rs
Tetrergeru/ComputerVision
7ffe95c21ce1ae1cb1d4d033ef2ebf45a71f761d
use opencv::{ core::{ abs, min_max_loc, no_array, subtract, Mat, Point, Scalar, BORDER_DEFAULT, CV_32F, CV_32FC1, CV_32S, CV_64FC1, CV_8UC1, CV_8UC3, }, highgui, imgcodecs::{self, IMREAD_GRAYSCALE}, imgproc::{ cvt_color, dilate, draw_contours, filter_2d, find_contours, ...
use opencv::{ core::{ abs, min_max_loc, no_array, subtract, Mat, Point, Scalar, BORDER_DEFAULT, CV_32F, CV_32FC1, CV_32S, CV_64FC1, CV_8UC1, CV_8UC3, }, highgui, imgcodecs::{self, IMREAD_GRAYSCALE}, imgproc::{ cvt_color, dilate, draw_contours, filter_2d, find_contours, ...
t_2d_mut(i, j)? = data[i as usize][j as usize]; } } Ok(mat) } fn invert(mat: &Mat) -> Result<Mat> { let mut clone = new_mat(CV_32FC1); mat.convert_to(&mut clone, CV_32FC1, -1.0, 1.0)?; Ok(clone) } fn sub_image(left: &Mat, right: &Mat) -> Result<Mat> { let mut clone = left.clone(); ...
let peaks = invert(&bw_thr)?; highgui::imshow("Peaks", &peaks)?; let mut background_markers = new_mat(CV_32F); let kernel1 = Mat::ones(5, 5, CV_8UC1)?; dilate( &peaks, &mut background_markers, &kernel1, Point::new(-1, -1), 7, BORDER_DEFAULT, morph...
random
[ { "content": "fn show(name: &str, mat: &Mat) -> Result<()> {\n\n highgui::named_window(name, 0)?;\n\n highgui::imshow(name, &{\n\n let mut clone = mat.clone();\n\n mat.convert_to(&mut clone, CV_8UC1, 255.0, 0.0)?;\n\n clone\n\n })?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "...
Rust
core/executor/src/native_contract/account.rs
KaoImin/huobi-chain-1
1c69a9fb03a29cdfc291fab62175a377828f7f63
use std::cell::RefCell; use std::collections::BTreeMap; use std::error::Error; use std::rc::Rc; use derive_more::{Display, From}; use protocol::traits::executor::contract::{AccountContract, ContractStateAdapter}; use protocol::traits::executor::RcInvokeContext; use protocol::types::{ Account, Address, AssetID, As...
use std::cell::RefCell; use std::collections::BTreeMap; use std::error::Error; use std::rc::Rc; use derive_more::{Display, From}; use protocol::traits::executor::contract::{AccountContract, ContractStateAdapter}; use protocol::traits::executor::RcInvokeContext; use protocol::types::{ Account, Address, AssetID, As...
let account = match address { Address::User(_) => Account::User(UserAccount { nonce: 0, assets: BTreeMap::new(), }), Address::Contract(_) => Account::Contract(ContractAccount { nonce: 0, assets: B...
if let Some(fixed_account) = self .state_adapter .borrow() .get::<FixedAccountSchema>(&address.clone())? { return Ok(fixed_account); }
if_condition
[ { "content": "pub fn mock_asset_id() -> AssetID {\n\n Hash::digest(Bytes::from(\"asset_id\"))\n\n}\n\n\n", "file_path": "protocol/src/fixed_codec/tests/mod.rs", "rank": 0, "score": 248767.8494690166 }, { "content": "pub fn mock_user_account() -> UserAccount {\n\n UserAccount {\n\n ...
Rust
consensus/src/liveness/proposal_generator.rs
zekun000/aptos-core
4fac00575269ce5b77ab6a18ac0a5f75abfe153d
use crate::{ block_storage::BlockReader, state_replication::TxnManager, util::time_service::TimeService, }; use anyhow::{bail, ensure, format_err, Context}; use consensus_types::{ block::Block, block_data::BlockData, common::{Author, Round}, quorum_cert::QuorumCert, }; use aptos_infallible::Mutex...
use crate::{ block_storage::BlockReader, state_replication::TxnManager, util::time_service::TimeService, }; use anyhow::{bail, ensure, format_err, Context}; use consensus_types::{ block::Block, block_data::BlockData, common::{Author, Round}, quorum_cert::QuorumCert, }; use aptos_infallible::Mutex...
fn ensure_highest_quorum_cert(&self, round: Round) -> anyhow::Result<Arc<QuorumCert>> { let hqc = self.block_store.highest_quorum_cert(); ensure!( hqc.certified_block().round() < round, "Given round {} is lower than hqc round {}", round, hqc.certifie...
pub async fn generate_proposal( &mut self, round: Round, wait_callback: BoxFuture<'static, ()>, ) -> anyhow::Result<BlockData> { { let mut last_round_generated = self.last_round_generated.lock(); if *last_round_generated < round { *last_round_g...
function_block-full_function
[ { "content": "// GET /\n\npub fn index(context: Context) -> BoxedFilter<(impl Reply,)> {\n\n warp::path::end()\n\n .and(warp::get())\n\n .and(context.filter())\n\n .and_then(handle_index)\n\n .with(metrics(\"get_ledger_info\"))\n\n .boxed()\n\n}\n\n\n\npub async fn handle_i...
Rust
src/connectivity/overnet/lib/core/src/node_table.rs
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
use crate::labels::{VersionCounter, LinkId, NodeId, INITIAL_VERSION, TOMBSTONE_VERSION}; use std::collections::{btree_map, BTreeMap, BTreeSet}; use std::time::Duration; use std::u64; #[derive(Debug)] pub struct NodeDescription { services: Vec<String>, } impl Default for NodeDescription { fn default() -> Sel...
use crate::labels::{VersionCounter, LinkId, NodeId, INITIAL_VERSION, TOMBSTONE_VERSION}; use std::collections::{btree_map, BTreeMap, BTreeSet}; use std::time::Duration; use std::u64; #[derive(Debug)] pub struct NodeDescription { services: Vec<String>, } impl Default for NodeDescription { fn default() -> Sel...
); } node_table } fn is_outcome(mut got: Vec<(NodeId, LinkId)>, outcome: &[(u64, u64)]) -> bool { let mut result = true; for (node_id, link_id) in outcome { if !remove_item(&((*node_id).into(), (*link_id).into()), &mut got) { println!("Expecte...
for (from, to, link_id, rtt) in links { node_table.update_link( (*from).into(), (*to).into(), (*link_id).into(), FIRST_VERSION, LinkDescription { round_trip_time: Duration::from_millis(*rtt), ...
function_block-random_span
[]
Rust
src/handler/content.rs
alluLinger/kylyp
5d7740fec021d3974bd04b34e3ebd7421ad8449a
use diesel; use diesel::prelude::*; use model::article::{Article,Comment,NewArticle,NewComment,STATUS}; use model::user::{User,NewMessage,message_mode,message_status}; use controller::user::UserId; use chrono::prelude::*; use regex::{Regex,Captures}; use config::*; use CFG_DEFAULT; use chrono::{DateTime,Utc}; use spong...
use diesel; use diesel::prelude::*; use model::article::{Article,Comment,NewArticle,NewComment,STATUS}; use model::user::{User,NewMessage,message_mode,message_status}; use controller::user::UserId; use chrono::prelude::*; use regex::{Regex,Captures}; use config::*; use CFG_DEFAULT; use chrono::{DateTime,Utc}; use spong...
pub fn get_user_articles(conn_pg: &Connection, user_id: i32) -> Vec<Article> { let u_id = user_id; let mut user_articles: Vec<Article> = vec![]; for row in &conn_pg.query("SELECT article.id, article.uid, article.category, article.status, article.comments_count, article.title, ...
let uid = user_id; let user_result = users.filter(&id.eq(&uid)).load::<User>(conn_dsl); let login_user = match user_result { Ok(user_s) => match user_s.first() { Some(a_user) => Some(a_user.clone()), None => None, }, Err(_) => None, }; login_user }
function_block-function_prefix_line
[ { "content": "#[get(\"/<aid>\")]\n\npub fn article(conn_pg: ConnPg, conn_dsl: ConnDsl, user: UserOr, aid: i32, user_id: UserId) -> Template {\n\n let article_data = get_article_by_aid(&conn_pg, aid);\n\n let comment_data = get_comment_by_aid(&conn_pg, aid);\n\n let context = TemplateContext {\n\n ...
Rust
program-native/src/game.rs
sunnygleason/example-tictactoe
5fa8e50468403eab3bcb9fcbd80ba49e3853f2c4
use result::{ProgramError, Result}; use solana_sdk::pubkey::Pubkey; const BOARD_ITEM_FREE: u8 = 0; const BOARD_ITEM_X: u8 = 1; const BOARD_ITEM_O: u8 = 2; #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)] pub enum GameState { Waiting, XMove, OMove, XWon, OWon, Draw, } impl De...
use result::{ProgramError, Result}; use solana_sdk::pubkey::Pubkey; const BOARD_ITEM_FREE: u8 = 0; const BOARD_ITEM_X: u8 = 1; const BOARD_ITEM_O: u8 = 2; #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)] pub enum GameState { Waiting, XMove, OMove, XWon, OWon, Draw, } impl De...
#[test] pub fn left_diagonal_x_wins() { /* X|O|X -+-+- O|X|O -+-+- O|X|X */ let player_x = Pubkey::new(&[1; 32]); let player_o = Pubkey::new(&[2; 32]); let mut g = Game::new(player_x, player_o); g.nex...
pub fn bottom_row_o_wins() { /* X|X| -+-+- X| | -+-+- O|O|O */ let player_x = Pubkey::new(&[1; 32]); let player_o = Pubkey::new(&[2; 32]); let mut g = Game::new(player_x, player_o); g.next_move(player_x, 0, 0)....
function_block-full_function
[ { "content": "fn process_instruction(info: &mut [KeyedAccount], input: &[u8], tick_height: u64) -> Result<()> {\n\n let command = Command::deserialize(input)?;\n\n debug!(\"entrypoint: command={:?}\", command);\n\n\n\n if command == Command::InitDashboard {\n\n expect_n_accounts(info, 1)?;\n\n ...
Rust
hello-world/src/main.rs
snehainguva/rust-practice
bc196b6d3c70ea7810a0707e3bed1cb8569a2407
use std::{fmt::Display}; pub struct Point { pub x: i32, pub y: i32, } #[derive(Debug)] struct SemVer { major: u16, minor: u16, patch: u16, } enum CrateKind { Binary, Library, Other {description: String }, } struct Crate { version: SemVer, kind: CrateKind, } impl SemVer...
use std::{fmt::Display}; pub struct Point { pub x: i32, pub y: i32, } #[derive(Debug)] struct SemVer { major: u16, minor: u16, patch: u16, } enum CrateKind { Binary, Library, Other {description: String }, } struct Crate { version: SemVer, kind: CrateKind, } impl SemVer...
fn info(&self) { println!("I am a SemVer! major number: {}", self.major) } } fn main() { println!("Hello, world!"); let an_int: i32 = 123; let a_big_int: i32 = 1_000_000; let a_float: f64 = 3.14; let less_precise_float: f32 = 3.1416; let a_string_slice: &str = "hello, s...
fn new(major: u16, minor:u16, patch: u16) -> Self { Self { major, minor, patch, } }
function_block-full_function
[ { "content": "#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]\n\nstruct SemVer {\n\n major: u16,\n\n minor: u16,\n\n patch: u16,\n\n}\n\n\n\nimpl SemVer {\n\n fn new(major: u16, minor: u16, patch: u16) -> SemVer {\n\n SemVer {\n\n major,\n\n minor,\n...
Rust
src/google/api/control.rs
jrconlin/rspan
b1889e70f62a84936717ce84beb02279c76f8218
#![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #!...
#![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #!...
#[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if !self.environment.is_empty() { my_size += ::protobuf::rt::string_size(1, &self.environment); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); ...
e) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.environment)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_typ...
function_block-function_prefixed
[ { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n unsafe {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n }\n\n}\n", "file_path": "src/google/protobuf/struct_pb.rs", "rank": 1, "s...
Rust
src/main.rs
andrewhickman/midi-playback
2ce09bdb1a78b0744dbc26e3e60b67112429bd11
use std::{ mem, sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }, time::Duration, }; use anyhow::{Context, Result}; use midir::{Ignore, MidiInput, MidiOutput}; use nwg::NativeUi; mod db; mod ui; #[derive(Clone, Default)] struct PlaybackEngine { inner: Arc<Mutex<PlaybackEngine...
use std::{ mem, sync::{ atomic::{AtomicBool, Ordering}, Arc, Mutex, }, time::Duration, }; use anyhow::{Context, Result}; use midir::{Ignore, MidiInput, MidiOutput}; use nwg::NativeUi; mod db; mod ui; #[derive(Clone, Default)] struct PlaybackEngine { inner: Arc<Mutex<PlaybackEngine...
} impl Default for PlaybackEngineState { fn default() -> Self { PlaybackEngineState::Idle } }
PlaybackEngineState::Playing { stop_handle } => { stop_handle.store(true, Ordering::Relaxed); } _ => (), } }
function_block-function_prefix_line
[ { "content": "pub fn write_phrase(phrase: &Phrase) -> anyhow::Result<()> {\n\n let path = \"./data/phrase.dat\";\n\n let bytes = phrase.encode_to_vec();\n\n fs_err::write(path, bytes)?;\n\n Ok(())\n\n}\n", "file_path": "src/db/mod.rs", "rank": 0, "score": 92753.41554165824 }, { "...
Rust
src/saf/read/reader.rs
MaltheSR/angsd-io
387ac4abf19931d98c0c6b43703a9484c6ad3f06
use std::{fs::File, io, path::Path}; #[cfg(feature = "ndarray")] use ndarray::{Array, Array2}; use super::{iter, BinaryRead, PositionReader, ValueReader}; use crate::{ saf::{ self, constants::{INDEX_EXTENSION, POSITION_EXTENSION, VALUE_EXTENSION}, index, }, utils, }; #[derive(Deb...
use std::{fs::File, io, path::Path}; #[cfg(feature = "ndarray")] use ndarray::{Array, Arr
_paths<P>(index_path: &P, position_path: &P, value_path: &P) -> io::Result<Self> where P: AsRef<Path>, { let index = File::open(index_path).map(|x| index::Reader::new(x).read_index())??; let position_reader = PositionReader::from_path(position_path)?; let value_reader = ValueRe...
ay2}; use super::{iter, BinaryRead, PositionReader, ValueReader}; use crate::{ saf::{ self, constants::{INDEX_EXTENSION, POSITION_EXTENSION, VALUE_EXTENSION}, index, }, utils, }; #[derive(Debug)] pub struct Reader<R> { index: index::Index, position_reader: PositionReader<R...
random
[ { "content": "fn main() -> io::Result<()> {\n\n let path = env::args().nth(1).expect(\"missing path to GLF file\");\n\n let n = env::args()\n\n .nth(2)\n\n .map(|s| s.parse().expect(\"failed to parse number of individuals\"))\n\n .unwrap_or(1);\n\n let mut reader = glf::BgzfReader:...
Rust
weld/src/codegen/llvm2/jit.rs
winding-lines/weld
beebaacabd11327dea2e51071b708de238c84386
use libc; use llvm_sys; use time; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use std::sync::{Once, ONCE_INIT}; use libc::c_char; use self::time::PreciseTime; use crate::conf::ParsedConf; use crate::error::*; use crate::util::stats::CompilationStats; use self::llvm_sys::core::*; use self::llvm_sys...
use libc; use llvm_sys; use time; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use std::sync::{Once, ONCE_INIT}; use libc::c_char; use self::time::PreciseTime; use crate::conf::ParsedConf; use crate::error::*; use crate::util::stats::CompilationStats; use self::llvm_sys::core::*; use self::llvm_sys...
pub unsafe fn set_triple_and_layout(module: LLVMModuleRef) -> WeldResult<()> { LLVMSetTarget(module, PROCESS_TRIPLE.as_ptr() as *const _); debug!("Set module target {:?}", PROCESS_TRIPLE.to_str().unwrap()); let target_machine = target_machine()?; let layout = LLVMCreateTargetDataLayout(target_machine)...
unsafe fn target_machine() -> WeldResult<LLVMTargetMachineRef> { let mut target = mem::uninitialized(); let mut err = ptr::null_mut(); let ret = LLVMGetTargetFromTriple(PROCESS_TRIPLE.as_ptr(), &mut target, &mut err); if ret == 1 { let err_msg = CStr::from_ptr(err as *mut c_char) .to...
function_block-full_function
[]
Rust
src/main.rs
shawnanastasio/rudo
e746f3420028a949b01df8c87beb374e56ee9ded
use std::env; use std::io; use std::error::Error; use std::process; use std::process::Command; use std::io::Write; use std::os::unix::process::CommandExt; mod session; mod auth; use auth::authenticate_current_user_n; mod osutils; use osutils::OSUtils; use osutils::unix::UnixOSUtils; mod settings; use settings::Setti...
use std::env; use std::io; use std::error::Error; use std::process; use std::process::Command; use std::io::Write; use std::os::unix::process::CommandExt; mod session; mod auth; use auth::authenticate_current_user_n; mod osutils; use osutils::OSUtils; use osutils::unix::UnixOSUtils; mod settings; use settings::Setti...
fn run_command<T: OSUtils>(osutils: &T, user: Option<String>, group: Option<String>, command: &str, args: &Vec<String>) -> Result<i32, Box<dyn Error>> { let settings = Settings::from_file(CONFIG_PATH) .expect("Unable to read configuration file! Run --genconfig."); let auth_res = authe...
gs, 3)?; if !auth_res { return Ok(1); } let username = osutils.get_username()?; let user = settings.get_user(&username)?; let mut all_commands: String = String::new(); for cmd in &user.permissions.allowed_commands { all_commands += cmd; all_commands += " "; ...
function_block-function_prefixed
[ { "content": "/// Create a session for the given user that will last for the given time in seconds\n\npub fn create_session(username: &str, time: i64) -> Result<(), Box<dyn Error>> {\n\n // Make sure the user has a session directory and it has the correct permissions\n\n init_session_dir(username);\n\n\n\...
Rust
crates/mun_compiler/src/diagnostics.rs
parasyte/mun
73d0839380a711c61885735320de78c4639691f8
use mun_hir::diagnostics::DiagnosticSink; use mun_hir::{FileId, HirDatabase, Module}; use std::cell::RefCell; use annotate_snippets::snippet::Snippet; use crate::diagnostics_snippets; pub fn diagnostics(db: &impl HirDatabase, file_id: FileId) -> Vec<Snippet> { let parse = db.parse(file_id); let mut result ...
use mun_hir::diagnostics::DiagnosticSink; use mun_hir::{FileId, HirDatabase, Module}; use std::cell::RefCell; use annotate_snippets::snippet::Snippet; use crate::diagnostics_snippets; pub fn diagnostics(db: &impl HirDatabase, file_id: FileId) -> Vec<Snippet> { let parse = db.parse(file_id); let mut result ...
&line_index, )); }) .on::<mun_hir::diagnostics::AccessUnknownField, _>(|d| { result .borrow_mut() .push(diagnostics_snippets::access_unknown_field_error( d, db, &parse, &relative_file_path, ...
le_relative_path(file_id).display().to_string(); let line_index = db.line_index(file_id); result.extend(parse.errors().iter().map(|err| { diagnostics_snippets::syntax_error( err, db, &parse, &relative_file_path, &source_code, &lin...
random
[ { "content": "/// Main entry point for the language server\n\npub fn run_server() -> Result<()> {\n\n async_std::task::block_on(run_server_async())\n\n}\n", "file_path": "crates/mun_language_server/src/lib.rs", "rank": 1, "score": 217580.70013810927 }, { "content": "/// Generates the gene...
Rust
crates/yuck/src/parser/ast_iterator.rs
druskus20/eww
106106ade31e7cc669f2ae53f24191cd0a683c39
use itertools::Itertools; use simplexpr::{ast::SimplExpr, dynval::DynVal}; use std::collections::HashMap; use std::fmt::Display; use super::{ ast::{Ast, AstType}, from_ast::FromAst, }; use crate::{ config::attributes::{AttrEntry, Attributes}, error::{AstError, AstResult, OptionAstErrorExt}, }; use eww...
use itertools::Itertools; use simplexpr::{ast::SimplExpr, dynval::DynVal}; use std::collections::HashMap; use std::fmt::Display; use super::{ ast::{Ast, AstType}, from_ast::FromAst, }; use crate::{ config::attributes::{AttrEntry, Attributes}, error::{AstError, AstResult, OptionAstErrorExt}, }; use eww...
self.put_back(other); Err(AstError::WrongExprType(span, expr_type, actual_type)) } } } )* }; } impl<I: Iterator<Item = Ast>> AstIterator<I> { return_or_put_back! { fn expect_symbol -> AstType::Symbol, (Span, Stri...
er: itertools::PutBack<I>, } macro_rules! return_or_put_back { ($(fn $name:ident -> $expr_type:expr, $t:ty = $p:pat => $ret:expr)*) => { $( pub fn $name(&mut self) -> AstResult<$t> { let expr_type = $expr_type; match self.expect_any()? { $p =>...
random
[ { "content": "/// get a single ast node from a list of asts, returning an Err if the length is not exactly 1.\n\npub fn require_single_toplevel(span: Span, mut asts: Vec<Ast>) -> AstResult<Ast> {\n\n match asts.len() {\n\n 0 => Err(AstError::MissingNode(span)),\n\n 1 => Ok(asts.remove(0)),\n\n ...
Rust
vendor/bstr/src/slice_index.rs
raspbian-packages/cargo
3b1b88e08c83b03469c9a98c3237317c7eb5c330
use core::ops; use bstr::BStr; pub trait Sealed {} impl Sealed for usize {} impl Sealed for ops::Range<usize> {} impl Sealed for ops::RangeTo<usize> {} impl Sealed for ops::RangeFrom<usize> {} impl Sealed for ops::RangeFull {} impl Sealed for ops::RangeInclusive<usize> {} impl Sealed for ops::RangeToInclusive<usize> ...
use core::ops; use bstr::BStr; pub trait Sealed {} impl Sealed for usize {} impl Sealed for ops::Range<usize> {} impl Sealed for ops::RangeTo<usize> {} impl Sealed for ops::RangeFrom<usize> {} impl Sealed for ops::RangeFull {} impl Sealed for ops::RangeInclusive<usize> {} impl Sealed for ops::RangeToInclusive<usize> ...
BStr) -> &BStr { &slice[self] } #[inline] fn index_mut(self, slice: &mut BStr) -> &mut BStr { &mut slice[self] } } impl SliceIndex for ops::RangeTo<usize> { type Output = BStr; #[inline] fn get(self, slice: &BStr) -> Option<&BStr> { slice.as_bytes().get(self).map(B...
f::Output; fn index(self, slice: &BStr) -> &Self::Output; fn index_mut(self, slice: &mut BStr) -> &mut Self::Output; } impl SliceIndex for usize { type Output = u8; #[inline] fn get(self, slice: &BStr) -> Option<&u8> { slice.as_bytes().get(self) } #[inline] ...
random
[ { "content": " #[lang = \"sized\"]\n\n pub trait Sized {\n\n // Empty.\n\n }\n", "file_path": "tests/testsuite/custom_target.rs", "rank": 0, "score": 242596.01418561712 }, { "content": "pub fn output_depinfo<'a, 'b>(cx: &mut Context<'a, 'b>, un...
Rust
frame/lending/src/mocks/oracle.rs
ArturoFinance/composable
8ea2468b3ea955cf12dc98a0fbd4979788c67864
pub use pallet::*; #[frame_support::pallet] pub mod pallet { use codec::Codec; use composable_traits::{ currency::LocalAssets, math::SafeArithmetic, oracle::{Oracle, Price}, vault::Vault, }; use frame_support::pallet_prelude::*; use sp_runtime::{ helpers_128bit::multiply_by_rational, ArithmeticError, Di...
pub use pallet::*; #[frame_support::pallet] pub mod pallet { use codec::Codec; use composable_traits::{ currency::LocalAssets, math::SafeArithmetic, oracle::{Oracle, Price}, vault::Vault, }; use frame_support::pallet_prelude::*; use sp_runtime::{ helpers_128bit::multiply_by_rational, ArithmeticError, Di...
let price = multiply_by_rational(p, a, e) .map_err(|_| DispatchError::Arithmetic(ArithmeticError::Overflow))?; Ok(Price { price, block: () }) }; #[allow(clippy::inconsistent_digit_grouping)] match asset { /* NOTE(hussein-aitlahcen) Ideally we would have all the static currency quoted a...
let e = 10_u128 .checked_pow(Self::LocalAssets::decimals(asset)?) .ok_or(DispatchError::Arithmetic(ArithmeticError::Overflow))?;
assignment_statement
[]
Rust
below/view/src/controllers/view_controllers.rs
ahornby/below
7b2ce1e135a2a023ae62af3201092e84f7d0db26
use super::*; use crate::MainViewState; use cursive::views::{NamedView, OnEventView, ResizedView, StackView}; make_event_controller!( InvokeCmdPalette, "invoke_cmd_palette", "", Event::Char(':'), |view: &mut StatsView<T>, _cmd_vec: &[&str]| { view.get_cmd_palette().invoke_cmd(); } );...
use super::*; use crate::MainViewState; use cursive::views::{NamedView, OnEventView, ResizedView, StackView}; make_event_controller!( InvokeCmdPalette, "invoke_cmd_palette", "", Event::Char(':'), |view: &mut StatsView<T>, _cmd_vec: &[&str]| { view.get_cmd_palette().invoke_cmd(); } );...
et_mut()) .find_layer_from_name("cgroup_view_panel") .expect("Failed to find cgroup view"); (*stack.get_mut()).move_to_front(cgroup_pos); } MainViewState::Core => {} } }) .expect("failed to fi...
.main_view_state .clone(); if current_state == MainViewState::ProcessZoomedIntoCgroup { crate::process_view::ProcessView::get_process_view(c) .state .borrow_mut() .reset_state_for_quiting_zoom(); } c.us...
random
[ { "content": "fn fill_content(c: &mut Cursive, v: &mut LinearLayout) {\n\n let view_state = &c\n\n .user_data::<ViewState>()\n\n .expect(\"No data stored in Cursive object!\");\n\n\n\n let system_model = view_state.system.borrow();\n\n let network_model = view_state.network.borrow();\n\n ...
Rust
genesis-programs/src/lib.rs
sorpaas/solana
1ffd6b4b4d43e28eab010914427efa1d67b5595c
use solana_sdk::{ clock::Epoch, genesis_config::OperatingMode, inflation::Inflation, move_loader::solana_move_loader_program, nonce_program::solana_nonce_program, pubkey::Pubkey, system_program::solana_system_program, }; #[macro_use] extern crate solana_bpf_loader_program; #[macro_use] extern crate solana_...
use solana_sdk::{ clock::Epoch, genesis_config::OperatingMode, inflation::Inflation, move_loader::solana_move_loader_program, nonce_program::solana_nonce_program, pubkey::Pubkey, system_program::solana_system_program, }; #[macro_use] extern crate solana_bpf_loader_program; #[macro_use] extern crate solana_...
#[cfg(test)] mod tests { use super::*; use solana_sdk::nonce_program::solana_nonce_program; use std::collections::HashSet; #[test] fn test_id_uniqueness() { let mut unique = HashSet::new(); let ids = get_programs(OperatingMode::Development, 0).unwrap(); assert!(ids.into_it...
f let Some(inflation) = get_inflation(operating_mode, bank.epoch()) { bank.set_inflation(inflation); } if let Some(new_programs) = get_programs(operating_mode, bank.epoch()) { for (name, program_id) in new_programs.iter() { info!("Registering {} at {}", name, prog...
function_block-function_prefixed
[ { "content": "/// At the specified epoch, collect the delegate account balance and vote states for delegates\n\n/// that have non-zero balance in any of their managed staking accounts\n\npub fn staked_nodes_at_epoch(bank: &Bank, epoch: Epoch) -> Option<HashMap<Pubkey, u64>> {\n\n bank.epoch_vote_accounts(epo...
Rust
rust/serde_bser/src/de/bunser.rs
louissobel/watchman
461f99e1e22546025a5d3a4fcd28a59bf9809914
use byteorder::{ByteOrder, NativeEndian}; use de::read::{DeRead, Reference}; use errors::*; use header::*; #[derive(Debug)] pub struct Bunser<R> { read: R, scratch: Vec<u8>, } pub struct PduInfo { pub bser_capabilities: u32, len: i64, start: i64, } impl<'de, R> Bunser<R> where R: DeRead<'d...
use byteorder::{ByteOrder, NativeEndian}; use de::read::{DeRead, Reference}; use errors::*; use header::*; #[derive(Debug)] pub struct Bunser<R> { read: R, scratch: Vec<u8>, } pub struct PduInfo { pub bser_capabilities: u32, len: i64, start: i64, } impl<'de, R> Bunser<R> where R: DeRead<'d...
}
pub fn next_f64(&mut self) -> Result<f64> { self.read.discard(); let bytes = self.read_bytes(8) .chain_err(|| "error while reading f64")? .get_ref(); Ok(NativeEndian::read_f64(bytes)) }
function_block-full_function
[ { "content": "pub fn header_byte_desc(byte: u8) -> String {\n\n match byte {\n\n BSER_ARRAY => \"BSER_ARRAY\".into(),\n\n BSER_OBJECT => \"BSER_OBJECT\".into(),\n\n BSER_BYTESTRING => \"BSER_BYTESTRING\".into(),\n\n BSER_INT8 => \"BSER_INT8\".into(),\n\n BSER_INT16 => \"BSE...
Rust
ark-bcs/src/bcs/constraints/transcript.rs
arkworks-rs/bcs
baf903d87c0ee98d82e931610439b3d0e03a982f
use crate::{ bcs::{constraints::proof::BCSProofVar, transcript::LDTInfo}, iop::{ bookkeeper::{MessageBookkeeper, NameSpace}, constraints::{ message::VerifierMessageVar, oracles::{VirtualOracleVar, VirtualOracleVarWithInfo}, }, message::{LeavesType, MsgRoun...
use crate::{ bcs::{constraints::proof::BCSProofVar, transcript::LDTInfo}, iop::{ bookkeeper::{MessageBookkeeper, NameSpace}, constraints::{ message::VerifierMessageVar, oracles::{VirtualOracleVar, VirtualOracleVarWithInfo}, }, message::{LeavesType, MsgRoun...
fn attach_latest_verifier_round_to_namespace( &mut self, namespace: NameSpace, trace: TraceInfo, ) -> MsgRoundRef { let index = self.reconstructed_verifier_messages.len() - 1; self.bookkeeper .attach_verifier_round_to_namespace(namespace, index, tra...
fn attach_latest_prover_round_to_namespace( &mut self, namespace: NameSpace, is_virtual: bool, trace: TraceInfo, ) -> MsgRoundRef { let index = if is_virtual { self.registered_virtual_oracles.len() - 1 } else { self.current_prover_roun...
function_block-full_function
[ { "content": "/// fix a bit array to a certain length by remove extra element on the end or\n\n/// pad with zero\n\nfn fit_bits_to_length<F: PrimeField>(bits: &[Boolean<F>], length: usize) -> Vec<Boolean<F>> {\n\n if bits.len() < length {\n\n bits.to_vec()\n\n .into_iter()\n\n .c...
Rust
common/crypto/src/asymmetric/encryption/mod.rs
tommyv1987/nym
938eb2d0f0220a8411b6462b76480223140bc033
use pemstore::traits::{PemStorableKey, PemStorableKeyPair}; use rand::{CryptoRng, RngCore}; use std::fmt::{self, Display, Formatter}; pub const PRIVATE_KEY_SIZE: usize = 32; pub const PUBLIC_KEY_SIZE: usize = 32; pub const SHARED_SECRET_SIZE: usize = 32; #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum KeyRe...
use pemstore::traits::{PemStorableKey, PemStorableKeyPair}; use rand::{CryptoRng, RngCore}; use std::fmt::{self, Display, Formatter}; pub const PRIVATE_KEY_SIZE: usize = 32; pub const PUBLIC_KEY_SIZE: usize = 32; pub const SHARED_SECRET_SIZE: usize = 32; #[derive(Clone, Copy, Eq, PartialEq, Debug)] pub enum KeyRe...
#[test] fn works_for_backward_conversion() { for _ in 0..NUM_ITERATIONS { let (sphinx_private, sphinx_public) = nymsphinx_types::crypto::keygen(); let private_bytes = sphinx_private.to_bytes(); let public_bytes = sphinx_public.as_bytes(); let private: ...
let recovered_private = PrivateKey::from(sphinx_private); let sphinx_public: nymsphinx_types::PublicKey = public.into(); let recovered_public = PublicKey::from(sphinx_public); assert_eq!(private_bytes, recovered_private.to_bytes()); assert_eq!(public_bytes, recovered_pub...
function_block-function_prefix_line
[]
Rust
src/dsc/roman_numeral.rs
CmdrMoozy/euler
ae30dcaeb86b8442b5e7f95565f72175e6abeeb4
use crate::util::error::*; use failure::bail; use lazy_static::lazy_static; use regex::Regex; use std::cmp::Ordering; use std::collections::BTreeSet; use std::collections::HashMap; use std::collections::HashSet; use std::fmt; use std::hash::{Hash, Hasher}; use std::str::FromStr; #[derive(Clone, Debug)] struct ValueP...
use crate::util::error::*; use failure::bail; use lazy_static::lazy_static; use regex::Regex; use std::cmp::Ordering; use std::collections::BTreeSet; use std::collections::HashMap; use std::collections::HashSet; use std::fmt; use std::hash::{Hash, Hasher}; use std::str::FromStr; #[derive(Clone, Debug)] struct ValueP...
}
fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> { let mut v: u64 = self.value; for ov in OUTPUT_VALUES.iter().rev() { while v >= ov.value { write!(f, "{}", ov.text)?; v -= ov.value; } } Ok(()) }
function_block-full_function
[ { "content": "/// This is a convenient shorthand to call permutate() with a standard <\n\n/// comparator.\n\npub fn permutate_lt<T: Ord>(v: &mut Vec<T>) -> bool {\n\n permutate(v, |a, b| a.cmp(b))\n\n}\n\n\n", "file_path": "src/algorithm/sequence.rs", "rank": 2, "score": 232387.44655564672 }, ...
Rust
src/plugins/nut/graphql/members.rs
cinnabaris/Arche
980cdf77dc6285d8b2ee24d09f2505837faa1305
use std::ops::Deref; use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc}; use diesel::{delete, insert_into, prelude::*, update}; use rocket::http::Status; use validator::Validate; use super::super::super::super::{ errors::Result, graphql::{context::Context, H}, orm::{schema::members, Connection as Db}, ...
use std::ops::Deref; use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc}; use diesel::{delete, insert_into, prelude::*, update}; use rocket::http::Status; use validator::Validate; use super::super::super::super::{ errors::Result, graphql::{context::Context, H}, orm::{schema::members, Connection as Db}, ...
#[derive(GraphQLInputObject, Debug, Validate, Deserialize)] pub struct Create { #[validate(length(min = "1"))] pub nick_name: String, #[validate(length(min = "1"))] pub real_name: String, pub gender: String, pub birthday: String, pub phone: Option<String>, pub email: Option<String>, ...
pub fn list(ctx: &Context) -> Result<Vec<Member>> { let user = ctx.current_user()?; let db = ctx.db.deref(); can_view(db, &user.id)?; let items = members::dsl::members .select(( members::dsl::id, members::dsl::nick_name, members::dsl::real_name, me...
function_block-full_function
[ { "content": "pub fn sign_in(db: &Db, id: &i64, ip: &String) -> Result<()> {\n\n let now = Utc::now().naive_utc();\n\n let it = users::dsl::users.filter(users::dsl::id.eq(id));\n\n let (current_sign_in_at, current_sign_in_ip, sign_in_count) = users::dsl::users\n\n .select((\n\n users:...
Rust
tonic/src/codec/decode.rs
NeoLegends/tonic
5d0a7955541509d2dbfdb9b689fb57cd2b842172
use super::Decoder; use crate::{body::BoxBody, metadata::MetadataMap, Code, Status}; use bytes::{Buf, BufMut, Bytes, BytesMut, IntoBuf}; use futures_core::Stream; use futures_util::{future, ready}; use http::StatusCode; use http_body::Body; use std::{ fmt, pin::Pin, task::{Context, Poll}, }; use tracing::{d...
use super::Decoder; use crate::{body::BoxBody, metadata::MetadataMap, Code, Status}; use bytes::{Buf, BufMut, Bytes, BytesMut, IntoBuf}; use futures_core::Stream; use futures_util::{future, ready}; use http::StatusCode; use http_body::Body; use std::{ fmt, pin::Pin, task::{Context, Poll}, }; use tracing::{d...
} impl<T> Stream for Streaming<T> { type Item = Result<T, Status>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { loop { match self.decode_chunk()? { Some(item) => return Poll::Ready(Some(Ok...
len, } } if let State::ReadBody { len, .. } = &self.state { if buf.remaining() < *len { return Ok(None); } self.buf.advance(5); match self.decoder.decode(&mut self.buf) { Ok(Some(msg)) => { ...
function_block-function_prefix_line
[ { "content": "fn invalid_header_value_byte<Error: fmt::Display>(err: Error) -> Status {\n\n debug!(\"Invalid header: {}\", err);\n\n Status::new(\n\n Code::Internal,\n\n \"Couldn't serialize non-text grpc status header\".to_string(),\n\n )\n\n}\n\n\n\n#[cfg(feature = \"h2\")]\n\nimpl From...
Rust
rust-sgx/sgxs-loaders/src/sgx_enclave_common/mod.rs
jethrosun/SafeBricks
290734c3f50a41dfd7bcd155d0447dd250e4fc10
/* Copyright (c) Fortanix, Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub extern crate libloading as dl; use std::convert::TryFrom; use std::io::{Re...
/* Copyright (c) Fortanix, Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pub extern crate libloading as dl; use std::convert::TryFrom; use std::io::{Re...
o.flags.intersects(SecinfoFlags::R) { flags.insert(PageProperties::R) } if eadd.secinfo.flags.intersects(SecinfoFlags::W) { flags.insert(PageProperties::W) } if eadd.secinfo.flags.intersects(SecinfoFlags::X) { flags.insert(PageProperties::X) } ...
dd( mapping: &mut Mapping<Self>, page: (MeasEAdd, PageChunks, [u8; 4096]), ) -> Result<(), Self::Error> { let (eadd, chunks, data) = page; let mut flags = PageProperties::empty(); if eadd .secinfo .flags .intersects(SecinfoFlags::PENDING |...
function_block-random_span
[ { "content": "pub fn run_server(file: String) -> Result<(), ()> {\n\n let mut device = IsgxDevice::new()\n\n .unwrap()\n\n .einittoken_provider(AesmClient::new())\n\n .build();\n\n\n\n let mut enclave_builder = EnclaveBuilder::new(file.as_ref());\n\n enclave_builder.dummy_signature...
Rust
amethyst_derive/tests/system_desc.rs
murarth/amethyst
ac3de03a2bf650c5069186c3a8e3c14c9f4d14fd
use std::marker::PhantomData; use amethyst_core::{ ecs::{System, SystemData, World, WorldExt}, shrev::{EventChannel, ReaderId}, SystemDesc, }; use amethyst_error::Error; use amethyst_derive::SystemDesc; #[test] fn simple_derive() -> Result<(), Error> { #[derive(Debug, SystemDesc)] struct SystemUn...
use std::marker::PhantomData; use amethyst_core::{ ecs::{System, SystemData, World, WorldExt}, shrev::{EventChannel, ReaderId}, SystemDesc, }; use amethyst_error::Error; use amethyst_derive::SystemDesc; #[test] fn simple_derive() -> Result<(), Error> { #[derive(Debug, SystemDesc)] struct SystemUn...
#[test] fn struct_tuple_with_event_channel_reader() -> Result<(), Error> { #[derive(Debug, SystemDesc)] #[system_desc(name(SystemTupleEventChannelDesc))] struct SystemTupleEventChannel(#[system_desc(event_channel_reader)] ReaderId<u32>); impl SystemTupleEventChannel { fn new(reader_id: Re...
fn struct_tuple_with_passthrough() -> Result<(), Error> { #[derive(Debug, Default, SystemDesc)] #[system_desc(name(SystemTuplePassthroughDesc))] struct SystemTuplePassthrough(u32); impl<'s> System<'s> for SystemTuplePassthrough { type SystemData = (); fn run(&mut self, _: Self::SystemDa...
function_block-full_function
[ { "content": "fn create_default_mat<B: Backend>(world: &mut World) -> Material {\n\n use crate::mtl::TextureOffset;\n\n\n\n use amethyst_assets::Loader;\n\n\n\n let loader = world.fetch::<Loader>();\n\n\n\n let albedo = load_from_srgba(Srgba::new(0.5, 0.5, 0.5, 1.0));\n\n let emission = load_from...
Rust
cabi/src/sourcemap.rs
unclead/symbolic
5a8376714d26d0340729fe14973c2bdb871a1e55
use std::os::raw::c_char; use std::ptr; use std::slice; use symbolic::sourcemap::{SourceMapView, SourceView, TokenMatch}; use crate::core::SymbolicStr; use crate::utils::ForeignObject; pub struct SymbolicSourceView; impl ForeignObject for SymbolicSourceView { type RustObject = SourceView<'static>; } pub struct...
use std::os::raw::c_char; use std::ptr; use std::slice; use symbolic::sourcemap::{SourceMapView, SourceView, TokenMatch}; use crate::core::SymbolicStr; use crate::utils::ForeignObject; pub struct SymbolicSourceView; impl ForeignObject for SymbolicSourceView { type RustObject = SourceView<'static>; } pub struct...
; Ok(convert_token_match(token)) } } ffi_fn! { unsafe fn symbolic_sourcemapview_get_sourceview( source_map: *const SymbolicSourceMapView, index: u32 ) -> Result<*const SymbolicSourceView> { Ok(match SymbolicSourceMapView::as_rust(source_map).get_source_view(index) { ...
onst _, len); let view = SourceMapView::from_json_slice(slice)?; Ok(SymbolicSourceMapView::from_rust(view)) } } ffi_fn! { unsafe fn symbolic_sourcemapview_free(source_map: *mut SymbolicSourceMapView) { SymbolicSourceMapView::drop(source_map); } } fn convert_token_match(token: ...
random
[ { "content": "/// Converts an owned raw pointer to characters to an owned `String`.\n\n///\n\n/// If the pointer is NULL, an empty string `\"\"` is returned.\n\npub fn ptr_to_string(ptr: *mut c_char) -> String {\n\n if ptr.is_null() {\n\n return String::new();\n\n }\n\n\n\n let string = unsafe {...
Rust
src/schema/wires/mod.rs
xavierhamel/oregano
0b642515fb7821aa91aa901f0513523aa7a86789
mod layout; pub mod wire; use crate::intrinsics::*; use crate::schema::{mouse, parts, utils}; pub use layout::*; pub use wire::*; pub struct Wires { pub wires: Vec<Wire>, pub selected: Vec<usize>, copied: Vec<usize>, } impl Wires { pub fn new() -> Self { let wires = vec![Wire::new(Point::new(0...
mod layout; pub mod wire; use crate::intrinsics::*; use crate::schema::{mouse, parts, utils}; pub use layout::*; pub use wire::*; pub struct Wires { pub wires: Vec<Wire>, pub selected: Vec<usize>, copied: Vec<usize>, } impl Wires { pub fn new() -> Self { let wires = vec![Wire::new(Point::new(0...
} return false; } pub fn iter(&self) -> std::slice::Iter<'_, Wire> { self.wires.iter() } pub fn collide_with_point(&self, point: Point) -> Vec<usize> { let mut collisions = Vec::new(); for (idx, wire) in self.wires.iter().enumerate() { if wire.layou...
if self.wires[idx].collide_with_point(mouse.scene_pos) == &utils::Colliding::Shape { return true; }
if_condition
[ { "content": "pub fn ground() -> parts::Layout {\n\n let size = Size::new(20.0, 15.0);\n\n let offset = 5.0;\n\n parts::Layout::new(\n\n Point::new(0.0, 0.0),\n\n shape::Shape::new(\n\n vec![\n\n vec![\n\n Point::new(size.w / 2.0, 0.0),\n\n ...
Rust
jormungandr/src/leadership/protocols/logs.rs
Diversified1/jormungandr
87df20878aff333c9b0f4c43d538ecee120e7f14
use jormungandr_lib::interfaces::{LeadershipLog, LeadershipLogId}; use std::time::Duration; use tokio::{ prelude::*, sync::lock::{Lock, LockGuard}, timer, }; #[derive(Clone)] pub struct Logs(Lock<internal::Logs>); pub struct LeadershipLogHandle { internal_id: LeadershipLogId, logs: Logs, } impl L...
use jormungandr_lib::interfaces::{LeadershipLog, LeadershipLogId}; use std::time::Duration; use tokio::{ prelude::*, sync::lock::{Lock, LockGuard}, timer, }; #[derive(Clone)] pub struct Logs(Lock<internal::Logs>); pub struct LeadershipLogHandle { internal_id: LeadershipLogId, logs: Logs, } impl L...
pub fn poll_purge(&mut self) -> impl Future<Item = (), Error = timer::Error> { self.inner() .and_then(move |mut guard| future::poll_fn(move || guard.poll_purge())) } pub fn logs(&self) -> impl Future<Item = Vec<LeadershipLog>, Error = ()> { self.inner() .and_then(|...
fn mark_finished( &self, leadership_log_id: LeadershipLogId, ) -> impl Future<Item = (), Error = ()> { self.inner().and_then(move |mut guard| { guard.mark_finished(&leadership_log_id.into()); future::ok(()) }) }
function_block-function_prefix_line
[ { "content": "pub fn get_settings(context: State<Context>) -> Result<impl Responder, Error> {\n\n let blockchain = context.blockchain.lock_read();\n\n let mut ledger = blockchain\n\n .tip\n\n .ledger()\n\n .map_err(|_| ErrorInternalServerError(\"Failed to get blockchain tip ledger\"))...
Rust
cranelift-codegen/meta/src/gen_settings.rs
lzutao/cranelift
c053a0bbe1fec8c23ad6f15148e0b26efe194f7c
use std::collections::HashMap; use cranelift_codegen_shared::constant_hash::{generate_table, simple_hash}; use crate::cdsl::camel_case; use crate::cdsl::settings::{ BoolSetting, Predicate, Preset, Setting, SettingGroup, SpecificSetting, }; use crate::error; use crate::srcgen::{Formatter, Match}; use crate::unique...
use std::collections::HashMap; use cranelift_codegen_shared::constant_hash::{generate_table, simple_hash}; use crate::cdsl::camel_case; use crate::cdsl::settings::{ BoolSetting, Predicate, Preset, Setting, SettingGroup, SpecificSetting, }; use crate::error; use crate::srcgen::{Formatter, Match}; use crate::unique...
ln!(fmt, "Builder::new(&TEMPLATE)"); }); fmtln!(fmt, "}"); } fn gen_display(group: &SettingGroup, fmt: &mut Formatter) { fmtln!(fmt, "impl fmt::Display for Flags {"); fmt.indent(|fmt| { fmtln!( fmt, "fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {" ); ...
; fmtln!(fmt, "defaults: &[{}],", default_bytes_str); fmtln!(fmt, "presets: &PRESETS,"); }); fmtln!(fmt, "};"); fmt.doc_comment(format!( "Create a `settings::Builder` for the {} settings group.", group.name )); fmtln!(fmt, "pub fn builder() -> Builder {"); fmt.in...
function_block-random_span
[ { "content": "#[allow(non_snake_case)]\n\npub fn FxHashSet<V: Hash + Eq>() -> FxHashSet<V> {\n\n HashSet::default()\n\n}\n\n\n\n/// A speedy hash algorithm for use within rustc. The hashmap in liballoc\n\n/// by default uses SipHash which isn't quite as speedy as we want. In the\n\n/// compiler we're not rea...
Rust
cli/src/main.rs
sgmenda/openmls
0d4de92d37f733470685556fcf16e9a3541eadab
use std::io::{stdin, stdout, StdoutLock, Write}; use termion::input::TermRead; mod backend; mod conversation; mod identity; mod networking; mod user; const HELP: &str = " >>> Available commands: >>> - update update the client state >>> - reset r...
use std::io::{stdin, stdout, StdoutLock, Write}; use termion::input::TermRead; mod backend; mod conversation; mod identity; mod networking; mod user; const HELP: &str = " >>> Available commands: >>> - update update the client state >>> - reset r...
#[test] fn basic_test() { backend::Backend::default().reset_server(); const MESSAGE_1: &str = "Thanks for adding me Client1."; const MESSAGE_2: &str = "Welcome Client3."; const MESSAGE_3: &str = "Thanks so much for the warm welcome! 😊"; let mut client_1 = user::User::new("Client1".to_...
p(); } continue; } if op2 == "update" { update(client, Some(group_name.to_string()), &mut stdout); continue; } ...
function_block-function_prefixed
[ { "content": "pub fn write(file_name: &str, payload: &[u8]) {\n\n let mut file = match File::create(file_name) {\n\n Ok(f) => f,\n\n Err(_) => panic!(\"Couldn't open file {}.\", file_name),\n\n };\n\n file.write_all(payload)\n\n .expect(\"Error writing test vector file\");\n\n}\n\n...
Rust
src/sender_queue/mod.rs
vyugov/hbbft
e2d0e5f47f0fda4ed861e08c370d27f744d6aa18
mod dynamic_honey_badger; mod error; mod honey_badger; mod message; mod queueing_honey_badger; use rand::Rng; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Debug; use log::debug; use crate::traits::EpochT; use crate::{ConsensusProtocol, CpStep, Epoched, NodeIdT, Target}; pub use self::error::Error; pu...
mod dynamic_honey_badger; mod error; mod honey_badger; mod message; mod queueing_honey_badger; use rand::Rng; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Debug; use log::debug; use crate::traits::EpochT; use crate::{ConsensusProtocol, CpStep, Epoched, NodeIdT, Target}; pub use self::error::Error; pu...
pub fn handle_message<R: Rng>( &mut self, sender_id: &D::NodeId, message: Message<D::Message>, rng: &mut R, ) -> Result<CpStep<Self>, Error<D::Error>> { if self.is_removed { return Ok(Step::<D>::default()); } match message { ...
rng: &mut R, ) -> Result<CpStep<Self>, Error<D::Error>> { if self.is_removed { return Ok(Step::<D>::default()); } self.apply(|algo| algo.handle_input(input, rng)) }
function_block-function_prefix_line
[ { "content": "/// Return true with a certain `probability` ([0 .. 1.0]).\n\npub fn randomly<R: Rng>(probability: f32, rng: &mut R) -> bool {\n\n assert!(probability <= 1.0);\n\n assert!(probability >= 0.0);\n\n rng.gen_range(0.0, 1.0) <= probability\n\n}\n", "file_path": "hbbft_testing/src/util.rs"...
Rust
src/emulator.rs
yuku-t/x86
f7d6be0ffcccd0cee65f70bfacf3d168a4f6ac72
use std::io::Read; use std::fs::File; use modrm; use instructions; const REGISTERS_COUNT: usize = 8; const REGISTER_NAMES: [&'static str; REGISTERS_COUNT] = [ "EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI" ]; pub const EAX: usize = 0; pub const ESP: usize = 4; pub const EBP: usize = 5; const CARRY_FLAG: u...
use std::io::Read; use std::fs::File; use modrm; use instructions; const REGISTERS_COUNT: usize = 8; const REGISTER_NAMES: [&'static str; REGISTERS_COUNT] = [ "EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI" ]; pub const EAX: usize = 0; pub const ESP: usize = 4; pub const EBP: usize = 5; const CARRY_FLAG: u...
}, _ => { panic!("not implemented"); }, } } pub fn dump_registers(&self) { println!("\ndump registers"); for i in 0..REGISTERS_COUNT { println!("{} = 0x{:08X}", REGISTER_NAMES[i], self.registers[i]); } prin...
match modrm.reg { 0 => instructions::inc_rm32(self, &modrm), _ => panic!(format!("not implemented: FF /{}", modrm.reg)), }
if_condition
[ { "content": "pub fn emulate(memory_size: usize, path: &str) {\n\n let mut emu = emulator::Emulator::new(memory_size, 0x7c00, 0x7c00);\n\n emu.load(path);\n\n emu.run();\n\n emu.dump_registers();\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 174880.9028850196 }, { "cont...
Rust
src/middleware/test.rs
aleksandrpak/iron
f9f174322133249120920149c1752341fd9dfe03
use std::old_io::net::ip::ToSocketAddr; use std::old_io::util::NullReader; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; use hyper::http::HttpReader; use self::Kind::{Fine, Prob}; use prelude::*; use request::Body; use {method, headers}; use {AfterMiddleware, Before...
use std::old_io::net::ip::ToSocketAddr; use std::old_io::util::NullReader; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; use hyper::http::HttpReader; use self::Kind::{Fine, Prob}; use prelude::*; use request::Body; use {method, headers}; use {AfterMiddleware, Before...
rmal: normal.clone(), error: error.clone(), mode: mode } } fn to_kind(val: bool) -> Kind { if val { Fine } else { Prob } } fn test_chain(chain: ChainLike<Kind>, expected: ChainLike<Kind>) { let actual = counters(&chain); let chain = to_chain(&actual, chain); let _ = chain.han...
dleware>) .collect::<Vec<_>>(); Chain { befores: befores, handler: Some(box handler as Box<Handler>), afters: afters } } fn into_middleware(input: (Kind, &Twice<Arc<AtomicBool>>)) -> Middleware { let mode = input.0; let (ref normal, ref error) = *input.1; Middlewar...
random
[ { "content": "fn write_with_body(mut res: HttpResponse<Fresh>, mut body: Box<Reader + Send>) -> IoResult<()> {\n\n let content_type = res.headers().get::<headers::ContentType>()\n\n .map(|cx| cx.clone())\n\n .unwrap_or_else(|| headers::ContentType(\"text/pl...
Rust
compiler/hir/import/parse.rs
mwatts/arret
3b3bae27ca7283376d420fa7d69fe5073ecf9ef0
use std::result; use arret_syntax::datum::{DataStr, Datum}; use arret_syntax::span::Span; use crate::hir::error::{Error, ErrorKind}; use crate::hir::loader::ModuleName; use crate::hir::util::{expect_ident, expect_spanned_ident}; type Result<T> = result::Result<T, Error>; pub enum ParsedImportSet { Module(Span, ...
use std::result; use arret_syntax::datum::{DataStr, Datum}; use arret_syntax::span::Span; use crate::hir::error::{Error, ErrorKind}; use crate::hir::loader::ModuleName; use crate::hir::util::{expect_ident, expect_spanned_ident}; type Result<T> = result::Result<T, Error>; pub enum ParsedImportSet { Module(Span, ...
} pub fn module_name(&self) -> &ModuleName { self.spanned_module_name().1 } } pub enum ParsedFilter { Only(Box<[(Span, DataStr)]>), Exclude(Box<[(Span, DataStr)]>), Rename(Box<[((Span, DataStr), DataStr)]>), Prefix(DataStr), } fn parse_module_name(span: Span, name: &[Datum]) -> R...
match self { ParsedImportSet::Module(span, module_name) => (*span, module_name), ParsedImportSet::Filter(_, inner_import) => inner_import.spanned_module_name(), }
if_condition
[ { "content": "/// Converts body data from a `#()` reader macro in to an anonymous function\n\npub fn convert_anon_fun(outer_span: Span, body_data: impl Iterator<Item = Datum>) -> Result<Datum> {\n\n use std::iter;\n\n\n\n let mut found_arity = FoundArity {\n\n fixed_args: 0,\n\n has_rest: fa...
Rust
src/helix/points/create_custom_rewards.rs
FoxLisk/twitch_api2
25f9d43fcf3ac0236fbc7835532d3b11f22cf9fe
use super::*; use helix::RequestPost; #[derive(PartialEq, typed_builder::TypedBuilder, Deserialize, Serialize, Clone, Debug, Default)] #[non_exhaustive] pub struct CreateCustomRewardRequest { #[builder(setter(into))] pub broadcaster_id: types::UserId, } #[derive(PartialEq, typed_builder::TypedBuilder, ...
use super::*; use helix::RequestPost; #[derive(PartialEq, typed_builder::TypedBuilder, Deserialize, Serialize, Clone, Debug, Default)] #[non_exhaustive] pub struct CreateCustomRewardRequest { #[builder(setter(into))] pub broadcaster_id: types::UserId, } #[derive(PartialEq, typed_builder::TypedBuilder, ...
ation.cursor, request, }) } } #[test] fn test_request() { use helix::*; let req = CreateCustomRewardRequest::builder() .broadcaster_id("274637212") .build(); let body = CreateCustomRewardBody::builder() .cost(50000) .title("game analysis 1v1") ...
to_string(), status, uri: uri.clone(), } })?; Ok(helix::Response { data, pagination: response.pagin
function_block-random_span
[]
Rust
crates/hir_def/src/expr.rs
iamseb/wgsl-analyzer
35a2a8f655f5904ae16ca947b37fa11ec91fd833
use la_arena::Idx; use syntax::ast::{self}; use crate::{ body::BindingId, db::Interned, module_data::Name, type_ref::{AccessMode, StorageClass, TypeRef}, }; pub use syntax::ast::operators::*; pub type ExprId = Idx<Expr>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Literal { Int(i64, Bu...
use la_arena::Idx; use syntax::ast::{self}; use crate::{ body::BindingId, db::Interned, module_data::Name, type_ref::{AccessMode, StorageClass, TypeRef}, }; pub use syntax::ast::operators::*; pub type ExprId = Idx<Expr>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Literal { Int(i64, Bu...
ext.strip_prefix("0x") { Some(hex) => i64::from_str_radix(hex, 16), None => text.parse(), } .expect("invalid literal"); if negative { value = -value; } Literal::Int(value, BuiltinInt::I32) } ast...
Idx<Statement>; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Statement { Missing, Compound { statements: Vec<StatementId>, }, LetStatement { binding_id: BindingId, type_ref: Option<Interned<TypeRef>>, initializer: Option<ExprId>, }, VariableStatement { ...
random
[ { "content": "#[derive(Debug)]\n\nenum Type {\n\n Vec(VecSize, Box<Type>),\n\n Matrix(VecSize, VecSize, Box<Type>),\n\n Texture(TextureType),\n\n Sampler { comparison: bool },\n\n Bool,\n\n F32,\n\n I32,\n\n U32,\n\n RuntimeArray(Box<Type>),\n\n Ptr(Box<Type>),\n\n Atomic(Box<Ty...
Rust
src/scene/exit_confirm_scene.rs
shaderboi/shooterboi
d483500cd717f665ea36723f42c9b3bf8b97ba1b
use conrod_core::widget::envelope_editor::EnvelopePoint; use conrod_core::{Labelable, Positionable, Sizeable, Widget}; use std::collections::HashMap; use winit::event_loop::ControlFlow; use crate::audio::AudioContext; use crate::gui::ConrodHandle; use crate::input_manager::InputManager; use crate::renderer::Renderer; ...
use conrod_core::widget::envelope_editor::EnvelopePoint; use conrod_core::{Labelable, Positionable, Sizeable, Widget}; use std::collections::HashMap; use winit::event_loop::ControlFlow; use crate::audio::AudioContext; use crate::gui::ConrodHandle; use crate::input_manager::InputManager; use crate::renderer::Renderer; ...
}
w: &mut Window, _renderer: &mut Renderer, _conrod_handle: &mut ConrodHandle, _audio_context: &mut AudioContext, _database: &mut Database, ) { }
function_block-function_prefixed
[ { "content": "pub fn setup_player_collider(physics: &mut GamePhysics, position: Vector3<f32>) -> RigidBodyHandle {\n\n let player_rigid_body_handle = physics.rigid_body_set.insert(\n\n RigidBodyBuilder::new(RigidBodyType::Dynamic)\n\n .translation(position)\n\n .user_data(u128::M...
Rust
src/components/help.rs
andyslucky/gobang
c373a80efa122280315ab838669d9d4526e59bcc
use std::convert::From; use anyhow::Result; use async_trait::async_trait; use itertools::Itertools; use tui::{ backend::Backend, layout::{Alignment, Constraint, Direction, Layout, Rect}, style::{Color, Modifier, Style}, text::{Span, Spans}, widgets::{Block, BorderType, Borders, Clear, Paragraph}, ...
use std::convert::From; use anyhow::Result; use async_trait::async_trait; use itertools::Itertools; use tui::{ backend::Backend, layout::{Alignment, Constraint, Direction, Layout, Rect}, style::{Color, Modifier, Style}, text::{Span, Spans}, widgets::{Block, BorderType, Borders, Clear, Paragraph}, ...
:Key, _message_queue: &mut crate::app::GlobalMessageQueue, ) -> Result<EventState> { if self.visible { if key == self.key_config.exit_popup { self.hide(); return Ok(EventState::Consumed); } else if key == self.key_config.scroll_down { ...
ible: bool, selection: u16, key_config: KeyConfig, } impl DrawableComponent for HelpComponent { fn draw<B: Backend>(&self, f: &mut Frame<B>, _area: Rect, _focused: bool) -> Result<()> { if self.visible { const SIZE: (u16, u16) = (65, 24); let scroll_threshold = SIZE.1 / 3; ...
random
[ { "content": "fn syntact_style_to_tui(style: &Style) -> tui::style::Style {\n\n let mut res = tui::style::Style::default().fg(tui::style::Color::Rgb(\n\n style.foreground.r,\n\n style.foreground.g,\n\n style.foreground.b,\n\n ));\n\n\n\n if style.font_style.contains(FontStyle::BOLD...
Rust
tests/all.rs
clearloop/cfger
c61cee4a0bbc36b9536d17777bbe95d74437a7a6
use etc::{Etc, FileSystem, Read, Tree, Write}; use std::{env, iter::FromIterator, path::PathBuf}; #[test] fn test_init() { let mut dir = env::temp_dir(); dir.push(".etc.init"); let etc = Etc::new(&dir).unwrap(); assert!(dir.exists()); assert!(etc.drain().is_ok()); assert!...
use etc::{Etc, FileSystem, Read, Tree, Write}; use std::{env, iter::FromIterator, path::PathBuf}; #[test]
#[test] fn test_io() { let mut dir = env::temp_dir(); dir.push(".etc.io"); let etc = Etc::new(&dir).unwrap(); let hello = etc.open("hello.md").unwrap(); assert!(hello.write(b"hello, world!\n").is_ok()); assert_eq!(hello.read().unwrap(), b"hello, world!\n"); assert!(e...
fn test_init() { let mut dir = env::temp_dir(); dir.push(".etc.init"); let etc = Etc::new(&dir).unwrap(); assert!(dir.exists()); assert!(etc.drain().is_ok()); assert!(!dir.exists()); }
function_block-full_function
[ { "content": "/// io read\n\npub trait Read: Meta {\n\n /// read stream from file\n\n fn read(&self) -> Result<Vec<u8>, Error> {\n\n let mut f = File::open(self.real_path()?)?;\n\n let mut buffer = Vec::new();\n\n\n\n // read the whole file\n\n f.read_to_end(&mut buffer)?;\n\n ...
Rust
tracing-subscriber/src/registry/sharded.rs
cjlucas/tracing
754e68d79aee46f03b4d630817ad7a9207294178
use sharded_slab::{Guard, Slab}; use super::stack::SpanStack; use crate::{ registry::{ extensions::{Extensions, ExtensionsInner, ExtensionsMut}, LookupSpan, SpanData, }, sync::RwLock, }; use std::{ cell::{Cell, RefCell}, sync::atomic::{fence, AtomicUsize, Ordering}, }; use tracing_c...
use sharded_slab::{Guard, Slab}; use super::stack::SpanStack; use crate::{ registry::{ extensions::{Extensions, ExtensionsInner, ExtensionsMut}, LookupSpan, SpanData, }, sync::RwLock, }; use std::{ cell::{Cell, RefCell}, sync::atomic::{fence, AtomicUsize, Ordering}, }; use tracing_c...
} struct ClosingSpan { is_removed: Arc<AtomicBool>, } impl Drop for ClosingSpan { fn drop(&mut self) { self.is_removed.store(true, Ordering::Release) } } #[test] fn spans_are_removed_from_registry() { let span1_removed = Arc::new(AtomicBool::ne...
fn on_close(&self, id: Id, ctx: Context<'_, S>) { dbg!(&id); assert!(&ctx.span(&id).is_some()); let span = &ctx.span(&id).unwrap(); match dbg!(span.name()) { "span1" | "span2" => {} _ => return, }; let extensions = s...
function_block-full_function
[ { "content": "pub fn mock() -> MockSubscriber<fn(&Metadata<'_>) -> bool> {\n\n MockSubscriber {\n\n expected: VecDeque::new(),\n\n filter: (|_: &Metadata<'_>| true) as for<'r, 's> fn(&'r Metadata<'s>) -> _,\n\n }\n\n}\n\n\n\nimpl<F> MockSubscriber<F>\n\nwhere\n\n F: Fn(&Metadata<'_>) -> b...
Rust
rlink-connectors/connector-clickhouse/src/clickhouse_sink.rs
biuboombiuboom/rlink-rs
877e20b5404d866d63724b842edd86c8000dd4e6
use std::borrow::BorrowMut; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use clickhouse_rs::{ClientHandle, Options, Pool}; use rlink::channel::utils::handover::Handover; use rlink::core::checkpoint::CheckpointFunction; use rlink::core::element::Record; use rlink::core::function::{Context, NamedF...
use std::borrow::BorrowMut; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use clickhouse_rs::{ClientHandle, Options, Pool}; use rlink::channel::utils::handover::Handover; use rlink::core::checkpoint::CheckpointFunction; use rlink::core::element::Record; use rlink::core::function::{Context, NamedF...
{ error!("write clickhouse error. {}", e); self.reconnection(client.borrow_mut()).await?; } } } } async fn reconnection(&mut self, client: &mut ClientHandle) -> anyhow::Result<()> { let mut err = None; ...
mpl ClickhouseSink { pub fn new( url: &str, table: &str, batch_size: usize, batch_timeout: Duration, tasks: usize, builder: Box<dyn ClickhouseConverter>, ) -> Self { ClickhouseSink { url: url.to_string(), table: table.to_string(), ...
random
[ { "content": "pub trait KafkaRecordDeserializer: Sync + Send {\n\n fn deserialize(\n\n &mut self,\n\n timestamp: i64,\n\n key: &[u8],\n\n payload: &[u8],\n\n topic: &str,\n\n partition: i32,\n\n offset: i64,\n\n ) -> Vec<Record>;\n\n}\n\n\n", "file_path...
Rust
cranelift/src/clif-util.rs
PLSysSec/wasmtime
8082aeaa5f593d8f343c9e6f1cca111802732724
#![deny(trivial_numeric_casts)] #![warn(unused_import_braces, unstable_features, unused_extern_crates)] #![cfg_attr( feature = "cargo-clippy", warn( clippy::float_arithmetic, clippy::mut_mut, clippy::nonminimal_bool, clippy::option_map_unwrap_or, clippy::option_map_unwrap...
#![deny(trivial_numeric_casts)] #![warn(unused_import_braces, unstable_features, unused_extern_crates)] #![cfg_attr( feature = "cargo-clippy", warn( clippy::float_arithmetic, clippy::mut_mut, clippy::nonminimal_bool, clippy::option_map_unwrap_or, clippy::option_map_unwrap...
ings") } fn add_target_flag<'a>() -> clap::Arg<'a, 'a> { Arg::with_name("target") .takes_value(true) .long("target") .help("Specify the Cranelift target") } fn add_print_flag<'a>() -> clap::Arg<'a, 'a> { Arg::with_name("print") .short("p") .help("Print the resulting Cra...
g<'a>() -> clap::Arg<'a, 'a> { Arg::with_name("set") .long("set") .takes_value(true) .multiple(true) .help("Configure Cranelift sett
function_block-random_span
[ { "content": "pub fn run(files: &[String]) -> CommandResult {\n\n for (i, f) in files.iter().enumerate() {\n\n if i != 0 {\n\n println!();\n\n }\n\n cat_one(f)?\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "cranelift/src/cat.rs", "rank": 0, "score": 551457.4163...
Rust
src/app_state.rs
h3r2tic/notorious6
b128f223934f1c6c52927ad099cbf9ecb7c80572
use crate::{ fbo::Fbo, image_pool::*, lut_lib::{AnyLutsChanged, LutDesc, LutLib}, shader::ShaderKey, shader_lib::{AnyShadersChanged, ShaderLib}, texture::Texture, }; use anyhow::Context; use glutin::event::{ElementState, KeyboardInput, MouseButton, VirtualKeyCode, WindowEvent}; use jpeg_encoder:...
use crate::{ fbo::Fbo, image_pool::*, lut_lib::{AnyLutsChanged, LutDesc, LutLib}, shader::ShaderKey, shader_lib::{AnyShadersChanged, ShaderLib}, texture::Texture, }; use anyhow::Context; use glutin::event::{ElementState, KeyboardInput, MouseButton, VirtualKeyCode, WindowEvent}; use jpeg_encoder:...
} pub fn update(&mut self, gl: &gl::Gl) -> NeedsRedraw { let luts_changed = self.lut_lib.compile_all(gl); let shaders_changed = self.shader_lib.compile_all(gl); if matches!(luts_changed, AnyLutsChanged::Yes) || matches!(shaders_changed, AnyShadersChanged::Yes) { ...
Ok(Self { image_pool, current_image: 0, shader_lib, lut_lib, current_shader: 0, _lazy_cache: lazy_cache, shaders, interaction: Default::default(), pending_image_capture: Default::default(), ev: 0.0, ...
call_expression
[ { "content": "pub fn setup_basic_gl_state(gl: &gl::Gl) {\n\n use std::ffi::CStr;\n\n\n\n unsafe {\n\n let mut vao: u32 = 0;\n\n gl.GenVertexArrays(1, &mut vao);\n\n gl.BindVertexArray(vao);\n\n\n\n log::info!(\n\n \"GL_VENDOR: {:?}\",\n\n CStr::from_ptr(gl...
Rust
src/class/macros.rs
c410-f3r/pyo3
5a927088355a275cad054c0505b8407d75fad2cc
macro_rules! py_unary_func { ($trait: ident, $class:ident :: $f:ident, $call:ident, $ret_type: ty) => {{ unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject) -> $ret_type where T: for<'p> $trait<'p>, { $crate::callback_body!(py, { let slf = ...
macro_rules! py_unary_func { ($trait: ident, $class:ident :: $f:ident, $call:ident, $ret_type: ty) => {{ unsafe extern "C" fn wrap<T>(slf: *mut $crate::ffi::PyObject) -> $ret_type where T: for<'p> $trait<'p>, { $crate::callback_body!(py, { let slf = ...
}; } macro_rules! py_func_set { ($trait_name:ident, $generic:ident, $fn_set:ident) => {{ unsafe extern "C" fn wrap<$generic>( slf: *mut $crate::ffi::PyObject, name: *mut $crate::ffi::PyObject, value: *mut $crate::ffi::PyObject, ) -> libc::c_int where ...
let rhs = extract_or_return_not_implemented!(py, rhs); $class::$f(lhs.extract()?, rhs).convert(py) }) } Some(wrap::<$class>) }}; } macro_rules! py_binary_reversed_num_func { ($trait:ident, $class:ident :: $f:ident) => {{ unsafe extern "C" fn wr...
random
[ { "content": "type PyOS_sighandler_t = unsafe extern \"C\" fn(arg1: c_int);\n\n\n\nextern \"C\" {\n\n pub fn PyOS_getsig(arg1: c_int) -> PyOS_sighandler_t;\n\n pub fn PyOS_setsig(arg1: c_int, arg2: PyOS_sighandler_t) -> PyOS_sighandler_t;\n\n}\n", "file_path": "src/ffi/pylifecycle.rs", "rank": 0, ...
Rust
gtk/src/app/views/images.rs
whereswaldon/popsicle
aad5765e7ef1749de0edc77b40d005dff722afee
use super::View; use gtk::*; use pango::{AttrList, Attribute, EllipsizeMode}; use std::path::Path; pub struct ImageView { pub view: View, pub check: Button, pub chooser_container: Stack, pub chooser: Button, pub image_path: Label, pub hash: ComboBoxText, pub hash_label: Entry, } impl Image...
use super::View; use gtk::*; use pango::{AttrList, Attribute, EllipsizeMode}; use std::path::Path; pub struct ImageView { pub view: View, pub check: Button, pub chooser_container: Stack, pub chooser: Button, pub image_path: Label, pub hash: ComboBoxText, pub hash_label: Entry, } impl Image...
cascade! { Stack::new(); ..add_named(&button_box, "chooser"); ..add_named(&spinner_box, "checksum"); ..set_visible_child_name("chooser"); ..set_margin_top(12); ..set_margin_bottom(24); }; let view = View::new( "applica...
bel, false, false, 0); ..pack_start(&combo_container, true, true, 0); ..pack_start(&check, false, false, 0); ..set_border_width(6); }; let chooser_container =
function_block-random_span
[ { "content": "fn set_hash_widget(state: &State, ui: &GtkUi) {\n\n let hash = &ui.content.image_view.hash;\n\n\n\n let path = state.image_path.borrow();\n\n let kind = match hash.get_active() {\n\n Some(1) => \"SHA256\",\n\n Some(2) => \"MD5\",\n\n _ => return,\n\n };\n\n\n\n ...
Rust
packages/sycamore-router/src/lib.rs
Submersible/sycamore
99a3ff0fc4d6499276748277f87e1ddadd5b067f
extern crate self as sycamore_router; mod router; pub use sycamore_router_macro::Route; use std::str::FromStr; pub use router::*; pub trait Route: Sized { fn match_route(segments: &[&str]) -> Self; fn match_path(path: &str) -> Self { let segments = path .spli...
extern crate self as sycamore_router; mod router; pub use sycamore_router_macro::Route; use std::str::FromStr; pub use router::*; pub trait Route: Sized { fn match_route(segments: &[&str]) -> Self; fn match_path(path: &str) -> Self { let segments = path .spli...
} #[derive(Clone)] pub struct RoutePath { segments: Vec<Segment>, } impl RoutePath { pub fn new(segments: Vec<Segment>) -> Self { Self { segments } } pub fn match_path<'a>(&self, path: &[&'a str]) -> Option<Vec<Capture<'a>>> { let mut paths = path.iter(); let mut segments = s...
pub fn as_dyn_segments(&self) -> Option<&Vec<&'a str>> { if let Self::DynSegments(v) = self { Some(v) } else { None } }
function_block-full_function
[ { "content": "pub fn route(i: &str) -> IResult<&str, RoutePathAst> {\n\n map(separated_list0(tag(\"/\"), segment), |segments| {\n\n let segments = segments\n\n .into_iter()\n\n .filter(|x| !matches!(x, SegmentAst::Param(param) if param.is_empty()))\n\n .collect();\n\n ...
Rust
2017/day16/src/main.rs
mour/advent-of-code
664c7838bf3ea269dfcf67fea1db70d0e5c3f1b9
extern crate regex; #[macro_use] extern crate lazy_static; use regex::Regex; use std::str::FromStr; use std::string::ToString; use std::io; use std::io::prelude::*; use std::collections::BTreeMap; lazy_static! { static ref SPIN_RE: Regex = Regex::new(r"^s(?P<spin_by>[0-9]+)$").unwrap(); static ref EXCHAN...
extern crate regex; #[macro_use] extern crate lazy_static; use regex::Regex; use std::str::FromStr; use std::string::ToString; use std::io; use std::io::prelude::*; use std::collections::BTreeMap; lazy_static! { static ref SPIN_RE: Regex = Regex::new(r"^s(?P<spin_by>[0-9]+)$").unwrap(); static ref EXCHAN...
} else { let last_seen_at_idx = states_seen[&self.programs]; let skip_size = i - last_seen_at_idx; i += ((num_dances - i) / skip_size) * skip_size; } i += 1; } Ok(()) } } impl ToString for Programs { fn to_str...
|_| (), )?; Ok(DanceMove::Spin(spin_by)) } else if let Some(caps) = EXCHANGE_RE.captures(s) { let a = caps.name("exchange_a") .ok_or(())? .as_str() .parse() .map_err(|_| ())?; let b = caps.name("ex...
random
[ { "content": "fn get_histograms(input: &str) -> Vec<HashMap<char, usize>> {\n\n input\n\n .lines()\n\n .map(|line| {\n\n let mut histo = HashMap::new();\n\n\n\n line.chars().for_each(|ch| {\n\n *histo.entry(ch).or_insert(0) += 1;\n\n });\n\n\n\n ...
Rust
fluent-bundle/examples/simple-app.rs
kgv/fluent-rs
626bc832519355ee0c8ed68da4d47def8ff6836d
use fluent_bundle::{FluentArgs, FluentBundle, FluentResource, FluentValue}; use fluent_locale::{negotiate_languages, NegotiationStrategy}; use std::env; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::str::FromStr; use unic_langid::{langid, LanguageIdentifier}; fn ...
use fluent_bundle::{FluentArgs, FluentBundle, FluentResource, FluentValue}; use fluent_locale::{negotiate_languages, NegotiationStrategy}; use std::env; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::str::FromStr; use unic_langid::{langid, LanguageIdentifier}; fn ...
ng, ); let current_locale = resolved_locales .get(0) .expect("At least one locale should match."); let mut bundle = FluentBundle::new(resolved_locales.clone()); for path in L10N_RESOURCES { let mut full_path = env::current_dir().expect("Failed to retireve current...
= name.parse().expect("Parsing failed."); locales.push(langid); } } } } } return Ok(locales); } static L10N_RESOURCES: &[&str] = &["simple.ftl"]; fn main() { let args: Vec<String> = env::args().collect(); ...
random
[ { "content": "fn get_attributes<'p>(ps: &mut ParserStream<'p>) -> Vec<ast::Attribute<'p>> {\n\n let mut attributes = vec![];\n\n\n\n loop {\n\n let line_start = ps.ptr;\n\n ps.skip_blank_inline();\n\n if !ps.is_current_byte(b'.') {\n\n ps.ptr = line_start;\n\n br...
Rust
src/parser.rs
snylonue/Hana
e4f759e5a7dc7bcc42f2d9bce384519faf35e7a7
use crate::error::Error; use crate::error::InvalidArgument; use crate::error::ParseError; use crate::time::TimeStamp; use crate::track::Index; use crate::track::Track; use crate::track::TrackInfo; use crate::utils; use crate::Cuna; use std::fmt; use std::iter::Enumerate; use std::str::Lines; pub type Parser<'a> = Parn...
use crate::error::Error; use crate::error::InvalidArgument; use crate::error::ParseError; use crate::time::TimeStamp; use crate::track::Index; use crate::track::Track; use crate::track::TrackInfo; use crate::utils; use crate::Cuna; use std::fmt; use std::iter::Enumerate; use std::str::Lines; pub type Parser<'a> = Parn...
match command.to_ascii_lowercase().as_ref() { "rem" => Ok(Self::Rem(content)), "title" => Ok(Self::Title(trimq(content))), "performer" => Ok(Self::Performer(trimq(content))), "songwriter" => Ok(Self::Songwriter(trimq(content))), "catalog" => match uti...
let (content, command) = match utils::token(s) { Ok(ok) => ok, Err(_) => fail!(syntax s, "missing arguments"), };
assignment_statement
[ { "content": "pub fn token(content: &str) -> IResult<&str, &str> {\n\n terminated(take_until(\" \"), tag(\" \"))(content)\n\n}\n", "file_path": "src/utils.rs", "rank": 0, "score": 118840.83060878093 }, { "content": "pub fn keyword<'a>(kd: &'a str) -> impl Fn(&'a str) -> IResult<&'a str, &...
Rust
src/pipe.rs
Byron/piper
e0b36b8a83769492f942f1d1c93a73b09018852b
use std::cell::Cell; use std::io::{self, IoSlice, IoSliceMut}; use std::mem; use std::pin::Pin; use std::slice; use std::sync::atomic::{self, AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::task::{Context, Poll}; use futures::io::{AsyncRead, AsyncWrite}; use futures::task::AtomicWaker; pub fn pipe(ca...
use std::cell::Cell; use std::io::{self, IoSlice, IoSliceMut}; use std::mem; use std::pin::Pin; use std::slice; use std::sync::atomic::{self, AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::task::{Context, Poll}; use futures::io::{AsyncRead, AsyncWrite}; use futures::task::AtomicWaker; pub fn pipe(ca...
ence(Ordering::SeqCst); head = self.inner.head.load(Ordering::Acquire); self.head.set(head); if distance(head, tail) == cap { if self.inner.closed.load(Ordering::Relaxed) { ...
{ return Poll::Ready(Ok(0)); } else { return Poll::Pending; } } } } self.inner.reader.take(); let real_index = |i: usize| { if i < cap { ...
random
[ { "content": "/// Creates a bounded multi-producer multi-consumer channel.\n\n///\n\n/// This channel has a buffer that can hold at most `cap` messages at a time.\n\n///\n\n/// Senders and receivers can be cloned. When all senders associated with a channel get dropped, it\n\n/// becomes closed. Receive operatio...
Rust
loopers-engine/src/metronome.rs
Be-ing/loopers
a1dc180453e6493f51d004aa6d42db1f25bc0683
use crate::sample::PlayOutput::Done; use crate::sample::{Sample, SamplePlayer}; use crate::MetricStructure; use loopers_common::api::FrameTime; use std::sync::Arc; #[cfg(test)] mod tests { use super::*; fn sample(v: f32, n: usize) -> Sample { Sample { buffer: [vec![v; n], vec![-v; n]], ...
use crate::sample::PlayOutput::Done; use crate::sample::{Sample, SamplePlayer}; use crate::MetricStructure; use loopers_common::api::FrameTime; use std::sync::Arc; #[cfg(test)] mod tests { use super::*; fn sample(v: f32, n: usize) -> Sample { Sample { buffer: [vec![v; n], vec![-v; n]], ...
} pub struct Metronome { metric_structure: MetricStructure, beat_normal: Arc<Sample>, beat_emphasis: Arc<Sample>, time: FrameTime, player: Option<SamplePlayer>, volume: f32, } impl Metronome { pub fn new( metric_structure: MetricStructure, beat_normal: Sample, beat...
met.advance(&mut [&mut l, &mut r]); assert_eq!(vec![6f32, 6.0], l); assert_eq!(vec![-6f32, -6.0], r); assert_eq!(10, met.time.0); met.advance(&mut [&mut l, &mut r]); assert_eq!(vec![7f32, 7.0], l); assert_eq!(vec![-7f32, -7.0], r); assert_eq!(12, met.tim...
function_block-function_prefix_line
[ { "content": "pub fn norm(x: f32) -> f32 {\n\n x / (x * x + (1.0 - x) * (1.0 - x)).sqrt()\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct Sample {\n\n pub buffer: [Vec<f32>; 2],\n\n}\n\n\n\npub enum XfadeDirection {\n\n IN,\n\n OUT,\n\n}\n\n\n\nimpl Sample {\n\n pub fn new() -> Sample {\n\n Sam...
Rust
web/server/src/main.rs
redbadger/dapr-todomvc
1b08ecaebda66e5241ccee37791bb41cf5bfdb1f
use anyhow::{anyhow, Result}; use failure::Fail; use openidconnect::{ core::{CoreClient, CoreProviderMetadata, CoreResponseType}, AccessTokenHash, AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl...
use anyhow::{anyhow, Result}; use failure::Fail; use openidconnect::{ core::{CoreClient, CoreProviderMetadata, CoreResponseType}, AccessTokenHash, AuthenticationFlow, AuthorizationCode, ClientId, ClientSecret, CsrfToken, IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl...
let config = Config::from_args(); let issuer_url = IssuerUrl::new("https://accounts.google.com".to_string()).expect("Invalid issuer URL"); let provider_metadata = CoreProviderMetadata::discover_async(issuer_url, async_client::async_http_client) .await .map_err(|e| anyhow...
function_block-function_prefix_line
[ { "content": "pub fn get_cookie_or_default(name: &str, default: &str) -> String {\n\n get_cookie(name).unwrap_or_else(|| default.to_owned())\n\n}\n", "file_path": "web/client/src/cookies.rs", "rank": 0, "score": 154016.341187671 }, { "content": "pub fn decode_jwt(token: &str) -> Result<Cl...
Rust
keys/src/signature.rs
monacohq/rust-eos
a54e873baaf21db9268e9537856b04357583d8bf
use crate::{base58, error, hash}; use byteorder::{ByteOrder, LittleEndian}; use core::fmt; use core::str::FromStr; #[derive(Clone, PartialEq, Eq, Debug)] pub struct Signature { pub recv_id: libsecp256k1::RecoveryId, pub sig: libsecp256k1::Signature, } impl Signature { pub fn is_canonical(&self) -> bool { ...
use crate::{base58, error, hash}; use byteorder::{ByteOrder, LittleEndian}; use core::fmt; use core::str::FromStr; #[derive(Clone, PartialEq, Eq, Debug)] pub struct Signature { pub recv_id: libsecp256k1::RecoveryId, pub sig: libsecp256k1::Signature, } impl Signature { pub fn is_canonical(&self) -> bool { ...
} impl FromStr for Signature { type Err = error::Error; fn from_str(s: &str) -> crate::Result<Signature> { if !s.starts_with("SIG_K1_") { return Err(libsecp256k1::Error::InvalidSignature.into()); } let s_hex = base58::from(&s[7..])?; if ...
mpact(data: &[u8; 65]) -> crate::Result<Self> { let recv_id = if data[0] >= 31 { data[0] - 4 } else { data[0] }; let recv_id = libsecp256k1::RecoveryId::parse_rpc(recv_id)?; let sig = libsecp256k1::Signature::parse_standard_slice(&data[1..])?; Ok(Self { recv_id, sig }) }
function_block-function_prefixed
[ { "content": "/// Decode base58-encoded string into a byte vector\n\npub fn from(data: &str) -> Result<Vec<u8>, Error> {\n\n // 11/15 is just over log_256(58)\n\n let mut scratch = vec![0u8; 1 + data.len() * 11 / 15];\n\n // Build in base 256\n\n for d58 in data.bytes() {\n\n // Compute \"X =...
Rust
hexadventure/src/level/basic.rs
as-f/roguelike-things
51965689815058ec440c55a0f61b670634861011
use rand::Rng; use floodfill::flood; use grid::{self, Grid, Pos}; use std::collections::HashSet; use util; const MIN_CAVE_SIZE: usize = 4; const MIN_WALL_SIZE: usize = 6; #[derive(PartialEq, Eq, Copy, Clone)] pub enum Terrain { Floor, Wall, } pub(super) fn generate<R: Rng>(rng: &mut R) -> Grid<Terrain> {...
use rand::Rng; use floodfill::flood; use grid::{self, Grid, Pos}; use std::collections::HashSet; use util; const MIN_CAVE_SIZE: usize = 4; const MIN_WALL_SIZE: usize = 6; #[derive(PartialEq, Eq, Copy, Clone)] pub enum Terrain { Floor, Wall, } pub(super) fn generate<R: Rng>(rng: &mut R) -> Grid<Terrain> {...
contains(&pos))); } }
rgest_floor_set = HashSet::new(); for pos in grid::inner_positions() { if grid[pos] == Terrain::Floor { let floor_set = flood(pos, |pos| grid[pos] == Terrain::Floor); for &pos in &floor_set { grid[pos] = Terrain::Wall; } if floor_set.len() > la...
random
[ { "content": "fn remove_isolated_walls(grid: &mut Grid<Terrain>) {\n\n let outer_wall = flood(grid::corner(), |pos| {\n\n grid::contains(pos) && grid[pos] == Terrain::Wall\n\n });\n\n let mut visited = Grid::new(|pos| outer_wall.contains(&pos));\n\n for pos in grid::positions() {\n\n i...
Rust
postgres-rest/src/lib.rs
kaibyao/experiment00
6bb97b56bfa459b7e1b26133df76420d72ca67fd
#![deny(clippy::complexity, clippy::correctness, clippy::perf, clippy::style)] #![recursion_limit = "128"] mod error; pub mod queries; mod stats_cache; use stats_cache::{get_stats_cache_addr, StatsCacheMessage}; pub use error::Error; use actix::{spawn as actix_spawn, System}; use futures::future::{err, ok, Eithe...
#![deny(clippy::complexity, clippy::correctness, clippy::perf, clippy::style)] #![recursion_limit = "128"] mod error; pub mod queries; mod stats_cache; use stats_cache::{get_stats_cache_addr, StatsCacheMessage}; pub use error::Error; use actix::{spawn as actix_spawn, System}; use futures::future::{err, ok, Eithe...
pub fn reset_cache(&self) -> impl Future<Item = (), Error = Error> { if !self.is_cache_table_stats { return Either::A(err(Error::generate_error( "TABLE_STATS_CACHE_NOT_ENABLED", "".to_string(), ))); } match get_stats_cache_addr(...
pub fn connect(&self) -> impl Future<Item = Client, Error = Error> { pg_connect(self.db_url, self.tls.clone()) .map_err(Error::from) .and_then(|(client, connection)| { let is_actix_result = std::panic::catch_unwind(|| { System::current(); ...
function_block-full_function
[ { "content": "/// Returns a Future resolving to a QueryResult.\n\npub fn generate_query_result_from_db<T: MakeTlsConnect<Socket> + Clone + Send + Sync + 'static>(\n\n config: Config<T>,\n\n statement_str: String,\n\n prepared_values: Vec<TypedColumnValue>,\n\n is_return_rows: bool,\n\n) -> impl Futu...
Rust
backend/src/torrents.rs
kilork/rustorrent
dcdfd44ede8b069463d55e4c685c82883d2e9a56
use crate::{login::User, BroadcasterMessage, Failure}; use actix::prelude::*; use actix_web::{dev::Payload, web, Error, FromRequest, HttpRequest, HttpResponse, Responder}; use log::{error, info}; use rsbt_service::{ RsbtCommand, RsbtCommandDeleteTorrent, RsbtCommandTorrentAction, RsbtCommandTorrentAnnounce, Rsb...
use crate::{login::User, BroadcasterMessage, Failure}; use actix::prelude::*; use actix_web::{dev::Payload, web, Error, FromRequest, HttpRequest, HttpResponse, Responder}; use log::{error, info}; use rsbt_service::{ RsbtCommand, RsbtCommandDeleteTorrent, RsbtCommandTorrentAction, RsbtCommandTorrentAnnounce, Rsb...
#[derive(Serialize, Deserialize)] struct Action { pub action: RsbtTorrentAction, } #[post("/torrent/{id}/action")] async fn torrent_create_action( event_sender: web::Data<Sender<RsbtCommand>>, id: web::Path<usize>, body: web::Json<Action>, _user: User, ) -> impl Responder { let (request_respo...
t() { info!("order by field {} {:?}", field, order); let mut field_order: Box<dyn Fn(TD, TD) -> Ordering> = match field { "id" => Box::new(id_comparator), "name" => Box::new(name_comparator), _ => panic!(), ...
function_block-function_prefixed
[ { "content": "pub fn parse_torrent(buf: &[u8]) -> Result<Torrent, RsbtError> {\n\n let torrent = buf.try_into()?;\n\n\n\n Ok(torrent)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::Torrent;\n\n use std::convert::TryInto;\n\n\n\n #[test]\n\n fn parse_torrent() {\n\n let torrent_b...
Rust
pest/src/prec_climber.rs
lwandrebeck/pest
548919caa008ce2b281e77f77e5638e0128be798
use alloc::borrow::Cow; use alloc::boxed::Box; use alloc::vec::Vec; use core::iter::Peekable; use core::ops::BitOr; use crate::iterators::Pair; use crate::RuleType; #[cfg(feature = "const_prec_climber")] #[macro_export] macro_rules! prec_climber { ( $( $assoc:ident $rule:ident $( | $rules:ident )* ),+ $...
use alloc::borrow::Cow; use alloc::boxed::Box; use alloc::vec::Vec; use core::iter::Peekable; use core::ops::BitOr; use crate::iterators::Pair; use crate::RuleType; #[cfg(feature = "const_prec_climber")] #[macro_export] macro_rules! prec_climber { ( $( $assoc:ident $rule:ident $( | $rules:ident )* ),+ $...
next = op_next.map(|op| *op); } vec }); PrecClimber { ops: Cow::Owned(ops), } } pub fn climb<'...
c, [(R, u32, Assoc)]>, } #[cfg(feature = "const_prec_climber")] impl<R: Clone + 'static> PrecClimber<R> { pub const fn new_const(ops: &'static [(R, u32, Assoc)]) -> PrecClimber<R> { ...
random
[]
Rust
src/handler.rs
mkazutaka/ramup
c5d4cf164990379c13cdc1f69d7af92ed714c475
use crate::appenv; use crate::apperror; use crate::apppath::AbsPath; use crate::maccmd::{DiskUtil, HdiUtil}; use crate::ram::RAM; use crate::state::State; use crate::subcmd::{Backup, Restore}; use anyhow::{Context, Result}; use std::convert::TryFrom; use std::path::Path; pub struct Handler { ram: RAM, state: S...
use crate::appenv; use crate::apperror; use crate::apppath::AbsPath; use crate::maccmd::{DiskUtil, HdiUtil}; use crate::ram::RAM; use crate::state::State; use crate::subcmd::{Backup, Restore}; use anyhow::{Context, Result}; use std::convert::TryFrom; use std::path::Path; pub struct Handler { ram: RAM, state: S...
pub fn clean(&self) -> Result<()> { let sp = appenv::state(); if Path::new(&sp).exists() { std::fs::remove_file(&sp).with_context(|| "Failed to delete state file")?; } Handler::unmount(&self.ram) } fn mount(ram: &RAM) -> Result<()> { if HdiUtil::exist_v...
pub fn restore(&mut self, targets: Vec<String>) -> Result<()> { let source_base_path = AbsPath::try_from(&self.ram.mount_path)?.join(&self.ram.name)?; for target in &targets { let source = source_base_path.join(&target)?; let target = AbsPath::new(&target)?; match R...
function_block-full_function
[ { "content": "pub fn state() -> String {\n\n let default = shellexpand::tilde(\"~/.config/ramup/state.toml\");\n\n env::var(KEY_STATE_PATH).unwrap_or_else(|_| String::from(default))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use serial_test::serial;\n\n\n\n #[test]\n\n #[ser...
Rust
src/gpio.rs
thejpster/ke06z
709a3fa57c72e7da31aa72eafc3f6bf004145c6f
use super::registers as reg; use super::uart::UartId; #[derive(PartialEq, Clone, Copy)] #[allow(missing_docs)] pub enum Pin { Pin0, Pin1, Pin2, Pin3, Pin4, Pin5, Pin6, Pin7, } #[derive(PartialEq, Clone, Copy)] #[allow(missing_docs)] pub enum PinPort { PortA(Pin), PortB(Pin), ...
use super::registers as reg; use super::uart::UartId; #[derive(PartialEq, Clone, Copy)] #[allow(missing_docs)] pub enum Pin { Pin0, Pin1, Pin2, Pin3, Pin4, Pin5, Pin6,
PortD(Pin), PortE(Pin), PortF(Pin), PortG(Pin), PortH(Pin), PortI(Pin), } #[derive(PartialEq, Clone, Copy)] pub enum PinMode { InputPull(Level), Input, Output, Peripheral, } #[derive(PartialEq, Clone, Copy)] pub enum Level { High, Low, } enum ...
Pin7, } #[derive(PartialEq, Clone, Copy)] #[allow(missing_docs)] pub enum PinPort { PortA(Pin), PortB(Pin), PortC(Pin),
random
[ { "content": "/// Configure the oscillator to use an external crystal.\n\npub fn init() {\n\n let mut osc = reg::get_osc();\n\n osc.cr.write(reg::OSC_CR_RANGE | reg::OSC_CR_OSCOS | reg::OSC_CR_OSCEN);\n\n while (osc.cr.read() & reg::OSC_CR_OSCINIT) == 0 {\n\n\n\n }\n\n}\n\n\n\n// *******************...
Rust
src/backend/types.rs
simnic/aries-askar
eafdc85e76f073426ea2ba57991cdf5d881b37a5
use crate::{ error::Error, future::BoxFuture, protect::{PassKey, StoreKeyMethod}, storage::{Entry, EntryKind, EntryOperation, EntryTag, Scan, TagFilter}, }; pub trait Backend: Send + Sync { type Session: QueryBackend; fn create_profile(&self, name: Option<String>) -> BoxFuture<'_, Re...
use crate::{ error::Error, future::BoxFuture, protect::{PassKey, StoreKeyMethod}, storage::{Entry, EntryKind, EntryOperation, EntryTag, Scan, TagFilter}, }; pub trait Backend: Send + Sync { type Session: QueryBackend; fn create_profile(&self, name: Option<String>) -> BoxFuture<'_, Re...
fn remove_backend(self) -> BoxFuture<'a, Result<bool, Error>>; } pub trait QueryBackend: Send { fn count<'q>( &'q mut self, kind: EntryKind, category: &'q str, tag_filter: Option<TagFilter>, ) -> BoxFuture<'q, Result<i64, Error>>; fn fetch<'q>( &'q mut se...
fn close(&self) -> BoxFuture<'_, Result<(), Error>>; } pub trait ManageBackend<'a> { type Store; fn open_backend( self, method: Option<StoreKeyMethod>, pass_key: PassKey<'a>, profile: Option<&'a str>, ) -> BoxFuture<'a, Result<Self::Store, Error>>; fn pr...
random
[ { "content": "pub fn parse_raw_store_key(raw_key: &str) -> Result<StoreKey, Error> {\n\n ArrayKey::<<StoreKeyType as KeyMeta>::KeySize>::temp(|key| {\n\n let key_len = bs58::decode(raw_key)\n\n .into(&mut *key)\n\n .map_err(|_| err_msg!(Input, \"Error parsing raw key as base58 va...
Rust
src/bindings/pbn_control/_impl_perturbation_graph.rs
sybila/biodivine-lib-bdd-py
0b2de2cd9410be06cd2d1c25e6ed3511d8adf420
use crate::bindings::lib_bdd::PyBddVariableSet; use crate::bindings::lib_param_bn::{ PyBooleanNetwork, PyGraphColoredVertices, PyGraphColors, PyParameterId, PySymbolicAsyncGraph, PyVariableId, }; use crate::bindings::pbn_control::{PyControlMap, PyPerturbationGraph}; use crate::{throw_runtime_error, AsNative}; u...
use crate::bindings::lib_bdd::PyBddVariableSet; use crate::bindings::lib_param_bn::{ PyBooleanNetwork, PyGraphColoredVertices, PyGraphColors, PyParameterId, PySymbolicAsyncGraph, PyVariableId, }; use crate::bindings::pbn_control::{PyControlMap, PyPerturbationGraph}; use crate::{throw_runtime_error, AsNative}; u...
} /* WARNING: The unit color set in the perturbed graph is not correct! It enforces observability and for a regulation to be observable, the variable cannot be perturbed. So the unit set only contains one non-perturbed parametrisation. Consequently, we use the original graph wh...
if let Some(id) = self.as_native().get_perturbation_parameter(variable) { Ok(id.into()) } else { return throw_runtime_error(format!("Variable {:?} not found", variable)); }
if_condition
[ { "content": "#[pyfunction]\n\npub fn reach_fwd(\n\n graph: &PySymbolicAsyncGraph,\n\n states: &PyGraphColoredVertices,\n\n universe: Option<&PyGraphColoredVertices>,\n\n) -> PyGraphColoredVertices {\n\n let variables = graph\n\n .as_native()\n\n .as_network()\n\n .variables()\n...
Rust
derive/src/union.rs
qwtsc/async-graphql
8aa406575b7f7bb05cb2fe1eb9512146cfbbed77
use crate::args; use crate::utils::{get_crate_name, get_rustdoc, GeneratorResult}; use darling::ast::{Data, Style}; use proc_macro::TokenStream; use quote::quote; use std::collections::HashSet; use syn::{Error, Type}; pub fn generate(union_args: &args::Union) -> GeneratorResult<TokenStream> { let crate_name = get_...
use crate::args; use crate::utils::{get_crate_name, get_rustdoc, GeneratorResult}; use darling::ast::{Data, Style}; use proc_macro::TokenStream; use quote::quote; use std::collections::HashSet; use syn::{Error, Type}; pub fn generate(union_args: &args::Union) -> GeneratorResult<TokenStream> { let crate_name = get_...
#ident::#enum_name(obj) => <#p as #crate_name::Type>::type_name() }); } else { get_introspection_typename.push(quote! { #ident::#enum_name(obj) => <#p as #crate_name::Type>::introspection_type_name(obj) }); ...
-> Self { #ident::#enum_name(obj) } } }); } registry_types.push(quote! { <#p as #crate_name::Type>::create_type_info(registry); }); if !variant.flatten { ...
random
[ { "content": "pub fn get_param_getter_ident(name: &str) -> Ident {\n\n Ident::new(&format!(\"__{}_getter\", name), Span::call_site())\n\n}\n\n\n", "file_path": "derive/src/utils.rs", "rank": 0, "score": 271880.6102825229 }, { "content": "fn validate_type(ctx: &mut VisitorContext<'_>, type...
Rust
src/middleware/compression.rs
Adrodoc/another-rust-load-balancer
166c97aae13c35b125a3f3658fa0374627589456
use crate::utils::split_once; use super::{Context, Middleware, MiddlewareChain}; use async_compression::tokio::bufread::{BrotliEncoder, DeflateEncoder, GzipEncoder}; use async_trait::async_trait; use futures::TryStreamExt; use hyper::{ header::{HeaderValue, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH}, Body,...
use crate::utils::split_once; use super::{Context, Middleware, MiddlewareChain}; use async_compression::tokio::bufread::{BrotliEncoder, DeflateEncoder, GzipEncoder}; use async_trait::async_trait; use futures::TryStreamExt; use hyper::{ header::{HeaderValue, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH}, Body,...
#[test] fn test_get_preferred_encoding_deflate_and_gzip_qvalues() { let mut headers = HeaderMap::new(); headers.insert(ACCEPT_ENCODING, "deflate;q=0.9, gzip;q=1".parse().unwrap()); let actual = get_preferred_encoding(&headers); assert_eq!(actual, Some(GZIP)); } #[test] fn t...
G, "deflate, gzip".parse().unwrap()); let actual = get_preferred_encoding(&headers); assert_eq!(actual, Some(DEFLATE)); }
function_block-function_prefixed
[ { "content": "fn backend_request(request: Request<Body>, context: &Context) -> Request<Body> {\n\n let builder = Request::builder().uri(&context.backend_uri);\n\n\n\n let mut builder = request\n\n .headers()\n\n .iter()\n\n .fold(builder, |builder, (key, val)| builder.header(key, val))\n\n .header...
Rust
linkerd/app/inbound/src/http/mod.rs
ecafkoob/linkerd2-proxy
556cc61a218861e7e31c6cb19eac601e16542357
mod router; mod server; mod set_identity_header; #[cfg(test)] mod tests; fn trace_labels() -> std::collections::HashMap<String, String> { let mut l = std::collections::HashMap::new(); l.insert("direction".to_string(), "inbound".to_string()); l } #[cfg(fuzzing)] pub mod fuzz { use crate::{ http...
mod router; mod server; mod set_identity_header; #[cfg(test)] mod tests; fn trace_labels() -> std::collections::HashMap<String, String> { let mut l = std::collections::HashMap::new(); l.insert("direction".to_string(), "inbound".to_string()); l } #[cfg(fuzzing)] pub mod fuzz { use crate::{ http...
{ hyper::http::Method::POST }; if let Ok(req) = Request::builder() .method(http_method) .uri(uri) .header(header_name, header_value) ...
::resolver(); let profile_tx = profiles .profile_tx(NameAddr::from_str_and_port("foo.svc.cluster.local", 5550).unwrap()); profile_tx.send(profile::Profile::default()).unwrap(); let cfg = default_config(); let (rt, _shutdown) = runtime(); let server = build_f...
function_block-random_span
[ { "content": "#[tracing::instrument]\n\nfn connect_error() -> impl Fn(Remote<ServerAddr>) -> io::Result<io::BoxedIo> {\n\n move |_| {\n\n Err(io::Error::new(\n\n io::ErrorKind::Other,\n\n \"server is not listening\",\n\n ))\n\n }\n\n}\n\n\n", "file_path": "linkerd/a...
Rust
src/stats/univariate/sample.rs
eclipseo/criterion.rs
3e8c890afd2a8373886fd8dadadaa480d5b85154
use std::{mem, ops}; use crate::stats::float::Float; use crate::stats::tuple::{Tuple, TupledDistributionsBuilder}; use crate::stats::univariate::Percentiles; use crate::stats::univariate::Resamples; use cast; use rayon::prelude::*; pub struct Sample<A>([A]); impl<A> Sample<A> where A: Float, { ...
use std::{mem, ops}; use crate::stats::float::Float; use crate::stats::tuple::{Tuple, TupledDistributionsBuilder}; use crate::stats::univariate::Percentiles; use crate::stats::univariate::Resamples; use cast; use rayon::prelude::*; pub struct Sample<A>([A]); impl<A> Sample<A> where A: Float, { ...
A { crate::stats::sum(self) } pub fn t(&self, other: &Sample<A>) -> A { let (x_bar, y_bar) = (self.mean(), other.mean()); let (s2_x, s2_y) = (self.var(Some(x_bar)), other.var(Some(y_bar))); let n_x = A::cast(self.len()); let n_y = A::cast(other.len()); ...
rdering::Less } else if a == b { Ordering::Equal } else { Ordering::Greater } } let mut v = self.to_vec().into_boxed_slice(); v.par_sort_unstable_by(cmp); unsafe { mem::transmute(v) } } ...
random
[ { "content": "#[cfg_attr(feature = \"cargo-clippy\", allow(clippy::inline_always))]\n\n#[inline(always)]\n\npub fn Output<P>(path: P) -> OutputType\n\nwhere\n\n P: Into<Cow<'static, Path>>,\n\n{\n\n OutputType(path.into())\n\n}\n", "file_path": "plot/src/proxy.rs", "rank": 0, "score": 159852.7...
Rust
src/environment.rs
cakebaker/rlox
c13865ad093a4ec99e6b9a5e289a4ee1963a786f
use crate::error::RuntimeError; use crate::value::Value; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; #[derive(Clone, Debug, Default, PartialEq)] pub struct Environment { parent: Option<Rc<RefCell<Environment>>>, values: HashMap<String, Value>, } impl Environment { pub fn new() ...
use crate::error::RuntimeError; use crate::value::Value; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; #[derive(Clone, Debug, Default, PartialEq)] pub struct Environment { parent: Option<Rc<RefCell<Environment>>>, values: HashMap<String, Value>, } impl Environment { pub fn new() ...
t] fn assign_value_to_var() { let mut env = Environment::new(); env.define("key".to_string(), Value::String("value".to_string())); let previous_value = env .assign("key".to_string(), Value::String("new value".to_string())) .unwrap(); assert_eq!(previous_value...
value: Value) { self.values.insert(name, value); } pub fn get(&self, name: String) -> Result<Value, RuntimeError> { match self.values.get(&name) { Some(literal) => Ok(literal.clone()), None => match &self.parent { Some(c) => { let env ...
random
[ { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n\n\n match args.len() {\n\n 1 => run_prompt(),\n\n 2 => run_file(&args[1]),\n\n _ => {\n\n println!(\"Usage: rlox [script]\");\n\n // exit code from https://www.freebsd.org/cgi/man.cg...
Rust
vrp-scientific/src/common/text_reader.rs
andrewgy8/vrp
c94574ad555c6ca06480f678f52850caf9aa71cb
#[cfg(test)] #[path = "../../tests/unit/common/text_reader_test.rs"] mod text_reader_test; use std::collections::HashMap; use std::io::prelude::*; use std::io::{BufReader, Read}; use std::sync::Arc; use vrp_core::construction::constraints::*; use vrp_core::construction::heuristics::{create_end_activity, create_start_a...
#[cfg(test)] #[path = "../../tests/unit/common/text_reader_test.rs"] mod text_reader_test; use std::collections::HashMap; use std::io::prelude::*; use std::io::{BufReader, Read}; use std::sync::Arc; use vrp_core::construction::constraints::*; use vrp_core::construction::heuristics::{create_end_activity, create_start_a...
String::new(); let mut solution = Solution { registry: Registry::new(&problem.fleet), routes: vec![], unassigned: Default::default(), extras: problem.extras.clone(), }; loop { match read_line(&mut reader, &mut buffer) { Ok(read) if read > 0 => { ...
osts { fixed: 0.0, per_distance: 0.0, per_driving_time: 0.0, per_waiting_time: 0.0, per_service_time: 0.0, }, dimens: create_dimens_with_id("driver", 0), details: Default::default(), })], ...
random
[ { "content": "/// Creates time agnostic or time aware routing costs based on matrix data passed.\n\npub fn create_matrix_transport_cost(costs: Vec<MatrixData>) -> Result<Arc<dyn TransportCost + Send + Sync>, String> {\n\n if costs.is_empty() {\n\n return Err(\"No matrix data found\".to_string());\n\n ...
Rust
crates/revm/src/interpreter/memory.rs
alcuadrado/revm
eb3282dfa37bb4e97145037303dcc1853d88fe34
use crate::alloc::vec::Vec; use core::{ cmp::min, ops::{BitAnd, Not}, }; use primitive_types::U256; #[derive(Clone, Debug)] pub struct Memory { data: Vec<u8>, } impl Default for Memory { fn default() -> Self { Memory::new() } } impl Memory { pub fn new() -> Self { Self { ...
use crate::alloc::vec::Vec; use core::{ cmp::min, ops::{BitAnd, Not}, }; use primitive_type
n() == 0 } pub fn data(&self) -> &Vec<u8> { &self.data } pub fn resize(&mut self, new_size: usize) { self.data.resize(new_size, 0); } #[inline(always)] pub fn get_slice(&self, offset: usize, size: usize) -> &[u8] { &self.data[offset..offset + si...
s::U256; #[derive(Clone, Debug)] pub struct Memory { data: Vec<u8>, } impl Default for Memory { fn default() -> Self { Memory::new() } } impl Memory { pub fn new() -> Self { Self { data: Vec::with_capacity(4 * 1024), } } pub fn effective_len(&self) -...
random
[ { "content": "pub fn gas_query(gas_used: u64, gas_limit: u64) -> Result<u64, Return> {\n\n if gas_used > gas_limit {\n\n return Err(Return::OutOfGas);\n\n }\n\n Ok(gas_used)\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct PrecompileOutput {\n\n pub cost: u64,\n\n pub output: Vec<u8>,\n\n pub...
Rust
src/mechanisms/aes256cbc.rs
robin-nitrokey/trussed
d0df53a858594847c6a1b65582894c33e4b69968
use core::convert::TryInto; use crate::api::*; use crate::error::Error; use crate::service::*; use crate::types::*; #[cfg(feature = "aes256-cbc")] impl Encrypt for super::Aes256Cbc { fn encrypt(keystore: &mut impl Keystore, request: &request::Encrypt) -> Result<reply::Encrypt, Error> { use blo...
use core::convert::TryInto; use crate::api::*; use crate::error::Error; use crate::service::*; use crate::types::*; #[cfg(feature = "aes256-cbc")] impl Encrypt for super::Aes256Cbc { fn encrypt(keystore: &mut impl Keystore, request: &request::Encrypt) -> Result<reply::Encrypt, Error> { use blo...
} #[cfg(feature = "aes256-cbc")] impl Decrypt for super::Aes256Cbc { fn decrypt(keystore: &mut impl Keystore, request: &request::Decrypt) -> Result<reply::Decrypt, Error> { use block_modes::{BlockMode, Cbc}; use block_modes::block_padding::ZeroPadding; use aes::Aes256; type ...
r)?; let encryption_request = request::Encrypt { mechanism: Mechanism::Aes256Cbc, key: request.wrapping_key, message, associated_data: ShortData::new(), nonce: None, }; let encryption_reply = <super::Aes256Cbc>::encrypt(keystore, &encr...
function_block-function_prefixed
[ { "content": " #[inline(never)]\n\nfn increment_nonce(nonce: &mut [u8]) -> Result<(), Error> {\n\n let mut carry: u16 = 1;\n\n for digit in nonce.iter_mut() {\n\n let x = (*digit as u16) + carry;\n\n *digit = x as u8;\n\n carry = x >> 8;\n\n }\n\n if carry == 0 {\n\n O...
Rust
server/entity/src/object/item.rs
Inky-developer/feather
2a83e56e01e63622d0abe29831b6f25bb37f73fd
use feather_core::anvil::entity::{ BaseEntityData, EntityData, EntityDataKind, ItemData, ItemEntityData, }; use feather_core::entitymeta::{EntityMetadata, META_INDEX_ITEM_SLOT}; use feather_core::inventory::Inventory; use feather_core::items::{Item, ItemStack}; use feather_core::network::packets::SpawnObject; use...
use feather_core::anvil::entity::{ BaseEntityData, EntityData, EntityDataKind, ItemData, ItemEntityData, }; use feather_core::entitymeta::{EntityMetadata, META_INDEX_ITEM_SLOT}; use feather_core::inventory::Inventory; use feather_core::items::{Item, ItemStack}; use feather_core::network::packets::SpawnObject; use...
pub fn create(stack: ItemStack, collectable_at: u64) -> EntityBuilder { let meta = EntityMetadata::entity_base().with(META_INDEX_ITEM_SLOT, Some(stack)); let collectable_at = CollectableAt(collectable_at); crate::base() .with(stack) .with(IsRemoved(AtomicBool::new(false))) .with(c...
pub fn item_collect(game: &mut Game, world: &mut World) { if game.tick_count % (TPS / 10) != 0 { return; } let items_to_remove = Mutex::new(vec![]); let inventory_update_events = Mutex::new(vec![]); let item_collect_events = Mutex::new(vec![]); unsafe { ...
function_block-full_function
[ { "content": "#[fecs::system]\n\npub fn broadcast_velocity(world: &mut World, game: &mut Game) {\n\n <(Read<Velocity>, Read<PreviousVelocity>, Read<NetworkId>)>::query().par_entities_for_each(\n\n world.inner(),\n\n |(entity, (vel, prev_vel, entity_id))| {\n\n let entity_id = entity_...
Rust
src/lib.rs
WillyWoosley/lamport_ots
2a0e51cffe1cafa732a275f2d1e69d15fccccc95
use digest::Digest; use rand::{thread_rng, Rng}; use std::marker::PhantomData; use std::cmp::Ordering; use std::hash::{Hash, Hasher}; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)] pub struct PrivateKey { key_options: Vec<(Vec<u8>, Vec<u8>)>, } impl PrivateKey { ...
use digest::Digest; use rand::{thread_rng, Rng}; use std::marker::PhantomData; use std::cmp::Ordering; use std::hash::{Hash, Hasher}; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)] pub struct PrivateKey { key_options: Vec<(Vec<u8>, Vec<u8>)>, } impl PrivateKey { ...
public.cmp(&other.public)) .then(self.hasher.cmp(&other.hasher)) } } impl<T> Hash for KeyPair<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.private.hash(state); self.public.hash(state); self.hasher.hash(state); } } #[derive(Debug, Clone)] pub struct Signature<T> ...
ata<T>, } impl<T: Digest> KeyPair<T> { pub fn private(&self) -> &PrivateKey { &self.private } pub fn public(&self) -> &PublicKey<T> { &self.public } pub fn generate() -> Self { let privat...
random
[ { "content": "#[test]\n\nfn test_privkey_traits() {\n\n let pair1 = KeyPair::<Sha256>::generate();\n\n let pair2 = KeyPair::<Sha256>::generate();\n\n \n\n assert_ne!(pair1.private(), pair2.private());\n\n assert!(pair1.private() > pair2.private() || pair2.private() > pair1.private());\n\n\n\n ...
Rust
src/tools/math_stat_analysis/crispness_index.rs
Afrancioni/whitebox-tools
3208082ed182524e843158c8c4b2e846eb8a2ae8
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: August 15, 2017 Last Modified: Dec. 15, 2017 License: MIT NOTES: This index (C) is taken from Lindsay (2006) Sensitivity of channel mapping techniques to uncertainty in digital elevation data: C = SS_mp ∕ SS_B ...
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: August 15, 2017 Last Modified: Dec. 15, 2017 License: MIT NOTES: This index (C) is taken from Lindsay (2006) Sensitivity of channel mapping techniques to uncertainty in digital elevation data: C = SS_mp ∕ SS_B ...
} impl WhiteboxTool for CrispnessIndex { fn get_source_file(&self) -> String { String::from(file!()) } fn get_tool_name(&self) -> String { self.name.clone() } fn get_tool_description(&self) -> String { self.description.clone() } fn get_tool_parameters(&self) ...
parameters.push(ToolParameter{ name: "Output HTML File".to_owned(), flags: vec!["-o".to_owned(), "--output".to_owned()], description: "Optional output html file (default name will be based on input file if unspecified).".to_owned(), parameter_type: ParameterType::NewFil...
function_block-function_prefix_line
[ { "content": "pub fn read_surfer7(file_name: &String, configs: &mut RasterConfigs, data: &mut Vec<f64>) -> Result<(), Error> {\n\n\n\n // read data file\n\n let mut f = try!(File::open(file_name.clone()));\n\n let metadata = try!(fs::metadata(file_name.clone()));\n\n let file_size: usize = metadata....
Rust
src/resources/claimable_balance.rs
salessandri/stellar-horizon-rs
da160c36045dbca2251b45f8aad06a9fdc11e9cd
use crate::error::{Error, Result}; use crate::link::Link; use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Deserializer, Serialize}; use std::str::FromStr; use stellar_base::claim::ClaimPredicate; #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct ClaimableBalance { #[serde(rename...
use crate::error::{Error, Result}; use crate::link::Link; use chrono::{DateTime, Duration, Utc}; use serde::{Deserialize, Deserializer, Serialize}; use std::str::FromStr; use stellar_base::claim::ClaimPredicate; #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct ClaimableBalance { #[serde(rename...
:Or(inner) => { let mut predicates = inner.iter(); match (predicates.next(), predicates.next()) { (Some(p1), Some(p2)) => { let p1_claim_predicate = p1.to_claim_predicate()?; let p2_claim_predicate = p2.to_claim_predicat...
sactions: Link, pub operations: Link, } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct Claimant { pub destination: String, pub predicate: Predicate, } #[derive(Debug, Clone, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum Predicate { And(Vec<Box<Predicate>>),...
random
[ { "content": "/// Creates a request to retrieve a single liquidity pool.\n\npub fn single(id: String) -> SingleLiquidityPoolRequest {\n\n SingleLiquidityPoolRequest { id }\n\n}\n\n\n\n/// Request all liquidity pools.\n\n#[derive(Debug, Clone)]\n\npub struct AllLiquidityPoolsRequest {\n\n reserves: Option<...
Rust
chain-evm/src/tests.rs
The-Blockchain-Company/chain-libs
35086749fba07a5b3681dbd416e831337a4e60a9
use crate::machine::test::TestEvmState; use crate::machine::{transact_call, VirtualMachine}; use crate::{state::Account, Config}; use ethereum_types::{H160, U256}; use evm_test_suite::{AccountState, BlockHeader, CallTransaction, NetworkType}; use std::collections::BTreeSet; struct TestEvmLedger { state: TestEvmSta...
use crate::machine::test::TestEvmState; use crate::machine::{transact_call, VirtualMachine}; use crate::{state::Account, Config}; use ethereum_types::{H160, U256}; use evm_test_suite::{AccountState, BlockHeader, CallTransaction, NetworkType}; use std::collections::BTreeSet; struct TestEvmLedger { state: TestEvmSta...
} } impl evm_test_suite::TestEvmState for TestEvmLedger { fn init_state() -> Self { Self { state: TestEvmState { environment: Default::default(), accounts: Default::default(), logs: Default::default(), }, config: Defau...
Ok(Self { nonce: val.nonce, balance: val .balance .try_into() .map_err(|_| "can not convert balance")?, storage: val.storage.into_iter().collect(), code: val.code, })
call_expression
[ { "content": "fn unpack_account_state(codec: &mut Codec<&[u8]>) -> Result<AccountState<()>, ReadError> {\n\n let spending = unpack_spending_strategy(codec)?;\n\n let delegation = unpack_delegation_type(codec)?;\n\n let value = codec.get_be_u64()?;\n\n let last_rewards = unpack_last_rewards(codec)?;\...
Rust
kernel/src/syscall/signal.rs
EatenBagpipe/rCore
e7bad89a207fc818a3b24cd6bdaa1b767c516190
use crate::arch::interrupt::TrapFrame; use crate::process::{current_thread, process_of, thread_manager, PROCESSES}; use crate::process::{process, process_group}; use crate::signal::Signal::SIGINT; use crate::signal::*; use crate::syscall::SysError::{EINVAL, ENOMEM, EPERM, ESRCH}; use crate::syscall::{SysResult, Syscall...
use crate::arch::interrupt::TrapFrame; use crate::process::{current_thread, process_of, thread_manager, PROCESSES}; use crate::process::{process, process_group}; use crate::signal::Signal::SIGINT; use crate::signal::*; use crate::syscall::SysError::{EINVAL, ENOMEM, EPERM, ESRCH}; use crate::syscall::{SysResult, Syscall...
send_signal(process, -1, info); } Ok(0) } } } } else { info!("kill: pid: {}, signal: UNKNOWN", pid); Err(EINVAL) } } pub fn sys_tkill(&mut self, tid: usize, sign...
ion( &self, signum: usize, act: *const SignalAction, oldact: *mut SignalAction, sigsetsize: usize, ) -> SysResult { if let Some(signal) = <Signal as FromPrimitive>::from_usize(signum) { info!( "rt_sigaction: signum: {:?}, act: {:?}, oldact:...
random
[ { "content": "/// return the process which thread tid is in\n\npub fn process_of(tid: usize) -> Option<Arc<Mutex<Process>>> {\n\n PROCESSES.read().iter().find_map(|(pid, weak)| {\n\n if let Some(process) = weak.upgrade() {\n\n if process.lock().threads.contains(&tid) {\n\n So...
Rust
sdk/zksync-rs/src/utils.rs
smishraIOV/ri-aggregation
abcd90954335b6ee8513876de0118f567d979a32
use std::time::Duration; use std::time::Instant; use num::BigUint; use sha2::{Digest, Sha256}; use zksync_crypto::bellman::{pairing::ff::PrimeField, PrimeFieldRepr}; use zksync_crypto::franklin_crypto::alt_babyjubjub::fs::FsRepr; use zksync_crypto::{priv_key_from_fs, Fs, PrivateKey}; use zksync_eth_signer::EthereumSi...
use std::time::Duration; use std::time::Instant; use num::BigUint; use sha2::{Digest, Sha256}; use zksync_crypto::bellman::{pairing::ff::PrimeField, PrimeFieldRepr}; use zksync_crypto::franklin_crypto::alt_babyjubjub::fs::FsRepr; use zksync_crypto::{priv_key_from_fs, Fs, PrivateKey}; use zksync_eth_signer::EthereumSi...
.id .is_none() { if start.elapsed() > timeout { return None; } poller.tick().await; } wallet.update_account_id().await.ok()?; wallet.account_id() } pub fn u256_to_biguint(value: U256) -> BigUint { let mut bytes = [0u8; 32]; value.to_little_...
tion::from_millis(100)); let start = Instant::now(); while wallet .provider .account_info(wallet.address()) .await .ok()?
random
[ { "content": "/// Decodes a private key from a field element.\n\npub fn priv_key_from_fs(fs: Fs) -> PrivateKey {\n\n PrivateKeyImport(fs)\n\n}\n\n\n", "file_path": "core/lib/crypto/src/lib.rs", "rank": 0, "score": 283913.0005534991 }, { "content": "pub fn bench_rescue_hasher(c: &mut Crite...
Rust
eval/src/values/variable_map.rs
slowli/arithmetic-parser
3e01a6069ddea36740126c40386deea0b6dfaee7
#![allow(renamed_and_removed_lints, clippy::unknown_clippy_lints)] use arithmetic_parser::{grammars::Grammar, Block}; use core::{cmp::Ordering, fmt}; use crate::{fns, Environment, Error, ExecutableModule, ModuleId, ModuleImports, Value}; pub trait VariableMap<'a, T> { fn get_variable(&self, name: &str) -...
#![allow(renamed_and_removed_lints, clippy::unknown_clippy_lints)] use arithmetic_parser::{grammars::Grammar, Block}; use core::{cmp::Ordering, fmt}; use crate::{fns, Environment, Error, ExecutableModule, ModuleId, ModuleImports, Value}; pub trait VariableMap<'a, T> { fn get_variable(&self, name: &str) -...
} impl<'a, T: Clone> VariableMap<'a, T> for Environment<'a, T> { fn get_variable(&self, name: &str) -> Option<Value<'a, T>> { self.get(name).cloned() } } impl<'a, T: Clone> VariableMap<'a, T> for ModuleImports<'a, T> { fn get_variable(&self, name: &str) -> Option<Value<'a, T>> { self.get(...
fn compile_module<Id, G>( &self, id: Id, block: &Block<'a, G>, ) -> Result<ExecutableModule<'a, T>, Error<'a>> where Id: ModuleId, G: Grammar<'a, Lit = T>, T: Clone + fmt::Debug, { ExecutableModule::builder(id, block)? .with_imports_from(se...
function_block-full_function
[ { "content": "/// Checks if the provided string is a valid variable name.\n\npub fn is_valid_variable_name(name: &str) -> bool {\n\n if name.is_empty() || !name.is_ascii() {\n\n return false;\n\n }\n\n\n\n match var_name(InputSpan::new(name)) {\n\n Ok((rest, _)) => rest.fragment().is_empt...
Rust
dlc-trie/src/multi_oracle_trie_with_diff.rs
p2pderivatives/rust-dlc
5df14bac49f7abcf9b62d9bb498783fecad49543
use crate::digit_decomposition::group_by_ignoring_digits; use crate::multi_trie::{MultiTrie, MultiTrieDump, MultiTrieIterator}; use crate::utils::get_adaptor_point_for_indexed_paths; use crate::DlcTrie; use crate::{Error, RangeInfo, RangePayout}; use bitcoin::{Script, Transaction}; use secp256k1_zkp::{All, EcdsaAdapt...
use crate::digit_decomposition::group_by_ignoring_digits; use crate::multi_trie::{MultiTrie, MultiTrieDump, MultiTrieIterator}; use crate::utils::get_adaptor_point_for_indexed_paths; use crate::DlcTrie; use crate::{Error, RangeInfo, RangePayout}; use bitcoin::{Script, Transaction}; use secp256k1_zkp::{All, EcdsaAdapt...
adaptor_pairs.push((range_info.adaptor_index, adaptor_pair)); Ok(()) }; self.iter(precomputed_points, &mut callback)?; adaptor_pairs.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); Ok(adaptor_pairs.into_iter().map(|x| x.1).collect()) } } pub st...
let adaptor_pair = dlc::create_cet_adaptor_sig_from_point( &secp, &cets[range_info.cet_index], &adaptor_point, fund_privkey, &funding_script_pubkey, fund_output_value, )?;
assignment_statement
[ { "content": "fn get_pkh_script_pubkey_from_sk<C: Signing>(secp: &Secp256k1<C>, sk: &SecretKey) -> Script {\n\n use bitcoin::hashes::*;\n\n let pk = bitcoin::PublicKey {\n\n compressed: true,\n\n key: PublicKey::from_secret_key(secp, sk),\n\n };\n\n let mut hash_engine = PubkeyHash::en...
Rust
core/src/domain/supply/resources/types.rs
Szetty/seven_wonders
77f6f4ff015a8fc481c7edfc87e3cd77b61bc79b
use derive_more::Display; use itertools::Itertools; use std::collections::HashMap; use strum::IntoEnumIterator; use strum_macros::EnumIter; pub type ResourceTypes<'a> = &'a [ResourceType]; #[derive( Display, Debug, EnumIter, PartialEq, Clone, Copy, Eq, Hash, PartialOrd, Ord, serde::Serialize, )] pub enum Resource...
use derive_more::Display; use itertools::Itertools; use std::collections::HashMap; use strum::IntoEnumIterator; use strum_macros::EnumIter; pub type ResourceTypes<'a> = &'a [ResourceType]; #[derive( Display, Debug, EnumIter, PartialEq, Clone, Copy, Eq, Hash, PartialOrd, Ord, serde::Serialize, )] pub enum Resource...
fn test_diff_resource_costs() { assert_eq!(diff_resource_costs(vec![], vec![]), vec![]); assert_eq!( diff_resource_costs(vec![ResourceCost(Wood, 1)], vec![ResourceCost(Wood, 1)]), vec![] ); assert_eq!( diff_resource_costs(vec![ResourceCost(Wood, 1)], vec![ResourceCost(Loom, 1)]),...
function_block-full_function
[ { "content": "pub fn assert_combination_of_three(\n\n f: fn(\n\n any_resources: Vec<Vec<ResourceType>>,\n\n resource_costs: Vec<ResourceCost>,\n\n ) -> Vec<Combination>,\n\n) {\n\n assert_eq!(\n\n f(\n\n vec![vec![Ore], vec![Loom], vec![Stone]],\n\n vec![Resou...
Rust
crates/vhdl/src/component.rs
matthijsr/til-vhdl
ef1bffdf17a976403f2b3b95ea853a4df012cfd7
use itertools::Itertools; use textwrap::indent; use tydi_common::{ error::{Result, TryResult}, traits::{Document, Documents, Identify}, }; use crate::object::object_type::ObjectType; use crate::{ architecture::arch_storage::Arch, common::vhdl_name::{VhdlName, VhdlNameSelf}, declaration::{Declare, ...
use itertools::Itertools; use textwrap::indent; use tydi_common::{ error::{Result, TryResult}, traits::{Document, Documents, Identify}, }; use crate::object::object_type::ObjectType; use crate::{ architecture::arch_storage::Arch, common::vhdl_name::{VhdlName, VhdlNameSelf}, declaration::{Declare, ...
} pub fn ports(&self) -> &Vec<Port> { &self.ports } pub fn parameters(&self) -> &Vec<Parameter> { &self.parameters } pub fn name(&self) -> &VhdlName { &self.identifier } } impl Identify for Component { fn identifier(&self) -> String { self.i...
Ok(Component { identifier: identifier.try_result()?, parameters, ports, doc, })
call_expression
[]
Rust
crates/sui-core/src/safe_client.rs
bmwill/sui
a0f57697ad546bf97b30cffffef132028783b88f
use crate::authority_client::{AuthorityAPI, BatchInfoResponseItemStream}; use async_trait::async_trait; use futures::StreamExt; use sui_types::batch::{AuthorityBatch, SignedBatch, TxSequenceNumber, UpdateItem}; use sui_types::crypto::PublicKeyBytes; use sui_types::messages_checkpoint::{CheckpointRequest, CheckpointRe...
use crate::authority_client::{AuthorityAPI, BatchInfoResponseItemStream}; use async_trait::async_trait; use futures::StreamExt; use sui_types::batch::{AuthorityBatch, SignedBatch, TxSequenceNumber, UpdateItem}; use sui_types::crypto::PublicKeyBytes; use sui_types::messages_checkpoint::{CheckpointRequest, CheckpointRe...
fn check_object_response( &self, request: &ObjectInfoRequest, response: &ObjectInfoResponse, ) -> SuiResult { if let Some(certificate) = &response.parent_certificate { certificate.verify(&self.committee)?; } if let Some((object_id,...
fn check_transaction_response( &self, digest: TransactionDigest, response: &TransactionInfoResponse, ) -> SuiResult { if let Some(signed_transaction) = &response.signed_transaction { signed_transaction.verify(&self.committee)?; fp_ens...
function_block-full_function
[ { "content": "/// Generate a keypair from the specified RNG (useful for testing with seedable rngs).\n\npub fn get_key_pair_from_rng<R>(csprng: &mut R) -> (SuiAddress, KeyPair)\n\nwhere\n\n R: rand::CryptoRng + rand::RngCore,\n\n{\n\n let kp = DalekKeypair::generate(csprng);\n\n let keypair = KeyPair {...
Rust
src/backend/test.rs
sagiegurari/tui-rs
087a2398f0c2c1e7d9b73cb82c746a2f6f38355f
use crate::{ backend::Backend, buffer::{Buffer, Cell}, layout::Rect, }; use std::{fmt::Write, io}; use unicode_width::UnicodeWidthStr; #[derive(Debug)] pub struct TestBackend { width: u16, buffer: Buffer, height: u16, cursor: bool, pos: (u16, u16), } fn buffer_view(buffer: &Buffer) -> ...
use crate::{ backend::Backend, buffer::{Buffer, Cell}, layout::Rect, }; use std::{fmt::Write, io}; use unicode_width::UnicodeWidthStr; #[derive(Debug)] pub struct TestBackend { width: u16,
io::Error> where I: Iterator<Item = (u16, u16, &'a Cell)>, { for (x, y, c) in content { let cell = self.buffer.get_mut(x, y); *cell = c.clone(); } Ok(()) } fn hide_cursor(&mut self) -> Result<(), io::Error> { self.cursor = false; ...
buffer: Buffer, height: u16, cursor: bool, pos: (u16, u16), } fn buffer_view(buffer: &Buffer) -> String { let mut view = String::with_capacity(buffer.content.len() + buffer.area.height as usize * 3); for cells in buffer.content.chunks(buffer.area.width as usize) { let mut overwritten = ...
random
[]
Rust
src/rust/core/server/src/process/builder.rs
wandaitzuchen/pelikan
7421cdedbd5cf5c9814d244ae02eef5ec05904bf
use super::*; use crate::threads::*; use crate::THREAD_PREFIX; use config::AdminConfig; use config::ServerConfig; use config::TlsConfig; use config::WorkerConfig; use entrystore::EntryStore; use logger::*; use protocol::{Compose, Execute, Parse}; use queues::QueuePairs; use std::io::Error; pub struct ProcessBuilder<...
use super::*; use crate::threads::*; use crate::THREAD_PREFIX; use config::AdminConfig; use config::ServerConfig; use config::TlsConfig; use config::WorkerConfig; use entrystore::EntryStore; use logger::*; use protocol::{Compose, Execute, Parse}; use queues::QueuePairs; use std::io::Error; pub struct ProcessBuilder<...
der::new() .name(format!("{}_listener", THREAD_PREFIX)) .spawn(move || listener.run()) .unwrap()]; let worker_threads = self.worker.launch_threads(); for thread in worker_threads { threads.push(thread); } threads.push( std::thre...
stener.signal_queue()); signal_queue.add_pair(self.listener.signal_queue()); for queue in self.worker.signal_queues() { self.admin.add_signal_queue(queue); } let mut admin = self.admin; let mut listener = self.listener; let mut threads = ve...
function_block-random_span
[ { "content": "/// A `Drain` serves to receive log messages from a queue and flush them to an\n\n/// `Output`.\n\npub trait Drain: Send {\n\n /// Flushes log messages from the queue to the `Output` for this `Drain`.\n\n /// This function must be called periodically to ensure there is capacity on\n\n ///...
Rust
darknet-test/build.rs
jerry73204/yolo-dl
35fde79c70d62fc70f045acc8fee7aa85555298b
use anyhow::{format_err, Result}; use fs_extra::dir::CopyOptions; use std::{ env, fs, path::{Path, PathBuf}, }; const DARKNET_SRC_ENV: &'static str = "DARKNET_SRC"; lazy_static::lazy_static! { static ref BINDINGS_SRC_PATH: PathBuf = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("Failed to get CARGO_...
use anyhow::{format_err, Result}; use fs_extra::dir::CopyOptions; use std::{ env, fs, path::{Path, PathBuf}, }; const DARKNET_SRC_ENV: &'static str = "DARKNET_SRC"; lazy_static::lazy_static! { static ref BINDINGS_SRC_PATH: PathBuf = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("Failed to get CARGO_...
fn main() -> Result<()> { println!("cargo:rerun-if-env-changed={}", DARKNET_SRC_ENV); if cfg!(feature = "docs-rs") { return Ok(()); } build_from_source()?; Ok(()) }
fn build_from_source() -> Result<()> { let src_dir: PathBuf = match env::var_os(DARKNET_SRC_ENV) { Some(src) => src.into(), None => PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("darknet"), }; build_with_cmake(src_dir)?; Ok(()) }
function_block-full_function
[ { "content": "fn default_libtorch_cxx11_abi() -> bool {\n\n true\n\n}\n", "file_path": "tch-nms/build.rs", "rank": 2, "score": 236127.5438241637 }, { "content": "fn info(config_file: impl AsRef<Path>) -> Result<()> {\n\n let graph = Graph::load_newslab_v1_json(config_file)?;\n\n let...