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
44_data_processing/examples/user.rs
JosephInAfrica/geektime-rust
7c9337608739e7aa8e50c7b9c4b7c4f9961435a5
use anyhow::{anyhow, Result}; use argon2::{ password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, SaltString}, Argon2, PasswordVerifier, }; use lazy_static::lazy_static; use sqlx::{sqlite::SqlitePoolOptions, SqlitePool}; use std::env; const ARGON_SECRET: &[u8] = b"deadbeef"; lazy_static! { s...
use anyhow::{anyhow, Result}; use argon2::{ password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, SaltString}, Argon2, PasswordVerifier, }; use lazy_static::lazy_static; use sqlx::{sqlite::SqlitePoolOptions, SqlitePool}; use std::env; const ARGON_SECRET: &[u8] = b"deadbeef"; lazy_static! { s...
} async fn recreate_table(pool: &SqlitePool) -> Result<()> { sqlx::query("DROP TABLE users").execute(pool).await?; sqlx::query( r#"CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY NOT NULL, email VARCHAR UNIQUE NOT NULL, ...
t?; println!("find user: {:?}", user); if verify_password(password, &user.hashed_password).is_err() { return Err(anyhow!("failed to login")); } Ok("awesome token".into()) }
function_block-function_prefixed
[]
Rust
src/http.rs
dockwa/seatrial
e0c22cc65b5cb103c3f51acc79781954018d3624
use nanoserde::DeRon; use ureq::{Agent, AgentBuilder}; use std::collections::HashMap; use crate::config_duration::ConfigDuration; use crate::grunt::Grunt; use crate::pipeline::action::{ConfigActionMap, PipelineAction, Reference}; use crate::pipeline::step_handler::{ StepCompletion, StepError, StepHandler, StepHan...
use nanoserde::DeRon; use ureq::{Agent, AgentBuilder}; use std::collections::HashMap; use crate::config_duration::ConfigDuration; use crate::grunt::Grunt; use crate::pipeline::action::{ConfigActionMap, PipelineAction, Reference}; use crate::pipeline::step_handler::{ StepCompletion, StepError, StepHandler, StepHan...
pub fn timeout(&self) -> Option<&ConfigDuration> { match self { Self::Delete { timeout, .. } | Self::Get { timeout, .. } | Self::Head { timeout, .. } | Self::Post { timeout, .. } | Self::Put { timeout, .. } => timeout.as_ref(), } } } ...
pub fn body(&self) -> Option<&Reference> { match self { Self::Delete { body, .. } | Self::Get { body, .. } | Self::Head { body, .. } | Self::Post { body, .. } | Self::Put { body, .. } => body.as_ref(), } }
function_block-full_function
[ { "content": "#[inline]\n\nfn normalize_header_name(name: &str) -> String {\n\n name.trim().to_lowercase()\n\n}\n\n\n", "file_path": "src/validator.rs", "rank": 0, "score": 123436.56375340576 }, { "content": "pub fn parse_args() -> CmdArgs {\n\n argh::from_env::<CmdArgsBase>().into()\n...
Rust
src/main.rs
extrasharp/uokichi
b1a40ca56ed36eeada38dda586fba1ba4255fce4
#![allow(dead_code)] use std::collections::HashMap; use std::fmt; use std::fmt::{Debug, Display}; use std::mem; use num::{PrimInt, ToPrimitive, Unsigned}; trait Bits: Debug + PrimInt + Unsigned { fn from_u64(val: u64) -> Self { Self::from(val & Self::max_value().to_u64().unwrap()).unwrap() ...
#![allow(dead_code)] use std::collections::HashMap; use std::fmt; use std::fmt::{Debug, Display}; use std::mem; use num::{PrimInt, ToPrimitive, Unsigned}; trait Bits: Debug + PrimInt + Unsigned { fn from_u64(val: u64) -> Self { Self::from(val & Self::max_value().to_u64().unwrap()).unwrap() ...
fn compile(settings: CompileSettings, code: Vec<CodeObject>) -> Result<Vec<HexRecord>, CompileError> { let address_image = generate_address_image(&code)?; let label_table = generate_label_table(&code, &address_image)?; let hex_objects = generate_hex_objects(&code, &address_image, &label_table)?; gener...
fn generate_hex_records(hex_objects: &[HexObject], settings: &CompileSettings) -> Result<Vec<HexRecord>, CompileError> { use HexObject::*; let mut records = Vec::new(); let i_addresses = hex_objects.iter() .filter_map(| obj | { if let A...
function_block-full_function
[ { "content": "trait Bits: Debug + PrimInt + Unsigned {\n\n // has to be unsigned\n\n // 1. using them as bytes anyway\n\n // 2. max_value is all ones\n\n\n\n fn from_u64(val: u64) -> Self {\n\n Self::from(val & Self::max_value().to_u64().unwrap()).unwrap()\n\n }\n\n\n\n fn mask(ct: u...
Rust
src/rust/src/graph.rs
informatik-mannheim/gcatcirc
3745e87fa714ee91a738e8d3b232676bc87f35bf
use extendr_api::prelude::*; use rust_gcatcirc_lib::graph_circ::CircGraph; use crate::lib_utils::new_code_from_vec; #[extendr] pub fn get_representing_graph_obj(tuples: Vec<String>, show_cycles: bool, show_longest_path: bool) -> Robj { let code = new_code_from_vec(tuples); let g = match code.get_associated_gr...
use extendr_api::prelude::*; use rust_gcatcirc_lib::graph_circ::CircGraph; use crate::lib_utils::new_code_from_vec; #[extendr] pub fn get_representing_graph_obj(tuples: Vec<String>, show_cycles: bool, show_longest_path: bool) -> Robj { let code = new_code_from_vec(tuples); let g = match code.get_associated_gr...
extendr_module! { mod graph; fn get_representing_graph_obj; fn get_representing_component_obj; fn get_longest_paths; fn get_cyclic_paths; }
if let Ok(s_g) = g.all_cycles_as_sub_graph() { s_g.get_edges() } else { vec![] } } false => vec![], }; let longest_paths = match show_longest_path { true => { if let Ok(s_g) = g.all_longest_paths_as_sub_graph() { ...
function_block-function_prefix_line
[ { "content": "#[extendr]\n\npub fn is_code(tuples: Vec<String>) -> bool {\n\n let code = new_code_from_vec(tuples);\n\n return code.is_code();\n\n}\n\n\n\n/// If a set of words is not a code it returns all ambiguous sequences.\n\n///\n\n/// This function returns all ambiguous sequences\n\n/// which only e...
Rust
fastpay_core/src/base_types.rs
asonnino/fastpay
d5e07a7ff1bd25174071f454872927bf58865fff
use ed25519_dalek as dalek; use ed25519_dalek::{Signer, Verifier}; use rand::rngs::OsRng; use serde::{Deserialize, Serialize}; use std::convert::{TryFrom, TryInto}; use crate::error::FastPayError; #[cfg(test)] #[path = "unit_tests/base_types_tests.rs"] mod base_types_tests; #[derive( Eq, PartialEq, Ord, Parti...
use ed25519_dalek as dalek; use ed25519_dalek::{Signer, Verifier}; use rand::rngs::OsRng; use serde::{Deserialize, Serialize}; use std::convert::{TryFrom, TryInto}; use crate::error::FastPayError; #[cfg(test)] #[path = "unit_tests/base_types_tests.rs"] mod base_types_tests; #[derive( Eq, PartialEq, Ord, Parti...
Amount { type Error = std::num::TryFromIntError; fn try_from(val: Balance) -> Result<Self, Self::Error> { Ok(Amount(val.0.try_into()?)) } } impl SequenceNumber { pub fn new() -> Self { SequenceNumber(0) } pub fn max() -> Self { SequenceNumber(0x7fff_ffff_ffff_ffff) ...
H]); pub type PrimaryAddress = PublicKeyBytes; pub type FastPayAddress = PublicKeyBytes; pub type AuthorityName = PublicKeyBytes; pub fn get_key_pair() -> (FastPayAddress, KeyPair) { let mut csprng = OsRng; let keypair = dalek::Keypair::generate(&mut csprng); (PublicKeyBytes(keypair.public.to_bytes()), Ke...
random
[ { "content": "pub fn serialize_message(msg: &SerializedMessage) -> Vec<u8> {\n\n serialize(msg)\n\n}\n\n\n", "file_path": "fastpay_core/src/serialize.rs", "rank": 0, "score": 142453.5309938187 }, { "content": "pub fn serialize_error(value: &FastPayError) -> Vec<u8> {\n\n serialize(&Sha...
Rust
examples/do_swap.rs
patternmachine/terra-rust
a731fbdca43374193fdaca4d96fece39d678ec11
use anyhow::Result; use dotenv::dotenv; use rust_decimal::Decimal; use secp256k1::Secp256k1; use serde::Serialize; use structopt::StructOpt; use terra_rust_api::core_types::Coin; use terra_rust_api::terra_u64_format; use terra_rust_api::{GasOptions, Message, MsgExecuteContract, Terra}; use terra_rust_wallet::Wallet; p...
use anyhow::Result; use dotenv::dotenv; use rust_decimal::Decimal; use secp256k1::Secp256k1; use serde::Serialize; use structopt::StructOpt; use terra_rust_api::core_types::Coin; use terra_rust_api::terra_u64_format; use terra_rust_api::{GasOptions, Message, MsgExecuteContract, Terra}; use terra_rust_wallet::Wallet; p...
#[tokio::main] async fn main() { dotenv().ok(); env_logger::init(); if let Err(ref err) = run().await { log::error!("{}", err); err.chain() .skip(1) .for_each(|cause| log::error!("because: {}", cause)); ::std::...
llet::create(&cli.wallet); let seed: Option<&str> = if cli.seed.is_empty() { None } else { Some(&cli.seed) }; let coins: Vec<Coin> = if cli.coins.is_empty() { vec![] } else { Coin::parse_coins(&cli.coins)? }; let from_key = wallet.get_private_key(&secp, &cl...
function_block-function_prefixed
[ { "content": "/// put out into a separate function to facilitate better testing\n\nfn generate_hash<'a>(salt: &'a str, exchange_string: &'a str, validator: &'a str) -> String {\n\n let mut sha = Sha256::new();\n\n let mut to_hash: String = String::new();\n\n to_hash = to_hash.add(salt);\n\n to_hash ...
Rust
thoth-api/src/model/publisher/crud.rs
OpenBookPublishers/thoth
9c2c6f9d2b7bd5a8dc29d56672e23ee50db91ad2
use super::{ NewPublisher, NewPublisherHistory, PatchPublisher, Publisher, PublisherField, PublisherHistory, PublisherOrderBy, }; use crate::graphql::utils::Direction; use crate::model::{Crud, DbInsert, HistoryEntry}; use crate::schema::{publisher, publisher_history}; use crate::{crud_methods, db_insert}; use d...
use super::{ NewPublisher, NewPublisherHistory, PatchPublisher, Publisher, PublisherField, PublisherHistory, PublisherOrderBy, }; use crate::graphql::utils::Direction; use crate::model::{Crud, DbInsert, HistoryEntry}; use crate::schema::{publisher, publisher_history}; use crate::{crud_methods, db_insert}; use d...
Direction::Asc => query = query.order(publisher_url.asc()), Direction::Desc => query = query.order(publisher_url.desc()), }, PublisherField::CreatedAt => match order.direction { Direction::Asc => query = query.order(created_at.asc()), Direction::...
isherField::PublisherId => match order.direction { Direction::Asc => query = query.order(publisher_id.asc()), Direction::Desc => query = query.order(publisher_id.desc()), }, PublisherField::PublisherName => match order.direction { Direction::Asc =>...
random
[ { "content": "fn issue_imprints_match(work_id: Uuid, series_id: Uuid, db: &crate::db::PgPool) -> ThothResult<()> {\n\n use diesel::prelude::*;\n\n\n\n let connection = db.get().unwrap();\n\n let series_imprint = crate::schema::series::table\n\n .select(crate::schema::series::imprint_id)\n\n ...
Rust
Packages/app-server-rs/src/db/_general.rs
Venryx/DebateMap
be2f82979eba3aed43d0e4247be7cee655adbe66
use anyhow::{Context, Error}; use async_graphql::{Object, Result, Schema, Subscription, ID, async_stream, OutputType, scalar, EmptySubscription, SimpleObject}; use futures_util::{Stream, stream, TryFutureExt, StreamExt, Future}; use hyper::{Body, Method}; use rust_macros::wrap_slow_macros; use serde::{Serialize, Deseri...
use anyhow::{Context, Error}; use async_graphql::{Object, Result, Schema, Subscription, ID, async_stream, OutputType, scalar, EmptySubscription, SimpleObject}; use futures_util::{Stream, stream, TryFutureExt, StreamExt, Future}; use hyper::{Body, Method}; use rust_macros::wrap_slow_macros; use serde::{Serialize, Deseri...
let query_as_str = format!("query {{ _PassConnectionID(connectionID: \"{}\") {{ userID }} }}", connection_id); let request_body_as_str = json!({ "query": query_as_str, "variables":{}, }).to_string(); let request = hyper::Request::builder() .method(Method::POST) .uri...
function_block-function_prefix_line
[ { "content": "pub fn wrap_async_graphql_impl(input: TokenStream, force_proceed: bool) -> TokenStream {\n\n //return input; // uncommenting this can be helpful for debugging in some cases\n\n\n\n let proceed = force_proceed || {\n\n let mut temp = false;\n\n if let Ok(val) = env::var(\"STRIP_...
Rust
src/sensors/powercap_rapl.rs
zwerdlds/scaphandre
0b55674e7111e3ddfcd10a91c9ddd1bc40a89db3
use crate::sensors::Sensor; use crate::sensors::Topology; use procfs::{modules, KernelModule}; use regex::Regex; use std::collections::HashMap; use std::error::Error; use std::{env, fs}; pub struct PowercapRAPLSensor { base_path: String, buffer_per_socket_max_kbytes: u16, buffer_per_domain_max_kbytes: u16,...
use crate::sensors::Sensor; use crate::sensors::Topology; use procfs::{modules, KernelModule}; use regex::Regex; use std::collections::HashMap; use std::error::Error; use std::{env, fs}; pub struct PowercapRAPLSensor { base_path: String, buffer_per_socket_max_kbytes: u16, buffer_per_domain_max_kbytes: u16,...
fn get_topology(&mut self) -> Box<Option<Topology>> { let topology = self.generate_topology().ok(); if topology.is_none() { panic!("Couldn't generate the topology !"); } Box::new(topology) } } #[cfg(test)] mod tests { use super::*; use std::any::type_n...
fn generate_topology(&self) -> Result<Topology, Box<dyn Error>> { let modules_state = PowercapRAPLSensor::check_module(); if modules_state.is_err() && !self.virtual_machine { panic!("Couldn't find intel_rapl modules."); } let mut topo = Topology::new(); let re_domain ...
function_block-full_function
[ { "content": "/// Returns options needed for each exporter as a HashMap.\n\n/// This function has to be updated to enable a new exporter.\n\npub fn get_exporters_options() -> HashMap<String, HashMap<String, ExporterOption>> {\n\n let mut options = HashMap::new();\n\n options.insert(\n\n String::fro...
Rust
serde-generate/tests/ocaml_generation.rs
zefchain/serde-reflection
3bc9fa7422a2e725960ae8a1166f6929961f6128
use serde_generate::{ocaml, test_utils, CodeGeneratorConfig, Encoding, SourceInstaller}; use std::{fs::File, io::Write, process::Command}; use tempfile::{tempdir, TempDir}; fn test_that_ocaml_code_compiles_with_config( config: &CodeGeneratorConfig, must_fail: bool, more: Option<&str>, encoding: Optio...
use serde_generate::{ocaml, test_utils, CodeGeneratorConfig, Encoding, SourceInstaller}; use std::{fs::File, io::Write, process::Command}; use tempfile::{tempdir, TempDir}; fn test_that_ocaml_code_compiles_with_config( config: &CodeGeneratorConfig, must_fail: bool, more: Option<&str>, encoding: Optio...
let config = CodeGeneratorConfig::new("testing".to_string()) .with_serialization(false) .with_custom_code(custom_code); let (_dir, source_path) = test_that_ocaml_code_compiles_with_config(&config, false, None, None); let content = std::fs::read_to_string(&source_path).unwrap(); assert!(conte...
function_block-function_prefix_line
[ { "content": "#[derive(Deserialize)]\n\nstruct Unit;\n\n\n", "file_path": "serde-name/tests/trace.rs", "rank": 0, "score": 242278.70346082692 }, { "content": "#[derive(Serialize)]\n\n#[serde(remote = \"Unit\")]\n\nstruct Unit;\n\n\n", "file_path": "serde-name/tests/ser_adapter.rs", "...
Rust
src/main.rs
nirsarkar/feroxbuster
6921ac03a9a3e08a931bfe160cd4854d76ba6a02
use feroxbuster::config::{CONFIGURATION, PROGRESS_PRINTER}; use feroxbuster::scanner::scan_url; use feroxbuster::utils::{ferox_print, get_current_depth, module_colorizer, status_colorizer}; use feroxbuster::{banner, heuristics, logger, reporter, FeroxResult}; use futures::StreamExt; use reqwest::Response; use std::coll...
use feroxbuster::config::{CONFIGURATION, PROGRESS_PRINTER}; use feroxbuster::scanner::scan_url; use feroxbuster::utils::{ferox_print, get_current_depth, module_colorizer, status_colorizer}; use feroxbuster::{banner, heuristics, logger, reporter, FeroxResult}; use futures::StreamExt; use reqwest::Response; use std::coll...
async fn get_targets() -> FeroxResult<Vec<String>> { log::trace!("enter: get_targets"); let mut targets = vec![]; if CONFIGURATION.stdin { let stdin = io::stdin(); let mut reader = FramedRead::new(stdin, LinesCodec::new()); while let Some(line) = reader.next()...
async fn scan( targets: Vec<String>, tx_term: UnboundedSender<Response>, tx_file: UnboundedSender<String>, ) -> FeroxResult<()> { log::trace!("enter: scan({:?}, {:?}, {:?})", targets, tx_term, tx_file); let words = tokio::spawn(async move { get_unique_words_from_wordlist(&CONF...
function_block-full_function
[ { "content": "/// Given the path to a file, open the file in append mode (create it if it doesn't exist) and\n\n/// return a reference to the file that is buffered and locked\n\nfn open_file(filename: &str) -> Option<Arc<RwLock<io::BufWriter<fs::File>>>> {\n\n log::trace!(\"enter: open_file({})\", filename);...
Rust
catholic-polity-app/db-postgres/src/province_gateway/mutation.rs
HocVienCongGiao/catholic-polity-service
43bb8e6796ded1129a1d5fe35de4b890b15ba9dd
use tokio_postgres::types::ToSql; use tokio_postgres::{Error, Transaction}; use uuid::Uuid; pub(crate) async fn save_id(transaction: &Transaction<'_>, id: Uuid) -> Result<u64, Error> { let stmt = (*transaction) .prepare("INSERT into public.polity__polity (id, type) VALUES ($1, 'province')") .await ...
use tokio_postgres::types::ToSql; use tokio_postgres::{Error, Transaction}; use uuid::Uuid; pub(crate) async fn save_id(transaction: &Transaction<'_>, id: Uuid) -> Result<u64, Error> { let stmt = (*transaction) .prepare("INSERT into public.polity__polity (id, type) VALUES ($1, 'province')") .await ...
nc)] = &[&id, &name]; transaction.execute(&stmt, params).await } pub(crate) async fn update_location_email( transaction: &Transaction<'_>, id: Uuid, location_email: String, ) -> Result<u64, Error> { let stmt = (*transaction) .prepare( "INSERT into public.polity__polity_location_...
ring, ) -> Result<u64, Error> { let stmt = (*transaction) .prepare( "INSERT into public.polity__polity_location_email (id, location_email) VALUES ($1, $2)", ) .await .unwrap(); let params: &[&(dyn ToSql + Sync)] = &[&id, &location_email]; transaction.execute...
random
[]
Rust
nom-derive-impl/src/config.rs
katyo/nom-derive
e0799cf68e46dd500baa0aeb4839a5886ff3b897
use crate::endian::ParserEndianness; use crate::meta::attr::{MetaAttr, MetaAttrType}; use proc_macro2::Span; use syn::{spanned::Spanned, Error}; #[derive(Debug)] pub struct Config { pub struct_name: String, pub global_endianness: ParserEndianness, pub object_endianness: ParserEndianness, ...
use crate::endian::ParserEndianness; use crate::meta::attr::{MetaAttr, MetaAttrType}; use proc_macro2::Span; use syn::{spanned::Spanned, Error}; #[derive(Debug)] pub struct Config { pub struct_name: String, pub global_endianness: ParserEndianness, pub object_endianness: ParserEndianness, ...
} if req_big_endian & req_little_endian { return Err(Error::new( span_endian.unwrap_or_else(Span::call_site), "Struct cannot be both big and little endian", )); } let object_endianness = if req_big_endian { ParserEndian...
match meta.attr_type { MetaAttrType::BigEndian => { req_big_endian = true; span_endian = Some(meta.span()); } MetaAttrType::LittleEndian => req_little_endian = true, MetaAttrType::Complete => complete = true, ...
if_condition
[ { "content": "fn get_selector(meta_list: &[MetaAttr]) -> Option<String> {\n\n for meta in meta_list {\n\n if MetaAttrType::Selector == meta.attr_type {\n\n return Some(meta.arg().unwrap().to_string());\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "nom-derive-impl/src/enum...
Rust
src/physics/systems.rs
gschup/bevy_jam_1
e44decf453f55de63dbdcef54593930ad49c7e35
use crate::physics::contact; use crate::physics::contact::Contact; use crate::physics::utils::QueryExt; use crate::physics::SUB_DT; use super::components::*; use super::resources::*; use super::COLLISION_PAIR_VEL_MARGIN_FACTOR; use bevy::prelude::*; pub fn update_aabb_ball(mut query: Query<(&mut Aabb, &Pos, &Vel, &Ci...
use crate::physics::contact; use crate::physics::contact::Contact; use crate::physics::utils::QueryExt; use crate::physics::SUB_DT; use super::components::*; use super::resources::*; use super::COLLISION_PAIR_VEL_MARGIN_FACTOR; use bevy::prelude::*; pub fn update_aabb_ball(mut query: Query<(&mut Aabb, &Pos, &Vel, &Ci...
fn constrain_body_position(pos: &mut Pos, n: Vec2, penetration_depth: f32) { pos.0 -= n * penetration_depth; } fn constrain_body_velocities( vel_a: &mut Vel, vel_b: &mut Vel, pre_solve_vel_a: &PreSolveVel, pre_solve_vel_b: &PreSolveVel, mass_a: &Mass, mass_b: &Mass, restitution_a: &Re...
pos_a: &mut Pos, pos_b: &mut Pos, mass_a: &Mass, mass_b: &Mass, n: Vec2, penetration_depth: f32, ) { let w_a = 1. / mass_a.0; let w_b = 1. / mass_b.0; let w_sum = w_a + w_b; let pos_impulse = n * (-penetration_depth / w_sum); pos_a.0 += pos_impulse * w_a; pos_b.0 -= pos_impul...
function_block-function_prefix_line
[ { "content": "pub fn ball_box(pos_a: Vec2, radius_a: f32, pos_b: Vec2, size_b: Vec2) -> Option<Contact> {\n\n let box_to_circle = pos_a - pos_b;\n\n let box_to_circle_abs = box_to_circle.abs();\n\n let half_extents = size_b / 2.;\n\n let corner_to_center = box_to_circle_abs - half_extents;\n\n le...
Rust
multiversion-macros/src/target.rs
calebzulawski/function-multiversioning
4f4013d0a7e75ee4158da139e6c091e78926a9e5
use crate::safe_inner::process_safe_inner; use crate::static_dispatch::process_static_dispatch; use crate::target_cfg::process_target_cfg; use proc_macro2::TokenStream; use quote::quote; use std::convert::TryInto; use syn::{parse_quote, Attribute, Error, ItemFn, Lit, LitStr, Path, Result}; #[derive(Clone, Debug)] pub(...
use crate::safe_inner::process_safe_inner; use crate::static_dispatch::process_static_dispatch; use crate::target_cfg::process_target_cfg; use proc_macro2::TokenStream; use quote::quote; use std::convert::TryInto; use syn::{parse_quote, Attribute, Error, ItemFn, Lit, LitStr, Path, Result}; #[derive(Clone, Debug)] pub(...
#[test] fn parse_single_arch_with_features() { let s = LitStr::new("x86_64+sse4.2+xsave", Span::call_site()); let target = Target::parse(&s).unwrap(); assert_eq!(target.architectures, vec!["x86_64"]); assert_eq!(target.features, vec!["sse4.2", "xsave"]); } #[test] ...
fn parse_multiple_arch_no_features() { let s = LitStr::new("[arm|aarch64|mips|mips64]", Span::call_site()); let target = Target::parse(&s).unwrap(); assert_eq!( target.architectures, vec!["arm", "aarch64", "mips", "mips64"] ); assert_eq!(target.features.le...
function_block-full_function
[ { "content": "fn lit_bool(lit: Lit) -> Result<bool, Error> {\n\n if let Lit::Bool(b) = lit {\n\n Ok(b.value)\n\n } else {\n\n Err(Error::new(lit.span(), \"expected string\"))\n\n }\n\n}\n\n\n", "file_path": "multiversion-macros/src/multiversion.rs", "rank": 0, "score": 217554....
Rust
src/parsers.rs
rjahrj/gisture
c87c8b69aee8bd4032076b48bbf0cb690d9e55ac
use once_cell::sync::Lazy; use std::collections::HashMap; use std::process::exit; use pulldown_cmark::{html, Options, Parser}; use syntect::highlighting::ThemeSet; use syntect::html::highlighted_html_for_string; use syntect::parsing::SyntaxSet; use html_escape::{encode_text, decode_html_entities}; use lol_html::html...
use once_cell::sync::Lazy; use std::collections::HashMap; use std::process::exit; use pulldown_cmark::{html, Options, Parser}; use syntect::highlighting::ThemeSet; use syntect::html::highlighted_html_for_string; use syntect::parsing::SyntaxSet; use html_escape::{encode_text, decode_html_entities}; use lol_html::html...
} pub fn _sort_by_date(_page_metadata: HashMap<String, String>) -> HashMap<i32, String> { /* This is not required atm because gist already outputs a sorted list. It's in descending order so we just traverse the list in reverse. If anyone asks for sorting config...
if url.ends_with("/") { format!("{}{}", url, path) } else { format!("{}/{}", url, path) }
if_condition
[]
Rust
src/rr.rs
dhild/dns-rs
92b798d31a939a0de6c6b2c4659f20cec6abf333
use crate::names::Name; use std::convert::From; use std::fmt; use std::fmt::{Display, Formatter}; use std::io::{Cursor, Write}; use std::net::{Ipv4Addr, Ipv6Addr}; use byteorder::{BigEndian, WriteBytesExt}; #[derive(Debug, PartialEq, Clone, Copy)] pub enum Type { A, AAAA, CNAME, P...
use crate::names::Name; use std::convert::From; use std::fmt; use std::fmt::{Display, Formatter}; use std::io::{Cursor, Write}; use std::net::{Ipv4Addr, Ipv6Addr}; use byteorder::{BigEndian, WriteBytesExt}; #[derive(Debug, PartialEq, Clone, Copy)] pub enum Type { A, AAAA, CNAME, P...
} impl fmt::Display for Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Type::A => write!(f, "A"), Type::AAAA => write!(f, "AAAA"), Type::CNAME => write!(f, "CNAME"), Type::SOA => write!(f, "SOA"), Type::PTR => write!(...
H"), Class::Hesoid => write!(f, "HS"), Class::Unknown { value: x } => write!(f, "0x{:x}", x), } }
function_block-function_prefixed
[ { "content": "fn parse_name<'a>(data: &'a [u8]) -> impl Fn(&'a [u8]) -> IResult<&'a [u8], Name> {\n\n |i| -> IResult<&[u8], Name> {\n\n let (i, length) = be_u8(i)?;\n\n if length == 0 {\n\n return Ok((i, Name { name: vec![0] }));\n\n }\n\n match length & 0xC0 {\n\n ...
Rust
tcp/src/lib.rs
katyo/unicom
0da0ecbe2cb0a9bb7609dd2eff80a7b6b58f2aec
#![doc = include_str!("../README.md")] use std::{net::SocketAddr, sync::Arc}; #[cfg(feature = "tokio")] use tokio_rs::net::TcpStream; #[cfg(feature = "async-std")] use async_std_rs::net::TcpStream; use unicom::{Backend, BoxedConnect, BoxedConnection, BoxedConnector, Connector, Error, Host, Url}; use unicom_nres::{...
#![doc = include_str!("../README.md")] use std::{net::SocketAddr, sync::Arc}; #[cfg(feature = "tokio")] use tokio_rs::net::TcpStream; #[cfg(feature = "async-std")] use async_std_rs::net::TcpStream; use unicom::{Backend, BoxedConnect, BoxedConnection, BoxedConnector, Connector, Error, Host, Url}; use unicom_nres::{...
} impl<R> Backend for TcpSocket<R> where R: Resolver, { fn name(&self) -> &str { &self.name } fn description(&self) -> &str { &self.description } fn connector(&self, url: &Url) -> Option<BoxedConnector> { if (url.scheme() == "socket" || url.scheme() == "tcp") ...
f { name: "tcp-socket".into(), description: "Support for tcp/ip network socket connections.".into(), resolver, } }
function_block-function_prefixed
[ { "content": "#[derive(Clone)]\n\nstruct SerialConnector {\n\n url: Url,\n\n builder: SerialPortBuilder,\n\n}\n\n\n\nimpl Connector for SerialConnector {\n\n fn url(&self) -> &Url {\n\n &self.url\n\n }\n\n\n\n fn connect(&self) -> BoxedConnect {\n\n let this = self.clone();\n\n ...
Rust
codespan-reporting/src/emitter.rs
wycats/codespan
ecd9da5d5e296005526ce266f7fbc899cdfdb293
use codespan::CodeMap; use std::{fmt, io}; use termcolor::{Color, ColorSpec, WriteColor}; use {Diagnostic, LabelStyle}; struct Pad<T>(T, usize); impl<T: fmt::Display> fmt::Display for Pad<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for _ in 0..(self.1) { self.0.fmt(f)?; ...
use codespan::CodeMap; use std::{fmt, io}; use termcolor::{Color, ColorSpec, WriteColor}; use {Diagnostic, LabelStyle}; struct Pad<T>(T, usize); impl<T: fmt::Display> fmt::Display for Pad<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for _ in 0..(self.1) { self.0.fmt(f)?; ...
writer.reset()?; }, } }, } } Ok(()) }
LabelStyle::Secondary => ColorSpec::new() .set_fg(Some(if cfg!(windows) { Color::Cyan } else { Color::Blue })) .clone(), }; ...
random
[ { "content": "/// Translates a `codespan_reporting::Diagnostic` to a `languageserver_types::Diagnostic`.\n\n///\n\n/// Since the language client requires `Url`s to locate the errors `codespan_name_to_file` is\n\n/// necessary to resolve codespan `FileName`s\n\n///\n\n/// `code` and `source` are left empty by th...
Rust
common/mixnode-common/src/cached_packet_processor/processor.rs
confio/nym
495ca35c1f46e7244d89fdf73402021d70df625d
use crate::cached_packet_processor::cache::KeyCache; use crate::cached_packet_processor::error::MixProcessingError; use log::*; use nymsphinx_acknowledgements::surb_ack::SURBAck; use nymsphinx_addressing::nodes::NymNodeRoutingAddress; use nymsphinx_forwarding::packet::MixPacket; use nymsphinx_framing::packet::FramedS...
use crate::cached_packet_processor::cache::KeyCache; use crate::cached_packet_processor::error::MixProcessingError; use log::*; use nymsphinx_acknowledgements::surb_ack::SURBAck; use nymsphinx_addressing::nodes::NymNodeRoutingAddress; use nymsphinx_forwarding::packet::MixPacket; use nymsphinx_framing::packet::FramedS...
} async fn perform_final_processing( &self, packet: ProcessedPacket, packet_size: PacketSize, packet_mode: PacketMode, ) -> Result<MixProcessingResult, MixProcessingError> { match packet { ProcessedPacket::ForwardHop(packet, address, delay) => ...
Ok(MixProcessingResult::FinalHop(ProcessedFinalHop { destination, forward_ack, message, }))
call_expression
[ { "content": "type CachedKeys = (Option<SharedSecret>, RoutingKeys);\n\n\n\npub(super) struct KeyCache {\n\n vpn_key_cache: Arc<DashMap<SharedSecret, CachedKeys>>,\n\n invalidator_sender: InvalidatorActionSender,\n\n cache_entry_ttl: Duration,\n\n}\n\n\n\nimpl Drop for KeyCache {\n\n fn drop(&mut se...
Rust
claybrick/src/pdf/xref.rs
weichweich/claybrick
b5548b4b6dedceabc22373c004a4d9e21f766244
#[derive(Debug, Clone, PartialEq)] pub enum XrefKind { Table, Stream { number: usize, generation: usize }, } #[derive(Debug, Clone, PartialEq)] pub struct Xref { pub(crate) entries: Vec<XrefEntry>, pub(crate) kind: Option<XrefKind>, } impl Xref { pub(crate) fn new(mut entries: Vec<XrefE...
#[derive(Debug, Clone, PartialEq)] pub enum XrefKind { Table, Stream { number: usize, generation: usize }, } #[derive(Debug, Clone, PartialEq)] pub struct Xref { pub(crate) entries: Vec<XrefEntry>, pub(crate) kind: Option<XrefKind>, } impl Xref { pub(crate) fn new(mut entries: Vec<XrefE...
} } impl From<Unsupported> for XrefEntry { fn from(v: Unsupported) -> Self { Self::Unsupported(v) } } impl From<UsedCompressedObject> for XrefEntry { fn from(v: UsedCompressedObject) -> Self { Self::UsedCompressed(v) } } impl From<UsedObject> for XrefEntry { fn from(v: UsedOb...
match self { XrefEntry::Free(FreeObject { number, .. }) => *number, XrefEntry::Used(UsedObject { number, .. }) => *number, XrefEntry::UsedCompressed(UsedCompressedObject { number, .. }) => *number, XrefEntry::Unsupported(Unsupported { number, .. }) => *number, }
if_condition
[ { "content": "/// Fills the byte buffer using the iterator. Returns the number of elements\n\n/// that where copied to the buffer.\n\nfn fill_from_iter<'a>(stream: &mut impl Iterator<Item = &'a u8>, buf: &mut [u8]) -> usize {\n\n for (i, digit) in buf.iter_mut().enumerate() {\n\n if let Some(&b) = str...
Rust
game/src/board_fen.rs
dalloriam/chessengine
4c8df7eb306e029e30c998889901fe2b177d8920
use std::{convert::TryFrom, num::ParseIntError}; use snafu::{ensure, ResultExt, Snafu}; use crate::{ board::CastleState, constants::BOARD_DIMENSION, pieces::PieceError, square::Error as SquareError, Board, Color, Column, Piece, PieceType, Square, }; #[derive(Debug, Snafu)] pub enum FenError { InvalidFEN,...
use std::{convert::TryFrom, num::ParseIntError}; use snafu::{ensure, ResultExt, Snafu}; use crate::{ board::CastleState, constants::BOARD_DIMENSION, pieces::PieceError, square::Error as SquareError, Board, Color, Column, Piece, PieceType, Square, }; #[derive(Debug, Snafu)] pub enum FenError { InvalidFEN,...
, PieceType::Rook => match piece.color { Color::White => { let rook_squares = &[Square::new(Column::A, 0), Square::new(Column::H, 0)]; if !rook_squares.contains(&squar...
match piece.color { Color::White => { board.white_king_position = square.clone(); } Color::Black => { board.black_king_position = square.clone(); ...
if_condition
[]
Rust
src/main.rs
Gachapen/lsystem
e3428b68e1fc7a9ffff0f8646751c6174dddf8c5
extern crate bincode; extern crate chrono; extern crate clap; extern crate cpuprofiler; extern crate crossbeam; extern crate csv; extern crate futures; extern crate futures_cpupool; extern crate glfw; extern crate kiss3d; #[cfg(feature = "record")] extern crate mpeg_encoder; extern crate nalgebra as na; extern crate nc...
extern crate bincode; extern crate chrono; extern crate clap; extern crate cpuprofiler; extern crate crossbeam; extern crate csv; extern crate futures; extern crate futures_cpupool; extern crate glfw; extern crate kiss3d; #[cfg(feature = "record")] extern crate mpeg_encoder; extern crate nalgebra as na; extern crate nc...
fn setup_window() -> (Window, ArcBall) { configure_window(Window::new("lsystem")) } #[allow(dead_code)] fn setup_window_with_size(width: u32, height: u32) -> (Window, ArcBall) { configure_window(Window::new_with_size("lsystem", width, height)) } fn configure_window(mut window: Window) -> (Window, ArcBall) {...
fn main() { let matches = App::new("lsystem") .version("0.0.1") .author("Magnus Bjerke Vik <mbvett@gmail.com>") .about("Various L-system generation and visualization experiments") .subcommand(SubCommand::with_name("static").about("Run visualization of static plant")) .subcomm...
function_block-full_function
[ { "content": "/// Save an `ol::LSystem` to the \"model\" directory with the current date time as the filename.\n\npub fn save_lsystem(lsystem: &ol::LSystem) -> PathBuf {\n\n let model_dir = Path::new(\"model\");\n\n fs::create_dir_all(model_dir).unwrap();\n\n\n\n let filename = format!(\"{}.yaml\", Loc...
Rust
src/macros.rs
Ogeon/rustful
24173f35462a976e53d7826c1b107a995572d132
/** A macro for making content types. It takes a main type, a sub type and a parameter list. Instead of this: ```rust use rustful::header::ContentType; use rustful::mime::{Mime, TopLevel, SubLevel, Attr, Value}; ContentType( Mime ( TopLevel::Text, SubLevel::Html, vec![(Attr::Charset, Va...
/** A macro for making content types. It takes a main type, a sub type and a parameter list. Instead of this: ```rust use rustful::header::ContentType; use rustful::mime::{Mime, TopLevel, SubLevel, Attr, Value}; ContentType( Mime ( TopLevel::Text, SubLevel::Html, vec![(Attr::Charset, Va...
} impl<'a, T: FromStr> From<&'a str> for MimeHelper<'a, T> { fn from(s: &'a str) -> MimeHelper<'a, T> { MimeHelper::Str(s) } } impl<'a> From<TopLevel> for MimeHelper<'a, TopLevel> { fn from(t: TopLevel) -> MimeHelper<'a, TopLevel> { MimeHelper::Target(t) } } impl<'a> From<SubLevel> f...
t(self) -> T { match self { MimeHelper::Str(s) => s.parse().unwrap(), MimeHelper::Target(t) => t } }
function_block-function_prefixed
[ { "content": "///Returns the MIME type from a given file extension, if known.\n\n///\n\n///The file extension to MIME type mapping is based on [data from the Apache\n\n///server][apache].\n\n///\n\n///```\n\n///use rustful::file::ext_to_mime;\n\n///use rustful::mime::Mime;\n\n///use rustful::mime::TopLevel::Ima...
Rust
src/commands/otaku.rs
KurozeroPB/Maika
06c5e3cba266ebe5710f97120a28fb07490708ef
use serenity::utils::Colour; use kitsu::KitsuReqwestRequester; use reqwest::Client; use utils::logger; command!(anime(_ctx, msg, args) { if args.is_empty() { let _ = msg.channel_id.say("Which anime should I search for?"); return Ok(()); } let search = args.full(); let client = Client::new(); if let Ok(result...
use serenity::utils::Colour; use kitsu::KitsuReqwestRequester; use reqwest::Client; use utils::logger; command!(anime(_ctx, msg, args) { if args.is_empty() { let _ = msg.channel_id.say("Which anime should I search for?"); return Ok(()); } let search = args.full(); let client = Client::new(); if let Ok(result...
.description(&manga_synopsis) .thumbnail(manga_poster_image) .field("Average Rating", &manga_average_rating, true) .field("Type", &format!("{:?}", manga_type), true) .field("Volumes", &manga_volume_count, true) .field("Chapters", &manga_chapter_count, true) .field("Start/End", &format!("...
} }); command!(manga(_ctx, msg, args) { if args.is_empty() { let _ = msg.channel_id.say("Which manga should I search for?"); return Ok(()); } let search = args.full(); let client = Client::new(); if let Ok(result) = client.search_manga(|f| f.filter("text", &search)){ if let Some(mango) = result.data.get(0...
random
[ { "content": "pub fn info(msg: String) {\n\n\tprintln!(\"{}\", msg.green().bold());\n\n}\n\n\n\n/* Not yet used\n", "file_path": "src/utils/logger.rs", "rank": 0, "score": 52933.50863657707 }, { "content": "pub fn error(msg: String) {\n\n println!(\"{}\", msg.red().bold());\n\n}\n\n\n", ...
Rust
oqs/src/sig.rs
KEMTLS-SIKE/oqs-rs
e7614dcaab81fbe9b713f4efaf37aa561c807286
use alloc::vec::Vec; use core::ptr::NonNull; #[cfg(not(feature = "std"))] use cstr_core::CStr; #[cfg(feature = "std")] use std::ffi::CStr; use crate::ffi::sig as ffi; use crate::newtype_buffer; use crate::*; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; newtype_buffer!(PublicKey, PublicKeyRef); ...
use alloc::vec::Vec; use core::ptr::NonNull; #[cfg(not(feature = "std"))] use cstr_core::CStr; #[cfg(feature = "std")] use std::ffi::CStr; use crate::ffi::sig as ffi; use crate::newtype_buffer; use crate::*; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; newtype_buffer!(PublicKey, PublicKeyRef); ...
pub fn signature_from_bytes<'a>(&self, buf: &'a [u8]) -> Option<SignatureRef<'a>> { if buf.len() > self.length_signature() { None } else { Some(SignatureRef::new(buf)) } } pub fn keypair(&self) -> Result<(PublicKey, SecretKey)> { let sig =...
pub fn public_key_from_bytes<'a>(&self, buf: &'a [u8]) -> Option<PublicKeyRef<'a>> { if buf.len() != self.length_public_key() { None } else { Some(PublicKeyRef::new(buf)) } }
function_block-full_function
[ { "content": "fn main() -> Result<()> {\n\n oqs::init();\n\n let kemalg = kem::Kem::new(kem::Algorithm::SikeP434Compressed1CCA).unwrap();\n\n\n\n // A -> B: kem_pk\n\n let start = Instant::now();\n\n kemalg.init()?;\n\n let elapsed = start.elapsed();\n\n println!(\"Init Millis: {} ms\", ela...
Rust
third_party/rust_crates/vendor/backtrace/src/dbghelp.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
#![allow(non_snake_case)] use crate::windows::*; use core::mem; use core::ptr; #[cfg(feature = "verify-winapi")] mod dbghelp { use crate::windows::*; pub use winapi::um::dbghelp::{ StackWalk64, SymCleanup, SymFromAddrW, SymFunctionTableAccess64, SymGetLineFromAddrW64, SymGetModuleBase64, Sym...
#![allow(non_snake_case)] use crate::windows::*; use core::mem; use core::ptr; #[cfg(feature = "verify-winapi")] mod dbghelp { use crate::windows::*; pub use winapi::um::dbghelp::{ StackWalk64, SymCleanup, SymFromAddrW, SymFunctionTableAccess64, SymGetLineFromAddrW64, SymGetModuleBase64, Sym...
}
fn drop(&mut self) { unsafe { let r = ReleaseMutex(self.lock); debug_assert!(r != 0); } }
function_block-full_function
[]
Rust
src/lib.rs
dotcypress/pid-loop
984f4522f742c8c4fe1a11b52ef66cabb9dde304
#![no_std] #![deny(nonstandard_style, future_incompatible, rust_2018_idioms)] use core::ops::*; pub struct PID<F, const W: usize> { pub kp: F, pub ki: F, pub kd: F, pub kf: F, pub kv: F, last_sp: F, last_error_idx: usize, errors: [F; W], err_history: F, } ...
#![no_std] #![deny(nonstandard_style, future_incompatible, rust_2018_idioms)] use core::ops::*; pub struct PID<F, const W: usize> { pub kp: F, pub ki: F, pub kd: F, pub kf: F, pub kv: F, last_sp: F, last_error_idx: usize, errors: [F; W], err_history: F, } ...
}
0; } self.err_history = self.err_history - self.errors[self.last_error_idx]; self.err_history = self.err_history + error; self.errors[self.last_error_idx] = error; }
function_block-function_prefixed
[]
Rust
datafusion/core/tests/join_fuzz.rs
PierreZ/arrow-datafusion
9745fc4146ade60f3c46e72c5e46bacb5e11617f
use std::sync::Arc; use arrow::array::{ArrayRef, Int32Array}; use arrow::compute::SortOptions; use arrow::record_batch::RecordBatch; use arrow::util::pretty::pretty_format_batches; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; use datafusion::logical_plan::JoinType; use datafusion::physical_plan::collect; u...
use std::sync::Arc; use arrow::array::{ArrayRef, Int32Array}; use arrow::compute::SortOptions; use arrow::record_batch::RecordBatch; use arrow::util::pretty::pretty_format_batches; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; use datafusion::logical_plan::JoinType; use datafusion::physical_plan::collect; u...
#[tokio::test] async fn test_anti_join_1k() { run_join_test( make_staggered_batches(10000), make_staggered_batches(10000), JoinType::Anti, ) .await } async fn run_join_test( input1: Vec<RecordBatch>, input2: Vec<RecordBatch>, join_type: JoinType, ) { let batch_size...
in_test( make_staggered_batches(10000), make_staggered_batches(10000), JoinType::Semi, ) .await }
function_block-function_prefixed
[ { "content": "fn make_topk_context() -> SessionContext {\n\n let config = SessionConfig::new().with_target_partitions(48);\n\n let runtime = Arc::new(RuntimeEnv::new(RuntimeConfig::default()).unwrap());\n\n let state = SessionState::with_config_rt(config, runtime)\n\n .with_query_planner(Arc::ne...
Rust
kubert/src/server.rs
adleong/kubert
e0286c83faa56e8a28ff24e64e3acab58cac9ea7
use std::{convert::Infallible, net::SocketAddr, path::PathBuf, str::FromStr, sync::Arc}; use thiserror::Error; use tokio::net::{TcpListener, TcpStream}; use tokio_rustls::{rustls, TlsAcceptor}; use tower_service::Service; use tracing::{debug, error, info, info_span, Instrument}; #[derive(Clone, Debug)] #[cfg_attr(fe...
use std::{convert::Infallible, net::SocketAddr, path::PathBuf, str::FromStr, sync::Arc}; use thiserror::Error; use tokio::net::{TcpListener, TcpStream}; use tokio_rustls::{rustls, TlsAcceptor}; use tower_service::Service; use tracing::{debug, error, info, info_span, Instrument}; #[derive(Clone, Debug)] #[cfg_attr(fe...
async fn load_tls(pk: &TlsKeyPath, crts: &TlsCertPath) -> Result<TlsAcceptor, Error> { let key = pk .load_private_key() .await .map_err(Error::TlsKeyReadError)?; let certs = crts.load_certs().await.map_err(Error::TlsCertsReadError)?; let mut cfg = rustls::ServerConfig::builder() ...
e = drain.signaled() => { Pin::new(&mut conn).graceful_shutdown(); release.release_after(conn).await } }; match res { Ok(()) => debug!("Connection closed"), Err(error) => info!(%error, "Connection lost"), } }
function_block-function_prefixed
[ { "content": "#[cfg_attr(docsrs, doc(cfg(feature = \"shutdown\")))]\n\npub fn sigint_or_sigterm() -> Result<(Shutdown, Watch), RegisterError> {\n\n let interrupt = signal(SignalKind::interrupt())?;\n\n let terminate = signal(SignalKind::terminate())?;\n\n\n\n let (tx, rx) = drain::channel();\n\n let...
Rust
wavetk/src/fst.rs
thomashk0/wave
20df2198645b40f782328a8c8c10d36f8dbe4583
use std::convert::TryFrom; use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_uchar, c_void}; use std::ptr::null_mut; use std::slice; use std::str; use crate::types::{Direction, FstHeader, Scope, ScopeKind, VariableInfo, VariableKind}; use fst_sys; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum ...
use std::convert::TryFrom; use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_uchar, c_void}; use std::ptr::null_mut; use std::slice; use std::str; use crate::types::{Direction, FstHeader, Scope, ScopeKind, VariableInfo, VariableKind}; use fst_sys; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum ...
&mut self, range: Option<(u64, u64)>) { match range { None => unsafe { fst_sys::fstReaderSetUnlimitedTimeRange(self.handle) }, Some((start, end)) => unsafe { fst_sys::fstReaderSetLimitTimeRange(self.handle, start, end) }, } } } impl Drop for FstRe...
string() } } impl FstReader { pub fn from_file(name: &str, use_extensions: bool) -> Result<FstReader, FstError> { let p = unsafe { fst_sys::fstReaderOpen(CString::new(name).unwrap().as_ptr()) }; if p.is_null() { return Err(FstError::InvalidFile); } if use_extensions ...
random
[ { "content": "/// Identifiers for variables\n\ntype VarHandle = u32;\n\n\n\n/// Analogous to VariableInfo (for VCD), the two representation will be merged soon\n\n#[derive(Debug, Clone, PartialEq, Serialize)]\n\npub struct VariableInfo {\n\n pub id: String,\n\n pub name: String,\n\n pub direction: Dire...
Rust
src/persist/src/postgres.rs
guswynn/materialize
f433173ed71f511d91311769ec58c2d427dd6c3b
use std::time::Instant; use anyhow::{anyhow, bail, Context}; use async_trait::async_trait; use bytes::Bytes; use openssl::ssl::{SslConnector, SslFiletype, SslMethod, SslVerifyMode}; use postgres_openssl::MakeTlsConnector; use tokio::task::JoinHandle; use tokio_postgres::config::SslMode; use tokio_postgres::types::{t...
use std::time::Instant; use anyhow::{anyhow, bail, Context}; use async_trait::async_trait; use bytes::Bytes; use openssl::ssl::{SslConnector, SslFiletype, SslMethod, SslVerifyMode}; use postgres_openssl::MakeTlsConnector; use tokio::task::JoinHandle; use tokio_postgres::config::SslMode; use tokio_postgres::types::{t...
} else { Ok(results) } } async fn truncate( &self, deadline: Instant, key: &str, seqno: SeqNo, ) -> Result<(), ExternalError> { let q = "DELETE FROM consensus WHERE shard = $1 AND sequence_number < $2 AND E...
Err(ExternalError::from(anyhow!( "sequence number lower bound too high for scan: {:?}", from )))
call_expression
[ { "content": "fn write_value_ref(schema: &Schema, value: &Value, buffer: &mut Vec<u8>) -> Result<(), Error> {\n\n if !value.validate(schema.top_node()) {\n\n return Err(ValidationError::new(\"value does not match schema\").into());\n\n }\n\n encode_ref(value, schema.top_node(), buffer);\n\n O...
Rust
src/client/mock.rs
flier/tokio-kafka
0ae7e34766832f6bc3d0df52042f4ebb5f9d107f
#![allow(unused_variables)] use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::time::Duration; use std::usize; use bytes::Bytes; use typemap::{Key, TypeMap}; use tokio_core::reactor::Handle; use client::{Broker, BrokerRef, Client, Cluster, ConsumerGroup, ConsumerG...
#![allow(unused_variables)] use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::time::Duration; use std::usize; use bytes::Bytes; use typemap::{Key, TypeMap}; use tokio_core::reactor::Handle; use client::{Broker, BrokerRef, Client, Cluster, ConsumerGroup, ConsumerG...
pub fn with_handle(mut self, handle: Handle) -> Self { self.handle = Some(handle); self } pub fn with_group_coordinator(mut self, group_id: Cow<'a, str>, broker: Broker) -> Self { self.group_coordinators.insert(group_id, broker); self } pub fn with_consumer_group(...
handle: None, metadata: Rc::new(metadata), group_coordinators: HashMap::new(), consumer_groups: HashMap::new(), member_assignments: HashMap::new(), future_responses: Rc::new(RefCell::new(TypeMap::custom())), } }
function_block-function_prefix_line
[ { "content": "/// A trait for representation of a subset of the nodes, topics, and partitions in the Kafka\n\n/// cluster.\n\npub trait Cluster {\n\n /// The known set of brokers.\n\n fn brokers(&self) -> &[Broker];\n\n\n\n /// Get all topic with partition information.\n\n fn topics(&self) -> HashMa...
Rust
rust/src/linalg/mod.rs
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
use std::f32; use std::ops::{Index, Mul, Add}; pub use self::vector::Vector; pub mod vector; pub fn cross<A: Index<usize, Output = f32>, B: Index<usize, Output = f32>>(a: &A, b: &B) -> Vector { Vector::new( a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], ...
use std::f32; use std::ops::{Index, Mul, Add}; pub use self::vector::Vector; pub mod vector; pub fn cross<A: Index<usize, Output = f32>, B: Index<usize, Output = f32>>(a: &A, b: &B) -> Vector { Vector::new( a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], ...
pub fn reflect(w: &Vector, v: &Vector) -> Vector { 2.0 * dot(w, v) * *v - *w } pub fn refract(w: &Vector, n: &Vector, eta_1: f32, eta_2: f32) -> Option<Vector> { let eta = eta_1 / eta_2; let cos_t1 = dot(n, w); let sin_t1_sqr = f32::max(0.0, 1.0 - f32::powf(cos_t1, 2.0)); let sin_t2_sqr = f32::po...
1.0 / f32::sqrt(e1.x * e1.x + e1.z * e1.z); Vector::new(-e1.z * inv_len, 0.0, e1.x * inv_len) } else { let inv_len = 1.0 / f32::sqrt(e1.y * e1.y + e1.z * e1.z); Vector::new(0.0, e1.z * inv_len, -e1.y * inv_len) }; let e3 = cross(e1, &e2); (e2, e3) }
function_block-function_prefixed
[ { "content": "fn main() {\n\n println!(\"{:?}\", linalg::Vector::new(1., 2., 3.));\n\n}\n", "file_path": "rust/src/main.rs", "rank": 12, "score": 66519.16053721431 }, { "content": "//! println!(\"{:?}\", a[2]); // will print the z value of a\n\n//! println!(\"{:?}\", a.z); // will print t...
Rust
rustsec/src/advisory/affected.rs
davidarreolam/rustsec
5ece87519d53db3091c37de8f50b8fea6cf74f0a
use crate::{ error::{Error, ErrorKind}, Map, }; use platforms::target::{Arch, OS}; use semver::VersionReq; use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer}; use std::{ fmt::{self, Display}, slice, str::FromStr, }; #[derive(Clone, Debug, Default, Deserialize, Eq,...
use crate::{ error::{Error, ErrorKind}, Map, }; use platforms::target::{Arch, OS}; use semver::VersionReq; use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer}; use std::{ fmt::{self, Display}, slice, str::FromStr, }; #[derive(Clone, Debug, Default, Deserialize, Eq,...
for c in chars { match c { 'A'..='Z' | 'a'..='z' | '0'..='9' | '_' | '<' | '>' | ',' => (), '(' | ')' => fail!( ErrorKind::Parse, "omit parameters when specifying affected paths: '{}'", identifier ), _ => fail!...
if let Some(first_char) = chars.next() { match first_char { 'A'..='Z' | 'a'..='z' | '_' | '<' => (), _ => fail!( ErrorKind::Parse, "invalid character at start of ident: '{}'", identifier ), } } else { fail!(E...
if_condition
[ { "content": "/// Prepare the authentication callbacks for cloning a git repository.\n\n///\n\n/// The main purpose of this function is to construct the \"authentication\n\n/// callback\" which is used to clone a repository. This callback will attempt to\n\n/// find the right authentication on the system (witho...
Rust
onion/src/hop.rs
LightningPeach/lpd
6c6797f4fd06a477525273583f5d2922c0fee40f
use dependencies::secp256k1; use dependencies::chacha; use super::crypto::HmacData; use wire::{Satoshi, ShortChannelId}; use secp256k1::PublicKey; use serde::{Serialize, Serializer, Deserialize, Deserializer}; use chacha::{ChaCha, KeyStream}; use std::ops::BitXorAssign; #[derive(Debug, Clone, Eq, PartialEq)] pub stru...
use dependencies::secp256k1; use dependencies::chacha; use super::crypto::HmacData; use wire::{Satoshi, ShortChannelId}; use secp256k1::PublicKey; use serde::{Serialize, Serializer, Deserialize, Deserializer}; use chacha::{ChaCha, KeyStream}; use std::ops::BitXorAssign; #[derive(Debug, Clone, Eq, PartialEq)] pub stru...
Ok(HopData::Bitcoin(bitcoin_data)) } t @ _ => panic!("unknown realm: {:?}", t), } } } deserializer.deserialize_tuple(2, V) } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struc...
let bitcoin_data = seq .next_element()? .ok_or(Error::custom("expecting hop data"))?;
assignment_statement
[ { "content": "// It is easy to derive such trait, just add `_extension: Option<E>` where `E` is also DBValue\n\npub trait DBValue: Serialize + DeserializeOwned {\n\n // Extension is also further DBValue\n\n type Extension: DBValue;\n\n\n\n fn extend(self, e: Self::Extension) -> Self;\n\n fn cf_name(...
Rust
html-parser/core/src/lib.rs
pitbuster/deno-dom
06a1a0199968c42102fb40f3ad205dc19a61d978
mod rcdom; use crate::rcdom::Node; use crate::rcdom::NodeData; pub use crate::rcdom::RcDom; use html5ever::driver::parse_document; use html5ever::driver::parse_fragment; use html5ever::tendril::stream::TendrilSink; use html5ever::{namespace_url, ns}; use markup5ever::Attribute; use markup5ever::{LocalName, QualName}; ...
mod rcdom; use crate::rcdom::Node; use crate::rcdom::NodeData; pub use crate::rcdom::RcDom; use html5ever::driver::parse_document; use html5ever::driver::parse_fragment; use html5ever::tendril::stream::TendrilSink; use html5ever::{namespace_url, ns}; use markup5ever::Attribute; use markup5ever::{LocalName, QualName}; ...
} write!(&mut *buf, "]").unwrap(); }
if idx + 1 < vec_count { write!(&mut *buf, "],").unwrap(); } else { write!(&mut *buf, "]").unwrap(); }
if_condition
[ { "content": "#[wasm_bindgen]\n\npub fn parse_frag(html: &str) -> String {\n\n parse_frag_rs(html.into())\n\n}\n\n\n", "file_path": "html-parser/wasm/src/lib.rs", "rank": 6, "score": 152574.19797322125 }, { "content": "#[wasm_bindgen]\n\npub fn parse(html: &str) -> String {\n\n parse_r...
Rust
src/lib.rs
noloerino/ripples
2f1d0b60f9647ffaa30c9d8354a6f25be950a2dc
mod utils; use wasm_bindgen::prelude::*; type Coordinate = u16; type DropletStrength = u16; type Color = u32; type RippleCtr = u16; struct Droplets { xs: Vec<Coordinate>, ys: Vec<Coordinate>, next_mags: Vec<DropletStrength>, ripple_freqs: Vec<RippleCtr>, ripple_ctrs: Vec<RippleCtr>...
mod utils; use wasm_bindgen::prelude::*; type Coordinate = u16; type DropletStrength = u16; type Color = u32; type RippleCtr = u16; struct Droplets { xs: Vec<Coordinate>, ys: Vec<Coordinate>, next_mags: Vec<DropletStrength>, ripple_freqs: Vec<RippleCtr>, ripple_ctrs: Vec<RippleCtr>...
pub fn add_droplet( &mut self, x: Coordinate, y: Coordinate, mag: DropletStrength, color: Color, freq: RippleCtr, ) { if x >= self.width || y >= self.height || mag == 0 { return; } let Droplets { xs, ys...
pub fn tick(&mut self) { if self.paused { return; } let Droplets { xs, ys, next_mags, ripple_freqs, ripple_ctrs, colors, ripple_mags, ripple_max_mags, ripple_counts, ...
function_block-function_prefix_line
[ { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
contracts/mixnet/src/queries.rs
huitseeker/nym
6a1c2fa5dd1a55bddc6f1d0f750a3c137a4bb8bf
use crate::state::{config_read, gateways_read, mixnodes_read, StateParams, PREFIX_MIXNODES}; use cosmwasm_std::Deps; use cosmwasm_std::HumanAddr; use cosmwasm_std::Order; use cosmwasm_std::StdResult; use cosmwasm_storage::bucket_read; use mixnet_contract::{ GatewayBond, GatewayOwnershipResponse, MixNodeBond, MixOw...
use crate::state::{config_read, gateways_read, mixnodes_read, StateParams, PREFIX_MIXNODES}; use cosmwasm_std::Deps; use cosmwasm_std::HumanAddr; use cosmwasm_std::Order; use cosmwasm_std::StdResult; use cosmwasm_storage::bucket_read; use mixnet_contract::{ GatewayBond, GatewayOwnershipResponse, MixNodeBond, MixOw...
fn calculate_start_value( start_after: std::option::Option<cosmwasm_std::HumanAddr>, ) -> Option<Vec<u8>> { start_after.as_ref().map(|addr| { let mut bytes = addr.as_bytes().to_owned(); bytes.push(0); bytes }) } pub(crate) fn query_state_params(deps: Deps) -> StateParams { ...
let has_gateway = gateways_read(deps.storage) .may_load(address.as_ref())? .is_some(); Ok(GatewayOwnershipResponse { address, has_gateway, }) }
function_block-function_prefix_line
[ { "content": "pub fn mixnodes_read(storage: &dyn Storage) -> ReadonlyBucket<MixNodeBond> {\n\n bucket_read(storage, PREFIX_MIXNODES)\n\n}\n\n\n\n// Gateway-related stuff\n\n\n\npub const PREFIX_GATEWAYS: &[u8] = b\"gateways\";\n\n\n", "file_path": "contracts/mixnet/src/state.rs", "rank": 0, "scor...
Rust
sdl_viewer/src/terrain_drawer/layer.rs
googlecartographer/point_cloud_viewer
189a81d53b3f674c7738a6a16d9674c20fc7c106
use crate::graphic::tiled_texture_loader::TiledTextureLoader; use crate::graphic::{GlMovingWindowTexture, GlProgram, GlUniform}; use crate::terrain_drawer::read_write::Metadata; use image::{ImageBuffer, LumaA, Rgba}; use nalgebra::{Isometry3, Matrix4, Point3, Vector2, Vector3}; use std::convert::TryInto; use std::io; u...
use crate::graphic::tiled_texture_loader::TiledTextureLoader; use crate::graphic::{GlMovingWindowTexture, GlProgram, GlUniform}; use crate::terrain_drawer::read_write::Metadata; use image::{ImageBuffer, LumaA, Rgba}; use nalgebra::{Isometry3, Matrix4, Point3, Vector2, Vector3}; use std::convert::TryInto; use std::io; u...
} pub fn update(&mut self, cur_world_pos: Point3<f64>) { let cur_pos = self .grid_coordinates .terrain_pos_for_camera_pos(&cur_world_pos); let moved = cur_pos - self.terrain_pos; let hori_strip = if moved.y > 0 { self.load( ...
Ok(TerrainLayer { grid_coordinates, terrain_pos, u_terrain_pos, height_tiles, color_tiles, heightmap, colormap, texture_size, })
call_expression
[ { "content": "pub fn image_from_path(image_path: &Path) -> Option<ImageResult<RgbaImage>> {\n\n if image_path.exists() {\n\n Some(image::open(image_path).map(|image| image.to_rgba()))\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "xray/src/utils.rs", "rank": 0, "score"...
Rust
flow-rs/src/node/demux.rs
MegEngine/MegFlow
4bbf15acc21fb1f51e95311e28fb0a10fe4a91d3
/** * \file flow-rs/src/node/demux.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BA...
/** * \file flow-rs/src/node/demux.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BA...
} node_register!("Demux", Demux); #[cfg(test)] mod test { use crate::envelope::Envelope; use crate::sandbox::Sandbox; #[flow_rs::rt::test] async fn test_demux() { let demux = Sandbox::pure("Demux").unwrap(); let input = demux.input("inp").unwrap(); let output = demux.output("o...
async fn exec(&mut self, _: &Context) -> Result<()> { if let Ok(msg) = self.inp.recv_any().await { let id = msg .info() .to_addr .expect("the envelope has no destination address"); if let Some(out) = self.out.get(&id) { out....
function_block-full_function
[ { "content": "/// prevents from long stupid paths, and replace the home path by the literal `$HOME`\n\nfn pretty_path(a: &Path) -> Result<String> {\n\n #[cfg(unix)]\n\n let home_var = \"$HOME\";\n\n #[cfg(windows)]\n\n let home_var = \"%userprofile%\";\n\n Ok(a.display()\n\n .to_string()\n...
Rust
src/main.rs
sanxiyn/linky
ed62c6e3342fe96940555e3d197b4bf87be8a03c
mod error; mod linky; use std::borrow::Cow; use std::cmp; use std::collections::hash_map::Entry; use std::collections::BinaryHeap; use std::collections::HashMap; use std::collections::HashSet; use std::fmt; use std::fs; use std::io; use std::io::BufRead; use std::iter; use std::iter::FromIterator; use std::path::PathB...
mod error; mod linky; use std::borrow::Cow; use std::cmp; use std::collections::hash_map::Entry; use std::collections::BinaryHeap; use std::collections::HashMap; use std::collections::HashSet; use std::fmt; use std::fs; use std::io; use std::io::BufRead; use std::iter; use std::iter::FromIterator; use std::path::PathB...
fn print_result( record: &Record, res: &Option<Result<(), Arc<error::Error>>>, silence: &HashSet<&Tag>, ) { let tag = res .as_ref() .map(|res| res.as_ref().err().map(|err| err.tag).unwrap_or(Tag::Ok)); if !tag.as_ref().map_or(false, |tag| silence.contains(&tag)) { if let S...
fn group_fragments( mut acc: HashMap<Link, Vec<(usize, Option<String>, Record)>>, link: (usize, (Record, Link, Option<String>)), ) -> HashMap<Link, Vec<(usize, Option<String>, Record)>> { let (index, (record, base, fragment)) = link; match acc.entry(base.clone()) { Entry::Vacant(vacant) => { ...
function_block-full_function
[ { "content": "pub fn slurp<P: AsRef<Path>>(filename: &P, mut buffer: &mut String) -> io::Result<usize> {\n\n File::open(filename.as_ref())?.read_to_string(&mut buffer)\n\n}\n\n\n\nlazy_static! {\n\n static ref GITHUB_PUNCTUATION: Regex = Regex::new(r\"[^\\w -]\").unwrap();\n\n}\n\n\n", "file_path": "s...
Rust
datafusion/row/src/accessor.rs
PierreZ/arrow-datafusion
9745fc4146ade60f3c46e72c5e46bacb5e11617f
use crate::layout::{RowLayout, RowType}; use crate::validity::NullBitsFormatter; use crate::{fn_get_idx, fn_get_idx_opt, fn_set_idx}; use arrow::datatypes::{DataType, Schema}; use arrow::util::bit_util::{get_bit_raw, set_bit_raw}; use datafusion_common::ScalarValue; use std::sync::Arc; pub struct RowAccessor<'a> { ...
use crate::layout::{RowLayout, RowType}; use crate::validity::NullBitsFormatter; use crate::{fn_get_idx, fn_get_idx_opt, fn_set_idx}; use arrow::datatypes::{DataType, Schema}; use arrow::util::bit_util::{get_bit_raw, set_bit_raw}; use datafusion_common::ScalarValue; use std::sync::Arc; pub struct RowAccessor<'a> { ...
} else { ScalarValue::$SCALAR(None) } } } }; } impl<'a> RowAccessor<'a> { pub fn new(schema: &Schema, row_type: RowType) -> Self { Self { layout: Arc::new(RowLayout::new(schema, row_type)), data: &mut []...
[macro_export] macro_rules! fn_add_idx { ($NATIVE: ident) => { paste::item! { pub fn [<add_ $NATIVE>](&mut self, idx: usize, value: $NATIVE) { if self.is_valid_at(idx) { self.[<set_ $NATIVE>](idx, value + self.[<get_ $NATIVE>](idx)); ...
random
[ { "content": "/// Returns if all fields are valid\n\npub fn all_valid(data: &[u8], n: usize) -> bool {\n\n for item in data.iter().take(n / 8) {\n\n if *item != ALL_VALID_MASK[7] {\n\n return false;\n\n }\n\n }\n\n if n % 8 == 0 {\n\n true\n\n } else {\n\n data...
Rust
day-12/src/main.rs
kecors/aoc21
8cade758934eb3093ff8095bc07122e2c6c57706
use std::collections::HashMap; use std::io::{stdin, Read}; #[derive(Debug, PartialEq, Eq, Hash, Clone)] enum Cave { Start, End, Big(String), Small(String), } impl From<&str> for Cave { fn from(string: &str) -> Self { match string { "start" => Cave::Start, "end" => C...
use std::collections::HashMap; use std::io::{stdin, Read}; #[derive(Debug, PartialEq, Eq, Hash, Clone)] enum Cave { Start, End, Big(String), Small(String), } impl From<&str> for Cave { fn from(string: &str) -> Self { match string { "start" => Cave::Start, "end" => C...
fn find_paths(&self, revisitable: bool) -> Vec<Vec<Cave>> { let mut complete_paths: Vec<Vec<Cave>> = Vec::new(); let mut partial_paths: Vec<(Vec<Cave>, bool)> = Vec::new(); for cave in self.connections[&Cave::Start].iter() { partial_paths.push((vec![Cave::Start, cave.clone()],...
fn new(input: String) -> State { let mut connections: HashMap<Cave, Vec<Cave>> = HashMap::new(); let pairs: Vec<(Cave, Cave)> = input .lines() .map(|line| { let strs: Vec<&str> = line.split('-').collect(); (Cave::from(strs[0]), Cave::from(strs[1])...
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nstruct State {\n\n iea: Iea,\n\n image: Image,\n\n field: bool,\n\n}\n\n\n\nimpl State {\n\n fn new(input: &str) -> State {\n\n let iea = Iea::new(input.lines().take_while(|line| !line.is_empty()).collect());\n\n let image = Image::new(\n\n ...
Rust
src/chunk/animation_key.rs
KernelErr0r/spooky_bsp
84fb0a6cf6766d3885e00800c5b409883d6dcb80
use crate::{BoundingBox, Decode, QuantizedQuaternion, Vector3}; use derive_new::new; use num_enum::TryFromPrimitive; use std::io::Read; #[derive(new)] pub struct AnimationKey { pub type_: i32, pub target_hash: u32, pub time_step: f32, pub material_block_index: u16, pub bounding_box_maximum: Option...
use crate::{BoundingBox, Decode, QuantizedQuaternion, Vector3}; use derive_new::new; use num_enum::TryFromPrimitive; use std::io::Read; #[derive(new)] pub struct AnimationKey { pub type_: i32, pub target_hash: u32, pub time_step: f32, pub material_block_index: u16, pub bounding_box_maximum: Option...
odulationType::decode(reader, ())?, Vector3::decode(reader, ())?, Vector3::decode(reader, ())?, )) } } #[derive(Debug, TryFromPrimitive, PartialEq, Eq)] #[repr(i32)] pub enum AdaptiveDifferentialPulseCodeModulationType { None = 0, Linear = 1, Exponential = 2, } impl Dec...
impl Read, _state: ()) -> eyre::Result<Self> { Ok(Self::new( AdaptiveDifferentialPulseCodeModulationType::decode(reader, ())?, AdaptiveDifferentialPulseCodeM
function_block-random_span
[ { "content": "pub trait Decode<S = ()>\n\nwhere\n\n Self: Sized,\n\n{\n\n type Output = Self;\n\n\n\n fn decode(reader: &mut impl Read, state: S) -> eyre::Result<Self::Output>;\n\n}\n\n\n\nimpl Decode for bool {\n\n fn decode(reader: &mut impl Read, _state: ()) -> eyre::Result<Self> {\n\n Ok(...
Rust
src/base/gl/nm.rs
math4tots/mtots_core
8af09eab832fa728057fea23aec8354c3e9f5da1
use super::*; pub struct NativeModule { name: RcStr, data: Box<dyn FnOnce(&mut Globals) -> NativeModuleData>, } pub struct NativeModuleData { pub(super) fields: Vec<RcStr>, pub(super) init: Box<dyn FnOnce(&mut Globals, &HashMap<RcStr, Rc<RefCell<Value>>>) -> Result<()>>, pub(super) doc: Op...
use super::*; pub struct NativeModule { name: RcStr, data: Box<dyn FnOnce(&mut Globals) -> NativeModuleData>, } pub struct NativeModuleData { pub(super) fields: Vec<RcStr>, pub(super) init: Box<dyn FnOnce(&mut Globals, &HashMap<RcStr, Rc<RefCell<Value>>>) -> Result<()>>, pub(super) doc: Op...
pub fn getattr<F>(&mut self, f: F) -> &mut Self where F: Fn(&mut Globals, Handle<T>, &str) -> Result<Option<Value>> + 'static, { self.behavior.getattr(f); self } pub fn setattr<F>(&mut self, f: F) -> &mut Self where F: Fn(&mut Globals, Handle<T>, &str, Value) -> ...
pub fn repr<F>(&mut self, f: F) -> &mut Self where F: Fn(&T) -> RcStr + 'static, { self.behavior.repr(f); self }
function_block-full_function
[]
Rust
src/job.rs
ohadravid/win32job-rs
e6bf728cf03f7a778e551f3bb24dceb7df7bfb03
use crate::error::JobError; use crate::limits::ExtendedLimitInfo; use std::{io, mem, ptr}; use winapi::shared::minwindef::*; use winapi::um::handleapi::*; use winapi::um::jobapi2::*; use winapi::um::winnt::*; pub use crate::utils::{get_current_process, get_process_memory_info}; #[derive(Debug)] pub struct Job { h...
use crate::error::JobError; use crate::limits::ExtendedLimitInfo; use std::{io, mem, ptr}; use winapi::shared::minwindef::*; use winapi::um::handleapi::*; use winapi::um::jobapi2::*; use winapi::um::winnt::*; pub use crate::utils::{get_current_process, get_process_memory_info}; #[derive(Debug)] pub struct Job { h...
pub fn assign_current_process(&self) -> Result<(), JobError> { let current_proc_handle = get_current_process(); self.assign_process(current_proc_handle) } } impl Drop for Job { fn drop(&mut self) { unsafe { CloseHandle(self.handle); } } } #[cfg(test)...
pub fn assign_process(&self, proc_handle: HANDLE) -> Result<(), JobError> { let return_value = unsafe { AssignProcessToJobObject(self.handle, proc_handle) }; if return_value == 0 { Err(JobError::AssignFailed(io::Error::last_os_error())) } else { Ok(()) } }
function_block-full_function
[ { "content": "/// Retrieves information about the memory usage of the specified process.\n\n/// See also [Microsoft Docs](https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getprocessmemoryinfo) for this function.\n\npub fn get_process_memory_info(\n\n process_handle: HANDLE,\n\n) -> Result<PR...
Rust
built-in-services/asset/src/tests/mod.rs
KaoImin/muta
a0dff93744716590a80b555238d6e8cdb4e52101
use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; use async_trait::async_trait; use cita_trie::MemoryDB; use framework::binding::sdk::{DefaultChainQuerier, DefaultServiceSDK}; use framework::binding::state::{GeneralServiceState, MPTTrie}; use protocol::traits::{Context, NoopDispatcher, Storage}; use protoc...
use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; use async_trait::async_trait; use cita_trie::MemoryDB; use framework::binding::sdk::{DefaultChainQuerier, DefaultServiceSDK}; use framework::binding::state::{GeneralServiceState, MPTTrie}; use protocol::traits::{Context, NoopDispatcher, Storage}; use protoc...
#[test] fn test_transfer_from() { let cycles_limit = 1024 * 1024 * 1024; let caller = Address::from_hex("0x755cdba6ae4f479f7164792b318b2a06c759833b").unwrap(); let context = mock_context(cycles_limit, caller.clone()); let mut service = new_asset_service(); let supply = 1024 * 1024; let asse...
succeed_data; let to_address = Address::from_hex("0x666cdba6ae4f479f7164792b318b2a06c759833b").unwrap(); service.approve(context.clone(), ApprovePayload { asset_id: asset.id.clone(), to: to_address.clone(), value: 1024, }); let allowance_res = service .get_allo...
function_block-function_prefix_line
[ { "content": "fn mock_context(cycles_limit: u64, caller: Address) -> ServiceContext {\n\n let params = ServiceContextParams {\n\n tx_hash: None,\n\n nonce: None,\n\n cycles_limit,\n\n cycles_price: 1,\n\n cycles_used: Rc::new(RefCell::new(0)),\n\n caller,\n\n ...
Rust
src/types/fetch.rs
jonasc/rust-imap
6808dfef79e26945366794dc16e66cc0ad3d2a15
use super::{Flag, Seq, Uid}; use crate::error::Error; use crate::parse::{parse_many_into, MapOrNot}; use crate::types::UnsolicitedResponse; use chrono::{DateTime, FixedOffset}; use imap_proto::types::{ AttributeValue, BodyStructure, Envelope, MessageSection, Response, SectionPath, }; use ouroboros::self_referencing...
use super::{Flag, Seq, Uid}; use crate::error::Error; use crate::parse::{parse_many_into, MapOrNot}; use crate::types::UnsolicitedResponse; use chrono::{DateTime, FixedOffset}; use imap_proto::types::{ AttributeValue, BodyStructure, Envelope, MessageSection, Response, SectionPath, }; use ouroboros::self_referencing...
) } pub fn body(&self) -> Option<&[u8]> { self.fetch.iter().find_map(|av| match av { AttributeValue::BodySection { section: None, data: Some(body), .. } | AttributeValue::Rfc822(Some(body)) => Some(&**bod...
match av { AttributeValue::BodySection { section: Some(SectionPath::Full(MessageSection::Header)), data: Some(hdr), .. } | AttributeValue::Rfc822Header(Some(hdr)) => Some(&**hdr), _ => None, }
if_condition
[ { "content": "/// A convenience function to always cause the IDLE handler to exit on any change.\n\npub fn stop_on_any(_response: UnsolicitedResponse) -> bool {\n\n false\n\n}\n\n\n", "file_path": "src/extensions/idle.rs", "rank": 0, "score": 133904.42454166868 }, { "content": "pub fn par...
Rust
sdk/src/types.rs
CapCap/aptos-core
d1874e341927ed6ffefd1c8995b500fa762ccb4c
use crate::{ crypto::{ ed25519::{Ed25519PrivateKey, Ed25519PublicKey}, traits::Uniform, }, transaction_builder::TransactionBuilder, types::{ account_address::AccountAddress, transaction::{authenticator::AuthenticationKey, RawTransaction, SignedTransaction}, }, }; p...
use crate::{ crypto::{ ed25519::{Ed25519PrivateKey, Ed25519PublicKey}, traits::Uniform, }, transaction_builder::TransactionBuilder, types::{ account_address::AccountAddress, transaction::{authenticator::AuthenticationKey, RawTransaction, SignedTransaction}, }, }; p...
let raw_txn = builder .sender(self.address()) .sequence_number(self.sequence_number()) .build(); *self.sequence_number_mut() += 1; raw_txn .sign_multi_agent( self.private_key(), secondary_signer_addresses, ...
let secondary_signer_privkeys = secondary_signers .iter() .map(|signer| signer.private_key()) .collect();
assignment_statement
[ { "content": "pub fn from_public_key(public_key: &Ed25519PublicKey) -> AccountAddress {\n\n AuthenticationKey::ed25519(public_key).derived_address()\n\n}\n\n\n", "file_path": "types/src/account_address.rs", "rank": 0, "score": 424557.93516363215 }, { "content": "pub fn postorder_to_inorde...
Rust
testing/jormungandr-testing-utils/src/testing/node/grpc/server/data.rs
input-output-hk/jormungandr
0f9688aa652dcaab5ab84b7a135560adec65adba
use super::ProtocolVersion; use chain_core::{ mempack::{ReadBuf, ReadError, Readable}, property::Serialize, }; use chain_crypto::{Ed25519, KeyPair, PublicKey, Signature, Verification}; use chain_impl_mockchain::{ block::{self, Block, BlockDate, ContentsBuilder, Header}, header::BlockVersion, key::Ha...
use super::ProtocolVersion; use chain_core::{ mempack::{ReadBuf, ReadError, Readable}, property::Serialize, }; use chain_crypto::{Ed25519, KeyPair, PublicKey, Signature, Verification}; use chain_impl_mockchain::{ block::{self, Block, BlockDate, ContentsBuilder, Header}, header::BlockVersion, key::Ha...
keynesis::key::ed25519::SecretKey::new(&mut rand::thread_rng()); let profile = poldercast::Profile::new(addr, &topology_key); Self { genesis_hash, protocol, keypair, profile, auth_nonce: [0; AUTH_NONCE_LEN], storage, } }...
r, Debug)] pub enum Error { #[error(transparent)] Storage(#[from] chain_storage::Error), #[error(transparent)] Read(#[from] ReadError), #[error(transparent)] Io(#[from] std::io::Error), } impl MockServerData { const TIP_TAG: &'static str = "tip"; pub fn new( genesis_hash: Hash, ...
random
[ { "content": "fn get_block_from_storage(storage: &Storage, id: HeaderHash) -> Result<Block, Error> {\n\n match storage.get(id) {\n\n Ok(Some(block)) => Ok(block),\n\n Ok(None) => Err(Error::not_found(format!(\n\n \"block {} is not known to this node\",\n\n id\n\n ))...
Rust
edb/components/embedded_lmdb/src/write_batch.rs
whtcorpsinc/einsteindb-prod
3b1c63a421ff37f1ca6bef4d67ef7f4c4c78a6d7
use std::sync::Arc; use crate::edb::LmdbEngine; use crate::options::LmdbWriteOptions; use crate::util::get_causet_handle; use edb::{self, Error, MuBlock, Result, WriteBatchExt, WriteOptions}; use lmdb::{WriBlock, WriteBatch as RawWriteBatch, DB}; const WRITE_BATCH_MAX_BATCH: usize = 16; const WRITE_BATCH_LIMIT: usi...
use std::sync::Arc; use crate::edb::LmdbEngine; use crate::options::LmdbWriteOptions; use crate::util::get_causet_handle; use edb::{self, Error, MuBlock, Result, WriteBatchExt, WriteOptions}; use lmdb::{WriBlock, WriteBatch as RawWriteBatch, DB}; const WRITE_BATCH_MAX_BATCH: usize = 16; const WRITE_BATCH_LIMIT: usi...
.unwrap(); assert!(engine.support_write_batch_vec()); let mut wb = engine.write_batch(); for _i in 0..LmdbEngine::WRITE_BATCH_MAX_KEYS { wb.put(b"aaa", b"bbb").unwrap(); } assert!(!wb.should_write_to_engine()); wb.put(b"aaa", b"bbb").unwrap(); ...
new_engine_opt( path.path().join("db").to_str().unwrap(), LmdbDBOptions::from_raw(opt), vec![], )
call_expression
[ { "content": "pub fn must_get(engine: &Arc<DB>, causet: &str, key: &[u8], value: Option<&[u8]>) {\n\n for _ in 1..300 {\n\n let res = engine.c().get_value_causet(causet, &tuplespaceInstanton::data_key(key)).unwrap();\n\n if let (Some(value), Some(res)) = (value, res.as_ref()) {\n\n a...
Rust
lib/rc_models/src/candle.rs
mmihira/rocket_wasm
52555c9610a45f3ebd039906b93affc3e5eb1fb0
use timestamp::{TimeStamp}; use rc_schema::schema::candles; use rc_schema::schema::candles::dsl::candles as candles_dsl; use diesel::prelude::{PgConnection}; use diesel::{Identifiable, ExpressionMethods, QueryDsl, RunQueryDsl, BoolExpressionMethods}; use diesel::result::Error as DieselError; use analysis_range::{ Perio...
use timestamp::{TimeStamp}; use rc_schema::schema::candles; use rc_schema::schema::candles::dsl::candles as candles_dsl; use diesel::prelude::{PgConnection}; use diesel::{Identifiable, ExpressionMethods, QueryDsl, RunQueryDsl, BoolExpressionMethods}; use diesel::result::Error as DieselError; use analysis_range::{ Perio...
pub fn candle_for_range<T: TimePeriod>(conn: &PgConnection, range: &T) -> Result<Self, DieselError> { candles_dsl.filter( candles::start_time.eq(range.range_start()) .and(candles::end_time.eq(range.range_end())) .and(candles::period.eq(range.period() as i32))) ...
p) -> Result<Vec<Self>, DieselError> { candles_dsl.filter( candles::start_time.ge(start) .and(candles::end_time.le(end)) .and(candles::period.eq(period as i32)) ) .order_by(candles::start_time.asc()) .get_results::<Self>(conn) }
function_block-function_prefixed
[ { "content": "pub fn rsi_for_interval<T: TimePeriod>(conn: &PgConnection, range: &T) -> Result<RsiProperties, String> {\n\n candles_for_rsi_calc(conn, range)\n\n .map_err(|err: DieselError| {\n\n format!(\"{}\", err)\n\n })\n\n .and_then(|candles| {\n\n match candle...
Rust
src/api.rs
insipx/polkadot-rewards
36eb95023691fe7fd8bd9ed7b1599e027040fdca
use crate::{ cli::{App, Network}, primitives::{ApiResponse, List, Price, Reward, RewardEntry, SeparatedRewardEntry}, }; use anyhow::{anyhow, Context, Error}; use chrono::{naive::NaiveDateTime, NaiveDate}; use indicatif::ProgressBar; use std::{ collections::{BTreeMap, BTreeSet}, convert::TryInto, }; const POLKADO...
use crate::{ cli::{App, Network}, primitives::{ApiResponse, List, Price, Reward, RewardEntry, SeparatedRewardEntry}, }; use anyhow::{anyhow, Context, Error}; use chrono::{naive::NaiveDateTime, NaiveDate}; use indicatif::ProgressBar; use std::{ collections::{BTreeMap, BTreeSet}, convert::TryInto, }; const POLKADO...
fn fetch_rewards(&self) -> Result<Vec<Reward>, Error> { const PAGE_SIZE: usize = 100; self.progress.map(|r| r.reset()); self.progress.map(|p| p.set_message("Fetching Rewards")); self.progress.map(|r| r.tick()); let page_estimate = { let num_entries = self.rewards(0, 1).context("Failed to fetch initi...
ds(&self, page: usize, count: usize) -> Result<List<Reward>, Error> { let req = self.agent.post(&get_endpoint(&self.app.network, REWARD_SLASH)); let rewards = req .set("Content-Type", "application/json") .send_json(ureq::json!({ "address": self.app.address.as_str(), "page": page, "row": count ...
function_block-function_prefixed
[ { "content": "pub fn app() -> Result<(), Error> {\n\n\tlet mut app: App = argh::from_env();\n\n\tlet progress = if app.verbose {\n\n\t\tBuilder::from_env(Env::default().default_filter_or(\"info\")).init();\n\n\t\tNone\n\n\t} else {\n\n\t\tSome(construct_progress_bar())\n\n\t};\n\n\tlet api = Api::new(&app, prog...
Rust
src/maze/square_maze/mod.rs
Colocasian/maze-generator-two
007b8083dd4866389c455feca0a7bd06e83f2590
extern crate alloc; mod dfs; mod kruskal; pub mod renderer; mod wilson; use super::MazeAlgo; use crate::utils::set_panic_hook; use alloc::vec::Vec; use bit_vec::BitVec; use core::ops::Index; use wasm_bindgen::prelude::*; #[wasm_bindgen] #[derive(Debug, Clone)] pub struct SquareMaze { width: usize, height: us...
extern crate alloc; mod dfs; mod kruskal; pub mod renderer; mod wilson; use super::MazeAlgo; use crate::utils::set_panic_hook; use alloc::vec::Vec; use bit_vec::BitVec; use core::ops::Index; use wasm_bindgen::prelude::*; #[wasm_bindgen] #[derive(Debug, Clone)] pub struct SquareMaze { width: usize, height: us...
pub fn is_traversable_no_loops(&self) -> bool { let mut stk = Vec::new(); let mut visited = BitVec::from_elem(self.width * self.height, false); let init_pos = 0; let mut dir_buf = Vec::with_capacity(4); stk.push((init_pos, usize::MAX)); while !stk.is_empty() { ...
fn get_wall(&self, cell: usize, w_dir: SqDir) -> Option<usize> { let y = cell / self.width; let x = cell % self.width; match w_dir { SqDir::Up => { if y == 0 { None } else { Some(x + (y - 1) * ((self.width << 1) ...
function_block-full_function
[ { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details se...
Rust
frontend/src/init.rs
kkourt/diloti.online
df275491df7493aaf3f73b700f3c5b5a6e2c324a
use std::convert::TryFrom; use seed::{*, prelude::*}; use core::srvcli::{CreateRep, CreateReq, CreateReqDebug}; use crate::{ DEFAULT_NR_PLAYERS, Model, Msg, lobby::{LobbySt}, to_elem::{ToElem}, }; fn get_create_game_req_url() -> impl Into<std::borrow::Cow<'static, str>> { "/creategame" } #[derive(C...
use std::convert::TryFrom; use seed::{*, prelude::*}; use core::srvcli::{CreateRep, CreateReq, CreateReqDebug}; use crate::{ DEFAULT_NR_PLAYERS, Model, Msg, lobby::{LobbySt}, to_elem::{ToElem}, }; fn get_create_game_req_url() -> impl Into<std::borrow::Cow<'static, str>> { "/creategame" } #[derive(C...
fn debug_options(&self) -> Node<Msg> { let no_debug = self.debug_hand.len() == 0 && self.debug_table.len() == 0; let debug_hand = core::Deck::try_from(self.debug_hand.as_str()).map_or(span![], |x| x.to_elem()); let debug_table = core::Deck::try_from(self.debug_table.as_str()).map_or(span!...
fn select_nplayers(&self) -> Node<Msg> { let get_option = |txt: &str, val: &str, selected| { if selected { option![txt, attrs!{At::Value => val, At::Selected => "true"} ] } else { option![txt, attrs!{At::Value => val,} ] } }; l...
function_block-full_function
[ { "content": "fn update(msg: Msg, mut model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n\n\n //log(format!(\"update => {:?}\", msg));\n\n let upd_ret = match (&mut model, msg) {\n\n (_, Msg::Error(x)) => Some(Model::Error(x)),\n\n (&mut Model::Init(st), Msg::Init(ref msg)) => st.upd...
Rust
handel/src/multisig.rs
Smittyvb/core-rs-albatross
1e1ad5269bd64d9f6de8d7094359c5ddd2927416
use failure::Fail; use beserial::{Serialize, Deserialize, WriteBytesExt, ReadBytesExt, SerializingError, BigEndian}; use bls::bls12_381; use collections::bitset::BitSet; #[derive(Clone, Debug, Fail)] pub enum SignatureError { #[fail(display = "Signatures are overlapping: {:?}", _0)] Overlapping(BitSet), #...
use failure::Fail; use beserial::{Serialize, Deserialize, WriteBytesExt, ReadBytesExt, SerializingError, BigEndian}; use bls::bls12_381; use collections::bitset::BitSet; #[derive(Clone, Debug, Fail)] pub enum SignatureError { #[fail(display = "Signatures are overlapping: {:?}", _0)] Overlapping(BitSet), #...
} } impl IndividualSignature { pub fn new(signature: bls12_381::Signature, signer: usize) -> Self { Self { signature, signer } } pub fn as_multisig(&self) -> MultiSignature { let mut aggregate = bls12_381::AggregateSignature::new(); let mut sign...
Ok(Self { signature: Deserialize::deserialize(reader)?, signer: reader.read_u16::<BigEndian>()? as usize })
call_expression
[ { "content": "pub fn log_error_cause_chain(mut fail: &dyn Fail) {\n\n let level = Level::Error;\n\n force_log!(level, \"{}\", fail);\n\n if fail.cause().is_some() {\n\n force_log!(level, \" caused by\");\n\n while let Some(cause) = fail.cause() {\n\n force_log!(level, \" {}...
Rust
src/doubly_linked_list.rs
Raigiku/multiple_ownership
5aa4cd8ef77761cfc42c7e1c22a89a06027439d9
use std::cell::{Ref, RefCell, RefMut}; use std::rc::Rc; type Link<T> = Option<Rc<RefCell<Node<T>>>>; #[derive(Debug)] struct Node<T> { value: T, next: Link<T>, prev: Link<T>, } impl<T> Node<T> { fn new(value: T, next: Link<T>, prev: Link<T>) -> Self { Self { value, next, prev } } } #[der...
use std::cell::{Ref, RefCell, RefMut}; use std::rc::Rc; type Link<T> = Option<Rc<RefCell<Node<T>>>>; #[derive(Debug)] struct Node<T> { value: T, next: Link<T>, prev: Link<T>, } impl<T> Node<T> { fn new(value: T, next: Link<T>, prev: Link<T>) -> Self { Self { value, next, prev } } } #[der...
pub fn pop_front(&mut self) -> Option<Result<T, &str>> { self.head.take().map(|old_head| { self.size -= 1; match old_head.borrow_mut().next.take() { Some(new_head) => { new_head.borrow_mut().prev.take(); self.head = Some(new_h...
pub fn push_back(&mut self, value: T) { self.size += 1; let new_tail = Rc::new(RefCell::new(Node::new(value, None, None))); match self.tail.take() { Some(old_tail) => { old_tail.borrow_mut().next = Some(Rc::clone(&new_tail)); new_tail.borrow_mut().prev...
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nstruct Node<T> {\n\n value: T,\n\n next: Link<T>,\n\n}\n\n\n\nimpl<T> Node<T> {\n\n fn new(value: T, next: Link<T>) -> Self {\n\n Self { value, next }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Queue<T> {\n\n head: Link<T>,\n\n tail: Link<T>,\n\n ...
Rust
engine/src/datastr/rank_select_map.rs
pka/rust_road_router
2bef5b54ca2c85e82bceee852b13aa7ad28c6945
use std::cmp::min; use std::mem::size_of; use std::ops::Deref; use std::alloc::{alloc_zeroed, Layout}; use crate::io::*; const CACHE_LINE_WIDTH: usize = 64; const STORAGE_BITS: usize = size_of::<u64>() * 8; #[derive(Debug)] pub struct BitVec { data: Vec<u64>, size: usize, } impl BitVec { pub f...
use std::cmp::min; use std::mem::size_of; use std::ops::Deref; use std::alloc::{alloc_zeroed, Layout}; use crate::io::*; const CACHE_LINE_WIDTH: usize = 64; const STORAGE_BITS: usize = size_of::<u64>() * 8; #[derive(Debug)] pub struct BitVec { data: Vec<u64>, size: usize, } impl BitVec { pub f...
size; if lower_ones <= adjusted_rank { word >>= 32; adjusted_rank -= lower_ones; shifted += 32; } debug_assert!(adjusted_rank < 32); let lower_ones = (word as u16).count_ones() as usize; if lower_ones <= adjusted_rank { word >>= 16...
: usize) { assert!(index < self.size, "index: {} size: {}", index, self.size); self.data[index / STORAGE_BITS] |= 1 << (index % STORAGE_BITS); } pub fn unset(&mut self, index: usize) { assert!(index < self.size, "index: {} size: {}", index, self.size); sel...
random
[ { "content": "// Encapsulates the creation of the CATCHUp main customization lambdas\n\n// The function signature gives us some additional control of lifetimes and stuff\n\nfn create_customization_fn<'s, F: 's>(cch: &'s CCH, metric: &'s TDGraph, merge_iter: F) -> impl Fn(Range<usize>, usize, &mut [Shortcut], &m...
Rust
sources/api/early-boot-config/src/main.rs
rckasa/bottlerocket
24ed37cbab295d9f036ffc5afc326b03048768e7
/*! # Introduction early-boot-config sends provider-specific platform data to the Bottlerocket API. For most providers this means configuration from user data and platform metadata, taken from something like an instance metadata service. Currently, Amazon EC2 is supported through the IMDSv1 HTTP API. Data will be t...
/*! # Introduction early-boot-config sends provider-specific platform data to the Bottlerocket API. For most providers this means configuration from user data and platform metadata, taken from something like an instance metadata service. Currently, Amazon EC2 is supported through the IMDSv1 HTTP API. Data will be t...
st USER_DATA_ENDPOINT: &'static str = "http://169.254.169.254/2018-09-24/user-data"; const IDENTITY_DOCUMENT_FILE: &'static str = "/etc/early-boot-config/identity-document"; const IDENTITY_DOCUMENT_ENDPOINT: &'static str = "http://169.254.169.254/2018-09-24/dynamic/instance-identity/document"; ...
: String, source: reqwest::Error, }, #[snafu(display("Response '{}' from '{}': {}", get_bad_status_code(&source), uri, source))] BadResponse { uri: String, source: reqwest::Error }, #[snafu(display("Error {}ing '{}': {}", method, uri, source))] APIRequest { ...
random
[ { "content": "fn transaction_name(query: &web::Query<HashMap<String, String>>) -> &str {\n\n if let Some(name_str) = query.get(\"tx\") {\n\n name_str\n\n } else {\n\n \"default\"\n\n }\n\n}\n\n\n\n// Can also override `render_response` if we want to change headers, content type, etc.\n\ni...
Rust
src/core/search/collector/timeout.rs
unix1986/rucene
bf4de84dafb58eeedfc2b975556890ed3e5dc1f6
use core::codec::Codec; use core::index::reader::LeafReaderContext; use core::search::collector; use core::search::collector::{Collector, ParallelLeafCollector, SearchCollector}; use core::search::scorer::Scorer; use core::util::external::Volatile; use core::util::DocId; use error::{ErrorKind, Result}; use std::sync:...
use core::codec::Codec; use core::index::reader::LeafReaderContext; use core::search::collector; use core::search::collector::{Collector, ParallelLeafCollector, S
, )) } Ok(()) } } impl ParallelLeafCollector for TimeoutLeafCollector { fn finish_leaf(&mut self) -> Result<()> { Ok(()) } }
earchCollector}; use core::search::scorer::Scorer; use core::util::external::Volatile; use core::util::DocId; use error::{ErrorKind, Result}; use std::sync::Arc; use std::time::{Duration, SystemTime}; pub struct TimeoutCollector { timeout_duration: Duration, start_time: SystemTime, timeout: Arc<Volatile<bo...
random
[ { "content": "/// `Collector` that collect parallel for a single segment.\n\n///\n\n/// once finished, the `finish_leaf` method must be\n\n/// called to notify to main thread.\n\npub trait ParallelLeafCollector: Collector + Send + 'static {\n\n fn finish_leaf(&mut self) -> Result<()>;\n\n}\n", "file_path...
Rust
src/rust/protocol/src/memcache/wire/mod.rs
huayl/pelikan
6a9579493a54547f1a6318ed13d7534ba32c94ff
mod request; mod response; pub use request::*; pub use response::*; use super::*; use crate::*; use metrics::Stat; impl<'a, T> Execute<MemcacheRequest, MemcacheResponse> for T where T: MemcacheStorage, { fn execute(&mut self, request: MemcacheRequest) -> Option<MemcacheResponse> { let response = m...
mod request; mod response; pub use request::*; pub use response::*; use super::*; use crate::*; use metrics::Stat; impl<'a, T> Execute<MemcacheRequest, MemcacheResponse> for T where T: MemcacheStorage, {
}
fn execute(&mut self, request: MemcacheRequest) -> Option<MemcacheResponse> { let response = match request { MemcacheRequest::Get { keys } => { increment_counter!(&Stat::Get); let entries = self.get(&keys); increment_counter_by!(&Stat::GetKey, keys.l...
function_block-full_function
[ { "content": "pub trait Execute<Request, Response> {\n\n fn execute(&mut self, request: Request) -> Option<Response>;\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub enum ParseError {\n\n Invalid,\n\n Incomplete,\n\n UnknownCommand,\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub struct ParseOk<T> {\n...
Rust
weaver/src/storage/index.rs
divinerapier/weaver
6473d67a41ad256f54d7333c28e2cc1390cf3484
use std::collections::HashMap; use std::io::Write; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use byteorder::ByteOrder; #[allow(dead_code)] use crate::error::Result; pub trait Codec: Clone + Send + Sync { fn encode(&self, entry: &Entry) -> Result<Vec<u8>>; fn decode(&s...
use std::collections::HashMap; use std::io::Write; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, RwLock}; use byteorder::ByteOrder; #[allow(dead_code)] use crate::error::Result; pub trait Codec: Clone + Send + Sync { fn encode(&self, entry: &Entry) -> Result<Vec<u8>>; fn decode(&s...
_id, offset, length, } } } impl Default for Entry { fn default() -> Entry { Entry { needle_id: 0, offset: 0, length: 0, } } }
), 24); Ok(Entry { needle_id: bytes::BigEndian::read_u64(&data[0..8]), offset: bytes::BigEndian::read_u64(&data[8..16]) as usize, length: bytes::BigEndian::read_u64(&data[16..24]) as usize, }) } } pub struct Index<C: Codec> { writer: Arc<Mutex<std::fs::File>>...
random
[ { "content": "#[tonic::async_trait]\n\npub trait DirectoryStorage: Send + Sync {\n\n async fn create(&mut self, key: &str, chunks: Vec<Chunk>) -> Result<()>;\n\n async fn update(&mut self, key: &str, chunks: Vec<Chunk>) -> Result<()>;\n\n\n\n /// Retrieve chunks of the target key.\n\n ///\n\n ///...
Rust
experiments/src/model.rs
meowjesty/hello-actix
0c5809d46c7de83a887ec5da1d7b64a8398d0d95
use actix_web::{body::BoxBody, HttpRequest, HttpResponse, Responder}; use serde::{Deserialize, Serialize}; use sqlx::{FromRow, SqlitePool}; use crate::errors::TodoError; #[derive(Clone, Debug, Serialize, Deserialize, FromRow)] pub(crate) struct Todo { id: i64, task: String, details: String, } #[derive(De...
use actix_web::{body::BoxBody, HttpRequest, HttpResponse, Responder}; use serde::{Deserialize, Serialize}; use sqlx::{FromRow, SqlitePool}; use crate::errors::TodoError; #[derive(Clone, Debug, Serialize, Deserialize, FromRow)] pub(crate) struct Todo { id: i64, task: String, details: String, } #[derive(De...
.bind(id) .fetch_optional(pool) .await?; Ok(result) } pub(crate) async fn create(pool: &SqlitePool, input: &InputTodo) -> Result<i64, TodoError> { let mut connection = pool.acquire().await?; let result = sqlx::query(Self::INSERT) .bind(&input...
(pool: &SqlitePool, id: i64) -> Result<Option<Todo>, TodoError> { let result = sqlx::query_as(Self::FIND_BY_ID)
function_block-random_span
[ { "content": "delete from Done\n\nwhere task_id = $1", "file_path": "login/src/tasks/queries/undo.sql", "rank": 0, "score": 182816.1273103836 }, { "content": "delete from Done\n\nwhere task_id = $1", "file_path": "authorization/src/tasks/queries/undo.sql", "rank": 1, "score": 182...
Rust
kernel-ewasm/cap9-std/src/data/vec.rs
sambacha/cap9
05fe5451468679efa89e93e19614bedd7b4ca349
extern crate pwasm_abi; use pwasm_abi::types::*; use cap9_core::Serialize; use cap9_core::StorageValue; #[derive(Debug)] pub struct Error; use crate::proc_table; use crate::syscalls::*; use crate::*; use crate::data::*; use core::marker::PhantomData; pub struct StorageVec<V> { cap_index: u8, location:...
extern crate pwasm_abi; use pwasm_abi::types::*; use cap9_core::Serialize; use cap9_core::StorageValue; #[derive(Debug)] pub struct Error; use crate::proc_table; use crate::syscalls::*; use crate::*; use crate::data::*; use core::marker::PhantomData; pub struct StorageVec<V> { cap_index: u8, location:...
f.length.into()).unwrap(); value } pub fn iter(&self) -> StorageVecIter<V> { StorageVecIter::new(self) } } pub struct StorageVecIter<'a, V> { storage_vec: &'a StorageVec<V>, offset: U256, } impl<'a, V: Storable> StorageVecIter<'a, V> { fn new(storage_vec: &'a S...
{ return None; } let base_key: U256 = U256::from(self.location); let offset: U256 = self.length.checked_mul(V::n_keys()).unwrap(); let val_location: U256 = base_key.checked_add(offset).unwrap(); let value = V::read(val_location); ...
random
[ { "content": "/// Perform a log system call.\n\npub fn log(cap_index: u8, topics: Vec<H256>, value: Vec<u8>) -> Result<(), Error> {\n\n let mut input: Vec<u8> = Vec::new();\n\n let syscall = SysCall {\n\n cap_index,\n\n action: SysCallAction::Log(LogCall{topics,value: Payload(value)}),\n\n ...
Rust
envoy-sdk/src/extension/module/config.rs
tetratelabs/envoy-wasm-rust-sdk
c4bca64ed17ccc5b1f131921cb555aa0e9333b91
use super::{ContextFactory, ContextFactoryHashMap}; use crate::abi::proxy_wasm::traits::{HttpContext, RootContext, StreamContext}; use crate::extension::access_logger::{AccessLogger, AccessLoggerContext}; use crate::extension::error::ModuleError; use crate::extension::factory::{ChildContextFactory, ExtensionFactory,...
use super::{ContextFactory, ContextFactoryHashMap}; use crate::abi::proxy_wasm::traits::{HttpContext, RootContext, StreamContext}; use crate::extension::access_logger::{AccessLogger, AccessLoggerContext}; use crate::extension::error::ModuleError; use crate::extension::factory::{ChildContextFactory, ExtensionFactory,...
Box::new(NetworkFilterContext::with_default_ops(network_filter)) } Err(err) => { Box::new(VoidNetworkFilterContext::with_default_ops(err)) } }...
+ 'static, { let factory = Box::new(move |context_id| -> Result<Box<dyn RootContext>> { let logger = new(InstanceId::from(context_id))?; Ok(Box::new(AccessLoggerContext::with_default_ops(logger))) }); self.add_extension(T::name(), factory) } pu...
random
[ { "content": "pub fn register_shared_queue(name: &str) -> host::Result<SharedQueueHandle> {\n\n hostcalls::register_shared_queue(name)\n\n .map(SharedQueueHandle::from)\n\n .map_err(|err| format_err!(err))\n\n}\n\n\n", "file_path": "envoy-sdk/src/abi/proxy_wasm/hostcalls.rs", "rank": 0,...
Rust
native-windows-gui/src/errors.rs
cg31/native-windows-gui
19fe8f6fadc3c5cd9365106e78d87e46d9c813dd
use std::fmt; use std::error::Error; /** Error enums used in the native window gui crate */ #[derive(Debug, Clone)] pub enum NwgError { Unknown, InitializationError(String), ControlCreationError(String), MenuCreationError(String), ResourceCreationError(String), ...
use std::fmt; use std::error::Error; /** Error enums used in the native window gui crate */ #[derive(Debug, Clone)] pub enum NwgError { Unknown, InitializationError(String), ControlCreationError(String), MenuCreationError(String), ResourceCreationError(String), ...
> write!(f, "Image decoder failed: {:?}", reason), #[cfg(feature = "winnls")] BadLocale(reason) => write!(f, "Windows locale functions failed: {:?}", reason), } } } impl Error for NwgError {}
#[cfg(feature = "file-dialog")] FileDialogError(String), #[cfg(feature = "image-decoder")] ImageDecoderError(i32, String), #[cfg(feature = "winnls")] BadLocale(String), } impl NwgError { pub fn initialization<S: Into<String>>(e: S) -> NwgError { NwgError::InitializationErr...
random
[ { "content": "/// Initializes some application wide GUI settings.\n\n/// This includes default styling and common controls resources.\n\npub fn init() -> std::result::Result<(), errors::NwgError> {\n\n if cfg!(not(feature=\"no-styling\")) {\n\n enable_visual_styles();\n\n }\n\n \n\n init_comm...
Rust
libchisel/src/checkfloat.rs
g-r-a-n-t/wasm-chisel
31e4575cdb00950a633c9d15f1b2798fb2c9c015
use std::collections::HashMap; use parity_wasm::elements::{Instruction, Module}; use super::{ChiselModule, ModuleError, ModuleKind, ModuleValidator}; pub struct CheckFloat {} impl<'a> ChiselModule<'a> for CheckFloat { type ObjectReference = &'a dyn ModuleValidator; fn id(&'a self) -> String { "chec...
use std::collections::HashMap; use parity_wasm::elements::{Instruction, Module}; use super::{ChiselModule, ModuleError, ModuleKind, ModuleValidator}; pub struct CheckFloat {} impl<'a> ChiselModule<'a> for CheckFloat { type ObjectReference = &'a dyn ModuleValidator; fn id(&'a self) -> String { "chec...
0x6a, 0x0b, ]; let module = Module::from_bytes(&wasm).unwrap(); let checker = CheckFloat::with_defaults().unwrap(); let result = checker.validate(&module).unwrap(); assert_eq!(true, result); } #[test] fn add_f32_fp() { ...
| Instruction::F32Gt | Instruction::F32Le | Instruction::F32Ge | Instruction::F32Abs | Instruction::F32Neg | Instruction::F32Ceil | Instruction::F32Floor | Instruction::F32Trun...
random
[ { "content": "/// Resolves an imported function's signature from its callable index.\n\npub fn imported_func_sig_by_index(module: &Module, index: usize) -> FunctionType {\n\n module.import_section().expect(\"No function section found\");\n\n let type_section = module.type_section().expect(\"No type sectio...
Rust
ethereum-types/src/uint.rs
chainx-org/primitives
9476bd1a61d4269d8e08a39a7839e918a6857c88
#[cfg(feature="serialize")] use serde::{Serialize, Serializer, Deserialize, Deserializer}; #[cfg(feature="serialize")] use ethereum_types_serialize; macro_rules! impl_serde { ($name: ident, $len: expr) => { #[cfg(feature="serialize")] impl Serialize for $name { fn serialize<S>(&self, serializer: S) -> Result<...
#[cfg(feature="serialize")] use serde::{Serialize, Serializer, Deserialize, Deserializer}; #[cfg(feature="serialize")] use ethereum_types_serialize; macro_rules! impl_serde { ($name: ident, $len: expr) => { #[cfg(feature="serialize")] impl Serialize for $name { fn serialize<S>(&self, serializer: S) -> Result<...
} impl From<U128> for U512 { fn from(value: U128) -> U512 { let U128(ref arr) = value; let mut ret = [0; 8]; ret[0] = arr[0]; ret[1] = arr[1]; U512(ret) } } impl From<U128> for U256 { fn from(value: U128) -> U256 { let U128(ref arr) = value; let mut ret = [0; 4]; ret[0] = arr[0]; ret[1] = arr[1]...
fn from(value: U512) -> U128 { let U512(ref arr) = value; if arr[2] | arr[3] | arr[4] | arr[5] | arr[6] | arr[7] != 0 { panic!("Overflow"); } let mut ret = [0; 2]; ret[0] = arr[0]; ret[1] = arr[1]; U128(ret) }
function_block-full_function
[ { "content": "/// Deserialize into vector of bytes with additional size check.\n\n/// Returns number of bytes written.\n\npub fn deserialize_check_len<'a, 'de, D>(deserializer: D, len: ExpectedLen<'a>) -> Result<usize, D::Error> where\n\n\tD: Deserializer<'de>,\n\n{\n\n\tstruct Visitor<'a> {\n\n\t\tlen: Expecte...
Rust
src/ctor.rs
Nugine/moveit
18404f9d0d66c0b60d8471d5f93e66447d9826b8
use core::convert::Infallible; use core::convert::TryFrom; use core::convert::TryInto; use core::marker::PhantomData; use core::mem; use core::mem::MaybeUninit; use core::ops::Deref; use core::pin::Pin; use crate::unique::DerefMove; #[cfg(doc)] use alloc::{boxed::Box, rc::Rc, sync::Arc}; #[must_use = "`Ctor`s do n...
use core::convert::Infallible; use core::convert::TryFrom; use core::convert::TryInto; use core::marker::PhantomData; use core::mem; use core::mem::MaybeUninit; use core::ops::Deref; use core::pin::Pin; use crate::unique::DerefMove; #[cfg(doc)] use alloc::{boxed::Box, rc::Rc, sync::Arc}; #[must_use = "`Ctor`s do n...
pub fn copy<P>(ptr: P) -> impl Ctor<Output = P::Target> where P: Deref, P::Target: CopyCtor, { unsafe { from_placement_fn(move |dest| { CopyCtor::copy_ctor(&*ptr, dest); mem::drop(ptr) }) } }
function_block-full_function
[ { "content": "## Constructors\n\n\n\nA constructor is any type that implements `Ctor`. Constructors are like\n\nclosures that have guaranteed RVO, which can be used to construct a\n\nself-referential type in-place. To use the example from the `Pin<T>` docs:\n\n```rust\n\nuse std::marker::PhantomPinned;\n\nuse s...
Rust
crates/interledger-btp/src/oer.rs
niklaslong/interledger-rs
cc7ca07bf53f692a1cfe5997a8301009790a13e5
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use bytes::{Buf, BufMut, Bytes, IntoBuf}; use num_bigint::BigUint; use std::fmt::Debug; use std::io::{self, Read, Result, Write}; const HIGH_BIT: u8 = 0x80; const LOWER_SEVEN_BITS: u8 = 0x7f; pub trait ReadOerExt: Read + ReadBytesExt + Debug { #[inline] ...
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use bytes::{Buf, BufMut, Bytes, IntoBuf}; use num_bigint::BigUint; use std::fmt::Debug; use std::io::{self, Read, Result, Write}; const HIGH_BIT: u8 = 0x80; const LOWER_SEVEN_BITS: u8 = 0x7f; pub trait ReadOerExt: Read + ReadBytesExt + Debug { #[inline] ...
} #[cfg(test)] mod reader_ext { use super::*; use std::io::Cursor; #[test] fn it_reads_var_octet_strings() { let nothing = vec![0]; assert_eq!( Cursor::new(nothing).read_var_octet_string().unwrap().len(), 0 ); let two_bytes = vec![0x01, 0xb0]; ...
let mut one = vec![]; one.write_var_octet_string(&[0xb0]).unwrap(); assert_eq!(one, vec![0x01, 0xb0]); let mut larger = vec![]; let larger_string: Vec<u8> = vec![0xb0; 256]; larger.write_var_octet_string(&larger_string).unwrap(); let mut expected = vec![0x82, 0x01, 0x00]...
function_block-function_prefix_line
[ { "content": "/// Decrypts a AES256-GCM encrypted ciphertext.\n\n///\n\n/// The secret key is generated deterministically by HMAC-256'ing the `shared_secret`\n\n/// and the hardcoded string \"ilp_stream_encryption\"\n\n///\n\n/// The `additional_data` field is left empty.\n\n///\n\n/// The nonce and auth tag ar...
Rust
secio/src/crypto/ring_impl.rs
chanhsu001/tentacle
9308fd5ae502ef0fd5bf803b6f99a3db4a16731e
use bytes::BytesMut; use ring::{ aead::{ Aad, BoundKey, Nonce, NonceSequence, OpeningKey, SealingKey, UnboundKey, AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305, }, error::Unspecified, }; use std::ptr; use crate::{ crypto::{cipher::CipherType, nonce_advance, CryptoMode, StreamCipher}, ...
use bytes::BytesMut; use ring::{ aead::{ Aad, BoundKey, Nonce, NonceSequence, OpeningKey, SealingKey, UnboundKey, AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305, }, error::Unspecified, }; use std::ptr; use crate::{ crypto::{cipher::CipherType, nonce_advance, CryptoMode, StreamCipher}, ...
pub fn decrypt_in_place(&mut self, input: &mut BytesMut) -> Result<(), SecioError> { let output_len = input .len() .checked_sub(self.cipher_type.tag_size()) .ok_or(SecioError::FrameTooShort)?; if let RingAeadCryptoVariant::Open(ref mut key) = self.cipher { ...
pub fn decrypt(&mut self, input: &[u8]) -> Result<Vec<u8>, SecioError> { let output_len = input .len() .checked_sub(self.cipher_type.tag_size()) .ok_or(SecioError::FrameTooShort)?; let mut buf = Vec::with_capacity(input.len()); unsafe { buf.set_le...
function_block-full_function
[ { "content": "#[doc(hidden)]\n\n#[cfg(not(target_arch = \"wasm32\"))]\n\n#[cfg(not(unix))]\n\npub fn new_stream(t: cipher::CipherType, key: &[u8], mode: CryptoMode) -> BoxStreamCipher {\n\n Box::new(ring_impl::RingAeadCipher::new(t, key, mode))\n\n}\n\n\n\n/// Generate a specific Cipher with key and initiali...
Rust
slimchain-network/src/p2p/config.rs
hkbudb/slimchain
acd527b1cc00d5b87170de5cecfcbf6db0dfa12f
use libp2p::{multiaddr::Multiaddr, PeerId}; use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer}; use slimchain_common::error::{Error, Result}; use std::fmt; #[derive(Debug, Clone, Deserialize)] pub struct NetworkConfig { #[serde(default = "default_listen")] pub listen: Stri...
use libp2p::{multiaddr::Multiaddr, PeerId}; use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize, Serializer}; use slimchain_common::error::{Error, Result}; use std::fmt; #[derive(Debug, Clone, Deserialize)] pub struct NetworkConfig { #[serde(default = "default_listen")] pub listen: Stri...
} mod peer_id_serde_impl { use super::*; pub fn serialize<S>(value: &PeerId, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { value.to_base58().serialize(serializer) } pub fn deserialize<'de, D>(deserializer: D) -> Result<PeerId, D::Error> where D:...
he followings to the config file." ); println!(); println!(" [[network.peers]]"); println!(" peer_id = \"{}\"", self.peer_id.to_base58()); println!(" address = \"{}\"", self.address.to_string()); println!(); }
function_block-function_prefixed
[ { "content": "#[inline]\n\nfn get_value(id: TxTaskId, acc_address: Address, key: StateKey) -> Result<StateValue> {\n\n let mut task_state = crate::engine::TaskState::get_task_state(id)?;\n\n task_state.get_read_ctx_mut().get_value(acc_address, key)\n\n}\n\n\n\n#[no_mangle]\n\npub unsafe extern \"C\" fn oc...
Rust
cranelift/isle/veri/veri_engine/src/interp.rs
avanhatt/wasmtime
1299fcbb6c30cd0cba742202fa6ba406c1f080ad
use crate::renaming::rename_annotation_vars; use crate::type_check::TypeContext; use veri_annotation::parser_wrapper::AnnotationEnv; use veri_ir::{BoundVar, RuleSemantics, UndefinedTerm, VIRExpr, VIRTermAnnotation, VIRType}; use std::collections::HashMap; use std::fmt::Debug; use cranelift_isle as isle; use isle::se...
use crate::renaming::rename_annotation_vars; use crate::type_check::TypeContext; use veri_annotation::parser_wrapper::AnnotationEnv; use veri_ir::{BoundVar, RuleSemantics, UndefinedTerm, VIRExpr, VIRTermAnnotation, VIRType}; use std::collections::HashMap; use std::fmt::Debug; use cranelift_isle as isle; use isle::se...
} #[derive(Clone, Debug)] pub struct Assumption { assume: VIRExpr, } impl Assumption { pub fn new(assume: VIRExpr) -> Self { assert!(assume.ty().is_bool()); Self { assume } } pub fn assume(&self) -> &VIRExpr { &self.assume } } pub struct AssumptionContext<'ctx> ...
t!( !ctx.rhs_undefined_terms.contains_key(&term.name), "Duplicate undefined terms on RHS currently unsupported: {}", term.name ); ctx.rhs_undefined_terms.insert(term.name.clone(), term); }
function_block-function_prefixed
[ { "content": "fn pattern_term_name(pattern: Pattern, termenv: &TermEnv, typeenv: &TypeEnv) -> String {\n\n match pattern {\n\n Pattern::Term(_, termid, _) => {\n\n let term = &termenv.terms[termid.index()];\n\n typeenv.syms[term.name.index()].clone()\n\n }\n\n _ => ...
Rust
examples/random_dungeon.rs
blamelessgames/bevy_tilemap
d46618fc1462fb17e3842cb0fe6a4299f403cd71
use bevy::{asset::LoadState, prelude::*, sprite::TextureAtlasBuilder, window::WindowMode}; use bevy_tilemap::{ dimensions::{Dimensions2, Dimensions3}, map::{TileMap, TileMapComponents}, tile::{Tile, TileSetter}, ChunkTilesPlugin, }; use rand::Rng; #[derive(Default, Clone)] pub struct TileSpriteHandles ...
use bevy::{asset::LoadState, prelude::*, sprite::TextureAtlasBuilder, window::WindowMode}; use bevy_tilemap::{ dimensions::{Dimensions2, Dimensions3}, map::{TileMap, TileMapComponents}, tile::{Tile, TileSetter}, ChunkTilesPlugin, }; use rand::Rng; #[derive(Default, Clone)] pub struct TileSpriteHandles ...
fn main() { App::build() .add_resource(WindowDescriptor { title: "Random Tile Dungeon".to_string(), width: 1024, height: 1024, vsync: false, resizable: false, mode: WindowMode::Windowed, ..Default::default() }) ...
fn build_random_dungeon( mut map_state: ResMut<MapState>, mut textures: ResMut<Assets<Texture>>, texture_atlases: Res<Assets<TextureAtlas>>, asset_server: Res<AssetServer>, mut query: Query<&mut TileMap>, ) { if map_state.map_loaded { return; } for mut map in query.iter_mut() { ...
function_block-full_function
[ { "content": "/// Trait methods that have to do with the 3rd dimension.\n\npub trait Dimensions3 {\n\n /// A `Vec3` containing the dimensions.\n\n fn dimensions(&self) -> Vec3;\n\n\n\n /// The width of this dimension.\n\n fn width(&self) -> f32 {\n\n self.dimensions().x()\n\n }\n\n\n\n ...
Rust
bin_codec/src/utils.rs
ywzjackal/bin_codec.rs
07e6037eeec1765261433d9a2930d9e6bba5bbb4
pub const MASK_U8_REV: [u8; 9] = [ 0b1111_1111, 0b111_1111, 0b11_1111, 0b1_1111, 0b1111, 0b111, 0b11, 0b1, 0, ]; pub const MASK_U8_REV_BIT: [u8; 9] = [ 0, 0b10000000, 0b11000000, 0b11100000, 0b11110000, 0b11111000, 0b11111100, 0b11111110, 0b11111111, ]; pub const CLEAR_U8: [...
pub const MASK_U8_REV: [u8; 9] = [ 0b1111_1111, 0b111_1111, 0b11_1111, 0b1_1111, 0b1111, 0b111, 0b11, 0b1, 0, ]; pub const MASK_U8_REV_BIT: [u8; 9] = [ 0, 0b10000000, 0b11000000, 0b11100000, 0b11110000, 0b11111000, 0b11111100, 0b11111110, 0b11111111, ]; pub const CLEAR_U8: [...
(), 0, 15 * 8); } assert_eq!(target[0], 0b11111010); assert_eq!(target[1], 0b10101111); assert_eq!(target[14], 0b11000011); assert_eq!(target[15], 0b00110000); let mut target = [0xfc; 20]; let src = [ 0xff, 0x01, 0xff, 0x02, 0xff, 0x03, 0xff, 0x04, 0xff, 0x05, 0xff, 0x06, 0xff, ...
*($target.offset(target_byte) as *mut $ty) = number.to_be(); let bits_copied = std::mem::size_of::<$ty>() * 8 - lsh - target_start_remainder; *$target_start += bits_copied; $src_start += bits_copied; continue; ...
random
[ { "content": "pub trait EncodeBe {\n\n fn encode<T>(&self, target: &mut [u8], ctx: &mut T) {\n\n assert!(target.len() >= (self.bits() + 7) / 8);\n\n Self::encode_offset(self, target, ctx, &mut 0, self.bits());\n\n }\n\n fn encode_offset<T>(&self, target: &mut [u8], ctx: &mut T, offset: &m...
Rust
src/main.rs
sebastian-xyz/yablo
35964a0cd5b6b02fd5291875cc8d344833e7bdb9
extern crate battery; extern crate clap; extern crate num_cpus; extern crate rev_lines; extern crate systemstat; extern crate toml; use crossterm::style::Stylize; use crossterm::ExecutableCommand; use systemstat::{Platform, System}; mod cli; mod lib; fn main() { let matches = cli::build_cli().get_matches(); ...
extern crate battery; extern crate clap; extern crate num_cpus; extern crate rev_lines; extern crate systemstat; extern crate toml; use crossterm::style::Stylize; use crossterm::ExecutableCommand; use systemstat::{Platform, System}; mod cli; mod lib; fn main() { let matches = cli::build_cli().get_matches(); ...
b::check_root(); let mut stdout = std::io::stdout(); match stdout.execute(crossterm::terminal::EnterAlternateScreen) { Ok(_) => (), Err(x) => { eprintln!("[{}] Error: {}", "!".red(), x); std::process::exit(1) } }; lib::c...
stdout = std::io::stdout(); match stdout.execute(crossterm::terminal::EnterAlternateScreen) { Ok(_) => (), Err(x) => { eprintln!("[{}] Error: {}", "!".red(), x); std::process::exit(1) } }; lib::check_config_existence(); ...
random
[ { "content": "fn main() {\n\n let outdir = match std::env::var_os(\"OUT_DIR\") {\n\n None => return,\n\n Some(outdir) => outdir,\n\n };\n\n let mut app = build_cli();\n\n app.gen_completions(\"yablo\", Shell::Bash, outdir.clone());\n\n app.gen_completions(\"yablo\", Shell::Fish, out...
Rust
src/autodiff/ops/loss.rs
agemor/sage
af6b660aff16c701ce01153d82a451f048cc8d10
use crate::autodiff::ops::{elemwise_comp_time, pairwise_comp_time, DebugInfo, Operator}; use crate::autodiff::var::{ToVar, Var}; use crate::profile::Profiler; use crate::tensor::Tensor; struct SoftmaxCrossEntropy; impl Operator<2> for SoftmaxCrossEntropy { fn compute(&self, x: [&Tensor; 2]) -> Tensor { le...
use crate::autodiff::ops::{elemwise_comp_time, pairwise_comp_time, DebugInfo, Operator}; use crate::autodiff::var::{ToVar, Var}; use crate::profile::Profiler; use crate::tensor::Tensor; struct SoftmaxCrossEntropy; impl Operator<2> for SoftmaxCrossEntropy { fn compute(&self, x: [&Tensor; 2]) -> Tensor { le...
fn debug_info(&self, x: [&Var; 2], y: &Var, profiler: &Profiler) -> DebugInfo { DebugInfo::new("SoftmaxCrossEntropy", y.shape().size(), 1) } fn forward(self, x: [&Var; 2]) -> Var { let x0 = x[0]; let x1 = x[1]; if x0.shape() != x1.shape() { panic!("shape does ...
x[1]; let log_z = x0 - x0.log_sum_exp(1, true); let log_p = log_z * t; -log_p.sum_axis(1, false) }
function_block-function_prefixed
[ { "content": "pub fn pairwise_comp_time(c: f32, x0: &Var, x1: &Var) -> usize {\n\n let s = std::cmp::max(x0.shape().size(), x1.shape().size()) as f32;\n\n (s * c) as usize\n\n}\n\n\n", "file_path": "src/autodiff/ops/mod.rs", "rank": 0, "score": 150976.4608747001 }, { "content": "// mat...
Rust
src/base.rs
ban-m/partial_order_alignment
b434418447aad843e9267f616a0b609d2da4c38a
use super::base_table::BASE_TABLE; use super::{LAMBDA_INS, LAMBDA_MATCH}; use std::fmt; #[derive(Default, Clone)] pub struct Base { pub base: u8, pub edges: Vec<usize>, pub ties: Vec<usize>, pub weights: Vec<f64>, pub base_count: [f64; 4], pub weight: f64, ...
use super::base_table::BASE_TABLE; use super::{LAMBDA_INS, LAMBDA_MATCH}; use std::fmt; #[derive(Default, Clone)] pub struct Base { pub base: u8, pub edges: Vec<usize>, pub ties: Vec<usize>, pub weights: Vec<f64>, pub base_count: [f64; 4], pub weight: f64, ...
#[inline] pub fn insertion(&self, base: u8) -> f64 { let p = self.base_count[BASE_TABLE[base as usize]]; let q = 0.25; p * LAMBDA_INS + (1. - LAMBDA_INS) * q } #[inline] pub fn has_edge(&self) -> bool { !self.edges.is_empty() } pub fn edges(&self) -> &[usize]...
1. - config.mismatch } else { config.mismatch / 3. }; p * LAMBDA_MATCH + (1. - LAMBDA_MATCH) * q }
function_block-function_prefix_line
[ { "content": "pub fn introduce_randomness<T: rand::Rng>(seq: &[u8], rng: &mut T, p: &Profile) -> Vec<u8> {\n\n let mut res = vec![];\n\n let mut remainings: Vec<_> = seq.iter().copied().rev().collect();\n\n while !remainings.is_empty() {\n\n match *OPERATIONS.choose_weighted(rng, |e| e.weight(p)...
Rust
src/mgmt/worker.rs
hnakamur/weldr
c3a9b2e9a8ac19ca938059131896e86204d41bff
use std::net::SocketAddr; use std::rc::Rc; use std::cell::RefCell; use std::str::FromStr; use weldr_capnp::{publisher, subscriber}; use futures::Future; use capnp_rpc::{RpcSystem, twoparty, rpc_twoparty_capnp}; use capnp::capability::{Response, Promise}; use hyper::Uri; use tokio_io::AsyncRead; use tokio_core::rea...
use std::net::SocketAddr; use std::rc::Rc; use std::cell::RefCell; use std::str::FromStr; use weldr_capnp::{publisher, subscriber}; use futures::Future; use capnp_rpc::{RpcSystem, twoparty, rpc_twoparty_capnp}; use capnp::capability::{Response, Promise}; use hyper::Uri; use tokio_io::AsyncRead; use tokio_core::rea...
ion<Response<publisher::subscribe_results::Owned<::capnp::data::Owned>>>, } pub fn subscribe(addr: SocketAddr, handle: Handle, pool: Pool) -> Rc<RefCell<S>> { let handle1 = handle.clone(); let s = S { response: None }; let s = Rc::new(RefCell::new(s)); let s1 = s.clone(); let request = TcpStream:...
l, true); match self.pool.find(&server) { Some(backend) => { backend.mark_down(); } None => { error!("Unable to find server {:?} to mark as down", server); } } Promise::ok(()) } fn mark_server_active( ...
random
[ { "content": "fn all_servers_reponse(pool: &Pool) -> Response {\n\n let backends = pool.all();\n\n let all_servers: Vec<Server> = backends.iter().map(|backend| backend.server()).collect();\n\n let servers: Vec<PoolServer> = all_servers\n\n .into_iter()\n\n .map(|server| {\n\n l...
Rust
src/mac_os/mod.rs
FreeMasen/rust-sysbar
f95acefe47b9917103c1738b3e3a56a6b9f3b0b7
#![allow(non_snake_case)] use std::mem; extern crate objc; pub use objc::Message; extern crate cocoa; pub use self::cocoa::appkit::{ NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps, NSMenu, NSMenuItem, NSRunningApplication, NSStatusBar, NSStatusItem, NSWindow, }; pub use self::cocoa::base::{nil...
#![allow(non_snake_case)] use std::mem; extern crate objc; pub use objc::Message; extern crate cocoa; pub use self::cocoa::appkit::{ NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps, NSMenu, NSMenuItem, NSRunningApplication, NSStatusBar, NSStatusItem, NSWindow, }; pub use self::cocoa::base::{nil...
} impl INSObject for Callback { fn class() -> &'static Class { let cname = "Callback"; let mut klass = Class::get(cname); if klass.is_none() { println!("registering class for {}", cname); let superclass = NSObject::class(); let mut decl = ClassDecl::new...
runtime::Object); println!("setting the ptr: {}", uptr); obj.set_ivar("_cbptr", uptr); } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let mut bar = sysbar::Sysbar::new(\"Foo\");\n\n\n\n bar.add_item(\n\n \"Say 'bar'\",\n\n Box::new(move || {\n\n println!(\"bar\");\n\n }),\n\n );\n\n\n\n bar.add_quit_item(\"Quit\");\n\n\n\n bar.display();\n\n}\n", "file_path": "ex...
Rust
src/main.rs
compilenix/rust-simple-httpd
05c68ed62fe9c500b844dafd18989bd63584aa78
extern crate chrono; extern crate num_cpus; extern crate rust_hello; use chrono::prelude::*; use rust_hello::*; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::net::{TcpListener, TcpStream}; use std::path::Path; use std::process; fn handle_connection(mut stream: TcpStream, files: H...
extern crate chrono; extern crate num_cpus; extern crate rust_hello; use chrono::prelude::*; use rust_hello::*; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::net::{TcpListener, TcpStream}; use std::path::Path; use std::process; fn handle_connection(mut stream: TcpStream, files: H...
ing() )); let response = format!( "HTTP/1.1 {} {}\r\n{}\r\n\r\n{}\r\n", status_code, status_message, headers, contents ); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap(); return; } if let Some(x) = files.get("/index.ht...
ontents ); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap(); return; } if !request_raw.starts_with("GET") { status_code = 501; status_message = String::from("Not Implemented"); contents = Box::new(String::from("501 - Not Imp...
random
[ { "content": "pub fn string_trim_end(mut s: &str) -> &str {\n\n const TRAILER: &'static str = \"\\0\";\n\n\n\n while s.ends_with(TRAILER) {\n\n let new_len = s.len().saturating_sub(TRAILER.len());\n\n s = &s[..new_len];\n\n }\n\n s\n\n}\n\n\n", "file_path": "src/lib.rs", "rank"...
Rust
library/src/space/shape.rs
saveriomiroddi/ray_tracer_challenge-progress
afcd13e78c4f3c13e8ea21cd3998812d1108b713
use std::{ fmt, sync::{ atomic::{AtomicU32, Ordering}, Arc, Weak, }, }; use super::{BoundedShape, Bounds, Intersection, PointLight, Ray}; use crate::{ math::{Matrix, Tuple}, properties::{Color, Material}, }; #[cfg(test)] use std::any::Any; static NEXT_ID: AtomicU32 = AtomicU32::ne...
use std::{ fmt, sync::{ atomic::{AtomicU32, Ordering}, Arc, Weak, }, }; use super::{BoundedShape, Bounds, Intersection, PointLight, Ray}; use crate::{ math::{Matrix, Tuple}, properties::{Color, Material}, }; #[cfg(test)] use std::any::Any; static NEXT_ID: AtomicU32 = AtomicU32::ne...
fn normal_to_world(&self, normal: &Tuple) -> Tuple { let mut normal = self.transform().inverse().transpose() * normal; normal.w = 0.0; normal = normal.normalize(); if let Some(parent) = self.parent() { parent.normal_to_world(&normal) } else { ...
fn world_to_object(&self, point: &Tuple) -> Tuple { let transform_inverse = self.transform().inverse(); if let Some(parent) = self.parent() { transform_inverse * &parent.world_to_object(point) } else { transform_inverse * point } }
function_block-full_function
[ { "content": "pub trait Pattern: fmt::Debug + Sync + Send {\n\n fn transform(&self) -> &Matrix;\n\n fn previous_pattern(&self) -> &Option<Box<dyn Pattern>>;\n\n\n\n // point: In pattern space.\n\n //\n\n fn color_at(&self, point: &crate::math::Tuple) -> Color {\n\n let mut summed_colors = ...
Rust
relayer-cli/tests/integration.rs
livelybug/ibc-rs
e83a2d0963fe6fa675b4125a4e8c18b13b792d88
#![forbid(unsafe_code)] #![warn( missing_docs, rust_2018_idioms, trivial_casts, unused_lifetimes, unused_qualifications )] use std::sync::Arc; use std::{str::FromStr, sync::Mutex}; use ibc::ics02_client::raw::ConnectionIds as DomainTypeClientConnections; use ibc::ics04_channel::channel::{Channel...
#![forbid(unsafe_code)] #![warn( missing_docs, rust_2018_idioms, trivial_casts, unused_lifetimes, unused_qualifications )] use std::sync::Arc; use std::{str::FromStr, sync::Mutex}; use ibc::ics02_client::raw::ConnectionIds as DomainTypeClientConnections; use ibc::ics04_channel::channel::{Channel...
nState::Init); assert_eq!(query.client_id(), "clientidone"); assert_eq!(query.counterparty().client_id(), "clientidtwo"); assert_eq!(query.counterparty().connection_id(), "connectionidtwo"); assert_eq!(query.counterparty().prefix(), &b"prefix".to_vec().into()); assert_eq!( query.versions(), ...
hain() -> CosmosSDKChain { let rt = Arc::new(Mutex::new(tokio::runtime::Runtime::new().unwrap())); CosmosSDKChain::from_config(simd_config().chains[0].clone(), rt).unwrap() } #[test] #[ignore] fn query_connection_id() { /* the current informaldev/simd image has an incompatible (old?) protobuf implementatio...
random
[ { "content": "fn validate_gas_settings(id: &ChainId, config: &ChainConfig) -> Result<(), Diagnostic<Error>> {\n\n // Check that the gas_adjustment option is not set\n\n if let Some(gas_adjustment) = config.gas_adjustment {\n\n let gas_multiplier = gas_adjustment + 1.0;\n\n\n\n return Err(Dia...
Rust
mercat/common/src/account_transfer.rs
PolymathNetwork/crypto-framework
92f33ce54de7bf3b137459d2cec88ffeb5bebd04
use crate::{ compute_enc_pending_balance, confidential_transaction_file, construct_path, create_rng_from_seed, debug_decrypt, errors::Error, last_ordering_state, load_object, non_empty_account_id, save_object, user_public_account_balance_file, user_public_account_file, user_secret_account_file, OrderedP...
use crate::{ compute_enc_pending_balance, confidential_transaction_file, construct_path, create_rng_from_seed, debug_decrypt, errors::Error, last_ordering_state, load_object, non_empty_account_id, save_object, user_public_account_balance_file, user_public_account_file, user_secret_account_file, OrderedP...
timing!( "account.create_tx.save_to_file", save_to_file_timer, Instant::now() ); Ok(()) } pub fn process_finalize_tx( seed: String, db_dir: PathBuf, sender: String, receiver: String, ticker: String, amount: u32, stdout: bool, tx_id: u32, cheat:...
if stdout { info!( "CLI log: tx-{}: Transaction as base64:\n{}\n", tx_id, base64::encode(asset_tx.encode()) ); }
if_condition
[ { "content": "#[inline]\n\npub fn confidential_transaction_file(tx_id: u32, user: &String, state: TransferTxState) -> String {\n\n format!(\"tx_{}_{}_{}.json\", tx_id, user, state)\n\n}\n\n\n", "file_path": "mercat/common/src/lib.rs", "rank": 0, "score": 313908.55746430287 }, { "content":...
Rust
src/psnark/constraint_system.rs
mmaker/gemini
a8a640a3c91b48640cb6954d61e125ed01c77651
#![allow(non_snake_case)] use crate::ahp::indexer::Matrix; use crate::ahp::*; use ark_ff::{Field, PrimeField}; use ark_poly::{ univariate::DensePolynomial, EvaluationDomain, GeneralEvaluationDomain, UVPolynomial, }; use ark_relations::{ lc, r1cs::{ConstraintMatrices, ConstraintSystemRef}, }; use ark_seria...
#![allow(non_snake_case)] use crate::ahp::indexer::Matrix; use crate::ahp::*; use ark_ff::{Field, PrimeField}; use ark_poly::{ univariate::DensePolynomial, EvaluationDomain, GeneralEvaluationDomain, UVPolynomial, }; use ark_relations::{ lc, r1cs::{ConstraintMatrices, ConstraintSystemRef}, }; use ark_seria...
pub fn num_oracles(&self) -> usize { self.row_poly.len() + self.col_poly.len() + self.val_poly.len() + self.read_ts_row.len() + self.write_ts_row.len() + self.audit_ts_row.len() + self.read_ts_col.len() + self.write_t...
chain(self.val_poly.iter()) .chain(self.read_ts_row.iter()) .chain(self.write_ts_row.iter()) .chain(self.audit_ts_row.iter()) .chain(self.read_ts_col.iter()) .chain(self.write_ts_col.iter()) .chain(self.audit_ts_col.iter()) }
function_block-function_prefix_line
[ { "content": "pub fn dummy_r1cs<F: Field>(rng: &mut impl RngCore, n: usize) -> R1cs<F> {\n\n let e = F::rand(rng);\n\n let inv_e = e.inverse().expect(\"Buy a lottery ticket and retry\");\n\n let z = vec![e; n];\n\n let w = vec![e; n - 1];\n\n let x = vec![e];\n\n\n\n let diagonal_matrix = (0.....
Rust
rs/registry/helpers/src/crypto/tests.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
use super::*; use ic_protobuf::registry::crypto::v1::AlgorithmId as AlgorithmIdProto; use ic_registry_client_fake::FakeRegistryClient; use ic_registry_proto_data_provider::ProtoRegistryDataProvider; use ic_types::PrincipalId; use std::sync::Arc; const REG_V1: RegistryVersion = RegistryVersion::new(1); #[test] fn shou...
use super::*; use ic_protobuf::registry::crypto::v1::AlgorithmId as AlgorithmIdProto; use ic_registry_client_fake::FakeRegistryClient; use ic_registry_proto_data_provider::ProtoRegistryDataProvider; use ic_types::PrincipalId; use std::sync::Arc; const REG_V1: RegistryVersion = RegistryVersion::new(1); #[test] fn shou...
fn node_id(id: u64) -> NodeId { NodeId::from(PrincipalId::new_node_test_id(id)) } fn subnet_id(id: u64) -> SubnetId { SubnetId::from(PrincipalId::new_subnet_test_id(id)) }
fn should_get_tls_certificate_for_node() { let cert_proto = X509PublicKeyCert { certificate_der: b"DER-encoded X509 certificate".to_vec(), }; let node_id = node_id(1); let data_provider = Arc::new(ProtoRegistryDataProvider::new()); data_provider .add( &make_crypto_tls_cer...
function_block-full_function
[]
Rust
src/helpers.rs
vegaluisjose/edifier
546a25260624d99d00216c0e4c93d3c01c76543e
/* MIT License Copyright (c) 2021 Pedro M. Torruella N. */ use serde::{Serialize}; use serde::ser::{Serializer, SerializeSeq}; use crate::ast::*; impl Serialize for PortRef { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializ...
/* MIT License Copyright (c) 2021 Pedro M. Torruella N. */ use serde::{Serialize}; use serde::ser::{Serializer, SerializeSeq}; use crate::ast::*; impl Serialize for PortRef { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializ...
} impl Serialize for InterfacePort { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_seq(Some(3))?; seq.serialize_element(&"port".to_string())?; seq.serialize_element(&self.name)?; ...
r> where S: Serializer, { match self { PortElements::Direction(dir) => dir.serialize(serializer) } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn portref() {\n\n let myport = PortRef { name: \"y\".to_string(),\n\n instanceref: \"myinst\".to_string(), \n\n };\n\n let actual = serde_sexpr::to_string(&myport).unwrap();\n\n assert_eq!(actual, \"...
Rust
src/logic/theory/boolean.rs
akitsu-sanae/verifront
8e46094b21acfe10e0cc965f0ce8df981dae55c8
use crate::format::smtlib2::Smtlib2Theory; use crate::logic::{symbol, theory::*}; use crate::util; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SortSymbol { Bool, } impl IsSortSymbol for SortSymbol {} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FunctionSymbol { Not, And, Or, Im...
use crate::format::smtlib2::Smtlib2Theory; use crate::logic::{symbol, theory::*}; use crate::util; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SortSymbol { Bool, } impl IsSortSymbol for SortSymbol {} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FunctionSymbol { Not, And, Or, Im...
lt<ConstSymbol, ParseError> { if term == &util::make_str_atom("true") { Ok(ConstSymbol::True) } else if term == &util::make_str_atom("false") { Ok(ConstSymbol::False) } else { Err(ParseError::InvalidSexp("const symbol", term.clone())) } } }
PartialEq, Eq)] pub struct Boolean {} impl Theory for Boolean { type SortSymbol = SortSymbol; type FunctionSymbol = FunctionSymbol; type ConstSymbol = ConstSymbol; } use crate::format::smtlib2::{ParseError, PrintError}; use sexp::{Atom, Sexp}; impl Smtlib2Theory for Boolean { fn sexp_of_sort_symbol(s...
random
[ { "content": "pub trait IsSortSymbol: From<boolean::SortSymbol> + Eq + Debug + Clone {}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub enum Sort<T: Theory> {\n\n Symbol(T::SortSymbol),\n\n Var(Symbol),\n\n}\n\n\n", "file_path": "src/logic/theory.rs", "rank": 0, "score": 193329.0920943698...
Rust
src/stream/mod.rs
creator-rs/rust-plist
8812e7a07aa73c685dbf8513615360b0712401b3
mod binary_reader; pub use self::binary_reader::BinaryReader; mod binary_writer; pub use self::binary_writer::BinaryWriter; mod xml_reader; pub use self::xml_reader::XmlReader; mod xml_writer; pub use self::xml_writer::XmlWriter; use std::{ io::{self, Read, Seek, SeekFrom}, vec, }; use crate::{ dicti...
mod binary_reader; pub use self::binary_reader::BinaryReader; mod binary_writer; pub use self::binary_writer::BinaryWriter; mod xml_reader; pub use self::xml_reader::XmlReader; mod xml_writer; pub use self::xml_writer::XmlWriter; use std::{ io::{self, Read, Seek, SeekFrom}, vec, }; use crate::{ dicti...
Write> Sealed for super::XmlWriter<W> {} }
self, event: &Event) -> Result<(), Error> { match event { Event::StartArray(len) => self.write_start_array(*len), Event::StartDictionary(len) => self.write_start_dictionary(*len), Event::EndCollection => self.write_end_collection(), Event::Boolean(value) => self....
random
[ { "content": "/// Deserializes an instance of type `T` from a seekable byte stream containing a plist of any encoding.\n\npub fn from_reader<R: Read + Seek, T: de::DeserializeOwned>(reader: R) -> Result<T, Error> {\n\n let reader = stream::Reader::new(reader);\n\n let mut de = Deserializer::new(reader);\n...
Rust
necsim/core/src/cogs/event_sampler.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
use core::{ cmp::Ordering, hash::{Hash, Hasher}, num::NonZeroU64, }; use necsim_core_bond::{ClosedUnitF64, NonNegativeF64, PositiveF64}; use super::{ CoalescenceSampler, DispersalSampler, EmigrationExit, Habitat, LineageReference, LineageStore, RngCore, SpeciationProbability, TurnoverRate, }; use ...
use core::{ cmp::Ordering, hash::{Hash, Hasher}, num::NonZeroU64, }; use necsim_core_bond::{ClosedUnitF64, NonNegativeF64, PositiveF64}; use super::{ CoalescenceSampler, DispersalSampler, EmigrationExit, Habitat, LineageReference, LineageStore, RngCore, SpeciationProbability, TurnoverRate, }; use ...
} impl PartialEq for SpeciationSample { fn eq(&self, other: &Self) -> bool { self.speciation_sample.cmp(&other.speciation_sample) == Ordering::Equal && f64::from_bits(self.time.get()).total_cmp(&f64::from_bits(other.time.get())) == Ordering::Equal && self.indexed_lo...
n, time: unsafe { NonZeroU64::new_unchecked(time.get().to_bits()) }, speciation_sample, } }
function_block-function_prefixed
[ { "content": "#[contract_trait]\n\npub trait EmigrationExit<H: Habitat, G: RngCore, R: LineageReference<H>, S: LineageStore<H, R>>:\n\n crate::cogs::Backup + core::fmt::Debug\n\n{\n\n #[must_use]\n\n #[debug_ensures(match &ret {\n\n Some((\n\n ret_lineage_reference,\n\n ret...
Rust
src/browser_states.rs
ralt/broot
9c3722ba4ccbe5a812cce4620e2b5059d0e07559
use std::io::{self, Write}; use std::path::PathBuf; use std::time::Instant; use termion::color; use crate::app::{AppState, AppStateCmdResult}; use crate::app_context::AppContext; use crate::commands::{Action, Command}; use crate::external::Launchable; use crate::flat_tree::{LineType, Tree}; use crate::help_states::H...
use std::io::{self, Write}; use std::path::PathBuf; use std::time::Instant; use termion::color; use crate::app::{AppState, AppStateCmdResult}; use crate::app_context::AppContext; use crate::commands::{Action, Command}; use crate::external::Launchable; use crate::flat_tree::{LineType, Tree}; use crate::help_states::H...
pattern(), screen, &tl, )) } LineType::SymLinkToFile(target) => { AppStateCmdResult::Launch(Launchable::opener(&PathBuf::from(target))?) ...
e { Some(ref mut tree) => { tree.move_selection(*dy, page_height); } None => { self.tree.move_selection(*dy, page_height); } }; AppStateCmdResult::Keep ...
random
[ { "content": "pub fn change_directory(line: &TreeLine, con: &AppContext) -> io::Result<AppStateCmdResult> {\n\n Ok(\n\n if let Some(ref output_path) = con.output_path {\n\n // an output path was provided, we write to it\n\n let f = OpenOptions::new().append(true).open(output_path...
Rust
2020/11/src/lib.rs
PsypherPunk/advent-of-code
5da9cea793d0dd326d01ccaa307bfbb13ab8c06f
use std::collections::HashMap; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::str::FromStr; type Point = (usize, usize); type Direction = (isize, isize); const LINE_OF_SIGHT: [Direction; 8] = [ (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), ]; ...
use std::collections::HashMap; use std::fmt::{Display, Formatter, Result as FmtResult}; use std::str::FromStr; type Point = (usize, usize); type Direction = (isize, isize); const LINE_OF_SIGHT: [Direction; 8] = [ (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), ]; ...
} impl SeatLayout { pub fn get_occupied_seat_count(&self) -> usize { self.positions .values() .filter(|position| matches!(position, Position::OccupiedSeat)) .count() } pub fn set_tolerance(&mut self, tolerance: usize) { self.tolerance = tolerance; }...
f: &mut Formatter<'_>) -> FmtResult { let (max_x, max_y) = self.positions.keys().max().unwrap(); let output = (0..=*max_y) .map(|y| { (0..=*max_x) .map(|x| match self.positions.get(&(x, y)).unwrap() { Position::OccupiedSeat => '#',...
function_block-function_prefixed
[ { "content": "pub fn get_part_one(input: &str, display: bool) -> usize {\n\n let mut octopodes = get_octopodes(input);\n\n let mut flash_count = 0;\n\n\n\n let height = octopodes.len();\n\n let width = octopodes[0].len();\n\n\n\n for _ in 1..=100 {\n\n octopodes.iter_mut().for_each(|row| {...
Rust
src/ppb/icsr.rs
austinglaser/xmc4700
12e1d2b638af5ff0e7088605a4299590a2cd60eb
#[doc = "Reader of register ICSR"] pub type R = crate::R<u32, super::ICSR>; #[doc = "Writer for register ICSR"] pub type W = crate::W<u32, super::ICSR>; #[doc = "Register ICSR `reset()`'s with value 0"] impl crate::ResetValue for super::ICSR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register ICSR"] pub type R = crate::R<u32, super::ICSR>; #[doc = "Writer for register ICSR"] pub type W = crate::W<u32, super::ICSR>; #[doc = "Register ICSR `reset()`'s with value 0"] impl crate::ResetValue for super::ICSR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
W { PENDSVSET_W { w: self } } #[doc = "Bit 31 - NMI set-pending bit: 0b0=no effect, 0b1=changes NMI exception state to pending., 0b0=NMI exception is not pending, 0b1=NMI exception is pending.,"] #[inline(always)] pub fn nmipendset(&mut self) -> NMIPENDSET_W { NMIPENDSET_W { w: self } ...
= "0: no effect"] VALUE1 = 0, #[doc = "1: changes SysTick exception state to pending."] VALUE2 = 1, } impl From<PENDSTSET_A> for bool { #[inline(always)] fn from(variant: PENDSTSET_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PENDSTSET`"] pub type PENDSTSET_R = crate::R...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/statsd_backend.rs
lyft/statsrelay
b7114823c1bdfa0c6b00330c6e931dfc6685b1d3
use std::collections::HashMap; use std::sync::atomic::AtomicU64; use futures::stream::FuturesUnordered; use regex::bytes::RegexSet; use crate::config; use crate::discovery; use crate::shard::{statsrelay_compat_hash, Ring}; use crate::stats; use crate::statsd_client::StatsdClient; use crate::statsd_proto; use crate::s...
use std::collections::HashMap; use std::sync::atomic::AtomicU64; use futures::stream::FuturesUnordered; use regex::bytes::RegexSet; use crate::config; use crate::discovery; use crate::shard::{statsrelay_compat_hash, Ring}; use crate::stats; use crate::statsd_client::StatsdClient; use crate::statsd_proto; use crate::s...
.unwrap_or_default(), self.conf .suffix .as_ref() .map(|s| s.as_bytes()) .unwrap_or_default(), ) } else { pdu }; match sender.try_send(pdu_clone) { ...
_ => statsrelay_compat_hash(&pdu), }; let client = ring_read.pick_from(code); let sender = client.sender(); let pdu_clone = if self.conf.prefix.is_some() || self.conf.suffix.is_some() { pdu.with_prefix_suffix( self.conf ...
function_block-random_span
[ { "content": "pub fn statsrelay_compat_hash(pdu: &Pdu) -> u32 {\n\n murmur3::murmur3_32(&mut Cursor::new(pdu.name()), HASHLIB_SEED).unwrap_or(0)\n\n}\n\n\n\npub struct Ring<C: Send + Sync + 'static> {\n\n members: Vec<C>,\n\n}\n\n\n\nimpl<C: Send + Sync + 'static> Ring<C> {\n\n pub fn new() -> Self {\n...
Rust
src/bart/attention.rs
sachaarbonel/rust-bert
6f1888e8f963c9b6671689e6185b48c37c6264f4
use crate::common::dropout::Dropout; use std::borrow::Borrow; use tch::{nn, Tensor}; #[derive(Debug)] pub struct LayerState { pub prev_key: Tensor, pub prev_value: Tensor, } impl Clone for LayerState { fn clone(&self) -> Self { LayerState { prev_key: self.prev_key.copy(), ...
use crate::common::dropout::Dropout; use std::borrow::Borrow; use tch::{nn, Tensor}; #[derive(Debug)] pub struct LayerState { pub prev_key: Tensor, pub prev_value: Tensor, } impl Clone for LayerState {
} impl LayerState { pub(crate) fn reorder_cache(&mut self, new_indices: &Tensor) { self.prev_key = self.prev_key.index_select(0, new_indices); self.prev_value = self.prev_value.index_select(0, new_indices); } } #[derive(Debug)] pub struct BartAttention { num_heads: i64, head_dim: i64,...
fn clone(&self) -> Self { LayerState { prev_key: self.prev_key.copy(), prev_value: self.prev_value.copy(), } }
function_block-full_function
[]
Rust
import/src/shape/smoother.rs
pixunil/tiny-transport
7aee05ba0303e005768e44cabd995b6413c4ce85
use std::error::Error; use std::fmt; use std::str::FromStr; use crate::coord::Point; use crate::shape::Shape; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Mode { Off, Deduplicate, Full, } impl Mode { pub(super) fn smooth(self, shape: Shape) -> Shape { let mut smoother = Smoother::new...
use std::error::Error; use std::fmt; use std::str::FromStr; use crate::coord::Point; use crate::shape::Shape; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Mode { Off, Deduplicate, Full, } impl Mode { pub(super) fn smooth(self, shape: Shape) -> Shape { let mut smoother = Smoother::new...
} #[derive(Debug)] struct Smoother { mode: Mode, points: Vec<Point>, last_sharp_turn: Option<usize>, } impl Smoother { fn new(mode: Mode) -> Self { Self { mode, points: Vec::new(), last_sharp_turn: None, } } fn dedup(&mut self) -> bool { ...
k(Self::Deduplicate), "full" => Ok(Self::Full), _ => Err(InvalidModeError(value.to_string())), } }
function_block-function_prefixed
[ { "content": "pub fn project_back(position: Point) -> (f64, f64) {\n\n let utm = Utm::new(position.x, position.y, true, 33, 'U', false);\n\n let coord = Coord::from(utm);\n\n (coord.lat, coord.lon)\n\n}\n\n\n", "file_path": "import/src/coord.rs", "rank": 1, "score": 104640.00640536266 }, ...
Rust
src/http_peer.rs
tim77/websocat
8a7cda3164a2ab9ff6fbec2feedf4351d5072c35
#![allow(unused)] #![cfg_attr(feature="cargo-clippy",allow(needless_pass_by_value,cast_lossless,identity_op))] use futures::future::{err, ok, Future}; use std::rc::Rc; use super::{box_up_err, peer_strerr, BoxedNewPeerFuture, Peer}; use super::{ConstructParams, L2rUser, PeerConstructor, Specifier}; use tokio_io::io::...
#![allow(unused)] #![cfg_attr(feature="cargo-clippy",allow(needless_pass_by_value,cast_lossless,identity_op))] use futures::future::{err, ok, Future}; use std::rc::Rc; use super::{box_up_err, peer_strerr, BoxedNewPeerFuture, Peer}; use super::{ConstructParams, L2rUser, PeerConstructor, Specifier}; use tokio_io::io::...
specifier_boilerplate!(noglobalstate has_subspec); self_0_is_subspecifier!(proxy_is_multiconnect); } specifier_class!( name = HttpClass, target = Http, prefixes = ["http:"], arg_handling = { fn construct(self: &HttpClass, arg: &str) -> super::Result<Rc<dyn Specifier>> { let ...
fn construct(&self, cp: ConstructParams) -> PeerConstructor { let inner = self.0.construct(cp.clone()); let uri = self.1.clone(); inner.map(move |p, l2r| { let mut b = crate::http::request::Builder::default(); b.uri(uri.clone()); if let Some(method) = cp.progr...
function_block-full_function
[ { "content": "pub fn get_ws_lowlevel_peer(mode: WsLlContext, mut inner: Peer, opts: Rc<Options>) -> BoxedNewPeerFuture {\n\n info!(\"get_ws_lowlevel_peer\");\n\n \n\n use ::tokio_codec::Decoder;\n\n\n\n let c = websocket_base::codec::ws::MessageCodec::new(mode);\n\n let hup = inner.2;\n\n inne...
Rust
src/handlers/topic.rs
yasushisakai/ornot_server
1b090c24c4acfd16f320e3b42b7b43be705ea1b2
use crate::{ model::{PartialTopic, Settable, Topic, RawPlan, Plan}, redis_helper::{redis_add, redis_delete, redis_get_slice}, }; use actix::prelude::*; use actix_redis::{Command, RedisActor}; use actix_web::{web, Error as AWError, HttpResponse}; use futures::future::join; use redis_async::{resp::RespValue, resp...
use crate::{ model::{PartialTopic, Settable, Topic, RawPlan, Plan}, redis_helper::{redis_add, redis_delete, redis_get_slice}, }; use actix::prelude::*; use actix_redis::{Command, RedisActor}; use actix_web::{web, Error as AWError, HttpResponse}; use futures::future::join; use redis_async::{resp::RespValue, resp...
.await?; match res { Ok(RespValue::SimpleString(x)) if x == "OK" => Ok(HttpResponse::Ok().json(topic)), _ => Ok(HttpResponse::InternalServerError().finish()), } } pub async fn add_user( redis: web::Data<Addr<RedisActor>>, path: web::Path<(String, String)>, ) -> Result<HttpRespo...
mmand(resp_array!["SET", &topic.domain(), &topic.json()])); let setting_domain = format!("setting:{}", topic.setting_hash); let set_setting = redis.send(Command(resp_array![ "SET", setting_domain, topic.setting_json() ])); let (res, _) = join(set_top...
random
[]
Rust
lang/src/tests/rects.rs
HactarCE/NDCell
ca2e5f8aae39013a50276c5e9662719fde9c2c3e
use super::{assert_fn_result, compile_test_fn, ConstValue, LangInt}; fn vec_args(arg1: &[LangInt], arg2: &[LangInt]) -> Vec<ConstValue> { vec![ ConstValue::Vector(arg1.to_vec()), ConstValue::Vector(arg2.to_vec()), ] } fn ok_rect<T>(start: &[LangInt], end: &[LangInt]) -> Result<ConstValue, T> { ...
use super::{assert_fn_result, compile_test_fn, ConstValue, LangInt}; fn vec_args(arg1: &[LangInt], arg2: &[LangInt]) -> Vec<ConstValue> { vec![ ConstValue::Vector(arg1.to_vec()), ConstValue::Vector(arg2.to_vec()), ] } fn ok_rect<T>(start: &[LangInt], end: &[LangInt]) -> Result<ConstValue, T> { ...
assert c == [-40..-10, -30..0] // Truncate vector c *= -vec5(10) assert c.ndim == 2 assert c == [400..100, 300..0] // Use integers c -= 200 assert c.ndim == 2 assert c == [200..-100, 100..-200] }", ); asser...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_vector_construct() {\n\n // Test with length and value specified.\n\n let mut f = compile_test_fn(\"@function Vec10 test() { return Vec10(-3) }\");\n\n assert_fn_result(&mut f, &mut [], Ok(ConstValue::Vector(vec![-3; 10])));\n\n\n\n // Test with length specified.\n\n...