lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/bin/main.rs
DanielJoyce/websocket-serial-server
27eee51e364d8852ad4f995272a30241d2ac6ab9
#[macro_use] extern crate log; use std::io::Write; use std::net::TcpStream; use std::sync::mpsc::{channel, Sender}; use std::thread; use hyper::net::Fresh; use hyper::server::request::Request; use hyper::server::response::Response; use hyper::Server as HttpServer; use rand::{thread_rng, Rng}; use websocket::client:...
#[macro_use] extern crate log; use std::io::Write; use std::net::TcpStream; use std::sync::mpsc::{channel, Sender};
pStream>, ) { thread::spawn(move || ws_handler(sub_id, &sub_tx_clone, &sreq_tx_clone, connection)); } fn ws_handler( sub_id: String, sub_tx: &Sender<SubscriptionRequest>, sreq_tx: &Sender<(String, SerialRequest)>, connection: WsUpgrade<TcpStream>, ) { if !connection .protocols() .contains(&"websock...
use std::thread; use hyper::net::Fresh; use hyper::server::request::Request; use hyper::server::response::Response; use hyper::Server as HttpServer; use rand::{thread_rng, Rng}; use websocket::client::Writer; use websocket::message::Type; use websocket::result::WebSocketError; use websocket::server::upgrade::WsUpgrade...
random
[ { "content": "//! The serial support library contains all\n\n//! the functionality to read ports, and send data\n\n//! between threads reading serial port data\n\n//! and threads handling websocket requests\n\n\n\n#![recursion_limit = \"1024\"]\n\n#![allow(dead_code)]\n\n#![allow(unused_variables)]\n\nextern cr...
Rust
src/shader/service.rs
vojd/skuggbox
724ddb025623345f634634f4ea70cb022fc20e2b
use log::{error, info}; use std::path::PathBuf; use crate::shader::VERTEX_SHADER; use crate::shader::{find_included_files, PreProcessor, Shader, ShaderError}; use crate::uniforms::{read_uniforms, Uniform}; use crate::utils::cstr_with_len; pub fn create_program(fragment_src: String) -> Result<ShaderProgram, ShaderErro...
use log::{error, info}; use std::path::PathBuf; use crate::shader::VERTEX_SHADER; use crate::shader::{find_included_files, PreProcessor, Shader, ShaderError}; use crate::uniforms::{read_uniforms, Uniform}; use crate::utils::cstr_with_len; pub fn create_program(fragment_src: String) -> Result<ShaderProgram, ShaderErro...
= self.use_camera_integration; self.pre_processor.reload(); match create_program(self.pre_processor.shader_src.clone()) { Ok(new_program) => { self.program = Some(new_program); self.uniforms = read_uniforms(self.fs.clone()); info!("Shader rec...
_shader.id); gl::DetachShader(id, frag_shader.id); } Self { id } } } impl Drop for ShaderProgram { fn drop(&mut self) { unsafe { gl::DeleteProgram(self.id); } } } pub struct ShaderService { pre_processor: Box<PreProcessor>, fs: PathBuf, ...
random
[ { "content": "pub fn cstr_with_len(len: usize) -> CString {\n\n let mut buffer: Vec<u8> = Vec::with_capacity(len + 1);\n\n buffer.extend([b' '].iter().cycle().take(len));\n\n unsafe { CString::from_vec_unchecked(buffer) }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 1, "score": 136967....
Rust
libsplinter/src/peer/notification.rs
rbuysse/splinter
1864eb39be8c44f910dc0ce79693fea7f136fd5a
use std::collections::{HashMap, VecDeque}; use std::sync::mpsc::{Receiver, TryRecvError}; use super::error::PeerManagerError; use super::PeerTokenPair; #[derive(Debug, PartialEq, Clone)] pub enum PeerManagerNotification { Connected { peer: PeerTokenPair }, Disconnected { peer: PeerTokenPair }...
use std::collections::{HashMap, VecDeque}; use std::sync::mpsc::{Receiver, TryRecvError}; use super::error::PeerManagerError; use super::PeerTokenPair; #[derive(Debug, PartialEq, Clone)] pub enum PeerManagerNotification { Connected { peer: PeerTokenPair }, Disconnected { peer: PeerTokenPair }...
#[test] fn test_broadcast_queue_limit() { let mut subscriber_map = SubscriberMap::new_with_queue_limit(1); for i in 0..3 { subscriber_map.broadcast(PeerManagerNotification::Connected { peer: PeerTokenPair::new(...
assert_eq!( sub1.try_recv().expect("Unable to receive value"), PeerManagerNotification::Connected { peer: PeerTokenPair::new( PeerAuthorizationToken::Trust { peer_id: "test_peer_2".into() }, PeerA...
function_block-function_prefix_line
[ { "content": "#[cfg(not(any(feature = \"trust-authorization\", feature = \"challenge-authorization\")))]\n\nfn connect_msg_bytes() -> Result<Vec<u8>, AuthorizationManagerError> {\n\n let connect_msg = AuthorizationMessage::ConnectRequest(ConnectRequest::Bidirectional);\n\n\n\n IntoBytes::<network::Network...
Rust
crates/platform/src/input/mouse.rs
gents83/NRG
62743a54ac873a8dea359f3816e24c189a323ebb
use std::collections::HashMap; use sabi_commands::CommandParser; use sabi_messenger::{implement_message, Message, MessageFromString}; #[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone, Copy)] pub enum MouseButton { None, Left, Right, Middle, Other(u16), } #[derive(Debug, Hash, Ord, Parti...
use std::collections::HashMap; use sabi_commands::CommandParser; use sabi_messenger::{implement_message, Message, MessageFromString}; #[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone, Copy)] pub enum MouseButton { None, Left, Right, Middle, Other(u16), } #
ues_of("mouse_move"); return Some( MouseEvent { x: values[0], y: values[1], normalized_x: values[0] as _, normalized_y: values[1] as _, button: MouseButton::None, state: Mo...
[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone, Copy)] pub enum MouseState { Invalid, Move, DoubleClick, Down, Up, } #[derive(Debug, PartialOrd, PartialEq, Clone, Copy)] pub struct MouseEvent { pub x: f64, pub y: f64, pub normalized_x: f32, pub normalized_y: f32, pub...
random
[]
Rust
tools/ldr2img/src/main.rs
segfault87/ldraw.rs
f181317cf1505ca64456cf67efdf3ac406d05831
use std::{ collections::HashMap, env, fs::File, io::BufReader, path::Path, rc::Rc, }; use bincode::deserialize_from; use clap::{App, Arg}; use glutin::event_loop::EventLoop; use ldraw::{ parser::{parse_color_definition, parse_multipart_document}, }; use ldraw_ir::{ part::PartBuilder, };...
use std::{ collections::HashMap, env, fs::File, io::BufReader, path::Path, rc::Rc, }; use bincode::deserialize_from; use clap::{App, Arg}; use glutin::event_loop::EventLoop; use ldraw::{ parser::{parse_color_definition, parse_multipart_document}, }; use ldraw_ir::{ part::PartBuilder, };...
fn main() { let matches = App::new("ldr2img") .about("Render LDraw model into still image") .arg(Arg::with_name("ldraw_dir") .long("ldraw-dir") .value_name("PATH") .takes_value(true) .help("Path to LDraw directory")) .arg(Arg::with_name("pa...
function_block-full_function
[ { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{parse_color_definition, parse_multipart_document, parse_single_document};\n\n use crate::color::MaterialRegistry;\n\n use crate::error::{ColorDefinitionParseError, ParseError};\n\n use std::fs::File;\n\n use std::io::BufReader;\n\...
Rust
src/components/message.rs
jtakalai/sanuli
e21e1f887f88ab7c9716b8cba98b1fe59727cf24
use yew::prelude::*; use crate::manager::GameMode; use crate::Msg as GameMsg; const FORMS_LINK_TEMPLATE_ADD: &str = "https://docs.google.com/forms/d/e/1FAIpQLSfH8gs4sq-Ynn8iGOvlc99J_zOG2rJEC4m8V0kCgF_en3RHFQ/viewform?usp=pp_url&entry.461337706=Lis%C3%A4yst%C3%A4&entry.560255602="; const FORMS_LINK_TEMPLATE_DEL: &str ...
use yew::prelude::*; use crate::manager::GameMode; use crate::Msg as GameMsg; const FORMS_LINK_TEMPLATE_ADD: &str = "https://docs.google.com/forms/d/e/1FAIpQLSfH8gs4sq-Ynn8iGOvlc99J_zOG2rJEC4m8V0kCgF_en3RHFQ/viewform?usp=pp_url&entry.461337706=Lis%C3%A4yst%C3%A4&entry.560255602="; const FORMS_LINK_TEMPLATE_DEL: &str ...
|e: MouseEvent| { e.prevent_default(); callback.emit(GameMsg::ShareEmojis); }); let callback = props.callback.clone(); let share_link = Callback::from(move |e: MouseEvent| { e.prevent_default(); callback.emit(GameMsg::ShareLink); }); if props.game_mode == GameMode::Q...
meMsg>, } #[function_component(Message)] pub fn message(props: &MessageProps) -> Html { html! { <div class="message"> { &props.message } <div class="message-small">{ if props.is_hidden { let callback = props.callback.clone(); l...
random
[ { "content": "pub trait Game {\n\n fn title(&self) -> String;\n\n fn next_word(&mut self);\n\n fn keyboard_tilestate(&self, key: &char) -> KeyState;\n\n fn submit_guess(&mut self);\n\n fn push_character(&mut self, character: char);\n\n fn pop_character(&mut self);\n\n fn share_emojis(&self,...
Rust
src/corroboy/gpu/background.rs
squidboylan/corroboy
4c264c2604eb0cc6830add3c9e98dee0cb054c40
use gfx_device_gl; use image::*; use piston_window; use piston_window::PistonWindow as Window; use piston_window::Texture; use piston_window::TextureSettings; use sdl2_window::Sdl2Window; use crate::corroboy::mmu::Mmu; struct Tile { raw_val: [[u8; 8]; 8], } impl Tile { pub fn new() -> Tile { ...
use gfx_device_gl; use image::*; use piston_window; use piston_window::PistonWindow as Window; use piston_window::Texture; use piston_window::TextureSettings; use sdl2_window::Sdl2Window; use crate::corroboy::mmu::Mmu; struct Tile { raw_val: [[u8; 8]; 8], } impl Tile { pub fn new() -> Tile { ...
pub fn build_tile_data(&mut self, mem: &mut Mmu) { if self.background_data_bot == 0x8000 { for i in 0..256 { for j in 0..8 { let left = mem.get_vram(self.background_data_bot + (i * 16) + (j * 2)); let right = mem.get_vram(self.backgr...
self.bg_palette[2] = ((ff47 & 0b00110000) >> 4) as usize; self.bg_palette[3] = ((ff47 & 0b11000000) >> 6) as usize; }
function_block-function_prefix_line
[ { "content": "pub fn ret_z(mem: &mut Mmu, flags: u8, pc: &mut u16, sp: &mut u16) -> bool {\n\n if flags & 0b10000000 != 0 {\n\n *pc = mem.pop_u16(sp);\n\n return true;\n\n }\n\n return false;\n\n}\n\n\n", "file_path": "src/corroboy/cpu/ops/ret.rs", "rank": 0, "score": 298418.8...
Rust
crates/holochain/tests/gossip_test.rs
zdb999/holochain
45dd3f827caea18f41f77486ca2c37149a18b4ca
use ::fixt::prelude::*; use hdk3::prelude::*; use holochain::conductor::{ api::{AppInterfaceApi, AppRequest, AppResponse, RealAppInterfaceApi}, dna_store::MockDnaStore, }; use holochain::core::ribosome::ZomeCallInvocation; use holochain::{ fixt::*, test_utils::{install_app, setup_app}, }; use holochain_...
use ::fixt::prelude::*; use hdk3::prelude::*; use holochain::conductor::{ api::{AppInterfaceApi, AppRequest, AppResponse, RealAppInterfaceApi}, dna_store::MockDnaStore, }; use holochain::core::ribosome::ZomeCallInvocation; use holochain::{ fixt::*, test_utils::{install_app, setup_app}, }; use holochain_...
Bytes, Error = SerializedBytesError>, { Ok(ZomeCallInvocation { cell_id: cell_id.clone(), zome_name: TestWasm::Anchor.into(), cap: Some(CapSecretFixturator::new(Unpredictable).next().unwrap()), fn_name: func.into(), payload: ExternInput::new(payload.try_into()?), prov...
function_block-function_prefixed
[ { "content": "/// Helper to create a zome invocation for tests\n\npub fn new_invocation<P, Z: Into<ZomeName>>(\n\n cell_id: &CellId,\n\n func: &str,\n\n payload: P,\n\n zome_name: Z,\n\n) -> Result<ZomeCallInvocation, SerializedBytesError>\n\nwhere\n\n P: TryInto<SerializedBytes, Error = Serializ...
Rust
query/src/servers/mysql/mysql_interactive_worker.rs
CNLHC/databend
fad0df2843c148c9c74793dadd38a9e5db274a36
use std::marker::PhantomData; use std::time::Instant; use common_datablocks::DataBlock; use common_exception::ErrorCode; use common_exception::Result; use common_runtime::tokio; use metrics::histogram; use msql_srv::ErrorKind; use msql_srv::InitWriter; use msql_srv::MysqlShim; use msql_srv::ParamParser; use msql_srv...
use std::marker::PhantomData; use std::time::Instant; use common_datablocks::DataBlock; use common_exception::ErrorCode; use common_exception::Result; use common_runtime::tokio; use metrics::histogram; use msql_srv::ErrorKind; use msql_srv::InitWriter; use msql_srv::MysqlShim; use msql_srv::ParamParser; use msql_srv...
; } self.base .do_execute(id, param, writer, self.session.create_context()) } fn on_close(&mut self, id: u32) { self.base.do_close(id, self.session.create_context()); } fn on_query(&mut self, query: &str, writer: QueryResultWriter<W>) -> Result<()> { if sel...
Err(ErrorCode::AbortedSession( "Aborting this connection. because we are try aborting server.", ))
call_expression
[ { "content": "fn query<T: FromRow>(connection: &mut Conn, query: &str) -> Result<Vec<T>> {\n\n connection\n\n .query::<T, &str>(query)\n\n .map_err_to_code(ErrorCode::UnknownException, || \"Query error\")\n\n}\n\n\n", "file_path": "query/src/servers/mysql/mysql_handler_test.rs", "rank":...
Rust
beacon_node/network/src/sync/range_sync/chain_collection.rs
protolambda/lighthouse
3acb3cc640c7a1fe4aab94ce35be1c300a4146d8
use super::chain::{ChainSyncingState, ProcessingResult, SyncingChain}; use crate::message_processor::PeerSyncInfo; use crate::sync::network_context::SyncNetworkContext; use beacon_chain::{BeaconChain, BeaconChainTypes}; use eth2_libp2p::PeerId; use slog::{debug, warn}; use std::sync::Weak; use types::EthSpec; use types...
use super::chain::{ChainSyncingState, ProcessingResult, SyncingChain}; use crate::message_processor::PeerSyncInfo; use crate::sync::network_context::SyncNetworkContext; use beacon_chain::{BeaconChain, BeaconChainTypes}; use eth2_libp2p::PeerId; use slog::{debug, warn}; use std::sync::Weak; use types::EthSpec; use types...
pub fn update_finalized( &mut self, beacon_chain: Weak<BeaconChain<T>>, network: &mut SyncNetworkContext, log: &slog::Logger, ) { let local_info = match beacon_chain.upgrade() { Some(chain) => PeerSyncInfo::from(&chain), None => { ...
pub fn get_head_mut( &mut self, target_head_root: Hash256, target_head_slot: Slot, ) -> Option<&mut SyncingChain<T>> { ChainCollection::get_chain( self.head_chains.as_mut(), target_head_root, target_head_slot, ) }
function_block-full_function
[ { "content": "/// Ensures that the finalized root can be set to all values in `roots`.\n\nfn test_update_finalized_root(roots: &[(Hash256, Slot)]) {\n\n let harness = &FORKED_HARNESS;\n\n\n\n let lmd = harness.new_fork_choice();\n\n\n\n for (root, _slot) in roots.iter().rev() {\n\n let block = h...
Rust
truck-meshalgo/src/analyzers/collision.rs
leomcelroy/truck
081a6938f479b37f3516c3b380ce69e403f64d42
use super::*; pub trait Collision { fn collide_with(&self, other: &PolygonMesh) -> Option<(Point3, Point3)>; fn extract_interference(&self, other: &PolygonMesh) -> Vec<(Point3, Point3)>; } impl Collision for PolygonMesh { #[inline(always)] fn collide_with(&self, other: &Polygo...
use super::*; pub trait Collision { fn collide_with(&self, other: &PolygonMesh) -> Option<(Point3, Point3)>; fn extract_interference(&self, other: &PolygonMesh) -> Vec<(Point3, Point3)>; } impl Collision for PolygonMesh { #[inline(always)] fn collide_with(&self, other: &Polygo...
each(|pt| match tuple { (None, _) => tuple.0 = *pt, (Some(_), None) => tuple.1 = *pt, (Some(ref mut p), Some(ref mut q)) => { if let Some(pt) = pt { let dist0 = pt.distance2(*p); let dist1 = pt.distance2(*q); let dist2 = p.distance2(*q)...
collide_seg_triangle([tri1[0], tri1[1]], tri0), collide_seg_triangle([tri1[1], tri1[2]], tri0), collide_seg_triangle([tri1[2], tri1[0]], tri0), ] .iter() .for_
function_block-random_span
[ { "content": "fn tri_to_seg(tri: [Point3; 3], unit: Vector3, tol: f64) -> (f64, f64) {\n\n let a = tri[0].to_vec().dot(unit);\n\n let b = tri[1].to_vec().dot(unit);\n\n let c = tri[2].to_vec().dot(unit);\n\n (\n\n f64::min(f64::min(a, b), c) - tol,\n\n f64::max(f64::max(a, b), c) + tol...
Rust
testspace/src/history.rs
galacticfungus/Egg
a8d80d046f28ae9688432c69890dd44bf6516315
use std::fs; use std::path; use std::vec; #[derive(Clone, Debug)] pub enum FileItem { Directory(path::PathBuf), File(path::PathBuf), } #[derive(Debug, Clone)] pub struct FileHistory { history: vec::Vec<FileItem>, allow_cleanup: bool, } impl Default for FileHistory { fn default() -> FileHistory { ...
use std::fs; use std::path; use std::vec; #[derive(Clone, Debug)] pub enum FileItem { Directory(path::PathBuf), File(path::PathBuf), } #[derive(Debug, Clone)] pub struct FileHistory { history: vec::Vec<FileItem>, allow_cleanup: bool, } impl Default for FileHistory { fn default() -> FileHistory { ...
} #[cfg(test)] mod tests { use super::FileHistory; use std::fs; #[test] fn test_history() { let mut history = FileHistory::default(); let mut temp_dir = std::env::temp_dir(); temp_dir.push("remove_me"); let temp_path = temp_dir.as_path(); fs::create_dir(temp_pa...
pub fn cleanup(&mut self) { while let Some(file_item) = self.history.pop() { match file_item { FileItem::Directory(path) => { fs::remove_dir_all(&path).unwrap_or_else(|err| { eprintln!( "Failed t...
function_block-full_function
[ { "content": "/// Represents a file in the working directory that we may wish to snapshot or otherwise investigate,\n\n/// This structure does not contain the path of the file since the path is used as a key inside a map of WorkingFiles\n\nstruct WorkingFile {\n\n hash: Option<Hash>,\n\n file_size: u64,\n...
Rust
src/main.rs
RyanBluth/mangy2
2a64daf7c911f5af52ace6e185f6cb47deed8b3d
extern crate clap; extern crate term_table; use clap::{App, AppSettings, Arg, SubCommand}; use std::process; use std::fmt::Display; use std::fs::{metadata, File, OpenOptions}; use std::io::prelude::*; use std::process::{Command, Stdio}; use std::collections::HashMap; use term_table::row::Row; use term_table::Table; u...
extern crate clap; extern crate term_table; use clap::{App, AppSettings, Arg, SubCommand}; use std::process; use std::fmt::Display; use std::fs::{metadata, File, OpenOptions}; use std::io::prelude::*; use std::process::{Command, Stdio}; use std::collections::HashMap; use term_table::row::Row; use term_table::Table; u...
etadata { Ok(metadata) => { if metadata.is_dir() { go(key); } else { run(key, matches.values_of_lossy(RUN_ARGS)); } } Err(_) => run(key, matches.values_of_lossy(RUN...
hes(RUN) { match sub_matches.value_of(KEY) { Some(key) => run(key, sub_matches.values_of_lossy(RUN_ARGS)), None => exit_with_message("go requires a variable key"), } } else if let Some(sub_matches) = matches.subcommand_matches(DELETE) { match sub_matches.value_of(KEY)...
function_block-random_span
[ { "content": "# managed-alias\n\n\n\nmanaged-alias is an alternative to the alias command. managed-alias allows you to maintain a list of aliases that you can modify on the fly and is persitent across terminal sessions.\n\n\n\n\n\n| Command | Result ...
Rust
src/bin/taxonate/app.rs
elasticdog/taxonate
6d7a5591778e6d53744ffde3d40ba91972d0840f
use std::{ collections::HashSet, env, io::{self, BufRead}, path::{Path, PathBuf}, }; use clap::{crate_authors, crate_name, crate_version, App, AppSettings, Arg, ArgMatches}; use taxonate::config::{Color, Config, LogLevel}; pub fn build() -> App<'static, 'static> { let color = env::var("TAXONATE...
use std::{ collections::HashSet, env, io::{self, BufRead}, path::{Path, PathBuf}, }; use clap::{crate_authors, crate_name, crate_version, App, AppSettings, Arg, ArgMatches}; use taxonate::config::{Color, Config, LogLevel}; pub fn build() -> App<'static, 'static> { let color = env::var("TAXONATE...
ove(Path::new("-")) { let stdin = io::stdin(); for line in stdin.lock().lines() { paths.insert(PathBuf::from(line.unwrap())); } } if paths.is_empty() { paths.insert(PathBuf::from(".")); } Config::new() .set_color(color) .set_filename...
ever, _ => unreachable!(), }; let filename_only = matches.is_present("filename_only"); let log_level = match matches.value_of("debug").unwrap() { "error" => LogLevel::Error, "warning" => LogLevel::Warning, "info" => LogLevel::Info, "debug" => LogLevel::Debug, ...
function_block-random_span
[ { "content": "#[must_use]\n\npub fn identify(file: &Path) -> Option<&Language> {\n\n find_lang_by_interpreter(&file).or_else(|| find_lang_by_glob(&file))\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 96360.11204077046 }, { "content": "/// # Errors\n\n///\n\n/// Will return `...
Rust
core/src/reflection/microfacet_reflection.rs
hackmad/pbr-rust
d181621fcde300e88e1063b481fa240a49157627
#![allow(dead_code)] use super::*; use crate::microfacet::*; use bumpalo::Bump; use std::fmt; pub struct MicrofacetReflection<'arena> { bxdf_type: BxDFType, fresnel: &'arena mut Fresnel<'arena>, r: Spectrum, distribution: &'arena mut MicrofacetDistribution<'arena>, } impl...
#![allow(dead_code)] use super::*; use crate::microfacet::*; use bumpalo::Bump; use std::fmt; pub struct MicrofacetReflection<'arena> { bxdf_type: BxDFType, fresnel: &'arena mut Fresnel<'arena>, r: Spectrum, distribution: &'arena mut MicrofacetDistribution<'arena>, } impl...
pub fn pdf(&self, wo: &Vector3f, wi: &Vector3f) -> Float { if same_hemisphere(wo, wi) { let wh = (wo + wi).normalize(); self.distribution.pdf(wo, &wh) / (4.0 * wo.dot(&wh)) } else { 0.0 } } } impl<'arena> fmt::Display for MicrofacetReflect...
let pdf = self.distribution.pdf(wo, &wh) / (4.0 * wo.dot(&wh)); BxDFSample::new(self.f(wo, &wi), pdf, wi, self.bxdf_type) } } } }
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn reflect(wo: &Vector3f, n: &Vector3f) -> Vector3f {\n\n -wo + 2.0 * wo.dot(n) * n\n\n}\n", "file_path": "core/src/reflection/common.rs", "rank": 0, "score": 258319.93077896046 }, { "content": "/// Uniformly sample a direction from a sphere.\n\n///\n\n/// *...
Rust
src/lib.rs
rkanati/podchamp
84488b1e92532052f1c1176150a8afa95779de65
#[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; use { chrono::{DateTime, Utc, NaiveDateTime}, thiserror::Error, url::Url, }; embed_migrations!(); pub mod models; pub mod schema; pub fn run_migrations(db: &diesel::sqlite::SqliteConnection) -> anyhow::Result<()> { embe...
#[macro_use] extern crate diesel; #[macro_use] extern crate diesel_migrations; use { chrono::{DateTime, Utc, NaiveDateTime}, thiserror::Error, url::Url, }; embed_migrations!(); pub mod models; pub mod schema; pub fn run_migrations(db: &diesel::sqlite::SqliteConnection) -> anyhow::Result<()> { embe...
0) } } #[derive(Debug, Error)] pub enum RegisterEpisodeError { #[error(transparent)] Database(#[from] diesel::result::Error), } impl Database { pub fn register_episode(&mut self, feed: &str, guid: &str) -> Result<(), RegisterEpisodeError> { let registration = models::NewRegistrati...
= diesel::update(dsl::feeds.filter(dsl::name.eq(feed))) .set(dsl::backlog.eq(backlog.get() as i32)) .execute(&self.conn)?; if n == 0 { return Err(SetColumnError::NoSuchFeed(feed.into())); } Ok(()) } pub fn set_fetch_since(&mut self, feed: &str, since...
random
[ { "content": "fn collect_recent_episodes<'c> (channel: &'c feed_rs::model::Feed, now: &DateTime<Utc>)\n\n -> Vec<(&'c feed_rs::model::Entry, &'c Url, DateTime<Utc>)>\n\n{\n\n let mut recents: Vec<_> = channel.entries.iter()\n\n // ignore items with no date, or no actual episode to download\n\n ...
Rust
src/from.rs
Eijebong/derive_more
591918e68bb695cb90842ae3a1d70551ade64be2
use std::collections::HashMap; use std::ops::Index; use quote::{ToTokens, Tokens}; use syn::{Data, DataEnum, DeriveInput, Field, Fields}; use utils::{field_idents, get_field_types, named_to_vec, number_idents, unnamed_to_vec}; pub fn expand(input: &DeriveInput, trait_name: &str) -> Tokens { match input.data { ...
use std::collections::HashMap; use std::ops::Index; use quote::{ToTokens, Tokens}; use syn::{Data, DataEnum, DeriveInput, Field, Fields}; use utils::{field_idents, get_field_types, named_to_vec, number_idents, unnamed_to_vec}; pub fn expand(input: &DeriveInput, trait_name: &str) -> Tokens { match input.data { ...
*counter += 1; } Fields::Named(ref fields) => { let original_types = named_to_vec(fields).iter().map(|f| &f.ty).collect(); let counter = type_signature_counts.entry(original_types).or_insert(0); *counter += 1; } Fields::Unit...
fields[0].ident; quote!(#return_type{#field_name: original}) } else { let argument_field_names = &number_idents(fields.len()); let field_names = &field_idents(fields); quote!(#return_type{#(#field_names: original.#argument_field_names),*}) } } fn enum_from(input: &DeriveInput, d...
random
[ { "content": "/// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into`\n\npub fn expand(input: &DeriveInput, _: &str) -> Tokens {\n\n let input_type = &input.ident;\n\n let field_vec: Vec<_>;\n\n let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();...
Rust
src/parser.rs
ikanago/qz
3e59c25af2107d72e1cbe776c15c0aadd42525fc
use crate::{ header::{HeaderName, HeaderValue}, method::Method, status::StatusCode, Uri, Version, }; use std::convert::TryFrom; use std::str; #[derive(Debug)] pub struct Parser<'a> { state: &'a [u8], } impl<'a> Parser<'a> { pub fn new(input: &'a [u8]) -> Self { Self { state: input...
use crate::{ header::{HeaderName, HeaderValue}, method::Method, status::StatusCode, Uri, Version, }; use std::convert::TryFrom; use std::str; #[derive(Debug)] pub struct Parser<'a> { state: &'a [u8], } impl<'a> Parser<'a> { pub fn new(input: &'a [u8]) -> Self { Self { state: input...
pub fn parse_request_line(&mut self) -> crate::Result<(Method, Uri, Version)> { let method = self.parse_method()?; let uri = self.parse_uri()?; let version = self.parse_version()?; self.expect(b'\n', StatusCode::BadRequest)?; Ok((method, uri, version)) } fn parse_m...
pub fn expect(&mut self, target: u8, error: StatusCode) -> crate::Result<()> { match self.consume() { Some(b) if b == target => Ok(()), _ => Err(error), } }
function_block-full_function
[ { "content": "pub fn filename_to_mime<P: AsRef<Path>>(filename: P) -> &'static [u8] {\n\n match filename.as_ref().extension().and_then(OsStr::to_str) {\n\n Some(\"txt\") => TEXT_PLAIN,\n\n Some(\"html\") => TEXT_HTML,\n\n Some(\"css\") => TEXT_CSS,\n\n Some(\"js\") => TEXT_JAVASCR...
Rust
crates/codec/src/codec/limit.rs
YZITE/futures
9d4300dfaa22d0bc7cb51bf41edd305aa95b2839
#![allow(missing_docs)] use super::{Decoder, Encoder, EncoderError}; use bytes::{Buf, BytesMut}; pub trait SkipAheadHandler: Sized + std::fmt::Debug { fn continue_skipping(self, src: &[u8]) -> Result<(usize, Option<Self>), ()>; } impl SkipAhea...
#![allow(missing_docs)] use super::{Decoder, Encoder, EncoderError}; use bytes::{Buf, BytesMut}; pub trait SkipAheadHandler: Sized + std::fmt::Debug { fn continue_skipping(self, src: &[u8]) -> Result<(usize, Option<Self>), ()>; } impl SkipAhea...
} } /* #[cfg(test)] mod tests { use super::*; mod decode { use super::*; #[test] fn x() { } } } */
match self.inner.decode(src) { Ok(None) if src.len() > self.max_frame_size => { self.skip_ahead_state = Some(self.inner.prepare_skip_ahead(src)); Err(LimitError::LimitExceeded(src.len())) } Ok(x) => Ok(x), Err(x) => Err(Lim...
if_condition
[ { "content": "/// Encoding of messages as bytes, for use with [`Framed`](crate::Framed).\n\n///\n\n/// `Item` is the type of items consumed by `encode`\n\npub trait Encoder<Item: ?Sized>: EncoderError {\n\n /// Encodes an item into the `BytesMut` provided by dst.\n\n fn encode(&mut self, item: &Item, dst:...
Rust
src/diagnostics/archivist/tests/v2/src/logs/budget.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
use crate::{constants::*, test_topology, utils}; use anyhow::Error; use archivist_lib::configs::parse_config; use component_events::{events::*, matcher::ExitStatusMatcher}; use diagnostics_data::{Data, LogError, Logs, Severity}; use diagnostics_hierarchy::trie::TrieIterableNode; use diagnostics_message::message::{fx_...
use crate::{constants::*, test_topology, utils}; use anyhow::Error; use archivist_lib::configs::parse_config; use component_events::{events::*, matcher::ExitStatusMatcher}; use diagnostics_data::{Data, LogError, Logs, Severity}; use diagnostics_hierarchy::trie::TrieIterableNode; use diagnostics_message::message::{fx_...
struct PuppetEnv { max_puppets: usize, instance: RealmInstance, controllers: Receiver<SocketPuppetControllerRequestStream>, messages_allowed_in_cache: usize, messages_sent: Vec<MessageReceipt>, launched_monikers: Vec<String>, running_puppets: Vec<Puppet>, inspect_reader: ArchiveReader,...
async fn test_budget() { fuchsia_syslog::init().unwrap(); fuchsia_syslog::set_severity(fuchsia_syslog::levels::DEBUG); info!("testing that the archivist's log buffers correctly enforce their budget"); info!("creating nested environment for collecting diagnostics"); let mut env = PuppetEnv::create(...
function_block-full_function
[]
Rust
cortex-m-rtfm/macros/src/codegen/util.rs
ButtNaked/m4mon8
017dc3e1caed191804e795c0709580f1a58ad73e
use core::sync::atomic::{AtomicUsize, Ordering}; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use rtfm_syntax::{ast::App, Context, Core}; use syn::{Attribute, Ident, LitInt, PatType}; use crate::check::Extra; pub fn capacity_literal(capacity: u8) -> LitInt { LitInt::new(&capacity.to_st...
use core::sync::atomic::{AtomicUsize, Ordering}; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use rtfm_syntax::{ast::App, Context, Core}; use syn::{Attribute, Ident, LitInt, PatType}; use crate::check::Extra; pub fn capacity_literal(capacity: u8) -> LitInt { LitInt::new(&capacity.to_st...
pub fn link_section_uninit(core: Option<Core>) -> Option<TokenStream2> { let section = if let Some(core) = core { let index = link_section_index(); if cfg!(feature = "homogeneous") { format!(".uninit_{}.rtfm{}", core, index) } else { format!(".uninit.rtfm{}", index...
pub fn link_section(section: &str, core: Core) -> Option<TokenStream2> { if cfg!(feature = "homogeneous") { let section = format!(".{}_{}.rtfm{}", section, core, link_section_index()); Some(quote!(#[link_section = #section])) } else { None } }
function_block-full_function
[ { "content": "pub fn xpend(_core: u8, _interrupt: impl Nr) {}\n\n\n\n/// Fake monotonic timer\n\npub struct MT;\n\n\n\nimpl Monotonic for MT {\n\n type Instant = Instant;\n\n\n\n fn ratio() -> Fraction {\n\n Fraction {\n\n numerator: 1,\n\n denominator: 1,\n\n }\n\n ...
Rust
src/cache/cache.rs
ELCHILEN0/memcached
f0291bdddd050b2cb46014e1364a435f48ed7c50
use cache::key::Key; use cache::value::Value; use cache::data_entry::DataEntry; use cache::storage_structure::CacheStorageStructure; use cache::replacement_policy::CacheReplacementPolicy; use cache::error::CacheError; pub struct CacheMetrics { pub evictions: u64, pub hit_count_get: u64, pub hit_count_set: ...
use cache::key::Key; use cache::value::Value; use cache::data_entry::DataEntry; use cache::storage_structure::CacheStorageStructure; use cache::replacement_policy::CacheReplacementPolicy; use cache::error::CacheError; pub struct CacheMetrics { pub evictions: u64, pub hit_count_get: u64, pub hit_count_set: ...
pub fn set(&mut self, key: Key, value: Value) -> Result<(), CacheError> { let entry = DataEntry::new(key.clone(), value); let current_elem_size = match self.storage_structure.get(key) { Some((_, curr_entry)) => curr_entry.len(), None => 0, }; if c...
pub fn get(&mut self, key: Key) -> Option<DataEntry> { match self.storage_structure.get(key) { Some((index, entry)) => { self.replacement_policy.update(index); self.metrics.hit_count_get += 1; Some(entry) }, None => { ...
function_block-full_function
[ { "content": "// TODO: This will eventually be removed once a client is implemented, for now this exists for the purposes of telnet\n\npub fn parse_command<T: CacheStorageStructure, R: CacheReplacementPolicy>(command: &str, cache: &mut Cache<T, R>) -> Option<MemPacket> {\n\n let mut iter = command.split_whit...
Rust
generator/src/block_data.rs
Redrield/feather
8614692f8e0a24979853e29d41567b5a82249831
use super::WriteExt; use byteorder::{LittleEndian, WriteBytesExt}; use failure::Error; use indexmap::IndexMap; use std::collections::HashMap; use std::fs::File; use std::io::{BufReader, BufWriter, Write}; pub const DEFAULT_STATE_ID: u16 = 1; #[derive(Clone, Debug, Deserialize, Deref, DerefMut)] pub struct BlockRepor...
use super::WriteExt; use byteorder::{LittleEndian, WriteBytesExt}; use failure::Error; use indexmap::IndexMap; use std::collections::HashMap; use std::fs::File; use std::io::{BufReader, BufWriter, Write}; pub const DEFAULT_STATE_ID: u16 = 1; #[derive(Clone, Debug, Deserialize, Deref, DerefMut)] pub struct BlockRepor...
fn find_state_in_report( report: &BlockReport, name: &str, props: &HashMap<String, String>, ) -> Option<u16> { let block = report.blocks.get(name)?; let state = block.states.iter().find(|state| match &state.properties { None => props.is_empty(), Some(state_props) => props == &stat...
info!("Parsing data file"); let report: BlockReport = serde_json::from_reader(BufReader::new(&in_file))?; info!("Parsing successful"); let mut out = BufWriter::new(&out_file); write_header(&mut out, version, proto, true)?; let mut count = 0; let mut buf = vec![]; for (block_na...
function_block-function_prefix_line
[ { "content": "pub fn generate_mappings_file(input: &str, output: &str) -> Result<(), Error> {\n\n info!(\"Parsing data file\");\n\n let report = load_report(input)?;\n\n info!(\"Data file parsed successfully\");\n\n\n\n info!(\"Generating mappings file {}\", output);\n\n\n\n let buf = mappings::g...
Rust
src/input/wacom.rs
vlisivka/libremarkable
5f87bd1ec152fab94a2ed93b41ee4f1219de2a9d
use atomic::Atomic; use evdev::raw::input_event; use input::{InputDeviceState, InputEvent}; use std; use std::sync::atomic::{AtomicU16, Ordering}; use framebuffer::cgmath; use framebuffer::common::{DISPLAYHEIGHT, DISPLAYWIDTH, WACOMHEIGHT, WACOMWIDTH}; const WACOM_HSCALAR: f32 = (DISPLAYWIDTH as f32) / (WACOMWIDTH as...
use atomic::Atomic; use evdev::raw::input_event; use input::{InputDeviceState, InputEvent}; use std; use std::sync::atomic::{AtomicU16, Ordering}; use framebuffer::cgmath; use framebuffer::common::{DISPLAYHEIGHT, DISPLAYWIDTH, WACOMHEIGHT, WACOMWIDTH}; const WACOM_HSCALAR: f32 = (DISPLAYWIDTH as f32) / (WACOMWIDTH as...
} #[repr(u16)] #[derive(PartialEq, Copy, Clone, Debug)] pub enum WacomPen { ToolPen = 320, ToolRubber = 321, Touch = 330, Stylus = 331, Stylus2 = 332, } #[derive(PartialEq, Copy, Clone)] pub enum WacomEventType { InstrumentChange, Hover, Draw, Unknown, } #[derive(Partia...
fn default() -> Self { WacomState { last_x: AtomicU16::new(0), last_y: AtomicU16::new(0), last_xtilt: AtomicU16::new(0), last_ytilt: AtomicU16::new(0), last_dist: AtomicU16::new(0), last_pressure: AtomicU16::new(0), last_tool: A...
function_block-full_function
[ { "content": "struct thrinit {\n\n int sid;\n\n int tid;\n\n int *data;\n\n};\n\n\n\n\n\nextern \"C\" {\n\n #include \"libremarkable/lib.h\"\n\n #include \"libremarkable/bitmap.h\"\n\n #include \"libremarkable/shapes.h\"\n\n}\n\n\n\n#define BITS_PER_LONG (sizeof(long) * 8)\n\n#define NBITS(x) ((((x)...
Rust
crypto/src/verify.rs
AllSafeCybercurity/RClient
88aa5fe784621041b05038ae62139398a34b74bc
pub trait USizeExt { fn constrain_value(&self) -> usize; } pub trait SliceExt { fn constrain_value(&self) -> usize; } impl USizeExt for usize { fn constrain_value(&self) -> usize { *self } } impl<T: AsRef<[u8]>> SliceExt for T { fn constrain_value(&self) -> usize { self.as_ref()...
pub trait USizeExt { fn constrain_value(&self) -> usize; } pub trait SliceExt { fn constrain_value(&self) -> usize; } impl USizeExt for usize { fn constrain_value(&self) -> usize { *self } } impl<T: AsRef<[u8]>> SliceExt for T { fn constrain_value(&self) -> usize { self.as_ref()...
("Buffer is too small") } else { Ok(()) }; error.map_err(|e| $crate::Error::CryptoError(e.into()))?; }}; } #[macro_export] macro_rules! verify_encrypt { ($key:expr => [$key_size:expr], $nonce:expr => [$nonce_size:expr], $plain:expr => [$buf:expr, $plain_limit:expr]) => {{ ...
erify::{SliceExt, USizeExt}; let error = if $buf.constrain_value() != $size { Err("Invalid buffer size") } else { Ok(()) }; error.map_err(|e| $crate::Error::CryptoError(e.into()))?; }}; } #[macro_export] macro_rules! verify_auth { ($key:expr => [$key_si...
random
[ { "content": "/// A Hash interface\n\npub trait Hash {\n\n /// Get the information block that describes the hash\n\n fn info(&self) -> HashInfo;\n\n /// hashes data and returns the hash length. `buf` contains the outgoing hashed data. \n\n fn hash(&self, buf: &mut [u8], data: &[u8]) -> Result<usize...
Rust
src/vm/mod.rs
bpandreotti/monkey-rust
970b808530495d94d1bb82a3787c198bcef3b7c7
#[cfg(test)] mod tests; use crate::builtins::{self, BuiltinFn}; use crate::compiler::code::*; use crate::error::{MonkeyError, MonkeyResult, RuntimeError::*}; use crate::lexer::token::Token; use crate::object::*; use std::collections::HashMap; const STACK_SIZE: usize = 2048; pub const GLOBALS_SIZE: usize = 65536; st...
#[cfg(test)] mod tests; use crate::builtins::{self, BuiltinFn}; use crate::compiler::code::*; use crate::error::{MonkeyError, MonkeyResult, RuntimeError::*}; use crate::lexer::token::Token; use crate::object::*; use std::collections::HashMap; const STACK_SIZE: usize = 2048; pub const GLOBALS_SIZE: usize = 65536; st...
self.stack.resize(self.sp, Object::Nil); Ok(()) } fn execute_builtin_call(&mut self, func: BuiltinFn, num_args: usize) -> MonkeyResult<()> { let args = self.take(num_args); let result = func.0(args).map_err(MonkeyError::Vm)?; self.pu...
pc += 1; let new_frame = Frame { instructions: closure.func.instructions, free_vars: closure.free_vars, pc: 0, base_pointer: self.sp - num_args, }; frame_stack.push(new_frame); self.sp += closure.func.num_locals as usize;
function_block-random_span
[ { "content": "pub fn eval_index_expression(object: &Object, index: &Object) -> Result<Object, RuntimeError> {\n\n // This function is pub because the \"get\" built-in needs to call it\n\n match (object, index) {\n\n (Object::Array(vector), Object::Integer(i)) => {\n\n if *i < 0 || *i >= ...
Rust
language/vm/src/proptest_types/types.rs
w3f-community/sp-move-vm
1c94891be56ec67eb04a8d1bd21775219d526f48
use crate::{ file_format::{ FieldDefinition, IdentifierIndex, ModuleHandleIndex, SignatureToken, StructDefinition, StructFieldInformation, StructHandle, StructHandleIndex, TableIndex, TypeSignature, }, proptest_types::signature::{KindGen, SignatureTokenGen}, }; use proptest::{ collecti...
use crate::{ file_format::{ FieldDefinition, IdentifierIndex, ModuleHandleIndex, SignatureToken, StructDefinition, StructFieldInformation, StructHandle, StructHandleIndex, TableIndex, TypeSignature, }, proptest_types::signature::{KindGen, SignatureTokenGen}, }; use proptest::{ collecti...
inal_resource, type_parameters, is_public, field_defs, }, ) } pub fn materialize( self, state: &mut StDefnMaterializeState, ) -> (Option<StructDefinition>, usize) { let mut field_names = HashSet:...
Vector(targ) => self.contains_nominal_resource(targ), Reference(token) | MutableReference(token) => self.contains_nominal_resource(token), Bool | U8 | U64 | U128 | Address | TypeParameter(_) => false, } } } #[derive(Clone, Debug)] pub struct StructHandleGen { module_idx: P...
random
[ { "content": "fn struct_handle(token: &SignatureToken) -> Option<StructHandleIndex> {\n\n use SignatureToken::*;\n\n\n\n match token {\n\n Struct(sh_idx) => Some(*sh_idx),\n\n StructInstantiation(sh_idx, _) => Some(*sh_idx),\n\n Reference(token) | MutableReference(token) => struct_han...
Rust
platform/nutekt-digital/demos/raves/src/lib.rs
atomb/logue-sdk
3ba795ece7e90871e171c483c652040186800f5b
#![no_std] use panic_halt as _; use core::f32; use core::ptr; use micromath::F32Ext; pub mod dsp; pub mod mathutil; pub mod nts1; use dsp::biquad; use mathutil::*; use nts1::*; use nts1::clipsat::osc_softclipf; use nts1::platform::*; use nts1::random::osc_white; use nts1::userosc::*; use nts1::wavebank::*; #[repr(u...
#![no_std] use panic_halt as _; use core::f32; use core::ptr; use micromath::F32Ext; pub mod dsp; pub mod mathutil; pub mod nts1; use dsp::biquad; use mathutil::*; use nts1::*; use nts1::clipsat::osc_softclipf; use nts1::platform::*; use nts1::random::osc_white; use nts1::userosc::*; use nts1::wavebank::*; #[repr(u...
NT + K_WAVES_C_CNT; p.wave0 = (value % cnt as u16) as u8; s.flags |= RavesFlags::Wave0 as u8; }, UserOscParamId::Id2 => { let cnt : usize = K_WAVES_D_CNT + K_WAVES_E_CNT + K_WAVES_F_CNT; p.wave1 = (value % cnt as u16) as u8; s.flag...
function_block-function_prefixed
[ { "content": "/// Convert 10-bit parameter value to f32\n\npub fn param_val_to_f32(x: u16) -> f32 {\n\n x as f32 * 9.77517106549365e-004f32\n\n}\n\n\n", "file_path": "platform/nutekt-digital/demos/raves/src/nts1/userosc.rs", "rank": 1, "score": 362597.1218847061 }, { "content": "pub fn ge...
Rust
gstreamer/src/subclass/pad.rs
snapview/gstreamer-rs
a1da562e960208572f124d5a8b878dc0e11b03f5
use gst_sys; use glib; use glib::translate::*; use glib::subclass::prelude::*; use Pad; use PadClass; pub trait PadImpl: PadImplExt + ObjectImpl + Send + Sync { fn linked(&self, pad: &Pad, peer: &Pad) { self.parent_linked(pad, peer) } fn unlinked(&self, pad: &Pad, peer: &Pad) { self.p...
use gst_sys; use glib; use glib::translate::*; use glib::subclass::prelude::*; use Pad; use PadClass; pub trait PadImpl: PadImplExt + ObjectImpl + Send + Sync { fn linked(&self, pad: &Pad, peer: &Pad) { self.parent_linked(pad, peer) } fn unlinked(&self, pad: &Pad, peer: &Pad) { self.p...
.unwrap_or(()) } } } unsafe impl<T: PadImpl> IsSubclassable<T> for PadClass { fn override_vfuncs(&mut self) { <glib::ObjectClass as IsSubclassable<T>>::override_vfuncs(self); unsafe { let klass = &mut *(self as *mut Self as *mut gst_sys::GstPadClass); ...
t_class = data.as_ref().get_parent_class() as *mut gst_sys::GstPadClass; (*parent_class) .unlinked .map(|f| f(pad.to_glib_none().0, peer.to_glib_none().0))
function_block-random_span
[ { "content": "pub trait ChildProxyImpl: ObjectImpl + Send + Sync {\n\n fn get_child_by_name(&self, object: &ChildProxy, name: &str) -> Option<glib::Object> {\n\n unsafe {\n\n let type_ = gst_sys::gst_child_proxy_get_type();\n\n let iface = gobject_sys::g_type_default_interface_re...
Rust
src/tests/conformance/invalid_message/reject.rs
ljedrz/ziggurat
718b5f090c0c2642dcebd0636de7fc7b3c8b844d
use std::{io, time::Duration}; use crate::{ protocol::{ message::Message, payload::{block::Block, reject::CCode, FilterAdd, FilterLoad, Inv, Version}, }, setup::node::{Action, Node}, tools::synthetic_node::{PingPongError, SyntheticNode}, }; #[tokio::test] async fn version_post_handsh...
use std::{io, time::Duration}; use crate::{ protocol::{ message::Message, payload::{block::Block, reject::CCode, FilterAdd, FilterLoad, Inv, Version}, }, setup::node::{Action, Node}, tools::synthetic_node::{PingPongError, SyntheticNode}, }; #[tokio::test] async fn version_post_handsh...
T) .await { Ok(_) => Err(io::Error::new(io::ErrorKind::Other, "Message was ignored")), Err(PingPongError::Unexpected(msg)) => match *msg { Message::Reject(reject) if reject.ccode == expected_code => Ok(()), Message::Reject(reject) => { return Err(io::E...
:0".parse().unwrap(), )); run_test_case(version, CCode::Duplicate).await.unwrap(); } #[tokio::test] async fn verack_post_handshake() { run_test_case(Message::Verack, CCode::Duplicate) .await .unwrap(); } #[tokio::test] async fn mixed_inventory() { let genesis_block...
random
[ { "content": "/// Enables tracing for all [`SyntheticNode`] instances (usually scoped by test).\n\npub fn enable_tracing() {\n\n use tracing_subscriber::{fmt, EnvFilter};\n\n\n\n fmt()\n\n .with_test_writer()\n\n .with_env_filter(EnvFilter::from_default_env())\n\n .init();\n\n}\n\n\n\...
Rust
crates/sentry-actix/src/lib.rs
sharingcloud/github-scbot
953ba1ae7f3bb06c37084756458a1ddb53c8fa65
#![doc(html_favicon_url = "https://sentry-brand.storage.googleapis.com/favicon.ico")] #![doc(html_logo_url = "https://sentry-brand.storage.googleapis.com/sentry-glyph-black.png")] #![warn(missing_docs)] #![allow(deprecated)] #![allow(clippy::type_complexity)] use std::{borrow::Cow, pin::Pin, sync::Arc}; use actix_w...
#![doc(html_favicon_url = "https://sentry-brand.storage.googleapis.com/favicon.ico")] #![doc(html_logo_url = "https://sentry-brand.storage.googleapis.com/sentry-glyph-black.png")] #![warn(missing_docs)] #![allow(deprecated)] #![allow(clippy::type_complexity)] use std::{borrow::Cow, pin::Pin, sync::Arc}; use actix_w...
pub fn builder() -> SentryBuilder { Sentry::new().into_builder() } pub fn into_builder(self) -> SentryBuilder { SentryBuilder { middleware: self } } } impl Default for Sentry { fn default() -> Self { Sentry::new() } } impl<S, B> Transform<S> for Sentry wher...
w() -> Self { Sentry { hub: None, emit_header: false, capture_server_errors: true, } }
function_block-function_prefixed
[ { "content": "/// Captures an [`eyre::Report`].\n\n///\n\n/// This will capture an eyre report as a sentry event if a\n\n/// [`sentry::Client`](../../struct.Client.html) is initialised, otherwise it will be a\n\n/// no-op. The event is dispatched to the thread-local hub, with semantics as described in\n\n/// [...
Rust
src/address.rs
jkilpatr/clarity
e75e1419095f02cd52e7e3213b1e2226a312ed02
use serde::Serialize; use serde::Serializer; use std::str; use std::str::FromStr; use utils::bytes_to_hex_str; use utils::{hex_str_to_bytes, ByteDecodeError}; #[derive(PartialEq, Debug, Clone, Eq, PartialOrd, Hash, Deserialize)] pub struct Address { data: Vec<u8>, } impl Serialize for Address { fn serial...
use serde::Serialize; use serde::Serializer; use std::str; use std::str::FromStr; use utils::bytes_to_hex_str; use utils::{hex_str_to_bytes, ByteDecodeError}; #[derive(PartialEq, Debug, Clone, Eq, PartialOrd, Hash, Deserialize)] pub struct Address { data: Vec<u8>, } impl Serialize for Address { fn serial...
e(), "Bar"); assert_eq!(map.get(&a).unwrap(), &"Foo"); assert_eq!(map.get(&b).unwrap(), &"Bar"); } #[test] fn ordered() { let a = Address::from_str("0x000000000000000000000000000000000000000a").unwrap(); let b = Address::from_str("0x000000000000000000000000000000000000000b").unwrap(); let c = Addr...
rap(); let b = Address::from_str("0x00000000000000000000000000000000deadbeef").unwrap(); let mut map = HashMap::new(); map.insert(a.clone(), "Foo"); map.insert(b.clon
function_block-random_span
[ { "content": "/// A function that takes a hexadecimal representation of bytes\n\n/// back into a stream of bytes.\n\npub fn hex_str_to_bytes(s: &str) -> Result<Vec<u8>, ByteDecodeError> {\n\n let s = if s.starts_with(\"0x\") { &s[2..] } else { s };\n\n s.as_bytes()\n\n .chunks(2)\n\n .map(|c...
Rust
bencher/src/main.rs
dimforge/dimforge-bench
b662de5580095e3a15ffc65a4abc5b40bc8db622
#[macro_use] extern crate log; use amiquip::{ Connection, ConsumerMessage, ConsumerOptions, Exchange, Publish, QueueDeclareOptions, }; use bson::DateTime; use clap::{App, Arg, SubCommand}; use dimforge_bench_common::{ BenchCSVEntry, BenchConfig, BenchContext, BenchKey, BenchMessage, BenchPlatform, }; use log::...
#[macro_use] extern crate log; use amiquip::{ Connection, ConsumerMessage, ConsumerOptions, Exchange, Publish, QueueDeclareOptions, }; use bson::DateTime; use clap::{App, Arg, SubCommand}; use dimforge_bench_common::{ BenchCSVEntry, BenchConfig, BenchContext, BenchKey, BenchMessage, BenchPlatform, }; use log::...
fn parse_csv(path: impl AsRef<Path>) -> csv::Result<(Vec<String>, Vec<Vec<f32>>)> { let mut reader = csv::ReaderBuilder::new() .has_headers(true) .from_path(path) .unwrap(); let headers: Vec<_> = reader.headers()?.iter().map(|h| h.to_string()).collect(); let mut values = vec![Vec::...
ri, &config.mongodb_db)?; let coll = db.collection("rapier3d"); for entry in entries { let doc = bson::to_document(entry).unwrap(); coll.insert_one(doc, None)?; } Ok(()) }
function_block-function_prefixed
[ { "content": "fn connect_to_mongodb(uri: &str, db: &str) -> mongodb::error::Result<Database> {\n\n use mongodb::sync::Client;\n\n let client = Client::with_uri_str(&uri)?;\n\n Ok(client.database(db))\n\n}\n", "file_path": "server/src/main.rs", "rank": 0, "score": 139675.0472944086 }, { ...
Rust
server/src/main.rs
smokku/soldank
9aa7d307121faf7d482bf102c76db34411910a5e
#[macro_use] extern crate clap; use color_eyre::eyre::Result; use hecs::World; use smol::future; use std::{ collections::VecDeque, net::SocketAddr, sync::{Arc, RwLock}, time::{Duration, Instant}, }; use crate::{ constants::*, cvars::{set_cli_cvars, Config, NetConfig}, networking::Networkin...
#[macro_use] extern crate clap; use color_eyre::eyre::Result; use hecs::World; use smol::future; use std::{ collections::VecDeque, net::SocketAddr, sync::{Arc, RwLock}, time::{Duration, Instant}, }; use crate::{ constants::*, cvars::{set_cli_cvars, Config, NetConfig}, networking::Networkin...
networking.post_process(&config); } log::info!("Exiting server"); Ok(()) }) }
tion(&mut server); if networking.connections.is_empty() { log::info!("No connections...
function_block-random_span
[ { "content": "pub fn lobby(world: &mut World, game_state: &mut GameState, networking: &Networking) {\n\n if *game_state != GameState::Lobby {\n\n log::error!(\"Running lobby system outside Lobby GameState\");\n\n }\n\n\n\n let ready = !networking.connections.is_empty()\n\n && networking\n...
Rust
lib/src/settings.rs
orhun/pueue
8b033231e8b95a987d284c621b45ed20203700d3
use std::collections::HashMap; use std::fs::{create_dir_all, File}; use std::io::{prelude::*, BufReader}; use std::path::{Path, PathBuf}; use log::info; use serde_derive::{Deserialize, Serialize}; use shellexpand::tilde; use crate::error::Error; use crate::platform::directories::*; use crate::setting_defaults::*; #[...
use std::collections::HashMap; use std::fs::{create_dir_all, File}; use std::io::{prelude::*, BufReader}; use std::path::{Path, PathBuf}; use log::info; use serde_derive::{Deserialize, Serialize}; use shellexpand::tilde; use crate::error::Error; use crate::platform::directories::*; use crate::setting_defaults::*; #[...
} impl Settings { pub fn read(from_file: &Option<PathBuf>) -> Result<(Settings, bool), Error> { if let Some(path) = from_file { let file = File::open(path) .map_err(|err| Error::IoPathError(path.clone(), "opening config file", err)...
pub fn shared_secret_path(&self) -> PathBuf { if let Some(path) = &self.shared_secret_path { expand_home(path) } else { self.pueue_directory().join("shared_secret") } }
function_block-full_function
[ { "content": "/// This is a small helper which either returns a given group or the default group.\n\npub fn group_or_default(group: &Option<String>) -> String {\n\n group\n\n .clone()\n\n .unwrap_or_else(|| PUEUE_DEFAULT_GROUP.to_string())\n\n}\n\n\n", "file_path": "client/client.rs", "...
Rust
capi/src/optimizer.rs
shinolab/acoustic-field-calculator
620c363c5003cdff085fe41db10ebfbddd25153d
/* * File: optimizer.rs * Project: src * Created Date: 22/09/2020 * Author: Shun Suzuki * ----- * Last Modified: 17/06/2021 * Modified By: Shun Suzuki (suzuki@hapis.k.u-tokyo.ac.jp) * ----- * Copyright (c) 2020 Hapis Lab. All rights reserved. * */ use libc::c_char; use std::ffi::c_void; use std::ffi::CStr; ...
/* * File: optimizer.rs * Project: src * Created Date: 22/09/2020 * Author: Shun Suzuki * ----- * Last Modified: 17/06/2021 * Modified By: Shun Suzuki (suzuki@hapis.k.u-tokyo.ac.jp) * ----- * Copyright (c) 2020 Hapis Lab. All rights reserved. * */ use libc::c_char; use std::ffi::c_void; use std::ffi::CStr; ...
#[no_mangle] pub unsafe extern "C" fn AFO_GS( handle: *mut c_void, foci: *const c_void, amps: *const f32, size: u64, source_type: i32, ) { let len = size as usize; let foci = std::slice::from_raw_parts(foci as *const Vector3, len); let amps = std::slice::from_raw_parts(amps, len); ...
i = std::slice::from_raw_parts(foci as *const Vector3, len); let amps = std::slice::from_raw_parts(amps, len); gen_match_src_type!( source_type, handle, Gspat::new(foci.to_vec(), amps.to_vec()) ); }
function_block-function_prefixed
[ { "content": "pub fn to_vec4(v: Vector3) -> [f32; 4] {\n\n [v[0] as f32, v[1] as f32, v[2] as f32, 0.]\n\n}\n", "file_path": "acoustic-field-calculator/src/gpu/gpu_prelude.rs", "rank": 0, "score": 210100.9783508046 }, { "content": "#[inline(always)]\n\npub fn sub(a: Vector3, b: Vector3) -...
Rust
src/test/util/matchable.rs
PhotonQuantum/mongo-rust-driver
fd0f75c1af911d02d55659876456838d5f2b8bf0
use std::{any::Any, fmt::Debug, time::Duration}; use crate::{ bson::{Bson, Document}, bson_util, options::{AuthMechanism, Credential}, }; pub trait Matchable: Sized + 'static { fn is_placeholder(&self) -> bool { false } fn content_matches(&self, expected: &Self) -> Result<(), String>;...
use std::{any::Any, fmt::Debug, time::Duration}; use crate::{ bson::{Bson, Document}, bson_util, options::{AuthMechanism, Credential}, }; pub trait Matchable: Sized + 'static { fn is_placeholder(&self) -> bool { false } fn content_matches(&self, expected: &Self) -> Result<(), String>;...
.prefix("username")?; self.source .content_matches(&expected.source) .prefix("source")?; self.password .content_matches(&expected.password) .prefix("password")?; self.mechanism .content_matches(&expected.mechanism) .pre...
k)?, None => { if v != &Bson::Null { return Err(format!("{:?}: expected value {:?}, got null", k, v)); } } } } Ok(()) } } impl Matchable for Credential { fn content_matches(&self, expecte...
random
[ { "content": "fn numbers_match(actual: &Bson, expected: &Bson) -> bool {\n\n if actual.element_type() == expected.element_type() {\n\n return actual == expected;\n\n }\n\n\n\n match (get_int(actual), get_int(expected)) {\n\n (Some(actual), Some(expected)) => actual == expected,\n\n ...
Rust
src/json_dsl/param.rs
swarkentin/valico
f6aed770ef3b0f1215636b29c696c2a69e29f92b
use serde::Serialize; use serde_json::{to_value, Value}; use super::super::json_schema; use super::builder; use super::coercers; use super::validators; pub struct Param { pub name: String, pub coercer: Option<Box<dyn coercers::Coercer + Send + Sync>>, pub nest: Option<builder::Builder>, pub descripti...
use serde::Serialize; use serde_json::{to_value, Value}; use super::super::json_schema; use super::builder; use super::coercers; use super::validators; pub struct Param { pub name: String, pub coercer: Option<Box<dyn coercers::Coercer + Send + Sync>>, pub nest: Option<builder::Builder>, pub descripti...
pub fn new_with_coercer( name: &str, coercer: Box<dyn coercers::Coercer + Send + Sync>, ) -> Param { Param { name: name.to_string(), description: None, coercer: Some(coercer), nest: None, allow_null: false, validat...
pub fn new(name: &str) -> Param { Param { name: name.to_string(), description: None, coercer: None, nest: None, allow_null: false, validators: vec![], default: None, schema_builder: None, schema_id: None,...
function_block-full_function
[ { "content": "pub fn string() -> Box<dyn coercers::Coercer + Send + Sync> {\n\n Box::new(coercers::StringCoercer)\n\n}\n", "file_path": "src/json_dsl/mod.rs", "rank": 0, "score": 279433.43672192114 }, { "content": "pub trait Coercer: Send + Sync {\n\n fn get_primitive_type(&self) -> Pr...
Rust
day7/src/main.rs
monkeydom/adventofcode-2020-rust
9b9105fabc51b9c793fae59528ac593f54524e11
#[allow(dead_code)] mod aoc; #[allow(dead_code)] mod file; use std::collections::HashMap; use std::collections::HashSet; use std::fmt; fn main() { aoc::preamble(); part2(); } #[derive(Debug)] struct BagContents { bt: BagType, contents: Vec<BagType>, } impl BagContents { fn from_strings(stri...
#[allow(dead_code)] mod aoc; #[allow(dead_code)] mod file; use std::collections::HashMap; use std::collections::HashSet; use std::fmt; fn main() { aoc::preamble(); part2(); } #[derive(Debug)] struct BagContents { bt: BagType, contents: Vec<BagType>, } impl BagContents { fn from_strings(stri...
(|bt| cc.get(&bt).is_some()) { updated_some = true; let value = bc .contents .iter() .fold(0, |acc, v| acc + cc.get(v).unwrap() + 1); println!("{:?} -> updating with value {}", &bc.bt, va...
elf.color) } } impl BagType { fn from_strings(strings: &[&str]) -> Self { BagType { attribute: strings[0].to_string(), color: strings[1].to_string(), } } } fn parse_rule(line: String) -> BagContents { let tokens: Vec<&str> = line.split(" ").collect(); l...
random
[ { "content": "fn process_lines(lines: impl Iterator<Item = String>) -> (Vec<Field>, Vec<i64>, Vec<Vec<i64>>) {\n\n let mut my_ticket: Vec<i64> = vec![];\n\n let mut nearby_tickets: Vec<Vec<i64>> = vec![];\n\n let mut fields: Vec<Field> = vec![];\n\n let mut state = 0;\n\n for line in lines {\n\n ...
Rust
fortress/src/lib/enemies/state/enemy_state_machine.rs
j-rock/fortress
23b71bbd75afe75370b59e2117893f1023142c17
use crate::{ audio::{ AudioPlayer, Sound, }, dimensions::{ Attack, Reverse, time::{ DeltaTime, Microseconds, } }, enemies::{ DamageTextWriter, EnemySystemConfig, EnemyConfig, EnemyState, s...
use crate::{ audio::{ AudioPlayer, Sound, }, dimensions::{ Attack, Reverse, time::{ DeltaTime, Microseconds, } }, enemies::{ DamageTextWriter, EnemySystemConfig, EnemyConfig, EnemyState, s...
let image_name = match self { Self::Dying(_, _) => String::from("enemy1_dying.png"), _ => String::from("enemy1.png") }; let frame = match self { Self::Base(_, time_elapsed) => (*time_elapsed / config.walk_frame_duration_micros) as usize, Self::Dying(...
pub fn post_update(&mut self, config: &EnemyConfig, audio: &AudioPlayer, enemy_state: &EnemyState, items: &mut ItemSystem, physics_sim: &mut PhysicsSimulation) -> Option<Self> { match self { ...
random
[ { "content": "pub fn milliseconds(t: i64) -> Microseconds {\n\n t * 1000\n\n}\n\n\n\n#[derive(Copy, Clone)]\n\npub struct DeltaTime {\n\n microseconds_elapsed: Microseconds\n\n}\n\n\n\nimpl DeltaTime {\n\n fn duration_to_microseconds(duration: Duration) -> Microseconds {\n\n let nanos = Microsec...
Rust
examples/box_game/box_game_p2p.rs
johanhelsing/ggrs
6d1b7d6112692619a8638646cf5229a085bc3986
extern crate freetype as ft; use ggrs::{GGRSEvent, PlayerType, SessionState}; use glutin_window::GlutinWindow as Window; use opengl_graphics::{GlGraphics, OpenGL}; use piston::event_loop::{EventSettings, Events}; use piston::input::{RenderEvent, UpdateEvent}; use piston::window::WindowSettings; use piston::{Button, Ev...
extern crate freetype as ft; use ggrs::{GGRSEvent, PlayerType, SessionState}; use glutin_window::GlutinWindow as Window; use opengl_graphics::{GlGraphics, OpenGL}; use piston::event_loop::{EventSettings, Events}; use piston::input::{RenderEvent, UpdateEvent}; use piston::window::WindowSettings; use piston::{Button, Ev...
let mut event_settings = EventSettings::new(); event_settings.set_ups(FPS); event_settings.set_max_fps(FPS); let mut events = Events::new(event_settings); let mut frames_to_skip = 0; while let Some(e) = events.next(&mut window) { if let Some(args) = e.render_args() { ...
function_block-function_prefix_line
[ { "content": "#[derive(StructOpt)]\n\nstruct Opt {\n\n #[structopt(short, long)]\n\n local_port: u16,\n\n #[structopt(short, long)]\n\n num_players: usize,\n\n #[structopt(short, long)]\n\n host: SocketAddr,\n\n}\n\n\n", "file_path": "examples/box_game/box_game_spectator.rs", "rank": 0...
Rust
src/tcp.rs
tearust/natsclient
d41211cb35e0a4fcec5fa0e45a07fbce494655e4
use crate::protocol::{ProtocolHandler, ProtocolMessage, ServerInfo}; use crate::ClientOptions; use crate::Result; use crossbeam_channel::{Receiver, Sender}; use nats_types::DeliveredMessage; use std::io::Read; use std::sync::{Arc, RwLock}; use std::thread; use std::{ io::{BufRead, BufReader, Write}, net::TcpStr...
use crate::protocol::{ProtocolHandler, ProtocolMessage, ServerInfo}; use crate::ClientOptions; use crate::Result; use crossbeam_channel::{Receiver, Sender}; use nats_types::DeliveredMessage; use std::io::Read; use std::sync::{Arc, RwLock}; use std::thread; use std::{ io::{BufRead, BufReader, Write}, net::TcpStr...
fn connect_to_host(servers: &[ServerInfo]) -> Result<TcpStream> { for si in servers { debug!("Attempting to connect to {}:{}", si.host, si.port); let stream = TcpStream::connect((si.host.as_ref(), si.port)); match stream { Ok(s) => return Ok(s), ...
let connlatch = self.connlatch.clone(); thread::spawn(move || { let mut line = String::new(); loop { match buf_reader.read_line(&mut line) { Ok(line_len) if line_len > 0 => { let pm = if line.starts_with("MSG") { ...
function_block-function_prefix_line
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n pretty_env_logger::init();\n\n\n\n info!(\"Starting market service...\");\n\n let jwt = \"eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJBNDNRN1NLT0tCT0tYUDc1WVhMWjcyVDZKNDVIVzJKR0ZRWUJFQ1I2VE1FWEZFN1RKSjVBIiwiaWF0IjoxNTU0ODk2O...
Rust
src/mesh/mod.rs
LukasKalbertodt/cantucci
dea982b39d849de4a34082c4864b46d806eadd72
use cgmath::{prelude::*, Point3, Vector3}; use num_cpus; use std::{array::IntoIter, sync::mpsc::{channel, Receiver, Sender}}; use std::sync::Arc; use threadpool::ThreadPool; use crate::{ prelude::*, camera::Camera, octree::{Octree, SpanExt}, shape::Shape, util::iter, wgpu::DrawContext, }; mod ...
use cgmath::{prelude::*, Point3, Vector3}; use num_cpus; use std::{array::IntoIter, sync::mpsc::{channel, Receiver, Sender}}; use std::sync::Arc; use threadpool::ThreadPool; use crate::{ prelude::*, camera::Camera, octree::{Octree, SpanExt}, shape::Shape, util::iter, wgpu::DrawContext, }; mod ...
pub(crate) fn draw( &self, draw_ctx: DrawContext<'_>, camera: &Camera, ) { let it = self.tree.iter() .filter_map(|n| n.leaf_data().map(|data| (data, n.span()))); for (leaf_data, _span) in it { match leaf_data { ...
pub fn update(&mut self, device: Arc<wgpu::Device>, camera: &Camera) { const FOCUS_POINTS: u8 = 5; let focii = self.get_focii(camera, FOCUS_POINTS); for focus in focii { if let Some(mut leaf) = self.tree.leaf_around_mut(focus) { ...
function_block-full_function
[ { "content": "/// Creates 8 equally sized children spans of a passed parent span. The spans are defined\n\n/// in a way that will be no gaps between them due to floating point precision errors.\n\npub fn create_spans(parent_span: Range<Point3<f32>>) -> [Range<Point3<f32>>; 8] {\n\n let start = parent_span.st...
Rust
crates/dkg-core/src/node.rs
kafeikui/BLS-DKG-Demo
7e3e46b10715d76e6dfcdf48b8628ccb2c1eb305
use super::{ board::BoardPublisher, primitives::{ phases::{Phase0, Phase1, Phase2, Phase3}, types::{BundledJustification, BundledResponses, BundledShares, DKGOutput}, DKGError, }, }; use async_trait::async_trait; use rand::RngCore; use thiserror::Error; use threshold_bls::group::Cur...
use super::{ board::BoardPublisher, primitives::{ phases::{Phase0, Phase1, Phase2, Phase3}, types::{BundledJustification, BundledResponses, BundledShares, DKGOutput}, DKGError, }, }; use async_trait::async_trait; use rand::RngCore; use thiserror::Error; use threshold_bls::group::Cur...
#[tokio::test] async fn not_enough_validator_shares() { let (t, n) = (6, 10); let bad = t + 1; let honest = n - bad; let rng = &mut rand::thread_rng(); let (mut board, phase0s) = setup::<bls12_377::G1Curve, G1Scheme<BLS12_377>, _>(n, t, rng); let mut phase1s =...
let (mut board, phase0s) = setup::<C, S, _>(n, t, rng); let mut phase1s = Vec::new(); for phase0 in phase0s { phase1s.push(phase0.run(&mut board, rng).await.unwrap()); } let shares = board.shares.clone(); let mut phase2s = Vec::new(); ...
function_block-function_prefix_line
[ { "content": "/// Creates the encrypted shares with the given secret polynomial to the given\n\n/// group.\n\npub fn create_share_bundle<C: Curve, R: RngCore>(\n\n dealer_idx: Idx,\n\n secret: &PrivatePoly<C>,\n\n public: &PublicPoly<C>,\n\n group: &Group<C>,\n\n rng: &mut R,\n\n) -> DKGResult<Bu...
Rust
pageserver/src/layered_repository/filename.rs
libzenith/zenith
4b3b19f4448f650b918230d972e2ec68815dcbdb
use crate::config::PageServerConf; use crate::layered_repository::storage_layer::SegmentTag; use crate::relish::*; use std::fmt; use std::path::PathBuf; use zenith_utils::lsn::Lsn; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] pub struct DeltaFileName { pub seg: SegmentTag, pub start_lsn: Lsn, ...
use crate::config::PageServerConf; use crate::layered_repository::storage_layer::SegmentTag; use crate::relish::*; use std::fmt; use std::path::PathBuf; use zenith_utils::lsn::Lsn; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] pub struct DeltaFileName { pub seg: SegmentTag, pub start_lsn: Lsn, ...
} impl fmt::Display for ImageFileName { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let basename = match self.seg.rel { RelishTag::Relation(reltag) => format!( "rel_{}_{}_{}_{}", reltag.spcnode, reltag.dbnode, reltag.relnode, reltag.forknum ...
l = RelishTag::Slru { slru: SlruKind::Clog, segno: u32::from_str_radix(parts.next()?, 16).ok()?, }; } else if let Some(rest) = fname.strip_prefix("pg_multixact_members_") { parts = rest.split('_'); rel = RelishTag::Slru { slru: ...
function_block-function_prefixed
[ { "content": "fn check_slru_segno(rel: &RelishTag, expected_slru: SlruKind, expected_segno: u32) -> bool {\n\n if let RelishTag::Slru { slru, segno } = rel {\n\n *slru == expected_slru && *segno == expected_segno\n\n } else {\n\n false\n\n }\n\n}\n\n\n\n/// An error happened in WAL redo\n...
Rust
src/main.rs
dbrgn/galerio
1fe5984f36f8362aca36aa03541f73322fb943c8
use std::{ fs, io::{self, Write}, path::{Path, PathBuf}, time::Instant, }; use anyhow::{anyhow, Result}; use exif::{In as IdfNum, Reader as ExifReader, Tag as ExifTag, Value as ExifValue}; use image::{self, imageops::FilterType, GenericImageView, ImageFormat}; use lazy_static::lazy_static; use serde::S...
use std::{ fs, io::{self, Write}, path::{Path, PathBuf}, time::Instant, }; use anyhow::{anyhow, Result}; use exif::{In as IdfNum, Reader as ExifReader, Tag as ExifTag, Value as ExifValue}; use image::{self, imageops::FilterType, GenericImageView, ImageFormat}; use lazy_static::lazy_static; use serde::S...
let full_path = args.output_dir.join(&filename_full); if let Some(max_size) = args.max_large_size { let (w, h) = get_dimensions(&f)?; if w > max_size || h > max_size { let large_bytes = resize_image(&f, max_size, max_size, &orientatio...
orientation| match orientation { 1 => Orientation::Deg0, 8 => Orientation::Deg90, 3 => Orientation::Deg180, 6 => Orientation::Deg270, _ => Orientation::Deg0, }); Ok(orientation.unwrap_or(Orientation::Deg0)) } fn main() -> Result<()> { let args...
random
[ { "content": "# Galerio\n\n\n\nGalerio is a simple generator for HTML flexbox galleries written in Rust. From\n\na directory with JPEG files, it generates a self-contained gallery without\n\nexternal dependencies.\n\n\n\n## Features\n\n\n\n- Simple CSS3/Flexbox based gallery\n\n- Touch friendly lightbox for vie...
Rust
oxidizer-entity-macro/src/utils.rs
TylerLafayette/oxidizer
c59ce9a50243f0eb35203d2d72fbc9ff36cb5afd
use proc_macro2::TokenStream; use quote::{quote, quote_spanned}; use syn::{ spanned::Spanned, AngleBracketedGenericArguments, Field, GenericArgument, Meta, Path, PathArguments, PathSegment, Type, TypePath, }; pub fn iterate_angle_bracketed( ab: &AngleBracketedGenericArguments, expected: &Vec<String>, ...
use proc_macro2::TokenStream; use quote::{quote, quote_spanned}; use syn::{ spanned::Spanned, AngleBracketedGenericArguments, Field, GenericArgument, Meta, Path, PathArguments, PathSegment, Type, TypePath, }; pub fn iterate_angle_bracketed( ab: &AngleBracketedGenericArguments, expected: &Vec<String>, ...
egments.iter() { if iterate_path_arguments(seg, &expected, index) { return true; } } expected.len() == index } pub fn check_type_order(p: &TypePath, expected: &Vec<String>, index: usize) -> bool { let mut index = index; if expected.len() == index { return true; ...
)) => check_type_order(tp, expected, index), _ => unimplemented!(), }; if res { return true; } } false } pub fn iterate_path_arguments(seg: &PathSegment, expected: &Vec<String>, index: usize) -> bool { let mut index = index; if expected.len() == index ...
random
[ { "content": "type GetFieldsIter<'a> = std::iter::Filter<syn::punctuated::Iter<'a, Field>, fn(&&Field) -> bool>;\n\n\n\nimpl Props {\n\n pub fn new(\n\n input: DeriveInput,\n\n attrs: Option<EntityAttr>,\n\n indexes: Vec<IndexAttr>,\n\n has_many_attrs: Vec<HasManyAttr>,\n\n ) -...
Rust
src/day5.rs
mathstar/adventOfCode2021
19e843ebf1f0e2abbee5c4502b39bfdab5755a1e
use std::cmp::{max, min}; use std::collections::HashMap; use crate::day::Day; pub struct Day5 {} #[derive(Debug)] struct Line { start: (i32, i32), end: (i32, i32) } enum AxialClassification { X, Y, NonAxial } impl Line { fn axial_classification(&self) -> AxialClassification { if self.start.0...
use std::cmp::{max, min}; use std::collections::HashMap; use crate::day::Day; pub struct Day5 {} #[derive(Debug)] struct Line { start: (i32, i32), end: (i32, i32) } enum AxialClassification { X, Y, NonAxial } impl Line {
} fn parse_input(input: &str) -> Vec<Line> { let mut lines = Vec::new(); for line in input.lines() { let mut split = line.split(" -> "); let mut p_split = split.next().unwrap().split(","); let start = (p_split.next().unwrap().parse().unwrap(), p_split.next().unwrap().parse().unwrap())...
fn axial_classification(&self) -> AxialClassification { if self.start.0 == self.end.0 { AxialClassification::X } else if self.start.1 == self.end.1 { AxialClassification::Y } else { AxialClassification::NonAxial } }
function_block-full_function
[ { "content": "struct BingoBoard {\n\n values: Vec<Vec<i32>>,\n\n marked: Vec<Vec<bool>>\n\n}\n\n\n\nimpl BingoBoard {\n\n fn new(values: Vec<Vec<i32>>) -> BingoBoard {\n\n let mut marked = Vec::new();\n\n for a in &values {\n\n let mut row = Vec::new();\n\n for _ in ...
Rust
pongo-rs-derive/src/raw_index_options.rs
simoneromano96/pongo-rs
615e776990e4c0435efc1ff7b87aa0d39e3b9024
use darling::FromMeta; #[derive(Clone, Debug)] pub(crate) struct Document(mongodb::bson::Document); impl FromMeta for Document { fn from_string(value: &str) -> darling::Result<Self> { println!("{value:#?}"); let value = serde_json::from_str(value); match value { Ok(document) =>...
use darling::FromMeta; #[derive(Clone, Debug)] pub(crate) struct Document(mongodb::bson::Document); impl FromMeta for Document { fn from_string(value: &str) -> darling::Result<Self> { println!("{value:#?}"); let value = serde_json::from_str(value); match value { Ok(document) =>...
t)] pub(crate) bits: Option<u32>, #[darling(default)] pub(crate) max: Option<f64>, #[darling(default)] pub(crate) min: Option<f64>, #[darling(default)] pub(crate) bucket_size: Option<u32>, #[darling(default)] pub(crate) partial_filter_expre...
match value { Ok(document) => Ok(Self(document)), Err(error) => Err(darling::Error::unsupported_shape(&format!("{error}"))), } } } #[derive(Clone, Debug)] pub(crate) struct IndexOptions(mongodb::options::IndexOptions); impl FromMeta for IndexOptions { fn from_string(va...
random
[ { "content": "fn impl_model_derive_macro(ast: &syn::DeriveInput) -> TokenStream {\n\n let parsed: Model = FromDeriveInput::from_derive_input(ast).unwrap();\n\n println!(\"{parsed:#?}\");\n\n let name = &parsed.ident;\n\n\n\n let collection_name = match parsed.collection_options {\n\n Some(col...
Rust
src/python_module.rs
gchers/fbleau
fe66cc859efaba47526cb864fbe8438bfd6bdc35
use numpy::*; use pyo3::prelude::*; use pyo3::types::PyDict; use crate::estimates::*; use crate::fbleau_estimation::{run_fbleau, Logger}; use crate::Label; #[pymodule(fbleau)] fn pyfbleau(_py: Python, m: &PyModule) -> PyResult<()> { ...
use numpy::*; use pyo3::prelude::*; use pyo3::types::PyDict; use crate::estimates::*; use crate::fbleau_estimation::{run_fbleau, Logger}; use crate::Label; #[pymodule(fbleau)] fn pyfbleau(_py: Python, m: &PyModule) -> PyResult<()> { ...
estimates", if let Some(Logger::LogVec(v)) = error_logger { v } else { vec![] }, )?; res.set_item( "min-individual-errors", if let Some(Logger::LogVec(v)) = individual_error_logger { v ...
function_block-function_prefixed
[ { "content": "pub fn knn_strategy(strategy: KNNStrategy) -> Box<dyn Fn(usize) -> usize> {\n\n match strategy {\n\n KNNStrategy::NN => Box::new(move |_| 1),\n\n KNNStrategy::FixedK(k) => Box::new(move |_| k),\n\n KNNStrategy::Ln => Box::new(move |n| {\n\n next_odd(if n != 0 {\n...
Rust
src/emit/flatbin.rs
kubasz/rvasm
f28c2e857bd41c5f511bd5494ae89d8425882535
use crate::arch; use crate::parser::Node; use smallvec::SmallVec; use std::collections::HashMap; #[derive(Clone, Debug)] pub enum EmitError { UnexpectedNodeType(String), InvalidInstruction(String), InvalidArgumentCount(String), InvalidArgumentType(String, usize), InvalidEncoding(String), Duplic...
use crate::arch; use crate::parser::Node; use smallvec::SmallVec; use std::collections::HashMap; #[derive(Clone, Debug)] pub enum EmitError { UnexpectedNodeType(String), InvalidInstruction(String), InvalidArgumentCount(String), InvalidArgumentType(String, usize), InvalidEncoding(String), Duplic...
let mut argv: SmallVec<[u64; 4]> = SmallVec::new(); for (i, arg) in args.iter().enumerate() { match fmt.fields[specinsn.args[i]].vtype { arch::FieldType::Value => { if let N...
if let Node::Instruction(_, sargs) = simpinsn.0 { args = sargs; } else { panic!("Simplified instruction is now a {:?}", simpinsn.0); }
if_condition
[ { "content": "pub fn ast_from_str(s: &str, spec: &arch::RiscVSpec) -> Result<Node, ParseError> {\n\n grammar::top_level(s, spec)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 0, "score": 137818.47554548547 }, { "content": "pub fn ast_from_file(path: &str, spec: &arch::RiscVSpec) -> R...
Rust
anvil/src/eth/backend/executor.rs
Rjected/dapptools-rs
b11b776934cce2a0e70ce4879e7a05c9a34ac008
use crate::eth::{ backend::{db::Db, validate::TransactionValidator}, error::InvalidTransactionError, pool::transactions::PoolTransaction, }; use anvil_core::eth::{ block::{Block, BlockInfo, Header, PartialHeader}, receipt::{EIP1559Receipt, EIP2930Receipt, EIP658Receipt, Log, TypedReceipt}, trans...
use crate::eth::{ backend::{db::Db, validate::TransactionValidator}, error::InvalidTransactionError, pool::transactions::PoolTransaction, }; use anvil_core::eth::{ block::{Block, BlockInfo, Header, PartialHeader}, receipt::{EIP1559Receipt, EIP2930Receipt, EIP658Receipt, Log, TypedReceipt}, trans...
on { transaction, exit, out, gas, logs: logs.into_iter().map(Into::into).collect(), traces: tracer.traces.arena, }; Some(TransactionExecutionOutcome::Executed(tx)) } } fn logs_bloom(logs: Vec<Log>, bloom: &mut Bloom) { for...
b); let mut tracer = Tracer::default(); trace!(target: "backend", "[{:?}] executing", transaction.hash()); let (exit, out, gas, logs) = evm.inspect_commit(&mut tracer); if exit == Return::OutOfGas { warn!(target: "backend", "[{:?}] executed w...
function_block-random_span
[ { "content": "/// Returns the RLP for this account.\n\npub fn trie_account_rlp(info: &AccountInfo, storage: Map<U256, U256>) -> Bytes {\n\n let mut stream = RlpStream::new_list(4);\n\n stream.append(&info.nonce);\n\n stream.append(&info.balance);\n\n stream.append(&{\n\n sec_trie_root(storage...
Rust
menoh/src/model/mod.rs
Hakuyume/menoh-rs
2d463e94c0159a56821ec6766cba681cdc6a5edd
use menoh_sys; use std::ffi; use std::mem; use std::ptr; use std::slice; use Dtype; use handler::Handler; use Error; use error::check; pub struct Model { handle: menoh_sys::menoh_model_handle, } impl Model { pub fn get_variable_dims(&self,...
use menoh_sys; use std::ffi; use std::mem; use std::ptr; use std::slice; use Dtype; use handler::Handler; use Error; use error::check; pub struct Model { handle: menoh_sys::menoh_model_handle, } impl Model { pub fn get_variable_dims(&self,...
pub fn get_variable_mut<T>(&mut self, name: &str) -> Result<(Vec<usize>, &mut [T]), Error> where T: Dtype { T::check(self.get_variable_dtype(name)?)?; let dims = self.get_variable_dims(name)?; let name = ffi...
e { check(menoh_sys::menoh_model_get_variable_buffer_handle(self.handle, name.as_ptr(), &mut buffer))?; let buffer = slice::from_raw_parts(buffer as _, dims.ite...
function_block-function_prefixed
[ { "content": "pub fn check(code: menoh_sys::menoh_error_code) -> Result<(), Error> {\n\n let code = code as menoh_sys::menoh_error_code_constant;\n\n\n\n if code == menoh_sys::menoh_error_code_success {\n\n Ok(())\n\n } else {\n\n let message = unsafe {\n\n ffi::CStr::from_ptr(...
Rust
src/component/transformed.rs
DaseinPhaos/arendur
5c3b6c4dffd969131ebf37a3f8eb9b6a3cf7f5c6
use geometry::prelude::*; use super::*; use std::sync::Arc; use spectrum::*; use renderer::scene::Scene; use lighting::{LightFlag, LightSample, SampleInfo, PathInfo}; #[derive(Clone, Debug)] pub struct TransformedComposable<T> { inner: T, local_parent: Arc<Matrix4f>, parent_local: Arc<Matrix4f>, } impl<...
use geometry::prelude::*; use super::*; use std::sync::Arc; use spectrum::*; use renderer::scene::Scene; use lighting::{LightFlag, LightSample, SampleInfo, PathInfo}; #[derive(Clone, Debug)] pub struct TransformedComposable<T> { inner: T, local_parent: Arc<Matrix4f>, parent_local: Arc<Matrix4f>, } impl<...
#[inline] fn pdf(&self, pos: Point3f, wi: Vector3f) -> Float { let pos = self.parent_local.transform_point(pos); let wi = self.parent_local.transform_vector(wi); self.inner.pdf(pos, wi) } #[inline] fn power(&self) -> RGBSpectrumf { self.inner.power() } } impl ...
s); let dir = self.parent_local.transform_vector(dir); let norm = self.parent_local.transform_norm(norm); self.inner.pdf_path(pos, dir, norm) }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn sample_uniform_cone(u: Point2f, cos_max: Float) -> Vector3f {\n\n let costheta = (1.0 as Float - u.x) + u.x * cos_max;\n\n let sintheta = (1.0 as Float - costheta*costheta).sqrt();\n\n let phi = u.y * (2.0 as Float * float::pi());\n\n Vector3f::new(sintheta*phi.cos(...
Rust
src/game.rs
frellica/bevy_mine_sweeper
31bf44c00615a25f03e1dabc12c61a2e4d4c666b
use std::cmp; use bevy::{ diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin}, prelude::*, }; use crate::mine_core::{ BlockType, BlockStatus, MinePlayground, MineBlock, Position, ClickResult }; pub fn game_app(config: GameConfig) { App::build() .add_resource(WindowDescriptor { vsync: ...
use std::cmp; use bevy::{ diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin}, prelude::*, }; use crate::mine_core::{ BlockType, BlockStatus, MinePlayground, MineBlock, Position, ClickResult }; pub fn game_app(config: GameConfig) { App::build() .add_resource(WindowDescriptor { vsync: ...
lexEnd, position_type: PositionType::Absolute, position: Rect { top: Val::Px(5.0), left: Val::Px(5.0), ..Default::default() }, ..Default::default() }, text: Text { value: "debug text here".to_stri...
ze, } #[derive(Debug, Clone, PartialEq)] enum GameState { Prepare, Ready, Running, Over, } #[derive(Default, Debug)] struct CursorLocation(Vec2); struct LastActionText(String); struct ButtonMaterials { normal: Handle<ColorMaterial>, hovered: Handle<ColorMaterial>, pressed: Handle<ColorMat...
random
[ { "content": "fn get_surroundings(&x: &usize, &y: &usize, &max_width: &usize, &max_height: &usize) -> Vec<(usize, usize)> {\n\n let max_x = max_width - 1;\n\n let max_y = max_height - 1;\n\n let mut r = vec![];\n\n if x > 0 { r.push((x - 1, y)); }\n\n if x < max_x { r.push((x + 1, y)); }\n\n i...
Rust
src/parser/error.rs
boxofrox/combine
5b89f1913d7932b20c37e6a11bebd347a5942df1
use crate::{ error::{ ErrorInfo, ParseError, ParseResult::{self, *}, StreamError, Tracked, }, lib::marker::PhantomData, parser::ParseMode, Parser, Stream, StreamOnce, }; #[derive(Clone)] pub struct Unexpected<I, T, E>(E, PhantomData<fn(I) -> (I, T)>) where I: Stream; i...
use crate::{ error::{ ErrorInfo, ParseError, ParseResult::{self, *}, StreamError, Tracked, }, lib::marker::PhantomData, parser::ParseMode, Parser, Stream, StreamOnce, }; #[derive(Clone)] pub struct Unexpected<I, T, E>(E, PhantomData<fn(I) -> (I, T)>) where I: Stream; i...
pected(); err }) } fn add_error(&mut self, _errors: &mut Tracked<<Input as StreamOnce>::Error>) {} fn add_consumed_expected_error(&mut self, _errors: &mut Tracked<<Input as StreamOnce>::Error>) { } forward_parser!(Input, parser_count, 0); } pub fn silent<Input, P>(p: P) -> Si...
t: &mut Input, state: &mut Self::PartialState, ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> where M: ParseMode, { self.0.parse_mode(mode, input, state).map_err(|mut err| { err.clear_ex
function_block-random_span
[ { "content": "pub fn repeat_until<F, Input, P, E>(parser: P, end: E) -> RepeatUntil<F, P, E>\n\nwhere\n\n Input: Stream,\n\n F: Extend<P::Output> + Default,\n\n P: Parser<Input>,\n\n E: Parser<Input>,\n\n{\n\n RepeatUntil {\n\n parser,\n\n end,\n\n _marker: PhantomData,\n\n ...
Rust
providers/nitro/nitro-helper/src/command/nitro_enclave.rs
chatchai-hub/tmkms-light
972a739277002704308bfc4e75a0cfa79f62bbb6
use crate::command::check_vsock_proxy; use crate::config::{EnclaveOpt, VSockProxyOpt}; use crate::enclave_log_server::LogServer; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::process::{Command, Output}; use std::sync::mpsc::Receiver; #[derive(Clone, Serialize, Deserialize)] pub struc...
use crate::command::check_vsock_proxy; use crate::config::{EnclaveOpt, VSockProxyOpt}; use crate::enclave_log_server::LogServer; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::process::{Command, Output}; use std::sync::mpsc::Receiver; #[derive(Clone, Serialize, Deserialize)] pub struc...
; } serde_json::from_slice(output.stdout.as_slice()) .map_err(|_| "command invalid output".to_string()) } fn run_enclave_daemon( image_path: &str, cpu_count: usize, memory_mib: u64, cid: Option<u64>, ) -> Result<EnclaveRunInfo, String> { let mut cmd = Command::new("nitro-cli"); ...
Err(format!( "{}, status code: {:?}", String::from_utf8_lossy(output.stderr.as_slice()), output.status.code(), ))
call_expression
[]
Rust
src/main.rs
mverleg/next_semver
c9c9833f41e4fb768354479a05f32f6440ff2325
use ::std::fmt; use ::rocket::get; use ::rocket::launch; use ::rocket::request::FromParam; use ::rocket::response::status; use ::rocket::routes; use ::rocket::Build; use ::rocket::Rocket; use ::semver::Version; use ::next_semver::bump; use ::next_semver::Part; #[cfg(feature = "jemalloc")] #[global_allocator] static ...
use ::std::fmt; use ::rocket::get; use ::rocket::launch; use ::rocket::request::FromParam; use ::rocket::response::status; use ::rocket::routes; use ::rocket::Build; use ::rocket::Rocket; use ::semver::Version; use ::next_semver::bump; use ::next_semver::Part; #[cfg(feature = "jemalloc")] #[global_allocator] static ...
) } } #[derive(Debug, Clone)] pub struct BumpVersion { version: Version, } impl From<BumpVersion> for Version { fn from(version: BumpVersion) -> Self { version.version } } impl fmt::Display for BumpVersion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}"...
match param { "ma" | "major" | "breaking" => BumpPart::Major, "mi" | "minor" | "feature" => BumpPart::Minor, "pa" | "patch" | "fix" => BumpPart::Patch, _ => return Err(()), }
if_condition
[ { "content": "pub fn bump(version: impl Borrow<Version>, part: Part) -> Version {\n\n let version = version.borrow();\n\n match part {\n\n Part::Major => Version {\n\n major: version.major + 1,\n\n minor: 0,\n\n patch: 0,\n\n pre: version.pre.clone(),\n\n...
Rust
plotters/src/coord/ranged2d/cartesian.rs
facorread/plotters
f86adaec5236551d9be3adf5c631549a1bc1c977
/*! The 2-dimensional cartesian coordinate system. This module provides the 2D cartesian coordinate system, which is composed by two independent ranged 1D coordinate sepcification. This types of coordinate system is used by the chart constructed with [ChartBuilder::build_cartesian_2d](../../chart/ChartBuilder.htm...
/*! The 2-dimensional cartesian coordinate system. This module provides the 2D cartesian coordinate system, which is composed by two independent ranged 1D coordinate sepcification. This types of coordinate system is used by the chart constructed with [ChartBuilder::build_cartesian_2d](../../chart/ChartBuilder.htm...
?; } Ok(()) } pub fn get_x_range(&self) -> Range<X::ValueType> { self.logic_x.range() } pub fn get_y_range(&self) -> Range<Y::ValueType> { self.logic_y.range() } pub fn get_x_axis_pixel_range(&self) -> Range<i32> { self.logic_x.axis_pixe...
draw_mesh(MeshLine::YMesh( (self.back_x.0, y), (self.back_x.1, y), &logic_y, ))
call_expression
[ { "content": "/// Draw power function f(x) = x^power.\n\npub fn draw(canvas_id: &str, power: i32) -> DrawResult<impl Fn((i32, i32)) -> Option<(f32, f32)>> {\n\n let backend = CanvasBackend::new(canvas_id).expect(\"cannot find canvas\");\n\n let root = backend.into_drawing_area();\n\n let font: FontDesc...
Rust
src/fs/mmap.rs
Ryanmtate/future-aio
be6fd0ab83358c808248ffb7f2b5d127a3aaa4cc
use std::fs::OpenOptions; use std::io::Error as IoError; use std::path::Path; use std::sync::Arc; use std::sync::RwLock; use std::sync::RwLockReadGuard; use std::sync::RwLockWriteGuard; use memmap::Mmap; use memmap::MmapMut; use crate::task::spawn_blocking; use crate::fs::File; pub struct MemoryMappedMutFile(Arc<R...
use std::fs::OpenOptions; use std::io::Error as IoError; use std::path::Path; use std::sync::Arc; use std::sync::RwLock; use std::sync::RwLockReadGuard; use std::sync::RwLockWriteGuard; use memmap::Mmap; use memmap::MmapMut; use crate::task::spawn_blocking; use crate::fs::File; pub struct MemoryMappedMutFile(Arc<R...
fn from_mmap(mmap: Mmap) -> MemoryMappedFile { MemoryMappedFile(Arc::new(RwLock::new(mmap))) } pub fn inner(&self) -> RwLockReadGuard<Mmap> { self.0.read().unwrap() } } #[cfg(test)] mod tests { use std::env::temp_dir; use std::fs::File; use std::io::Error as IoErro...
pub async fn open<P>(path: P,min_len: u64) -> Result<(Self, File), IoError> where P: AsRef<Path> { let m_path = path.as_ref().to_owned(); let (m_map, mfile,_) = spawn_blocking (move || { let mfile = OpenOptions::new().read(true).open(&m_path).unwrap(); le...
function_block-full_function
[ { "content": "#[proc_macro_attribute]\n\npub fn test_async(_attr: TokenStream, item: TokenStream) -> TokenStream {\n\n\n\n let input = syn::parse_macro_input!(item as ItemFn);\n\n let name = &input.sig.ident;\n\n let sync_name = format!(\"{}_sync\",name);\n\n let out_fn_iden = Ident::new(&sync_name,...
Rust
src/board.rs
jstnlef/rustris
0133b9e43c22cf26f640da8e74cef9c365c5b7ad
use std::collections::VecDeque; use piston_window::{Context, G2d, Line, Transformed, types, Rectangle}; use piston_window::rectangle; use piston_window::grid::Grid; use colors::GREY; use tetromino::{Piece, Block}; use settings::*; type GridRow = [CellState; WIDTH_IN_BLOCKS as usize]; pub struct Board { grid: V...
use std::collections::VecDeque; use piston_window::{Context, G2d, Line, Transformed, types, Rectangle}; use piston_window::rectangle; use piston_window::grid::Grid; use colors::GREY; use tetromino::{Piece, Block}; use settings::*; type GridRow = [CellState; WIDTH_IN_BLOCKS as usize]; pub struct Board { grid: V...
fn create_empty_row() -> GridRow { [CellState::Empty; WIDTH_IN_BLOCKS as usize] } fn row_is_empty(row: &GridRow) -> bool { row.iter().all(|&block| block == CellState::Empty) } fn row_is_complete(row: &GridRow) -> bool { row.iter().all(|&block| block != CellState::Empty) ...
fn create_empty_grid() -> VecDeque<GridRow> { let mut grid = VecDeque::with_capacity(HEIGHT_IN_BLOCKS as usize); for _ in 0..HEIGHT_IN_BLOCKS { grid.push_back(Self::create_empty_row()); } grid }
function_block-full_function
[ { "content": "pub fn set_ui(ref mut ui: UICell, game: &mut Rustris) {\n\n Canvas::new().flow_right(&[\n\n (LEFT_COLUMN, Canvas::new().color(color::DARK_CHARCOAL).pad(20.0)),\n\n (MIDDLE_COLUMN, Canvas::new().color(color::TRANSPARENT).length(300.0)),\n\n (RIGHT_COLUMN, Canvas::new().color...
Rust
src/text_input.rs
khyperia/scopie
af97b9e1286583c095f3e5f0c2665bdb326f8fe6
use crate::Result; use glutin::{self, event::VirtualKeyCode as Key}; use khygl::{render_text::TextRenderer, render_texture::TextureRenderer, Rect}; use std::{convert::TryInto, mem::replace}; pub struct TextInput { old_inputs: Vec<String>, old_input_index: usize, input_text: String, message: String...
use crate::Result; use glutin::{self, event::VirtualKeyCode as Key}; use khygl::{render_text::TextRenderer, render_texture::TextureRenderer, Rect}; use std::{convert::TryInto, mem::replace}; pub struct TextInput { old_inputs: Vec<String>, old_input_index: usize, input_text: String, message: String...
}
pub fn render( &mut self, texture_renderer: &TextureRenderer, text_renderer: &mut TextRenderer, screen_size: (usize, usize), ) -> Result<usize> { let input_pos_y = screen_size.1 as isize - text_renderer.spacing as isize - 1; let input_pos_y = input_pos_y.try_into().un...
function_block-full_function
[ { "content": "pub fn autoconnect(live: bool) -> Result<Camera> {\n\n init_qhyccd_resource();\n\n let mut best = None;\n\n for id in 0..Camera::num_cameras() {\n\n let info = CameraInfo::new(id)?;\n\n let is163 = info.name.contains(\"163\");\n\n if best.is_none() || is163 {\n\n ...
Rust
src/app/lua/render.rs
nokevair/nokevair
40494bbe843394f3757f0f525bdcac5acfda4538
use hyper::{Response, Body}; use rlua::Value as LV; use std::fs; use std::path::PathBuf; use crate::conv; use crate::utils::SourceChain; use super::{Ctx, Version, Result, AppState}; pub fn with_entries<F: FnMut(String, PathBuf)>(app_ctx: &Ctx, mut f: F) { let dir = match fs::read_dir(&app_ctx.cfg.paths.re...
use hyper::{Response, Body}; use rlua::Value as LV; use std::fs; use std::path::PathBuf; use crate::conv; use crate::utils::SourceChain; use super::{Ctx, Version, Result, AppState}; pub fn with_entries<F: FnMut(String, PathBuf)>(app_ctx: &Ctx, mut f: F) { let dir = match fs::read_dir(&app_ctx.cfg.paths.re...
ocus.lua"); let code = match fs::read_to_string(&path) { Ok(code) => code, Err(e) => { app_ctx.log.err(format_args!( "failed to read file '{}': {}", path.display(), e ...
; self.lua.context(|ctx| ctx.expire_registry_values()); } pub(super) fn load_focuses(&mut self, app_ctx: &Ctx) { with_entries(app_ctx, |name, mut path| { path.push("f
random
[]
Rust
src/bin/debugger.rs
Hexilee/tifs
184363cf1cc8ece62421d376d8cd97eb001b25a8
use std::fmt::Debug; use std::io::{stdin, stdout, BufRead, BufReader, Write}; use anyhow::{anyhow, Result}; use clap::{crate_version, App, Arg}; use tifs::fs::inode::Inode; use tifs::fs::key::{ScopedKey, ROOT_INODE}; use tifs::fs::tikv_fs::TiFs; use tifs::fs::transaction::Txn; use tikv_client::TransactionClient; use t...
use std::fmt::Debug; use std::io::{stdin, stdout, BufRead, BufReader, Write}; use anyhow::{anyhow, Result}; use clap::{crate_version, App, Arg}; use tifs::fs::inode::Inode; use tifs::fs::key::{ScopedKey, ROOT_INODE}; use tifs::fs::tikv_fs::TiFs; use tifs::fs::transaction::Txn; use tikv_client::TransactionClient; use t...
=> return Ok(true), "reset" => self.reset(txn).await?, "get" => self.get_block(txn, &commands[1..]).await?, "get_str" => self.get_block_str(txn, &commands[1..]).await?, "get_attr" => self.get_attr(txn, &commands[1..]).await?, "get_raw" => self.get_attr_raw(tx...
_name("ENDPOINTS") .default_value("127.0.0.1:2379") .help("set all pd endpoints of the tikv cluster") .takes_value(true), ) .get_matches(); tracing_subscriber::fmt() .with_env_filter(EnvFilter::from_default_env()) .try_init() ....
random
[ { "content": "fn default_tls_config_path() -> anyhow::Result<PathBuf> {\n\n Ok(DEFAULT_TLS_CONFIG_PATH.parse()?)\n\n}\n\n\n\nmacro_rules! define_options {\n\n {\n\n $name: ident ($type: ident) {\n\n $(builtin $($optname: literal)? $opt: ident,)*\n\n $(define $($newoptname: lit...
Rust
src/service.rs
wpbrown/ntex-mqtt
be783119479e532705848ee224297a19ec524184
use std::task::{Context, Poll}; use std::{fmt, future::Future, marker::PhantomData, pin::Pin, rc::Rc}; use ntex::codec::{AsyncRead, AsyncWrite, Decoder, Encoder}; use ntex::service::{IntoServiceFactory, Service, ServiceFactory}; use ntex::time::{Millis, Seconds, Sleep}; use ntex::util::{select, Either, Pool}; use sup...
use std::task::{Context, Poll}; use std::{fmt, future::Future, marker::PhantomData, pin::Pin, rc::Rc}; use ntex::codec::{AsyncRead, AsyncWrite, Decoder, Encoder}; use ntex::service::{IntoServiceFactory, Service, ServiceFactory}; use ntex::time::{Millis, Seconds, Sleep}; use ntex::util::{select, Either, Pool}; use sup...
{:?}", e); e })?; log::trace!("Connection handshake succeeded"); let handler = handler.new_service(st).await?; log::trace!("Connection handler is created, starting dispatcher"); (io, state, codec, ka, handler) ...
l, time: Timer, _t: PhantomData<(St, Io, Codec)>, } impl<St, C, T, Io, Codec> Service for FramedServiceImpl<St, C, T, Io, Codec> where Io: AsyncRead + AsyncWrite + Unpin + 'static, C: Service<Request = Io, Response = (Io, State, Codec, St, Seconds)>, C::Error: fmt::Debug, C::Future: 'static, ...
random
[ { "content": "struct DispatcherState<S: Service, U: Encoder + Decoder> {\n\n error: Option<IoDispatcherError<S::Error, <U as Encoder>::Error>>,\n\n base: usize,\n\n queue: VecDeque<ServiceResult<Result<S::Response, S::Error>>>,\n\n}\n\n\n", "file_path": "src/io.rs", "rank": 0, "score": 2365...
Rust
imxrt1062-pac/imxrt1062-dmamux/src/chcfg.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register CHCFG[%s]"] pub type R = crate::R<u32, super::CHCFG>; #[doc = "Writer for register CHCFG[%s]"] pub type W = crate::W<u32, super::CHCFG>; #[doc = "Register CHCFG[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::CHCFG { type Type = u32; #[inline(always)] fn reset_va...
#[doc = "Reader of register CHCFG[%s]"] pub type R = crate::R<u32, super::CHCFG>; #[doc = "Writer for register CHCFG[%s]"] pub type W = crate::W<u32, super::CHCFG>; #[doc = "Register CHCFG[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::CHCFG { type Type = u32; #[inline(always)] fn reset_va...
L_0) } #[doc = "DMA Mux channel is enabled"] #[inline(always)] pub fn enbl_1(self) -> &'a mut W { self.variant(ENBL_A::ENBL_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] ...
(Normal mode)"] #[inline(always)] pub fn trig_0(self) -> &'a mut W { self.variant(TRIG_A::TRIG_0) } #[doc = "Triggering is enabled. If triggering is enabled and ENBL is set, the DMA_CH_MUX is in Periodic Trigger mode."] #[inline(always)] pub fn trig_1(self) -> &'a mut W { self.va...
random
[ { "content": "/// Migrate the `lib.rs` of the PAC subscrate, adding\n\n/// our necessary header to the top of the file.\n\nfn write_lib<R: Read>(crate_path: &Path, mut src: R) {\n\n static LIB_PRELUDE: &str = r#\"#![deny(warnings)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(clippy::all)]\n\n#![no_std]\n\...
Rust
all-crate-storage/blob_storage.rs
est31/cargo-local-serve
eabb70eb45ce390d927a781b2a24bbd9101df52f
use std::io::{Read, Write, Seek, SeekFrom, Result as IoResult, ErrorKind}; use std::collections::HashMap; use std::collections::hash_map::Entry; use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; use super::hash_ctx::Digest; pub struct BlobStorage<S> { blob_offsets :HashMap<Digest, u64>, pub name_inde...
use std::io::{Read, Write, Seek, SeekFrom, Result as IoResult, ErrorKind}; use std::collections::HashMap; use std::collections::hash_map::Entry; use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; use super::hash_ctx::Digest; pub struct BlobStorage<S> { blob_offsets :HashMap<Digest, u64>, pub name_inde...
&mut d)); let s = String::from_utf8(s_bytes).unwrap(); nidx.insert(s, d); } Ok(nidx) } fn write_name_idx<W :Write>(mut wtr :W, nidx :&HashMap<String, Digest>) -> IoResult<()> { try!(wtr.write_u64::<BigEndian>(nidx.len() as u64)); for (s,d) in nidx.iter() { try!(write_delim_byte_slice(&mut wtr, s.as_bytes()...
est_to_multi_blob, storage, index_offset, }) } pub fn has(&self, digest :&Digest) -> bool { self.blob_offsets.get(digest).is_some() } pub fn get(&mut self, digest :&Digest) -> IoResult<Option<Vec<u8>>> { let blob_offs = match self.blob_offsets.get(digest) { Some(d) => *d, None => return Ok(None)...
random
[ { "content": "fn handle_blocking_task<ET :FnMut(ParallelTask), S :Read + Seek + Write>(task :BlockingTask,\n\n\t\tblob_store :&mut BlobStorage<S>, blobs_to_store :&mut HashSet<Digest>,\n\n\t\tmut emit_task :ET) {\n\n\tmatch task {\n\n\t\tBlockingTask::StoreCrateUndeduplicated(crate_file_name, crate_blob) => {\n...
Rust
chain/cosmos/src/adapter.rs
Perpetual-Altruism-Ltd/graph-node
abbb2d04713d9e988419814d2e6ca433ee165bd1
use std::collections::HashSet; use prost::Message; use prost_types::Any; use crate::capabilities::NodeCapabilities; use crate::{data_source::DataSource, Chain}; use graph::blockchain as bc; use graph::firehose::EventTypeFilter; use graph::prelude::*; const EVENT_TYPE_FILTER_TYPE_URL: &str = "type.googleapis.com/...
use std::collections::HashSet; use prost::Message; use prost_types::Any; use crate::capabilities::NodeCapabilities; use crate::{data_source::DataSource, Chain}; use graph::blockchain as bc; use graph::firehose::EventTypeFilter; use graph::prelude::*; const EVENT_TYPE_FILTER_TYPE_URL: &str = "type.googleapis.com/...
vent_types: event_types.iter().map(ToString::to_string).collect(), }, block_filter: CosmosBlockFilter { trigger_every_block, }, } } } fn event_type_filter_with(event_types: &[&str]) -> EventTypeFilter { EventTypeFil...
(TriggerFilter::test_new(true, &["event_1", "event_2"]), None), ( TriggerFilter::test_new(false, &["event_1", "event_2", "event_3"]), Some(event_type_filter_with(&["event_1", "event_2", "event_3"])), ), ]; for (trigger_filter, expected_filter) i...
random
[ { "content": "pub fn place(name: &str) -> Result<Option<(Vec<Shard>, Vec<NodeId>)>, String> {\n\n CONFIG.deployment.place(name, NETWORK_NAME)\n\n}\n\n\n\npub async fn create_subgraph(\n\n subgraph_id: &DeploymentHash,\n\n schema: &str,\n\n base: Option<(DeploymentHash, BlockPtr)>,\n\n) -> Result<Dep...
Rust
sudachi/src/dic/build/conn.rs
bignumorg/sudachi.rs
df9997ed6b95af8dc9f9cc77c60c359b78a7105b
/* * Copyright (c) 2021 Works Applications Co., Ltd. * * 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 ...
/* * Copyright (c) 2021 Works Applications Co., Ltd. * * 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 ...
self.matrix[index] = bytes[0]; self.matrix[index + 1] = bytes[1]; Ok(()) } } fn num_error<T>(part: &'static str, value: i16) -> SudachiResult<T> { return Err(DicBuildError { file: "<connection>".to_owned(), line: 0, cause: BuildFailure::InvalidConnSize(part, value), ...
t index = right as usize * self.num_left as usize + left as usize; let index = index * 2; let bytes = cost.to_le_bytes();
function_block-random_span
[ { "content": "pub fn dictionary_bytes_from_path<P: AsRef<Path>>(dictionary_path: P) -> SudachiResult<Vec<u8>> {\n\n let dictionary_path = dictionary_path.as_ref();\n\n let dictionary_stat = fs::metadata(&dictionary_path)?;\n\n let mut dictionary_file = File::open(dictionary_path)?;\n\n let mut dicti...
Rust
miri/bin/miri.rs
oli-obk/miri
4654d6d04e2b2bf1fc72f6fe5a3c4353c560d2c6
#![feature(rustc_private, i128_type)] extern crate getopts; extern crate miri; extern crate rustc; extern crate rustc_driver; extern crate rustc_errors; extern crate env_logger; extern crate log_settings; extern crate syntax; extern crate log; use rustc::session::Session; use rustc::middle::cstore::CrateStore; use ru...
#![feature(rustc_private, i128_type)] extern crate getopts; extern crate miri; extern crate rustc; extern crate rustc_driver; extern crate rustc_errors; extern crate env_logger; extern crate log_settings; extern crate syntax; extern crate log; use rustc::session::Session; use rustc::middle::cstore::CrateStore; use ru...
up or multirust", ) .to_owned() } } } fn main() { init_logger(); let mut args: Vec<String> = std::env::args().collect(); let sysroot_flag = String::from("--sysroot"); if !args.contains(&sysroot_flag) { args.push(sysroot_flag); args.push(find_...
OT") { return sysroot; } let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME")); let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN")); match (home, toolchain) { (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, too...
function_block-random_span
[ { "content": "fn after_analysis<'a, 'tcx>(state: &mut CompileState<'a, 'tcx>) {\n\n state.session.abort_if_errors();\n\n\n\n let tcx = state.tcx.unwrap();\n\n let limits = Default::default();\n\n\n\n if std::env::args().any(|arg| arg == \"--test\") {\n\n struct Visitor<'a, 'tcx: 'a>(miri::Res...
Rust
src/profiles.rs
rafamatias/rogcat
d90d1e02784b965c49e6ea67815e60b5c11a0e76
use clap::ArgMatches; use failure::{err_msg, Error}; use std::collections::HashMap; use std::convert::Into; use std::env::var; use std::fs::File; use std::io::prelude::*; use std::ops::AddAssign; use std::path::PathBuf; use toml::{from_str, to_string}; const EXTEND_LIMIT: u32 = 1000; #[derive(Clone, Debug, Default,...
use clap::ArgMatches; use failure::{err_msg, Error}; use std::collections::HashMap; use std::convert::Into; use std::env::var; use std::fs::File; use std::io::prelude::*; use std::ops::AddAssign; use std::path::PathBuf; use toml::{from_str, to_string}; const EXTEND_LIMIT: u32 = 1000; #[derive(Clone, Debug, Default,...
Ok(Profiles { file, profile, profiles, }) } } fn expand(n: &str, p: &mut Profile, a: &HashMap<String, Profile>) -> Result<(), Error> { let mut loops = EXTEND_LIMIT; while !p.extends.is_empty() { let ex...
if let Some(n) = args.value_of("profile") { profile = profiles .get(n) .ok_or_else(|| format_err!("Unknown profile {}", n))? .clone(); Self::expand(n, &mut profile, &profiles)?; }
if_condition
[ { "content": "pub fn file_content(file: &PathBuf) -> Result<SVec, Error> {\n\n let content = BufReader::new(File::open(file)?)\n\n .lines()\n\n .map(|e| e.unwrap())\n\n .collect();\n\n Ok(content)\n\n}\n\n\n", "file_path": "src/tests/utils.rs", "rank": 0, "score": 187593.4...
Rust
src/yuv444i/mod.rs
dunkelstern/grapho-bitplane
4db3789284fa89c85e6b1b1c972aa4d42eda9bbf
use crate::*; pub use grapho_color::DigitalYCbCrColor; pub use crate::yuv422i::YUVComponent; #[derive(Debug, PartialEq)] pub struct YUV444iPixelBuffer<'a> { width: usize, height: usize, stride: usize, fourcc: &'a str, component_order: Vec<YUVComponent>, data: Vec<u8> } impl<'a> YUV444iPixelB...
use crate::*; pub use grapho_color::DigitalYCbCrColor; pub use crate::yuv422i::YUVComponent; #[derive(Debug, PartialEq)] pub struct YUV444iPixelBuffer<'a> { width: usize, height: usize, stride: usize, fourcc: &'a str, component_order: Vec<YUVComponent>, data: Vec<u8> } impl<'a> YUV444iPixelB...
fn new_with_data(width: usize, height: usize, data: Vec<u8>, stride: Option<usize>, fourcc: Option<&'a str>) -> Result<Self, PixelBufferError> { let f = fourcc.unwrap_or("YUV444"); le...
fn new(width: usize, height: usize, stride: Option<usize>, fourcc: Option<&'a str>) -> Self { let f = fourcc.unwrap_or("YUV444"); let component_order = YUV444iPixelBuffer::decode_component_order(f); let line_width = stride.unwrap_or(width * 3); YUV444iPixelBuffer { width, ...
function_block-full_function
[ { "content": "/// Pixel buffer trait, all Pixel buffers will implement this\n\npub trait PixelBuffer<'a>: Sized + IntoIterator\n\n // + Sub + Mul + Add + Div + SubAssign + MulAssign + AddAssign + DivAssign\n\n{\n\n /// The color type this pixel buffer contains\n\n type ColorType;\n\n\n\n /// Create ...
Rust
src/main.rs
kurtbuilds/checkexec
22af898b48c2c10432762406c4ec4b714995f5f2
use std::borrow::Cow; use std::fmt::{Display}; use std::path::{Path}; use std::process::{exit, Command}; use clap::{App, AppSettings, Arg}; use std::fs; use shell_escape::escape; const VERSION: &str = env!("CARGO_PKG_VERSION"); struct Error { message: String, } impl std::fmt::Debug for Error { fn fmt(&self,...
use std::borrow::Cow; use std::fmt::{Display}; use std::path::{Path}; use std::process::{exit, Command}; use clap::{App, AppSettings, Arg}; use std::fs; use shell_escape::escape; const VERSION: &str = env!("CARGO_PKG_VERSION"); struct Error { message: String, } impl std::fmt::Debug for Error { fn fmt(&self,...
#[cfg(test)] mod test { use std::io::Write; use super::*; use tempfile::{TempDir, tempdir}; struct TempFiles { #[allow(dead_code)] dir: TempDir, pub files: Vec<String>, } fn touch(path: &str) -> std::io::Result<()> { let mut file = fs::File::create(path).unwra...
get_matches(); let verbose = args.is_present("verbose"); let target = args.value_of("target").unwrap(); let command_args = args.values_of("command").unwrap().into_iter().skip(1).collect::<Vec<&str>>(); let dependencies = if args.is_present("infer") { infer_dependencies(&command_args)? } el...
function_block-function_prefix_line
[ { "content": "<div id=\"top\"></div>\n\n\n\n<p align=\"center\">\n\n<a href=\"https://github.com/kurtbuilds/checkexec/graphs/contributors\">\n\n <img src=\"https://img.shields.io/github/contributors/kurtbuilds/checkexec.svg?style=flat-square\" alt=\"GitHub Contributors\" />\n\n</a>\n\n<a href=\"https://githu...
Rust
shapes/src/plymesh.rs
hackmad/pbr_rust
b7ae75564bf71c4dfea8b20f49d05ac1b89e6734
#![allow(dead_code)] use super::TriangleMesh; use core::geometry::*; use core::paramset::*; use core::texture::FloatTextureMap; use ply_rs::parser::Parser; use ply_rs::ply::*; use std::fs::File; use std::io::BufReader; use std::sync::Arc; use textures::ConstantTexture; pub struct PLYMesh; impl PLYMesh { ...
#![allow(dead_code)] use super::TriangleMesh; use core::geometry::*; use core::paramset::*; use core::texture::FloatTextureMap; use ply_rs::parser::Parser; use ply_rs::ply::*; use std::fs::File; use std::io::BufReader; use std::sync::Arc; use textures::ConstantTexture; pub struct PLYMesh; impl PLYMesh { ...
} struct Vertex { point: Point3f, normal: Normal3f, uv: Point2f, has_normal: bool, has_uv: bool, } impl Vertex { fn new(point: Point3f, normal: Normal3f, uv: Point2f, has_normal: bool, has_uv: bool) -> Self { Self { point, normal, uv, ha...
else if let Property::ListUInt(vi) = value { if vi.len() != 3 && vi.len() != 4 { panic!("Only triangles and quads are supported!"); } if vi.len() >= 3 { vertex_indices.push(vi[0] as usize); ...
function_block-function_prefix_line
[]
Rust
examples/custom_router/src/router/mod.rs
arn-the-long-beard/old_seed_archive
9aed8e64ab6ee5a2a6e9fd650eefb752fcb9144c
mod model; mod path; mod url; mod view; use seed::Url; use std::fmt::Debug; pub use {model::*, path::*, path::*, url::*, url::*, view::*}; use seed::{*, *}; struct_urls!(); impl<'a> Urls<'a> { pub fn build_url(self, segments: Vec<&str>) -> Url { self.base_url().set_path(segments) } } pub enum Move ...
mod model; mod path; mod url; mod view; use seed::Url; use std::fmt::Debug; pub use {model::*, path::*, path::*, url::*, url::*, view::*}; use seed::{*, *}; struct_urls!(); impl<'a> Urls<'a> { pub fn build_url(self, segments: Vec<&str>) -> Url { self.base_url().set_path(segments) } } pub enum Move ...
fn reload_without_cache() {} pub fn navigate_to_new(&mut self, route: &Routes) { self.current_route = Some(route.clone()); self.push_to_history(route.clone()); } fn navigate_to_url(&mut self, url: Url) { let path = &mut url.to_string(); p...
pub fn is_current_route(&self, route: &Routes) -> bool { if let Some(current_route) = &self.current_route { route.eq(&current_route) } else { false } }
function_block-full_function
[ { "content": "pub fn init(url: Url, model: &mut Model, id: &String, orders: &mut impl Orders<Msg>) -> Model {\n\n Model {}\n\n}\n\n\n\npub struct Model {}\n\npub enum Msg {}\n", "file_path": "examples/custom_router/tests/routing_module/pages/profile.rs", "rank": 0, "score": 480232.6109669417 },...
Rust
src/ui/app.rs
xfbs/afp
0bd950504f24e2c762029b83f1c5142a6973664c
extern crate gio; extern crate gtk; use crate::ui::*; use gio::prelude::*; use gtk::prelude::*; use std::cell::RefCell; use std::env; use std::rc::Rc; const STYLE: &'static str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/data/style.css")); #[derive(Clone)] pub struct App { app: gtk::Application, win...
extern crate gio; extern crate gtk; use crate::ui::*; use gio::prelude::*; use gtk::prelude::*; use std::cell::RefCell; use std::env; use std::rc::Rc; const STYLE: &'static str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/data/style.css")); #[derive(Clone)] pub struct App { app: gtk::Application, win...
if let Some(window) = app.window.borrow().as_ref() { dialog.set_transient_for(Some(window)); } dialog.run(); dialog.destroy(); }); self.app.add_action(&quit); self.app.add_action(&about); } pub fn init(&self) { let ap...
; let app = self.clone(); quit.connect_activate(move |_, _| { if let Some(window) = app.window.borrow().clone() { window.destroy(); } }); let about = gio::SimpleAction::new("about", None); let app = self.clone(); about.connect_acti...
random
[ { "content": "#[test]\n\nfn test_load_file() {\n\n let mut d = std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n\n d.push(\"test/datastore.yaml\");\n\n\n\n let ds = DataStore::load(&d);\n\n assert!(ds.is_ok());\n\n let ds = ds.ok().unwrap();\n\n assert_eq!(&ds.filename, &d);\n\n}\n\n\n...
Rust
hphp/hack/src/rupro/lib/shallow_decl_provider/provider.rs
ianhoffman/hhvm
decc4e479e0e689c65f936f0828cb761d34075b1
use std::rc::Rc; use std::{fs, io}; use bumpalo::Bump; use crate::decl_defs::{ShallowClass, ShallowFun, ShallowMethod}; use crate::decl_ty_provider::DeclTyProvider; use crate::pos::{RelativePath, RelativePathCtx, Symbol}; use crate::reason::Reason; use crate::shallow_decl_provider::ShallowDeclCache; #[derive(Debug...
use std::rc::Rc; use std::{fs, io}; use bumpalo::Bump; use crate::decl_defs::{ShallowClass, ShallowFun, ShallowMethod}; use crate::decl_ty_provider::DeclTyProvider; use crate::pos::{RelativePath, RelativePathCtx, Symbol}; use crate::reason::Reason; use crate::shallow_decl_provider::ShallowDeclCache; #[derive(Debug...
}
l_ty_provider; ShallowFun { fe_pos: decl_tys.get_pos_provider().mk_pos_of_ref::<R>(sf.pos), fe_type: decl_tys.mk_decl_ty_from_parsed(sf.type_), } }
function_block-function_prefixed
[]
Rust
src/input/system.rs
alanpoon/crayon
ab320e4cab285e1baee802363f024235883f8aef
use std::sync::{Arc, RwLock}; use crate::application::prelude::{LifecycleListener, LifecycleListenerHandle}; use crate::window::prelude::{Event, EventListener, EventListenerHandle}; use super::events::InputEvent; use super::keyboard::{Key, Keyboard}; use super::mouse::{Mouse, MouseButton}; use super::touchpad::{Gestu...
use std::sync::{Arc, RwLock}; use crate::application::prelude::{LifecycleListener, LifecycleListenerHandle}; use crate::window::prelude::{Event, EventListener, EventListenerHandle}; use super::events::InputEvent; use super::keyboard::{Key, Keyboard}; use super::mouse::{Mouse, MouseButton}; use super::touchpad::{Gestu...
b fn key_presses(&self) -> FastHashSet<Key> { self.state.keyboard.read().unwrap().key_presses() } #[inline] pub fn is_key_release(&self, key: Key) -> bool { self.state.keyboard.read().unwrap().is_key_release(key) } #[inline] pub fn key_releases(&self) -> FastHashSet<Key> { ...
).reset(); *self.state.touch_emulation_button.write().unwrap() = None; } #[inline] pub fn has_keyboard_attached(&self) -> bool { true } #[inline] pub fn is_key_down(&self, key: Key) -> bool { self.state.keyboard.read().unwrap().is_key_down(key) }...
random
[ { "content": "#[inline]\n\npub fn is_mouse_down(button: MouseButton) -> bool {\n\n ctx().is_mouse_down(button)\n\n}\n\n\n\n/// Checks if a mouse button has been pressed during last frame.\n", "file_path": "src/input/mod.rs", "rank": 0, "score": 293791.80774219765 }, { "content": "#[inline...
Rust
tremor-script/src/ast/support.rs
0xd34b33f/tremor-runtime
73af8033509e224e4cbf078559f27bec4c12cf3d
#![cfg_attr(tarpaulin, skip)] use super::{ BinOpKind, EventPath, Invoke, InvokeAggr, InvokeAggrFn, LocalPath, MetadataPath, Segment, StatePath, UnaryOpKind, }; use std::fmt; impl<'script> fmt::Debug for InvokeAggrFn<'script> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "fn(...
#![cfg_attr(tarpaulin, skip)] use super::{ BinOpKind, EventPath, Invoke, InvokeAggr, InvokeAggrFn, LocalPath, MetadataPath, Segment, StatePath, UnaryOpKind, }; use std::fmt; impl<'script> fmt::Debug for InvokeAggrFn<'script> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "fn(...
} impl fmt::Display for BinOpKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.operator_name()) } } impl UnaryOpKind { fn operator_name(self) -> &'static str { match self { Self::Plus => "+", Self::Minus => "-", Self::Not =>...
Self::Eq => "==", Self::NotEq => "!=", Self::Gte => ">=", Self::Gt => ">", Self::Lte => "<=", Self::Lt => "<", Self::RBitShiftSigned => ">>", Self::RBitShiftUnsigned => ">>>", Self::LBitShift => "<<", Self::Add =...
function_block-function_prefix_line
[]
Rust
src/core/image.rs
RahulDas-dev/ndarray-vision
fddbb85f67b2e9124a8c9582ecd775ff5d60a3e7
use crate::core::colour_models::*; use crate::core::traits::PixelBound; use ndarray::prelude::*; use ndarray::{s, Data, DataMut, OwnedRepr, RawDataClone, ViewRepr}; use num_traits::cast::{FromPrimitive, NumCast}; use num_traits::Num; use std::{fmt, hash, marker::PhantomData}; pub type Image<T, C> = ImageBase<OwnedRepr...
use crate::core::colour_models::*; use crate::core::traits::PixelBound; use ndarray::prelude::*; use ndarray::{s, Data, DataMut, OwnedRepr, RawDataClone, ViewRepr}; use num_traits::cast::{FromPrimitive, NumCast}; use num_traits::Num; use std::{fmt, hash, marker::PhantomData}; pub type Image<T, C> = ImageBase<OwnedRepr...
pub fn from_shape_data(rows: usize, cols: usize, data: Vec<T>) -> Image<T, C> { let data = Array3::from_shape_vec((rows, cols, C::channels()), data).unwrap(); Image { data, model: PhantomData, } } } impl<T, C> Image<T, C> where T: Clone + Nu...
n to_owned(&self) -> Image<T, C> { Image { data: self.data.to_owned(), model: PhantomData, } }
function_block-function_prefixed
[]
Rust
examples3/convex_decomposition.rs
BenBergman/nphysics
11ca4d6f967c35e7f51e65295174c5b0395cbd93
extern crate rand; extern crate kiss3d; extern crate nalgebra as na; extern crate ncollide; extern crate nphysics; extern crate nphysics_testbed3d; use std::sync::Arc; use std::path::Path; use rand::random; use na::{Pnt3, Vec3, Translation}; use kiss3d::loader::obj; use ncollide::shape::{Plane, Compound, Convex}; use ...
extern crate rand; extern crate kiss3d; extern crate nalgebra as na; extern crate ncollide; extern crate nphysics; extern crate nphysics_testbed3d; use std::sync::Arc; use std::path::Path; use rand::random; use na::{Pnt3, Vec3, Translation}; use kiss3d::loader::obj; use ncollide::shape::{Plane, Compound, Convex}; use ...
, "media/models/genus3.obj".to_string() , "media/models/genus3_decimated.obj".to_string() , "media/models/greek_sculpture_decimated.obj".to_string() , "media/models/hand2_decimated.obj".to_string() , "media/models/hand_decimated.obj".to_string() , "media/models/helix.obj"....
models/Hand1_decimated.obj".to_string() , "media/models/RSCREATURE_F_decimated.obj".to_string() , "media/models/Sketched-Brunnen_decimated.obj".to_string() , "media/models/Teapot_decimated.obj".to_string() , "media/models/block.obj".to_string() , "media/models/block_decimate...
function_block-random_span
[ { "content": "fn add_ragdoll(pos: Vec3<f32>, world: &mut World) {\n\n // head\n\n let head_geom = Ball::new(0.8);\n\n let mut head = RigidBody::new_dynamic(head_geom, 1.0, 0.3, 0.5);\n\n head.append_translation(&(pos + Vec3::new(0.0, 2.4, 0.0)));\n\n\n\n // body\n\n let body_geom ...
Rust
src/content/content_encoding.rs
felippemr/http-types
f77c653d6703192430b4ba8fb016fe17ba8d457f
use crate::content::{Encoding, EncodingProposal}; use crate::headers::{HeaderName, HeaderValue, Headers, ToHeaderValues, CONTENT_ENCODING}; use std::fmt::{self, Debug}; use std::ops::{Deref, DerefMut}; use std::option; pub struct ContentEncoding { inner: Encoding, } impl ContentEncoding { pub fn new(e...
use crate::content::{Encoding, EncodingProposal}; use crate::headers::{HeaderName, HeaderValue, Headers, ToHeaderValues, CONTENT_ENCODING}; use std::fmt::{self, Debug}; use std::ops::{Deref, DerefMut}; use std::option; pub struct ContentEncoding { inner: Encoding, } impl ContentEncoding { pub fn new(e...
TENT_ENCODING } pub fn value(&self) -> HeaderValue { self.inner.into() } pub fn encoding(&self) -> Encoding { self.inner } } impl ToHeaderValues for ContentEncoding { type Iter = option::IntoIter<HeaderValue>; fn to_header_values(&self) -> crate::Result<Self::Ite...
er = inner.expect("Headers instance with no entries found"); Ok(Some(Self { inner })) } pub fn apply(&self, mut headers: impl AsMut<Headers>) { headers.as_mut().insert(CONTENT_ENCODING, self.value()); } pub fn name(&self) -> HeaderName { CON
random
[ { "content": "#[inline]\n\npub fn powered_by(mut headers: impl AsMut<Headers>, value: Option<HeaderValue>) {\n\n let name = HeaderName::from_lowercase_str(\"X-Powered-By\");\n\n match value {\n\n Some(value) => {\n\n headers.as_mut().insert(name, value);\n\n }\n\n None => {...
Rust
sflk-lang/src/parser.rs
anima-libera/sflk
973e7435ec44e5d775aad5737ad3835b6558d0f2
use crate::ast::{Chop, Comment, Expr, Node, Program, Stmt, TargetExpr}; use crate::scu::{Loc, SourceCodeUnit}; use crate::tokenizer::{BinOp, CharReadingHead, Kw, Matched, StmtBinOp, Tok, Tokenizer}; use std::{collections::VecDeque, rc::Rc}; pub struct ParsingWarning { } pub struct TokBuffer { crh: CharReadingHead,...
use crate::ast::{Chop, Comment, Expr, Node, Program, Stmt, TargetExpr}; use crate::scu::{Loc, SourceCodeUnit}; use crate::tokenizer::{BinOp, CharReadingHead, Kw, Matched, StmtBinOp, Tok, Tokenizer}; use std::{collections::VecDeque, rc::Rc}; pub struct ParsingWarning { } pub struct TokBuffer { crh: CharReadingHead,...
le let Some(chop_node) = self.maybe_parse_chop(tb) { chops.push(chop_node); } if chops.is_empty() { expr_node } else { let loc = expr_node.loc() + chops.last().unwrap().loc(); Node::from( Expr::Chain { init: Box::new(expr_node), chops, }, loc, ) } } fn parse_expr_beg(&mut...
(); let expr_node = self.parse_expr(tb); let full_loc = &kw_loc + expr_node.loc(); Some(Node::from(Stmt::DoFileHere { expr: expr_node }, full_loc)) } Kw::If => { let kw_loc = first_loc.clone(); tb.disc(); let cond_expr_node = self.parse_expr(tb); let th_stmt_node = self.maybe_...
random
[ { "content": "struct Comments {\n\n\tleft_comments: Vec<Comment>,\n\n\tinternal_comments: Vec<Comment>,\n\n}\n\n\n\nimpl Comments {\n\n\tfn new() -> Comments {\n\n\t\tComments {\n\n\t\t\tleft_comments: Vec::new(),\n\n\t\t\tinternal_comments: Vec::new(),\n\n\t\t}\n\n\t}\n\n}\n\n\n\nimpl<T> Node<T> {\n\n\tpub fn ...
Rust
cubespin/src/mcube.rs
setekhid/tastes
923c3ececc02a0f6282b7507a861a4ed68b19314
#[derive(Hash, Eq, PartialEq, Debug)] pub struct StatT(pub [[i8; 9]; 6]); pub fn print(stat: &StatT) { let StatT(s) = *stat; println!(" {} {} {}", s[0][0], s[0][1], s[0][2]); println!(" {} {} {}", s[0][3], s[0][4], s[0][5]); println!(" {} {} {}", s[0][6], s[0][7], s[0][8]); pri...
#[derive(Hash, Eq, PartialEq, Debug)] pub struct StatT(pub [[i8; 9]; 6]); pub fn print(stat: &StatT) { let StatT(s) = *stat; println!(" {} {} {}", s[0][0], s[0][1], s[0][2]); println!(" {} {} {}", s[0][3], s[0][4], s[0][5]); println!(" {} {} {}", s[0][6], s[0][7], s[0][8]); pri...
); rlist.reverse(); for rlist_step in rlist { llist.push(-rlist_step); } Some(llist) }, None => None } } fn bfstep2list_hm(steps: Option<&Rc<BfsNode>>) -> Vec<i8> { match steps { Some(thing) => bfstep2list(Some(thing.clon...
Some(result) => return result, None => () } for _ in 0..16 { lleaves = expand_leaves(lleaves); match link_trees(&lleaves, &rleaves, check_linkage(&lleaves, &rleaves)) { Some(result) => return result, None => () } rleaves = expand_leaves(rleave...
random
[ { "content": "fn mcube_mix(stat: mcube::StatT, steps: &[i8]) -> mcube::StatT {\n\n let mut s = stat;\n\n for st in steps {\n\n s = mcube::spin(s, *st);\n\n }\n\n return s;\n\n}\n", "file_path": "cubespin/src/main.rs", "rank": 6, "score": 107929.81570244649 }, { "content": ...
Rust
src/sp_lib/datastore/history.rs
jrtabash/stock_portfolio
84dcb73dee43152b323159e780333d36ee23bfe3
use std::error::Error; use crate::util::datetime; use crate::util::datetime::LocalDate; use crate::util::price_type::PriceType; use crate::datastore::datastore::DataStore; pub type Price = PriceType; #[inline(always)] pub fn tag() -> &'static str { &"history" } pub struct HistoryEntry { pub date: LocalDate,...
use std::error::Error; use crate::util::datetime; use crate::util::datetime::LocalDate; use crate::util::price_type::PriceType; use crate::datastore::datastore::DataStore; pub type Price = PriceType; #[inline(always)] pub fn tag() -> &'static str { &"history" } pub struct HistoryEntry { pub date: LocalDate,...
hist = History::parse_filter_csv("AAPL", &csv, |entry| entry.date > datetime::make_date(2021, 2, 24)).unwrap(); assert_eq!(hist.symbol(), "AAPL"); assert_eq!(hist.count(), 2); let entries = hist.entries(); check_entry(&entries[0], datetime::make_date(2021, 2, 25), 26.1, 31.0, 22.0, 24.0...
) || line.starts_with(char::is_alphabetic) { continue; } let entry = HistoryEntry::parse_csv(line)?; if pred(&entry) { hist.entries.push(entry); } } Ok(hist) } pub fn ds_select_all(ds: &DataStore, symbol: &str) -> R...
random
[ { "content": "pub fn update_stock_from_csv(stock: &mut Stock, csv: &str) -> Result<bool, Box<dyn Error>> {\n\n let hist = History::parse_csv(&stock.symbol, csv)?;\n\n if hist.count() > 0 {\n\n let latest = &hist.entries()[hist.count() - 1];\n\n if latest.adj_close > 0.0 {\n\n stoc...
Rust
src/main.rs
miyachan/lnx
a0fed83e43df6b898ff4d85dfb0f6ecd844af04c
#[macro_use] extern crate log; #[macro_use] extern crate serde_json; use std::fs::File; use std::io::BufReader; use std::sync::Arc; use anyhow::{Error, Result}; use axum::handler::{delete, get, post, Handler}; use axum::http::header; use axum::Router; use fern::colors::{Color, ColoredLevelConfig}; use hyper::http::H...
#[macro_use] extern crate log; #[macro_use] extern crate serde_json; use std::fs::File; use std::io::BufReader; use std::sync::Arc; use anyhow::{Error, Result}; use axum::handler::{delete, get, post, Handler}; use axum::http::header; use axum::Router; use fern::colors::{Color, ColoredLevelConfig}; use hyper::http::H...
fn tls_server_config(key: &str, cert: &str) -> Result<Arc<ServerConfig>> { let mut config = ServerConfig::new(NoClientAuth::new()); let mut key_reader = BufReader::new(File::open(key)?); let mut cert_reader = BufReader::new(File::open(cert)?); let key = pkcs8_private_keys(&mut key_reader) .m...
files(settings: &Settings) -> Result<Option<Arc<ServerConfig>>> { match (&settings.tls_key_file, &settings.tls_cert_file) { (Some(fp1), Some(fp2)) => Ok(Some(tls_server_config(fp1, fp2)?)), (None, None) => Ok(None), _ => { return Err(Error::msg( "missing a require...
function_block-function_prefixed
[ { "content": "fn main() -> Result<()> {\n\n // Tell Cargo that if the given file changes, to rerun this build script.\n\n println!(\"cargo:rerun-if-changed=./datasets\");\n\n\n\n let _ = fs::remove_dir_all(\"./_dist\");\n\n fs::create_dir_all(\"./_dist\")?;\n\n\n\n compress_frequency_dicts()?;\n\...
Rust
src/forex.rs
iamsauravsharma/alpha_vantage
80fbfb6ea798c4f80b0151d8c6b85ff4793cbe0d
use std::collections::HashMap; use serde::Deserialize; use crate::{ api::{ApiClient, OutputSize, TimeSeriesInterval}, deserialize::from_str, error::{detect_common_helper_error, Error, Result}, }; #[derive(Debug, Clone, Default)] struct MetaData { information: String, from_symbol: String, to...
use std::collections::HashMap; use serde::Deserialize; use crate::{ api::{ApiClient, OutputSize, TimeSeriesInterval}, deserialize::from_str, error::{detect_common_helper_error, Error, Result}, }; #[derive(Debug, Clone, Default)] struct MetaData { information: String, from_symbol: String, to...
fn latestn(&self, n: usize) -> Result<Vec<Entry>> { let mut time_list = Vec::new(); for entry in self { time_list.push(entry.time.clone()); } time_list.sort(); time_list.reverse(); let time_list_count: usize = time_list.len(); let mut full_list =...
let mut latest = Entry::default(); let mut new_time = String::new(); for entry in self { if new_time < entry.time { latest = entry.clone(); new_time = entry.time.clone(); } } latest }
function_block-function_prefix_line
[ { "content": "// convert str which has percent form to f64 val\n\nfn convert_str_percent_f64(val: &str) -> f64 {\n\n let mut s = val.to_owned();\n\n s.pop();\n\n s.trim().parse::<f64>().unwrap()\n\n}\n\n\n\n/// Builder to create new Sector\n\npub struct SectorBuilder<'a> {\n\n api_client: &'a ApiCli...
Rust
src/connectivity/wlan/lib/common/rust/src/test_utils/fake_stas.rs
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
use { crate::{ ie::{self, IeType}, mac, test_utils::fake_frames::{ fake_eap_rsne, fake_wpa1_ie, fake_wpa2_enterprise_rsne, fake_wpa2_legacy_rsne, fake_wpa2_mixed_rsne, fake_wpa2_rsne, fake_wpa2_wpa3_rsne, fake_wpa3_enterprise_192_bit_rsne, fake_wpa3_rsne...
use { crate::{ ie::{self, IeType}, mac, test_utils::fake_frames::{ fake_eap_rsne, fake_wpa1_ie, fake_wpa2_enterprise_rsne, fake_wpa2_legacy_rsne, fake_wpa2_mixed_rsne, fake_wpa2_rsne, fake_wpa2_wpa3_rsne, fake_wpa3_enterprise_192_bit_rsne, fake_wpa3_rsne...
0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x08, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x40, 0xbf, 0x0c, 0x91, 0x59, 0x82, 0x0f, 0xea, ...
:ident $(, $bss_key:ident: $bss_value:expr)* $(,)?) => {{ let fidl_bss = $crate::fake_fidl_bss!($protection_type $(, $bss_key: $bss_value)*); let bss = $crate::bss::BssDescription::from_fidl(fidl_bss) .expect("expect BSS conversion to succeed"); bss }} } #[cfg(tests)] mod tests ...
random
[]
Rust
src/port.rs
carlosmn/gphoto-rs
faf9dbb972c5d66f77d1265cd959314e6283fae1
use std::borrow::Cow; use std::ffi::{CStr, CString}; use std::marker::PhantomData; use std::mem; use ::libc::c_void; #[derive(Debug,PartialEq,Eq,Clone,Copy,Hash)] pub enum PortType { Serial, USB, Disk, PTPIP, Direct, SCSI, Other, } pub struct Port<...
use std::borrow::Cow; use std::ffi::{CStr, CString}; use std::marker::PhantomData; use std::mem; use ::libc::c_void; #[derive(Debug,PartialEq,Eq,Clone,Copy,Hash)] pub enum PortType { Serial, USB, Disk, PTPIP, Direct, SCSI, Other, } pub struct Port<...
; Ok(idx as usize) } pub fn lookup_path(&mut self, path: &str) -> ::Result<usize> { let cpath = match CString::new(path) { Ok(s) => s, Err(_) => return Err(::error::from_libgphoto2(::gphoto2::GP_ERROR_BAD_PARAMETERS)), }; let idx...
match unsafe { ::gphoto2::gp_port_info_list_lookup_name(self.as_mut_ptr(), cname.as_ptr()) } { idx if idx >= 0 => idx, err => return Err(::error::from_libgphoto2(err)), }
if_condition
[ { "content": "/// Returns a structure with the version of the `libgphoto2` C library.\n\npub fn libgphoto2_version() -> LibraryVersion {\n\n LibraryVersion::new()\n\n}\n", "file_path": "src/version.rs", "rank": 2, "score": 62897.67397201661 }, { "content": "fn main() {\n\n let mut cont...
Rust
src/cai/uciv.rs
provotum/rust-crypto
3f284c3e6f3e3412a44d3cea11cd6487862c0d9f
use std::vec::Vec; use num::pow::Pow; use num::Zero; use std::ops::{Mul, Div, Sub, Add, Neg}; use ::arithmetic::mod_int::From; use ::arithmetic::mod_int::RandModInt; use ::arithmetic::mod_int::ModInt; use ::el_gamal::encryption::PublicKey; use ::el_gamal::ciphertext::CipherText; use ::el_gamal::serializer::Serializer...
use std::vec::Vec; use num::pow::Pow; use num::Zero; use std::ops::{Mul, Div, Sub, Add, Neg}; use ::arithmetic::mod_int::From; use ::arithmetic::mod_int::RandModInt; use ::arithmetic::mod_int::ModInt; use ::el_gamal::encryption::PublicKey; use ::el_gamal::ciphertext::CipherText; use ::el_gamal::serializer::Serializer...
}
ut voting_options = Vec::new(); voting_options.push(ModInt::zero()); voting_options.push(ModInt::one()); let message: ModInt = ModInt { value: BigInt::one(), modulus: BigInt::from(5) }; let cipher_text = encrypt(&pub_key, message.clone()); let ch...
function_block-function_prefixed
[ { "content": "pub fn encrypt(public_key: &PublicKey, message: ModInt) -> CipherText {\n\n let random: ModInt = ModInt::gen_modint(public_key.q.clone());\n\n\n\n let g = public_key.g.clone();\n\n let h = public_key.h.clone();\n\n\n\n let big_g = g.clone().pow(random.clone());\n\n let big_h1= h.clo...
Rust
third-party/stringprep/tests/nameprep_tests.rs
capyloon/api-daemon
ab4e4b60aa9bb617734c64655c0b8940fff098bc
extern crate stringprep; use stringprep::{Error, nameprep}; fn assert_prohibited_character<T>(result: Result<T, Error>) { assert!(result.is_err()); } fn assert_prohibited_bidirectional_text<T>(result: Result<T, Error>) { assert!(result.is_err()); } #[test] fn test_nameprep() { assert_eq!("安室奈美恵-with-su...
extern crate stringprep; use stringprep::{Error, nameprep}; fn assert_prohibited_character<T>(result: Result<T, Error>) { assert!(result.is_err()); } fn assert_prohibited_bidirectional_text<T>(result: Result<T, Error>) { assert!(result.is_err()); } #[test] fn test_nameprep() { assert_eq!("安室奈美恵-with-su...
#[test] fn should_permit_ascii_space() { assert_eq!(" ", nameprep(" ").unwrap()); } #[test] fn should_map_8bit_space() { assert_eq!(" ", nameprep("\u{00a0}").unwrap()); } #[test] fn should_prohibit_multibyte_space() { assert_prohibited_character(nameprep("\u{1680}")); } #[test] fn should_map_multibyte_...
fn should_revert_case_fold_and_normalization() { let inputs = ["\u{01f0}", "\u{0390}", "\u{03b0}", "\u{1e96}", "\u{1f56}"]; for input in inputs.iter() { assert_eq!(input.clone(), nameprep(input).unwrap()); } }
function_block-full_function
[]
Rust
src/airport_gates.rs
DarrenTsung/interview-rs
aa195501f35ba8d0d1be1c681de29145a8c3c054
use binary_heap_plus::*; /* At an airport you have a timetable for arrivals and departures. You need to determine the minimum number of gates you'd need to provide so that all the planes can be placed at a gate as per their schedule. The arrival and departure times for each plane are presented in two arrays, sorted b...
use binary_heap_plus::*; /* At an airport you have a timetable for arrivals and departures. You need to determine the minimum number of gates you'd need to provide so that all the planes can be placed at a gate as per their schedule. The arrival and departure times for each plane are presented in two arrays, sorted b...
} #[cfg(test)] mod tests { use super::*; fn check_correctness_for_all_solutions(assertions: impl Fn(&dyn AirportGatesSolution)) { assertions(&AirportGatesSolutionNaive); assertions(&AirportGatesSolutionMoreEfficient); assertions(&AirportGatesSolutionCounter); } #[test] fn...
fn airport_gates(&self, schedules_sorted_by_arrival: &[(u32, u32)]) -> u32 { #[derive(PartialEq, Eq, PartialOrd, Ord)] enum EventType { Arrival, Departure, } let sorted_events = { let mut events = vec![]; for (arrival, departure) in schedu...
function_block-full_function
[ { "content": "pub fn has_two_movies_for_flight(flight_length: u32, movie_lengths: Vec<u32>) -> bool {\n\n let mut complement_movie_lengths = HashSet::new();\n\n\n\n for movie_length in movie_lengths {\n\n // If movie is not valid, ignore.\n\n if movie_length > flight_length {\n\n ...
Rust
src/server/entry_api.rs
bingryan/quake
be1aae0ff36a22d47bdef5c99797d95293792a33
use std::collections::HashMap; use std::fs; use std::fs::File; use std::path::PathBuf; use rocket::fs::NamedFile; use rocket::response::status::NotFound; use rocket::response::Redirect; use rocket::serde::json::Json; use rocket::serde::{Deserialize, Serialize}; use rocket::tokio::task::spawn_blocking; use rocket::Stat...
use std::collections::HashMap; use std::fs; use std::fs::File; use std::path::PathBuf; use rocket::fs::NamedFile; use rocket::response::status::NotFound; use rocket::response::Redirect; use rocket::serde::json::Json; use rocket::serde::{Deserialize, Serialize}; use rocket::tokio::task::spawn_blocking; use rocket::Stat...
#[get("/<entry_type>/<id>")] pub(crate) async fn get_entry( entry_type: &str, id: usize, config: &State<QuakeConfig>, ) -> Result<Json<EntryFile>, NotFound<Json<ApiError>>> { let base_path = PathBuf::from(&config.workspace).join(entry_type); let index = id; let prefix = EntryFile::file_prefix(...
ub(crate) async fn create_entry( entry_type: String, text: String, config: &State<QuakeConfig>, ) -> Result<Json<EntryFile>, NotFound<Json<ApiError>>> { let workspace = config.workspace.to_string(); return match entry_usecases::create_entry(&workspace, &entry_type, &text) { Ok((_path, file))...
function_block-function_prefixed
[ { "content": "fn highlight_content(string: &str, lang: &str) {\n\n use syntect::easy::HighlightLines;\n\n use syntect::highlighting::{Style, ThemeSet};\n\n use syntect::parsing::SyntaxSet;\n\n use syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings};\n\n\n\n // Load these once at the sta...
Rust
api/src/lib.rs
fdeantoni/ph-quakes
75d888276a091335436c9435f22d9c81f3870ad3
use serde_derive::*; pub use chrono::prelude::*; pub mod time { pub use ::chrono::Duration; } pub use geojson::{FeatureCollection, Feature, GeoJson, Geometry, Value}; use serde_json::{Map, to_value}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Quake { datetime: DateTime<Utc>, longitude: f6...
use serde_derive::*; pub use chrono::prelude::*; pub mod time { pub use ::chrono::Duration; } pub use geojson::{FeatureCollection, Feature, GeoJson, Geometry, Value}; use serde_json::{Map, to_value}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Quake { datetime: DateTime<Utc>, longitude: f6...
} #[derive(Debug, Clone)] pub struct QuakeList(Box<[Quake]>); impl QuakeList { pub fn list(&self) -> Box<[Quake]> { self.0.clone() } pub fn new(vec: Vec<Quake>) -> QuakeList { QuakeList(vec.into_boxed_slice()) } pub fn to_geojson(&self) -> GeoJson { let bbox = None; ...
0..pos - 1]; (location.to_string(), province.to_string()) } None => { let location = text.clone(); let mut province = ""; if let Some(pos) = text.rfind("of ") { province = &text[pos + 3..text.len()] ...
function_block-function_prefixed
[ { "content": "type Row = HashMap<String, String>;\n\n\n\npub struct HtmlParser(Vec<Row>, String);\n\n\n\nimpl HtmlParser {\n\n\n\n pub async fn parse(html: String, source_url: String) -> HtmlParser {\n\n let mut collection: Vec<Row> = Vec::new();\n\n let expected_headers: HashSet<String> = [\n\...
Rust
src/voxel_tools/mesh_builder.rs
TanTanDev/first_voxel_engine
1cb19a85fdba285e478eb97819dc762753c6c5e9
use crate::rendering::gpu_resources::GpuResources; use super::{ chunk, chunks::{adjacent_voxels, Chunks}, }; use super::{ direction::Direction, quad::Quad, rendering::voxel_vertex::VoxelVertex, voxel::Voxel, }; use wgpu::util::DeviceExt; pub fn build_chunk_mesh( chunks: &mut Chunks, ...
use crate::rendering::gpu_resources::GpuResources; use super::{ chunk, chunks::{adjacent_voxels, Chunks}, }; use super::{ direction::Direction, quad::Quad, rendering::voxel_vertex::VoxelVertex, voxel::Voxel, }; use wgpu::util::DeviceExt; pub fn build_chunk_mesh( chunks: &mut Chunks, ...
fn construct_buffers( device: &wgpu::Device, vertices: Vec<VoxelVertex>, indices: Vec<u32>, ) -> (wgpu::Buffer, wgpu::Buffer) { let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("voxel_chunk_vertices"), contents: bytemuck::cast_slice(&vertice...
fn process_voxel( voxel: &Voxel, voxel_pos: cgmath::Vector3<f32>, left: &Voxel, down: &Voxel, back: &Voxel, quads: &mut Vec<Quad>, ) { match voxel.is_solid() { true => { if !left.is_solid() { quads.push(Quad::from_direction(Direction::Left, vo...
function_block-full_function
[ { "content": "pub fn adjacent_voxels<'a>(\n\n chunks: &'a mut Chunks,\n\n local_pos: (i32, i32, i32),\n\n chunk_pos: &cgmath::Vector3<i32>,\n\n) -> Result<(&'a Voxel, &'a Voxel, &'a Voxel, &'a Voxel)> {\n\n let (x, y, z) = (local_pos.0, local_pos.1, local_pos.2);\n\n let voxel = chunks\n\n ...
Rust
components/restreamer/src/dvr.rs
iAnanich/ephyr
0ed272838d04b4e952e105bd0e170005c363dcf9
use std::{ ffi::OsString, io, path::{Path, PathBuf}, time::SystemTime, }; use anyhow::anyhow; use ephyr_log::log; use futures::{future, TryFutureExt as _, TryStreamExt as _}; use once_cell::sync::OnceCell; use tokio::fs; use url::Url; use uuid::Uuid; use crate::state; static STORAGE: OnceCell<Stora...
use std::{ ffi::OsString, io, path::{Path, PathBuf}, time::SystemTime, }; use anyhow::anyhow; use ephyr_log::log; use futures::{future, TryFutureExt as _, TryStreamExt as _}; use once_cell::sync::OnceCell; use tokio::fs; use url::Url; use uuid::Uuid; use crate::state; static STORAGE: OnceCell<Stora...
og::error!("Failed to cleanup DVR files: {}", e) }) } } #[allow(clippy::missing_panics_doc)] pub async fn new_file_path(url: &Url) -> io::Result<PathBuf> { let mut path = url.to_file_path().map_err(|_| { io::Error::new(io::ErrorKind::Other, "File URL contains bad file path") })?; i...
#[must_use] pub fn global() -> &'static Storage { STORAGE.get().expect("dvr::Storage is not initialized") } #[inline] pub fn set_global(self) -> anyhow::Result<()> { STORAGE .set(self) .map_err(|_| anyhow!("dvr::Stora...
random
[ { "content": "/// Interprets given [panic payload][1] as displayable message.\n\n///\n\n/// [1]: std::panic::PanicInfo::payload\n\npub fn display_panic<'a>(err: &'a (dyn Any + Send + 'static)) -> &'a str {\n\n if let Some(s) = err.downcast_ref::<&str>() {\n\n return s;\n\n }\n\n if let Some(s) =...
Rust
src/file_watcher.rs
devzbysiu/podium
ee45e5e8c880b6b8bf638f5257db3f773df4e61b
use crate::contracts::file_to_process::{new_file_to_process, FileToProcess}; use crate::custom_tantivy::wrapper::*; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher}; use tracing::info; use walkdir::{DirEntry, WalkDir}; use std::path::PathBuf; use std::sync::mpsc::channel; use std::time::Duration; pub as...
use crate::contracts::file_to_process::{new_file_to_process, FileToProcess}; use crate::custom_tantivy::wrapper::*; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher}; use tracing::info; use walkdir::{DirEntry, WalkDir}; use std::path::PathBuf; use std::sync::mpsc::channel; use std::time::Duration; pub as...
pub fn is_hidden(entry: &DirEntry) -> bool { entry .file_name() .to_str() .map(|s| s.starts_with('.')) .unwrap_or(false) }
function_block-full_function
[ { "content": "pub fn log_and_return_error_string(error_string: String) -> String {\n\n error!(\"{}\", error_string);\n\n error_string\n\n}\n", "file_path": "src/error_adapter.rs", "rank": 3, "score": 106939.53277923616 }, { "content": "fn bench_indexing_text_file(c: &mut Criterion) {\n...
Rust
tests/integration/cli/tests/create_exe.rs
psy-repos-rust/wasmer
75a98ab171bee010b9a7cd0f836919dc4519dcaf
use anyhow::{bail, Context}; use std::fs; use std::io::prelude::*; use std::path::PathBuf; use std::process::Command; use wasmer_integration_tests_cli::*; fn create_exe_test_wasm_path() -> String { format!("{}/{}", C_ASSET_PATH, "qjs.wasm") } const JS_TEST_SRC_CODE: &[u8] = b"function greet(name) { return JS...
use anyhow::{bail, Context}; use std::fs; use std::io::prelude::*; use std::path::PathBuf; use std::process::Command; use wasmer_integration_tests_cli::*; fn create_exe_test_wasm_path() -> String { format!("{}/{}", C_ASSET_PATH, "qjs.wasm") } const JS_TEST_SRC_CODE: &[u8] = b"function greet(name) { return JS...
} #[test] fn create_exe_works() -> anyhow::Result<()> { let temp_dir = tempfile::tempdir()?; let operating_dir: PathBuf = temp_dir.path().to_owned(); let wasm_path = operating_dir.join(create_exe_test_wasm_path()); #[cfg(not(windows))] let executable_path = operating_dir.join("wasm.out"); #[c...
e arbitrary bytes"), std::str::from_utf8(&output.stderr) .expect("stderr is not utf8! need to handle arbitrary bytes") ); } Ok(()) }
function_block-function_prefixed
[ { "content": "fn compile_and_compare(name: &str, engine: impl Engine, wasm: &[u8]) {\n\n let store = Store::new(&engine);\n\n\n\n // compile for first time\n\n let module = Module::new(&store, wasm).unwrap();\n\n let first = module.serialize().unwrap();\n\n\n\n // compile for second time\n\n l...
Rust
src/scd30/mod.rs
joemclo/knurling-sessions-cabon-sensor
893ffccb58166f273c02f3951bdce793f2fbd5fd
use crc_all::Crc; use embedded_hal::blocking::i2c::{Read, Write}; pub struct SensorData { pub co2: f32, pub temperature: f32, pub humidity: f32, } const DEFAULT_ADDRESS: u8 = 0x61; enum Command { StartContinuousMeasurement = 0x0010, StopContinuousMeasurement = 0x0104, MeasurementInterval = 0x...
use crc_all::Crc; use embedded_hal::blocking::i2c::{Read, Write}; pub struct SensorData { pub co2: f32, pub temperature: f32, pub humidity: f32, } const DEFAULT_ADDRESS: u8 = 0x61; enum Command { StartContinuousMeasurement = 0x0010, StopContinuousMeasurement = 0x0104, MeasurementInterval = 0x...
_bytes([ rd_buffer[6], rd_buffer[7], rd_buffer[9], rd_buffer[10], ]), humidity: f32::from_be_bytes([ rd_buffer[12], rd_buffer[13], rd_buffer[15], rd_buffer[16], ...
= SensorData { co2: f32::from_be_bytes([rd_buffer[0], rd_buffer[1], rd_buffer[3], rd_buffer[4]]), temperature: f32::from_be
function_block-random_span
[ { "content": "pub fn draw_titles(mut display: Display4in2) -> Display4in2 {\n\n draw_large_text(&mut display, \"Air Quality\", (20, 30));\n\n\n\n draw_mid_text(&mut display, \"Carbon Dioxide:\", (20, 90));\n\n draw_mid_text(&mut display, \"Temperature:\", (20, 130));\n\n draw_mid_text(&mut display, ...
Rust
src/block_renderer.rs
AnthonyTornetta/bevy_testing
9f8a8e6bda66b2ac6b8caea72dded2e4740bdab3
use crate::blocks::block; use bevy::prelude::*; use bevy::render::mesh::Indices; use bevy::render::render_resource::PrimitiveTopology; use crate::base_renderable; use crate::base_renderable::CanCreateSubMesh; use crate::blocks::block::Side; pub const U_WIDTH: f32 = 0.5; pub const V_HEIGHT: f32 = 0.5; const DEFAULT_F...
use crate::blocks::block; use bevy::prelude::*; use bevy::render::mesh::Indices; use bevy::render::render_resource::PrimitiveTopology; use crate::base_renderable; use crate::base_renderable::CanCreateSubMesh; use crate::blocks::block::Side; pub const U_WIDTH: f32 = 0.5; pub const V_HEIGHT: f32 = 0.5; const DEFAULT_F...
n(side); item.2[1] = has_uvs.v_height(side) * item.2[1] + has_uvs.v_min(side); res.push(item); } res } pub trait HasUVs { fn u_min(&self, side: block::Side) -> f32; fn u_width(&self, _side: block::Side) -> f32 { U_WIDTH } fn v_min(&self, side: block::Side) -> f32; ...
nfo: [([f32; 3], [f32; 3], [f32; 2]); 4], offset: &Vec3, has_uvs: &T, side: Side, ) -> Vec<([f32; 3], [f32; 3], [f32; 2])> { let mut res = Vec::with_capacity(default_info.len()); for mut item in default_info { item.0[0] += offset.x; item.0[1] += offset.y; item.0[2] += of...
function_block-random_span
[ { "content": "pub fn camera_movement_system(\n\n mut query: Query<(&Camera, &mut Transform)>,\n\n mut ev_motion: EventReader<MouseMotion>,\n\n keys: Res<Input<KeyCode>>,\n\n)\n\n{\n\n let (_cam, mut transform) = query.single_mut();\n\n\n\n let speed = (keys.pressed(KeyCode::LShift) as i32 * 5 + 1...