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
fruity_core/fruity_graphic/src/resources/material_resource.rs
DoYouRockBaby/fruity_game_engine
299a8fe641efb142a551640f6d1aa4868e1ad670
use crate::graphic_service::GraphicService; use crate::resources::shader_resource::ShaderResource; use crate::resources::texture_resource::TextureResource; use fruity_any::*; use fruity_core::introspect::FieldInfo; use fruity_core::introspect::IntrospectObject; use fruity_core::introspect::MethodInfo; use fruity_core::...
use crate::graphic_service::GraphicService; use crate::resources::shader_resource::ShaderResource; use crate::resources::texture_resource::TextureResource; use fruity_any::*; use fruity_core::introspect::FieldInfo; use fruity_core::introspect::IntrospectObject; use fruity_core::introspect::MethodInfo; use fruity_core::...
fn build_material_binding( settings: &Settings, resource_container: Arc<ResourceContainer>, ) -> Option<MaterialSettingsBinding> { match &settings.get::<String>("type", String::default()) as &str { "texture" => { let value = settings.get::<String>("value", String::default()); ...
filter_map(|params| build_material_binding(params, resource_container.clone())) .collect::<Vec<_>>(); let instance_attributes_settings = settings.get::<Vec<Settings>>("instance_attributes", Vec::new()); let mut instance_attributes = HashMap::<String, MaterialSettingsInstanceAttribute>::new(); ...
function_block-function_prefix_line
[ { "content": "/// Build a Settings by reading a yaml document\n\npub fn read_settings(reader: &mut dyn Read) -> Settings {\n\n let mut buffer = String::new();\n\n if let Err(err) = reader.read_to_string(&mut buffer) {\n\n log::error!(\"{}\", err.to_string());\n\n return Settings::Object(Hash...
Rust
crates/lab-core/src/lib.rs
insrcd/labyrinth-game
abb3758f825578a135eb6d058e81a701794de7bb
pub use bevy::{input::mouse::MouseButtonInput, prelude::*, render::camera::*}; pub use crate::interaction::*; pub use crate::tiles::*; pub use crate::world::*; use rand::distributions::{Distribution, Standard}; use rand::Rng; mod interaction; mod systems; mod tiles; mod world; pub mod prelude { pub use crate::*...
pub use bevy::{input::mouse::MouseButtonInput, prelude::*, render::camera::*}; pub use crate::interaction::*; pub use crate::tiles::*; pub use crate::world::*; use rand::distributions::{Distribution, Standard}; use rand::Rng; mod interaction; mod systems; mod tiles; mod world; pub mod prelude { pub use crate::*...
} pub struct AdventureLog { pub logs: Vec<String>, } impl Default for AdventureLog { fn default() -> Self { AdventureLog { logs: Vec::new() } } } impl AdventureLog { pub fn add_message(&mut self, log: String) -> &mut AdventureLog { if self.logs.len() == 0 || self.logs[self.l...
WorldSettings { tile_size: 16., base_player_speed: 8., base_npc_speed: 8., base_scale: 5., } }
function_block-function_prefix_line
[ { "content": "// TODO Re-implement\n\npub fn save_world_system(_world: &mut World, _resources: &mut Resources) {}\n\n\n", "file_path": "crates/lab-world/src/systems.rs", "rank": 0, "score": 218834.2737782919 }, { "content": "pub fn interaction_system(\n\n items: ResMut<Items>,\n\n mut ...
Rust
src/cargo.rs
vmiklos/cargo-llvm-cov
caf9a68bff722ce0b4d6f53a8967051772ed479c
use std::{ ffi::OsStr, path::{Path, PathBuf}, }; use anyhow::{format_err, Context as _, Result}; use camino::{Utf8Path, Utf8PathBuf}; use crate::{ cli::{Args, ManifestOptions, RunOptions}, config::Config, context::Context, env, process::ProcessBuilder, }; pub(crate) struct Workspace { ...
use std::{ ffi::OsStr, path::{Path, PathBuf}, }; use anyhow::{format_err, Context as _, Result}; use camino::{Utf8Path, Utf8PathBuf}; use crate::{ cli::{Args, ManifestOptions, RunOptions}, config::Config, context::Context, env, process::ProcessBuilder, }; pub(crate) struct Workspace { ...
cmd.arg(color.cargo_color()); } cmd.arg("--manifest-path"); cmd.arg(&cx.ws.current_manifest); cmd.arg("--target-dir"); cmd.arg(&cx.ws.target_dir); cx.manifest.cargo_args(cmd); if cx.build.verbose > 1 { cmd.arg(format!("-{}", "v".repeat(cx.build.verbose as usize - 1))); }...
function_block-function_prefix_line
[ { "content": "fn context_from_args(args: &mut Args, show_env: bool) -> Result<Context> {\n\n Context::new(\n\n args.build(),\n\n args.manifest(),\n\n args.cov(),\n\n &args.exclude,\n\n &args.exclude_from_report,\n\n args.doctests,\n\n args.no_run,\n\n s...
Rust
src/handler/routing.rs
Ogeon/rustful
24173f35462a976e53d7826c1b107a995572d132
use std::collections::HashMap; use std::iter::{Iterator, FlatMap}; use std::slice::Split; use std::ops::Deref; use context::MaybeUtf8Owned; pub trait Route<'a> { type Segments: Iterator<Item=&'a [u8]>; fn segment...
use std::collections::HashMap; use std::iter::{Iterator, FlatMap}; use std::slice::Split; use std::ops::Deref; use context::MaybeUtf8Owned; pub trait Route<'a> { type Segments: Iterator<Item=&'a [u8]>; fn segment...
} impl<'a, 'b: 'a, I: 'a, T: 'a> Route<'a> for I where &'a I: IntoIterator<Item=&'a T>, T: Deref, <T as Deref>::Target: Route<'a> + 'b { type Segments = FlatMap<<&'a I as IntoIterator>::IntoIter, <<T as Deref>::Target as Route<'a>>::Segments, fn(&'a T) -> <<T as Deref>::Target as Route<'a>>::Segments>...
fn segments(&'a self) -> <Self as Route<'a>>::Segments { let s = if self.starts_with(b"/") { &self[1..] } else { self }; let s = if s.ends_with(b"/") { &s[..s.len() - 1] } else { s }; if s.len() == 0 { R...
function_block-full_function
[ { "content": "///A trait for request handlers.\n\npub trait Handler: Send + Sync + 'static {\n\n ///Handle a request from the client. Panicking within this method is\n\n ///discouraged, to allow the server to run smoothly.\n\n fn handle(&self, context: Context, response: Response);\n\n\n\n ///Get a ...
Rust
lib/vector-core/src/config/proxy.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use headers::Authorization; use http::uri::InvalidUri; use hyper_proxy::{Custom, Intercept, Proxy, ProxyConnector}; use no_proxy::NoProxy; use url::Url; fn from_env(key: &str) -> Option<String> { std::env::var(key.to_lowercase()) .ok() .or_else(|| std::env::var(key.to_uppercase()).ok()) } #[d...
use headers::Authorization; use http::uri::InvalidUri; use hyper_proxy::{Custom, Intercept, Proxy, ProxyConnector}; use no_proxy::NoProxy; use url::Url; fn from_env(key: &str) -> Option<String> { std::env::var(key.to_lowercase()) .ok() .or_else(|| std::env::var(key.to_uppercase()).ok()) } #[d...
} impl ProxyConfig { fn default_enabled() -> bool { true } pub fn from_env() -> Self { Self { enabled: true, http: from_env("HTTP_PROXY"), https: from_env("HTTPS_PROXY"), no_proxy: from_env("NO_PROXY").map(NoProxy::from).unwrap_or_default(),...
fn default() -> Self { Self { enabled: Self::default_enabled(), http: None, https: None, no_proxy: NoProxy::default(), } }
function_block-full_function
[ { "content": "#[inline]\n\npub fn skip_serializing_if_default<E: Default + PartialEq>(e: &E) -> bool {\n\n e == &E::default()\n\n}\n\n\n", "file_path": "lib/vector-core/src/serde.rs", "rank": 0, "score": 509568.2804817014 }, { "content": "/// grpc doesn't like an address without a scheme,...
Rust
bin/amphora/src/amphora/server/filters.rs
menmos/menmos
9e71569eb1ad93e73476092eb9d63f89c39d2c1e
use std::{convert::Infallible, sync::Arc}; use apikit::auth::user; use interface::StorageNode; use mime::Mime; use warp::Filter; use super::handlers; use crate::Config; const HEALTH_PATH: &str = "health"; const BLOBS_PATH: &str = "blob"; const METADATA_PATH: &str = "metadata"; const VERSION_PATH: &str = "version...
use std::{convert::Infallible, sync::Arc}; use apikit::auth::user; use interface::StorageNode; use mime::Mime; use warp::Filter; use super::handlers; use crate::Config; const HEALTH_PATH: &str = "health"; const BLOBS_PATH: &str = "blob"; const METADATA_PATH: &str = "metadata"; const VERSION_PATH: &str = "version...
::health) } fn put<N>( node: Arc<N>, config: Config, ) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone where N: StorageNode + Send + Sync, { warp::post() .and(user(config.node.encryption_key)) .and(with_node(node)) .and(warp::path(BLOBS_PATH)) ...
N: StorageNode + Send + Sync, { warp::get() .and(warp::path(HEALTH_PATH)) .and(with_node(node)) .and_then(handlers
function_block-random_span
[ { "content": "pub fn ip_address_from_url<S: AsRef<str>>(url: S) -> Result<Ipv4Addr, Error> {\n\n let splitted: Vec<_> = url.as_ref().split('.').collect();\n\n ensure!(splitted.len() >= 2, NameWithoutIp);\n\n\n\n let ip_segment = *splitted.first().unwrap();\n\n let (rest, ip) = ip_address(ip_segment)...
Rust
src/main.rs
ynuwenhof/egui-overlay
da9940b753519ee09d36788be1479403357630ff
use anyhow::bail; use egui::epaint::Shadow; use egui::{Color32, Frame, Window}; use egui_glium::egui_winit::winit::event::Event; use egui_glium::EguiGlium; use glium::glutin::dpi::{PhysicalPosition, PhysicalSize}; use glium::glutin::event::WindowEvent; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium:...
use anyhow::bail; use egui::epaint::Shadow; use egui::{Color32, Frame, Window}; use egui_glium::egui_winit::winit::event::Event; use egui_glium::EguiGlium; use glium::glutin::dpi::{PhysicalPosition, PhysicalSize}; use glium::glutin::event::WindowEvent; use glium::glutin::event_loop::{ControlFlow, EventLoop}; use glium:...
ui.horizontal_wrapped(|ui| { ui.label("Overlay handle: "); ui.colored_label( Color32::from_rgb(110, 255, 110), format!("{:#X}", overlay_handle.0), ); ...
rovided")[2..], 16, ) .expect("invalid window handle"), ); let event_loop = EventLoop::with_user_event(); let display = create_display(&event_loop)?; let mut render_gui = true; let overlay_handle = HWND(match display.gl_window().window().raw_window_handle() { Ra...
random
[ { "content": "# egui-overlay\n\n\n\nWork in progress and proof of concept external [egui](https://crates.io/crates/egui) overlay for windows.\n\n\n\n## Usage\n\n\n\nGet the target window handle and pass it in as an argument.\n\n\n\n```\n\n./egui-overlay 0x27071A\n\n```\n\n\n\nToggle the GUI with the **right shi...
Rust
core-sdk/src/bitboards/mod.rs
TerjeKir/FabChess
ebcdf63db15b1513c0e7ffe69ac5a2ffc84d55ae
use crate::bitboards::bitboards::constants::*; use crate::bitboards::bitboards::*; use crate::bitboards::magic_constants::*; use crate::board_representation::game_state::{ file_of, rank_of, BLACK, CASTLE_ALL, CASTLE_ALL_BLACK, CASTLE_ALL_WHITE, CASTLE_BLACK_KS, CASTLE_BLACK_QS, CASTLE_WHITE_KS, CASTLE_WHITE_QS, WHI...
use crate::bitboards::bitboards::constants::*; use crate::bitboards::bitboards::*; use crate::bitboards::magic_constants::*; use crate::board_representation::game_state::{ file_of, rank_of, BLACK, CASTLE_ALL, CASTLE_ALL_BLACK, CASTLE_ALL_WHITE, CASTLE_BLACK_KS, CASTLE_BLACK_QS, CASTLE_WHITE_KS, CASTLE_WHITE_QS, WHI...
pub fn print_castle_permisssion() { let mut res = [CASTLE_ALL; 64]; res[square::E1] &= !CASTLE_ALL_WHITE; res[square::A1] &= !CASTLE_WHITE_QS; res[square::H1] &= !CASTLE_WHITE_KS; res[square::E8] &= !CASTLE_ALL_BLACK; res[square::A8] &= !CASTLE_BLACK_QS; res[square::H8] &= !CASTLE_BLACK_KS...
s = Vec::with_capacity(0); for sq in 0..64 { let mask = OCCUPANCY_MASKS_BISHOP[sq]; res.push(Magic { occupancy_mask: mask, shift: mask.count_ones() as usize, magic: MAGICS_BISHOP[sq], offset: previous_offset, }); previous_offset += 1 <<...
function_block-function_prefixed
[]
Rust
plugins/websockets_wasm/src/lib.rs
ArtemGr/gun
183b6034d4107d7615a8d00047fdca00bf29cd14
use std::sync::{Arc, Mutex}; use anyhow::Result; use async_std::task; use async_trait::async_trait; use serde_json::{json, Value as JSON}; use gun::{ dedup::{Dedup, random_soul}, GunBuilder, GunOptions, plugins::GunPlugin, ham::mix_ham, util::{lex_from_graph, parse_json, METADATA, SOUL}, }; use wasm_bind...
use std::sync::{Arc, Mutex}; use anyhow::Result; use async_std::task; use async_trait::async_trait; use serde_json::{json, Value as JSON}; use gun::{ dedup::{Dedup, random_soul}, GunBuilder, GunOptions, plugins::GunPlugin, ham::mix_ham, util::{lex_from_graph, parse_json, METADATA, SOUL}, }; use wasm_bind...
se if url.contains("http") { url.replace("http", "wss").into() } else { url.into() } } #[async_trait] impl GunPlugin for WebsocketsWASM { async fn start<'a>(&self, options: &GunOptions<'a>) -> Result<()> { for peer in options.peers { let url = replace_http(peer); let ws = W...
Arc::new(Box::new(WebsocketsWASM::new())); } } fn handle_message(store: &Arc<Mutex<Store>>, msg_str: &str) { store.lock().unwrap().last_msg = Some(msg_str.into()); match parse_json(msg_str) { Some(msg) => { let soul = match msg[SOUL].as_str() { Some(soul) => soul, ...
random
[ { "content": "pub fn next_state(soul: &str, data: &JSON, graph: JSON) -> JSON {\n\n let mut state = json!({});\n\n\n\n if let Some(node) = graph.get(soul) {\n\n let node_state = &node[METADATA][STATE];\n\n\n\n for (key, val) in data.as_object().unwrap().iter() {\n\n state[key] = j...
Rust
src/nia/parser/mod.rs
kerryeon/nia_rust
c5b718b7b56084f6763f69de2b2ede7fc2d851c4
/* ------------------------------------------------------------ Universal Task-Distributed Language Project.Github: "https://github.com/kerryeon/nia_rust" --------------------------------------------------------------- Author: Name: "kerryeon" Email: "besqer996@gnu.ac.kr" Github: "ht...
/* ------------------------------------------------------------ Universal Task-Distributed Language Project.Github: "https://github.com/kerryeon/nia_rust" --------------------------------------------------------------- Author: Name: "kerryeon" Email: "besqer996@gnu.ac.kr" Github: "ht...
arent_index = parent.parent; let grandparent = &mut self.nodes[grandparent_index]; grandparent.insert_left_swap_alert(parent_index, node_index) } fn remove(&mut self, node_index: NodeNum) -> ParseQuery { let node = &mut self.nodes[node_index]; let child_left_index = node.left; ...
path: &str) -> ParseQuery { if self.right != NIL { syntax::inappropriate_token(path, node) } self.right = node_index; node.update(node_index, self.current, self.root) } fn open_bracket(&mut self, node: &mut Node, node_index: NodeNum, path: &str) -> ParseQuery { ...
random
[ { "content": "pub fn inappropriate_token(path: &str, target: &Node) {\n\n let message = if target.config.is_op\n\n { \"This operator can't be here.\" } else\n\n { \"This operand can't be here.\" };\n\n error_target(message, path, target)\n\n}\n\n\n", "file_path": "src/nia/error/syntax.rs", "...
Rust
glyph-brush/src/glyph_brush_indexed/builder.rs
BourgondAries/glyph-brush
123877348b6fbf041e3c68118f7849f9f7c10917
use crate::{Font, FontId, GlyphBrushIndexed, SharedBytes}; use full_rusttype::gpu_cache::{Cache, CacheBuilder}; pub struct GlyphBrushIndexedBuilder<'a> { pub font_data: Vec<Font<'a>>, pub gpu_cache_builder: CacheBuilder, _private_construction: (), } impl<'a> GlyphBrushIndexedBuilder<'a> { pu...
use crate::{Font, FontId, GlyphBrushIndexed, SharedBytes}; use full_rusttype::gpu_cache::{Cache, CacheBuilder}; pub struct GlyphBrushIndexedBuilder<'a> { pub font_data: Vec<Font<'a>>, pub gpu_cache_builder: CacheBuilder, _private_construction: (), } impl<'a> GlyphBrushIndexedBuilder<'a> { pu...
pub fn rebuild<V>(self, brush: &mut GlyphBrushIndexed<'a, V>) { std::mem::replace(brush, self.build()); } }
fonts: self.font_data, texture_cache: self.gpu_cache_builder.build(), glyph_store: <_>::default(), glyphs_custom_layout: None, } }
function_block-function_prefix_line
[ { "content": "#[inline]\n\nfn hash_section_text<H: Hasher>(state: &mut H, text: &[SectionText]) {\n\n for t in text {\n\n let SectionText {\n\n text,\n\n scale,\n\n color,\n\n font_id,\n\n } = *t;\n\n\n\n let ord_floats: &[OrderedFloat<_>] = &[...
Rust
crates/polyhorn-ios/src/raw/builtin.rs
polyhorn/polyhorn
e0a1f2f336643b0519e62adf3b579e6badd90cd5
use polyhorn_ios_sys::polykit::{ PLYImageView, PLYKeyboardAvoidingView, PLYLabel, PLYScrollView, PLYTextInputView, PLYView, PLYViewController, PLYWindow, }; use polyhorn_ios_sys::uikit::UIApplication; use polyhorn_ui::geometry::{Dimension, Size}; use polyhorn_ui::layout::{LayoutNode, MeasureFunc}; use polyhorn_...
use polyhorn_ios_sys::polykit::{ PLYImageView, PLYKeyboardAvoidingView, PLYLabel, PLYScrollView, PLYTextInputView, PLYView, PLYViewController, PLYWindow, }; use polyhorn_ios_sys::uikit::UIApplication; use polyhorn_ui::geometry::{Dimension, Size}; use polyhorn_ui::layout::{LayoutNode, MeasureFunc}; use polyhorn_...
}
Builtin::Label(measure) => container.layout().unwrap().set_measure(measure.clone()), Builtin::Modal => { let view_controller = if let Some(view_controller) = container.downcast_mut::<PLYViewController>() { view_controller } else...
function_block-function_prefix_line
[ { "content": "pub fn parse_token(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Result<Token, Error> {\n\n match input.next() {\n\n Some(TokenTree::Punct(punct)) if punct.as_char() == '<' => {}\n\n Some(TokenTree::Literal(literal)) => return Ok(Token::Literal(literal)),\n\n So...
Rust
jormungandr/src/jrpc/eth_transaction/logic.rs
MitchellTesla/jormungandr-rom_io
2325582d4dced77e2b023b12ffe6d014005078c8
use crate::{ context::Context, intercom::{self, TransactionMsg}, jrpc::{ eth_block_info::get_block_by_number_from_context, eth_types::{ block::Block, block_number::BlockNumber, bytes::Bytes, number::Number, receipt::Receipt, transaction::Transaction, }, ...
use crate::{ context::Context, intercom::{self, TransactionMsg}, jrpc::{ eth_block_info::get_block_by_number_from_context, eth_types::{ block::Block, block_number::BlockNumber, bytes::Bytes, number::Number, receipt::Receipt, transaction::Transaction, }, ...
pub async fn get_transaction_by_block_number_and_index( number: BlockNumber, index: Number, context: &Context, ) -> Result<Option<Transaction>, Error> { let blockchain_tip = context.blockchain_tip()?.get_ref().await; let gas_price = blockchain_tip.ledger().evm_gas_price(); let blockchain = con...
pub async fn get_transaction_by_block_hash_and_index( hash: H256, index: Number, context: &Context, ) -> Result<Option<Transaction>, Error> { let blockchain_tip = context.blockchain_tip()?.get_ref().await; let gas_price = blockchain_tip.ledger().evm_gas_price(); let block = context.blockchain()?...
function_block-full_function
[ { "content": "pub fn new_block_filter(_context: &Context) -> Result<Number, Error> {\n\n // TODO implement\n\n Ok(0.into())\n\n}\n\n\n", "file_path": "jormungandr/src/jrpc/eth_filter/logic.rs", "rank": 3, "score": 466864.84043049027 }, { "content": "pub fn new_pending_transaction_filte...
Rust
src/vtok_agent/src/main.rs
andrewhop/aws-nitro-enclaves-acm
1b7d538da7ae1b470e2ce7d9464dabc3526c99fb
extern crate lazy_static; extern crate log; extern crate nix; extern crate serde; extern crate serde_json; extern crate serde_yaml; extern crate vtok_rpc; mod agent; mod config; mod enclave; mod imds; mod logger; mod ne; mod util; use log::{debug, info}; use nix::sys::signal; use std::fmt; use std::sync::atomic::Or...
extern crate lazy_static; extern crate log; extern crate nix; extern crate serde; extern crate serde_json; extern crate serde_yaml; extern crate vtok_rpc; mod agent; mod config; mod enclave; mod imds; mod logger; mod ne; mod util; use log::{debug, info}; use nix::sys::signal; use std::fmt; use std::sync::atomic::Or...
}
match rusty_main() { Ok(()) => std::process::exit(0), Err(e) => { eprintln!("Error: {}", e); std::process::exit(i32::from(e)) } }
if_condition
[ { "content": "pub fn invalidate_cache() -> Result<(), Error> {\n\n IMDS_CACHE\n\n .lock()\n\n .map(|mut opt| {\n\n opt.take();\n\n })\n\n .map_err(|_| Error::PoisonedLock)\n\n}\n\n\n", "file_path": "src/vtok_agent/src/imds.rs", "rank": 0, "score": 280060.424...
Rust
examples/todo-warp/src/main.rs
juhaku/utoipa
070b00c13b41040e9605c62a0d7c3b5fcf04899c
use std::{net::Ipv4Addr, sync::Arc}; use utoipa::{ openapi::security::{ApiKey, ApiKeyValue, SecurityScheme}, Modify, OpenApi, }; use utoipa_swagger_ui::Config; use warp::{ hyper::{Response, StatusCode}, path::Tail, Filter, Rejection, Reply, }; use crate::todo::Todo; #[tokio::main] async fn main()...
use std::{net::Ipv4Addr, sync::Arc}; use utoipa::{ openapi::security::{ApiKey, ApiKeyValue, SecurityScheme}, Modify, OpenApi, }; use utoipa_swagger_ui::Config; use warp::{ hyper::{Response, StatusCode}, path::Tail, Filter, Rejection, Reply, }; use crate::todo::Todo; #[tokio::main] async fn main()...
r<Extract = impl warp::Reply, Error = warp::Rejection> + Clone { let store = Store::default(); let list = warp::path("todo") .and(warp::get()) .and(warp::path::end()) .and(with_store(store.clone())) .and_then(list_todos); let create = warp::path(...
mut().unwrap(); components.add_security_scheme( "api_key", SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::new("todo_apikey"))), ) } } let api_doc = warp::path("api-doc.json") .and(warp::get()) .map(|| warp::reply::json(&ApiDoc...
random
[]
Rust
src/num.rs
zeta12ti/Checked
71601e376e81949d3e8590c2258741ddc8ffa621
use num_traits::{One, Zero}; use std::fmt; use std::ops::*; use std::cmp::Ordering; #[derive(PartialEq, Eq, Clone, Copy, Hash)] pub struct Checked<T>(pub Option<T>); impl<T> Checked<T> { #[inline] pub fn new(x: T) -> Checked<T> { Checked(Some(x)) }...
use num_traits::{One, Zero}; use std::fmt; use std::ops::*; use std::cmp::Ordering; #[derive(PartialEq, Eq, Clone, Copy, Hash)] pub struct Checked<T>(pub Option<T>); impl<T> Checked<T> { #[inline] pub fn new(x: T) -> Checked<T> { Checked(Some(x)) }...
} impl<T> Zero for Checked<T> where T: Zero, Checked<T>: Add<Checked<T>, Output = Checked<T>>, { fn zero() -> Checked<T> { Checked(Some(T::zero())) } fn is_zero(&self) -> bool { self.deref().as_ref().map_or(false, Zero::is_zero) } } impl<T> One for Checked<T> where T: One...
fn partial_cmp(&self, other: &Checked<T>) -> Option<Ordering> { match (self.deref(), other.deref()) { (&Some(ref x), &Some(ref y)) => PartialOrd::partial_cmp(x, y), _ => None, } }
function_block-full_function
[ { "content": "#[test]\n\nfn mut_ref_option_methods() {\n\n let mut x = Checked::from(1_000_i64);\n\n let mut y = Checked::<i64>::from(None);\n\n\n\n Option::as_mut(&mut x);\n\n Option::as_mut(&mut y);\n\n\n\n println!(\"Numbers in x: \");\n\n for t in x.iter_mut() {\n\n println!(\"{:?}\...
Rust
scutiger-core/src/errors.rs
tsligh33/scutiger
298cc8b1511d40340e59daa3141654e347f244ca
#![allow(unknown_lints)] #![allow(bare_trait_objects)] use std::convert; use std::error; use std::fmt; use std::io; use git2; use pcre2; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExitStatus { Success = 0, NonFatal = 1, Fatal = 2, ExternalProgramFailed = 3, } #[derive(Debug, Clone, Copy, ...
#![allow(unknown_lints)] #![allow(bare_trait_objects)] use std::convert; use std::error; use std::fmt; use std::io; use git2; use pcre2; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ExitStatus { Success = 0, NonFatal = 1, Fatal = 2, ExternalProgramFailed = 3, } #[derive(Debug, Clone, Copy, ...
} impl error::Error for Error { fn description(&self) -> &str { "an unknown error" } } impl PartialEq for Error { fn eq(&self, other: &Self) -> bool { self.kind == other.kind } } impl Error { pub fn new<E: Into<Box<error::Error + Send + Sync>>>( kind: Error...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.kind { ErrorKind::NoSuchRevision => write!(f, "fatal: needed a single revision"), ErrorKind::Conflict => write!(f, "fatal: merge conflict"), ErrorKind::PCREError => match self.internal...
function_block-full_function
[ { "content": "#![allow(unknown_lints)]\n\n#![allow(bare_trait_objects)]\n\n#![allow(ellipsis_inclusive_range_patterns)]\n\n\n\nuse super::errors::{Error, ErrorKind};\n\nuse std::cmp;\n\nuse std::io;\n\n\n\n/// The type of a packet received.\n\n#[derive(Eq, PartialEq, Debug, Copy, Clone)]\n\npub enum PacketType ...
Rust
fuzzer/src/command.rs
barnardb/rust-decimal
a2a8137012058f7a24de093099236ab59ec0845d
use std::fs::File; use std::path::Path; use std::str::FromStr; use rust_decimal::Decimal; #[derive(Serialize, Deserialize)] struct FuzzInput { test: String, left: String, right: String, operator: Op, result: String, } impl FuzzInput { fn new(test_number: u32, a: &String, b: &String, op: Op) -...
use std::fs::File; use std::path::Path; use std::str::FromStr; use rust_decimal::Decimal; #[derive(Serialize, Deserialize)] struct FuzzInput { test: String, left: String, right: String, operator: Op, result: String, } impl FuzzInput { fn new(test_number: u32, a: &String, b: &String, op: Op) -...
let result = match item.operator { Op::Add => a + b, Op::Sub => a - b, Op::Mul => a * b, Op::Div => a / b, }.to_string(); if result.ne(&item.result) { panic!("Result mismatch for test {}: {}", item.test, result); } ...
let b = Decimal::from_str(&item.right) .expect(&format!("Failed to unwrap right for test: {}", item.test));
assignment_statement
[ { "content": "#[inline(always)]\n\nfn rescale(left: &mut [u32; 3], left_scale: &mut u32, right: &mut [u32; 3], right_scale: &mut u32) {\n\n if left_scale == right_scale {\n\n // Nothing to do\n\n return;\n\n }\n\n\n\n enum Target {\n\n Left,\n\n Right,\n\n }\n\n\n\n le...
Rust
implementations/rust/node/src/node.rs
digikata/ockam
015a834ce0d34921b634439d965f726d877fd076
#![allow(dead_code)] use ockam_channel::*; use ockam_common::commands::ockam_commands::*; use ockam_kex::xx::{XXInitiator, XXNewKeyExchanger, XXResponder}; use ockam_kex::CipherSuite; use ockam_message::message::*; use ockam_router::router::*; use ockam_transport::transport::*; use ockam_vault::software::DefaultVault; ...
#![allow(dead_code)] use ockam_channel::*; use ockam_common::commands::ockam_commands::*; use ockam_kex::xx::{XXInitiator, XXNewKeyExchanger, XXResponder}; use ockam_kex::CipherSuite; use ockam_message::message::*; use ockam_router::router::*; use ockam_transport::transport::*; use ockam_vault::software::DefaultVault; ...
} } pub fn receive_channel(&mut self, m: Message) -> Result<(), String> { let mut return_route = m.return_route.clone(); self.channel_address = m.return_route.addresses[0].address.clone(); let pending_opt = self.pending_message.clone(); match pe...
match self .router_tx .send(OckamCommand::Router(RouterCommand::SendMessage(m))) { Ok(()) => Ok(()), Err(_unused) => Err("handle_send failed in TestWorker".into()), }
if_condition
[ { "content": " codec_address_t local_address;\n", "file_path": "implementations/c/ockam/channel/channel_impl.h", "rank": 1, "score": 237120.51070033346 }, { "content": " codec_address_t local_host_address;\n", "file_path": "implementations/c/ockam/channel/channel_impl.h", "rank": 2...
Rust
src/parsers/sequence/tuples_ignore.rs
juliotpaez/jpar
f90e55236de738af1dc05d2beda28ef9aa526f85
use crate::parsers::helpers::not_found_restore; use crate::result::ParserResult; use crate::ParserInput; pub trait TupleIgnore<'a, C, Err> { fn parse(&mut self, reader: &mut ParserInput<'a, Err, C>) -> ParserResult<(), Err>; fn parse_separated<S, RSep>( &mut self, reader: &mut P...
use crate::parsers::helpers::not_found_restore; use crate::result::ParserResult; use crate::ParserInput; pub trait TupleIgnore<'a, C, Err> { fn parse(&mut self, reader: &mut ParserInput<'a, Err, C>) -> ParserResult<(), Err>; fn parse_separated<S, RSep>( &mut self, reader: &mut P...
; let result = parser(&mut reader); assert_eq!(result, Ok(()), "Step: {}", i); assert_eq!( reader.byte_offset(), input.len(), "Step: {} - byte_offset", i ); } } #[test] fn test_tuple5() {...
tuple_ignore(( value.remove(0), value.remove(0), value.remove(0), value.remove(0), ))
call_expression
[ { "content": "/// It is ok only at the end of the input.\n\npub fn end<C, Err>(reader: &mut ParserInput<Err, C>) -> ParserResult<(), Err> {\n\n if reader.is_end() {\n\n Ok(())\n\n } else {\n\n Err(ParserResultError::NotFound)\n\n }\n\n}\n\n\n", "file_path": "src/parsers/combinator.rs"...
Rust
crates/rune/src/macros/macro_compiler.rs
darinmorrison/rune
cdc855efb98fd770c5f5f604550ad40541fec2d8
use crate::macros::{MacroContext, Storage, TokenStream}; use crate::query::Query; use crate::shared::Consts; use crate::CompileResult; use crate::{ ast, CompileError, CompileErrorKind, IrError, Options, Parse, ParseError, Parser, Spanned as _, }; use runestick::{CompileItem, Context, Hash, Source}; use std::sync:...
use crate::macros::{MacroContext, Storage, TokenStream}; use crate::query::Query; use crate::shared::Consts; use crate::CompileResult; use crate::{ ast, CompileError, CompileErrorKind, IrError, Options, Parse, ParseError, Parser, Spanned as _, }; use runestick::{CompileItem, Context, Hash, Source}; use std::sync:...
Err(error) => error, }; let error = match error.downcast::<IrError>() { Ok(error) => return Err(CompileError::from(error)), Err(error) => error, }; let error = match error.downcast::<CompileError>() { ...
macro_call.span(), stream_span: macro_call.stream_span(), source: self.source.clone(), storage: self.storage.clone(), item: self.item.clone(), query: self.query.clone(), consts: self.consts.clone(), }; let result = crate::macros::...
function_block-random_span
[ { "content": "fn as_ptr_impl<T>(this: *const (), expected: Hash) -> Option<*const ()>\n\nwhere\n\n T: Any,\n\n{\n\n if expected == Hash::from_type_id(any::TypeId::of::<T>()) {\n\n Some(this)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "crates/runestick/src/any_obj.rs", ...
Rust
core/src/literals/lit_set.rs
franklinselva/aries
eb0e906012ecd6e22a88c96c0338de64e51c3103
use crate::*; use std::array::TryFromSliceError; use std::convert::{TryFrom, TryInto}; #[derive(Default, Clone, Debug)] pub struct LitSet { elements: Vec<Lit>, } impl LitSet { pub const EMPTY: LitSet = Self { elements: vec![] }; pub fn empty() -> Self { Self::default() } pub fn with_capa...
use crate::*; use std::array::TryFromSliceError; use std::convert::{TryFrom, TryInto}; #[derive(Default, Clone, Debug)] pub struct LitSet { elements: Vec<Lit>, } impl LitSet { pub const EMPTY: LitSet = Self { elements: vec![] }; pub fn empty() -> Self { Self::default() } pub fn with_capa...
}
set.remove(A.leq(1), tauto); assert_eq!(set.elements.len(), 1); assert!(!set.contains(A.leq(1))); assert!(set.contains(A.leq(2))); assert!(!set.contains(A.leq(0))); set.remove(A.leq(3), tauto); assert_eq!(set.elements.len(), 0); }
function_block-function_prefix_line
[ { "content": "pub fn implies(a: impl Into<Lit>, b: impl Into<Lit>) -> Or {\n\n or([!a.into(), b.into()])\n\n}\n\n\n\npub struct Or(Box<[Lit]>);\n\n\n\nimpl Normalize<Disjunction> for Or {\n\n fn normalize(&self) -> NormalExpr<Disjunction> {\n\n let vec = self.0.to_vec();\n\n if let Some(disj...
Rust
src/stream/frame/mod.rs
Delapouite/rust-id3
0e01faa3bb8a4b54c8d538d80dd7c3d7351fca34
use crate::frame::Content; use crate::frame::Frame; use crate::stream::unsynch; use crate::tag; use flate2::read::ZlibDecoder; use std::io; mod content; pub mod v2; mod v3; mod v4; pub fn decode( mut reader: impl io::Read, version: tag::Version, unsynchronization: bool, ) -> crate::Result<Option<(usize, F...
use crate::frame::Content; use crate::frame::Frame; use crate::stream::unsynch; use crate::tag; use flate2::read::ZlibDecoder; use std::io; mod content; pub mod v2; mod v3; mod v4; pub fn decode( mut reader: impl io::Read, version: tag::Versio
pub fn decode_content( reader: impl io::Read, id: &str, compression: bool, unsynchronisation: bool, ) -> crate::Result<Content> { let result = if unsynchronisation { let reader_unsynch = unsynch::Reader::new(reader); if compression { content::decode(id, ZlibDecoder::new...
n, unsynchronization: bool, ) -> crate::Result<Option<(usize, Frame)>> { match version { tag::Id3v22 => unreachable!(), tag::Id3v23 => v3::decode(&mut reader, unsynchronization), tag::Id3v24 => v4::decode(&mut reader), } }
function_block-function_prefixed
[ { "content": "/// Attempts to decode the request.\n\npub fn decode(id: &str, mut reader: impl io::Read) -> crate::Result<Content> {\n\n let mut data = Vec::new();\n\n reader.read_to_end(&mut data)?;\n\n match id {\n\n \"APIC\" => parse_apic_v3(data.as_slice()),\n\n \"PIC\" => parse_apic_v...
Rust
src/search/queries/compound/function_score_query.rs
ypenglyn/elasticsearch-dsl-rs
bff3508055fb20eb54bde78edffa69da3ccbf4eb
use crate::search::*; use crate::util::*; #[derive(Debug, Clone, PartialEq, Serialize)] pub struct FunctionScoreQuery { #[serde(rename = "function_score")] inner: Inner, } #[derive(Debug, Clone, PartialEq, Serialize)] struct Inner { query: Box<Query>, #[serde(skip_serializing_if = "ShouldSkip::should...
use crate::search::*; use crate::util::*; #[derive(Debug, Clone, PartialEq, Serialize)] pub struct FunctionScoreQuery { #[serde(rename = "function_score")] inner: Inner, } #[derive(Debug, Clone, PartialEq, Serialize)] struct Inner { query: Box<Query>, #[serde(skip_serializing_if = "ShouldSkip::should...
pub fn min_score(mut self, min_score: impl Into<f32>) -> Self { self.inner.min_score = Some(min_score.into()); self } pub fn score_mode(mut self, score_mode: FunctionScoreMode) -> Self { self.inner.score_mode = Some(score_mode); self } ...
pub fn max_boost(mut self, max_boost: impl std::convert::TryInto<Boost>) -> Self { if let Ok(max_boost) = max_boost.try_into() { self.inner.max_boost = Some(max_boost); } self }
function_block-full_function
[ { "content": "#[doc(hidden)]\n\npub trait Origin: Debug + PartialEq + Serialize + Clone {\n\n type Scale: Debug + PartialEq + Serialize + Clone;\n\n type Offset: Debug + PartialEq + Serialize + Clone;\n\n}\n\n\n\nimpl Origin for DateTime<Utc> {\n\n type Scale = Time;\n\n type Offset = Time;\n\n}\n\n...
Rust
hal/src/thumbv6m/eic/pin.rs
kadencartwright/atsamd
b5d0f267a436f64f887f5f801d5c25bf4e5e8778
use crate::gpio::{ self, pin::*, AnyPin, FloatingInterrupt, PinId, PinMode, PullDownInterrupt, PullUpInterrupt, }; use crate::pac; pub trait EicPin { type Floating; type PullUp; type PullDown; fn into_floating_ei(self) -> Self::Floating; fn into_pull_up_ei(self) -> Self::PullUp; ...
use crate::gpio::{ self, pin::*, AnyPin, FloatingInterrupt, PinId, PinMode, PullDownInterrupt, PullUpInterrupt, }; use crate::pac; pub trait EicPin { type Floating; type PullUp; type PullDown; fn into_floating_ei(self) -> Self::Floating; fn into_pull_up_ei(self) -> Self::PullUp; ...
c.wakeup.modify(|_, w| { w.[<wakeupen $num>]().set_bit() }) } pub fn disable_interrupt(&mut self, eic: &mut super::EIC) { eic.eic.intenclr.modify(|_, w| { w.[<extint $num>]().set_bit() }); } pub fn is_interrupt(&mut se...
r:meta])* $PinType:ident, )+ } ) => { crate::paste::item! { pub struct [<$PadType $num>]<GPIO> where GPIO: AnyPin, { _pin: Pin<GPIO::Id, GPIO::Mode>, } impl<GPIO: AnyPin> [<$PadType $num>]<GPIO> { ...
random
[]
Rust
tests/substrate.rs
evannetwork/vade-evan
7d37225a4756c7595b03a4901a5e3805654f2f7d
/* Copyright (c) 2018-present evan GmbH. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
/* Copyright (c) 2018-present evan GmbH. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to i...
?; let _detail_count = substrate::get_payload_count_for_did( env::var("VADE_EVAN_SUBSTRATE_IP") .unwrap_or_else(|_| DEFAULT_VADE_EVAN_SUBSTRATE_IP.to_string()), did.clone(), ) .await?; let did_detail1 = substrate::get_did( env::var("VADE_EVAN_SUBSTRATE_IP") ...
are distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ extern crate regex; mod test_data; use regex::Regex; use std::{en...
random
[ { "content": "const copyVadeFiles = `rm -rf dist/${VADE_WASM_FOLDER} && cp -r ${VADE_WASM_FOLDER} dist/${VADE_WASM_FOLDER}`;\n", "file_path": "builds/wasm/package-scripts.js", "rank": 0, "score": 81094.96042363245 }, { "content": "### Fixes\n\n\n\n- add `payload` argument to did_create in CL...
Rust
src/slsm/skiplist/src/run.rs
wellls/pomegranate
de80812be4dc226add4373f28c2cfac331cde4a6
use std::borrow::Borrow; use std::cmp::Ordering; use std::cmp::PartialEq; use std::cmp::PartialOrd; use std::marker::PhantomData; use std::ops::Bound; use crate::node::Node; #[derive(Copy, Clone, Debug)] pub struct KVpair<K, V> { pub key: Option<K>, pub value: Option<V>, } impl<K: Ord, V: Ord> Ord ...
use std::borrow::Borrow; use std::cmp::Ordering; use std::cmp::PartialEq; use std::cmp::PartialOrd; use std::marker::PhantomData; use std::ops::Bound; use crate::node::Node; #[derive(Copy, Clone, Debug)] pub struct KVpair<K, V> { pub key: Option<K>, pub value: Option<V>, } impl<K: Ord, V: Ord> Ord ...
fn size_hint(&self) -> (usize, Option<usize>) { (self.size, Some(self.size)) } } pub trait Run<K, V> { fn new() -> Self; fn get_min(&mut self) -> Option<K>; fn get_max(&mut self) -> Option<K>; fn insert_key(&mut self, key: K, value: V); fn delete_key<Q: ?Sized>(&mut self, key: &Q)...
1; } return Some(( (*self.start).key.as_ref().unwrap(), (*self.start).value.as_ref().unwrap(), )); } None } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n println!(\"Hello, world!\");\n\n}\n", "file_path": "src/slsm/src/main.rs", "rank": 1, "score": 30506.230729615927 }, { "content": "pub trait LevelGenerator {\n\n fn total(&self) -> usize;\n\n\n\n fn random(&mut self) -> usize;\n\n}\n\n\n\npub struct Geo...
Rust
src/aoc2021/day22.rs
h3fang/adventofcode
4649dea7f7e82037c1cf9f1c5b6683962923ba33
use regex::Regex; #[derive(Debug, Clone, PartialEq)] struct LineSegment { start: i32, end: i32, } impl LineSegment { fn new(start: i32, end: i32) -> Self { debug_assert!(start <= end); Self { start, end } } fn size(&self) -> usize { (self.end - self.start + 1) as usize ...
use regex::Regex; #[derive(Debug, Clone, PartialEq)] struct LineSegment { start: i32, end: i32, } impl LineSegment { fn new(start: i32, end: i32) -> Self { debug_assert!(start <= end); Self { start, end } } fn size(&self) -> usize { (self.end - self.start + 1) as usize ...
}
10)), a.intersection(&LineSegment::new(3, 20)) ); assert_eq!( Some(LineSegment::new(1, 5)), a.intersection(&LineSegment::new(1, 5)) ); }
function_block-function_prefixed
[ { "content": "fn parse(data: &str) -> (Vec<bool>, Image) {\n\n let mut parts = data.split(\"\\n\\n\");\n\n let algo = parts\n\n .next()\n\n .unwrap()\n\n .as_bytes()\n\n .iter()\n\n .map(|p| *p == b'#')\n\n .collect::<Vec<_>>();\n\n assert_eq!(512, algo.len());...
Rust
src/main.rs
grant0417/neural_net
8c6f6818c732967e2cc69e64676d19f46545bb86
use nalgebra::{DMatrix, Dynamic, MatrixXx1, U1}; use rand::prelude::*; use serde::{Deserialize, Serialize}; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::path::Path; struct MnistDataset { records: Vec<MnistRecord>, } struct MnistRecord { target: usize, targets: Vec<f32>, inputs: Vec...
use nalgebra::{DMatrix, Dynamic, MatrixXx1, U1}; use rand::prelude::*; use serde::{Deserialize, Serialize}; use std::fs::File; use std::io::{BufReader, BufWriter}; use std::path::Path; struct MnistDataset { records: Vec<MnistRecord>, } struct MnistRecord { target: usize, targets: Vec<f32>, inputs: Vec...
fn mnist_train(&mut self, epochs: usize) -> Result<(), String> { let dataset = load_mnist_data("data/mnist_train.csv")?.records; let start = std::time::Instant::now(); for epoch in 0..epochs { println!("Epoch {}/{}...", epoch + 1, epochs); for ( i,...
uts = &self.output_weights * &hidden_outputs; final_outputs.apply(sigmoid); let targets = MatrixXx1::from_column_slice(target_data); let output_errors = targets - &final_outputs; let hidden_errors = &self.output_weights.transpose() * &output_errors; self.outpu...
function_block-function_prefixed
[ { "content": "# Neural Net\n\n\n\nCreated a 2-layer neural network that can classify digits in the\n\n[MNIST dataset](https://en.wikipedia.org/wiki/MNIST_database)\n\nwith 98.1% accuracy with the pretrained model (data/pretrained.model).\n\n\n\nThe model was trained with 800 hidden layers with a 5% learning\n\n...
Rust
oot-explorer-web/src/reflect_value.rs
mvanbem/oot-explorer
a2574ac5d2c3b2eb8bc6229e887b0ad7ff0fe732
use oot_explorer_read::{FromVrom, Layout}; use oot_explorer_reflect::{PrimitiveType, StructFieldLocation, TypeDescriptor}; use oot_explorer_segment::{SegmentAddr, SegmentTable}; use oot_explorer_vrom::{Vrom, VromAddr}; use serde::Serialize; use std::fmt::{Debug, Display}; use std::ops::Range; use wasm_bindgen::prelude:...
use oot_explorer_read::{FromVrom, Layout}; use oot_explorer_reflect::{PrimitiveType, StructFieldLocation, TypeDescriptor}; use oot_explorer_segment::{SegmentAddr, SegmentTable}; use oot_explorer_vrom::{Vrom, VromAddr}; use serde::Serialize; use std::fmt::{Debug, Display}; use std::ops::Range; use wasm_bindgen::prelude:...
} } pub fn reflect_field( vrom: Vrom<'_>, segment_table: &SegmentTable, base_addr: VromAddr, field_name: Option<String>, location: &StructFieldLocation, desc: TypeDescriptor, ) -> ReflectResult { let type_string = desc.name().to_string() + match location { Stru...
reflect_field( vrom, &root.segment_table, self.base_addr, self.name.clone(), &self.location, self.desc, )
call_expression
[ { "content": "pub fn aligned_data<T: Layout>(vrom: Vrom<'_>, addr: VromAddr) -> Result<&[u8], ReadError> {\n\n check_alignment::<T>(addr)?;\n\n Ok(vrom.slice(addr..addr + T::SIZE)?)\n\n}\n", "file_path": "oot-explorer-read/src/layout.rs", "rank": 1, "score": 204324.87377395522 }, { "co...
Rust
logic/src/parse/if.rs
bailion/compiler
3c5bd1b51503467f4a60ab90983f380c31afe154
use std::fmt::{self, Write}; use crate::{ diagnostics::span::Span, parse::utils::{write_indentation, ParseError}, }; use super::{block::Block, expr::Expr, ident::Ident, utils::Parse}; #[derive(Debug, PartialEq, Eq)] pub struct If<'a, IDENT = Ident<'a>, EXPR = Expr<'a>> { pub(crate) r#if: Branch<'a, IDENT...
use std::fmt::{self, Write}; use crate::{ diagnostics::span::Span, parse::utils::{write_indentation, ParseError}, }; use super::{block::Block, expr::Expr, ident::Ident, utils::Parse}; #[derive(Debug, PartialEq, Eq)] pub struct If<'a, IDENT = Ident<'a>, EXPR = Expr<'a>> { pub(crate) r#if: Branch<'a, IDENT...
; } } } } impl fmt::Display for If<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("if ")?; self.r#if.condition.fmt(f)?; f.write_str(" then")?; f.write_char('\n')?; self.r#if.block.fmt(f)?; f.writ...
Ok(Self { r#if, else_ifs: elseifs, r#else: None, indent: input.indent, span: rec.finish_recording(input), })
call_expression
[ { "content": "fn tagged_ret<'a>(ret: Return<'a>, ctx: &mut TaggingCtx<'a>) -> Return<'a, TaggedExpr<'a>> {\n\n Return {\n\n expr: tagged_expr(ret.expr, ctx),\n\n indent: ret.indent,\n\n _a: PhantomData,\n\n }\n\n}\n\n\n", "file_path": "logic/src/id/mod.rs", "rank": 0, "sco...
Rust
src/main.rs
gwadej/quikdecision-web
9e276872c6f8c0cc4bf9ad5ddcbfe5e49356e1af
extern crate futures; extern crate hyper; extern crate quikdecision; extern crate qdweb; use futures::future; use hyper::rt::Future; use hyper::service::service_fn; use hyper::{Body, Method, Request, Response, Server, StatusCode}; use std::path::{Path,PathBuf}; use std::fs::File; use std::io::prelude::*; use std::ffi:...
extern crate futures; extern crate hyper; extern crate quikdecision; extern crate qdweb; use futures::future; use hyper::rt::Future; use hyper::service::service_fn; use hyper::{Body, Method, Request, Response, Server, StatusCode}; use std::path::{Path,PathBuf}; use std::fs::File; use std::io::prelude::*; use std::ffi:...
match uri_path.strip_prefix("/static/") { Ok(path) => { let file = Path::new("static/").join(path); let content_type = find_type(file.extension()); match load_file(file.to_str().unwrap()) { Ok(content) => builder .h...
if has_path_traverse(&uri_path) { return builder .status(StatusCode::NOT_FOUND) .body(Body::from("Invalid path")) .unwrap(); }
if_condition
[ { "content": "pub fn process_command(cmdres: Result<Command>) -> Response<Body>\n\n{\n\n let mut builder = Response::builder();\n\n let body = match cmdres\n\n {\n\n Ok(cmd) => {\n\n Body::from(match cmd.decide()\n\n {\n\n Decision::Text(value) => { json!({ \...
Rust
sylt/src/test.rs
sylt-lang/sylt-lang
1b7ec677581cf1d9327d1faff1152a922db7cd1a
use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use sylt_common::error::Error; #[derive(Debug, Clone)] pub enum TestableError { Type(String), Runtime, Syntax(Option<usize>), Containing(String), } #[derive(Debug, Clone)] pub struct TestSettings { pub path: PathBuf, pub erro...
use std::fmt; use std::path::{Path, PathBuf}; use std::str::FromStr; use sylt_common::error::Error; #[derive(Debug, Clone)] pub enum TestableError { Type(String), Runtime, Syntax(Option<usize>), Containing(String), } #[derive(Debug, Clone)] pub struct TestSettings { pub path: PathBuf, pub erro...
{ format!("{:?}", a).contains(msg) || format!("{}", a).contains(msg) } _ => false, }) } pub fn write_errors(result: &[Error], expected: &[TestableError]) { eprintln!("* GOT {} ERRORS", result.len()); for err in result.iter() { eprintln!(" {}", err); ...
result .iter() .zip(expected.iter()) .all(|(a, b)| match (a, b) { (Error::SyntaxError { span, .. }, TestableError::Syntax(Some(line))) => { span.line_start == *line } (Error::SyntaxError { .. }, TestableError::Syntax(None)) => true, ...
function_block-random_span
[ { "content": "#[sylt_macro::timed(\"parser::tree\")]\n\npub fn tree<F>(path: &Path, reader: F, bundle_std: bool) -> Result<AST, Vec<Error>>\n\nwhere\n\n F: Fn(&Path) -> Result<String, Error>,\n\n{\n\n // Files we've already parsed. This ensures circular includes don't parse infinitely.\n\n let mut visi...
Rust
lib/src/sync.rs
galenbwill/tpscube
842ce0d874af78056bc6a90e5773d7f907a91f54
use crate::request::{SyncRequest, SyncResponse}; use anyhow::{anyhow, Result}; use serde_json::Value; use std::sync::{Arc, Mutex}; #[cfg(feature = "native-storage")] use http::StatusCode; #[cfg(feature = "native-storage")] use reqwest::{ blocking::Client, header::{HeaderValue, CONTENT_TYPE, USER_AGENT}, }; #[...
use crate::request::{SyncRequest, SyncResponse}; use anyhow::{anyhow, Result}; use serde_json::Value; use std::sync::{Arc, Mutex}; #[cfg(feature = "native-storage")] use http::StatusCode; #[cfg(feature = "native-storage")] use reqwest::{ blocking::Client, header::{HeaderValue, CONTENT_TYPE, USER_AGENT}, }; #[...
#[cfg(feature = "native-storage")] fn execute_native(request: String) -> Result<SyncResponse> { let client = Client::new(); let result = client .post(ENDPOINT) .header(USER_AGENT, HeaderValue::from_static("tpscube")) .header(CONTENT_TYPE, HeaderValue::from_s...
operation_copy.lock().unwrap().response = Some(result); }); #[cfg(feature = "web-storage")] spawn_future(async move { let result = Self::execute(&operation_copy).await; operation_copy.lock().unwrap().response = Some(result); }); operation }
function_block-function_prefix_line
[ { "content": "#[cfg(target_arch = \"wasm32\")]\n\n#[wasm_bindgen]\n\npub fn start(canvas_id: &str) -> Result<(), JsValue> {\n\n let app: Box<dyn app::App> = match app::Application::new() {\n\n Ok(app) => Box::new(app),\n\n Err(error) => Box::new(app::ErrorApplication::new(error.to_string())),\n...
Rust
aoc_2021/src/day_14/mod.rs
dragonrider7225/AdventOfCode
ee0f5695bf8aa5d79aad1d2aa2fb5f07c9a3ae4b
use std::{ collections::HashMap, fs::File, hash::Hash, io::{self, BufRead, BufReader}, mem, }; struct Polymer { len: u64, pairs: HashMap<(char, char), u64>, counts: HashMap<char, u64>, rules: HashMap<(char, char), char>, } impl Polymer { fn read(input: &mut dyn BufRead) -> io::...
use std::{ collections::HashMap, fs::File, hash::Hash, io::{self, BufRead, BufReader}, mem, }; struct Polymer { len: u64, pairs: HashMap<(char, char), u64>, counts: HashMap<char, u64>, rules: HashMap<(char, char), char>, } impl Polymer { fn read(input: &mut dyn BufRead) -> io::...
} fn part1(input: &mut dyn BufRead) -> io::Result<u64> { let mut polymer = Polymer::read(input)?; for _ in 0..10 { polymer.polymerize(); } Ok(polymer.counts().values().max().unwrap() - polymer.counts().values().min().unwrap()) } fn part2(input: &mut dyn BufRead) -> io::Result<u64> { let m...
fn polymerize(&mut self) { fn update_entry<K>(map: &mut HashMap<K, u64>, key: K, count: u64) where K: Eq + Hash, { *map.entry(key).or_default() += count; } for ((left, right), count) in mem::take(&mut self.pairs) { let center = self.rules.get(...
function_block-full_function
[ { "content": "fn part1(input: &mut dyn BufRead) -> io::Result<u64> {\n\n a_star::run_a_star_for_distance(State::read(input)?, amphipod_heuristic)\n\n .ok_or_else(|| io::Error::new(io::ErrorKind::Other, \"Couldn't find path to sorted state\"))\n\n}\n\n\n", "file_path": "aoc_2021/src/day_23/mod.rs",...
Rust
server/src/application/metaapi.rs
sia-services/foundation-rs
1e185c4ff48b3d8e7d4cbf686fe2f45a4a1e0669
use std::collections::HashSet; use std::iter::FromIterator; use std::sync::Arc; use actix_web::dev::HttpServiceFactory; use actix_web::{get, web, HttpResponse, Responder}; use serde::Serialize; use crate::metainfo::{ColumnType,EntityType}; use super::ApplicationState; pub fn metainfo_scope() -> impl HttpServiceFact...
use std::collections::HashSet; use std::iter::FromIterator; use std::sync::Arc; use actix_web::dev::HttpServiceFactory; use actix_web::{get, web, HttpResponse, Responder}; use serde::Serialize; use crate::metainfo::{ColumnType,EntityType}; use super::ApplicationState; pub fn metainfo_scope() -> impl HttpServiceFact...
; let columns = info .columns .iter() .enumerate() .map(|(ref i, c)| { let is_pk = pk_indices.contains(i); ColumnMetaInfo { name: c.name.as_str(), col_ty...
match &info.primary_key { Some(pk) => { HashSet::from_iter(pk) }, None => { HashSet::new() } }
if_condition
[ { "content": "pub fn load_columns(\n\n conn: &Connection,\n\n available_schemas: &str,\n\n metainfo: &mut HashMap<String, Schema>,\n\n) -> SimpleResult<()> {\n\n let sql = format!(\n\n \"SELECT OWNER, TABLE_NAME, COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, NULLABLE \\\n\n...
Rust
src/query.rs
martinsotirov/access_control
a2c26f717f38a488f3b05df63461d83a1966df38
use crate::Action; use crate::Possession; use crate::Rights; use crate::right::Right; #[derive(Debug)] pub struct Query { roles: Vec<String>, rights: Rights } impl Query { pub fn new(roles: Vec<String>, rights: Rights) -> Self { Query{roles, rights} } pub fn check(&self, action: Action, posse...
use crate::Action; use crate::Possession; use crate::Rights; use crate::right::Right; #[derive(Debug)] pub struct Query { roles: Vec<String>, rights: Rights } impl Query { pub fn new(roles: Vec<String>, rights: Rights) -> Self { Query{roles, rights} } pub fn check(&self, action: Action, posse...
#[test] fn can_check_custom_access() { let query = init_query(Right::new("publish", "team", "news")); assert_eq!(query.access("publish", "team", "news"), true); } #[test] fn can_check_custom_access_by_right() { let query = init_query(Right::new("create", "any", "page")); ...
fn init_query(right: Right) -> Query { let mut query = Query{roles: vec![String::from("user")], rights: Rights::new()}; let mut rights: HashSet<Right> = HashSet::new(); rights.insert(right); query.rights.insert(String::from("user"), rights); query }
function_block-full_function
[ { "content": "use regex::Regex;\n\nuse crate::Action;\n\nuse crate::Possession;\n\n\n\n#[derive(Debug, Eq, PartialEq, Hash, Clone)]\n\npub struct Right {\n\n pub action: Action,\n\n pub resource: String,\n\n pub possession: Possession\n\n}\n\n\n\nimpl Right {\n\n pub fn new<S: Into<String>>(action: ...
Rust
src/document.rs
couchbaselabs/couchbase-lite-rust
39d58b58f778caed24fd9ebdd8c54ea1e737794c
use super::*; use super::slice::*; use super::c_api::*; /** An in-memory copy of a document. */ pub struct Document { _ref: *mut CBLDocument } /** Conflict-handling options when saving or deleting a document. */ pub enum ConcurrencyControl { LastWriteWins = kCBLConcurrencyControlLastWriteWins as isize, ...
use super::*; use super::slice::*; use super::c_api::*; /** An in-memory copy of a document. */ pub struct Document { _ref: *mut CBLDocument } /** Conflict-handling options when saving or deleting a document. */ pub enum ConcurrencyControl { LastWriteWins = kCBLConcurrencyControlLastWriteWins as isize, ...
return Ok(Document{_ref: doc}); } } /** Saves a new or modified document to the database. If a conflicting revision has been saved since `doc` was loaded, the `concurrency` parameter specifies whether the save should fail, or the conflicting revision should be overw...
if doc.is_null() { if error.code != 0 { return failure(error); } else { return Err(Error::cbl_error(CouchbaseLiteError::NotFound)); } }
if_condition
[ { "content": "fn add_doc(db: &mut Database, id: &str, i: i64, s: &str) {\n\n let mut doc = Document::new_with_id(id);\n\n let mut props = doc.mutable_properties();\n\n props.at(\"i\").put_i64(i);\n\n props.at(\"s\").put_string(s);\n\n db.save_document(&mut doc, ConcurrencyControl::FailOnConflict)...
Rust
crypto/stark/src/rational_expression.rs
jingleizhang/OpenZKP
be3d1de1c62e0c9079891b4418c15018cf99e941
use crate::polynomial::DensePolynomial; use std::{ collections::BTreeSet, iter::Sum, ops::{Add, Div, Mul, Sub}, prelude::v1::*, }; use zkp_primefield::FieldElement; #[derive(Clone)] #[cfg_attr(feature = "std", derive(Debug))] pub enum RationalExpression { X, Constant(FieldElement), Trace(us...
use crate::polynomial::DensePolynomial; use std::{ collections::BTreeSet, iter::Sum, ops::{Add, Div, Mul, Sub}, prelude::v1::*, }; use zkp_primefield::FieldElement; #[derive(Clone)] #[cfg_attr(feature = "std", derive(Debug))] pub enum RationalExpression { X, Constant(FieldElement), Trace(us...
b.trace_arguments_impl(s); } } } }
i, j)); } X | Constant(_) => (), Polynomial(_, a) | Exp(a, _) | Neg(a) | Inv(a) => a.trace_arguments_impl(s), Add(a, b) | Mul(a, b) => { a.trace_arguments_impl(s);
function_block-random_span
[ { "content": "/// Benchmark over the number of threads.\n\n///\n\n/// Produces a log-log plot.\n\n///\n\n/// The `size` argument is for througput computations.\n\npub fn log_thread_bench<F>(crit: &mut Criterion, id: &str, size: usize, mut f: F)\n\nwhere\n\n F: FnMut(&mut Bencher<'_>) + 'static + Send,\n\n{\n...
Rust
miden/tests/integration/operations/io_ops/mem_ops.rs
grjte/miden
a07da543291e1e6fab77a9d9ab80f7ed42865621
use super::{build_op_test, build_test}; #[test] fn push_mem() { let addr = 1; let asm_op = "push.mem"; let test = build_op_test!(asm_op, &[addr]); test.expect_stack(&[0]); let asm_op = format!("{}.{}", asm_op, addr); let test = build_op_test!(&asm_op); test.expect_stack(&[0]); ...
use super::{build_op_test, build_test}; #[test] fn push_mem() { let addr = 1; let asm_op = "push.mem"; let test = build_op_test!(asm_op, &[addr]); test.expect_stack(&[0]); let asm_op = format!("{}.{}", asm_op, addr); let test = build_op_test!(&asm_op); test.expect_stack(&[0]); ...
#[test] fn loadw_mem() { let addr = 1; let asm_op = "loadw.mem"; let test = build_op_test!(asm_op, &[addr, 5, 6, 7, 8]); test.expect_stack(&[0, 0, 0, 0]); let asm_op = format!("{}.{}", asm_op, addr); let test = build_op_test!(asm_op, &[5, 6, 7, 8]); test.expect_stack(&[0, 0, 0...
fn popw_mem() { let asm_op = "popw.mem"; let addr = 0; let test = build_op_test!(asm_op, &[1, 2, 3, 4, addr]); test.expect_stack_and_memory(&[], addr, &[1, 2, 3, 4]); let asm_op = format!("{}.{}", asm_op, addr); let test = build_op_test!(&asm_op, &[1, 2, 3, 4]); test.expect_stack...
function_block-full_function
[ { "content": "/// This helper function tests overflowing add with carry for two u32 inputs a, b and one binary\n\n/// value c. It tests a number of simple cases as well as random u32 values. It checks that a\n\n/// result of (a + b + c) % 2^32 is pushed to the stack, along with a flag indicating whether or\n\n/...
Rust
src/request_builder.rs
CarlosLanderas/igdb-rs
50dbb4b932f950afcd7e2a3f029752d0a8d0c970
use crate::request_filters::Filter; use std::str::FromStr; use std::string::ToString; use surf::middleware::HttpClient; use url::Url; const HEADER_KEY_NAME: &str = "user-key"; #[derive(Clone)] pub struct RequestBuilder { pub(crate) fields: Vec<String>, pub(crate) filters: Vec<Filter>, pub(crate) sort: (S...
use crate::request_filters::Filter; use std::str::FromStr; use std::string::ToString; use surf::middleware::HttpClient; use url::Url; const HEADER_KEY_NAME: &str = "user-key"; #[derive(Clone)] pub struct RequestBuilder { pub(crate) fields: Vec<String>, pub(crate) filters: Vec<Filter>, pub(crate) sort: (S...
#[test] fn request_builder_with_fields_and_where_clause_body_build() { let mut builder = RequestBuilder::new(); builder .add_field("name") .add_field("involved_companies") .add_where("name", Equality::Equal, "Conan") .add_where("id", Equality::Less, 39047.to_string()); le...
ll_fields(); let body = builder.build_body(); assert_eq!( "fields *; limit 10;", String::from_utf8_lossy(&body).to_owned() ); }
function_block-function_prefixed
[ { "content": " M = 11,\n\n AO = 12,\n\n}\n\n\n\n#[derive(Deserialize_repr, Debug, Clone)]\n\n#[repr(u8)]\n\npub enum RatingCategory {\n\n ESRB = 1,\n\n PEGI = 2,\n\n}\n\n\n\nimpl Default for RatingCategory {\n\n fn default() -> Self {\n\n RatingCategory::ESRB\n\n }\n\n}\n\n\n\nimpl Defa...
Rust
src/vcf/record/as_turtle.rs
togovar/vcf2rdf
edef7ecb429c51a826716ea633d159ae716858a7
use std::io::Write; use rust_htslib::bcf; use crate::cli::Subject; use crate::errors::Result; use crate::rdf::turtle_writer::{AsTurtle, TurtleWriter}; use crate::vcf::alteration::AlterationPosition; use crate::vcf::reader::InfoValue; use crate::vcf::record::Record; const BUFFER_DEFAULT: usize = 40 * 1024; struct Bu...
use std::io::Write; use rust_htslib::bcf; use crate::cli::Subject; use crate::errors::Result; use crate::rdf::turtle_writer::{AsTurtle, TurtleWriter}; use crate::vcf::alteration::AlterationPosition; use crate::vcf::reader::InfoValue; use crate::vcf::record::Record; const BUFFER_DEFAULT: usize = 40 * 1024; struct Bu...
} }; buf.push_str("\n ]"); } fn write_info(&self, buf: &mut Buffer) { let info = self.info; if info.len() > 0 { buf.push_str(" ;\n gvo:info"); for (i, info) in info.iter().enumerate() { buf.push_str(if i == 0 { " [" } else ...
if let Some(ref reference) = self.sequence.reference { buf.push_str(" ;\n faldo:reference "); buf.push_iri(reference.as_str()); }
if_condition
[ { "content": "/// Compress read content to bgzip\n\n///\n\n/// # Arguments\n\n///\n\n/// * `reader` - An object that implements `BufRead`.\n\n/// * `output` - Path to output VCF.\n\n/// * `level` - Compression level to use when compressing. From `Some(0)` (Faster) to `Some(9)` (Best). Set `None` for default lev...
Rust
src/node/build.rs
omni-viral/xfg-rs
0330958d8dbdc672f97e860348e233ed883cb543
use std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, ops::Range}; use hal::{ buffer, format::Format, image, pool::{CommandPool, CommandPoolCreateFlags}, pso::PipelineStage, queue::{Capability, CommandQueue, QueueFamily, QueueFamilyId, QueueType}, window::Backbuffer, Backend, Device, }; use chain:...
use std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, ops::Range}; use hal::{ buffer, format::Format, image, pool::{CommandPool, CommandPoolCreateFlags}, pso::PipelineStage, queue::{Capability, CommandQueue, QueueFamily, QueueFamilyId, QueueType}, window::Backbuffer, Backend, Device, }; use chain:...
rces[id.0.index() as usize]; BufferInfo { id, barriers: Barriers { acquire: submission.sync().acquire.buffers.get(&id.0).map(|barrier| { let Range { ref start, ref end } = barrier.states; (start.access, start...
.images .iter() .map(|id| id.0) .zip(N::images().into_iter().map(image_state_usage)) .collect(), }; assert_eq!(pass.buffers.len(), self.buffers.len()); assert_eq!(pass.images.len(), self.images.len()); pass } fn b...
random
[ { "content": "fn find_family<'a, B, F>(families: F, qid: QueueFamilyId) -> &'a B::QueueFamily\n\nwhere\n\n B: Backend,\n\n F: IntoIterator<Item = &'a B::QueueFamily>,\n\n{\n\n families.into_iter().find(|qf| qf.id() == qid).unwrap()\n\n}\n", "file_path": "src/graph/mod.rs", "rank": 1, "score...
Rust
src/errors.rs
onurzdg/tokio-proxy
111727900577644d7681efdf61213000f3853ac8
use crate::config::MAX_HTTP_CONNECT_REQUEST_SIZE; use crate::description::AsDescription; use serde::{Serialize, Serializer}; use std::borrow::Cow; use std::fmt; use tokio::io::ErrorKind; #[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub enum HttpTunnelRequestError { RequestDecodeError(HttpTunnelRequestDecodeEr...
use crate::config::MAX_HTTP_CONNECT_REQUEST_SIZE; use crate::description::AsDescription; use serde::{Serialize, Serializer}; use std::borrow::Cow; use std::fmt; use tokio::io::ErrorKind; #[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub enum HttpTunnelRequestError { RequestDecodeError(HttpTunnelRequestDecodeEr...
} impl std::error::Error for HttpParseError {} #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum IoErrorKind { ErrorKind(ErrorKind), } impl Serialize for IoErrorKind { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where ...
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { let HttpParseError::ParseError(err) = self; let err_str = format!("HttpParseError({:?})", err); serializer.serialize_str(&err_str) }
function_block-full_function
[ { "content": "fn check_method(m: Option<&str>) -> Result<(), HttpTunnelRequestDecodeError> {\n\n match m {\n\n Some(\"CONNECT\") => Ok(()),\n\n Some(other) => Err(HttpTunnelRequestDecodeError::NotSupportedMethod(\n\n other.into(),\n\n )),\n\n _ => Err(HttpTunnelRequestD...
Rust
cargo-apk/src/config.rs
codeforks/android-rs-glue
3bfc87a4141ca37f9615f02895a34c3204d1e862
use std::collections::btree_map::BTreeMap; use std::env; use std::fs::File; use std::io::Read; use std::path::Path; use std::path::PathBuf; use toml; use toml::Parser as TomlParser; pub struct Config { pub sdk_path: PathBuf, pub ndk_path: PathBuf, pub ant_command: String, ...
use std::collections::btree_map::BTreeMap; use std::env; use std::fs::File; use std::io::Read; use std::path::Path; use std::path::PathBuf; use toml; use toml::Parser as TomlParser; pub struct Config { pub sdk_path: PathBuf, pub ndk_path: PathBuf, pub ant_command: String, ...
_owned(), ant_command: if cfg!(target_os = "windows") { "ant.bat" } else { "ant" }.to_owned(), package_name: manifest_content.as_ref().and_then(|a| a.package_name.clone()) .unwrap_or_else(|| format!("rust.{}", package_name)), project_name: package_name.clon...
unwrap(); let decoded: TomlPackage = toml::decode(toml["package"].clone()).unwrap(); let package_name = decoded.name.clone(); (package_name, decoded.metadata.and_then(|m| m.android)) }; let ndk_path = env::var("NDK_HOME").expect("Please set the path to the Android NDK with the \ ...
function_block-random_span
[ { "content": "pub fn install(manifest_path: &Path, config: &Config) {\n\n let build_result = build::build(manifest_path, config);\n\n\n\n let adb = config.sdk_path.join(\"platform-tools/adb\");\n\n\n\n TermCmd::new(\"Installing apk to the device\", &adb)\n\n .arg(\"install\")\n\n .arg(\"-...
Rust
src/components/token_input.rs
slowli/justwebtoken.io
9c509305a4c834aa21ff33fdbc2f03836f953daf
use base64ct::{Base64UrlUnpadded, Encoding}; use jwt_compact::{Header, ParseError, UntrustedToken}; use wasm_bindgen::{JsCast, UnwrapThrowExt}; use web_sys::{HtmlTextAreaElement, InputEvent}; use yew::{classes, html, Callback, Component, Context, Html, Properties}; use super::common::{view_wide_data_row, ComponentRe...
use base64ct::{Base64UrlUnpadded, Encoding}; use jwt_compact::{Header, ParseError, UntrustedToken}; use wasm_bindgen::{JsCast, UnwrapThrowExt}; use web_sys::{HtmlTextAreaElement, InputEvent}; use yew::{classes, html, Callback, Component, Context, Html, Properties}; use super::common::{view_wide_data_row, ComponentRe...
fn view(&self) -> Html { html! { <> { Self::ALG_FIELD.with_value(&self.algorithm).view_aux() } { if let Some(key_set_url) = &self.header.key_set_url { StandardHeader::by_name("jku").with_code_value(key_set_url).view_aux() } el...
fn new(token: &UntrustedToken<'_>) -> Self { Self { algorithm: token.algorithm().to_owned(), header: token.header().clone(), } }
function_block-full_function
[ { "content": "#[derive(Debug, Deserialize)]\n\nstruct Field {\n\n name: String,\n\n description: String,\n\n link: Option<String>,\n\n}\n\n\n\nimpl fmt::Display for Field {\n\n fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(\n\n formatter,\n\n ...
Rust
hooks_game/src/repl/tick.rs
leod/hooks
1b3a44e672c897fd0a6f1f245a7076cbcab8f9e7
use std::collections::btree_map; use std::collections::BTreeMap; use std::collections::Bound::{Excluded, Included, Unbounded}; use bit_manager::{self, BitRead, BitWrite}; use defs::{TickDeltaNum, TickNum, INVALID_PLAYER_ID, NO_DELTA_TICK}; use event::{self, Event}; use repl::snapshot::{self, EntityClasses, EntitySnap...
use std::collections::btree_map; use std::collections::BTreeMap; use std::collections::Bound::{Excluded, Included, Unbounded}; use bit_manager::{self, BitRead, BitWrite}; use defs::{TickDeltaNum, TickNum, INVALID_PLAYER_ID, NO_DELTA_TICK}; use event::{self, Event}; use repl::snapshot::{self, EntityClasses, EntitySnap...
fn write_events( &self, events: &[Box<Event>], writer: &mut event::Writer, ) -> Result<(), bit_manager::Error> { writer.write_bit(!events.is_empty())?; if !events.is_empty() { writer.write(&(events.len() as u32))?; for e...
pub fn delta_read_tick( &mut self, classes: &EntityClasses<T::ComponentType>, reader: &mut event::Reader, ) -> Result<Option<ReadInfo>, Error> { let cur_num = reader.read::<TickNum>()?; if self.max_num().is_some() && cur_num < self.max_num().unwrap() { ...
function_block-full_function
[ { "content": "/// Handle events regarding player creation. Note that, both on the server and the clients, this\n\n/// event comes from the outside. Thus, we want to handle these before starting the tick.\n\nfn handle_event_pre_tick(world: &mut World, event: &Event) -> Result<(), repl::Error> {\n\n match_even...
Rust
image.rs
metajack/rust-stb-image
59275bd55654bfcbc9783c4047eefbbbad145e13
use stb_image::bindgen::*; use std::libc; use std::libc::{c_void, c_int}; use std::ptr::{is_null, to_mut_unsafe_ptr}; use std::str::as_c_str; use std::task; use std::vec::raw::from_buf_raw; pub struct Image<T> { width : uint, height : uint, depth : uint, data : ~[T], } pub fn new_image<T>(w...
use stb_image::bindgen::*; use std::libc; use std::libc::{c_void, c_int}; use std::ptr::{is_null, to_mut_unsafe_ptr}; use std::str::as_c_str; use std::task; use std::vec::raw::from_buf_raw; pub struct Image<T> { width : uint, height : uint, depth : uint, data : ~[T], } pub fn new_image<T>(w...
}
pub fn load_from_memory_with_depth(buffer: &[u8], force_depth: uint, convert_hdr:bool) -> LoadResult { unsafe { do task::unkillable { let mut width = 0 as c_int; let mut height = 0 as c_int; let mut depth = 0 as c_int; do buffer.as_imm_buf |bytes, len| { ...
function_block-full_function
[ { "content": "fn stbi_loadf_from_memory(buffer: *stbi_uc, len: c_int, x: *mut c_int, y: *mut c_int, comp: *mut c_int, req_comp: c_int) -> *c_float;\n\n\n", "file_path": "stb_image.rs", "rank": 5, "score": 108767.88692467293 }, { "content": "fn stbi_load_from_memory(buffer: *stbi_uc, len: c_i...
Rust
src/meta_rules/lines.rs
bvssvni/meta
4882caeb1a7543482244a5224d05a86aa40d2d88
use range::Range; use read_token::ReadToken; use super::{ ret_err, err_update, IndentSettings, ParseResult, }; use { DebugId, MetaData, ParseError, Rule, }; use tokenizer::TokenizerState; #[derive(Clone, Debug, PartialEq)] pub struct Lines { pub rule: Rule, pub d...
use range::Range; use read_token::ReadToken; use super::{ ret_err, err_update, IndentSettings, ParseResult, }; use { DebugId, MetaData, ParseError, Rule, }; use tokenizer::TokenizerState; #[derive(Clone, Debug, PartialEq)] pub struct Lines { pub rule: Rule, pub d...
} #[cfg(test)] mod tests { use all::*; use all::tokenizer::*; use meta_rules::{ IndentSettings, Lines, Number, Sequence, Text, Whitespace }; use range::Range; use read_token::ReadToken; use std::sync::Arc; #[test] fn fail() { let text = " 1 2 3 \"error\" 4 "; ...
pub fn parse( &self, tokenizer: &mut Vec<Range<MetaData>>, state: &TokenizerState, read_token: &ReadToken, refs: &[Rule], indent_settings: &mut IndentSettings, ) -> ParseResult<TokenizerState> { let mut state = state.clone(); let mut opt_error = None; ...
function_block-full_function
[ { "content": "/// Optimizes syntax rule.\n\npub fn optimize_rule(rule: &Rule, refs: &[Rule]) -> Rule {\n\n use meta_rules::*;\n\n\n\n match *rule {\n\n Rule::Whitespace(_) |\n\n Rule::Tag(_) |\n\n Rule::UntilAny(_) |\n\n Rule::UntilAnyOrWhitespace(_) |\n\n Rule::Text(_) ...
Rust
src/proto/request.rs
joyent/tokio-zookeeper
73ded3eedb8f620b688095b3fb99eedcf64c99e2
use byteorder::{BigEndian, WriteBytesExt}; use std::borrow::Cow; use std::io::{self, Write}; use crate::error::ZkError; use crate::types::acl::Acl; use crate::types::watch::Watch; use crate::types::CreateMode; #[derive(Debug)] pub(crate) enum Request { Connect { protocol_version: i32, last_zxid_se...
use byteorder::{BigEndian, WriteBytesExt}; use std::borrow::Cow; use std::io::{self, Write}; use crate::error::ZkError; use crate::types::acl::Acl; use crate::types::watch::Watch; use crate::types::CreateMode; #[derive(Debug)] pub(crate) enum Request { Connect { protocol_version: i32, last_zxid_se...
pub(super) fn opcode(&self) -> OpCode { match *self { Request::Connect { .. } => OpCode::CreateSession, Request::Exists { .. } => OpCode::Exists, Request::Delete { .. } => OpCode::Delete, Request::Create { .. } => OpCode::Create, Request::GetChil...
te_to(&mut *buffer)?; buffer.write_i32::<BigEndian>(version)?; } Request::Create { ref path, ref data, mode, ref acl, } => { path.write_to(&mut *buffer)?; data.write_to(&mu...
function_block-function_prefixed
[ { "content": "pub trait BufferReader: Read {\n\n fn read_buffer(&mut self) -> io::Result<Vec<u8>>;\n\n}\n\n\n\nimpl<R: Read> BufferReader for R {\n\n fn read_buffer(&mut self) -> io::Result<Vec<u8>> {\n\n let len = self.read_i32::<BigEndian>()?;\n\n let len = if len < 0 { 0 } else { len as u...
Rust
programs/gem_farm/src/number128.rs
tmalcolm-0607/gem-farm
ffb48a0806466d903f97ab62b32bdcc9b4055a5e
use std::{ convert::TryFrom, fmt::{Display, Formatter}, }; use anchor_lang::prelude::*; use gem_common::{errors::ErrorCode, TryAdd, TryDiv, TryMul, TryPow, TryRem, TrySub}; const ONE: u128 = 1_000; const PRECISION: i32 = 3; const U64_MAX: u128 = u64::MAX as u128; #[derive( Default, Debug, Clone, Copy, ...
use std::{ convert::TryFrom, fmt::{Display, Formatter}, }; use anchor_lang::prelude::*; use gem_common::{errors::ErrorCode, TryAdd, TryDiv, TryMul, TryPow, TryRem, TrySub}; const ONE: u128 = 1_000; const PRECISION: i32 = 3; const U64_MAX: u128 = u64::MAX as u128; #[derive( Default, Debug, Clone, Copy, ...
#[test] fn test_mul_assign() { let mut x = Number128::from(10_u64); let y = Number128::from(2_u64); x.try_mul_assign(y).unwrap(); assert_eq!(x, Number128::from(20_u64)); } #[test] fn test_pow_assign() { let mut x = Number128::from(10_u64); let y = 2...
fn test_div_assign() { let mut x = Number128::from(10_u64); let y = Number128::from(2_u64); x.try_div_assign(y).unwrap(); assert_eq!(x, Number128::from(5_u64)); }
function_block-full_function
[ { "content": "pub fn now_ts() -> Result<u64> {\n\n //i64 -> u64 ok to unwrap\n\n Ok(clock::Clock::get()?.unix_timestamp.try_into().unwrap())\n\n}\n", "file_path": "lib/gem_common/src/util.rs", "rank": 0, "score": 209391.1822074926 }, { "content": "/// if rarity account is present, extr...
Rust
examples/perceptron.rs
busyboredom/rust-mnist
ee83f02c58ab3a7760505c1cd78b49254cdb42ff
extern crate rand; extern crate rust_mnist; use rand::distributions::{IndependentSample, Range}; use rust_mnist::{print_sample_image, Mnist}; use std::io::{self, Write}; const LEARNING_RATE: f64 = 0.0001; const BIAS: f64 = 1.0; fn main() { let mnist = Mnist::new("examples/MNIST_data/"); prin...
extern crate rand; extern crate rust_mnist; use rand::distributions::{IndependentSample, Range}; use rust_mnist::{print_sample_image, Mnist}; use std::io::{self, Write}; const LEARNING_RATE: f64 = 0.0001; const BIAS: f64 = 1.0; fn main() { let mnist = Mnist::new("examples/MNIST_data/"); prin...
ifference } fn one_hot(value: u8) -> [f64; 10] { let mut arr: [f64; 10] = [0.0; 10]; arr[usize::from(value)] = 1.0; arr } fn normalize(image: &[u8]) -> Vec<f64> { image .into_iter() .map(|pixel| 2.0 * f64::from(*pixel) / 255.0 - 1.0) .collect() } fn largest(arr: &[f64; 10...
f64; 10]) -> [f64; 10] { let mut difference: [f64; 10] = [0.0; 10]; for index in 0..difference.len() { difference[index] = lhs[index] - rhs[index]; } d
function_block-random_span
[ { "content": "pub fn print_sample_image(image: &[u8; IMAGE_ROWS * IMAGE_COLUMNS], label: u8) {\n\n // Check that the image isn't empty and has a valid number of rows.\n\n assert!(image.len() != 0, \"There are no pixels in this image.\");\n\n assert_eq!(\n\n image.len() % usize::try_from(IMAGE_RO...
Rust
core-client/transports/src/transports/duplex.rs
pietgeursen/jsonrpc
380627b11887d993b293b04be5b0401ba56aca96
use failure::format_err; use futures::prelude::*; use futures::sync::{mpsc, oneshot}; use jsonrpc_core::Id; use log::debug; use serde_json::Value; use std::collections::HashMap; use std::collections::VecDeque; use super::RequestBuilder; use crate::{RpcChannel, RpcError, RpcMessage}; pub struct Duplex<TSink, TStream...
use failure::format_err; use futures::prelude::*; use futures::sync::{mpsc, oneshot}; use jsonrpc_core::Id; use log::debug; use serde_json::Value; use std::collections::HashMap; use std::collections::VecDeque; use super::RequestBuilder; use crate::{RpcChannel, RpcError, RpcMessage}; pub struct Duplex<TSink, TStream...
}
fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> { loop { if self.channel.is_none() { break; } let msg = match self.channel.as_mut().expect("channel is some; qed").poll() { Ok(Async::Ready(Some(msg))) => msg, Ok(Async::Ready(None)) => { self.channel.take(); br...
function_block-full_function
[ { "content": "/// Create a new future-base rendezvous channel.\n\n///\n\n/// The returned `Sender` and `Receiver` objects are wrapping\n\n/// the regular `futures::sync::oneshot` counterparts and have the same functionality.\n\n/// Additionaly `Sender::send_and_wait` allows you to send a message to the channel\...
Rust
src/keypair.rs
FelipeACP/gateway-rs
fd2a119babb8dcb7bc3546ef73772b33b7a7f65b
use crate::*; use helium_crypto::{ecc608, KeyTag, KeyType, Network}; use http::Uri; use rand::rngs::OsRng; use serde::{de, Deserializer}; use std::{collections::HashMap, convert::TryFrom, fmt, fs, io, path, path::Path, str::FromStr}; #[derive(Debug)] pub struct Keypair(helium_crypto::Keypair); pub type PublicKey = hel...
use crate::*; use helium_crypto::{ecc608, KeyTag, KeyType, Network}; use http::Uri; use rand::rngs::OsRng; use serde::{de, Deserializer}; use std::{collections::HashMap, convert::TryFrom, fmt, fs, io, path, path::Path, str::FromStr}; #[derive(Debug)] pub struct Keypair(helium_crypto::Keypair); pub type PublicKey = hel...
, }, Some("ecc") => { let args = KeypairArgs::from_uri(&url).map_err(error::DecodeError::keypair_uri)?; let bus_address = url.port_u16().unwrap_or(96); let slot = args.get::<u8>("slot", 0)?; let network = args.get("network", Networ...
Err(uri_error!( "unable to load key file \"{}\": {err:?}", url.path() ))
call_expression
[ { "content": "/// An empty timestamp function for when timestamp should not be included in\n\n/// the output. This is commonly used with logd on OpenWRT which adds its own\n\n/// timestamp information after capturing stdout.\n\nfn timestamp_none(_io: &mut dyn io::Write) -> io::Result<()> {\n\n Ok(())\n\n}\n\...
Rust
src/sensors/cpu.rs
Obito1903/rusty-hass-laptop
abd67231f307425b73ba075c956fc5198cdc2903
use super::{Provider, Sensor, SensorData, SensorRegisterData, SensorType, SensorUpdateData}; use serde::Serialize; use sys_info; pub struct CpuProvider { pub cpu_cores: CpuCores, pub cpu_freq: CpuFreq, } impl Provider for CpuProvider { fn new() -> Self { CpuProvider { cpu_cores: C...
use super::{Provider, Sensor, SensorData, SensorRegisterData, SensorType, SensorUpdateData}; use serde::Serialize; use sys_info; pub struct CpuProvider { pub cpu_cores: CpuCores, pub cpu_freq: CpuFreq, } impl Provider for CpuProvider { fn new() -> Self { CpuProvider { cpu_cores: C...
#type: SensorType::Sensor, unique_id: self.unique_id.clone(), state: self.state, icon: Some(String::from("mdi:memory")), }, } } }
get_register_info(&self) -> SensorData<Self::StateType> { SensorData::RegisterSensor::<Self::StateType> { data: SensorRegisterData { r#type: SensorType::Sensor, unique_id: self.unique_id.clone(), name: String::from("CPU Frequency"), sta...
random
[ { "content": "pub trait Sensor<T: Provider> {\n\n type StateType: Serialize;\n\n\n\n fn new() -> Self;\n\n fn get_current(provider: &T) -> Result<Self::StateType, &'static str>;\n\n fn get_register_info(&self) -> SensorData<Self::StateType>;\n\n fn get_update_info(&self) -> SensorData<Self::State...
Rust
src/static_checking/exhaustiveness.rs
P-bibs/skiff
05269a614f375b0c3be83fde26549da528258b96
use im::HashMap; use crate::{ ast::{AstNode, Pattern, Program, SrcLoc, Type}, type_inferencer::ast::Term, }; #[derive(PartialEq, Debug, Clone, Hash)] pub enum ExhaustivenessError { UnknownTypeToMatchOn(), UnknownTypeVariant(), CantMatchFunction(), CantMatchAny(), NotEnoughArgsInPattern(), ...
use im::HashMap; use crate::{ ast::{AstNode, Pattern, Program, SrcLoc, Type}, type_inferencer::ast::Term, }; #[derive(PartialEq, Debug, Clone, Hash)] pub enum ExhaustivenessError { UnknownTypeToMatchOn(), UnknownTypeVariant(), CantMatchFunction(), CantMatchAny(), NotEnoughArgsInPattern(), ...
}
a( "two".to_string(), vec![Pattern::BoolLiteral(false), Pattern::BoolLiteral(false)], ), Pattern::Data( "two".to_string(), vec![ Pattern::BoolLiteral(true), Pattern::Identifier("_".to_string()...
function_block-function_prefixed
[ { "content": "/// Interpret a Skiff program, possibly returning a runtime error\n\npub fn interpret(program: &Program) -> Result<Vec<Val>, InterpError> {\n\n // Find every data declaration in the program and add functions declarations\n\n // to the AST. Add a constructor function for each variant of each ...
Rust
satisfactory-accounting-app/src/app.rs
satisfactory-accounting/satisfactory-accounting
ff0876111890034f7f8d5ea48a4f2aa023b22f53
use std::collections::HashMap; use std::mem; use std::rc::Rc; use gloo::storage::errors::StorageError; use gloo::storage::{LocalStorage, Storage}; use log::warn; use serde::{Deserialize, Serialize}; use uuid::Uuid; use yew::prelude::*; use satisfactory_accounting::accounting::{Group, Node}; use satisfactory_account...
use std::collections::HashMap; use std::mem; use std::rc::Rc; use gloo::storage::errors::StorageError; use gloo::storage::{LocalStorage, Storage}; use log::warn; use serde::{Deserialize, Serialize}; use uuid::Uuid; use yew::prelude::*; use satisfactory_accounting::accounting::{Group, Node}; use satisfactory_account...
fn add_undo_state(&mut self, previous_state: AppState) { self.undo_stack.push(previous_state); if self.undo_stack.len() > 100 { let num_to_remove = self.undo_stack.len() - 100; self.undo_stack.drain(..num_to_remove); } self.redo_stack.clear(); ...
ATA_KEY, &self.metadata) { warn!("Unable to save metadata: {}", e); } if let Err(e) = LocalStorage::set(GLOBAL_METADATA_KEY, &self.global_metadata) { warn!("Unable to save global metadata: {}", e); } }
function_block-function_prefixed
[ { "content": "/// Recursively removes a child node. Returns the new group to replace the one modified\n\n/// and the node that was removed. Returns none if not a group or out of bounds.\n\npub fn remove_child(node: &Node, child: &[usize]) -> Option<(Node, Node)> {\n\n let group = match node.kind() {\n\n ...
Rust
sxg_rs/src/fetcher/mock_fetcher.rs
quangIO/sxg-rs
db62dbd467343762d2868bff49eda1c240243d14
use super::Fetcher; use crate::http::{HttpRequest, HttpResponse}; use anyhow::{anyhow, Result}; use async_trait::async_trait; use std::cell::RefCell; use std::time::Duration; use tokio::sync::mpsc; use tokio::time::timeout; pub struct MockFetcher { request_sender: mpsc::Sender<HttpRequest>, response_receiver...
use super::Fetcher; use crate::http::{HttpRequest, HttpResponse}; use anyhow::{anyhow, Result}; use async_trait::async_trait; use std::cell::RefCell; use std::time::Duration; use tokio::sync::mpsc; use tokio::time::timeout; pub struct MockFetcher { request_sender: mpsc::Sender<HttpRequest>, response_receiver...
} impl MockServer { pub async fn handle_next_request( &mut self, expected_request: HttpRequest, response: HttpResponse, ) -> Result<()> { let actual_request = timeout(self.time_limit, self.request_receiver.recv()) .await .map_err(|_e| { a...
async fn fetch(&self, request: HttpRequest) -> Result<HttpResponse> { let request_url = request.url.clone(); self.request_sender.send(request).await?; timeout( self.time_limit, self.response_receiver.try_borrow_mut()?.recv(), ) .await .map_err(|_e|...
function_block-full_function
[ { "content": "/// Tries to read the contents of given file; if the file does not exist,\n\n/// generates a private key, and writes PEM to the file, and returns it.\n\npub fn read_or_create_private_key_pem(file: impl AsRef<Path>) -> Result<String> {\n\n if file.as_ref().exists() {\n\n println!(\"Readin...
Rust
kernel/framebuffer.rs
devyn/kit
1f587a937e08a2725f264ce430637dee51c1d4fe
/******************************************************************************* * * kit/kernel/framebuffer.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more information...
/******************************************************************************* * * kit/kernel/framebuffer.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more information...
}
fn copy_within( &self, sx: usize, sy: usize, dx: usize, dy: usize, width: usize, height: usize ) { let mut buf = self.buffer.lock(); let pitch = self.config.pitch; let bpp = self.config.bytes_per_pixel(); let sx_offs...
function_block-full_function
[ { "content": "pub fn zero_memory(buf: &mut [u8]) {\n\n set_memory(buf, 0);\n\n}\n\n\n\n#[inline(always)]\n\npub const fn align_up(number: usize, align: usize) -> usize {\n\n if align & (align - 1) == 0 {\n\n // power of two\n\n (number + (align - 1)) & !(align - 1)\n\n } else {\n\n ...
Rust
src/runner.rs
stevenroose/rust-daemon-runner
07b3b5d043191114806b27add4a47f4c672300da
use std::{process, fmt, io, ops, thread, time, mem}; use std::sync::{Arc, Mutex}; use std::io::{BufRead, Read}; use error::Error; struct KillOnDropChild(process::Child); impl KillOnDropChild { pub fn get(&self) -> &process::Child { &self.0 } pub fn get_mut(&mut self) -> &mut process::Child { &mut self.0 } ...
use std::{process, fmt, io, ops, thread, time, mem}; use std::sync::{Arc, Mutex}; use std::io::{BufRead, Read}; use error::Error; struct KillOnDropChild(process::Child); impl KillOnDropChild { pub fn get(&self) -> &process::Child { &self.0 } pub fn get_mut(&mut self) -> &mut process::Child { &mut self.0 } ...
n {:?} stopped", self); Ok(()) } fn status(&self) -> Result<Status, Error> { let rt = match self._get_runtime() { Some(rt) => rt, None => return Ok(Status::Init), }; let mut lock = rt.lock().unwrap(); match lock.process.as_mut().unwrap().0.try_wait()? { None => Ok(Status::Running), Some(c) =...
Status::Stopped(_) => return Ok(()), } let rt_ref = self._get_runtime().unwrap(); let mut rt = rt_ref.lock().unwrap(); info!("Stopping daemon {:?}...", self); rt.process.as_mut().unwrap().get_mut().kill()?; info!("Daemo
function_block-random_span
[ { "content": "pub trait RegexUtils: AsRef<str> {\n\n\t/// Get the first group from the first capture of the regex.\n\n\tfn rx_single<'a>(&self, s: &'a str) -> Option<&'a str> {\n\n\t\tRegex::new(self.as_ref()).expect(\"invalid regex\").captures(s).map(|c| {\n\n\t\t\tc.get(1).unwrap().as_str()\n\n\t\t})\n\n\t}\n...
Rust
src/read.rs
moshg/algorithms
fa9d8d2f86568126140386d93a1151a355b021f5
pub mod io_ext { use std::io::BufRead; pub struct Reader<R> { buf: String, inner: R, } impl<R> Reader<R> { #[inline] pub fn new(inner: R) -> Self { Reader { buf: String::new(), inner: inner, } } #...
pub mod io_ext { use std::io::BufRead; pub struct Reader<R> { buf: String, inner: R, } impl<R> Reader<R> { #[inline] pub fn new(inner: R) -> Self { Reader { buf: String::new(), inner: inner, } } #...
pub fn read_lines(&mut self, n: usize) -> Lines<R> { Lines { reader: self, n: n } } } pub struct Lines<'a, R: 'a> { reader: &'a mut Reader<R>, n: usize, } impl<'a, R: 'a + BufRead> Iterator for Lines<'a, R> { type Item = String; fn next(&m...
pub fn read_line(&mut self) -> &str { self.buf.clear(); self.inner .read_line(&mut self.buf) .unwrap_or_else(|e| panic!("{}", e)); self.buf.trim_right() }
function_block-function_prefix_line
[ { "content": "pub fn digits10(mut n: i64) -> i64 {\n\n if n < 0 {\n\n n = -n;\n\n }\n\n\n\n let mut d = 1;\n\n let mut p = 10;\n\n while p <= n {\n\n p *= 10;\n\n d += 1;\n\n }\n\n d\n\n}\n\n\n", "file_path": "src/math.rs", "rank": 0, "score": 45358.94422371...
Rust
src/telling.rs
Earthmark/Rok
7626f370f0601702686c7be4261e04f83a034be8
use super::story; use std::{error, fmt}; #[derive(Clone)] pub struct Telling<'a> { story: &'a story::Story, scene: &'a story::Scene, running: bool, } #[derive(Debug)] pub struct IntroSceneNotFound {} impl fmt::Display for IntroSceneNotFound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result...
use super::story; use std::{error, fmt}; #[derive(Clone)] pub struct Telling<'a> { story: &'a story::Story, scene: &'a story::Scene, running: bool, } #[derive(Debug)] pub struct IntroSceneNotFound {} impl fmt::Display for IntroSceneNotFound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result...
make_test_telling(&story); assert_eq!("test_message", telling.message()); } #[test] fn move_scene_failure_returns_not_found() { let story = make_test_story(); let mut telling = make_test_telling(&story); let result = telling.do_choice(&Choice::MoveScene { destination: "unknown_sce...
}, ); Story { intro: "potato".to_string(), scenes, } } fn make_test_telling<'a>(story: &'a Story) -> Telling<'a> { Telling { story: story, scene: story.scenes.get("test_scene").unwrap(), running: true, } } #[test] fn message_returns_from...
random
[ { "content": "fn main() -> Result<(), Box<dyn error::Error>> {\n\n let story = story::Story::from_file(\"story.json\")?;\n\n let mut state = telling::Telling::new(&story)?;\n\n while state.is_running() {\n\n println!(\"{}\", state.message());\n\n let word: String = read!(\"{}\");\n\n match state.mak...
Rust
src/lib.rs
reclutch-nursery/revenq
7772b8edfc942f2824eb1d43c680d7370bd6fe30
/*! # Nomenclature This library generally is designed to handle events. It doesn't "pin" the user to a single event container, instead, it abstracts away from this and generally handles so-called revisions, which may contain one event at a time, or a `Vec<Event>`, the only requirements are that the revisions must have ...
/*! # Nomenclature This library generally is designed to handle events. It doesn't "pin" the user to a single event container, instead, it abstracts away from this and generally handles so-called revisions, which may contain one event at a time, or a `Vec<Event>`, the only requirements are that the revisions must have ...
} impl<T> Queue<T> { #[inline(always)] pub fn new() -> Self { Default::default() } fn publish_intern(&mut self) -> Option<RevisionRef<T>> { enum State<T> { ToPublish { rest: Vec<T>, last: T }, Published { latest: NextRevision<T> }, } let last =...
x, }; if orig_pending_len != self.pending.len() { self.next_ops.notify(usize::MAX); } ret }
function_block-function_prefixed
[ { "content": "fn accumulate<T>(rv: &mut impl Iterator<Item = revenq::RevisionRef<T>>) -> T\n\nwhere\n\n T: Copy + std::iter::Sum,\n\n{\n\n rv.map(|i| *i).sum()\n\n}\n\n\n", "file_path": "tests/queue.rs", "rank": 0, "score": 87299.69750801177 }, { "content": "fn queue_bench(c: &mut Crit...
Rust
ftdi-vcp-rs/src/mpsse.rs
xobs/swot
2696ddf4d3a4a0a1ac45af28ba56a4b5068ac32d
/* MPSSE engine command definitions */ #[allow(non_camel_case_types)] pub enum Command { MC_SETB_LOW, MC_READB_LOW, MC_SETB_HIGH, MC_READB_HIGH, MC_LOOPBACK_EN, MC_LOOPBACK_DIS, MC_SET_CLK_DIV, MC_FLUSH,...
/* MPSSE engine command definitions */ #[allow(non_camel_case_types)] pub enum Command { MC_SETB_LOW, MC_READB_LOW, MC_SETB_HIGH, MC_READB_HIGH, MC_LOOPBACK_EN, MC_LOOPBACK_DIS, MC_SET_CLK_DIV, MC_FLUSH,...
}
fn to_u8(&self) -> u8{ use Command::*; match *self { /* Mode commands */ MC_SETB_LOW => 0x80, /* Set Data bits LowByte */ MC_READB_LOW => 0x81, /* Read Data bits LowByte */ MC_SETB_HIGH => 0x82, /* Set Data bits HighByte */ MC_...
function_block-function_prefixed
[ { "content": "pub fn create_device_info_list() -> Result<usize, usize> {\n\n let device_count: DWORD = 0;\n\n let result = unsafe { FT_CreateDeviceInfoList(&device_count as *const _ as LPDWORD) };\n\n if result == 0 {\n\n Ok(device_count as usize)\n\n } else {\n\n Err(result as usize)\...
Rust
rustrial-k8s-aws-iam-controller/src/main.rs
rustrial/k8s-aws-iam-controller
beffcdd5bd24d966360b9633accebfb25580ed89
#[macro_use] extern crate log; use futures::{FutureExt, StreamExt}; use indoc::indoc; use k8s_openapi::api::core::v1::ServiceAccount; use kube::{api::ListParams, Api, Client, Config}; use kube_runtime::{reflector, reflector::store::Writer, watcher}; use log::{error, info, warn}; use metrics_exporter_prometheus::Prometh...
#[macro_use] extern crate log; use futures::{FutureExt, StreamExt}; use indoc::indoc; use k8s_openapi::api::core::v1::ServiceAccount; use kube::{api::ListParams, Api, Client, Config}; use kube_runtime::{reflector, reflector::store::Writer, watcher}; use log::{error, info, warn}; use metrics_exporter_prometheus::Prometh...
, }) } } #[async_trait] impl ProvideAwsCredentials for AwsCredentialsProvider { async fn credentials( &self, ) -> Result<rusoto_core::credential::AwsCredentials, rusoto_core::credential::CredentialsError> { match self.web_identity_provider.credentials().await { Err(e...
if with_fallback { Some(DefaultCredentialsProvider::new()?) } else { None }
if_condition
[ { "content": "pub fn main() {\n\n println!(\n\n \"{}\",\n\n serde_yaml::to_string(&TrustPolicyStatement::crd()).unwrap()\n\n );\n\n println!(\n\n \"{}\",\n\n serde_yaml::to_string(&RoleUsagePolicy::crd()).unwrap()\n\n );\n\n}\n", "file_path": "rustrial-k8s-aws-iam-api...
Rust
src/model.rs
tisonkun/aredis-rs
e73f80125fd939c833c6e0d85fcc850539562ec2
use std::{cmp::Ordering, io::Cursor}; use bytes::Buf; use num::BigInt; use crate::error::{ParseError, ParseResult}; #[derive(Debug)] pub enum Model { Error(String), Status(String), Integer(i64), Double(f64), Nil, String(Vec<u8>), Array(Vec<Model>), Map(Vec<(Model, Model)>), Set(...
use std::{cmp::Ordering, io::Cursor}; use bytes::Buf; use num::BigInt; use crate::error::{ParseError, ParseResult}; #[derive(Debug)] pub enum Model { Error(String), Status(String), Integer(i64), Double(f64), Nil, String(Vec<u8>), Array(Vec<Model>), Map(Vec<(Model, Model)>), Set(...
fn parse_int<T: atoi::FromRadix10SignedChecked>(i: &[u8]) -> ParseResult<T> { match atoi::atoi::<T>(i) { Some(i) => Ok(i), None => Err(ParseError::Other(format!("malformed integer: {:?}", i))), } }
let inner = cursor.get_ref(); if inner[i] == b'\r' && inner[i + 1] == b'\n' { cursor.set_position((i + 2) as u64); return Ok(&cursor.get_ref()[start..i]); } } Err(ParseError::EndOfStream) }
function_block-function_prefix_line
[ { "content": "struct Log<K: Into<Vec<u8>> + Copy> {\n\n client: Client,\n\n key: K,\n\n}\n\n\n\nimpl<K: Into<Vec<u8>> + Copy> Log<K> {\n\n const LOG_SEPARATOR: u8 = b'\\n';\n\n\n\n pub fn new(client: Client, key: K) -> Self {\n\n Log { client, key }\n\n }\n\n\n\n pub async fn add<In>(&m...
Rust
src/server/state.rs
vyomkeshj/hyperqueue
24d367c9f6b9d690a25ec01e59a4db053e3d533a
use std::collections::BTreeMap; use tako::messages::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, LostWorkerReason, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use crate::common::WrappedRcRefCell; use crate::server::job::Job; use crate::server::rpc::TakoSe...
use std::collections::BTreeMap; use tako::messages::gateway::{ CancelTasks, FromGatewayMessage, LostWorkerMessage, LostWorkerReason, NewWorkerMessage, TaskFailedMessage, TaskState, TaskUpdate, ToGatewayMessage, }; use crate::common::WrappedRcRefCell; use crate::server::job::Job; use crate::server::rpc::TakoSe...
impl State { pub fn get_job(&self, job_id: JobId) -> Option<&Job> { self.jobs.get(&job_id) } pub fn get_job_mut(&mut self, job_id: JobId) -> Option<&mut Job> { self.jobs.get_mut(&job_id) } pub fn jobs(&self) -> impl Iterator<Item = &Job> { self.jobs.values() } pu...
d); } } ToGatewayMessage::Error(msg) => { log::debug!("Canceling job {} failed: {}", job_id, msg.message); } _ => { panic!("Invalid message"); } }; }); }
function_block-function_prefixed
[ { "content": "fn compute_job_detail(state_ref: &StateRef, job_id: JobId, include_tasks: bool) -> ToClientMessage {\n\n let state = state_ref.get();\n\n ToClientMessage::JobDetailResponse(\n\n state\n\n .get_job(job_id)\n\n .map(|j| j.make_job_detail(include_tasks)),\n\n )\n...
Rust
src/manifests/mod.rs
ecyrbe/apix-rust
e12a26c9dd7f84b872111bdb8fad4230d1a6d0ea
use std::path::{Path, PathBuf}; pub use self::config::ApixConfiguration; pub mod config; use anyhow::Result; use indexmap::{indexmap, IndexMap}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use strum_macros::Display as EnumDisplay; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Defa...
use std::path::{Path, PathBuf}; pub use self::config::ApixConfiguration; pub mod config; use anyhow::Result; use indexmap::{indexmap, IndexMap}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use strum_macros::Display as EnumDisplay; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Defa...
self { ApixManifest::V1(manifest) => { manifest.metadata.extensions.insert(key, value); } ApixManifest::None => (), } } #[allow(dead_code)] pub fn get_annotation(&self, key: &str) -> Option<&String> { match self { ApixManifest::V1(manifest) => manifest.metadata.annotations...
n<(PathBuf, ApixManifest)> { Self::find_manifests() .ok() .map(|mut manifests| { manifests.find(|(_, manifest)| match manifest { ApixManifest::V1(manifest) => { manifest.kind.to_string().to_lowercase() == kind && manifest.metadata.name == name } _ => fal...
random
[ { "content": "pub fn pretty_print(content: String, theme: &str, language: &str, enable_color: bool) -> Result<()> {\n\n match language {\n\n \"json\" => {\n\n let json: Value = serde_json::from_str(&content)?;\n\n let formatted = serde_json::to_string_pretty(&json)?;\n\n PrettyPrinter::new()\...
Rust
src/render/flat_model.rs
aperolix/doom-rs
f9af669788e43d385d2627a2646c4890715cdd0e
use std::rc::Rc; use cgmath::Matrix4; use crate::render::doom_gl::{gl, DoomGl}; use super::material::{Material, MaterialParam, MaterialValue, Stride}; pub struct FlatModel { vbuffer: Vec<f32>, ibuffer: Vec<u16>, pub light: f32, pub ceil: f32, pub floor: f32, material: Material, ceil_text...
use std::rc::Rc; use cgmath::Matrix4; use crate::render::doom_gl::{gl, DoomGl}; use super::material::{Material, MaterialParam, MaterialValue, Stride}; pub struct FlatModel { vbuffer: Vec<f32>, ibuffer: Vec<u16>, pub light: f32, pub ceil: f32, pub floor: f32, material: Material, ceil_text...
pub fn init(&mut self) { let mut ib = unsafe { std::mem::zeroed() }; let mut vao = unsafe { std::mem::zeroed() }; let mut vb = unsafe { std::mem::zeroed() }; unsafe { let gl = DoomGl::gl(); gl.GenBuffers(1, &mut vb); gl.BindBuffer(gl::ARRAY_BUFF...
pub fn new( vbuffer: Vec<f32>, ibuffer: Vec<u16>, ceil_texture: u32, floor_texture: u32, sky: bool, ) -> Self { unsafe { DoomGl::gl().Disable(gl::CULL_FACE) }; let mut material = Material::new(FLAT_VERT_STR, FLAT_FRAG_STR); let light_att = MaterialPar...
function_block-full_function
[ { "content": "pub fn create_shader(content: &str, shader_type: gl::types::GLenum) -> u32 {\n\n let length = content.len() as i32;\n\n\n\n let vs;\n\n unsafe {\n\n let gl = DoomGl::gl();\n\n vs = gl.CreateShader(shader_type);\n\n gl.ShaderSource(vs, 1, [content.as_ptr() as *const _]...
Rust
paxconsola-ide/src/ui.rs
tcr/paxconsola
0fca2fd3fe131a8f522b7e50f56c7e7897d342bc
use crate::*; use gloo_console::log; use js_sys::Uint8Array; use maplit::*; use std::io::prelude::*; use wasm_bindgen::prelude::*; use yew::worker::*; use yew::{html, ChangeData, Component, ComponentLink, Html, InputData, MouseEvent, ShouldRender}; const SNAKE_WORLD: &str = include_str!("../../games/snake_world.fth");...
use crate::*; use gloo_console::log; use js_sys::Uint8Array; use maplit::*; use std::io::prelude::*; use wasm_bindgen::prelude::*; use yew::worker::*; use yew::{html, ChangeData, Component, ComponentLink, Html, InputData, MouseEvent, ShouldRender}; const SNAKE_WORLD: &str = include_str!("../../games/snake_world.fth");...
b enum Msg { Noop, ChangeInput(String), ChangeExampleSelection(String), ChangeExample, CompileGameboy, CompileDos, CompileC64, PaxForthCompilerResult(String, CurrentTarget, Engine), PaxForthCompilerError(String), RgbasmCompilerResult(HashMap<String, Vec<u8>>, Engine), Gam...
meboy_binary(binary) { console.info('Playing Game Boy!'); document.querySelector('#console-target').innerHTML = '\ <iframe src="/emularity/gameboy/" id="window-gameboy" width="700" height="444"></iframe>\ '; document.querySelector('#window-gameboy').onload = (e) => { let dos = document.q...
random
[ { "content": "; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n", "file_path": "consoles/odyssey2/src/g7000.h", "rank": 0, "score": 66871.64036313878 }, { "content": "pub fn inline_into_function(program: &mut PaxProgram, method: &str, skip_method: &HashSet<String>...
Rust
src/directional_light.rs
ChangeCaps/bevy-shadows
fe3a802f413b0b990b8b5c7c37a167881d995b78
use crate::shadow_pass_node::*; use bevy::prelude::*; use bevy::render::camera::{CameraProjection, OrthographicProjection}; use bevy::render::pipeline::PrimitiveTopology; use bevy_mod_bounding::{sphere, Bounded}; const HALF_SIZE: f32 = 25.0; const MIN_BIAS: f32 = 0.00001; const MAX_BIAS: f32 = 0.00015; pub struct Sha...
use crate::shadow_pass_node::*; use bevy::prelude::*; use bevy::render::camera::{CameraProjection, OrthographicProjection}; use bevy::render::pipeline::PrimitiveTopology; use bevy_mod_bounding::{sphere, Bounded}; const HALF_SIZE: f32 = 25.0; const MIN_BIAS: f32 = 0.00001; const MAX_BIAS: f32 = 0.00015; pub struct Sha...
} impl Light for DirectionalLight { type Config = ShadowDirectionalLight; fn proj_matrix(&self, config: Option<&Self::Config>) -> Mat4 { let left = config.map_or(-HALF_SIZE, |config| config.left); let right = config.map_or(HALF_SIZE, |config| config.right); let bottom = config.map_or(...
top: HALF_SIZE, near: -20.0 * HALF_SIZE, far: 20.0 * HALF_SIZE, bias: Vec2::new(MIN_BIAS, MAX_BIAS), } }
function_block-function_prefix_line
[ { "content": "#[derive(Default)]\n\nstruct CameraState {\n\n yaw: f32,\n\n pitch: f32,\n\n}\n\n\n", "file_path": "examples/simple.rs", "rank": 3, "score": 33682.35671706798 }, { "content": "fn main() {\n\n App::build()\n\n .insert_resource(Msaa { samples: 8 })\n\n .add...
Rust
src/main.rs
skoky/arp-scanner
ff2a49b30053842494ec5e44bb7f7436648a7e9e
#[macro_use]extern crate prettytable; use std::collections::HashSet; use std::fs::File; use std::io::Write; use std::net::{IpAddr, Ipv4Addr}; use std::sync::mpsc::{self, Receiver, Sender}; use std::thread; use std::time::Duration; use clap::{App, Arg, ArgMatches}; use ipnetwork::IpNetwork; use pnet::datalink::{self...
#[macro_use]extern crate prettytable; use std::collections::HashSet; use std::fs::File; use std::io::Write; use std::net::{IpAddr, Ipv4Addr}; use std::sync::mpsc::{self, Receiver, Sender}; use std::thread; use std::time::Duration; use clap::{App, Arg, ArgMatches}; use ipnetwork::IpNetwork; use pnet::datalink::{self...
} secs...", timeout_parsed); thread::sleep(Duration::from_secs(timeout_parsed)); println!(); let mut macs: HashSet<(Ipv4Addr, MacAddr)> = HashSet::new(); loop { match rx.try_recv() { Ok((ipv4_addr, mac_addr)) => { let _ = macs.insert((ipv4_addr, mac_addr)); ...
nterface, source_ip: Ipv4Addr, source_mac: MacAddr, target_ip: Ipv4Addr, target_mac: MacAddr, arp_operation: ArpOperation) { let (mut tx, _) = match datalink::channel(&interface, Default::default()) { Ok(Channel::Ethernet(tx, rx)) => (tx, rx), Ok(_) => panic!("Unknown channel typ...
random
[ { "content": "\n\n# arp-scanner\n\n\n\nSimple tool to discover hosts on your network using ARP requests.\n\n\n\nWorks by firing ARP requests for each possible address and listening for ARP replies.\n\n\n\nBuilt in rust using the `pnet` crate and works on Linux, Windows and probably OS X (untested).\n\n\n\n## Us...
Rust
rill-engine/src/tracers/tracer.rs
danielparks/rillrate
7ef536619248b6333e880e859191a831e60a47cc
use crate::actors::connector; use anyhow::Error; use meio::Action; use rill_protocol::flow::core::{self, ActionEnvelope, TimedEvent}; use rill_protocol::io::provider::{Description, Path, ProviderProtocol, Timestamp}; use rill_protocol::io::transport::Direction; use std::sync::{Arc, Mutex, Weak}; use std::time::{Dura...
use crate::actors::connector; use anyhow::Error; use meio::Action; use rill_protocol::flow::core::{self, ActionEnvelope, TimedEvent}; use rill_protocol::io::provider::{Description, Path, ProviderProtocol, Timestamp}; use rill_protocol::io::transport::Direction; use std::sync::{Arc, Mutex, Weak}; use std::time::{Dura...
unwrap_or_else(SystemTime::now) .duration_since(SystemTime::UNIX_EPOCH) .map(Timestamp::from) .map_err(Error::from) }
function_block-function_prefix_line
[]
Rust
src/lib.rs
thomasjgrady/nd
12be19e540a174698b1679116f5cc0c7c9eec3ad
#![feature(generic_associated_types)] #![feature(trait_alias)] use std::{ fmt::{Display, Formatter}, ops::{Index, IndexMut} }; use collect_slice::CollectSlice; use num_traits::{Num, Zero}; pub mod index_tricks; use index_tricks::*; #[derive(Clone, Debug, PartialEq)] pub enum Error { DimensionError(Str...
#![feature(generic_associated_types)] #![feature(trait_alias)] use std::{ fmt::{Display, Formatter}, ops::{Index, IndexMut} }; use collect_slice::CollectSlice; use num_traits::{Num, Zero}; pub mod index_tricks; use index_tricks::*; #[derive(Clone, Debug, PartialEq)] pub enum Error { DimensionError(Str...
eshape<M> for Array<K, N> { type Output = Array<K, M>; fn reshape(self, shape: Size<M>) -> Result<Self::Output> { let p1: usize = self.shape.iter().product(); let p2: usize = shape.iter().product(); if p1 != p2 { return Err(Error::DimensionError(format!("Shape products do n...
range: self, shape, curr } } } #[derive(Clone, Debug, PartialEq)] pub struct Array<K, const N: usize> { pub shape: Size<N>, pub strides: Size<N>, pub data: Box<[K]> } #[derive(Clone, Debug, PartialEq)] pub struct ArrayView<'a, K, const N: usize> { pub s...
random
[ { "content": "pub fn shape_from_bounds<const N: usize>(start: &Size<N>, stop: &Size<N>) -> Size<N> {\n\n let mut out = [0; N];\n\n start.iter()\n\n .zip(stop.iter())\n\n .map(|(s1, s2)| s2-s1)\n\n .collect_slice(&mut out);\n\n out\n\n}\n\n\n", "file_path": "src/index_tricks.rs"...
Rust
automerge-persistent-localstorage/src/lib.rs
pixelspark/automerge-persistent
2ea5324fa5d0d9a845fa5d79c672fa0ad499066d
#![warn(missing_docs)] #![warn(missing_crate_level_docs)] #![warn(missing_doc_code_examples)] #![warn(clippy::pedantic)] #![warn(clippy::nursery)] use std::collections::HashMap; use automerge_persistent::{Persister, StoredSizes}; use automerge_protocol::ActorId; #[derive(Debug)] pub struct LocalStoragePersister { ...
#![warn(missing_docs)] #![warn(missing_crate_level_docs)] #![warn(missing_doc_code_examples)] #![warn(clippy::pedantic)] #![warn(clippy::nursery)] use std::collections::HashMap; use automerge_persistent::{Persister, StoredSizes}; use automerge_protocol::ActorId; #[derive(Debug)] pub struct LocalStoragePersister { ...
lt<(), Self::Error> { self.sizes.sync_states += sync_state.len(); if let Some(old) = self.sync_states.insert(peer_id, sync_state) { self.sizes.sync_states -= old.len(); } self.storage .set_item( &self.sync_states_key, &serde_json::t...
g(&self.changes)?) .map_err(LocalStoragePersisterError::StorageError)?; Ok(()) } fn remove_changes(&mut self, changes: Vec<(&ActorId, u64)>) -> Result<(), Self::Error> { let mut some_removal = false; for (a, s) in changes { let key = make_key(a, s); i...
random
[]
Rust
src/prediction/first.rs
pczarn/bnf
99d7f1e6e294c859bff1bc7fc5b0bdaa56caf87e
use std::collections::{BTreeMap, BTreeSet}; use grammar::{ContextFree, ContextFreeRef}; use prediction::PerSymbolSets; use rule::GrammarRule; use symbol::{Symbol, SymbolBitSet}; pub struct FirstSets { pub(super) map: PerSymbolSets, } pub struct FirstSetsCollector<'a, G> { pub(super) map: PerSymbolSets, ...
use std::collections::{BTreeMap, BTreeSet}; use grammar::{ContextFree, ContextFreeRef}; use prediction::PerSymbolSets; use rule::GrammarRule; use symbol::{Symbol, SymbolBitSet}; pub struct FirstSets { pub(super) map: PerSymbolSets, } pub struct FirstSetsCollector<'a, G> { pub(super) map: PerSymbolSets, ...
fn rule(&mut self, lhs: Symbol, rhs: &[Symbol]) -> bool { self.first_set_collect(rhs); let first_set = self.map.entry(lhs).or_insert_with(BTreeSet::new); let prev_cardinality = first_set.len(); first_set.extend(self.lookahead.iter().cloned()); self.lookahead.clear(); ...
fn collect(&mut self) { while self.changed { self.changed = false; for rule in self.grammar.rules() { let set_changed = self.rule(rule.lhs(), rule.rhs()); self.changed |= set_changed; } } }
function_block-full_function
[ { "content": "/// Returns the set of used symbols.\n\nfn used_syms<'a, G>(grammar: &'a G) -> BitVec\n\n where G: ContextFree,\n\n &'a G: ContextFreeRef<'a, Target = G>\n\n{\n\n let num_syms = grammar.sym_source().num_syms();\n\n let mut used_syms = BitVec::from_elem(num_syms, false);\n\n\n\n ...
Rust
apk/src/sign.rs
cloudpeers/xcross
6ccbde906b7cc5ad071f7f714eb5f276695574a4
use anyhow::Result; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use rasn_pkix::Certificate; use rsa::pkcs8::{DecodePublicKey, EncodePublicKey}; use rsa::{Hash, PaddingScheme, PublicKey, RsaPublicKey}; use sha2::{Digest as _, Sha256}; use std::fs::File; use std::io::{BufReader, Cursor, Read, Seek, SeekFr...
use anyhow::Result; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use rasn_pkix::Certificate; use rsa::pkcs8::{DecodePublicKey, EncodePublicKey}; use rsa::{Hash, PaddingScheme, PublicKey, RsaPublicKey}; use sha2::{Digest as _, Sha256}; use std::fs::File; use std::io::{BufReader, Cursor, Read, Seek, SeekFr...
fn write(&self, w: &mut impl Write) -> Result<()> { let mut buffer = vec![]; for signer in &self.signers { let mut signer_buffer = vec![]; signer_buffer.write_u32::<LittleEndian>(signer.signed_data.len() as u32)?; signer_buffer.write_all(&signer.signed_data)?; ...
eEndian>()?; let mut signature = vec![0; size as usize]; r.read_exact(&mut signature)?; signatures.push(ApkSignature { algorithm, signature, }); remaining_signature_size -= signature_size + 4; ...
function_block-function_prefixed
[ { "content": "pub fn p7x(signer: &Signer, digests: &Digests) -> Vec<u8> {\n\n let payload = Payload::encode(digests);\n\n let encap_content_info = EncapsulatedContentInfo {\n\n content_type: SPC_INDIRECT_DATA_OBJID.into(),\n\n content: Any::new(payload),\n\n };\n\n let signed_data = bu...
Rust
src/split.rs
celestecote21/Tity3
54cf1468dc81e400b3496482ac69569225d4584d
use crate::container::*; use crate::container_action::*; use crate::layout::*; use crate::size_utilis::*; use std::str; use std::sync::mpsc::Sender; pub struct Split { parent_com: Sender<ChildToParent>, list_child: ContainerList, layout: Layout, focused: Option<usize>, id: String, } impl Split { ...
use crate::container::*; use crate::container_action::*; use crate::layout::*; use crate::size_utilis::*; use std::str; use std::sync::mpsc::Sender; pub struct Split { parent_com: Sender<ChildToParent>, list_child: ContainerList, layout: Layout, focused: Option<usize>, id: String, } impl Split { ...
for cont in self.list_child.iter_mut() { match destroy_container(cont, id) { Ok(_) => { self.list_child.remove(i); let mut rect_child = self.layout.del_child(); self.update_rect_child(&mut rect_child); r...
if id == "-2" && self.focused.is_some() { match destroy_container( self.list_child.get_mut(self.focused.unwrap()).unwrap(), "-2", ) { Ok(_) => { get_focused_child(self, None); self.list_child.remove(self.focu...
if_condition
[ { "content": "/// Call the get_input fonction of corresponding struct inside the Container\n\npub fn get_input_container(data: [u8; 4096], size: usize, cont: &mut Container) {\n\n match cont {\n\n Container::Split(sp) => {\n\n sp.get_input(data, size);\n\n }\n\n Container::Pan...
Rust
services/graphics-server/src/op.rs
lnceballosz/xous-core
520c5aa18f96fe367299e77278c38ff2198bb607
use crate::api::{Circle, DrawStyle, Line, Pixel, PixelColor, Point, Rectangle}; pub const LCD_WORDS_PER_LINE: usize = 11; pub const LCD_PX_PER_LINE: usize = 336; pub const LCD_LINES: usize = 536; pub const LCD_FRAME_BUF_SIZE: usize = LCD_WORDS_PER_LINE * LCD_LINES; pub const WIDTH: i16 = 336; pub const HEIGHT: i16 = ...
use crate::api::{Circle, DrawStyle, Line, Pixel, PixelColor, Point, Rectangle}; pub const LCD_WORDS_PER_LINE: usize = 11; pub const LCD_PX_PER_LINE: usize = 336; pub const LCD_LINES: usize = 536; pub const LCD_FRAME_BUF_SIZE: usize = LCD_WORDS_PER_LINE * LCD_LINES; pub const WIDTH: i16 = 336; pub const HEIGHT: i16 = ...
fb, pixel.0.x, pixel.0.y, pixel.1); } }
y1 { 1 } else { -1 }; let mut err = dx + dy; /* error value e_xy */ loop { /* loop */ if x0 >= 0 && y0 >= 0 && x0 < (WIDTH as _) && y0 < (HEIGHT as _) { put_pixel(fb, x0 as _, y0 as _, color); } if x0 == x1 && y0 == y1 { break; } let e2 = 2...
random
[ { "content": "pub fn irq(_irq_number: usize, _arg: *mut usize) {\n\n println!(\n\n \"Interrupt {}: Key pressed: {}\",\n\n _irq_number,\n\n Uart {}\n\n .getc()\n\n .expect(\"no character queued despite interrupt\") as char\n\n );\n\n}\n\n\n\n#[cfg(baremetal)]\n\ni...
Rust
src/day_08.rs
misfits42/advent_of_code_2021
f66cb0e723e28c8d63297ad81887768be8614a8a
use std::collections::HashMap; use std::collections::HashSet; use itertools::Itertools; #[aoc_generator(day8)] fn parse_input(input: &str) -> Vec<(Vec<String>, Vec<String>)> { let mut output: Vec<(Vec<String>, Vec<String>)> = vec![]; for line in input.lines() { let line = line.trim(); if line....
use std::collections::HashMap; use std::collections::HashSet; use itertools::Itertools; #[aoc_generator(day8)] fn parse_input(input: &str) -> Vec<(Vec<String>, Vec<String>)> { let mut output: Vec<(Vec<String>, Vec<String>)> = vec![]; for line in input.lines() { let line = line.trim(); if line....
} } value.remove(&to_remove[0]); } } let mut signal_wire_map: HashMap<char, char> = HashMap::new(); for (segment, wires) in overlaps { signal_wire_map.insert(segment, *wires.iter().next().unwrap()); } ...
(); } overlaps.insert(*key, output_set); } let mut unique_output_segments: HashSet<char> = HashSet::new(); for (_key, value) in overlaps.iter() { if value.len() == 1 { unique_output_segments.insert(*value.iter().next().unwrap()); ...
function_block-random_span
[]
Rust
garnet/bin/setui/src/privacy/privacy_fidl_handler.rs
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
use parking_lot::RwLock; use std::sync::Arc; use futures::lock::Mutex; use futures::TryStreamExt; use fidl::endpoints::ServiceMarker; use fidl_fuchsia_settings::{ Error, PrivacyMarker, PrivacyRequest, PrivacyRequestStream, PrivacySetResponder, PrivacySettings, PrivacyWatchResponder, }; use fuchsia_async as ...
use parking_lot::RwLock; use std::sync::Arc; use futures::lock::Mutex; use futures::TryStreamExt; use fidl::endpoints::ServiceMarker; use fidl_fuchsia_settings::{ Error, PrivacyMarker, PrivacyRequest, PrivacyRequestStream, PrivacySetResponder, PrivacySettings, PrivacyWatchResponder, }; use fuchsia_async as ...
}
ARING_CONSENT: bool = true; let mut privacy_settings = PrivacySettings::empty(); privacy_settings.user_data_sharing_consent = Some(USER_DATA_SHARING_CONSENT); let request = SettingRequest::from(privacy_settings); assert_eq!( request, SettingRequest::SetUserData...
function_block-function_prefixed
[]
Rust
src/day19.rs
TheJare/aoc2021
1aabacc5bf3210e98c2d5997bbf00f4bad9bbe30
use crate::utils::read_from_file; use anyhow::Result; use itertools::{iproduct, Itertools}; use std::collections::HashSet; type Point = (i32, i32, i32); type Scanner = HashSet<Point>; pub fn read_input(args: &crate::File) -> Result<Vec<Scanner>> { let lines = read_from_file(&args.file)?; let mut scanners = V...
use crate::utils::read_from_file; use anyhow::Result; use itertools::{iproduct, Itertools}; use std::collections::HashSet; type Point = (i32, i32, i32); type Scanner = HashSet<Point>; pub fn read_input(args: &crate::File) -> Result<Vec<Scanner>> { let lines = read_from_file(&args.file)?; let mut scanners = V...
fn try_match_scanner(main: &Scanner, candidate: &Scanner) -> Option<(Scanner, Point)> { for rot in 0..24 { let rotated_candidate = candidate.iter().map(|p| rotate(*p, rot)).collect(); if let Some(offset) = find_matching_offset(main, &rotated_candidate) { return Some((rotated_candi...
for (point_from_scanner, point_from_candidate) in pairs { let offset = sub_points(point_from_candidate, point_from_scanner); let num_identical = candidate .iter() .filter(|&v| scanner.contains(&sub_points(v, &offset))) .take(12) .count(); ...
function_block-function_prefix_line
[ { "content": "pub fn run_1(mut a: usize, mut b: usize) -> usize {\n\n let mut dice = 0;\n\n let (mut s1, mut s2) = (0, 0);\n\n while s1 < 1000 && s2 < 1000 {\n\n a = (a + dice % 100 + (dice + 1) % 100 + (dice + 2) % 100 + 3) % 10;\n\n dice += 3;\n\n s1 += a + 1;\n\n if s1 < ...
Rust
src/manifest/common.rs
Perlmint/sxs-manifest
fadd48c0eca6d45b2029caeb207f03cc8cfd7866
use crate::xml_alias::{XmlAttribute, XmlName, XmlNamespace}; use crate::{ consts::NS_MS_ASM_V1, debug::Path, serialize::{SerializableElement, SerializableValue, SerializeResult}, }; use std::{borrow::Cow, io::Write}; use xml::{writer::XmlEvent, EventWriter}; #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub...
use crate::xml_alias::{XmlAttribute, XmlName, XmlNamespace}; use crate::{ consts::NS_MS_ASM_V1, debug::Path, serialize::{SerializableElement, SerializableValue, SerializeResult}, }; use std::{borrow::Cow, io::Write}; use xml::{writer::XmlEvent, EventWriter}; #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub...
; if let Some(process_architecture) = &process_architecture { attributes.push(XmlAttribute { name: AssemblyIdentity::ATTRIBUTE_PROCESS_ARCHITECTURE_NAME, value: process_architecture, }); } let version = if let Some(version) = &self.version...
if let Some(process_architecture) = &self.process_architecture { Some(process_architecture.serialize()) } else { None }
if_condition
[ { "content": "pub trait SerializableValue {\n\n fn serialize(&self) -> Cow<'_, str>;\n\n}\n", "file_path": "src/serialize.rs", "rank": 0, "score": 43453.534894012555 }, { "content": "#[test]\n\nfn test_max_version_tested() {\n\n use manifest::*;\n\n\n\n let mut manifest = AssemblyMa...
Rust
src/gameboy/gfx/gpu.rs
simon-whitehead/chemboy
c25a60152172a397a0a3cf8fb5cb27ce84e66320
use byteorder::{ByteOrder, LittleEndian}; use std; use gameboy; use gameboy::{Interconnect, Interrupt, Irq, Memory}; use gameboy::gfx::{Color, Frame, GpuMode, GpuStat, SpriteShape, TileRenderOptions, TileRenderType}; use gameboy::ui::theme::Theme; pub struct Gpu { pub enabled: bool, pub ram: Memory, pub ...
use byteorder::{ByteOrder, LittleEndian}; use std; use gameboy; use gameboy::{Interconnect, Interrupt, Irq, Memory}; use gameboy::gfx::{Color, Frame, GpuMode, GpuStat, SpriteShape, TileRenderOptions, TileRenderType}; use gameboy::ui::theme::Theme; pub struct Gpu { pub enabled: bool, pub ram: Memory, pub ...
pub fn write_u16(&mut self, addr: u16, val: u16) { let addr = addr as usize; LittleEndian::write_u16(&mut self.ram[addr..], val) } fn check_coincidence(&mut self, irq: &mut Irq) { if self.lyc == self.ly && self.stat.coincidence_interrupt_enabled { irq.request(...
self.frame = Frame::new(); } } 0x41 => self.stat = GpuStat::from(val), 0x42 => self.scroll_y = val, 0x43 => self.scroll_x = val, 0x44 => (), 0x45 => { self.lyc = val; } 0x47 => self.bg_palette...
function_block-function_prefix_line
[ { "content": "pub fn get_ram_size(b: u8) -> usize {\n\n match b {\n\n 0x01 => 0x800, // 2KB (2048 bytes)\n\n 0x02 => 0x2000, // 8KB (8096 bytes)\n\n 0x03 => 0x8000, // 32KB\n\n _ => 0x00,\n\n }\n\n}", "file_path": "src/gameboy/mbc/mbc.rs", "rank": 0, "s...
Rust
wheel/src/components/raft_log_store.rs
MrCroxx/RunKV
0770ce449363a98814c80e343a4e6e6a029e5f6b
use async_trait::async_trait; use bytes::{Buf, BufMut}; use itertools::Itertools; use runkv_storage::raft_log_store::entry::RaftLogBatch; use runkv_storage::raft_log_store::RaftLogStore; use crate::error::{Error, Result}; const RAFT_HARD_STATE_KEY: &[u8] = b"raft_hard_state"; const RAFT_CONF_STATE_KEY: &[u8] = b"raft...
use async_trait::async_trait; use bytes::{Buf, BufMut}; use itertools::Itertools; use runkv_storage::raft_log_store::entry::RaftLogBatch; use runkv_storage::raft_log_store::RaftLogStore; use crate::error::{Error, Result}; const RAFT_HARD_STATE_KEY: &[u8] = b"raft_hard_state"; const RAFT_CONF_STATE_KEY: &[u8] = b"raft...
str().unwrap(); let options = RaftLogStoreOptions { node: 0, log_dir_path: path.to_string(), log_file_capacity: 64 << 20, block_cache_capacity: 64 << 20, persist: Persist::Sync, }; let raft_log_store = RaftLogStore::open(options).await...
ult<Vec<raft::prelude::Entry>> { let high = match max_size { None => high, Some(max_size) => std::cmp::min(high, low.saturating_add(std::cmp::max(max_size, 1))), }; let index = low; let max_len = (high - low) as usize; let raw_entries = self .c...
random
[ { "content": "fn key(group: u8, i: u64, size: usize) -> Vec<u8> {\n\n let mut buf = Vec::with_capacity(size);\n\n buf.put_u8(b'k');\n\n buf.put_u8(group);\n\n buf.put_u64(i);\n\n buf.put_slice(&vec![b' '; size - 10]);\n\n buf\n\n}\n\n\n", "file_path": "tests/src/lib.rs", "rank": 1, ...
Rust
benches/json.rs
AlienKevin/straight-parse
7565789c1e4f51eb1a5e8af9a5606625a8b35bce
use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion}; #[macro_use] extern crate partial_application; use lip::Trailing; use lip::*; use std::collections::HashMap; use std::convert::identity; type Object = HashMap<String, Value>; type Array = Vec<Value>; #[derive(Debug, Clone, PartialEq)]...
use criterion::{black_box, criterion_group, criterion_main, Bencher, Criterion}; #[macro_use] extern crate partial_application; use lip::Trailing; use lip::*; use std::collections::HashMap; use std::convert::identity; type Object = HashMap<String, Value>; type Array = Vec<Value>; #[derive(Debug, Clone, PartialEq)]...
.keep(repeat(4, hex_digit())) )) ), "a closing `\"`", token("\""), )) .skip(token("\"")) } fn hex_digit<'a>() -> BoxedParser<'a, char, ()> { succeed!(|cs: String| cs.chars().next().unwrap()).keep(take_chomped(chomp_ifc( |c| match *...
is_non_escape, "Any Unicode characters except \" or \\ or control characters", ))), succeed!(identity).skip(token("\\")).keep(one_of!( token("\"").map(|_| '\"'), token("\\").map(|_| '\\'), token("/...
function_block-random_span
[ { "content": "/// Pretty print the error.\n\n///\n\n/// Example:\n\n/// 1| A=A+2\n\n/// ^^^\n\n/// ⚠️ I can't find a computation instruction matching `A+2`.\n\n/// Try something like `D+1` and `0`.\n\npub fn display_error(source: &str, error_message: String, from: Location, to: Location) -> String {\n\n ...
Rust
sv-parser-parser/src/specify_section/specify_path_delays.rs
zarubaf/sv-parser
1189f2d1c9f0275eb15990ca6c074282b4f88d3c
use crate::*; #[tracable_parser] #[packrat_parser] pub(crate) fn path_delay_value(s: Span) -> IResult<Span, PathDelayValue> { alt(( map(list_of_path_delay_expressions, |x| { PathDelayValue::ListOfPathDelayExpressions(Box::new(x)) }), path_delay_value_paren, ))(s) } #[tracab...
use crate::*; #[tracable_parser] #[packrat_parser] pub(crate) fn path_delay_value(s: Span) -> IResult<Span, PathDelayValue> { alt(( map(list_of_path_delay_expressions, |x| { PathDelayValue::ListOfPathDelayExpressions(Box::new(x)) }), path_delay_value_paren, ))(s) } #[tracab...
Ok((s, ParallelEdgeSensitivePathDescription { nodes: (a,) })) } #[tracable_parser] #[packrat_parser] pub(crate) fn full_edge_sensitive_path_description( s: Span, ) -> IResult<Span, FullEdgeSensitivePathDescription> { let (s, a) = paren(tuple(( opt(edge_identifier), list_of_path_inputs, ...
let (s, a) = paren(tuple(( opt(edge_identifier), specify_input_terminal_descriptor, opt(polarity_operator), symbol("=>"), paren(tuple(( specify_output_terminal_descriptor, opt(polarity_operator), symbol(":"), data_source_expression,...
assignment_statement
[ { "content": " class C extends B;\n\n endclass\"##,\n\n Ok((_, _))\n\n );\n\n test!(\n\n many1(module_item),\n\n r##\"interface class PutImp#(type PUT_T = logic);\n\n pure virtual function void put(PUT_T a);\n\n ...
Rust
src/api_handling/api_desc_dir.rs
arctic-alpaca/fritz_box_tr064_igd_api_files_generator
a90e2b439c994a5505731caacc7ea92db5a2df0a
use crate::api_handling::api_desc::ApiDesc; use std::fs; use std::fs::File; use std::io::Write; #[derive(Deserialize, Debug, Default)] pub struct ApiDescDir { #[serde(rename = "specVersion")] pub spec_version: SpecVersion, #[serde(rename = "systemVersion")] #[serde(default)] pub system_...
use crate::api_handling::api_desc::ApiDesc; use std::fs; use std::fs::File; use std::io::Write; #[derive(Deserialize, Debug, Default)] pub struct ApiDescDir { #[serde(rename = "specVersion")] pub spec_version: SpecVersion, #[serde(rename = "systemVersion")] #[serde(default)] pub system_...
fn write_requests_files(&self) { for request_file in &self.request_files { let mut file = File::create(format!( "{}/{}{}.rs", &self.request_output_folder, self.prefix, request_file.name )) .unwrap(); for function...
p(); file_name_vec.clear(); let mut file = File::create(format!("{}/mod.rs", &self.request_output_folder)).unwrap(); for request_file in &self.request_files { file_name_vec.push(format!("pub mod {}{};\n", self.prefix, request_file.name)); } file_name_vec.sort(...
function_block-function_prefixed
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let resp = reqwest::blocking::get(format!(\"{}/tr64desc.xml\", ADDRESS).as_str())?.text()?;\n\n let tr64desc: ApiDescDir = serde_xml_rs::from_str(&*resp)?;\n\n tr64desc.generate_files(\n\n ADDRESS,\n\n RESPONSES_OUTPU...
Rust
rpc-server/src/dispatchers/blockchain.rs
terorie/nimiq-core-rs-albatross
56a214cd91d2230bc48693d0777cb5e88dd8a303
use std::sync::Arc; use async_trait::async_trait; use futures::stream::{BoxStream, StreamExt}; use nimiq_blockchain_albatross::{Blockchain, BlockchainEvent}; use nimiq_hash::Blake2bHash; use nimiq_primitives::policy; use nimiq_rpc_interface::{ types::{Block, OrLatest, SlashedSlots, Slot, Stake, Stakes, Validator}...
use std::sync::Arc; use async_trait::async_trait; use futures::stream::{BoxStream, StreamExt}; use nimiq_blockchain_albatross::{Blockchain, BlockchainEvent}; use nimiq_hash::Blake2bHash; use nimiq_primitives::policy; use nimiq_rpc_interface::{ types::{Block, OrLatest, SlashedSlots, Slot, Stake, Stakes, Validator}...
async fn get_slot_at(&mut self, block_number: u32, view_number_opt: Option<u32>) -> Result<Slot, Error> { if policy::is_macro_block_at(block_number) { return Err(Error::UnexpectedMacroBlock(block_number.into())); } let view_number = if let Some(view_...
OrLatest::Value(block_number) => self .blockchain .get_block_at(block_number, true) .ok_or_else(|| Error::BlockNotFound(block_number.into()))?, OrLatest::Latest => self.blockchain.head().clone(), }; Ok(Block::from_block(&self.blockchain, block...
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn is_election_block_at(block_number: u32) -> bool {\n\n epoch_index_at(block_number) == EPOCH_LENGTH - 1\n\n}\n\n\n\n/// Returns the number (height) of the next macro block after a given block number (height).\n", "file_path": "primitives/src/policy.rs", "rank": 0, ...
Rust
src/github.rs
EmbarkStudios/opensource
e6e5bd11919d0de6516c367f63a508a6ffd4dfc7
mod codeowners; use std::collections::{HashMap, HashSet}; pub use codeowners::CodeOwners; use eyre::{eyre, WrapErr}; use lazy_static::lazy_static; use regex::Regex; use serde::de::DeserializeOwned; pub struct Client { github_api_token: Option<String>, } impl Client { pub fn new(github_api_token: Option<Str...
mod codeowners; use std::collections::{HashMap, HashSet}; pub use codeowners::CodeOwners; use eyre::{eyre, WrapErr}; use lazy_static::lazy_static; use regex::Regex; use serde::de::DeserializeOwned; pub struct Client { github_api_token: Option<String>, } impl Client { pub fn new(github_api_token: Option<Str...
} fn next_pagination_page_from_link_header( header: &reqwest::header::HeaderValue, ) -> eyre::Result<Option<String>> { Ok(header .to_str() .wrap_err("Header was not valid unicode")? .split(',') .find_map(parse_next_link_url)) } fn parse_next_link_url(content: &str) -> Option<S...
match response.headers().get("link") { None => Ok(None), Some(link) => Ok(next_pagination_page_from_link_header(link) .wrap_err("Unable to find next pagination page url in link header")?), }
if_condition
[ { "content": "fn validate_name_format(name: String) -> eyre::Result<String> {\n\n if name.starts_with('@') {\n\n Ok(name.trim_start_matches('@').to_string())\n\n } else {\n\n Err(eyre!(\"Code owner `{}` does not start with an @\", name))\n\n }\n\n}\n\n\n\nimpl CodeOwners {\n\n pub fn n...
Rust
fantoch/src/client/workload.rs
vitorenesduarte/planet_sim
aea6e324fdce7802976cbafa88a516ed40609ce9
use crate::client::key_gen::{KeyGen, KeyGenState}; use crate::command::Command; use crate::id::{RiflGen, ShardId}; use crate::kvs::{KVOp, Key, Value}; use crate::trace; use crate::HashMap; use rand::distributions::Alphanumeric; use rand::Rng; use serde::{Deserialize, Serialize}; use std::iter; #[derive(Debug, Clone, C...
use crate::client::key_gen::{KeyGen, KeyGenState}; use crate::command::Command; use crate::id::{RiflGen, ShardId}; use crate::kvs::{KVOp, Key, Value}; use crate::trace; use crate::HashMap; use rand::distributions::Alphanumeric; use rand::Rng; use serde::{Deserialize, Serialize}; use std::iter; #[derive(Debug, Clone, C...
} let read_only_percentage = 0; Self { shard_count: shard_count as u64, keys_per_command, key_gen, commands_per_client, read_only_percentage, payload_size, command_count: 0, } } pu...
if keys_per_command > 2 { panic!("invalid workload; can't generate more than two keys with the conflict_rate key generator"); }
if_condition
[ { "content": "#[allow(clippy::ptr_arg)]\n\npub fn key_hash(key: &Key) -> u64 {\n\n let mut hasher = DefaultHasher::default();\n\n key.hash(&mut hasher);\n\n hasher.finish()\n\n}\n\n\n", "file_path": "fantoch/src/util.rs", "rank": 0, "score": 281407.3342443938 }, { "content": "pub fn...
Rust
src/markets/market/orderbook.rs
mikedotexe/flux-protocol
6de7c44b1d406fc799ff092ca16aec0a4a2d99be
use std::collections::{BTreeMap, HashMap}; use std::cmp; use borsh::{BorshDeserialize, BorshSerialize}; use near_sdk::{near_bindgen}; use serde::{Deserialize, Serialize}; use std::convert::TryInto; pub mod order; pub type Order = order::Order; #[near_bindgen] #[derive(Serialize, Deserialize, BorshDeserialize, BorshSe...
use std::collections::{BTreeMap, HashMap}; use std::cmp; use borsh::{BorshDeserialize, BorshSerialize}; use near_sdk::{near_bindgen}; use serde::{Deserialize, Serialize}; use std::convert::TryInto; pub mod order; pub type Order = order::Order; #[near_bindgen] #[derive(Serialize, Deserialize, BorshDeserialize, BorshSe...
} } for entry in to_remove { self.remove_order(entry.0); } } pub fn calc_claimable_amt( &self, account_id: String ) -> u128 { let mut claimable = 0; let empty_vec: Vec<u128> = vec![]; let orders_by_user_vec = self.orders_by_user.get(&account_id).unwrap_or(&empty_vec); for i in...
if amt_of_shares_to_fill > 0 { let shares_remaining_in_order = order.amt_of_shares - order.shares_filled; let filling = cmp::min(shares_remaining_in_order, amt_of_shares_to_fill); *self.liquidity_by_price.entry(order.price).or_insert(0) -= filling * order.price; order...
if_condition
[ { "content": "type Order = orderbook::Order;\n\n\n\n#[near_bindgen]\n\n#[derive(Serialize, Deserialize, BorshDeserialize, BorshSerialize, Debug)]\n\npub struct Market {\n\n\tpub id: u64,\n\n\tpub description: String,\n\n\tpub extra_info: String,\n\n\tpub creator: String,\n\n\tpub outcomes: u64,\n\n\tpub outcome...
Rust
src/connection/connector.rs
dedefer/alopecosa
5ecb7ab1972e85aca3badc3ca00839cdc70733cf
use std::{ str, net::SocketAddr, sync::{Arc, atomic::AtomicBool}, time::Duration, }; use base64::decode; use dashmap::DashMap; use sha1::{Digest, Sha1}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpSocket, TcpStream}, sync::mpsc, }; use crate::iproto::{ request::{self, Auth}, response::R...
use std::{ str, net::SocketAddr, sync::{Arc, atomic::AtomicBool}, time::Duration, }; use base64::decode; use dashmap::DashMap; use sha1::{Digest, Sha1}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpSocket, TcpStream}, sync::mpsc, }; use crate::iproto::{ request::{self, Auth}, response::R...
fn parse_greeting<'g>(&self, greeting: &'g [u8; 128]) -> Option<(&'g str, &'g [u8])> { const START: &str = "Tarantool "; const PROTO: &str = " (Binary) "; const SEP: &str = "\n"; const SALT_LEN: usize = 44; let greeting = match str::from_utf8(&greeting[..]) { Ok(g) => g, Err(_) => r...
async fn handle_greating_and_auth( &self, conn: &mut TcpStream, ) -> Result<String, std::io::Error> { let mut greeting_buf = [0u8; 128]; conn.read_exact(&mut greeting_buf).await?; let (version, salt) = self.parse_greeting(&greeting_buf) .ok_or_else(|| std::io::Error::new( std::io::Err...
function_block-full_function
[ { "content": "struct OnExit(SocketAddr, &'static str);\n\n\n\nimpl Drop for OnExit {\n\n fn drop(&mut self) {\n\n log::debug!(\"[{}] {} closed\", self.0, self.1);\n\n }\n\n}\n", "file_path": "src/connection/connection_server.rs", "rank": 0, "score": 107171.39111408529 }, { "content": "f...
Rust
src/instruments/mdt693_b.rs
TsuITOAR/rustrument
3bb0fc5c51bc81cda94883bf22d2b0dbe40892be
use super::Model; use crate::DefaultConfig; #[derive(Default)] pub struct MDT693B; impl DefaultConfig for MDT693B { type DefaultProtocol = crate::protocols::Serial; const DEFAULT_PROTOCOL: Self::DefaultProtocol = Self::DefaultProtocol { baud_rate: serial::Baud115200, data_bits: serial::Bits8, ...
use super::Model; use crate::DefaultConfig; #[derive(Default)] pub struct MDT693B; impl DefaultConfig for MDT693B { type DefaultProtocol = crate::protocols::Serial; const DEFAULT_PROTOCOL: Self::DefaultProtocol = Self::DefaultProtocol { baud_rate: serial::Baud115200, data_bits: serial::Bits8, ...
} impl super::Command for Command { type R = Box<[u8]>; fn to_bytes(self) -> Self::R { match self { Command::SetEchoCommand(bo) => format!("echo={}", bo).into_bytes(), Command::SetDisplayIntensity(n) => format!("intensity={}", n).into_bytes(), Command::SetAllVoltag...
fn to_bytes(self) -> Self::R { match self { Query::GetCommands => "?", Query::ProductInformation => "id?", Query::GetEchoCommandValue => "echo?", Query::LimitSwitchSetting => "vlimit?", Query::GetDisplayIntensity => "intensity?", Query::Get...
function_block-full_function
[ { "content": "pub trait DefaultConfig: Model + Sized + Default {\n\n type DefaultProtocol: Protocol;\n\n const TIME_OUT: Duration = Duration::from_secs(1);\n\n const DEFAULT_PROTOCOL: Self::DefaultProtocol;\n\n fn default_connect(\n\n address: <Self::DefaultProtocol as Protocol>::Address,\n\n...
Rust
src/target.rs
valkyrierobotics/nfc.rs
78eeed65b6fcc450a04adc4cbc9d9a7135069fed
use crate::ffi; pub mod target_info { pub use crate::ffi::{ nfc_barcode_info as BarcodeInfo, nfc_dep_info as DepInfo, nfc_felica_info as FelicaInfo, nfc_iso14443a_info as Iso14443aInfo, nfc_iso14443b2ct_info as Iso14443b2ctInfo, nfc_iso14443b2sr_info as Iso14443b2srInfo, nfc_iso14443b_info ...
use crate::ffi; pub mod target_info { pub use crate::ffi::{ nfc_barcode_info as BarcodeInfo, nfc_dep_info as DepInfo, nfc_felica_info as FelicaInfo, nfc_iso14443a_info as Iso14443aInfo, nfc_iso14443b2ct_info as Iso14443b2ctInfo, nfc_iso14443b2sr_info as Iso14443b2srInfo, nfc_iso14443b_info ...
, TargetInfo::ISO14443B2SR { info } => ( ffi::nfc_target_info { nsi: info }, ffi::nfc_modulation_type::NMT_ISO14443B2SR, ), TargetInfo::ISO14443B2CT { info } => ( ffi::nfc_target_info { nci: info }, ffi::nfc_modulation_t...
info: target.nti.nfi, }, ffi::nfc_modulation_type::NMT_BARCODE => TargetInfo::BARCODE { info: target.nti.nti, }, ffi::nfc_modulation_type::NMT_JEWEL => TargetInfo::JEWEL { info: target.nti.nji, ...
random
[ { "content": "/// Retrieves the version of the linked NFC library.\n\npub fn version() -> &'static str {\n\n unsafe {\n\n std::ffi::CStr::from_ptr(ffi::nfc_version())\n\n .to_str()\n\n .unwrap()\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 44022.26...
Rust
src/state/history.rs
preston-evans98/akula
5e5c0c7378114f2cebf4ce81ac49348888f682be
use crate::{ changeset::*, kv::{tables::BitmapKey, *}, models::*, read_account_storage, Cursor, Transaction, }; use ethereum_types::*; pub async fn get_account_data_as_of<'db: 'tx, 'tx, Tx: Transaction<'db>>( tx: &'tx Tx, address: Address, timestamp: BlockNumber, ) -> anyhow::Result<Option<...
use crate::{ changeset::*, kv::{tables::BitmapKey, *}, models::*, read_account_storage, Cursor, Transaction, }; use ethereum_types::*; pub async fn get_account_data_as_of<'db: 'tx, 'tx, Tx: Transaction<'db>>( tx: &'tx Tx, address: Address, timestamp: BlockNumber, ) -> anyhow::Result<Option<...
m_of_state_keys, ) .await; let mut plain_state = tx.cursor(&tables::PlainState).await.unwrap(); for i in 0..num_of_accounts { let a = addrs[i]; let acc = read_account_data(&tx, a).await.unwrap().unwrap(); assert_eq!(acc_state[i], acc); ...
assert_eq!(count, 0, "changeset must be deleted"); assert_eq!( tx.get( &tables::AccountHistory, BitmapKey { inner: addrs[0], block_number: bn } ) .await .unwrap(), ...
random
[ { "content": "pub fn keccak256(data: impl AsRef<[u8]>) -> H256 {\n\n H256::from_slice(&Keccak256::digest(data.as_ref()))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use hex_literal::hex;\n\n use secp256k1::SECP256K1;\n\n\n\n #[test]\n\n fn generate_address() {\n\n asse...
Rust
tests/demovcregistry/src/demovcregistryTestFixture.rs
credentia-network/VCRegistry
f5cdc7b5b2367d2a3328bd12feb6e33135ab961b
#![allow(unused_imports)] #![allow(non_snake_case)] #![allow(dead_code)] use std::thread::AccessError; use casper_engine_test_support::{Code, SessionBuilder, TestContext, TestContextBuilder}; use casper_types::{ account::AccountHash, bytesrepr::{FromBytes, ToBytes}, runtime_args, AsymmetricType, CLTyped,...
#![allow(unused_imports)] #![allow(non_snake_case)] #![allow(dead_code)] use std::thread::AccessError; use casper_engine_test_support::{Code, SessionBuilder, TestContext, TestContextBuilder}; use casper_types::{ account::AccountHash, bytesrepr::{FromBytes, ToBytes}, runtime_args, AsymmetricType, CLTyped,...
pub fn sendVPRequest( &mut self, sender: AccountHash, ipfsHash: [u8;32], holder: AccountHash ) { self.call( sender, "sendVPRequest", runtime_args! { "ipfsHash" => ipfsHash, "holder" => holder ...
let ipfsHashResponce_value = match ipfsHashResponce_value { None => [0u8;32], Some(ipfsHashResponce_value) => ipfsHashResponce_value }; let holder_value = match holder_value { None => AccountHash::new([0u8;32]), Some(holder_value) => holder_value ...
function_block-function_prefix_line
[ { "content": "fn vc_key(issuer: &AccountHash, index: u64, attribute: &str) -> String {\n\n format!(\"VC_{}_{}_{}\", issuer, index, attribute)\n\n}\n\n\n", "file_path": "contract/demovcregistry/src/main.rs", "rank": 0, "score": 282898.5108029513 }, { "content": "fn vprequest_key(verifier: ...
Rust
src/files.rs
jcthomassie/yurt
7fc82ab57d4fdb506bbfdefeef05b1af1161fda3
use anyhow::{anyhow, Error, Result}; use log::info; use serde::Deserialize; use std::{fs, path::PathBuf}; #[derive(Debug)] enum Status { Valid, NullHead, NullTail, InvalidHead(Error), InvalidTail(Error), } #[derive(Debug, PartialEq, Deserialize, Clone)] pub struct Link { pub head: PathBuf...
use anyhow::{anyhow, Error, Result}; use log::info; use serde::Deserialize; use std::{fs, path::PathBuf}; #[derive(Debug)] enum Status { Valid, NullHead, NullTail, InvalidHead(Error), InvalidTail(Error), } #[derive(Debug, PartialEq, Deserialize, Clone)] pub struct Link { pub head: PathBuf...
link.head.read_link().expect("Failed to read link"), link.tail ); } #[test] fn unlink_normal() { let (_dir, link) = fixture(); File::create(&link.tail).expect("Failed to create tempfile"); link.link(false).expect("Failed to create link"); l...
e_parent_dirs() { let dir = tempfile::tempdir().expect("Failed to create tempdir"); let link = Link::new( dir.path().join("parent").join("link.head"), dir.path().join("link.tail"), ); File::create(&link.tail).expect("Failed to create tempfile"); l...
function_block-random_span
[ { "content": "fn clean(matches: &ArgMatches) -> Result<()> {\n\n parse_resolved(matches)?\n\n .clean()\n\n .context(\"Failed to clean link heads\")\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 0, "score": 108184.45647582671 }, { "content": "#[inline]\n\npub fn which_has(...
Rust
src/binops/add_sub.rs
mamrhein/rust-fixed-point-decimal
a753d22c29e13b25a9b816338125caadda7b532a
use std::{ cmp::Ordering, ops::{Add, AddAssign, Sub, SubAssign}, }; use num::Zero; use rust_fixed_point_decimal_core::mul_pow_ten; use crate::{ binops::const_max_u8, prec_constraints::{PrecLimitCheck, True}, Decimal, MAX_PREC, }; impl<const P: u8> Zero for Decimal<P> where PrecLimitCheck<{ ...
use std::{ cmp::Ordering, ops::{Add, AddAssign, Sub, SubAssign}, }; use num::Zero; use rust_fixed_point_decimal_core::mul_pow_ten; use crate::{ binops::const_max_u8, prec_constraints::{PrecLimitCheck, True}, Decimal, MAX_PREC, }; impl<const P: u8> Zero for Decimal<P> where PrecLimitCheck<{ ...
); impl_add_sub_decimal!(impl Sub, sub); #[cfg(test)] mod add_sub_decimal_tests { use super::*; #[test] fn test_add_same_prec() { let x = Decimal::<3>::new_raw(1234567890); let y = x + x; assert_eq!(y.coeff, 2 * x.coeff); let z = x + Decimal::<3>::NEG_ONE; assert_e...
= Decimal<P>>, { #[inline(always)] fn zero() -> Self { Self::ZERO } #[inline(always)] fn is_zero(&self) -> bool { self.coeff.is_zero() } } #[cfg(test)] mod zero_tests { use super::*; #[test] fn test_zero() { assert!(Decimal::<0>::is_zero(&Decimal::<0>::zer...
random
[ { "content": "#[doc(hidden)]\n\n#[inline]\n\npub fn adjust_prec(x: i128, p: u8, y: i128, q: u8) -> (i128, i128) {\n\n match p.cmp(&q) {\n\n Ordering::Equal => (x, y),\n\n Ordering::Greater => (x, mul_pow_ten(y, p - q)),\n\n Ordering::Less => (mul_pow_ten(x, q - p), y),\n\n }\n\n}\n\n\...
Rust
crates/parse/src/pat.rs
kopecs/millet
515a482e3fa5fd3aa4c1ed1b92fac433fe7b1e24
use crate::parser::{Entered, ErrorKind, Exited, Expected, OpInfo, Parser}; use crate::ty::ty_annotation; use crate::util::{ comma_sep, eat_name_star, lab, must, name_star, path, path_no_infix, scon, should_break, ShouldBreak, }; use syntax::SyntaxKind as SK; #[must_use] pub(crate) fn pat(p: &mut Parser<'_>) -> Opt...
use crate::parser::{Entered, ErrorKind, Exited, Expected, OpInfo, Parser}; use crate::ty::ty_annotation; use crate::util::{ comma_sep, eat_name_star, lab, must, name_star, path, path_no_infix, scon, should_break, ShouldBreak, }; use syntax::SyntaxKind as SK; #[must_use] pub(crate) fn pat(p: &mut Parser<'_>) -> Opt...
}); p.exit(en, SK::RecordPat) } else if p.at(SK::LRound) { p.bump(); let kind = at_pat_l_round(p); p.exit(en, kind) } else if p.at(SK::LSquare) { p.bump(); comma_sep(p, SK::RSquare, SK::PatArg, |p| must(p, pat, Expected::Pat)); p.exit(en, SK::ListPat) } else if p.at(SK::Hash) { ...
if p.at_n(1, SK::Eq) { lab(p); p.eat(SK::Eq); must(p, pat, Expected::Pat); p.exit(en, SK::LabAndPatPatRow); } else { eat_name_star(p); let _ = ty_annotation(p); let _ = as_pat_tl(p); p.exit(en, SK::LabPatRow); }
if_condition
[ { "content": "#[must_use]\n\nfn tok_ty(p: &mut Parser<'_>, tok: SK, wrap: SK) -> Option<Exited> {\n\n if p.at(tok) {\n\n let en = p.enter();\n\n p.bump();\n\n ty(p);\n\n Some(p.exit(en, wrap))\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "crates/parse/src/ty.rs", "rank": 0, "s...