lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/error.rs
crumblingstatue/amf
4b728dc8b2ea7b8389616c8de45d7c402cf387e7
use std::error; use std::fmt; use std::io; use std::string; #[derive(Debug)] pub enum DecodeError { Io(io::Error), String(string::FromUtf8Error), Unknown { marker: u8, }, Unsupported { marker: u8, }, UnexpectedObjectEnd, ...
use std::error; use std::fmt; use std::io; use std::string; #[derive(Debug)] pub enum DecodeError { Io(io::Error), String(string::FromUtf8Error), Unknown { marker: u8, }, Unsupported { marker: u8, }, UnexpectedObjectEnd, ...
rReference { index: x }, &CircularReference { index: y }) => x == y, (&OutOfRangeReference { index: x }, &OutOfRangeReference { index: y }) => x == y, (&NonZeroTimeZone { offset: x }, &NonZeroTimeZone { offset: y }) => x == y, (&InvalidDate { millis: x }, &InvalidDate { millis: y }) ...
}, OutOfRangeReference { index: usize, }, NonZeroTimeZone { offset: i16, }, InvalidDate { millis: f64, }, ExternalizableType { name: String, }, } impl error::Error for DecodeError { fn source(...
random
[ { "content": "#[derive(Debug)]\n\nenum SizeOrIndex {\n\n Size(usize),\n\n Index(usize),\n\n}\n\n\n\n/// AMF3 decoder.\n\n#[derive(Debug)]\n\npub struct Decoder<R> {\n\n inner: R,\n\n traits: Vec<Trait>,\n\n strings: Vec<String>,\n\n complexes: Vec<Value>,\n\n}\n\nimpl<R> Decoder<R> {\n\n //...
Rust
src/atsame70q21b/twihs0/twihs_sr.rs
tstellanova/atsame7x-pac
f7e24c71181651c141d0727379147c388661ce0e
#[doc = "Reader of register TWIHS_SR"] pub type R = crate::R<u32, super::TWIHS_SR>; #[doc = "Reader of field `TXCOMP`"] pub type TXCOMP_R = crate::R<bool, bool>; #[doc = "Reader of field `RXRDY`"] pub type RXRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `TXRDY`"] pub type TXRDY_R = crate::R<bool, bool>; #[doc ...
#[doc = "Reader of register TWIHS_SR"] pub type R = crate::R<u32, super::TWIHS_SR>; #[doc = "Reader of field `TXCOMP`"] pub type TXCOMP_R = crate::R<bool, bool>; #[doc = "Reader of field `RXRDY`"] pub type RXRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `TXRDY`"] pub type TXRDY_R = crate::R<bool, bool>; #[doc ...
#[doc = "Bit 9 - Arbitration Lost (cleared on read)"] #[inline(always)] pub fn arblst(&self) -> ARBLST_R { ARBLST_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - Clock Wait State"] #[inline(always)] pub fn sclws(&self) -> SCLWS_R { SCLWS_R::new(((self.bits >> 10) &...
7) & 0x01) != 0) } #[doc = "Bit 8 - Not Acknowledged (cleared on read)"] #[inline(always)] pub fn nack(&self) -> NACK_R { NACK_R::new(((self.bits >> 8) & 0x01) != 0) }
random
[ { "content": "#[doc = \"This trait shows that register has `write`, `write_with_zero` and `reset` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Readable` can be also `modify`'ed\"]\n\npub trait Writable {}\n", "file_path": "src/generic.rs", "rank": 0, "score": 58126.51002228791 },...
Rust
src/combinators/sequential.rs
codgician/parsic
1b2a32ab568ebf93ceb90db8b21ee931851cfd96
use crate::combinators::FunctorExt; use crate::core::{return_none, Parsable, Parser}; pub fn and<'f, A: 'f, B: 'f, S: Clone>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, ) -> Parser<'f, (A, B), S> { Parser::new(move |stream: &mut S, logger| { let ...
use crate::combinators::FunctorExt; use crate::core::{return_none, Parsable, Parser};
pub fn left<'f, A: 'f, B: 'f, S: Clone + 'f>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, ) -> Parser<'f, A, S> { p1.and(p2).map(|(l, _)| l) } pub fn right<'f, A: 'f, B: 'f, S: Clone + 'f>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: imp...
pub fn and<'f, A: 'f, B: 'f, S: Clone>( p1: impl Parsable<Stream = S, Result = A> + 'f, p2: impl Parsable<Stream = S, Result = B> + 'f, ) -> Parser<'f, (A, B), S> { Parser::new(move |stream: &mut S, logger| { let st = stream.clone(); p1.parse(stream, logger) .and_then(|x| p2.pars...
function_block-full_function
[ { "content": "/// # `Parsable` trait\n\n/// Anything that is parsable should implement `Parsable` trait,\n\n/// The return types of all the combinators and combinators in this library\n\n/// Implement `Parsable` trait, meaning you can treat them as parsers\n\n/// and call `parse()` or `exec()` from them to pars...
Rust
src/core/context/default_context.rs
another-s347/rusty-p4
b2c395e1b14e105762d7eb0879315ed8a7dca7d2
use crate::app::P4app; use crate::entity::UpdateType; use crate::error::{ContextError, ContextErrorKind}; use crate::event::{CommonEvents, CoreEvent, CoreRequest, Event, PacketReceived}; use crate::p4rt::bmv2::Bmv2SwitchConnection; use crate::p4rt::pipeconf::{Pipeconf, PipeconfID}; use crate::p4rt::pure::{ new_pack...
use crate::app::P4app; use crate::entity::UpdateType; use crate::error::{ContextError, ContextErrorKind}; use crate::event::{CommonEvents, CoreEvent, CoreRequest, Event, PacketReceived}; use crate::p4rt::bmv2::Bmv2SwitchConnection; use crate::p4rt::pipeconf::{Pipeconf, PipeconfID}; use crate::p4rt::pure::{ new_pack...
} fn add_device(&mut self, device: Device) -> bool { if self.connections.contains_key(&device.id) { return false; } self.core_request_sender .try_send(CoreRequest::AddDevice { device, }) .unwrap(); return true; ...
if let Some(c) = self.connections.get_mut(&to.device) { let request = new_packet_out_request(&c.pipeconf, to.port, packet); if let Err(err) = c.send_stream_request(request).await { error!(target: "core", "packet out err {:?}", err); } } else { ...
if_condition
[ { "content": "pub fn new_set_entity_request(\n\n device_id: u64,\n\n entity: Entity,\n\n update_type: crate::proto::p4runtime::update::Type,\n\n) -> WriteRequest {\n\n WriteRequest {\n\n device_id,\n\n role_id: 0,\n\n election_id: Some(Uint128 { high: 0, low: 1 }),\n\n up...
Rust
src/lib.rs
matclab/automattermostatus
169b72638dbda91528e30e54a7a614e2e6a20471
#![warn(missing_docs)] use anyhow::{bail, Context, Result}; use std::fs; use std::path::PathBuf; use std::thread::sleep; use std::{collections::HashMap, time}; use tracing::{debug, error, info, warn}; use tracing_subscriber::prelude::*; use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter}; pub mod config; p...
#![warn(missing_docs)] use anyhow::{bail, Context, Result}; use std::fs; use std::path::PathBuf; use std::thread::sleep; use std::{collections::HashMap, time}; use tracing::{debug, error, info, warn}; use tracing_subscriber::prelude::*; use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter}; pub mod config; p...
pub fn get_cache(dir: Option<PathBuf>) -> Result<Cache> { let mut state_file_name: PathBuf; if let Some(ref state_dir) = dir { state_file_name = PathBuf::from(state_dir); fs::create_dir_all(&state_dir) .with_context(|| format!("Creating cache dir {:?}", &state_dir))?; } else { ...
pub fn setup_tracing(args: &Args) -> Result<()> { let fmt_layer = fmt::layer().with_target(false); let filter_layer = EnvFilter::try_new(args.verbose.get_level_filter().to_string()).unwrap(); tracing_subscriber::registry() .with(filter_layer) .with(fmt_layer) .init(); Ok(()) }
function_block-full_function
[ { "content": "/// Trait implementing function necessary to establish a session (getting a authenticating token).\n\npub trait BaseSession {\n\n /// Get session token\n\n fn token(&self) -> Result<&str>;\n\n\n\n /// Get session `base_uri`\n\n fn base_uri(&self) -> &str;\n\n\n\n /// Login to matter...
Rust
imtui-sys/src/bindings.rs
richinseattle/imtui-rs
09ecddbd9a0e535068406d580c9aaf21d096d7af
/* automatically generated by rust-bindgen */ extern crate imgui_sys; #[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] pub mod root { #[allow(unused_imports)] use self::super::root; use imgui_sys::ImDrawData; pub mod ImTui { #[allow(unused_imports)] use self::supe...
/* automatically generated by rust-bindgen */ extern crate imgui_sys; #[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] pub mod root { #[allow(unused_imports)] use self::super::root; use imgui_sys::ImDrawData; pub mod ImTui { #[allow(unused_imports)] use self::supe...
} } extern "C" { #[link_name = "\u{1}__Z19ImTui_ImplText_Initv"] pub fn ImTui_ImplText_Init() -> bool; } extern "C" { #[link_name = "\u{1}__Z23ImTui_ImplText_Shutdownv"] pub fn ImTui_ImplText_Shutdown(); } extern "C" { #[link_name = "\u{1}__Z23ImT...
pnx: ::std::os::raw::c_int, pny: ::std::os::raw::c_int, ) { TScreen_resize(self, pnx, pny) }
function_block-function_prefix_line
[ { "content": "type HnItemId = u32;\n\n\n", "file_path": "examples/hnterm/main.rs", "rank": 0, "score": 67556.55634805921 }, { "content": "pub fn generate_bindings(imtui_path: &Path, imgui_include_path: &Path) -> Result<Bindings, Error> {\n\n let imtui_include_path = imtui_path.join(\"incl...
Rust
procgen/src/connections.rs
gridbugs/rip
4bb5388df5d8fd694399773bf2faeba51f2cf2e5
use crate::hull::HullCell; use direction::{CardinalDirection, Direction}; use grid_2d::{ coord_2d::{static_axis, Axis, StaticAxis}, Coord, Grid, }; use rand::{seq::SliceRandom, Rng}; use std::collections::{HashMap, HashSet, VecDeque}; type RoomId = usize; type DoorCandidateId = usize; pub enum ConnectedCell {...
use crate::hull::HullCell; use direction::{CardinalDirection, Direction}; use grid_2d::{ coord_2d::{static_axis, Axis, StaticAxis}, Coord, Grid, }; use rand::{seq::SliceRandom, Rng}; use std::collections::{HashMap, HashSet, VecDeque}; type RoomId = usize; type DoorCandidateId = usize; pub enum ConnectedCell {...
fn choose_door_candidates<R: Rng>( door_candidate_graph: &DoorCandidateGraph, door_candidates: &[DoorCandidate], rng: &mut R, ) -> Vec<DoorCandidateId> { let mut chosen_door_candidates = make_random_door_candidate_graph_minimum_spanning_tree(&door_candidate_graph, door_candidates, rng); le...
fn make_random_door_candidate_graph_minimum_spanning_tree<R: Rng>( door_candidate_graph: &DoorCandidateGraph, door_candidates: &[DoorCandidate], rng: &mut R, ) -> HashSet<DoorCandidateId> { let mut mst = HashSet::new(); let mut visited_room_ids = HashSet::new(); let mut to_visit = vec![rng.gen_r...
function_block-full_function
[ { "content": "pub fn add_internal_walls<R: Rng>(grid: &Grid<HullCell>, rng: &mut R) -> Grid<HullCell> {\n\n let external_walls = ExternalWalls::classify(grid);\n\n let mut internal_walls = Vec::new();\n\n add_internal_walls_rec(\n\n &external_walls,\n\n Rect {\n\n coord: Coord:...
Rust
alacritty/src/renderer/graphics/draw.rs
SonaliBendre/alacritty-sixel
4b143ad2c623f54610a71dba1687d63a2b0f751a
use std::collections::BTreeMap; use std::mem::{self, MaybeUninit}; use crate::display::content::RenderableCell; use crate::gl::{self, types::*}; use crate::renderer::graphics::{shader, GraphicsRenderer}; use alacritty_terminal::graphics::GraphicId; use alacritty_terminal::index::{Column, Line}; use alacritty_termin...
use std::collections::BTreeMap; use std::mem::{self, MaybeUninit}; use crate::display::content::RenderableCell; use crate::gl::{self, types::*}; use crate::renderer::graphics::{shader, GraphicsRenderer}; use alacritty_terminal::graphics::GraphicId; use alacritty_terminal::index::{Column, Line}; use alacritty_termin...
#[inline] pub fn is_empty(&self) -> bool { self.items.is_empty() } pub fn build_vertices(self, renderer: &GraphicsRenderer) -> Vec<shader::Vertex> { use shader::VertexSide::{BottomLeft, BottomRight, TopLeft, TopRight}; let mut vertices = Vec::new(); for (gr...
y, padding_y: size_info.padding_y() as u16, }; self.items.insert(graphic_id, render_item); } }
function_block-function_prefixed
[ { "content": "pub fn derive_deserialize<T>(\n\n ident: Ident,\n\n generics: Generics,\n\n fields: Punctuated<Field, T>,\n\n) -> TokenStream {\n\n // Create all necessary tokens for the implementation.\n\n let GenericsStreams { unconstrained, constrained, phantoms } =\n\n generics_streams(g...
Rust
xhcid/src/usb/setup.rs
redox-os/drivers
36b3af426260cb1bd740426f5fb8a07a5f37e4c5
use super::DescriptorKind; use crate::driver_interface::*; #[repr(packed)] #[derive(Clone, Copy, Debug, Default)] pub struct Setup { pub kind: u8, pub request: u8, pub value: u16, pub index: u16, pub length: u16, } #[repr(u8)] pub enum ReqDirection { HostToDevice = 0, DeviceToHost = 1, } i...
use super::DescriptorKind; use crate::driver_interface::*; #[repr(packed)] #[derive(Clone, Copy, Debug, Default)] pub struct Setup { pub kind: u8, pub request: u8, pub value: u16, pub index: u16, pub length: u16, } #[repr(u8)] pub enum ReqDirection { HostToDevice = 0, DeviceToHost = 1, } i...
}
ce(interface: u8, alternate_setting: u8) -> Self { Self { kind: 0b0000_0001, request: 0x09, value: alternate_setting as u16, index: interface as u16, length: 0, } }
function_block-function_prefixed
[ { "content": "pub fn mode_page_iter(buffer: &[u8]) -> impl Iterator<Item = AnyModePage> {\n\n ModePageIter {\n\n raw: ModePageIterRaw { buffer },\n\n }\n\n}\n", "file_path": "usbscsid/src/scsi/cmds.rs", "rank": 0, "score": 236183.29528297443 }, { "content": "pub fn enable(relati...
Rust
src/app_service.rs
Zignar-Technologies/did-api
18efc8fab44c055d2eddfd4567cf830d011e94d6
use std::str::FromStr; use actix_web::{post, web, HttpResponse}; use identity::{ core::{FromJson, ToJson}, credential::{Credential, Presentation}, iota::{ClientMap, IotaDID}, prelude::IotaDocument, }; use serde_json::{json, Value}; use crate::utils_did::validator::CredentialValidation; use crate::utils...
use std::str::FromStr; use actix_web::{post, web, HttpResponse}; use identity::{ core::{FromJson, ToJson}, credential::{Credential, Presentation}, iota::{ClientMap, IotaDID}, prelude::IotaDocument, }; use serde_json::{json, Value}; use crate::utils_did::validator::CredentialValidation; use crate::utils...
#[post("/create_vc")] async fn createVcApi(data_json: web::Json<CreateVc>) -> HttpResponse { let data = data_json.into_inner(); let data_issuer = data.issuer; let iota_did = IotaDID::from_str(&data_issuer.did.unwrap()).unwrap(); let account = User::new( data_issuer.nick_name.to_string(), ...
or": false, "Status": "Method Created", "Explorer": explorer, "vm_name": vm_randon })) }
function_block-function_prefixed
[ { "content": "pub fn holder_presentation(holder: &IotaDID, credential: Credential) -> Result<Presentation> {\n\n // Create VC \"subject\" field containing subject ID and claims about it.\n\n\n\n // Create an unsigned Presentation from the previously issued Verifiable Credential.\n\n let presentation: P...
Rust
src/lib.rs
Noskcaj19/macos-notifications
04c02ef0bf1c63bd9244eef0c3e09e8116cee8fc
extern crate cocoa; #[macro_use] extern crate objc; use objc::declare::ClassDecl; use objc::runtime::{self, Class, Method, Object, Sel}; use cocoa::base::nil; use cocoa::foundation::NSString; pub fn init() -> bool { let superclass = Class::get("NSObject").unwrap(); let mut decl = ClassDecl::new("NSBu...
extern crate cocoa; #[macro_use] extern crate objc; use objc::declare::ClassDecl; use objc::runtime::{self, Class, Method, Object, Sel}; use cocoa::base::nil; use cocoa::foundation::NSString; pub fn init() -> bool { let superclass = Class::get("NSObject").unwrap(); let mut decl = ClassDecl::new("NSBu...
if let Some(ref image_data) = self.app_image { let img_cls = Class::get("NSImage").unwrap(); let image: *mut Object = msg_send![img_cls, alloc]; let image: *mut Object = match image_data { &NotificationImage::File(file) => msg_send![ ...
if let Some(ref image_data) = self.content_image { let img_cls = Class::get("NSImage").unwrap(); let image: *mut Object = msg_send![img_cls, alloc]; let image: *mut Object = match image_data { &NotificationImage::File(file) => msg_send![ ...
if_condition
[ { "content": "fn main() {\n\n let dir = get_dir();\n\n let image1 = dir.join(\"rust.png\");\n\n let image2 = dir.join(\"ferris.png\");\n\n\n\n // Call init so we get notifcations\n\n macos_notifications::init();\n\n\n\n // Construct and send a new notification\n\n Notification::new()\n\n ...
Rust
research/gaia-x/pegasus/pegasus/src/operator/iteration/switch.rs
bmmcq/GraphScope
a480d941f3a3f1270ddc0570e72059e6a34dab24
use std::rc::Rc; use crate::api::{IterCondition, Notification}; use crate::communication::input::{new_input_session, InputProxy}; use crate::communication::output::{new_output, OutputProxy}; use crate::communication::Output; use crate::config::LOOP_OPT; use crate::data::{MarkedData, MicroBatch}; use crate::errors::Job...
use std::rc::Rc; use crate::api::{IterCondition, Notification}; use crate::communication::input::{new_input_session, InputProxy}; use crate::communication::output::{new_output, OutputProxy}; use crate::communication::Output; use crate::config::LOOP_OPT; use crate::data::{MarkedData, MicroBatch}; use crate::errors::Job...
error_worker!("both data and signal empty of {:?}", dataset.tag); unreachable!("both data and signal empty of {:?}", dataset.tag); } } } Ok(()) }) } } fn switch<D: Data>( dataset: &mut MicroBatch<D>,...
} if let Some(end) = dataset.take_end() { let p = end.tag.to_parent_uncheck(); let mut ends = self .iter_scope .remove(&p) .expect("unknown iteration scope;"); ...
random
[ { "content": "pub fn u32_to_vec(x: u32) -> Vec<u8> {\n\n int_to_vec!(x, u32)\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/groot/src/db/common/bytes/transform.rs", "rank": 0, "score": 354433.37192331563 }, { "content": "/// Parses an escape sequence within a string literal....
Rust
2016/day14/src/main.rs
RussellChamp/AdventOfCode
492784bd690d7323990dcddd64b20459bf3263ae
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; #[derive(Debug)] struct Key { idx: u64, letters: Vec<char>, is_valid: bool, hash: String, } fn repeat_letters(line: &String, size: u64, only_first: bool) -> Vec<char> { let mut result: Vec<char> = vec![]; let mut count = 1...
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; #[derive(Debug)] struct Key { idx: u64, letters: Vec<char>, is_valid: bool, hash: String, } fn repeat_letters(line: &String, size: u64, only_first: bool) -> Vec<char> { let mut result: Vec<char> = vec![]; let mut count = 1...
E) { if keys.len() >= PAD_SIZE { println!("We're done! Finished on idx {}", idx); println!("The {}th key is {:?}", PAD_SIZE, keys.iter().nth(PAD_SIZE).unwrap()); } else { println!("Uh oh! We didn't find enough keys. :("); ...
function_block-function_prefixed
[ { "content": "fn build_maze(maze: &mut Vec<Vec<(bool, u32)>>, key: u32) {\n\n for row in 0..MAZE_HEIGHT {\n\n for col in 0..MAZE_WIDTH {\n\n match get_space(col as u32, row as u32, key) {\n\n Space::Open => maze[row][col] = (true, u32::max_value()),\n\n Space::...
Rust
bee-snapshot/src/lib.rs
neumoxx/bee-p
2a68c3c6c17bd2c8dd36d8274ef0db3a04d50b16
pub(crate) mod constants; pub(crate) mod pruning; pub(crate) mod worker; pub mod config; pub mod event; pub mod global; pub mod local; pub mod metadata; use bee_common::shutdown_stream::ShutdownStream; use bee_common_ext::{bee_node::BeeNode, event::Bus, shutdown_tokio::Shutdown, worker::Worker}; use bee_crypto::ter...
pub(crate) mod constants; pub(crate) mod pruning; pub(crate) mod worker; pub mod config; pub mod event; pub mod global; pub mod local; pub mod metadata; use bee_common::shutdown_stream::ShutdownStream; use bee_common_ext::{bee_node::BeeNode, event::Bus, shutdown_tokio::Shutdown, worker::Worker}; use bee_crypto::ter...
n( snapshot_worker_shutdown_tx, spawn(worker::SnapshotWorker::new(config.clone()).start( ShutdownStream::new(snapshot_worker_shutdown_rx, snapshot_worker_rx), bee_node, (), )), ); bus.add_listener(move |latest_solid_milestone: &LatestSolidMilestoneCha...
function_block-function_prefixed
[ { "content": "// TODO testing\n\npub fn get_new_solid_entry_points(target_index: MilestoneIndex) -> Result<DashMap<Hash, MilestoneIndex>, Error> {\n\n let solid_entry_points = DashMap::<Hash, MilestoneIndex>::new();\n\n for index in *target_index - SOLID_ENTRY_POINT_CHECK_THRESHOLD_PAST..*target_index {\n...
Rust
xtask/src/main.rs
dureuill/yew-sse-example
c1bbc94bbcbd91cb7a4b7ab3a3361514983ff1bf
use std::ops::Index; use cargo_metadata::camino::Utf8PathBuf; use cargo_metadata::Metadata; use clap::crate_version; use clap::Clap; use color_eyre::eyre::Context; use color_eyre::eyre::ContextCompat; use color_eyre::eyre::Result; use color_eyre::owo_colors::colors::xterm::UserGreen; use color_eyre::owo_colors::colors...
use std::ops::Index; use cargo_metadata::camino::Utf8PathBuf; use cargo_metadata::Metadata; use clap::crate_version; use clap::Clap; use color_eyre::eyre::Context; use color_eyre::eyre::ContextCompat; use color_eyre::eyre::Result; use color_eyre::owo_colors::colors::xterm::UserGreen; use color_eyre::owo_colors::colors...
println!( "- Copying backend to {}", output_dir.join("backend").bold().fg::<UserGreen>() ); std::fs::copy(backend_path, output_dir.join("backend")) .wrap_err("Copying the backend failed")?; Ok(()) }
if !errors.is_empty() { eprintln!( "{} Copy succeeded, but the following errors occurred during the copy:", "WARNING:".bold().fg::<UserYellow>() ); for error in errors { eprintln!("\t{}", error.fg::<UserYellow>()) } }
if_condition
[ { "content": "fn main() {\n\n yew::start_app::<Model>();\n\n}", "file_path": "frontend/src/main.rs", "rank": 9, "score": 69425.33094278068 }, { "content": "#[derive(Debug, Clone)]\n\nenum Message {\n\n Message(String),\n\n}\n\n\n", "file_path": "backend/src/main.rs", "rank": 10...
Rust
ndless-async/src/keypad.rs
jkcoxson/ndless-rs
6242bd3e08c8d6aeac419e19431acc91ba9c0ff1
use alloc::rc::{Rc, Weak}; use core::cell::{Ref, RefCell}; use core::future::Future; use core::mem; use core::pin::Pin; use core::task::{Context, Poll}; use core::time::Duration; use crossbeam_queue::ArrayQueue; use futures_util::{stream::Stream, task::AtomicWaker, StreamExt}; use ignore_result::Ignore; use ndless::...
use alloc::rc::{Rc, Weak}; use core::cell::{Ref, RefCell}; use core::future::Future; use core::mem; use core::pin::Pin; use core::task::{Context, Poll}; use core::time::Duration; use crossbeam_queue::ArrayQueue; use futures_util::{stream::Stream, task::AtomicWaker, StreamExt}; use ignore_result::Ignore; use ndless::...
pub fn stream_with_buffer(&self, size: usize) -> KeyStream { let mut queues = self.inner.queues.borrow_mut(); let queue = Rc::new(SharedKeyQueue { queue: ArrayQueue::new(size), waker: AtomicWaker::new(), }); queues.push(queue.clone()); KeyStream { queue, interval: self.interval...
pub fn stream(&self) -> KeyStream { let mut queues = self.inner.queues.borrow_mut(); let queue = Rc::new(SharedKeyQueue { queue: ArrayQueue::new(100), waker: AtomicWaker::new(), }); queues.push(queue.clone()); KeyStream { queue, interval: self.interval(), } }
function_block-full_function
[ { "content": "/// Returns true if the specific key is pressed.\n\n/// Note that you may pass either an owned [`Key`] or a borrowed [`&Key`][Key].\n\npub fn is_key_pressed(key: impl Borrow<Key>) -> bool {\n\n\tKEY_MAPPING\n\n\t\t.iter()\n\n\t\t.find(|(_, other)| other == key.borrow())\n\n\t\t.map_or(\n\n\t\t\tfa...
Rust
reql/src/cmd/do_.rs
kid/rethinkdb-rs
945e161aec8288fa4f915bc59bc0575438a1d4ae
use super::args::Args; use crate::{cmd, Command, Func}; use ql2::term::TermType; use serde::Serialize; pub trait Arg { fn arg(self, parent: Option<Command>) -> cmd::Arg<()>; } impl Arg for Command { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let cmd = Command::new(TermType::Funcall).with_...
use super::args::Args; use crate::{cmd, Command, Func}; use ql2::term::TermType; use serde::Serialize; pub trait Arg { fn arg(self, parent: Option<Command>) -> cmd::Arg<()>; } impl Arg for Command { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let cmd = Command::new(TermType::Funcall).with_...
} } impl<T> Arg for T where T: Serialize, { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { Command::from_json(self).arg(parent) } } impl Arg for Args<(Command, Command)> { fn arg(self, parent: Option<Command>) -> cmd::Arg<()> { let Args((arg, expr)) = self; expr.a...
match parent { Some(parent) => cmd.with_arg(parent).into_arg(), None => cmd.into_arg(), }
if_condition
[ { "content": "pub trait Arg {\n\n fn arg(self) -> cmd::Arg<()>;\n\n}\n\n\n\nimpl Arg for Command {\n\n fn arg(self) -> cmd::Arg<()> {\n\n Self::new(TermType::Or).with_arg(self).into_arg()\n\n }\n\n}\n", "file_path": "reql/src/cmd/or.rs", "rank": 0, "score": 216228.98313413086 }, ...
Rust
cranelift/codegen/src/isa/x64/abi.rs
jgouly/wasmtime-old
715ca4112a1bd187a32e8238e3bce2b5a2c9d635
#![allow(dead_code)] #![allow(non_snake_case)] use crate::ir; use crate::ir::types; use crate::ir::types::*; use crate::ir::StackSlot; use crate::ir::Type; use crate::isa; use crate::isa::x64::inst::*; use crate::isa::x64::*; use crate::machinst::*; use alloc::vec::Vec; use regalloc::{RealReg, Reg, RegClass, Set, ...
#![allow(dead_code)] #![allow(non_snake_case)] use crate::ir; use crate::ir::types; use crate::ir::types::*; use crate::ir::StackSlot; use crate::ir::Type; use crate::isa; use crate::isa::x64::inst::*; use crate::isa::x64::*; use crate::machinst::*; use alloc::vec::Vec; use regalloc::{RealReg, Reg, RegClass, Set, ...
fn get_intreg_for_arg_ELF(idx: usize) -> Option<Reg> { match idx { 0 => Some(reg_RDI()), 1 => Some(reg_RSI()), 2 => Some(reg_RDX()), 3 => Some(reg_RCX()), 4 => Some(reg_R8()), 5 => Some(reg_R9()), _ => None, } } fn get_intreg_for_retval_ELF(idx: usize) ...
fn in_int_reg(ty: types::Type) -> bool { match ty { types::I8 | types::I16 | types::I32 | types::I64 => true, types::B1 | types::B8 | types::B16 | types::B32 | types::B64 => true, _ => false, } }
function_block-full_function
[ { "content": "fn memarg_regs(memarg: &MemArg, used: &mut Set<Reg>, modified: &mut Set<Writable<Reg>>) {\n\n match memarg {\n\n &MemArg::Unscaled(reg, ..) | &MemArg::UnsignedOffset(reg, ..) => {\n\n used.insert(reg);\n\n }\n\n &MemArg::RegScaled(r1, r2, ..) => {\n\n ...
Rust
src/test/instruction_tests/instr_vfmsub213ss.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vfmsub213ss_1() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, ...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vfmsub213ss_1() { run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, ...
EBX, 1132410721, Some(OperandSize::Dword), None, )), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), ...
{ run_test( &Instruction { mnemonic: Mnemonic::VFMSUB213SS, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM4)), operand3: Some(Direct(XMM4)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Down), ...
random
[ { "content": "fn encode32_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
src/assets/texture.rs
jkugelman/roomdust
3b23685ab36b24dd76ba72f7ac099943e7bd4b5a
use std::collections::BTreeMap; use std::convert::TryInto; use std::ops::{Deref, Index}; use bytes::Buf; use crate::wad::{self, Lump, Wad}; #[derive(Clone, Debug)] pub struct TextureBank(BTreeMap<String, Texture>); impl TextureBank { pub fn load(wad: &Wad) -> wad::Result<Self> { let mut t...
use std::collections::BTreeMap; use std::convert::TryInto; use std::ops::{Deref, Index}; use bytes::Buf; use crate::wad::{self, Lump, Wad}; #[derive(Clone, Debug)] pub struct TextureBank(BTreeMap<String, Texture>); impl TextureBank { pub fn load(wad: &Wad) -> wad::Result<Self> { let mut t...
pub fn get(&self, name: &str) -> Option<&Texture> { self.0.get(&name.to_ascii_uppercase()) } } impl Index<&str> for TextureBank { type Output = Texture; fn index(&self, name: &str) -> &Self::Output { self.get(name).expect("texture not found") } } impl Deref for Texture...
p, offset.try_into().unwrap())?; textures.insert(texture.name.clone(), texture); } Ok(()) }
function_block-function_prefixed
[ { "content": "#[derive(Debug)]\n\nstruct LumpLocation {\n\n pub offset: usize,\n\n pub size: usize,\n\n pub name: String,\n\n}\n\n\n\nimpl WadFile {\n\n /// Loads a WAD file from disk.\n\n pub fn load(path: impl AsRef<Path>) -> wad::Result<Arc<Self>> {\n\n let path = path.as_ref();\n\n ...
Rust
src/dataflow-types/src/client/controller/storage.rs
pjmore/materialize
5a46f9b30910679d504c94438b1d1c5ace4e80c7
use std::collections::BTreeMap; use differential_dataflow::lattice::Lattice; use timely::progress::{Antichain, Timestamp}; use tracing::error; use super::SinceUpperMap; use crate::client::SourceConnector; use crate::client::{Client, Command, StorageCommand}; use crate::Update; use mz_expr::GlobalId; use mz_expr::Pa...
use std::collections::BTreeMap; use differential_dataflow::lattice::Lattice; use timely::progress::{Antichain, Timestamp}; use tracing::error; use super::SinceUpperMap; use crate::client::SourceConnector; use crate::client::{Client, Command, StorageCommand}; use crate::Update; use mz_expr::GlobalId; use mz_expr::Pa...
} None => { } } } for (id, (description, since)) in bindings.iter() { self.storage .source_descriptions .insert(*id, Some((description.clone(), since.clone()))); sel...
if prior_description != description_since { Err(StorageError::SourceIdReused(*id))? }
if_condition
[ { "content": "pub fn build_compression(cmd: &mut BuiltinCommand) -> Result<Compression, anyhow::Error> {\n\n match cmd.args.opt_string(\"compression\") {\n\n Some(s) => s.parse(),\n\n None => Ok(Compression::None),\n\n }\n\n}\n\n\n", "file_path": "src/testdrive/src/action/file.rs", "...
Rust
src/driver/text.rs
jutuon/vga
678dc64cf3cb3fd17fb5bd3ce6cdb92f10fab64c
use volatile::Volatile; use crate::io::{ VIDEO_RAM_START_ADDRESS, MemoryMappedIo, PortIo, }; use crate::raw::{ VgaRegisters, }; pub use vga_framebuffer::Colour; use vga_framebuffer::Char; pub const TEXT_BUFFER_FIST_BYTE_ADDRESS: usize = 0xB8000; pub const VIDEO_RAM_BYTES_BEFORE_TEXT: usize = TEX...
use volatile::Volatile; use crate::io::{ VIDEO_RAM_START_ADDRESS, MemoryMappedIo, PortIo, }; use crate::raw::{ VgaRegisters, }; pub use vga_framebuffer::Colour; use vga_framebuffer::Char; pub const TEXT_BUFFER_FIST_BYTE_ADDRESS: usize = 0xB8000; pub const VIDEO_RAM_BYTES_BEFORE_TEXT: usize = TEX...
rator<Item=VgaCharRefMut<'_>> { VgaCharRefMut::raw_slice_to_ref_mut_slice(self.raw_line) } pub fn iter(&self) -> impl Iterator<Item=VgaCharRef<'_>> { VgaCharRef::raw_slice_to_ref_slice(self.raw_line) } pub fn write_line<'a, T: Into<VgaCharLine<'a>>>(&mut self, src: T) { for (sr...
-> VgaChar { self.vga_chars().nth(character_i).unwrap().read() } pub fn write_char(&mut self, character_i: usize, vga_char: VgaChar) { self.vga_chars_mut().nth(character_i).unwrap().write(vga_char) } pub fn clear_screen(&mut self, value: VgaChar) { for mut vga_char in self...
random
[ { "content": " pub trait RegisterRelIoW<T: RegisterGroup, U: Sized> {\n\n fn write(&mut self, rel_address: u16, value: U);\n\n }\n", "file_path": "src/raw/generated.rs", "rank": 0, "score": 79613.21741051001 }, { "content": " pub trait RegisterAbsIoW<T: RegisterGroup, U: Size...
Rust
src/lib/fixture_tests.rs
loalang/loalang
745edc192564b3f362ad1623fbb8853fcefa876e
use crate::optimization::Optimizable; use crate::*; use serde::Deserialize; extern crate serde_yaml; extern crate simple_logging; #[derive(Deserialize)] struct FixtureConfig { main_class: Option<String>, expected: FixtureExpectations, } #[derive(Deserialize)] struct FixtureExpectations { success: bool, ...
use crate::optimization::Optimizable; use crate::*; use serde::Deserialize; extern crate serde_yaml; extern crate simple_logging; #[derive(Deserialize)] struct FixtureConfig { main_class: Option<String>, expected: FixtureExpectations, } #[derive(Deserialize)] struct FixtureExpectations { success: bool, ...
n(); ( comment.span.start.line, comment.span.start.uri.clone(), &comment.lexeme()[4..], ) == ( d_span.start.line, d_span.start.uri.clone(), diagnostic.to_string().as_str(), ) }
function_block-function_prefixed
[ { "content": "pub fn is_valid_symbol(string: &String) -> bool {\n\n let source = Source::new(SourceKind::Module, URI::Exact(\"tmp\".into()), string.clone());\n\n let tokens = tokenize(source);\n\n\n\n tokens.len() == 2 && matches!(tokens[0].kind, TokenKind::SimpleSymbol(_))\n\n}\n\n\n", "file_path"...
Rust
src/api/process/process.rs
DaanA32/lunatic
b7dc3f98e10c50337526f8a42cb39032f7b4b9be
use anyhow::Result; use async_wormhole::{ stack::{OneMbStack, Stack}, AsyncWormhole, AsyncYielder, }; use lazy_static::lazy_static; use smol::{Executor as TaskExecutor, Task}; use uptown_funk::{Executor, FromWasm, HostFunctions, ToWasm}; use crate::module::{LunaticModule, Runtime}; use crate::{ api::{chann...
use anyhow::Result; use async_wormhole::{ stack::{OneMbStack, Stack}, AsyncWormhole, AsyncYielder, }; use lazy_static::lazy_static; use smol::{Executor as TaskExecutor, Task}; use uptown_funk::{Executor, FromWasm, HostFunctions, ToWasm}; use crate::module::{LunaticModule, Runtime}; use crate::{ api::{chann...
pub async fn create( context_receiver: Option<ChannelReceiver>, module: LunaticModule, function: FunctionLookup, memory: MemoryChoice, profiler: <HeapProfilerState as HostFunctions>::Wrap, ) -> Result<()> { let api = crate::api::default::DefaultApi::new(con...
let func = instance.get_func(name).ok_or_else(|| { anyhow::Error::msg(format!( "No function {} in wasmtime instance", name )) })?; ...
function_block-function_prefix_line
[ { "content": "/// Adds WASM functions required by the stdlib implementation:\n\n/// * `lunatic_spawn_by_index(i32)`\n\n/// - receives the index of the function (in the table) to be called indirectly.\n\npub fn patch(module: &mut Module) -> Result<()> {\n\n if let Some(main_function_table) = module.tables.m...
Rust
connectorx/src/s3.rs
Yizhou150/connector-x
3c56c539d29bc252d205a20700edd63efec301ab
use anyhow::Error; use arrow::datatypes::{Schema, SchemaRef}; use arrow::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; use arrow::json::reader::ReaderBuilder; use arrow::record_batch::RecordBatch; use fehler::throws; use flate2::read::GzDecoder; use futures::stream::{FuturesOrdered, StreamExt}; use futures::TryFutureExt; use...
use anyhow::Error; use arrow::datatypes::{Schema, SchemaRef}; use arrow::ffi::{FFI_ArrowArray, FFI_ArrowSchema}; use arrow::js
um::EnumString; use tokio::io::AsyncReadExt; use tokio::task::spawn_blocking; #[derive(Debug, Clone, Copy, EnumString)] pub enum JsonFormat { JsonL, Array, } #[throws(Error)] pub async fn read_s3<S>( bucket: &str, objects: &[S], schema: &str, json_format: JsonFormat, ) -> HashMap<String, Vec<(...
on::reader::ReaderBuilder; use arrow::record_batch::RecordBatch; use fehler::throws; use flate2::read::GzDecoder; use futures::stream::{FuturesOrdered, StreamExt}; use futures::TryFutureExt; use rusoto_core::Region; use rusoto_s3::{GetObjectOutput, GetObjectRequest, S3Client, S3}; use serde_json::{from_str, Value}; use...
random
[ { "content": "use super::{Consume, Destination, DestinationPartition};\n\nuse crate::data_order::DataOrder;\n\nuse crate::dummy_typesystem::DummyTypeSystem;\n\nuse crate::errors::{ConnectorAgentError, Result};\n\nuse crate::typesystem::{Realize, TypeAssoc, TypeSystem};\n\nuse anyhow::anyhow;\n\nuse arrow::datat...
Rust
rpc/src/streaming.rs
jjs-dev/commons
f53ebfa3bd973aa711f79f4d824fa297ac21b1ad
use futures_util::StreamExt; use std::{convert::Infallible, marker::PhantomData, pin::Pin}; use tokio::io::AsyncBufReadExt; pub struct Streaming<E, F>(Infallible, PhantomData<(E, F)>); impl<E, F> crate::Direction for Streaming<E, F> where E: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static, ...
use futures_util::StreamExt; use std::{convert::Infallible, marker::PhantomData, pin::Pin}; use tokio::io::AsyncBufReadExt; pub struct Streaming<E, F>(Infallible, PhantomData<(E, F)>); impl<E, F> crate::Direction for Streaming<E, F> where E: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static, ...
} #[derive(Debug, thiserror::Error)] pub enum SendError { #[error("serialization failed")] Serialize(serde_json::Error), #[error("data not sent to client")] Network(hyper::Error), } impl<E: serde::Serialize, F: serde::Serialize> StreamingTx<E, F> { async fn priv_send(&mut self, item: Item<E, F>) ...
fn send_batch(mut self, mut batch: Self::BatchData) -> Self::BatchFuture { Box::pin(async move { while let Some(event) = batch.0.next().await { self.send_event(event).await?; } self.finish(batch.1).await }) }
function_block-function_prefix_line
[ { "content": "/// Creates new channel, returning one sender and one receiver.\n\n/// Other can be created using `Clone::clone`\n\npub fn channel<T: Send + 'static>() -> (Sender<T>, Receiver<T>) {\n\n let inner = Inner {\n\n q: Mutex::new(Queue {\n\n values: VecDeque::new(),\n\n w...
Rust
tests/parse_test.rs
msanou/crystallake
f72eada9f9ea3dbb6846a8549095394f90959108
extern crate crystalrake; use crystalrake::json::*; #[test] fn true_value() { let t = "true".parse::<JsonValue>(); if let Ok(JsonValue::Boolean(b)) = t { assert!(b, "expect true, but {}", b); } else { panic!("unexpect value : {:?}", t); } } #[test] fn true_string() { let t = "...
extern crate crystalrake; use crystalrake::json::*; #[test] fn true_value() { let t = "true".parse::<JsonValue>(); if let Ok(JsonValue::Boolean(b)) = t { assert!(b, "expect true, but {}", b); } else { panic!("unexpect value : {:?}", t); } } #[test] fn true_string() { let t = "...
fn contain_emoji() { let json_value = r#""\uD83D\uDE04\uD83D\uDE07\uD83D\uDC7A""#.parse::<JsonValue>(); if let Ok(JsonValue::String(v)) = json_value { assert_eq!(v, r#"😄😇👺"#.to_string()); } else { panic!("unexpect value : {:?}", json_value); } }
function_block-function_prefix_line
[ { "content": "#[test]\n\n#[allow(overflowing_literals)]\n\nfn simple_deserialize() {\n\n let a : A = \"1000000000000000\".parse::<JsonValue>().unwrap().deserialize().unwrap();\n\n assert_eq!(a, A::new(1000000000000000));\n\n}", "file_path": "tests/deserialize_test.rs", "rank": 15, "score": 473...
Rust
src/chopper/types.rs
snaar/drat
8c9c1e2e413d8a93f3fd50df852915a27cb37e6f
use std::cmp::Ordering; use std::fmt; use ndarray::ArrayD; use crate::chopper::error::{Error, Result}; use crate::util::timestamp_util; use crate::util::tz::ChopperTz; pub type ChainId = usize; pub type NodeId = usize; pub type Nanos = u64; #[derive(Copy, Clone)] pub struct TimestampRange { pub begin: Option<N...
use std::cmp::Ordering; use std::fmt; use ndarray::ArrayD; use crate::chopper::error::{Error, Result}; use crate::util::timestamp_util; use crate::util::tz::ChopperTz; pub type ChainId = usize; pub type NodeId = usize; pub type Nanos = u64; #[derive(Copy, Clone)] pub struct TimestampRange { pub begin: Option<N...
} pub fn string_field_to_string(&self) -> Result<&str> { if let FieldValue::String(string) = self { Ok(string) } else { Err(Error::from("expected FieldValue::String")) } } pub fn matches_field_type(&self, field_type: FieldType) -> bool { let sel...
if let FieldValue::String(string) = self { let float = string.parse::<f64>().unwrap(); Ok(float) } else { Err(Error::from("expected FieldValue::String")) }
if_condition
[]
Rust
pallets/worker/src/prover.rs
edgeware-builders/substrate-eth-light-client
acdfa163ccbb1ccfb3b7f4681bd1ec05d706cd07
#![cfg_attr(not(feature = "std"), no_std)] use crate::*; use rlp::Rlp; pub trait Prover { fn extract_nibbles(a: Vec<u8>) -> Vec<u8>; fn concat_nibbles(a: Vec<u8>) -> Vec<u8>; fn assert_ethclient_hash( block_number: u64, expected_block_hash: H256, ) -> bool; fn verify_log_entry( ...
#![cfg_attr(not(feature = "std"), no_std)] use crate::*; use rlp::Rlp; pub trait Prover { fn extract_nibbles(a: Vec<u8>) -> Vec<u8>; fn concat_nibbles(a: Vec<u8>) -> Vec<u8>; fn assert_ethclient_hash( block_number: u64, expected_block_hash: H256, ) -> bool; fn verify_log_entry( ...
fn assert_ethclient_hash( block_number: u64, expected_block_hash: H256, ) -> bool { match Self::block_hash_safe(block_number) { Some(hash) => hash == expected_block_hash, None => false, } } fn verify_log_entry( log_index: u64, lo...
r() .enumerate() .filter(|(i, _)| i % 2 == 0) .zip(a.iter().enumerate().filter(|(i, _)| i % 2 == 1)) .map(|((_, x), (_, y))| (x << 4) | y) .collect() }
function_block-function_prefixed
[ { "content": "/// This pallet's configuration trait\n\npub trait Config: system::Config + CreateSignedTransaction<Call<Self>> {\n\n /// The identifier type for an offchain worker.\n\n type AuthorityId: AppCrypto<Self::Public, Self::Signature>;\n\n\n\n /// The overarching event type.\n\n type Event: ...
Rust
src/year2018/day10.rs
CraZySacX/aoc
c96faf4c3fb0f39db0c2f5b573a307e5c779e421
use error::Result; use regex::Regex; use std::io::BufRead; pub fn find_solution<T: BufRead>(reader: T, _second_star: bool) -> Result<u32> { println!("{}", align(reader, false)?); Ok(0) } fn align<T: BufRead>(reader: T, test: bool) -> Result<String> { let line_re = Regex::new(r"position=<(.*), (.*)> velo...
use error::Result; use regex::Regex; use std::io::BufRead; pub fn find_solution<T: BufRead>(reader: T, _second_star: bool) -> Result<u32> { println!("{}", align(reader, false)?); Ok(0) } fn align<T: BufRead>(reader: T, test: bool) -> Result<String> { let line_re = Regex::new(r"position=<(.*), (.*)> velo...
#[cfg(test)] mod one_star { use super::align; use error::Result; use std::io::Cursor; const TEST_CHAIN: &str = r"position=< 9, 1> velocity=< 0, 2> position=< 7, 0> velocity=<-1, 0> position=< 3, -2> velocity=<-1, 1> position=< 6, 10> velocity=<-2, -1> position=< 2, -4> velocity=< 2, 2> position...
if star.0 > max_x { max_x = star.0; } if star.1 < min_y { min_y = star.1; } if star.1 > max_y { max_y = star.1; } } for y in min_y..=max_y { for x in min_x..=max_x { let mut found_star = false; for sta...
function_block-function_prefix_line
[ { "content": "fn lca<T: BufRead>(reader: T, max_i: usize, max_j: usize, _second_star: bool, test: bool) -> Result<Array2<char>> {\n\n let mut lca = Array2::<char>::default((max_i, max_j));\n\n\n\n for (j, line) in reader.lines().filter_map(|x| x.ok()).enumerate() {\n\n for (i, ch) in line.chars().e...
Rust
src/endian/write.rs
zaksabeast/no_std_io
092305d45807619ad35a5bb89f3396f562c27f13
use crate::Error; use core::mem; pub trait EndianWrite { fn get_size(&self) -> usize; fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error>; fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error>; } impl EndianWrite for bool { #[inline(always)] fn get_size...
use crate::Error; use core::mem; pub trait EndianWrite { fn get_size(&self) -> usize; fn try_write_le(&self, dst: &mut [u8]) -> Result<usize, Error>; fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error>; } impl EndianWrite for bool { #[inline(always)] fn get_size...
); } let bytes = self.to_le_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } #[inline(always)] fn try_write_be(&self, dst: &mut [u8]) -> Result<usize, Error> { let byte_count = mem::size_of::<u64>(); if byte_count > dst.len() { ...
wanted_size: byte_count, offset: 0, data_len: dst.len(), }); } let bytes = self.to_be_bytes(); dst[..byte_count].copy_from_slice(&bytes); Ok(bytes.len()) } } impl EndianWrite for i8 { #[inline(always)] fn get_size(&sel...
random
[ { "content": "#[test]\n\nfn should_error_if_there_are_not_enough_bytes() {\n\n let bytes = vec![0xaa, 0xbb, 0xcc, 0xdd];\n\n let result = bytes\n\n .read_le::<Test>(0)\n\n .expect_err(\"This should have failed\");\n\n assert_eq!(\n\n result,\n\n Error::InvalidSize {\n\n ...
Rust
src/flows_node.rs
maidsafe/routing_model
97f11a3dda8a6ff12a4db19b2096867ec9fa2d59
use crate::{ state::JoiningState, utilities::{ GenesisPfxInfo, LocalEvent, Name, ProofRequest, RelocatedInfo, Rpc, TryResult, WaitedEvent, }, }; use unwrap::unwrap; #[derive(Debug, PartialEq)] pub struct JoiningRelocateCandidate<'a>(pub &'a mut JoiningState); impl<'a> JoiningRelocateCandidate<'a...
use crate::{ state::JoiningState, utilities::{ GenesisPfxInfo, LocalEvent, Name, ProofRequest, RelocatedInfo, Rpc, TryResult, WaitedEvent, }, }; use unwrap::unwrap; #[derive(Debug, PartialEq)] pub struct JoiningRelocateCandidate<'a>(pub &'a mut JoiningState); impl<'a> JoiningRelocateCandidate<'a...
fn exit(&mut self, info: GenesisPfxInfo) { self.0.join_routine.routine_complete_output = Some(info); } fn discard(&mut self) {} fn send_next_proof_response(&mut self, source: Name) { if let Some(next_part) = self.0.action.get_next_resource_proof_part(source) { self.0 ...
andled } LocalEvent::JoiningTimeoutResendInfo => { self.connect_or_send_candidate_info(); TryResult::Handled } _ => TryResult::Unhandled, } }
function_block-function_prefixed
[ { "content": "fn process_events(mut state: MemberState, events: &[Event]) -> MemberState {\n\n for event in events.iter().cloned() {\n\n if TryResult::Unhandled == state.try_next(event) {\n\n state.failure_event(event);\n\n }\n\n\n\n if state.failure.is_some() {\n\n ...
Rust
src/adapters/twitter.rs
w3f/polkadot-registrar-bot
3c5aa36cf5de8edae0ac434947eb585b7ca92c75
use crate::adapters::Adapter; use crate::primitives::{ExternalMessage, ExternalMessageType, MessageId, Timestamp}; use crate::Result; use hmac::{Hmac, Mac}; use rand::{thread_rng, Rng}; use reqwest::header::{self, HeaderValue}; use reqwest::{Client, Request}; use serde::de::DeserializeOwned; use serde::Serialize; use s...
use crate::adapters::Adapter; use crate::primitives::{ExternalMessage, ExternalMessageType, MessageId, Timestamp}; use crate::Result; use hmac::{Hmac, Mac}; use rand::{thread_rng, Rng}; use reqwest::header::{self, HeaderValue}; use reqwest::{Client, Request}; use serde::de::DeserializeOwned; use serde::Serialize; use s...
} #[derive(Debug, Deserialize, Serialize)] struct ApiMessageRequest { events: Vec<ApiEvent>, } #[derive(Debug, Deserialize, Serialize)] struct ApiEvent { #[serde(rename = "type")] t_type: String, id: String, created_timestamp: Option<String>, message_create: ApiMessageCreate, } #[derive(Debu...
into_iter() .map(|obj| (obj.id, format!("@{}", obj.screen_name.to_lowercase()))) .collect()) }
function_block-function_prefix_line
[ { "content": "fn try_decode_hex(display_name: &mut String) {\n\n if display_name.starts_with(\"0x\") {\n\n // Might be a false positive. Leave it as is if it cannot be decoded.\n\n if let Ok(name) = hex::decode(&display_name[2..]) {\n\n if let Ok(name) = String::from_utf8(name) {\n\n...
Rust
simulator/src/memory.rs
Laegluin/mikrorechner
7e5e878072c941e422889465c43dea838b83e5fd
use crate::vm; use byteorder::{ByteOrder, LittleEndian}; use rand; use std::cmp::min; use std::mem; use std::ptr; pub type Word = u32; pub const WORD_BYTES: Word = mem::size_of::<Word>() as Word; pub const WORD_BITS: Word = WORD_BYTES * 8; pub const OP_CODE_BITS: Word = 5; pub const REG_REF_BITS: Word = 6; const WRIT...
use crate::vm; use byteorder::{ByteOrder, LittleEndian}; use rand; use std::cmp::min; use std::mem; use std::ptr; pub type Word = u32; pub const WORD_BYTES: Word = mem::size_of::<Word>() as Word; pub const WORD_BITS: Word = WORD_BYTES * 8; pub const OP_CODE_BITS: Word = 5; pub const REG_REF_BITS: Word = 6; const WRIT...
pub fn store_word(&mut self, addr: Word, value: Word) -> Result<(), vm::ErrorKind> { let mut bytes = [0; WORD_BYTES as usize]; LittleEndian::write_u32(&mut bytes, value); self.store(addr, &bytes, Access::Protected) } pub fn store(&mut self, addr: Word, buf...
pub fn new() -> Memory { Memory { init_value: rand::random(), page_table: Level2Table::empty(), } }
function_block-full_function
[ { "content": "pub fn to_hex(word: Word) -> String {\n\n let width = WORD_BYTES as usize * 2 + 2;\n\n format!(\"{:#0width$x}\", word, width = width)\n\n}\n\n\n", "file_path": "simulator/src/support.rs", "rank": 0, "score": 217301.66889780847 }, { "content": "struct Instruction(u32);\n\n...
Rust
examples/minijava/src/enumabsyn.rs
chuckcscccl/rustlr
0e9794cca27589c25115325f69fb5b417a77400d
/* Abstract syntax for minijava (adopted from 2014 java program) Using internally generated RetTypeEnum */ #![allow(dead_code)] use rustlr::LBox; use crate::Expr::*; use crate::Stat::*; use crate::Declaration::*; #[derive(Debug)] pub enum Expr<'t> { Int(i32), Strlit(&'t str), Bool(bool), Var(&'t str), ...
/* Abstract syntax for minijava (adopted from 2014 java program) Using internally generated RetTypeEnum */ #![allow(dead_code)] use rustlr::LBox; use crate::Expr::*; use crate::Stat::*; use crate::Declaration::*; #[derive(Debug)] pub enum Expr<'t> { Int(i32), Strlit(&'t str), Bool(bool), Var(&'t str), ...
rs.push(dec.transfer(vdec)); }, Mdec(md) => { let mdec = std::mem::replace(md,MethodDec::default()); mths.push(dec.transfer(mdec)); }, _ => {}, } } }
function_block-function_prefixed
[ { "content": "pub fn parse_train_with<'lt>(parser:&mut ZCParser<RetTypeEnum<'lt>,Program<'lt>>, lexer:&mut mjenumlexer<'lt>, parserpath:&str) -> Result<Program<'lt>,Program<'lt>>\n\n{\n\n if let RetTypeEnum::Enumvariant_0(_xres_) = parser.parse_train(lexer,parserpath) {\n\n if !parser.error_occurred() {Ok(...
Rust
src/main.rs
zxrs/pinion
95a7e624b40040e4b208731bb6c3e06b6950612f
#![windows_subsystem = "windows"] use anyhow::{ensure, Error, Result}; use image::{self, imageops, GenericImageView}; use std::char::{decode_utf16, REPLACEMENT_CHARACTER}; use std::env; use std::mem; use std::ptr; use std::slice; use winapi::{ ctypes::c_void, shared::{ minwindef::{HIWORD, LOWORD, LPARA...
#![windows_subsystem = "windows"] use anyhow::{ensure, Error, Result}; use image::{self, imageops, GenericImageView}; use std::char::{decode_utf16, REPLACEMENT_CHARACTER}; use std::env; use std::mem; use std::ptr; use std::slice; use winapi::{ ctypes::c_void, shared::{ minwindef::{HIWORD, LOWORD, LPARA...
fn msg_box(e: Error) { unsafe { MessageBoxW( H_WINDOW, l(&e.to_string()).as_ptr(), l("Error").as_ptr(), MB_OK, ) }; } fn l(source: &str) -> Vec<u16> { source.encode_utf16().chain(Some(0)).collect() } fn decode(source: &[u16]) -> String { ...
TRUCT>(); let hdc = BeginPaint(h_wnd, &mut ps); let mut bi = zeroed::<BITMAPINFO>(); bi.bmiHeader = zeroed::<BITMAPINFOHEADER>(); bi.bmiHeader.biSize = mem::size_of::<BITMAPINFOHEADER>() as u32; bi.bmiHeader.biWidth = WIDTH; bi.bmiHeader.biHeight = -HEIGHT; bi.bmiHeader.biPlanes = 1; bi...
function_block-function_prefixed
[ { "content": "# pinion\n\nAn image viewer sample application for Windows written in Rust.\n", "file_path": "README.md", "rank": 18, "score": 3.0048466812659997 } ]
Rust
changeforest-py/src/control.rs
mlondschien/changeforest
4188ba4de34e05214a8cf6a3bb88912067695c14
use biosphere::MaxFeatures; use changeforest::Control; use pyo3::exceptions; use pyo3::prelude::{pyclass, FromPyObject, PyAny, PyErr, PyResult}; use pyo3::prelude::{PyObject, Python}; pub fn control_from_pyobj(py: Python, obj: Option<PyObject>) -> PyResult<Control> { let mut control = Control::default(); if l...
use biosphere::MaxFeatures; use changeforest::Control; use pyo3::exceptions; use pyo3::prelude::{pyclass, FromPyObject, PyAny, PyErr, PyResult}; use pyo3::prelude::{PyObject, Python}; pub fn control_from_pyobj(py: Python, obj: Option<PyObject>) -> PyResult<Control> { let mut control = Control::default(); if l...
control.random_forest_parameters.with_n_jobs(value); } }; } Ok(control) } #[pyclass(name = "MaxFeatures")] pub struct PyMaxFeatures { pub value: MaxFeatures, } impl PyMaxFeatures { fn new(value: MaxFeatures) -> Self { PyMaxFeatures { value } } } impl FromPyObj...
control.random_forest_parameters = control.random_forest_parameters.with_seed(value); } }; if let Ok(pyvalue) = obj.getattr(py, "seeded_segments_alpha") { if let Ok(value) = pyvalue.extract::<f64>(py) { control = control.with_seeded_s...
function_block-random_span
[ { "content": "pub fn changeforest(\n\n X: &ndarray::ArrayView2<'_, f64>,\n\n method: &str,\n\n segmentation_type: &str,\n\n control: &Control,\n\n) -> BinarySegmentationResult {\n\n let segmentation_type_enum: SegmentationType;\n\n let mut tree: BinarySegmentationTree;\n\n\n\n if segmentati...
Rust
src/tokenstream.rs
nikodemus/foolang
f8d824a8d7ef5ef828911a8b4d0d6419ad29bf6e
use crate::source_location::Span; use crate::unwind::Unwind; #[allow(non_camel_case_types)] #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum Token { EOF, HEX_INTEGER, BIN_INTEGER, DEC_INTEGER, SINGLE_FLOAT, DOUBLE_FLOAT, BLOCK_COMMENT, COMMENT, BLOCK_STRING, STRING, ...
use crate::source_location::Span; use crate::unwind::Unwind; #[allow(non_camel_case_types)] #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] pub enum Token { EOF, HEX_INTEGER, BIN_INTEGER, DEC_INTEGER, SINGLE_FLOAT, DOUBLE_FLOAT, BLOCK_COMMENT, COMMENT, BLOCK_STRING, STRING, ...
fn consume(&mut self, target: &str) -> usize { assert!(self.at_str(target)); let p = self.pos(); self.reset(p + target.len()); return p; } fn reset(&mut self, position: usize) { self.offset = position; self.indices = std::cell::RefCell::new(self.source[posi...
fn next(&mut self) -> usize { let p = self.pos(); self.current = match self.indices.borrow_mut().next() { Some((p, ch)) => (p + self.offset, ch), None => (self.len(), '.'), }; return p; }
function_block-full_function
[ { "content": "fn _append_context_line(context: &mut String, lineno: usize, line: &str) {\n\n if lineno == 0 {\n\n context.push_str(format!(\" {}\\n\", line).as_str());\n\n } else {\n\n context.push_str(format!(\"{:03} {}\\n\", lineno, line).as_str());\n\n }\n\n}\n", "file_path": "s...
Rust
crates/lib/kajiya-backend/src/shader_compiler.rs
MrBenj4min/kajiya
fdf3a4e11ef0d4bfd5d177396fc9d674b5b8317a
use crate::file::LoadFile; use anyhow::{anyhow, bail, Context, Result}; use bytes::Bytes; use relative_path::RelativePathBuf; use std::{path::PathBuf, sync::Arc}; use turbosloth::*; pub struct CompiledShader { pub name: String, pub spirv: Bytes, } #[derive(Clone, Hash)] pub struct CompileShader { pub path...
use crate::file::LoadFile; use anyhow::{anyhow, bail, Context, Result}; use bytes::Bytes; use relative_path::RelativePathBuf; use std::{path::PathBuf, sync::Arc}; use turbosloth::*; pub struct CompiledShader { pub name: String, pub spirv: Bytes, } #[derive(Clone, Hash)] pub struct CompileShader { pub path...
} pub struct RayTracingShader { pub name: String, pub spirv: Bytes, } #[derive(Clone, Hash)] pub struct CompileRayTracingShader { pub path: PathBuf, } #[async_trait] impl LazyWorker for CompileRayTracingShader { type Output = Result<RayTracingShader>; async fn run(self, ctx: RunContext) -> Self...
async fn run(self, ctx: RunContext) -> Self::Output { let ext = self .path .extension() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| "".to_string()); let name = self .path .file_stem() .map(|s| s.to_stri...
function_block-full_function
[ { "content": "pub fn normalized_path_from_vfs(path: impl Into<PathBuf>) -> anyhow::Result<PathBuf> {\n\n let path = path.into();\n\n\n\n for (mount_point, mounted_path) in VFS_MOUNT_POINTS.lock().iter() {\n\n if let Ok(rel_path) = path.strip_prefix(mount_point) {\n\n return Ok(mounted_pa...
Rust
physx/src/aggregate.rs
FredrikNoren/physx-rs
92a09a98f3825d52c84d487d0fc575fb8cf04feb
use crate::{ actor::{Actor, ActorMap}, articulation::Articulation, articulation_base::ArticulationBase, articulation_link::ArticulationLink, articulation_reduced_coordinate::ArticulationReducedCoordinate, base::Base, bvh_structure::BvhStructure, owner::Owner, rigid_actor::RigidActor,...
use crate::{ actor::{Actor, ActorMap}, articulation::Articulation, articulation_base::ArticulationBase, articulation_link::ArticulationLink, articulation_reduced_coordinate::ArticulationReducedCoordinate, base::Base, bvh_structure::BvhStructure, owner::Owner, rigid_actor::RigidActor,...
fn get_max_nb_actors(&self) -> u32 { unsafe { PxAggregate_getMaxNbActors(self.as_ptr()) } } fn get_nb_actors(&self) -> u32 { unsafe { PxAggregate_getNbActors(self.as_ptr()) } } fn get_self_collision(&self) -> bool { unsafe { PxAggregate_getSelfCollision(sel...
unsafe { let len = PxAggregate_getActors( self.as_mut_ptr(), buffer.as_mut_ptr() as *mut *mut physx_sys::PxActor, capacity, 0, ); buffer.set_len(len as usize); } buffer }
function_block-function_prefix_line
[ { "content": "pub fn PxAggregate_addActor_mut(self_: *mut PxAggregate, actor: *mut PxActor, bvhStructure: *const PxBVHStructure, ) -> bool;\n", "file_path": "physx-sys/src/physx_generated.rs", "rank": 0, "score": 550958.7046268866 }, { "content": "pub fn PxAggregate_removeArticulation_mut(se...
Rust
crates/aleph-target-build/src/platform.rs
nathanvoglsam/aleph
00f12548f7f50ade0f60343b6c5001bc0ddde6cd
#[derive(Copy, Clone, PartialEq, Debug)] pub enum Platform { UniversalWindowsGNU, UniversalWindowsMSVC, WindowsGNU, WindowsMSVC, Linux, Android, Unknown, } impl Platform { pub fn print_host_cargo_cfg(self) { match self { Platform::UniversalWindowsGNU => { ...
#[derive(Copy, Clone, PartialEq, Debug)] pub enum Platform { UniversalWindowsGNU, UniversalWindowsMSVC, WindowsGNU, WindowsMSVC, Linux, Android, Unknown, } impl Platform { pub fn print_host_cargo_cfg(self) { match self { Platform::UniversalWindowsGNU => { ...
} else { Platform::Unknown } } else if target.contains("android") { Platform::Android } else if target.contains("linux") { Platform::Linux } else { Platform::Unknown } }
t fn is_gnu(self) -> bool { match self { Platform::WindowsGNU => true, Platform::UniversalWindowsGNU => true, _ => false, } } pub const fn is_android(self) -> bool { match self { Platform::Android => true, _ => false, }...
random
[ { "content": "///\n\n/// Gets the vendor string for the current CPU\n\n///\n\n/// # Warning\n\n///\n\n/// At the moment this only works on x86 and x86_64. Otherwise it will just return an \"Unknown CPU\n\n/// Vendor\" string.\n\n///\n\npub fn cpu_vendor() -> &'static str {\n\n CPU_VENDOR_STRING.as_str()\n\n}...
Rust
desktop/src/gui/styles.rs
koompi/koompi-desktop
497a16b68befd3e99cd75169f4d7800312bde2e8
use iced::{button, container, slider, checkbox, pick_list, Color, Vector}; pub const BACKGROUND: Color = Color::from_rgb(238.0 / 255.0, 238.0 / 255.0, 238.0 / 255.0); pub const FOREGROUND: Color = Color::from_rgb(224.0 / 255.0, 224.0 / 255.0, 224.0 / 255.0); pub const HOVERED: Color = Color::from_rgb(66.0 / 255.0, 66....
use iced::{button, container, slider, checkbox, pick_list, Color, Vector}; pub const BACKGROUND: Color = Color::from_rgb(238.0 / 255.0, 238.0 / 255.0, 238.0 / 255.0); pub const FOREGROUND: Color = Color::from_rgb(224.0 / 255.0, 224.0 / 255.0, 224.0 / 255.0); pub const HOVERED: Color = Color::from_rgb(66.0 / 255.0, 66....
struct ContainerFill(pub Color); impl container::StyleSheet for ContainerFill { fn style(&self) -> container::Style { container::Style { background: Some(self.0.into()), ..container::Style::default() } } }
tainer::Style { use CustomContainer::*; container::Style { background: Some(match self { Foreground => FOREGROUND, }.into()), border_...
random
[ { "content": "pub fn search() -> Text {\n\n icon('\\u{f002}')\n\n}\n\n\n", "file_path": "panel/src/views/common.rs", "rank": 0, "score": 132919.60925981292 }, { "content": "pub fn wifi() -> Text {\n\n icon('\\u{f1eb}')\n\n}\n", "file_path": "panel/src/views/common.rs", "rank": ...
Rust
src/models.rs
Roba1993/SPE3D
b453ef33a6fc0adfc042784034634aa75e459573
use crate::error::*; use std::sync::atomic::{AtomicUsize, Ordering}; use dlc_decrypter::DlcPackage; use std::sync::{Arc, RwLock, Mutex}; use std::sync::mpsc::{Sender, Receiver}; use std::fs::File; use std::io::prelude::*; use crate::bus::{MessageBus, Message}; use std::thread; static IDCOUNTER: AtomicUsize = AtomicU...
use crate::error::*; use std::sync::atomic::{AtomicUsize, Ordering}; use dlc_decrypter::DlcPackage; use std::sync::{Arc, RwLock, Mutex}; use std::sync::mpsc::{Sender, Receiver}; use std::fs::File; use std::io::prelude::*; use crate::bus::{MessageBus, Message}; use std::thread; static IDCOUNTER: AtomicUsize = AtomicU...
} }); Ok(d_list) } pub fn set_status(&self, id: usize, status: &FileStatus) -> Result<()> { { let mut dloads = self.downloads.write()?; match dloads.iter().find(|i| i.id() == id) { Some(_) => { ...
}; match d_list.load() { Ok(_) => {}, Err(_) => {println!("Can't read previus status of the download list")} }; let d_list_internal = d_list.clone(); thread::spawn(move || loop { match d_list_internal.handle_msg() { ...
function_block-random_span
[ { "content": "/// Trait to write a stream of data to a file.\n\npub trait FileWriter : Read {\n\n /// Function to write a stream of data, to a file\n\n /// based on the std::io::Read trait. This functions\n\n /// returns as result the hash of the written file.\n\n fn write_to_file<S: Into<String>>(&...
Rust
src/database/meta.rs
eomain/ejdb.rs
43cf24608c5d970f3641d764124122a50438a6e5
use std::iter; use std::ops::Deref; use std::result; use std::slice; use std::str::FromStr; use bson::{Bson, Document, ValueAccessError}; use ejdb_sys; use super::Database; use ejdb_bson::EjdbBsonDocument; use Result; impl Database { ...
use std::iter; use std::ops::Deref; use std::result; use std::slice; use std::str::FromStr; use bson::{Bson, Document, ValueAccessError}; use ejdb_sys; use super::Database; use ejdb_bson::EjdbBsonDocument; use Result; impl Database { ...
} pub fn file(&self) -> Option<&str> { match self.0.get_str("file") { Ok(f) => Some(f), Err(ValueAccessError::NotPresent) => None, Err(_) => panic!("cannot get index file"), } } } impl<'a> Deref for IndexMetadata<'a> { type Target = Document; ...
match self.0.get_i64("records") { Ok(n) => Some(n as u64), Err(ValueAccessError::NotPresent) => None, Err(_) => panic!("cannot get index records count"), }
if_condition
[ { "content": "pub trait BsonNumber {\n\n fn to_bson(self) -> Bson;\n\n}\n\n\n\nimpl BsonNumber for f32 {\n\n #[inline]\n\n fn to_bson(self) -> Bson {\n\n Bson::FloatingPoint(self as f64)\n\n }\n\n}\n\n\n\nimpl BsonNumber for f64 {\n\n #[inline]\n\n fn to_bson(self) -> Bson {\n\n ...
Rust
src/coreobjs.rs
mayadata-io/dynservice
3ce44fd53a8986056c85edecefa84c81c87b6e59
use crate::{ common::{ServiceUnregister, DEFAULT_SERVICE_TIMEOUT}, store::{StoreError, TimedLease}, ServiceError, }; use serde::{Deserialize, Serialize}; use snafu::ResultExt; #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Service { name: String, instance_id...
use crate::{ common::{ServiceUnregister, DEFAULT_SERVICE_TIMEOUT}, store::{StoreError, TimedLease}, ServiceError, }; use serde::{Deserialize, Serialize}; use snafu::ResultExt; #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Service { name: String, instance_id...
> i64 { self.lease.ttl() } pub fn service(&self) -> &str { &self.service } pub fn instance(&self) -> &str { &self.instance } }
); self.heartbeat_interval = Some(interval); self } pub fn with_endpoints<S: AsRef<str>, E: AsRef<[S]>>(mut self, endpoints: E) -> Self { let eps: Vec<String> = endpoints .as_ref() .iter() .map(|e| e.as_ref().to_string()) .coll...
random
[ { "content": "fn get_container_mount() -> String {\n\n tempdir()\n\n .unwrap()\n\n .into_path()\n\n .as_path()\n\n .to_string_lossy()\n\n .to_string()\n\n}\n\n\n\nimpl Builder {\n\n pub fn new(num_nodes: u32) -> Self {\n\n assert!(\n\n num_nodes > 0 && ...
Rust
src/board.rs
Rejyr/sf21_22
974887cfb655eb48a23b9b425166884194719c00
use std::fmt::Display; use std::ops::ControlFlow; use board_game::board::Board as BoardTrait; use board_game::board::BoardMoves; use board_game::board::Outcome; use board_game::board::Player; use board_game::board::UnitSymmetryBoard; use chess::{BitBoard, Color}; use internal_iterator::Internal; use internal_iterato...
use std::fmt::Display; use std::ops::ControlFlow; use board_game::board::Board as BoardTrait; use board_game::board::BoardMoves; use board_game::board::Outcome; use board_game::board::Player; use board_game::board::UnitSymmetryBoard; use chess::{BitBoard, Color}; use internal_iterator::Internal; use internal_iterato...
fn outcome(&self) -> Option<board_game::board::Outcome> { if self.white & BitBoard(RANKS[self.size - 1]) != EMPTY_BB { Some(Outcome::WonBy(Player::A)) } else if self.black & BitBoard(RANKS[0]) != EMPTY_BB { Some(Outcome::WonBy(Player::B)) ...
m_square(mv.dest()); *self.pieces_to_move_mut() ^= src_bb | dest_bb; *self.pieces_not_to_move_mut() &= !dest_bb; self.side_to_move = !self.side_to_move; }
function_block-function_prefixed
[ { "content": "pub fn inspect_moves(board: &Board) {\n\n if board\n\n .available_moves()\n\n .inspect(|mv| println!(\"{mv}\"))\n\n .count()\n\n == 0\n\n {\n\n println!(\"No moves\");\n\n }\n\n}\n\n\n", "file_path": "src/tests.rs", "rank": 0, "score": 106015...
Rust
amethyst_input/src/gilrs_events_system.rs
niconicoj/amethyst
83fa765987fabb3a5f43e1b2f23381c880d52a6c
use std::{ collections::{hash_map::DefaultHasher, HashMap}, fmt, hash::{Hash, Hasher}, marker::PhantomData, }; use derivative::Derivative; use derive_new::new; use gilrs::{Axis, Button, Event, EventType, GamepadId, Gilrs}; use amethyst_core::{ ecs::prelude::{System, SystemData, World, Write}, ...
use std::{ collections::{hash_map::DefaultHasher, HashMap}, fmt, hash::{Hash, Has
er: PhantomData<T>, } type GilrsEventsData<'a, T> = ( Write<'a, InputHandler<T>>, Write<'a, EventChannel<InputEvent<T>>>, ); impl<'a, T: BindingTypes> System<'a> for GilrsEventsSystem<T> { type SystemData = GilrsEventsData<'a, T>; fn run(&mut self, (mut handler, mut output): Self::SystemData) { ...
her}, marker::PhantomData, }; use derivative::Derivative; use derive_new::new; use gilrs::{Axis, Button, Event, EventType, GamepadId, Gilrs}; use amethyst_core::{ ecs::prelude::{System, SystemData, World, Write}, shrev::EventChannel, SystemDesc, }; use super::{ controller::{ControllerAxis, Contro...
random
[ { "content": "/// Basic building block of rendering in [RenderingBundle].\n\n///\n\n/// Can be used to register rendering-related systems to the dispatcher,\n\n/// building render graph by registering render targets, adding [RenderableAction]s to them\n\n/// and signalling when the graph has to be rebuild.\n\np...
Rust
src/float/conv.rs
mattico/compiler-builtins
35dec6bd8ab1214078e6284d58e9ba62271e2fb9
use float::Float; use int::{Int, CastInto}; fn int_to_float<I: Int, F: Float>(i: I) -> F where F::Int: CastInto<u32>, F::Int: CastInto<I>, I::UnsignedInt: CastInto<F::Int>, u32: CastInto<F::Int>, { if i == I::ZERO { return F::ZERO; } let two = I::UnsignedInt::ONE + I::UnsignedInt::...
use float::Float; use int::{Int, CastInto}; fn int_to_float<I: Int, F: Float>(i: I) -> F where F::Int: CastInto<u32>, F::Int: CastInto<I>, I::UnsignedInt: CastInto<F::Int>, u32: CastInto<F::Int>, { if i == I::ZERO { return F::ZERO; } let two = I::UnsignedInt::ONE + I::UnsignedInt::...
pub extern "C" fn __floatuntidf(i: u128) -> f64 { int_to_float(i) } } #[derive(PartialEq)] enum Sign { Positive, Negative } fn float_to_int<F: Float, I: Int>(f: F) -> I where F::Int: CastInto<u32>, F::Int: CastInto<I>, { let f = f; let fixint_min = I::min_value(); let fixint...
_plus_two { a } else { (a >> (sd - mant_dig_plus_two)) | Int::from_bool((a & I::UnsignedInt::max_value()).wrapping_shl((n + mant_dig_plus_two) - sd) != Int::ZERO) }; /* finish: */ a |= Int::from_bool((a & four) != I::UnsignedInt::ZERO); /* Or P into R...
random
[ { "content": "#[test]\n\nfn two() {\n\n let mut aligned = Aligned::new([0u8; 8]);;\n\n assert_eq!(mem::align_of_val(&aligned), 4);\n\n let xs = &mut aligned.array;\n\n let n = 2;\n\n let c = 0xdeadbeef;\n\n\n\n unsafe {\n\n __aeabi_memset4(xs.as_mut_ptr(), n, c)\n\n }\n\n\n\n asse...
Rust
kube/src/client/tls.rs
Ka1wa/kube-rs
50acf98ce7513809634d297392663539c06478c2
#[cfg(feature = "native-tls")] pub mod native_tls { use tokio_native_tls::native_tls::{Certificate, Identity, TlsConnector}; use crate::{Error, Result}; const IDENTITY_PASSWORD: &str = " "; pub fn native_tls_connector( identity_pem: Option<&Vec<u8>>, root_cert: Option<&Vec<Vec<u8...
#[cfg(feature = "native-tls")] pub mod native_tls { use tokio_native_tls::native_tls::{Certificate, Identity, TlsConnector}; use crate::{Error, Result}; const IDENTITY_PASSWORD: &str = " "; pub fn native_tls_connector( identity_pem: Option<&Vec<u8>>, root_cert: Option<&Vec<Vec<u8...
} }
fn verify_server_cert( &self, _roots: &rustls::RootCertStore, _presented_certs: &[rustls::Certificate], _dns_name: DNSNameRef<'_>, _ocsp: &[u8], ) -> Result<ServerCertVerified, rustls::TLSError> { Ok(ServerCertVerified::assertion()) ...
function_block-full_function
[ { "content": "/// Returns certification from specified path in cluster.\n\npub fn load_cert() -> Result<Vec<Vec<u8>>> {\n\n Ok(utils::certs(&utils::read_file(SERVICE_CERTFILE)?))\n\n}\n\n\n", "file_path": "kube/src/config/incluster_config.rs", "rank": 0, "score": 250389.20424861487 }, { "...
Rust
rust/agents/kathy/src/kathy.rs
aaronwinter/optics-monorepo
82b74a232b87064456bda20ba5f1171bd2b6fe70
use std::time::Duration; use async_trait::async_trait; use color_eyre::eyre::bail; use ethers::core::types::H256; use optics_core::traits::Replica; use tokio::{task::JoinHandle, time::sleep}; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use color_eyre::Result; use optics_base::{ agent::{A...
use std::time::Duration; use async_trait::async_trait; use color_eyre::eyre::bail; use ethers::core::types::H256; use optics_core::traits::Replica; use tokio::{task::JoinHandle, time::sleep}; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use color_eyre::Result; use optics_base::{ agent::{A...
#[tracing::instrument] fn run(&self, name: &str) -> Instrumented<JoinHandle<Result<()>>> { let replica_opt = self.replica_by_name(name); let name = name.to_owned(); let home = self.home(); let mut generator = self.generator.clone(); let duration = Duration::from_secs(s...
settings.interval.parse().expect("invalid u64"), settings.chat.into(), settings.base.try_into_core(Self::AGENT_NAME).await?, )) }
function_block-function_prefix_line
[ { "content": "/// Strips the '0x' prefix off of hex string so it can be deserialized.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `s` - The hex str\n\npub fn strip_0x_prefix(s: &str) -> &str {\n\n if s.len() < 2 || &s[..2] != \"0x\" {\n\n s\n\n } else {\n\n &s[2..]\n\n }\n\n}\n\n\n", "f...
Rust
pallets/template/src/lib.rs
Vietdung113/substrateTemplateNode
a5a9edd4280149de5ad24b4fd5a2b572d647a278
#![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; #[cfg(test)] mod mock; #[cfg(test)] mod tests; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; #[frame_support::pallet] pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::config] pub tra...
#![cfg_attr(not(feature = "std"), no_std)] pub use pallet::*; #[cfg(test)] mod mock; #[cfg(test)] mod tests; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; #[frame_support::pallet] pub mod pallet { use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; #[pallet::config] pub tra...
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))] pub fn transfer_money(origin: OriginFor<T>, to: T::AccountId, amount: u32) -> DispatchResult { let who = ensure_signed(origin)?; let whoBalance: Result<u32, ()> = <AccountToBalance<T>>::try_get(&who); assert!(whoBalan...
if <AccountToBalance<T>>::try_get(&who).is_err() { <AccountToBalance<T>>::insert(&who, 10); Self::deposit_event(Event::AccountCreated(who)); } else { Self::deposit_event(Event::AccountExists(who)); } Ok(()) }
function_block-function_prefix_line
[ { "content": "// Build genesis storage according to the mock runtime.\n\npub fn new_test_ext() -> sp_io::TestExternalities {\n\n\tsystem::GenesisConfig::default().build_storage::<Test>().unwrap().into()\n\n}\n", "file_path": "pallets/template/src/mock.rs", "rank": 1, "score": 118374.5519331848 }, ...
Rust
src/grouped_rects_to_place.rs
chinedufn/rectangle-pack
648774b13ff9af85019eddeb1856e1607191fb8c
use crate::RectToInsert; #[cfg(not(std))] use alloc::collections::BTreeMap as KeyValMap; #[cfg(std)] use std::collections::HashMap as KeyValMap; use alloc::{ collections::{btree_map::Entry, BTreeMap}, vec::Vec, }; use core::{fmt::Debug, hash::Hash}; #[derive(Debug)] pub struct GroupedRectsToPlace<RectToPlace...
use crate::RectToInsert; #[cfg(not(std))] use alloc::collections::BTreeMap as KeyValMap; #[cfg(std)] use std::collections::HashMap as KeyValMap; use alloc::{ collections::{btree_map::Entry, BTreeMap}, vec::Vec, }; use core::{fmt::Debug, hash::Hash}; #[derive(Debug)] pub struct GroupedRectsToPlace<RectToPlace...
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)] enum RectToPlaceId { One, Two, } }
fn store_the_inbound_rectangle() { let mut lrg = GroupedRectsToPlace::new(); lrg.push_rect( RectToPlaceId::One, Some(vec![0, 1]), RectToInsert::new(10, 10, 1), ); assert_eq!(lrg.rects[&RectToPlaceId::One], RectToInsert::new(10, 10, 1)); }
function_block-full_function
[ { "content": "/// Determine how to fit a set of incoming rectangles (2d or 3d) into a set of target bins.\n\n///\n\n/// ## Example\n\n///\n\n/// ```\n\n/// //! A basic example of packing rectangles into target bins\n\n///\n\n/// use rectangle_pack::{\n\n/// GroupedRectsToPlace,\n\n/// RectToInsert,\n\n/...
Rust
src/controllers/time.rs
gopalsgs/rustRocket
ef8e8e45ae3d0a3131b0024b66ee2b8322d56235
use std::f64; use rand::Rng; use super::Actions; use game_state::GameState; use geometry::{Advance, Position, Point}; use models::{Bullet, Enemy, Particle, Vector}; use util; const BULLETS_PER_SECOND: f64 = 100.0; const BULLET_RATE: f64 = 1.0 / BULLETS_PER_SECOND; const ENEMY_SPAWNS_PER_SECOND: f64 = 1.0; const ENEM...
use std::f64; use rand::Rng; use super::Actions; use game_state::GameState; use geometry::{Advance, Position, Point}; use models::{Bullet, Enemy, Particle, Vector}; use util; const BULLETS_PER_SECOND: f64 = 100.0; const BULLET_RATE: f64 = 1.0 / BULLETS_PER_SECOND; const ENEMY_SPAWNS_PER_SECOND: f64 = 1.0; const ENEM...
pub fn update_seconds(&mut self, dt: f64, actions: &Actions, state: &mut GameState) { self.current_time += dt; if actions.rotate_left { *state.world.player.direction_mut() += -ROTATE_SPEED * dt; } if actions.rotate_right { *state.wor...
pub fn new(rng: T) -> TimeController<T> { TimeController { rng, current_time: 0.0, last_tail_particle: 0.0, last_shoot: 0.0, last_spawned_enemy: 0.0 } }
function_block-full_function
[ { "content": "/// Generates a new explosion of the given intensity at the given position.\n\n/// This works best with values between 5 and 25\n\npub fn make_explosion(particles: &mut Vec<Particle>, position: &Point, intensity: u8) {\n\n use itertools_num;\n\n for rotation in itertools_num::linspace(0.0, 2...
Rust
calyx/src/passes/compile_control.rs
yoonachang/futil
2ef8c89ac3e8c398f9db42c28ec8d495ee0a45e2
use crate::errors::Error; use crate::lang::{ ast, component::Component, context::Context, structure_builder::ASTBuilder, }; use crate::passes::visitor::{Action, Named, VisResult, Visitor}; use crate::{add_wires, guard, port, structure}; use ast::{Control, Enable, GuardExpr}; use std::collections::HashMap; use std::...
use crate::errors::Error; use crate::lang::{ ast, component::Component, context::Context, structure_builder::ASTBuilder, }; use crate::passes::visitor::{Action, Named, VisResult, Visitor}; use crate::{add_wires, guard, port, structure}; use ast::{Control, Enable, GuardExpr}; use std::collections::HashMap; use std::...
}
fn finish_par( &mut self, s: &ast::Par, comp: &mut Component, ctx: &Context, ) -> VisResult { let st = &mut comp.structure; let par_group: ast::Id = st.namegen.gen_name("par").into(); let par_group_idx = st.insert_group(&par_group, HashMap::new())?; ...
function_block-full_function
[ { "content": "/// Given a StructureGraph `st`, this function inlines assignments\n\n/// to `x[hole]` into any uses of `x[hole]` in a GuardExpr. This works\n\n/// in 2 passes over the edges. The first pass only considers assignments\n\n/// into `x[hole]` and builds up a mapping from `x[hole] -> (edge index, guar...
Rust
src/online/registry/github_registry.rs
SierraSoftworks/git-tool
961f0d7b2a9dfc58c2346571e09f4cf8b7851c01
use super::*; use crate::errors; use serde::Deserialize; pub struct GitHubRegistry; impl GitHubRegistry { async fn get(&self, core: &Core, url: &str) -> Result<reqwest::Response, errors::Error> { let uri: reqwest::Url = url.parse().map_err(|e| { errors::system_with_internal( &f...
use super::*; use crate::errors; use serde::Deserialize; pub struct GitHubRegistry; impl GitHubRegistry { async fn get(&self, core: &Core, url: &str) -> Result<reqwest::Response, errors::Error> { let uri: reqwest::Url = url.parse().map_err(|e| { errors::system_with_internal( &f...
async fn get_entry(&self, core: &Core, id: &str) -> Result<Entry, Error> { let resp = self .get( core, &format!( "https://raw.githubusercontent.com/SierraSoftworks/git-tool/main/registry/{}.yaml", id ), ) ....
t?; let mut entries: Vec<String> = Vec::new(); let prefix = "registry/"; let suffix = ".yaml"; for node in tree.tree { if node.node_type == "blob" && node.path.starts_with(prefix) && no...
function_block-function_prefixed
[ { "content": "pub fn render(tmpl: &str, context: Value) -> Result<String, errors::Error> {\n\n template(tmpl, context).map_err(|e| errors::user_with_internal(\n\n format!(\"We couldn't render your template '{}'.\", tmpl).as_str(),\n\n \"Check that your template follows the Go template syntax he...
Rust
onion_lib/src/api_protocol/messages/mod.rs
leonbeckmann/voip-onion-routing
06e86d957c01cf83e7095ff966c24a0fd99a2ff0
use std::convert::{TryFrom, TryInto}; use std::net::IpAddr; /* * Onion Message Header [size: u16, type: u16] * Direction: Incoming, Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionMessageHeader { pub size: u16, pub msg_type: u16, } impl OnionMessageHeader { pub fn new(size: u16, msg_type: u16) ...
use std::convert::{TryFrom, TryInto}; use std::net::IpAddr; /* * Onion Message Header [size: u16, type: u16] * Direction: Incoming, Outgoing */ #[derive(Debug, PartialEq)] pub struct OnionMessageHeader { pub size: u16, pub msg_type: u16, } impl OnionMessageHeader { pub fn new(size: u16, msg_type: u16) ...
}
fn unit_test_only_messages() { let hdr = OnionMessageHeader::new(25, ONION_TUNNEL_DATA); let mut hdr_raw: [u8; 4] = hdr.to_be_vec().try_into().unwrap(); let hdr2 = OnionMessageHeader::try_from(&hdr_raw).unwrap(); assert_eq!(hdr, hdr2); hdr_raw[0] = 0; h...
function_block-full_function
[ { "content": "fn write_msg(msg_type: u16, data: Vec<u8>, stream: &mut TcpStream) {\n\n let hdr = OnionMessageHeader::new(\n\n (data.len() + OnionMessageHeader::hdr_size()) as u16,\n\n msg_type,\n\n )\n\n .to_be_vec();\n\n\n\n stream.write_all(hdr.as_slice()).unwrap();\n\n stream.wri...
Rust
noodles-bam/src/bai/reader.rs
MaltheSR/noodles
8530af08ced193795480ea8ee2667fe8af82bd92
use std::{ convert::TryFrom, io::{self, Read}, }; use byteorder::{LittleEndian, ReadBytesExt}; use noodles_bgzf as bgzf; use noodles_csi::index::reference_sequence::{bin::Chunk, Metadata}; use super::{ index::{reference_sequence, ReferenceSequence}, Bin, Index, MAGIC_NUMBER, }; pub struct Reader<R> {...
use std::{ convert::TryFrom, io::{self, Read}, }; use byteorder::{LittleEndian, ReadBytesExt}; use noodles_bgzf as bgzf; use noodles_csi::index::reference_sequence::{bin::Chunk, Metadata}; use super::{ index::{reference_sequence, ReferenceSequence}, Bin, Index, MAGIC_NUMBER, }; pub struct Reader<R> {...
let intervals = read_intervals(reader)?; references.push(ReferenceSequence::new(bins, intervals, metadata)); } Ok(references) } fn read_bins<R>(reader: &mut R) -> io::Result<(Vec<Bin>, Option<Metadata>)> where R: Read, { use reference_sequence::bin::METADATA_ID; let n_bin = reade...
::ErrorKind::InvalidData, e)) })?; let mut references = Vec::with_capacity(n_ref); for _ in 0..n_ref { let (bins, metadata) = read_bins(reader)?;
function_block-random_span
[ { "content": "fn read_header<R>(reader: &mut R) -> io::Result<index::Header>\n\nwhere\n\n R: Read,\n\n{\n\n let format = reader.read_i32::<LittleEndian>().and_then(|n| {\n\n Format::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))\n\n })?;\n\n\n\n let col_seq = reader.re...
Rust
imxrt1062-pac/imxrt1062-semc/src/bmcr1.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register BMCR1"] pub type R = crate::R<u32, super::BMCR1>; #[doc = "Writer for register BMCR1"] pub type W = crate::W<u32, super::BMCR1>; #[doc = "Register BMCR1 `reset()`'s with value 0"] impl crate::ResetValue for super::BMCR1 { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
#[doc = "Reader of register BMCR1"] pub type R = crate::R<u32, super::BMCR1>; #[doc = "Writer for register BMCR1"] pub type W = crate::W<u32, super::BMCR1>; #[doc = "Register BMCR1 `reset()`'s with value 0"] impl crate::ResetValue for super::BMCR1 { type Type = u32; #[inline(always)] fn reset_value() -> Sel...
] #[inline(always)] pub fn wbr(&self) -> WBR_R { WBR_R::new(((self.bits >> 24) & 0xff) as u8) } } impl W { #[doc = "Bits 0:3 - Weight of QoS"] #[inline(always)] pub fn wqos(&mut self) -> WQOS_W { WQOS_W { w: self } } #[doc = "Bits 4:7 - Weight of Aging"] #[inline(alwa...
oc = "Write proxy for field `WPH`"] pub struct WPH_W<'a> { w: &'a mut W, } impl<'a> WPH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 8)) | (((value as u32) & 0xff) << 8); self....
random
[ { "content": "/// Migrate the `lib.rs` of the PAC subscrate, adding\n\n/// our necessary header to the top of the file.\n\nfn write_lib<R: Read>(crate_path: &Path, mut src: R) {\n\n static LIB_PRELUDE: &str = r#\"#![deny(warnings)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(clippy::all)]\n\n#![no_std]\n\...
Rust
src/git.rs
jhzn/purs
574971936795c484acf3d3785c6ed6bbbc15ee13
use ansi_term::Colour::{Cyan, Green, Purple, Red}; use ansi_term::{ANSIGenericString, ANSIStrings}; use git2::{self, Repository, StatusOptions}; use std::fmt; pub struct Info { detailed: bool, head_description: Option<String>, current_action: Option<String>, index_change: usi...
use ansi_term::Colour::{Cyan, Green, Purple, Red}; use ansi_term::{ANSIGenericString, ANSIStrings}; use git2::{self, Repository, StatusOptions}; use std::fmt; pub struct Info { detailed: bool, head_description: Option<String>, current_action: Option<String>, index_change: usi...
fn get_action(r: &Repository) -> Option<String> { let gitdir = r.path(); for tmp in &[ gitdir.join("rebase-apply"), gitdir.join("rebase"), gitdir.join("..").join(".dotest"), ] { if tmp.join("rebasing").exists() { return Some("rebase".to_string()); } ...
function_block-full_function
[ { "content": "pub fn cli_arguments<'a>() -> App<'a, 'a> {\n\n let v = &[\n\n Arg::with_name(\"git-detailed\")\n\n .long(\"git-detailed\")\n\n .help(\"Prints detailed git status\"),\n\n Arg::with_name(\"shortened-path\")\n\n .long(\"shortened-path\")\n\n ...
Rust
src/app/widgets/tag.rs
AngelOfSol/art-organize
ed4ad1d936a585a80e9f98b672d7875edb553f5d
use db::{ commands::{AttachCategory, EditTag}, Db, Tag, TagId, }; use imgui::{im_str, Selectable, StyleColor, Ui}; use super::{category, combo_box, confirm::confirm_delete_popup, date}; pub fn view(tag_id: TagId, db: &Db, ui: &Ui<'_>) { let tag = &db[tag_id]; ui.text_wrapped(&im_str!("Name: {}", tag.n...
use db::{ commands::{AttachCategory, EditTag}, Db, Tag, TagId, }; use imgui::{im_str, Selectable, StyleColor, Ui}; use super::{category, combo_box, confirm::confirm_delete_popup, date}; pub fn view(tag_id: TagId, db: &Db, ui: &Ui<'_>) { let tag = &db[tag_id]; ui.text_wrapped(&im_str!("Name: {}", tag.n...
{ return EditTagResponse::AttachCategory(AttachCategory { src: tag_id, dest: new_id, }); } if ui.button(im_str!("Delete")) { ui.open_popup(im_str!("Confirm Delete")); } if confirm_delete_popup(ui) { EditTagResponse::Delete } else { Ed...
combo_box( ui, &im_str!("Category"), x, &db.category_for_tag(tag_id), |id| match id { Some(category_id) => im_str!("{}", &db[category_id].name), None => Default::default(), }, )
call_expression
[ { "content": "pub fn view_tags(piece_id: PieceId, db: &Db, ui: &Ui<'_>) -> Option<(TagId, ItemViewResponse)> {\n\n for category_id in db\n\n .tags_for_piece(piece_id)\n\n .flat_map(|tag| db.category_for_tag(tag))\n\n .sorted_by_key(|category_id| &db[category_id].name)\n\n .dedup()...
Rust
src/writer/string_buffer.rs
efharkin/swc2dot
f08a38e7ae18344c4b9da8730ada01050ac2c496
#[derive(Clone, Debug)] pub struct StringBuffer { buf: String, empty_buf: String, has_been_written_to: bool, indent_level: u8, line_width: u32, cursor_position: u32, } impl StringBuffer { pub fn new(leading_newline: bool, indent: Indent, capacity: usize) -> StringBuffer { let ...
#[derive(Clone, Debug)] pub struct StringBuffer { buf: String, empty_buf: String, has_been_written_to: bool, indent_level: u8, line_width: u32, cursor_position: u32, } impl StringBuffer { pub fn new(leading_newline: bool, indent: Indent, capacity: usize) -> StringBuffer { let ...
} #[test] fn hard_wrap_long_second_line_with_indent() { let mut string = StringBuffer::new(false, Indent::flat(1), 32); string.line_width = 8; string.push_str("123"); string.push_str("456789"); string.push_str("0"); assert_eq!(" 123\n 456789\n 0".to_str...
t::flat(0), 32); string.line_width = 4; string.push_str("12345"); string.push_str("678"); assert_eq!("12345\n678".to_string(), string.to_string());
function_block-random_span
[ { "content": "fn parse_line(line: String) -> Result<SWCLine, String> {\n\n let trimmed_line = line.trim(); // Remove leading and trailing whitespace.\n\n\n\n let parse_result: SWCLine;\n\n if trimmed_line.is_empty() {\n\n // Line is empty.\n\n parse_result = SWCLine::Blank;\n\n } else...
Rust
src/lib.rs
kyclark/excel2txt-rust
a573b3fa0cd5017d80866b1365f8edb2875c3cb8
extern crate clap; extern crate csv; extern crate regex; extern crate tempdir; use calamine::{open_workbook, Reader, Xlsx}; use clap::{App, Arg}; use csv::WriterBuilder; use regex::Regex; use std::error::Error; use std::fs::{self, DirBuilder}; use std::path::{Path, PathBuf}; type MyResult<T> = Result<T, Box<dyn Error...
extern crate clap; extern crate csv; extern crate regex; extern crate tempdir; use calamine::{open_workbook, Reader, Xlsx}; use clap::{App, Arg}; use csv::WriterBuilder; use regex::Regex; use std::error::Error; use std::fs::{self, DirBuilder}; use std::path::{Path, PathBuf}; type MyResult<T> = Result<T, Box<dyn Error...
#[test] fn test_2() { let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let file = manifest_dir.join(PathBuf::from("tests/Test 2.xlsx")); if let Ok(tmp_dir) = TempDir::new("test") { let outdir = &tmp_dir.path().display().to_string(); let conf = Confi...
to_string(); let conf = Config { files: vec![file.display().to_string()], outdir: outdir.to_string(), delimiter: 9, normalize: false, make_dirs: false, }; let _res = match run(conf) { Ok...
function_block-function_prefixed
[ { "content": "fn main() {\n\n let config = match excel2txt::get_args() {\n\n Ok(c) => c,\n\n Err(e) => {\n\n println!(\"Error: {}\", e);\n\n process::exit(1);\n\n }\n\n };\n\n\n\n if let Err(e) = excel2txt::run(config) {\n\n println!(\"Error: {}\", e);\...
Rust
src/mapper.rs
whitfin/efflux
fe756d76cedb962abcd1934285b9d58e6b00d48c
use crate::context::{Context, Offset}; use crate::io::Lifecycle; pub trait Mapper { fn setup(&mut self, _ctx: &mut Context) {} fn map(&mut self, key: usize, value: &[u8], ctx: &mut Context) { ctx.write(key.to_string().as_bytes(), value); } fn cleanup(&mut ...
use crate::context::{Context, Offset}; use crate::io::Lifecycle; pub trait Mapper { fn setup(&mut self, _ctx: &mut Context) {} fn map(&mut self, key: usize, value: &[u8], ctx: &mut Context) { ctx.write(key.to_string().as_bytes(), value); } fn cleanup(&mut ...
}; vet(b"first_input_line", 18); vet(b"second_input_line", 37); vet(b"third_input_line", 55); } mapper.on_end(&mut ctx); } struct TestPair(usize, Vec<u8>); impl Contextual for TestPair {} struct TestMapper; impl Mapper for TestMapper { ...
let pair = pair.unwrap(); assert_eq!(pair.0, expected); assert_eq!(pair.1, input);
random
[ { "content": "/// Marker trait to represent types which can be added to a `Context`.\n\npub trait Contextual: Any {}\n\n\n\n// all internal contextual types\n\nimpl Contextual for Configuration {}\n\nimpl Contextual for Delimiters {}\n\nimpl Contextual for Offset {}\n\n\n\n/// Context structure to represent a H...
Rust
src/main.rs
erikbrinkman/stats
f709428cd7a8e734b67f32693678ed269b384fa7
use std::f64; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Read, StdinLock, StdoutLock, Write}; use std::iter; use clap::{crate_version, App, Arg, ArgGroup, ArgMatches}; use inc_stats::{Mode, Percentiles, SummStats}; fn parse_command_line<'a>() -> ArgMatches<'a> { App::new("stats") ...
use std::f64; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Read, StdinLock, StdoutLock, Write}; use std::iter; use clap::{crate_version, App, Arg, ArgGroup, ArgMatches}; use inc_stats::{Mode, Percentiles, SummStats}; fn parse_command_line<'a>() -> ArgMatches<'a> { App::new("stats") ...
stats: &SummStats<f64>, percs: &mut Percentiles<f64>, mode: &Mode<f64>, ) -> Vec<(String, f64)> { let mut results = Vec::new(); if matches.is_present("count") { results.push((String::from("count"), stats.count() as f64)); } if matches.is_present("min") { results.push((String...
t") .long("mode-count") .help("Print the number of times the mode occured (Note: computing mode takes O(n) space")) .arg(Arg::with_name("distinct") .long("distinct") .help("Print the number of distinct values (Note: computing mode takes O(n) space")) ....
random
[ { "content": "/// Get the mean of a set of data\n\n///\n\n/// This method takes constant space and linear time.\n\n///\n\n/// # Examples:\n\n///\n\n/// ```\n\n/// let mean: f64 = inc_stats::mean(&[2.0, 4.0]).unwrap();\n\n/// assert!((3.0 - mean).abs() < 1.0e-6);\n\n/// ```\n\npub fn mean<T, V, I>(data: I) -> Op...
Rust
src/volume/storage/redis/redis.rs
isgasho/zbox
752c2739f883f416e27e9c342552ff1f9838c0e6
use std::fmt::{self, Debug}; use std::sync::Mutex; use redis::{Client, Commands, Connection}; use base::crypto::{Crypto, Key}; use base::IntoRef; use error::{Error, Result}; use trans::Eid; use volume::address::Span; use volume::storage::Storable; use volume::BLK_SIZE; #[inline] fn super_blk_key(suffix: u64) -> Stri...
use std::fmt::{self, Debug}; use std::sync::Mutex; use redis::{Client, Commands, Connection}; use base::crypto::{Crypto, Key}; use base::IntoRef; use error::{Error, Result}; use trans::Eid; use volume::address::Span; use volume::storage::Storable; use volume::BLK_SIZE; #[inline] fn super_blk_key(suffix: u64) -> Stri...
}
Error::NotFound ); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(1, 1)) .unwrap_err(), Error::NotFound ); assert_eq!( rs.get_blocks(&mut dst[..BLK_SIZE], Span::new(2, 1)) .unwrap_err(), Error::Not...
function_block-function_prefix_line
[ { "content": "pub fn random_buf(buf: &mut [u8]) {\n\n unsafe {\n\n randombytes_buf(buf.as_mut_ptr(), buf.len());\n\n }\n\n}\n\n\n", "file_path": "tests/common/crypto.rs", "rank": 0, "score": 387509.8669507819 }, { "content": "pub fn random_slice(buf: &[u8]) -> (usize, &[u8]) {\n...
Rust
crates/holochain_zome_types/src/dna_def.rs
guillemcordoba/holochain
fa4acd2067176757327328446368b1e09bfa2a34
use super::zome; use crate::prelude::*; #[cfg(feature = "full-dna-def")] use crate::zome::error::ZomeError; #[cfg(feature = "full-dna-def")] use holo_hash::*; pub type IntegrityZomes = Vec<(ZomeName, zome::IntegrityZomeDef)>; pub type CoordinatorZomes = Vec<(ZomeName, zome::CoordinatorZomeDef)>; pub type Uid = St...
use super::zome; use crate::prelude::*; #[cfg(feature = "full-dna-def")] use crate::zome::error::ZomeError; #[cfg(feature = "full-dna-def")] use holo_hash::*; pub type IntegrityZomes = Vec<(ZomeName, zome::IntegrityZomeDef)>; pub type CoordinatorZomes = Vec<(ZomeName, zome::CoordinatorZomeDef)>; pub type Uid = St...
pub fn modify_phenotype(&self, uid: Uid, properties: SerializedBytes) -> Self { let mut clone = self.clone(); clone.properties = properties; clone.uid = uid; clone } } #[cfg(feature = "full-dna-def")] pub fn random_uid() -> String { nanoid::nanoid!() } #[cfg(fea...
f.all_zomes() .find(|(name, _)| *name == zome_name) .map(|(_, def)| def) .ok_or_else(|| ZomeError::ZomeNotFound(format!("Zome '{}' not found", &zome_name,))) .and_then(|def| { if let ZomeDef::Wasm(wasm_zome) = def { Ok(wasm_zome) ...
function_block-function_prefixed
[]
Rust
benches/hashmap.rs
junghan0611/node-replication
c06f653051987a8bbc097486f1f815bd9787cb81
#![allow(dead_code)] #![feature(test)] use std::collections::HashMap; use std::fmt::Debug; use std::marker::Sync; use rand::seq::SliceRandom; use rand::{distributions::Distribution, Rng, RngCore}; use zipf::ZipfDistribution; use node_replication::Dispatch; use node_replication::Replica; mod hashmap_comparisons; m...
#![allow(dead_code)] #![feature(test)] use std::collections::HashMap; use std::fmt::Debug; use std::marker::Sync; use rand::seq::SliceRandom; use rand::{distributions::Distribution, Rng, RngCore}; use zipf::ZipfDistribution; use node_replication::Dispatch; use node_replication::Replica; mod hashmap_comparisons; m...
, ); } fn partitioned_hashmap_scale_out(c: &mut TestHarness, name: &str, write_ratio: usize) { let ops = generate_operations(NOP, write_ratio, KEY_SPACE, UNIFORM); let bench_name = format!("{}-scaleout-wr{}", name, write_ratio); mkbench::ScaleBenchBuilder::<Partitioner<NrHashMap>>::new(ops) ...
match op { Operation::ReadOperation(op) => { replica.exec_ro(*op, rid); } Operation::WriteOperation(op) => { replica.exec(*op, rid); } }
if_condition
[ { "content": "fn concurrent_ds_nr_scale_out<R>(c: &mut TestHarness, name: &str, write_ratio: usize)\n\nwhere\n\n R: ReplicaTrait + Send + Sync + 'static,\n\n R::D: Send,\n\n R::D: Dispatch<ReadOperation = SkipListConcurrent>,\n\n R::D: Dispatch<WriteOperation = OpWr>,\n\n <R::D as Dispatch>::Writ...
Rust
src/gen/generate.rs
warpwm/lule
dd429596aa32895bd19ba814951ba1fda65275c3
use rand::prelude::*; use crate::scheme::*; pub fn gen_main_six(col: &Vec<pastel::Color>) -> Vec<pastel::Color> { let mut colors = col.clone(); colors.retain(|x| x.to_lab().l > 20.0); colors.retain(|x| x.to_lab().l < 80.0); colors.sort_by_key(|c| (c.to_lch().l) as i32); colors.reverse(); let ...
use rand::prelude::*; use crate::scheme::*; pub fn gen_main_six(col: &Vec<pastel::Color>) -> Vec<pastel::Color> { let mut colors = col.clone(); colors.retain(|x| x.to_lab().l > 20.0); colors.retain(|x| x.to_lab().l < 80.0); colors.sort_by_key(|c| (c.to_lch().l) as i32); colors.reverse(); let ...
et Some(ref cols) = scheme.pigments() { for c in cols.iter() { palette.push(pastel::Color::from_hex(c)); } } let main = gen_main_six(&palette); let mut black = pastel::Color::from_rgb(0,0,0); let mut white = pastel::Color::from_rgb(255,255,255); if !theme { white...
function_block-function_prefixed
[ { "content": "pub fn write_colors(scheme: &mut SCHEME, old: bool) -> Result<()> {\n\n if old {\n\n if let Some(cachepath) = scheme.cache().clone() {\n\n let mut palette_temp = PathBuf::from(&cachepath); palette_temp.push(\"palette\");\n\n scheme.set_pigments(Some(text::lines_to_v...
Rust
contracts/terranames_auction/src/state.rs
jonls/terranames-contracts
13f50b1d396c26391f43478b06f72b220978e4ab
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Addr, Order, StdError, StdResult, Storage, Uint128}; use cosmwasm_storage::{ bucket, bucket_read, singleton, singleton_read, }; use terranames::auction::{ seconds_from_deposit, deposit_from_seconds_ceil, deposit_from_seconds...
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{Addr, Order, StdError, StdResult, Storage, Uint128}; use cosmwasm_storage::{ bucket, bucket_read, singleton, singleton_read, }; use terranames::auction::{ seconds_from_deposit, deposit_from_seconds_ceil, deposit_from_seconds...
transition_reference_time: self.transition_reference_time, } } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub enum OwnerStatus { CounterDelay { name_owner: Option<Addr>, bid_owner: Addr, transition_reference_time: Timesta...
dResult<()> { singleton(storage, CONFIG_KEY).save(config) } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct NameState { pub owner: Addr, pub controller: Option<Addr>, pub transition_reference_time: Timestamp, pub rate: Uint128, pub beg...
random
[ { "content": "pub fn read_config(storage: &dyn Storage) -> StdResult<Config> {\n\n singleton_read(storage, CONFIG_KEY).load()\n\n}\n\n\n", "file_path": "contracts/terranames_resolver/src/state.rs", "rank": 1, "score": 233558.8203027719 }, { "content": "pub fn read_config(storage: &dyn Sto...
Rust
hive-core/src/lua/shared/kv.rs
hackerer1c/hive
a98ab9a97836f208646df252175283067a398b7b
use super::SharedTable; use mlua::{ExternalError, ExternalResult, FromLua, Lua, ToLua}; use serde::{Serialize, Serializer}; use smallvec::SmallVec; use std::hash::{Hash, Hasher}; use std::sync::Arc; #[derive(Clone, Serialize)] #[serde(untagged)] pub enum SharedTableValue { Nil, Boolean(bool), Integer(i64), Num...
use super::SharedTable; use mlua::{ExternalError, ExternalResult, FromLua, Lua, ToLua}; use serde::{Serialize, Serializer}; use smallvec::SmallVec; use std::hash::{Hash, Hasher}; use std::sync::Arc; #[derive(Clone, Serialize)] #[serde(untagged)] pub enum SharedTableValue { Nil, Boolean(bool), Integer(i64), Num...
} impl<'lua> ToLua<'lua> for SharedTableValue { fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { use SharedTableValue::*; let result = match self { Nil => mlua::Value::Nil, Boolean(x) => mlua::Value::Boolean(x), Integer(x) => mlua::Value::Integer(x), Number(x) => ...
fn to_lua(self, lua: &'lua Lua) -> mlua::Result<mlua::Value<'lua>> { use SharedTableValue::*; let result = match self { Nil => mlua::Value::Nil, Boolean(x) => mlua::Value::Boolean(*x), Integer(x) => mlua::Value::Integer(*x), Number(x) => mlua::Value::Number(*x), String(x) => mlua::...
function_block-full_function
[ { "content": "pub fn apply_table_module_patch(lua: &Lua, table_module: Table) -> mlua::Result<()> {\n\n table_module.raw_set(\"dump\", create_fn_table_dump(lua)?)?;\n\n table_module.raw_set(\"insert\", create_fn_table_insert(lua)?)?;\n\n table_module.raw_set(\"scope\", create_fn_table_scope(lua)?)?;\n\n Ok(...
Rust
src/table_properties_rc.rs
hustwp233/rust-rocksdb
bac3ef613692ba783cfe9256cfd2388411c25a6d
use crocksdb_ffi::{DBTablePropertiesCollection, DBTableProperty}; use libc::size_t; use librocksdb_sys as crocksdb_ffi; use std::ops::Deref; use std::slice; use std::str; use crate::table_properties_rc_handles::{ TablePropertiesCollectionHandle, TablePropertiesCollectionIteratorHandle, TablePropertiesHandle,...
use crocksdb_ffi::{DBTablePropertiesCollection, DBTableProperty}; use libc::size_t; use librocksdb_sys as crocksdb_ffi; use std::ops::Deref; use std::slice; use std::str; use crate::table_properties_rc_handles::{ TablePropertiesCollectionHandle, TablePropertiesCollectionIteratorHandle, TablePropertiesHandle,...
e { let ptr = crocksdb_ffi::crocksdb_user_collected_properties_get( self.handle.ptr(), bytes.as_ptr(), bytes.len(), &mut size, ); if ptr.is_null() { return None; } Some(slice::from...
ey, TableProperties); fn next(&mut self) -> Option<Self::Item> { unsafe { loop { if !crocksdb_ffi::crocksdb_table_properties_collection_iter_valid(self.handle.ptr()) { return None; } let mut keylen: size_t = 0;...
random
[ { "content": "#[test]\n\npub fn test_iterator() {\n\n let path = tempdir_with_prefix(\"_rust_rocksdb_iteratortest\");\n\n\n\n let k1 = b\"k1\";\n\n let k2 = b\"k2\";\n\n let k3 = b\"k3\";\n\n let k4 = b\"k4\";\n\n let v1 = b\"v1111\";\n\n let v2 = b\"v2222\";\n\n let v3 = b\"v3333\";\n\n...
Rust
src/mesh/pointcloud.rs
elrnv/meshx
8119edab6eb744bc2a7d21577a472de8927e81e5
use crate::attrib::*; use crate::mesh::topology::*; use crate::mesh::{VertexMesh, VertexPositions}; use crate::Real; #[derive(Clone, Debug, PartialEq, Attrib, Intrinsic)] pub struct PointCloud<T: Real> { #[intrinsic(VertexPositions)] pub vertex_positions: IntrinsicAttribute<[T; 3], VertexIndex>, ...
use crate::attrib::*; use crate::mesh::topology::*; use crate::mesh::{VertexMesh, VertexPositions}; use crate::Real; #[derive(Clone, Debug, PartialEq, Attrib, Intrinsic)] pub struct PointCloud<T: Real> { #[intrinsic(VertexPositions)] pub vertex_positions: IntrinsicAttribute<[T; 3], VertexIndex>, ...
#[test] fn convert_test() { use crate::mesh::{PolyMesh, QuadMesh, TetMesh, TriMesh}; let pts = vec![ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], ]; let ptcloud = PointCloud::new(pts.clone()); let...
n_iter().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } for (pt1, pt2) in ptcloud.vertex_position_iter_mut().zip(pts.iter()) { assert_eq!(*pt1, *pt2); } for (pt1, pt2) in ptcloud.vertex_positions().iter().zip(pts.iter()) { assert_eq!(*pt1, *pt2); ...
function_block-function_prefixed
[ { "content": "pub fn convert_polymesh_to_obj_format<T: Real>(mesh: &PolyMesh<T>) -> Result<ObjData, Error> {\n\n let position: Vec<[f32; 3]> = mesh\n\n .vertex_position_iter()\n\n .cloned()\n\n .map(|[x, y, z]| {\n\n [\n\n x.to_f32().unwrap(),\n\n ...
Rust
rust/rsmgp-sys/src/testing.rs
memgraph/mage
8c389146dfce35c436e941b04655d9f758351e46
#[cfg(test)] pub mod alloc { use libc::malloc; use std::mem::size_of; use crate::mgp::*; pub(crate) unsafe fn alloc_mgp_type() -> *mut mgp_type { malloc(size_of::<mgp_type>()) as *mut mgp_type } pub(crate) unsafe fn alloc_mgp_value() -> *mut mgp_value { malloc(size_of::<mgp_...
#[cfg(test)] pub mod alloc { use libc::malloc; use std::mem::size_of; use crate::mgp::*; pub(crate) unsafe fn alloc_mgp_type() -> *mut mgp_type { malloc(size_of::<mgp_type>()) as *mut mgp_type } pub(crate) unsafe fn alloc_mgp_value() -> *mut mgp_value { malloc(size_of::<mgp_...
$c_func_name.expect().times(1).returning($rs_return_func); }; } #[macro_export] macro_rules! with_dummy { ($rs_test_func:expr) => { let memgraph = Memgraph::new_default(); $rs_test_func(&memgraph); }; (List, $rs_test_func:expr) => { ...
malloc(size_of::<mgp_path>()) as *mut mgp_path } pub(crate) unsafe fn alloc_mgp_date() -> *mut mgp_date { malloc(size_of::<mgp_date>()) as *mut mgp_date } pub(crate) unsafe fn alloc_mgp_local_time() -> *mut mgp_local_time { malloc(size_of::<mgp_local_time>()) as *mut mgp_local_t...
random
[ { "content": "/// Combines the given array of types from left to right to construct [mgp_type]. E.g., if the\n\n/// input is [Type::List, Type::Int], the constructed [mgp_type] is going to be list of integers.\n\nfn resolve_mgp_type(types: &[Type]) -> *mut mgp_type {\n\n unsafe {\n\n let mut mgp_type_...
Rust
whisper/src/bin/whisper-create.rs
GiantPlantsSociety/graphite-rs
d2657ae3ddf110023417ec255f5192ac8fa83bfc
use humansize::{file_size_opts as options, FileSize}; use std::error::Error; use std::fs; use std::path::PathBuf; use std::process::exit; use structopt::StructOpt; use whisper::aggregation::AggregationMethod; use whisper::retention::Retention; use whisper::WhisperBuilder; #[derive(Debug, StructOpt)] #[structopt(name =...
use humansize::{file_size_opts as options, FileSize}; use std::error::Error; use std::fs; use std::path::PathBuf; use std::process::exit; use structopt::StructOpt; use whisper::aggregation::AggregationMethod; use whisper::retention::Retention; use whisper::WhisperBuilder; #[derive(Debug, StructOpt)] #[structopt(name =...
number, (number * 1000_usize * disk_size) .file_size(&custom_options) .unwrap() ); } } fn run(args: &Args) -> Result<(), Box<dyn Error>> { if args.estimate { estimate_info(&args.retentions); } else { if args.overwrite && args.path.ex...
me = "path", parse(from_os_str))] path: PathBuf, #[structopt( name = "retentions", help = r#"Specify lengths of time, for example: 60:1440 60 seconds per datapoint, 1440 datapoints = 1 day of retention 15m:8 15 minutes per datapoint, 8 datapoints = 2 hours of retention 1h:7d ...
random
[ { "content": "#[derive(Debug, StructOpt)]\n\n#[structopt(name = \"rrd2whisper\")]\n\nstruct Args {\n\n /// The xFilesFactor to use in the output file. Defaults to the input RRD's xFilesFactor.\n\n #[structopt(long = \"xFilesFactor\")]\n\n x_files_factor: Option<f64>,\n\n\n\n /// The consolidation fu...
Rust
src/main.rs
erikjohnston/matrix-media-store-size
16055e1964c58f2f35bdff1e888e84d963a1c37a
#[macro_use] extern crate clap; extern crate humansize; extern crate linear_map; extern crate rand; extern crate rusqlite; extern crate twox_hash; extern crate walkdir; extern crate indicatif; use humansize::{FileSize, file_size_opts as options}; use clap::{App, Arg}; use linear_map::LinearMap; use rand::Rng; use st...
#[macro_use] extern crate clap; extern crate humansize; extern crate linear_map; extern crate rand; extern crate rusqlite; extern crate twox_hash; extern crate walkdir; extern crate indicatif; use humansize::{FileSize, file_size_opts as options}; use clap::{App, Arg}; use linear_map::LinearMap; use rand::Rng; use st...
.len()) as u64); } } } pb.finish(); println!(); println!( "Total wasted size: {} out of {}. Percentage: {:.2}%", total_wasted_size.file_size(options::CONVENTIONAL).unwrap(), total_size.file_size(options::CONVENTIONAL).unwrap(), (total_wasted_size * 1...
"); } let wasted = file_size * (paths.len() - 1); total_wasted_size += wasted; pb.inc((file_size * paths
random
[]
Rust
src/entities.rs
brooks-builds/improve_skills_by_building_ecs_library_in_rust
d8131b0b6a963456fd4c2ad94382924060847905
pub mod query; pub mod query_entity; use std::{ any::{Any, TypeId}, cell::RefCell, collections::HashMap, rc::Rc, vec, }; use eyre::Result; use crate::custom_errors::CustomErrors; pub type Component = Rc<RefCell<dyn Any>>; pub type Components = HashMap<TypeId, Vec<Option<Component>>>; #[derive(D...
pub mod query; pub mod query_entity; use std::{ any::{Any, TypeId}, cell::RefCell, collections::HashMap, rc::Rc, vec, }; use eyre::Result; use crate::custom_errors::CustomErrors; pub type Component = Rc<RefCell<dyn Any>>; pub type Components = HashMap<TypeId, Vec<Option<Component>>>; #[derive(D...
Ok(self) } pub fn get_bitmask(&self, type_id: &TypeId) -> Option<u32> { self.bit_masks.get(type_id).copied() } pub fn delete_component_by_entity_id<T: Any>(&mut self, index: usize) -> Result<()> { let type_id = TypeId::of::<T>(); let mask = if let Some(mask) = self.bit...
if let Some(components) = self.components.get_mut(&type_id) { let component = components .get_mut(index) .ok_or(CustomErrors::CreateComponentNeverCalled)?; *component = Some(Rc::new(RefCell::new(data))); let bitmask = self.bit_masks.get(&type_id).unwr...
if_condition
[ { "content": "struct Health(pub u32);\n\n\n\nimpl Health {\n\n pub fn new(data: u32) -> Self {\n\n Self(data)\n\n }\n\n\n\n pub fn lose_health(&mut self, amount: u32) {\n\n self.0 -= amount;\n\n }\n\n\n\n pub fn print_health(&self) {\n\n println!(\"health: {:?}\", **self);\n\...
Rust
src/main.rs
detedetedetedete/DictWalker
81ebbf52a0e124172b7697a1f8ee0748f98ed60e
extern crate serde_json; extern crate encoding; extern crate fern; extern crate clap; extern crate chrono; extern crate regex; #[macro_use] extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; extern crate serde; extern crate libc; use dict_entry::DictEntry; use std::path::...
extern crate serde_json; extern crate encoding; extern crate fern; extern crate clap; extern crate chrono; extern crate regex; #[macro_use] extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; extern crate serde; extern crate libc; use dict_entry::DictEntry; use std::path::...
in(0..) .map(|v| TrainingEntry::construct(v, &mut phoneme_resolvers)) .collect(); let json = match serde_json::to_string_pretty(&t_entries) { Ok(v) => v, Err(e) => { error!("Cannot serialize processed entries to JSON: {}", e); panic!(); } };...
, Box::new(DeadEndPhonemeResolver::new()) ]; let mut entries = match DictEntry::collect_entries( Path::new(dictionary), &HashSet::from_iter(matches.value_of("audio extensions").unwrap().split(",").map(|v| String::from(v))), &HashSet::from_iter(matches.value_of("text extensions"...
function_block-random_span
[ { "content": "fn serialize_phoneme_vec<S>(vec: &Vec<Phoneme>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {\n\n let mut str = String::new();\n\n for ph in vec {\n\n str.push_str(&ph.to_string());\n\n }\n\n serializer.serialize_str(&str)\n\n}\n\n\n\nimpl TrainingEntry {\n\n ...
Rust
src/pixel.rs
B-Reif/asefile
4bb33e1398461b3d153d99ab0830bb87f347dce2
use image::{Pixel, Rgba}; use crate::{reader::AseReader, AsepriteParseError, ColorPalette, PixelFormat, Result}; use std::{borrow::Cow, io::Read}; fn read_rgba(chunk: &[u8]) -> Result<Rgba<u8>> { let mut reader = AseReader::new(chunk); let red = reader.byte()?; let green = reader.byte()?; let blue = r...
use image::{Pixel, Rgba}; use crate::{reader::AseReader, AsepriteParseError, ColorPalette, PixelFormat, Result}; use std::{borrow::Cow, io::Read}; fn read_rgba(chunk: &[u8]) -> Result<Rgba<u8>> { let mut reader = AseReader::new(chunk); let red = reader.byte()?; let green = reader.byte()?; let blue = r...
let pixels: Result<Vec<_>> = bytes.chunks_exact(2).map(Grayscale::new).collect(); pixels.map(Self::Grayscale) } PixelFormat::Rgba => { if bytes.len() % 4 != 0 { return Err(AsepriteParseError::InvalidInput( ...
impl Pixels { fn from_bytes(bytes: Vec<u8>, pixel_format: PixelFormat) -> Result<Self> { match pixel_format { PixelFormat::Indexed { .. } => { let pixels = bytes.iter().map(|byte| Indexed(*byte)).collect(); Ok(Self::Indexed(pixels)) } Pixe...
random
[ { "content": "fn parse_pixel_format(color_depth: u16, transparent_color_index: u8) -> Result<PixelFormat> {\n\n match color_depth {\n\n 8 => Ok(PixelFormat::Indexed {\n\n transparent_color_index,\n\n }),\n\n 16 => Ok(PixelFormat::Grayscale),\n\n 32 => Ok(PixelFormat::Rg...
Rust
modbus_server/src/server_status.rs
guozhaohui/modbus_simulator
3707d068a4ea10925a25f489516d9721b67f5ba0
use rand::Rng; use modbus_protocol::exception_code::{Result, Error, ExceptionCode}; use modbus_protocol::coils::Coil; use modbus_protocol::requests::Requests; enum ModbusRegisterType{ Coil = 0x01, DiscreteInput = 0x02, InputRegister = 0x04, HoldingRegister = 0x03, } pub struct StatusInfo { capacit...
use rand::Rng; use modbus_protocol::exception_code::{Result, Error, ExceptionCode}; use modbus_protocol::coils::Coil; use modbus_protocol::requests::Requests; enum ModbusRegisterType{ Coil = 0x01, DiscreteInput = 0x02, InputRegister = 0x04, HoldingRegister = 0x03, } pub struct StatusInfo { capacit...
fn convert_addr_to_index(self: &Self, register_type: ModbusRegisterType, addr: u16) -> Result<u16> { match register_type { ModbusRegisterType::Coil => { if addr > self.capacity { return Err(Error::Exception(ExceptionCode::IllegalDataAddress)); ...
d::thread_rng().gen_bool(0.5))).collect(); let input_registers: Vec<u16> = (0..size).map(|_| rand::thread_rng().gen_range(0..100)).collect(); let holding_registers = vec![0u16; size]; for i in 0..size { coils[i] = Coil::from(rand::thread_rng().gen_bool(0.5)); } Status...
function_block-function_prefixed
[ { "content": "pub fn unpack_bits(bytes: &[u8], count: u16) -> Vec<Coil> {\n\n let mut res = Vec::with_capacity(count as usize);\n\n for i in 0..count {\n\n if (bytes[(i / 8u16) as usize] >> (i % 8)) & 0b1 > 0 {\n\n res.push(Coil::On);\n\n } else {\n\n res.push(Coil::Off...
Rust
src/n64/cpu/cpu.rs
Protowalker/rustendo64
2e6405bfadd923a3ab6c5ace29d2bdf85b0ae3c4
use super::super::Interconnect; use super::opcode::Opcode::*; use super::opcode::RegImmOpcode::*; use super::opcode::SpecialOpcode::*; use super::{cp0, Instruction}; use std::fmt; const NUM_GPR: usize = 32; enum SignExtendResult { Yes, No, } enum WriteLink { Yes, No, } pub struct Cpu { reg_gpr:...
use super::super::Interconnect; use super::opcode::Opcode::*; use super::opcode::RegImmOpcode::*; use super::opcode::SpecialOpcode::*; use super::{cp0, Instruction}; use std::fmt; const NUM_GPR: usize = 32; enum SignExtendResult { Yes, No, } enum WriteLink { Yes, No, } pub struct Cpu { reg_gpr:...
} fn read_instruction(&self, interconnect: &mut Interconnect, addr: u64) -> Instruction { Instruction(self.read_word(interconnect, addr)) } fn execute_instruction(&mut self, interconnect: &mut Interconnect, instr: Instruction) { match instr.opcode() { Special => { ...
if let Some(pc) = self.delay_slot_pc { let instr = self.read_instruction(interconnect, pc); self.delay_slot_pc = None; self.execute_instruction(interconnect, instr); } else { let instr = self.read_instruction(interconnect, self.reg_pc); self.reg_pc +...
if_condition
[ { "content": "pub fn map_addr(addr: u32) -> Addr {\n\n match addr {\n\n PIF_ROM_START..=PIF_ROM_END => Addr::PifRom(addr - PIF_ROM_START),\n\n PIF_RAM_START..=PIF_RAM_END => Addr::PifRam(addr - PIF_RAM_START),\n\n\n\n CART_DOM1_ADDR2_START..=CART_DOM1_ADDR2_END => Addr::CartDom1(addr - C...
Rust
src/signed_url.rs
mysilkway/tame-gcs
e05ff7af85bd8592f98e4deb3a8900a20d0c0152
use crate::{error::Error, signing, types::ObjectIdentifier}; use percent_encoding as perc_enc; use std::borrow::Cow; use url::Url; pub struct UrlSigner<D, S> { digester: D, signer: S, } #[cfg(feature = "signing")] impl UrlSigner<signing::RingDigest, signing::RingSigner> { pub fn with_ring() -> UrlS...
use crate::{error::Error, signing, types::ObjectIdentifier}; use percent_encoding as perc_enc; use std::borrow::Cow; use url::Url; pub struct UrlSigner<D, S> { digester: D, signer: S, } #[cfg(feature = "signing")] impl UrlSigner<signing::RingDigest, signing::RingSigner> { pub fn with_ring() -> UrlS...
; } let mut signed_url = Url::parse("https://storage.googleapis.com").map_err(Error::UrlParse)?; let resource_path = format!( "/{}/{}", perc_enc::percent_encode(id.bucket().as_ref(), cra...
Err(Error::TooLongExpiration { requested: optional.duration.as_secs(), max: SEVEN_DAYS, })
call_expression
[ { "content": "/// Used to sign a block of data\n\npub trait Signer {\n\n /// Sign a block of data with the specified algorith, and a private key\n\n fn sign(\n\n &self,\n\n algorithm: SigningAlgorithm,\n\n key: Key<'_>,\n\n data: &[u8],\n\n ) -> Result<Vec<u8>, Error>;\n\n}\...
Rust
remote-trait-object-macro/src/service/dispatcher.rs
junha1/baselink-rs
51480ea1635a7c88ad4a13a76d8133aa9110233f
use super::MacroArgs; use crate::create_env_path; use proc_macro2::{Span, TokenStream as TokenStream2}; pub(super) fn generate_dispatcher( source_trait: &syn::ItemTrait, args: &MacroArgs, ) -> Result<TokenStream2, TokenStream2> { if args.no_skeleton { return Ok(TokenStream2::new()); } let ...
use super::MacroArgs; use crate::create_env_path; use proc_macro2::{Span, TokenStream as TokenStream2}; pub(super) fn generate_dispatcher( source_trait: &syn::ItemTrait, args: &MacroArgs, ) -> Result<TokenStream2, TokenStream2> { if args.no_skeleton { return Ok(TokenStream2::new()); } let ...
e_annotation.elems.push(arg_type.clone()); } type_annotation .elems .push_punct(syn::token::Comma(Span::call_site())); let arg_ident = quote::format_ident!("a{}", j + 1); let the_arg = if crate::helper::is_ref(arg_type) .m...
unctuated<syn::Expr, syn::token::Comma> = syn::punctuated::Punctuated::new(); let no_self = "All your method must take &self or &mut self (Object safety)"; let mut_self = match method .sig .inputs .first() .ok_or_else(|| syn::Error::new_spanne...
random
[ { "content": "fn id_method_entry_ident(the_trait: &syn::ItemTrait, method: &syn::TraitItemMethod) -> Ident {\n\n quote::format_ident!(\"ID_METHOD_ENTRY_{}_{}\", the_trait.ident, method.sig.ident)\n\n}\n\n\n", "file_path": "remote-trait-object-macro/src/service/id.rs", "rank": 0, "score": 147821.7...
Rust
src/response.rs
ghairfield/TinyHTTP
9559caa86bb4afb75e6ca2d5a912469b6f881650
use chrono::{DateTime, Local, TimeZone, Utc}; use std::collections::HashMap; use std::fs::{File, Metadata}; use std::io::prelude::*; use std::path::Path; use std::time::SystemTime; use crate::configuration::CONFIG; use crate::protocol::*; use crate::request; #[derive(Debug, Clone, PartialEq)] pub struct ResponseErr...
use chrono::{DateTime, Local, TimeZone, Utc}; use std::collections::HashMap; use std::fs::{File, Metadata}; use std::io::prelude::*; use std::path::Path; use std::time::SystemTime; use crate::configuration::CONFIG; use crate::protocol::*; use crate::request; #[derive(Debug, Clone, PartialEq)] pub struct ResponseErr...
fn post_request(&mut self, _req: &request::Header) { todo!() } fn unsupported_request(&mut self, _req: &request::Header) { todo!() } }
match self.get_resource(req.get_path()) { Ok(_) => self.status = StatusCode::OK, Err(_) => { self.status = StatusCode::NotFound; } } self.content.clear(); }
function_block-function_prefix_line
[ { "content": "/// Get the string representation of a HTTP version\n\npub fn version_to_string(r: &RequestVersion) -> String {\n\n match r {\n\n RequestVersion::SimpleRequest => \"Simple Request\".to_string(),\n\n RequestVersion::HTTP1 => \"HTTP/1.0\".to_string(),\n\n RequestVersion::HTTP...
Rust
cocoon-core/src/message/mod.rs
d42ejh/ilnyaplus-dev
c5f2d04b3d1c6a1b2d6089e583b470779c9b4278
use crate::constant; use bytecheck::CheckBytes; use rkyv::{ ser::{serializers::AllocSerializer, Serializer}, Archive, Deserialize, Infallible, Serialize, }; use std::net::SocketAddr; use tracing::{event, Level}; #[derive(Debug, PartialEq, Eq, FromPrimitive)] pub enum MessageType { PingRequest = 1, Find...
use crate::constant; use bytecheck::CheckBytes; use rkyv::{ ser::{serializers::AllocSerializer, Serializer}, Archive, Deserialize, Infallible, Serialize, }; use std::net::SocketAddr; use tracing::{event, Level}; #[derive(Debug, PartialEq, Eq, FromPrimitive)] pub enum MessageType { PingRequest = 1, Find...
} pub fn from_bytes(bytes: &[u8]) -> (MessageHeader, Self) { let header = MessageHeader::from_bytes(bytes); let archived = rkyv::check_archived_root::<Self>(&bytes[constant::MESSAGE_HEADER_SIZE..]).unwrap(); let msg: Self = archived.deserialize(&mut Infallible).unwrap(); ...
if node.is_some() && data.is_none() { FindValueResponseMessage { key: key.to_vec(), node: Some(*node.unwrap()), data: None, } } else { FindValueResponseMessage { key: key.to_vec(), node: None, ...
if_condition
[]
Rust
src/options.rs
Dentosal/constcodegen
09d61a536d729aeda9639d03a52025b401ab1b53
use std::collections::HashMap; use serde::Deserialize; use crate::constants::Constant; use crate::format_value::*; use crate::template; #[derive(Debug, Deserialize, Default)] #[serde(default, deny_unknown_fields)] pub struct Options { pub codegen: CodegenOptions, lang: HashMap<String, LangOptions>...
use std::collections::HashMap; use serde::Deserialize; use crate::constants::Constant; use crate::format_value::*; use crate::template; #[derive(Debug, Deserialize, Default)] #[serde(default, deny_unknown_fields)] pub struct Options { pub codegen: CodegenOptions, lang: HashMap<String, LangOptions>...
pub fn constant_imports(&self, constant: &Constant) -> Vec<String> { if let Some(type_) = constant.type_.clone() { if let Some(type_opts) = self.types.get(&type_) { return type_opts.import.clone(); } } Vec::new() } } #[derive(Debug, Deserialize,...
g { let t_ctx = HashMap::new(); self.outro .clone() .map(|c| format!("{}\n", template::replace_parameters(&c, &t_ctx))) .unwrap_or_else(String::new) }
function_block-function_prefixed
[ { "content": "pub fn contains_parameter(text: &str, parameter: &str) -> bool {\n\n for cap in RE_PARAM.find_iter(text) {\n\n let name = cap.as_str();\n\n if name != \"$$\" && name == parameter {\n\n return true;\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "src/te...
Rust
websolver/src/ui/view/sudoku.rs
pepijnd/sudoku_web_solver
c3c04da1349d268843772abc5703bec3634a2906
use solver::Cell; use crate::{ ui::controller::{app::AppController, sudoku::SudokuController}, util::InitCell, }; use webelements::{we_builder, Result, WebElement}; #[we_builder( <div class="sdk-sudoku"> <CellBox we_field="cells" we_repeat="81" we_element /> </div> )] #[derive(Debug, Clone)] ...
use solver::Cell; use crate::{ ui::controller::{app::AppController, sudoku::SudokuController}, util::InitCell, }; use webelements::{we_builder, Result, WebElement}; #[we_builder( <div class="sdk-sudoku"> <CellBox we_field="cells" we_repeat="81" we_element /> </div> )] #[derive(Debug, Clone)] ...
if selected == self.cell { self.add_class("selected"); } } self.options.update(sudoku); } } #[we_builder( <div class="cell-indicator"> <div class="indicator top" /> <div class="indicator left" /> <div class="indicator right" /> <d...
Cell, } impl CellBox { pub fn cell(&self) -> Cell { self.cell } pub fn set_cell(&mut self, cell: Cell) { self.cell = cell; self.options.cell = cell; self.indicator.cell = cell; } pub fn update(&self, sudoku: &SudokuController) { let info = sudoku.app.info....
random
[ { "content": "#[cfg(feature = \"worker\")]\n\n#[wasm_bindgen]\n\npub fn solve(sudoku: &JsValue) -> Result<JsValue, JsValue> {\n\n let s: Sudoku = sudoku\n\n .into_serde()\n\n .map_err(|e| JsValue::from_str(&format!(\"{}\", e)))?;\n\n let solve = s.solve_steps();\n\n JsValue::from_serde(&s...
Rust
firm-construction/src/runtime.rs
comprakt/comprakt
2315e85972e63ea327c4d115ffe623253b520440
use libfirm_rs::{types::*, Entity}; use strum_macros::EnumDiscriminants; use crate::type_checking::type_system; #[strum_discriminants(derive(Display))] #[derive(EnumDiscriminants)] pub enum RuntimeFunction { SystemOutPrintln, SystemOutWrite, SystemOutFlush, SystemInRead, New, Dumpstack, Nu...
use libfirm_rs::{types::*, Entity}; use strum_macros::EnumDiscriminants; use crate::type_checking::type_system; #[strum_discriminants(derive(Display))] #[derive(EnumDiscriminants)] pub enum RuntimeFunction { SystemOutPrintln, SystemOutWrite, SystemOutFlush, SystemInRead, New, Dumpstack, Nu...
fn mj_main_name(&self) -> &'static str { "mj_main" } } pub struct Runtime { pub lib: Box<dyn RTLib>, pub system_out_println: Entity, pub system_out_write: Entity, pub system_out_flush: Entity, pub system_in_read: Entity, pub new: Entity, pub dumpstack: Entity, pub nul...
fn ld_name(&self, rtf: RuntimeFunction) -> &'static str { match rtf { RuntimeFunction::SystemOutPrintln => "mjrt_system_out_println", RuntimeFunction::SystemOutWrite => "mjrt_system_out_write", RuntimeFunction::SystemOutFlush => "mjrt_system_out_flush", RuntimeFun...
function_block-full_function
[ { "content": "pub fn dot_string(string: &str) -> String {\n\n format!(\"\\\"{}\\\"\", string.replace(\"\\\"\", \"\\\\\\\"\").replace(\"\\n\", \"\\\\n\"))\n\n}\n", "file_path": "debugging/src/dot/mod.rs", "rank": 0, "score": 206150.33104397444 }, { "content": "// dummy_writer returns a Wri...
Rust
src/chirps.rs
vi/desyncmeasure
ed9767c6d2b52e74133c9a8ba8ce6dbf504a48c2
use std::sync::Arc; pub fn get_buckets() -> [[usize; 4]; 7] { let mut ret = [[0; 4]; 7]; let mut freq = 830; for b in &mut ret { for x in b { *x = freq / 10; freq += 87; } } ret } fn encode_bucket(x: usize) -> [f32; 4] { assert!(x < 4); match x ...
use std::sync::Arc; pub fn get_buckets() -> [[usize; 4]; 7] { let mut ret = [[0; 4]; 7]; let mut freq = 830; for b in &mut ret { for x in b { *x = freq / 10; freq += 87; } } ret } fn encode_bucket(x: usize) -> [f
pub fn number_indexes(mut x: usize) -> [usize; 7] { assert!(x < 4096); let mut idxs = [0; 7]; let mut parity = 0; for i in 0..=5 { idxs[i] = x & 0b11; parity ^= x & 0b11; x >>= 2; } idxs[6] = parity; idxs } pub fn encode_number(x: usize) -> [[f32; 4]; 7] { asse...
32; 4] { assert!(x < 4); match x { 0 => [1.0, 0.0, 0.0, 0.0], 1 => [0.0, 1.0, 0.0, 0.0], 2 => [0.0, 0.0, 1.0, 0.0], 3 => [0.0, 0.0, 0.0, 1.0], _ => unreachable!(), } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let buckets = desyncmeasure::chirps::get_buckets();\n\n\n\n let zeroes = [0.0f32; 800];\n\n\n\n let mut audio_data = Vec::with_capacity(800 * 2 * 8192);\n\n\n\n let fft = rustfft::FftPlanner::<f32>::new().plan_fft_forward(800);\n\n\n\n\n\n for x in 0..4096 {\n\n ...
Rust
mindup_server/src/lib.rs
noogen-projects/mindup
74bcb9288337ea4daba473c55f30fa222c8cb8bc
use borsh::BorshSerialize; pub use dapla_wasm::{alloc, dealloc}; use dapla_wasm::{ database::{execute, query, Value}, WasmSlice, }; use mindup_common::{Response, Task}; use sql_builder::{quote, SqlBuilder, SqlBuilderError}; use thiserror::Error; const TASKS_TABLE_NAME: &str = "Tasks"; #[no_mangle] pub unsafe ...
use borsh::BorshSerialize; pub use dapla_wasm::{alloc, dealloc}; use dapla_wasm::{ database::{execute, query, Value}, WasmSlice, }; use mindup_common::{Response, Task}; use sql_builder::{quote, SqlBuilder, SqlBuilderError}; use thiserror::Error; const TASKS_TABLE_NAME: &str = "Tasks"; #[no_mangle] pub unsafe ...
.map_err(|err| format!("Parse task index error: {:?}", err)) } fn parse_task(source: &str) -> Result<Task, String> { serde_json::from_str(source).map_err(|err| format!("Parse task error: {:?}", err)) } fn process_list() -> Result<Vec<Task>, TaskError> { let sql = SqlBuilder::select_from(TASKS_TABLE_NAME).sq...
completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0,1)) );", table = TASKS_TABLE_NAME )); let data = result .map(drop) .try_to_vec() .expect("Init result should be serializable"); WasmSlice::from(data) } #[no_mangle] pub unsafe extern "C" fn get(uri: ...
random
[ { "content": "fn main() {\n\n yew::start_app::<Root>();\n\n}\n", "file_path": "mindup_client/src/main.rs", "rank": 8, "score": 31229.389855600333 }, { "content": "use std::fmt;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\n#[derive(Debug, Default, Clone, Deserialize, Serialize)]\n\np...
Rust
apis/clyde-3g-eps-api/examples/eps.rs
wau/kubos
074b61738a49ef87fbb08814285fa3173f4f32df
/* * Copyright (C) 2018 Kubos Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or ...
/* * Copyright (C) 2018 Kubos Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance w
, ArrayTempSa1a, ArrayTempSa1b, SunDetectorSa1a, SunDetectorSa1b, VoltageFeedingBcr2, CurrentBcr2Sa2a, CurrentBcr2Sa2b, ArrayTempSa2a, ArrayTempSa2b, SunDetectorSa2a, SunDetectorSa2b, VoltageFeedingBcr3, CurrentBcr3S...
ith the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express ...
random
[ { "content": " const char* file;\n", "file_path": "cmocka/cmocka-1.1.0/include/cmocka.h", "rank": 0, "score": 132737.9092915765 }, { "content": "/// Fetch information about the version(s) of KubOS installed in the system\n\n///\n\n/// Returns the current and previous version(s) of KubOS.\...
Rust
examples/todomvc/src/store.rs
tlively/wasm-bindgen
64e53a5502d92143ff312d461c286cc22522c8ae
use js_sys::JSON; use wasm_bindgen::prelude::*; pub struct Store { local_storage: web_sys::Storage, data: ItemList, name: String, } impl Store { pub fn new(name: &str) -> Option<Store> { let window = web_sys::window()?; if let Ok(Some(local_storage)) = window.local_storage() { ...
use js_sys::JSON; use wasm_bindgen::prelude::*; pub struct Store { local_storage: web_sys::Storage, data: ItemList, name: String, } impl Store { pub fn new(name: &str) -> Option<Store> { let window = web_sys::window()?; if let Ok(Some(local_storage)) = window.local_storage() { ...
self.data = item_list; Some(()) } fn sync_local_storage(&mut self) { let array = js_sys::Array::new(); for item in self.data.iter() { let child = js_sys::Array::new(); child.push(&JsValue::from(&item.title)); child.push(&JsValue::from(it...
if let Ok(Some(value)) = self.local_storage.get_item(&self.name) { let data = JSON::parse(&value).ok()?; let iter = js_sys::try_iter(&data).ok()??; for item in iter { let item = item.ok()?; let item_array: &js_sys::Array = wasm_bindgen::JsCast::dyn_ref...
if_condition
[ { "content": "#[wasm_bindgen]\n\npub fn return_optional_str_none() -> Option<String> {\n\n None\n\n}\n\n\n", "file_path": "tests/wasm/simple.rs", "rank": 0, "score": 469336.6002525708 }, { "content": "#[wasm_bindgen]\n\npub fn take_optional_str_none(x: Option<String>) {\n\n assert!(x.i...
Rust
circlemud_ffi_client/src/slack_descriptor.rs
medwards/CircleMUD
f24154b52cceec7df93d750816c4aea7e332cc29
use std::collections::{HashMap, HashSet}; use std::sync::mpsc; use std::sync::Mutex; use std::thread; use slack_morphism::prelude::*; use slack_morphism_hyper::*; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response}; use log::*; use tokio::runtime::Runtime; use std::sync::Arc; use...
use std::collections::{HashMap, HashSet}; use std::sync::mpsc; use std::sync::Mutex; use std::thread; use slack_morphism::prelude::*; use slack_morphism_hyper::*; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Response}; use log::*; use tokio::runtime::Runtime; use std::sync::Arc; use...
channel: Arc::new(Mutex::new(input_channel)), channel_id: channel_id, identifier: identifier, user_id: 0, } } async fn send_message( &self, content: SlackMessageContent, ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> { info!( ...
ror::Error + Send + Sync>> { let addr = std::env::var("SLACK_SOCKET_ADDR") .unwrap_or("127.0.0.1:8000".to_owned()) .parse() .expect("Invalid SLACK_SOCKET_ADDR provided"); info!("Loading server: {}", addr); async fn your_others_routes( _req: Request<Body>, ) -> Result<Res...
random
[ { "content": "// TODO: this should probably just require the Read trait\n\npub trait Descriptor: Send + Sync {\n\n fn identifier(&self) -> &DescriptorId;\n\n fn read(&mut self, read_point: &mut [u8]) -> Result<usize, ErrorCode>;\n\n fn write(&mut self, content: String) -> Result<usize, ErrorCode>;\n\n}...
Rust
src/io/sequences_reader.rs
Guilucand/biloki
7c1d710bd03e797584e7f4db151d7b4c7b4433d7
use crate::io::lines_reader::LinesReader; use bstr::ByteSlice; use nix::sys::signal::{self, Signal}; use nix::unistd::Pid; use rand::Rng; use serde::Serialize; use std::fs::File; use std::hint::unreachable_unchecked; use std::intrinsics::unlikely; use std::io::{BufRead, BufReader, Read}; use std::num::Wrapping; use std...
use crate::io::lines_reader::LinesReader; use bstr::ByteSlice; use nix::sys::signal::{self, Signal}; use nix::unistd::Pid; use rand::Rng; use serde::Serialize; use std::fs::File; use std::hint::unreachable_unchecked; use std::intrinsics::unlikely; use std::io::{BufRead, BufReader, Read}; use std::num::Wrapping; use std...
e[IDENT_STATE], seq: &intermediate[SEQ_STATE], qual: None, }); intermediate[SEQ_STATE].clear(); } intermediate[IDENT_STATE].clear(); intermediate[IDENT_STAT...
source, |line: &[u8], finished| { if finished || (line.len() > 0 && line[0] == b'>') { if intermediate[SEQ_STATE].len() > 0 { Self::normalize_sequence(&mut intermediate[SEQ_STATE]); func(FastaSequence { ...
random
[ { "content": "pub fn decompress_file_buffered(file: impl AsRef<Path>, func: impl FnMut(&[u8]) -> Result<(), ()>, buf_size: usize) -> Result<(), LibdeflateError> {\n\n let mut read_file = File::open(file).unwrap();\n\n\n\n let mut input_stream = DeflateChunkedBufferInput::new(|buf| {\n\n read_file.r...
Rust
riddle-image/src/image.rs
LaudateCorpus1/riddle-2
eec60152f2c934a0ebdb627a50286ce05fb6914d
use crate::*; use riddle_common::{Color, ColorElementConversion}; use riddle_math::*; use futures::{AsyncRead, AsyncReadExt}; use std::io::{BufReader, Cursor, Read, Write}; const ERR_PNG_ENCODE_FAILURE: &str = "Failed to encode Png"; const ERR_BMP_ENCODE_FAILURE: &str = "Failed to encode Bmp"; const ERR_JPEG_ENCODE_...
use crate::*; use riddle_common::{Color, ColorElementConversion}; use riddle_math::*; use futures::{AsyncRead, AsyncReadExt}; use std::io::{BufReader, Cursor, Read, Write}; const ERR_PNG_ENCODE_FAILURE: &str = "Failed to encode Png"; const ERR_BMP_ENCODE_FAILURE: &str = "Failed to encode Bmp"; const ERR_JPEG_ENCODE_...
rel_src_rect.dimensions, ); let mut dest_view = self.create_view_mut(rel_dest_rect.clone().convert()); let src_view = source.create_view(abs_src_rec.convert()); for row in 0..(rel_dest_rect.dimensions.y as u32) { let dest = dest_view.get_row_rgba8_mut(row); let src = src_view.get_row_rgba8(row); ...
.convert(); let color: [u8; 4] = color.into(); let location = location.into(); self.img.put_pixel(location.x, location.y, color.into()); } pub fn as_rgba8(&self) -> &[u8] { self.img.as_ref() } pub fn as_rgba8_mut(&mut self) -> &mut [u8] { self.img.as_mut() } ...
random
[ { "content": "pub fn simple<R, F: FnOnce(&AudioSystem) -> Result<R>>(f: F) {\n\n\tlet (audio_system, _main_thread_state) = AudioSystem::new_system_pair().unwrap();\n\n\tlet _r = f(&audio_system).unwrap();\n\n\tlet start_time = Instant::now();\n\n\twhile Instant::now() - start_time < Duration::from_secs(2) {\n\n...
Rust
src/lang.rs
alamminsalo/ram
22ecebf41d1919e8f996779dc8fccb6a80740c88
use super::assets::Assets; use super::util; use super::Model; use failure::Fallible; use handlebars::Handlebars; use handlebars::*; use itertools::Itertools; use maplit::hashmap; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; #[derive(Debug, Deseri...
use super::assets::Assets; use super::util; use super::Model; use failure::Fallible; use handlebars::Handlebars; use handlebars::*; use itertools::Itertools; use maplit::hashmap; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; #[derive(Debug, Deseri...
pub fn default_path(&self, path: &str) -> PathBuf { PathBuf::from( &self .paths .get(path) .expect(&format!("failed to find default path: {}", path)), ) } pub fn files_relative(&self) -> Vec<AddFile> { self.files ...
json" | _ => serde_json::from_str(&data)?, }; lang.path = pathbuf .parent() .expect("failed to get lang parent dir") .to_owned(); if lang.paths.get("root") == None { lang.paths.insert("root".into(), "".into()); } ...
function_block-function_prefix_line
[ { "content": "pub fn register_helpers(hb: &mut Handlebars) {\n\n hb.register_helper(\"lowercase\", Box::new(lowercase));\n\n hb.register_helper(\"uppercase\", Box::new(uppercase));\n\n hb.register_helper(\"pascalcase\", Box::new(pascalcase));\n\n hb.register_helper(\"snakecase\", Box::new(snakecase)...
Rust
src/curve25519/point.rs
cronokirby/eddo
015b8ce77249605f2f760ea5d907a0e6e1ea79bd
use std::{ convert::{TryFrom, TryInto}, ops::{Add, Mul}, }; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq}; use super::{arithmetic::U256, error::SignatureError, field::Z25519, scalar::Scalar}; const D: Z25519 = Z25519 { value: U256 { limbs: [ 0x75eb4dca135978a3, ...
use std::{ convert::{TryFrom, TryInto}, ops::{Add, Mul}, }; use subtle::{Choice, ConditionallySelectable, ConstantTimeEq}; use super::{arithmetic::U256, error::SignatureError, field::Z25519, scalar::Scalar}; const D: Z25519 = Z25519 { value: U256 { limbs: [ 0x75eb4dca135978a3, ...
#[must_use] fn doubled(&self) -> Point { let a = self.x.squared(); let b = self.y.squared(); let c = self.z.squared() * 2; let h = a + b; let e = h - (self.x + self.y).squared(); let g = a - b; let f = c + g; Point { ...
9) -> Point { Point { x, y, z: Z25519::from(1), t: x * y, } }
function_block-function_prefixed
[ { "content": "/// Represents a \"hash value\", as described in Section 6:\n\n/// https://datatracker.ietf.org/doc/html/rfc6234#section-6\n\n///\n\n/// This can be thought of as the ongoing state of our hash function,\n\n/// which gets modified using our message blocks.\n\nstruct HashValue {\n\n data: [u64; 8...
Rust
src/pointer/raw.rs
oliver-giersch/reclaim
ab55cb7eb9078376597dcdbaa298daeb9bf22d0b
use core::cmp::{self, PartialEq, PartialOrd}; use core::fmt; use core::marker::PhantomData; use core::ptr::{self, NonNull}; use typenum::{IsGreaterOrEqual, True, Unsigned}; use crate::pointer::{self, MarkedNonNull, MarkedPtr}; /********** impl Clone *******************************************************************...
use core::cmp::{self, PartialEq, PartialOrd}; use core::fmt; use core::marker::PhantomData; use core::ptr::{self, NonNull}; use typenum::{IsGreaterOrEqual, True, Unsigned}; use crate::pointer::{self, MarkedNonNull, MarkedPtr}; /********** impl Clone *******************************************************************...
r: &Self) -> Option<cmp::Ordering> { self.inner.partial_cmp(&other.inner) } } impl<T, N> PartialOrd<MarkedNonNull<T, N>> for MarkedPtr<T, N> { #[inline] fn partial_cmp(&self, other: &MarkedNonNull<T, N>) -> Option<cmp::Ordering> { self.inner.partial_cmp(&other.inner.as_ptr()) } } #[cfg...
Self { let (ptr, tag) = pair; Self::compose(ptr, tag) } } impl<T, N: Unsigned> From<(*const T, usize)> for MarkedPtr<T, N> { #[inline] fn from(pair: (*const T, usize)) -> Self { let (ptr, tag) = pair; Self::compose(ptr as *mut _, tag) } } /********** impl PartialEq ****...
random
[ { "content": "#[inline]\n\nfn compose<T, N: Unsigned>(ptr: *mut T, tag: usize) -> *mut T {\n\n debug_assert_eq!(ptr as usize & mark_mask::<T>(N::USIZE), 0);\n\n ((ptr as usize) | (mark_mask::<T>(N::USIZE) & tag)) as *mut _\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use core::ptr;\n\n\n\n use typenum...
Rust
lib/grammers-client/src/types/chat/mod.rs
the-blank-x/grammers
ad3fd4b7facafccc1eeacbf1df11a67b58d52e60
mod channel; mod group; mod user; use grammers_tl_types as tl; use std::fmt; pub use channel::Channel; pub use group::Group; pub use user::{Platform, RestrictionReason, User}; #[derive(Clone, Debug)] pub enum Chat { User(User), Group(Group), Channel(Channel), } #[repr(u8)] #[derive(Cl...
mod channel; mod group; mod user; use grammers_tl_types as tl; use std::fmt; pub use channel::Channel; pub use group::Group; pub use user::{Platform, RestrictionReason, User}; #[derive(Clone, Debug)] pub enum Chat { User(User), Group(Group), Channel(Channel), } #[repr(u8)] #[derive(Cl...
lf::User(user) => user.access_hash(), Self::Group(group) => group.access_hash(), Self::Channel(channel) => channel.access_hash(), } } pub fn name(&self) -> &str { match self { Self::User(user) => user.first_name(), Se...
Self::Channel(channel) => Some(channel.to_input()), } } pub(crate) fn to_chat_id(&self) -> Option<i32> { match self { Self::User(_) => None, Self::Group(group) => group.to_chat_id(), Self::Channel(_) => None, } } ...
random
[ { "content": "fn message_channel_id(message: &tl::enums::Message) -> Option<i32> {\n\n match message {\n\n tl::enums::Message::Empty(_) => None,\n\n tl::enums::Message::Message(m) => match &m.peer_id {\n\n tl::enums::Peer::Channel(c) => Some(c.channel_id),\n\n _ => None,\n...
Rust
edgelet/edgelet-http-workload/src/edge_ca.rs
brotherneeru/iotedge
830259ad2f748db58f7271101ed58fdf5fc7bf3f
#[cfg(not(test))] use aziot_cert_client_async::Client as CertClient; #[cfg(not(test))] use aziot_key_client_async::Client as KeyClient; #[cfg(not(test))] use aziot_key_openssl_engine as KeyEngine; #[cfg(test)] use test_common::client::CertClient; #[cfg(test)] use test_common::client::KeyClient; #[cfg(test)] use test...
#[cfg(not(test))] use aziot_cert_client_async::Client as CertClient; #[cfg(not(test))] use aziot_key_client_async::Client as KeyClient; #[cfg(not(test))] use aziot_key_openssl_engine as KeyEngine; #[cfg(test)] use test_common::client::CertClient; #[cfg(test)] use test_common::client::KeyClient; #[cfg(test)] use test...
async fn renew_cert( &mut self, old_cert_chain: &[openssl::x509::X509], key_id: &str, ) -> Result<(Vec<openssl::x509::X509>, Self::NewKey), cert_renewal::Error> { let (key_id, key_handle) = { let key_client = self.key_client.lock().await; if se...
async fn get_key( &mut self, key_id: &str, ) -> Result<openssl::pkey::PKey<openssl::pkey::Private>, cert_renewal::Error> { let key_client = self.key_client.lock().await; let key_handle = key_client .load_key_pair(key_id) .await .map_err(|_| cert_r...
function_block-full_function
[ { "content": "pub fn prepare_cert_uri_module(hub_name: &str, device_id: &str, module_id: &str) -> String {\n\n format!(\"URI: azureiot://{hub_name}/devices/{device_id}/modules/{module_id}\")\n\n}\n", "file_path": "edgelet/edgelet-utils/src/lib.rs", "rank": 0, "score": 326233.4091490721 }, { ...
Rust
httpfs/tests/httpfs.rs
obonobo/ecurl
715d407f287728933cadc35eaad927d02e10ec73
#![allow(clippy::type_complexity)] #[cfg(test)] pub mod test_utils; use crate::test_utils::*; use core::panic; use httpfs::bullshit_scanner::BullshitScanner; use std::{ io::Write, net::TcpStream, sync::{mpsc, Arc, Mutex}, thread, }; use test_utils::better_ureq::*; lazy_static::lazy_static! { stat...
#![allow(clippy::type_complexity)] #[cfg(test)] pub mod test_utils; use crate::test_utils::*; use core::panic; use httpfs::bullshit_scanner::BullshitScanner; use std::{ io::Write, net::TcpStream, sync::{mpsc, Arc, Mutex}, thread, }; use test_utils::better_ureq::*; lazy_static::lazy_static! { stat...
#[test] fn test_multiple_clients_get_same_file() { let server = server(); let contents = "Hello world\n"; let file = TempFile::new("hello.txt", contents).unwrap(); let n = 25; let mut threads = Vec::with_capacity(n); let (taskout, taskin) = mpsc::channel::<Result<(u16, String), ureq::Error>>()...
ct::<Vec<_>>() .join("\n"); assert!(body.contains("hello.txt' is located outside the directory that is being served")) }
function_block-function_prefixed
[ { "content": "fn parse_request_line(scnr: &mut BullshitScanner) -> Result<(Proto, Method, String), ServerError> {\n\n let words = scnr\n\n .next_line()\n\n .map(|l| l.0)\n\n .map_err(|e| ServerError::new().msg(&format!(\"{}\", e)))?\n\n .split_whitespace()\n\n .map(String::...