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
crates/brine_proto_backend/src/backend_stevenarella/codec.rs
BGR360/brine
048656dfb3dc5c608536f14d687c6f7a9075df0a
use std::{ io::{self, Cursor, Write}, ops::Deref, }; use bevy::log; use steven_protocol::protocol::{self, State, VarInt}; pub use steven_protocol::protocol::{packet, Direction, Error, PacketType, Serializable}; use brine_net::{Decode, DecodeResult, Encode, EncodeResult}; use crate::codec::{ IntoDecodeRes...
use std::{ io::{self, Cursor, Write}, ops::Deref, }; use bevy::log; use steven_protocol::protocol::{self, State, VarInt}; pub use steven_protocol::protocol::{packet, Direction, Error, PacketType, Serializable}; use brine_net::{Decode, DecodeResult, Encode, EncodeResult}; use crate::codec::{ IntoDecodeRes...
} impl Decode for MinecraftClientCodec<MinecraftCodec> { type Item = Packet; type Error = Error; fn decode(&mut self, buf: &mut [u8]) -> (usize, DecodeResult<Packet, Error>) { let result = MinecraftCodec::decode_packet( self.protocol_version(), self.protocol_state(), ...
fn react_to_packet(&self, packet: &Packet) { match packet { Packet::Known(packet::Packet::Handshake(handshake)) => { if let Some(next_state) = match handshake.next.0 { HANDSHAKE_STATUS_NEXT => Some(MinecraftProtocolState::Status), ...
function_block-full_function
[ { "content": "type CodecWriteEvent<Codec> = Write<<Codec as Encode>::Item, Codec>;\n\n\n\nimpl<Codec> Plugin for NetworkPlugin<Codec>\n\nwhere\n\n Codec: Decode + Encode + Default + Clone + Unpin + Any + Send + Sync,\n\n <Codec as Decode>::Item: Debug + Send + Sync,\n\n <Codec as Encode>::Item: Debug +...
Rust
src/lib.rs
d2ce/byteorder-extended
d328770d31d983d5df256db7fb967851455339fa
extern crate byteorder; use std::io::{self, Read, Write, Result}; use byteorder::{WriteBytesExt, ReadBytesExt, BigEndian}; macro_rules! read_var { ($rdr: expr, $t: ty, $size: expr) => {{ let mut value: $t = 0; let mut offset = 0; while offset < $size { let b = try!(ReadExt::r...
extern crate byteorder; use std::io::{self, Read, Write, Result}; use byteorder::{WriteBytesExt, ReadBytesExt, BigEndian}; macro_rules! read_var { ($rdr: expr, $t: ty, $size: expr) => {{ let mut value: $t = 0; let mut offset = 0; while offset < $size { let b = try!(ReadExt::r...
} impl<R: Read + ?Sized> ReadExt for R {} pub trait WriteExt: WriteBytesExt { #[inline] fn write_u8(&mut self, data: u8) -> Result<()> { WriteBytesExt::write_u8(self, data).map_err(From::from) } #[inline] fn write_u16(&mut self, data: u16) -> Result<()> { WriteBytesExt::write_u16...
fn read_utf(&mut self, len: usize) -> Result<String> { let mut buf = vec![0; len]; try!(self.read_exact(&mut buf[0..])); match String::from_utf8(buf) { Ok(s) => Ok(s), Err(_) => { Err(io::Error::new( io::ErrorKind::InvalidInput, ...
function_block-full_function
[]
Rust
src/mqueue.rs
M1cha/nix
432fb906150599c0072420f9524ac42080e1ca20
use crate::Result; use crate::errno::Errno; use libc::{self, c_char, mqd_t, size_t}; use std::ffi::CStr; use crate::sys::stat::Mode; use std::mem; libc_bitflags!{ pub struct MQ_OFlag: libc::c_int { O_RDONLY; O_WRONLY; O_RDWR; O_CREAT; O_EXCL; O_NONBLOCK; O...
use crate::Result; use crate::errno::Errno; use libc::{self, c_char, mqd_t, size_t}; use std::ffi::CStr; use crate::sys::stat::Mode; use std::mem; libc_bitflags!{ pub struct MQ_OFlag: libc::c_int { O_RDONLY; O_WRONLY; O_RDWR; O_CREAT; O_EXCL; O_NONBLOCK; O...
g, oldattr.mq_attr.mq_msgsize, oldattr.mq_attr.mq_curmsgs); mq_setattr(mqd, &newattr) }
function_block-function_prefixed
[ { "content": "#[allow(clippy::useless_conversion)]\n\npub fn open<P: ?Sized + NixPath>(path: &P, oflag: OFlag, mode: Mode) -> Result<RawFd> {\n\n let fd = path.with_nix_path(|cstr| {\n\n unsafe { libc::open(cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint) }\n\n })?;\n\n\n\n Errno::result(fd)\...
Rust
src/solver/strategy/specific/sum.rs
florian1345/sudoku-variants
dd493c8e0745de10f3697c7cc3657c30136018b2
use std::iter::Peekable; use crate::util::USizeSet; fn find_options_unique_rec<'a, I>(mut missing: I, current_sum: usize, required_sum: usize, new_options: &mut [USizeSet], numbers: &mut USizeSet) -> bool where I: ExactSizeIterator<Item = &'a USizeSet> + Clone { let options = missing.next().unwrap(); ...
use std::iter::Peekable; use crate::util::USizeSet; fn find_options_unique_rec<'a, I>(mut missing: I, current_sum: usize, required_sum: usize, new_options: &mut [USizeSet], numbers: &mut USizeSet) -> bool where I: ExactSizeIterator<Item = &'a USizeSet> + Clone { let options = missing.next().unwrap(); ...
} pub(crate) fn is_possible_unique<'a, I>(missing: I, current_sum: usize, required_sum: usize) -> bool where I: ExactSizeIterator<Item = &'a USizeSet> + Clone { if missing.len() == 0 { return current_sum == required_sum; } find_options_unique(missing, current_sum, required_sum).iter() ...
find_options(missing, current_sum, required_sum, |missing, current_sum, required_sum, new_options| { let lower = new_options[0].lower(); let upper = new_options[0].upper(); let mut numbers = USizeSet::new(lower, upper).unwrap(); find_options_unique_rec(missing, cu...
call_expression
[ { "content": "fn is_bun(options: &USizeSet, size: usize) -> bool {\n\n (options - &bun(size)).is_empty()\n\n}\n\n\n", "file_path": "src/solver/strategy/specific/sandwich.rs", "rank": 3, "score": 164042.2931048206 }, { "content": "fn is_non_bun(options: &USizeSet, size: usize) -> bool {\n\...
Rust
src/moc/mod.rs
cds-astro/cds-moc-rust
d736c013371bd9ab2f728f321b3a9290661c02a5
use std::io::Write; use std::ops::Range; use std::marker::PhantomData; use crate::deser; use crate::idx::Idx; use crate::qty::{MocQty, Bounded}; use crate::elem::{ cell::Cell, cellcellrange::CellOrCellRange, range::MocRange, }; use crate::moc::adapters::{ RangeMOCIteratorFromCells, RangeMOCIteratorFromCell...
use std::io::Write; use std::ops::Range; use std::marker::PhantomData; use crate::deser; use crate::idx::Idx; use crate::qty::{MocQty, Bounded}; use crate::elem::{ cell::Cell, cellcellrange::CellOrCellRange, range::MocRange, }; use crate::moc::adapters::{ RangeMOCIteratorFromCells, RangeMOCIteratorFromCell...
#[test] fn test_range2cells_3() { let ranges = MocRanges::<u64, Hpx<u64>>::new_unchecked(vec![ 0..5, 6..59, 78..6953, 12458..55587, 55787..65587 ]); let rm = RangeMOC::new(29, ranges); let rit = (&rm).into_range_moc_iter(); let mut v1: Vec<Cell<u64>> = rit.cells()...
x<u64>>::new_unchecked(ranges); let rm = RangeMOC::new(29, ranges); let rit = (&rm).into_range_moc_iter(); let v1: Vec<Cell<u64>> = rit.cells().collect(); assert_eq!(v1, vec![ Cell::new(29, 2), Cell::new(29, 3), Cell::new(28, 1) ]); let v2: Vec<(i8, u64)> = HpxUniq2DepthIdxIte...
function_block-function_prefixed
[ { "content": "pub trait CellOrCellRangeMOC2ElemIt<T: Idx, Q: MocQty<T>, U: Idx, R: MocQty<U>> {\n\n type It1: CellOrCellRangeMOCIterator<T, Qty=Q>;\n\n type It2: CellOrCellRangeMOCIterator<U, Qty=R>;\n\n fn cellcellrange_mocs_it(self) -> (Self::It1, Self::It2);\n\n}\n\n\n", "file_path": "src/moc2d/mod.rs...
Rust
modules/maps/src/lvl/parser.rs
enteryournamehere/assembly_rs
dd5250abb586e135b59bf574543c386a4c89cbd9
use super::file::*; use assembly_core::{ nom::{ bytes::complete::{tag, take}, combinator::{cond, map}, multi::{count, fill, length_count}, number::complete::{le_f32, le_u16, le_u32, le_u8}, sequence::tuple, IResult, }, parser::{ parse_object_id, parse...
use super::file::*; use assembly_core::{ nom::{ bytes::complete::{tag, take}, combinator::{cond, map}, multi::{count, fill, length_count}, number::complete::{le_f32, le_u16, le_u32, le_u8}, sequence::tuple, IResult, }, parser::{ parse_object_id, parse...
pub fn parse_env_chunk_data(input: &[u8]) -> IResult<&[u8], EnvironmentChunkData> { let (input, section1_address) = le_u32(input)?; let (input, sky_address) = le_u32(input)?; let (input, section3_address) = le_u32(input)?; Ok(( input, EnvironmentChunkData { section1_address...
obj_id, lot, asset_type, value_1, position, rotation, scale, settings, extra: extra.unwrap_or_default(), }, )) }; let mut _parse_objects_chunk_data = map(length_co...
function_block-function_prefix_line
[ { "content": "pub fn parse_file_revision(input: &[u8], version: FileVersion) -> IResult<&[u8], Option<u32>> {\n\n cond(version.id() >= 0x24, le_u32)(input)\n\n}\n\n\n", "file_path": "modules/maps/src/luz/parser.rs", "rank": 0, "score": 545777.2715927878 }, { "content": "pub fn parse_scene...
Rust
src/diff/wrap.rs
jonsim/jiff
8797385bcc87fff8a54ee8175e000175163163cd
use std::cmp::min; use std::iter::Iterator; use ansi_term::{ANSIString, ANSIStrings}; pub struct WrappedStrIter<'a> { s: &'a str, len: usize, wrap_at: usize, cur_pos: usize, output_once: bool, } impl<'a> Iterator for WrappedStrIter<'a> { type Item = &'a str; fn next(&mut self) -> Option<&...
use std::cmp::min; use std::iter::Iterator; use ansi_term::{ANSIString, ANSIStrings}; pub struct WrappedStrIter<'a> { s: &'a str, len: usize, wrap_at: usize, cur_pos: usize, output_once: bool, } impl<'a> Iterator for WrappedStrIter<'a> { type Item = &'a str; fn next(&mut self) -> Option<&...
#[test] fn wrap_ansi_single_line_under() { let s = vec![Red.paint("hel"), Red.paint("lo")]; let s_fmt = vec![format!("{} ", ANSIStrings(&s))]; let wrapped: Vec<String> = wrap_ansistrings(&s, 10).collect(); assert_eq!(1, wrapped.len()); assert_eq!(s_fmt, wrapped); ...
let s = vec![Red.paint("")]; let s_fmt = vec![format!("{}", ANSIStrings(&s))]; let wrapped: Vec<String> = wrap_ansistrings(&s, 0).collect(); assert_eq!(1, wrapped.len()); assert_eq!(s_fmt, wrapped); }
function_block-function_prefix_line
[ { "content": "fn calculate_diff(left: &str, right: &str, split: &str) -> Vec<Diff> {\n\n let mut changeset = Changeset::new(left, right, split);\n\n let mut diffs = Vec::new();\n\n let mut previous: Option<Difference> = None;\n\n\n\n for change in changeset.diffs.drain(..) {\n\n match change ...
Rust
bevy2d/src/main.rs
Luminoth/bevy2d
44e3828c255022a8f2ade25165f5c8dafd2a3fff
mod components; mod events; mod resources; mod states; mod systems; use bevy::diagnostic::*; use bevy::prelude::*; use bevy_prototype_lyon::prelude::*; use bevy_rapier2d::physics::RapierPhysicsPlugin; use bevy_rapier2d::rapier::geometry::InteractionGroups; use once_cell::sync::Lazy; use core_lib::components::camera...
mod components; mod events; mod resources; mod states; mod systems; use bevy::diagnostic::*; use bevy::prelude::*; use bevy_prototype_lyon::prelude::*; use bevy_rapier2d::physics::RapierPhysicsPlugin; use bevy_rapier2d::rapier::geometry::InteractionGroups; use once_cell::sync::Lazy; use core_lib::components::camera...
>.system(), ) .add_system(debug_system.system()) .add_system(fps_text_system.system()) .run(); }
CTER_MASS: f32 = 100.0; const CHARACTER_GRAVITY: f32 = -750.0; const CHARACTER_JUMP_FORCE: f32 = 1500.0; const WINDOW_WIDTH: f32 = 1280.0; const WINDOW_HEIGHT: f32 = 720.0; const ASPECT_RATIO: f32 = WINDOW_WIDTH / WINDOW_HEIGHT; const PIXELS_PER_UNIT: f32 = 32.0; const CAMERA_SIZE: f32 = WINDOW_HEIGHT / (2.0 * PIXELS...
random
[ { "content": "/// Checks for pause input\n\npub fn pause_input(keyboard_input: Res<Input<KeyCode>>, mut pause_events: EventWriter<PauseEvent>) {\n\n if keyboard_input.just_pressed(KeyCode::Escape) {\n\n pause_events.send(PauseEvent);\n\n }\n\n}\n\n\n", "file_path": "bevy2d/src/systems/mod.rs", ...
Rust
src/objects/sphere.rs
cdriehuys/raytracer
7b0e67003d172f1b3ea571b39db133f3926a277a
use crate::intersections::{Intersection, Intersections}; use crate::linear::Tuple; use crate::Ray; use super::{BaseShape, Shape}; #[derive(Clone, Debug, Default)] pub struct Sphere { base: BaseShape, } impl Shape for Sphere { fn base_shape(&self) -> &BaseShape { &self.base } fn base_shape_mu...
use crate::intersections::{Intersection, Intersections}; use crate::linear::Tuple; use crate::Ray; use super::{BaseShape, Shape}; #[derive(Clone, Debug, Default)] pub struct Sphere { base: BaseShape, } impl Shape for Sphere { fn base_shape(&self) -> &BaseShape { &self.base } fn base_shape_mu...
#[test] fn normal_at_local_on_z_axis() { let s = Sphere::default(); let n = s.normal_at_local(&Tuple::new_point(0, 0, 1)); assert_eq!(n, Tuple::new_vector(0, 0, 1)); } #[test] fn normal_at_local_non_axial_point() { let s = Sphere::default(); let sqrt_3_ov...
fn normal_at_local_on_y_axis() { let s = Sphere::default(); let n = s.normal_at_local(&Tuple::new_point(0, 1, 0)); assert_eq!(n, Tuple::new_vector(0, 1, 0)); }
function_block-full_function
[ { "content": "pub trait Shape: std::fmt::Debug {\n\n /// Retrieve the object's base shape.\n\n ///\n\n /// This is used to provide default implementations for most of the shape's\n\n /// behavior. It can be replaced with [`unimplemented!`] if a shape wishes\n\n /// to provide custom implementatio...
Rust
tools/dla/src/cmdline.rs
Notgnoshi/generative
d9702c18b59553541f0cce706089f9fad501cd33
use log::trace; use std::fs::File; use std::io::{BufWriter, Write}; use std::path::PathBuf; use std::str::FromStr; use std::string::ParseError; use structopt::StructOpt; #[derive(Debug)] pub enum OutputFormat { GraphTGF, PointCloudWKT, } impl FromStr for OutputFormat { type Err = Parse...
use log::trace; use std::fs::File; use std::io::{BufWriter, Write}; use std::path::PathBuf; use std::str::FromStr; use std::string::ParseError; use structopt::StructOpt; #[derive(Debug)] pub enum OutputFormat { GraphTGF, PointCloudWKT, } impl FromStr for OutputFormat { type Err = Parse...
ness: f64, #[structopt(long, default_value = "1")] pub seeds: usize, #[structopt(long, default_value = "0")] pub seed: u64, #[structopt(short, long, default_value = "2")] pub dimensions: u8, #[structopt(short, long, default_value = "10000")] pub pa...
=> Ok(OutputFormat::GraphTGF), "points" => Ok(OutputFormat::PointCloudWKT), _ => { Ok(OutputFormat::GraphTGF) } } } } #[derive(Debug, StructOpt)] #[structopt(name = "dla...
random
[ { "content": "pub fn format_tgf(writer: &mut BufWriter<Box<dyn Write>>, graph: dla::GraphType) {\n\n // let (nodes, edges) = graph.into_nodes_edges();\n\n for idx in graph.node_indices() {\n\n let particle = graph\n\n .node_weight(idx)\n\n .expect(\"Got index to nonexistent no...
Rust
service/src/signals/link.rs
autokrator-uog/core
989986657daddb108901ee5978a2b4cac9c6291c
use std::process::exit; use actix::{AsyncContext, Context, Handler, SyncAddress, ResponseType}; use chrono::{DateTime, NaiveDateTime, Utc}; use common::schemas::{Register, Query}; use failure::{Error, ResultExt}; use redis::Commands; use rlua::Table; use serde_json::to_string_pretty; use client::Client; use error::Er...
use std::process::exit; use actix::{AsyncContext, Context, Handler, SyncAddress, ResponseType}; use chrono::{DateTime, NaiveDateTime, Utc}; use common::schemas::{Register, Query}; use failure::{Error, ResultExt}; use redis::Commands; use rlua::Table; use serde_json::to_string_pretty; use client::Client; use error::Er...
fn send_query_for_timestamp(&mut self, client: &SyncAddress<Client>) -> Result<(), Error> { let globals = self.lua.globals(); let bus: Bus = globals.get::<_, Bus>("bus").context(ErrorKind::MissingBusUserData)?; let event_types: Vec<_> = bus.event_types.into_iter().collect(); let ...
y"); let script_result: Table = self.lua.exec(&contents, Some(name)).context( ErrorKind::EvaluateLuaScript)?; info!("setting global: name='{}'", name); globals.set(name, script_result)?; Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn add_http_status_codes(lua: &mut Lua) -> Result<(), Error> {\n\n let globals = lua.globals();\n\n\n\n macro_rules! status_codes {\n\n (\n\n $(\n\n $(#[$docs:meta])*\n\n ($num:expr, $konst:ident);\n\n )+\n\n ) => {\n\n ...
Rust
src/configuration.rs
austinJayIves/metrical
30cb80bd9ad54db4a91ca315fe587339ba83c9ec
use crate::connection::Connection; use crate::protocol::{Protocol, NetworkProtocol}; use crate::metric::{MetricData, Namespace}; use std::net::IpAddr; use crate::MetricalError; #[derive(Clone)] pub struct FlushConfigurationOptions { pub flush_after_amount: Option<usize>, pub flush_after_interval: Option<u64> ...
use crate::connection::Connection; use crate::protocol::{Protocol, NetworkProtocol}; use crate::metric::{MetricData, Namespace}; use std::net::IpAddr; use crate::MetricalError; #[derive(Clone)] pub struct FlushConfigurationOptions { pub flush_after_amount: Option<usize>, pub flush_after_interval: Option<u64> ...
let ip_addr = if self.ip_addr.is_some() { self.ip_addr.unwrap() } else { return Err(MetricalError::ConfigurationInvalid("IP Address unspecified")) }; let port = if self.port.is_some() { self.port.unwrap() } else { return Err(MetricalError::ConfigurationInvalid("Port un...
let network_protocol = if self.network_protocol.is_none() { return Err(MetricalError::ConfigurationInvalid("Network Protocol unspecified")) } else { self.network_protocol.unwrap() };
assignment_statement
[]
Rust
rtcoin-client/src/main.rs
tildecoin/rtcoin
942e085f446897b35f19b86c2b9c02adc319f3c0
use std::error::Error; use std::thread; use std::time::Duration; use clap::{crate_version, value_t}; use clap::{App, Arg, SubCommand}; fn main() -> Result<(), Box<dyn Error>> { println!(); let args = App::new("rtcoin") .version(crate_version!()) .author("Ben Morri...
use std::error::Error; use std::thread; use std::time::Duration; use clap::{crate_version, value_t}; use clap::{App, Arg, SubCommand}; fn main() -> Result<(), Box<dyn Error>> { println!(); let args = App::new("rtcoin") .version(crate_version!()) .author("Ben Morri...
/* fn next_step(user: User, args: clap::ArgMatches) { let mut user = user; match args.subcommand() { ("messages", Some(msg_args)) => handle_messages(msg_args, &user), ("send", Some(send_args)) => send_tcoin(send_args, &mut user), ("", None) => println!("No subcommand issued. Something'...
s.") .required(false) .index(3), ), ) .subcommand(SubCommand::with_name("on").about("Log in to rtcoin")) .subcommand(SubCommand::with_name("off").about("Log out of rtcoin")) ...
function_block-function_prefixed
[ { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n logging::init();\n\n log::info!(\"rtcoin-server is initializing.\\n\");\n\n\n\n eprintln!(\"\\nrtcoin-server 0.1-dev\");\n\n eprintln!(\"\\nPlease enter the ledger password:\");\n\n let mut db_key_in = rpassword::prompt_password_stderr(\...
Rust
src/lib.rs
organization/jda-nas-rust
df0a91054a3928cb8113ea8e9a1677e476372697
use indexmap::IndexMap; use jni::JNIEnv; use jni::objects::{JByteBuffer, JObject, JString}; use jni::sys::{jboolean, jint, jlong, jobject, jstring}; use std::collections::HashMap; use std::ffi::c_void; use std::net::{IpAddr, UdpSocket}; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{channel, Receiver, Sender}; use...
use indexmap::IndexMap; use jni::JNIEnv; use jni::objects::{JByteBuffer, JObject, JString}; use jni::sys::{jboolean, jint, jlong, jobject, jstring}; use std::collections::HashMap; use std::ffi::c_void; use std::net::{IpAddr, UdpSocket}; use std::sync::{Arc, Mutex}; use std::sync::mpsc::{channel, Receiver, Sender}; use...
} struct Manager { senders: Arc<Mutex<HashMap<i64, Sender<Packet>>>>, queues: Arc<Mutex<IndexMap<i64, Queue>>>, capacity: usize, interval: Duration, } impl Manager { fn new(capacity: usize, interval: Duration) -> Self { Self { senders: Default::default(), queues: D...
fn send(&mut self) { self.last_sent = Instant::now(); if let Ok(packet) = self.rx.try_recv() { self.socket.send(&packet).unwrap(); } }
function_block-full_function
[ { "content": "# jda-nas-rust\n\nRewrite [JDA-NAS](https://github.com/sedmelluq/jda-nas/tree/master/udp-queue-natives) library with Rust\n", "file_path": "README.md", "rank": 19, "score": 0.9451020616027604 } ]
Rust
src/main.rs
k-nasa/playback
8ecf9743421425b8b546dbae7e51a94ecdc65401
use anyhow::{bail, Result}; use chrono::{DateTime, Duration, NaiveDateTime, Utc}; use clap::{App, AppSettings, Arg}; use reqwest::{Method, Url}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::convert::TryInto; use std::str::FromStr; use std::time; use tokio::sync::mpsc; use tokio::task; us...
use anyhow::{bail, Result}; use chrono::{DateTime, Duration, NaiveDateTime, Utc}; use clap::{App, AppSettings, Arg}; use reqwest::{Method, Url}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::convert::TryInto; use std::str::FromStr; use std::time; use tokio::sync::mpsc; use tokio::task; us...
w::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let tail = match s.chars().last() { None => bail!("invalid shift time"), Some(tail) => tail, }; let number = s[0..(s.len() - 1)].parse()?; let time_type = match tail { 's' => TimeType::...
!("please specify log filepath or access log text") } let logs = if let Some(path) = filepath { resolve_log_file(path) } else if let Some(text) = access_log { resolve_log_text(text) } else { unreachable!() }?; let shift = matches.value_of("shift").unwrap_or("0s"); l...
random
[ { "content": "# playback (wip)\n\n\n\n## Overview\n\n\n\n[![Actions Status](https://github.com/k-nasa/playback/workflows/CI/badge.svg)](https://github.com/k-nasa/playback/actions)\n\n\n\nA tool for replaying access.\n\n\n\nResend the request that was actually sent based on the access log.\n\n(Please use it when...
Rust
src/lib.rs
lmammino/gmaps-static
3cc8ee1b5994fcf9ae2b1f33c3de17a5c1bd2188
mod center; pub mod credentials; mod format; mod language; mod location; mod maptype; pub mod marker; mod path; mod querystringable; mod region; mod rgb_color; mod rgba_color; mod scale; mod size; pub mod style; mod visible; mod zoom; pub use center::*; pub use credentials::*; pub use format::*; pub use language::*; p...
mod center; pub mod credentials; mod format; mod language; mod location; mod maptype; pub mod marker; mod path; mod querystringable; mod region; mod rgb_color; mod rgba_col
value)| { pairs.append_pair(key.as_str(), value.as_str()); }); pairs.append_pair( self.credentials.get_key_name().as_str(), self.credentials.get_key().as_str(), ); } if let Some(secr...
or; mod scale; mod size; pub mod style; mod visible; mod zoom; pub use center::*; pub use credentials::*; pub use format::*; pub use language::*; pub use location::*; pub use maptype::*; pub use path::*; pub use querystringable::*; pub use region::*; pub use rgb_color::*; pub use rgba_color::*; pub use scale::*; pub u...
random
[ { "content": "/// Signs a URL using [Google Static Map API signature algorithm](https://developers.google.com/maps/documentation/maps-static/get-api-key#dig-sig-manual).\n\n///\n\n/// You don't have to use this function directly. When creating URLs using [`crate::Map`], if [`crate::Credentials`] with\n\n/// a s...
Rust
tests/lex/lexer.rs
JSAbrahams/mamba
66ae435a4abf496aae945a78e4fdfa8e4785d854
use mamba::common::position::{CaretPos, Position}; use mamba::lex::token::Lex; use mamba::lex::token::Token; use mamba::lex::tokenize; #[test] fn from() { let source = String::from("from i import b"); let tokens = tokenize(&source).unwrap(); assert_eq!(tokens, vec![ Lex { pos: Positio...
use mamba::common::position::{CaretPos, Position}; use mamba::lex::token::Lex; use mamba::lex::token::Token; use mamba::lex::tokenize; #[test] fn from() { let source = String::from("from i import b"); let tokens = tokenize(&source).unwrap(); assert_eq!(tokens, vec![ Lex { pos: Positio...
on::new(&CaretPos::new(1, 1), &CaretPos::new(1, 21)), token: Token::Str(String::from("my string {my_var}"), vec![vec![Lex { pos: Position::new(&CaretPos::new(1, 13), &CaretPos::new(1, 19)), token: Token::Id(String::from("my_var")) }]],) },]); } #[test] fn fstring_set() { ...
n fstring() { let source = String::from("\"my string {my_var}\""); let tokens = tokenize(&source).unwrap(); assert_eq!(tokens, vec![Lex { pos: Positi
function_block-random_span
[ { "content": "fn create(state: &mut State, token: Token) -> LexResult<Vec<Lex>> { Ok(state.token(token)) }\n\n\n", "file_path": "src/lex/tokenize.rs", "rank": 0, "score": 276549.32708594296 }, { "content": "pub fn pass(input: &[Lex]) -> Vec<Lex> {\n\n let passes: Vec<Box<dyn Pass>> = vec!...
Rust
rust/src/parseable.rs
AdamLassiter/coalescence
7b0585d1f2e4784770ecceb868b430acab4894a8
use crate::expression::Expr; pub trait Parseable: Sized { fn inner_parse(input: &str, parent: &str) -> Result<Self, String>; fn parse(input: &str) -> Result<Self, String> { Self::inner_parse(input, "[root]") } } fn nongreedy_parse(input: &str, parent: &str) -> Result<(Expr, usize), String> { ...
use crate::expression::Expr; pub trait Parseable: Sized { fn inner_parse(input: &str, parent: &str) -> Result<Self, String>; fn parse(input: &str) -> Result<Self, String> { Self::inner_parse(input, "[root]") } } fn nongreedy_parse(input: &str, parent: &str) -> Result<(Expr, usize), String> { ...
) } }
match maybe_expr_fn { Some(expr_fn) => { let right_inp_string = mid_inp.chars().skip(mid_idx + 1).collect::<String>(); let right_inp = &right_inp_string.trim_start(); let right_expr = Self::inner_parse(right_inp, left_inp)?; expr_fn(right_expr)...
if_condition
[ { "content": "#[test]\n\nfn atoms() -> Result<(), String> {\n\n log_init();\n\n\n\n assert_eq!(\n\n Expr::parse(\"(a & ~b) | (c & ~a)\")?.normal().atoms(),\n\n Set::from([\n\n &Expr::Atom(\"a\".to_string()),\n\n &Expr::NotAtom(\"a\".to_string()),\n\n &Expr::N...
Rust
steward/src/lib.rs
GrandmasterTash/OpenRec
74b6a49a17b15d520c0ad3307539d3277c473503
mod state; mod display; mod metrics; mod register; use chrono::Utc; use crossbeam::channel; use parking_lot::Mutex; use register::Register; use itertools::Itertools; use prometheus::Histogram; use anyhow::{Result, bail}; use lazy_static::lazy_static; use std_semaphore::Semaphore; use fs_extra::dir::get_dir_content; us...
mod state; mod display; mod metrics; mod register; use chrono::Utc; use crossbeam::channel; use parking_lot::Mutex; use register::Register; use itertools::Itertools; use prometheus::Histogram; use anyhow::{Result, bail}; use lazy_static::lazy_static; use std_semaphore::Semaphore; use fs_extra::dir::get_dir_content; us...
fn handle_keyboard(app_state: AppState, key: Option<Result<u8, std::io::Error>>) -> AppState { if app_state == AppState::Running { if let Some(Ok(b'q')) = key { return AppState::Terminating; } if let Some(Ok(b'r')) = key { return AppState::Reloading; }...
e(register_path: &Path) -> Result<State, anyhow::Error> { let register = Register::load(register_path)?; Ok(State::new(&register, register_path)) }
function_block-function_prefixed
[ { "content": "pub fn display(stdout: &mut RawTerminal<StdoutLock>, state: &mut State, app_state: &AppState, mut terminal_size: (u16, u16)/* , selected: Option<usize> */) -> (u16, u16) {\n\n\n\n // If the terminal has been resized then clear it.\n\n terminal_size = clear_if_resized(terminal_size, stdout);\...
Rust
r3_kernel/src/drivers/display/fb_text.rs
Narasimha1997/r3
fbeea8de1c7b07bad3a30c511a1085c8dd0c4495
extern crate alloc; extern crate log; extern crate spin; use crate::drivers::display::font::{get_bit_for_char, FONT_HEIGHT, FONT_WIDTH, LINUX_BOOT_FONT}; use crate::drivers::display::framebuffer; use alloc::string::ToString; use core::fmt; use lazy_static::lazy_static; use spin::{Mutex, MutexGuard}; const SCROLL_LIN...
extern crate alloc; extern crate log; extern crate spin; use crate::drivers::display::font::{get_bit_for_char, FONT_HEIGHT, FONT_WIDTH, LINUX_BOOT_FONT}; use crate::drivers::display::framebuffer; use alloc::string::ToString; use core::fmt; use lazy_static::lazy_static; use spin::{Mutex, MutexGuard}; const SCROLL_LIN...
} pub struct FramebufferLogger { pub current_lines: FramebufferLines, pub color: framebuffer::Pixel, } impl FramebufferLogger { pub fn init(color: framebuffer::Pixel) -> Self { FramebufferLogger { current_lines: FramebufferLines { row_line: 0, col_line:...
let mut c_col = pos.col_line; for ch in string.as_bytes() { if *ch <= 0x20 && *ch >= 0x7e { continue; } if *ch == b'\n' { c_col = 0; c_row += 1; continue; } else if *ch == b'\t' { ...
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn get_bit_for_char(ch: u8, pos: usize) -> u8 {\n\n ch & (0x80 >> pos)\n\n}\n", "file_path": "r3_kernel/src/drivers/display/font.rs", "rank": 0, "score": 290301.91661693057 }, { "content": "pub fn read_stdin(buffer: &mut [u8], size: usize) -> usize {\n\n ...
Rust
src/pixelindex.rs
tene/silmaril
80cb669bfedc0768520c9d9e80c876a038844e81
use crate::Color; use core::marker::PhantomData; use typenum::Unsigned; pub enum FaceType { Side, Top, } pub enum PixelIterator<T: PixelIndexable> { All(PixelIndex<T>), Down(Option<PixelIndex<T>>), Right(Option<PixelIndex<T>>, PixelIndex<T>), } impl<T: PixelIndexable> PixelIterator<T> { pub fn...
use crate::Color; use core::marker::PhantomData; use typenum::Unsigned; pub enum FaceType { Side, Top, } pub enum PixelIterator<T: PixelIndexable> { All(PixelIndex<T>), Down(Option<PixelIndex<T>>), Right(Option<PixelIndex<T>>, PixelIndex<T>), } impl<T: PixelIndexable> PixelIterator<T> { pub fn...
} pub trait PixelIndexable: Sized { type Face; type SIZE: Unsigned; type FACES: Unsigned; fn get(&self, idx: PixelIndex<Self>) -> Color; fn get_mut(&mut self, idx: PixelIndex<Self>) -> &mut Color; fn get_cylindrical_mut(&mut self, dir: f32, height: f32) -> &mut Color { let idx = Self::...
use PixelIterator::*; match self { All(next) => { let blah: usize = (*next).into(); if blah >= T::SIZE::to_usize() { None } else { let rv = Some(*next); *next += 1; rv ...
function_block-function_prefix_line
[ { "content": "pub fn lch_to_rgb(lch: Color) -> [u8; 3] {\n\n let rgb: Srgb<f32> = Srgb::convert_from(lch);\n\n let [r, g, b]: [f32; 3] = rgb.into_raw();\n\n //[(r * 256.0) as u8, (g * 256.0) as u8, (b * 256.0) as u8]\n\n [r.convert(), g.convert(), b.convert()]\n\n}\n\n\n", "file_path": "src/colo...
Rust
src/lib.rs
ferhatgec/tyfers
cf323776eb26910b27e133d87a1446d0a6269a39
pub enum Tyfes { Nothing, FPaper, Jpeg, Png, Gif, Bmp, WebP, Pdf, Ico } pub enum Markers { FPaperStart, FPaperStart2, FPaperStart3, FPaperStart4, FPaperStart5, FPaperStart6, JpegSoi, JpegStart, PngSoi, PngStart2, PngStart3, PngStar...
pub enum Tyfes { Nothing, FPaper, Jpeg, Png, Gif, Bmp, WebP, Pdf, Ico } pub enum Markers { FPaperStart, FPaperStart2, FPaperStart3, FPaperStart4, FPaperStart5, FPaperStart6, JpegSoi, JpegStart, PngSoi, PngStart2, PngStart3, PngStar...
fn what_is_this(&self) -> Tyfes { let data = std::fs::read(&self.filename).unwrap(); if *data.get(0).unwrap() == Markers::FPaperStart.val() && *data.get(1).unwrap() == Markers::FPaperStart2.val() && *data.get(2).unwrap() == Markers::FPaperStart3.val() && *data....
bmp" | "webp" | "pdf" | "ico" => { self.what_is_this() }, _ => { Tyfes::Nothing } } }
function_block-function_prefix_line
[ { "content": "# tyfers\n\n## tyfers, Rust implementation of [Tyfe](https://github.com/ferhatgec/tyfe) (file type info library)\n\n\n\n### tyfers licensed under the terms of MIT License.\n", "file_path": "README.md", "rank": 12, "score": 2.2422695951374756 } ]
Rust
rust/src/core/common/util.rs
QE-Lab/dqcsim
2257d1ec5dc9578929b1b0726d5ab299bcab04e9
use crate::common::error::{inv_arg, Result}; const fn num_bits<T>() -> usize { std::mem::size_of::<T>() * 8 } pub fn log_2(x: usize) -> Option<usize> { if x == 0 { None } else { let result = num_bits::<usize>() as u32 - x.leading_zeros() - 1; if 2_usize.pow(result) == x { ...
use crate::common::error::{inv_arg, Result}; const fn num_bits<T>() -> usize { std::mem::size_of::<T>() * 8 } pub fn log_2(x: usize) -> Option<usize> { if x == 0 { None } else { let result = num_bits::<usize>() as u32 - x.leading_zeros() - 1; if 2_usize.pow(result) == x { ...
nd y" ); assert_eq!(friendly_enumerate(vec!["x", "y"].into_iter(), None), "x, y"); assert_eq!( friendly_enumerate(vec!["foo", "bar", "baz"].into_iter(), None), "foo, bar, baz" ); assert_eq!( friendly_enumerate(vec!["one"].into_iter(), Some("and...
Iter, EnumString}; #[derive(Display, EnumIter, EnumString, Clone, PartialEq, Debug)] enum TestEnum { #[strum(to_string = "Foo", serialize = "foo", serialize = "f")] Foo, #[strum(to_string = "Bar", serialize = "bar", serialize = "b")] Bar, #[strum(to_string = "Baz", seria...
random
[ { "content": "/// Same as `api_return()`, but specialized for returning strings.\n\npub fn api_return_string(call: impl FnOnce() -> Result<String>) -> *mut c_char {\n\n api_return(null_mut(), || {\n\n call().and_then(|s| {\n\n let s = CString::new(&s[..])?;\n\n let s = unsafe { s...
Rust
src/main.rs
berrym/tic_tac_toe_rust
0e420efa27ec7b810a36f3478faf7f7e45512559
use clap::{App, Arg}; use std::io::{self, Write}; use tic_tac_toe::game::{empty_plays, Config, MiniMaxResult, Play, Player, TicTacToe}; fn main() -> Result<(), Box<dyn std::error::Error>> { let cli = App::new("Tic-Tac-Toe") .version("0.1.1") .author("Michael Berry <trismegustis@gmail.com>") ...
use clap::{App, Arg}; use std::io::{self, Write}; use tic_tac_toe::game::{empty_plays, Config, MiniMaxResult, Play, Player, TicTacToe}; fn main() -> Result<(), Box<dyn std::error::Error>> { let cli = App::new("Tic-Tac-Toe") .version("0.1.1") .author("Michael Berry <trismegustis@gmail.com>") ...
continue, } std::thread::sleep(std::time::Duration::from_millis(1000)); } else { play = player.get_play(game.board()); } } else { if config.player_o_ai { mini_max_result = player.minimax(&mut game, moves, player)...
function_block-function_prefix_line
[ { "content": " io::stdin()\n\n .read_line(&mut play)\n\n .expect(\"Failed to get input!\");\n\n let play = play.trim().parse::<usize>();\n\n let coord = translate_to_coord(play.unwrap());\n\n if empty_plays(board).iter().any(|&p| p == coo...
Rust
src/tilemap.rs
analog-hors/game-util-rs
7b238abe8ad842af6f3da32059358b0aa5ffe5a4
use crate::prelude::*; use scopeguard::ScopeGuard; pub struct TilemapRenderer { gl: Gl, shader: glow::Program, tilemap: glow::Texture, proj_loc: glow::UniformLocation, size_loc: glow::UniformLocation, offset_loc: glow::UniformLocation, tilemap_size_loc: glow::UniformLocation, tileset_lo...
use crate::prelude::*; use scopeguard::ScopeGuard; pub struct TilemapRenderer { gl: Gl, shader: glow::Program, tilemap: glow::Texture, proj_loc: glow::UniformLocation, size_loc: glow::UniformLocation, offset_loc: glow::UniformLocation, tilemap_size_loc: glow::UniformLocation, tileset_lo...
} impl Drop for TilemapRenderer { fn drop(&mut self) { unsafe { self.gl.delete_texture(self.tilemap); } } } pub fn tilemap_shader(gl: &Gl) -> glow::Program { glutil::compile_shader_program( gl, include_str!("shaders/tilemap.vert.glsl"), include_str!("sh...
pub fn render_section( &self, camera: Transform3D<f32>, tileset: glow::Texture, rect: Rect<f32>, ) { unsafe { self.gl.use_program(Some(self.shader)); self.gl.uniform_1_i32(Some(&self.tileset_loc), 1); self.gl .uniform_2_f32...
function_block-full_function
[ { "content": "pub fn link_program(gl: &Gl, shaders: &[glow::Shader]) -> Result<glow::Program, String> {\n\n unsafe {\n\n let program = gl.create_program()?;\n\n for &shader in shaders {\n\n gl.attach_shader(program, shader);\n\n }\n\n gl.link_program(program);\n\n\n\n ...
Rust
src/lalr_utils/src/rule.rs
0xcxdxxr/lalalere
95ba2a46e61f822f53a7c74b56b682ff3e2e814e
use std::collections::{hash_map, HashMap, HashSet}; use std::hash::{Hash, Hasher}; use super::ast::{Ast, AstNode}; use super::symbol::Symbol; pub struct Rule<T> { pub id: usize, pub src: Symbol, pub ast_cnt: u16, pub term_cnt: u16, pub symbols: Vec<Symbol>, pub attributes: HashSet<String>, ...
use std::collections::{hash_map, HashMap, HashSet}; use std::hash::{Hash, Hasher}; use super::ast::{Ast, AstNode}; use super::symbol::Symbol; pub struct Rule<T> { pub id: usize, pub src: Symbol, pub ast_cnt: u16, pub term_cnt: u16, pub symbols: Vec<Symbol>, pub attributes: HashSet<String>, ...
for literal in symbol_literals.iter() { let symbol = Symbol::from(*literal).as_terminal(); if terminals.contains(&symbol) { rule.symbols.push(symbol.as_terminal()); } else { rule.symbols.push(symbol.as_non_terminal()); } } ...
let mut rule = Rule { id, src, ast_cnt: 0, term_cnt: 0, symbols: vec![], attributes: HashSet::new(), handle_reduce: None, handle_exec: Box::new(|ast: &Ast<T>| -> Option<T> { let mut res = None; ...
assignment_statement
[ { "content": "pub fn make_first<T>(first: &mut HashMap<Symbol, HashSet<Symbol>>, grammar: &Grammar<T>) {\n\n\tlet mut add_sub: bool;\n\n\tloop {\n\n\t\tadd_sub = false;\n\n\t\tfor (src, rule_set) in grammar.iter() {\n\n\t\t\t// i am curr param\n\n\t\t\tlet my_firsts = first.get(&src).unwrap();\n\n\t\t\tlet mut ...
Rust
src/assets.rs
jayphbee/galois
38c68881d77fc1c2c6dc3a3482aabd684d91ae7e
use crate::core::*; use rust_decimal::{prelude::Zero, Decimal}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)] pub struct Account { pub available: Decimal, pub frozen: Decimal, } pub fn get_mut(accounts: &mut Accounts, user:...
use crate::core::*; use rust_decimal::{prelude::Zero, Decimal}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)] pub struct Account { pub available: Decimal, pub frozen: Decimal, } pub fn get_mut(accounts: &mut Accounts, user:...
; } } #[test] pub fn test_deser_from_json() { let mut all = Accounts::new(); let s = r#"{"amount":"10000","cmd":11,"currency":101,"user_id":2}"#; help(&mut all, s); let s = r#"{"amount":"3.41","cmd":11,"currency":101,"user_id":2}"#; help(&mut all, s); ...
deduct_available( all, cmd.user_id.unwrap(), cmd.currency.unwrap(), cmd.amount.unwrap(), )
call_expression
[ { "content": "pub fn cancel(book: &mut OrderBook, order_id: u64) -> Option<Match> {\n\n let price = book.indices.remove(&order_id)?;\n\n match (book.get_best_ask(), book.get_best_bid()) {\n\n (Some(best_ask), _) => {\n\n let (from, removed) = if price >= best_ask {\n\n (\n...
Rust
crates/hyperqueue/src/common/parser.rs
User3574/hyperqueue
d4dea5a805925cb624eb81da65840d5a8226d4a9
use std::fmt::{Debug, Write}; use nom::character::complete::satisfy; use nom::combinator::{all_consuming, map, map_res}; use nom::error::{ContextError, ErrorKind, FromExternalError, ParseError}; use nom::multi::many0; use nom::sequence::tuple; use nom::{AsChar, IResult, InputLength, Parser}; use nom_supreme::error::{B...
use std::fmt::{Debug, Write}; use nom::character::complete::satisfy; use nom::combinator::{all_consuming, map, map_res}; use nom::error::{ContextError, ErrorKind, FromExternalError, ParseError}; use nom::multi::many0; use nom::sequence::tuple; use nom::{AsChar, IResult, InputLength, Parser}; use nom_supreme::error::{B...
#[test] fn test_parse_u32_repeated_underscore() { assert_eq!(all_consuming(p_u32)("1___0__0_0").unwrap().1, 1000); } #[test] fn test_parse_u32_starts_with_underscore() { check_parse_error( p_u32, "_", r#"Parse error expected integer at character...
fn test_parse_u32_underscores() { assert_eq!(all_consuming(p_u32)("0_1").unwrap().1, 1); assert_eq!(all_consuming(p_u32)("1_").unwrap().1, 1); assert_eq!(all_consuming(p_u32)("100_100").unwrap().1, 100100); assert_eq!(all_consuming(p_u32)("123_456_789").unwrap().1, 123456789); }
function_block-full_function
[ { "content": "pub fn check_parse_error<F: FnMut(&str) -> NomResult<O>, O>(\n\n parser: F,\n\n input: &str,\n\n expected_error: &str,\n\n) {\n\n match consume_all(parser, input) {\n\n Err(e) => {\n\n let output = format!(\"{:?}\", e);\n\n assert_eq!(output, expected_error...
Rust
tests/borrow.rs
rust-numpy/rust-numpy
19bfc9d2d0e72bb3ed30c08244ee81abd02d7386
use std::thread::spawn; use numpy::{ npyffi::NPY_ARRAY_WRITEABLE, PyArray, PyArray1, PyArray2, PyReadonlyArray3, PyReadwriteArray3, }; use pyo3::{py_run, pyclass, pymethods, types::IntoPyDict, Py, PyAny, Python}; #[test] fn distinct_borrows() { Python::with_gil(|py| { let array1 = PyArray::<f64, _>::z...
use std::thread::spawn; use numpy::{ npyffi::NPY_ARRAY_WRITEABLE, PyArray, PyArray1, PyArray2, PyReadonlyArray3, PyReadwriteArray3, }; use pyo3::{py_run, pyclass, pymethods, types::IntoPyDict, Py, PyAny, Python}; #[test] fn distinct_borrows() { Python::with_gil(|py| { let array1 = PyArray::<f64, _>::z...
(5).unwrap(); assert_eq!(array.as_slice_mut().unwrap(), &[0.0; 5]); }); }
.eval("array[0:2]", None, Some(locals)) .unwrap() .downcast::<PyArray1<f64>>() .unwrap(); assert_eq!(view1.shape(), [2]); let view2 = py .eval("array[1:3]", None, Some(locals)) .unwrap() .downcast::<PyArray1<f64>>() ...
random
[ { "content": "fn not_contiguous_array(py: Python) -> &PyArray1<i32> {\n\n py.eval(\n\n \"np.array([1, 2, 3, 4], dtype='int32')[::2]\",\n\n None,\n\n Some(get_np_locals(py)),\n\n )\n\n .unwrap()\n\n .downcast()\n\n .unwrap()\n\n}\n\n\n", "file_path": "tests/array.rs", ...
Rust
sos21-use-case/src/get_project_by_code.rs
sohosai/sos21-backend
f1883844b0e5c68d6b3f9d159c9268142abc81b4
use crate::error::{UseCaseError, UseCaseResult}; use crate::model::project::{Project, ProjectFromEntityInput}; use anyhow::Context; use sos21_domain::context::project_repository::{self, ProjectRepository}; use sos21_domain::context::Login; use sos21_domain::model::project; #[derive(Debug, Clone)] pub enum Error { ...
use crate::error::{UseCaseError, UseCaseResult}; use crate::model::project::{Project, ProjectFromEntityInput}; use anyhow::Context; use sos21_domain::context::project_repository::{self, ProjectRepository}; use sos21_domain::context::Login; use sos21_domain::model::project; #[derive(Debug, Clone)] pub enum Error { ...
( get_project_by_code::run(&app, project_other.code().to_string()).await, Err(UseCaseError::UseCase(get_project_by_code::Error::NotFound)) )); } #[tokio::test] async fn test_committee_different_kind_other() { let user = test::model::new_committee_user(); ...
m_entity(project.id()) && got.name == project.name().as_str() )); } #[tokio::test] async fn test_committee_other() { let user = test::model::new_committee_user(); let other = test::model::new_general_user(); let project_other = test::model::new_general_proje...
random
[ { "content": "pub fn new_general_project_with_subowner(owner_id: UserId, subowner_id: UserId) -> Project {\n\n new_project_with_subowner(owner_id, subowner_id, ProjectCategory::General)\n\n}\n\n\n", "file_path": "sos21-domain/src/test/model/project.rs", "rank": 0, "score": 404058.4298273364 }, ...
Rust
src/rt-plot/approximation.rs
svencurkovic/rt-plot
d0510bbf6b09a01f89bd567508cb27ffd9f22b54
use ndarray::*; use ndarray_linalg::*; use ordered_float::OrderedFloat; use std::collections::BTreeMap; #[derive(Debug)] pub enum Type { Constant, Linear, Quadratic, } fn polyfit( x_values: &Vec<f32>, y_values: &Vec<f32>, polynomial_degree: usize, ) -> (Vec<f32>, Vec<f32>) { let number_of_...
use ndarray::*; use ndarray_linalg::*; use ordered_float::OrderedFloat; use std::collections::BTreeMap; #[derive(Debug)] pub enum Type { Constant, Linear, Quadratic, } fn polyfit( x_values: &Vec<f32>, y_values: &Vec<f32>, polynomial_degree: usize, ) -> (Vec<f32>, Vec<f32>) { let number_of_...
), 2.0 * a], vec![ ((b / a).powf(4.0) / 16.0 * sigma_a.powf(2.0) + (b / a).powf(2.0) / 4.0 * sigma_b.powf(2.0) + sigma_c.powf(2.0)) .sqrt(), ((b / a).powf(2.0) / (4.0 * a.powf(2.0)) * sigma_a.powf...
=> (coefficients.clone(), errors.clone()), Type::Linear => { let b = coefficients[0]; let a = coefficients[1]; let sigma_b = errors[0]; let sigma_a = errors[1]; (vec![-b / a, a], vec![(sigma_b / a).abs(), sigma_a.abs()]) } Type::Quadr...
random
[ { "content": "pub fn transformation_matrix(translation: [f32; 2], scale: [f32; 2]) -> Matrix3<f32> {\n\n Matrix3::new_nonuniform_scaling(&Vector2::new(scale[0], scale[1]))\n\n * (Matrix3::new_translation(&Vector2::new(translation[0], translation[1])))\n\n}\n", "file_path": "src/rt-plot/renderer.rs...
Rust
src/lib.rs
lukaspustina/clam
9ca2730ca05b8b464cf490f7bc1e6444c2678156
mod reexports { #[doc(hidden)] pub use colored::*; #[doc(hidden)] pub use indicatif::*; #[doc(hidden)] pub use log::*; } pub mod prelude { pub use crate::reexports::*; pub use crate::config::{Config, default_locations}; pub use crate::console::ask_for_confirmation; pub use crate::fs::FileE...
mod reexports { #[doc(hidden)] pub use colored::*; #[doc(hidden)] pub use indicatif::*; #[doc(hidden)] pub use log::*; } pub mod prelude { pub use crate::reexports::*; pub use crate::config::{Config, default_locations}; pub use crate::console::ask_for_confirmation; pub use crate::fs::FileE...
error_chain! { types { ConfigError, ConfigErrorKind, ConfigResultExt, ConfigResult; } errors { NoSuitableConfigFound(configs: Vec<String>) { description("No suitable configuration found") display("No suitable configuration found '{:?...
pub fn default_locations(config_file_name: &str) -> Vec<PathBuf> { let mut locations: Vec<PathBuf> = Vec::new(); if let Some(mut path) = home_dir() { let home_config = format!(".{}", config_file_name); path.push(home_config); locations.push(path); } ...
function_block-function_prefix_line
[]
Rust
src/ui/diff.rs
mrkline/backpak
5bb9dc9760119867f4025d975f0e3d72c31923bc
use std::path::Path; use anyhow::*; use log::*; use structopt::StructOpt; use crate::backend; use crate::diff; use crate::fs_tree; use crate::hashing::ObjectId; use crate::index; use crate::ls; use crate::snapshot; use crate::tree::{self, Forest, Node, NodeType}; #[derive(Debug, StructOpt)] pub struct Args { #[s...
use std::path::Path; use anyhow::*; use log::*; use structopt::StructOpt; use crate::backend; use crate::diff; use crate::fs_tree; use crate::hashing::ObjectId; use crate::index; use crate::ls; use crate::snapshot; use crate::tree::{self, Forest, Node, NodeType}; #[derive(Debug, StructOpt)] pub struct Args { #[s...
}
old_node: &Node, old_forest: &Forest, new_node: &Node, new_forest: &Forest, ) -> Result<()> { ls::print_node("- ", node_path, old_node, ls::Recurse::Yes(old_forest)); ls::print_node("+ ", node_path, new_node, ls::Recurse::Yes(new_forest)); Ok(()) ...
function_block-function_prefixed
[ { "content": "#[cfg(target_family = \"windows\")]\n\npub fn get_metadata(path: &Path) -> Result<NodeMetadata> {\n\n use std::os::windows::fs::MetadataExt;\n\n\n\n let meta =\n\n fs::symlink_metadata(path).with_context(|| format!(\"Couldn't stat {}\", path.display()))?;\n\n let attributes = meta....
Rust
src/qubits.rs
oxarbitrage/RustQIP
56757b5a3eb2474542aa8a47ff839470d98d4f91
use crate::errors::CircuitError; use crate::pipeline::*; use crate::types::Precision; use crate::Complex; use std::cmp::Ordering; use std::fmt; use std::rc::Rc; #[derive(Debug)] pub enum Parent { Owned(Vec<Register>, Option<StateModifier>), Shared(Rc<Register>), } pub struct Register { ...
use crate::errors::CircuitError; use crate::pipeline::*; use crate::types::Precision; use crate::Complex; use std::cmp::Ordering; use std::fmt; use std::rc::Rc; #[derive(Debug)] pub enum Parent { Owned(Vec<Register>, Option<StateModifier>), Shared(Rc<Register>), } pub struct Register { ...
e_measurement_handle(id: u64, r: Register) -> (Register, MeasurementHandle) { let indices = r.indices.clone(); let shared_parent = Rc::new(r); let handle = MeasurementHandle::new(&shared_parent); ( Register { indices, parent: Some(Parent::Share...
return CircuitError::make_err(message); } } if indices.len() == r.indices.len() { CircuitError::make_str_err("Cannot split out all indices into own Registers.") } else if indices.is_empty() { CircuitError::make_str_err("Must provide indices to sp...
random
[ { "content": "/// Get the index for a submatrix indexed by `indices` given the `full_index` for the larger 2^n by 2^n matrix.\n\npub fn full_to_sub(n: u64, mat_indices: &[u64], full_index: u64) -> u64 {\n\n let nindices = mat_indices.len() as u64;\n\n mat_indices\n\n .iter()\n\n .enumerate()...
Rust
src/adc.rs
Piroro-hs/stm32l4xx-hal
09c652660af83878556510266f58ca6349718c21
use core::convert::Infallible; use core::ptr; use crate::{ gpio::Analog, hal::{ adc::{Channel as EmbeddedHalChannel, OneShot}, blocking::delay::DelayUs, }, pac, rcc::{AHB2, CCIPR}, }; #[cfg(any(feature = "stm32l4x1", feature = "stm32l4x2", feature = "stm32l4x3",))] use pac::ADC a...
use core::convert::Infallible; use core::ptr; use crate::{ gpio::Analog, hal::{ adc::{Channel as EmbeddedHalChannel, OneShot}, blocking::delay::DelayUs, }, pac, rcc::{AHB2, CCIPR}, }; #[cfg(any(feature = "stm32l4x1", feature = "stm32l4x2", feature = "stm32l4x3",))] use pac::ADC a...
pub fn set_resolution(&mut self, resolution: Resolution) { self.resolution = resolution; } pub fn set_sample_time(&mut self, sample_time: SampleTime) { self.sample_time = sample_time; } pub fn release(self) -> ADC1 { self.inner } } impl<...
f { ahb.enr().modify(|_, w| w.adcen().set_bit()); ahb.rstr().modify(|_, w| w.adcrst().set_bit()); ahb.rstr().modify(|_, w| w.adcrst().clear_bit()); ccipr.ccipr().modify(|_, w| { unsafe { w.adcsel().bits(0b11); ...
function_block-function_prefixed
[ { "content": "#[entry]\n\nfn main() -> ! {\n\n rtt_target::rtt_init_print!();\n\n rprint!(\"Initializing...\");\n\n\n\n let cp = pac::CorePeripherals::take().unwrap();\n\n let dp = pac::Peripherals::take().unwrap();\n\n\n\n let mut rcc = dp.RCC.constrain();\n\n let mut flash = dp.FLASH.constra...
Rust
rend3/src/renderer/object.rs
Noxime/rend3
8270d40cb7522a1212b1b99ab768cc525786f04f
use crate::{ bind_merge::BindGroupBuilder, datatypes::{AffineTransform, MaterialHandle, Object, ObjectHandle}, mode::ModeData, registry::ResourceRegistry, renderer::{frustum::BoundingSphere, material::MaterialManager, mesh::MeshManager}, RendererMode, }; use std::{mem::size_of, sync::Arc}; use w...
use crate::{ bind_merge::BindGroupBuilder, datatypes::{AffineTransform, MaterialHandle, Object, ObjectHandle}, mode::ModeData, registry::ResourceRegistry, renderer::{frustum::BoundingSphere, material::MaterialManager, mesh::MeshManager}, RendererMode, }; use std::{mem::size_of, sync::Arc}; use w...
; *self.object_info_buffer_storage.as_gpu_mut() = Some(obj_buffer.get_current_inner()); } object_count } pub fn values(&self) -> impl Iterator<Item = &InternalObject> { self.registry.values() } pub fn gpu_append_to_bgb<'a>(&'a self, general_bgb: &mut BindGroupBuil...
write_to_buffer1(device, encoder, obj_buffer, obj_buffer_size, |_, obj_slice| { let obj_slice: &mut [ShaderInputObject] = bytemuck::cast_slice_mut(obj_slice); for (object_idx, object) in registry.values().enumerate() { obj_slice[object_idx] = Sh...
call_expression
[]
Rust
client/src/render/deferred.rs
grunnt/yab-world
0aa327cb1d3d1dd7ca81fbdb4cdfbbf5790f9849
use failure; use gamework::video::*; use gamework::*; use gl; use nalgebra_glm::*; use rand::Rng; const SSAO_KERNEL_SIZE: usize = 128; #[derive(VertexAttribPointers, Copy, Clone, Debug)] #[repr(C, packed)] pub struct QuadVertex { #[location = "0"] pub position: data::f32_f32, #[location = "1"] pub tex...
use failure; use gamework::video::*; use gamework::*; use gl; use nalgebra_glm::*; use rand::Rng; const SSAO_KERNEL_SIZE: usize = 128; #[derive(VertexAttribPointers, Copy, Clone, Debug)] #[repr(C, packed)] pub struct QuadVertex { #[location = "0"] pub position: data::f32_f32, #[location = "1"] pub tex...
(gl::TRIANGLE_STRIP, 0, 4); self.gl.Disable(gl::FRAMEBUFFER_SRGB); } } }
color_buffer, normal_buffer, lights_buffer, view_uniform, projection_uniform, light_dir_uniform, light_col_uniform, fog_col_uniform, fog_start_uniform, fog_end_uniform, random_texture, ...
random
[ { "content": "pub fn aspect_ratio(width: u32, height: u32) -> f32 {\n\n width as f32 / height as f32\n\n}\n", "file_path": "gamework/src/video/mod.rs", "rank": 0, "score": 384175.81689749844 }, { "content": "fn orthographic(width: f32, height: f32) -> Mat4 {\n\n Mat4::new_orthographic(...
Rust
src/proc/bin/starnix/types.rs
billchen1977/fuchsia
d443f9c7b03ad317d1700c2c9457be8ed1147b86
#![allow(non_camel_case_types)] #![allow(dead_code)] use { fuchsia_zircon::{self as zx, sys::zx_vaddr_t}, std::fmt, std::ops, zerocopy::AsBytes, }; pub type uid_t = u32; pub type gid_t = u32; pub type dev_t = u64; pub type ino_t = u64; pub type mode_t = u16; pub type off_t = i64; pub struct Errno(i...
#![allow(non_camel_case_types)] #![allow(dead_code)] use { fuchsia_zircon::{self as zx, sys::zx_vaddr_t}, std::fmt, std::ops, zerocopy::AsBytes, }; pub type uid_t = u32; pub type gid_t = u32; pub type dev_t = u64; pub type ino_t = u64; pub type mode_t = u16; pub type off_t = i64; pub struct Errno(i...
, pub _pad0: u32, pub st_rdev: dev_t, pub st_size: off_t, pub st_blksize: i64, pub st_blocks: i64, pub st_atim: timespec_t, pub st_mtim: timespec_t, pub st_ctim: timespec_t, pub _pad3: [i64; 3], }
4 = 6; pub const AT_UID: u64 = 11; pub const AT_EUID: u64 = 12; pub const AT_GID: u64 = 13; pub const AT_EGID: u64 = 14; pub const AT_SECURE: u64 = 23; pub const AT_RANDOM: u64 = 25; #[derive(Debug, Eq, PartialEq, Hash, Copy, Clone, AsBytes)] #[repr(C)] pub struct utsname_t { pub sysname: [u8; 65], pub nodenam...
random
[]
Rust
src/main-viz.rs
paavohuhtala/struggle
26ebf0c3ceac91d561d5b5d5c96c0f12f48b4bbf
use struggle_core::{ players::{default_heuristic, maximize_length_expectiminimax, GameContext, StrugglePlayer}, struggle::{Board, Player, COLORS}, }; use ::rand::prelude::*; use macroquad::prelude::*; pub const WIDTH: usize = 1000; pub const HEIGHT: usize = 1000; pub const OUTER_RADIUS: f32 = 500.0; pub const...
use struggle_core::{ players::{default_heuristic, maximize_length_expectiminimax, GameContext, StrugglePlayer}, struggle::{Board, Player, COLORS}, }; use ::rand::prelude::*; use macroquad::prelude::*; pub const WIDTH: usize = 1000; pub const HEIGHT: usize = 1000; pub const OUTER_RADIUS: f32 = 500.0; pub const...
; for (i, tile) in board.tiles.iter().enumerate() { let relative_rad = i as f32 * sector; let x = center_x + INNER_RADIUS * relative_rad.cos(); let y = center_y + INNER_RADIUS * relative_rad.sin(); let is_home_base = i % 7 == 0; let game_color = if ...
draw_text( &last_die.to_string(), center_x, center_y, 40.0, player_to_color(last_die_player), )
call_expression
[ { "content": "pub fn default_heuristic(board: &Board, player: Player, enemy: Player) -> f64 {\n\n let mut score = 0.0;\n\n\n\n match board.get_winner() {\n\n Some(winner) if winner == player => {\n\n return 10000000.0;\n\n }\n\n Some(_) => {\n\n return -10000000....
Rust
src/config/yaml_trait.rs
Joxit/task-scheduler
4125700968a01b5d41b887160c2ec91ab8287e71
use crate::config::*; use linked_hash_map::LinkedHashMap; use std::collections::HashMap; use yaml_rust::Yaml; const TASKS_KEY: &str = "tasks"; const COMMAND_KEY: &str = "commands"; const DEPENDS_ON_KEY: &str = "depends_on"; const CONCURRENCY_KEY: &str = "concurrency"; const NOTIFICATION_KEY: &str = "notification"; con...
use crate::config::*; use linked_hash_map::LinkedHashMap; use std::collections::HashMap; use yaml_rust::Yaml; const TASKS_KEY: &str = "tasks"; const COMMAND_KEY: &str = "commands"; const DEPENDS_ON_KEY: &str = "depends_on"; const CONCURRENCY_KEY: &str = "concurrency"; const NOTIFICATION_KEY: &str = "notification"; con...
fn get_on_failure(&self) -> Result<Option<OnFailure>, String> { if let Some(on_failure) = self.as_hash() { on_failure.get_on_failure() } else { Ok(None) } } fn get_messages(&self) -> Result<Messages, String> { if let Some(messages) = self.as_hash() { messages.get_messages() ...
fn get_when_notify(&self) -> Result<Option<WhenNotify>, String> { if let Some(when_notify) = self.as_hash() { when_notify.get_when_notify() } else { Ok(None) } }
function_block-full_function
[ { "content": "pub fn notification_print(print: &Print, message: &str) -> Result<(), String> {\n\n writeln(\n\n print.output(),\n\n format!(\n\n \"{} INFO [notification::print] {}\",\n\n Local::now().format(\"%Y-%m-%d %H:%M:%S,%3f\"),\n\n message\n\n ),\n\n )\n\n .map_err(|msg| format!...
Rust
src/options.rs
yusdacra/rust-nix-templater
b3f270b964d45121db15a7caebc80d046db86b1c
use std::{ fmt::{self, Display, Formatter}, path::PathBuf, str::FromStr, }; use structopt::StructOpt; #[allow(clippy::struct_excessive_bools)] #[derive(StructOpt, Debug, Default, Clone)] #[structopt(name = "rust-nix-templater")] pub struct Options { #[structopt(long)] pub github_ci: bool, ...
use std::{ fmt::{self, Display, Formatter}, path::PathBuf, str::FromStr, }; use structopt::StructOpt; #[allow(clippy::struct_excessive_bool
ite!(f, "stable"), Self::Beta => write!(f, "beta"), Self::Nightly => write!(f, "nightly"), } } }
s)] #[derive(StructOpt, Debug, Default, Clone)] #[structopt(name = "rust-nix-templater")] pub struct Options { #[structopt(long)] pub github_ci: bool, #[structopt(long)] pub gitlab_ci: bool, #[structopt(long)] pub disable_build: bool, #[structopt(short, long, default_val...
random
[ { "content": "fn quote(value: impl Display) -> String {\n\n format!(\"\\\"{}\\\"\", value)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 22061.65750032662 }, { "content": "fn write_files(out_dir: &std::path::Path, files: Vec<(&str, String)>) -> anyhow::Result<()> {\n\n us...
Rust
src/providers/mod.rs
Superhepper/parsec
b595ff7769598d2da9a7515f6306fac4c8a00bd1
use parsec_interface::requests::ProviderID; use serde::Deserialize; pub mod core_provider; #[cfg(feature = "pkcs11-provider")] pub mod pkcs11_provider; #[cfg(feature = "mbed-crypto-provider")] pub mod mbed_provider; #[cfg(feature = "tpm-provider")] pub mod tpm_provider; #[derive(Deserialize, Debug)] #[serde(tag...
use parsec_interface::requests::ProviderID; use serde::Deserialize; pub mod core_provider; #[cfg(feature = "pkcs11-provider")] pub mod pkcs11_provider; #[cfg(feature = "mbed-crypto-provider")] pub mod mbed_provider; #[cfg(feature = "tpm-provider")] pub mod tpm_provider; #[derive(Deserialize, Debug)] #[serde(tag...
}
fn psa_verify_hash( &self, _app_name: ApplicationName, _op: psa_verify_hash::Operation, ) -> Result<psa_verify_hash::Result> { Err(ResponseStatus::PsaErrorNotSupported) }
function_block-full_function
[ { "content": "/// Decodes base64 bytes to its original String value.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns an error as a string if either the decoding or the bytes conversion to UTF-8 failed.\n\nfn base64_data_to_string(base64_bytes: &[u8]) -> Result<String, String> {\n\n match base64::decode_config(b...
Rust
src/main.rs
arashsm79/jade-swarm
18d269264bfa26cf0e8ca64ec597826bd304eca0
mod problem; mod breadthfs; mod dfs; mod ids; mod bestfs; mod ucs; mod bidibestfs; mod greedybestfs; mod a_star; mod ida_star; mod rbfs; use crate::problem::JadeSwarm; use crate::problem::JadeGraph; use crate::problem::StoneColor; enum SearchMethod { BFS(bool), DFSReached(bool), DFSWithoutCycleChecking(b...
mod problem; mod breadthfs; mod dfs; mod ids; mod bestfs; mod ucs; mod bidibestfs; mod greedybestfs; mod a_star; mod ida_star; mod rbfs; use crate::problem::JadeSwarm; use crate::problem::JadeGraph; use crate::problem::StoneColor; enum SearchMethod { BFS(bool), DFSReached(bool), DFSWithoutCycleChecking(b...
#[allow(dead_code)] fn test2(search_choices: &Vec<SearchMethod>) { let mut jade_graph = JadeGraph::new(7); jade_graph.set_edge((0, 4)); jade_graph.set_edge((1, 2)); jade_graph.set_edge((1, 3)); jade_graph.set_edge((1, 4)); jade_graph.set_edge((3, 5)); jade_graph.set_edge((4, 5)); jade_...
e((0, 3)); jade_graph.set_edge((1, 2)); jade_graph.set_edge((3, 4)); jade_graph.set_node_color(0, StoneColor::Black); jade_graph.set_node_color(1, StoneColor::Red); jade_graph.set_node_color(2, StoneColor::Red); jade_graph.set_node_color(3, StoneColor::Green); jade_graph.set_node_color(4, S...
function_block-function_prefixed
[ { "content": "use crate::problem::JadeSwarm;\n\nuse crate::problem::Node;\n\nuse crate::problem::StoneColor;\n\n\n\nimpl JadeSwarm {\n\n/*\n\n* --------------------------------------\n\n* --------------------------------------\n\n* Uniform Cost Search\n\n* --------------------------------------\n\n* ----------...
Rust
src/messages.rs
mattwoodyard/proxykit
7edbe936365d06edbe6fd1a8764b10081b9c5e25
use bytes::{BytesMut, Bytes}; use futures::{Poll, Async}; use futures::stream::Stream; use headers::*; use http; use httparse; use http::{header, HttpTryFrom, Method, Uri, Version}; use piece_buf::Slice; use std; use std::mem; use std::rc::Rc; enum Frame<H, B> { Header(H), Body(B), EndOfMessage } struct ...
use bytes::{BytesMut, Bytes}; use futures::{Poll, Async}; use futures::stream::Stream; use headers::*; use http; use httparse; use http::{header, HttpTryFrom, Method, Uri, Version}; use piece_buf::Slice; use std; use std::mem; use std::rc::Rc; enum Frame<H, B> { Header(H), Body(B), EndOfMessage } struct ...
/* fn get_or_eval<F>(&mut self, f: F) -> &T */ /* where F: FnOnce() -> T */ /* { */ /* match self { */ /* Lazy::Value(v) => { */ /* v */ /* } */ /* } */ /* } */ } const MAX_HEADERS:usize = 16; pub struct HeaderMap { headers: Vec<(Slic...
fn as_option(&self) -> Option<&T> { match self { &Lazy::NotYetEvaluated => { None } &Lazy::NoValue => { None } &Lazy::Value(ref v) => { Some(v) } } }
function_block-full_function
[ { "content": "#[derive(Message)]\n\nenum PoolNotice {\n\n Available(TcpStream),\n\n CheckoutFailed\n\n}\n\n\n\n\n\nimpl ConnectionPool {\n\n\n\n pub fn new() -> ConnectionPool {\n\n ConnectionPool {\n\n max_per_peer: 100,\n\n max_peers: 100,\n\n lifetime: 120,\n\...
Rust
src/bin/debug_cpu.rs
kurisuke/nessuno
a48820bde73b45bbfe66b0a247869bc1843f0da8
use nessuno::cpu::{Disassembly, Flag}; use nessuno::screen::backend::{Frame, ScreenBackend}; use nessuno::screen::textwriter::{TextScreenParams, TextWriter}; use nessuno::screen::{Screen, ScreenParams}; use nessuno::system_debug_cpu::SystemDebugCpu; use winit::event::VirtualKeyCode; use winit_input_helper::WinitInputHe...
use nessuno::cpu::{Disassembly, Flag}; use nessuno::screen::backend::{Frame, ScreenBackend}; use nessuno::screen::textwriter::{TextScreenParams, TextWriter}; use nessuno::screen::{Screen, ScreenParams}; use nessuno::system_debug_cpu::SystemDebugCpu; use winit::event::VirtualKeyCode; use winit_input_helper::WinitInputHe...
fn main() { let screen = Screen::new( ScreenParams { width: SCREEN_WIDTH, height: SCREEN_HEIGHT, title: "debug_cpu", backend: Box::new(DebugCpu::new()), }, false, ) .unwrap(); screen.run(); }
function_block-full_function
[ { "content": "#[derive(Deserialize, PartialEq, Serialize)]\n\nenum FrameCounterMode {\n\n Step4,\n\n Step5,\n\n}\n\n\n", "file_path": "src/apu.rs", "rank": 0, "score": 107629.5555711973 }, { "content": "enum StatusRegFlag {\n\n SpriteOverflow,\n\n SpriteZeroHit,\n\n VerticalBl...
Rust
rdftk_core/src/simple/mapping.rs
johnstonskj/rust-rdftk
6741ddd9c14349ecdd0658058aa62cd7d8b81cd1
/*! Simple, in-memory implementation of the `PrefixMappings` trait. */ use crate::model::graph::mapping::{PrefixMappingFactory, PrefixMappingFactoryRef, DEFAULT_PREFIX}; use crate::model::graph::{PrefixMappingRef, PrefixMappings}; use crate::model::qname::QName; use bimap::BiHashMap; use rdftk_iri::{Fragment, IRIRef};...
/*! Simple, in-memory implementation of the `PrefixMappings` trait. */ use crate::model::graph::mapping::{PrefixMappingFactory, PrefixMappingFactoryRef, DEFAULT_PREFIX}; use crate::model::graph::{PrefixMappingRef, PrefixMappings}; use crate::model::qname::QName; use bimap::BiHashMap; use rdftk_iri::{Fragment, IRIRef};...
}
let fragment = fragment.as_ref().unwrap(); ( iri.with_new_fragment(Fragment::default()), fragment.value().clone(), ) } else if iri.path().has_slug() { let mut path = iri.path().clone(); let name = path.pop_slug(); (iri.w...
function_block-function_prefix_line
[ { "content": "///\n\n/// A prefix mapping factory provides an interface to create a new prefix mapping. This allows for\n\n/// implementations where underlying shared resources are required and so may be owned by the\n\n/// factory.\n\n///\n\n/// Such a factory may only be retrieved by the [`GraphFactory::prefi...
Rust
rust/test/dt/type_constructor/many_parametrized_main_test_only.rs
Wandalen/wtools
d9e3bb7cf7423493f08dd65efc5fdc4799d1e2d5
tests_impls! { #[ test ] fn main() { #[ cfg( any( feature = "make", feature = "dt_make" ) ) ] { /* test.case( "make0" ) */ let got : Many< f32, f64 > = TheModule::make!(); let exp = Many::< f32, f64 >( std::vec::Vec::new() ); a_id!( got, exp ); /* test.case( "make1" ) ...
tests_impls! { #[ test ] fn main() { #[ cfg( any( feature = "make", feature = "dt_make" ) ) ] { /* test.case( "make0" ) */ let got : Many< f32, f64 > = TheModule::make!(); let exp = Many::< f32, f64 >( std::vec::Vec::new() ); a_id!( got, exp ); /* test.case( "make1" ) ...
k!( 1.0 ) ) ); a_id!( got, exp ); } /* test.case( "from f32 into Many" ) */ let instance1 : Many< f32, f64 > = [ mk!( 13.0 ) ].into(); let instance2 = Many::< f32, f64 >::from([ mk!( 13.0 ) ]); a_id!( instance1.0, vec![ mk!( 13.0 ) ] ); a_id!( instance2.0, vec![ mk!( 13.0 ) ] ); a_id!...
), mk!( 1.0 ) ) ); a_id!( got, exp ); /* test.case( "make3" ) */ let got : Many< f32, f64 > = TheModule::make!( mk!( 1.0 ), mk!( 1.0 ), mk!( 1.0 ) ); let exp = Many::< f32, f64 >( vec!( mk!( 1.0 ), mk!( 1.0 ), m
random
[ { "content": "fn main()\n\n{\n\n let x = make!( 0, 1, 2, 3 );\n\n}\n\n\n\n/* xxx : does not work properly currently */\n", "file_path": "rust/test/dt/type_constructor/dynamic/make/make_too_many.rs", "rank": 0, "score": 288990.2637824303 }, { "content": "fn main()\n\n{\n\n}\n", "file_pat...
Rust
rust/display-sim-core/src/general_types.rs
theypsilon/crt-3d-sim
e96d1f7f32c753da9febe34b2aed4e26b6381877
/* Copyright (c) 2019-2021 José manuel Barroso Galindo <theypsilon@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option)...
/* Copyright (c) 2019-2021 José manuel Barroso Galindo <theypsilon@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option)...
pub fn get_int_from_3_f32color(color: &[f32; 3]) -> i32 { let r = get_u8_from_f32color(color[0]); let g = get_u8_from_f32color(color[1]); let b = get_u8_from_f32color(color[2]); ((r << 16) + (g << 8) + b) as i32 } #[cfg(test)] mod tests { mod get_3_f32color_from_int { mod gives_good { ...
fn get_u8_from_f32color(color: f32) -> u32 { (match color { c if c < 0.0 => 0.0, c if c > 1.0 => 1.0, c => c, } * 255.0) as u32 }
function_block-full_function
[ { "content": "fn calculate_offsets(width: u32, height: u32) -> Vec<f32> {\n\n let pixels_total = width * height;\n\n let mut offsets: Vec<f32> = vec![0.0; pixels_total as usize * 2];\n\n {\n\n let half_width: f32 = width as f32 / 2.0;\n\n let half_height: f32 = height as f32 / 2.0;\n\n ...
Rust
src/providers/digitalocean.rs
fmeringdal/node-discover
829e92ef81a16013d6b714dd5e60f035206923c1
use log::{debug, info}; use serde::Deserialize; use std::convert::TryFrom; use std::env; use crate::{args::ParsedArgs, SupportedProvider}; use super::{DiscoverError, Provider}; #[derive(Debug, Clone, Deserialize)] struct ListDropletsResponse { pub droplets: Vec<Droplet>, } #[derive(Debug, Clone, Deserialize)] s...
use log::{debug, info}; use serde::Deserialize; use std::convert::TryFrom; use std::env; use crate::{args::ParsedArgs, SupportedProvider}; use super::{DiscoverError, Provider}; #[derive(Debug, Clone, Deserialize)] struct ListDropletsResponse { pub droplets: Vec<Droplet>, } #[derive(Debug, Clone, Deserialize)] s...
ug != *region { return None; } } let mut addrs = Vec::new(); for ipv4 in &networks.v4 { if ipv4.variant == "private" { info!( "Found instance {} ({}) with ...
lse(|| DiscoverError::MissingArgument("tag_name".into()))?; let api_token = match api_token { Some(val) => val, None => env::var("API_TOKEN") .map_err(|_| DiscoverError::MissingArgument("api_token".into()))?, }; Ok(DOProvider { tag_name, ...
random
[ { "content": "fn get_help(args: Vec<String>) {\n\n let provider = args.get(0);\n\n match provider {\n\n Some(provider) => match &provider[..] {\n\n \"aws\" => {\n\n help(\"aws\");\n\n }\n\n \"digitalocean\" => {\n\n help(\"digitalocean\...
Rust
src/db/global.rs
TrionProg/server_master
8afcbe890e2db8d09fe396931f3e25a8759249b4
use std; use bincode; use redis; use cdrs; use postgres; use mongodb; use bson; use uuid::{Uuid,UuidVersion}; use super::Error; use super::{BinaryData,ServerID,UserID}; use super::{RedisClient,MongoDatabase}; use super::{RedisCollection,MongoCollection,CassandraSession,PostgresSession}; use super::Images; use post...
use std; use bincode; use redis; use cdrs; use postgres; use mongodb; use bson; use uuid::{Uuid,UuidVersion}; use super::Error; use super::{BinaryData,ServerID,UserID}; use super::{RedisClient,MongoDatabase}; use super::{RedisCollection,MongoCollection,CassandraSession,PostgresSession}; use super::Images; use post...
pub fn set_default_avatars(&self, small_avatar:Uuid, big_avatar:Uuid) -> Result<(),Error> { let find_filter=doc! { "_id" => 1 }; let default_avatar_small_s=small_avatar.to_string(); let default_avatar_big_s=big_avatar.to_string(); let update_doc=doc! { ...
let global=match doc { Some( doc ) => doc, None => return Err(Error::Other( "mongo does not contain \"global\"".to_string() )), }; match global.get("default_avatar_small") { Some(&Bson::String(ref s)) => { let default_avatar_small=Uuid::parse_str(s.as...
function_block-function_prefix_line
[ { "content": "pub fn fill(global:&mut Global, users:&mut Users, images:&mut Images, forum:&mut Forum) -> Result<(),Error>{\n\n use std::fs::File;\n\n use std::io::BufReader;\n\n use std::io::prelude::*;\n\n\n\n println!(\"reading zaratustra\");\n\n\n\n let file = File::open(\"zaratustra.txt\").un...
Rust
libgraffiti/src/interop/nodejs.rs
egasimus/graffiti
b06c57a61c5cbcf7ee5a6d247abd0b244cb4df9d
#![allow(dead_code)] use crate::app::{App}; use crate::interop::{InteropApi}; use std::os::raw::{c_int, c_uint, c_char, c_void}; use std::ptr; use std::mem; dylib! { #[load_napi] extern "C" { fn napi_module_register(module: *mut NapiModule) -> NapiStatus; fn napi_get_undefined(env: NapiEnv, ...
#![allow(dead_code)] use crate::app::{App}; use crate::interop::{InteropApi}; use std::os::raw::{c_int, c_uint, c_char, c_void}; use std::ptr; use std::mem; dylib! { #[load_napi] extern "C" { fn napi_module_register(module: *mut NapiModule) -> NapiStatus; fn napi_get_undefined(env: NapiEnv, ...
napi_value) } } impl FromNapi for i32 { fn from(napi_value: NapiValue) -> Self { get_res!(napi_get_value_int32, napi_value) } } impl FromNapi for f32 { fn from(napi_value: NapiValue) -> Self { let v: f64 = napi_value.into2(); v as f32 } } impl FromNapi for f64 { fn fr...
{ (value as f64).into() } } impl From<f64> for NapiValue { fn from(value: f64) -> Self { get_res!(napi_create_double, value) } } impl From<String> for NapiValue { fn from(_value: String) -> Self { panic!("TODO"); } } impl From<bool> for NapiValue { fn from(value: bool)...
random
[ { "content": "pub fn get_static_ref(stretch_layout: &mut StretchLayout) -> &'static mut StretchLayout {\n\n unsafe { std::mem::transmute(stretch_layout) }\n\n}\n", "file_path": "libgraffiti/src/box_layout/stretch.rs", "rank": 0, "score": 175506.91288762336 }, { "content": "pub fn dylib_fi...
Rust
photosquid/src/checkbox.rs
IsaacShelton/photosquid
cde6cbed88081efc78325ba4d3d11e5650959e8e
use crate::{ aabb::AABB, capture::Capture, color::Color, icon_button::IconButton, matrix_helpers::reach_inside_mat4, press_animation::PressAnimation, render_ctx::RenderCtx, smooth::Smooth, text_helpers, }; use glium::glutin::event::MouseButton; use glium_text_rusttype::{FontTexture, TextDisplay, TextSystem}; us...
use crate::{ aabb::AABB, capture::Capture, color::Color, icon_button::IconButton, matrix_helpers::reach_inside_mat4, press_animation::PressAnimation, render_ctx::RenderCtx, smooth::Smooth, text_helpers, }; use glium::glutin::event::MouseButton; use glium_text_rusttype::{FontTexture, TextDisplay, TextSystem}; us...
pub fn toggle(&mut self) { self.checked = !self.checked; self.has_new_content = true; } fn update_checkmark(&mut self, ctx: &mut RenderCtx) { if self.color.is_none() { self.color = Some(Smooth::new(ctx.color_scheme.light_ribbon, Duration::from_millis(200))); } ...
pub fn poll(&mut self) -> Option<bool> { if self.has_new_content { self.has_new_content = false; Some(self.checked) } else { None } }
function_block-full_function
[ { "content": "pub fn render(circle: &mut Circle, ctx: &mut RenderCtx, as_preview: Option<PreviewParams>) {\n\n let CircleData { position, radius, color, .. } = circle.data.get_animated();\n\n\n\n if circle.mesh.is_none() {\n\n circle.mesh = Some(MeshXyz::new_shape_circle(ctx.display));\n\n }\n\n...
Rust
src/waiter.rs
ngroman/waiter
edd9bffb85c1ecda395e9422f1c50d4ab80e4ef9
extern crate nix; use nix::sys::signal; use nix::unistd; use std::process::Command; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use std::time::{Duration, Instant}; #[derive(Debug)] pub struct Waiter<'a> { pub message: String, pub action: Action<'a>, pub speak: bool, pub start: Instant, } #[...
extern crate nix; use nix::sys::signal; use nix::unistd; use std::process::Command; use std::sync::{Arc, Condvar, Mutex}; use std::thread; use std::time::{Duration, Instant}; #[derive(Debug)] pub struct Waiter<'a> { pub message: String, pub action: Action<'a>, pub speak: bool, pub start: Instant, } #[...
fn print_timer(&self, rem: Duration, total: Duration) { eprint!( " {} {} \r", Waiter::progress_bar(rem, total), Waiter::fmt_duration(rem) ); } fn fmt_duration(d: Duration) -> String { let secs = d.as_secs(); if secs > HOUR_IN_SECS { ...
fn run_command(&self, cmd: &[&str]) { let pair = Arc::new((Mutex::new(false), Condvar::new())); let pair2 = pair.clone(); let start = self.start; let th = thread::spawn(move || { let (lock, cvar) = &*pair2; let mut done = false; while !done { ...
function_block-full_function
[ { "content": "pub fn parse_dur(s: &str) -> Result<Duration, &'static str> {\n\n let s = s.trim().to_lowercase();\n\n if let Ok(secs) = s.parse::<f32>() {\n\n return Ok(Duration::from_secs_f32(secs));\n\n } else if s.contains(\":\") {\n\n match split_as_ints(&s, 3).as_slice() {\n\n ...
Rust
src/scanner/result/mod.rs
xIris-Corp/arrow-client
06fdf899c4df207eb3e9ebc92a4a257e7ca2ef87
pub mod host; use std::collections::hash_map::Iter as HashMapIterator; use std::collections::HashMap; use std::net::{IpAddr, SocketAddr}; use crate::net::raw::ether::MacAddr; use crate::svc_table::{Service, ServiceIdentifier}; pub use self::host::HR_FLAG_ARP; pub use self::host::HR_FLAG_ICMP; pub use self::host::...
pub mod host; use std::collections::hash_map::Iter as HashMapIterator; use std::collections::HashMap; use std::net::{IpAddr, SocketAddr}; use crate::net::raw::ether::MacAddr; use crate::svc_table::{Service, ServiceIdentifier}; pub use self::host::HR_FLAG_ARP; pub use self::host::HR_FLAG_ICMP; pub use self::host::...
ator.next().map(|host| host.socket_addrs()); SocketAddrIterator { host_iterator, saddr_iterator, } } } impl<'a> Iterator for SocketAddrIterator<'a> { type Item = (MacAddr, SocketAddr); fn next(&mut self) -> Option<(MacAddr, SocketAddr)> { while self.saddr_i...
Identifier, HostRecord>, services: HashMap<ServiceIdentifier, Service>, } impl ScanResult { pub fn new() -> Self { Self::default() } pub fn add_host(&mut self, mac: MacAddr, ip: IpAddr, flags: u8) { let key = (mac, ip); if let Some(host) = self.hosts.get_mut(&key) { ...
random
[ { "content": "/// Helper trait for getting Any reference to an object.\n\npub trait AsAny {\n\n /// Get Any reference to this object.\n\n fn as_any(&self) -> &dyn Any;\n\n\n\n /// Get mutable Any reference to this object.\n\n fn as_any_mut(&mut self) -> &mut dyn Any;\n\n}\n\n\n\nimpl<T: Any + 'stati...
Rust
common/src/configuration/network.rs
AaronFeickert/tari
5e55bf22110ac40ffc0dea88d88ba836982591eb
use std::{ convert::TryFrom, fmt, fmt::{Display, Formatter}, str::FromStr, }; use serde::{Deserialize, Serialize}; use crate::ConfigurationError; #[repr(u8)] #[derive(Clone, Debug, PartialEq, Eq, Copy, Serialize, Deserialize)] #[serde(try_from = "String", into = "String")] pub enum Network { Ma...
use std::{ convert::TryFrom, fmt, fmt::{Display, Formatter}, str::FromStr, }; use serde::{Deserialize, Serialize}; use crate::ConfigurationError; #[repr(u8)] #[derive(Clone, Debug, PartialEq, Eq, Copy, Serialize, Deserialize)] #[serde(try_from = "String", into = "String")] pub enum Network { Ma...
#[test] fn network_default() { let network = Network::default(); assert_eq!(network, Network::MainNet); } #[test] fn network_from_str() { let mainnet_str = "mainnet"; let localnet_str = "localnet"; let ridcully_str = "ridcully"; let stibbons_str = "...
fn network_bytes() { let mainnet = Network::MainNet; let localnet = Network::LocalNet; let ridcully = Network::Ridcully; let stibbons = Network::Stibbons; let weatherwas = Network::Weatherwax; let igor = Network::Igor; let dibbler = Network::Dibbler; ...
function_block-full_function
[ { "content": "pub fn get_path(name: Option<&str>) -> String {\n\n let mut path = PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n path.push(\"tests/data\");\n\n path.push(name.unwrap_or(\"\"));\n\n path.to_str().unwrap().to_string()\n\n}\n\n\n", "file_path": "base_layer/wallet/tests/support/data...
Rust
language/diem-framework/src/lib.rs
yuxiamit/diem
49f024a270876f8fa23c8561f6b0c4207f12d602
#![forbid(unsafe_code)] use bytecode_verifier::{cyclic_dependencies, dependencies, verify_module}; use move_binary_format::{access::ModuleAccess, file_format::CompiledModule}; use move_lang::{compiled_unit::CompiledUnit, move_compile_and_report, shared::Flags}; use once_cell::sync::Lazy; use sha2::{Digest, Sha256}; ...
#![forbid(unsafe_code)] use bytecode_verifier::{cyclic_dependencies, dependencies, verify_module}; use move_binary_format::{access::ModuleAccess, file_format::CompiledModule}; use move_lang::{compiled_unit::CompiledUnit, move_compile_and_report, shared::Flags}; use once_cell::sync::Lazy; use sha2::{Digest, Sha256}; ...
{ return true; } } false }) .map(|path| path.into_os_string().into_string().unwrap()) .collect(); assert!( !res.is_empty(), "Unexpected: no stdlib bytecode files found" ); res } pub(crate) fn ...
string().into_string()) .collect() } pub fn diem_stdlib_files() -> Vec<String> { let mut files = move_stdlib::move_stdlib_files(); files.extend(diem_stdlib_files_no_dependencies()); files } pub fn stdlib_bytecode_files() -> Vec<String> { let path = path_in_crate(COMPILED_OUTPUT_PATH); let ...
random
[ { "content": "/// Generate the text for the \"interface\" file of a compiled module. This \"interface\" is the\n\n/// publically visible contents of the CompiledModule, represented in source language syntax\n\n/// Additionally, it returns the module id (address+name) of the module that was deserialized\n\npub f...
Rust
nocargo/src/init.rs
oxalica/nocargo
51172857f4c2d5ae9fd2ffe4bb8293e49decbbc2
use std::collections::BTreeSet; use std::io::Write; use std::path::{Path, PathBuf}; use anyhow::{bail, ensure, Context, Result}; use askama::Template; use cargo_toml::{Dependency, Manifest}; use once_cell::sync::Lazy; use regex::Regex; use structopt::StructOpt; use crate::App; #[derive(StructOpt)] pub struct Opt { ...
use std::collections::BTreeSet; use std::io::Write; use std::path::{Path, PathBuf}; use anyhow::{bail, ensure, Context, Result}; use askama::Template; use cargo_toml::{Dependency, Manifest}; use once_cell::sync::Lazy; use regex::Regex; use structopt::StructOpt; use crate::App; #[derive(StructOpt)] pub struct Opt { ...
}
3"); assert_eq!(f("git+https://github.com/foo/bar.git", "ref", Some("123")).unwrap(), "github:foo/bar/123"); }
function_block-function_prefixed
[ { "content": "pub fn foo() -> i32 {\n\n 42\n\n}\n", "file_path": "tests/dep-source-kinds/local/src/lib.rs", "rank": 2, "score": 106470.4848680578 }, { "content": "pub fn hello() {\n\n assert!(semver::VersionReq::parse(\">=1.2.3, <1.8.0\")\n\n .unwrap()\n\n .matches(&semve...
Rust
leftwm-core/src/handlers/window_handler.rs
clay53/leftwm
bc5d7df6ae27ea398b9395f2909b8ee132c031b8
use super::{Manager, Window, WindowChange, WindowType, Workspace}; use crate::child_process::exec_shell; use crate::config::{Config, ScratchPad}; use crate::display_action::DisplayAction; use crate::display_servers::DisplayServer; use crate::layouts::Layout; use crate::models::{Size, WindowHandle, WindowState, Xyhw, Xy...
use super::{Manager, Window, WindowChange, WindowType, Workspace}; use crate::child_process::exec_shell; use crate::config::{Config, ScratchPad}; use crate::display_action::DisplayAction; use crate::display_servers::DisplayServer; use crate::layouts::Layout; use crate::models::{Size, WindowHandle, WindowState, Xyhw, Xy...
fn is_scratchpad(state: &State, window: &Window) -> bool { state .active_scratchpads .iter() .any(|(_, &id)| window.pid == id) } fn find_terminal(state: &State, pid: Option<u32>) -> Option<&Window> { let shell_path = env::var("SHELL").ok()?; let shell = shell_path.split(...
ating(true); window.normal = ws.xyhw; let xyhw = window.requested.map_or_else( || ws.center_halfed(), |mut requested| { requested.center_relative(outer, window.border); if ws.xyhw.contains_xyhw(&requested) { requested } else { w...
function_block-function_prefixed
[ { "content": "fn focus_workspace_change(state: &mut State, val: i32) -> Option<bool> {\n\n let current = state.focus_manager.workspace(&state.workspaces)?;\n\n let workspace = helpers::relative_find(&state.workspaces, |w| w == current, val, true)?.clone();\n\n\n\n if state.focus_manager.behaviour.is_sl...
Rust
src/wire_msg.rs
madadam/sn_messaging
a9c94795fdaa4a1bd8dfab84bc3ecee9bb096c02
use super::{Error, MsgEnvelope, Result}; use bytes::Bytes; use cookie_factory::{bytes::be_u16, combinator::slice, gen}; use std::{fmt::Debug, mem::size_of}; const MESSAGING_PROTO_VERSION: u16 = 1u16; #[derive(Debug)] pub(crate) struct WireMsg { header: WireMsgHeader, payload: Bytes, } impl WireMsg { ...
use super::{Error, MsgEnvelope, Result}; use bytes::Bytes; use cookie_factory::{bytes::be_u16, combinator::slice, gen}; use std::{fmt::Debug, mem::size_of}; const MESSAGING_PROTO_VERSION: u16 = 1u16; #[derive(Debug)] pub(crate) struct WireMsg { header: WireMsgHeader, payload: Bytes, } impl WireMsg { ...
)) })?; let (_, _) = gen(slice(self.payload.clone()), &mut buf_at_payload[..]).map_err(|err| { Error::Serialization(format!("message payload couldn't be serialized: {}", err)) })?; Ok(Bytes::from(buffer)) } pub fn serialize_m...
"Could not serialize message payload (id: {}) with Msgpack: {}", msg.id(), err )) })?; Ok(Self { header: WireMsgHeader::new(), payload: Bytes::from(payload_vec), }) } pub fn from(bytes: Bytes) -> Result<Self>...
random
[ { "content": " | Self::NodeQuery { id, .. }\n\n | Self::NodeCmdError { id, .. }\n\n | Self::NodeQueryResponse { id, .. } => *id,\n\n }\n\n }\n\n\n\n /// Serialize this Message, ready for signing\n\n pub fn serialize(&self) -> Result<Bytes> {\n\n let payloa...
Rust
src/github/mod.rs
dustlang/rust-repos
dd7b21ceed9b4b8d13084085a87769c9fd65292f
mod api; use config::Config; use crossbeam_utils::thread::scope; use data::{Data, Repo}; use github::api::GitHubApi; use prelude::*; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use utils::wrap_thread; static WANTED_LANG: &str = "Rust"; fn load_thread(api: &GitHubApi, data: &D...
mod api; use config::Config; use crossbeam_utils::thread::scope; use data::{Data, Repo}; use github::api::GitHubApi; use prelude::*; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use utils::wrap_thread; static WANTED_LANG: &str = "Rust"; fn load_thread(api: &GitHubApi, data: &D...
t); for repo in repos.drain(..) { if let Some(repo) = repo { last_id = repo.id; if repo.fork { continue; } to_load.push(repo.node_id); if to_load.len() == 100 { ...
function_block-function_prefixed
[ { "content": "pub fn wrap_thread<F: FnOnce() -> Fallible<()>>(f: F) {\n\n if let Err(err) = f() {\n\n log_error(&err);\n\n }\n\n}\n", "file_path": "src/utils.rs", "rank": 2, "score": 61173.5823368188 }, { "content": "pub fn log_error(err: &Error) {\n\n error!(\"{}\", err);\n\...
Rust
kernel/src/ipc.rs
DieracDelta/tockfork
c266c02e62b473de3cf2353d19cc0924154c68e4
pub const DRIVER_NUM: usize = 0x00010000; use callback::{AppId, Callback}; use capabilities::MemoryAllocationCapability; use driver::Driver; use grant::Grant; use mem::{AppSlice, Shared}; use process; use returncode::ReturnCode; use sched::Kernel; struct IPCData { shared_memory: [Option<AppSlice<Shared, u8>>; 8...
pub const DRIVER_NUM: usize = 0x00010000; use callback::{AppId, Callback}; use capabilities::MemoryAllocationCapability; use driver::Driver; use grant::Grant; use mem::{AppSlice, Shared}; use process; use returncode::ReturnCode; use sched::Kernel; struct IPCData { shared_memory: [Option<AppSlice<Shared, u8>>; 8...
rget_id - 1, |target| { let ret = target.enqueue_task(process::Task::IPC((appid, cb_type))); match ret { true => ReturnCode::SUCCESS, false => ReturnCode::FAIL, } }) } ...
ize, _: usize, appid: AppId, ) -> ReturnCode { let cb_type = if client_or_svc == 0 { process::IPCType::Service } else { process::IPCType::Client }; self.data .kernel .process_map_or(ReturnCode::EINVAL, ta
function_block-random_span
[ { "content": "pub fn u16_to_slice(short: u16, slice: &mut [u8]) {\n\n slice[0] = (short >> 8) as u8;\n\n slice[1] = (short & 0xff) as u8;\n\n}\n", "file_path": "capsules/src/net/util.rs", "rank": 1, "score": 272554.0753385781 }, { "content": "/// Helper function to load processes from ...
Rust
crates/nu-cli/src/commands/histogram.rs
jankoprowski/nushell
e5a79d09dfd6da3af4d1ce962c15d327d460c6af
use crate::commands::group_by::group; use crate::commands::WholeStreamCommand; use crate::prelude::*; use crate::utils::data_processing::{columns_sorted, evaluate, map_max, reduce, t_sort}; use nu_errors::ShellError; use nu_protocol::{ Primitive, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedVal...
use crate::commands::group_by::group; use crate::commands::WholeStreamCommand; use crate::prelude::*; use crate::utils::data_processing::{columns_sorted, evaluate, map_max, reduce, t_sort}; use nu_errors::ShellError; use nu_protocol::{ Primitive, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedVal...
fn usage(&self) -> &str { "Creates a new table with a histogram based on the column name passed in." } fn run( &self, args: CommandArgs, registry: &CommandRegistry, ) -> Result<OutputStream, ShellError> { args.process(registry, histogram)?.run() } } pub fn...
lumn_name", SyntaxShape::String, "the name of the column to graph by", ) .rest( SyntaxShape::String, "column name to give the histogram's frequency column", ) }
function_block-function_prefixed
[ { "content": "pub fn style_leaf<'a>(value: impl Into<&'a UntaggedValue>) -> &'static str {\n\n match value.into() {\n\n UntaggedValue::Primitive(p) => style_primitive(p),\n\n _ => \"\",\n\n }\n\n}\n\n\n", "file_path": "crates/nu-cli/src/data/value.rs", "rank": 0, "score": 342467....
Rust
hotham/src/app.rs
leetvr/hotham
90502acdb346fbe8ff84be343fd793575ef98005
use crate::{resources::XrContext, HothamResult}; use legion::{Resources, Schedule, World}; use openxr as xr; use std::{ sync::{ atomic::{AtomicBool, Ordering}, Arc, }, thread::sleep, time::Duration, }; use xr::SessionState; #[cfg(target_os = "android")] pub const ANDROID_LOOPER_ID_MAI...
use crate::{resources::XrContext, HothamResult}; use legion::{Resources, Schedule, World}; use openxr as xr; use std::{ sync::{ atomic::{AtomicBool, Ordering}, Arc, }, thread::sleep, time::Duration, }; use xr::SessionState; #[cfg(target_os = "android")] pub const ANDROID_LOOPER_ID_MAI...
unreachable!( "Unrecognised looper identifier: {:?} but LOOPER_ID_INPUT is {:?}", ident, ANDROID_LOOPER_ID_INPUT ); } } _ => None, } } }
); } } } None } else {
function_block-random_span
[ { "content": "pub fn sync_debug_server(world: &mut World, resources: &mut Resources) {\n\n let mut debug_server = resources.get_mut::<DebugServer>().unwrap();\n\n let physics_context = resources.get::<PhysicsContext>().unwrap();\n\n let debug_data = world_to_debug_data(\n\n &world,\n\n &p...
Rust
src/capnp/message.rs
kinghajj/capnproto-rust
91b6aaff49a0633bb42497b28bc954591e861451
/* * Copyright (c) 2013-2014, David Renshaw (dwrenshaw@gmail.com) * * See the LICENSE file in the capnproto-rust root directory. */ use std; use std::vec::Vec; use any_pointer; use capability::ClientHook; use common::*; use arena::{BuilderArena, ReaderArena, SegmentBuilder, SegmentReader, NumWords, ZeroedWords}; u...
/* * Copyright (c) 2013-2014, David Renshaw (dwrenshaw@gmail.com) * * See the LICENSE file in the capnproto-rust root directory. */ use std; use std::vec::Vec; use any_pointer; use capability::ClientHook; use common::*; use arena::{BuilderArena, ReaderArena, SegmentBuilder, SegmentReader, NumWords, ZeroedWords}; u...
} fn init_root<'a, T : FromPointerBuilder<'a>>(&'a mut self) -> T { self.get_root_internal().init_as() } fn get_root<'a, T : FromPointerBuilder<'a>>(&'a mut self) -> T { self.get_root_internal().get_as() } fn set_root<To, From : SetPointerBuilder<To>>(&mut self, value : From...
if self.arena().segment0.current_size() == 0 { match self.mut_arena().segment0.allocate(WORDS_PER_POINTER as u32) { None => {panic!("could not allocate root pointer") } Some(location) => { assert!(location == self.arena().segment0.get_ptr_unchecked(0), ...
if_condition
[ { "content": "#[inline]\n\npub fn allocate_zeroed_words(size : WordCount) -> ::std::vec::Vec<Word> {\n\n\n\n// Do this, but faster:\n\n// return ::std::vec::Vec::from_elem(size, 0);\n\n\n\n let mut result : ::std::vec::Vec<Word> = ::std::vec::Vec::with_capacity(size);\n\n unsafe {\n\n result....
Rust
lapce-ui/src/editor/tab_header.rs
dakata1337/lapce
48456fcc74ee568990c1726226ac5a12297e394e
use std::time::Duration; use druid::{ kurbo::Line, piet::{Text, TextAttribute, TextLayout, TextLayoutBuilder}, BoxConstraints, Command, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx, MouseEvent, PaintCtx, Point, RenderContext, Size, Target, TimerToken, UpdateCtx, Widget, WidgetId, Widget...
use std::time::Duration; use druid::{ kurbo::Line, piet::{Text, TextAttribute, TextLayout, TextLayoutBuilder}, BoxConstraints, Command, Env, Event, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx, MouseEvent, PaintCtx, Point, RenderContext, Size, Target, TimerToken, UpdateCtx, Widget, WidgetId, Widget...
text} (Working tree)"); } } EditorTabChild::Settings(_, _) => { text = "Settings".to_string(); hint = format!("v{}", VERSION); } } let font_size = data.config.ui.font_size() as f64; let size = ctx.size(); ...
n self.icons.iter() { if icon.rect.contains(mouse_event.pos) { ctx.submit_command(icon.command.clone()); } } } fn ensure_active_visible<F>( &mut self, data: &LapceTabData, request_timer: F, env: &Env, ) where F: FnOnce(...
random
[]
Rust
examples/dust/src/light.rs
jimy-byerley/tri-mesh
10bef23b44321bb33365d248a748a922c99a79d2
use crate::core::rendertarget::{self, DepthRenderTarget}; use gl; use crate::camera::{self, Camera}; use crate::*; #[derive(Debug)] pub enum Error { Rendertarget(rendertarget::Error), ShadowRendertargetNotAvailable {message: String} } impl From<rendertarget::Error> for Error { fn from(other: rendertarget:...
use crate::core::rendertarget::{self, DepthRenderTarget}; use gl; use crate::camera::{self, Camera}; use crate::*; #[derive(Debug)] pub enum Error { Rendertarget(rendertarget::Error), ShadowRendertargetNotAvailable {message: String} } impl From<rendertarget::Error> for Error { fn from(other: rendertarget:...
} fn compute_up_direction(&self) -> Vec3 { if vec3(1.0, 0.0, 0.0).dot(self.direction).abs() > 0.9 { (vec3(0.0, 1.0, 0.0).cross(self.direction)).normalize() } else { (vec3(1.0, 0.0, 0.0).cross(self.direction)).normalize() } } pub fn s...
if let Some(ref mut camera) = self.shadow_camera { camera.set_view(*target - self.direction, *target, up); }
if_condition
[ { "content": "pub fn vec3(x: f32, y: f32, z: f32) -> Vec3\n\n{\n\n Vector3::new(x, y, z)\n\n}\n\n\n", "file_path": "examples/dust/src/types.rs", "rank": 0, "score": 219686.50091867766 }, { "content": "// COMMON FUNCTIONS\n\nfn generate(gl: &gl::Gl) -> Result<gl::Texture, Error>\n\n{\n\n ...
Rust
src/main.rs
sagebind/sqs-pull
d41d780e22adf9f9c0dff9de06001a416583de66
use indicatif::ProgressBar; use regex::Regex; use rusoto_core::Region; use rusoto_sqs::{ DeleteMessageBatchRequest, DeleteMessageBatchRequestEntry, GetQueueAttributesRequest, GetQueueUrlRequest, ReceiveMessageRequest, SendMessageBatchRequest, SendMessageBatchRequestEntry, Sqs, SqsCli...
use indicatif::ProgressBar; use regex::Regex; use rusoto_core::Region; use rusoto_sqs::{ DeleteMessageBatchRequest, DeleteMessageBatchRequestEntry, GetQueueAttributesRequest, GetQueueUrlRequest, ReceiveMessageRequest, SendMessageBatchRequest, SendMessageBatchRequestEntry, Sqs, SqsCli...
wait_time_seconds: Some(0), }).await?; let messages = if let Some(messages) = receive_result.messages { messages } else { return Ok(()); }; if messages.is_empty() { return Ok(()); } let mut messages_to_move = Vec::new(); ...
function_block-function_prefix_line
[ { "content": "# sqs-pull\n\n\n\nMoves SQS messages from one queue to another really fast, and also allows you to filter which messages to move based on regular expressions. Currently a bit rough around the edges.\n\n\n\n## Installation\n\n\n\nBinaries are available on the [Releases](https://github.com/sagebind/...
Rust
third_party/rust_crates/vendor/gpt/src/mbr.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use crate::disk; use crate::DiskDevice; use std::io::{Read, Write}; use std::{fmt, io}; pub struct ProtectiveMBR { bootcode: [u8; 440], disk_signature: [u8; 4], unknown: u16, partitions: [PartRecord; 4], signature: [u8; 2], } impl fmt::Debug for ProtectiveMBR { fn fmt(&self, f: &mut fmt::For...
use crate::disk; use crate::DiskDevice; use std::io::{Read, Write}; use std::{fmt, io}; pub struct ProtectiveMBR { bootcode: [u8; 440], disk_signature: [u8; 4], unknown: u16, partitions: [PartRecord; 4], signature: [u8; 2], } impl fmt::Debug for ProtectiveMBR { fn fmt(&self, f: &mut fmt::For...
pub fn from_disk<D: DiskDevice>( device: &mut D, sector_size: disk::LogicalBlockSize ) -> io::Result<Self> { let totlen: u64 = sector_size.into(); let mut buf = vec![0u8; totlen as usize]; let cur = device.seek(io::SeekFrom::Current(0))?; device.seek(io::S...
t", ) })? .checked_add(446) .ok_or_else(|| { io::Error::new(io::ErrorKind::Other, "partition overflow - start offset") })?; let end = start.checked_add(16).ok_or_else(|| { io::Error::new( ...
function_block-function_prefixed
[]
Rust
src/resource.rs
WillzZz/legion
23a0b29c0ddefa05dcde39fc0ce73629fa0abf40
use crate::borrow::{AtomicRefCell, Exclusive, Ref, RefMut, Shared}; use crate::query::{Read, Write}; use std::{ any::TypeId, collections::HashMap, marker::PhantomData, ops::{Deref, DerefMut}, }; use downcast_rs::{impl_downcast, Downcast}; #[cfg(not(feature = "ffi"))] #[derive(Copy, Clone, Debug, Eq, ...
use crate::borrow::{AtomicRefCell, Exclusive, Ref, RefMut, Shared}; use crate::query::{Read, Write}; use std::{ any::TypeId, collections::HashMap, marker::PhantomData, ops::{Deref, DerefMut}, }; use downcast_rs::{impl_downcast, Downcast}; #[cfg(not(feature = "ffi"))] #[derive(Copy, Clone, Debug, Eq, ...
) -> Option<FetchMut<'_, T>> { self.get_mut_or_insert((f)()) } pub fn get_or_insert<T: Resource>(&mut self, value: T) -> Option<Fetch<'_, T>> { Some(Fetch { inner: self .storage .entry(ResourceTypeId::of::<T>()) .or_insert_...
} } } unsafe impl<T: Resource> Send for PreparedWrite<T> {} unsafe impl<T: Resource> Sync for PreparedWrite<T> {} pub struct Fetch<'a, T: 'a + Resource> { inner: Ref<'a, Shared<'a>, Box<dyn Resource>>, _marker: PhantomData<T>, } impl<'a, T: Resource> Deref for Fetch<'a, T> { type Target = T; #[inline]...
random
[ { "content": "/// A `Tag` is shared data that can be attached to multiple entities at once.\n\npub trait Tag: Clone + Send + Sync + PartialEq + 'static {}\n\n\n\nimpl<T: Send + Sync + 'static> Component for T {}\n\nimpl<T: Clone + Send + Sync + PartialEq + 'static> Tag for T {}\n\n\n\n/// Stores slices of `Comp...
Rust
rafx-plugins/src/pipelines/modern/graph_generator/ssao_pass.rs
aclysma/renderer_prototype
a274b82c873c0ec7f9d6c3376cd054bfccfe3895
use crate::pipelines::modern::graph_generator::ModernPipelineContext; use crate::shaders::ssao::ssao_frag; use rafx::api::{RafxFormat, RafxSampleCount}; use rafx::framework::{ImageViewResource, MaterialPassResource, ResourceArc}; use rafx::graph::{RenderGraphImageConstraint, RenderGraphImageUsageId, RenderGraphQueue}; ...
use crate::pipelines::modern::graph_generator::ModernPipelineContext; use crate::shaders::ssao::ssao_frag; use rafx::api::{RafxFormat, RafxSampleCount}; use rafx::framework::{ImageViewResource, MaterialPassResource, ResourceArc}; use rafx::graph::{RenderGraphImageConstraint, RenderGraphImageUsageId, RenderGraphQueue}; ...
pub(super) fn ssao_pass( context: &mut ModernPipelineContext, ssao_material_pass: &ResourceArc<MaterialPassResource>, depth_rt: RenderGraphImageUsageId, noise_texture: &ResourceArc<ImageViewResource>, ) -> SsaoPass { let node = context .graph .add_node("SsaoPass", RenderGraphQueue::D...
function_block-full_function
[ { "content": "fn random_color(rng: &mut impl Rng) -> Vec3 {\n\n let r = rng.gen_range(0.2..1.0);\n\n let g = rng.gen_range(0.2..1.0);\n\n let b = rng.gen_range(0.2..1.0);\n\n let v = Vec3::new(r, g, b);\n\n v.normalize()\n\n}\n\n\n", "file_path": "demo/src/scenes/mod.rs", "rank": 0, "...
Rust
tonic/src/transport/service/reconnect.rs
imotai/tonic
91b73f9fc3c1bc281e85177808721b3efe37ece0
use crate::Error; use pin_project::pin_project; use std::fmt; use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use tower::make::MakeService; use tower_service::Service; use tracing::trace; pub(crate) struct Reconnect<M, Target> where M: Service<Target>, M::Error: Into<Error>, { mk...
use crate::Error; use pin_project::pin_project; use std::fmt; use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use tower::make::MakeService; use tower_service::Service; use tracing::trace; pub(crate) struct Reconnect<M, Target> where M: Service<Target>, M::Error: Into<Error>, { mk...
}
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let me = self.project(); match me.inner.project() { InnerProj::Future(fut) => fut.poll(cx).map_err(Into::into), InnerProj::Error(e) => { let e = e.take().expect("Polled after read...
function_block-full_function
[ { "content": "type BoxFuture<T, E> = Pin<Box<dyn Future<Output = std::result::Result<T, E>> + Send + 'static>>;\n\n\n\n#[tonic::async_trait]\n\nimpl pb::test_service_server::TestService for TestService {\n\n async fn empty_call(&self, _request: Request<Empty>) -> Result<Empty> {\n\n Ok(Response::new(E...
Rust
gio/src/pollable_output_stream.rs
jf2048/gtk-rs-core
02de84c94e50145604a9187fdfa1460a155bb723
use crate::error::to_std_io_result; use crate::prelude::*; use crate::Cancellable; use crate::PollableOutputStream; use futures_channel::oneshot; use futures_core::task::{Context, Poll}; use futures_core::Future; use futures_io::AsyncWrite; use glib::object::{Cast, IsA}; use glib::translate::*; use std::cell::RefCell...
use crate::error::to_std_io_result; use crate::prelude::*; use crate::Cancellable; use crate::PollableOutputStream; use futures_channel::oneshot; use futures_core::task::{Context, Poll}; use futures_core::Future; use futures_io::AsyncWrite; use glib::object::{Cast, IsA}; use glib::translate::*; use std::cell::RefCell...
)(PollableOutputStream::from_glib_borrow(stream).unsafe_cast_ref()).into_glib() } unsafe extern "C" fn destroy_closure<O, F>(ptr: glib::ffi::gpointer) { Box::<RefCell<F>>::from_raw(ptr as *mut _); } let cancellable = cancellable.map(|c| c.as_ref()); let gcancellable =...
lf, cancellable: Option<&C>, name: Option<&str>, priority: glib::Priority, func: F, ) -> glib::Source where F: FnMut(&Self) -> glib::Continue + 'static, C: IsA<Cancellable>; fn create_source_future<C: IsA<Cancellable>>( &self, cancellable: Opt...
random
[ { "content": "// rustdoc-stripper-ignore-next\n\n/// A trait for creating an uninitialized value. Handy for receiving outparams.\n\npub trait Uninitialized {\n\n // Returns an uninitialized value.\n\n unsafe fn uninitialized() -> Self;\n\n}\n\n\n\n// rustdoc-stripper-ignore-next\n\n/// Returns an uninitia...
Rust
src/completion/default.rs
nushell/reedline
13ff774bcca79409282ad6a7b6e0cf1d5dedb85d
use crate::{Completer, Span, Suggestion}; use std::{ collections::{BTreeMap, BTreeSet}, str::Chars, sync::Arc, }; #[derive(Debug, Clone)] pub struct DefaultCompleter { root: CompletionNode, min_word_len: usize, } impl Default for DefaultCompleter { fn default() -> Self { let inclusions...
use crate::{Completer, Span, Suggestion}; use std::{ collections::{BTreeMap, BTreeSet}, str::Chars, sync::Arc, }; #[derive(Debug, Clone)] pub struct DefaultCompleter { root: CompletionNode, min_word_len: usize, } impl Default for DefaultCompleter { fn default() -> Self { let inclusions...
fn collect(&self, partial: &str) -> Vec<String> { let mut completions = vec![]; if self.leaf { completions.push(partial.to_string()); } if !self.subnodes.is_empty() { for (c, node) in &self.subnodes { let mut partial = partial.to_string(); ...
fn complete(&self, mut iter: Chars) -> Option<Vec<String>> { if let Some(c) = iter.next() { if let Some(subnode) = self.subnodes.get(&c) { subnode.complete(iter) } else { None } } else { Some(self.collect("")) } ...
function_block-full_function
[ { "content": "fn incomplete_brackets(line: &str) -> bool {\n\n let mut balance: Vec<char> = Vec::new();\n\n\n\n for c in line.chars() {\n\n if c == '{' {\n\n balance.push('}');\n\n } else if c == '[' {\n\n balance.push(']');\n\n } else if c == '(' {\n\n ...
Rust
src/rust/vendor/universal-hash/src/lib.rs
thisconnect/bitbox02-firmware
e081ac18dc28c2bdffdc58a94afa36a1bb5bade2
#![no_std] #![forbid(unsafe_code)] #![doc(html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")] #![warn(missing_docs, rust_2018_idioms)] #[cfg(feature = "std")] extern crate std; pub use generic_array::{self, typenum::consts}; use generic_array::typenum::Unsigned; use generic_...
#![no_std] #![forbid(unsafe_code)] #![doc(html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")] #![warn(missing_docs, rust_2018_idioms)] #[cfg(feature = "std")] extern crate std; pub use generic_array::{self, typenum::consts}; use generic_array::typenum::Unsigned; use generic_...
fn reset(&mut self); fn finalize(self) -> Output<Self>; fn finalize_reset(&mut self) -> Output<Self> { let res = self.clone().finalize(); self.reset(); res } fn verify(self, other: &Block<Self>) -> Result<(), Error> { if self.fi...
fn update_padded(&mut self, data: &[u8]) { let mut chunks = data.chunks_exact(Self::BlockSize::to_usize()); for chunk in &mut chunks { self.update(GenericArray::from_slice(chunk)); } let rem = chunks.remainder(); if !rem.is_empty() { let mut padded_bloc...
function_block-full_function
[ { "content": "#[cfg(feature = \"testing\")]\n\npub fn encode_xpub_at_keypath(keypath: &[u32], xpub_type: xpub_type_t) -> Result<String, ()> {\n\n let data = crate::testing::DATA.0.borrow();\n\n data.keystore_encode_xpub_at_keypath.as_ref().unwrap()(keypath, xpub_type)\n\n}\n\n\n\npub struct SignResult {\n...
Rust
nalgebra-lapack/src/eigen.rs
msmorgan/nalgebra
c1eaac2fae30d7269e693b1dacab93af4d5a6248
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num::Zero; use num_complex::Complex; use simba::scalar::RealField; use crate::ComplexHelper; use na::allocator::Allocator; use na::dimension::{Dim, U1}; use na::storage::Storage; use na::{DefaultAllocator, Matrix, MatrixN, Scalar, VectorN};...
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num::Zero; use num_complex::Complex; use simba::scalar::RealField; use crate::ComplexHelper; use na::allocator::Allocator; use na::dimension::{Dim, U1}; use na::storage::Storage; use na::{DefaultAllocator, Matrix, MatrixN, Scalar, VectorN};...
pub fn complex_eigenvalues(mut m: MatrixN<N, D>) -> VectorN<Complex<N>, D> where DefaultAllocator: Allocator<Complex<N>, D>, { assert!( m.is_square(), "Unable to compute the eigenvalue decomposition of a non-square matrix." ); let nro...
k!(info); let mut work = unsafe { crate::uninitialized_vec(lwork as usize) }; match (left_eigenvectors, eigenvectors) { (true, true) => { let mut vl = unsafe { Matrix::new_uninitialized_generic(nrows, ncols) }; let mut vr = unsafe { Matrix::new_uninitialized...
function_block-function_prefixed
[ { "content": "/// Computes in-place `D * m * D.inverse()`, where `D` is the matrix with diagonal `d`.\n\npub fn unbalance<N: RealField, D: Dim>(m: &mut MatrixN<N, D>, d: &VectorN<N, D>)\n\nwhere\n\n DefaultAllocator: Allocator<N, D, D> + Allocator<N, D>,\n\n{\n\n assert!(m.is_square(), \"Unable to unbalan...
Rust
signature/signature_derive/src/lib.rs
garbageslam/traits
4255865505d32e3de58686808c4c969765da8dbe
#![crate_type = "proc-macro"] #![recursion_limit = "128"] #![deny(warnings, unused_import_braces, unused_qualifications)] #![forbid(unsafe_code)] extern crate proc_macro; use proc_macro2::TokenStream; use quote::quote; use synstructure::{decl_derive, AddBounds}; fn derive_signer(mut s: synstructure::Structure) -> ...
#![crate_type = "proc-macro"] #![recursion_limit = "128"] #![deny(warnings, unused_import_braces, unused_qualifications)] #![forbid(unsafe_code)] extern crate proc_macro; use proc_macro2::TokenStream; use quote::quote; use synstructure::{decl_derive, AddBounds}; fn derive_signer(mut s: synstructure::Structure) -> ...
decl_derive! { [Verifier] => derive_verifier } #[cfg(test)] mod tests { use super::*; use synstructure::test_derive; #[test] fn signer() { test_derive! { derive_signer { struct MySigner<C: El...
s(AddBounds::None); s.gen_impl(quote! { gen impl<S> signature::Verifier<S> for @Self where S: signature::DigestSignature, Self: signature::DigestVerifier<S::Digest, S> { fn verify(&self, msg: &[u8], signature: &S) -> Result<(), signature::Error> { ...
function_block-function_prefixed
[ { "content": "pub fn xof_test<D>(input: &[u8], output: &[u8]) -> Option<&'static str>\n\nwhere\n\n D: Input + ExtendableOutput + Default + Debug + Reset + Clone,\n\n{\n\n let mut hasher = D::default();\n\n let mut buf = [0u8; 1024];\n\n // Test that it works when accepting the message all at once\n\...
Rust
minidsp/src/transport/net/codec.rs
jpattWPC/minidsp-rs
d10961cb47ee3ca26d0407480c9f5596d529165b
use std::io; use anyhow::Result; use bytes::{Buf, Bytes}; use tokio_util::codec::{Decoder, Encoder}; #[derive(Copy, Clone)] pub struct Codec { server: bool, received_small_packet: bool, } impl Codec { pub fn new_server() -> Self { Codec { server: true, rec...
use std::io; use anyhow::Result; use bytes::{Buf, Bytes}; use tokio_util::codec::{Decoder, Encoder}; #[derive(Copy, Clone)] pub struct Codec { server: bool, received_small_packet: bool, } impl Codec { pub fn new_server() -> Self { Codec { server: true, rec...
let mut codec = Codec::new_client(); let decoded = codec.decode(&mut packet).unwrap().unwrap(); assert_eq!(hex::encode(decoded), "0531010c0a"); let decoded = codec.decode(&mut packet).unwrap().unwrap(); assert_eq!(hex::encode(decoded), "0505ffa164"); let decoded = co...
let mut packet: BytesMut = parts .iter() .flat_map(|s| hex::decode(s).unwrap().into_iter()) .collect();
assignment_statement
[ { "content": "/// Replaces the Content-Type for all responses with `content_type`.\n\npub fn set_content_type(responses: &mut Responses, content_type: impl ToString) -> Result<()> {\n\n for ref mut resp_refor in responses.responses.values_mut() {\n\n let response = ensure_not_ref(*resp_refor)?;\n\n ...
Rust
client/lib/src/process_event.rs
SEbbaDK/playform
5c8781ff137592c6c687b5d0c9fb55633850e3a2
use cgmath::{Vector2, Vector3}; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::mouse::MouseButton; use std::f32::consts::PI; use stopwatch; use common::entity; use common::protocol; use client; use view; #[allow(missing_docs)] pub fn process_event<UpdateServer>( update_server: &mut UpdateServer, ...
use cgmath::{Vector2, Vector3}; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::mouse::MouseButton; use std::f32::consts::PI; use stopwatch; use common::entity; use common::protocol; use client; use view; #[allow(missing_docs)] pub fn process_event<UpdateServer>( update_server: &mut UpdateServer, ...
fn mouse_press<UpdateServer>( player_id: entity::id::Player, update_server: &mut UpdateServer, mouse_btn: MouseButton, ) where UpdateServer: FnMut(protocol::ClientToServer) { stopwatch::time("event.mouse_press", || { match mouse_btn { MouseButton::Left => { update_server( protocol:...
fn key_press<UpdateServer>( update_server: &mut UpdateServer, view: &mut view::T, client: &client::T, key: Keycode, ) where UpdateServer: FnMut(protocol::ClientToServer) { use common::protocol::ClientToServer::*; let lr = |update_server: &mut UpdateServer, view: &mut view::T, k| { match view.input_mode...
function_block-full_function
[ { "content": "#[allow(missing_docs)]\n\npub fn apply_client_to_view(view: &mut view::T, up: T) {\n\n match up {\n\n T::MoveCamera(position) => {\n\n view.camera.translate_to(position);\n\n },\n\n T::UpdateMob(id, triangles) => {\n\n view.mob_buffers.insert(&mut view.gl, id, &triangles);\n\n ...
Rust
src/lib.rs
Max-astro/cyclomatic_complexity_calculator
f68cbe0a853f371f5384b717e198931bbfc2a060
use tree_sitter::{Node, Parser, Tree}; use tree_sitter_python; pub struct FunctionCC { cnt: usize, } impl FunctionCC { pub fn count_cc(func_root: Node) -> usize { let mut cc = FunctionCC { cnt: 1 }; cc.travers(func_root); cc.cnt } fn travers(&mut self, node: Node) { for...
use tree_sitter::{Node, Parser, Tree}; use tree_sitter_python; pub struct FunctionCC { cnt: usize, } impl FunctionCC { pub fn count_cc(func_root: Node) -> usize { let mut cc = FunctionCC { cnt: 1 }; cc.travers(func_root); cc.cnt } fn travers(&mut self, node: Node) { for...
pub fn process_files(path: &str) -> Self { let pool = ThreadPool::new(4); let (tx, rx) = channel(); for entry in WalkDir::new(path) .follow_links(true) .into_iter() .filter_map(|e| e.ok()) .filter(|e| e.path().extension().unwrap_or_default(...
fn single_file_cc(filepath: PathBuf) -> (String, CcResult) { let mut src = String::new(); let mut reader = BufReader::new(File::open(&filepath).unwrap()); let _ = reader.read_to_string(&mut src); let ast = AST::new(&src); let cc = ast.travers_ast(); let file_name = filep...
function_block-full_function
[ { "content": " class CC(metaclass=CMeta):\n", "file_path": "testcase/py_grammer.py", "rank": 8, "score": 50733.2843128042 }, { "content": "class GrammarTests(unittest.TestCase):\n\n\n\n check_syntax_error = check_syntax_error\n\n\n\n # single_input: NEWLINE | simple_stmt | compo...
Rust
src/install.rs
jkamb/bftracks-launcher
8121cd8f95d61336da39f00f782a68f01ef89e6d
use super::config; use anyhow::{anyhow, Result}; use std::ffi::OsStr; use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::slice; mod native { use winapi::shared::minwindef::DWORD; use winapi::shared::ntdef::{HANDLE, LONG, NTSTATUS, PULONG, PVOID, ULONG}; pub type FnNtQueryInformationProcess = ...
use super::config; use anyhow::{anyhow, Result}; use std::ffi::OsStr; use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::slice; mod native { use winapi::shared::minwindef::DWORD; use winapi::shared::ntdef::{HANDLE, LONG, NTSTATUS, PULONG, PVOID, ULONG}; pub type FnNtQueryInformationProcess = ...
key.set_value("", &format!("{} \"%1\"", launcher_path))?; /* Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\BFTracks] "UninstallString"="C:\\Users\\jkamb\\AppData\\Local\\BFTracks\\bftracks-launcher.exe" ...
match disp { REG_CREATED_NEW_KEY => { println!("A new key has been created, checking & fixing up parent"); let (key, _) = hklm.create_subkey("SOFTWARE\\Classes\\bftracks")?; key.set_value("", &"BFTracks launcher")?; key.set_value("URL Protocol"...
if_condition
[ { "content": "fn launch(config_file: &Path, server_address: &str) -> Result<()> {\n\n use config::Config;\n\n\n\n let config = fs::read_to_string(config_file.as_os_str())?;\n\n let config: Config = toml::from_str(&config)?;\n\n let game_path = Path::new(&config.game_path);\n\n let mut child = Com...
Rust
apollo-router/src/introspection.rs
apollographql/router
2be423c53933e0daa6d58e82fbc7aabeb1f97eb0
use crate::*; use include_dir::include_dir; use once_cell::sync::Lazy; use router_bridge::introspect::{self, IntrospectionError}; use std::collections::HashMap; static KNOWN_INTROSPECTION_QUERIES: Lazy<Vec<String>> = Lazy::new(|| { include_dir!("$CARGO_MANIFEST_DIR/well_known_introspection_queries") .files...
use crate::*; use include_dir::include_dir; use once_cell::sync::Lazy; use router_bridge::introspect::{self, IntrospectionError}; use std::collections::HashMap; static KNOWN_INTROSPECTION_QUERIES: Lazy<Vec<String>> = Lazy::new(|| { include_dir!("$CARGO_MANIFEST_DIR/well_known_introspection_queries") .files...
.pop() .ok_or_else(|| IntrospectionError { message: String::from("cannot find the introspection response").into(), })? .into_result() .map_err(|err| IntrospectionError { message: format!( "introspection error ...
r| IntrospectionError { message: format!("Deno runtime error: {:?}", err).into(), })??; let introspection_result = response
random
[ { "content": "/// This generate an arbitrary valid GraphQL operation\n\npub fn generate_valid_operation(input: &[u8], schema_path: &'static str) -> Result<String> {\n\n drop(env_logger::try_init());\n\n\n\n let parser = Parser::new(&fs::read_to_string(schema_path).expect(\"cannot read file\"));\n\n\n\n ...
Rust
src/testdrive/src/action/kafka/verify.rs
rjnn/materialize
e69b18a51a09401957a056d82e5fabf3c8921b79
use std::cmp; use std::str; use std::time::Duration; use async_trait::async_trait; use byteorder::{BigEndian, ByteOrder}; use ore::result::ResultExt; use rdkafka::consumer::{Consumer, StreamConsumer}; use rdkafka::message::Message; use tokio::pin; use tokio_stream::StreamExt; use crate::action::{Action, Context, St...
use std::cmp; use std::str; use std::time::Duration; use async_trait::async_trait; use byteorder::{BigEndian, ByteOrder}; use ore::result::ResultExt; use rdkafka::consumer::{Consumer, StreamConsumer}; use rdkafka::message::Message; use tokio::pin; use tokio_stream::StreamExt; use crate::action::{Action, Context, St...
fn avro_from_bytes( schema: &mz_avro::Schema, mut bytes: &[u8], ) -> Result<mz_avro::types::Value, String> { if bytes.len() < 5 { return Err(format!( "avro datum is too few bytes: expected at least 5 bytes, got {}", bytes.len() )); } let magic = bytes[0]; ...
pub fn build_verify(mut cmd: BuiltinCommand, context: Context) -> Result<VerifyAction, String> { let format = match cmd.args.string("format")?.as_str() { "avro" => SinkFormat::Avro, "json" => SinkFormat::Json { key: cmd.args.parse("key")?, }, f => return Err(format!("unkn...
function_block-full_function
[ { "content": "// This function is derived from code in the avro_rs project. Update the license\n\n// header on this file accordingly if you move it to a new home.\n\npub fn from_json(json: &JsonValue, schema: SchemaNode) -> Result<Value, String> {\n\n match (json, schema.inner) {\n\n (JsonValue::Null,...
Rust
src/gui/main_window/menu_callbacks.rs
rnleach/sonde
75ffdd1bbe8a675e7762a51c3b7817b68f1838b5
use crate::{ app::AppContextPointer, coords::DeviceRect, errors::*, gui::{plot_context::PlotContext, utility::DrawingArgs, Drawable}, }; use gtk::{ prelude::*, FileChooserAction, FileChooserDialog, FileFilter, MessageDialog, ResponseType, Widget, Window, }; use std::path::PathBuf; pub fn open_t...
use crate::{ app::AppContextPointer, coords::DeviceRect, errors::*, gui::{plot_context::PlotContext, utility::DrawingArgs, Drawable}, }; use gtk::{ prelude::*, FileChooserAction, FileChooserDialog, FileFilter, MessageDialog, ResponseType, Widget, Window, }; use std::path::PathBuf; pub fn open_t...
fn save_image(path: &PathBuf, ac: &AppContextPointer) -> Result<(), Box<dyn Error>> { let DeviceRect { width, height, .. } = ac.skew_t.get_device_rect(); let img = cairo::ImageSurface::create(cairo::Format::ARgb32, width as i32, height as i32) .map_err(SondeError::from)?; let cr = &cairo::Contex...
pub fn save_image_callback(ac: &AppContextPointer, win: &Window) { let dialog = FileChooserDialog::new(Some("Save Image"), Some(win), FileChooserAction::Save); dialog.add_buttons(&[("Save", ResponseType::Ok), ("Cancel", ResponseType::Cancel)]); let filter = FileFilter::new(); filter.add_pattern("*.png...
function_block-full_function
[ { "content": "pub fn load_multiple(paths: &[PathBuf], ac: &AppContextPointer) -> Result<(), Box<dyn Error>> {\n\n let datas: Result<Vec<_>, _> = paths.iter().map(load_file).collect();\n\n let mut datas: Vec<_> = datas?.into_iter().flatten().collect();\n\n\n\n // Sort by valid time ascending, then by le...
Rust
crates/tempfile/sgx-tests/enclave/src/tests/namedtempfile.rs
Zha0Chan/crates-sgx
73dc6d9e130757d9e585ee757b3d94d5078512a9
#![deny(rust_2018_idioms)] use std::env; use std::fs::File; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::Path; use tempfile::{Builder, NamedTempFile}; use std::string::ToString; use crates_unittest::test_case; use std::prelude::v1::*; fn exists<P: AsRef<Path>>(path: P) -> bool { std::fs::metadata(pat...
#![deny(rust_2018_idioms)] use std::env; use std::fs::File; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::Path; use tempfile::{Builder, NamedTempFile}; use std::string::ToString; use crates_unittest::test_case; use std::prelude::v1::*; fn exists<P: AsRef<Path>>(path: P) -> bool { std::fs::metadata(pat...
drop(persist_target); } tmpfile.persist_noclobber(&persist_path).unwrap(); let mut f = File::open(&persist_path).unwrap(); f.seek(SeekFrom::Start(0)).unwrap(); let mut buf = String::new(); f.read_to_string(&mut buf).unwrap(); assert_eq!("abcde", buf); std::fs::remove_file(&persis...
"abcde").unwrap(); assert!(exists(&old_path)); { tmpfile = tmpfile.persist_noclobber(&persist_path).unwrap_err().into(); assert!(exists(&old_path)); std::fs::remove_file(&persist_path).unwrap();
function_block-random_span
[]
Rust
diesel/src/result.rs
FelixHenninger/diesel
ab9e38149328ce19f26b27bfd35d06e82246118e
use std::convert::From; use std::error::Error as StdError; use std::ffi::NulError; use std::fmt::{self, Display}; #[derive(Debug)] #[allow(clippy::enum_variant_names)] #[non_exhaustive] pub enum Error { InvalidCString(NulError), DatabaseError( DatabaseEr...
use std::convert::From; use std::error::Error as StdError; use std::ffi::NulError; use std::fmt::{self, Display}; #[derive(Debug)] #[allow(clippy::enum_variant_names)] #[non_exhaustive] pub enum Error { InvalidCString(NulError), DatabaseError( DatabaseEr...
} #[cfg(test)] #[allow(warnings)] fn error_impls_send() { let err: Error = unimplemented!(); let x: &Send = &err; } pub(crate) fn first_or_not_found<T>(records: QueryResult<Vec<T>>) -> QueryResult<T> { records?.into_iter().next().ok_or(Error::NotFound) } #[derive(Debug, Clone, Copy)] pub struct Unexpect...
er: &Error) -> bool { match (self, other) { (&Error::InvalidCString(ref a), &Error::InvalidCString(ref b)) => a == b, (&Error::DatabaseError(_, ref a), &Error::DatabaseError(_, ref b)) => { a.message() == b.message() } (&Error::NotFound, &Error::No...
function_block-function_prefixed
[ { "content": "pub fn edit_string(s: &str) -> Result<String, Box<dyn Error>> {\n\n let mut file = NamedTempFile::new()?;\n\n file.write_all(s.as_bytes())?;\n\n editor_output(&mut file)\n\n}\n\n\n", "file_path": "examples/postgres/advanced-blog-cli/src/editor.rs", "rank": 0, "score": 434570.1...
Rust
src/librustc/middle/trans/type_use.rs
lbonn/rust
09bb07bed9166105ea961a42b5fff7739ae0d2e9
use metadata::csearch; use middle::trans::common::*; use std::list::{List, Cons, Nil}; use std::list; use std::map::HashMap; use syntax::ast::*; use syntax::ast_map; use syntax::ast_util; use syntax::visit; type type_uses = uint; const use_repr: uint = 1u; /* Dependency on size/alignment/mode and ...
use metadata::csearch; use middle::trans::common::*; use std::list::{List, Cons, Nil}; use std::list; use std::map::HashMap; use syntax::ast::*; use syntax::ast_map; use syntax::ast_util; use syntax::visit; type type_uses = uint; const use_repr: uint = 1u; /* Dependency on size/alignment/mode and ...
false } ty::ty_param(p) => { cx.uses[p.idx] |= use_; false } _ => true } } else { false } } } fn node_type_needs(cx: ctx, use_: uint, id: node_id) { type_needs(cx, use_, ty::node_id_to_t...
if option::is_none(&list::find(enums_seen, |id| *id == did)) { let seen = @Cons(did, enums_seen); for vec::each(*ty::enum_variants(cx.ccx.tcx, did)) |v| { for vec::each(v.args) |aty| { let t = ty::subst(cx.ccx.tcx, &(*substs), *...
if_condition
[ { "content": "fn g() -> int { let x = match true { true => { f() } false => { 10 } }; return x; }\n\n\n", "file_path": "src/test/run-fail/expr-alt-fail-fn.rs", "rank": 4, "score": 591925.9118265692 }, { "content": "// error-pattern:explicit failure\n\nfn main() { let x = match true { false =...
Rust
rust/cubestore/src/remotefs/queue.rs
sergeylemekhov/cube.js
9a29ceec911f2fd3f50286c2a2342faeb8d553bc
use crate::config::ConfigObj; use crate::di_service; use crate::remotefs::{RemoteFile, RemoteFs}; use crate::util::lock::acquire_lock; use crate::CubeError; use async_trait::async_trait; use core::fmt; use datafusion::cube_ext; use deadqueue::unlimited; use futures::future::join_all; use log::error; use smallvec::alloc...
use crate::config::ConfigObj; use crate::di_service; use crate::remotefs::{RemoteFile, RemoteFs}; use crate::util::lock::acquire_lock; use crate::CubeError; use async_trait::async_trait; use core::fmt; use datafusion::cube_ext; use deadqueue::unlimited; use futures::future::join_all; use log::error; use smallvec::alloc...
} })); } for _ in 0..queue_remote_fs.config.download_concurrency() { let to_move = queue_remote_fs.clone(); futures.push(cube_ext::spawn(async move { let mut stopped_rx = to_move.stopped_rx.clone(); loop { ...
if let Err(err) = to_move.upload_loop(to_process).await { error!("Error during upload: {:?}", err); }
if_condition
[]
Rust
bls/src/threshold_sig.rs
zeroqn/signature-schemes
a98bd304b297cf555d59b9609715cf781077b479
use crate::{SignatureGroupVec, VerkeyGroupVec}; use amcl_wrapper::field_elem::{FieldElement, FieldElementVector}; use amcl_wrapper::group_elem::GroupElementVector; use common::{Params, SigKey, VerKey}; use secret_sharing::polynomial::Polynomial; use secret_sharing::shamir_secret_sharing::get_shared_secret; use simple::...
use crate::{SignatureGroupVec, VerkeyGroupVec}; use amcl_wrapper::field_elem::{FieldElement, FieldElementVector}; use amcl_wrapper::group_elem::GroupElementVector; use common::{Params, SigKey, VerKey}; use secret_sharing::polynomial::Polynomial; use secret_sharing::shamir_secret_sharing::get_shared_secret; use simple::...
pub fn aggregate_vk(threshold: usize, keys: Vec<(usize, &VerKey)>) -> VerKey { assert!(keys.len() >= threshold); let mut vk_bases = VerkeyGroupVec::with_capacity(threshold); let mut vk_exps = FieldElementVector::with_capacity(threshold); let signer_ids = keys .iter() ...
let signer_ids = sigs .iter() .take(threshold) .map(|(i, _)| *i) .collect::<HashSet<usize>>(); for (id, sig) in sigs.into_iter().take(threshold) { let l = Polynomial::lagrange_basis_at_0(signer_ids.clone(), id); s_bases.push(sig.point.clone...
function_block-function_prefix_line
[ { "content": "pub fn keygen(count_messages: usize, label: &[u8]) -> (Sigkey, Verkey) {\n\n // TODO: Take PRNG as argument\n\n let g = SignatureGroup::from_msg_hash(&[label, \" : g\".as_bytes()].concat());\n\n let g_tilde = OtherGroup::from_msg_hash(&[label, \" : g_tilde\".as_bytes()].concat());\n\n ...
Rust
cli/bufflib/src/protobuffers/buff_grpc.rs
BlueHotDog/buff
0403f68867e950945a47cce2d7442974d12583b2
#![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #!...
#![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #!...
iceBuilder::new(); let mut instance = s.clone(); builder = builder.add_unary_handler(&METHOD_AUTH_SERVICE_LOGIN, move |ctx, req, resp| { instance.login(ctx, req, resp) }); builder.build() } const METHOD_REGISTRY_SERVICE_PUBLISH: ::grpcio::Method<super::buff::PublishRequest, super::buff::Publish...
<::grpcio::ClientUnaryReceiver<super::buff::LoginResponse>> { self.login_async_opt(req, ::grpcio::CallOption::default()) } pub fn spawn<F>(&self, f: F) where F: ::futures::Future<Item = (), Error = ()> + Send + 'static { self.client.spawn(f) } } pub trait AuthService { fn login(&mut sel...
random
[ { "content": "pub fn publish() {\n\n let config = BuffCliConfig::new();\n\n let registry_url = config.preferred_registry.clone();\n\n let channel = get_channel(registry_url.as_str());\n\n let client = RegistryServiceClient::new(channel);\n\n let metadata = PackageMetadata::new(&get_buff_toml_path().to_str(...
Rust
src/bbox4.rs
johannesvollmer/psychopath
21cd04ce95deea631ef2c7ce50e200215668a3c0
#![allow(dead_code)] use std; use std::ops::{BitOr, BitOrAssign}; use crate::{ bbox::BBox, lerp::{lerp, Lerp}, math::{Point, Vector}, }; use glam::{Vec4, Vec4Mask}; const BBOX_MAXT_ADJUST: f32 = 1.000_000_24; #[derive(Debug, Copy, Clone)] pub struct BBox4 { pub x: (Vec4, Vec4), pub y: (Vec4, V...
#![allow(dead_code)] use std; use std::ops::{BitOr, BitOrAssign}; use crate::{ bbox::BBox, lerp::{lerp, Lerp}, math::{Point, Vector}, }; use glam::{Vec4, Vec4Mask}; const BBOX_MAXT_ADJUST: f32 = 1.000_000_24; #[derive(Debug, Copy, Clone)] pub struct BBox4 { pub x: (Vec4, Vec4), pub y: (Vec4, V...
} impl BitOr for BBox4 { type Output = BBox4; fn bitor(self, rhs: BBox4) -> BBox4 { BBox4 { x: (self.x.0.min(rhs.x.0), self.x.1.max(rhs.x.1)), y: (self.y.0.min(rhs.y.0), self.y.1.max(rhs.y.1)), z: (self.z.0.min(rhs.z.0), self.z.1.max(rhs.z.1)), } } } i...
i_z = Vec4::splat(dir_inv.co.z()); let max_t = Vec4::splat(max_t); let t1_x = (self.x.0 - ro_x) * rdi_x; let t1_y = (self.y.0 - ro_y) * rdi_y; let t1_z = (self.z.0 - ro_z) * rdi_z; let t2_x = (self.x.1 - ro_x) * rdi_x; let t2_y = (self.y.1 - ro_y) * rdi_y; ...
function_block-function_prefixed
[ { "content": "/// Calculates a point on a triangle's surface at the given barycentric\n\n/// coordinates.\n\n///\n\n/// Returns the point and the error magnitude of the point.\n\npub fn surface_point(tri: (Point, Point, Point), bary: (f32, f32, f32)) -> (Point, f32) {\n\n let pos = ((tri.0.into_vector() * ba...
Rust
rafx-plugins/src/features/mesh_basic/jobs/extract.rs
mmn80/rafx
056d01667cf94481f922b9c7e3c8bdf9542c9355
use rafx::render_feature_extract_job_predule::*; use super::*; use crate::components::{ DirectionalLightComponent, PointLightComponent, SpotLightComponent, TransformComponent, }; use legion::{Entity, EntityStore, IntoQuery, Read, World}; use rafx::assets::{AssetManagerExtractRef, AssetManagerRenderResource, Materi...
use rafx::render_feature_extract_job_predule::*; use super::*; use crate::components::{ DirectionalLightComponent, PointLightComponent, SpotLightComponent, TransformComponent, }; use legion::{Entity, EntityStore, IntoQuery, Read, World}; use rafx::assets::{AssetManagerExtractRef, AssetManagerRenderResource, Materi...
depth_material_pass: self .asset_manager .committed_asset(&self.depth_material) .unwrap() .get_single_material_pass() .ok(), }); } fn extract_render_object_instance( &self, ...
eContext<'extract, '_, Self>, ) { context .frame_packet() .per_frame_data() .set(MeshBasicPerFrameData {
function_block-random_span
[ { "content": "pub fn do_find_supported_format(\n\n instance: &ash::Instance,\n\n physical_device: vk::PhysicalDevice,\n\n candidates: &[RafxFormat],\n\n image_tiling: vk::ImageTiling,\n\n features: vk::FormatFeatureFlags,\n\n) -> Option<RafxFormat> {\n\n for &candidate in candidates {\n\n ...
Rust
kf-protocol-derive/src/de.rs
mocsy/flv-kf-protocol
e6159f064b9ebef1834bb6f4f6496568fcdf6166
use crate::ast::{ container::ContainerAttributes, prop::Prop, r#enum::EnumProp, r#enum::FieldKind, DeriveItem, }; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use std::str::FromStr; use syn::Ident; use syn::LitInt; pub(crate) fn generate_decode_trait_impls(input:...
use crate::ast::{ container::ContainerAttributes, prop::Prop, r#enum::EnumProp, r#enum::FieldKind, DeriveItem, }; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use std::str::FromStr; use syn::Ident; use syn::LitInt; pub(crate) fn generate_decode_trait_impls(input:...
; let enum_tokens = generate_variant_tokens(&int_type); let try_enum = generate_try_enum_from_kf_enum(&kf_enum.props, &int_type, ident, &attrs); let res = quote! { impl #impl_generics kf_protocol::Decoder for #ident #ty_generics #where_clause { fn ...
if let Some(int_type_name) = &attrs.repr_type_name { format_ident!("{}", int_type_name) } else { Ident::new("u8", Span::call_site()) }
if_condition
[ { "content": "fn generate_request_trait_impl(name: &Ident, attrs: &[Attribute]) -> TokenStream {\n\n // check if we have api version\n\n let version_meta = if let Some(version) = find_attr(attrs, \"fluvio_kf\") {\n\n version\n\n } else {\n\n return quote! {};\n\n };\n\n\n\n let api_...
Rust
src/utils/completer.rs
zzhengzhuo/ckb-cli
163ed210f526b69a1f957bbf17a31e05defb3182
use std::borrow::Cow::{self, Owned}; use std::collections::HashSet; use std::iter; use std::sync::Arc; use ansi_term::Colour::{Green, Red}; use rustyline::completion::{extract_word, Completer, Pair}; use rustyline::error::ReadlineError; use rustyline::highlight::Highlighter; use rustyline::hint::Hinter; use rustyline:...
use std::borrow::Cow::{self, Owned}; use std::collections::HashSet; use std::iter; use std::sync::Arc; use ansi_term::Colour::{Green, Red}; use rustyline::completion::{extract_word, Completer, Pair}; use rustyline::error::ReadlineError; use rustyline::highlight::Highlighter; use rustyline::hint::Hinter; use rustyline:...
})) .collect::<Vec<Vec<(String, String)>>>() .concat() } pub fn find_subcommand<'s, Iter: iter::Iterator<Item = &'s str>>( app: Arc<clap::App<'a>>, mut prefix_names: iter::Peekable<Iter>, ) -> Option<Arc<clap::App<'a>>> { if let Some(name) = pref...
switched_completions( a.get_short(), a.get_long(), a.is_set(clap::ArgSettings::MultipleValues), a.is_set(clap::ArgSettings::Required), )
call_expression
[ { "content": "pub fn to_vec<T: ?Sized>(value: &T, color: bool) -> Result<Vec<u8>, String>\n\nwhere\n\n T: ser::Serialize,\n\n{\n\n let mut vec = Vec::with_capacity(128);\n\n to_writer(&mut vec, value, color)?;\n\n Ok(vec)\n\n}\n\n\n", "file_path": "src/utils/yaml_ser.rs", "rank": 0, "sco...
Rust
bindings/python/native/src/client/high_level_api.rs
r-c-k/iota.rs
9f447b1dcbf604888d8953a6c81305379a71f8db
use crate::client::{ error::{Error, Result}, AddressBalancePair, Client, Input, Message, MessageMetadataResponse, Output, }; use iota::{ Bech32Address as RustBech32Address, MessageId as RustMessageId, Seed as RustSeed, TransactionId as RustTransationId, UTXOInput as RustUTXOInput, }; use pyo3::{except...
use crate::client::{ error::{Error, Result}, AddressBalancePair, Client, Input, Message, MessageMetadataResponse, Output, }; use iota::{ Bech32Address as RustBech32Address, MessageId as RustMessageId, Seed as RustSeed, TransactionId as RustTransationId, UTXOInput as RustUTXOInput, }; use pyo3::{except...
fn get_balance( &self, seed: String, account_index: Option<usize>, initial_address_index: Option<usize>, ) -> Result<u64> { let rt = tokio::runtime::Runtime::new()?; let seed = RustSeed::from_bytes(&hex::decode(&seed[..])?); let balance = rt.block_on(asyn...
0); let end: usize = input_range_end.unwrap_or(0); if get_all.unwrap_or(false) { let rt = tokio::runtime::Runtime::new()?; let addresses = rt.block_on(async { self.client .get_addresses(&seed) .with_account_index(account_ind...
function_block-function_prefixed
[ { "content": "fn get_mqtt_client(client: &mut Client) -> Result<&MqttClient> {\n\n match client.mqtt_client {\n\n Some(ref c) => Ok(c),\n\n None => {\n\n for node in client.sync.read().unwrap().iter() {\n\n let uri = match client.broker_options.use_ws {\n\n ...
Rust
src/lib.rs
safesurfer/rpassword
6d50a0068405de99223b251ca3f2da9f83cbc58b
#[cfg(unix)] extern crate libc; use std::io::Write; fn zero_memory(s: &mut String) { let vec = unsafe { s.as_mut_vec() }; for el in vec.iter_mut() { *el = 0u8; } } fn fixes_newline(password: &mut String) { if password.ends_with('\n') { password.pop(); ...
#[cfg(unix)] extern crate libc; use std::io::Write; fn zero_memory(s: &mut String) { let vec = unsafe { s.as_mut_vec() }; for el in vec.iter_mut() { *el = 0u8; } } fn fixes_newline(password: &mut String) { if password.ends_with('\n') { password.pop(); ...
if handle == winapi::INVALID_HANDLE_VALUE { return Err(::std::io::Error::last_os_error()); } let mut mode = 0; if unsafe { kernel32::GetConsoleMode(handle, &mut mode as winapi::LPDWORD) } == 0 { return Err(::std::io::Error::last_os_error()); } ...
let handle = if open_tty { unsafe { kernel32::CreateFileA(b"CONIN$\x00".as_ptr() as *const i8, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, ::std::ptr::null_...
assignment_statement
[ { "content": "fn main() {\n\n let pass = rpassword::read_password_from_tty(Some(\"Password: \")).unwrap();\n\n println!(\"Password: {}\", pass);\n\n}\n", "file_path": "examples/read-password-tty.rs", "rank": 7, "score": 50383.6067472977 }, { "content": "#[cfg(not(any(unix, windows)))]\...
Rust
core/src/header.rs
orangemio/ckb
5b3664e162c840f421469279e7e68fe9dcad75dd
use bincode::{deserialize, serialize}; use faster_hex::hex_string; use hash::blake2b_256; use numext_fixed_hash::H256; use numext_fixed_uint::U256; use serde_derive::{Deserialize, Serialize}; use std::{fmt, mem}; pub use crate::{BlockNumber, EpochNumber, Version}; pub const HEADER_VERSION: Version = 0; #[derive(Clon...
use bincode::{deserialize, serialize}; use faster_hex::hex_string; use hash::blake2b_256; use numext_fixed_hash::H256; use numext_fixed_uint::U256; use serde_derive::{Deserialize, Serialize}; use std::{fmt, mem}; pub use crate::{BlockNumber, EpochNumber, Version}; pub const HEADER_VERSION: Version = 0; #[derive(Clon...
r Header { fn eq(&self, other: &Header) -> bool { self.hash() == other.hash() } } #[derive(Default)] pub struct HeaderBuilder { raw: RawHeader, seal: Seal, } impl HeaderBuilder { pub fn from_header(header: Header) -> Self { let Header { raw, seal, .. } = header; Self { raw,...
timestamp: u64, number: BlockNumber, transactions_root: H256, proposals_hash: H256, witnesses_root: H256, difficulty: U256, uncles_hash: H256, uncles_count: u32, epoch: EpochNumber, } impl RawHeader { pub fn pow_hash(&self) -> H256 { ...
random
[ { "content": "pub fn wait_until<F>(secs: u64, mut f: F) -> bool\n\nwhere\n\n F: FnMut() -> bool,\n\n{\n\n let start = Instant::now();\n\n let timeout = Duration::new(secs, 0);\n\n while Instant::now().duration_since(start) <= timeout {\n\n if f() {\n\n return true;\n\n }\n\n...
Rust
geo-types/src/geometry_collection.rs
dabreegster/geo
d4f89e342e1855a00db0898a2750064a2fa172b7
use crate::{CoordinateType, Geometry}; use std::iter::FromIterator; use std::ops::{Index, IndexMut}; #[derive(Eq, PartialEq, Clone, Debug, Hash)] pub struct GeometryCollection<T>(pub Vec<Geometry<T>>) where T: CoordinateType; impl<T: CoordinateType> Default for GeometryCollection<T> { fn default() -> Self { ...
use crate::{CoordinateType, Geometry}; use std::iter::FromIterator; use std::ops::{Index, IndexMut}; #[derive(Eq, PartialEq, Clone, Debug, Hash)] pub struct GeometryCollection<T>(pub Vec<Geometry<T>>) where T: CoordinateType; impl<T: CoordinateType> Default for GeometryCollection<T> { fn default() -> Self { ...
>, } impl<'a, T: CoordinateType> IntoIterator for &'a GeometryCollection<T> { type Item = &'a Geometry<T>; type IntoIter = IterHelper<'a, T>; fn into_iter(self) -> Self::IntoIter { IterHelper { iter: self.0.iter(), } } } impl<'a, T: CoordinateType> Iterator for IterHe...
tem = IG>>(iter: I) -> Self { GeometryCollection(iter.into_iter().map(|g| g.into()).collect()) } } impl<T: CoordinateType> Index<usize> for GeometryCollection<T> { type Output = Geometry<T>; fn index(&self, index: usize) -> &Geometry<T> { self.0.index(index) } } impl<T: CoordinateType...
random
[ { "content": "pub fn point_contains_point<T>(p1: Point<T>, p2: Point<T>) -> bool\n\nwhere\n\n T: Float,\n\n{\n\n let distance = line_euclidean_length(Line::new(p1, p2)).to_f32().unwrap();\n\n relative_eq!(distance, 0.0)\n\n}\n\n\n", "file_path": "geo-types/src/private_utils.rs", "rank": 0, ...
Rust
src/imp/schannel.rs
segfault87/rust-native-tls
acec3be35515433431cadd07ec07f182ae37a18b
extern crate schannel; use std::io; use std::fmt; use std::error; use std::sync::Arc; use self::schannel::cert_store::{PfxImportOptions, Memory, CertStore, CertAdd}; use self::schannel::cert_context::CertContext; use self::schannel::schannel_cred::{Direction, SchannelCred, Protocol}; use self::schannel::tls_stream; f...
extern crate schannel; use std::io; use std::fmt; use std::error; use std::sync::Arc; use self::schannel::cert_store::{PfxImportOptions, Memory, CertStore, CertAdd}; use self::schannel::cert_context::CertContext; use self::schannel::schannel_cred::{Direction, SchannelCred, Protocol}; use self::schannel::tls_stream; f...
} pub struct MidHandshakeTlsStream<S>(tls_stream::MidHandshakeTlsStream<S>); impl<S> fmt::Debug for MidHandshakeTlsStream<S> where S: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, fmt) } } impl<S> MidHandshakeTlsStream<S> where S: io::Read + ...
pub fn from_pem(buf: &[u8]) -> Result<Certificate, Error> { match ::std::str::from_utf8(buf) { Ok(s) => { let cert = try!(CertContext::from_pem(s)); Ok(Certificate(cert)) } Err(_) => { Err( io::Error::new( ...
function_block-full_function
[ { "content": "fn supported_protocols(protocols: &[Protocol], ctx: &mut SslContextBuilder) {\n\n // This constant is only defined on OpenSSL 1.0.2 and above, so manually do it.\n\n let ssl_op_no_ssl_mask = ssl::SSL_OP_NO_SSLV2 | ssl::SSL_OP_NO_SSLV3 | ssl::SSL_OP_NO_TLSV1 |\n\n ssl::SSL_OP_NO_TLSV1_...
Rust
src/headers/ip.rs
coldFireworks/packet_crafter
8bcb72df4a248d593be187fb512eb13012dd789b
use super::{Header, PacketData, ParseError, Protocol}; use crate::{checksum, protocol_numbers, AsBeBytes}; use std::net::IpAddr; #[derive(AddGetter, AddSetter)] pub struct IpHeader { #[get] #[set] tos: u8, #[get] #[set] packet_len: u16, #[get] #[set] identification: u16, #[get] ...
use super::{Header, PacketData, ParseError, Protocol}; use crate::{checksum, protocol_numbers, AsBeBytes}; use std::net::IpAddr; #[derive(AddGetter, AddSetter)] pub struct IpHeader { #[get] #[set] tos: u8, #[get] #[set] packet_len: u16, #[get] #[set] identification: u16, #[get] ...
pub fn set_next_protocol(&mut self, proto: Protocol) -> &mut Self { self.next_protocol = match proto { Protocol::ICMP => protocol_numbers::IPPROTO_ICMP, Protocol::TCP => protocol_numbers::IPPROTO_TCP, Protocol::UDP => protocol_numbers::IPPROTO_UDP, _ => pani...
pub fn new<IA: Into<IpAddr>>(src_ip: IA, dst_ip: IA, next_proto: Protocol) -> Self { let (src_ip, dst_ip) = (src_ip.into(), dst_ip.into()); match (src_ip, dst_ip) { (IpAddr::V4(_), IpAddr::V4(_)) => { /* OK */ } (IpAddr::V6(_), IpAddr::V6(_)) => { /* OK */ } _ => pani...
function_block-full_function
[ { "content": "/// Calculates a checksum. Used by ipv4 and icmp. The two bytes starting at `skipword * 2` will be\n\n/// ignored. Supposed to be the checksum field, which is regarded as zero during calculation.\n\npub fn checksum(data: &[u8], skipword: usize) -> u16 {\n\n finalize_checksum(sum_be_words(data, ...
Rust
tests/it/array/utf8/mod.rs
houqp/arrow2
a238efe3826ef0d6950ae28536bdb95da608b3b4
use arrow2::{array::*, bitmap::Bitmap, buffer::Buffer, datatypes::DataType, error::Result}; mod mutable; #[test] fn basics() { let data = vec![Some("hello"), None, Some("hello2")]; let array: Utf8Array<i32> = data.into_iter().collect(); assert_eq!(array.value(0), "hello"); assert_eq!(array.value(1),...
use arrow2::{array::*, bitmap::Bitmap, buffer::Buffer, datatypes::DataType, error::Result}; mod mutable; #[test] fn basics() { let data = vec![Some("hello"), None, Some("hello2")]; let array: Utf8Array<i32> = data.into_iter().collect(); assert_eq!(array.value(0), "hello"); assert_eq!(array.value(1),...
#[test] fn from_iter_values() { let b = Utf8Array::<i32>::from_iter_values(["a", "b", "cc"].iter()); let offsets = Buffer::from(&[0, 1, 2, 4]); let values = Buffer::from("abcc".as_bytes()); assert_eq!( b, Utf8Array::<i32>::from_data(DataType::Utf8, offsets, values, None) ); } #[t...
let b = Utf8Array::<i32>::from_slice(&["a", "b", "cc"]); let offsets = Buffer::from(&[0, 1, 2, 4]); let values = Buffer::from("abcc".as_bytes()); assert_eq!( b, Utf8Array::<i32>::from_data(DataType::Utf8, offsets, values, None) ); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn basic() {\n\n let a = MutableFixedSizeBinaryArray::from_data(\n\n DataType::FixedSizeBinary(2),\n\n MutableBuffer::from([1, 2, 3, 4]),\n\n None,\n\n );\n\n assert_eq!(a.len(), 2);\n\n assert_eq!(a.data_type(), &DataType::FixedSizeBinary(2));\n\n as...