lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/platform/linux/mod.rs
eladyn/souvlaki
29d1edbc09482f2c30f1b837de95f64a4eda1089
#![cfg(target_os = "linux")] use crate::{ MediaControlEvent, MediaMetadata, MediaPlayback, MediaPosition, PlatformConfig, SeekDirection, }; use std::collections::HashMap; use std::convert::From; use std::convert::{TryFrom, TryInto}; use std::sync::{mpsc, Arc, Mutex}; use std::thread::{self, JoinHandle}; use std::t...
#![cfg(target_os = "linux")] use crate::{ MediaControlEvent, MediaMetadata, MediaPlayback, MediaPosition, PlatformConfig, SeekDirection, }; use std::collections::HashMap; use std::convert::From; use std::convert::{TryFrom, TryInto}; use std::sync::{mpsc, Arc, Mutex}; use std::thread::{self, JoinHandle}; use std::t...
; Ok(()) } pub fn detach(&mut self) -> Result<(), Error> { if let Some(ServiceThreadHandle { event_channel, thread, }) = self.thread.take() { event_channel.send(InternalEvent::Kill).unwrap(); thread.join().unwrap(); } ...
Some(ServiceThreadHandle { event_channel, thread: thread::spawn(move || { run_service(dbus_name, friendly_name, event_handler, rx).unwrap() }), })
call_expression
[ { "content": "fn main() {\n\n #[cfg(target_os = \"macos\")]\n\n build_macos();\n\n}\n", "file_path": "build.rs", "rank": 7, "score": 37235.08535307792 }, { "content": "fn main() {\n\n let event_loop = EventLoop::new();\n\n #[allow(unused_variables)]\n\n let window = WindowBuil...
Rust
minitt-util/src/repl.rs
ice1000/minitt-rs
ff8b37516990be1267dd23b7bc86f436ac5557f2
use std::fmt::{Display, Error, Formatter}; use std::io::{stdin, stdout, Write}; use std::path::PathBuf; use rustyline::completion::{Completer, FilenameCompleter, Pair}; use rustyline::error::ReadlineError; use rustyline::highlight::Highlighter; use rustyline::hint::Hinter; use rustyline::validate::Validator; use rusty...
use std::fmt::{Display, Error, Formatter}; use std::io::{stdin, stdout, Write}; use std::path::PathBuf; use rustyline::completion::{Completer, FilenameCompleter, Pair}; use rustyline::error::ReadlineError; use rustyline::highlight::Highlighter; use rustyline::hint::Hinter; use rustyline::validate::Validator; use rusty...
pub fn repl<TCS>( tcs: TCS, prompt: &str, repl_kind: ReplEnvType, create_editor: impl FnOnce() -> Editor<MiniHelper>, history: impl FnOnce() -> Option<PathBuf>, welcome_message: impl FnOnce(ReplEnvType) -> (), work: impl Fn(TCS, ReplEnvType, &str) -> Option<TCS>, ) { use ReplEnvType::*...
k; }; } Err(ReadlineError::Interrupted) => {} Err(ReadlineError::Eof) => { println!("Interrupted"); break; } Err(err) => { println!("Error: {:?}", err); break; } ...
function_block-function_prefixed
[ { "content": "fn eval_impl(ctx: Telescope, line: &str, map: impl FnOnce(Value) -> ()) {\n\n parse_str_err_printed(line)\n\n .map_err(|()| TCE::Textual(\"\".to_string()))\n\n .map(|ast| ast.eval(ctx))\n\n .map(map)\n\n .unwrap_or_else(|err| eprintln!(\"{}\", err))\n\n}\n\n\n", ...
Rust
src/wrappers/unreal/camera.rs
edmiester777/bakkesmod-rust
d7ef3861cfa9f80c8eaa2bbf443028361b14287e
use crate::wrappers::{*, structs::*, unreal::*}; use super::*; pub struct CameraWrapper(pub usize); impl_object!(CameraWrapper); impl Camera for CameraWrapper {} impl CameraX for CameraWrapper {} impl BaseCamera for CameraWrapper {} impl Actor for CameraWrapper {} pub trait Camera : CameraX { fn get_location(&self)...
use crate::wrappers::{*, structs::*, unreal::*}; use super::*; pub struct CameraWrapper(pub usize); impl_object!(CameraWrapper); impl Camera for CameraWrapper {} impl CameraX for CameraWrapper {} impl BaseCamera for CameraWrapper {} impl Actor for CameraWrapper {} pub trait Camera : CameraX { fn get_location(&self)...
fn update_swivel(&self, delta_time: f32) { unsafe { Camera_TA_UpdateSwivel(self.addr(), delta_time); } } fn get_default_fov_offset(&self) -> f32 { unsafe { Camera_TA_GetDefaultFOVOffset(self.addr()) } } fn get_default_view_height_offset(&self)...
fn get_desired_swivel(&self, look_up: f32, look_right: f32) -> Rotator { unsafe { let mut result = Rotator::new(); let result_ptr: *mut Rotator = &mut result as *mut Rotator; Camera_TA_GetDesiredSwivel(self.addr(), look_up, look_right, result_ptr); result ...
function_block-full_function
[ { "content": "pub trait BaseCamera : Actor {\n\n fn get_default_fov(&self) -> f32 {\n\n unsafe {\n\n Camera_Get_DefaultFOV(self.addr())\n\n }\n\n }\n\n fn get_b_locked_fov(&self) -> bool {\n\n unsafe {\n\n Camera_Get_bLockedFOV(self.addr())\n\n }\n\n ...
Rust
src/widget_schemes/gleam.rs
fltk-rs/fltk-theme
8e792be048cb6c868c66f526bffd7782f52f54ee
use super::*; fn frame_rect(x: i32, y: i32, w: i32, h: i32, bc: Color) { set_draw_color(Color::color_average(Color::Black, Color::BackGround, 0.1)); draw_line(x, y, x + w, y); draw_line(x + w, y, x + w, y + h); draw_line(x + w, y + h, x, y + h); draw_line(x, y + h, x, y); } fn shade_rect_up(x...
use super::*; fn frame_rect(x: i32, y: i32, w: i32, h: i32, bc: Color) { set_draw_color(Color::color_average(Color::Black, Color::BackGround, 0.1)); draw_line(x, y, x + w, y); draw_line(x + w, y, x + w, y + h); draw_line(x + w, y + h, x, y + h); draw_line(x, y + h, x, y); } fn shade_rect_up(x...
bc, color.darker(), 0.65, ))); draw_line(x, y + 1, x + w, y + 1); draw_line(x, y + 1, x, y + h - 2); set_draw_color(activated_color(Color::color_average( bc, color.darker(), 0.85, ))); draw_line(x + 1, y + 2, x + w, y + 2); draw_line(x + 1, y ...
{ if k >= 0.90 { break; } j += 1; set_draw_color(activated_color(Color::color_average(bc, Color::White, k))); draw_line( x, y + j + third as i32 - 1, x + w - 1, y + j + third as i32 - 1, ); k -= step_size...
random
[ { "content": "fn frame_round(x: i32, y: i32, w: i32, h: i32, c: &str, bc: Color) {\n\n let b = c.len() / 4 + 1;\n\n let mut bc = bc;\n\n if !app::draw_frame_active() {\n\n bc = bc.inactive();\n\n }\n\n\n\n if w == h {\n\n for i in b..1 {\n\n let x = x + 1;\n\n ...
Rust
ara-tide-app/src/core/user/service.rs
mmrath/ara
f62eeac56a8ae3885a243e22314e6aae1fffdbc7
use failure::{Error, Fail}; use ara_common::config::AppConfig; use ara_common::context::{Context, UnauthContext}; use ara_common::template; use ara_common::utils::{argon2_hash, argon2_verify, new_uuid, sha256_hex, sha512}; use ara_error::{unexpected_error, AppError, HttpStatus}; use ara_model::db::{tx, Connection}; us...
use failure::{Error, Fail}; use ara_common::config::AppConfig; use ara_common::context::{Context, UnauthContext}; use ara_common::template; use ara_common::utils::{argon2_hash, argon2_verify, new_uuid, sha256_hex, sha512}; use ara_error::{unexpected_error, AppError, HttpStatus}; use ara_model::db::{tx, Connection}; us...
} fn create_email_body(user: &UserRecord, token: &str, base_url: &str) -> Result<String, Error> { use serde_json::value::Map; let mut data = Map::new(); data.insert("base_url".to_owned(), json!(base_url)); data.insert("user".to_owned(), json!(user)); data.insert("token".to_owned(), json!(token)); ...
tx(context.db(), |conn| { debug!("User to register {:?}", user_ac); let config = AppConfig::get(); let maybe_user = User::find_by_username(conn, &*user_ac.email)?; if maybe_user.is_some() { let user = maybe_user.unwrap(); if !user.active { info!("...
call_expression
[ { "content": "fn create_email_body(user: &UserRecord, token: &str, base_url: &str) -> Result<String, Error> {\n\n use serde_json::json;\n\n use serde_json::value::Map;\n\n\n\n let mut data = Map::new();\n\n\n\n data.insert(\"base_url\".to_owned(), json!(base_url));\n\n data.insert(\"user\".to_own...
Rust
src/main.rs
m42e/zsh-histdb-skim
385c039f4338963e4cada1ab9c3035e1d969a552
extern crate skim; mod environment; mod history; mod location; mod query; mod title; use crate::environment::*; use crate::history::History; use crate::location::Location; use crate::query::build_query_string; use crate::title::generate_title; use rusqlite::{Connection, OpenFlags, Result}; use skim::prelude::*; use s...
extern crate skim; mod environment; mod history; mod location; mod query; mod title; use crate::environment::*; use crate::history::History; use crate::location::Location; use crate::query::build_query_string; use crate::title::generate_title; use rusqlite::{Connection, OpenFlags, Result}; use skim::prelude::*; use s...
electionResult { selected_cmd: None, abort: true, }; } Key::Enter => { return SelectionResult { selected_cmd: Some(format!( "{}", ((*sel.selected_items[0])....
item.send(Arc::new("Cannot open database")); drop(tx_item); return; } let conn = conn_res.unwrap(); let s = build_query_string(&location, grouped); let stmt_result = conn.prepare(&s); if stmt_result.is_err() { let _ = tx_item.send(Arc::new(format!("Cannot get result from dat...
random
[ { "content": "pub fn build_query_string(theloc: &Location, grouped: bool) -> String {\n\n let mut query = String::from(\"select history.id as id, commands.argv as cmd,\");\n\n if !grouped {\n\n query.push_str(\" start_time\")\n\n } else {\n\n query.push_str(\" max(start_time)\")\n\n }\...
Rust
crates/bevy_reflect/bevy_reflect_derive/src/derive_data.rs
thibaudio/bevy
dbd856de71a3a00bfd30bd3113147819b97688a6
use crate::container_attributes::ReflectTraits; use crate::field_attributes::{parse_field_attrs, ReflectFieldAttr}; use crate::utility::get_bevy_reflect_path; use crate::{REFLECT_ATTRIBUTE_NAME, REFLECT_VALUE_ATTRIBUTE_NAME}; use syn::{Data, DataStruct, DeriveInput, Field, Fields, Generics, Ident, Meta, Path}; pub(cra...
use crate::container_attributes::ReflectTraits; use crate::field_attributes::{parse_field_attrs, ReflectFieldAttr}; use crate::utility::get_bevy_reflect_path; use crate::{REFLECT_ATTRIBUTE_NAME, REFLECT_VALUE_ATTRIBUTE_NAME}; use syn::{Data, DataStruct, DeriveInput, Field, Fields, Generics, Ident, Meta, Path}; pub(cra...
let mut errors: Option<syn::Error> = None; output.fields = fields .iter() .enumerate() .map(|(index, field)| { let attrs = parse_field_attrs(&field.attrs).unwrap_or_else(|err| { if let Some(ref mut errors) = errors { ...
let fields = match &input.data { Data::Struct(DataStruct { fields: Fields::Named(fields), .. }) => { if !force_reflect_value { output.derive_type = DeriveType::Struct; } &fields.named ...
assignment_statement
[]
Rust
src/pitch_class.rs
noeddl/ukebox
2c910607ce8df6a37e09941901d66666f8f32315
#![allow(clippy::suspicious_arithmetic_impl)] use std::ops::{Add, Sub}; use crate::Semitones; const PITCH_CLASS_COUNT: Semitones = 12; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum PitchClass { C, CSharp, D, DSharp, E, F, FSharp, G, GSharp, A, ASha...
#![allow(clippy::suspicious_arithmetic_impl)] use std::ops::{Add, Sub}; use crate::Semitones; const PITCH_CLASS_COUNT: Semitones = 12; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum PitchClass { C, CSharp, D, DSharp, E, F, FSharp, G, GSharp, A, ASha...
} impl Add<Semitones> for PitchClass { type Output = Self; fn add(self, n: Semitones) -> Self { let v = self as Semitones + n; Self::from(v) } } impl Sub for PitchClass { type Output = Semitones; fn sub(self, other: Sel...
fn from(n: Semitones) -> Self { use PitchClass::*; let v = n % PITCH_CLASS_COUNT; match v { 0 => C, 1 => CSharp, 2 => D, 3 => DSharp, 4 => E, 5 => F, 6 => FSharp, ...
function_block-full_function
[ { "content": "#[derive(StructOpt)]\n\nenum Subcommand {\n\n /// Chord chart lookup\n\n Chart {\n\n /// Print out all voicings of <chord> that fulfill the given conditions\n\n #[structopt(short, long)]\n\n all: bool,\n\n #[structopt(flatten)]\n\n voicing_opts: VoicingOpts...
Rust
src/uniprot/model/feature.rs
althonos/uniprot.rs
f0fc6308e1cca4933935fe15bcfd229642b1daef
use std::io::BufRead; use std::str::FromStr; use quick_xml::events::BytesStart; use quick_xml::Reader; use crate::error::Error; use crate::error::InvalidValue; use crate::parser::utils::attributes_to_hashmap; use crate::parser::utils::decode_attribute; use crate::parser::utils::get_evidences; use crate::parser::FromX...
use std::io::BufRead; use std::str::FromStr; use quick_xml::events::BytesStart; use quick_xml::Reader; use crate::error::Error; use crate::error::InvalidValue; use crate::parser::utils::attributes_to_hashmap; use crate::parser::utils::decode_attribute; use crate::parser::utils::get_evidences; use crate::parser::FromX...
alPeptide), "site" => Ok(Site), "splice variant" => Ok(Site), "strand" => Ok(Strand), "topological domain" => Ok(TopologicalDomain), "transit peptide" => Ok(TransitPeptide), "transmembrane region" => Ok(TransmembraneRegion), "turn" => O...
{ "active site" => Ok(ActiveSite), "binding site" => Ok(BindingSite), "calcium-binding region" => Ok(CalciumBindingRegion), "chain" => Ok(Chain), "coiled-coil region" => Ok(CoiledCoilRegion), "compositionally biased region" => Ok(CompositionallyBi...
random
[ { "content": "#[inline(always)]\n\npub fn parse<B: std::io::BufRead>(reader: B) -> self::uniprot::Parser<B> {\n\n self::uniprot::parse(reader)\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 135573.73087128642 }, { "content": "/// Decode the attribute `name` from `event.attributes...
Rust
src/auto/content_disposition.rs
vhdirk/gmime-rs
1d02cf114bfcd4c4d9c09e457454d14b8dbe0293
use crate::FormatOptions; use crate::ParamList; use crate::ParserOptions; use glib::object::IsA; use glib::translate::*; use std::fmt; glib::wrapper! { #[doc(alias = "GMimeContentDisposition")] pub struct ContentDisposition(Object<ffi::GMimeContentDisposition, ffi::GMimeContentDispositionClass>); match ...
use crate::FormatOptions; use crate::ParamList; use crate::ParserOptions; use glib::object::IsA; use glib::translate::*; use std::fmt; glib::wrapper! { #[doc(alias = "GMimeContentDisposition")] pub struct ContentDisposition(Object<ffi::GMimeContentDisposition, ffi::GMimeContentDispositionClass>); match ...
} } fn parameters(&self) -> Option<ParamList> { unsafe { from_glib_none(ffi::g_mime_content_disposition_get_parameters( self.as_ref().to_glib_none().0, )) } } fn is_attachment(&self) -> bool { unsafe { from_glib(ffi::...
from_glib_none(ffi::g_mime_content_disposition_get_parameter( self.as_ref().to_glib_none().0, name.to_glib_none().0, ))
call_expression
[ { "content": "fn get_var(name: &str, default: &str) -> Result<Vec<String>, Box<dyn Error>> {\n\n match env::var(name) {\n\n Ok(value) => Ok(shell_words::split(&value)?),\n\n Err(env::VarError::NotPresent) => Ok(shell_words::split(default)?),\n\n Err(err) => Err(format!(\"{} {}\", name, e...
Rust
src/network_interface/mod.rs
openhab-nodes/wifi-captive-rs
4e7d9bf62f881565679ec0c973de1106cfd04203
mod connection; mod signal_stream; pub mod dbus_tokio { pub use super::connection::*; pub use super::signal_stream::SignalStream; } use crate::CaptivePortalError; use core::fmt; use serde::Serialize; use std::convert::TryFrom; pub type SSID = String; #[derive(Serialize, Clone, Debug)] pub struct WifiConne...
mod connection; mod signal_stream; pub mod dbus_tokio { pub use super::connection::*; pub use super::signal_stream::SignalStream; } use crate::CaptivePortalError; use core::fmt; use serde::Serialize; use std::convert::TryFrom; pub type S
sphrase: String, identity: Option<String>, mode: Security, ) -> Result<AccessPointCredentials, CaptivePortalError> { match mode { Security::ENTERPRISE => Ok(AccessPointCredentials::Enterprise { identity: identity.ok_or(CaptivePortalError::NoSharedKeyProvided)?, passphrase, ...
SID = String; #[derive(Serialize, Clone, Debug)] pub struct WifiConnection { pub ssid: SSID, pub hw: String, pub security: &'static str, pub strength: u8, pub frequency: u32, pub is_own: bool, } #[derive(Serialize, Debug, Copy, Clone)] pub enum WifiConnectionEventType ...
random
[ { "content": "pub trait Connection {\n\n fn update(\n\n &self,\n\n properties: ::std::collections::HashMap<\n\n &str,\n\n ::std::collections::HashMap<&str, arg::Variant<Box<dyn arg::RefArg>>>,\n\n >,\n\n ) -> nonblock::MethodReply<()>;\n\n fn update_unsaved(\n...
Rust
examples/test-with-pin-non-rk/src/main.rs
shimunn/ctap-hid-fido2
3357a7777986ffc89dae0e979f6549f957a2f3d0
use anyhow::Result; use ctap_hid_fido2::get_assertion_params::Extension as Gext; use ctap_hid_fido2::make_credential_params::CredentialSupportedKeyType; use ctap_hid_fido2::make_credential_params::Extension as Mext; use ctap_hid_fido2::MakeCredentialArgsBuilder; use ctap_hid_fido2::{verifier, Cfg, Key}; fn main() -> R...
use anyhow::Result; use ctap_hid_fido2::get_assertion_params::Extension as Gext; use ctap_hid_fido2::make_credential_params::CredentialSupportedKeyType; use ctap_hid_fido2::make_credential_params::Extension as Mext; use ctap_hid_fido2::MakeCredentialArgsBuilder; use ctap_hid_fido2::{verifier, Cfg, Key}; fn main() -> R...
fn with_key_type( cfg: &Cfg, rpid: &str, pin: &str, key_type: CredentialSupportedKeyType, ) -> Result<()> { println!("----- with_key_type ({:?}) -----", key_type); println!("- Register"); let challenge = verifier::create_challenge(); let make_credential_args = MakeCredentialArgsBuild...
println!("-- Verify Assertion"); let is_success = verifier::verify_assertion( rpid, &verify_result.credential_publickey_der, &challenge, &assertions[0], ); if is_success { println!("-- Verify Assertion Success"); } else { println!("-- ! Verify Assertion Fa...
function_block-function_prefix_line
[ { "content": "fn discoverable_credentials(cfg: &Cfg, rpid: &str, pin: &str) -> Result<()> {\n\n println!(\"----- discoverable_credentials -----\");\n\n\n\n println!(\"- Register\");\n\n let challenge = verifier::create_challenge();\n\n let rkparam =\n\n PublicKeyCredentialUserEntity::new(Some...
Rust
src/idml_parser/mod.rs
askepen/idml-to-pdf
4f4aa905e044414ad2e93da2ca96def3cf7a702d
pub mod designmap_parser; pub mod fonts_parser; mod formats; pub mod graphic_parser; pub mod spread_parser; #[macro_use] pub mod styles; pub mod story_parser; pub mod styles_parser; use derive_getters::Getters; use serde::Deserialize; use std::collections::HashMap; use std::iter::FromIterator; use std::path::{Path, Pa...
pub mod designmap_parser; pub mod fonts_parser; mod formats; pub mod graphic_parser; pub mod spread_parser; #[macro_use] pub mod styles; pub mod story_parser; pub mod styles_parser; use derive_getters::Getters; use serde::Deserialize; use std::collections::HashMap; use std::iter::FromIterator; use std::path::{Path, Pa...
pub fn master_spread_with_id(&self, id: &str) -> Option<&Spread> { self.master_spreads.get(id) } } fn parse_design_map(path: &Path) -> Result<DesignMap, quick_xml::DeError> { let mut xml_path = PathBuf::from(path); xml_path.push("designmap.xml"); designmap_parser::parse_designmap_from_pat...
urces, master_spreads: master_spreads, spreads: spreads, stories: stories, xml: IdmlXml { backing_story: vec!["BackingStory dummy".to_string()], mapping: vec!["Mapping dummy".to_string()], tags: vec!["Tags dummy".to_string()...
function_block-function_prefixed
[ { "content": "pub fn parse_designmap_from_path(path: &Path) -> Result<DesignMap, DeError> {\n\n let xml = std::fs::read_to_string(path).unwrap();\n\n let document: Document = quick_xml::de::from_str(xml.as_str())?;\n\n\n\n let re = Regex::new(r\"_(.+)\\.xml\").unwrap();\n\n let path_to_id = |path| r...
Rust
src/parse/slice.rs
cmyr/pinot
7001393e7ef824ca99a7ed60a7592a9950a88230
use super::ReadData; use core::ops::Range; #[derive(Copy, Clone)] pub struct Slice<'a, T: ReadData> { data: &'a [u8], len: usize, _p: core::marker::PhantomData<T>, } impl<'a, T: ReadData> Slice<'a, T> { pub(crate) fn new(data: &'a [u8]) -> Self { Self { data, len: dat...
use super::ReadData; use core::ops::Range; #[derive(Copy, Clone)] pub struct Slice<'a, T: ReadData> { data: &'a [u8], len: usize, _p: core::marker::
_p: core::marker::PhantomData {}, } } pub fn len(&self) -> usize { self.len } pub fn is_empty(&self) -> bool { self.len == 0 } pub fn get(&self, index: usize) -> Option<T> { if index >= self.len { None } else { ...
PhantomData<T>, } impl<'a, T: ReadData> Slice<'a, T> { pub(crate) fn new(data: &'a [u8]) -> Self { Self { data, len: data.len() / T::SIZE,
random
[ { "content": "/// Trait for types that can be read from a big endian encoded buffer.\n\npub trait ReadData: Sized + Copy + Clone {\n\n /// The encoded size of `Self`.\n\n const SIZE: usize = core::mem::size_of::<Self>();\n\n\n\n /// Reads `Self` from the buffer at the specified offset. Returns `None`\n...
Rust
src/mb_std/mb_ptr_resolver.rs
shady831213/mailbox_rs
9b809e9bceb54c5478f09f3356936cb15b431a68
use super::mb_share_mem::*; use crate::mb_rpcs::*; use std::io::{BufRead, BufReader, Read, Write}; use std::sync::Arc; use std::sync::Mutex; pub trait MBPtrReader: Read { fn read_slice<T: Sized + Copy>(&mut self, data: &mut [T]); fn read_sized<T: Sized>(&mut self, data: &mut T); } pub trait MBPtrWriter: Write...
use super::mb_share_mem::*; use crate::mb_rpcs::*; use std::io::{BufRead, BufReader, Read, Write}; use std::sync::Arc; use std::sync::Mutex; pub trait MBPtrReader: Read { fn read_slice<T: Sized + Copy>(&mut self, data: &mut [T]); fn read_sized<T: Sized>(&mut self, data: &mut T); } pub trait MBPtrWriter: Write...
sh(&mut self) -> std::io::Result<()> { Ok(()) } } pub struct MBSMPtrResolver<SM: MBShareMem> { sm: Arc<Mutex<SM>>, } impl<SM: MBShareMem> MBSMPtrResolver<SM> { pub fn new(sm: &Arc<Mutex<SM>>) -> MBSMPtrResolver<SM> { MBSMPtrResolver { sm: sm.clone() } } } impl<SM: MBShareMem> MBPtrResol...
opy_from_slice(std::slice::from_raw_parts( self.ptr as *const T as *const u8, std::mem::size_of::<T>(), )) } } } impl Read for MBLocalPtrReader { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { let len = buf.len(); u...
random
[ { "content": "pub trait MBAsyncRPC<RA: MBPtrReader, WA: MBPtrWriter, R: MBPtrResolver<READER = RA, WRITER = WA>> {\n\n fn poll_cmd(\n\n &self,\n\n server_name: &str,\n\n r: &R,\n\n req: &MBReqEntry,\n\n cx: &mut Context,\n\n ) -> Poll<MBAsyncRPCResult>;\n\n fn do_cmd<...
Rust
tests/variable.rs
glugg23/rox
f766df6bc948b1a8db63d9d500b266017e3f6011
use std::process::Command; use std::str; #[test] fn duplicate_local() { let result = Command::new("cargo") .args(&[ "run", "-q", "--release", "--", "tests/resources/variable/duplicate_local.lox", ]) .output() .expect("Error...
use std::process::Command; use std::str; #[test] fn duplicate_local() { let result = Command::new("cargo") .args(&[ "run", "-q", "--release", "--", "tests/resources/variable/duplicate_local.lox", ]) .output() .expect("Error...
assert_eq!(str::from_utf8(&result.stdout).unwrap(), "nil\n"); assert!(result.status.success()); } #[test] fn redefine_global() { let result = Command::new("cargo") .args(&[ "run", "-q", "--release", "--", "tests/resources/variable/redefi...
let result = Command::new("cargo") .args(&[ "run", "-q", "--release", "--", "tests/resources/variable/redeclare_global.lox", ]) .output() .expect("Error while running variable/redeclare_global()");
assignment_statement
[ { "content": "#[test]\n\nfn only_line_comment_and_line() {\n\n let result = Command::new(\"cargo\")\n\n .args(&[\n\n \"run\",\n\n \"-q\",\n\n \"--release\",\n\n \"--\",\n\n \"tests/resources/comments/only_line_comment_and_line.lox\",\n\n ])...
Rust
lib/common/src/codegen.rs
tmzt/incrust
1686a34b8dc4d83847613c2bb252737a7aacf7cc
use syntax::ast; use syntax::codemap::{Span, DUMMY_SP}; use syntax::util::small_vector::SmallVector; use syntax::ext::base::{DummyResult, ExtCtxt, MacEager, MacResult}; use syntax::ext::build::AstBuilder; use syntax::ptr::P; use nodes::view_node::View; use nodes::template_node::Template; pub trait IntoViewItem { ...
use syntax::ast; use syntax::codemap::{Span, DUMMY_SP}; use syntax::util::small_vector::SmallVector; use syntax::ext::base::{DummyResult, ExtCtxt, MacEager, MacResult}; use syntax::ext::build::AstBuilder; use syntax::ptr::P; use nodes::view_node::View; use nodes::template_node::Template; pub trait IntoViewItem { ...
ter"); let block = { let mut out = Vec::new(); match lang { _ if lang == "html" => { self.write_output_stmts(ecx, &mut out, html_writer); }, ...
ng> { fn write_named_output<'cx>(&self, ecx: &'cx ExtCtxt, name: &str, ty: NamedOutputType, item: P<ast::Item>); } } pub mod output_string_writer { use std::iter::Iterator; use syntax::codemap::{DUMMY_SP, Span}; use syntax::ext::base::ExtCtxt; use syntax::ast; use super::lang::{Lang, Ht...
random
[ { "content": "pub fn render(main_fn: fn(html: &mut String, js: &mut String, head_tags: &mut String)) -> String {\n\n\n\n let mut page = String::new();\n\n let mut main_html = String::new();\n\n let mut main_js = String::new();\n\n let mut head_tags = String::new();\n\n\n\n // Render Rust and JS m...
Rust
src/rust/driver/vgmmeta.rs
h1romas4/libymfm.wasm
cc5bf55b965748c61b58eac20475caadb107893e
use nom::bytes::complete::{tag, take}; use nom::number::complete::{le_u16, le_u32, le_u8}; use nom::IResult; use crate::driver::gd3meta::{Gd3, parse_gd3}; use crate::driver::meta::Jsonlize; #[derive(Deserialize, Serialize, Default, Debug)] pub struct VgmHeader { pub eof: u32, pub version: u32, pub clock...
use nom::bytes::complete::{tag, take}; use nom::number::complete::{le_u16, le_u32, le_u8}; use nom::IResult; use crate::driver::gd3meta::{Gd3, parse_gd3}; use crate::driver::meta::Jsonlize; #[derive(Deserialize, Serialize, Default, Debug)] pub struct VgmHeader { pub eof: u32, pub version: u32, pub clock...
impl Jsonlize for VgmHeader {} #[cfg(test)] mod tests { use super::parse_vgm_meta; use super::Jsonlize; use std::fs::File; use std::io::Read; #[test] fn test_1() { parse("./docs/vgm/ym2612.vgm") } #[test] fn test_2() { parse("./docs/vgm/segapcm-2.vgm") } ...
pub(crate) fn parse_vgm_meta(vgmdata: &[u8]) -> Result<(VgmHeader, Gd3), &'static str> { let mut vgm_data_offset: usize = (u32::from_le_bytes(vgmdata[0x34..=0x37].try_into().unwrap()) + 0x34) as usize; if vgm_data_offset >= 0xff { vgm_data_offset = 0xff; } let mut header = [0_u8; 0x100...
function_block-full_function
[ { "content": "///\n\n/// parse_vgm_gd3\n\n///\n\npub fn parse_gd3(i: &[u8]) -> IResult<&[u8], Gd3> {\n\n let (i, _) = tag(\"Gd3 \")(i)?;\n\n let (i, _) = take(4usize)(i)?; // version\n\n let (i, _) = take(4usize)(i)?; // length\n\n\n\n let (i, track_name) = parse_utf16_until_null(i)?;\n\n let (i,...
Rust
src/crypto.rs
aaronwinter/ecc
d40a55804065f9f1b216fe3ad2d2cf89419faaf4
use std::rand; use std::default::Default; use num::{BigUint, Zero}; use num::bigint::RandBigInt; use fields::Field; use curves::{Curve, AffinePoint}; pub struct DiffieHellman; impl DiffieHellman { pub fn key_gen<C: Curve<F, G>, F: Field, G: Field>() -> (AffinePoint<C, F, G>, BigUint) { let mut rng = mat...
use std::rand; use std::default::Default; use num::{BigUint, Zero}; use num::bigint::RandBigInt; use fields::Field; use curves::{Curve, AffinePoint}; pub struct DiffieHellman; impl DiffieHellman { pub fn key_gen<C: Curve<F, G>, F: Field, G: Field>() -> (AffinePoint<C, F, G>, BigUint) { let mut rng = mat...
#[test] fn invalid_dh_exchange() { type Point = AffinePoint<C192<P192, R192>, P192, R192>; let (_, x): (Point, _) = DiffieHellman::key_gen(); let Y: Point = AffinePoint { x: FieldElem { limbs: Zero::zero() }, y: FieldElem { limbs: Zero::zero() } }; ...
fn valid_dh_exchange() { type Point = AffinePoint<C192<P192, R192>, P192, R192>; let (X, x): (Point, _) = DiffieHellman::key_gen(); let (Y, y): (Point, _) = DiffieHellman::key_gen(); let s1 = DiffieHellman::shared(&x, &Y).unwrap(); let s2 = DiffieHellman::shared(&y, &X).unwrap(...
function_block-full_function
[ { "content": "fn add_jacobian_to_affine<C: Curve<F, G>, F: Field, G: Field>(this: &JacobianPoint<C, F, G>, other: &AffinePoint<C, F, G>) -> JacobianPoint<C, F, G> {\n\n if this.is_zero() {\n\n (*other).to_jacobian()\n\n } else if other.is_zero() {\n\n (*this).clone()\n\n } else {\n\n ...
Rust
src/command/version.rs
DmitryDodzin/mol
2823b181912cd847cd6dd4d9de35b1d192c5afee
use std::collections::HashMap; use std::ffi::OsStr; use std::path::PathBuf; use std::sync::Arc; use anyhow::Context; use async_trait::async_trait; use clap::Parser; use tokio::fs; use mol_core::prelude::*; use super::{ExecutableCommand, ExecutableContext}; #[derive(Parser, Debug)] pub struct Version { #[clap(long...
use std::collections::HashMap; use std::ffi::OsStr; use std::path::PathBuf; use std::sync::Arc; use anyhow::Context; use async_trait::async_trait; use clap::Parser; use tokio::fs; use mol_core::prelude::*; use super::{ExecutableCommand, ExecutableContext}; #[derive(Parser, Debug)] pub struct Version { #[clap(long...
{:?}", changeset_path))?; bump.add( Changeset::<V>::parse(&raw_changeset) .with_context(|| format!("Unable to parse changeset at {:?}", changeset_path))?, package_graph, ); changeset_files_paths.push(changeset_path); } } } Ok(...
args: Vec<String>, } impl Version { async fn consume_changesets<V: VersionEditor>( changesets: &Changesets, package_graph: &PackageGraph<'_, V>, ) -> anyhow::Result<(Vec<PathBuf>, Bump<V>)> { let mut bump = Bump::default(); let mut changeset_files_paths = Vec::new(); let mut changeset_files = ...
random
[ { "content": "pub trait VersionEditor:\n\n AsChangelogFmt + Versioned + Clone + Default + Hash + FromStr + Ord\n\n{\n\n fn options() -> Vec<Self>;\n\n\n\n fn mask<'a>(mask: &str, version: &'a str) -> &'a str;\n\n\n\n fn r#match(mask: &str, version: &str) -> bool;\n\n}\n\n\n", "file_path": "crates/mol-co...
Rust
day20b/src/main.rs
LinAGKar/advent-of-code-2017-rust
770d655a32964585e660fdd009222f44dcc65377
extern crate regex; use regex::Regex; use std::collections::HashMap; use std::collections::HashSet; use std::f64; use std::io; use std::io::Read; #[derive(Debug, Clone, Copy)] struct Vec3 { x: f64, y: f64, z: f64, } fn approx_eq(a: f64, b: f64) -> bool { a * 0.9999999999999 < b && b < a * 1.000000000...
extern crate regex; use regex::Regex; use std::collections::HashMap; use std::collections::HashSet; use std::f64; use std::io; use std::io::Read; #[derive(Debug, Clone, Copy)] struct Vec3 { x: f64, y: f64, z: f64, } fn approx_eq(a: f64, b: f64) -> bool { a * 0.9999999999999 < b && b < a * 1.000000000...
fn eq_or_nan(a: f64, b: f64, c: f64) -> Option<f64> { if a.is_nan() { if b.is_nan() { if c.is_nan() { Some(0.0) } else { Some(c) } } else if c.is_nan() || approx_eq(b, c) { Some(b) } else { None ...
fn intersections(p_1: f64, v_1: f64, a_1: f64, p_2: f64, v_2: f64, a_2: f64) -> Vec<f64> { if a_1 != a_2 { let half_p = 0.5 + (v_1 - v_2) / (a_1 - a_2); let q = 2.0 * (p_1 - p_2) / (a_1 - a_2); let root = (half_p * half_p - q).sqrt(); let t_1 = -half_p + root; let t_2 = -half...
function_block-full_function
[ { "content": "#[derive(Debug, Eq, Clone, Copy)]\n\nstruct Vec3 {\n\n x: i64,\n\n y: i64,\n\n z: i64,\n\n}\n\n\n\nimpl Vec3 {\n\n fn non_negative(&self) -> bool {\n\n self.x >= 0 && self.y >= 0 && self.z >= 0\n\n }\n\n}\n\n\n\nimpl Ord for Vec3 {\n\n fn cmp(&self, other: &Vec3) -> Orderi...
Rust
src/directip.rs
gadomski/sbd-rs
5b794f99420a8a3e0cfb5a789038c49379f1d933
use std::{ io, net::{TcpListener, TcpStream, ToSocketAddrs}, sync::{Arc, Mutex}, thread, }; use log::{debug, error, info, warn}; use crate::{mo::Message, storage::Storage}; #[derive(Debug)] pub struct Server<A: ToSocketAddrs + Sync, S: Storage + Sync + Send> { addr: A, listener: Option<TcpL...
use std::{ io, net::{TcpListener, TcpStream, ToSocketAddrs}, sync::{Arc, Mutex}, thread, }; use log::{debug, error, info, warn}; use crate::{mo::Message, storage::Storage}; #[derive(Debug)] pub struct Server<A: ToSocketAddrs + Sync, S: Storage + Sync + Send> { addr: A, listener: Option<TcpL...
fn create_listener(&self) -> io::Result<TcpListener> { TcpListener::bind(&self.addr) } } fn handle_stream(stream: TcpStream, storage: Arc<Mutex<dyn Storage>>) { match stream.peer_addr() { Ok(addr) => { debug!("Handling TcpStream from {}", addr); } Err(err) => {...
match stream { Ok(stream) => { let storage = Arc::clone(&self.storage); thread::spawn(move || handle_stream(stream, storage)); } Err(err) => { thread::spawn(move || handle_error(&err)); } ...
function_block-function_prefix_line
[ { "content": "/// Basic storage operations.\n\npub trait Storage {\n\n /// Stores a message, consuming it.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// # use sbd::mo::Message;\n\n /// # use sbd::storage::{Storage, MemoryStorage};\n\n /// let message = Message::from_path(\"data/...
Rust
server/src/fhir/definitions/signature.rs
gematik/ref-eRp-FD-Server
94d6245829a08d03c8d872ba71c5d8cae0d9dccf
/* * Copyright (c) 2021 gematik GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
/* * Copyright (c) 2021 gematik GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
e = Self; fn from_parts(code: Self::Code) -> Self { code } fn code(&self) -> &Self::Code { &self } fn display(&self) -> Option<&'static str> { match &self { Self::AuthorsSignature => Some("Author's Signature"), Self::CoauthorsSignature => Some("Coau...
data, format, }) } } /* Encode */ impl Encode for &Signature { fn encode<S>(self, stream: &mut EncodeStream<S>) -> Result<(), EncodeError<S::Error>> where S: DataStorage, { let (target_format, sig_format) = match self.format.as_ref() { Some(S...
random
[ { "content": "fn encode_for<S>(value: &Kvnr, stream: &mut EncodeStream<S>) -> Result<(), EncodeError<S::Error>>\n\nwhere\n\n S: DataStorage,\n\n{\n\n stream\n\n .element()?\n\n .encode(\"identifier\", value, encode_identifier)?\n\n .end()?;\n\n\n\n Ok(())\n\n}\n\n\n\npub const PROF...
Rust
src/common.rs
tedil/cyrcular
7a4d7e690f397e8ac157cc35ed2bb702affeb57d
use std::collections::HashMap; use std::iter::once; use bam::{Header, Record}; use bio::data_structures::interval_tree::ArrayBackedIntervalTree; use itertools::Itertools; use num_traits::{One, Zero}; use rayon::prelude::*; pub(crate) type ReferenceId = u32; pub(crate) type Count = i32; pub(crate) type ReadDepth = Has...
use std::collections::HashMap; use std::iter::once; use bam::{Header, Record}; use bio::data_structures::interval_tree::ArrayBackedIntervalTree; use itertools::Itertools; use num_traits::{One, Zero}; use rayon::prelude::*; pub(crate) type ReferenceId = u32; pub(crate) type Count = i32; pub(crate) type ReadDepth = Has...
t { dbg!(&record); continue; } let tree = trees .entry(ref_id as u32) .or_insert_with(ArrayBackedIntervalTree::new); tree.insert(start..end, record); } } trees.valu...
start, end) = (record.start(), record.calculate_end()); if start >= 0 && end >= 0 { let (start, end) = (start as usize, end as usize); if end <= star
function_block-random_span
[ { "content": "fn neighbour_coverage(read_depth: &ReadDepth, target: ReferenceId, a: u32, b: u32) -> f64 {\n\n let (a, b) = (a.min(b), a.max(b));\n\n let between_coverage = &read_depth[&target][a as usize..b as usize];\n\n let n = between_coverage.len() as f64;\n\n between_coverage\n\n .iter()...
Rust
src/state.rs
kbknapp/usbwatch-rs
9f3cda54abda676f2d4ba15c34f226883074d494
use std::collections::HashMap; use std::fs::{self, File}; use std::path::Path; use tracing::{self, debug, info, span, Level}; use yaml_rust::YamlLoader; use crate::{ rule::{Rule, Rules}, usb::{UsbDevice, UsbDevices, UsbPort, UsbPorts}, }; #[derive(Default)] pub struct State { ports: Vec<UsbPort>, dev...
use std::collections::HashMap; use std::fs::{self, File}; use std::path::Path; use tracing::{self, debug, info, span, Level}; use yaml_rust::YamlLoader; use crate::{ rule::{Rule, Rules}, usb::{UsbDevice, UsbDevices, UsbPort, UsbPorts}, }; #[derive(Default)] pub struct State { ports: Vec<UsbPort>, dev...
}
debug!("Setting slot map {} to None", p); *self.slot_map.entry(*p).or_insert(None) = None; } let mut to_rem = None; for (j, idx) in self.active_devices.iter().enumerate() { if *idx == i { to_rem = Some(j); ...
function_block-function_prefix_line
[ { "content": "pub fn main() {\n\n use cli::UsbWatchSubCmd::*;\n\n\n\n let args = cli::UsbWatchArgs::parse();\n\n\n\n match args.verbose {\n\n 0 => (),\n\n 1 => env::set_var(\"RUST_LOG\", \"usbwatch=info\"),\n\n 2 => env::set_var(\"RUST_LOG\", \"usbwatch=debug\"),\n\n _ => en...
Rust
src/main.rs
kisasexypantera94/khalzam-cli
85f76284960971aa0ed8fecc1f90d339cc7dd9bd
use clap::{App, Arg, SubCommand}; use khalzam::db::pg::PostgresRepo; use khalzam::MusicLibrary; use rayon::prelude::{IntoParallelRefIterator, ParallelIterator}; use std::fs; use std::io::Write; use std::path::Path; use std::time::Instant; fn main() { let matches = App::new("khalzam-cli") .author("kisasexyp...
use clap::{App, Arg, SubCommand}; use khalzam::db::pg::PostgresRepo; use khalzam::MusicLibrary; use rayon::prelude::{IntoParallelRefIterator, ParallelIterator}; use std::fs; use std::io::Write; use std::path::Path; use std::time::Instant; fn main() { let matches = App::new("khalzam-cli") .author("kisasexyp...
; let duration = start.elapsed(); println!("\nDone in {:?}", duration); } if let Some(matches) = matches.subcommand_matches("recognize") { let start = Instant::now(); let filename = matches.value_of("filename").unwrap(); let name = String::from(Path::new(filename).file...
match m_lib.add(filename) { Ok(()) => println!("Added {}", filename), Err(e) => println!("Can't add {}: {}", filename, e), }
if_condition
[ { "content": "--\n\n-- Name: songs songs_song_key; Type: CONSTRAINT; Schema: public; Owner: -\n\n--\n\n\n", "file_path": "initdb.sql", "rank": 1, "score": 22747.61045484555 }, { "content": "--\n\n-- Name: songs songs_pkey; Type: CONSTRAINT; Schema: public; Owner: -\n\n--\n\n\n", "file_pa...
Rust
key_management/src/keystore.rs
jonnycrunch/forest
fc523a326e28407401693a7af7bade5d2faaef3f
use super::errors::Error; use crypto::SignatureType; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Clone, PartialEq, Debug, Eq, Serialize, Deserialize)] pub struct KeyInfo { key_type: SignatureType, private_key: Vec<u8>, } impl KeyInfo { pub fn new(key_type: Sign...
use super::errors::Error; use crypto::SignatureType; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Clone, PartialEq, Debug, Eq, Serialize, Deserialize)] pub struct KeyInfo { key_type: SignatureType, private_key: Vec<u8>, } impl KeyInfo { pub fn new(key_type: Sign...
} pub trait KeyStore { fn list(&self) -> Vec<String>; fn get(&self, k: &str) -> Result<KeyInfo, Error>; fn put(&mut self, key: String, key_info: KeyInfo) -> Result<(), Error>; fn remove(&mut self, key: String) -> Option<KeyInfo>; } #[derive(Default, Clone, PartialEq, Debug, Eq)] p...
pub fn deserialize<'de, D>(deserializer: D) -> Result<KeyInfo, D::Error> where D: Deserializer<'de>, { let JsonHelper { sig_type, private_key, } = Deserialize::deserialize(deserializer)?; Ok(KeyInfo { key_type: sig_type, private_key...
function_block-full_function
[ { "content": "/// Gets the home directory of the current system.\n\n/// Will return correct path for windows, linux, and osx.\n\n///\n\n/// # Panics\n\n/// We will panic if we cannot determine a home directory.\n\npub fn get_home_dir() -> String {\n\n home_dir().unwrap().to_str().unwrap().to_owned()\n\n}\n\n...
Rust
src/log.rs
joseluis/stakker
689aa3d1116acc34db9db4a4085adb6c1742b4f4
use std::error::Error; use std::fmt::{Arguments, Display}; use std::ops::{BitOr, BitOrAssign}; use std::str::FromStr; pub trait LogVisitor { fn kv_u64(&mut self, key: Option<&str>, val: u64); fn kv_i64(&mut self, key: Option<&str>, val: i64); fn kv_f64(&mut self, key: Option<&str>, val: f64); fn kv_boo...
use std::error::Error; use std::fmt::{Arguments, Display}; use std::ops::{BitOr, BitOrAssign}; use std::str::FromStr; pub trait LogVisitor { fn kv_u64(&mut self, key: Option<&str>, val: u64); fn kv_i64(&mut self, key: Option<&str>, val: i64); fn kv_f64(&mut self, key: Option<&str>, val: f64); fn kv_boo...
} impl FromStr for LogFilter { type Err = LogLevelError; fn from_str(s: &str) -> Result<LogFilter, LogLevelError> { let mut rv = LogFilter::new(); for level in s.split(',') { let level = LogLevel::from_str(level)?; rv |= LogFilter::from(level); } Ok(rv)...
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { "LogFilter(".fmt(f)?; let mut first = true; for level in LogLevel::all_levels() { if 0 != (self.0 & (1 << *level as u32)) { if first { first = false; } else { ...
function_block-full_function
[ { "content": "type BoxFnMutCB = Box<dyn FnMut(&mut Stakker, bool) + 'static>;\n\n\n\n#[cfg(feature = \"inter-thread\")]\n\npub(crate) struct WakeHandlers {\n\n pollwaker: Arc<PollWaker>,\n\n slab: Slab<Option<BoxFnMutCB>>,\n\n bitmaps: Array<Vec<Arc<BitMap>>>,\n\n}\n\n\n\n#[cfg(feature = \"inter-thread...
Rust
charmath/src/linear/quaternion.rs
CallumMackenzie/charengine
4f193a9f861075d3f1bc00f0af1c29ea40d9f367
#[cfg(target_family = "wasm")] use wasm_bindgen::prelude::*; #[cfg(target_family = "wasm")] #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console, js_name = log)] fn js_log_string(a: &str); } use crate::linear::vector::{Vec3, Vec4, Vector, VectorBase}; use crate::numeric::CharMathNumeric; use cra...
#[cfg(target_family = "wasm")] use wasm_bindgen::prelude::*; #[cfg(target_family = "wasm")] #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console, js_name = log)] fn js_log_string(a: &str); } use crate::linear::vector::{Vec3, Vec4, Vector, VectorBase}; use crate::numeric::CharMathNumeric; use cra...
$NUM) -> $QUAT { $QUAT { vec: [x, y, z, w] } } #[cfg(target_family = "wasm")] #[wasm_bindgen(js_name = copy)] pub fn wcopy(&self) -> $QUAT { self.cm_copy() } #[cfg(target_family = "wasm")] #[wasm_bindgen(js_name = getX)] ...
fn $ASOPNAME(&mut self, rhs: Quaternion<N>) { self.$VCALL(&rhs); } } impl<N: CharMathNumeric<N>> $ASOP<&Quaternion<N>> for Quaternion<N> { fn $ASOPNAME(&mut self, rhs: &Quaternion<N>) { self.$VCALL(rhs); } } impl<N: C...
random
[ { "content": "pub trait Vec4<N: CharMathNumeric<N>, V: Vec4<N, V>>: Vector<N, V> {\n\n fn new(x: N, y: N, z: N, w: N) -> V;\n\n fn get_x(&self) -> N {\n\n self.get_value(0)\n\n }\n\n fn set_x(&mut self, x: N) {\n\n self.set_value(0, x);\n\n }\n\n fn get_y(&self) -> N {\n\n ...
Rust
src/lib.rs
here1009/expression_tree
b595a2717b6acc66495eb3c678f4370376daf706
pub mod symrust { use regex::Regex; use std::collections::HashMap; use std::str; extern crate regex; use indextree_ng::Arena; #[derive(Debug,PartialEq,Clone)] pub struct OP { pub tag: String, pub reg: String, pub id: i64, pub pre: i64, pub skip_climb_...
pub mod symrust { use regex::Regex; use std::collections::HashMap; use std::str; extern crate regex; use indextree_ng::Arena; #[derive(Debug,PartialEq,Clone)] pub struct OP { pub tag: String, pub reg: String, pub id: i64, pub pre: i64, pub skip_climb_...
pub fn expr_scan(expr: &String)->Vec<String>{ let hash_to_norm : HashMap<&str,&str> = [ ("(","OPENBRACKET"), (")","CLOSEBRACKET"), ("+ve","POSITIVE"), ("-ve","NEGATIVE"), ("+","PLUS"), ("-","MINUS"), ("*","TIMES"), ...
pub fn get_op(flag:&str,pre_tag:&str) -> OP{ let mut OPENBRACKET =OP::new(String::from("OPENBRACKET"), String::from("\\("), 1, 1, true, false, 0.0); let mut CLOSEBRACKET =OP::new(String::from("CLOSEBRACKET"), String::from("\\)"), 2, 1, false, true, 0.0); let mut POSITIVE ...
function_block-full_function
[]
Rust
src/smoothing.rs
PhilippGawlik/naive_langguesser
17ce94e39fbf12f47480f4d0e487bc0ca7449b97
use errors::SmoothingError; use models::ngram_model::NGramModel; use std::collections::HashMap; pub enum SmoothingType { NoSmoothing, AddOneSmoothing, WittenBellSmoothing, } pub fn smoothing( ngram_model: &mut NGramModel, type_: &SmoothingType, ) -> Result<(), SmoothingError> { match type_ { ...
use errors::SmoothingError; use models::ngram_model::NGramModel; use std::collections::HashMap; pub enum SmoothingType { NoSmoothing, AddOneSmoothing, WittenBellSmoothing, } pub fn smoothing( ngram_model: &mut NGramModel, type_: &SmoothingType, ) -> Result<(), SmoothingError> { match type_ { ...
let vocabulary_size: f64 = 3.0; add_one_to_hashmap(&mut model, total, vocabulary_size).unwrap(); assert_eq!(&0.0000000000000000, model.get("a").unwrap()); assert_eq!(&0.0000000000000000, model.get("b").unwrap()); assert_eq!(&0.0000000000000000, model.get("c").unwrap()); } ...
ssert_eq!(&0.0000000000000000, model.get("c").unwrap()); } #[test] fn test_add_one_smoothing1() { let mut model: HashMap<String, f64> = HashMap::new(); model.insert("a".to_string(), 2.0); model.insert("b".to_string(), 2.0); model.insert("c".to_string(), 0.0); let tot...
random
[ { "content": "/// Calculate a probability based language model from a text example file\n\n///\n\n/// # Arguments\n\n///\n\n/// * `config` - a struct holding config settings, partly given through cli\n\npub fn model(config: config::ModelConfig) -> Result<(), ModellingError> {\n\n let mut text_model = TextMod...
Rust
src/loader/elf64/mod.rs
njerris/uefi-boot
0bd6ec1c76665366cb5d07348a6cc2df233cdb55
pub mod program; use core::mem::size_of; use core::result::Result; pub use program::*; #[derive(Debug)] pub enum Elf64Error { SliceTooSmall(usize), NotElf, NotElf64, InvalidVersion, } #[derive(Clone, Copy, PartialEq, Debug)] pub enum ElfAbi { None, Unknown(u8), ...
pub mod program; use core::mem::size_of; use core::result::Result; pub use program::*; #[derive(Debug)] pub enum Elf64Error { SliceTooSmall(usize), NotElf, NotElf64, InvalidVersion, } #[derive(Clone, Copy, PartialEq, Debug)] pub enum ElfAbi { None, Unknown(u8), ...
if header.ident[4] != 2 { return Err(Elf64Error::NotElf64); } if header.ident[6] != 1 { return Err(Elf64Error::InvalidVersion); } if header.version != 1 { return Err(Elf64Error::InvalidVersion); } ...
let header: &Elf64Header = unsafe { &*(slice.as_ptr() as *const _ as *const Elf64Header) };
assignment_statement
[ { "content": "// TODO: finish get_gop_modes, which gets multiple graphics modes\n\n// set the highest-resolution graphics mode on every available graphics device\n\n// return a pointer to an array of pointers to graphics mode structures,\n\n// and the number of those structures\n\npub fn get_gop_modes(image_han...
Rust
deprecated/query_planning_deprecated/query_planner/src/tests/select.rs
Tolledo/database
65e7e5b2de3020000110a3883291377b8e3019af
use super::*; use plan::{FullTableId, SelectInput}; use sql_ast::{ObjectName, Query, Select, SelectItem, SetExpr, Statement, TableFactor, TableWithJoins}; #[rstest::rstest] fn select_from_table_that_in_nonexistent_schema(planner: QueryPlanner) { assert_eq!( planner.plan(&Statement::Query(Box::new(Query {...
use super::*; use plan::{FullTableId, SelectInput}; use sql_ast::{ObjectName, Query, Select, SelectItem, SetExpr, Statement, TableFactor, TableWithJoins}; #[rstest::rstest] fn select_from_table_that_in_nonexistent_schema(planner: QueryPlanner) { assert_eq!( planner.plan(&Statement::Query(Box::new(Query {...
q!( planner_with_no_column_table.plan(&Statement::Query(Box::new(Query { with: None, body: SetExpr::Select(Box::new(Select { distinct: false, top: None, projection: vec![SelectItem::Wildcard], from: vec![TableWithJoins { ...
tExpr::Select(Box::new(Select { distinct: false, top: None, projection: vec![SelectItem::Wildcard], from: vec![TableWithJoins { relation: TableFactor::Table { name: ObjectName(vec![ident(SCHEMA), ident("non_exist...
random
[ { "content": "fn select_with_columns(name: ObjectName, projection: Vec<SelectItem>) -> Statement {\n\n Statement::Query(Box::new(Query {\n\n with: None,\n\n body: SetExpr::Select(Box::new(Select {\n\n distinct: false,\n\n top: None,\n\n projection,\n\n ...
Rust
ffi/emf-core-base-rs-ffi/src/sys/api.rs
GabeRealB/emf-rs
24a812c052602aeb7aa8747ab306e4c33a0a72d6
use crate::collections::Optional; use crate::errors::Error; use crate::sys::sync_handler::SyncHandlerInterface; use crate::{Bool, CBase, CBaseFn, CBaseInterface, FnId, TypeWrapper}; use std::ptr::NonNull; pub type ShutdownFn = TypeWrapper<unsafe extern "C-unwind" fn(base_module: Option<NonNull<CBase>>) -> !>; p...
use crate::collections::Optional; use crate::errors::Error; use crate::sys::sync_handler::SyncHandlerInterface; use crate::{Bool, CBase, CBaseFn, CBaseInterface, FnId, TypeWrapper}; use std::ptr::NonNull; pub type ShutdownFn = TypeWrapper<unsafe extern "C-unwind" fn(base_module: Option<NonNull<CBase>>) -> !>; p...
n_fn)(self.base_module, id) } #[inline] unsafe fn get_function(&self, id: FnId) -> Optional<CBaseFn> { (self.vtable.as_ref().sys_get_function_fn)(self.base_module, id) } #[inline] unsafe fn lock(&self) { (self.vtable.as_ref().sys_lock_fn)(self.base_module) } #[inline] ...
e fn unlock(&self); unsafe fn get_sync_handler(&self) -> SyncHandlerInterface; unsafe fn set_sync_handler(&mut self, handler: Optional<SyncH...
random
[]
Rust
2019/24/rs/src/main.rs
Bigsby/aoc
409fefbb0467628fa298288064acb622bb53ee58
use num::Complex; use std::collections::{HashMap, HashSet}; type Bug = Complex<i32>; type Bugs = Vec<Bug>; type LayeredBugs = HashMap<i32, Bugs>; static DIRECTIONS: &'static [Bug] = &[ Bug::new(1, 0), Bug::new(-1, 0), Bug::new(0, 1), Bug::new(0, -1), ]; fn gets_bug(has_bug: bool, adjacent_count: usize...
use num::Complex; use std::collections::{HashMap, HashSet}; type Bug = Complex<i32>; type Bugs = Vec<Bug>; type LayeredBugs = HashMap<i32, Bugs>; static DIRECTIONS: &'static [Bug] = &[ Bug::new(1, 0), Bug::new(-1, 0), Bug::new(0, 1), Bug::new(0, -1), ]; fn gets_bug(has_bug: bool, adjacent_count: usize...
{ layer_bugs.push(position); } } } new_state.insert(layer, layer_bugs); } new_state } fn part2(bugs: &Bugs) -> usize { let mut layers = LayeredBugs::new(); layers.insert(0, bugs.iter().copied().collect()); for _ in 0..200 { la...
gets_bug( layers .get(&layer) .unwrap_or(&Bugs::new()) .contains(&(position)), adjacent_count, )
call_expression
[ { "content": "fn play_game(player1: &mut Player, player2: &mut Player, round_decider: bool) -> usize {\n\n if round_decider {\n\n if player1.last_card_smaller() && player2.last_card_smaller() {\n\n return play_game(&mut player1.clone(true), &mut player2.clone(true), false);\n\n } els...
Rust
src/rar.rs
xcf-t/wasm-khash
961952a35d3a37a252d889e4d5ecc555f373d074
use crate::constants::*; use std::io::{Cursor, Read, Seek, SeekFrom, Result}; use sha2::{Digest, Sha256}; use core::fmt::Write; use crate::constants::*; use crate::utils::ProcessingResult; use crate::utils::{basename, bytes_to_hex, read_le_u32, read_u8, read_var_int}; type RarCursor = Cursor<Vec<u8>>; #[derive(Debug...
use crate::constants::*; use std::io::{Cursor, Read, Seek, SeekFrom, Result}; use sha2::{Digest, Sha256}; use core::fmt::Write; use crate::constants::*; use crate::utils::ProcessingResult; use crate::utils::{basename, bytes_to_hex, read_le_u32, read_u8, read_var_int}; type RarCursor = Cursor<Vec<u8>>; #[derive(Debug...
fn process_rar5_header(state: &mut Rar5ReaderState, cursor: &mut RarCursor) -> Result<u64> { let (mut extra_size, mut data_size) = (0, 0); if state.encrypted { let mut rar5_iv = [0u8; SIZE_INITV]; cursor.read_exact(&mut rar5_iv)?; let rar5_iv_hex = bytes_to_hex(&rar5_iv)?; le...
fn process_rar5(mut cursor: RarCursor) -> Result<Rar5ReaderState> { let mut state = Rar5ReaderState::new(); loop { let pos = cursor.position(); let next = process_rar5_header(&mut state, &mut cursor); if let Err(_) = next { return Ok(state); } let next = nex...
function_block-full_function
[ { "content": "pub fn read_u8(cursor: &mut Cursor<Vec<u8>>) -> Result<u8> {\n\n let mut buffer = [0u8; 1];\n\n cursor.read_exact(&mut buffer)?;\n\n Ok(u8::from_le_bytes(buffer))\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 0, "score": 193918.6531668988 }, { "content": "pub fn re...
Rust
src/peer/router.rs
threefoldtech/dbreboot
d7798a79b3f665e6d86d7159e0a3114b24d9b011
use super::PeersList; use crate::database::*; use crate::identity::Identity; use crate::rpc::generated::bcdb_client::BcdbClient; use crate::rpc::generated::*; use anyhow::Result; use async_trait::async_trait; use std::collections::HashMap; use tokio::sync::mpsc; #[derive(Clone)] pub struct Router<L, P> where L: Da...
use super::PeersList; use crate::database::*; use crate::identity::Identity; use crate::rpc::generated::bcdb_client::BcdbClient; use crate::rpc::generated::*; use anyhow::Result; use async_trait::async_trait; use std::collections::HashMap; use tokio::sync::mpsc; #[derive(Clone)] pub struct Router<L, P> where L: Da...
?; Ok(BcdbClient::new(con)) } fn set_headers<T>(&self, request: &mut tonic::Request<T>) { request.metadata_mut().append( "authorization", tonic::metadata::AsciiMetadataValue::from_str( crate::auth::header(&self.id, None).as_ref(), ) ...
d to get peer: {}", e)))?; let con = peer .connect() .await .map_err(|e| Reason::CannotGetPeer(format!("failed to connect to peer: {}", e)))
function_block-random_span
[ { "content": "pub fn router<S>(\n\n storage: ACLStorage<S>,\n\n) -> impl Filter<Extract = impl warp::Reply, Error = Rejection> + Clone\n\nwhere\n\n S: Storage + Clone + Send + Sync,\n\n{\n\n let base = warp::any().and(with_storage(storage.clone()));\n\n\n\n let create = base\n\n .clone()\n\n ...
Rust
day10/src/bin/part1.rs
bmatcuk/adventofcode2019
d4523e9182af4b05e5ca7f0417afccf23fff812e
use std::fs::File; use std::io::{self, BufRead, BufReader}; fn gcd(a: isize, b: isize) -> isize { if a == 0 { b } else if b == 0 { a } else { gcd(b, a % b) } } fn calculate(astroids: &Vec<Vec<bool>>, x: usize, y: usize, width: usize, height: usize) -> u16 { let mut count ...
use std::fs::File; use std::io::{self, BufRead, BufReader}; fn gcd(a: isize, b: isize) -> isize { if a == 0 { b } else if b == 0 { a } else { gcd(b, a % b) } }
fn main() -> io::Result<()> { let file = File::open("input.txt")?; let reader = BufReader::new(file); let astroids = reader .lines() .map(|line| line.map(|l| l.bytes().map(|b| b == b'#').collect())) .collect::<io::Result<Vec<Vec<bool>>>>()?; let width = astroids[0].len(); l...
fn calculate(astroids: &Vec<Vec<bool>>, x: usize, y: usize, width: usize, height: usize) -> u16 { let mut count = 0; if x > 0 { for x1 in (0..x).rev() { if astroids[y][x1] { count += 1; break; } } } for x1 in (x + 1)..width { ...
function_block-full_function
[ { "content": "# Advent of Code, 2019 :christmas_tree:\n\nMy implementations of the [2019 Advent of Code] puzzles in [rust].\n\n\n\nI like to use the Advent of Code as a learning opportunity. This year, I\n\ndecided on learning [rust]. I've had a little experience with the language\n\nbefore AoC, but I really wa...
Rust
src/storage/result_storage.rs
Bixkog/dotastats
7bbfc8eebd28c4be8e6bda14551cc97bbf363c73
use crate::{storage::Storage, types::GuildId, BoxError}; use chrono::Utc; use mongodb::options::FindOptions; use mongodb::{ self, bson::{self, doc}, }; use serde::{Deserialize, Serialize}; use std::{ collections::{HashMap, HashSet}, fmt, }; use strum::IntoEnumIterator; use strum_macros::EnumIter; use to...
use crate::{storage::Storage, types::GuildId, BoxError}; use chrono::Utc; use mongodb::options::FindOptions; use mongodb::{ self, bson::{self, doc}, }; use serde::{Deserialize, Serialize}; use std::{ collections::{HashMap, HashSet}, fmt, }; use strum::IntoEnumIterator; use strum_macros::EnumIter; use to...
pub async fn get_result( &self, guild_id: &GuildId, analysis_tag: AnalysisTag, ) -> Result<String, BoxError> { let coll = self.db_client.collection("analysis_results"); let filter = doc! {"guild_id": guild_id, "tag": analysis_tag.to_string()}; let result_do...
pub async fn store_result( &self, guild_id: &GuildId, payload: serde_json::Value, analysis_tag: AnalysisTag, ) -> mongodb::error::Result<()> { let res = StoredResult { guild_id: guild_id.clone(), timestamp: Utc::now().timestamp(), tag: anal...
function_block-full_function
[ { "content": "/// Extracts match info from bson. Used for parsing the database match data output.\n\nfn extract_match_data_from_doc(match_bson: &mut Bson) -> Option<serde_json::Value> {\n\n let match_json: serde_json::Value = match_bson.clone().into();\n\n match serde_json::from_str(match_json[\"info\"].a...
Rust
src/registers.rs
multivac61/gameboy
c5ae3114c5fab33121f29b85a4af7bd37dd5cac6
use crate::util::{ith_bit, little_endian}; #[derive(Debug, PartialEq, Copy, Clone)] pub enum ConditionalFlag { Zero = 7, Subtract = 6, HalfCarry = 5, Carry = 4, } #[derive(Debug, PartialEq, Copy, Clone)] pub struct Flags { pub z: bool, pub n: bool, pub h: bool, pub c: bool, } #[derive...
use crate::util::{ith_bit, little_endian}; #[derive(Debug, PartialEq, Copy, Clone)] pub enum ConditionalFlag { Zero = 7, Subtract = 6, HalfCarry = 5, Carry = 4, } #[derive(Debug, PartialEq, Copy, Clone)] pub struct Flags { pub z: bool, pub n: bool, pub h: bool, pub c: bool, } #[derive...
}
fn flags() { let mut r = Registers::new(); let flags = [ ConditionalFlag::Zero, ConditionalFlag::Subtract, ConditionalFlag::HalfCarry, ConditionalFlag::Carry, ]; assert_eq!(r.read(Register::F) & 0x0F, 0); r.write(Register...
function_block-function_prefix_line
[ { "content": "pub fn ith_bit(n: u8, i: u8) -> bool {\n\n assert!(i <= 7);\n\n n & (1 << i) == (1 << i)\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 86775.2090423615 }, { "content": "pub fn set_bit(n: u8, i: u8) -> u8 {\n\n n | (1 << i)\n\n}\n\n\n", "file_path": "...
Rust
rust/rsnano/src/socket.rs
simpago/rsnano-node
6a59b6005b14eca1a00c362e314d1e0f6234f714
use std::{ ffi::c_void, net::SocketAddr, sync::{ atomic::{AtomicBool, AtomicU64, Ordering}, Arc, Mutex, }, time::Duration, }; use crate::{ logger_mt::Logger, seconds_since_epoch, stats::{DetailType, Direction, Stat, StatType}, ThreadPool, }; #[derive(Clone, Copy, De...
use std::{ ffi::c_void, net::SocketAddr, sync::{ atomic::{AtomicBool, AtomicU64, Ordering}, Arc, Mutex, }, time::Duration, }; use crate::{ logger_mt::Logger, seconds_since_epoch, stats::{DetailType, Direction, Stat, StatType}, ThreadPool, }; #[derive(Clone, Copy, De...
Direction::In } else { Direction::Out }, ); condition_to_disconnect = true; } if condition_to_disconnect { i...
ol, endpoint_type, silent_connection_tolerance_time: AtomicU64::new( silent_connection_tolerance_time.as_secs(), ), network_timeout_logging, logger, timed_out: AtomicBool::new(false), closed: AtomicBool::new(false), ...
random
[]
Rust
src/main.rs
prokoptasis/rust_sdl2
01e30171de96d23288c4a09d6ea36c465129c91d
extern crate sdl2; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::render::TextureQuery; use std::collections::HashSet; use std::env; use std::time::Duration; use sdl2::audio::{AudioCVT, AudioCallback, AudioSpecDesired, AudioSpecWAV}...
extern crate sdl2; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::render::TextureQuery; use std::collections::HashSet; use std::env; use std::time::Duration; use sdl2::audio::{AudioCVT, AudioCallback, AudioSpecDesired, AudioSpecWAV}...
let fnt_path: &Path = Path::new("./assets/d2coding.ttc"); let ttf_context = sdl2::ttf::init().map_err(|e| e.to_string())?; let texture_creator = canvas.texture_creator(); let mut font = ttf_context.load_font(fnt_path, 128)?; font.set_style(sdl2:...
let mut device = audio_subsystem.open_playback(None, &desired_spec, |spec| { let wav = AudioSpecWAV::load_wav(wav_file).expect("Could not load test WAV file"); let cvt = AudioCVT::new( wav.format, wav.channels, wav.freq, spec.format, spec.chan...
assignment_statement
[ { "content": "### Rust SDL2\n\n\n\n[Rust_SDL2 Source Codes](https://prokoptasis.github.io/docs/documents/projects/rust_sdl2/)\n\n\n\nRust를 이용한 SDL2 Test\n\n\n\n![rust_sdl2](201216_05_prj_rust_sdl2.png)\n", "file_path": "README.md", "rank": 4, "score": 7594.201989076482 } ]
Rust
src/library_postprocessing.rs
sdroege/gir
10e1d4f89dbcc87fc7d71a28d6a29aa102be73a5
use std::collections::HashMap; use library::*; use parser::is_empty_c_type; impl Namespace { fn unresolved(&self) -> Vec<&str> { self.index.iter().filter_map(|(name, &id)| { if self.types[id as usize].is_none() { Some(&name[..]) } else { None ...
use std::collections::HashMap; use library::*; use parser::is_empty_c_type; impl Namespace { fn unresolved(&self) -> Vec<&str> { self.index.iter().filter_map(|(name, &id)| { if self.types[id as usize].is_none() { Some(&name[..]) } else { None ...
signal: &Signal, c_types: &mut DetectedCTypes) -> bool { let mut detected = false; for par in &signal.parameters { if self.detect_empty_c_type(&par.c_type, par.typ, c_types) { detected = true; } } if self.detect_empty_c_type(&signal.ret.c_type, signal.ret.typ, c_types) { de...
); } fn update_empty_c_type(c_type: &mut String, tid: TypeId, c_types: &DetectedCTypes) { if !is_empty_c_type(c_type) { return } if let Some(ref mut s) = c_types.get(&tid) { *c_type = s.clone(); } } for tid in tids { match...
random
[ { "content": "pub fn analyze(env: &Env, signals: &[library::Signal], type_tid: library::TypeId,\n\n in_trait: bool, trampolines: &mut trampolines::Trampolines,\n\n obj: &GObject, imports: &mut Imports) -> Vec<Info> {\n\n let mut sns = Vec::new();\n\n\n\n for signal in signals {...
Rust
day11/src/octopuses.rs
faffeldt/aoc2021
2c5d497f7f19912b0a9f8b674f8bf6c1f1e4c102
use std::fmt; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct OctopusField { octopuses: Vec<Vec<usize>>, width: usize, height: usize, flashes: usize, step: usize, } impl OctopusField { fn new(octopuses: Vec<Vec<usize>>, height: usize, width: usize) -> OctopusField { OctopusFiel...
use std::fmt; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct OctopusField { octopuses: Vec<Vec<usize>>, width: usize, height: usize, flashes: usize, step: usize, } impl OctopusField { fn new(octopuses: Vec<Vec<usize>>, height: usize, width: usize) -> OctopusField { OctopusFiel...
}
lf, f: &mut fmt::Formatter) -> fmt::Result { write! {f, "Octopusfield (w: {}, h: {}, step: {}, flashes: {}):\n", self.width, self.height, self.step, self.flashes}; for row in &self.octopuses { for octopus in row { if *octopus == 0 { write! {f, "*"}; ...
function_block-function_prefixed
[ { "content": "pub fn hex_str_to_bitvec(input: &str) -> BitVec<Msb0, u8> {\n\n let mut buffer: BitVec<Msb0, u8> = BitVec::new();\n\n input.as_bytes().iter().for_each(|c| {\n\n if *c <= ('9' as u8) {\n\n let parsed = c - ('0' as u8);\n\n buffer.append(&mut BitVec::<Msb0, u8>::fr...
Rust
src/commands/test.rs
JoachimBorup/kitty
fe081ed38dd689d3ad2424582ba664fd11751ecf
use crate::commands::get; use crate::problem::Problem; use crate::utils::prompt_bool; use crate::StdErr; use clap::ArgMatches; use colored::Colorize; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher}; use std::fs::{self, File}; use std::io::{Read, Write}; use std::path::PathBuf; use std::process::{Command, ...
use crate::commands::get; use crate::problem::Problem; use crate::utils::prompt_bool; use crate::StdErr; use clap::ArgMatches; use colored::Colorize; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher}; use std::fs::{self, File}; use std::io::{Read, Write}; use std::path::PathBuf; use std::process::{Command, ...
fn watch<F: Fn() -> Result<(), StdErr>>(problem: &Problem, test_runner: F) -> Result<(), StdErr> { let (tx, rx) = channel(); let mut watcher = watcher(tx, Duration::from_secs(1)).unwrap(); let src_file = problem.file(); watcher.watch(&src_file, RecursiveMode::NonRecursive)?; let test_runner_wrappe...
function_block-full_function
[ { "content": "pub fn init_file(problem_id: &str, lang: &Language, cmd: &ArgMatches<'_>) -> Result<(), StdErr> {\n\n let filename = if cmd.is_present(\"no-domain\") {\n\n problem_id.split('.').last().unwrap()\n\n } else {\n\n problem_id\n\n };\n\n let templates_dir = Config::templates_d...
Rust
src/tests/arithmetic/shifts.rs
lemmy-64/n64-systemtest
15f663c548278d005004e137e68fc17de6bffa15
use alloc::boxed::Box; use alloc::string::{String, ToString}; use alloc::vec; use alloc::vec::Vec; use core::any::Any; use core::arch::asm; use crate::tests::{Level, Test}; use crate::tests::soft_asserts::soft_assert_eq; fn test_sra<const SHIFT_AMOUNT: u32>(source_value: u64) -> u64 { let mut result: u64 = 0; ...
use alloc::boxed::Box; use alloc::string::{String, ToString}; use alloc::vec; use alloc::vec::Vec; use core::any::Any; use core::arch::asm; use crate::tests::{Level, Test}; use crate::tests::soft_asserts::soft_assert_eq; fn test_sra<const SHIFT_AMOUNT: u32>(source_value: u64) -> u64 { let mut result: u64 = 0; ...
Result<(), String> { let mut sll: u64 = 0xDECAF15BADC0FFEE; let mut srl: u64 = 0xDECAF15BADC0FFEE; let mut sra: u64 = 0xDECAF15BADC0FFEE; unsafe { asm!(" LUI $2, 0x1234 SLL $0, $2, 1 SD $0, 0($3) SRL $0, $2, 1 ...
onality } fn values(&self) -> Vec<Box<dyn Any>> { vec! { Box::new((0x00000000_12345678u64, 4u32, 0x00000000_01234567u64)), Box::new((0x00000000_82345678u64, 0u32, 0xFFFFFFFF_82345678u64)), Box::new((0x01234567_89ABCDEFu64, 4u32, 0x00000000_089ABCDEu64)), Box...
random
[ { "content": "pub fn soft_assert_less(v1: u32, v2: u32, help: &str) -> Result<(), String> {\n\n if v1 < v2 {\n\n Ok(())\n\n } else {\n\n Err(format!(\"a < b expected, but a={} b={} (hex: a=0x{:x} b=0x{:x}). {}\", v1, v2, v1, v2, help))\n\n }\n\n}\n", "file_path": "src/tests/soft_asser...
Rust
src/pdf/mod.rs
drahnr/shinypenny
98025455a38f8fee8218eb725e135a6110347e18
use crate::errors::*; use std::collections::BTreeMap; use lopdf::{Document, Object, ObjectId}; use printpdf::*; mod types; pub mod constants; mod tabular; mod helper; pub use self::helper::*; use std::io::{BufRead, Read, Seek, SeekFrom}; use std::path::Path; use fs_err as fs; fn load_image(stream: impl BufRea...
use crate::errors::*; use std::collections::BTreeMap; use lopdf::{Document, Object, ObjectId}; use printpdf::*; mod types; pub mod constants; mod tabular; mod helper; pub use self::helper::*; use std::io::{BufRead, Read, Seek, SeekFrom}; use std::path::Path; use fs_err as fs; fn load_image(stream: impl BufRea...
document .objects .insert(pages_object.0, Object::Dictionary(dictionary)); } if let Ok(dictionary) = catalog_object.1.as_dict() { let mut dictionary = dictionary.clone(); dictionary.set("Pages", pages_object.0); dictionary.remove(b"Outlines"); ...
( object_id, document.get_object(object_id).unwrap().to_owned(), ) }) .collect::<BTreeMap<ObjectId, Object>>(); documents_pages.extend(pages); documents_objects.extend(document.objects.clone()); } let m...
random
[ { "content": "/// Introduce a sized image page.\n\npub fn sized_image_page(image: image::DynamicImage) -> Result<lopdf::Document> {\n\n let (width, height) = image.dimensions();\n\n let dpi = 200. as f64;\n\n\n\n let height: Mm = Px(height as usize).into_pt(dpi).into();\n\n let width: Mm = Px(width ...
Rust
src/c3_q3.rs
d-kos/cracking_the_coding_interview_6th_edition_rust
3f2de3335ea1d872403d4d61c1f36ab0cefb245e
use crate::vec_stack::{Stack, VecStack}; #[derive(Debug)] struct SetOfStacks<T> { stacks: Vec<VecStack<T>>, a_reg: AddressRegister, } #[derive(Default, Debug)] struct AddressRegister { max: usize, current: usize, } impl<T> SetOfStacks<T> where T: Copy, { fn new(max: usize) -> Self { ...
use crate::vec_stack::{Stack, VecStack}; #[derive(Debug)] struct SetOfStacks<T> { stacks: Vec<VecStack<T>>, a_reg: AddressRegister, } #[derive(Default, Debug)] struct AddressRegister { max: usize, current: usize, } impl<T> SetOfStacks<T> where T: Copy, { fn new(max: usize) -> Self { ...
set.size()); } }
lf) -> bool { self.stacks[self.a_reg.current].size() >= self.a_reg.max } fn switch_stack(&mut self) { self.a_reg.current = self.a_reg.current + 1; self.stacks.push(VecStack::new()); } fn stack(&mut self) -> &mut VecStack<T> { &mut self.stacks[self.a_reg.current] } ...
random
[ { "content": "fn sort_stack(stack: &mut VecStack<usize>) {\n\n let mut t_stack: VecStack<usize> = VecStack::new();\n\n let mut min = usize::max_value();\n\n let mut l_min = min;\n\n\n\n // find the min element in every iteration store to temp in reverse sorted order\n\n // and copy to original st...
Rust
cache/src/logic/serve/recent/label.rs
votecube/votecube-cache
a9ee901a7c5d50f9744ecff2aae2422dffa8ca8c
use int_hash::IntHashMap; use common::model::consts::GLOBAL_TZ_INDEX; use common::model::types::LabelId; use common::model::types::DayId; use common::model::types::MonthId; use common::model::types::PollId; use common::model::types::WeekId; use super::super::super::super::cache::cache_reader::CacheReader; use super:...
use int_hash::IntHashMap; use common::model::consts::GLOBAL_TZ_INDEX; use common::model::types::LabelId; use common::model::types::DayId; use common::model::types::MonthId; use common::model::types::PollId; use common::model::types::WeekId; use super::super::super::super::cache::cache_reader::CacheReader; use super:...
et_future_polls_by_label().next_week, block_number, global_label_id, cache.get_poll_id_byte_counts().next_week[GLOBAL_TZ_INDEX as usize]); } pub fn get_next_months_label_polls( vc_month_id: MonthId, block_number: u32, global_label_id: LabelId, cache: &Box<CacheReader + Send + Sync>...
super::utils::get_8_byte_recent_poll_ids; pub fn get_tomorrows_label_polls( vc_day_id: DayId, block_number: u32, global_label_id: LabelId, cache: &Box<CacheReader + Send + Sync>, ) -> Vec<u8> { return get_global_label_polls( cache.get_label_cache_period_ids().tomorrows_vc_day_id, ...
random
[ { "content": "use futures::future;\n\nuse futures::Future;\n\nuse net2::TcpBuilder;\n\n#[cfg(not(windows))]\n\nuse net2::unix::UnixTcpBuilderExt;\n\nuse num_cpus;\n\nuse std::io;\n\nuse std::net::ToSocketAddrs;\n\nuse std::sync::Arc;\n\nuse std::thread;\n\nuse tokio;\n\nuse tokio::net::{TcpStream, TcpListener};...
Rust
src/clang/compiler.rs
marynate/octobuild
71af3c6887c7aa66f50ff4cf893fb1436560051c
pub use super::super::compiler::*; use super::super::cache::Cache; use super::super::filter::comments::CommentsRemover; use super::super::io::memstream::MemStream; use std::io; use std::io::{Error, Read, Write}; use std::hash::{SipHasher, Hasher}; use std::path::{Path, PathBuf}; use std::process::{Command, Output, St...
pub use super::super::compiler::*; use super::super::cache::Cache; use super::super::filter::comments::CommentsRemover; use super::super::io::memstream::MemStream; use std::io; use std::io::{Error, Read, Write}; use std::hash::{SipHasher, Hasher}; use std::path::{Path, PathBuf}; use std::process::{Command, Output, St...
fn read_stderr<T: Read + Send + 'static>(stream: Option<T>) -> Receiver<Result<Vec<u8>, Error>> { let (tx, rx) = channel(); match stream { Some(mut stream) => { thread::spawn(move || { let mut ret = Vec::new(); let res = stream.read_to_end(&mut ret).map(|_| ret); tx.send(res).unwrap(); ...
fn read_stdout<T: Read>(stream: Option<T>) -> MemStream { stream.map_or(Ok(MemStream::new()), |mut stream| { let mut ret = MemStream::new(); io::copy(&mut stream, &mut ret).map(|_| ret) }).unwrap_or(MemStream::new()) }
function_block-function_prefix_line
[ { "content": "pub fn hash_write_stream(hash: &mut Hasher, stream: &mut Read) -> Result<(), Error> {\n\n\tlet mut buf: [u8; DEFAULT_BUF_SIZE] = [0; DEFAULT_BUF_SIZE];\n\n\tloop {\n\n\t\tlet size = try! (stream.read(&mut buf));\n\n\t\tif size <= 0 {\n\n\t\t\tbreak;\n\n\t\t}\n\n\t\thash.write(&buf[0..size]);\n\n\t...
Rust
src/base/ui.rs
raulanatol/rnd-cli
a65c51e38ba081222b9be4b9b41e71619bfcefda
use std::borrow::Cow; use std::error::Error; use std::io; use std::io::Stdout; use termion::{ event::Key, input::MouseTerminal, raw::IntoRawMode, screen::AlternateScreen, }; use termion::input::TermRead; use termion::raw::RawTerminal; use tui::backend::TermionBackend; use tui::layout::{Alignment, Const...
use std::borrow::Cow; use std::error::Error; use std::io; use std::io::Stdout; use termion::{ event::Key, input::MouseTerminal, raw::IntoRawMode, screen::AlternateScreen, }; use termion::input::TermRead; use termion::raw::RawTerminal; use tui::backend::TermionBackend; use tui::layout::{Alignment, Const...
pub struct UI { terminal: Terminal<TermionBackend<AlternateScreen<MouseTerminal<RawTerminal<Stdout>>>>>, events: Events, } pub enum Actions { QUIT, NONE, } impl UI { pub fn new() -> UI { UI { terminal: terminal_init().unwrap(), events: Events::new(), } ...
pub fn terminal_init() -> Result<Terminal<TermionBackend<AlternateScreen<MouseTerminal<RawTerminal<Stdout>>>>>, Box<dyn Error>> { let stdout = io::stdout().into_raw_mode()?; let stdout = MouseTerminal::from(stdout); let stdout = AlternateScreen::from(stdout); let backend = TermionBackend::new(stdout); ...
function_block-full_function
[ { "content": "use tui::widgets::ListState;\n\n\n\nuse crate::utils::numbers::get_random_to;\n\n\n\npub struct StatefulList<String> {\n\n pub state: ListState,\n\n pub items: Vec<String>,\n\n}\n\n\n\nimpl<String> StatefulList<String> {\n\n pub fn with_items(items: Vec<String>) -> StatefulList<String> {\...
Rust
src/types/list.rs
SirWindfield/markdown-composer-rs
8924a16d0107ec16859b49655c41b0d492e0abde
use crate::MarkdownElement; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::{borrow::Cow, fmt}; #[derive(Clone, Debug, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub enum ListType { Ordered, Unordered, } impl Default for ListType { fn d...
use crate::MarkdownElement; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::{borrow::Cow, fmt}; #[derive(Clone, Debug, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub enum ListType { Ordered, Unordered, } impl Default for ListType { fn d...
; write!(f, "{}", c) } } #[derive(Clone, Debug, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] pub enum NumberedListItemMarkerSeparator { Dot, Parenthesis, } impl Default for NumberedListItemMarkerSeparator { fn default() -> Self { Self::Dot ...
match self { Self::Asterisk => Cow::Borrowed("*"), Self::Dash => Cow::Borrowed("-"), Self::Numbered(separator) => Cow::Owned(format!("{}", separator)), Self::Plus => Cow::Borrowed("+"), }
if_condition
[ { "content": "#[clonable]\n\npub trait MarkdownElement: Clone + fmt::Debug {\n\n /// Renders the element to markdown.\n\n fn render(&self) -> String;\n\n}\n\n\n\n/// Implemented for all types that do implement `Display`.\n\n///\n\n/// The implementation calls the `Display::fmt` method.\n\nimpl<T> Markdown...
Rust
src/sim/clkdiv1.rs
mgottschlag/mkl25z4
3dae1bd33c66d0eeaa7d4eea1360514633a8a409
#[doc = "Reader of register CLKDIV1"] pub type R = crate::R<u32, super::CLKDIV1>; #[doc = "Writer for register CLKDIV1"] pub type W = crate::W<u32, super::CLKDIV1>; #[doc = "Register CLKDIV1 `reset()`'s with value 0x0001_0000"] impl crate::ResetValue for super::CLKDIV1 { type Type = u32; #[inline(always)] f...
#[doc = "Reader of register CLKDIV1"] pub type R = crate::R<u32, super::CLKDIV1>; #[doc = "Writer for register CLKDIV1"] pub type W = crate::W<u32, super::CLKDIV1>; #[doc = "Register CLKDIV1 `reset()`'s with value 0x0001_0000"] impl crate::ResetValue for super::CLKDIV1 { type Type = u32; #[inline(always)] f...
} #[doc = "Checks if the value of the field is `_0000`"] #[inline(always)] pub fn is_0000(&self) -> bool { *self == OUTDIV1_A::_0000 } #[doc = "Checks if the value of the field is `_0001`"] #[inline(always)] pub fn is_0001(&self) -> bool { *self == OUTDIV1_A::_0001 }...
match self.bits { 0 => OUTDIV1_A::_0000, 1 => OUTDIV1_A::_0001, 2 => OUTDIV1_A::_0010, 3 => OUTDIV1_A::_0011, 4 => OUTDIV1_A::_0100, 5 => OUTDIV1_A::_0101, 6 => OUTDIV1_A::_0110, 7 => OUTDIV1_A::_0111, 8 => OUTDI...
if_condition
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/vcf/reader.rs
togovar/vcf2rdf
edef7ecb429c51a826716ea633d159ae716858a7
use std::collections::HashMap; use std::ffi::{CString, OsString}; use std::fmt::{Display, Formatter}; use std::fs::File; use std::io; use std::io::{BufRead, BufWriter, Write}; use std::path::{Path, PathBuf}; use log::*; use rust_htslib::bcf; use rust_htslib::bcf::Read; use rust_htslib::errors::Error as htslib_error; u...
use std::collections::HashMap; use std::ffi::{CString, OsString}; use std::fmt::{Display, Formatter}; use std::fs::File; use std::io; use std::io::{BufRead, BufWriter, Write}; use std::path::{Path, PathBuf}; use log::*; use rust_htslib::bcf; use rust_htslib::bcf::Read; use rust_htslib::errors::Error as htslib_error; u...
allelic_record() { let records = read_dbsnp_example_as_vec(); assert_eq!(records[14].rid(), Some(1)); assert_eq!(records[14].pos(), 10018); assert_eq!(records[14].id(), b"rs1558169388".to_vec()); assert_eq!(records[14].alleles(), vec![b"C" as &[u8], b"CACA", b"CACG"]); a...
!(contig[0].name, "NC_000001.10"); assert_eq!(contig[23].name, "NC_000024.9"); } #[test] fn test_count() { let vcf = Reader::from_path("test/dbsnp_example.vcf.gz").expect("Error opening file."); assert_eq!(vcf.count(), 250); } fn read_vcf_as_vec<P: AsRef<Path>>(path: P) ->...
random
[ { "content": "fn extract_string(record: &bcf::record::Record, key: &String) -> Option<Vec<InfoValue>> {\n\n let info = record.info(key.as_bytes());\n\n\n\n info.string().ok().and_then(|string| {\n\n string.and_then(|v| {\n\n Some(\n\n v.iter()\n\n .map(|...
Rust
todorpc_client_quic/src/lib.rs
hjiayz/todorpc
bc420f18871b1ffd8e4f155613ceb8e362b61212
use log::{debug, info}; use quinn::Connection; use quinn::Endpoint; use quinn::EndpointBuilder; use quinn::RecvStream; use quinn::SendStream; use quinn::VarInt; use serde::de::DeserializeOwned; use std::marker::Unpin; use std::net::SocketAddr; use todorpc::*; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; u...
use log::{debug, info}; use quinn::Connection; use quinn::Endpoint; use quinn::EndpointBuilder; use quinn::RecvStream; use quinn::SendStream; use quinn::VarInt; use serde::de::DeserializeOwned; use std::marker::Unpin; use std::net::SocketAddr; use todorpc::*; use tokio::io::AsyncReadExt; use tokio::io::AsyncWriteExt; u...
Ok(recv) } } pub struct ConnectInfo { timeout: Duration, addr: SocketAddr, hostname: String, ep: Endpoint, } impl ConnectInfo { async fn try_connect(&self) -> Result<Connection> { let local_addr = match self.addr { SocketAddr::V4(_) => "0.0.0.0:0", So...
ct( timeout: i32, remote_addr: SocketAddr, hostname: &str, builder: EndpointBuilder, ) -> Result<QuicClient> { let (endpoint, _) = builder.bind(&"[::]:0".parse().unwrap()).map_err(|e| { debug!("{}", e); Error::ConnectionFailed })?; let ...
random
[ { "content": "fn decode<R: RPC + Verify>(bytes: &[u8]) -> Result<RPCResult<R>, R::Return> {\n\n match deserialize::<R>(bytes) {\n\n Ok(r) => r.verify_result().map(Ok),\n\n Err(e) => {\n\n debug!(\"{}\", e);\n\n Ok(Err(Error::DeserializeFaild))\n\n }\n\n }\n\n}\n\...
Rust
src/platform_impl/macos/util/async.rs
crlf0710/winit
1f86c8301e66f1568fdbece41ccb5912243eb57e
use std::{os::raw::c_void, sync::{Mutex, Weak}}; use cocoa::{ appkit::{CGFloat, NSWindow, NSWindowStyleMask}, base::{id, nil}, foundation::{NSAutoreleasePool, NSPoint, NSSize}, }; use dispatch::ffi::{dispatch_async_f, dispatch_get_main_queue, dispatch_sync_f}; use dpi::LogicalSize; use platform_impl::plat...
use std::{os::raw::c_void, sync::{Mutex, Weak}}; use cocoa::{ appkit::{CGFloat, NSWindow, NSWindowStyleMask}, base::{id, nil}, foundation::{NSAutoreleasePool, NSPoint, NSSize}, }; use dispatch::ffi::{dispatch_async_f, dispatch_get_main_queue, dispatch_sync_f}; use dpi::LogicalSize; use platform_impl::plat...
struct OrderOutData { nswindow: id, } impl OrderOutData { fn new_ptr(nswindow: id) -> *mut Self { Box::into_raw(Box::new(OrderOutData { nswindow })) } } extern fn order_out_callback(context: *mut c_void) { unsafe { let context_ptr = context as *mut OrderOutData; { l...
shared_state, ); dispatch_async_f( dispatch_get_main_queue(), context as *mut _, toggle_full_screen_callback, ); }
function_block-function_prefix_line
[ { "content": "pub fn new_view(nswindow: id) -> (IdRef, Weak<Mutex<util::Cursor>>) {\n\n let cursor = Default::default();\n\n let cursor_access = Arc::downgrade(&cursor);\n\n let state = ViewState {\n\n nswindow,\n\n cursor,\n\n ime_spot: None,\n\n raw_characters: None,\n\n ...
Rust
src/http/uri.rs
LunarCoffee/Lucent
d8b0669488c032a9131782a00ee603ae6b29560e
use std::{ collections::HashMap, fmt::{self, Display, Formatter}, }; use crate::{ consts, http::{ parser::{MessageParseError, MessageParseResult}, request::Method, }, util, }; pub struct Authority { pub user_info: Option<String>, pub host: String, pub port: Op...
use std::{ collections::HashMap, fmt::{self, Display, Formatter}, }; use crate::{ consts, http::{ parser::{MessageParseError, MessageParseResult}, request::Method, }, util, }; pub struct Authority { pub user_info: Option<String>, pub host: String, pub port: Op...
ng(); err_if!(!accept_user || !info.chars().all(is_user_info_char)); authority_part = &authority_part[index + 1..]; Some(decode_percent(info).ok_or(MessageParseError::InvalidUri)?) } _ => None, ...
} else if self.raw == "*" && *self.method == Method::Options { Ok(Uri::AsteriskForm) } else if *self.method == Method::Connect { let authority = self.parse_authority(false)?; Ok(Uri::AuthorityForm { authority }) } else if self.raw.starts_...
random
[ { "content": "// Logs details about a request.\n\npub fn req(status: impl Display, method: Method, target: impl Display, target_suffix: &str, host: &str) {\n\n info(format!(\"({}) {} {}{} ({})\", status, method, target, target_suffix, host));\n\n}\n", "file_path": "src/log.rs", "rank": 0, "score"...
Rust
src/ppu/mod.rs
markglenn/nesrs
4f8cef5a8429234589571599ccd7fc02c4802b90
mod address_register; mod control_register; mod mask_register; mod scroll_register; mod status_register; use std::fmt::Debug; use address_register::AddressRegister; use control_register::ControlRegister; use mask_register::MaskRegister; use scroll_register::ScrollRegister; use status_register::StatusRegister; use cr...
mod address_register; mod control_register; mod mask_register; mod scroll_register; mod status_register; use std::fmt::Debug; use address_register::AddressRegister; use control_register::ControlRegister; use mask_register::MaskRegister; use scroll_register::ScrollRegister; use status_register::StatusRegister; use cr...
a: &[u8]) { for i in 0..256 { self.write_oam_data(data[i]); } } fn mirror_vram_addr(&self, addr: u16) -> usize { let vram_index = (addr & 0x0FFF) as usize; let name_table = vram_index / 0x400; match (&self.mirroring, name_table...
le[self.mirror_palette(address)] } _ => unimplemented!("Attempted to read from #{:04X}", address), } } pub fn write_data(&mut self, data: u8) { let address = self.addr.get(); self.addr.increment(self.ctrl.vram_address_increment()); match address { ...
random
[ { "content": "fn sprite_palette(ppu: &Ppu, pallete_idx: u8) -> [u8; 4] {\n\n let start = 0x11 + (pallete_idx * 4) as usize;\n\n [\n\n 0,\n\n ppu.palette_table[start],\n\n ppu.palette_table[start + 1],\n\n ppu.palette_table[start + 2],\n\n ]\n\n}\n\n\n", "file_path": "src...
Rust
csml_interpreter/src/data/literal.rs
CSML-by-Clevy/csml-interpreter
d76d92a8a2fef4a24ebe2ae7ecd7baa04c2a5c4a
use crate::data::position::Position; use crate::data::primitive::{Primitive, PrimitiveObject, PrimitiveString}; use crate::data::{Data, Interval}; use crate::error_format::*; use std::cmp::Ordering; use std::collections::HashMap; use std::ops::Add; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serializ...
use crate::data::position::Position; use crate::data::primitive::{Primitive, PrimitiveObject, PrimitiveString}; use crate::data::{Data, Interval}; use crate::error_format::*; use std::cmp::Ordering; use std::collections::HashMap; use std::ops::Add; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serializ...
match map.get(key) { Some(value) => Ok(value.to_owned()), None => { let mut lit = PrimitiveObject::get_literal(map, interval); let error_msg = format!("get_info() failed, key '{}' not found", key); ...
let key = Literal::get_value::<String>( &key.primitive, &data.context.flow, interval, usage.to_owned(), )?;
assignment_statement
[ { "content": "pub fn exists(args: ArgsType, data: &mut Data, interval: Interval) -> Result<Literal, ErrorInfo> {\n\n match args.get(\"string\", 0) {\n\n Some(literal) if literal.primitive.get_type() == PrimitiveType::PrimitiveString => {\n\n let value = literal.primitive.to_string();\n\n ...
Rust
src/bin_utils/loaders.rs
isabella232/Evokit
54c21ff318b623a9c1ac168a2323ab2fdb4598cf
extern crate es_core; extern crate es_data; extern crate rand; extern crate rand_xorshift; use std::fmt::Debug; use std::fs::File; use self::rand::distributions::{Distribution, Uniform}; use self::rand::SeedableRng; use self::rand_xorshift::XorShiftRng; use self::es_core::model::sampler::ModelGS; use self::es_core::...
extern crate es_core; extern crate es_data; extern crate rand; extern crate rand_xorshift; use std::fmt::Debug; use std::fs::File; use self::rand::distributions::{Distribution, Uniform}; use self::rand::SeedableRng; use self::rand_xorshift::XorShiftRng; use self::es_core::model::sampler::ModelGS; use self::es_core::...
(dims, train) } pub fn build_l2r_datasets< Data: 'static + Debug + Dimension<Out = usize> + Send + Sync + Clone, D: DataParse<Out = Data>, >( fname: &str, vname: Option<String>, mini_batch: Option<f32>, freeze: u32, seed: u32, parser: &D, ) -> ( usize, Box<dyn Dataset<Data,...
let train: Box<dyn Dataset<Data, Iter = EagerIterator<Data>> + Send + Sync> = match mini_batch { Some(p) => { assert!(p > 0.0 && p < 1.0); assert!(freeze > 0); Box::new(MinibatchDataset::new(train_set, p, freeze, seed + 1)) } None => Box::new(StaticDataset::ne...
assignment_statement
[ { "content": "/// Given a file path, loads it into a dataset\n\npub fn read_libsvm<D: Debug + Send + Clone, F: DataParse<Out = D>>(\n\n fmt: &F,\n\n fname: &str,\n\n) -> Result<Vec<Grouping<F::Out>>, Error> {\n\n let f = File::open(fname)?;\n\n let br = BufReader::new(f);\n\n let mut y = Vec::new...
Rust
example/ciphers/worker-rs/client/src/apis/tasks_api.rs
swallez/tasques
819361787a0683e17cbf0f8fe6febb556f50d14f
/* * Tasques API * * A Task queue backed by Elasticsearch * * The version of the OpenAPI document: 0.0.1 * * Generated by: https://openapi-generator.tech */ use std::borrow::Borrow; #[allow(unused_imports)] use std::option::Option; use std::rc::Rc; use reqwest; use super::{configuration, Error}; pub struct ...
/* * Tasques API * * A Task queue backed by Elasticsearch * * The version of the OpenAPI document: 0.0.1 * * Generated by: https://openapi-generator.tech */ use std::borrow::Borrow; #[allow(unused_imports)] use std::option::Option; use std::rc::Rc; use reqwest; use super::{configuration, Error}; pub struct ...
req_builder = req_builder.json(&new_task); let req = req_builder.build()?; Ok(client.execute(req)?.error_for_status()?.json()?) } fn get_existing_task(&self, queue: &str, id: &str) -> Result<crate::models::TaskTask, Error> { let configuration: &configuration::Configu...
if let Some(ref user_agent) = configuration.user_agent { req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); }
if_condition
[ { "content": "\tQueue string\n", "file_path": "client/tasks/report_on_claimed_task_parameters.go", "rank": 1, "score": 279408.1154471866 }, { "content": "\tID string\n", "file_path": "client/tasks/report_on_claimed_task_parameters.go", "rank": 2, "score": 279375.925249304 }, ...
Rust
examples/qrcodeflow.rs
uklotzde/flowcalc
cfa28c9fce02d584a909d45a398326dc8ab41b54
use flowcalc::{flow::*, node::*, port::*}; use std::{cell::RefCell, rc::Rc, time::Instant}; use rand::{self, rngs::ThreadRng, Rng as _}; #[derive(Debug, Clone)] enum Value { Text(String), GrayImage(image::GrayImage), } #[derive(Debug)] struct RandomAsciiTextSource { num_chars: usize, rng: ThreadRng,...
use flowcalc::{flow::*, node::*, port::*}; use std::{cell::RefCell, rc::Rc, time::Instant}; use rand::{self, rngs::ThreadRng, Rng as _}; #[derive(Debug, Clone)] enum Value { Text(String), GrayImage(image::GrayImage), } #[derive(Debug)] struct RandomAsciiTextSource { num_chars: usize, rng: ThreadRng,...
ken: AccessToken, _input_index: PortIndex, ) -> Option<Packet<(), Value>> { self.input.try_dispatch_packet() } } impl NodeOutputs<(), Value> for TextQrEncoder { fn num_outputs(&self) -> usize { 1 } fn accept_output_packet( &mut self, _token: AccessToken, ...
lf, _token: AccessToken, _input_index: PortIndex, ) -> Option<Packet<(), Value>> { unimplemented!(); } } impl NodeOutputs<(), Value> for RandomAsciiTextSource { fn num_outputs(&self) -> usize { 1 } fn accept_output_packet( &mut self, _token: AccessTo...
random
[]
Rust
src/catalogue/manga.rs
dashrandom/tanoshi
9fe5bb1bd1160ff204cd5237055d9fbbd21d2b7e
use super::Chapter; use crate::{context::GlobalContext, user}; use async_graphql::{Context, Object, Result}; #[derive(Debug)] pub struct Manga { pub id: i64, pub source_id: i64, pub title: String, pub author: Vec<String>, pub genre: Vec<String>, pub status: Option<String>, pub description: ...
use super::Chapter; use crate::{context::GlobalContext, user}; use async_graphql::{Context, Object, Result}; #[derive(Debug)] pub struct Manga { pub id: i64, pub source_id: i64, pub title: String, pub author: Vec<String>, pub genre: Vec<String>, pub status: Option<String>, pub description: ...
db.insert_chapters(&chapters).await?; Ok(db .get_chapters_by_manga_id(manga_id) .await? .into_iter() .map(|c| c.into()) .collect()) } async fn chapter( &self, ctx: &Context<'_>, #[graphql(desc = "chapter id")...
let chapters: Vec<crate::db::model::Chapter> = { let extensions = ctx.extensions.clone(); extensions .get_chapters(self.source_id, self.path.clone()) .await? .into_iter() .map(|c| { let mut c: crate::db::model::C...
assignment_statement
[ { "content": "fn map_entry_to_chapter(source_id: i64, path: &Path) -> Option<ChapterInfo> {\n\n let modified = match path\n\n .metadata()\n\n .ok()\n\n .and_then(|metadata| metadata.modified().ok())\n\n .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())\n\n {\n\n ...
Rust
qsrs/src/utils.rs
ejwilson3/qsearch
9f966db0f3d54fdaff15f1dd7a0e1d28de55b1b4
use ndarray::Array2; use num_complex::Complex64; use squaremat::SquareMatrix; use crate::{i, r}; use std::f64::consts::{E, PI}; pub fn rot_x(theta: f64) -> SquareMatrix { let half_theta = Complex64::new(theta / 2.0, 0.0); let negi = Complex64::new(0.0, -1.0); SquareMatrix::from_vec( vec![ ...
use ndarray::Array2; use num_complex::Complex64; use squaremat::SquareMatrix; use crate::{i, r}; use std::f64::consts::{E, PI}; pub fn rot_x(theta: f64) -> SquareMatrix { let half_theta = Complex64::new(theta / 2.0, 0.0); let negi = Complex64::new(0.0, -1.0); SquareMatrix::from_vec( vec![ ...
pub fn matrix_residuals_jac( u: &SquareMatrix, _m: &SquareMatrix, jacs: &[SquareMatrix], ) -> Array2<f64> { let u_h = u.H(); Array2::from_shape_vec( (jacs.len(), u.size * u.size * 2), jacs.iter().fold(Vec::new(), |mut acc, j| { let m = j.matmul(&u_h.clone()); ...
quareMatrix, b: &SquareMatrix, i: &Array2<f64>) -> Vec<f64> { let m = b.matmul(&a.H()); let (re, im) = m.split_complex(); let r = re - i; r.iter().chain(im.iter()).copied().collect() }
function_block-function_prefixed
[ { "content": "pub fn astar(dsq: f64, depth: usize) -> f64 {\n\n 10.0 * dsq + depth as f64\n\n}\n", "file_path": "qsrs/src/heuristic.rs", "rank": 1, "score": 249964.7636419325 }, { "content": "fn log_2(x: usize) -> usize {\n\n num_bits::<usize>() - x.leading_zeros() as usize - 1\n\n}\n\...
Rust
src/core/access_tracker/history.rs
cateiru/servant
bb861ba8f02f722acb2265e1cd17b0287ebea0dc
use crate::utils::graph as util_graph; use chrono::{DateTime, Datelike, FixedOffset, Local}; use chrono_tz::{Asia::Tokyo, Tz}; use reqwest; use rustc_serialize::{json, json::Json}; use serde::{Deserialize, Serialize}; use std::error::Error; use termion::color; use whois::WhoIs; #[derive(Debug, Deserialize)] struct His...
use crate::utils::graph as util_graph; use chrono::{DateTime, Datelike, FixedOffset, Local}; use chrono_tz::{Asia::Tokyo, Tz}; use reqwest; use rustc_serialize::{json, json::Json}; use serde::{Deserialize, Serialize}; use std::error::Error; use termion::color; use whois::WhoIs; #[derive(Debug, Deserialize)] struct His...
pub fn print_oneline(&self) -> Result<(), Box<dyn Error>> { println!( "💿 {}{}{} - {}{}{}({}{}{})", color::Fg(color::Magenta), self.user_agent.name, color::Fg(color::Reset), color::Fg(color::Magenta), self.ip, color::Fg(co...
pub fn print(&self, is_whois: bool, is_user_agent: bool) -> Result<(), Box<dyn Error>> { println!( "💿 {}{}{}", color::Fg(color::Magenta), self.unique_id, color::Fg(color::Reset) ); println!( "\t📆 Date: {}{}{}", color::Fg(c...
function_block-full_function
[ { "content": "pub fn plot_barchart(data: Vec<(DateTime<Tz>, usize)>) -> Result<(), Box<dyn Error>> {\n\n let max = data.iter().max_by(|x, y| x.1.cmp(&y.1));\n\n let term_size = terminal_size()?;\n\n\n\n if let Some(max) = max {\n\n let max_index = data.len();\n\n\n\n if max_index != 0 {\n...
Rust
src/handlers/storage/handler.rs
bennyz/qarax
2a9e8c6f6b7bfd93fd6dc19886d8af47634e461f
use super::local_storage::LocalStorage; use super::storage::Storage; use super::*; use crate::handlers::volumes::NewVolumeRequest; use crate::models::storage as storage_model; use crate::models::storage::{NewStorage, Storage as StorageModel}; use crate::models::storage::{StorageConfig, StorageError, StorageName, Storag...
use super::local_storage::LocalStorage; use super::storage::Storage; use super::*; use crate::handlers::volumes::NewVolumeRequest; use crate::models::storage as storage_model; use crate::models::storage::{NewStorage, Storage as StorageModel}; use crate::models::storage::{StorageConfig, StorageError, StorageName, Storag...
pub(crate) async fn create_volume_concrete( storage_id: &Uuid, new_volume: NewVolume, env: Environment, ) -> Result<Uuid, ServerError> { let storage: StorageModel = storage_model::by_id(env.db(), &storage_id).await?; let concrete_storage = match storage.storage_type { StorageType::Local =>...
Path(storage_id): Path<Uuid>, Json(volume_request): Json<NewVolumeRequest>, ) -> Result<ApiResponse<Uuid>, ServerError> { let new_volume = NewVolume::try_from(volume_request)?; let volume_id = create_volume_concrete(&storage_id, new_volume, env).await?; Ok(ApiResponse { data: volume_id, ...
function_block-function_prefix_line
[ { "content": "pub fn storage() -> Router {\n\n Router::new()\n\n .route(\"/:id\", get(storage::handler::get))\n\n .route(\"/\", get(storage::handler::list).post(storage::handler::add))\n\n .route(\"/:id/volumes\", post(storage::handler::create_volume))\n\n}\n\n\n", "file_path": "src/...
Rust
src/manager/var_order.rs
GouwarPower/rsdd
2e7c3871edbebc57fd28fdd5b1d386f7590ebde5
use repr::bdd::*; use repr::var_label::VarLabel; use std::slice::Iter; use util; pub struct VarOrder { var_to_pos: Vec<usize>, pos_to_var: Vec<usize>, } impl VarOrder { pub fn new(order: Vec<VarLabel>) -> VarOrder { let mut v = util::malloc_vec(order.len()); let mut pos...
use repr::bdd::*; use repr::var_label::VarLabel; use std::slice::Iter; use util; pub struct VarOrder { var_to_pos: Vec<usize>, pos_to_var: Vec<usize>, } impl VarOrder { pub fn new(order: Vec<VarLabel>) -> VarOrder { let mut v = util::malloc_vec(order.len()); let mut pos...
pub fn first_essential(&self, a: BddPtr, b: BddPtr, c: BddPtr) -> VarLabel { let f1 = self.first(a, b); let f2 = self.first(f1, c); f2.label() } pub fn get_vec(&self) -> Vec<usize> { self.var_to_pos.clone() } pub fn last_var(&self) -> VarLabel { ...
pub fn above(&self, a: VarLabel) -> Option<VarLabel> { let this_level = self.var_to_pos[a.value() as usize]; if this_level == 0 { None } else { Some(VarLabel::new(self.pos_to_var[this_level - 1] as u64)) } }
function_block-full_function
[ { "content": "pub fn from_cnf(cnf: &Cnf) -> Hypergraph<VarLabel> {\n\n let mut vars: HashSet<VarLabel> = HashSet::new();\n\n let mut hedges: Vec<HashSet<VarLabel>> = vec![];\n\n\n\n for clause in cnf.clauses() {\n\n let hedge = clause\n\n .iter()\n\n .map(|l| {\n\n ...
Rust
tests/arp.rs
faern/rips-old
abff3837894a404895c6c2dc11ec45377f6dc811
extern crate pnet; extern crate ipnetwork; extern crate rips; #[macro_use] extern crate lazy_static; use ipnetwork::Ipv4Network; use pnet::packet::{MutablePacket, Packet}; use pnet::packet::arp::{ArpPacket, MutableArpPacket, ArpOperations}; use pnet::packet::ethernet::{EthernetPacket, MutableEthernetPacket}; use rip...
extern crate pnet; extern crate ipnetwork; extern crate rips; #[macro_use] extern crate lazy_static; use ipnetwork::Ipv4Network; use pnet::packet::{MutablePacket, Packet}; use pnet::packet::arp::{ArpPacket, MutableArpPacket, ArpOperations}; use pnet::packet::ethernet::{EthernetPacket, MutableEthernetPacket}; use rip...
fn send_arp_request(inject_handle: mpsc::Sender<io::Result<Box<[u8]>>>) { let mut buffer = vec![0; EthernetPacket::minimum_packet_size() + ArpPacket::minimum_packet_size()]; { let mut eth_pkg = MutableEthernetPacket::new(&mut buffer[..]).unwrap(); eth_pkg.set_ether...
dr(MacAddr::new(9, 8, 7, 6, 5, 4)); arp_pkg.set_sender_proto_addr(Ipv4Addr::new(10, 0, 0, 1)); } inject_handle.send(Ok(buffer.into_boxed_slice())).unwrap(); }
function_block-function_prefixed
[ { "content": "fn dummy_ipv4_tx(dst_ip: Ipv4Addr, dst_mac: MacAddr) -> DummyIpv4Tx {\n\n let mut dummy = helper::dummy_stack();\n\n dummy.stack.interface(&dummy.interface).unwrap().arp_table().insert(dst_ip, dst_mac);\n\n\n\n let net = Ipv4Network::new(*SRC_IP, 24).unwrap();\n\n dummy.stack.add_ipv4(...
Rust
src/battle/mod.rs
ravecrab/bevy-jam
1b30bb06844d823143dc379aa84fc6e1d50860ba
mod battle_tick; mod components; mod ui; use bevy::prelude::{Plugin as PluginTrait, *}; use bevy_kira_audio::Audio; use rand::{seq::SliceRandom, thread_rng}; use crate::{ battle::{ battle_tick::{ bring_out_your_dead_oppo, bring_out_your_dead_player, oppo_battle_tick, player_battle_...
mod battle_tick; mod components; mod ui; use bevy::prelude::{Plugin as PluginTrait, *}; use bevy_kira_audio::Audio; use rand::{seq::SliceRandom, thread_rng}; use crate::{ battle::{ battle_tick::{ bring_out_your_dead_oppo, bring_out_your_dead_player, oppo_battle_tick, player_battle_...
if card.0.name == "Deviant Cat-ipular" { audio.play(asset_server.load("sounds/nya-dialog.wav")); } let texture_handle = asset_server.load(&card.0.sprites); let texture_atlas = TextureAtlas::from_grid( texture_han...
if let Ok(sprite_entity) = sprite_query.get_single() { commands.entity(sprite_entity).despawn(); }
if_condition
[ { "content": "#[allow(dead_code)]\n\npub fn create_ui(parent: &mut ChildBuilder, card_back: &Handle<Image>) {\n\n parent\n\n .spawn_bundle(NodeBundle {\n\n style: Style {\n\n justify_content: JustifyContent::FlexEnd,\n\n padding: Rect::all(Val::Px(30.)),\n\n ...
Rust
src/main.rs
VeyronSakai/bevy_shooting
a4bf42d54ca39b0cd4a463552529089d78cbc438
mod bullet; mod common; mod enemy; mod explosion; mod physics; mod player; use crate::bullet::*; use crate::common::*; use crate::enemy::*; use crate::explosion::*; use crate::physics::*; use crate::player::*; use bevy::prelude::*; use bevy::sprite::collide_aabb::collide; const PLAYER_SPRITE: &str = "player.png"; con...
mod bullet; mod common; mod enemy; mod explosion; mod physics; mod player; use crate::bullet::*; use crate::common::*; use crate::enemy::*; use crate::explosion::*; use crate::physics::*; use crate::player::*; use bevy::prelude::*; use bevy::sprite::collide_aabb::collide; const PLAYER_SPRITE: &str = "player.png"; con...
; match collision { Some(collision) => collision, None => continue, }; commands .spawn_bundle(SpriteSheetBundle { texture_atlas: materials.explosion.clone(), transform: Transform { ...
collide( bullet_transform.translation, bullet_sprite.size * Vec2::from(bullet_transform.scale), enemy_transform.translation, enemy_sprite.size * Vec2::from(enemy_transform.scale), )
call_expression
[ { "content": "fn update_player_pos(mut player_query: Query<(&mut Transform, &Velocity), With<Player>>) {\n\n if let Ok((mut transform, velocity)) = player_query.single_mut() {\n\n transform.translation.x += velocity.dir.x * velocity.speed * 0.2;\n\n transform.translation.y += velocity.dir.y * v...
Rust
src/wgpu/texture/reshaper/mod.rs
freesig/nannou
fcd857d4ced73c8716e7641c59a72210ece95ad6
use crate::wgpu; #[derive(Debug)] pub struct Reshaper { _vs_mod: wgpu::ShaderModule, _fs_mod: wgpu::ShaderModule, bind_group_layout: wgpu::BindGroupLayout, bind_group: wgpu::BindGroup, render_pipeline: wgpu::RenderPipeline, sampler: wgpu::Sampler, uniform_buffer: Option<wgpu::Buffer>, v...
use crate::wgpu; #[derive(Debug)] pub struct Reshaper { _vs_mod: wgpu::ShaderModule, _fs_mod: wgpu::ShaderModule, bind_group_layout: wgpu::BindGroupLayout, bind_group: wgpu::BindGroup, render_pipeline: wgpu::RenderPipeline, sampler: wgpu::Sampler, uniform_buffer: Option<wgpu::Buffer>, v...
pub fn encode_render_pass( &self, dst_texture: &wgpu::TextureView, encoder: &mut wgpu::CommandEncoder, ) { let vertex_range = 0..VERTICES.len() as u32; let instance_range = 0..1; let render_pass_desc = wgpu::RenderPassDescriptor { color_at...
pub fn new( device: &wgpu::Device, src_texture: &wgpu::TextureView, src_sample_count: u32, dst_sample_count: u32, dst_format: wgpu::TextureFormat, ) -> Self { let vs = include_bytes!("shaders/vert.spv"); let vs_spirv = wgpu::read_spirv(std::io::Cursor...
function_block-full_function
[ { "content": "/// Types used as vertices that can be used to describe geometric points in space.\n\npub trait Vertex: Clone + Copy + PartialEq {\n\n /// The values used to describe the vertex position.\n\n type Scalar: BaseNum;\n\n}\n\n\n", "file_path": "src/geom/vertex.rs", "rank": 0, "score"...
Rust
crates/tako/src/tests/integration/test_resources.rs
User3574/hyperqueue
d4dea5a805925cb624eb81da65840d5a8226d4a9
use std::time::{Duration, Instant}; use crate::common::resources::CpuRequest; use tokio::time::sleep; use crate::tests::integration::utils::api::{get_latest_overview, wait_for_task_start}; use crate::tests::integration::utils::server::run_test; use crate::tests::integration::utils::task::{ simple_args, simple_tas...
use std::time::{Duration, Instant}; use crate::common::resources::CpuRequest; use tokio::time::sleep; use crate::tests::integration::utils::api::{get_latest_overview, wait_for_task_start}; use crate::tests::integration::utils::server::run_test; use crate::tests::integration::utils::task::{ simple_args, simple_tas...
.await; } #[tokio::test] async fn test_submit_2_sleeps_on_separated_2() { run_test(Default::default(), |mut handler| async move { handler .submit( GraphBuilder::default() .task(simple_task(&["sleep", "1"], 1)) .task(simple_task(&["sle...
run_test(Default::default(), |mut handler| async move { handler .submit( GraphBuilder::default() .task(simple_task(&["sleep", "1"], 1)) .task(simple_task(&["sleep", "1"], 2)) .build(), ) .await; ...
call_expression
[ { "content": "pub fn on_new_worker(core: &mut Core, comm: &mut impl Comm, worker: Worker) {\n\n comm.broadcast_worker_message(&ToWorkerMessage::NewWorker(NewWorkerMsg {\n\n worker_id: worker.id,\n\n address: worker.configuration.listen_address.clone(),\n\n }));\n\n\n\n comm.send_client_wo...
Rust
file_syncer.rs/src/directory_watcher/mod.rs
corka149/change_detector
3ff60e904d610ffd739ed367758eaee55e22cdd2
mod checksum; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::{thread, time}; use std::error::Error; use std::fs::{ReadDir, Metadata}; use error::PathError; pub struct DirectoryWatcher { secs_interval: u64, file_register: HashMap<PathBuf, u32>, dir: PathBuf, recurisve: bo...
mod checksum; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::{thread, time}; use std::error::Error; use std::fs::{ReadDir, Metadata}; use error::PathError; pub struct DirectoryWatcher { secs_interval: u64, file_register: HashMap<PathBuf, u32>, dir: PathBuf, recurisve: bo...
= file.write_all(content).unwrap(); } }
let files = self.collect_changed_files(&path)?; changed_files.extend(files); } } } Ok(changed_files) } fn register_file(&mut self, path: PathBuf, checksum: u32) { self.file_register.insert(path, checksum); } ...
random
[ { "content": "/// Checks if the checksum of a file is the same\n\npub fn has_file_changed(file_path: &Path, crc32_ieee_checksum: &u32) -> (bool, u32) {\n\n\t\n\n match read_file(file_path) {\n\n Ok(bytes) => {\n\n let calc_checksum = calculate_crc32(&bytes);\n\n (calc_che...
Rust
src/gen/pawn.rs
ratosh/rust_move_gen
ae3864008c786db4356d63d0d1c802da9e59fc60
use super::slider::*; use bb::*; use mv_list::MoveList; use piece::*; use position::Position; use side::{Side, WHITE}; use square; pub fn pawn_moves<L: MoveList>( position: &Position, capture_mask: BB, push_mask: BB, from_mask: BB, list: &mut L, ) { pawn_pushes(position, push_mask, from_mask, ...
use super::slider::*; use bb::*; use mv_list::MoveList; use piece::*; use position::Position; use side::{Side, WHITE}; use square; pub fn pawn_moves<L: MoveList>( position: &Position, capture_mask: BB, push_mask: BB, from_mask: BB, list: &mut L, ) { pawn_pushes(position, push_mask, from_mask, ...
t = MoveVec::new(); pawn_moves::<MoveVec>(position, !EMPTY, !EMPTY, !EMPTY, &mut list); assert_eq!(list.len(), 4); assert_list_includes_moves(&list, &["b7b8=N", "b7b8=B", "b7b8=R", "b7b8=Q"]); let position = &Position::from_fen("rnbqkbnr/8/8/8/8/8/PPPpPPPP/RN3BNR b").unwrap(); ...
capture_mask: BB, push_mask: BB, from_mask: BB, list: &mut L, ) { let move_mask = capture_mask | push_mask; let stm = position.state().stm; let piece = PAWN.pc(stm); let movers = position.bb_pc(piece) & from_mask; if movers == EMPTY { return; } let enemies = position...
random
[]
Rust
macros-internals/src/schema/parse.rs
datalove-app/ipld
ff24fd2440980e371fd110b32b5308975cb40fe7
use super::*; use crate::dev::*; use proc_macro2::TokenStream; use std::fmt; use syn::{ braced, parse::{Error as ParseError, Parse, ParseStream, Peek, Result as ParseResult}, parse_quote, parse_str, token, Generics, Ident, ItemFn, Lit, LitStr, Meta, MetaNameValue, Path, Token, Type, Visibility, }; impl...
use super::*; use crate::dev::*; use proc_macro2::TokenStream; use std::fmt; use syn::{ braced, parse::{Error as ParseError, Parse, ParseStream, Peek, Result as ParseResult}, parse_quote, parse_str, token, Generics, Ident, ItemFn, Lit, LitStr, Meta, MetaNameValue, Path, Token, Type, Visibility, }; impl...
} pub(crate) fn parse_rest(input: ParseStream) -> ParseResult<TokenStream> { let args; braced!(args in input); Ok(args.parse::<TokenStream>()?) } #[doc(hidden)] #[macro_export(local_inner_macros)] macro_rules! impl_advanced_parse { ($def:ident => $type:ident, $repr_variant:ident) => { impl sy...
fn parse(input: ParseStream) -> ParseResult<Self> { let mut vec = Vec::new(); while !input.is_empty() { vec.push(input.parse::<T>()?); } Ok(Self(vec)) }
function_block-full_function
[ { "content": "fn field_typedef(field: &UnionField<LitStr>) -> TokenStream {\n\n let attrs = &field.attrs;\n\n let value = &field.value;\n\n let key = &field.key;\n\n\n\n let value_tokens: TokenStream = if let Some(wrapper_type) = &field.wrapper {\n\n quote!(#wrapper_type<#value>)\n\n } els...
Rust
src/tests.rs
ing-systems/crcxx
fb40e364c0e897d8070e5afcaf7d05d966fc19d1
use std::prelude::v1::*; use rand::{thread_rng, Rng}; use super::*; const ITERATIONS: usize = 10_000; const MIN_DATA_SIZE: usize = 1; const MAX_DATA_SIZE: usize = 4096; fn gen_rand_data(min_data_size: usize, max_data_size: usize) -> Box<[u8]> { let mut rng = thread_rng(); let data_size = rng.gen_range(min_d...
use std::prelude::v1::*; use rand::{thread_rng, Rng}; use super::*; const ITERATIONS: usize = 10_000; const MIN_DATA_SIZE: usize = 1; const MAX_DATA_SIZE: usize = 4096; fn gen_rand_data(min_data_size: usize, max_data_size: usize) -> Box<[u8]> { let mut rng = thread_rng(); let data_size = rng.gen_range(min_d...
#[test] fn test_rand_crc64() { let lut = crc64::crc64_make_sliced_lut(0x42f0_e1eb_a9ea_3693, false); for _ in 0..ITERATIONS { let data = gen_rand_data(MIN_DATA_SIZE, MAX_DATA_SIZE); let crc_trusted = crc64::crc64_update_lut_256(0, &data, &lut[0]); let crc_fast = crc64::crc64_update(0...
for _ in 0..ITERATIONS { let data = gen_rand_data(MIN_DATA_SIZE, MAX_DATA_SIZE); let crc_trusted = crc32::crc32_update_ref_lut_256(0, &data, &lut[0]) ^ 0xFFFF_FFFF; let crc_fast = crc32::crc32_update_ref(0, &data, &lut) ^ 0xFFFF_FFFF; assert_eq!(crc_trusted, crc_fast); } }
function_block-function_prefix_line
[ { "content": "pub fn crc32_update(mut crc: u32, mut buf: &[u8], lut: &[[u32; 256]]) -> u32 {\n\n // slice-by-32\n\n if SLICES >= 32 && lut.len() >= SLICE_32 && buf.len() >= SLICE_32 {\n\n while buf.len() >= SLICE_32 {\n\n crc = lut[0x1f][buf[0x00] as usize ^ ((crc >> 0x18) & 0xFF) as usi...
Rust
src/header/types/cseq.rs
iostat/rtsp-rs
26586cfde2644d83a9cb7304390905902273cdd7
use core::num::IntErrorKind; use rand::{self, Rng}; use std::convert::{Infallible, TryFrom}; use std::error::Error; use std::fmt::{self, Display, Formatter}; use std::iter::once; use std::ops::{Add, Deref, Sub}; use crate::header::map::TypedHeader; use crate::header::name::HeaderName; use crate::header::value::HeaderV...
use core::num::IntErrorKind; use rand::{self, Rng}; use std::convert::{Infallible, TryFrom}; use std::error::Error; use std::fmt::{self, Display, Formatter}; use std::iter::once; use std::ops::{Add, Deref, Sub}; use crate::header::map::TypedHeader; use crate::header::name::HeaderName; use crate::header::value::HeaderV...
} } #[cfg(test)] mod test { use super::*; #[test] fn test_sub() { let cseq_1 = CSeq::try_from(50).unwrap(); let cseq_2 = CSeq::try_from(100).unwrap(); assert_eq!(*(cseq_1 - cseq_1), 0); assert_eq!(*(cseq_2 - cseq_1), 50); assert_eq!(*(cseq_1 - cseq_2), MAX_CSE...
match value { IntErrorKind::Empty => Ok(Empty), IntErrorKind::InvalidDigit => Ok(InvalidDigit), IntErrorKind::Overflow => Ok(Overflow), _ => Err(()), }
if_condition
[ { "content": "fn parse_time_of_day(value: &str) -> Result<(u32, u32, Option<u32>, &str), DateTimeError> {\n\n fn parse_2_digit_number(value: &str) -> Result<(u32, &str), DateTimeError> {\n\n let mut chars = value.chars();\n\n let first_digit = chars\n\n .next()\n\n .ok_or(...
Rust
src/leader/mod.rs
jeffreybolle/ironcast
d750893f6c9da5eb3964037025b003585c643ad8
use std::collections::{HashMap, HashSet}; use tokio::sync::mpsc::{Receiver, Sender}; use tokio::sync::mpsc::channel; use tokio::sync::oneshot; use election::{Election, ElectionInput, ElectionOutput}; use tag::Tag; use crate::leader::heartbeat::{HeartbeatMonitor, HeartbeatOutput}; use crate::net; use crate::net::mess...
use std::collections::{HashMap, HashSet}; use tokio::sync::mpsc::{Receiver, Sender}; use tokio::sync::mpsc::channel; use tokio::sync::oneshot; use election::{Election, ElectionInput, ElectionOutput}; use tag::Tag; use crate::leader::heartbeat::{HeartbeatMonitor, HeartbeatOutput}; use crate::net; use crate::net::mess...
await { log::trace!("could not send election input"); } } Tag::Ack => { let generation = read_u64(&message.data[1..9]); let len = read_u32(&message.data[9..13]) as usize; let peer_id =...
let (output_sender, output_receiver) = channel(1024); let senders = node.senders(); tokio::spawn(async move { let mut election = Election::new(id.clone(), node.senders(), cluster_size); let mut heartbeat_monitor: Option<HeartbeatMonitor> = None; loop { ...
random
[ { "content": "pub fn write_u16(msg: &mut Vec<u8>, value: u16) {\n\n msg.push(((value >> 8) & 0xff) as u8);\n\n msg.push((value & 0xff) as u8);\n\n}\n\n\n", "file_path": "src/net/utils.rs", "rank": 0, "score": 122572.26660136631 }, { "content": "pub fn read_u16(msg: &[u8]) -> u16 {\n\n ...
Rust
src/graphml.rs
Lesstat/ppts
73f9ccd08f2babace065bfd5622dd9dda8238f5b
use std::error::Error; use std::io::Read; use std::path::Path; use std::collections::{BTreeMap, HashMap}; use std::convert::TryInto; use crate::graph::{Edge, Graph, Node}; use crate::EDGE_COST_DIMENSION; use roxmltree::Document; #[derive(Debug)] enum GraphObject { Node, Edge, } #[derive(Debug)] pub enum A...
use std::error::Error; use std::io::Read; use std::path::Path; use std::collections::{BTreeMap, HashMap}; use std::convert::TryInto; use crate::graph::{Edge, Graph, Node}; use crate::EDGE_COST_DIMENSION; use roxmltree::Document; #[derive(Debug)] enum GraphObject { Node, Edge, } #[derive(Debug)] pub enum A...
fn parse_node_id(node_id: &str) -> u32 { let tail: String = node_id.chars().skip(1).collect(); tail.parse().expect("could not parse node id") }
fn parse_edge_from_xml<'a, 'input>( id: u32, node: &roxmltree::Node<'a, 'input>, keys: &KeyMap, edge_lookup: &EdgeLookup, ) -> Edge { let mut costs = [0.0; super::EDGE_COST_DIMENSION]; let source_text = node .attribute("source") .expect("edge element has no source attribute."); ...
function_block-function_prefix_line
[ { "content": "pub fn parse_graph_file(file_path: &str) -> Result<Graph, Box<dyn std::error::Error>> {\n\n use crate::EDGE_COST_DIMENSION;\n\n use std::fs::File;\n\n use std::io::{BufRead, BufReader};\n\n\n\n println!(\"Parsing graph...\");\n\n let mut nodes: Vec<Node> = Vec::new();\n\n let mut...
Rust
src/header/types/transport/connection.rs
iostat/rtsp-rs
26586cfde2644d83a9cb7304390905902273cdd7
use std::convert::{Infallible, TryFrom}; use std::error::Error; use std::fmt::{self, Display, Formatter}; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Connection { Existing, New, } impl Connection { pub fn as_s...
use std::convert::{Infallible, TryFrom}; use std::error::Error; use std::fmt::{self, Display, Formatter}; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Connection { Existing, New, } impl Connection { pub fn as_s...
pl PartialEq<[u8]> for Connection { fn eq(&self, other: &[u8]) -> bool { self.as_str().as_bytes().eq_ignore_ascii_case(other) } } impl PartialEq<Connection> for [u8] { fn eq(&self, other: &Connection) -> bool { self.eq_ignore_ascii_case(other.as_str().as_bytes()) } } impl<'connection> ...
Connection::Existing } } impl Display for Connection { fn fmt(&self, formatter: &mut Formatter) -> fmt::Result { write!(formatter, "{}", self.as_str()) } } impl From<Connection> for String { fn from(value: Connection) -> Self { value.to_string() } } im
random
[ { "content": "/// A helper function used to trim whitespace as it is used in\n\n/// [[RFC7826](https://tools.ietf.org/html/rfc7826)]. Specifically, whitespace includes `' '`,\n\n/// `'\\t'`, and `\"\\r\\n\"`. The trim functions defined on the `str` slice do not seem to be enough to\n\n/// trim the whitespace in...
Rust
src/tests/uuid.rs
basiliqio/messy_json
aa4f6dfbb5bb2a40ee03e7c1cac0b22c4893db59
use super::*; #[test] fn uuid_simple() { let nested_string = MessyJson::from(MessyJsonInner::Uuid(MessyJsonScalar::new(false))); let test_uuid = feat_uuid::Uuid::parse_str("31ee8240-630b-416a-8c54-0e2a0d070488").unwrap(); let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from( Messy...
use super::*; #[test] fn uuid_simple() { let nested_string = MessyJson::from(MessyJsonInner::Uuid(MessyJsonScalar::new(false))); let test_uuid = feat_uuid::Uuid::parse_str("31ee8240-630b-416a-8c54-0e2a0d070488").unwrap(); let schema = MessyJson::from(MessyJsonInner::Obj(MessyJsonObject::from( Messy...
sert_eq!( matches!(parsed.inner(), MessyJsonValue::Obj(_)), true, "The root should be an object" ); match parsed.inner() { MessyJsonValue::Obj(obj) => { assert_eq!( obj.len(), 1, "The root object should only contain a si...
function_block-function_prefixed
[ { "content": "#[cfg(test)]\n\npub fn gen_key(k: &str) -> super::object::KeyType {\n\n ArcStr::from(k)\n\n}\n", "file_path": "src/object.rs", "rank": 0, "score": 172450.05936977605 }, { "content": "fn run_test(schema: &MessyJson, value: &str) {\n\n let mut deserializer = serde_json::Des...
Rust
src/solvepy.rs
MEhrn00/pwninit
bfb1fca5a40a3264f5342842643da043b7a0aaaa
use crate::opts::Opts; use crate::set_exec; use std::path::Path; use std::path::PathBuf; use std::string; use colored::Colorize; use ex::fs; use ex::io; use handlebars::Handlebars; use serde::Serialize; use snafu::ResultExt; use snafu::Snafu; #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("solve script...
use crate::opts::Opts; use crate::set_exec; use std::path::Path; use std::path::PathBuf; use std::string; use colored::Colorize; use ex::fs; use ex::io; use handlebars::Handlebars; use serde::Serialize; use snafu::ResultExt; use snafu::Snafu; #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("solve script...
_libc_name, &opts.libc), bind_line(&opts.template_ld_name, &opts.ld), ] .iter() .filter_map(|x| x.as_ref()) .cloned() .collect::<Vec<String>>() .join("\n") } fn _make_proc_args(opts: &Opts) -> String { let args = if opts.ld.is_some() { format!( "{}.path, {}.path"...
plate: {}", source))] WriteError { source: io::Error }, #[snafu(display("error reading solve script template: {}", source))] ReadError { source: io::Error }, #[snafu(display("error initializing template: {}", source))] TmplError { source: handlebars::TemplateError }, #[snafu(display("error re...
random
[ { "content": "/// Download the glibc deb package with a given name, find a file inside it, and\n\n/// extract the file.\n\npub fn write_ubuntu_pkg_file<P: AsRef<Path>>(\n\n deb_file_name: &str,\n\n file_name: &str,\n\n out_path: P,\n\n) -> Result<()> {\n\n let out_path = out_path.as_ref();\n\n\n\n ...
Rust
crates/read_ctags/src/ctag_item.rs
maco/unused
f543c1bd3ed6af12b4a41f4c186741093e2b50b7
use super::language::Language; use super::parser; use super::tag_program::TagProgram; use super::tags::Tags; use super::tags_file::TagsFile; use super::token_kind::TokenKind; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::fmt::{Display, Formatter}; use std::path::PathBuf; #[derive(Clone,...
use super::language::Language; use super::parser; use super::tag_program::TagProgram; use super::tags::Tags; use super::tags_file::TagsFile; use super::token_kind::TokenKind; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::fmt::{Display, Formatter}; use std::path::PathBuf; #[derive(Clone,...
pub fn encode(&self) -> String { let tags = self .tags .iter() .map(|(k, v)| format!("{}:{}", k, v)) .collect::<Vec<String>>() .join("\t"); match (self.file_path.to_str(), self.tags.len(), &self.kind) { (None, _, _) => S...
pub fn parse_input(input: &str) -> Result<(TagProgram, Tags), CtagsParseError> { match parser::parse(input) { Ok(("", value)) => Ok(value), Ok(_) => Err(CtagsParseError::IncompleteParse), Err(e) => Err(CtagsParseError::FailedParse( e.map(|(v1, v2)| (v1.to_stri...
function_block-full_function
[ { "content": "fn tag_address_parser(input: &str) -> IResult<&str, String> {\n\n terminated(\n\n map(\n\n verify(take_until(\";\\\"\"), |s: &str| !s.contains('\\n')),\n\n |v: &str| v.to_string(),\n\n ),\n\n tag(\";\\\"\"),\n\n )(input)\n\n}\n\n\n", "file_path"...
Rust
ergo-lib/src/wallet/derivation_path.rs
dav009/sigma-rust
53b66aff4420f3dc39e360c6108549c94feb6ff6
#[derive(PartialEq, Eq, Clone, Debug)] pub struct ChildIndexHardened(u32); impl ChildIndexHardened { pub fn from_31_bit(i: u32) -> Result<Self, ChildIndexError> { if i & (1 << 31) == 0 { Ok(ChildIndexHardened(i)) } else { Err(ChildIndexError::NumberTooLarge(i)) ...
#[derive(PartialEq, Eq, Clone, Debug)] pub struct ChildIndexHardened(u32); impl ChildIndexHardened { pub fn from_31_bit(i: u32) -> Result<Self, ChildIndexError> { if i & (1 << 31) == 0 { Ok(ChildIndexHardened(i)) } else { Err(ChildIndexError::NumberTooLarge(i)) ...
} } #[derive(PartialEq, Eq, Debug, Clone)] pub struct DerivationPath(Box<[ChildIndex]>); impl DerivationPath { pub fn new(acc: ChildIndexHardened, address_indices: Vec<ChildIndexNormal>) -> Self { let mut res = vec![PURPOSE, ERG, ChildIndex::Hardened(acc), CHANGE]; res.app...
match self { ChildIndex::Hardened(index) => (1 << 31) | index.0, ChildIndex::Normal(index) => index.0, }
if_condition
[ { "content": "/// Returns cryptographically secure PRNG\n\n/// Uses ThreadRng - <https://rust-random.github.io/rand/rand/rngs/struct.ThreadRng.html>\n\n/// which is StgRng (ChaCha block cipher with 12 as of July 2021 -\n\n/// <https://rust-random.github.io/rand/rand/rngs/struct.StdRng.html>) seeded from OsRng -...
Rust
stargate-grpc/src/result.rs
stargate/stargate-grpc-rust-client
c44520685f91c01a43f9a503461c875eeccb3bdc
use crate::error::ConversionError; use crate::from_value::TryFromValue; use crate::proto::{Response, ResultSet, Row}; use std::collections::HashMap; use std::convert::TryFrom; use std::error::Error; use std::fmt::{Debug, Display, Formatter}; use std::marker::PhantomData; impl TryFrom<tonic::Response<crate::proto::R...
use crate::error::ConversionError; use crate::from_value::TryFromValue; use crate::proto::{Response, ResultSet, Row}; use std::collections::HashMap; use std::convert::TryFrom; use std::error::Error; use std::fmt::{Debug, Display, Formatter}; use std::marker::PhantomData; impl TryFrom<tonic::Response<crate::proto::R...
}
ize> { let mut result = HashMap::new(); for (i, column) in self.columns.iter().enumerate() { result.insert(column.name.clone(), i); } result }
function_block-function_prefixed
[ { "content": "/// Must be implemented by all types except Any.\n\npub trait ConcreteType {}\n\n\n\npub struct Bigint;\n\nimpl ConcreteType for Bigint {}\n\n\n\npub struct Boolean;\n\nimpl ConcreteType for Boolean {}\n\n\n\npub struct Blob;\n\nimpl ConcreteType for Blob {}\n\n\n\npub struct Counter;\n\nimpl Conc...
Rust
src/webapi/types.rs
claudiomattera/stanley
3310760bcd7e768d17bfde32bc8684ae7b6e69db
use std::collections::HashSet; use std::sync::{Arc, Mutex}; use serde::{Deserialize, Serialize}; use regex::Regex; use actix::prelude::{Addr, Message}; use crate::storage::Storage; use crate::types::{Timestamp, TimeSeries, Path}; use crate::webapi::actors::{WebSocketReplicatorActor, ReplicatorActor}; #[derive(C...
use std::collections::HashSet; use std::sync::{Arc, Mutex}; use serde::{Deserialize, Serialize}; use regex::Regex; use actix::prelude::{Addr, Message}; use crate::storage::Storage; use crate::types::{Timestamp, TimeSeries, Path}; use crate::webapi::actors::{WebSocketReplicatorActor, ReplicatorActor}; #[derive(C...
type.as_str()) { ("application", "json") => { return Some(SupportedContentType::Json); } ("application", "msgpack") => { return Some(SupportedContentType::MsgPack); } ("application", "*") => { ...
.map(Option::unwrap) .collect(); accept_entries.sort_unstable_by(|(_, _, a), (_, _, b)| b.partial_cmp(a).unwrap()); for (type_, subtype, _) in accept_entries.iter() { match (type_.as_str(), sub
function_block-random_span
[]
Rust
lib/rust/fuzzly/src/score.rs
cmarincia/enso
d59710c3cd9e356ce470edfa186c56cdca80f9d9
use crate::prelude::*; use crate::metric::Metric; use crate::subsequence_graph; use crate::SubsequenceGraph; use std::collections::hash_map::Entry; #[derive(Clone, Copy, Debug)] struct InputPath { value: f32, from: subsequence_graph::Vertex, } #[derive(Copy, Clone, Debug, Default)] struct VertexScore { ...
use crate::prelude::*; use crate::metric::Metric; use crate::subsequence_graph; use crate::SubsequenceGraph; use std::collections::hash_map::Entry; #[derive(Clone, Copy, Debug)] struct InputPath { value: f32, from: subsequence_graph::Vertex, } #[derive(Copy, Clone, Debug, Default)] struct VertexScore { ...
fn get_score(&self, vertex: subsequence_graph::Vertex) -> f32 { let Self(scores) = self; scores.get(&vertex).map(|v| v.score()).unwrap_or(0.0) } fn best_vertex( &self, vertices: impl Iterator<Item = subsequence_graph::Vertex>, ) -> Option<subsequence_graph::Vertex> { ...
y) => { let mut vertex = VertexScore::default(); vertex.update_input_path(candidate); entry.insert(vertex); } } }
function_block-function_prefixed
[]
Rust
src/engine/test_result.rs
ikrelln/ikrelln
939c33aaaa58c373cfde985f997f7e2adf1a3151
use std::collections::hash_map::{Entry, HashMap}; use actix::prelude::*; use futures::{future, Future}; #[cfg(feature = "python")] use cpython::{PyDict, Python, ToPyObject}; use crate::opentracing::tags::{IkrellnTags, KnownTag, OpenTracingTag}; #[derive(Default)] pub struct TraceParser; impl Actor for TraceParser {...
use std::collections::hash_map::{Entry, HashMap}; use actix::prelude::*; use futures::{future, Future}; #[cfg(feature = "python")] use cpython::{PyDict, Python, ToPyObject}; use crate::opentracing::tags::{IkrellnTags, KnownTag, OpenTracingTag}; #[derive(Default)] pub struct TraceParser; impl Actor for TraceParser {...
let class = Self::value_from_tag(&main_span.tags, IkrellnTags::Class)?; let remote_services: Vec<String> = spans .iter() .filter_map(|span| span.clone().remote_endpoint.and_then(|ep| ep.service_name)) .collect(); let mut call_by_remote_endpoint = HashMap::ne...
let suite = Self::value_from_tag_or(main_span, IkrellnTags::Suite, |span| { span.local_endpoint.clone().and_then(|ep| ep.service_name) })?;
assignment_statement
[ { "content": "pub fn hello() -> &'static str {\n\n \"I am i'Krelln\"\n\n}\n\n\n\nmacro_rules! typed_id {\n\n ($name:ident) => {\n\n #[derive(Serialize, Deserialize, Debug, Clone)]\n\n pub struct $name(pub String);\n\n impl TypedId for $name {}\n\n impl From<String> for $name {\...
Rust
rust/src/trans/cast/ffi.rs
souravrhythm/opendp
2c576dbf98389c349ca3a3be928f0e600cd0c10b
use std::convert::TryFrom; use std::os::raw::c_char; use crate::core::{FfiResult, IntoAnyTransformationFfiResultExt}; use crate::core::DatasetMetric; use crate::dist::{SubstituteDistance, SymmetricDistance}; use crate::dom::{AllDomain, InherentNull, VectorDomain}; use crate::err; use crate::ffi::any::AnyTransformation...
use std::convert::TryFrom; use std::os::raw::c_char; use crate::core::{FfiResult, IntoAnyTransformationFfiResultExt}; use crate::core::DatasetMetric; use crate::dist::{SubstituteDistance, SymmetricDistance}; use crate::dom::{AllDomain, InherentNull, VectorDomain}; use crate::err; use crate::ffi::any::AnyTransformation...
e(2.0), Some(3.0)]); Ok(()) } #[test] fn test_make_cast_default() -> Fallible<()> { let transformation = Result::from(opendp_trans__make_cast_default( "String".to_char_p(), "i32".to_char_p(), ))?; let arg = AnyObject::new_raw(vec!["a".to_string(), "1"...
(TIA)); let TOA = try_!(Type::try_from(TOA)); fn monomorphize<TIA, TOA>() -> FfiResult<*mut AnyTransformation> where TIA: 'static + Clone + CheckNull, TOA: 'static + RoundCast<TIA> + InherentNull { make_cast_inherent::<TIA, TOA>().into_any() } dispatch!(monomorphize, [(TIA...
random
[ { "content": "/// A [`Transformation`] that casts elements between types. Fills with TO::default if parsing fails.\n\n/// Maps a Vec<TIA> -> Vec<TOA>\n\npub fn make_cast_default<TIA, TOA>() -> Fallible<Transformation<VectorDomain<AllDomain<TIA>>, VectorDomain<AllDomain<TOA>>, SymmetricDistance, SymmetricDistanc...
Rust
core/src/backend/ui.rs
danielhjacobs/ruffle
ab88f9a23e413dc08b4a7a7f81a41c4251e77e3c
use crate::events::{KeyCode, PlayerEvent}; use std::collections::HashSet; pub type Error = Box<dyn std::error::Error>; pub trait UiBackend { fn mouse_visible(&self) -> bool; fn set_mouse_visible(&mut self, visible: bool); fn set_mouse_cursor(&mut self, cursor: MouseCursor); fn set_clipboa...
use crate::events::{KeyCode, PlayerEvent}; use std::collections::HashSet; pub type Error = Box<dyn std::error::Error>; pub trait UiBackend { fn mouse_visible(&self) -> bool; fn set_mouse_visible(&mut self, visible: bool); fn set_mouse_cursor(&mut self, cursor: MouseCursor); fn set_clipboa...
Hand, IBeam, Grab, } pub struct InputManager { keys_down: HashSet<KeyCode>, last_key: KeyCode, last_char: Option<char>, } impl InputManager { pub fn new() -> Self { Self { keys_down: HashSet::new(), last_key: KeyCode::Unknown, ...
sage(&self); fn message(&self, message: &str); } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MouseCursor { Arrow,
random
[ { "content": "fn scale_mode_to_allow_scale_bits(scale_mode: &WStr) -> Result<(bool, bool), Error> {\n\n if scale_mode == b\"none\" {\n\n Ok((false, false))\n\n } else if scale_mode == b\"horizontal\" {\n\n Ok((true, false))\n\n } else if scale_mode == b\"vertical\" {\n\n Ok((false,...
Rust
bolos-derive/src/nvm.rs
Zondax/ledger-rust
3a36d36810c471da6da12d6df8a8ffcbb8646de5
/******************************************************************************* * (c) 2021 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/lic...
/******************************************************************************* * (c) 2021 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/lic...
pub fn nvm(_: TokenStream, input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as NVMInput); let NVMInput { mut attrs, name, mutability, ty, vis, maybe_init, } = input; if cfg!(bolos_sdk) { let link_tokens = quote! {#...
fn walk_multi_array(ty: Box<Type>) -> Result<(usize, VecDeque<Expr>), Error> { let u8_ty = syn::parse2::<Type>(quote! {u8}).unwrap(); match *ty { Type::Array(TypeArray { len, elem, .. }) if *elem == u8_ty => Ok((1, vec![len].into())), Type::Array(TypeArray { len, elem, .. }) => match *elem { ...
function_block-full_function
[ { "content": "pub fn catch<T, F>(syscall: F) -> Result<T, Error>\n\nwhere\n\n F: FnOnce() -> T,\n\n{\n\n let t = catch_raw(syscall)?;\n\n Ok(t)\n\n}\n", "file_path": "bolos-impl/src/errors/exceptionsSP.rs", "rank": 1, "score": 139897.74894383375 }, { "content": "pub fn catch<T, F>(s...
Rust
gbam_tools/src/lib.rs
pjotrp/gbam
fa871328d91eb59db5211609a5903dc40d4bf3f2
#![allow(missing_docs)] use self::Fields::*; use std::mem; use std::slice::Iter; use serde::{Deserialize, Serialize}; pub mod bam { pub mod bam_to_gbam; pub mod bamrawrecord; mod tags; } pub mod meta; pub mod writer; pub mod reader; pub use self::reader::{ParsingTemplate, Reader}; use self::wr...
#![allow(missing_docs)] use self::Fields::*; use std::mem; use std::slice::Iter; use serde::{Deserialize, Serialize}; pub mod bam { pub mod bam_to_gbam; pub mod bamrawrecord; mod tags; } pub mod meta; pub mod writer; pub mod reader; pub use self::reader::{ParsingTemplate, Reader}; use self::wr...
} #[cfg(feature = "python-ffi")] mod ffi { use crate::bam_to_gbam; use crate::reader; use crate::Codecs; use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[pyfunction] pub fn bam_to_gbam_python(in_path: String, out_path: String, codec_str: String) { let codec = match &codec_s...
match field { Fields::ReadName => Fields::LName, Fields::RawQual => Fields::SequenceLength, Fields::RawSequence => Fields::RawSeqLen, Fields::RawTags => Fields::RawTagsLen, Fields::RawCigar => Fields::NCigar, _ => panic!("Unreachable"), }
if_condition
[ { "content": "/// Decodes sequence bytes into string\n\npub fn decode_seq(bytes: &[u8]) -> String {\n\n let mut res = String::new();\n\n res.reserve(2 * bytes.len());\n\n for byte in bytes {\n\n let first = (byte >> 4) as u32;\n\n let second = (byte & 0xf) as u32;\n\n res.push(get_...
Rust
src/board.rs
ejmount/othello
aabe53dffbc4e2ea7e08850205b19f951e233913
use std::fmt; use std::ops::{Add, Mul}; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Colour { Light, Dark, } impl Colour { pub fn opposite(&self) -> Colour { match self { Colour::Light => Colour::Dark, Colour::Dark => Colour::Light, } } } type GridSlot ...
use std::fmt; use std::ops::{Add, Mul}; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum Colour { Light, Dark, } impl Colour { pub fn opposite(&self) -> Colour { match self { Colour::Light => Colour::Dark, Colour::Dark => Colour::Light, } } } type GridSlot ...
x_boundary).abs(); let dist_y = (origin.1 as i32 - y_boundary).abs(); let min_steps = std::cmp::min(dist_x, dist_y) as i8; (1..min_steps).map(move |s| (origin + (going * s))) } pub fn get_empty_at_end_of_line(&self, origin: Position, going: Direction) -> Option<Position> { let s...
ZE_I32, x if x < 0 => -1, _ => Self::FAR_AWAY }; let y_boundary = match going.1 { y if y > 0 => Self::BOARD_SIZE_I32, y if y < 0 => -1, _ => Self::FAR_AWAY }; let dist_x = (origin.0 as i32 -
random
[ { "content": "pub trait Player: 'static {\n\n fn get_move(&mut self, b: &Board, availiable: &mut Iterator<Item = Move>) -> Option<Move>;\n\n}\n\n\n\n#[allow(dead_code)]\n\npub struct BasicPlayer {}\n\n\n\nimpl Player for BasicPlayer {\n\n fn get_move(&mut self, _b: &Board, availiable: &mut Iterator<Item =...
Rust
tests/rx_queue_tests.rs
cccs-rtmorti/xdpsock
92a03ac678f5073b86ff92880169cc1a605b1f01
mod setup; use libbpf_sys::XDP_PACKET_HEADROOM; use rusty_fork::rusty_fork_test; use std::{thread, time::Duration}; use xdpsock::{ socket::{SocketConfig, SocketConfigBuilder}, umem::{UmemConfig, UmemConfigBuilder}, xsk::Xsk, }; fn build_configs() -> (Option<UmemConfig>, Option<SocketConfig>) { let umem...
mod setup; use libbpf_sys::XDP_PACKET_HEADROOM; use rusty_fork::rusty_fork_test; use std::{thread, time::Duration}; use xdpsock::{ socket::{SocketConfig, SocketConfigBuilder}, umem::{UmemConfig, UmemConfigBuilder}, xsk::Xsk, }; fn build_configs() -> (Option<UmemConfig>, Option<SocketConfig>) {
let socket_config = SocketConfigBuilder::new() .tx_queue_size(4) .rx_queue_size(4) .build() .expect("failed to build socket config"); (Some(umem_config), Some(socket_config)) } rusty_fork_test! { #[test] fn rx_queue_consumes_nothing_if_no_tx_and_fill_q_empty() { ...
let umem_config = UmemConfigBuilder::new() .frame_count(8) .frame_size(2048) .fill_queue_size(4) .comp_queue_size(4) .build() .expect("failed to build umem config");
assignment_statement
[ { "content": "fn setup_logging() {\n\n INIT.call_once(|| {\n\n env_logger::init();\n\n });\n\n}\n\n\n\nmod veth_setup;\n\n\n", "file_path": "tests/setup/mod.rs", "rank": 0, "score": 106199.3487303869 }, { "content": "pub fn run_test<F>(\n\n dev1_umem_config: Option<UmemConfig...
Rust
src/utils/bounding_volume.rs
Straivers/shiny
d104e84b01843cf2ce6e01694cb52fd47ad7550c
use crate::{ math::vector2::Vec2, shapes::{ point::Point, rect::{BoundingBox, Rect}, }, }; pub struct Bvh<'a, T> where T: BoundingBox, { items: &'a [T], nodes: Vec<Node>, indirect: Vec<u32>, } impl<'a, T> Bvh<'a, T> where T: BoundingBox, { pub fn build(i...
use crate::{ math::vector2::Vec2, shapes::{ point::Point, rect::{BoundingBox, Rect}, }, }; pub struct Bvh<'a, T> where T: BoundingBox, { items: &'a [T], nodes: Vec<Node>, indirect: Vec<u32>, } impl<'a, T> Bvh<'a, T> where T: BoundingBox, { pub fn build(i...
fn find_split_axis<T>(bvh: &Bvh<T>, node_idx: usize) -> Split where T: BoundingBox, { let mut best_pos = 0.0; let mut best_axis = SplitAxis::X; let mut best_cost = f32::MAX; for item in leaf_items_indirect(bvh, node_idx) { let candidate_pos = item.bound...
1; } } let left_count = i as usize - leaf.first_indirect as usize; if left_count == 0 || left_count == leaf.count as usize { return; } let indirect = &mut bvh.indirect [leaf.first_indirect as usize..(leaf.first_indirect + leaf.count) as usize...
function_block-function_prefixed
[ { "content": "pub fn normalize(path: &mut Path) -> Rect {\n\n let rect = {\n\n let mut min_x = path.x[0];\n\n let mut min_y = path.y[0];\n\n let mut max_x = path.x[0];\n\n let mut max_y = path.y[0];\n\n\n\n for x in &path.x[1..] {\n\n min_x = min!(min_x, *x);\n\n...
Rust
dmbc/src/currency/transactions/delete_assets.rs
rude69/blockchain
1f861b13531d4b3931d1cf3d4791366839896950
use std::collections::HashMap; use exonum::blockchain::Transaction; use exonum::crypto::PublicKey; use exonum::messages::Message; use exonum::storage::Fork; use prometheus::{IntCounter, Histogram}; use currency::assets; use currency::assets::AssetBundle; use currency::error::Error; use currency::status; use currency:...
use std::collections::HashMap; use exonum::blockchain::Transaction; use exonum::crypto::PublicKey; use exonum::messages::Message; use exonum::storage::Fork; use prometheus::{IntCounter, Histogram}; use currency::assets; use currency::assets::AssetBundle; use currency::error::Error; use currency::status; use currency:...
} impl DeleteAssets { fn process(&self, view: &mut Fork) -> Result<(), Error> { info!("Processing tx: {:?}", self); let genesis_fees = CONFIGURATION.read().unwrap().fees(); let genesis_pub = genesis_fees.recipient(); let creator_pub = self.pub_key(); let mut genesis = wa...
fn calculate_fees(&self, _view: &mut Fork) -> Result<HashMap<PublicKey, u64>, Error> { let genesis_fees = CONFIGURATION.read().unwrap().fees(); let tx_fee = genesis_fees.delete_assets(); let mut fees_table = HashMap::new(); if genesis_fees.recipient() != self.pub_key() { fee...
function_block-full_function
[ { "content": "pub fn raw_message(id: u16, len: usize) -> RawMessage {\n\n let writer = MessageWriter::new(\n\n ::messages::PROTOCOL_MAJOR_VERSION,\n\n ::messages::TEST_NETWORK_ID,\n\n 0,\n\n id,\n\n len,\n\n );\n\n RawMessage::new(writer.sign(&gen_keypair().1))\n\n}\n...
Rust
packages/IC-Development/DIP721/nft/src/utils.rs
behfarkhosravi/Blockchain-in-a-Box
cde00b7a5073971e052e3fbb955781c380d18c8d
use crate::ledger::Ledger; use crate::management::Fleek; use crate::types::*; use common::account_identifier::{AccountIdentifierStruct, Subaccount}; use common::principal_id::PrincipalId; pub use ic_kit::candid::Principal; use ic_kit::ic::trap; use cap_sdk::insert; use cap_sdk::DetailValue; use cap_sdk::IndefiniteEv...
use crate::ledger::Ledger; use crate::management::Fleek; use crate::types::*; use common::account_identifier::{AccountIdentifierStruct, Subaccount}; use common::principal_id::PrincipalId; pub use ic_kit::candid::Principal; use ic_kit::ic::trap; use cap_sdk::insert; use cap_sdk::DetailValue; use cap_sdk::IndefiniteEv...
pub fn expect_principal(user: &User) -> Principal { match user { User::address(_) => { trap("only principals are allowed to preserve compatibility with Dip721") } User::principal(principal) => *principal, } } pub fn user_to_detail_value(user: User) -> DetailValue { mat...
if &AccountIdentifierStruct::new( PrincipalId(caller()), Some(Subaccount( subaccount .expect("SubAccount is missing") .try_into() .expect("unable to convert SubAccount to 32 bytes array"), ...
function_block-function_prefix_line
[ { "content": "pub fn expect_caller_general(user: &User, subaccount: Option<SubAccount>) {\n\n match user {\n\n User::address(from_address) => {\n\n if &AccountIdentifierStruct::new(\n\n PrincipalId(caller()),\n\n Some(Subaccount(\n\n subaccou...
Rust
src/build/gen/shader_code.rs
Fahien/rustspot
48d8be86c144b6c4d771034fd7a77efb2aa78e0f
use std::path::{Path, PathBuf}; use super::*; #[derive(Clone)] pub struct IncludeVariant { pub prefix: String, pub name: String, pub path: PathBuf, pub index: usize, } impl IncludeVariant { pub fn new(prefix: String, name: String, path: PathBuf, index: usize) -> Self { let nam...
use std::path::{Path, PathBuf}; use super::*; #[derive(Clone)] pub struct IncludeVariant { pub prefix: String, pub name: String, pub path: PathBuf, pub index: usize, } impl IncludeVariant { pub fn new(prefix: String, name: String, path: PathBuf, index: usize) -> Self { let nam...
let file_name = file_name.to_string_lossy(); if file_name != default_file_name && file_name.starts_with(include_name) { return Some(file_name.to_string()); } } } } ...
d variant dir"); for (index, variant_file_name) in include_dir .filter_map(|x| { if let Ok(entry) = x { if let Ok(file_type) = entry.file_type() { if file_type.is_file() { let file_name = entry.file_name();
random
[ { "content": "pub fn create_structure_scene(model: &mut Model) -> Handle<Node> {\n\n let mut root = Node::new();\n\n root.name = String::from(\"root\");\n\n\n\n let light = model\n\n .directional_lights\n\n .push(DirectionalLight::color(1.0, 1.0, 1.0));\n\n let mut light_node = Node::n...
Rust
apis/console/src/lib.rs
dcz-self/libtock-rs
f96b3b249c2820ec69ac67a1190d8299c9b7469b
#![no_std] use core::fmt; use core::marker::PhantomData; use libtock_platform as platform; use libtock_platform::allow_ro::AllowRo; use libtock_platform::allow_rw::AllowRw; use libtock_platform::share; use libtock_platform::subscribe::Subscribe; use libtock_platform::{DefaultConfig, ErrorCode, Syscalls}; pub struct C...
#![no_std] use core::fmt; use core::marker::PhantomData; use libtock_platform as platform; use libtock_platform::allow_ro::AllowRo; use libtock_platform::allow_rw::AllowRw; use libtock_platform::share; use libtock_platform::subscribe::Subscribe; use libtock_platform::{DefaultConfig, ErrorCode, Syscalls}; pub struct C...
pub fn read(buf: &mut [u8]) -> (usize, Result<(), ErrorCode>) { let called = core::cell::Cell::new(Option::<(u32, u32)>::None); let mut bytes_received = 0; let r = share::scope::< ( AllowRw<_, DRIVER_NUM, { allow_rw::READ }>, ...
loop { S::yield_wait(); if let Some((_,)) = called.get() { return Ok(()); } } }) }
function_block-function_prefix_line
[ { "content": "pub trait SupportsId<const DRIVER_NUM: u32, const SUBSCRIBE_NUM: u32> {}\n\n\n\npub struct AnyId;\n\nimpl<const DRIVER_NUM: u32, const SUBSCRIBE_NUM: u32> SupportsId<DRIVER_NUM, SUBSCRIBE_NUM>\n\n for AnyId\n\n{\n\n}\n\n\n\npub struct OneId<const DRIVER_NUM: u32, const SUBSCRIBE_NUM: u32>;\n\ni...
Rust
src/text.rs
mmalecot/rayquaza
5db2964c6d9440ebbd560261cdd205126f9b2be0
use crate::{ color::Color, drawing::Canvas, ffi, math::{Rectangle, Vector2}, window::{Handle, Window}, }; use std::{ffi::CString, fmt, path::Path, ptr, rc::Rc}; #[derive(Clone, Debug, Eq, PartialEq)] pub enum LoadFontError { ReadFailed, } impl fmt::Display for LoadFontError { fn fmt(&sel...
use crate::{ color::Color, drawing::Canvas, ffi, math::{Rectangle, Vector2}, window::{Handle, Window}, }; use std::{ffi::CString, fmt, path::Path, ptr, rc::Rc}; #[derive(Clone, Debug, Eq, PartialEq)] pub enum LoadFontError { ReadFailed, } impl fmt::Display for LoadFontError { fn fmt(&sel...
pub fn load_font_ex<P: AsRef<Path>>(&self, path: P, size: i32) -> Result<Font, LoadFontError> { unsafe { let path = CString::new(path.as_ref().display().to_string()).unwrap(); let raw = ffi::LoadFontEx(path.as_ptr(), size, ptr::null_mut(), 0); if raw.texture.id != ...
if raw.texture.id != 0 { Ok(Font { _handle: self.handle.clone(), raw, }) } else { Err(LoadFontError::ReadFailed) } } }
function_block-function_prefix_line
[]