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
fall/gen/src/generate/codegen.rs
zayenz/fall
71cd05c6eaa026f692db87d4a8ffe1326706efd4
use serde_json; use tera::Context; use fall_tree::{Text, AstNode}; use lang_fall::syntax::{FallFile, SynRule, LexRule, Expr, BlockExpr, MethodDef, Parameter}; use lang_fall::{RefKind, CallKind, MethodKind, Analysis, PratVariant, PrattOp, Arity, ChildKind}; use fall_parse as dst; use crate::ut...
use serde_json; use tera::Context; use fall_tree::{Text, AstNode}; use lang_fall::syntax::{FallFile, SynRule, LexRule, Expr, BlockExpr, MethodDef, Parameter}; use lang_fall::{RefKind, CallKind, MethodKind, Analysis, PratVariant, PrattOp, Arity, ChildKind}; use fall_parse as dst; use crate::ut...
} RefKind::RuleReference(rule) => return Ok(self.syn_rule_ref(rule)), RefKind::Param(p) => dst::Expr::Var(self.param_ref(p)), } } Expr::CallExpr(call) => { let call = self.analysis.resolve_call(call) ...
if rule.is_contextual() { dst::Expr::ContextualToken( ty_ref, rule.token_text() .ok_or(format_err!("Missing contextual token text"))? .to_string(), ...
if_condition
[ { "content": "fn parse_expr_pred(p: &mut Parser, expr: ExprRef, tokens: Pos) -> Option<Pos> {\n\n let old_mode = p.predicate_mode;\n\n p.predicate_mode = true;\n\n let result = parse_expr(p, expr, tokens);\n\n p.predicate_mode = old_mode;\n\n result\n\n}\n\n\n", "file_path": "fall/parse/src/s...
Rust
truck-rendimpl/src/shaperend.rs
mattiasgronlund/truck
df78ff348b448d41743c2f7db1f93ebb3c0f41ca
use crate::*; use truck_meshalgo::tessellation::*; use truck_topology::*; impl Default for ShapeInstanceDescriptor { #[inline(always)] fn default() -> Self { ShapeInstanceDescriptor { instance_state: Default::default(), mesh_precision: 0.005, } } } impl<Shape: Mesha...
use crate::*; use truck_meshalgo::tessellation::*; use truck_topology::*; impl Default for ShapeInstanceDescriptor { #[inline(always)] fn default() -> Self { ShapeInstanceDescriptor { instance_state: Default::default(), mesh_precision: 0.005, } } } impl<Shape: Mesha...
} impl<C, S> IntoInstance<WireFrameInstance> for Solid<Point3, C, S> where C: PolylineableCurve, { type Descriptor = ShapeWireFrameDescriptor; fn into_instance( &self, handler: &DeviceHandler, shaders: &WireShaders, desc: &ShapeWireFrameDescriptor, ) -> WireFrameInstanc...
fn into_instance( &self, handler: &DeviceHandler, shaders: &WireShaders, desc: &ShapeWireFrameDescriptor, ) -> WireFrameInstance { let mut lengths = Vec::new(); let points: Vec<[f32; 3]> = self .face_iter() .flat_map(|face| face.boundary_iters(...
function_block-full_function
[ { "content": "fn nontex_inst_desc() -> PolygonInstanceDescriptor {\n\n PolygonInstanceDescriptor {\n\n instance_state: InstanceState {\n\n matrix: Matrix4::from_cols(\n\n [1.0, 2.0, 3.0, 4.0].into(),\n\n [5.0, 6.0, 7.0, 8.0].into(),\n\n [9.0, 10....
Rust
src/units/units.rs
zboldyga/rustysd
ecc35896385d5909686f275dc6356226c9e5113b
use crate::fd_store::FDStore; use crate::platform::EventFd; use crate::services::Service; use crate::sockets::{Socket, SocketKind, SpecializedSocketConfig}; use crate::units::*; use nix::unistd::Pid; use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; use std::{fmt, path::PathBuf}; #[derive(Clone, Cop...
use crate::fd_store::FDStore; use crate::platform::EventFd; use crate::services::Service; use crate::sockets::{Socket, SocketKind, SpecializedSocketConfig}; use crate::units::*; use nix::unistd::Pid; use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; use std::{fmt, path::PathBuf}; #[derive(Clone, Cop...
} #[derive(Debug)] pub struct UnitConfig { pub filepath: PathBuf, pub description: String, pub wants: Vec<String>, pub requires: Vec<String>, pub before: Vec<String>, pub after: Vec<String>, } impl UnitConfig { pub fn name(&self) -> String { let name = self .filepath...
pub fn deactivate(&mut self, run_info: ArcRuntimeInfo) -> Result<(), UnitOperationError> { trace!("Deactivate unit: {}", self.conf.name()); match &mut self.specialized { UnitSpecialized::Target => { /* nothing to do */ } UnitSpecialized::Socket(sock) => { sock.clo...
function_block-full_function
[ { "content": "// make edges between units visible on bot sides: required <-> required_by after <-> before\n\npub fn fill_dependencies(units: &mut HashMap<UnitId, Unit>) {\n\n let mut name_to_id = HashMap::new();\n\n\n\n for (id, unit) in &*units {\n\n let name = unit.conf.name();\n\n name_t...
Rust
tests/roundtrip.rs
rrbutani/tower-web-protobuf
6787af73a44f5d4873d58dced0cbe11805cf7767
mod common; use common::*; use reqwest::{Client, StatusCode}; use std::io::Read; use std::net::SocketAddr; use tower_web_protobuf::MessagePlus; #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum Format { Protobuf, Json, } impl Format { fn get_header(self) -> &'static str { match self { ...
mod common; use common::*; use reqwest::{Client, StatusCode}; use std::io::Read; use std::net::SocketAddr; use tower_web_protobuf::MessagePlus; #[derive(Copy, Clone, Debug, PartialEq, Eq)] enum Format { Protobuf, Json, } impl Format { fn get_header(self) -> &'static str { match self { ...
id: 0, }, ); endpoint_test( "/identity/album/", *socket, Album { name: "In Colour".into(), id: 2015, album_type: 2, tracks: vec![ Track { ...
|socket| { use Format::*; const FORMATS: [Format; 2] = [Json, Protobuf]; fn endpoint_test<T: MessagePlus + PartialEq + Clone>( endpoint: &'static str, socket: SocketAddr, val: T, ) { FORMATS.iter().for_each(|inp| { FORMAT...
function_block-random_span
[ { "content": "fn setup(options: (bool, bool), socket: &SocketAddr) {\n\n ServiceBuilder::new()\n\n .resource(MusicService::new())\n\n .middleware(ProtobufMiddleware::new(options.0, options.1))\n\n .run(&socket)\n\n .unwrap();\n\n}\n\n\n", "file_path": "tests/common.rs", "r...
Rust
oot-explorer-demo/src/reflect_text.rs
mvanbem/oot-explorer
a2574ac5d2c3b2eb8bc6229e887b0ad7ff0fe732
use oot_explorer_read::{FromVrom, ReadError}; use oot_explorer_reflect::{ BitfieldDescriptor, EnumDescriptor, FieldDescriptor, PointerDescriptor, PrimitiveType, StructDescriptor, StructFieldLocation, TypeDescriptor, UnionDescriptor, }; use oot_explorer_segment::{SegmentAddr, SegmentTable}; use oot_explorer_vrom...
use oot_explorer_read::{FromVrom, ReadError}; use oot_explorer_reflect::{ BitfieldDescriptor, EnumDescriptor, FieldDescriptor, PointerDescriptor, PrimitiveType, StructDescriptor, StructFieldLocation, TypeDescriptor, UnionDescriptor, }; use oot_explorer_segment::{SegmentAddr, SegmentTable}; use oot_explorer_vrom...
, Err(e) => print!("{}", e), } } fn dump_primitive(vrom: Vrom<'_>, desc: PrimitiveType, addr: VromAddr) -> () { let try_print = || { match desc { PrimitiveType::Bool => print!("{}", bool::from_vrom(vrom, addr)?), PrimitiveType::U8 => print!("{}", u8::from_vrom(vrom, addr...
match desc.values.binary_search_by_key(&value, |&(x, _)| x) { Ok(index) => print!("{}", desc.values[index].1), Err(_) => print!("(unknown value 0x{:x}", value), }
if_condition
[ { "content": "pub fn is_end<T>(vrom: Vrom<'_>, addr: VromAddr) -> bool\n\nwhere\n\n T: FromVrom + Layout + Sentinel,\n\n{\n\n match T::from_vrom(vrom, addr) {\n\n Ok(value) => value.is_end(vrom),\n\n Err(_) => true,\n\n }\n\n}\n", "file_path": "oot-explorer-read/src/sentinel.rs", ...
Rust
src/trace/collector.rs
piercetrey-figure/minitrace-rust
1ab75c3399b07b86d8e142a8e5a81f1f0d1d9f17
use crossbeam::channel::Receiver; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; use crate::span::Span; use crate::span::{Anchor, DefaultClock}; use crate::trace::acquirer::SpanCollection; pub struct Collector { receiver: Receiver<SpanCollection>, closed: Arc<At...
use crossbeam::channel::Receiver; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; use crate::span::Span; use crate::span::{Anchor, DefaultClock}; use crate::trace::acquirer::SpanCollection; pub struct Collector { receiver: Receiver<SpanCollection>, closed: Arc<At...
} impl Collector { #[inline] fn amend(span_collections: Vec<SpanCollection>, anchor: Anchor) -> Vec<Span> { let capacity = span_collections .iter() .map(|sc| match sc { SpanCollection::LocalSpans { local_spans: raw_spans, ...
er().collect() }; self.closed.store(true, Ordering::SeqCst); let anchor = DefaultClock::anchor(); if let Some(duration) = duration_threshold { if let Some(root_span) = span_collections.iter().find_map(|s| match s { SpanCollection::Span(s) if s.pa...
function_block-function_prefixed
[ { "content": "#[proc_macro_attribute]\n\n#[proc_macro_error]\n\npub fn trace(args: TokenStream, item: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(item as syn::ItemFn);\n\n let event = syn::parse_macro_input!(args as syn::Expr);\n\n\n\n let syn::ItemFn {\n\n attrs,\n\n ...
Rust
src/bin/main.rs
yumcyaWiz/rusmallpt
aa7ce93096a6b5735a711cf6585dd969c4456389
use std::f32::consts::{FRAC_PI_2, FRAC_PI_4}; use std::sync::{Arc, Mutex}; use rusmallpt::camera::{Camera, PinholeCamera}; use rusmallpt::core::IntersectableLocal; use rusmallpt::image::Image; use rusmallpt::integrator::{Integrator, NormalIntegrator, PathTracingIntegrator}; use rusmallpt::sampler::Sampler; use rusmall...
use std::f32::consts::{FRAC_PI_2, FRAC_PI_4}; use std::sync::{Arc, Mutex}; use rusmallpt::camera::{Camera, PinholeCamera}; use rusmallpt::core::IntersectableLocal; use rusmallpt::image::Image; use rusmallpt::integrator::{Integrator, NormalIntegrator, PathTracingIntegrator}; use rusmallpt::sampler::Sampler; use rusmall...
fn cornellbox_scene() -> (PinholeCamera, Scene) { let camera = PinholeCamera::new( Vec3::new(278.0, 273.0, -900.0), Vec3::new(0.0, 0.0, 1.0), FRAC_PI_4, ); let floor = Box::new(Plane::new( Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 559.2), Vec3::new(556....
3::new(0.2, 0.8, 0.2), Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0), ), Material::new( Vec3::new(0.2, 0.2, 0.8), Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0), ), Material::new( Vec3::new(0.8, 0.8, 0.8), ...
function_block-function_prefixed
[ { "content": "pub trait Camera {\n\n fn sample_ray(&self, uv: Vec2, sampler: &mut Sampler) -> Ray;\n\n}\n\n\n\npub struct PinholeCamera {\n\n position: Vec3, // camera position\n\n forward: Vec3, // camera forward direction\n\n right: Vec3, // camera right direction\n\n up: Vec3, // cam...
Rust
src/config.rs
foeb/bootimage
e159e4095ca03826a5b366b1cf528804a06bf6bc
use failure::{Error, ResultExt}; use std::path::PathBuf; use toml::Value; #[derive(Debug, Clone)] pub struct Config { pub manifest_path: PathBuf, pub default_target: Option<String>, pub output: Option<PathBuf>, pub bootloader: BootloaderConfig, pub minimum_image_size: Option<u64>, pub run_comma...
use failure::{Error, ResultExt}; use std::path::PathBuf; use toml::Value; #[derive(Debug, Clone)] pub struct Config { pub manifest_path: PathBuf, pub default_target: Option<String>, pub output: Option<PathBuf>, pub bootloader: BootloaderConfig, pub minimum_image_size: Option<u64>, pub run_comma...
; let bootloader_features = match cargo_toml .get("dependencies") .and_then(|table| table.get("bootloader")) .and_then(|table| table.get("features")) { None => None, Some(Value::Array(array)) => { let mut features = Vec::new(); for feature_string...
match bootloader_dependency.and_then(|table| table.get("default-features")) { None => None, Some(Value::Boolean(default_features)) => Some(*default_features), Some(_) => { return Err(format_err!( "Bootloader 'default-features' field should be a boo...
if_condition
[ { "content": "fn build_bootloader(metadata: &CargoMetadata, config: &Config) -> Result<Box<[u8]>, Error> {\n\n use std::io::Read;\n\n\n\n let bootloader_metadata = metadata.packages.iter().find(|p| {\n\n if let Some(name) = config.bootloader.name.as_ref() {\n\n p.name == name.as_str()\n\...
Rust
der/src/asn1/bit_string.rs
xiaoyuxlu/utils
06276215ebdf9e5258c6daadcace9f9c64f57065
use crate::{ Any, ByteSlice, Encodable, Encoder, Error, ErrorKind, Header, Length, Result, Tag, Tagged, }; use core::convert::TryFrom; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct BitString<'a> { inner: ByteSlice<'a>, } impl<'a> BitString<'a> { pub fn new(slice: &'a [u8]) -> Result<...
use crate::{ Any, ByteSlice, Encodable, Encoder, Error, ErrorKind, Header, Length, Result, Tag, Tagged, }; use core::convert::TryFrom; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct BitString<'a> { inner: ByteSlice<'a>, } impl<'a> BitString<'a> { pub fn new(slice: &'a [u8]) -> Result<...
} impl<'a> From<BitString<'a>> for Any<'a> { fn from(bit_string: BitString<'a>) -> Any<'a> { Any { tag: Tag::BitString, value: bit_string.inner, } } } impl<'a> From<BitString<'a>> for &'a [u8] { fn from(bit_string: BitString<'a>) -> &'a [u8] { bit_string.as...
fn try_from(any: Any<'a>) -> Result<BitString<'a>> { any.tag().assert_eq(Tag::BitString)?; if let Some(bs) = any.as_bytes().get(1..) { if any.as_bytes()[0] == 0 { return ByteSlice::new(bs) .map(|inner| Self { inner }) ...
function_block-full_function
[ { "content": "/// Obtain the length of an ASN.1 `SEQUENCE` of [`Encodable`] values when\n\n/// serialized as ASN.1 DER, including the `SEQUENCE` tag and length prefix.\n\npub fn encoded_len(encodables: &[&dyn Encodable]) -> Result<Length> {\n\n let inner_len = encoded_len_inner(encodables)?;\n\n Header::n...
Rust
src/format.rs
samwho/hmm
8894296e98ab43e6937adbfe88af413c7edee881
use super::{entry::Entry, Result}; use chrono::prelude::*; use colored::*; use handlebars::{ Context, Handlebars, Helper, HelperDef, HelperResult, JsonRender, Output, RenderContext, }; use std::collections::BTreeMap; pub struct Format<'a> { renderer: Handlebars<'a>, data: BTreeMap<&'static str, String>, } ...
use super::{entry::Entry, Result}; use chrono::prelude::*; use colored::*; use handlebars::{ Context, Handlebars, Helper, HelperDef, HelperResult, JsonRender, Output, RenderContext, }; use std::collections::BTreeMap; pub struct Format<'a> { renderer: Handlebars<'a>, data: BTreeMap<&'static str, String>, } ...
} struct MarkdownHelper {} impl HelperDef for MarkdownHelper { fn call<'reg: 'rc, 'rc>( &self, h: &Helper, _: &Handlebars, _: &Context, _: &mut RenderContext, out: &mut dyn Output, ) -> HelperResult { let s = h.param(0).unwrap().value().render(); ...
fn call<'reg: 'rc, 'rc>( &self, h: &Helper, _: &Handlebars, _: &Context, _: &mut RenderContext, out: &mut dyn Output, ) -> HelperResult { let color = h.param(0).unwrap().value().render(); let s = h.param(1).unwrap().value().render(); Ok(out.wri...
function_block-full_function
[ { "content": "pub fn from_str(s: &str) -> Error {\n\n s.to_owned().into()\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum Error {\n\n Io(io::Error),\n\n Csv(csv::Error),\n\n QuickCsv(quick_csv::error::Error),\n\n ChronoParse(chrono::format::ParseError),\n\n SerdeJson(serde_json::error::Error),\n\n ...
Rust
src/jdk.rs
jht5945/buildj
26de9ddcc6dcd5c956da2f592d55bb504fe1a8f5
use std::{collections::HashMap, env, fs, str, path::Path, process::Command}; use rust_util::util_os; use rust_util::util_env; use crate::{local_util, tool, misc::VERBOSE}; use plist::Value; const PATH: &str = "PATH"; const JAVA_HOME: &str = "JAVA_HOME"; const OPENJDK_MACOS: &str = "openjdk-osx"; const JDK_LINUX: &str...
use std::{collections::HashMap, env, fs, str, path::Path, process::Command}; use rust_util::util_os; use rust_util::util_env; use crate::{local_util, tool, misc::VERBOSE}; use plist::Value; const PATH: &str = "PATH"; const JAVA_HOME: &str = "JAVA_HOME"; const OPENJDK_MACOS: &str = "openjdk-osx"; const JDK_LINUX: &str...
{ let mut new_env: HashMap<String, String> = HashMap::new(); for (key, value) in env::vars() { new_env.insert(key, value); } new_env } pub fn get_env_with_java_home(java_home: &str) -> HashMap<String, String> { let mut new_env: HashMap<String, String> = HashMap::new(); for (key, value)...
ch Value::from_reader_xml(&*java_home_x.stdout) { Err(e) => { debugging!("Parse java_home outputs failed: {}", e); return None; } Ok(val) => val, }; let java_home_plist_value_array = match java_home_plist_value.as_array() { None => { debugging!...
random
[ { "content": "pub fn get_and_extract_tool_package(base_dir: &str, dir_with_name: bool, name: &str, version: &str, extract_match: bool) -> XResult<bool> {\n\n let tool_package_detail = get_tool_package_detail(name, version)?;\n\n let build_json_object = json::parse(&tool_package_detail)?;\n\n if *VERBOS...
Rust
tests/basic_choice.rs
pasa-v2x/asn1rs
e8ab92d96c57e17f7cd82cdf825c0063c95a8430
use asn1rs::prelude::*; use asn1rs::syn::io::UperReader as NewUperReader; use asn1rs::syn::io::UperWriter as NewUperWriter; asn_to_rust!( r"BasicChoice DEFINITIONS AUTOMATIC TAGS ::= BEGIN Basic ::= CHOICE { abc UTF8String, def UTF8String, ghi INTEGER } Extensible ...
use asn1rs::prelude::*; use asn1rs::syn::io::UperReader as NewUperReader; use asn1rs::syn::io::UperWriter as NewUperWriter; asn_to_rust!( r"BasicChoice DEFINITIONS AUTOMATIC TAGS ::= BEGIN Basic ::= CHOICE { abc UTF8String, def UTF8String, ghi INTEGER } Extensible ...
let _abc = Basic::Abc(String::default()); let _def = Basic::Def(String::default()); let _ghi = Basic::Ghi(123_u64); match Basic::Abc(String::default()) { Basic::Abc(_) | Basic::Def(_) | Basic::Ghi(_) => {} } }
function_block-function_prefix_line
[ { "content": "fn serialize_uper(to_uper: impl Writable) -> (usize, Vec<u8>) {\n\n let mut writer = NewUperWriter::default();\n\n writer.write(&to_uper).unwrap();\n\n let bits = writer.bit_len();\n\n (bits, writer.into_bytes_vec())\n\n}\n\n\n", "file_path": "tests/basic_enumerated.rs", "rank"...
Rust
src/lib.rs
lucviala/rusty-vjoy
0767102ac650b357f8677ce4556732711468cbc1
mod ffi; pub type VJDStat = ffi::VjdStat; pub type JoystickPosition = ffi::_JOYSTICK_POSITION_V2; #[repr(u32)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum HidUsage { X = 0x30, Y = 0x31, Z = 0x32, RX = 0x33, RY = 0x34, RZ = 0x35, SL0 = 0x36, SL1 = 0x37, WHL = 0x38,...
mod ffi; pub type VJDStat = ffi::VjdStat; pub type JoystickPosition = ffi::_JOYSTICK_POSITION_V2; #[repr(u32)] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum HidUsage { X = 0x30, Y = 0x31, Z = 0x32, RX = 0x33, RY = 0x34, RZ = 0x35, SL0 = 0x36, SL1 = 0x37, WHL = 0x38,...
} } } pub fn get_number_existing_vjd() -> i32 { let mut number = 0; unsafe { if ffi::GetNumberExistingVJD(&mut number) != 0 { number } else { 0 } } } pub fn get_vjd_button_number(id: u32) -> i32 { unsafe { ffi::GetVJDButtonNumber(id) } } pub f...
et_vjoy_max_devices() -> i32 { let mut number = 0; unsafe { if ffi::GetvJoyMaxDevices(&mut number) != 0 { number } else { 0
function_block-random_span
[ { "content": "fn main() {\n\n //https://doc.rust-lang.org/rustc/command-line-arguments.html\n\n println!(r\"cargo:rustc-link-search=C:\\Program Files\\vJoy\\x64\");\n\n println!(\"cargo:rustc-link-lib=vJoyInterface\");\n\n\n\n //https://rust-lang.github.io/rust-bindgen\n\n let bindings = bindgen:...
Rust
src/parse/bam.rs
devsebb/ImmunoGenotyper
47be20f747e0e7541209be648e01aecf26433565
use debruijn::dna_string::DnaString; use rust_htslib::{bam, bam::record::Aux, bam::Read, bam::Reader}; pub struct UMIReader { reader: bam::Reader, pub current_umi_group: Vec<DnaString>, pub current_umi: String, pub current_cell_barcode: String, pub next_umi_group: Vec<DnaString>, next_umi: Stri...
use debruijn::dna_string::DnaString; use rust_htslib::{bam, bam::record::Aux, bam::Read, bam::Reader}; pub struct UMIReader { reader: bam::Reader, pub current_umi_group: Vec<DnaString>, pub current_umi: String, pub current_cell_barcode: String, pub next_umi_group: Vec<DnaString>, next_umi: Stri...
fn strip_nonbio_regions(seq: &[u8]) -> DnaString { let seq = String::from_utf8(seq.to_owned()).unwrap(); let mut tso_idx = seq.find("TTTCTTATATGGG"); if tso_idx.is_none() { tso_idx = seq.find("AAAGAATATACCC"); }; ...
rent_cell_barcode = current_cell_barcode.clone(); } else { self.next_umi_group .push(seq); self.next_umi = read_umi.clone(); return Some(true); } } None }
function_block-function_prefixed
[ { "content": "// Takes a reader and returns a csv reader that wraps it, configures to use tab delimiters\n\npub fn get_tsv_reader<R: Read>(reader: R) -> Reader<R> {\n\n csv::ReaderBuilder::new()\n\n .delimiter(b'\\t')\n\n .from_reader(reader)\n\n}\n\n\n\n/* Takes a reference to the ReferenceMet...
Rust
loadstone_config/src/codegen/memory_map.rs
arron-speake-bluefruit/loadstone
c65cb32809dc069b17830dd4a39d95c913994200
use anyhow::Result; use quote::{format_ident, quote}; use std::{fs::OpenOptions, io::Write, path::Path}; use crate::{ memory::{ExternalMemoryMap, InternalMemoryMap, MemoryConfiguration}, port::{Port, Subfamily}, }; use super::prettify_file; pub fn generate<P: AsRef<Path>>( autogenerated_folder_path: P, ...
use anyhow::Result; use quote::{format_ident, quote}; use std::{fs::OpenOptions, io::Write, path::Path}; use crate::{ memory::{ExternalMemoryMap, InternalMemoryMap, MemoryConfiguration}, port::{Port, Subfamily}, }; use super::prettify_file; pub fn generate<P: AsRef<Path>>( autogenerated_folder_path: P, ...
fn generate_external_banks( base_index: usize, map: &ExternalMemoryMap, golden_index: Option<usize>, ) -> Result<String> { let number_of_external_banks = map.banks.len(); let index: Vec<u8> = map.banks.iter().enumerate().map(|(i, _)| (i + base_index) as u8).collect(); let bootable = ve...
fn generate_imports(memory_configuration: &MemoryConfiguration, port: &Port) -> Result<String> { let external_address: Vec<_> = match &memory_configuration.external_flash { Some(external_flash) if external_flash.name.to_lowercase().contains("n25q128a") => { ["blue_hal", "drivers", "micron", "n25...
function_block-full_function
[ { "content": "pub fn read_key(mut file: File) -> Result<SigningKey, Error> {\n\n let mut string = String::new();\n\n file.read_to_string(&mut string).map_err(|_| Error::KeyParseFailed)?;\n\n SigningKey::from_str(string.as_str()).map_err(|_| Error::KeyParseFailed)\n\n}\n\n\n", "file_path": "tools/si...
Rust
src/influxdb_ioxd/rpc/management.rs
mitch292/influxdb_iox
7e8f3aaafbd497c0c6e8f993b4ce0330e6d43ccb
use std::convert::TryInto; use std::fmt::Debug; use std::sync::Arc; use tonic::{Request, Response, Status}; use tracing::error; use data_types::database_rules::DatabaseRules; use data_types::DatabaseName; use generated_types::google::{ AlreadyExists, FieldViolation, FieldViolationExt, InternalError, NotFound, ...
use std::convert::TryInto; use std::fmt::Debug; use std::sync::Arc; use tonic::{Request, Response, Status}; use tracing::error; use data_types::database_rules::DatabaseRules; use data_types::DatabaseName; use generated_types::google::{ AlreadyExists, FieldViolation, FieldViolationExt, InternalError, NotFound, ...
async fn get_database( &self, request: Request<GetDatabaseRequest>, ) -> Result<Response<GetDatabaseResponse>, Status> { let name = DatabaseName::new(request.into_inner().name).field("name")?; match self.server.db_rules(&name).await { Some(rules) => Ok(Response::ne...
f, _: Request<ListDatabasesRequest>, ) -> Result<Response<ListDatabasesResponse>, Status> { let names = self.server.db_names_sorted().await; Ok(Response::new(ListDatabasesResponse { names })) }
function_block-function_prefixed
[ { "content": "type DatabaseError = Box<dyn std::error::Error + Send + Sync + 'static>;\n\n\n\n/// A server ID of 0 is reserved and indicates no ID has been configured.\n\nconst SERVER_ID_NOT_SET: u32 = 0;\n\n\n\n#[derive(Debug, Snafu)]\n\npub enum Error {\n\n #[snafu(display(\"Server error: {}\", source))]\n...
Rust
src/unpack.rs
clouds56/crnlib
13dbc1e0e4184ad686e3987708c4564901ed92ef
use std::io::prelude::*; use anyhow::*; use serde::{Serialize, Deserialize}; use crate::{Tables, Huffman, codec::Codec}; pub trait Block: Serialize { const BLOCK_SIZE: usize; fn write_to<W: Write>(&self, mut w: W) -> std::io::Result<()> { use bincode::Options; let bin = bincode::config::DefaultOptions::new...
use std::io::prelude::*; use anyhow::*; use serde::{Serialize, Deserialize}; use crate::{Tables, Huffman, codec::Codec}; pub trait Block: Serialize { const BLOCK_SIZE: usize; fn write_to<W: Write>(&self, mut w: W) -> std::io::Result<()> { use bincode::Options; let bin = bincode::config::DefaultOptions::new...
} #[derive(Debug, Default, Serialize, Deserialize)] pub struct Dxn { pub alpha0_endpoint: (u8, u8), pub alpha0_selector: [u8; 6], pub alpha1_endpoint: (u8, u8), pub alpha1_selector: [u8; 6], } impl Block for Dxn { const BLOCK_SIZE: usize = 16; } impl Unpack for Dxn { fn unpack(tables: &Tables, codec: &mu...
fn unpack(tables: &Tables, codec: &mut Codec, width: u16, height: u16, face: u8) -> Result<Vec<u8>, Error> { let block_x = (width + 3) / 4; let block_y = (height + 3) / 4; let chunk_x = (block_x + 1) as usize / Self::TRUNK_SIZE; let chunk_y = (block_y + 1) as usize / Self::TRUNK_SIZE; let mut tile_...
function_block-full_function
[ { "content": "#[test]\n\nfn test_huffman() {\n\n let input = [0b0100_0000u8];\n\n let mut codec = Codec::new(&input);\n\n let huffman = Huffman::new(BTreeMap::<bool,_>::new()).expect(\"zero huffman\");\n\n assert!(huffman.next(&mut codec).is_err());\n\n\n\n let mut codec = Codec::new(&input);\n\n let mut ...
Rust
src/rngs/entropy.rs
robsmith11/rand
1e9554d79b915860894bfba3aaff8c3f1c8b2159
use rand_core::{RngCore, CryptoRng, Error, ErrorKind, impls}; #[allow(unused)] use rngs; #[derive(Debug)] pub struct EntropyRng { source: Source, } #[derive(Debug)] enum Source { Os(Os), Custom(Custom), Jitter(Jitter), None, } impl EntropyRng { pub fn new() -> Self ...
use rand_core::{RngCore, CryptoRng, Error, ErrorKind, impls}; #[allow(unused)] use rngs; #[derive(Debug)] pub struct EntropyRng { source: Source, } #[derive(Debug)] enum Source { Os(Os), Custom(Custom), Jitter(Jitter), None, } impl EntropyRng { pub fn new() -> Self ...
Ok(()) => return Ok(()), Err(err) => { warn!("EntropyRng: JitterRng failed: {}", err); reported_error = Some(err); }, } } else if Jitter::is_supported() { match Jitter::new_and_fill(dest) { O...
self, dest: &mut [u8]) { self.try_fill_bytes(dest).unwrap_or_else(|err| panic!("all entropy sources failed; first error: {}", err)) } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { let mut reported_error = None; if let Source::Os(ref mut os_rng) = ...
random
[ { "content": "/// Implement `next_u64` via `next_u32`, little-endian order.\n\npub fn next_u64_via_u32<R: RngCore + ?Sized>(rng: &mut R) -> u64 {\n\n // Use LE; we explicitly generate one value before the next.\n\n let x = u64::from(rng.next_u32());\n\n let y = u64::from(rng.next_u32());\n\n (y << 3...
Rust
src/validator/lockbox.rs
Cognoscan/fog_pack
7b3af246faa851bfc2aa09cc186ff2332124e791
use super::*; use crate::element::*; use crate::error::{Error, Result}; use serde::{Deserialize, Serialize}; #[inline] fn is_false(v: &bool) -> bool { !v } #[inline] fn u32_is_zero(v: &u32) -> bool { *v == 0 } #[inline] fn u32_is_max(v: &u32) -> bool { *v == u32::MAX } macro_rules! lockbox_validator { ...
use super::*; use crate::element::*; use crate::error::{Error, Result}; use serde::{Deserialize, Serialize}; #[inline] fn is_false(v: &bool) -> bool { !v } #[inline] fn u32_is_zero(v: &u32) -> bool { *v == 0 } #[inline] fn u32_is_max(v: &u32) -> bool { *v == u32::MAX } macro_rules! lockbox_validator { ...
r().all(|other| match other { Validator::$e(other) => self.query_check_self(other), _ => false, }), Validator::Any => true, _ => false, } } } }; ($t: ty, $e: ident, $v...
n) && u32_is_zero(&other.min_len)) } pub(crate) fn query_check(&self, other: &Validator) -> bool { match other { Validator::$e(other) => self.query_check_self(other), Validator::Multi(list) => list.ite
random
[ { "content": "/// Read raw lockbox data out from a buffer\n\npub fn read_raw_lockbox(buf: &mut &[u8], len: usize) -> crate::Result<Lockbox> {\n\n Ok(Lockbox::decode(len, buf)?)\n\n}\n\n\n\n\n", "file_path": "old/decode.rs", "rank": 2, "score": 338446.3248757994 }, { "content": "/// Genera...
Rust
ring/src/aead/poly1305.rs
Soptq/phala-blockchain
f2fbd1e62b1b8c2567bfed993ae85a56f227a880
use super::{Tag, TAG_LEN}; use crate::{c, cpu}; pub(super) struct Key { key_and_nonce: [u8; KEY_LEN], cpu_features: cpu::Features, } pub(super) const BLOCK_LEN: usize = 16; pub(super) const KEY_LEN: usize = 2 * BLOCK_LEN; impl Key { #[inline] pub(super) fn new(key_and_nonce: [u8; KEY_LEN], cpu_feat...
use super::{Tag, TAG_LEN}; use crate::{c, cpu}; pub(super) struct Key { key_and_nonce: [u8; KEY_LEN], cpu_features: cpu::Features, } pub(super) const BLOCK_LEN: usize = 16; pub(super) const KEY_LEN: usize = 2 * BLOCK_LEN; impl Key { #[inline] pub(super) fn new(key_and_nonce: [u8; KEY_LEN], cpu_feat...
pub(super) fn finish(mut self) -> Tag { let mut tag = Tag([0u8; TAG_LEN]); dispatch!( self.cpu_features => (GFp_poly1305_finish | GFp_poly1305_finish_neon) (statep: &mut poly1305_state, mac: &mut [u8; TAG_LEN]) (&mut self.state, &mut tag.0)); ...
pub fn update(&mut self, input: &[u8]) { dispatch!( self.cpu_features => (GFp_poly1305_update | GFp_poly1305_update_neon) (statep: &mut poly1305_state, input: *const u8, in_len: c::size_t) (&mut self.state, input.as_ptr(), input.len())); }
function_block-full_function
[ { "content": "pub fn shift_partial<F>((in_prefix_len, in_out): (usize, &mut [u8]), transform: F)\n\nwhere\n\n F: FnOnce(&[u8]) -> Block,\n\n{\n\n let (block, in_out_len) = {\n\n let input = &in_out[in_prefix_len..];\n\n let in_out_len = input.len();\n\n if in_out_len == 0 {\n\n ...
Rust
wire_protocol/src/connection.rs
vangork/pravega-client-rust
b57b2ea6eee3aa49d354e19b5fc457d4ccf72e9f
use crate::error::*; use async_trait::async_trait; use pravega_client_shared::PravegaNodeUri; use snafu::ResultExt; use std::fmt; use std::fmt::{Debug, Formatter}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{ReadHalf, WriteHalf}; use tokio::net::TcpStream; use tokio_rustls::client::TlsStream; use uu...
use crate::error::*; use async_trait::async_trait; use pravega_client_shared::PravegaNodeUri; use snafu::ResultExt; use std::fmt; use std::fmt::{Debug, Formatter}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{ReadHalf, WriteHalf}; use tokio::net::TcpStream; use tokio_rustls::client::TlsStream; use uu...
(read, write) } fn get_endpoint(&self) -> PravegaNodeUri { self.endpoint.clone() } fn get_uuid(&self) -> Uuid { self.uuid } fn is_valid(&self) -> bool { self.can_recycle && self.stream.as_ref().is_some() && self.stream.as_ref().expect("...
let write = Box::new(ConnectionWriteHalfTls { uuid: self.uuid, endpoint: self.endpoint.clone(), write_half: Some(write_half), }) as Box<dyn ConnectionWriteHalf>;
assignment_statement
[ { "content": "#[async_trait]\n\npub trait ClientConnection: Send + Sync {\n\n async fn read(&mut self) -> Result<Replies, ClientConnectionError>;\n\n async fn write(&mut self, request: &Requests) -> Result<(), ClientConnectionError>;\n\n fn split(&mut self) -> (ClientConnectionReadHalf, ClientConnectio...
Rust
nrf-softdevice/src/flash.rs
chris-ricketts/nrf-softdevice
6ee09a134d9366029462963650dcd7e3921d6c1d
use core::future::Future; use core::marker::PhantomData; use core::sync::atomic::{AtomicBool, Ordering}; use embedded_storage::nor_flash::{ErrorType, NorFlashError, NorFlashErrorKind}; use embedded_storage_async::nor_flash::{AsyncNorFlash, AsyncReadNorFlash}; use crate::raw; use crate::util::{DropBomb, Signal}; use cr...
use core::future::Future; use core::marker::PhantomData; use core::sync::atomic::{AtomicBool, Ordering}; use embedded_storage::nor_flash::{ErrorType, NorFlashError, NorFlashErrorKind}; use embedded_storage_async::nor_flash::{AsyncNorFlash, AsyncReadNorFlash}; use crate::raw; use crate::util::{DropBomb, Signal}; use cr...
w_parts(address as *const u8, data.len()) }); Ok(()) } } fn capacity(&self) -> usize { 256 * 4096 } } impl AsyncNorFlash for Flash { const WRITE_SIZE: usize = 4; const ERASE_SIZE: usize = 4096; type WriteFuture<'a> = impl Future<Output = Result<(), Fla...
ta: &'a mut [u8]) -> Self::ReadFuture<'a> { async move { data.copy_from_slice(unsafe { core::slice::from_ra
function_block-random_span
[ { "content": "pub fn get_value(_sd: &Softdevice, handle: u16, buf: &mut [u8]) -> Result<usize, GetValueError> {\n\n let mut value = raw::ble_gatts_value_t {\n\n p_value: buf.as_mut_ptr(),\n\n len: buf.len() as _,\n\n offset: 0,\n\n };\n\n let ret = unsafe {\n\n raw::sd_ble_g...
Rust
tests/elements/test_from_telemetry_stage.rs
dmrolfs/proctor
9b2fac5e80e4a8874906a85302af7b34b4433f46
use std::path::PathBuf; use anyhow::Result; use cast_trait_object::DynCastExt; use chrono::{DateTime, Utc}; use claim::*; use once_cell::sync::Lazy; use pretty_assertions::assert_eq; use proctor::elements; use proctor::graph::{stage, Connect, Graph, SinkShape}; use proctor::phases::collection::{make_telemetry_cvs_sour...
use std::path::PathBuf; use anyhow::Result; use cast_trait_object::DynCastExt; use chrono::{DateTime, Utc}; use claim::*; use once_cell::sync::Lazy; use pretty_assertions::assert_eq; use proctor::elements; use proctor::graph::{stage, Connect, Graph, SinkShape}; use proctor::phases::collection::{make_telemetry_cvs_sour...
assert_tokens( &data, &vec![ Token::Struct { name: "Data", len: 3 }, Token::Str("task.last_failure"), Token::Some, Token::Str(&NOW_REP), Token::Str("cluster.is_deploying"), Token::Bool(true), Token::Str("cluster.la...
let data = Data { last_failure: Some(NOW.clone()), is_deploying: true, last_deployment: NOW.clone(), };
assignment_statement
[ { "content": "#[tracing::instrument(level = \"debug\", skip(serializer))]\n\npub fn serialize_format<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let datetime_rep = format!(\"{}\", date.format(FORMAT));\n\n serializer.serialize_str(datetime_rep...
Rust
src/union_find/client.rs
ccozad/cozad-union-find
3ec2ac39cecf08e6d68977a67f2c7bb02409fc6f
#[cfg(test)] #[path = "client_tests.rs"] mod client_tests; use std::collections::HashMap; #[derive(Hash, Eq, PartialEq, Debug)] struct Node { pub uuid: String, pub parent_index: usize, pub index: usize, pub size: usize } #[derive(Hash, Eq, PartialEq, Debug)] pub struct BulkConnec...
#[cfg(test)] #[path = "client_tests.rs"] mod client_tests; use std::collections::HashMap; #[derive(Hash, Eq, PartialEq, Debug)] struct Node { pub uuid: String, pub parent_index: usize, pub index: usize, pub size: usize } #[derive(Hash, Eq, PartialEq, Debug)] pub struct BulkConnec...
self.set_count -= 1; } } pub fn connect_nodes_bulk(&mut self, connections: Vec<BulkConnection>) { for connection in connections.iter() { let uuid_a_root = self.find_root_index_bulk(connection.a + 1); let uuid_b_root = self.find...
if node_slice[uuid_a_root].size < node_slice[uuid_b_root].size { node_slice[uuid_a_root].parent_index = uuid_b_root; node_slice[uuid_b_root].size += node_slice[uuid_a_root].size; } else { node_slice[uuid_b_root].parent_index = uuid_a_root; node...
if_condition
[ { "content": "#[test]\n\nfn node_index_positive() {\n\n let mut client = ufclient::Client::new();\n\n client.add_node(\"A\");\n\n\n\n assert_eq!(1, client.node_index(\"A\"));\n\n}\n\n\n", "file_path": "src/union_find/client_tests.rs", "rank": 1, "score": 76115.25809501106 }, { "cont...
Rust
parser/src/typing/phase1.rs
thejohncrafter/projets-2020
2c4525f5d241a67663a1f74f2326abd2890c44fa
use std::collections::HashSet; use crate::ast::{Structure, Function, Exp, StaticType}; use super::data::*; use super::visit::IntoVisitor; use super::assign::collect_all_assign; use super::func_signatures::{build_signature, is_callable_with_exactly, format_signature}; fn is_reserved_name(n: &String) -> bool { match...
use std::collections::HashSet; use crate::ast::{Structure, Function, Exp, StaticType}; use super::data::*; use super::visit::IntoVisitor; use super::assign::collect_all_assign; use super::func_signatures::{build_signature, is_callable_with_exactly, format_signature}; fn is_reserved_name(n: &String) -> bool { match...
; } } for sig in self.function_sigs.entry(f.name.clone()).or_default() { if is_callable_with_exactly(f.params.iter().map(|arg| arg.ty.clone()).collect(), &sig) { return Err( (f.span, format!( ...
Err( (param.span, format!("This type is malformed, either it is not a primitive or it's not a declared before structure").to_string()).into() )
call_expression
[ { "content": "pub fn is_builtin_function(name: &String) -> bool {\n\n match name.as_str() {\n\n \"println\" | \"div\" | \"print\" => true,\n\n _ => false\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct TypedDecls<'a> {\n\n pub functions: HashMap<String, Vec<Function<'a>>>,\n\n pub str...
Rust
clashctl-tui/src/event.rs
EurusEurus/clashctl
6fabdeabc6dc4920cb9fb3da701242ac103fbf04
use std::fmt::Display; use crossterm::event::{KeyCode as KC, KeyEvent as KE, KeyModifiers as KM}; use log::Level; use tui::{ style::{Color, Style}, text::{Span, Spans}, }; use crate::{ clashctl::model::{ConnectionsWithSpeed, Log, Proxies, Rules, Traffic, Version}, components::MovableListItem, util...
use std::fmt::Display; use crossterm::event::{KeyCode as KC, KeyEvent as KE, KeyModifiers as KM}; use log::Level; use tui::{ style::{Color, Style}, text::{Span, Spans}, }; use crate::{ clashctl::model::{ConnectionsWithSpeed, Log, Proxies, Rules, Traffic, Version}, components::MovableListItem, util...
, ToggleDebug, ToggleHold, List(ListEvent), TestLatency, NextSort, PrevSort, Other(KE), } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ListEvent { pub fast: bool, pub code: KC, } #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub enum UpdateEvent { Config(clashct...
event)), ]), Event::Diagnostic(event) => match event { DiagnosticEvent::Log(level, payload) => Spans(vec![ Span::styled( format!("✇ {:<6}", level), Style::default().fg(level.as_color()), ), ...
random
[ { "content": "pub fn help_footer(content: &str, normal: Style, highlight: Style) -> Spans {\n\n if content.is_empty() {\n\n Spans(vec![])\n\n } else if content.len() == 1 {\n\n Spans(vec![Span::raw(content)])\n\n } else {\n\n let (index, _) = content.char_indices().nth(1).unwrap();...
Rust
src/widget_themes/classic.rs
fltk-rs/fltk-theme
8e792be048cb6c868c66f526bffd7782f52f54ee
use super::*; use fltk::{app, enums::Color, misc::Tooltip}; fn classic_button_up_frame(x: i32, y: i32, w: i32, h: i32, c: Color) { draw_frame2("AAWWMMRR", x, y, w, h); } fn classic_button_up_box(x: i32, y: i32, w: i32, h: i32, c: Color) { set_draw_color(activated_color(c)); draw_rectf(x + 2, y + 2, w - 4,...
use super::*; use fltk::{app, enums::Color, misc::Tooltip}; fn classic_button_up_frame(x: i32, y: i32, w: i32, h: i32, c: Color) { draw_frame2("AAWWMMRR", x, y, w, h); } fn classic_button_up_box(x: i32, y: i32, w: i32, h: i32, c: Color) { set_draw_color(activated_color(c)); draw_rectf(x + 2, y + 2, w - 4,...
pub(crate) fn use_classic_theme() { use_classic_scheme(); use_classic_colors(); use_native_settings(); }
fn use_classic_colors() { app::background(0xD4, 0xD0, 0xC8); app::background2(0xFF, 0xFF, 0xFF); app::foreground(0x00, 0x00, 0x00); app::set_color(Color::Inactive, 0x5F, 0x5F, 0x5F); app::set_color(Color::Selection, 0x0A, 0x24, 0x6A); app::set_color(Color::Free, 0xD4, 0xD0, 0xC8); Tooltip::s...
function_block-full_function
[ { "content": "fn up_frame(x: i32, y: i32, w: i32, h: i32, c: Color) {\n\n rect(x, y, w, h, Color::color_average(Color::White, c, 0.2));\n\n}\n\n\n", "file_path": "src/widget_schemes/clean.rs", "rank": 6, "score": 231206.04478592548 }, { "content": "fn up_box(x: i32, y: i32, w: i32, h: i32...
Rust
src/tools/builder.rs
feenkcom/gtoolkit-maestro-rs
1c1651b6ddaf8648bce6037fa24e34ca08be7a93
use crate::create::FileToCreate; use crate::download::{FileToDownload, FilesToDownload}; use crate::{ Application, Checker, Downloader, ExecutableSmalltalk, FileToMove, ImageSeed, InstallerError, Result, Smalltalk, SmalltalkCommand, SmalltalkExpressionBuilder, SmalltalkScriptToExecute, SmalltalkScriptsToExe...
use crate::create::FileToCreate; use crate::download::{FileToDownload, FilesToDownload}; use crate::{ Application, Checker, Downloader, ExecutableSmalltalk, FileToMove, ImageSeed, InstallerError, Result, Smalltalk, SmalltalkCommand, SmalltalkExpressionBuilder, SmalltalkScriptToExecute, SmalltalkScriptsToExe...
}
pub async fn build( &self, application: &mut Application, build_options: &BuildOptions, ) -> Result<()> { let started = Instant::now(); let image_seed = build_options.image_seed(); application.set_image_seed(image_seed.clone())?; Checker::new() ....
function_block-full_function
[ { "content": "pub trait ExecutableSmalltalk {\n\n fn create_command(&self, evaluator: &SmalltalkEvaluator) -> Result<Command>;\n\n fn execute(&self, evaluator: &SmalltalkEvaluator) -> Result<()> {\n\n let mut command = self.create_command(evaluator)?;\n\n if evaluator.is_verbose() {\n\n ...
Rust
src/lib.rs
gcarq/seek_bufread
1ff6dff6e449cff969e94bb77aacb89de20cc4ac
use std::fmt; use std::io::{self, BufRead, Read, Seek, SeekFrom}; const DEFAULT_BUF_SIZE: usize = 8 * 1024; pub struct BufReader<R> { inner: R, buf: Box<[u8]>, buf_pos: usize, cap: usize, absolute_pos: u64, } impl<R: Read + Seek> BufReader<R> { ...
use std::fmt; use std::io::{self, BufRead, Read, Seek, SeekFrom}; const DEFAULT_BUF_SIZE: usize = 8 * 1024; pub struct BufReader<R> { inner: R, buf: Box<[u8]>, buf_pos: usize, cap: usize, absolute_pos: u64, } impl<R: Read + Seek> BufReader<R> { ...
8]; reader.read(&mut buf).unwrap(); assert_eq!(buf, [0, 0, 0, 0, 0, 0, 0, 0]); } #[test] fn seek_end_std() { let inner = Cursor::new([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); let mut reader = io::BufReader::with_capacity(2, inner); reader.seek(Se...
From::End(-6)).unwrap(); let mut buf = [0; 8]; reader.read(&mut buf).unwrap(); assert_eq!(buf, [11, 12, 13, 14, 15, 16, 0, 0]); reader.seek(SeekFrom::End(0)).unwrap(); let mut buf = [0;
function_block-random_span
[ { "content": "#[bench]\n\nfn read_10mb_default_from_cursor(b: &mut Bencher) {\n\n b.iter(|| {\n\n let inner = Cursor::new(vec![1; 10000000]);\n\n let mut reader = BufReader::new(inner);\n\n\n\n let mut buf: Vec<u8> = Vec::with_capacity(10000000);\n\n reader.read_to_end(&mut buf).u...
Rust
src/types/rowkey.rs
TimeExceed/alicloud-tablestore-rust-sdk
d8a7b24c10803e4641d6f0d30e0b9d4ddda100c4
use bytes::Bytes; use crate::{Error, ErrorCode}; use std::convert::TryFrom; use super::*; #[cfg(test)] use quickcheck::{Arbitrary, Gen, empty_shrinker}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct RowKey(pub Vec<RowKeyColumn>); #[derive(Debug, Clone, Eq, PartialEq)] pub struct ExtendedRowKey(pub Vec<ExtendedRo...
use bytes::Bytes; use crate::{Error, ErrorCode}; use std::convert::TryFrom; use super::*; #[cfg(test)
y> for ExtendedRowKey { fn from(rk: RowKey) -> Self { let ext_rk = rk.into_iter() .map(|x| { ExtendedRowKeyColumn::from(x) }) .collect(); ExtendedRowKey::new(ext_rk) } } impl TryFrom<ExtendedRowKey> for RowKey { type Error = Error; fn...
] use quickcheck::{Arbitrary, Gen, empty_shrinker}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct RowKey(pub Vec<RowKeyColumn>); #[derive(Debug, Clone, Eq, PartialEq)] pub struct ExtendedRowKey(pub Vec<ExtendedRowKeyColumn>); #[derive(Debug, Clone, Eq, PartialEq)] pub struct RowKeyColumn { pub name: Name, ...
random
[ { "content": "fn peek_tag(inp: &mut dyn Buf) -> Result<super::Tag, Error> {\n\n if !inp.has_remaining() {\n\n return issue_error();\n\n }\n\n let xs = inp.bytes();\n\n assert!(!xs.is_empty());\n\n Ok(super::Tag::try_from(xs[0])?)\n\n}\n\n\n", "file_path": "src/plainbuffer/serde.rs", ...
Rust
src/timer.rs
guerinoni/yobemag
ace316106477092b354ccf77b278899685cc5ca1
use std::cell::RefCell; use std::rc::Rc; use crate::{ clock::Clock, interrupt::{InterruptFlag, InterruptKind}, memory_device::ReadWrite, }; pub struct Timer { divider: u8, tima: u8, tma: u8, tac: u8, clock...
use std::cell::RefCell; use std::rc::Rc; use crate::{ clock::Clock, interrupt::{InterruptFlag, InterruptKind}, memory_device::ReadWrite, }; pub struct Timer { divider: u8, tima: u8, tma: u8, tac: u8, clock...
} impl ReadWrite for Timer { fn contains(&self, address: usize) -> bool { 0xFF04 == address || 0xFF05 == address || 0xFF06 == address || 0xFF07 == address } fn read_byte(&self, address: usize) -> Result<u8, std::io::Error> { match address { 0xFF04 => Ok(self.divider), ...
for _ in 0..n { self.tima = self.tima.wrapping_add(1); if self.tima == 0x00 { self.tima = self.tma; self.interrupt_flag .borrow_mut() .request(InterruptKind::Timer); } } ...
function_block-function_prefix_line
[ { "content": "/// since gameboy check for non original games when loading cartridge.\n\npub fn valid_checksum(data: &[u8]) -> Result<(), std::io::Error> {\n\n let checksum: Wrapping<u8> = data[0x134..0x14D]\n\n .iter()\n\n .cloned()\n\n .fold(Wrapping(0), |acc, v| acc - Wrapping(v) - Wra...
Rust
src/worker.rs
dginev/rust-cortex-peripherals
c1eb9eb489e45ae80857cc3b00b20fe9bee6c258
use std::borrow::Cow; use std::error::Error; use std::fs::File; use std::io::{Read, Seek, SeekFrom, Write}; use std::ops::Deref; use std::path::Path; use std::thread; use std::time::Duration; use std::ffi::OsString; use tempdir::TempDir; use zmq::{Context, Message, Socket, SNDMORE}; pub trait Worker: Clone + Send {...
use std::borrow::Cow; use std::error::Error; use std::fs::File; use std::io::{Read, Seek, SeekFrom, Write}; use std::ops::Deref; use std::path::Path; use std::thread; use std::time::Duration; use std::ffi::OsString; use tempdir::TempDir; use zmq::{Context, Message, Socket, SNDMORE}; pub trait Worker: Clone + Send {...
fn receive_from_cortex( &self, input_tmpdir: &TempDir, source: &Socket, ) -> (Result<File, Box<dyn Error>>, String, usize, String) { let mut taskid_msg = Message::new(); let mut recv_msg = Message::new(); source.send(&self.get_service(), 0).unwrap(); source.recv(&mut taskid_msg, 0)....
loop { let input_tmpdir = TempDir::new("cortex_task").unwrap(); let (file_result, input_filepath, input_size, taskid) = self.receive_from_cortex(&input_tmpdir, &source); let converted_result = if file_result.is_ok() { self.convert(Path::new(&input_filepath)) } else { ...
function_block-function_prefix_line
[ { "content": "/// Transform the ZIP provided by cortex into a TempDir,\n\n/// for e.g. tools such as Engrafo that aren't ZIP-capable\n\npub fn extract_zip_to_tmpdir(path: &Path, tmpdir_prefix: &str) -> Result<TempDir, Box<dyn Error>> {\n\n let input_tmpdir = TempDir::new(tmpdir_prefix)?;\n\n let unpacked_...
Rust
chain/src/action.rs
monacohq/rust-eos
a54e873baaf21db9268e9537856b04357583d8bf
use alloc::string::{String, ToString}; use alloc::{format, vec}; use alloc::vec::Vec; use core::str::FromStr; use codec::{Encode, Decode}; use crate::{ AccountName, ActionName, Asset, Digest, NumBytes, PermissionLevel, Read, SerializeData, Write }; #[cfg(feature = "std")] use serde::{ Serialize, Deserializ...
use alloc::string::{String, ToString}; use alloc::{format, vec}; use alloc::vec::Vec; use core::str::FromStr; use codec::{Encode, Decode}; use crate::{ AccountName, ActionName, Asset, Digest, NumBytes, PermissionLevel, Read, SerializeData, Write }; #[cfg(feature = "std")] use serde::{ Serialize, Deserializ...
o.token", "transfer", vec![permission_level], action_transfer ) } } impl core::fmt::Display for Action { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "account: {}\n\ name: {}\n\ authorization: {}\n\ ...
T, to: T, quantity: T, memo: T) -> crate::Result<Action> { let permission_level = PermissionLevel::from_str(from.as_ref(), "active")?; let action_transfer = ActionTransfer::from_str(from, to, quantity, memo)?; Action::from_str( "eosi
function_block-random_span
[ { "content": "/// Directly encode a slice as base58\n\npub fn encode_slice(data: &[u8]) -> String {\n\n encode_iter(data.iter().cloned())\n\n}\n\n\n", "file_path": "keys/src/base58.rs", "rank": 0, "score": 273043.4003143676 }, { "content": "/// Obtain a string with the base58check encodin...
Rust
components/epaxos/src/replication/hdlreply.rs
openacid/celeritasdb
061d71e5e6305b6e3782530433ad082680c9fc14
use crate::qpaxos::replicate_reply::Phase; use crate::qpaxos::Direction; use crate::qpaxos::ReplicateReply; use crate::qpaxos::*; use crate::replica::*; use crate::replication::RpcHandlerError; pub fn check_repl_common(inst: &Instance, reply: ReplicateReply) -> Result<Phase, RpcHandlerError> { let iid = reply ...
use crate::qpaxos::replicate_reply::Phase; use crate::qpaxos::Direction; use crate::qpaxos::ReplicateReply; use crate::qpaxos::*; use crate::replica::*; use crate::replication::RpcHandlerError; pub fn check_repl_common(inst: &Instance, reply: ReplicateReply) -> Result<Phase, RpcHandlerError> { let iid = reply ...
pub fn handle_prepare_reply( st: &mut ReplicationStatus, from_rid: ReplicaId, repl: ReplicateReply, ) -> Result<(), RpcHandlerError> { if let Some(ref e) = repl.err { return Err(RpcHandlerError::RemoteError(e.clone())); } let phase = check_repl_common(&st.instance, repl)?; let fr...
format!("{}", inst.instance_id.unwrap()), format!("{}", iid), ); return Err(err.into()); } let phase = reply.phase.ok_or(ProtocolError::LackOf("phase".into()))?; let last_ballot = reply.last_ballot; if inst.ballot < last_ballot { let zero = Some(BallotNum::default()...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_display_replicate_reply_err() {\n\n let cmn = \"last:None, iid:None, phase\";\n\n\n\n {\n\n // storage error\n\n let r = ReplicateReply {\n\n err: Some(QError {\n\n sto: Some(StorageFailure::default()),\n\n req: None,\...
Rust
src/gui/raw_control.rs
rodrigocfd/winsafe
3e9e60cb12902f51e953bcedbecd911262ed795a
use std::ptr::NonNull; use std::sync::Arc; use crate::aliases::ErrResult; use crate::co; use crate::enums::IdMenu; use crate::gui::base::Base; use crate::gui::events::{EventsView, WindowEventsAll}; use crate::gui::privs::{multiply_dpi, paint_control_borders}; use crate::gui::raw_base::RawBase; use crate::gui...
use std::ptr::NonNull; use std::sync::Arc; use crate::aliases::ErrResult; use crate::co; use crate::enums::IdMenu; use crate::gui::base::Base; use crate::gui::events::{EventsView, WindowEventsAll}; use crate::gui::privs::{multiply_dpi, paint_control_borders}; use crate::gui::raw_base::RawBase; use crate::gui...
}
f { class_name: "".to_owned(), class_style: co::CS::DBLCLKS, class_icon: HICON::NULL, class_cursor: HCURSOR::NULL, class_bg_brush: HBRUSH::from_sys_color(co::COLOR::WINDOW), position: POINT { x: 0, y: 0 }, size: SIZE { cx: 0, cy: 0 }, style: co::WS::CHILD | co::WS::TABSTOP | co::WS::GROU...
function_block-function_prefixed
[ { "content": "/// [`RegisterClassEx`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerclassexw)\n\n/// function.\n\npub fn RegisterClassEx(wcx: &WNDCLASSEX) -> WinResult<ATOM> {\n\n\tmatch unsafe { user32::RegisterClassExW(wcx as *const _ as _) } {\n\n\t\t0 => Err(GetLastError()),\...
Rust
src/main.rs
almusil/portable-ecg
c39cf6aa9cf1aaee1167d2bc05cd0c895f7522c6
#![no_main] #![no_std] use lib as _; use cortex_m::singleton; use heapless::consts::U64; use heapless::spsc::{Queue, SingleCore}; use lib::display::Display; use lib::hw::{ get_calibration, init_clock, init_lcd, Adc, AdcConfig, BeatCounter, BeatTimer, FrameTimer, HwLcd, IliError, LcdInterface, }; use lib::samp...
#![no_main] #![no_std] use lib as _; use cortex_m::singleton; use heapless::consts::U64; use heapless::spsc::{Queue, SingleCore}; use lib::display::Display; use lib::hw::{ get_calibration, init_clock, init_lcd, Adc, AdcConfig, BeatCounter, BeatTimer, FrameTimer, HwLcd, IliError, LcdInterface, }; use lib::samp...
_counter; let timer: &mut BeatTimer = cx.resources.beat_timer; let display: &mut Display<'_, _, _, _> = cx.resources.display; timer.unpend(); display.update_bpm(counter.read() * 6).unwrap(); counter.reset(); } };
dma_buffer: &'static mut [u16; 4] = singleton!(: [u16; 4] = [0; 4]).unwrap(); let (producer, consumer) = queue.split(); let mut rcc = init_clock(device.RCC); let mut delay = core.SYST.delay(&mut rcc); let gpioa = device.GPIOA.split(&mut rcc); let gpiob = devic...
random
[ { "content": "pub fn init_lcd(\n\n interface: LcdInterface,\n\n lcd_rst: LcdRst,\n\n lcd_rd: LcdRD,\n\n scroller_offset: (u16, u16),\n\n delay: &mut Delay<SYST>,\n\n) -> Result<HwLcd, IliError> {\n\n let mut lcd_rd = lcd_rd;\n\n lcd_rd.set_high().unwrap();\n\n IliLcd::new(interface, lcd_...
Rust
2021/src/day17.rs
shrugalic/advent_of_code
8d18a3dbdcf847a667ab553f5441676003b9362a
use std::cmp::max; use std::ops::{AddAssign, RangeInclusive}; const INPUT: &str = include_str!("../input/day17.txt"); pub(crate) fn day17_part1() -> isize { Probe::from(INPUT).highest_point() } pub(crate) fn day17_part2() -> usize { Probe::from(INPUT).trajectory_count() } #[derive(Debug, PartialEq)] struct ...
use std::cmp::max; use std::ops::{AddAssign, RangeInclusive}; const INPUT: &str = include_str!("../input/day17.txt"); pub(crate) fn day17_part1() -> isize { Probe::from(INPUT).highest_point() } pub(crate) fn day17_part2() -> usize { Probe::from(INPUT).trajectory_count() } #[derive(Debug, PartialEq)] struct ...
} } (*max_ys.iter().max().unwrap(), target_velocity_count) } fn simulate_trajectory(&self, x: isize, y: isize) -> Option<isize> { let mut position = Pair::new(0, 0); let mut velocity = Pair::new(x, y); let mut max_y = isize::MIN; while !(position.is_...
if let Some(max_y) = self.simulate_trajectory(x, y) { max_ys.push(max_y); target_velocity_count += 1; }
if_condition
[ { "content": "fn parse_family(input: Vec<&str>) -> Vec<Vec<isize>> {\n\n // Vector of family members. This is only needed to get a unique index for each location\n\n let mut family: Vec<_> = vec![];\n\n // Happiness from each family member to all other family members (by index)\n\n let mut happiness...
Rust
crates/content-tree/src/leaf.rs
josephg/diamond-types
5e32135c760310964172adce5c4668034fe8bf35
use std::mem::take; use std::ptr::NonNull; use rle::Searchable; use super::*; impl<E: ContentTraits, I: TreeMetrics<E>, const IE: usize, const LE: usize> NodeLeaf<E, I, IE, LE> { pub(crate) unsafe fn new(next: Option<NonNull<Self>>) -> Self { Self::new_with_parent(ParentPtr::Root(NonNull::dangl...
use std::mem::take; use std::ptr::NonNull; use rle::Searchable; use super::*; impl<E: ContentTraits, I: TreeMetrics<E>, const IE: usize, const LE: usize> NodeLeaf<E, I, IE, LE> { pub(crate) unsafe fn new(next: Option<NonNull<Self>>) -> Self { Self::new_with_parent(ParentPtr::Root(NonNull::dangl...
} } None } }
Some(UnsafeCursor::new( unsafe { NonNull::new_unchecked(self as *const _ as *mut _) }, i, offset ))
call_expression
[ { "content": "struct DebugContent<'a, E: ContentTraits, I: TreeMetrics<E>, const IE: usize, const LE: usize>(&'a ContentTreeRaw<E, I, IE, LE>);\n\n\n\nimpl<'a, E: ContentTraits, I: TreeMetrics<E>, const IE: usize, const LE: usize> Debug for DebugContent<'a, E, I, IE, LE> {\n\n fn fmt(&self, f: &mut Formatter...
Rust
mythril/src/multiboot2.rs
barkera/mythril
b7b45fe08a05c5b66317bbf13fdd4fcf10c428d2
use crate::acpi; use crate::boot_info::{self, BootInfo}; use crate::global_alloc; use crate::memory::HostPhysAddr; use alloc::vec::Vec; extern "C" { pub static MULTIBOOT2_HEADER_START: u32; pub static MULTIBOOT2_HEADER_END: u32; } pub fn header_location() -> (u32, u32) { unsafe { (MULTIBOOT2_HEADER_START,...
use crate::acpi; use crate::boot_info::{self, BootInfo}; use crate::global_alloc; use crate::memory::HostPhysAddr; use alloc::vec::Vec; extern "C" { pub static MULTIBOOT2_HEADER_START: u32; pub static MULTIBOOT2_HEADER_END: u32; } pub fn header_location() -> (u32, u32) { unsafe { (MULTIBOOT2_HEADER_START,...
pub fn early_init_multiboot2(addr: HostPhysAddr) -> BootInfo { let multiboot_info = unsafe { multiboot2::load(addr.as_u64() as usize) }; let alloc_region = setup_global_alloc_region(&multiboot_info); info!( "Allocating from 0x{:x}-{:x}", alloc_region.0, alloc_region.1 ); unsafe ...
let sections_tag = info .elf_sections_tag() .expect("Missing multiboot elf sections tag"); debug!("Elf sections:"); let sections = sections_tag.sections().map(|section| { debug!( " 0x{:x}-0x{:x}", section.start_address(), section.end_address() ...
function_block-function_prefix_line
[ { "content": "/// Get this current core's sequential index\n\npub fn read_core_idx() -> u64 {\n\n unsafe {\n\n let value: u64;\n\n llvm_asm!(\"mov [%fs], %rax\"\n\n : \"={rax}\"(value)\n\n ::: \"volatile\");\n\n value >> 3 // Shift away the RPL and TI bi...
Rust
bin/wayland/scanner/src/ast.rs
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
use crate::parser::{self, ArgKind}; #[derive(Debug)] pub struct Protocol { pub name: String, pub copyright: Option<String>, pub description: Option<Description>, pub interfaces: Vec<Interface>, } #[derive(Debug)] pub struct Description { pub summary: String, pub description: String, } #[der...
use crate::parser::{self, ArgKind}; #[derive(Debug)] pub struct Protocol { pub name: String, pub copyright: Option<String>, pub description: Option<Description>, pub interfaces: Vec<Interface>, } #[derive(Debug)] pub struct Description { pub summary: String, pub description: String, } #[der...
fn build_enum(node: parser::ParseNode) -> AstResult<Enum> { if let parser::ParseElement::Enum { name, since, bitfield, } = node.element { let mut description: Option<Description> = None; let mut entries: Vec<EnumEntry> = Vec::new(); for child in node.childre...
fn build_arg(node: parser::ParseNode) -> AstResult<Vec<Arg>> { if let parser::ParseElement::Arg { name, kind, summary, interface, nullable, enum_type, } = node.element { let mut description: Option<Description> = None; for child in node.childre...
function_block-full_function
[]
Rust
server/src/sonos_endpoint.rs
papertigers/home-api
d9a430425ebfbc730b29683381f96e00317d2875
use crate::AppCtx; use dropshot::{endpoint, ApiDescription, HttpError, HttpResponseOk, RequestContext, TypedBody}; use futures::stream::StreamExt; use futures_util::stream::FuturesUnordered; use schemars::JsonSchema; use serde::Deserialize; use sonor::{rupnp::Device, Speaker}; use std::sync::Arc; use std::time::Duratio...
use crate::AppCtx; use dropshot::{endpoint, ApiDescription, HttpError, HttpResponseOk, RequestContext, TypedBody}; use futures::stream::StreamExt; use futures_util::stream::FuturesUnordered; use schemars::JsonSchema; use serde::Deserialize; use sonor::{rupnp::Device, Speaker}; use std::sync::Arc; use std::time::Duratio...
#[endpoint { method = POST, path = "/sonos/sleep", }] async fn sleep( rctx: Arc<RequestContext<AppCtx>>, body_param: TypedBody<SonosArgs>, ) -> Result<HttpResponseOk<()>, HttpError> { let body = body_param.into_inner(); let context = Arc::clone(&rctx); if let Some(speaker) = group_rooms(co...
async fn group_rooms( rctx: Arc<RequestContext<AppCtx>>, rooms: &[String], volume: Option<u16>, ) -> Result<Option<Speaker>, sonor::Error> { let first = match rooms.first() { Some(c) => c, None => return Ok(None), }; if let Some(coordinator) = sonor::find(first, Duration::f...
function_block-full_function
[ { "content": "type Result<T> = std::result::Result<T, error::AylaError>;\n\n\n\npub(crate) struct AylaClient {\n\n client: Client,\n\n region: Region,\n\n email: String,\n\n password: String,\n\n access_token: Option<String>,\n\n refresh_token: Option<String>,\n\n auth_expiration: Option<St...
Rust
crates/interledger-settlement/src/core/engines_api.rs
KevinWMatthews/interledger-rs
ec3c745e1af51b9aa83ac29b64111d2e9cbb3fbc
use super::{ get_hash_of, idempotency::{make_idempotent_call, IdempotentStore}, types::{Quantity, SettlementEngine}, }; use bytes::Bytes; use http::StatusCode; use hyper::Response; use interledger_errors::default_rejection_handler; use serde::{Deserialize, Serialize}; use warp::Filter; #[derive(Serialize...
use super::{ get_hash_of, idempotency::{make_idempotent_call, IdempotentStore}, types::{Quantity, SettlementEngine}, }; use bytes::Bytes; use http::StatusCode; use hyper::Response; use interledger_errors::default_rejection_handler; use serde::{Deserialize, Serialize}; use warp::Filter; #[derive(Serialize...
tEngine { async fn send_money(&self, _account_id: String, _money: Quantity) -> ApiResult { Ok(ApiResponse::Default) } async fn receive_message(&self, _account_id: String, _message: Vec<u8>) -> ApiResult { Ok(ApiResponse::Default) } async fn create_accoun...
async fn save_idempotent_data( &self, idempotency_key: String, input_hash: [u8; 32], status_code: StatusCode, data: Bytes, ) -> Result<(), IdempotentStoreError> { let mut cache = self.cache.write(); cache.insert( ...
random
[ { "content": "/// A trait for Store implmentations that have ILP routing tables.\n\npub trait RouterStore: AccountStore + Clone + Send + Sync + 'static {\n\n /// **Synchronously** return the routing table.\n\n /// Note that this is synchronous because it assumes that Stores should\n\n /// keep the rout...
Rust
9_error_handling/result/src/main.rs
rhavill/rust-programming-language
6fec6d84aa6a887e8dd5a5117ae7548780c1ecac
use std::io; use std::io::ErrorKind; use std::io::Read; use std::fs; use std::fs::File; fn main() { loop { println!("Input a number and press <Enter>:"); println!("1 - to see a generic error crash."); println!("2 - to match error and prevent crash."); println!("3 - to catch the erro...
use std::io; use std::io::ErrorKind; use std::io::Read; use std::fs; use std::fs::File; fn main() { loop { println!("Input a number and press <Enter>:"); println!("1 - to see a generic error crash."); println!("2 - to match error and prevent crash."); println!("3 - to catch the erro...
ssions. Using those methods will make your code more concise. In Chapter 13, you’ll learn about closures; the Result<T, E> type has many methods that accept a closure and are implemented using match expressions. Using those methods will make your code more concise. */ let f = File::open("he...
println!("7 - to propogate errors with ? operator."); println!("8 - to propogate errors with chained ? operator."); println!("9 - to propogate errors with fs::read_to_string."); println!("10 - to exit."); let mut option = String::new(); io::stdin().read_line(&mut option) ...
random
[ { "content": "fn main() {\n\n if_let_expressions();\n\n while_loop();\n\n for_loop();\n\n let_statement();\n\n function_parameters();\n\n}\n\n\n\n/*\n\nThe line if let Ok(age) = age introduces a new shadowed age variable that \n\ncontains the value inside the Ok variant. This means we need to pla...
Rust
src/number.rs
terrynsun/js.rs
702c162b7ad8e59c5e9b9ce0c0ec0ec43b532804
use std::cell::RefCell; use std::rc::Rc; use french_press::ScopeManager; use jsrs_common::backend::Backend; use jsrs_common::ast::*; use jsrs_common::ast::BinOp::*; use jsrs_common::types::coerce::{AsBool, AsNumber, AsString}; use jsrs_common::types::js_var::{JsVar, JsType}; use jsrs_common::types::js_var::JsPtrEnum:...
use std::cell::RefCell; use std::rc::Rc; use french_press::ScopeManager; use jsrs_common::backend::Backend; use jsrs_common::ast::*; use jsrs_common::ast::BinOp::*; use jsrs_common::types::coerce::{AsBool, AsNumber, AsString}; use jsrs_common::types::js_var::{JsVar, JsType}; use jsrs_common::types::js_var::JsPtrEnum:...
; JsBool(b) } NeqStrict => { if let Ok(JsBool(b)) = eval_binop(&EqlStrict, e1, e2, state) { JsBool(!b) } else { JsBool(false) } } BitOr => JsNum((ni32!(val1) | ni32!(val2)) as f64), BitXor => JsNum((...
match (&val1.t, &val2.t) { (&JsNull, &JsNull) => true, (&JsUndef, &JsUndef) => true, (&JsNum(ref n1), &JsNum(ref n2)) => n1 == n2, (&JsBool(ref b1), &JsBool(ref b2)) => b1 == b2, (&JsPtr(_), &JsPtr(_)) => { l...
if_condition
[ { "content": "/// Evaluate an expression into a JsVar.\n\npub fn eval_exp(e: &Exp, state: Rc<RefCell<ScopeManager>>) -> js_error::Result<JsVarValue> {\n\n match e {\n\n // [ e1, e2, ... ]\n\n &Array(ref elems) => {\n\n let proto = Some(Box::new(get_array_proto(elems.len() as f64, sta...
Rust
crates/zoon/src/routing/router.rs
afidegnum/MoonZoon
e8be4f08eedb295b01aa55295fe1ea2c2e24384a
use crate::{routing::decode_uri_component, *}; use futures_signals::signal::{channel, Sender}; use std::marker::PhantomData; use web_sys::MouseEvent; type UrlChangeSender = Sender<Option<Vec<String>>>; pub struct Router<R> { popstate_listener: SendWrapper<Closure<dyn Fn()>>, link_interceptor: SendWrapper<Clos...
use crate::{routing::decode_uri_component, *}; use futures_signals::signal::{channel, Sender}; use std::marker::PhantomData; use web_sys::MouseEvent; type UrlChangeSender = Sender<Option<Vec<String>>>; pub struct Router<R> { popstate_listener: SendWrapper<Closure<dyn Fn()>>, link_interceptor: SendWrapper<Clos...
fn setup_popstate_listener(url_change_sender: UrlChangeSender) -> SendWrapper<Closure<dyn Fn()>> { let closure = Closure::wrap(Box::new(move || { url_change_sender .send(current_url_segments()) .unwrap_throw(); }) as Box<dyn Fn()>); window() .add_event_listener_wit...
fn current_url_segments() -> Option<Vec<String>> { let path = window().location().pathname().unwrap_throw(); let mut segments = Vec::new(); for segment in path.trim_start_matches('/').split_terminator('/') { match decode_uri_component(segment) { Ok(segment) => segments.push(segment), ...
function_block-full_function
[ { "content": "#[static_ref]\n\npub fn router() -> &'static Router<Route> {\n\n Router::new(|route| match route {\n\n Some(Route::Active) => app::select_filter(app::Filter::Active),\n\n Some(Route::Completed) => app::select_filter(app::Filter::Completed),\n\n Some(Route::Root) | None => a...
Rust
roman-numeral/roman-numeral/src/lib.rs
Emilgardis/problems
9d1e8f917f78621b66816d624009bbd12861f075
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] extern crate num; #[macro_use] extern crate num_derive; extern crate itertools; #[macro_use] extern crate error_chain; mod errors; use errors::*; use itertools::Itertools; use std::str::FromStr; use num::traits::{CheckedS...
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] extern crate num; #[macro_use] extern crate num_derive; extern crate itertools; #[macro_use] extern crate error_chain; mod errors; use errors::*; use itertools::Itertools; use std::str::FromStr; use num::traits::{CheckedS...
pub fn expand(&mut self) -> Result<()> { let stred = self.as_string()?; println!("{}", stred); let res = stred .replace("IV", "IIII") .replace("XL", "XXXX") .replace("CD", "CCCC") .replace("XC", "LXXXX") .replace("CM", "DCCCC") ...
pub fn condense(&mut self) -> Result<()> { let stred = self.as_string().unwrap(); let res = stred .replace("IIIIII", "VI") .replace("VIIII", "IX") .replace("DCCCC", "CM") .replace("LXXXX", "XC") .replace("CCCC", "CD") ...
function_block-full_function
[ { "content": "#[derive(Debug, PartialEq, PartialOrd, Eq, Ord)]\n\nstruct Name<'a>(pub &'a str);\n\n\n\nimpl<'a> Name<'a> {\n\n pub fn value(&self) -> usize {\n\n self.0.chars().fold(0, |v, ch| v + (ch as u8 - 64) as usize )\n\n }\n\n}\n\n\n\n\n\n#[cfg(test)]\n\nmod tests{\n\n\n\n use super::*;\n...
Rust
src/main.rs
lang-import/rs-translate
60912ec66a6518a0436112b6825383d7bb90eb14
extern crate redis; extern crate clap; extern crate rouille; use rouille::{Request, Response}; use std::{process, str}; use clap::{Arg, App}; fn list_engines(command: &str) -> Vec<String> { let output = process::Command::new(command) .arg("-S") .output().expect("list of supported engines").stdout;...
extern crate redis; extern crate clap; extern crate rouille; use rouille::{Request, Response}; use std::{process, str}; use clap::{Arg, App};
fn translate_engine(command: &str, engine: &str, lang: &str, word: &str) -> Option<String> { let lang_arg: String = ":".to_string() + lang; let output = match process::Command::new(command) .arg("-e").arg(engine).arg("-b").arg(lang_arg).arg(word) .output() { Ok(v) => v.stdout, ...
fn list_engines(command: &str) -> Vec<String> { let output = process::Command::new(command) .arg("-S") .output().expect("list of supported engines").stdout; str::from_utf8(&output) .unwrap() .split_whitespace() .map(|x| x.trim()) .filter(|x| !x.is_empty() && !x.st...
function_block-full_function
[]
Rust
src/usi/chiyuri.rs
muzudho/rust-kifuwarabe-wcsc30
e21fda4d648c8fa162ca3e59dd2d85dab6272fc5
use crate::entities::cosmic::playing::{Game, PosNums}; use crate::entities::cosmic::universe::Universe; use crate::entities::law::cryptographic::*; use crate::entities::law::usi::*; use crate::entities::spaceship::equipment::Beam; use crate::entities::spaceship::facility::{CommandRoom, GameRoom}; use crate::movegen::Ps...
use crate::entities::cosmic::playing::{Game, PosNums}; use crate::entities::cosmic::universe::Universe; use crate::entities::law::cryptographic::*; use crate::entities::law::usi::*; use crate::entities::spaceship::equipment::Beam; use crate::entities::spaceship::facility::{CommandRoom, GameRoom}; use crate::movegen::Ps...
pub fn undo(universe: &mut Universe) { if !universe.game.undo_move() { Beam::shoot(&format!( "ply={} を、これより戻せません", universe.game.history.moves_num() )); } } }
pub fn teigi_conv() { Beam::shoot("teigi::convのテスト"); for ms in 1..9 { for hash in 0..10 { let sq = Square::from(FILE_1, ms); let next = push_sq_to_hash(hash, sq); let (hash_orig, sq_orig) = pop_sq_from_hash(next); Beam::shoot(...
function_block-full_function
[ { "content": "/// position コマンド読取\n\npub fn set_position(game: &mut Game, tokens: &Vec<&str>) {\n\n assert_eq!(tokens[0], \"position\");\n\n assert!(\n\n Regex::new(r\"[startpos|sfen]\").unwrap().is_match(tokens[1]),\n\n \"tokens1=[{}]\",\n\n tokens[1].to_string()\n\n );\n\n\n\n ...
Rust
rust/src/solutions/day14.rs
efrees/adventofcode2019
9267fdff07f0144d57b659744b83cc0c6b7ecb7b
use regex::Regex; use std::collections::HashMap; #[derive(Eq, PartialEq, Hash)] struct Chemical { count: u32, name: String, } pub fn solve() { println!("Day 14"); let raw_reactions = adventlib::read_input_lines("day14input.txt"); let reactions_list: Vec<_> = raw_reactions.iter().map(|m| parse_rea...
use regex::Regex; use std::collections::HashMap; #[derive(Eq, PartialEq, Hash)] struct Chemical { count: u32, name: String, } pub fn solve() { println!("Day 14"); let raw_reactions = adventlib::read_input_lines("day14input.txt"); let reactions_list: Vec<_> = raw_reactions.iter().map(|m| parse_rea...
; remnant = recipe_output * recipe_count - goal; } } *remnant_totals.get_mut(name).unwrap() = remnant; return requirement; } fn parse_reaction(raw_reaction: &String) -> (Chemical, Vec<Chemical>) { let sides_of_equation: Vec<_> = raw_reaction.split(" => ").collect(); let ...
compute_total_ore_requirements( &input.name, input.count as u64 * recipe_count, reactions, reaction_outputs, remnant_totals, )
call_expression
[ { "content": "pub fn read_input_raw(filename: &str) -> String {\n\n let filename = \"inputs/\".to_owned() + filename;\n\n let mut file = File::open(filename).expect(\"Could not find input file\");\n\n let mut string = String::new();\n\n file.read_to_string(&mut string)\n\n .expect(\"Could not...
Rust
radogost/rlox/src/resolver.rs
stormasm/lox
ec1d179f6c478c40b7eb10304e40a19995ef09e6
use crate::error::{LoxError, Result}; use crate::statement::{Expr, ExprId, Stmt}; use std::collections::HashMap; #[derive(Copy, Clone, PartialEq, Eq)] enum FunctionType { None, Method, Function, Initializer, } #[derive(Copy, Clone, PartialEq, Eq)] enum ClassType { None, Class, SubClass, }...
use crate::error::{LoxError, Result}; use crate::statement::{Expr, ExprId, Stmt}; use std::collections::HashMap; #[derive(Copy, Clone, PartialEq, Eq)] enum FunctionType { None, Method, Function, Initializer, } #[derive(Copy, Clone, PartialEq, Eq)] enum ClassType { None, Class, SubClass, }...
#[test] fn invalid_this() { let source = "var a = this;"; let scopes = scopes(source); assert_eq!(scopes.is_err(), true); assert_eq!( scopes.unwrap_err(), LoxError::ResolverError("Cannot use 'this' outside of a class.") ); } #[test] ...
fn valid_return_statement() { let source = r#" fun test() { return 42; } "#; let scopes = scopes(source); assert_eq!(scopes.is_ok(), true); }
function_block-full_function
[ { "content": "#[derive(PartialEq, Clone, Copy)]\n\nenum ClassType {\n\n None,\n\n Class,\n\n Subclass,\n\n}\n\n\n\npub struct LexicalScopesResolver {\n\n // Note that this doesn't track globals at all\n\n scopes: Vec<FnvHashMap<Identifier, VariableDefinition>>,\n\n current_function: Option<Fun...
Rust
nakadion/src/handler/mod.rs
chridou/nakadion
86975ec81cd4b1d14a8ce26e8bc02f0772cb71c9
use std::fmt; use std::time::{Duration, Instant}; pub use bytes::Bytes; use futures::future::BoxFuture; pub type BatchHandlerFuture<'a> = BoxFuture<'a, BatchPostAction>; use crate::nakadi_types::{ event_type::EventTypeName, partition::PartitionId, subscription::{EventTypePartition, StreamId, Subscripti...
use std::fmt; use std::time::{Duration, Instant}; pub use bytes::Bytes; use futures::future::BoxFuture; pub type BatchHandlerFuture<'a> = BoxFuture<'a, BatchPostAction>; use crate::nakadi_types::{ event_type::EventTypeName, partition::PartitionId, subscription::{EventTypePartition, StreamId, Subscripti...
:Unspecified => write!(f, "[unspecified]")?, HandlerAssignment::EventType(ref event_type) => { write!(f, "[event_type={}]", event_type)? } HandlerAssignment::EventTypePartition(ref event_type_partition) => write!( f, "[event_type={}, pa...
} } } } impl fmt::Display for HandlerAssignment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { HandlerAssignment:
random
[ { "content": "/// Something that has an event type and a partition\n\n///\n\n/// Must only return event types and partitions that belong together.\n\npub trait EventTypePartitionLike {\n\n fn event_type(&self) -> &EventTypeName;\n\n fn partition(&self) -> &PartitionId;\n\n}\n\n\n\n/// Represents event-typ...
Rust
src/clone_wait_signal_pass_wasm.rs
AliceOh/RUST_clone_cgroup_project
64d381f849c5581dd2133417d0b2c2459c5e7e27
use std::process::Command; use std::thread::sleep; use std::time::Duration; use libc::{_exit, kill, pause, prctl, sigemptyset, sigset_t, sigwait, write, STDOUT_FILENO}; use nix::sys::signal::{ sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal, SIGCHLD, SIGCONT, SIGSTOP, SIGUSR1, }; use std::ffi::c_void; u...
use std::process::Command; use std::thread::sleep; use std::time::Duration; use libc::{_exit, kill, pause, prctl, sigemptyset, sigset_t, sigwait, write, STDOUT_FILENO}; use nix::sys::signal::{ sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal, SIGCHLD, SIGCONT, SIGSTOP, SIGUSR1, }; use std::ffi::c_void; u...
fn main() -> Result<(), Box<dyn Error>> { Command::new("mkdir") .arg("-p") .arg("/sys/fs/cgroup/foo") .output() .expect("failed to execute process"); println!("[main] after mkdir"); const STACK_SIZE: usize = 1024 * 1024; let ref mut stack = [0; STACK_SIZE]; ...
rintln!("[child]: received from socket: {}, length is {} bytes", s, s.len()); } println!("[clone child] Try to allocate big array"); let _v = Box::new([0i32; 600]); println!("[clone child] Yeah, get my array memory successfully!"); Command::new("ip") .arg("link") .spawn() ...
function_block-function_prefixed
[ { "content": "/// allocate an array and new a \"ip\" process\n\nfn child() -> isize {\n\n println!(\n\n \"[clone child] Hello from child process with pid: {} and parent pid:{}\",\n\n getpid(),\n\n getppid()\n\n );\n\n\n\n // set signal handler for pause\n\n let sig_action = SigA...
Rust
gaoya/src/minhash/string_index.rs
serega/gaoya
b0fd049bcb5aa4c8f865462c209b48cf4d78349b
use crate::minhash::min_hasher64::MinHasher64V1; use crate::minhash::{MinHasher, MinHashIndex}; use crate::text::whitespace_split; use rayon::prelude::*; use std::collections::HashMap; use std::fmt; use std::fmt::{Display, Formatter, write}; use std::fs::File; use std::io::{BufRead, BufReader, Error}; use std::io::{Rea...
use crate::minhash::min_hasher64::MinHasher64V1; use crate::minhash::{MinHasher, MinHashIndex}; use crate::text::whitespace_split; use rayon::prelude::*; use std::collections::HashMap; use std::fmt; use std::fmt::{Display, Formatter, write}; use std::fs::File; use std::io::{BufRead, BufReader, Error}; use std::io::{Rea...
let mut file = Vec::new(); for bytes in strings.iter().map(|s| s.as_bytes()) { file.write_all(&bytes).unwrap(); file.write_all("\n".as_bytes()).unwrap(); } let mut lsh_index = MinHashStringIndex::new(42, 4, 0.5); lsh_index.load_from_l...
let strings: Vec<String> = [ "locality sensitive hashing is a cool algorithm", "locality sensitive hashing is a great algorithm", "locality sensitive hashing is a awesome algorithm", "we all scream for ice cream", "we all scream for ice cream", "we...
assignment_statement
[ { "content": "pub fn shingle_text_range<'a>(text: &'a str, from: usize, to: usize) -> impl Iterator<Item = &'a str> {\n\n MultiShingles::new(text, from, to)\n\n}\n\n\n", "file_path": "gaoya/src/text/tokenizers.rs", "rank": 0, "score": 228558.83057087305 }, { "content": "pub fn shingle_tex...
Rust
fsb5/src/lib.rs
raftario/assetbundle
58ce22c0e0774c8c88471f3cdcad65569097a4b7
use byteorder::{LittleEndian, ReadBytesExt}; use std::{ collections::HashMap, convert::{TryFrom, TryInto}, io::{BufRead, Read, Seek, SeekFrom}, }; mod error; pub use error::Error; #[cfg(feature = "pcm")] mod pcm; #[derive(Debug, Copy, Clone)] pub enum SoundFormat { None, PCM8, PCM16, PCM2...
use byteorder::{LittleEndian, ReadBytesExt}; use std::{ collections::HashMap, convert::{TryFrom, TryInto}, io::{BufRead, Read, Seek, SeekFrom}, }; mod error; pub use error::Error; #[cfg(feature = "pcm")] mod pcm; #[derive(Debug, Copy, Clone)] pub enum SoundFormat { None, PCM8, PCM16, PCM2...
} impl TryFrom<u32> for SoundFormat { type Error = Error; fn try_from(value: u32) -> Result<Self, Self::Error> { match value { 0 => Ok(SoundFormat::None), 1 => Ok(SoundFormat::PCM8), 2 => Ok(SoundFormat::PCM16), 3 => Ok(SoundFormat::PCM24), ...
pub fn file_extension(self) -> &'static str { match self { SoundFormat::MPEG => "mp3", SoundFormat::Vorbis => "ogg", SoundFormat::PCM8 | SoundFormat::PCM16 | SoundFormat::PCM32 => "wav", _ => "bin", } }
function_block-full_function
[ { "content": "pub fn rebuild(sample: Sample, width: u16) -> Result<Vec<u8>, Error> {\n\n let data = &sample.data.unwrap()[..(sample.samples * width as usize)];\n\n let mut writer = BufWriter::new(Cursor::new(Vec::new()));\n\n\n\n let spec = WavSpec {\n\n channels: sample.channels as u16,\n\n ...
Rust
day18/src/main.rs
theonejb/advent-of-code-20
d0cbefd5ef88cae566df1260750c1c7d7a98a9ec
use std::path::Path; use std::fs::File; use std::io::{BufReader, BufRead}; use std::cmp::Ordering; mod tests; #[derive(Debug, PartialEq, Eq)] enum Operator { Add, Sub, Mul, Div, } impl Ord for Operator { fn cmp(&self, other: &Self) -> Ordering { match self { Operator::Add => m...
use std::path::Path; use std::fs::File; use std::io::{BufReader, BufRead}; use std::cmp::Ordering; mod tests; #[derive(Debug, PartialEq, Eq)] enum Operator { Add, Sub, Mul, Div, } impl Ord for Operator { fn cmp(&self, other: &Self) -> Ordering { match self { Operator::Add => m...
r() { let parsed_expression = parse(expression.as_str()); sum += calculate2(&parsed_expression); } println!("Part 2: {}", sum); }
} '(' => { num_parens += 1; } _ => {} } parenthesised_group.push(c); } let left_over = input.strip_prefix(&parenthesised_group).unwrap(); let left_over = &left_over[1..]; ...
random
[ { "content": "fn get_input(rules_filename: &str, data_filename: &str) -> (Vec<String>, Vec<String>) {\n\n let f = File::open(Path::new(rules_filename)).unwrap();\n\n let mut rules = vec![];\n\n for line in BufReader::new(f).lines() {\n\n rules.push(line.unwrap());\n\n }\n\n\n\n let f = Fil...
Rust
src/link/classify.rs
CollinValley/hivemind
89c6e4214fb88d27404f7a48ac5453be807cb21e
use crate::link::utils::task_park::*; use crate::Classifier; use crate::{link::QueueStream, HStream, Link}; use crossbeam::atomic::AtomicCell; use crossbeam::crossbeam_channel; use crossbeam::crossbeam_channel::{Receiver, Sender}; use futures::prelude::*; use futures::ready; use futures::task::{Context, Poll}; use std:...
use crate::link::utils::task_park::*; use crate::Classifier; use crate::{link::QueueStream, HStream, Link}; use crossbeam::atomic::AtomicCell; use crossbeam::crossbeam_channel; use crossbeam::crossbeam_channel::{Receiver, Sender}; use futures::prelude::*; use futures::ready; use futures::task::{Context, Poll}; use std:...
} #[test] fn fizz_buzz_to_even_odd() { let mut runtime = initialize_runtime(); let results = runtime.block_on(async { let packet_generator = immediate_stream(0..=30); let (mut fb_runnables, mut fb_egressors) = fizz_buzz_link(packet_generator).take(); let ...
test_link(even_link(Box::new(packet_generator)), None).await }); assert_eq!(results[0], vec![0, 2, 420, 4, 6, 8]); assert_eq!(results[1], vec![1, 1337, 3, 5, 7, 9]); } #[test] fn only_odd() { let mut runtime = initialize_runtime(); let results = runtime.block_on(...
random
[ { "content": "pub fn fizz_buzz_link(stream: HStream<i32>) -> Link<i32> {\n\n DoClassify::do_classify(stream, FizzBuzz::new(), None)\n\n}\n", "file_path": "src/utils/test/classifier/fizz_buzz.rs", "rank": 0, "score": 165602.4877498499 }, { "content": "pub trait ClassifyFn<C: Classifier + C...
Rust
tests/end_to_end_cases/read_cli.rs
decadevvv/influxdb_iox
da440d8d277147e92c92fbdbe735cfcfb0c88912
use assert_cmd::Command; use predicates::prelude::*; use test_helpers::make_temp_file; use crate::common::server_fixture::ServerFixture; use super::scenario::rand_name; #[tokio::test] pub async fn test() { let server_fixture = ServerFixture::create_single_use().await; let db_name = rand_name(); let addr ...
use assert_cmd::Command; use predicates::prelude::*; use test_helpers::make_temp_file; use crate::common::server_fixture::ServerFixture; use super::scenario::rand_name; #[tokio::test] pub async fn test() { let server_fixture = ServerFixture::create_single_use().await; let db_name = rand_name(); let addr ...
.arg(db_name) .arg("select * from cpu") .arg("--host") .arg(addr) .arg("--format") .arg("json") .assert() .success() .stdout(predicate::str::contains(expected)); } async fn test_read_error(db_name: &str, addr: &str) { Command::cargo_bin("infl...
.arg(addr) .assert() .success() .stdout(predicate::str::contains("2 Lines OK")); } async fn test_read_default(db_name: &str, addr: &str) { let expected = "+--------+-------------------------------+------+\n\ | region | time | user |\n\ ...
random
[ { "content": "/// Loads the specified lines into the named database\n\nfn load_lp(addr: &str, db_name: &str, lp_data: Vec<&str>) {\n\n let lp_data_file = make_temp_file(lp_data.join(\"\\n\"));\n\n\n\n Command::cargo_bin(\"influxdb_iox\")\n\n .unwrap()\n\n .arg(\"database\")\n\n .arg(\...
Rust
http/src/util/buf_list.rs
aliemjay/xitca-web
b12188930663ab5d27aa0a25cbf29fc4ecc6a0f8
use std::{collections::VecDeque, io::IoSlice}; use crate::bytes::{Buf, BufMut, Bytes, BytesMut}; pub struct BufList<B> { bufs: VecDeque<B>, remaining: usize, } impl<B: Buf> Default for BufList<B> { fn default() -> Self { Self::new() } } impl<B: Buf> BufList<B> { #[inline] pub fn wi...
use std::{collections::VecDeque, io::IoSlice}; use crate::bytes::{Buf, BufMut, Bytes, BytesMut}; pub struct BufList<B> { bufs: VecDeque<B>, remaining: usize, } impl<B: Buf> Default for BufList<B> { fn default() -> Self { Self::new() } } impl<B: Buf> BufList<B> { #[inline] pub fn wi...
#[inline] fn copy_to_bytes(&mut self, len: usize) -> Bytes { match self.bufs.front_mut() { Some(front) if front.remaining() == len => { let b = front.copy_to_bytes(len); self.remaining -= len; self.bufs.pop_front(); ...
e { front.advance(rem); cnt -= rem; } } self.bufs.pop_front(); } }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn apply_mask(buf: &mut [u8], mask: [u8; 4]) {\n\n apply_mask_fast32(buf, mask)\n\n}\n\n\n\n/// A safe unoptimized mask application.\n", "file_path": "http-ws/src/mask.rs", "rank": 0, "score": 278887.4791281594 }, { "content": "#[inline]\n\npub fn apply_mask...
Rust
tests/test_lookup_ipv6.rs
tomhrr/owhois
94791fca1e01c7bfc5fe7f001d65fe3755213ab3
extern crate owhois; extern crate ipnet; #[cfg(test)] mod test_lookup { use ipnet::Ipv6Net; use owhois::lookup::ResourceLookup; use owhois::lookup::Ipv6ResourceLookup; use std::str::FromStr; #[test] fn ipv6_lookup_empty() { let ipv6_lookup: Ipv6ResourceLookup = ResourceLook...
extern crate owhois; extern crate ipnet; #[cfg(test)] mod test_lookup { use ipnet::Ipv6Net; use owhois::lookup::ResourceLookup; use owhois::lookup::Ipv6ResourceLookup; use std::str::FromStr; #[test] fn ipv6_lookup_empty() { let ipv6_lookup: Ipv6ResourceLookup = ResourceLook...
m_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128").unwrap() ); assert_eq!(value, Some(4)); let value = ipv6_lookup.get_longest_match_value( Ipv6Net::from_str("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe/128").unwrap() ); assert_eq!(value, Some(3)); let value = i...
match_value( Ipv6Net::from_str("::/128").unwrap() ); assert_eq!(value, Some(1)); let value = ipv6_lookup.get_longest_match_value( Ipv6Net::from_str("::1/128").unwrap() ); assert_eq!(value, Some(2)); let value = ipv6_lookup.get_longest_match_value( ...
random
[ { "content": "fn run_processors(directory: &str,\n\n servers: &HashMap<String, u32>,\n\n processors: Vec<Box<dyn Processor>>,\n\n ipv4_path: &str,\n\n ipv6_path: &str,\n\n asn_path: &str) {\n\n let mut ipv4_entries: ...
Rust
src/adjacency/graph/compressed.rs
colin-daniels/agnr-ml
fc936cb8b6a68c37dfaf64c74796e0cf795c1bb8
use itertools::Itertools; use rand::prelude::*; use std::iter::FromIterator; use std::ops::Range; use super::Edge; #[derive(Debug, Clone, Eq, PartialEq)] pub struct CompressedGraph<M = ()> { edges: Vec<Edge<M>>, edge_ranges: Vec<Range<usize>>, } impl<M> Default for CompressedGraph<M> { fn defau...
use itertools::Itertools; use rand::prelude::*; use std::iter::FromIterator; use std::ops::Range; use super::Edge; #[derive(Debug, Clone, Eq, PartialEq)] pub struct CompressedGraph<M = ()> { edges: Vec<Edge<M>>, edge_ranges: Vec<Range<usize>>, } impl<M> Default for CompressedGraph<M> { fn defau...
} offsets.resize(n_vertices + 1, self.edges.len()); self.edge_ranges = offsets .into_iter() .tuple_windows() .map(|(a, b)| a..b) .collect(); } }
if offsets.len() < from + 1 { offsets.resize(from + 1, i); }
if_condition
[ { "content": "#[inline]\n\npub fn iota<I: Idx>(start: I) -> std::iter::Map<RangeFrom<usize>, impl Fn(usize) -> I> {\n\n (start.index()..).map(I::new)\n\n}\n\n\n\n// NOTE: I don't want this to take arbitrary RangeBounds because it would either have\n\n// to use dynamic polymorphism, or panic on RangeFro...
Rust
src/packets.rs
gkbrk/RustOre-Classic
0ceb927ad06c5a6905811ba56137abff6b5ceb66
use std::io::MemReader; use std::io::net::tcp::TcpStream; use config::Configuration; use mc_string::MCString; pub struct Packet{ pub packet_id: u8, pub packet_len: uint, pub data: Vec<u8> } impl Packet{ pub fn receive(mut conn: TcpStream) -> Packet{ let packet_id = conn.read_byte().unwrap()...
use std::io::MemReader; use std::io::net::tcp::TcpStream; use config::Configuration; use mc_string::MCString; pub struct Packet{ pub packet_id: u8, pub packet_len: uint, pub data: Vec<u8> } impl Packet{ pub fn receive(mut conn: TcpStream) -> Packet{ let packet_id = conn.read_byte().unwrap()...
} fn send_ping(&mut self){ self.write_u8(0x01); } fn send_level_init(&mut self){ self.write_u8(0x02); } fn send_chunk_data(&mut self, length: i16, data: &[u8], percentage: u8){ self.write_u8(0x03); self.write_be_i16(length); self.wr...
-> SetBlock{ let mut reader = MemReader::new(self.data.clone()); return SetBlock{ x: reader.read_be_i16().unwrap(), y: reader.read_be_i16().unwrap(), z: reader.read_be_i16().unwrap(), destroyed: match reader.read_u8().unwrap(){ 0x00 => true...
random
[ { "content": "fn handle_connection(config: Configuration, mut conn: TcpStream, mutex_world: Arc<Mutex<World>>){\n\n let ip = match conn.peer_name(){\n\n Ok(x) => x.ip,\n\n Err(x) => {return;}\n\n };\n\n println!(\"{} is connecting to us...\", ip);\n\n loop{\n\n let packet = Pack...
Rust
src/db/users.rs
Follpvosten/swiki
7a5d216cd9776fa2958531bc8d357f0e695d3635
use std::{convert::TryFrom, result::Result as StdResult}; use rocket::{ outcome::try_outcome, request::{FromRequest, Outcome}, tokio::task::spawn_blocking, Request, }; use sqlx::PgPool; use uuid::Uuid; use zeroize::Zeroize; use crate::{Db, Error, Result}; #[derive(Debug, Clone, Copy)] pub struct User...
use std::{convert::TryFrom, result::Result as StdResult}; use rocket::{ outcome::try_outcome, request::{FromRequest, Outcome}, tokio::task::spawn_blocking, Request, }; use sqlx::PgPool; use uuid::Uuid; use zeroize::Zeroize; use crate::{Db, Error, Result}; #[derive(Debug, Clone, Copy)] pub struct User...
user_id.map(|user_id| UserSession { session_id, user_id, }) }) .await; result.as_ref().or_forward(()) } } #[derive(Debug, Clone, serde::Serialize)] pub struct LoggedUser { id: Uuid, na...
let user_id = match db.get_session_user(session_id).await { Err(e) => { log::error!("Error getting session user: {}", e); None } Ok(user_id) => Some(user_id), }?;
assignment_statement
[ { "content": "type Result<T> = std::result::Result<T, Error>;\n\n\n\n// Route modules\n\nmod articles;\n\nmod settings;\n\nmod users;\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 122101.93948178331 }, { "content": "pub fn routes() -> Vec<rocket::Route> {\n\n rocket::routes![\n\...
Rust
src/kernel/memory.rs
IamTheCarl/kernel_emulator
790be670460830f0f62e02b3b214d2c566264473
use crate::kernel::{bytes::Bytes, Pointer, Value, ValueSize}; use segmap::SegmentMap; use std::{ cell::{Ref, RefCell, RefMut}, ops::{Deref, DerefMut, Range}, }; use thiserror::Error; #[derive(Error, Debug)] pub enum Error { #[error("Loaded overlapping memory.")] MemoryOverlapps { sections: Ve...
use crate::kernel::{bytes::Bytes, Pointer, Value, ValueSize}; use segmap::SegmentMap; use std::{ cell::{Ref, RefCell, RefMut}, ops::{Deref, DerefMut, Range}, }; use thiserror::Error; #[derive(Error, Debug)] pub enum Error { #[error("Loaded overlapping memory.")] MemoryOverlapps { sections: Ve...
base_address, end: base_address + length, }, read, write, execute, } } } #[test] fn overlapping_memory() { #[cfg(not(tarpaulin_include))] fn assert_overlap_failed(result: Result<()>) -> std::result::Result<(), &'static str> { m...
value = Value::from_bytes(&bytes[..size.len()]); Ok(value) } pub fn write_random_bytes(&self, address: Pointer, data: &[u8]) -> Result<()> { let mut block = self.get_memory_block_mut(&address)?; let length = data.len(); if block.is_write() { let range = ...
random
[ { "content": "type Result<T> = std::result::Result<T, Error>;\n\n\n\npub struct SyscallRequest {\n\n process_id: ProcessId,\n\n call_code: Pointer,\n\n arguments: [Pointer; 6],\n\n}\n\n\n\npub enum SyscallResult {\n\n None,\n\n Some(Pointer),\n\n Exit,\n\n}\n\n\n\npub struct Executable {\n\n ...
Rust
prisma-fmt/src/text_document_completion.rs
ever0de/prisma-engines
4c9d4edf238ad9c4a706eb5b7201ee0b4ebee93e
use datamodel::{ datamodel_connector::{Connector, ReferentialIntegrity}, parse_configuration, parse_schema_ast, schema_ast::ast, }; use log::*; use lsp_types::*; pub(crate) fn empty_completion_list() -> CompletionList { CompletionList { is_incomplete: true, items: Vec::new(), } } p...
use datamodel::{ datamodel_connector::{Connector, ReferentialIntegrity}, parse_configuration, parse_schema_ast, schema_ast::ast, }; use log::*; use lsp_types::*; pub(crate) fn empty_completion_list() -> CompletionList { CompletionList { is_incomplete: true, items: Vec::new(), } } p...
#[test] fn position_to_offset_with_crlf() { let schema = "\r\nmodel Test {\r\n id Int @id\r\n}"; let expected_offset = schema.chars().position(|c| c == 'i').unwrap(); let found_offset = position_to_offset(&Position { line: 2, character: 4 }, schema).unwrap(); assert_eq!(found_offset, expected...
Y), ..Default::default() }) } } ast::SchemaPosition::Model( _model_id, ast::ModelPosition::Field(_, ast::FieldPosition::Attribute("relation", _, Some(attr_name))), ) if attr_name == "onDelete" || attr_name == "onUpdate" => {...
function_block-function_prefixed
[]
Rust
MBExtender/rust/speed-boostair/src/dds_loader.rs
RandomityGuy/MBExtender
5b5a4b5f8f9aafe76c6f50ab75f8a214ef22cb3c
use crate::dds_types::*; use crate::gl::{self, types::*}; use crate::io; use log::{debug, error, trace}; use mbx::core::{self, ResourceInstance, Stream}; use mbx::dgl::{self, BitmapFormat, GBitmap, TextureObject}; use mbx::prelude::*; use mbx::util; use std::error::Error; use std::ffi::CString; use std::mem; use std::o...
use crate::dds_types::*; use crate::gl::{self, types::*}; use crate::io; use log::{debug, error, trace}; use mbx::core::{self, ResourceInstance, Stream}; use mbx::dgl::{self, BitmapFormat, GBitmap, TextureObject}; use mbx::prelude::*; use mbx::util; use std::error::Error; use std::ffi::CString; use std::mem; use std::o...
l::TEXTURE_MIN_FILTER, min_filter as GLint); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, mag_filter as GLint); if clamp_to_edge { gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as GLint); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_E...
ixels(bpp) => bpp as u32, TextureLayout::Blocks(_) => 0, }; let mut mip_levels = 1; if header.flags & DDS_HEADER_FLAGS_MIPMAP != 0 { mip_levels = header.mip_map_count.max(1).min(10); } bitmap.num_mip_levels = mip_levels; let mut total_size = 0; for i in 0..mip_levels { ...
random
[ { "content": "fn fix_texture(name: u32, bitmap: &mut GBitmap, texture_type: u32) {\n\n if texture_type == 0 || texture_type == 1 || texture_type == 2 {\n\n return;\n\n }\n\n if bitmap.width <= 512 && bitmap.height <= 512 {\n\n return;\n\n }\n\n if bitmap.num_mip_levels > 1 {\n\n ...
Rust
src/discard_call_lives.rs
cgswords/rsc
cdfe135888fe1c6da11a792527fa98f86224acbe
use util::Binop; use util::Relop; use util::Label; use util::Location; use util::mk_uvar; use util::Ident; use std::collections::HashMap; use finalize_locations::Program as FLProgram; use finalize_locations::LetrecEntry as FLLetrecEntry; use finalize_locations::Body as FLBody; use finalize_locations::Exp...
use util::Binop; use util::Relop; use util::Label; use util::Location; use util::mk_uvar; use util::Ident; use std::collections::HashMap; use finalize_locations::Program as FLProgram; use finalize_locations::LetrecEntry as FLLetrecEntry; use finalize_locations::Body as FLBody; use finalize_locations::Exp...
} fn letrec_entry(input : LetrecEntry) -> FLLetrecEntry { FLLetrecEntry { label : input.label, rhs : body(input.rhs) } } fn body(input : Body) -> FLBody { FLBody { locations : input.locations , expression : exp(input.expression) } } macro_rules! mk_box { ($e:expr) => [Box::new($e)] } fn exp(input : Exp) -...
match input { Program::Letrec(letrecs, pgm_body) => FLProgram::Letrec( letrecs.into_iter().map(|x| letrec_entry(x)).collect() , body(pgm_body)) }
if_condition
[ { "content": "fn mk_mset(dest: Variable, offset: Offset, val : Triv) -> Effect {\n\n return Effect::MSet(dest, offset, val);\n\n}\n\n\n", "file_path": "src/finalize_locations.rs", "rank": 0, "score": 258680.8981013795 }, { "content": "fn mk_set_op(dest: Variable, op: Binop, t1 : Triv, t2: T...
Rust
src/lib.rs
rust-cv/cv-geom
645b4894a3c056f9043b4be7755a3a4dd0e41ae6
#![no_std] use cv_core::nalgebra::{zero, Matrix3x4, Matrix4, RowVector4}; use cv_core::{ Bearing, CameraPoint, CameraToCamera, Pose, TriangulatorObservances, TriangulatorRelative, WorldPoint, WorldToCamera, }; #[derive(Copy, Clone, Debug)] pub struct MinSquaresTriangulator { epsilon: f64, max_iterat...
#![no_std] use cv_core::nalgebra::{zero, Matrix3x4, Matrix4, RowVector4}; use cv_core::{ Bearing, CameraPoint, CameraToCamera, Pose, TriangulatorObservances, TriangulatorRelative, WorldPoint, WorldToCamera, }; #[derive(Copy, Clone, Debug)] pub struct MinSquaresTriangulator { epsilon: f64, max_iterat...
}
s)?; svd.singular_values .iter() .enumerate() .min_by_key(|&(_, &n)| float_ord::FloatOrd(n)) .map(|(ix, _)| svd.v_t.unwrap().row(ix).transpose().into_owned()) .map(|v| if v.w.is_sign_negative() { -v } else { v }) .map(Int...
function_block-function_prefixed
[ { "content": "#[panic_handler]\n\nfn panic(_info: &PanicInfo) -> ! {\n\n loop {}\n\n}\n\n\n\n#[no_mangle]\n\npub extern \"C\" fn _start() -> ! {\n\n loop {}\n\n}\n", "file_path": "ensure_no_std/src/main.rs", "rank": 0, "score": 12230.500703461832 }, { "content": "// ensure_no_std/src/m...
Rust
tests/src/vector.rs
sndels/yuki
bac8c1530ecc03b2c9657cd4cbde91112fbf82a8
#[cfg(test)] mod tests { use approx::{assert_abs_diff_eq, assert_abs_diff_ne, assert_relative_eq, assert_relative_ne}; use std::panic; use yuki::math::{Normal, Point3, Vec2, Vec3, Vec4}; #[test] fn new() { let v = Vec2::new(0.0, 1.0); assert_eq...
#[cfg(test)] mod tests { use approx::{assert_abs_diff_eq, assert_abs_diff_ne, assert_relative_eq, assert_relative_ne}; use std::panic; use yuki::math::{Normal, Point3, Vec2, Vec3, Vec4}; #[test] fn new() { let v = Vec2::new(0.0, 1.0); assert_eq...
#[test] fn max_comp() { assert_eq!(Vec2::new(0.0, 1.0).max_comp(), 1.0); assert_eq!(Vec2::new(1.0, 0.0).max_comp(), 1.0); assert_eq!(Vec3::new(0.0, 1.0, 2.0).max_comp(), 2.0); assert_eq!(Vec4::new(0.0, 1.0, 2.0, 3.0).max_comp(), 3.0); } #[test] fn max_dimension()...
assert_eq!(Vec3::new(0.0, 1.0, 2.0).min_comp(), 0.0); assert_eq!(Vec4::new(0.0, 1.0, 2.0, 3.0).min_comp(), 0.0); }
function_block-function_prefixed
[ { "content": "// Returns the refracted direction for `wi` and `n` or `None` if total internal reflection happens.\n\nfn refract(wi: Vec3<f32>, n: Normal<f32>, eta: f32) -> Option<Vec3<f32>> {\n\n let cos_theta_i = n.dot_v(wi);\n\n let sin_2_theta_i = (1.0 - cos_theta_i * cos_theta_i).max(0.0);\n\n let ...
Rust
wiz/wiz/src/build.rs
ChanTsune/wiz
199d0f4698822a177ede8015bf8e04f190f39934
use crate::core::dep::{resolve_manifest_dependencies, ResolvedDependencyTree}; use crate::core::error::CliError; use crate::core::load_project; use crate::core::workspace::Workspace; use clap::ArgMatches; use std::collections::{BTreeSet, HashMap, HashSet}; use std::env; use std::error::Error; use std::fs::create_dir_al...
use crate::core::dep::{resolve_manifest_dependencies, ResolvedDependencyTree}; use crate::core::error::CliError; use crate::core::load_project; use crate::core::workspace::Workspace; use clap::ArgMatches; use std::collections::{BTreeSet, HashMap, HashSet}; use std::env; use std::error::Error; use std::fs::create_dir_al...
let mut result = HashMap::new(); for dependency in dependencies.dependencies { dependency_list(&mut result, dependency); } result } fn compile_dependencies( ws: &Workspace, dependencies: ResolvedDependencyTree, target_dir: &str, ) -> Result<BTreeSet<String>, Box<dyn Error>> { l...
ask>>, dep: ResolvedDependencyTree, ) -> Task { let ResolvedDependencyTree { name, version, src_path, dependencies, } = dep; let task = Task { name, version, src_path, }; let dependenc...
function_block-function_prefixed
[ { "content": "pub fn parse_from_string(src: &str, name: Option<&str>) -> Result<WizFile> {\n\n match file(Span::from(src)) {\n\n Ok((s, f)) => {\n\n if !s.is_empty() {\n\n let location = Location::new(s.location_offset(), s.location_line());\n\n Err(ParseError:...
Rust
src/window.rs
TomasKralCZ/Leoric
df1c20319e4f0cc140dfbbce33a76dab0ac28188
use std::time::Instant; use egui::CtxRef; use egui_backend::{painter::Painter, DpiScaling, EguiStateHandler}; use egui_sdl2_gl::ShaderVersion; use eyre::{eyre, Result}; use sdl2::{ event::{Event, WindowEvent}, video::Window, video::{GLContext, GLProfile, SwapInterval}, EventPump, Sdl, VideoSubsystem, }...
use std::time::Instant; use egui::CtxRef; use egui_backend::{painter::Painter, DpiScaling, EguiStateHandler}; use egui_sdl2_gl::ShaderVersion; use eyre::{eyre, Result}; use sdl2::{ event::{Event, WindowEvent}, video::Window, video::{GLContext, GLProfile, SwapInterval}, EventPump, Sdl, VideoSubsystem, }...
pub fn begin_frame(&mut self) { self.egui_state.input.time = Some(self.start_time.elapsed().as_secs_f64()); self.egui_ctx.begin_frame(self.egui_state.input.take()); } pub fn end_frame(&mut self) -> bool { unsafe { gl::Disable(gl::DEPTH_TEST); ...
pub fn new(title: &str) -> Result<Self> { let sdl_context = sdl2::init().map_err(|e| eyre!("{e}"))?; let video_subsystem = sdl_context.video().map_err(|e| eyre!("{e}"))?; let size = video_subsystem .display_bounds(0) .map_err(|e| eyre!("{e}"))?; let width = (siz...
function_block-full_function
[ { "content": "/// Create an opengl buffer with integer content.\n\n///\n\n/// 'buffer' is a reference to a slice of T.\n\n///\n\n/// 'components', 'attrib index' and 'typ' have the same meaning as the respective\n\n/// arguments in glVertexAttribPointer.\n\npub fn create_int_buf<T: Copy>(buffer: &[T], component...
Rust
rmqtt-plugins/rmqtt-plugin-template/src/lib.rs
phial3/rmqtt
8c29529e273007178fd0af73dccb6b0bf6729339
use async_trait::async_trait; use rmqtt::{ broker::hook::{Handler, HookResult, Parameter, Register, ReturnType, Type}, plugin::{DynPlugin, DynPluginResult, Plugin}, Result, Runtime, }; #[inline] pub async fn register( runtime: &'static Runtime, name: &'static str, descr: &'static str, defa...
use async_trait::async_trait; use rmqtt::{ broker::hook::{Handler, HookResult, Parameter, Register, ReturnType, Type}, plugin::{DynPlugin, DynPluginResult, Plugin}, Result, Runtime, }; #[inline] pub async fn register( runtime: &'static Runtime, name: &'static str, descr: &'static str, defa...
} Parameter::MessagePublish(_session, c, publish) => { log::debug!("{:?} message publish, {:?}", c.id, publish); } Parameter::MessageDelivered(_session, c, from, _publish) => { log::debug!("{:?} MessageDelivered, {:?}", c.id, from); ...
onnack(connect_info, r) => { log::debug!("client connack, {:?}, {:?}", connect_info, r); } Parameter::ClientSubscribe(_session, c, subscribe) => { log::debug!("{:?} client subscribe, {:?}", c.id, subscribe); ...
function_block-random_span
[ { "content": "pub trait PluginFn: 'static + Sync + Send + Fn() -> BoxFuture<Result<DynPlugin>> {}\n\n\n\nimpl<T> PluginFn for T where T: 'static + Sync + Send + ?Sized + Fn() -> BoxFuture<Result<DynPlugin>> {}\n\n\n\npub type DynPluginResult = BoxFuture<Result<DynPlugin>>;\n\npub type DynPlugin = Box<dyn Plugin...
Rust
src/scope/lefthandsideexpr.rs
farodin91/js-parser-rs
8fdfe5b200788ec997d1446e1c44859a126493b7
use error::JsResult; use lexer::enums::{TokenType}; use scope::parser::{Parser, Item}; macro_rules! wait { ($expr:expr) => (match $expr { Item::None => (), Item::Item => return Ok(Item::Item), }) } macro_rules! none { ($expr:expr) => (match $expr { Item::None => return Ok(Item::No...
use error::JsResult; use lexer::enums::{TokenType}; use scope::parser::{Parser, Item}; macro_rules! wait { ($expr:expr) => (match $expr { Item::None => (), Item::Item => return Ok(Item::Item), }) } macro_rules! none { ($expr:expr) => (match $expr { Item::None => return Ok(Item::No...
Item => { first = true; continue }, Item::None => (), } match try!(self.parse_super_prop()) { Item::Item => { first = true; continue }, ...
) } Ok(Item::None) } pub fn member_expr_and_members(&mut self) -> JsResult<Item> { println!("member_expr_and_members {:?}", self.peek()); none!(try!(self.parse_member_expr())); self.parse_member() } pub fn parse_member_expr(&mut self) -> JsResult<Item> { ...
random
[ { "content": "pub fn parse<T, I>(iter: T) -> Result<Vec<TokenType>, ErrorType> where\n\n T: IntoIterator<Item = char, IntoIter = I> + Sized,\n\n I: Iterator<Item = char> + 'static {\n\n let state = &mut LexerState::new(Box::new(iter.into_iter()));\n\n match state.parse() {\n\n Ok(_)=> (),\n\n...
Rust
src/lib/runner.rs
jokeyrhyme/tuning
06b8efa15bebb1ddfefddd3e2322a81cce101edc
use std::{ collections::HashMap, sync::{Arc, Mutex}, thread, }; use thiserror::Error as ThisError; use crate::jobs::{self, is_result_done, is_result_settled, Execute, Status}; const MAX_THREADS: usize = 2; #[derive(Debug, ThisError)] pub enum Error { #[error(transparent)] Job { #[from] ...
use std::{ collections::HashMap, sync::{Arc, Mutex}, thread, }; use thiserror::Error as ThisError; use crate::jobs::{self, is_result_done, is_result_settled, Execute, Status}; const MAX_THREADS: usize = 2; #[derive(Debug, ThisError)] pub enum Error { #[error(transparent)] Job { #[from] ...
} impl FakeJob { fn new<S>(name: S, result: jobs::Result) -> (Self, Arc<Mutex<FakeJobSpy>>) where S: AsRef<str>, { let job = FakeJob { name: String::from(name.as_ref()), result, ..Default::default() }; ...
p: Duration::from_millis(0), spy_arc: Arc::new(Mutex::new(FakeJobSpy { calls: 0, time: None, })), when: true, } }
function_block-function_prefixed
[ { "content": "pub fn result_display(result: &Result) -> String {\n\n match result {\n\n Ok(s) => format!(\"{}\", s),\n\n Err(e) => format!(\"{:#?}\", e).red().to_string(),\n\n }\n\n}\n", "file_path": "src/lib/jobs/mod.rs", "rank": 0, "score": 172012.30064669653 }, { "cont...
Rust
rust/lib-hedgewars-engine/src/render/gear.rs
emorrp1/hw
0afbbead97ad3aa231391f60605a73cd2629a849
use crate::render::{ atlas::{AtlasCollection, SpriteIndex}, camera::Camera, gl::{ Buffer, BufferType, BufferUsage, InputElement, InputFormat, InputLayout, PipelineState, Shader, Texture2D, TextureDataType, TextureFilter, TextureFormat, TextureInternalFormat, VariableBinding, }, }...
use crate::render::{ atlas::{AtlasCollection, SpriteIndex}, camera::Camera, gl::{ Buffer, BufferType, BufferUsage, InputElement, InputFormat, InputLayout, PipelineState, Shader, Texture2D, TextureDataType, TextureFilter, TextureFormat, TextureInternalFormat, VariableBinding, }, }...
} fn load_sprite_pixels(path: &Path, buffer: &mut [u8]) -> io::Result<Size> { let decoder = Decoder::new(BufReader::new(File::open(path)?)); let (info, mut reader) = decoder.read_info()?; let size = Size::new(info.width as usize, info.height as usize); reader.next_frame(buffer)?; Ok(size) } fn l...
entry.position[1] + entry.size.height as f32 / 2.0, ], tex_coords: sprite_coords[0], }, Vertex { position: [ entry.position[0] + entry.size.width as f32 / 2.0, entry.position[1] + ...
function_block-function_prefix_line
[ { "content": "fn get_protocol_number(executable: &str) -> std::io::Result<u32> {\n\n let output = Command::new(executable).arg(\"--protocol\").output()?;\n\n\n\n Ok(u32::from_str(&String::from_utf8(output.stdout).unwrap().trim()).unwrap_or(55))\n\n}\n\n\n", "file_path": "rust/hedgewars-checker/src/mai...
Rust
src/views/help.rs
RedlineTriad/rshub
778d0a2f2d66998b6b1669def1f79573ccb54781
use std::io; use std::sync::Arc; use crossterm::event::KeyCode; use tui::layout::Rect; use tui::{ backend::CrosstermBackend, layout::{Alignment, Constraint, Direction, Layout, Margin}, style::{Modifier, Style}, text::Span, widgets::{Block, Borders, Paragraph, Wrap}, Frame, }; use crate::app::...
use std::io; use std::sync::Arc; use crossterm::event::KeyCode; use tui::layout::Rect; use tui::{ backend::CrosstermBackend, layout::{Alignment, Constraint, Direction, Layout, Margin}, style::{Modifier, Style}, text::Span, widgets::{Block, Borders, Paragraph, Wrap}, Frame, }; use crate::app::...
f.render_widget( Block::default() .title(Span::styled( "GLOBAL", Style::default().add_modifier(Modifier::BOLD), )) .title_alignment(Alignment::Center), chunks[1], ); f.rende...
let chunks = Layout::default() .direction(Direction::Vertical) .constraints(vec![ Constraint::Length(vertical_margin), Constraint::Length(1), Constraint::Length(help.global_hotkeys.len() as u16), Constraint::Length(1), ...
assignment_statement
[ { "content": "fn draw_info(f: &mut Frame<CrosstermBackend<io::Stdout>>, area: Rect, app: Arc<AppState>) {\n\n let chunks = Layout::default()\n\n .direction(Direction::Horizontal)\n\n .constraints(vec![Constraint::Percentage(100)])\n\n .split(area);\n\n\n\n f.render_widget(\n\n ...
Rust
puffin_http/src/client.rs
MarijnS95/puffin
71a4d7c97a63dac8dff42c573af3684559b952c6
use std::sync::{ atomic::{AtomicBool, Ordering::SeqCst}, Arc, Mutex, }; use puffin::{FrameData, FrameView}; pub struct Client { addr: String, connected: Arc<AtomicBool>, alive: Arc<AtomicBool>, frame_view: Arc<Mutex<FrameView>>, } impl Drop for Client { fn drop(&mut self) { self.a...
use std::sync::{ atomic::{AtomicBool, Ordering::SeqCst}, Arc, Mutex, }; use puffin::{FrameData, FrameView}; pub struct Client { addr: String, connected: Arc<AtomicBool>, alive: Arc<AtomicBool>, frame_view: Arc<Mutex<FrameView>>, } impl Drop for Client { fn drop(&mut self) { self.a...
use anyhow::Context as _; FrameData::read_next(stream) .context("Failed to parse FrameData")? .ok_or_else(|| anyhow::format_err!("End of stream")) } fn error_display_chain(error: &dyn std::error::Error) -> String { let mut s = error.to_string(); if let Some(source) = error.source() { ...
match server_version.cmp(&crate::PROTOCOL_VERSION) { std::cmp::Ordering::Less => { anyhow::bail!( "puffin server is using an older protocol version ({}) than the client ({}).", server_version, crate::PROTOCOL_VERSION ); } st...
if_condition
[ { "content": "/// Are the profiler scope macros turned on?\n\n/// This is [`false`] by default.\n\npub fn are_scopes_on() -> bool {\n\n MACROS_ON.load(Ordering::Relaxed)\n\n}\n\n\n\n/// All times are expressed as integer nanoseconds since some event.\n\npub type NanoSecond = i64;\n\n\n\n// ------------------...
Rust
firmware/hal/build.rs
Lotterleben/embedded2020
623fa53461c4da29d69318aa85de8b4119c50719
use std::{ env, error::Error, fs, path::{Path, PathBuf}, }; fn main() -> Result<(), Box<dyn Error>> { let out_dir = &PathBuf::from(env::var("OUT_DIR")?); let flash = env::var_os("CARGO_FEATURE_FLASH").is_some(); descs(&out_dir)?; fs::copy("interrupts.x", out_dir.join("interrupts....
use std::{ env, error::Error, fs, path::{Path, PathBuf}, }; fn main() -> Result<(), Box<dyn Error>> { let out_dir = &PathBuf::from(env::var("OUT_DIR")?); let flash = env::var_os("CARGO_FEATURE_FLASH").is_some(); descs(&out_dir)?; fs::copy("interrupts.x", out_dir.join("interrupts....
let line_coding = acm::LineCoding { bCharFormat: acm::bCharFormat::Stop1, bDataBits: acm::bDataBits::_8, bParityType: acm::bParityType::None, dwDTERate: 9_600, }; let serial_state = acm::SerialState { interface: 0, bOverRun: false, bParity: false, ...
r { bmCapabilities: acm::Capabilities { comm_features: false, line_serial: true, network_connection: false, send_break: false, }, }; bytes.extend_from_slice(&acm.bytes()); ...
function_block-function_prefixed
[ { "content": "fn main() -> Result<(), anyhow::Error> {\n\n let dev = serialport::available_ports()?\n\n .into_iter()\n\n .filter(|info| match info.port_type {\n\n SerialPortType::UsbPort(ref port) => port.vid == consts::VID,\n\n _ => false,\n\n })\n\n .next()...
Rust
examples/main.rs
grafana/grafana-plugin-sdk-rust
707d2b65b0c0be0d43d80a7b7778384d12f9d3c7
use std::{ sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, time::Duration, }; use bytes::Bytes; use chrono::prelude::*; use futures_util::stream::FuturesOrdered; use http::Response; use thiserror::Error; use tokio_stream::StreamExt; use tracing::{debug, info}; use grafana_plugin_sdk::{bac...
use std::{ sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, time::Duration, }; use bytes::Bytes; use chrono::prelude::*; use futures_util::stream::FuturesOrdered; use http::Response; use thiserror::Error; use tokio_stream::StreamExt; use tracing::{debug, info}; use grafana_plugin_sdk::{bac...
async fn publish_stream( &self, _request: backend::PublishStreamRequest, ) -> Result<backend::PublishStreamResponse, Self::Error> { info!("Publishing to stream"); todo!() } } #[derive(Debug, Error)] enum ResourceError { #[error("HTTP error: {0}")] Http(#[from] http...
ta::Frame::new("foo").with_field((x..x + n).into_field("x")); Ok(Box::pin( async_stream::try_stream! { loop { frame.fields_mut()[0].set_values( (x..x+n) )?; let packet = backend::StreamPacket::from_fr...
function_block-function_prefixed
[ { "content": "/// Error supertrait used in [`DataService::query_data`].\n\npub trait DataQueryError: std::error::Error {\n\n /// Return the `ref_id` of the incoming query to which this error corresponds.\n\n ///\n\n /// This allows the SDK to align queries up with any failed requests.\n\n fn ref_id(...
Rust
src/command/last.rs
wojexe/baca-cli
c024bd3d95a2e54dfc25bdc0dec352551a3b4e7c
use crate::api::baca_api::BacaApi; use crate::command::details::Details; use crate::command::Command; use crate::error::{Error, Result}; use crate::model::Submit; use crate::workspace::{ConfigObject, ConnectionConfig, Workspace}; use clap::ArgMatches; pub struct Last { task_id: Option<String>, } impl Last { p...
use crate::api::baca_api::BacaApi; use crate::command::details::Details; use crate::command::Command; use crate::error::{Error, Result}; use crate::model::Submit; use crate::workspace::{ConfigObject, ConnectionConfig, Workspace}; use clap::ArgMatches; pub struct Last { task_id: Option<String>, } impl Last { p...
; Ok(results.submits.first().ok_or(Error::NoSubmitsYet)?.clone()) } } impl Command for Last { fn execute<W, A>(self, workspace: &W, api: &A) -> Result<()> where W: Workspace, A: BacaApi, { let connection_config = ConnectionConfig::read_config(workspace)?; let la...
if let Some(task_id) = &self.task_id { api.get_results_by_task(connection_config, task_id)? } else { api.get_results(connection_config)? }
if_condition
[ { "content": "pub fn assert_contains_pattern(command: &[&str], pattern: &str) -> Result<(), Box<dyn Error>> {\n\n let (dir, mut cmd) = set_up_with_dir()?;\n\n\n\n cmd.args(command);\n\n cmd.assert()\n\n // .failure() // todo: exit codes\n\n .stdout(predicate::str::contains(pattern));\n\n\...
Rust
src/cmus_status/output/mod.rs
Noah2610/cmus-status-line
04727c8994b3e53c3d715f01500a226711e030d0
mod builder; mod format; pub use format::prelude::*; use super::data::prelude::*; use crate::error::prelude::*; use std::fmt; use builder::StatusOutputBuilder; const OVERFLOW_STR: &str = "..."; pub struct StatusOutput { data: CmusData, format: Format, } impl StatusOutput { pub fn builder() -> Status...
mod builder; mod format; pub use format::prelude::*; use super::data::prelude::*; use crate::error::prelude::*; use std::fmt; use builder::StatusOutputBuilder; const OVERFLOW_STR: &str = "..."; pub struct StatusOutput { data: CmusData, format: Format, } impl StatusOutput { pub fn builder() -> Status...
} FormatPart::Container(format_parts_inner) => Some( self.get_format_text_for_parts( format_parts_inner .iter() .map(std::ops::Deref::deref) .collect(), ), ),...
if let Some(time) = self.data.get_time() { let width = bar_config.inner_width(); let percent_complete = time.completion_percentage(); let characters = (width as f32 * percent_complete).round() as usize; Some(bar_conf...
if_condition
[ { "content": "pub fn dump_config() {\n\n print!(\n\n r#\"# DEFAULT CONFIG FOR {name}\n\n# To write this config to the proper config file, run something like:\n\n# mkdir -p ~/.config/{name}\n\n# {name} {cmd_dump_config} > ~/.config/{name}/config.toml\n\n\n\n{config}\"#,\n\n name = crate:...
Rust
risc0/zkvm/sdk/rust/serde/src/deserializer.rs
risc0/risc0
2e8a4959a4b4247a1d4b35678af20ab184317931
use serde::de::{Deserialize, DeserializeSeed, IntoDeserializer, Visitor}; use crate::{ align_up, err::{Error, Result}, }; pub fn from_slice<'a, T: Deserialize<'a>>(slice: &'a [u32]) -> Result<T> { let mut deserializer = Deserializer::new(slice); T::deserialize(&mut deserializer) } pub struct Deseri...
use serde::de::{Deserialize, DeserializeSeed, IntoDeserializer, Visitor}; use crate::{ align_up, err::{Error, Result}, }; pub fn from_slice<'a, T: Deserialize<'a>>(slice: &'a [u32]) -> Result<T> { let mut deserializer = Deserializer::new(slice); T::deserialize(&mut deserializer) } pub struct Deseri...
visitor.visit_char(character) } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { let len_bytes = self.try_take_word()? as usize; let bytes = self.try_take_n_bytes(len_bytes)?; let str = core::str::from_utf8(bytes).map_err(|_| ...
let character = core::str::from_utf8(&bytes) .map_err(|_| Error::DeserializeBadChar)? .chars() .next() .ok_or(Error::DeserializeBadChar)?;
assignment_statement
[ { "content": "fn into_words(slice: &[u8]) -> Result<Vec<u32>> {\n\n let mut vec = Vec::new();\n\n let chunks = slice.chunks_exact(4);\n\n assert!(chunks.remainder().len() == 0);\n\n for chunk in chunks {\n\n let word = chunk[0] as u32\n\n | (chunk[1] as u32) << 8\n\n | (...
Rust
botan/src/rng.rs
chux0519/botan-rs
4fc7560f2fa29a0ced584027fe2c791393d24773
use botan_sys::*; use utils::*; #[derive(Debug)] pub struct RandomNumberGenerator { obj: botan_rng_t } impl Drop for RandomNumberGenerator { fn drop(&mut self) { unsafe { botan_rng_destroy(self.obj); } } } impl RandomNumberGenerator { fn new_of_type(typ: &str) -> Result<RandomNumberGenerato...
use botan_sys::*; use utils::*; #[derive(Debug)] pub struct RandomNumberGenerator { obj: botan_rng_t } impl Drop for RandomNumberGenerator { fn drop(&mut self) { unsafe { botan_rng_destroy(self.obj); } } } impl RandomNumberGenerator { fn new_of_type(typ: &str) -> Result<RandomNumberGe
} pub fn new() -> Result<RandomNumberGenerator> { RandomNumberGenerator::new_userspace() } pub fn read(&self, len: usize) -> Result<Vec<u8>> { let mut result = vec![0; len]; self.fill(&mut result)?; Ok(r...
nerator> { let mut obj = ptr::null_mut(); let typ = make_cstr(typ)?; call_botan! { botan_rng_init(&mut obj, typ.as_ptr()) } Ok(RandomNumberGenerator { obj }) } pub(crate) fn handle(&self) -> botan_rng_t { self.obj } pub fn new_userspace() -> Re...
random
[ { "content": "/// Password based key derivation function\n\n///\n\n/// Note currently only PBKDF2 is supported by this interface.\n\n/// For PBKDF2, iterations >= 100000 is recommended.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// let rng = botan::RandomNumberGenerator::new().unwrap();\n\n/// let salt = rng.read(...
Rust
src/tests.rs
metal4people/merkletree
e2d3d22c51eb51a90da3b629ef71fc0423e61018
#![cfg(test)] use crate::merkletree::MerkleTree; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; fn hash_value<T>(value: T) -> u64 where T: Hash, { let mut hasher = DefaultHasher::new(); value.hash(&mut hasher); return hasher.finish(); } #[test] fn test_from_str_vec() { ...
#![cfg(test)] use crate::merkletree::MerkleTree; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; fn hash_value<T>(value: T) -> u64 where T: Hash, { let mut hasher = DefaultHasher::new(); value.hash(&mut hasher); return hasher.finish(); } #[test] fn test_from_str_vec() { ...
#[test] fn test_valid_proof_str() { let values = vec!["Hello", "my", "name", "is", "Rusty"]; let tree = MerkleTree::build_tree(values); let value = "Rusty"; let proof = tree.gen_proof(&value); assert!(proof.is_some()); let is_valid = tree.validate_proof(&proof.unwrap()); assert!(is_vali...
lid_proof() { let values = (1..10).map(|x| vec![x]).collect::<Vec<_>>(); let tree = MerkleTree::build_tree(values.clone()); for value in values { let proof = tree.gen_proof(value); assert!(proof.is_some()); let is_valid = tree.validate_proof(&proof.unwrap()); assert!(is_vali...
function_block-function_prefixed
[ { "content": "fn bench_big_rnd_tree(c: &mut Criterion) {\n\n c.bench_function(\"MerkleTree::build_tree - big\", |b| {\n\n let mut values = vec![vec![0u8; 256]; 160];\n\n let mut rng = rand::thread_rng();\n\n\n\n for mut v in &mut values {\n\n rng.fill_bytes(&mut v);\n\n ...
Rust
src/routes/balances/handlers_v2.rs
tharsis/safe-client-gateway
98206c5bfcd89f10c3429edccdc108017b179d49
use std::cmp::Ordering; use std::str::FromStr; use bigdecimal::BigDecimal; use rocket::futures::{stream, StreamExt}; use crate::cache::cache_operations::RequestCached; use crate::common::models::backend::balances_v2::Balance as BalanceDto; use crate::common::models::backend::balances_v2::TokenPrice as BackendTokenPri...
use std::cmp::Ordering; use std::str::FromStr; use bigdecimal::BigDecimal; use rocket::futures::{stream, StreamExt}; use crate::cache::cache_operations::RequestCached; use crate::common::models::backend::balances_v2::Balance as BalanceDto; use crate::common::models::backend::balances_v2::TokenPrice as BackendTokenPri...
; }
Ok(TokenPrice { address: token_address.to_string(), fiat_code: response.fiat_code, fiat_price: response.fiat_price, timestamp: response.timestamp, })
call_expression
[ { "content": "pub fn build_manifest_url(url: &str) -> ApiResult<String> {\n\n let mut url_parts = Url::parse(url).or(Err(api_error!(\"Not a valid Url\")))?;\n\n\n\n if !url_parts.scheme().starts_with(\"http\") {\n\n Err(api_error!(\"Invalid scheme\"))\n\n } else if url_parts.host_str().is_none()...
Rust
editor/src/inspector/handlers/collider.rs
thomasmatecki/rg3d
e1958b6615ae0a826e83614e8df45a1a6f821f82
use crate::{make_command, physics::Collider, scene::commands::physics::*, SceneCommand}; use rg3d::{ core::pool::Handle, gui::inspector::{FieldKind, PropertyChanged}, physics3d::desc::*, }; use std::any::TypeId; pub fn handle_collider_property_changed( args: &PropertyChanged, handle: Handle<Collide...
use crate::{make_command, physics::Collider, scene::commands::physics::*, SceneCommand}; use rg3d::{ core::pool::Handle, gui::inspector::{FieldKind, PropertyChanged}, physics3d::desc::*, }; use std::any::TypeId; pub fn handle_collider_property_changed( args: &PropertyChanged, handle: Handle<Collide...
fn handle_ball_desc_property_changed( handle: Handle<Collider>, collider: &Collider, property_changed: &PropertyChanged, ) -> Option<SceneCommand> { if let ColliderShapeDesc::Ball(_) = collider.shape { match property_changed.value { FieldKind::Object(ref value) => match property_ch...
None, }, _ => None, }, Collider::SHAPE => { if inner_property.owner_type_id == TypeId::of::<CuboidDesc>() { handle_cuboid_desc_property_changed(handle, collider, inner_property) } else if inner_property.owner_typ...
function_block-function_prefix_line
[ { "content": "/// Returns a list of `pub const [VARIANT_]FIELD: &'static str = \"key_value\"`;\n\npub fn quote_prop_keys(ty_args: &args::TypeArgs) -> TokenStream2 {\n\n let mut prop_idents = Vec::new();\n\n let mut prop_names = Vec::new();\n\n\n\n match &ty_args.data {\n\n ast::Data::Struct(fiel...
Rust
der/src/tag.rs
cipepser/utils
e96656b6b9d4e9313816316f4f287a1d2c04efcc
use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result}; use core::{convert::TryFrom, fmt}; const CONSTRUCTED_FLAG: u8 = 0b100000; const CONTEXT_SPECIFIC_FLAG: u8 = 0b10000000; #[derive(Copy, Clone, Eq, PartialEq)] #[allow(clippy::identity_op)] #[non_exhaustive] #[repr(u8)] pub enum T...
use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result}; use core::{convert::TryFrom, fmt}; const CONSTRUCTED_FLAG: u8 = 0b100000; const CONTEXT_SPECIFIC_FLAG: u8 = 0b10000000; #[derive(Copy, Clone, Eq, PartialEq)] #[allow(clippy::identity_op)] #[non_exhaustive] #[repr(u8)] pub enum T...
pub fn type_name(self) -> &'static str { match self { Self::Boolean => "BOOLEAN", Self::Integer => "INTEGER", Self::BitString => "BIT STRING", Self::OctetString => "OCTET STRING", Self::Null => "NULL", Self::ObjectIdentifier => "...
pub fn assert_eq(self, expected: Tag) -> Result<Tag> { if self == expected { Ok(self) } else { Err(ErrorKind::UnexpectedTag { expected: Some(expected), actual: self, } .into()) } }
function_block-full_function
[ { "content": "/// Obtain the length of an ASN.1 `SEQUENCE` of [`Encodable`] values when\n\n/// serialized as ASN.1 DER, including the `SEQUENCE` tag and length prefix.\n\npub fn encoded_len(encodables: &[&dyn Encodable]) -> Result<Length> {\n\n let inner_len = encoded_len_inner(encodables)?;\n\n Header::n...
Rust
src/xpath/tokenizer/mod.rs
James-LG/Skyscraper
e6fcecc20762d5c4e5d6d22d77cb1da083dd5871
mod helpers; mod tokens; use crate::vecpointer::VecPointerRef; pub use tokens::Token; use thiserror::Error; #[derive(Error, Debug)] pub enum LexError {} pub fn lex(text: &str) -> Result<Vec<Token>, LexError> { let mut symbols: Vec<Token> = Vec::new(); let chars: Vec<char> = text.chars().collect(); let m...
mod helpers; mod tokens; use crate::vecpointer::VecPointerRef; pub use tokens::Token; use thiserror::Error; #[derive(Error, Debug)] pub enum LexError {} pub fn lex(text: &str) -> Result<Vec<Token>, LexError> { let mut symbols: Vec<Token> = Vec::new(); let chars: Vec<char> = text.chars().collect(); let m...
Token::Number(1.0), Token::CloseSquareBracket, Token::Slash, Token::Identifier(String::from("page")), Token::OpenSquareBracket, Token::Identifier(String::from("last")), Token::OpenBracket, Token::CloseBracket, Toke...
ymbols.push(s); } else if let Some(s) = helpers::is_greater_than_sign(&mut pointer) { symbols.push(s); } else if let Some(s) = helpers::is_less_than_sign(&mut pointer) { symbols.push(s); } else if let Some(s) = helpers::is_double_colon(&mut pointer) { symbols....
random
[ { "content": "/// Checks if the [TextPointer](TextPointer) is currently pointing to a Number [Symbol](Symbol).\n\n/// If true it will move the text pointer to the next symbol, otherwise it will not change the pointer.\n\npub fn is_number(pointer: &mut VecPointerRef<char>) -> Option<Token> {\n\n if let Some(c...
Rust
src/graphics.rs
catid/rust_webgl_demo
b09490c0baba251009b8a9b9bfbf6040b4d43785
use stdweb::unstable::TryInto; use webgl_rendering_context::{ WebGLRenderingContext as WebGL, WebGLUniformLocation, WebGLBuffer, WebGLShader, WebGLProgram, }; use stdweb::web::{ IHtmlElement, IParentNode, document, TypedArray, }; use stdweb::web::html_element::CanvasElement; use glm...
use stdweb::unstable::TryInto; use webgl_rendering_context::{ WebGLRenderingContext as WebGL, WebGLUniformLocation, WebGLBuffer, WebGLShader, WebGLProgram, }; use stdweb::web::{ IHtmlElement, IParentNode, document, TypedArray, }; use stdweb::web::html_element::CanvasElement; use glm...
}
pub fn RenderScene(&mut self, nowSeconds: f64) { self.context.UpdateViewport(); self.context.Clear(); let eye = glm::vec3(0.0, 0.0, -10.0); let center = glm::vec3(0.0, 0.0, 0.0); let up = glm::vec3(0.0, 1.0, 0.0); let view_matrix = glm::look_at_rh( ...
function_block-full_function
[ { "content": "#[js_export]\n\nfn js_ontouch(x: i32, y: i32, w: i32, h: i32) {\n\n let norm_x = x as f32 / w as f32;\n\n let norm_y = y as f32 / h as f32;\n\n // FIXME: Convert x, y to normalized coordinates between -1..1\n\n js_log(format!(\"Tap at {}, {}\", norm_x, norm_y));\n\n}\n\n\n\nimpl InputS...
Rust
crate/divvunspell/src/ffi/fbs/tokenizer.rs
divvun/divvunspell-swift
9231ffb655752c3c3ad646216abd9aff3ec02ef0
#![allow(dead_code, unused_imports)] use std::cmp::Ordering; use std::mem; extern crate flatbuffers; use self::flatbuffers::EndianScalar; pub enum IndexedWordOffset {} #[derive(Copy, Clone, Debug, PartialEq)] pub struct IndexedWord<'a> { pub _tab: flatbuffers::Table<'a>, } impl<'a> flatbuffers::Follow<'a> for...
#![allow(dead_code, unused_imports)] use std::cmp::Ordering; use std::mem; extern crate flatbuffers; use self::flatbuffers::EndianScalar; pub enum IndexedWordOffset {} #[derive(Copy, Clone, Debug, PartialEq)] pub struct IndexedWord<'a> { pub _tab: flatbuffers::Table<'a>, } impl<'a> flatbuffers::Follow<'a> for...
#[inline] pub fn add_first_after(&mut self, first_after: flatbuffers::WIPOffset<IndexedWord<'b>>) { self.fbb_ .push_slot_always::<flatbuffers::WIPOffset<IndexedWord>>( WordContext::VT_FIRST_AFTER, first_after, ); } #[inline] pub fn add...
push_slot_always::<flatbuffers::WIPOffset<IndexedWord>>( WordContext::VT_SECOND_BEFORE, second_before, ); }
function_block-function_prefix_line
[ { "content": "pub fn cursor_context(first_half: &str, second_half: &str) -> WordContext {\n\n // Find the point in the first half where the first \"word\" happens\n\n let mut first_half_iter = first_half.word_bound_indices().rev();\n\n let mut second_half_iter = second_half.word_bound_indices();\n\n\n\...
Rust
native/src/lib.rs
zhangxh1023/node-image-search
2a66956f1fbe295208c6bc1a49b008d02860d4c6
extern crate neon; use neon::prelude::*; mod image; mod utils; struct ImageSearchTask { parent_image_path: String, child_image_path: String, out: String, result_level: u32, } impl Task for ImageSearchTask { type Output = Vec<Vec<image::ResultPoint>>; type Error = String; type JsEvent = JsArray; fn per...
extern crate neon; use neon::prelude::*; mod image; mod utils; struct ImageSearchTask { parent_image_path: String, child_image_path: String, out: String, result_level: u32, } impl Task for ImageSearchTask { type Output = Vec<Vec<image::ResultPoint>>; type Error = String; type JsEvent = JsArray; fn per...
struct GetDHashTask { image_path: String, } impl Task for GetDHashTask { type Output = String; type Error = String; type JsEvent = JsString; fn perform(&self) -> Result<Self::Output, Self::Error> { let image = image::Image::new(self.image_path.clone()); let result = image.get_d_hash(); Ok(resul...
fn image_search(mut cx: FunctionContext) -> JsResult<JsUndefined> { let parent_image_path = cx.argument::<JsString>(0)?.value(); let child_image_path = cx.argument::<JsString>(1)?.value(); let options = cx.argument::<JsObject>(2)?; let out = options .get(&mut cx, "out")? .downcast::<JsString>() .or_...
function_block-full_function
[ { "content": "pub fn convert_to_binary_from_hex(hex: &str) -> String {\n\n hex.chars().map(to_binary).collect()\n\n}\n\n\n", "file_path": "native/src/utils.rs", "rank": 4, "score": 67880.1477159762 }, { "content": "pub fn get_hamming_distance_by_hex_hash(hash_1: &str, hash_2: &str) -> u32 {...
Rust
services/headless-lms/server/src/ts_binding_generator.rs
rage/secret-project-331
3c78c02f2f1d2e4539522e73c3065ae8866604e3
use crate::controllers::{ auth::Login, course_material::{ exams::{ExamData, ExamEnrollmentData}, submissions::PreviousSubmission, }, main_frontend::{ courses::GetFeedbackQuery, exams::ExamCourseInfo, exercises::ExerciseSubmissions, feedback::MarkAsRead, proposed_edits::Ge...
use crate::controllers::{ auth::Login, course_material::{ exams::{ExamData, ExamEnrollmentData}, submissions::PreviousSubmission, }, main_frontend::{ courses::GetFeedbackQuery, exams::ExamCourseInfo, exercises::ExerciseSubmissions, feedback::MarkAsRead, proposed_edits::Ge...
organizations::Organization, page_history::PageHistory, page_history::HistoryChangeReason, pages::CmsPageExercise, pages::CmsPageExerciseSlide, pages::CmsPageExerciseTask, pages::CmsPageUpdate, pages::ContentManagementPage, pages::CoursePageWithUserData,...
function_block-function_prefix_line
[ { "content": "pub fn _add_routes(cfg: &mut ServiceConfig) {\n\n cfg.route(\"/uploads/{tail:.*}\", web::get().to(serve_upload))\n\n .route(\"{tail:.*}\", web::get().to(redirect_to_storage_service));\n\n}\n", "file_path": "services/headless-lms/server/src/controllers/files.rs", "rank": 0, "s...
Rust
src/lib.rs
Elinvynia/schwifty
e0233bf836af6382e5565801df452baf7c9f935b
#![forbid(unsafe_code)] #![warn(missing_debug_implementations)] #![warn(missing_docs)] pub use crate::country::Country; pub use crate::error::ValidationError; use std::str::FromStr; pub mod country; pub(crate) mod country_specific; pub mod error; #[allow(clippy::all)] pub(crate) mod u256 { uint::construct_uint...
#![forbid(unsafe_code)] #![warn(missing_debug_implementations)] #![warn(missing_docs)] pub use crate::country::Country; pub use crate::error::ValidationError; use std::str::FromStr; pub mod country; pub(crate) mod country_specific; pub mod error; #[allow(clippy::all)] pub(crate) mod u256 { uint::construct_uint...
} let integer = u256::U256::from_dec_str(&integer_string).unwrap(); if integer % 97 != 1.into() { return Err(ValidationError::InvalidIban); } Ok(Iban { country, raw: input, }) }
if ch.is_numeric() { integer_string.push(ch); } else { let x = ch.to_digit(36).unwrap().to_string(); integer_string.push_str(&x) }
if_condition
[ { "content": "fn c(num: usize) -> String {\n\n format!(\"[a-zA-Z0-9]{{{}}}\", num)\n\n}\n\n\n", "file_path": "src/country.rs", "rank": 1, "score": 59182.76963598044 }, { "content": "fn a(num: usize) -> String {\n\n format!(\"[A-Z]{{{}}}\", num)\n\n}\n\n\n\n// Almost-DSL macro for comfo...
Rust
examples/max11619-adc.rs
us-irs/vorago-reb1-rs
742a53d63a8d531d3e36068ee09987c2f38ef77e
#![no_main] #![no_std] use cortex_m_rt::entry; use embedded_hal::{blocking::delay::DelayUs, spi}; use max116xx_10bit::VoltageRefMode; use max116xx_10bit::{AveragingConversions, AveragingResults}; use panic_rtt_target as _; use rtt_target::{rprintln, rtt_init_print}; use va108xx_hal::timer::CountDownTimer; use va108xx...
#![no_main] #![no_std] use cortex_m_rt::entry; use embedded_hal::{blocking::delay::DelayUs, spi}; use max116xx_10bit::VoltageRefMode; use max116xx_10bit::{AveragingConversions, AveragingResults}; use panic_rtt_target as _; use rtt_target::{rprintln, rtt_init_print}; use va108xx_hal::timer::CountDownTimer; use va108xx...
fn spi_example_externally_clocked_with_delay( spi: SpiBase<SPIB>, mut delay: Delay, mut delay_us: impl DelayUs<u8>, ) -> ! { let mut adc = max11619_externally_clocked_with_wakeup(spi).expect("Creating MAX116xx device failed"); let mut cmd_buf: [u8; 32] = [0; 32]; let mut counter = 0; ...
up(spi) .expect("Creating externally clocked MAX11619 device failed"); if READ_MODE == ReadMode::AverageN { adc.averaging( AveragingConversions::FourConversions, AveragingResults::FourResults, ) .expect("Error setting up averaging register"); } let mut...
function_block-function_prefixed
[ { "content": "#[entry]\n\nfn main() -> ! {\n\n rtt_init_print!();\n\n rprintln!(\"-- Vorago Accelerometer Example --\");\n\n let mut dp = pac::Peripherals::take().unwrap();\n\n let mut delay = set_up_ms_delay_provider(&mut dp.SYSCONFIG, 50.mhz(), dp.TIM0);\n\n let pinsa = PinsA::new(&mut dp.SYSCO...
Rust
violetabftstore/src/store/worker/split_check.rs
whtcorpsinc/einsteindb-prod
3b1c63a421ff37f1ca6bef4d67ef7f4c4c78a6d7
use std::cmp::Ordering; use std::collections::BinaryHeap; use std::fmt::{self, Display, Formatter}; use std::mem; use edb::{CfName, IterOptions, Iterable, Iteron, CausetEngine, Causet_WRITE, LARGE_CausetS}; use ekvproto::meta_timeshare::Brane; use ekvproto::meta_timeshare::BraneEpoch; use ekvproto::fidel_timeshare::...
use std::cmp::Ordering; use std::collections::BinaryHeap; use std::fmt::{self, Display, Formatter}; use std::mem; use edb::{CfName, IterOptions, Iterable, Iteron, CausetEngine, Causet_WRITE, LARGE_CausetS}; use ekvproto::meta_timeshare::Brane; use ekvproto::meta_timeshare::BraneEpoch; use ekvproto::fidel_timeshare::...
} impl<E, S> Runnable for Runner<E, S> where E: CausetEngine, S: CasualRouter<E>, { type Task = Task; fn run(&mut self, task: Task) { match task { Task::SplitCheckTask { brane, auto_split, policy, } => self.check_split(&b...
fn change_causet(&mut self, change: ConfigChange) { info!( "split check config fideliod"; "change" => ?change ); self.causet.fidelio(change); }
function_block-full_function
[ { "content": "fn last_key_of_brane(db: &impl CausetEngine, brane: &Brane) -> Result<Option<Vec<u8>>> {\n\n let spacelike_key = tuplespaceInstanton::enc_spacelike_key(brane);\n\n let lightlike_key = tuplespaceInstanton::enc_lightlike_key(brane);\n\n let mut last_key = None;\n\n\n\n let iter_opt = Ite...
Rust
src/senet/renderer.rs
raybritton/rust_games_proto
5268bf7d37836d7e7bc1038ebbf49abdee1c649e
use crate::boards::idx_coord::BoardCoord; use crate::boards::{board_cols, board_rows}; use crate::constants::colors::{ BROWN, CREAM, LIGHT_BLUE, LIGHT_GRAY, PIECE_COMPUTER, PIECE_HUMAN, RED, WHITE, }; use crate::constants::Direction; use crate::senet::rules::{HOUSE_BEAUTY, HOUSE_HAPPINESS, HOUSE_REBIRTH, HOUSE_WATE...
use crate::boards::idx_coord::BoardCoord; use crate::boards::{board_cols, board_rows}; use crate::constants::colors::{ BROWN, CREAM, LIGHT_BLUE, LIGHT_GRAY, PIECE_COMPUTER, PIECE_HUMAN, RED, WHITE, }; use crate::constants::Direction; use crate::senet::rules::{HOUSE_BEAUTY, HOUSE_HAPPINESS, HOUSE_REBIRTH, HOUSE_WATE...
; if let Some((mesh, colour, offset)) = result { let pos = Point::from(BoardCoord::from(idx)) .multiply(cell_size, cell_size) .offset_point(offset); mesh_helper.draw_coloured_mesh(ctx, mesh, pos, colour); } }); if state.play_state.is_eithe...
match square { Square::Empty => None, Square::Human => Some((human.as_ref(), PIECE_HUMAN, board_start)), Square::Computer => Some(( computer.as_ref(), PIECE_COMPUTER, board_start.offset(cell_size * 0.16, cell_size * 0.15), )...
if_condition
[ { "content": "fn render(ctx: &mut Context, mesh_helper: &mut MeshHelper, state: &State) -> GameResult<()> {\n\n let menu_start = pt(34., 100.);\n\n let cursor_start = pt(16., 100.);\n\n let cursor = mesh_helper.make_triangle(ctx, 12., 12., Direction::Right)?;\n\n\n\n mesh_helper.draw_mesh(\n\n ...
Rust
mmids-core/src/endpoints/rtmp_server/actor/tests/rtmp_client.rs
AircastDev/mmids
c304d67d1498f7526e5186d315f07986aade1984
use crate::net::tcp::{OutboundPacket, RequestFailureReason, TcpSocketRequest, TcpSocketResponse}; use crate::net::ConnectionId; use crate::test_utils; use bytes::Bytes; use rml_rtmp::handshake::{Handshake, HandshakeProcessResult, PeerType}; use rml_rtmp::sessions::{ ClientSession, ClientSessionConfig, ClientSession...
use crate::net::tcp::{OutboundPacket, RequestFailureReason, TcpSocketRequest, TcpSocketResponse}; use crate::net::ConnectionId; use crate::test_utils; use bytes::Bytes; use rml_rtmp::handshake::{Handshake, HandshakeProcessResult, PeerType}; use rml_rtmp::sessions::{ ClientSession, ClientSessionConfig, ClientSession...
pub async fn accept_port_request(&mut self, port: u16, use_tls: bool) { let request = test_utils::expect_mpsc_response(&mut self.socket_manager_receiver).await; match request { TcpSocketRequest::OpenPort { port: requested_port, use_tls: requested_tls, ...
t (sender, receiver) = unbounded_channel(); let client = RtmpTestClient { socket_manager_receiver: receiver, socket_manager_response_sender: None, port: None, connection: None, }; (client, sender) }
function_block-function_prefixed
[ { "content": "/// Quick function to create an un-named gstreamer element, while providing a consumable error\n\n/// if that fails.\n\npub fn create_gst_element(name: &str) -> Result<Element> {\n\n ElementFactory::make(name, None).with_context(|| format!(\"Failed to create element '{}'\", name))\n\n}\n\n\n", ...
Rust
rafx-framework/src/visibility/visibility_object_arc.rs
aclysma/renderer_prototype
a274b82c873c0ec7f9d6c3376cd054bfccfe3895
use crate::render_features::RenderObjectHandle; use crate::visibility::visibility_object_allocator::VisibilityObjectId; use crate::visibility::ObjectId; use crossbeam_channel::Sender; use glam::{Quat, Vec3}; use rafx_visibility::geometry::Transform; use rafx_visibility::{ AsyncCommand, ModelHandle, PolygonSoup, Vis...
use crate::render_features::RenderObjectHandle; use crate::visibility::visibility_object_allocator::VisibilityObjectId; use crate::visibility::ObjectId; use crossbeam_channel::Sender; use glam::{Quat, Vec3}; use rafx_visibility::geometry::Transform; use rafx_visibility::{ AsyncCommand, ModelHandle, PolygonSoup, Vis...
#[allow(dead_code)] pub(super) fn set_zone( &self, zone: Option<ZoneHandle>, ) -> &Self { self.commands .send(AsyncCommand::SetObjectZone(self.handle, zone)) .expect("Unable to send SetObjectZone command."); self } pub fn object_id(&self) ->...
pub fn new( object_id: ObjectId, render_objects: Vec<RenderObjectHandle>, handle: VisibilityObjectHandle, commands: Sender<AsyncCommand>, ) -> Self { Self { commands, handle, object_id, render_objects, } }
function_block-full_function
[ { "content": "/// Call when winit sends an event\n\npub fn handle_sdl2_event(\n\n event: &Event,\n\n input_state: &mut InputState,\n\n) {\n\n let _is_close_requested = false;\n\n\n\n match event {\n\n Event::KeyDown {\n\n keycode, repeat: _, ..\n\n } => handle_keyboard_event...
Rust
core/bin/zksync_api/src/api_server/rest/v02/block.rs
w2k-star-forks/zksync
28b7402198a0eb5201f15e35183a73d4f6b983ca
use std::str::FromStr; use std::time::Instant; use actix_web::{web, Scope}; use zksync_api_types::v02::{ block::{BlockInfo, BlockStatus}, pagination::{parse_query, ApiEither, BlockAndTxHash, Paginated, PaginationQuery}, transaction::{Transaction, TxData, TxHashSerializeWrapper}, }; use zksync_crypto::{c...
use std::str::FromStr; use std::time::Instant; use actix_web::{web, Scope}; use zksync_api_types::v02::{ block::{BlockInfo, BlockStatus}, pagination::{parse_query, ApiEither, BlockAndTxHash, Paginated, PaginationQuery}, transaction::{Transaction, TxData, TxHashSerializeWrapper}, }; use zksync_crypto::{c...
async fn block_page( &self, query: PaginationQuery<ApiEither<BlockNumber>>, ) -> Result<Paginated<BlockInfo, BlockNumber>, Error> { let mut storage = self.pool.access_storage().await.map_err(Error::storage)?; storage.paginate_checked(&query).await } async fn transactio...
n { "lastCommitted" => self .get_last_committed_block_number() .await .map_err(Error::storage), "lastFinalized" => self .get_last_finalized_block_number() .await .map_e...
function_block-function_prefixed
[ { "content": "pub fn fr_into_u32_low(value: Fr) -> u32 {\n\n let mut be_bytes = [0u8; 32];\n\n value\n\n .into_repr()\n\n .write_be(be_bytes.as_mut())\n\n .expect(\"Write value bytes\");\n\n u32::from_be_bytes([be_bytes[28], be_bytes[29], be_bytes[30], be_bytes[31]])\n\n}\n\n\n\n//...
Rust
lib/src/nyengine_audio/src/lib.rs
NyantasticUwU/nyengine
b6a47d2bfb101366eeda1b318e66f09d37317688
mod stream; use crate::stream::OStream; use rodio::{Decoder, OutputStream, OutputStreamHandle, Sample, Sink, Source}; use std::{ ffi::CStr, fmt::Debug, fs::File, io::BufReader, os::raw::{c_char, c_float, c_int, c_void}, ptr, }; #[no_mangle] pub unsafe extern "C" fn na_new_default_ostream() -> *...
mod stream; use crate::stream::OStream; use rodio::{Decoder, OutputStream, OutputStreamHandle, Sample, Sink, Source}; use std::{ ffi::CStr, fmt::Debug, fs::File, io::BufReader, os::raw::{c_char, c_float, c_int, c_void}, ptr, }; #[no_mangle] pub unsafe extern "C" fn na_new_default_ostream() -> *...
false } #[no_mangle] pub unsafe extern "C" fn na_add_audio_to_sink( file_name: *const c_char, sink: *mut c_void, should_loop: c_int, ) -> c_int { if let Ok(file_name_str) = CStr::from_ptr(file_name).to_str() { if let Ok(file) = File::open(file_name_str) { ...
Handle)) { return Box::into_raw(Box::new(sink)) as *mut c_void; } } ptr::null_mut::<c_void>() } unsafe fn append_to_sink<D>(sink: *mut c_void, decoder: D) -> bool where D: Source + Send + 'static, D::Item: Debug + Sample + Send, { if !sink.is_null() { let sink: *mut...
random
[]
Rust
src/runner/command.rs
doy/nbsh
4151ab7aab939a12721a0f4207c87b5c09ace339
use crate::runner::prelude::*; pub struct Command { inner: Inner, exe: std::path::PathBuf, redirects: Vec<crate::parse::Redirect>, pre_exec: Option< Box<dyn FnMut() -> std::io::Result<()> + Send + Sync + 'static>, >, } impl Command { pub fn new(exe: crate::parse::Exe, io: super::builti...
use crate::runner::prelude::*; pub struct Command { inner: Inner, exe: std::path::PathBuf, redirects: Vec<crate::parse::Redirect>, pre_exec: Option< Box<dyn FnMut() -> std::io::Result<()> + Send + Sync + 'static>, >, } impl Command { pub fn new(exe: crate::parse::Exe, io: super::builti...
F: 'static + FnMut() -> std::io::Result<()> + Send + Sync, { self.pre_exec = Some(Box::new(f)); } pub fn spawn(self, env: &Env) -> Result<Child> { let Self { inner, exe, redirects, pre_exec, } = self; #[allow(clippy::...
th_buf(); let redirects = exe.redirects().to_vec(); let mut cmd = tokio::process::Command::new(exe.exe()); cmd.args(exe.args()); Self { inner: Inner::Binary(cmd), exe: exe_path, redirects, pre_exec: None, } } pub fn new_bui...
random
[ { "content": "pub fn setpgid_child(pg: Option<nix::unistd::Pid>) -> std::io::Result<()> {\n\n nix::unistd::setpgid(PID0, pg.unwrap_or(PID0))?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/runner/sys.rs", "rank": 0, "score": 130883.43219710211 }, { "content": "pub fn io_error(e: &std::io::...