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/spotify.rs
qstorey/ispot
1a19ae1247d3845af0b046e6c19bd16c3b53e6ca
use crate::error::{Error, ErrorKind}; use crate::types; use failure; use rspotify::spotify::client::{ApiError, Spotify}; use rspotify::spotify::model::playlist::{FullPlaylist, SimplifiedPlaylist}; use rspotify::spotify::model::track::FullTrack; use rspotify::spotify::oauth2::SpotifyClientCredentials; use rspotify::spot...
use crate::error::{Error, ErrorKind}; use crate::types; use failure; use rspotify::spotify::client::{ApiError, Spotify}; use rspotify::spotify::model::playlist::{FullPlaylist, SimplifiedPlaylist}; use rspotify::spotify::model::track::FullTrack; use rspotify::spotify::oauth2::SpotifyClientCredentials; use rspotify::spot...
earch_query( "Bohemian Rhapsody", None, Some("A Night at the Opera") ), "Bohemian Rhapsody album:A Night at the Opera" ); } }
t<R, Error> where F: Fn(&Spotify) -> Result<R, failure::Error>, { match func(&self.client) { Ok(v) => Ok(v), Err(e) => match e .downcast::<ApiError>() .expect("unable to handle spotify error") { ApiError::Unautho...
random
[ { "content": "pub fn match_playlist(spotify_client_id: &str, spotify_client_secret: &str, matches: &ArgMatches) {\n\n let default_playlist_name = format!(\"ispot - {}\", util::datetime_to_string());\n\n let path_to_playlist = matches.value_of(\"playlist\").unwrap();\n\n let print_only: bool = matches.i...
Rust
atari2600/src/tia/sprite.rs
bl-nero/atari-emulator
ac581216800aac1ae9acc0ebcae8b8d2640e08ca
use super::delay_buffer::DelayBuffer; use super::flags; const PLAYER_OFFSETS: [&[i32]; 8] = [ &[156], &[156, 12], &[156, 28], &[156, 12, 28], &[156, 60], &[157], &[156, 28, 60], &[157], ]; const MISSILE_OFFSETS: [&[i32]; 8] = [ &[156], &[156, 12], &[156, 28], ...
use super::delay_buffer::DelayBuffer; use super::flags; const PLAYER_OFFSETS: [&[i32]; 8] = [ &[156], &[156, 12], &[156, 28], &[156, 12, 28], &[156, 60], &[157], &[156, 28, 60], &[157], ]; const MISSILE_OFFSETS: [&[i32]; 8] = [ &[156], &[156, 12], &[156, 28], ...
set_reg_nusiz(player: &mut Sprite, missile: &mut Sprite, value: u8) { let player_value = value & flags::NUSIZX_PLAYER_MASK; let missile_value = value & flags::NUSIZX_MISSILE_WIDTH_MASK; player.offsets = PLAYER_OFFSETS[player_value as usize]; player.scale = match player_value { flags::NUSIZX_DOU...
None => 0, Some(bit) => 1 << if self.reflect { 7 - bit } else { bit }, }); self.position_counter = (self.position_counter + 1) % 160; let go_to_next_bit = (self.position_counter - self.current_start) % self.scale == 0; if go_to_next_bit { ...
random
[ { "content": "/// Performs a BCD subtraction with borrow, returning result and borrow.\n\npub fn bcd_sub(a: u8, b: u8, borrow: bool) -> (u8, bool) {\n\n // See comment in `bcd_add`.\n\n // Less significant digit\n\n let mut result: i16 =\n\n ((a as u16 as i16) & 0x0F) - ((b as u16 as i16) & 0x0F...
Rust
reql/src/cmd/run.rs
kid/rethinkdb-rs
945e161aec8288fa4f915bc59bc0575438a1d4ae
use super::args::Args; use super::connect::DEFAULT_DB; use crate::cmd::{Durability, ReadMode}; use crate::proto::{Payload, Query}; use crate::{err, r, Command, Connection, Result, Session}; use async_stream::try_stream; use futures::io::{AsyncReadExt, AsyncWriteExt}; use futures::stream::{Stream, StreamExt}; use ql2::q...
use super::args::Args; use super::connect::DEFAULT_DB; use crate::cmd::{Durability, ReadMode}; use crate::proto::{Payload, Query}; use crate::{err, r, Command, Connection, Result, Session}; use async_stream::try_stream; use futures::io::{AsyncReadExt, AsyncWriteExt}; use futures::stream::{Stream, StreamExt}; use ql2::q...
r)) => err::Runtime::Permission(msg).into(), Err(error) => error.into(), _ => err::Driver::Other(format!("unexpected runtime error: {}", msg)).into(), }, _ => err::Driver::Other(format!("unexpected response: {}", msg)).into(), } }
function_block-function_prefixed
[ { "content": "fn to_query_result(args: &VecDeque<super::Result<Command>>) -> super::Result<Vec<Query<'_>>> {\n\n let mut vec = Vec::with_capacity(args.len());\n\n for result in args {\n\n let arg = result.as_ref().map_err(|error| error.clone())?;\n\n vec.push(Query(arg));\n\n }\n\n Ok(...
Rust
src/de.rs
willemolding/serde-bin-prot
38e886e8f0b8faae81b06735ba9be0fb4627018f
use std::io::{BufReader, Read}; use crate::error::{Error, Result}; use crate::value::layout::{BinProtRule, BinProtRuleIterator}; use crate::ReadBinProtExt; use byteorder::{LittleEndian, ReadBytesExt}; use serde::de::{self, value::U8Deserializer, EnumAccess, IntoDeserializer, Visitor}; use serde::Deserialize; pub stru...
use std::io::{BufReader, Read}; use crate::error::{Error, Result}; use crate::value::layout::{BinProtRule, BinProtRuleIterator}; use crate::ReadBinProtExt; use byteorder::{LittleEndian, ReadBytesExt}; use serde::de::{self, value::U8Deserializer, EnumAccess, IntoDeserializer, Visitor}; use serde::Deserialize; pub stru...
0()?; let dummy_fields = std::iter::repeat("".to_string()).take(len).collect(); visitor.visit_map(MapAccess::new(self, dummy_fields)) } fn deserialize_struct<V>( self, _name: &'static str, fields: &'static [&'static str], visitor: V, ) -> Result<V::Value...
eserialize_map<V>(self, visitor: V) -> Result<V::Value> where V: Visitor<'de>, { let len: usize = self.rdr.bin_read_nat
function_block-random_span
[ { "content": "pub fn deserialize<'de, D, T>(d: D) -> Result<T, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n T: Unsigned + FromPrimitive,\n\n{\n\n d.deserialize_bytes(Nat0Visitor::new())\n\n}\n", "file_path": "src/integers/nat0.rs", "rank": 1, "score": 145324.3869686905 }, { "con...
Rust
src/generator/ical.rs
migmedia/ical-rs
26a0988b80410563afa7028e691b9d6450551999
use crate::{PARAM_DELIMITER, PARAM_VALUE_DELIMITER, VALUE_DELIMITER}; use parser::ical::component::{ IcalAlarm, IcalCalendar, IcalEvent, IcalFreeBusy, IcalJournal, IcalTimeZone, IcalTimeZoneTransition, IcalTodo, }; use property::Property; pub trait Emitter { fn generate(&self) -> String; } fn ge...
use crate::{PARAM_DELIMITER, PARAM_VALUE_DELIMITER, VALUE_DELIMITER}; use parser::ical::component::{ IcalAlarm, IcalCalendar, IcalEvent, IcalFreeBusy, IcalJournal, IcalTimeZone, IcalTimeZoneTransition, IcalTodo, }; use property::Property; pub trait Emitter { fn generate(&self) -> String; } fn ge...
} impl Emitter for Property { fn generate(&self) -> String { split_line(self.name.clone() + &get_params(&self.params) + &get_value(&self.value)) + "\n" } } impl Emitter for IcalTimeZoneTransition { fn generate(&self) -> String { use crate::parser::ical::component::IcalTimeZoneTransitionTy...
match params { None => String::new(), Some(vec) => { vec.iter() .map(|(name, values)| { let mut value = values.iter().map(protect_params).collect::<String>(); value.pop(); format!("{}{}={}", PARAM_DELIMITER, name, v...
if_condition
[ { "content": "/// An interface for an Ical/Vcard component.\n\n///\n\n/// It take a `PropertyParser` and fill the component with. It's also able to create\n\n/// sub-component used by event and alarms.\n\npub trait Component {\n\n /// Add the givent sub component.\n\n fn add_sub_component<B: BufRead>(\n\n...
Rust
src/lib.rs
zippiehq/opaque-wasm
c70433e2f45c8214ebdfa410129be2ca77e69e9c
mod hash_methods; mod utils; use hash_methods::Scrypt; use opaque_ke::ciphersuite::CipherSuite; use opaque_ke::keypair::KeyPair; use opaque_ke::{ ClientLogin, ClientLoginFinishParameters, ClientLoginStartParameters, ClientRegistration, CredentialResponse, RegistrationResponse, ClientRegistrationFinishParameter...
mod hash_methods; mod utils; use hash_methods::Scrypt; use opaque_ke::ciphersuite::CipherSuite; use opaque_ke::keypair::KeyPair; use opaque_ke::{ ClientLogin, ClientLoginFinishParameters, ClientLoginStartParameters, ClientRegistration, CredentialResponse, RegistrationResponse, ClientRegistrationFinishParameter...
ile: Vec<u8>, credential_request: Vec<u8>, server_privatekey: Vec<u8> ) -> Result<Vec<u8>, JsValue> { let server_kp = KeyPair::<curve25519_dalek::ristretto::RistrettoPoint>::from_private_key_slice(&server_privatekey).unwrap(); let request = CredentialRequest::deserialize(&credential_request[..]).unwra...
{ Ok(message) => message, Err(_e) => return Err("Message deserialize failed".into()), }; let server_registration_start_result = match ServerRegistration::<Default>::start( &mut self.rng, request, &server_kp.public(), ){ ...
random
[ { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
src/mulx.rs
davide125/bitintr
6c49e0139280c188e7daeb0f2551d63529827f74
pub trait Mulx: crate::marker::Sized { ...
pub trait Mulx: crate::marker::Sized {
x!(i32, u32); impl_smulx!(i64, u64);
fn mulx(self, y: Self) -> (Self, Self); } macro_rules! impl_umulx { ($id:ident, $id_l:ident) => { #[allow(clippy::use_self)] imp...
random
[ { "content": "/// Isolate lowest clear bit\n\npub trait Blci {\n\n /// Sets all bits of `self` to 1 except for the least significant zero bit.\n\n ///\n\n /// If there is no zero bit in `self`, it sets all bits.\n\n ///\n\n /// # Instructions\n\n ///\n\n /// - [`BLCI`](http://support.amd.co...
Rust
filesystem/src/fat32/mod.rs
Hanaasagi/kurumi
fbcfeb40cfc10ccc6cb1f7d0015bd1750f40ec08
mod bpb; mod directory; mod cluster; use core::slice; use core::str::Split; use alloc::Vec; use alloc::string::String; use self::directory::{Directory, LongFileName, FatDirectory}; use self::bpb::{Ebpb}; use self::cluster::{Cluster, ClusterChain}; use super::{File, FilePointer, FileSystem}; use device::disk::Disk; c...
mod bpb; mod directory; mod cluster; use core::slice; use core::str::Split; use alloc::Vec; use alloc::string::String; use self::directory::{Directory, LongFileName, FatDirectory}; use self::bpb::{Ebpb}; use self::cluster::{Cluster, ClusterChain}; use super::{File, FilePointer, FileSystem}; use device::disk::Disk; c...
#[inline] fn get_fat_size(&self) -> u32 { if self.ebpb.bpb.sectors_per_fat == 0 { return self.ebpb.sectors_per_fat; } self.ebpb.bpb.sectors_per_fat as u32 } #[inline] fn get_root_dir_sector(&self) -> u32 { 0 } #[inline] fn get...
pub unsafe fn new(disk: &Disk) -> Self { let mut boot_record = [0u8; 512]; disk.read(START_SECTOR, &mut boot_record) .expect("EBPB Read Error"); let ebpb = *(boot_record.as_ptr() as *const Ebpb); Fat32 { ebpb: ebpb, } }
function_block-full_function
[ { "content": "// Extended Boot Record\n\n#[derive(Debug, Clone, Copy)]\n\n#[repr(packed, C)]\n\npub struct Ebpb {\n\n pub bpb: Bpb,\n\n pub sectors_per_fat: u32,\n\n pub flags: u16,\n\n pub version_number: u16,\n\n pub root_dir_cluster: u32,\n\n pub fsinfo_secto...
Rust
src/sll.rs
oberblastmeister/rowan
b7735e58be57bc7d7bfdbeff57f37f604e1c9394
use std::{cell::Cell, cmp::Ordering, ptr}; use crate::utility_types::Delta; pub(crate) unsafe trait Elem { fn prev(&self) -> &Cell<*const Self>; fn next(&self) -> &Cell<*const Self>; fn key(&self) -> &Cell<u32>; } pub(crate) enum AddToSllResult<'a, E: Elem> { NoHead, EmptyHead(&'a Cell<*const E>...
use std::{cell::Cell, cmp::Ordering, ptr}; use crate::utility_types::Delta; pub(crate) unsafe trait Elem { fn prev(&self) -> &Cell<*const Self>; fn next(&self) -> &Cell<*const Self>; fn key(&self) -> &Cell<u32>; } pub(crate) enum AddToSllResult<'a, E: Elem> { NoHead, EmptyHead(&'a Cell<*const E>...
pub(crate) fn adjust<E: Elem>(elem: &E, from: u32, by: Delta<u32>) { let elem_ptr: *const E = elem; unsafe { let mut curr = elem_ptr; loop { let mut key = (*curr).key().get(); if key >= from { key += by; (*curr).key().set(key); ...
pub(crate) fn link<'a, E: Elem>(head: &'a Cell<*const E>, elem: &E) -> AddToSllResult<'a, E> { unsafe { let old_head = head.get(); if old_head.is_null() { return AddToSllResult::EmptyHead(head); } if elem.key() < (*old_head).key() { return A...
function_block-full_function
[ { "content": "fn element_id(elem: GreenElementRef<'_>) -> *const () {\n\n match elem {\n\n NodeOrToken::Node(it) => it as *const GreenNodeData as *const (),\n\n NodeOrToken::Token(it) => it as *const GreenTokenData as *const (),\n\n }\n\n}\n\n\n\nimpl NodeCache {\n\n pub(crate) fn node(\n...
Rust
src/ui/info/market/general/mod.rs
Philipp-Sc/terra-rust-bot
4ac6e3926c188da527673d56c3d9fd0e6c0d9c0d
use terra_rust_bot_essentials::shared::Entry; use crate::state::control::model::{Maybe}; use crate::view::interface::*; use std::collections::HashMap; use core::pin::Pin; use core::future::Future; use std::sync::Arc; use terra_rust_api_layer::services::blockchain::smart_contracts::objects::ResponseResult; use tokio:...
use terra_rust_bot_essentials::shared::Entry; use crate::state::control::model::{Maybe}; use crate::view::interface::*; use std::collections::HashMap; use core::pin::Pin; use core::future::Future; use std::sync::Arc; use terra_rust_api_layer::services::blockchain::smart_contracts::objects::ResponseResult; use tokio:...
pub async fn display_market_info(maybes: &HashMap<String, Arc<Mutex<Vec<Maybe<ResponseResult>>>>>) -> Vec<(Entry, Pin<Box<dyn Future<Output=Maybe<String>> + Send + 'static>>)> { let mut view: Vec<(Entry, Pin<Box<dyn Future<Output=Maybe<String>> + Send + 'static>>)> = Vec::new(); let t1 = Entry { timest...
function_block-full_function
[ { "content": "\n\nuse bot::action::*;\n\n\n\nmod ui;\n\n\n\nuse ui::info::auto_repay::*;\n\nuse ui::info::auto_borrow::*;\n\nuse ui::info::auto_stake::*;\n\nuse ui::info::auto_farm::*;\n\nuse ui::info::anchor::general::*;\n\nuse ui::info::anchor::account::*;\n\nuse ui::info::market::general::*;\n\nuse ui::logs:...
Rust
src/either_both.rs
ocornoc/bevy_either
027d9e5cdde74f1a22ead14f727fca6ec0fec587
use super::*; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)] pub enum EitherBoth<T, U> { Left(T), Right(U), Both(T, U), } enum Matches { Left, Right, Both, } pub struct EitherBothState<T: FetchState, U: FetchState> { pub(super) left_state: T, pub(super) right_stat...
use super::*; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)] pub enum EitherBoth<T, U> { Left(T), Right(U), Both(T, U), } enum Matches { Left, Right, Both, } pub struct EitherBothState<T: FetchState, U: FetchState> { pub(super) left_state: T, pub(super) right_stat...
fn matches_archetype(&self, archetype: &Archetype) -> bool { self.left_state.matches_archetype(archetype) || self.right_state.matches_archetype(archetype) } fn matches_table(&self, table: &Table) -> bool { self.left_state.matches_table(table) || self.right_state.matches_table(table) }...
etype: &Archetype, access: &mut Access<ArchetypeComponentId>, ) { self.left_state.update_archetype_component_access(archetype, access); self.right_state.update_archetype_component_access(archetype, access); }
function_block-function_prefixed
[ { "content": "fn push_entities(world: &mut World) -> (u32, u32, u32) {\n\n // 0 = None, 1 = Some(Left), 2 = Some(Right), 3 = Some(Both)\n\n static SUPERPERM: &[Option<EitherBoth<LeftElem, RightElem>>] = &[\n\n None,\n\n Some(EitherBoth::Left(LeftElem)),\n\n Some(EitherBoth::Right(Righ...
Rust
src/rel.rs
atouchet/datafusion-rs
17c408e517e1d81105f66b0035cf51d1a4964dd7
use super::data::*; #[derive(Debug,Clone,Serialize,Deserialize)] pub struct Schema { pub columns: Vec<Field> } impl Schema { pub fn empty() -> Self { Schema { columns: vec![] } } pub fn new(columns: Vec<Field>) -> Self { Schema { columns: columns } } pub fn column(&self, name: &str) -> ...
use super::data::*; #[derive(Debug,Clone,Serialize,Deserialize)] pub struct Schema { pub columns: Vec<Field> } impl Schema { pub fn empty() -> Self { Schema { columns: vec![] } } pub fn new(columns: Vec<Field>) -> Self { Schema { columns: columns } } pub fn column(&self, name: &str) -> ...
} #[derive(Debug,Clone,Serialize, Deserialize)] pub enum LogicalPlan { Limit { limit: usize, input: Box<LogicalPlan>, schema: Schema }, Projection { expr: Vec<Expr>, input: Box<LogicalPlan>, schema: Schema }, Selection { expr: Expr, input: Box<LogicalPlan>, schema: Schema }, Sort { expr: Vec<Expr>, i...
pub fn lt(&self, other: &Expr) -> Expr { Expr::BinaryExpr { left: Box::new(self.clone()), op: Operator::Lt, right: Box::new(other.clone()) } }
function_block-full_function
[ { "content": "/// Retrieve a list of DataFusion worker endpoints from etcd\n\npub fn get_worker_list(etcd_address: &str) -> Result<Vec<String>, String> {\n\n\n\n // create futures event loop\n\n let mut core = Core::new().unwrap();\n\n let handle = core.handle();\n\n\n\n // get list of workers from ...
Rust
my-server/src/main.rs
jacobrosenthal/rust_frontend_and_backend_template
405e91e122bd6af6595f3cfd5301aecf901b73e9
#![deny(warnings)] use handlebars::Handlebars; use headers::HeaderMapExt; use my_types::{IncrementReq, IncrementResp}; use serde::Serialize; use std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, sync::Arc, }; use tokio::sync::RwLock; use warp::Filter; use serde_json::json; #[derive(Serialize)] struct ErrorMessage<'...
#![deny(warnings)] use handlebars::Handlebars; use headers::HeaderMapExt; use my_types::{IncrementReq, IncrementResp}; use serde::Serialize; use std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, sync::Arc, }; use tokio::sync::RwLock; use warp::Filter; use serde_json::json; #[derive(Serialize)] struct ErrorMessage<'...
struct Trivial(hyper::Response<hyper::Body>); impl Trivial { fn not_found() -> Self { let r = hyper::Response::builder() .status(hyper::StatusCode::NOT_FOUND) .body(hyper::Body::empty()) .unwrap(); Trivial(r) } } impl warp::Reply for Trivial { fn int...
p { new_counter_state: *counter, }; let resp: Result<_, warp::Rejection> = Ok(warp::reply::json(&resp)); resp }); let static_route = warp::get() .and(warp::path::param::<String>()) .map( |path: String| match my_frontend:...
function_block-function_prefixed
[ { "content": "pub fn get_static_asset(s: &str) -> Option<&'static [u8]> {\n\n WASM.get(s).map(|p| *p)\n\n}\n", "file_path": "my-frontend/src/lib.rs", "rank": 0, "score": 58383.61365356451 }, { "content": "fn main() {\n\n let value = js!({\n\n return window.initial_counter_state;...
Rust
aoc2021/src/day19.rs
wufangjie/advent-of-code
a8ec46965f86509ab57ffd23cd456c82306cf1c8
use crate::read_lines; use std::collections::{HashMap, HashSet, VecDeque}; use std::fmt; use std::hash::Hash; const ORI: u8 = 24; pub fn part1() -> usize { let lines = read_lines("./data/day19.txt"); let mut iter = lines.into_iter(); let mut xyz_lst = vec![]; loop { let part = read_part(iter....
use crate::read_lines; use std::collections::{HashMap, HashSet, VecDeque}; use std::fmt; use std::hash::Hash; const ORI: u8 = 24; pub fn part1() -> usize { let lines = read_lines("./data/day19.txt"); let mut iter = lines.into_iter(); let mut xyz_lst = vec![]; loop { let part = read_part(iter....
fn count_overlap(pos: &Vec<Dim3>, delta: Dim3, set0: &HashSet<Dim3>) -> usize { pos.iter() .map(|triple| { if set0.contains(&(triple.add(&delta))) { 1 } else { 0 } }) .sum() } pub fn part2() -> i32 { let lines = read_...
b(&pos[i]); if !delta_used.contains(&delta) { delta_used.insert(delta); let count = count_overlap(pos, delta, set0); if count >= 12 { return Some(delta); } } } } None }
function_block-function_prefixed
[ { "content": "fn parse_type_4(iter: &mut impl Iterator<Item = u8>) -> Vec<u8> {\n\n let mut ret = vec![];\n\n loop {\n\n let prefix = iter.next().unwrap();\n\n for _ in 0..4 {\n\n ret.push(iter.next().unwrap());\n\n }\n\n if prefix == 0 {\n\n return ret;\n...
Rust
fortress/src/lib/text/screen_text_renderer.rs
j-rock/fortress
23b71bbd75afe75370b59e2117893f1023142c17
use crate::{ app::StatusOr, file, render::{ attribute, Attribute, AttributeProgram, BitmapTexture, ShaderProgram, ShaderUniformKey, Texel, TextureUnit, }, text::{ Base10CharIterator, GlyphId, Locale, Text...
use crate::{ app::StatusOr, file, render::{ attribute, Attribute, AttributeProgram, BitmapTexture, ShaderProgram, ShaderUniformKey, Texel, TextureUnit, }, text::{ Base10CharIterator, GlyphId, Locale, Text...
}, TextContent::Text(text) => { if let Some(text) = resolver.get_text(current_locale, text) { self.queue_glyphs(resolver, &request, text.chars(), &mut pen); } }, } } } pub fn dra...
if let Some(character_iterator) = Base10CharIterator::new(number) { self.queue_glyphs(resolver, &request, character_iterator, &mut pen); }
if_condition
[ { "content": "pub fn slurp_file(path: &PathBuf) -> StatusOr<String> {\n\n let file = File::open(path)\n\n .map_err(|e| format!(\"Error opening file {:?}: {}\", path, e))?;\n\n let mut buf_reader = BufReader::new(file);\n\n let mut contents = String::new();\n\n buf_reader.read_to_string(&mut c...
Rust
src/cards/two.rs
ContractBridge/ckc-rs
b505a30dd819f63db677e21d4ad5fc7e5884069d
use crate::cards::HandValidator; use crate::{BinaryCard, CKCNumber, CardNumber, HandError, PokerCard, Shifty, BC64}; use core::cmp; use core::slice::Iter; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Two([CKCNumber;...
use crate::cards::HandValidator; use crate::{BinaryCard, CKCNumber, CardNumber, HandError, PokerCard, Shifty, BC64}; use core::cmp; use core::slice::Iter; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Two([CKCNumber;...
__index__too_short() { let two = Two::try_from("A♠"); assert!(two.is_err()); } }
CKCNumber::from_binary_card(bc.peel()), CKCNumber::from_binary_card(bc.peel()), ); if two.is_valid() { Ok(two) } else { Err(HandError::InvalidBinaryFormat) } }, ...
random
[ { "content": "#[must_use]\n\npub fn five_from_index(index: &str) -> Option<[CKCNumber; 5]> {\n\n let mut esses = index.split_whitespace();\n\n\n\n let first = CKCNumber::from_index(esses.next()?);\n\n let second = CKCNumber::from_index(esses.next()?);\n\n let third = CKCNumber::from_index(esses.next...
Rust
read_buffer/src/column/encoding/scalar/transcoders.rs
goldenMetteyya/influxdb_iox
403f7297e1456d6cae3b7ec88c5292c81d026b11
use std::{ convert::TryFrom, fmt::{Debug, Display}, }; pub trait Transcoder<P, L>: Debug + Display { fn encode(&self, _: L) -> P; fn decode(&self, _: P) -> L; } #[derive(Debug)] pub struct NoOpTranscoder {} impl<T> Transcoder<T, T> for NoOpTranscoder { fn encode(&self, v: T) -> T { v }...
use std::{ convert::TryFrom, fmt::{Debug, Display}, }; pub trait Transcoder<P, L>: Debug + Display { fn encode(&self, _: L) -> P; fn decode(&self, _: P) -> L; } #[derive(Debug)] pub struct NoOpTranscoder {} impl<T> Transcoder<T, T> for NoOpTranscoder { fn encode(&self, v: T) -> T {
ic::Ordering, sync::Arc}; #[cfg(test)] #[derive(Debug)] pub struct MockTranscoder { encoding_calls: AtomicUsize, decoding_calls: AtomicUsize, } #[cfg(test)] impl Default for MockTranscoder { fn default() -> Self { Self { encoding_calls: AtomicUsize::default(), decoding_call...
v } fn decode(&self, v: T) -> T { v } } impl Display for NoOpTranscoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "None") } } #[derive(Debug)] pub struct ByteTrimmer {} impl<P, L> Transcoder<P, L> for ByteTrimmer where L: From<P>, ...
random
[ { "content": "pub trait NumericEncoding: Send + Sync + std::fmt::Display + std::fmt::Debug {\n\n type Item;\n\n\n\n fn size(&self) -> usize;\n\n fn value(&self, row_id: usize) -> Option<Self::Item>;\n\n fn values(&self, row_ids: &[usize]) -> Vec<Option<Self::Item>>;\n\n\n\n fn encoded_values(&sel...
Rust
fortress/src/lib/world/world_state.rs
j-rock/fortress
23b71bbd75afe75370b59e2117893f1023142c17
use crate::{ app::StatusOr, audio::AudioPlayer, control::Controller, dimensions::time::DeltaTime, enemies::EnemySystem, file::{ ConfigWatcher, SimpleConfigManager, }, hud::Hud, items::ItemSystem, maps::MapSystem, math::RandGen, particles::ParticleSystem, ...
use crate::{ app::StatusOr, audio::AudioPlayer, control::Controller, dimensions::time::DeltaTime, enemies::EnemySystem, file::{ ConfigWatcher, SimpleConfigManager, }, hud::Hud, items::ItemSystem, maps::MapSystem, math::RandGen, particles::ParticleSystem, ...
items: &mut self.items, particles: &mut self.particles, rng, dt }); } { self.players.post_update(); self.camera.post_update(self.players.player_locs(), dt); self.items.post_update(r...
{ self.background_renderer.pre_update(); self.text_renderer.pre_update(); self.camera.pre_update(dt); self.hud.pre_update(dt); if self.map.pre_update(&mut self.physics_sim) { self.players.respawn(self.map.spawns()); self.e...
function_block-random_span
[ { "content": "pub fn err_print(file: &'static str, line: u32) {\n\n unsafe {\n\n let error = gl::GetError();\n\n if error != gl::NO_ERROR {\n\n println!(\"Error was {} at {}:{}\", error, file, line);\n\n }\n\n }\n\n}", "file_path": "fortress/src/lib/render/opengl.rs", ...
Rust
rust-book/10-generics/src/traits.rs
foleyj2/rust-examples
a5eac9c935b32ac3f623d3063ad098a694b698b0
use std::fmt::Display; pub fn traits_main() { test_article_default(); } pub enum MyEnum { X, Y, } impl Summary for MyEnum { fn summarize(&self) -> String { match self { MyEnum::X => format!("I'm a MyEnum enum X"), MyEnum::Y => format!("I'm a MyEnum enum ...
use std::fmt::Display; pub fn traits_main() { test_article_default(); } pub enum MyEnum { X, Y, } impl Summary for MyEnum { fn summarize(&self) -> String { match self { MyEnum::X => format!("I'm a MyEnum enum X"), MyEnum::Y => format!("I'm a MyEnum enum ...
struct _Pair<T> { x: T, y: T, } impl<T> _Pair<T> { fn _new(x: T, y: T) -> Self { Self { x, y } } } impl<T: Display + PartialOrd> _Pair<T> { fn _cmp_display(&self) { if self.x >= self.y { println!("The largest member is x = {}", self.x); } else { pr...
let result = largest_using_traits(&number_list); println!("The largest number is {}", result); let char_list = vec!['y', 'm', 'a', 'q']; let result = largest_using_traits(&char_list); println!("The largest char is {}", result); }
function_block-function_prefix_line
[ { "content": "//fn largest<T>(list: &[T]) -> T {\n\n// // Generic but doesn't work due to need of PartialOrd trait!\n\nfn largest<T: PartialOrd + Copy>(list: &[T]) -> T {\n\n let mut largest = list[0];\n\n for &item in list {\n\n if item > largest {\n\n largest = item;\n\n }\n...
Rust
src/main.rs
McYoloSwagHam/WinPeek
1afe30a504efe935f981bd8c54b4cd7e9a2dfe1c
mod util; mod capture; use std::ptr::null_mut; use std::mem::{self, size_of}; use winapi::um::{libloaderapi, winuser, wingdi, uxtheme, dwmapi}; use winapi::shared::{windef, windowsx}; use winapi::ctypes::c_void; use std::sync::atomic::{AtomicBool, Ordering}; use std::mem::transmute as tcast; use std::fs::{remove_file, ...
mod util; mod capture; use std::ptr::null_mut; use std::mem::{self, size_of}; use winapi::um::{libloaderapi, winuser, wingdi, uxtheme, dwmapi}; use winapi::shared::{windef, windowsx}; use winapi::ctypes::c_void; use std::sync::atomic::{AtomicBool, Ordering}; use std::mem::transmute as tcast; use std::fs::{remove_file, ...
unsafe fn on_stop_resize(hwnd : windef::HWND) -> isize { winuser::RedrawWindow(hwnd, null_mut(), null_mut(), winuser::RDW_INVALIDATE | winuser::RDW_ERASE); 0 } unsafe extern "system" fn window_message_handler(hwnd : windef::HWND, msg : u32, ...
unsafe fn on_paint(hwnd : windef::HWND) -> isize { let window_state = tcast::<_, &mut WindowState>(winuser::GetWindowLongPtrW(hwnd, winuser::GWLP_USERDATA)); let mut ps :winuser::PAINTSTRUCT = mem::zeroed(); let mut client_rect : windef::RECT = mem::zeroed(); winuser::GetClientRect(hwnd, &mut client_...
function_block-function_prefix_line
[ { "content": "pub fn to_wstring(value: &str) -> Vec<u16> {\n\n use std::os::windows::ffi::OsStrExt;\n\n\n\n std::ffi::OsStr::new(value)\n\n .encode_wide()\n\n .chain(std::iter::once(0))\n\n .collect()\n\n}\n", "file_path": "src/util.rs", "rank": 0, "score": 57987.376275567...
Rust
teams/01-Web3Games/src/SubGat-Game-Web-Back-end-Server-Frame/src/handlers.rs
btspoony/hackathon-2021-spring
1d11e46c207a78526415f91c63df25e6ae12bb0b
use super::db::{ListOptions, Login, Login1, Login2, LoginGame, Register, RegistersDB}; use rbatis::crud::CRUD; use rbatis::rbatis::Rbatis; use rbatis::Error; use std::convert::Infallible; use std::sync::Arc; use warp::http::{self, StatusCode}; use warp::reply::Response; use warp::Reply; use chrono::{DateTime, Utc}; ...
use super::db::{ListOptions, Login, Login1, Login2, LoginGame, Register, RegistersDB}; use rbatis::crud::CRUD; use rbatis::rbatis::Rbatis; use rbatis::Error; use std::convert::Infallible; use std::sync::Arc; use warp::http::{self, StatusCode}; use warp::reply::Response; use warp::Reply; use chrono::{DateTime, Utc}; ...
http::StatusCode::BAD_REQUEST, )) } } } } pub async fn update_user( update: Register, db: Arc<Rbatis>, ) -> Result<impl warp::Reply, Infallible> { let mut update_register_db = RegistersDB::from(update.clone()); let now: DateTime<Ut...
db .new_wrapper() .eq("uuid", &create_uuid) .or() .eq("phone_number", &create_phone_number) .or() .eq("web3_address", &create_web3_address); let ret_create_register_db: Result<Vec<RegistersDB>, Error> = db.fetch_list_by_wrapper("", &w).await; match ret_...
function_block-random_span
[ { "content": "/// Execute the supplied function in a new storage transaction.\n\n///\n\n/// All changes to storage performed by the supplied function are discarded if\n\n/// the returned outcome is `Result::Err`.\n\n///\n\n/// Transactions can be nested to any depth. Commits happen to the parent\n\n/// transact...
Rust
zgwa/src/config.rs
vvvy/zgw
31b57e36cad891e943b5bbd011fc6ebc2606055a
use std::default::Default; use std::path::{Path, PathBuf}; use std::fs::File; use zgwlib::config::{GenOptions, DaemonizeOptions}; use nvimpl::*; pub use nvimpl::DeviceConfig; use nv::OperationTarget; use ::*; #[derive(Serialize, Deserialize)] pub struct AppConfig { pub g: GenOptions, pub d: DaemonizeOptions, ...
use std::default::Default; use std::path::{Path, PathBuf}; use std::fs::File; use zgwlib::config::{GenOptions, DaemonizeOptions}; use nvimpl::*; pub use nvimpl::DeviceConfig; use nv::OperationTarget; use ::*; #[derive(Serialize, Deserialize)] pub struct AppConfig { pub g: GenOptions, pub d: DaemonizeOptions, ...
}
s = line.split_whitespace(); let ourl = fields.next(); let ouser = fields.next(); let opwd = fields.next(); if let (Some(url), Some(user), Some(pwd)) = (ourl, ouser, opwd) { r....
function_block-function_prefixed
[ { "content": "/// '--sw=arg' => '--sw' 'arg'\n\n/// '-abc' => -a -b -c\n\npub fn convert_arg(v: String) -> Vec<String> {\n\n use std::iter::FromIterator;\n\n if v.starts_with(\"--\") {\n\n v.splitn(2, \"=\").map(|r| r.to_string()).collect()\n\n } else if v.starts_with(\"-\") && v != \"-\" {\n\n ...
Rust
src/core/mod.rs
sch00lb0y/rust-bpf-fork
ccaae5cde90bd459d2d3d490a84cc172b64e77e6
mod uprobe; use bcc_sys::bccapi::bpf_probe_attach_type_BPF_PROBE_ENTRY as BPF_PROBE_ENTRY; use bcc_sys::bccapi::bpf_probe_attach_type_BPF_PROBE_RETURN as BPF_PROBE_RETURN; use bcc_sys::bccapi::*; use failure::Error; use self::uprobe::Uprobe; use table::Table; use types::MutPointer; use std::collections::HashSet; use...
mod uprobe; use bcc_sys::bccapi::bpf_probe_attach_type_BPF_PROBE_ENTRY as BPF_PROBE_ENTRY; use bcc_sys::bccapi::bpf_probe_attach_type_BPF_PROBE_RETURN as BPF_PROBE_RETURN; use bcc_sys::bccapi::*; use failure::Error; use self::uprobe::Uprobe; use table::Table; use types::MutPointer; use std::collections::HashSet; use...
pub fn load_net(&mut self, name: &str) -> Result<File, Error> { return self.load(name, bpf_prog_type_BPF_PROG_TYPE_SCHED_ACT, 0, 0); } pub fn load_kprobe(&mut self, name: &str) -> Result<File, Error> { return self.load(name, bpf_prog_type_BPF_PROG_TYPE_KPROBE, 0, 0); } pub fn loa...
let cname = CString::new(name).unwrap(); let id = unsafe { bpf_table_id(self.p as MutPointer, cname.as_ptr()) }; Table::new(id, self.p) }
function_block-function_prefix_line
[ { "content": "// loosely based on https://github.com/iovisor/bcc/blob/v0.3.0/src/python/bcc/utils.py#L15\n\nfn read_cpu_range(cpu_range_str: &str) -> Result<Vec<usize>, Error> {\n\n let mut cpus = Vec::new();\n\n let cpu_range_str_trim = cpu_range_str.trim();\n\n for cpu_range in cpu_range_str_trim.spl...
Rust
ncollide_pipeline/world/collision_objects_dispatcher.rs
johnpmayer/ncollide
e7f1ae4111c85aeef4b4383660bc4a24dfbda386
use utils::data::hash_map::HashMap; use utils::data::pair::{Pair, PairTWHash}; use utils::data::uid_remap::{UidRemap, FastKey}; use queries::geometry::Contact; use narrow_phase::{CollisionDispatcher, CollisionAlgorithm, ContactSignal, ContactSignalHandler}; use world::CollisionObject; pub struct CollisionObjectsDispat...
use utils::data::hash_map::HashMap; use utils::data::pair::{Pair, PairTWHash}; use utils::data::uid_remap::{UidRemap, FastKey}; use queries::geometry::Contact; use narrow_phase::{CollisionDispatcher, CollisionAlgorithm, ContactSignal, ContactSignalHandler}; use world::CollisionObject; pub struct CollisionObjectsDispat...
pub fn is_proximity_allowed(objects: &UidRemap<CollisionObject<N, P, V, M, T>>, fk1: &FastKey, fk2: &FastKey) -> bool { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]; let can_move_ok = true; let groups_ok =...
d); } } else { match self.pairs.get_and_remove(&key) { Some(detector) => { if detector.value.num_colls() != 0 { let co1 = &objects[*fk1]; let co2 = &objects[*fk2]...
function_block-function_prefixed
[ { "content": "/// Finds the root of a function using the Newton method.\n\npub fn newton<V, M, F: Fn(&V) -> (V, M)>(niter: usize, guess: V, f: &mut F) -> (V, bool)\n\n where V: Sub<V, Output = V>,\n\n M: Inv + Mul<V, Output = V> + Copy {\n\n let mut curr = guess;\n\n\n\n for _ in 0 .. niter {\...
Rust
2016/src/day21.rs
shrugalic/advent_of_code
8d18a3dbdcf847a667ab553f5441676003b9362a
use crate::day21::Op::{MovePos, RotateLeft, RotateRight}; use line_reader::read_file_to_lines; pub(crate) fn day21_part1() -> String { let ops: Vec<Op> = parse_operations(read_file_to_lines("input/day21.txt")); scramble(&ops, "abcdefgh") } pub(crate) fn day21_part2() -> String { let ops: Vec<Op> = parse_o...
use crate::day21::Op::{MovePos, RotateLeft, RotateRight}; use line_reader::read_file_to_lines; pub(crate) fn day21_part1() -> String { let ops: Vec<Op> = parse_operations(read_file_to_lines("input/day21.txt")); scramble(&ops, "abcdefgh") } pub(crate) fn day21_part2() -> String { let ops: Vec<Op> = parse_o...
} fn parse_operations(input: Vec<String>) -> Vec<Op> { input.into_iter().map(Op::from).collect() } trait FindPos { fn find_pos(&self, wanted: &char) -> usize; fn find_pos_pair(&self, wanted1: &char, wanted2: &char) -> (usize, usize) { (self.find_pos(wanted1), self.find_pos(wanted2)) } } impl ...
p()), ("rotate", "based") => Op::RotateBasedOnLetterPos(p[6].parse().unwrap()), ("reverse", "positions") => { Op::ReversePositions(p[2].parse().unwrap(), p[4].parse().unwrap()) } ("move", "position") => Op::MovePos(p[2].parse().unwrap(), p[5].parse().unwra...
function_block-function_prefixed
[ { "content": "fn find_bottom_left_corner(mut x: usize, bottom: usize) -> (usize, usize) {\n\n while scan_position(x, bottom) != 1 {\n\n x += 1;\n\n }\n\n (x, bottom)\n\n}\n\n\n", "file_path": "2019/src/day19.rs", "rank": 1, "score": 267873.80728933075 }, { "content": "fn hex_...
Rust
src/ser.rs
remexre/serde_sexpr
7ee84ea8dad0d3feb9fc696168fd025e872f8967
use crate::{Error, Result, Value}; use serde::ser::{ Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, }; use std::{fmt::Display, io::Write, str::from_utf8}; pub fn to_writer<T: Serialize + ?Sized, W: Write>(mut writer: ...
use crate::{Error, Result, Value}; use serde::ser::{ Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple, SerializeTupleStruct, SerializeTupleVariant, }; use std::{fmt::Display, io::Write, str::from_utf8}; pub fn to_writer<T: Serialize + ?Sized, W: Write>(mut writer: ...
} #[derive(Debug)] pub struct ListSerializer(Vec<Value>); impl SerializeSeq for ListSerializer { type Ok = Value; type Error = Error; fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> { to_value(value).map(|v| self.0.push(v)) } fn end(self) -> Result<Value>...
fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant> { Ok(MapSerializer(vec![Value::Sym(variant.to_string())], None)) }
function_block-full_function
[ { "content": "/// Deserialize an instance of `T` from an S-Expression in a string.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// let s = \"(Hello! |Goodbye,\\\\ world!| |\\\\)\\\\|\\\\(|)\";\n\n/// let value: Vec<String> = serde_sexpr::from_str(s).unwrap();\n\n/// assert_eq!(value, vec![\"Hello!\".to_string...
Rust
src/model.rs
allancalix/ledgersync
29f6ed7102f6289ecd239ca7aa348eec156a52b5
use serde::{Deserialize, Serialize}; use std::fs::OpenOptions; use std::io::prelude::*; use std::path::PathBuf; use anyhow::Result; use rplaid::client::Environment; use crate::CLIENT_NAME; const CONFIG_NAME: &str = "config.toml"; #[derive(Debug, Default, Clone)] pub(crate) struct ConfigFile { path: PathBuf, ...
use serde::{Deserialize, Serialize}; use std::fs::OpenOptions; use std::io::prelude::*; use std::path::PathBuf; use anyhow::Result; use rplaid::client::Environment; use crate::CLIENT_NAME; const CONFIG_NAME: &str = "config.toml"; #[derive(Debug, Default, Clone)] pub(crate) struct ConfigFile { path: PathBuf, ...
pub(crate) fn valid(&self) -> bool { !self.conf.plaid.client_id.is_empty() && !self.conf.plaid.secret.is_empty() } } fn default_data_path() -> Result<String> { Ok(dirs::data_dir() .unwrap_or(std::env::current_dir()?) .join(CLIENT_NAME) .join(format!("{}.db", CLIENT_NAME)) ...
e() { path = root.clone().join(rule) }; rules.push(path); } rules }
function_block-function_prefixed
[ { "content": "fn to_plaid_opts(id: &str, secret: &str, env: &str) -> Result<PlaidOpts> {\n\n if id.is_empty() {\n\n return Err(anyhow!(\"Plaid client ID must not be empty\"));\n\n }\n\n\n\n if secret.is_empty() {\n\n return Err(anyhow!(\"Plaid client secret must not be empty\"));\n\n }...
Rust
timely/src/dataflow/operators/result.rs
davidselassie/timely-dataflow
03ea035d36c3eddcb6ea943cc159948a64f971b9
use crate::Data; use crate::dataflow::operators::Map; use crate::dataflow::{Scope, Stream}; pub trait ResultStream<S: Scope, T: Data, E: Data> { fn ok(&self) -> Stream<S, T>; fn err(&self)...
use crate::Data; use crate::dataflow::operators::Map; use crate::dataflow::{Scope, Stream}; pub trait ResultStream<S: Scope, T: Data, E: Data> { fn ok(&self) -> Stream<S, T>; fn err(&self)...
#[test] fn test_and_then() { let output = crate::example(|scope| { vec![Ok(0), Err(())].to_stream(scope) .and_then(|_| Ok(1)) .capture() }); assert_eq!(output.extract()[0].1, vec![Ok(1), Err(())]); } #[test] fn test_unwrap_or_els...
fn test_map_err() { let output = crate::example(|scope| { vec![Ok(0), Err(())].to_stream(scope) .map_err(|_| 10) .capture() }); assert_eq!(output.extract()[0].1, vec![Ok(0), Err(10)]); }
function_block-full_function
[ { "content": "/// Extension trait for `Stream`.\n\npub trait OkErr<S: Scope, D: Data> {\n\n /// Takes one input stream and splits it into two output streams.\n\n /// For each record, the supplied closure is called with the data.\n\n /// If it returns `Ok(x)`, then `x` will be sent\n\n /// to the fir...
Rust
sv-parser-parser/src/behavioral_statements/assertion_statements.rs
zarubaf/sv-parser
1189f2d1c9f0275eb15990ca6c074282b4f88d3c
use crate::*; #[tracable_parser] #[packrat_parser] pub(crate) fn assertion_item(s: Span) -> IResult<Span, AssertionItem> { alt(( map(concurrent_assertion_item, |x| { AssertionItem::Concurrent(Box::new(x)) }), map(deferred_immediate_assertion_item, |x| { AssertionItem...
use crate::*; #[tracable_parser] #[packrat_parser] pub(crate) fn assertion_item(s: Span) -> IResult<Span, AssertionItem> { alt(( map(concurrent_assertion_item, |x| { AssertionItem::Concurrent(Box::new(x)) }), map(deferred_immediate_assertion_item, |x| { AssertionItem...
#[tracable_parser] #[packrat_parser] pub(crate) fn procedural_assertion_statement( s: Span, ) -> IResult<Span, ProceduralAssertionStatement> { alt(( map(concurrent_assertion_statement, |x| { ProceduralAssertionStatement::Concurrent(Box::new(x)) }), map(immediate_assertion_s...
pub(crate) fn deferred_immediate_assertion_item( s: Span, ) -> IResult<Span, DeferredImmediateAssetionItem> { let (s, a) = opt(pair(block_identifier, symbol(":")))(s)?; let (s, b) = deferred_immediate_assertion_statement(s)?; Ok((s, DeferredImmediateAssetionItem { nodes: (a, b) })) }
function_block-full_function
[ { "content": "pub fn sv_parser(s: Span) -> IResult<Span, SourceText> {\n\n nom_packrat::init!();\n\n source_text(s)\n\n}\n\n\n", "file_path": "sv-parser-parser/src/lib.rs", "rank": 0, "score": 136896.57299318895 }, { "content": "pub fn pp_parser(s: Span) -> IResult<Span, PreprocessorTe...
Rust
src/auth.rs
kornstar11/openapi-context
ebe481d909345e4bf79ac9bc1b2e680ddd7d562c
use crate::{Push, ContextualPayload}; use hyper::HeaderMap; use std::collections::BTreeSet; use std::string::ToString; use std::marker::PhantomData; use std::task::{Context, Poll}; #[derive(Clone, Debug, PartialEq)] pub enum Scopes { Some(BTreeSet<String>), All, } #[derive(Clone, Debug, PartialEq)...
use crate::{Push, ContextualPayload}; use hyper::HeaderMap; use std::collections::BTreeSet; use std::string::ToString; use std::marker::PhantomData; use std::task::{Context, Poll}; #[derive(Clone, Debug, PartialEq)] pub enum Scopes { Some(BTreeSet<String>), All, } #[derive(Clone, Debug, PartialEq)...
context, }) } }
pub struct AllowAllAuthenticatorMakeService<C> { subject: String, phantom: PhantomData<C>, } impl<C> AllowAllAuthenticatorMakeService<C> { pub fn new<T: Into<String>>(subject: T) -> Self { AllowAllAuthenticatorMakeService { subject: subject.into(), phantom: PhantomData...
random
[ { "content": "/// Utility function to get the multipart boundary marker (if any) from the Headers.\n\npub fn boundary(headers: &HeaderMap) -> Option<String> {\n\n headers.typed_get::<ContentType>().and_then(|content_type| {\n\n if mime.type_() == mime::MULTIPART && mime.subtype() == mime::FORM_DATA {\...
Rust
src/parser/combinator/choice.rs
watcol/somen
5e264eff0d5dd24a0b82a480bb35c9afe6e73842
use core::pin::Pin; use core::task::{Context, Poll}; use futures_core::ready; use crate::error::{Error, PolledResult, Status}; use crate::parser::iterable::IterableParser; use crate::parser::utils::{merge_errors, EitherState}; use crate::parser::Parser; use crate::stream::{Input, Positioned}; #[derive(Clone, Debug, P...
use core::pin::Pin; use core::task::{Context, Poll}; use futures_core::ready; use crate::error::{Error, PolledResult, Status}; use crate::parser::iterable::IterableParser; use crate::parser::utils::{merge_errors, EitherState}; use crate::parser::Parser; use crate::stream::{Input, Positioned}; #[derive(Clone, Debug, P...
} Status::Failure(err, false) => { merge_errors(&mut state.error, Some(err)); Status::Failure(state.error().unwrap(), false) } res => res, }) } } crate::parser_state! { pub struct OrIterableState<I: Input,...
ext<'_>, state: &mut Self::State, ) -> PolledResult<Self::Output, I> { if let EitherState::Left(inner) = &mut state.inner { if state.marker.is_none() { state.marker = Some(input.as_mut().mark()?); } if state.start.is_none() { state...
function_block-random_span
[ { "content": "/// Merges two `Option<Error<L>>` into one.\n\npub fn merge_errors<L: PartialEq>(this: &mut Option<Error<L>>, other: Option<Error<L>>) {\n\n *this = match (mem::take(this), other) {\n\n (Some(e), Some(f)) if e.position.start == f.position.start => Some(Error {\n\n expects: e.e...
Rust
src/tagger.rs
JojiiOfficial/igo-rs-fork
8866db9e0cf8c0b539f4d17f6471587de51c0c19
use std::io; use std::path::Path; use std::rc::Rc; use log::debug; use crate::dictionary::{self, Matrix, Unknown, ViterbiNode, WordDic}; use crate::morpheme::Morpheme; use crate::{Utf16String, Utf16Str}; use crate::util::DirLike; type ViterbiNodeList = Vec<Rc<ViterbiNode>>; fn bos_nodes() -> ViterbiNodeList { v...
use std::io; use std::path::Path; use std::rc::Rc; use log::debug; use crate::dictionary::{self, Matrix, Unknown, ViterbiNode, WordDic}; use crate::morpheme::Morpheme; use crate::{Utf16String, Utf16Str}; use crate::util::DirLike
in_cost = cost; min_idx = i; } } vn.cost += min_cost; vn.prev = Some(prevs[min_idx].clone()); vn } } fn utf8_char_offsets(text: &str, num_chars: usize) -> Box<[usize]> { let mut utf8_offsets: Vec<usize> = Vec::with_capacity(num_chars + 1); let m...
; type ViterbiNodeList = Vec<Rc<ViterbiNode>>; fn bos_nodes() -> ViterbiNodeList { vec![Rc::new(ViterbiNode::make_boseos())] } fn empty_vec() -> ViterbiNodeList { Vec::new() } pub struct Tagger { wdc: WordDic, unk: Unknown, mtx: Matrix, } impl Tagger { pub fn new(data_dir: &P...
random
[]
Rust
src/wasm.rs
mwolicki/brainfuck_rust_web
84cb327841436e0e5435a90a230d669d81cb9544
use byteorder::{WriteBytesExt, LittleEndian}; use brainfuck::*; use std::fmt; use leb128; const EXTERNAL_CALL_PRINT:u8 = 0; const EXTERNAL_CALL_READ:u8 = 1; const FUNC:u8 = 0x60; const I32:u8 = 0x7f; const GET_LOCAL:u8 = 0x20; const SET_LOCAL:u8 = 0x21; const TEE_LOCAL:u8 = 0x22; const I32_ADD:u8 = 0x6a; const I32_...
use byteorder::{WriteBytesExt, LittleEndian}; use brainfuck::*; use std::fmt; use leb128; const EXTERNAL_CALL_PRINT:u8 = 0; const EXTERNAL_CALL_READ:u8 = 1; const FUNC:u8 = 0x60; const I32:u8 = 0x7f; const GET_LOCAL:u8 = 0x20; const SET_LOCAL:u8 = 0x21; const TEE_LOCAL:u8 = 0x22; const I32_ADD:u8 = 0x6a; const I32_...
fn code_section (functions: &Functions, vec: &mut Vec<u8>){ let elements = functions.len() as u8; if elements > 0 { let mut fns_vec = vec![]; fns_vec.write_u8(elements).unwrap(); for &(_, _, ref local_vars, ref wasmt) in func...
write_leb128(4092, &mut fns_vec); const MEMORY_SECTION : u8 = 5; vec.write_u8(MEMORY_SECTION).unwrap(); write_leb128(fns_vec.len() as u32, vec); vec.append(&mut fns_vec); }
function_block-function_prefix_line
[ { "content": "//based on https://github.com/nrc/leb128/blob/master/src/lib.rs\n\npub fn encode_unsigned(val:u32) -> Vec<u8> {\n\n let mut val = val;\n\n let mut result = vec![];\n\n loop {\n\n let mut byte = val as u8 & 0b0111_1111;\n\n val >>= 7;\n\n if val != 0 {\n\n b...
Rust
bot-rs/src/deck_parser.rs
emallson/arenalander-league-bot
08d759d422813ed731a093219bee35f90184340e
use anyhow::Result; use diesel::pg::PgConnection; use diesel::prelude::*; use nom::bytes::complete::tag; use nom::character::complete::{alphanumeric1, char, digit1, line_ending, none_of, space0, space1}; use nom::combinator::{complete, map, map_res, opt}; use nom::multi::many0; use nom::sequence::{delimited, preceded, ...
use anyhow::Result; use diesel::pg::PgConnection; use diesel::prelude::*; use nom::bytes::complete::tag; use nom::character::complete::{alphanumeric1, char, digit1, line_ending, none_of, space0, space1}; use nom::combinator::{complete, map, map_res, opt}; use nom::multi::many0; use nom::sequence::{delimited, preceded, ...
esel::pg::PgConnection; use diesel::prelude::*; use std::env; use uuid::Uuid; let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set."); let conn = PgConnection::establish(&database_url).expect("Unable to connect to database."); use super::{parse_de...
Err(DeckError::InvalidCount { name: name.to_string(), count, max: 7, } .into()) } } else if count > 1 { Err(DeckError::InvalidCount { name: name.to_string(), count, max: 1, } ...
random
[ { "content": "pub fn parse_mana(input: &str) -> Result<Vec<String>> {\n\n match parse_internal(input) {\n\n Ok((_, val)) => Ok(val),\n\n e => Err(anyhow!(\"Error parsing mana cost {:?}: {:?}\", input, e)),\n\n }\n\n}\n", "file_path": "bot-rs/src/mana_parser.rs", "rank": 1, "score...
Rust
src/system/windows/fabric.rs
Steve-xmh/fabric-ui
991f8abf5b74900d9433f25af16ed8c1982fdddf
use std::ffi::c_void; use std::mem::size_of; use std::ptr::null_mut; use font_kit::properties::Weight; use font_kit::{font::Font, properties::Properties, source::SystemSource}; use winapi::um::errhandlingapi::GetLastError; use winapi::um::wingdi::{ CreateCompatibleDC, CreateDIBSection, DeleteDC, SelectObject, BITM...
use std::ffi::c_void; use std::mem::size_of; use std::ptr::null_mut; use font_kit::properties::Weight; use font_kit::{font::Font, properties::Properties, source::SystemSource}; use winapi::um::errhandlingapi::GetLastError; use winapi::um::wingdi::{ CreateCompatibleDC, CreateDIBSection, DeleteDC, SelectObject, BITM...
let f = Self { raw, width, height, info, m_hdc, m_hbmp, hwnd: h_wnd, }; f } } impl super::super::traits::Fabric<'_> for WindowsFabric { #[inline] fn set_pixel(&mut self, pos: usize, color: u32) { ...
let fonts = [ font_kit::family_name::FamilyName::Title("Microsoft YaHei".to_string()), font_kit::family_name::FamilyName::Title("Helvetica".to_string()), font_kit::family_name::FamilyName::Title("Arial".to_string()), ];
assignment_statement
[ { "content": "pub fn gaussian_blur(data: &mut Vec<u8>, width: usize, height: usize, blur_radius: f32) {\n\n let boxes = create_box_gauss(blur_radius, 3);\n\n let mut backbuf = data.clone();\n\n\n\n for box_size in boxes.iter() {\n\n let radius = ((box_size - 1) / 2) as usize;\n\n box_blur...
Rust
lib/src/record/record_client/reqwest.rs
beltram/stubr
c140fd6a0f32c8bccdd1f7c7c7fb18692f27eac3
use reqwest::blocking::{RequestBuilder as ReqwestRequestBuilder, Request, Response}; use std::{ iter::FromIterator, str::FromStr }; use crate::{ RecordConfig, model::JsonStub, record::{ core::Record, writer::StubWriter, http::{RecordedRequest, RecordedResponse, RecordedExcha...
use reqwest::blocking::{RequestBuilder as ReqwestRequestBuilder, Request, Response}; use std::{ iter::FromIterator, str::FromStr }; use crate::{ RecordConfig, model::JsonStub, record::{ core::Record, writer::StubWriter, http::{RecordedRequest, RecordedResponse, RecordedExcha...
#[test] fn should_not_fail_when_no_req_header() { let input = ReqwestBlockingClientBuilder::new().build().unwrap().get(Url::from_str("https://github.com:8080").unwrap()).build().unwrap(); let output = RecordedRequest::from(input).0; assert!(output.header_names().col...
p()) .headers(HeaderMap::from_iter(vec![(ka, va)])) .build().unwrap(); let output = RecordedRequest::from(input).0; let ha = output.header("x-a").unwrap().get(0); assert_eq!(ha.unwrap().as_str(), "a"); }
function_block-function_prefixed
[ { "content": "fn resp_body_cfg() -> RecordConfig {\n\n RecordConfig {\n\n except_request_headers: Some(relaxed_req_headers()),\n\n except_response_headers: Some(resp_headers_with_content_type()),\n\n ..Default::default()\n\n }\n\n}", "file_path": "lib/tests/record/resp_body.rs", ...
Rust
src/database/sled/mod.rs
WebOfTrust/keriox
02b6dccd5ac26da35bdb6f0a0d1fc87e1c791cb2
mod tables; use crate::{ error::Error, event::EventMessage, event_message::{ key_event_message::KeyEvent, signed_event_message::{ SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt, TimestampedSignedEventMessage, }, Timestampe...
mod tables; use crate::{ error::Error, event::EventMessage, event_message::{ key_event_message::KeyEvent, signed_event_message::{ SignedEventMessage, SignedNontransferableReceipt, SignedTransferableReceipt, TimestampedSignedEventMessage, }, Timestampe...
pub fn remove_receipts_nt(&self, id: &IdentifierPrefix) -> Result<(), Error> { if let Some(receipts) = self.get_receipts_nt(id) { for receipt in receipts { self.receipts_nt .remove(self.identifiers.designated_key(id), &receipt)?; } } ...
pub fn get_receipts_nt( &self, id: &IdentifierPrefix, ) -> Option<impl DoubleEndedIterator<Item = SignedNontransferableReceipt>> { self.receipts_nt .iter_values(self.identifiers.designated_key(id)) }
function_block-full_function
[ { "content": "#[cfg(feature = \"query\")]\n\n#[test]\n\npub fn test_query() -> Result<(), Error> {\n\n use crate::{keri::witness::Witness, query::ReplyType};\n\n use tempfile::Builder;\n\n\n\n let root = Builder::new().prefix(\"test-db\").tempdir().unwrap();\n\n let witness = Witness::new(root.path(...
Rust
crates/graphics/src/common/gpu_buffer.rs
gents83/INOX
8ff4f851ab6493b9d613fce4a08bb0ba58dee568
use std::ops::Range; use inox_resources::{to_u8_slice, Buffer, BufferData, ResourceId}; use wgpu::util::DeviceExt; pub struct GpuBuffer<const U: u32> { cpu_buffer: Buffer, gpu_buffer: Option<wgpu::Buffer>, is_dirty: bool, is_realloc_needed: bool, } impl<const U: u32> Default for GpuBuffer<U> { fn...
use std::ops::Range; use inox_resources::{to_u8_slice, Buffer, BufferData, ResourceId}; use wgpu::util::DeviceExt; pub struct GpuBuffer<const U: u32> { cpu_buffer: Buffer, gpu_buffer: Option<wgpu::Buffer>, is_dirty: bool, is_realloc_needed: bool, } impl<const U: u32> Default for GpuBuffer<U> { fn...
pub fn is_empty(&self) -> bool { self.cpu_buffer.is_empty() } pub fn clear(&mut self) { if let Some(buffer) = self.gpu_buffer.take() { buffer.destroy(); } self.cpu_buffer.clear(); self.is_dirty = true; self.is_realloc_needed = true; } pub ...
h_id(id) { self.is_dirty = true; } if self.cpu_buffer.is_empty() { self.clear(); } }
function_block-function_prefixed
[]
Rust
src/config.rs
mgs255/handel
ccaa9f399949ef53dfc7ae4a91493fc59ebb39f8
use std::collections::HashMap; use std::path::Path; use serde::{Deserialize, Deserializer}; use yaml_rust::Yaml; use crate::reference::Reference; use crate::templates::{ComposeService, ComposeServiceMap}; use crate::volumes::VolumeInitializer; use snafu::{ResultExt, Snafu}; #[derive(Debug, Snafu)] pub enum Error { ...
use std::collections::HashMap; use std::path::Path; use serde::{Deserialize, Deserializer}; use yaml_rust::Yaml; use crate::reference::Reference; use crate::templates::{ComposeService, ComposeServiceMap}; use crate::volumes::VolumeInitializer; use snafu::{ResultExt, Snafu}; #[derive(Debug, Snafu)] pub enum Error { ...
fn build_services_recursive<'a>( self: &HandelConfig, parent: &str, svcs: &mut HashMap<String, &'a ComposeService>, templates: &'a ComposeServiceMap, ) -> Result<()> { let fragment = templates.get_service_fragment(parent); if let Some(f) = fragment { ...
w(); for (_, v) in svcs { svcs_list.push(v); } svcs_list.sort(); Ok(svcs_list) }
function_block-function_prefixed
[ { "content": "fn target_dir_valid(dir: &str) -> bool {\n\n let path_buf = PathBuf::from(dir);\n\n let path = path_buf.as_path();\n\n\n\n if !path.exists() {\n\n let _ = std::fs::create_dir_all(path);\n\n return true;\n\n }\n\n\n\n dir_is_empty(path)\n\n}\n\n\n", "file_path": "sr...
Rust
src/commands/osu/medals/list.rs
JoshiDhima/Bathbot
7a8dd8a768caede285df4f8ea5aead27bdbbf660
use std::{ cmp::{Ordering, Reverse}, mem, sync::Arc, }; use chrono::{DateTime, Utc}; use eyre::Report; use hashbrown::HashMap; use rosu_v2::prelude::{GameMode, OsuError}; use twilight_model::application::interaction::{ application_command::{CommandDataOption, CommandOptionValue}, ApplicationCommand...
use std::{ cmp::{Ordering, Reverse}, mem, sync::Arc, }; use chrono::{DateTime, Utc}; use eyre::Report; use hashbrown::HashMap; use rosu_v2::prelude::{GameMode, OsuError}; use twilight_model::application::interaction::{ application_command::{CommandDataOption, CommandOptionValue}, ApplicationCommand...
pub struct MedalEntryList { pub medal: OsekaiMedal, pub achieved: DateTime<Utc>, pub rarity: f32, } enum ListOrder { Alphabet, Date, MedalId, Rarity, } impl Default for ListOrder { fn default() -> Self { Self::Date } } pub struct ListArgs { config: UserConfig, or...
order, group, reverse, } = args; let name = match config.into_username() { Some(name) => name, None => return super::require_link(&ctx, &data).await, }; let user_args = UserArgs::new(name.as_str(), GameMode::STD); let user_fut = get_user(&ctx, &user_args); let r...
function_block-function_prefix_line
[ { "content": "fn log_interaction(ctx: &Context, interaction: &dyn InteractionExt, name: &str) {\n\n let username = interaction.username().unwrap_or(\"<unknown user>\");\n\n let location = InteractionLocationLog { ctx, interaction };\n\n info!(\"[{location}] {username} used `{name}` interaction\");\n\n}...
Rust
src/consolidation.rs
umanwizard/differential-dataflow
8ded097a17ec9d904b0ff7ba4d10c7a75ffb7fd5
use crate::difference::Semigroup; pub fn consolidate<T: Ord, R: Semigroup>(vec: &mut Vec<(T, R)>) { consolidate_from(vec, 0); } pub fn consolidate_from<T: Ord, R: Semigroup>(vec: &mut Vec<(T, R)>, offset: usize) { let length = consolidate_slice(&mut vec[offset..]); vec.truncate(offset + length); } pub ...
use crate::difference::Semigroup; pub fn consolidate<T: Ord, R: Semigroup>(vec: &mut Vec<(T, R)>) { consolidate_from(vec, 0); } pub fn consolidate_from<T: Ord, R: Semigroup>(vec: &mut Vec<(T, R)>, offset: usize) { let length = consolidate_slice(&mut vec[offset..]); vec.truncate(offset + length); } pub ...
2); } } } if !slice[offset].2.is_zero() { offset += 1; } offset } else { slice.len() } }
function_block-function_prefixed
[ { "content": "/// Concatenates multiple collections.\n\n///\n\n/// This method has the effect of a sequence of calls to `concat`, but it does\n\n/// so in one operator rather than a chain of many operators.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// extern crate timely;\n\n/// extern crate differential_d...
Rust
src/model/inline/mod.rs
johnstonskj/rust-somedoc
f992c1225384a905eaf4710398c8a39c3b500ecc
/*! This module is the root of a set of types that represent *inline* content; that is, content that does not stand on it's own. In general the `Text` type is used to represent plain text, and the `Span` type is used to represent a styled group of inline content. */ use crate::model::HasInnerContent; #[cfg(feature = "...
/*! This module is the root of a set of types that represent *inline* content; that is, content that does not stand on it's own. In general the `Text` type is used to represent plain text, and the `Span` type is used to represent a styled group of inline content. */ use crate::model::HasInnerContent; #[cfg(feature = "...
} s.clone() } #[doc(hidden)] pub mod character; pub use character::{Character, Emoji}; #[cfg(feature = "emoji_names")] #[allow(missing_docs)] pub mod emoji_names; #[doc(hidden)] pub mod image; pub use image::Image; #[doc(hidden)] pub mod link; pub use link::{HyperLink, HyperLinkTarget}; #[doc(hidden)] pub...
match item { InlineContent::Text(value) => s.push_str(value.inner()), InlineContent::Character(value) => match value { Character::Space => s.push(' '), Character::NonBreakSpace => s.push(' '), Character::Hyphen => s.push('-'), ...
if_condition
[ { "content": "///\n\n/// A marker trait denoting that a type, most likely an enum, should be treated as a syle by the\n\n/// type [`HasStyles`](trait.HasStyles.html). All styles **must** support `Default` to denote the\n\n/// *un-styled* case.\n\n///\n\npub trait Style: Default {}\n\n\n", "file_path": "src/...
Rust
shared/src/naming_utils.rs
vangork/pravega-client-rust
b57b2ea6eee3aa49d354e19b5fc457d4ccf72e9f
use crate::TxId; const EPOCH_DELIMITER: &str = ".#epoch."; const TRANSACTION_DELIMITER: &str = "#transaction."; const TRANSACTION_PART_LENGTH: i32 = 16; const TRANSACTION_ID_LENGTH: i32 = 2 * TRANSACTION_PART_LENGTH; pub struct NameUtils {} impl NameUtils { pub fn get_segment_number(segment_id: i64) -> i32 { ...
use crate::TxId; const EPOCH_DELIMITER: &str = ".#epoch."; const TRANSACTION_DELIMITER: &str = "#transaction."; const TRANSACTION_PART_LENGTH: i32 = 16; const TRANSACTION_ID_LENGTH: i32 = 2 * TRANSACTION_PART_LENGTH; pub struct NameUtils {} impl NameUtils { pub fn get_segment_number(segment_id: i64) -> i32 { ...
pub fn extract_segment_tokens(qualified_name: String) -> Vec<String> { assert!(!qualified_name.is_empty()); let original_segment_name = if NameUtils::is_transaction_segment(&qualified_name) { String::from(NameUtils::get_parent_stream_segment_name(&qualified_name)) } else { ...
Some(pos) => { if pos + TRANSACTION_DELIMITER.len() + TRANSACTION_ID_LENGTH as usize > transaction_name.len() { panic!("name is not legal"); } else { &transaction_name[..pos] } } None => { ...
function_block-function_prefix_line
[ { "content": "///\n\n///Helper method to iterate over the all the Pravega Scopes.\n\n///This method returns a stream of values, Pravega scopes, produced asynchronously.\n\n///\n\n/// The below snippets show case the example uses.\n\n/// Sample 1:\n\n///```\n\n/// # use tonic::transport::Channel;\n\n/// # use pr...
Rust
src/algos/computation.rs
sinhrks/brassfibre
86028eaf7271b2cd560ef064969ef1cbf47396d4
use std::cmp; use std::ops::{Add, Sub, Div}; use num::{Zero, Float, ToPrimitive}; pub trait NanMinMax<A> { fn nanmin(&self, n: A) -> A; fn nanmax(&self, n: A) -> A; fn nanmin_value() -> A; fn nanmax_value() -> A; } macro_rules! define_int_stats { ($t:ident) => { impl NanMinMax<$t> for $t...
use std::cmp; use std::ops::{Add, Sub, Div}; use num::{Zero, Float, ToPrimitive}; pub trait NanMinMax<A> { fn nanmin(&self, n: A) -> A; fn nanmax(&self, n: A) -> A; fn nanmin_value() -> A; fn nanmax_value() -> A; } macro_rules! define_int_stats { ($t:ident) => { impl NanMinMax<$t> for $t...
$t) -> $t { self.min(n) } fn nanmax(&self, n: $t) -> $t { self.max(n) } fn nanmin_value() -> $t { $t::min_value() } fn nanmax_value() -> $t { $t::max_value() } } ...
e() -> $t { $t::min_value() } fn nanmax_value() -> $t { $t::max_value() } } } } macro_rules! define_float_stats { ($t:ident) => { impl NanMinMax<$t> for $t { fn nanmin(&self, n:
random
[ { "content": "pub trait Description<'s>\n\n : BasicAggregation<'s> + NumericAggregation<'s> + ComparisonAggregation<'s> {\n\n type Described;\n\n\n\n fn describe(&'s self) -> Self::Described;\n\n}\n", "file_path": "src/traits.rs", "rank": 0, "score": 113000.71683545611 }, { "content...
Rust
src/query/closest_points_internal/composite_shape_against_shape.rs
kpdonn/ncollide
e9019b988ba187c428b56714db2f8f32e89406f7
use na::{self, Real}; use bounding_volume::AABB; use partitioning::BVTCostFn; use shape::{CompositeShape, Shape}; use query::{self, ClosestPoints, PointQuery}; use math::{Isometry, Point, Vector}; pub fn composite_shape_against_shape<N, G1: ?Sized>( m1: &Isometry<N>, g1: &G1, m2: &Isometry<N>, g2: &Sh...
use na::{self, Real}; use bounding_volume::AABB; use partitioning::BVTCostFn; use shape::{CompositeShape, Shape}; use query::{self, ClosestPoints, PointQuery}; use math::{Isometry, Point, Vector}; pub fn composite_shape_against_shape<N, G1: ?Sized>( m1: &Isometry<N>, g1: &G1, m2: &Isometry<N>, g2: &Sh...
; res = Some((dist, pts)) }); res } }
match pts { ClosestPoints::WithinMargin(ref p1, ref p2) => na::distance(p1, p2), ClosestPoints::Intersecting => { self.stop = true; na::zero() } ClosestPoints::Disjoint => self.margin, ...
if_condition
[ { "content": "/// Computes the minimum distance separating two shapes.\n\n///\n\n/// Returns `0.0` if the objects are touching or penetrating.\n\npub fn shape_against_shape<N: Real>(m1: &Isometry<N>, g1: &Shape<N>, m2: &Isometry<N>, g2: &Shape<N>) -> N {\n\n if let (Some(b1), Some(b2)) = (\n\n g1.as_s...
Rust
src/discord_events.rs
amative1/eris
57e6118a18e2fc16161c6dfc8b40c2cd73a7e22b
use crate::config::Config; use crate::extract::Extract; use crate::influxdb::{InfluxDB, Measurement, New, Timestamp}; use anyhow::{bail, Context as _, Error}; use joinery::Joinable; use serenity::async_trait; use serenity::http::client::Http; use serenity::model::prelude::*; use serenity::prelude::*; use std::collectio...
use crate::config::Config; use crate::extract::Extract; use crate::influxdb::{InfluxDB, Measurement, New, Timestamp}; use anyhow::{bail, Context as _, Error}; use joinery::Joinable; use serenity::async_trait; use serenity::http::client::Http; use serenity::model::prelude::*; use serenity::prelude::*; use std::collectio...
ent", event); if let Some(category_id) = channel.category_id { measurement = measurement.add_tag("category_id", category_id.to_string()); } measurement } async fn kick_from_voice( &self, http: &Http, guild: GuildId, user: UserId, ) -> Res...
ChannelType::Text | ChannelType::News => "text_channels", kind => unimplemented!("channel type: {:?}", kind), }; let mut measurement = Measurement::new(kind, Timestamp::Now) .add_tag("channel_id", channel.id.to_string()) .add_tag("channel_name", channel.name.as_str()...
function_block-random_span
[ { "content": "pub fn shorten(s: &str, max_codepoints: usize) -> Cow<str> {\n\n assert!(max_codepoints >= MARKER_LEN);\n\n\n\n let mut iter = s.char_indices();\n\n // The code point at `cut` is the first one that doesn't fit the string\n\n let cut = iter.nth(max_codepoints - MARKER_LEN).map(|(i, _)| ...
Rust
src/decoder.rs
antonok-edm/webp
31e9615f38a0a9781ad5ef97a22a3073c6021b79
use std::fmt::{Debug, Error, Formatter}; use libwebp_sys::*; use crate::shared::{PixelLayout, WebPImage, WebPMemory}; pub struct Decoder<'a> { data: &'a [u8], } impl<'a> Decoder<'a> { pub fn new(data: &'a [u8]) -> Self { Self { data } } pub fn decode(&self) -> Option<WebPImage> { ...
use std::fmt::{Debug, Error, Formatter}; use libwebp_sys::*; use crate::shared::{PixelLayout, WebPImage, WebPMemory}; pub struct Decoder<'a> { data: &'a [u8], } impl<'a> Decoder<'a> { pub fn new(data: &'a [u8]) -> Self { Self { data } } pub fn decode(&self) -> Option<WebPImage> { ...
e(BitstreamFormat::Lossless), _ => None, } } } impl Debug for BitstreamFeatures { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let mut debug_struct = f.debug_struct("BitstreamFeatures"); debug_struct .field("width", &self.width()) .fie...
if result == VP8StatusCode::VP8_STATUS_OK { return Some(Self(features)); } } None } pub fn width(&self) -> u32 { self.0.width as u32 } pub fn height(&self) -> u32 { self.0.height as u32 } pub fn has_alpha(...
random
[ { "content": "use std::fmt::{Debug, Error, Formatter};\n\nuse std::ops::{Deref, DerefMut};\n\n\n\n#[cfg(feature = \"img\")]\n\nuse image::*;\n\nuse libwebp_sys::WebPFree;\n\n\n\n/// This struct represents a safe wrapper around memory owned by libwebp.\n\n/// Its data contents can be accessed through the Deref a...
Rust
src/rust/src/programs/asteroid/ship.rs
roberts-ivanovs/asteroid-wasm
c853befd8487f8d41af2bc1273a09e9efa811f45
use std::f32::consts::PI; use crate::programs::asteroid::get_vec2_from_vec3; use crate::programs::asteroid::WebGlBuffer; use crate::utils::console_log; use rand::prelude::*; use crate::programs::asteroid::{Drawable, GameObject}; use web_sys::WebGlRenderingContext as GL; use super::get_matrix_rotation; pub struct Sp...
use std::f32::consts::PI; use crate::programs::asteroid::get_vec2_from_vec3; use crate::programs::asteroid::WebGlBuffer; use crate::utils::console_log; use rand::prelude::*; use crate::programs::asteroid::{Drawable, GameObject}; use web_sys::WebGlRenderingContext as GL; use super::get_matrix_rotation; pub struct Sp...
pub fn update(&mut self, delta_time: f32) { self.last_shot += delta_time; self.obj.update(delta_time); /* Wrap player */ if (self.obj.position.y() / 11.).abs() + 0.6 > 1. { self.obj.position.set_y(-self.obj.position.y()); } if (self.obj.position.x() / 1...
fer) { let position_buffer = gl.create_buffer().unwrap(); gl.bind_buffer(GL::ARRAY_BUFFER, Some(&position_buffer)); let vertices: Vec<(f32, f32, f32)> = vec![ (-1., -1., 0.), (0., 1., 0.), (0., 1., 0.), (1., -1., 0.), (1., -1....
function_block-function_prefixed
[ { "content": "pub fn initialize_webgl_context(\n\n canvas: &HtmlCanvasElement,\n\n) -> Result<WebGlRenderingContext, JsValue> {\n\n loop {\n\n let gl = canvas.get_context(\"webgl\")?;\n\n match gl {\n\n Some(gl_inner) => {\n\n let gl: WebGlRenderingContext = gl_inne...
Rust
src/databases/postgresql.rs
omid/diesel-adapter
3f0c99f3a0cd76060b8b8d8d154ad4314a0b07b5
use crate::diesel::PgExpressionMethods; use crate::schema; use crate::Error; use casbin::Result; use diesel::{ self, r2d2::{ConnectionManager, PooledConnection}, result::Error as DieselError, sql_query, BoolExpressionMethods, ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl, }; use std::error::Er...
use crate::diesel::PgExpressionMethods; use crate::schema; use crate::Error; use casbin::Result; use diesel::{ self, r2d2::{ConnectionManager, PooledConnection}, result::Error as DieselError, sql_query, BoolExpressionMethods, ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl, }; use std::error::Er...
) .execute(&conn) } else { diesel::delete( casbin_rules.filter( ptype .eq(pt) .and(v5.is_not_distinct_from(field_values.get(0))), ), ) .execute(&conn) }) .map_err(|err| Box::new(Error::DieselErr...
ry(format!( r#" CREATE TABLE IF NOT EXISTS {} ( id SERIAL PRIMARY KEY, ptype VARCHAR, v0 VARCHAR, v1 VARCHAR, v2 VARCHAR, v3 VARCHAR, v4 VARCHAR, ...
random
[ { "content": "type Pool = PooledConnection<ConnectionManager<Connection>>;\n\n\n", "file_path": "src/databases/mysql.rs", "rank": 1, "score": 85537.58535214294 }, { "content": "pub fn new(conn: Result<Pool>) -> Result<usize> {\n\n conn.and_then(|conn| {\n\n sql_query(format!(\n\n ...
Rust
precis-profiles/tests/nicknames.rs
sancane/precis
bf76b1c46bdd09ec34cc70a0ac489b74e3164f38
use precis_core::profile::Profile; use precis_core::{CodepointInfo, DerivedPropertyValue, Error}; use precis_profiles::Nickname; use std::borrow::Cow; #[test] fn prepare() { let profile = Nickname::new(); let res = profile.prepare(""); assert_eq!(res, Err(Error::Invalid)); let res = profile.prepare("...
use precis_core::profile::Profile; use precis_core::{CodepointInfo, DerivedPropertyValue, Error}; use precis_profiles::Nickname; use std::borrow::Cow; #[test]
#[test] fn enforce() { let profile = Nickname::new(); let res = profile.enforce(""); assert_eq!(res, Err(Error::Invalid)); let res = profile.enforce("Foo"); assert_eq!(res, Ok(Cow::from("Foo"))); let res = profile.enforce("foo"); assert_eq!(res, Ok(Cow::from("foo"))); let res = pro...
fn prepare() { let profile = Nickname::new(); let res = profile.prepare(""); assert_eq!(res, Err(Error::Invalid)); let res = profile.prepare("Foo"); assert_eq!(res, Ok(Cow::from("Foo"))); let res = profile.prepare("foo"); assert_eq!(res, Ok(Cow::from("foo"))); let res = profile.prepa...
function_block-full_function
[ { "content": "fn vector_end(file: &mut File) -> Result<(), Error> {\n\n writeln!(file, \"];\")?;\n\n Ok(writeln!(file)?)\n\n}\n\n\n", "file_path": "precis-tools/src/file_writer.rs", "rank": 0, "score": 50904.01346124626 }, { "content": "fn download(url: &str, dest: &Path) -> Result<(),...
Rust
src/lib.rs
bwt-dev/libbwt
98c832fc21e468e5436617a49e95a49e20d745b6
#![allow(clippy::not_unsafe_ptr_arg_deref)] #[macro_use] extern crate log; use std::ffi::{CStr, CString}; use std::os::raw::c_char; use std::sync::{mpsc, Once}; use std::{any, panic, thread}; use bwt::error::{BwtError, Context, Error, Result}; use bwt::util::on_oneshot_done; use bwt::{App, Config, Progress}; const ...
#![allow(clippy::not_unsafe_ptr_arg_deref)] #[macro_use] extern crate log; use std::ffi::{CStr, CString}; use std::os::raw::c_char; use std::sync::{mpsc, Once}; use std::{any, panic, thread}; use bwt::error::{BwtError, Context, Error, Result}; use bwt::util::on_oneshot_done; use bwt::{App, Config, Progress}; const ...
impl ShutdownHandler { fn into_raw(self) -> *const ShutdownHandler { Box::into_raw(Box::new(self)) } } fn notify(notify_fn: NotifyCallback, msg_type: &str, progress: f32, detail_n: u64, detail_s: &str) { let msg_type = CString::new(msg_type).unwrap(); let detail_s = CString::new(detail_s).unw...
own(shutdown_ptr: *mut ShutdownHandler) -> i32 { assert!(!shutdown_ptr.is_null()); unsafe { Box::from_raw(shutdown_ptr); } OK }
function_block-function_prefixed
[ { "content": "int32_t bwt_start(const char* json_config,\n\n bwt_notify_cb notify_cb,\n", "file_path": "libbwt.h", "rank": 7, "score": 34679.573649467784 }, { "content": "#define BWT_OK 0\n", "file_path": "libbwt.h", "rank": 9, "score": 17219.981341104158 }, ...
Rust
src/main.rs
mfs/dupr
931e91b70178bb9ef2bb65deadd0dd81341697e3
extern crate clap; extern crate walkdir; extern crate twox_hash; use std::collections::HashMap; use std::collections::BTreeSet; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::os::linux::fs::MetadataExt; use clap::{App, Arg, ArgMatches}; use walkdir::WalkDir; use twox_hash::XxHash; use ...
extern crate clap; extern crate walkdir; extern crate twox_hash; use std::collections::HashMap; use std::collections::BTreeSet; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::os::linux::fs::MetadataExt; use clap::{App, Arg, ArgMatches}; use walkdir::WalkDir; use twox_hash::XxHash; use ...
paths_completed, stats.file_count, 100.0 * paths_completed as f64 / stats.file_count as f64 ); } if paths.len() < 2 { continue; } paths_completed += paths.len(); let mut inode_paths = HashMap::new(); ...
tats.file_count += 1; stats.total_size += metadata.len(); let path = entry.path().to_path_buf(); length_paths .entry(metadata.len()) .or_insert(Vec::new()) .push(path); } eprint!("\r{:40}", " "); length_paths } fn main() { let matches = par...
random
[ { "content": "# dupr\n\n\n\nA duplicate file finder written in Rust.\n\n\n\n - compares files using [XXHash](https://github.com/Cyan4973/xxHash)\n\n - does not consider hardlinks to the same file as duplicates\n\n - includes zero length files by default\n\n\n\n[XXHash](https://github.com/Cyan4973/xxHash) is a f...
Rust
src/filepaths.rs
realcundo/ilc
fcea178cb4d27fc8e91c976233ea990aecb62bac
use std::{convert::From, path::PathBuf}; #[derive(Debug)] pub struct FilePathParser { pub files: Vec<PathBuf>, pub has_stdin: bool, } impl FilePathParser { pub fn new(files: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self { let dash = PathBuf::from("-"); let mut fi...
use std::{convert::From, path::PathBuf}; #[derive(Debug)] pub struct FilePathParser { pub files: Vec<PathBuf>, pub has_stdin: bool, } impl FilePathParser { pub fn new(files: impl IntoIterator<Item = impl Into<PathBuf>>) -> Self { let dash = PathBuf::from("-");
om("file1"), ]; let expected = input.clone(); let fp = FilePathParser::new(input); assert_eq!(fp.files, expected); assert_eq!(fp.has_stdin, false); } #[test] fn stdin_only() { let input = vec![PathBuf::from("-")]; let expected: Vec<PathBuf> = vec![...
let mut files = files.into_iter().map(Into::into).collect::<Vec<_>>(); let old_size = files.len(); files.retain(|f| *f != dash); let has_stdin = (files.len() != old_size) || (old_size == 0); Self { files, has_stdin } } } #[cfg(test)] mod te...
random
[ { "content": "/// Spawn a new thread that reads the contents of `files` and feed lines to\n\n/// `line_collector` if `regex` matches. If `files` is empty read the `stdin`.\n\n/// Termninate the thread on first io error.\n\npub fn spawn_input_thread(\n\n regex: Option<Regex>,\n\n input_files: FilePathParse...
Rust
src/rmt/rmt_ch2conf0.rs
ducktec/esp32c3
64b9547e200a3ee7e6587d81178be8732e99bee9
#[doc = "Reader of register RMT_CH2CONF0"] pub type R = crate::R<u32, super::RMT_CH2CONF0>; #[doc = "Writer for register RMT_CH2CONF0"] pub type W = crate::W<u32, super::RMT_CH2CONF0>; #[doc = "Register RMT_CH2CONF0 `reset()`'s with value 0"] impl crate::ResetValue for super::RMT_CH2CONF0 { type Type = u32; #[i...
#[doc = "Reader of register RMT_CH2CONF0"] pub type R = crate::R<u32, super::RMT_CH2CONF0>; #[doc = "Writer for register RMT_CH2CONF0"] pub type W = crate::W<u32, super::RMT_CH2CONF0>; #[doc = "Register RMT_CH2CONF0 `reset()`'s with value 0"] impl crate::ResetValue for super::RMT_CH2CONF0 { type Type = u32; #[i...
ine(always)] pub fn rmt_div_cnt_ch2(&mut self) -> RMT_DIV_CNT_CH2_W { RMT_DIV_CNT_CH2_W { w: self } } }
(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `RMT_MEM_SIZE_CH2`"] pub type RMT_MEM_SIZE_CH2_R = crat...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
oqs/src/lib.rs
msizanoen1/oqs-rs
e3a2b73fbc8053b982d42610781e2ec12624d23b
use std::ffi::{CStr, CString}; use std::mem::MaybeUninit; pub use failure::Error; pub use liboqs_sys as ffi; pub struct KeyEncap(*mut ffi::OQS_KEM); pub struct Signature(*mut ffi::OQS_SIG); impl Drop for KeyEncap { fn drop(&mut self) { unsafe { ffi::OQS_KEM_free(self.0); } } } im...
use std::ffi::{CStr, CString}; use std::mem::MaybeUninit; pub use failure::Error; pub use liboqs_sys as ffi; pub struct KeyEncap(*mut ffi::OQS_KEM); pub struct Signature(*mut ffi::OQS_SIG); impl Drop for KeyEncap { fn drop(&mut self) { unsafe { ffi::OQS_KEM_free(self.0); } } } im...
pub fn encaps_to_vec(&self, public_key: &[u8]) -> Result<(Vec<u8>, Vec<u8>), Error> { let mut ciphertext = vec![0; self.length_ciphertext()]; let mut shared_secret = vec![0; self.length_shared_secret()]; self.encaps(&mut ciphertext, &mut shared_secret, public_key)?; Ok((cipher...
pub fn encaps( &self, ciphertext: &mut [u8], shared_secret: &mut [u8], public_key: &[u8], ) -> Result<(), Error> { if ciphertext.len() != self.length_ciphertext() || shared_secret.len() != self.length_shared_secret() || public_key.len() != self.length_...
function_block-full_function
[ { "content": "fn env(name: &str) -> Option<String> {\n\n let target = env::var(\"TARGET\").unwrap().to_uppercase().replace(\"-\", \"_\");\n\n println!(\"cargo:rerun-if-env-changed={}_{}\", target, name);\n\n env::var(&format!(\"{}_{}\", target, name))\n\n .or_else(|_| {\n\n println!(\...
Rust
src/byte_slice.rs
StT191/rust-wgx
0b4948ae85ac8d9a9d43610cba20ed39c89632c8
use core::{fmt, mem, slice, any::type_name}; use std::error::Error as StdError; #[derive(Clone, Debug, PartialEq, Eq)] pub enum Error { AlignmentMismatch { dst_type: &'static str, dst_minimum_alignment: usize, }, LengthMismatch { dst_type: &'static str, ...
use core::{fmt, mem, slice, any::type_name}; use std::error::Error as StdError; #[derive(Clone, Debug, PartialEq, Eq)] pub enum Error { AlignmentMismatch { dst_type: &'static str, dst_minimum_alignment: usize, }, LengthMismatch { dst_type: &'static str, ...
ce<T: AsRef<[Self]> + ?Sized>(slice: &T) -> &[u8]; } pub unsafe trait ToMutByteSlice where Self: Sized, { fn to_mut_byte_slice<T: AsMut<[Self]> + ?Sized>(slice:&mut T) -> &mut [u8]; } unsafe impl<U: Sized> FromByteSlice for U { fn from_byte_slice<T: AsRef<[u8]> + ?Sized>(slice: &T) -> Result<&[U], Error>...
dst_type, dst_minimum_alignment, } => { write!( f, "cannot cast a &[u8] into a &[{}]: the slice's address is not divisible by the minimum alignment ({}) of {}", dst_type, dst_minimum_ali...
random
[ { "content": "// error constructor, works with all types that implement Display\n\npub fn error(err: impl ToString) -> Error {\n\n err.to_string()\n\n}\n\n\n\npub type Res<T> = Result<T, Error>;\n\n\n", "file_path": "src/error.rs", "rank": 0, "score": 167960.66681051737 }, { "content": "p...
Rust
2021/day-10/src/main.rs
dstoza/advent-2017
22de531632c1633814ed1d2b9827590af989fb6e
use std::{ collections::HashMap, fs::File, io::{BufRead, BufReader}, }; #[derive(Debug, Eq, PartialEq)] enum ParseStatus { Corrupted(u8), Incomplete(Vec<u8>), Valid, } fn parse_line(line: &str) -> ParseStatus { let closing_characters = HashMap::from([(b'(', b')'), (b'[', b']'), (b'...
use std::{ collections::HashMap, fs::File, io::{BufRead, BufReader}, }; #[derive(Debug, Eq, PartialEq)] enum ParseStatus { Corrupted(u8), Incomplete(Vec<u8>), Valid, } fn parse_line(line: &str) -> ParseStatus { let closing_characters = HashMap::from([(b'(', b')'), (b'[', b']'), (b'...
#[test] fn test_incomplete_score() { assert_eq!(get_incomplete_score(get_example().into_iter()), 288957); } }
fn test_incomplete_score_single() { assert_eq!( get_incomplete_score([String::from("<{([")].into_iter()), 294 ); }
function_block-full_function
[]
Rust
benches/i386.rs
avitex/sliceslice-rs
8df3dc5d2157c2c394bcc34baa865ed3c52e9a71
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use memmem::{Searcher, TwoWaySearcher}; use std::{ fs::{self, File}, io::{BufRead, BufReader}, }; fn search_short_haystack(c: &mut Criterion) { let mut needles = BufReader::new(File::open("data/words.txt").unwrap()) .lines() ...
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use memmem::{Searcher, TwoWaySearcher}; use std::{ fs::{self, File}, io::{BufRead, BufReader}, }; fn search_short_haystack(c: &mut Criterion) { let mut needles = BufReader::new(File::open("data/words.txt").unwrap()) .lines() ...
criterion_group!(benches, search_short_haystack, search_long_haystack); criterion_main!(benches);
r(|| { for searcher in &searchers { black_box(searcher.search_in(haystack.as_bytes())); } }); }); group.bench_function("twoway::find_bytes", |b| { b.iter(|| { for needle in &needles { black_box(twoway::find_bytes(haystack.as_by...
function_block-function_prefixed
[ { "content": "fn search(c: &mut Criterion) {\n\n let haystack = include_str!(\"../data/haystack\");\n\n let needle = include_str!(\"../data/needle\");\n\n\n\n let sizes = [1, 5, 10, 20, 50, 100, 1000];\n\n\n\n for (i, &size) in sizes.iter().enumerate() {\n\n let mut group = c.benchmark_group(...
Rust
src/stackvec/mod.rs
danielhenrymantilla/stackvec-rs
861a123b792da60019a515832a33c8ab9318cc95
use super::*; pub use self::traits::*; mod traits; pub struct StackVec<A: Array> { array: mem::ManuallyDrop<A>, len: usize, } impl<A: Array> Default for StackVec<A> { #[inline(always)] fn default () -> Self { debug_assert!(Self::CAPACITY <= isize::MAX as usize); StackVec { ...
use super::*; pub use self::traits::*; mod traits; pub struct StackVec<A: Array> { array: mem::ManuallyDrop<A>, len: usize, } impl<A: Array> Default for StackVec<A> { #[inline(always)] fn default () -> Self { debug_assert!(Self::CAPACITY <= isize::MAX as usize); StackVec { ...
#[inline] pub fn pop ( self: &mut Self, ) -> Option<A::Item> { debug_assert!(self.len <= Self::CAPACITY); if self.len > 0 { self.len -= 1; Some( unsafe { ptr::read( self.array.as_ptr()...
value: A::Item, ) { debug_assert!(self.len < Self::CAPACITY); ptr::write( self.array.as_mut_ptr() .offset(self.len as isize), value, ); self.len += 1; }
function_block-function_prefix_line
[ { "content": "/// Grants [`Array`]s an [`.into_iter()`][`ArrayIntoIter::into_iter`]\n\n/// method to almost seamlessly use [`array`]s\n\n/// as [by-owned-value iterators][`IntoIterator`].\n\n///\n\n/// # Example\n\n/// ```rust\n\n/// # use ::stackvec::prelude::*;\n\n/// let array: [_; 2] = [\n\n/// vec![1, ...
Rust
src/019-counting-sundays/rust/src/lib.rs
xfbs/ProjectEulerRust
e26768c56ff87b029cb2a02f56dc5cd32e1f7c87
use std::cmp::PartialOrd; use std::cmp::PartialEq; use std::cmp::Ordering; #[derive(Debug)] pub struct Date { weekday: u32, day: u32, month: u32, year: u32, } impl Date { pub fn new(weekday: u32, day: u32, month: u32, year: u32) -> Self { Date { weekday: weekday, da...
use std::cmp::PartialOrd; use std::cmp::PartialEq; use std::cmp::Ordering; #[derive(Debug)] pub struct Date { weekday: u32, day: u32, month: u32, year: u32, } impl Date { pub fn new(weekday: u32, day: u32, month: u32, year: u32) -> Self { Date { weekday: weekday, da...
6)); date = date.next_month(); assert_eq!(date, Date::new(1, 1, 10, 2016)); date = date.next_month(); assert_eq!(date, Date::new(3, 1, 11, 2016)); date = date.next_month(); assert_eq!(date, Date::new(6, 1, 0, 2017)); }
function_block-function_prefixed
[ { "content": " def initialize(weekday, day, month, year)\n\n @weekday = weekday\n\n @day = day\n\n @month = month\n\n @year = year\n\n end\n\n\n", "file_path": "src/019-counting-sundays/ruby/src/date.rb", "rank": 1, "score": 377310.2782590017 }, { "content": "pub fn solve(mut t...
Rust
src/reply.rs
casept/socks5_frontend
e24a05b92ac3b0a14636e067ff4da18538c903ae
use byteorder::{NetworkEndian, WriteBytesExt}; use std::io; use std::io::Write; use std::net; const ATYP_V4: u8 = 0x01; const ATYP_V6: u8 = 0x04; enum ReplyType { Succeeded, GeneralSocksServerFailure, ConnectionNotAllowed, NetworkUnreachable, DestinationUnreachable, ConnectionRef...
use byteorder::{NetworkEndian, WriteBytesExt}; use std::io; use std::io::Write; use std::net; const ATYP_V4: u8 = 0x01; const ATYP_V6: u8 = 0x04; enum ReplyType { Succeeded, GeneralSocksServerFailure, ConnectionNotAllowed, NetworkUnreachable, DestinationUnreachable, ConnectionRef...
pub(crate) fn report_success(&mut self, s: &mut net::TcpStream) -> Result<(), io::Error> { self.rep = Some(ReplyType::Succeeded); self.send(s)?; return Ok(()); } pub(crate) fn report_connection_not_allowed(&mut self, s: &mut net::TcpStream) -> Result<(), io::Error> { ...
s.write(&bnd_addr_buf)?; let mut bnd_port_buf: Vec<u8> = Vec::new(); bnd_port_buf.write_u16::<NetworkEndian>(self.bnd_port)?; s.write(&bnd_port_buf)?; return Ok(()); }
function_block-function_prefix_line
[ { "content": "/// Starts a small HTTP server as a target server to connect to.\n\nfn start_dest_server() -> u16 {\n\n let port: u16 = portpicker::pick_unused_port().expect(\"No ports free\");\n\n\n\n // V4 listener\n\n thread::spawn(move || {\n\n let server = simple_server::Server::new(|_request...
Rust
crates/rome_lsp/src/utils.rs
mrkldshv/tools
c173b0c01ee499fcb49d6ae328f1229daa183868
use std::collections::HashMap; use std::fmt::{Debug, Display}; use crate::line_index::{LineCol, LineIndex}; use rome_analyze::{ActionCategory, AnalyzerAction}; use rome_console::fmt::Termcolor; use rome_console::fmt::{self, Formatter}; use rome_console::MarkupBuf; use rome_diagnostics::termcolor::NoColor; use rome_dia...
use std::collections::HashMap; use std::fmt::{Debug, Display}; use crate::line_index::{LineCol, LineIndex}; use rome_analyze::{ActionCategory, AnalyzerAction}; use rome_console::fmt::Termcolor; use rome_console::fmt::{self, Formatter}; use rome_console::MarkupBuf; use rome_diagnostics::termcolor::NoColor; use rome_dia...
pub(crate) fn into_lsp_error(msg: impl Display + Debug) -> LspError { let mut error = LspError::internal_error(); error!("Error: {}", msg); error.message = msg.to_string(); error.data = Some(format!("{msg:?}").into()); error }
function_block-full_function
[ { "content": "pub fn reformat(text: impl Display) -> Result<String> {\n\n reformat_without_preamble(text).map(prepend_generated_preamble)\n\n}\n\n\n\nconst PREAMBLE: &str = \"Generated file, do not edit by hand, see `xtask/codegen`\";\n", "file_path": "xtask/src/lib.rs", "rank": 0, "score": 38677...
Rust
src/api_call.rs
NomadXD/threescalers
64e6df340c688fffc1f7f7c3c49071842ac1b175
use std::prelude::v1::*; use crate::{anyhow, Error}; use crate::{ application::Application, extensions::List, service::Service, transaction::Transaction, usage::Usage, user::User, }; use crate::ToParams; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Kind { Authorize, AuthRep, Report, } ...
use std::prelude::v1::*; use crate::{anyhow, Error}; use crate::{ application::Application, extensions::List, service::Service, transaction::Transaction, usage::Usage, user::User, }; use crate::ToParams; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Kind { Authorize, AuthRep, Report, } ...
; for (e, tx) in self.transactions().iter().enumerate() { tx.to_params_with_mangling(extendable, &mut |c| key_mangling(e, c)); } } }
if self.kind().is_report() { txfn_storage_report = |n, c: Cow<'k, str>| { key_mangling(format!("transactions[{}]{}", n, c).into()) }; &mut txfn_storage_report } else { txfn_storage_rest = |_n, c: Cow<'k,...
if_condition
[ { "content": "#[allow(dead_code)]\n\nfn emit_constant_maybe_using_feature(ac: &mut autocfg::AutoCfg, feature: &str, expr: &str) -> bool {\n\n let cfg = format!(\"supports_{}\", feature);\n\n if !ac.emit_constant_cfg(expr, &cfg) {\n\n ac.emit_features_with(&[feature], |fac| fac.emit_constant_cfg(exp...
Rust
ketch-core/src/resource/scene.rs
weclaw1/bliss-engine
0a48a546a9e7d4691493168cf707a74ab2c1cae6
use crate::renderer::shader::fragment_shader::ty::LightData; use nalgebra_glm::Vec3; use crate::resource::object::Object; use crate::resource::camera::Camera; #[derive(Clone)] pub struct Scene { name: String, camera: Camera, objects: Vec<Object>, light_position: Vec3, light_color: Vec3, } impl Sc...
use crate::renderer::shader::fragment_shader::ty::LightData; use nalgebra_glm::Vec3; use crate::resource::object::Object; use crate::resource::camera::Camera; #[derive(Clone)] pub struct Scene { name: String, camera: Camera, objects: Vec<Object>, light_position: Vec3, light_color: Vec3, } impl Sc...
} } pub fn name(&self) -> &str { &self.name } pub fn add_object(&mut self, object: Object) { self.objects.push(object); } pub fn remove_object(&mut self, id: u32) -> Option<Object> { let object_index = self.objects.iter().position(|x| x.id() == id); ...
String>>(name: S, camera: Camera) -> Self { Scene { name: name.into(), camera, objects: Vec::new(), light_position: Vec3::new(0.0, 0.0, 0.0), light_color: Vec3::new(1.0, 1.0, 1.0),
function_block-random_span
[ { "content": "pub fn generate_indices() -> Vec<u32> {\n\n let indices: Vec<u32> = vec![\n\n 0, 1, 2,\n\n 3, 4, 5,\n\n\n\n 6, 7, 8,\n\n 9, 10, 11,\n\n\n\n 12, 13, 14,\n\n 15, 16, 17,\n\n\n\n 18, 19, 20,\n\n 21, 22, 23,\n\n\n\n 24, 25, 26,\n\n ...
Rust
src/mbed/ssl/ssl_context.rs
erikjohnston/rust-mbedtls
790991efc61fb9e5a472ead9da5c71aafa47ae1d
use super::{bindings, constants, error, SSLAlertLevel}; use super::ssl_config::SSLConfig; use std::marker::PhantomData; use std::ffi::CStr; use std::io; use std::mem::transmute; use std::slice; use mbed::error::CError; pub struct SSLContext<'a> { inner: bindings::mbedtls_ssl_context, phantom: PhantomData<&'a...
use super::{bindings, constants, error, SSLAlertLevel}; use super::ssl_config::SSLConfig; use std::marker::PhantomData; use std::ffi::CStr; use std::io; use std::mem::transmute; use std::slice; use mbed::error::CError; pub struct SSLContext<'a> { inner: bindings::mbedtls_ssl_context, phantom: PhantomData<&'a...
pub fn close_notify(&mut self) -> Result<(), error::SSLError> { let r = unsafe { bindings::mbedtls_ssl_close_notify(&mut self.inner) }; error::SSLError::from_code(r).map(|_| ()) } pub fn session_reset(&mut self) -> Result<(), error::SSLError> { ...
d( &mut self.inner, buf.as_mut_ptr(), buf.len() as u64 ) }; error::SSLError::from_code(r).map(|i| i as usize) }
function_block-function_prefixed
[ { "content": "fn attempt_io<I, F: FnMut() -> Result<I, SSLError>>(mut f: F) -> I {\n\n loop {\n\n match f() {\n\n Ok(i) => return i,\n\n Err(SSLError::WantRead) | Err(SSLError::WantWrite) => {\n\n thread::sleep_ms(100);\n\n continue\n\n },...
Rust
tests/tiles.rs
hobofan/ucsf
0c21bb9f51ed9c724118d9d00bb920e6e01d30eb
use std::ops::Range; use ucsf_nmr::{Tiles, UcsfFile}; #[test] fn correct_axis_tiles_1() { let contents = include_bytes!("./data/15n_hsqc.ucsf"); let (_, file) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); assert_eq!(file.axis_tiles()[0], 2); assert_eq!(file.axis_tiles()[1], 2); } #[test...
use std::ops::Range; use ucsf_nmr::{Tiles, UcsfFile}; #[test] fn correct_axis_tiles_1() { let contents = include_bytes!("./data/15n_hsqc.ucsf"); let (_, file) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); assert_eq!(file.axis_tiles()[0], 2); assert_eq!(file.axis_tiles()[1], 2); } #[test...
es().count(); assert_eq!(tile_count, 4); } #[test] fn correct_num_tiles_2() { let contents = include_bytes!("./data/Nhsqc_highres_600MHz.ucsf"); let (_, contents) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); let tile_count = contents.tiles().count(); assert_eq!(tile_count, 20); } #[...
include_bytes!("./data/15n_hsqc.ucsf"); let (_, contents) = UcsfFile::parse(&contents[..]).expect("Failed parsing"); let tile_count = contents.til
function_block-random_span
[ { "content": "#[test]\n\n#[ignore]\n\nfn parse_3d_file() {\n\n let contents = std::fs::read(\"./tests/data/c13_noesy_aliph.ucsf\").unwrap();\n\n\n\n let (rem, _) = UcsfFile::parse(&contents[..]).expect(\"Failed parsing\");\n\n assert_eq!(rem.len(), 0);\n\n}\n", "file_path": "tests/3d.rs", "rank...
Rust
src/main.rs
Gordon01/merino
47a327f99a3955a65c14ac053d2019959805430b
#![forbid(unsafe_code)] #![cfg_attr(not(debug_assertions), deny(warnings))] #![warn(clippy::all, rust_2018_idioms)] #[macro_use] extern crate log; use clap::{ArgGroup, Parser}; use merino::*; use std::env; use std::error::Error; #[cfg(not(target_os = "windows"))] use std::os::unix::prelude::MetadataExt; use std::path:...
#![forbid(unsafe_code)] #![cfg_attr(not(debug_assertions), deny(warnings))] #![warn(clippy::all, rust_2018_idioms)] #[macro_use] extern crate log; use clap::{ArgGroup, Parser}; use merino::*; use std::env; use std::error::Error; #[cfg(not(target_os = "windows"))] use std::os::unix::prelude::MetadataExt; use std::path:...
async fn main() -> Result<(), Box<dyn Error>> { println!("{}", LOGO); let opt = Opt::parse(); let log_env = env::var("RUST_LOG"); if log_env.is_err() { let level = match opt.verbosity { 1 => "merino=DEBUG", 2 => "merino=TRACE", _ => "merino=INFO", ...
function_block-full_function
[ { "content": "/// Convert an address and AddrType to a SocketAddr\n\nfn addr_to_socket(addr_type: &AddrType, addr: &[u8], port: u16) -> io::Result<Vec<SocketAddr>> {\n\n match addr_type {\n\n AddrType::V6 => {\n\n let new_addr = (0..8)\n\n .map(|x| {\n\n tr...
Rust
raytracer/src/BVH.rs
AegeanYan/I-m-raytracer
a1f713cacd72c4b352f4a56ec205b99f524e002f
use crate::hit::{HitRecord, Hittable, HittableList}; use crate::material::Lambertian; use crate::moving_sphere::MovingSphere; use crate::Vec3; use crate::AABB::Aabb; use crate::{random_int, Ray}; use std::sync::Arc; pub struct BvhNode { pub left: Arc<dyn Hittable>, pub right: Arc<dyn Hittable>, pub box0: A...
use crate::hit::{HitRecord, Hittable, HittableList}; use crate::material::Lambertian; use crate::moving_sphere::MovingSphere; use crate::Vec3; use crate::AABB::Aabb; use crate::{random_int, Ray}; use std::sync::Arc; pub struct BvhNode { pub left: Arc<dyn Hittable>, pub right: Arc<dyn Hittable>, pub box0: A...
fn bounding_box(&self, _time0: f64, _time1: f64, output_box: &mut Aabb) -> bool { *output_box = self.box0; true } } impl BvhNode { pub fn new0( src_objects: &mut Vec<Arc<dyn Hittable>>, start: usize, end: usize, time0: f64, time1: ...
fn hit(&self, r: Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { if !self.box0.hit(r, t_min, t_max) { return None; } if let Some(rec_tmp) = self.left.hit(r, t_min, t_max) { if let Some(rec_) = self.right.hit(r, t_min, rec_tmp.t) { return Some(rec_); ...
function_block-full_function
[]
Rust
src/requests.rs
incker2/randomorg
a32970f18e53b9b0814805f876597529c13ec868
use crate::methods::Method; use crate::model::*; use crate::params::*; const API_JSON_RPC_VERSION: &str = "2.0"; pub type EmptyRequest = Request<ApiKeyParams>; impl EmptyRequest { pub fn new(method: Method, api_key: ApiKey) -> EmptyRequest { EmptyRequest { json_rpc: API_JSON_RPC_VERSION.t...
use crate::methods::Method; use crate::model::*; use crate::params::*; const API_JSON_RPC_VERSION: &str = "2.0"; pub type EmptyRequest = Request<ApiKeyParams>; impl EmptyRequest { pub fn new(method: Method, api_key: ApiKey) -> EmptyRequest { EmptyRequest { json_rpc: API_JSON_RPC_VERSION.t...
} pub type GenerateBlobsRequest = Request<GenerateBlobsParams>; impl GenerateBlobsRequest { pub fn new(api_key: ApiKey, limit: u16, size: u32) -> GenerateBlobsRequest { GenerateBlobsRequest { json_rpc: API_JSON_RPC_VERSION.to_owned(), method: Method::GenerateBlobs, ...
pub fn new(api_key: ApiKey, limit: u16) -> GenerateUUIDsRequest { GenerateUUIDsRequest { json_rpc: API_JSON_RPC_VERSION.to_owned(), method: Method::GenerateUUIDs, params: GenerateUUIDsParams { api_key, limit }, id: RequestId(1), } }
function_block-function_prefix_line
[ { "content": "pub fn profile() -> &'static str {{\\n\\t\\\"{}\\\"\\n}}\\n\",\n\n env::var(\"PROFILE\").unwrap()\n\n );\n\n f.write_all(&string.into_bytes()).unwrap();\n\n}\n\n\n", "file_path": "build.rs", "rank": 0, "score": 81131.01759408896 }, { "content": "pub fn features() -...
Rust
src/server.rs
dat2/rust-raft
8881ddba811664ddb4f67e143b876fc7f06a5c9d
use std::io; use std::error::Error; use std::net::SocketAddr; use std::str; use bytes::BytesMut; use tokio_io::codec::{Encoder, Decoder}; use bincode::{serialize, deserialize, Infinite}; use tokio_proto::pipeline::ServerProto; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::Framed; use tokio_service::{NewSe...
use std::io; use std::error::Error; use std::net::SocketAddr; use std::str; use bytes::BytesMut; use tokio_io::codec::{Encoder, Decoder}; use bincode::{serialize, deserialize, Infinite}; use tokio_proto::pipeline::ServerProto; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::Framed; use tokio_service::{NewSe...
} struct RaftServiceFactory { tx: UnboundedSender<oneshot::Sender<usize>> } impl RaftServiceFactory { fn new(handle: &Handle) -> RaftServiceFactory { let mut rng = rand::thread_rng(); let (tx, rx) = unbounded(); handle.spawn(rx.for_each(move |v: oneshot::Sender<_>| { v.send(rng.gen()); Ok...
fn call(&self, req: Self::Request) -> Self::Future { info!(target: "rust", "[SERVER] request {:?}", req); match req { RaftRequest::RequestVote(_term, _candidate) => { let (oneshot_tx,oneshot_rx) = oneshot::channel::<usize>(); self.tx.send(oneshot_tx).map_err(|e| io::Error::new(io::ErrorKin...
function_block-full_function
[ { "content": "fn main() {\n\n if let Err(ref e) = run() {\n\n println!(\"error: {}\", e);\n\n\n\n for e in e.iter().skip(1) {\n\n println!(\"caused by: {}\", e);\n\n }\n\n\n\n if let Some(backtrace) = e.backtrace() {\n\n println!(\"backtrace: {:?}\", backtrace);\n\n }\n\n\n\n ::std:...
Rust
rwarden/src/settings.rs
nn1ks/rwarden
e2a6331a546e4f9ca39a5f0fa62213ee492f6c82
use serde::{Deserialize, Serialize}; pub use request::*; mod request; #[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)] #[serde(transparent)] pub struct EquivalentDomains(pub Vec<String>); #[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] p...
use serde::{Deserialize, Serialize}; pub use request::*; mod request; #[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)] #[serde(transparent)] pub struct EquivalentDomains(pub Vec<String>); #[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] p...
NORTON: Self = Self(20); pub const VERIZON: Self = Self(21); pub const BUY: Self = Self(22); pub const SIRIUS: Self = Self(23); pub const EA: Self = Self(24); pub const BASECAMP: Self = Self(25); pub const STEAM: Self = Self(26); pub const CHART: Self = Self(27); pub const GOTOMEETING: S...
PAY_PAL: Self = Self(14); pub const AVON: Self = Self(15); pub const DIAPERS: Self = Self(16); pub const CONTACTS: Self = Self(17); pub const AMAZON: Self = Self(18); pub const COX: Self = Self(19); pub const
random
[ { "content": "pub trait Request<'request, 'client, TCache> {\n\n type Output;\n\n fn send(&'request self, client: &'client mut Client<TCache>) -> Self::Output;\n\n}\n\n\n\n/// Struct for specifying the URLs of API endpoints.\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]\n\npub st...
Rust
src/test.rs
m-ou-se/floatconv
e5b4387c3a2a6ff2b43469bfb074242a6aaf680d
use crate::*; #[test] fn test_all_from_u8() { for i in 0..=u8::MAX { let a = f32::from_bits(soft::u8_to_f32(i)); let b = i as f32; assert_eq!(a, b, "{} -> f32", i); let a = f64::from_bits(soft::u8_to_f64(i)); let b = i as f64; assert_eq!(a, b, "{} -> f64", i); ...
use crate::*; #[test] fn test_all_from_u8() { for i in 0..=u8::MAX { let a = f32::from_bits(soft::u8_to_f32(i)); let b = i as f32; assert_eq!(a, b, "{} -> f32", i); let a = f64::from_bits(soft::u8_to_f64(i)); let b = i as f64; assert_eq!(a, b, "{} -> f64", i); ...
#[test] fn test_i128() { for &i in &[ 0, 1, 2, 3, 1234, -0, -1, -2, -3, -1234, i128::max_value(), i128::max_value() - 1, i128::max_value() / 2, i128::min_value(), i128::min_value() + 1, ...
fn test_i64() { for &i in &[ 0, 1, 2, 3, 1234, -0, -1, -2, -3, -1234, i64::max_value(), i64::max_value() - 1, i64::max_value() / 2, i64::min_value(), i64::min_value() + 1, i64::min_value()...
function_block-full_function
[ { "content": "#[cfg_attr(not(noinline), inline)]\n\npub fn u8_to_f32(x: u8) -> u32 {\n\n u16_to_f32(x.into())\n\n}\n\n\n", "file_path": "src/soft.rs", "rank": 0, "score": 106132.21559986373 }, { "content": "#[cfg_attr(not(noinline), inline)]\n\npub fn u16_to_f32(x: u16) -> u32 {\n\n if...
Rust
src/main.rs
germansmedia/commedia
40682f7a357f18ee4f52db367ab91efd21d183da
use std::fs; use std::io::prelude::*; extern crate rand; use rand::Rng; use rand::seq::SliceRandom; extern crate rand_distr; use rand_distr::*; extern crate math; use math::*; extern crate image; use image::*; mod context3d_xcb_glx_opengl45; use context3d_xcb_glx_opengl45::*; mod opengl45; use opengl45::*; mod...
use std::fs; use std::io::prelude::*; extern crate rand; use rand::Rng; use rand::seq::SliceRandom; extern crate rand_distr; use rand_distr::*; extern crate math; use math::*; extern crate image; use image::*; mod context3d_xcb_glx_opengl45; use context3d_xcb_glx_opengl45::*; mod opengl45; use opengl45::*; mod...
} images",session.count); }, SessionStyle::StillDepth(_scale,_offset) => { println!(" generating {} images with depth",session.count); }, SessionStyle::Moving => { println!(" generating {} movies",session.count); }, ...
ckground = backgrounds.choose(rng).expect("unable to select background from set"); } let cropspace = background.size - ctx.framebuffer.size; let pos = usizexy { x: (rng.gen::<f32>() * (cropspace.x as f32)) as usize,y: (rng.gen::<f32>() * (cropspace.y as f32)) as usize, };...
random
[ { "content": "pub fn load_config(name: &str) -> Option<Vec<Session>> {\n\n let file = File::open(name).expect(\"cannot open config file\");\n\n let reader = BufReader::new(&file);\n\n let mut parser = Parser {\n\n lines: reader.lines(),\n\n linenr: 0usize,\n\n line: None,\n\n };...
Rust
crates/aleph-dx12/src/dxgi/swap_chain_desc.rs
nathanvoglsam/aleph
00f12548f7f50ade0f60343b6c5001bc0ddde6cd
use crate::dxgi::{AlphaMode, Format, SampleDesc, Scaling, SwapChainFlags, SwapEffect, UsageFlags}; use crate::Bool; pub struct SwapChainDesc1Builder { inner: SwapChainDesc1, } impl SwapChainDesc1Builder { #[inline] pub fn new() -> Self { Self { inner: SwapChainDesc1 { ...
use crate::dxgi::{AlphaMode, Format, SampleDesc, Scaling, SwapChainFlags, SwapEffect, UsageFlags}; use crate::Bool; pub struct SwapChainDesc1Builder { inner: SwapChainDesc1, } impl SwapChainDesc1Builder { #[inline] pub fn new() -> Self { Self { inner: SwapChainDesc1 { ...
le_desc: SampleDesc, pub buffer_usage: UsageFlags, pub buffer_count: u32, pub scaling: Scaling, pub swap_effect: SwapEffect, pub alpha_mode: AlphaMode, pub flags: SwapChainFlags, } impl SwapChainDesc1 { #[inline] pub fn builder() -> SwapChainDesc1Builder { SwapChainDesc1Builder:...
f.inner.alpha_mode = alpha_mode; self } #[inline] pub fn usage_flags(mut self, usage_flags: UsageFlags) -> Self { self.inner.buffer_usage |= usage_flags; self } #[inline] pub fn flags(mut self, flags: SwapChainFlags) -> Self { self.inner.flags |= flags; ...
random
[ { "content": "#[inline]\n\npub fn is_format_unsupported(format: VkFormat) -> bool {\n\n match format {\n\n VkFormat::UNDEFINED => true,\n\n _ => false,\n\n }\n\n}\n\n\n\n///\n\n/// A list of all formats allowed by the KTX2 spec\n\n///\n\npub const ALLOWED_FORMATS: [VkFormat; 176] = [\n\n ...
Rust
src/lib.rs
vojtechkral/bard
9bcaca90deb9f2d3230af0f4b3485ed5a4218938
use std::env; use std::ffi::OsString; use std::path::{Path, PathBuf}; use serde::Serialize; use structopt::clap::AppSettings; use structopt::StructOpt; pub mod book; pub mod cli; pub mod default_project; pub mod error; pub mod music; pub mod parser; pub mod project; pub mod render; pub mod util; pub mod util_cmd; pub...
use std::env; use std::ffi::OsString; use std::path::{Path, PathBuf}; use serde::Serialize; use structopt::clap::AppSettings; use structopt::StructOpt; pub mod book; pub mod cli; pub mod default_project; pub mod error; pub mod music; pub mod parser; pub mod project; pub mod render; pub mod util; pub mod util_cmd; pub...
pub fn bard_watch_at<P: AsRef<Path>>(opts: &MakeOpts, path: P, mut watch: Watch) -> Result<()> { loop { let project = bard_make_at(opts, &path)?; eprintln!(); cli::status("Watching", "for changes in the project ..."); match watch.watch(&project)? { WatchEvent::Path(pat...
n bard_make(opts: &MakeOpts) -> Result<()> { let cwd = get_cwd()?; bard_make_at(opts, &cwd)?; cli::success("Done!"); Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn sort_lines(path: &str, regex: &str) -> Result<()> {\n\n let regex = Regex::from_str(regex).with_context(|| format!(\"Invalid regex: `{}`\", regex))?;\n\n\n\n let path = PathBuf::from(path);\n\n let file =\n\n File::open(&path).with_context(|| format!(\"Could not open file `{...
Rust
launchdarkly-server-sdk/src/config.rs
ramosbugs/rust-server-sdk
f91c51c6426df29d567a4434698d4ad1f26f82cd
use crate::data_source_builders::{DataSourceFactory, NullDataSourceBuilder}; use crate::data_store_builders::{DataStoreFactory, InMemoryDataStoreBuilder}; use crate::events::processor_builders::{ EventProcessorBuilder, EventProcessorFactory, NullEventProcessorBuilder, }; use crate::{ServiceEndpointsBuilder, Streami...
use crate::data_source_builders::{DataSourceFactory, NullDataSourceBuilder}; use crate::data_store_builders::{DataStoreFactory, InMemoryDataStoreBuilder}; use crate::events::processor_builders::{ EventProcessorBuilder, EventProcessorFactory, NullEventProcessorBuilder, }; use crate::{ServiceEndpointsBuilder, Streami...
}
let builder = ConfigBuilder::new("sdk-key").service_endpoints( ServiceEndpointsBuilder::new().relay_proxy("http://my-relay-hostname:8080"), ); let endpoints = builder.service_endpoints_builder.unwrap().build().unwrap(); assert_eq!( endpoints.streaming_base_url(), ...
function_block-function_prefix_line
[ { "content": "fn process_put(data_store: &mut dyn DataStore, event: es::Event) -> Result<()> {\n\n let put: PutData = parse_event_data(&event)?;\n\n if put.path == \"/\" || put.path.is_empty() {\n\n data_store.init(put.data);\n\n Ok(())\n\n } else {\n\n Err(Error::InvalidPutPath(pu...
Rust
src/api/expense.rs
Aelto/calco
92d520ecc991a2b454a9db87d825cde7f6476d58
use crate::models::expense::Expense; use crate::models::user::{UserRole}; use crate::models::sheet::Sheet; use crate::utils::req_auth::request_authentication; use serde::{Deserialize, Serialize}; use actix_web::{web, HttpRequest, HttpResponse, Result, http}; use chrono::prelude::*; #[derive(Serialize, Deserialize)] pu...
use crate::models::expense::Expense; use crate::models::user::{UserRole}; use crate::models::sheet::Sheet; use crate::utils::req_auth::request_authentication; use serde::{Deserialize, Serialize}; use actix_web::{web, HttpRequest, HttpResponse, Result, http}; use chrono::prelude::*; #[derive(Serialize, Deserialize)] pu...
pub struct DeleteExpenseByIdBody { pub id: i32, pub sheet_id: i32 } pub async fn delete_expense_by_id(req: HttpRequest, form: web::Form<DeleteExpenseByIdBody>) -> Result<HttpResponse> { let auth_result = request_authentication(&req, UserRole::Guest); match auth_result { Ok(auth) => { if !auth.has_ac...
ount, form.sheet_id, date.and_hms(0, 0, 0).timestamp()); expense.insert() .map_err(|err| { println!("error when creating expense {}", err); HttpResponse::InternalServerError() .content_type("text/plain") .body("Internal server error: error when inserting expense into database") ...
random
[ { "content": "pub fn request_authentication(req: &HttpRequest, role: UserRole) -> Result<AuthenticationResult, String> {\n\n let token_cookie = req.cookie(\"token\");\n\n\n\n if token_cookie.is_none() {\n\n return Ok(AuthenticationResult::DoesNotHaveAccess);\n\n }\n\n \n\n let token_cookie = token_cooki...
Rust
src/input_text/utf8_input_text_builder.rs
denjiry/sudachi.rs
ab22cba0f0fe02dcdf67cca578e3f720ca33e537
use std::ops::Range; use super::utf8_input_text::Utf8InputText; use crate::dic::category_type::{CategoryType, CategoryTypes}; use crate::dic::grammar::Grammar; pub struct Utf8InputTextBuilder<'a> { grammar: &'a Grammar<'a>, pub original: &'a str, pub modified: String, modified_to_origin...
use std::ops::Range; use super::utf8_input_text::Utf8InputText; use crate::dic::category_type::{CategoryType, CategoryTypes}; use crate::dic::grammar::Grammar; pub struct Utf8InputTextBuilder<'a> { grammar: &'a Grammar<'a>, pub original: &'a str, pub modified: String, modified_to_origin...
}
ed.len()]; let mut ci = 0; while ci < char_category_types.len() { let clen = Utf8InputTextBuilder::get_char_category_continuous_length(&char_category_types, ci); let begin = char_bound[ci]; let end = char_bound[ci + clen]; for (i, v) in (0....
function_block-function_prefixed
[ { "content": "fn build_node_oov(start: usize, end: usize, cost: i32, surface: &str, length: u16) -> Node {\n\n let mut node_ai = Node::new_oov(\n\n 8,\n\n 8,\n\n 6000,\n\n WordInfo {\n\n surface: surface.to_string(),\n\n head_word_length: length,\n\n ...
Rust
src/lib.rs
cdecompilador/Python-Regex
ba8f0f02fe0dbdedc067e365bea708a28d70b01d
use pyo3::prelude::*; use pyo3::wrap_pyfunction; use regex::Regex; use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; #[pyclass(name=Regex)] pub struct PyRegex { regex: Regex, } #[pymethods] impl PyRegex { #[new] fn new(pattern: &str) -> Self { PyRegex { regex: Regex...
use pyo3::prelude::*; use pyo3::wrap_pyfunction; use regex::Regex; use mimalloc::MiMalloc; #[global_allocator] static GLOBAL: MiMalloc = MiMalloc; #[pyclass(name=Regex)] pub struct PyRegex { regex: Regex, } #[pymethods] impl PyRegex { #[new] fn new(pattern: &str) -> Self { PyRegex { regex: Regex...
fn captures(&self, other: &str) -> Option<Vec<Option<String>>> { let capture = match self.regex.captures(other) { Some(c) => c, _ => return None, }; let new = list_captures(capture); Some(new) } } fn list_captures(capture: regex::Captures) ->Vec<Optio...
g>>>> { let mut caps = Vec::new(); for capture in self.regex.captures_iter(other) { let new = list_captures(capture); caps.push(new); } Some(caps) }
function_block-function_prefixed
[ { "content": "from .regex import *", "file_path": "regex/__init__.py", "rank": 3, "score": 20412.44921878872 }, { "content": "import regex\n\nimport re\n\nimport time\n\n\n\nbody = \"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931). \"\n\n\n\nRUNS = 1000\n\n\n\n\n\nexp = regex.Re...
Rust
src/crh/poseidon/constraints.rs
stechu/crypto-primitives
fd9a0decc470a7c92d2ed2ef7a5fffa6952c9c83
use crate::crh::poseidon::{TwoToOneCRH, CRH}; use crate::crh::{ CRHSchemeGadget as CRHGadgetTrait, TwoToOneCRHSchemeGadget as TwoToOneCRHGadgetTrait, }; use crate::{CRHScheme, Vec}; use ark_ff::PrimeField; use ark_r1cs_std::alloc::{AllocVar, AllocationMode}; use ark_r1cs_std::fields::fp::FpVar; use ark_r1cs_std::R1...
use crate::crh::poseidon::{TwoToOneCRH, CRH}; use crate::crh::{ CRHSchemeGadget as CRHGadgetTrait, TwoToOneCRHSchemeGadget as TwoToOneCRHGadgetTrait, }; use crate::{CRHScheme, Vec}; use ark_ff::PrimeField; use ark_r1cs_std::alloc::{AllocVar, AllocationMode}; use ark_r1cs_std::fields::fp::FpVar; use ark_r1cs_std::R1...
} impl<F: PrimeField + Absorb> AllocVar<PoseidonParameters<F>, F> for CRHParametersVar<F> { fn new_variable<T: Borrow<PoseidonParameters<F>>>( _cs: impl Into<Namespace<F>>, f: impl FnOnce() -> Result<T, SynthesisError>, _mode: AllocationMode, ) -> Result<Self, SynthesisError> { ...
right_input: &Self::OutputVar, ) -> Result<Self::OutputVar, SynthesisError> { let cs = left_input.cs().or(right_input.cs()); if cs.is_none() { Ok(FpVar::Constant( CRH::<F>::evaluate( &parameters.parameters, vec![left_input.value()?...
function_block-function_prefix_line
[ { "content": "pub fn evaluate_blake2s_with_parameters<F: PrimeField>(\n\n input: &[Boolean<F>],\n\n parameters: &[u32; 8],\n\n) -> Result<Vec<UInt32<F>>, SynthesisError> {\n\n assert!(input.len() % 8 == 0);\n\n\n\n let mut h = Vec::with_capacity(8);\n\n h.push(UInt32::constant(0x6A09E667).xor(&UI...
Rust
examples/cyclic-data.rs
lebai-robotics/ethercat
9044ade6ce62a5d4c6001f9b4ac05f5477e9d252
use ethercat::{ AlState, DomainIdx as DomainIndex, Idx, Master, MasterAccess, Offset, PdoCfg, PdoEntryIdx, PdoEntryIdx as PdoEntryIndex, PdoEntryInfo, PdoEntryPos, PdoIdx, SlaveAddr, SlaveId, SlavePos, SmCfg, SubIdx, }; use ethercat_esi::EtherCatInfo; use std::{ collections::HashMap, env, fs::Fi...
use ethercat::{ AlState, DomainIdx as DomainIndex, Idx, Master, MasterAccess, Offset, PdoCfg, PdoEntryIdx, PdoEntryIdx as PdoEntryIndex, PdoEntryInfo, PdoEntryPos, PdoIdx, SlaveAddr, SlaveId, SlavePos, SmCfg, SubIdx, }; use ethercat_esi::EtherCatInfo; use std::{ collections::HashMap, env, fs::Fi...
Vec<PdoCfg> = dev .rx_pdo .iter() .map(|pdo| PdoCfg { idx: PdoIdx::from(pdo.index), entries: pdo .entries .iter() .enumerate() .map(|(i, e)| PdoEntryInfo { ...
SlaveAddr::ByPos(dev_nr as u16); let slave_id = SlaveId { vendor_id: esi.vendor.id, product_code: dev.product_code, }; let mut config = master.configure_slave(slave_addr, slave_id)?; let mut entry_offsets: HashMap<PdoEntryIndex, (u8, Offset)> = HashMap::new(); ...
function_block-random_span
[ { "content": "pub fn main() -> Result<(), std::io::Error> {\n\n let slave_pos = SlavePos::from(0);\n\n let mut master = Master::open(0, MasterAccess::ReadWrite)?;\n\n master.request_state(slave_pos, AlState::PreOp)?;\n\n #[cfg(feature = \"sncn\")]\n\n master.dict_upload(slave_pos)?;\n\n let sd...
Rust
src/engine/sound/generator.rs
gitcrtn/unrust
b8b062aa0e009f5d0e42215ca6d5347a595da387
use std::collections::HashMap; use std::sync::Arc; use uni_snd::SoundGenerator; use hound::WavReader; use super::{SoundEvent, SoundPlayEvent}; use super::channel::Channel; pub struct SoundBuffer { pub output_count: usize, pub sample_rate: usize, pub samples: Vec<f32>, } pub struct Generat...
use std::collections::HashMap; use std::sync::Arc; use uni_snd::SoundGenerator; use hound::WavReader; use super::{SoundEvent, SoundPlayEvent}; use super::channel::Channel; pub struct SoundBuffer { pub output_count: usize, pub sample_rate: usize, pub samples: Vec<f32>, } pub struct Generat...
let last_channel = self.next_channel; self.next_channel = (self.next_channel + 1) % self.channels.len(); while self.next_channel != last_channel && self.channels[self.next_channel].get_priority() > evt.priority { self.next...
= Vec::new(); for _ in 0..channel_count { channels.push(Channel::new()); } Self { cache: HashMap::new(), channels, next_channel: 0, } } fn handle_play_event(&mut self, evt: &SoundPlayEvent) { let mut free_channel_id = evt.c...
random
[ { "content": "pub fn pre_render(engine: &mut IEngine) {\n\n let imgui = instance::imgui_inst();\n\n let mut inner = imgui.inner.lock().unwrap();\n\n\n\n let ctx = { &mut engine.gui_context() };\n\n let mut ctx_mut = ctx.borrow_mut();\n\n\n\n ctx_mut.update(&mut inner, engine);\n\n}\n\n\n", "f...
Rust
src/usb/devintclr.rs
fuchsch1234/lpc178x_7x
3f16024f63b09c1f8b827d3728b5db2949743734
#[doc = "Writer for register DEVINTCLR"] pub type W = crate::W<u32, super::DEVINTCLR>; #[doc = "Register DEVINTCLR `reset()`'s with value 0"] impl crate::ResetValue for super::DEVINTCLR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `FR...
#[doc = "Writer for register DEVINTCLR"] pub type W = crate::W<u32, super::DEVINTCLR>; #[doc = "Register DEVINTCLR `reset()`'s with value 0"] impl crate::ResetValue for super::DEVINTCLR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `FR...
lse) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } impl W { #[doc = "Bit 0 - 0 = No effect. 1 = The corresponding bit in USBDevIntSt...
doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) <...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
packages/engine/src/nano/client.rs
mschrader15/hash
3f5e9a846183bdb9ee5a3c8a9f502b1411ac717b
use std::time::Duration; use nng::options::{protocol::reqrep::ResendTime, Options, ReconnectMaxTime, ReconnectMinTime}; use tokio::sync::{mpsc, oneshot}; use super::{ error::{Error, Result}, spmc, }; lazy_static::lazy_static! { static ref RESEND_TIME: Duration = Duration::from_secs(1); stat...
use std::time::Duration; use nng::options::{protocol::reqrep::ResendTime, Options, ReconnectMaxTime, ReconnectMinTime}; use tokio::sync::{mpsc, oneshot}; use super::{ error::{Error, Result}, spmc, }; lazy_static::lazy_static! { static ref RESEND_TIME: Duration = Duration::from_secs(1); stat...
} impl Drop for Client { fn drop(&mut self) { for worker in self.workers.iter() { worker.stop_tx.send(()).unwrap(); } } }
pub async fn send<T: serde::Serialize>(&mut self, msg: &T) -> Result<()> { let mut nng_msg = nng::Message::new(); serde_json::to_writer(&mut nng_msg, msg)?; let (tx, rx) = oneshot::channel(); self.sender.send((nng_msg, tx)).await.unwrap(); rx.await.unwrap() }
function_block-full_function
[ { "content": "pub fn behavior(state: &mut State<'_>, _context: &Context<'_>) -> Result<()> {\n\n let mut messages = state.take_messages()?;\n\n for i in 0..state.num_agents() {\n\n let m = &mut messages[i];\n\n m.push(OutboundMessage::remove_agent(\n\n state.agent_id()?[i].to_hyph...
Rust
src/draw/plot.rs
leod/malen
69c137bce7bd23a31e039eacd2a2a7e81df5baaf
use nalgebra::{convert, Matrix2, Matrix3, Point2, Point3, Vector2}; use crate::{ draw::{ColPass, ColVertex, Font, LineBatch, TextBatch, TriBatch}, AxisRect, Canvas, Color4, Error, }; const AXIS_MARGIN: f64 = 70.0; const TICK_SIZE: f64 = 7.5; const LEGEND_LINE_SIZE: f32 = 30.0; const LEGEND_TEXT_MARGIN: f32 =...
use nalgebra::{convert, Matrix2, Matrix3, Point2, Point3, Vector2}; use crate::{ draw::{ColPass, ColVertex, Font, LineBatch, TextBatch, TriBatch}, AxisRect, Canvas, Color4, Error, }; const AXIS_MARGIN: f64 = 70.0; const TICK_SIZE: f64 = 7.5; const LEGEND_LINE_SIZE: f32 = 30.0; const LEGEND_TEXT_MARGIN: f32 =...
self.text_batch, ); pos.x += text_size.x; pos.x += LEGEND_ENTRY_MARGIN; } } fn render_lines(&mut self) { for line in self.plot.lines.iter() { for (p, q) in line.points.iter().zip(line.points.iter().skip(1)) { let p = self.map...
_ranges(pos, self.x_range, self.y_range); let shifted = clipped - Vector2::new(self.x_range.0, self.y_range.0); let scaled = self.axis_scale * shifted; let margined = scaled + self.plot_offset; let flipped = Point2::new(margined.x, self.plot.size.y - margined.y); convert(flipped)...
random
[ { "content": "/// Build a 3x3 matrix that applies transformations in this order: first\n\n/// scaling, then translation.\n\npub fn scale_translate(scale: Vector2<f32>, offset: Vector2<f32>) -> Matrix3<f32> {\n\n scale_translate3(scale, Vector3::new(offset.x, offset.y, 0.0))\n\n}\n\n\n", "file_path": "src...
Rust
swift-sys/src/metadata/value_witness/flags.rs
rustswift/swift-bindgen
941dad1caccf199fadc9711f9d36c99ba9baef85
use std::fmt; #[repr(transparent)] #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ValueWitnessFlags { data: u32, } #[rustfmt::skip] #[allow(clippy::enum_variant_names)] enum Bits { AlignmentMask = 0x000000FF, IsNonPOD = 0x00010000, IsNonInline = ...
use std::fmt; #[repr(transparent)] #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ValueWitnessFlags { data: u32, } #[rustfmt::skip] #[allow(clippy::enum_variant_names)] enum Bits { AlignmentMask = 0x000000FF, IsNonPOD = 0x00010000, IsNonInline = ...
} impl ValueWitnessFlags { #[inline] pub const fn from_bits(bits: u32) -> Self { Self { data: bits } } #[inline] pub const fn into_bits(self) -> u32 { self.data } #[inline] pub const fn align_mask(self) -> us...
field("is_inline_storage", &self.is_inline_storage()) .field("has_spare_bits", &self.is_inline_storage()) .field("is_bitwise_takable", &self.is_bitwise_takable()) .field("has_enum_witnesses", &self.has_enum_witnesses()) .field("is_incomplete", &self.is_incomplete()); ...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n #[cfg(feature = \"link\")]\n\n println!(\"cargo:rustc-link-search=/usr/lib/swift/\");\n\n}\n", "file_path": "swift-sys/build.rs", "rank": 1, "score": 50226.87150271384 }, { "content": "fn main() {\n\n let metadata = Array::<String>::get_metadata();\n\n ...
Rust
src/avc/mod.rs
ratmice/selinux
7fe41dce770dad37585f7d4ea94de9bf09eeaecc
#[cfg(test)] mod tests; use std::convert::TryFrom; use std::marker::PhantomData; use std::mem::MaybeUninit; use std::os::raw::{c_char, c_int, c_uint, c_void}; use std::sync::Once; use std::{io, ptr}; use reference_counted_singleton::{RCSRef, RefCountedSingleton}; use crate::errors::{Error, Result}; use crate::utils:...
#[cfg(test)] mod tests; use std::convert::TryFrom; use std::marker::PhantomData; use std::mem::MaybeUninit; use std::os::raw::{c_char, c_int, c_uint, c_void}; use std::sync::Once; use std::{io, ptr}; use reference_counted_singleton::{RCSRef, RefCountedSingleton}; use crate::errors::{Error, Result}; use crate::utils:...
match result { Ok(value) => { if newly_initialized || value.0 == options { Ok(value) } else { let er...
let result = avc.get_or_init(|| { if unsafe { selinux_sys::avc_open(options_ptr, count) } == -1 { Err(Error::last_io_error("avc_open()")) } else { newly_initialized = true; Ok(AccessVectorCache(options.clone())) } });
assignment_statement
[ { "content": "#[doc(alias = \"selinux_contexts_path\")]\n\npub fn contexts() -> Result<&'static Path> {\n\n let proc_name = \"selinux_contexts_path()\";\n\n get_static_path(selinux_sys::selinux_contexts_path, proc_name)\n\n}\n\n\n\n/// Return the defines tty types for newrole securettys.\n\n///\n\n/// See...
Rust
src/snmpv3.rs
stisol/rust_snmp
87e8653c65779bdb8c015ab1e57320508505b871
use types; use std::net::UdpSocket; use std::time; pub fn smtpv3_send(addr: &str, community: &str, mibvals: &[u16]) { let mut buf: [u8; 1024] = [0; 1024]; /*let mut mib: [u8; 1024] = [0; 1024]; let orgmiblen = mibvals.len(); let mut miblen = orgmiblen; let...
use types; use std::net::UdpSocket; use std::time; pub fn smtpv3_send(addr: &str, community: &str, mibvals: &[u16]) { let mut buf: [u8; 1024] = [0; 1024]; /*let mut mib: [u8; 1024] = [0; 1024]; let orgmiblen = mibvals.len(); let mut miblen = orgmiblen; let...
0x4d, 0xab, 0x22, 0xcc]); index += types::write_u8(&mut buf[index..], 0x00); index += types::write_u8(&mut buf[index..], 0x00); index += types::write_octet_string(&mut buf[index..], "usr-none-none".as_bytes()); index += types::write_octet_string(&mut buf[index..], &[]...
function_block-function_prefix_line
[ { "content": "//! Contains various associated types for the library.\n\n\n\nuse std::{io, string, slice};\n\nuse traits::*;\n\n\n\nconst SNMP_INTEGER_CODE: u8 = 0x02;\n\nconst SNMP_OCTET_STRING_CODE: u8 = 0x04;\n\nconst SNMP_NULL_CODE: u8 = 0x05;\n\n\n\n/// Enum containing the various SNMP datatype...
Rust
evm-utils/programs/evm_loader/src/instructions.rs
mercury-dao/velas-chain
1dab61541dbc7677a3e1343e149c532a9629f580
use super::scope::*; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Serialize, Deserialize)] pub enum EvmBigTransaction { EvmTransactionAllocate { size: u64 }, EvmTransactionWrite { offset: u64, data: Vec<u8> }, EvmTransactionExecute {}, EvmT...
use super::scope::*; use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Eq, Ord, PartialOrd, Serialize, Deserialize)] pub enum EvmBigTransaction { EvmTransactionAllocate { size: u64 }, EvmTransactionWrite { offset: u64, data: Vec<u8> }, EvmTransactionExecute {}, EvmT...
macro_rules! len_and_hex_buf { ($buffer: expr, $data: ident $(,$fixed_len: expr)?) => { { let mut array_len: [u8; 8] = [66, 0, 0, 0, 0, 0, 0, 0]; let mut array_in_hex_bytes: [u8; 66] = [0; 66]; let data_in_hex = format!("0x{:x}", $data); ...
fn test_serialize_swap_native_to_ether_layout(lamports: u64, addr: Generator<evm::Address>) { fn custom_serialize(lamports: u64, addr: evm::Address) -> Vec<u8> { use byteorder::{LittleEndian, WriteBytesExt}; let tag: [u8; 4] = [1, 0, 0, 0]; let mut lamports_in_bytes: [u8; 8]...
function_block-full_function
[ { "content": "#[cfg(feature = \"full\")]\n\npub fn new_rand<R: ?Sized>(rng: &mut R) -> Hash\n\nwhere\n\n R: rand::Rng,\n\n{\n\n let mut buf = [0u8; HASH_BYTES];\n\n rng.fill(&mut buf);\n\n Hash::new(&buf)\n\n}\n", "file_path": "sdk/src/hash.rs", "rank": 0, "score": 378678.34726000327 }...
Rust
src/core/tick_marks.rs
Atul9/iced_audio
24be93f50fde590093c7e594e6d3c5d73f3cab6a
use std::fmt::Debug; use crate::core::Normal; #[derive(Debug, Clone)] pub struct TickMarkGroup { pub group: Vec<TickMark>, } impl Default for TickMarkGroup { fn default() -> Self { vec![TickMark::center(TickMarkTier::One)].into() } } impl TickMarkGroup { pub f...
use std::fmt::Debug; use crate::core::Normal; #[derive(Debug, Clone)] pub struct TickMarkGroup { pub group: Vec<TickMark>, } impl Default for TickMarkGroup { fn default() -> Self { vec![TickMark::center(TickMarkTier::One)].into() } } impl TickMarkGroup { pub f...
_ranges = three + 1; let one_span = 1.0 / one_ranges as f32; let two_span = one_span / two_ranges as f32; let three_span = two_span / three_ranges as f32; for i_1 in 0..one_ranges { let one_pos = (i_1 as f32 * one_span) + one_span; if i_1 != one { ...
elf, tick_mark: TickMark) { self.group.push(tick_mark); } pub fn subdivided(one: u16, two: u16, three: u16, sides: Option<TickMarkTier>) -> Self { let mut vec: Vec<TickMark> = Vec::new(); let one_ranges =...
random
[ { "content": "struct Default;\n\n\n\nimpl StyleSheet for Default {\n\n fn active(&self) -> Style {\n\n let line_color = Color::from_rgb(0.4, 0.4, 0.4);\n\n\n\n Style {\n\n background_color: Color::from_rgb(0.97, 0.97, 0.97),\n\n border_width: 1,\n\n border_color...
Rust
compiler/mlir/src/context.rs
mwatts/lumen
521fda4d040a53ad53ed88174650c60959bdbcc8
use std::convert::AsRef; use std::ffi::CString; use std::fmt; use std::path::Path; use std::thread::{self, ThreadId}; use anyhow::anyhow; use liblumen_llvm as llvm; use liblumen_llvm::enums::{CodeGenOptLevel, CodeGenOptSize}; use liblumen_llvm::target::{TargetMachine, TargetMachineRef}; use liblumen_llvm::utils::{Mem...
use std::convert::AsRef; use std::ffi::CString; use std::fmt; use std::path::Path; use std::thread::{self, ThreadId}; use anyhow::anyhow; use liblumen_llvm as llvm; use liblumen_llvm::enums::{CodeGenOptLevel, CodeGenOptSize}; use liblumen_llvm::target::{TargetMachine, TargetMachineRef}; use liblumen_llvm::utils::{Mem...
pub fn opt_level(&self) -> CodeGenOptLevel { self.opt } pub fn opt_size(&self) -> CodeGenOptSize { self.size } pub fn pass_manager_ref(&self) -> PassManagerRef { self.pass_manager } pub fn target_machine_ref(&self) -> TargetMachineRef { self.target_machin...
pub fn new( thread_id: ThreadId, options: &Options, diagnostics: &DiagnosticsHandler, target_machine: &TargetMachine, ) -> Self { let target_machine = target_machine.as_ref(); let (opt, size) = llvm::enums::to_llvm_opt_settings(options.opt_level); let context_...
function_block-full_function
[ { "content": "pub fn is_any_library(options: &Options) -> bool {\n\n options.project_type != ProjectType::Executable\n\n}\n\n\n", "file_path": "compiler/llvm/src/target.rs", "rank": 0, "score": 392523.16930104257 }, { "content": "pub fn is_pie_binary(options: &Options) -> bool {\n\n !i...
Rust
src/exec/serialize.rs
Healer-fuzz/healer-fuzz
89b3bb04150042fc1ccefa186fdf7667921607b2
use crate::model::{BinFmt, Call, Dir, Prog, ResValue, ResValueKind, Value, ValueKind}; use crate::targets::Target; use bytes::BufMut; use iota::iota; use rustc_hash::FxHashMap; use thiserror::Error; iota! { const EXEC_INSTR_EOF : u64 = (u64::MAX) ^ (iota); , EXEC_INSTR_COPY_IN , EXEC_INSTR_COPY_OU...
use crate::model::{BinFmt, Call, Dir, Prog, ResValue, ResValueKind, Value, ValueKind}; use crate::targets::Target; use bytes::BufMut; use iota::iota; use rustc_hash::FxHashMap; use thiserror::Error; iota! { const EXEC_INSTR_EOF : u64 = (u64::MAX) ^ (iota); , EXEC_INSTR_COPY_IN , EXEC_INSTR_COPY_OU...
fn write_u64(&mut self, val: u64) { if self.buf.len() >= 8 { if self.target.le_endian { self.buf.put_u64_le(val); } else { self.buf.put_u64(val); } } else { self.eof = true; } } fn write_slice<T: AsRef...
a = sz | (bf as u64) << 8 | bf_offset << 16 | bf_len << 24 | pid_stride << 32; self.write_u64(meta); self.write_u64(val); }
function_block-function_prefixed
[ { "content": "fn handle_struct(ctx: &mut ProgContext, val: &Value, parent_map: &FxHashMap<*const Value, &Value>) {\n\n let vals = val.group_val().unwrap();\n\n for v in vals {\n\n let v = if let Some(v) = v.inner_val() {\n\n v\n\n } else {\n\n continue;\n\n };\n\...
Rust
vamiliar-render/src/lib.rs
cjburkey01/vamiliar
f0bb6b381f427284e42aa5e813b2183238d884a3
mod vamiliar_shader; mod vamiliar_vertex; use std::sync::Arc; use vamiliar_shader::VamiliarShaders; use vulkano::command_buffer::ClearColorImageError; use vulkano::command_buffer::{ AutoCommandBufferBuilder, CommandBufferExecError, CommandBufferUsage, }; use vulkano::device::{Device, DeviceCreationError, DeviceExt...
mod vamiliar_shader; mod vamiliar_vertex; use std::sync::Arc; use vamiliar_shader::VamiliarShaders; use vulkano::command_buffer::ClearColorImageError; use vulkano::command_buffer::{ AutoCommandBufferBuilder, CommandBufferExecError, CommandBufferUsage, }; use vulkano::device::{Device, DeviceCreationError, DeviceExt...
self.render_frame( swapchain.as_ref().unwrap().clone(), swapchain_images, swapchain_dirty, ) .expect("failed to render frame"); Ok(()) } fn create_swapchain( &self, current_swapchain: &Option<SwapchainType>, ) -...
if *swapchain_dirty { let (new_swapchain, new_swapchain_images) = self.create_swapchain(swapchain)?; *swapchain = Some(new_swapchain); *swapchain_images = new_swapchain_images; *swapchain_dirty = false; }
if_condition
[ { "content": " vulkano_shaders::shader! {\n\n ty: \"fragment\",\n\n src: \"\n\n #version 450\n\n\n\n layout(location = 0) out vec4 fragColor;\n\n\n\n void main() {\n\n fragColor = vec4(1.0, 1.0, 1.0, 1.0);\n\n }\n\n \"\n\n }\n...
Rust
src/scene.rs
nathanross/SecondLaw
f1a6d0f9457875532b1561a81f7a0939610b2e80
extern crate tempdir; use std::env; use std::ffi::{OsStr,OsString}; use std::fs::{self}; use std::path::{Path,PathBuf}; use std::sync::Arc; use self::tempdir::TempDir; use super::atpath::AtPath; use super::ucommand::UCommand; use super::common::recursive_copy; use super::settings::SceneSettings; macro_rules! path_co...
extern crate tempdir; use std::env; use std::ffi::{OsStr,OsString}; use std::fs::{self}; use std::path::{Path,PathBuf}; use std::sync::Arc; use self::tempdir::TempDir; use super::atpath::AtPath; use super::ucommand::UCommand; use super::common::recursive_copy; use super::settings::SceneSettings; macro_rules! path_co...
pub fn ucmd(&mut self) -> UCommand { let settings = self.cloned_setting(); let mut cmd = self.cmd(&settings.as_ref().debug_bin_path); cmd.args(&settings.as_ref().subcmd_args); cmd } pub fn cmd<S: AsRef<OsStr>>(&mut self, bin: S) -> UCommand { let setting = self...
pub fn subcmd_args<'a, S: AsRef<OsStr>>(&'a mut self, added_args : &[S]) -> &'a Scene { if let Some(ref mut builder) = self.builder { if let Some(ref mut current_value) = builder.subcmd_args { for val in added_args.iter() { current_value.push(OsString::from(val.as...
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\npub fn get_root_path() -> &'static str {\n\n if cfg!(windows) {\n\n \"C:\\\\\"\n\n } else {\n\n \"/\"\n\n }\n\n}\n\n\n", "file_path": "src/common.rs", "rank": 0, "score": 125176.46640154094 }, { "content": "#[allow(dead_code)]\n\npu...
Rust
graph/src/transitivity.rs
LucaCappelletti94/EnsmallenGraph
572532b6d3f4352bf58f9ccca955376acd95fd89
use crate::constructors::build_graph_from_integers; use super::*; use indicatif::ParallelProgressIterator; use rayon::iter::ParallelIterator; impl Graph { #[fuzz_type(iterations: Option<u8>)] pub fn get_transitive_closure( &self, ...
use crate::constructors::build_graph_from_integers; use super::*; use indicatif::ParallelProgressIterator; use rayon::iter::ParallelIterator; impl Graph { #[fuzz_type(iterations: Option<u8>)] pub fn get_transitive_closure( &self, ...
!= dst_node_id as NodeT }) .map(move |(dst_node_id, distance)| { ( 0, ( src_node_id, ...
if i == 0 { return self.clone(); } } let verbose = verbose.unwrap_or(true); let pb = get_loading_bar( verbose, "Computing all unweighted shortest paths", self.get_nodes_number() as usize, ); build_graph_from_i...
function_block-random_span
[]
Rust
src/octree/node_iterator.rs
dudv/point_cloud_viewer
a48361e03d83f0dbbf33f5fa40a4fd85f4d8ffbb
use crate::codec::{decode, fixpoint_decode}; use crate::color; use crate::errors::*; use crate::math::Cube; use crate::octree::{ NodeId, NodeLayer, NodeMeta, OctreeDataProvider, OctreeMeta, PositionEncoding, }; use crate::{InternalIterator, Point}; use byteorder::{LittleEndian, ReadBytesExt}; use cgmath::Vector3; u...
use crate::codec::{decode, fixpoint_decode}; use crate::color; use crate::errors::*; use crate::math::Cube; use crate::octree::{ NodeId, NodeLayer, NodeMeta, OctreeDataProvider, OctreeMeta, PositionEncoding, }; use crate::{InternalIterator, Point}; use byteorder::{LittleEndian, ReadBytesExt}; use cgmath::Vector3; u...
; let mut position_color_reads = octree_data_provider.data(id, vec![NodeLayer::Position, NodeLayer::Color])?; Ok(NodeIterator { xyz_reader: BufReader::new( position_color_reads .remove(&NodeLayer::Position) .ok_or_else(|| "...
match octree_data_provider.data(id, vec![NodeLayer::Intensity]) { Ok(mut data_map) => match data_map.remove(&NodeLayer::Intensity) { Some(intensity_data) => Some(BufReader::new(intensity_data)), None => { return Err("No intensity reader available.".into())...
if_condition
[ { "content": "pub fn get_image_path(directory: &Path, id: NodeId) -> PathBuf {\n\n let mut rv = directory.join(&id.to_string());\n\n rv.set_extension(\"png\");\n\n rv\n\n}\n\n\n", "file_path": "xray/src/generation.rs", "rank": 0, "score": 139022.6212109248 }, { "content": "pub fn re...
Rust
src/text/fontconfig.rs
ChristopherJMiller/andrew
28a357c0cf6c69f6eb7319fdea6402c8754fb9f1
use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; #[cfg(target_os = "linux")] use xdg::BaseDirectories; use xml::reader::{EventReader, XmlEvent}; use walkdir::WalkDir; fn get_config() -> Option<PathBuf> { let xdg_dirs = BaseDirectories::with_prefix("fontconfig").unwrap(); xdg_dirs....
use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; #[cfg(target_os = "linux")] use xdg::BaseDirectories; use xml::reader::{EventReader, XmlEvent}; use walkdir::WalkDir; fn get_config() -> Option<PathBuf> { let xdg_dirs = BaseDirectories::with_prefix("fontconfig").unwrap(); xdg_dirs....
} } Ok(fonts) } }
if let Some(split) = line.find(' ') { let name = line[..split].to_string(); let settings = line[split..].to_string(); let mut char_buf = String::new(); for c in settings.chars() { if c == ' ' || c == '-' { ...
if_condition
[ { "content": "/// Loads a font file into a `Vec<u8>`\n\npub fn load_font_file<P: Into<PathBuf>>(path: P) -> Vec<u8> {\n\n let mut data: Vec<u8> = Vec::new();\n\n let mut file = File::open(path.into()).expect(\"Could not open font file\");\n\n file.read_to_end(&mut data)\n\n .expect(\"Could not r...
Rust
tezos/context-api/src/lib.rs
tezedge/tezedge
b8e20d9886ad8b6876ad62375bacf1f6b7999e3b
use serde::Deserialize; use serde::Serialize; use std::collections::BTreeMap; use std::{fmt, path::PathBuf, str::FromStr}; use strum::IntoEnumIterator; use strum_macros::EnumIter; use tezos_messages::base::rpc_support::{RpcJsonMap, UniversalValue}; pub const INMEM: &str = "inmem"; pub const ONDISK: &str = "ondisk"; ...
use serde::Deserialize; use serde::Serialize; use std::collections::BTreeMap; use std::{fmt, path::PathBuf, str::FromStr}; use strum::IntoEnumIterator; use strum_macros::EnumIter; use tezos_messages::base::rpc_support::{RpcJsonMap, UniversalValue}; pub const INMEM: &str = "inmem"; pub const ONDISK: &str = "ondisk"; ...
} } #[derive(Debug, Clone)] pub struct ParseKeyValueStoreBackendError(String); impl FromStr for SupportedContextKeyValueStore { type Err = ParseKeyValueStoreBackendError; fn from_str(s: &str) -> Result<Self, Self::Err> { let s = s.to_ascii_lowercase(); for sp in SupportedContextKeyValueS...
match self { SupportedContextKeyValueStore::InMem => vec!["inmem"], SupportedContextKeyValueStore::OnDisk => vec!["ondisk"], }
if_condition
[ { "content": "pub trait GenState: Clone + PartialEq + Eq + Hash + Debug {\n\n /// Predicate that allows limiting the size of state graph.\n\n fn within_bounds(&self) -> bool;\n\n}\n\n\n", "file_path": "shell_automaton/tests/state_explorer.rs", "rank": 0, "score": 348633.7368104221 }, { ...
Rust
src/write/file.rs
youngsofun/parquet2
e8a0c3576d5b43636fd16a942bc392d450344416
use std::io::Write; use parquet_format_async_temp::FileMetaData; use parquet_format_async_temp::thrift::protocol::TCompactOutputProtocol; use parquet_format_async_temp::thrift::protocol::TOutputProtocol; use parquet_format_async_temp::RowGroup; pub use crate::metadata::KeyValue; use crate::{ error::{ParquetError...
use std::io::Write; use parquet_format_async_temp::FileMetaData; use parquet_format_async_temp::thrift::protocol::TCompactOutputProtocol; use parquet_format_async_temp::thrift::protocol::TOutputProtocol; use parquet_format_async_temp::RowGroup; pub use crate::metadata::KeyValue; use crate::{ error::{ParquetError...
pub fn start(&mut self) -> Result<()> { self.offset = start_file(&mut self.writer)? as u64; Ok(()) } pub fn write<E>(&mut self, row_group: RowGroupIter<'_, E>, num_rows: usize) -> Result<()> where ParquetError: From<E>, E: std::error::Error, { ...
writer: W, schema: SchemaDescriptor, options: WriteOptions, created_by: Option<String>, ) -> Self { Self { writer, schema, options, created_by, offset: 0, row_groups: vec![], } }
function_block-function_prefixed
[ { "content": "/// writes the page header into `writer`, returning the number of bytes used in the process.\n\nfn write_page_header<W: Write>(mut writer: &mut W, header: &ParquetPageHeader) -> Result<u64> {\n\n let mut protocol = TCompactOutputProtocol::new(&mut writer);\n\n Ok(header.write_to_out_protocol...
Rust
src/game.rs
Niedzwiedzw/prawario
dcd29b6393fdc04832ee1dcbe9682e298ebde159
use rand::rngs::ThreadRng; use rand::thread_rng; use crate::obstacles::CollectibleHandle; use crate::rendering::Render; use itertools::Itertools; use quicksilver::input::Key; use quicksilver::Input; use quicksilver::{ geom::{Circle, Vector}, graphics::Color, Graphics, }; use crate::communication::ClientMes...
use rand::rngs::ThreadRng; use rand::thread_rng; use crate::obstacles::CollectibleHandle; use crate::rendering::Render; use itertools::Itertools; use quicksilver::input::Key; use quicksilver::Input; use quicksilver::{ geom::{Circle, Vector}, graphics::Color, Graphics, }; use crate::communication::ClientMes...
pub fn heal(&mut self, amount: f32) { self.size += amount*0.33; } } impl PartialEq for Player { fn eq(&self, other: &Player) -> bool { self.handle == other.handle } } impl Eq for Player {} impl Obstacle for Player { fn radius(&self) -> f32 { self.size } fn center...
pub fn new(player_handle: PlayerHandle) -> Self { Self { size: crate::config::PLAYER_MIN_SIZE, speed: crate::config::PLAYER_DEFAULT_SPEED, handle: player_handle, ..Default::default() } }
function_block-full_function
[ { "content": "#[wasm_bindgen_test(async)]\n\nfn async_test() -> impl Future<Item = (), Error = JsValue> {\n\n // Creates a JavaScript Promise which will asynchronously resolve with the value 42.\n\n let promise = js_sys::Promise::resolve(&JsValue::from(42));\n\n\n\n // Converts that Promise into a Futu...