lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/auto/filter.rs
vhdirk/gmime-rs
1d02cf114bfcd4c4d9c09e457454d14b8dbe0293
use glib::object::IsA; use glib::translate::*; use std::fmt; use std::mem; use std::ptr; glib::wrapper! { #[doc(alias = "GMimeFilter")] pub struct Filter(Object<ffi::GMimeFilter, ffi::GMimeFilterClass>); match fn { type_ => || ffi::g_mime_filter_get_type(), } } pub const NONE_FILTER: Option...
use glib::object::IsA; use glib::translate::*; use std::fmt; use std::mem; use std::ptr; glib::wrapper! { #[doc(alias = "GMimeFilter")] pub struct Filter(Object<ffi::GMimeFilter, ffi::GMimeFilterClass>); match fn { type_ => || ffi::g_mime_filter_get_type(), } } pub const NONE_FILTER: Option...
fn copy(&self) -> Option<Filter> { unsafe { from_glib_full(ffi::g_mime_filter_copy(self.as_ref().to_glib_none().0)) } } fn filter(&self, inbuf: &[u8], prespace: usize) -> (Vec<u8>, usize) { let inlen = inbuf.len() as usize; unsafe { let mut outbuf = ptr::null_mut(); ...
fn complete(&self, inbuf: &[u8], prespace: usize) -> (Vec<u8>, usize) { let inlen = inbuf.len() as usize; unsafe { let mut outbuf = ptr::null_mut(); let mut outlen = mem::MaybeUninit::uninit(); let mut outprespace = mem::MaybeUninit::uninit(); ffi::g_mime_...
function_block-full_function
[ { "content": "pub trait DataWrapperExt: 'static {\n\n #[doc(alias = \"g_mime_data_wrapper_get_encoding\")]\n\n #[doc(alias = \"get_encoding\")]\n\n fn encoding(&self) -> ContentEncoding;\n\n\n\n #[doc(alias = \"g_mime_data_wrapper_get_stream\")]\n\n #[doc(alias = \"get_stream\")]\n\n fn stream...
Rust
src/agent/debugger/src/debug_event.rs
bmc-msft/onefuzz
087e6d19b42add9285b53ec963c8bd4ead6067b3
use std::{ self, fmt::{self, Display}, path::Path, }; use win_util::file::get_path_from_handle; use winapi::{ shared::minwindef::DWORD, um::minwinbase::{ CREATE_PROCESS_DEBUG_EVENT, CREATE_PROCESS_DEBUG_INFO, CREATE_THREAD_DEBUG_EVENT, CREATE_THREAD_DEBUG_INFO, DEBUG_EVENT, EXCEPT...
use std::{ self, fmt::{self, Display}, path::Path, }; use win_util::file::get_path_from_handle; use winapi::{ shared::minwindef::DWORD, um::minwinbase::{ CREATE_PROCESS_DEBUG_EVENT, CREATE_PROCESS_DEBUG_INFO, CREATE_THREAD_DEBUG_EVENT, CREATE_THREAD_DEBUG_INFO, DEBUG_EVENT, EXCEPT...
}; Self { process_id: de.dwProcessId, thread_id: de.dwThreadId, info, } } pub fn process_id(&self) -> DWORD { self.process_id } pub fn thread_id(&self) -> DWORD { self.thread_id } pub fn info(&self) -> &DebugEventIn...
match de.dwDebugEventCode { EXCEPTION_DEBUG_EVENT => DebugEventInfo::Exception(de.u.Exception()), CREATE_PROCESS_DEBUG_EVENT => { DebugEventInfo::CreateProcess(de.u.CreateProcessInfo()) } CREATE_THREAD_DEBUG_EVENT => DebugEventInfo::Cre...
if_condition
[ { "content": "pub fn client_mut(client_type: ClientType) -> Option<RwLockWriteGuard<'static, TelemetryClient>> {\n\n Some(try_client_mut(client_type)?.unwrap())\n\n}\n\n\n", "file_path": "src/agent/onefuzz/src/telemetry.rs", "rank": 0, "score": 270930.7980870795 }, { "content": "pub fn ge...
Rust
qlib/kernel/print.rs
abel-von/Quark
7bbba67ee1105e3b7df751a278cbad9b2af666a1
use alloc::string::String; use super::task::*; use super::super::vcpu_mgr::*; use super::asm::*; pub const SCALE : i64 = 2_000; pub fn PrintPrefix() -> String { let now = if super::SHARESPACE.config.read().PerfDebug { TSC.Rdtsc()/SCALE } else { 0 }; return format!("[{}/{:x}|{}]", C...
use alloc::string::String; use super::task::*; use super::super::vcpu_mgr::*; use super::asm::*; pub const SCALE : i64 = 2_000; pub fn PrintPrefix() -> String { let now = if super::SHARESPACE.config.read().PerfDebug { TSC.Rdtsc()/SCALE } else { 0 }; return format!("[{}/{:x}|{}]", C...
ate::SHARESPACE.config.read().DebugLevel >= $crate::super::config::DebugLevel::Error { let prefix = $crate::print::PrintPrefix(); let s = &format!($($arg)*); let str = format!("[Print] {} {}", prefix, s); $crate::Kernel::HostSpace::SyncPrint($crate::super::c...
= &format!($($arg)*); let str = format!("[Print] {}", s); $crate::Kernel::HostSpace::SyncPrint($crate::super::config::DebugLevel::Error, &str); } }); } #[macro_export] macro_rules! print { ($($arg:tt)*) => ({ if $cr
random
[ { "content": "#[inline]\n\npub fn Scale(tsc: i64) -> i64 {\n\n tsc * 1000 /(LoadVcpuFreq() / 1_000)\n\n}\n\n\n", "file_path": "qlib/kernel/mod.rs", "rank": 0, "score": 360991.81440870906 }, { "content": "pub fn PrintPrefix() -> String {\n\n let now = if super::SHARESPACE.config.read()....
Rust
pallets/poe/src/tests.rs
xingfly/rust_pro_1
8425b3c5d059dd8847dce4676eb2d05e35de3cb9
use super::*; use crate::{mock::*, Error}; use frame_support::{assert_noop, assert_ok}; #[test] fn create_claim_works() { new_test_ext().execute_with(|| { let claim = vec![0 as u8, 1 as u8]; assert_ok!(PoeModule::create_claim(Origin::signed(1), claim.clone())); assert_eq!( Proofs...
use super::*; use crate::{mock::*, Error}; use frame_support::{assert_noop, assert_ok}; #[test] fn create_claim_works() { new_test_ext().execute_with(|| { let claim = vec![0 as u8, 1 as u8]; assert_ok!(PoeModule::create_claim(Origin::signed(1), claim.clone())); assert_eq!( Proofs...
laim = vec![0 as u8, 1 as u8]; let _ = PoeModule::create_claim(Origin::signed(1), claim.clone()); assert_noop!( PoeModule::transfer_claim(Origin::signed(2), claim.clone(), 3), Error::<Test>::NotProofOwner ); }); } #[test] fn create_claim_failed_...
( PoeModule::create_claim(Origin::signed(1), claim.clone()), Error::<Test>::ProofAlreadyClaimed ); }) } #[test] fn revoke_claim_works() { new_test_ext().execute_with(|| { let claim = vec![0 as u8, 1 as u8]; let _ = PoeModule::create_claim(Origin::signed(1), claim...
random
[ { "content": "#[test]\n\nfn correct_error_for_none_value() {\n\n new_test_ext().execute_with(|| {\n\n // Ensure the expected error is thrown when no value is present.\n\n assert_noop!(\n\n TemplateModule::cause_error(Origin::signed(1)),\n\n Error::<Test>::NoneValue\n\n ...
Rust
research/gaia-x/pegasus/pegasus/src/stream.rs
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
use std::fmt::{Debug, Formatter}; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use pegasus_common::codec::ShadeCodec; use crate::api::function::FnResult; use crate::api::meta::OperatorInfo; use crate::api::scope::ScopeDelta; use crate::api::{Map, Unary}; use cr...
use std::fmt::{Debug, Formatter}; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use pegasus_common::codec::ShadeCodec; use crate::api::function::FnResult; use crate::api::meta::OperatorInfo; use crate::api::scope::ScopeDelta; use crate::api::{Map, Unary}; use cr...
pub fn union_transform<R, O, F, T>( mut self, name: &str, mut other: Stream<R>, op_builder: F, ) -> Result<Stream<O>, BuildJobError> where R: Data, O: Data, T: OperatorCore, F: FnOnce(&OperatorInfo) -> T, { if self.get_scope_level() != other.get_scope_le...
r)?; let port = op.new_output::<O>(); let ch = Channel::mount_to(&port); Ok(Stream { has_cycles, port, ch, dfb }) }
function_block-function_prefixed
[ { "content": "struct AnonymityEmitter<D: Data, F: FnMut(&D) -> Option<u32> + Send + Clone + 'static> {\n\n func: F,\n\n _ph: std::marker::PhantomData<D>,\n\n}\n\n\n\nimpl<D: Data, F: FnMut(&D) -> Option<u32> + Send + Clone + 'static> AnonymityEmitter<D, F> {\n\n pub fn new(func: F) -> Self {\n\n ...
Rust
src/routing/pages/admin.rs
reslario/web-quiz
4077e243520c9b2738b969ef016b5d5217eac595
use { serde::Serialize, serde_repr::Serialize_repr, rocket_contrib::{ json::Json, templates::Template }, rocket::{ uri, get, put, post, delete, FromForm, response::Redirect, request::{Form, FromFormValue}, http::...
use { serde::Serialize, serde_repr::Serialize_repr, rocket_contrib::{ json::Json, templates::Template }, rocket::{ uri, get, put, post, delete, FromForm, response::Redirect, request::{Form, FromFormValue}, http::...
} impl UriDisplay<Query> for RegisterError { fn fmt(&self, f: &mut Formatter<Query>) -> std::fmt::Result { f.write_value(self.id().to_string()) } } impl_from_uri_param_identity!([Query] RegisterError); #[get("/admin?<error>")] pub fn admin(error: Option<RegisterError>, _guard: AdminGuard) -> Templat...
fn from_form_value(form_value: &'v RawStr) -> Result<Self, Self::Error> { form_value .parse::<u32>() .map(|int| match int { 1 => RegisterError::NameInUse, 2 => RegisterError::Other, _ => RegisterError::None }) }
function_block-function_prefix_line
[ { "content": "pub fn correct_ratio(question: &Question, conn: &PgConnection) -> QueryResult<u8> {\n\n question\n\n .stats()\n\n .load(conn)\n\n .map(|stats| stats.correct_ratio())\n\n}\n\n\n\npub struct Scores {\n\n pub placement: u64,\n\n pub top_three: Vec<Score>,\n\n pub lowe...
Rust
src/config.rs
rajarshimaitra/rust-nostr
36f43f78e708dca78bc2b34eecf9ddf2fb6dd06b
use lazy_static::lazy_static; use log::*; use secp256k1::XOnlyPublicKey; use serde::{Deserialize, Serialize}; use std::sync::RwLock; lazy_static! { pub static ref SETTINGS: RwLock<Settings> = RwLock::new(Settings::default()); } #[derive(Debug, Serialize, Deserialize, Clone)] #[allow(unused)] pub struct Info { ...
use lazy_static::lazy_static; use log::*; use secp256k1::XOnlyPublicKey; use serde::{Deserialize, Serialize}; use std::sync::RwLock; lazy_static! { pub static ref SETTINGS: RwLock<Settings> = RwLock::new(Settings::default()); } #[derive(Debug, Serialize, Deserialize, Clone)] #[allow(unused)] pub struct Info { ...
} impl Default for Settings { fn default() -> Self { Settings { info: Info { relay_url: None, name: Some("nostrd-v0.0.1".to_owned()), description: None, pubkey: None, contact: None, }, datab...
t).unwrap())? .with_merged(config::File::with_name("config"))? .try_into()?; Ok(settings) }
function_block-function_prefixed
[ { "content": "/// Return a requested DB name from command line arguments.\n\nfn db_from_args(args: Vec<String>) -> Option<String> {\n\n if args.len() == 3 && args.get(1) == Some(&\"--db\".to_owned()) {\n\n return args.get(2).map(|x| x.to_owned());\n\n }\n\n None\n\n}\n\n\n\n/// Handle arbitrary ...
Rust
src/data/user.rs
avielmenter/seriatim-server
c0256288623422820246b2fd490ebfdf11a5edb9
use data; use data::db::Connection; use data::schema::documents::dsl::{documents, user_id}; use data::schema::users; use data::schema::users::dsl::*; use diesel; use diesel::prelude::*; use diesel::Connection as DieselConnection; use oauth::facebook::FacebookUser; use oauth::google::GoogleUser; use oauth::twitter::Tw...
use data; use data::db::Connection; use data::schema::documents::dsl::{documents, user_id}; use data::schema::users; use data::schema::users::dsl::*; use diesel; use diesel::prelude::*; use diesel::Connection as DieselConnection; use oauth::facebook::FacebookUser; use oauth::google::GoogleUser; use oauth::twitter::Tw...
let merged_user_data = User::get_merged_user_data(&self.data, &merge_user.data); let new_data = self .connection .pg_connection .transaction::<_, diesel::result::Error, _>(|| { diesel::update(documents) .filter(user_id.eq(&merge_...
if (self.has_facebook() && merge_user.has_facebook()) || (self.has_twitter() && merge_user.has_twitter()) || (self.has_google() && merge_user.has_google()) { return Err(diesel::result::Error::QueryBuilderError(Box::new( std::io::Error::new( ...
if_condition
[ { "content": "pub fn send_success<T: Serialize>(data: &T) -> JsonValue {\n\n json!({\n\n \"status\": \"success\",\n\n \"timestamp\": SystemTime::now(),\n\n \"data\": data\n\n })\n\n}\n\n\n", "file_path": "src/routes/io.rs", "rank": 0, "score": 140615.81224318538 }, { ...
Rust
src/y21/d15.rs
whonore/aoc2020
f208a0814e71592bf97b5cc29216d32a287795fc
use std::cmp; use std::collections::{BinaryHeap, HashMap, HashSet}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct PointDist((usize, usize), u64); impl Ord for PointDist { fn cmp(&self, other: &Self) -> cmp::Ordering { self.1.cmp(&other.1).reverse() } } impl PartialOrd for PointDist { fn par...
use std::cmp; use std::collections::{BinaryHeap, HashMap, HashSet}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct PointDist((usize, usize), u64); impl Ord for PointDist { fn cmp(&self, other: &Self) -> cmp::Ordering { self.1.cmp(&other.1).reverse() } } impl PartialOrd for PointDist { fn par...
fn part1(risks: &[Vec<u64>]) -> u64 { find_path(risks) } fn part2(mut risks: Vec<Vec<u64>>) -> u64 { expand_map(&mut risks, 5); find_path(&risks) } #[allow(clippy::unnecessary_wraps)] pub fn run() -> Result<String, String> { let input = include_str!("input/d15.txt"); let risks = input .l...
for cell in 1..n { let mut new_risks = risks[..size].to_vec(); for row in &mut new_risks { for c in row.iter_mut() { *c = add_wrap_9(*c, cell as u64); } } risks.extend(new_risks); } }
function_block-function_prefix_line
[ { "content": "fn dist(x: u64, y: u64) -> u64 {\n\n assert!(x <= y);\n\n let n = y - x;\n\n n * (n + 1) / 2\n\n}\n\n\n", "file_path": "src/y21/d07.rs", "rank": 1, "score": 253313.78289786237 }, { "content": "fn part1(mut img: Image, alg: &Algorithm, n: u64) -> usize {\n\n for _ in...
Rust
src/model/blockchain/block_info.rs
BlockPuppets/symbol-sdk-rust
3d622a4d221736f3da7383db1167133111c5c8f1
/* * // Copyright 2021 BlockPuppets. * // * // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * // option. This file may not be copied, modified, or distribute...
/* * // Copyright 2021 BlockPuppets. * // * // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or * // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license * // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your * // option. This file may not be copied, modified, or distribute...
anceBlockInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", serde_json::to_string_pretty(&self).unwrap_or_default() ) } }
tate_hash_sub_cache_merkle_roots: Vec<H256>, pub total_transactions_count: u16, pub transactions_count: u16, pub statements_count: u16, #[serde(skip_serializing_if = "Option::is_none")] pub nemesis_importance_info: Option<NemesisImportanceBlockInfo>, } impl fmt::Display for Block...
random
[ { "content": "pub fn encode_base32(data: &[u8]) -> String {\n\n let mut encode_address = base32::encode(RFC4648 { padding: true }, data);\n\n encode_address.truncate(Address::LENGTH_IN_BASE32);\n\n encode_address.to_uppercase()\n\n}\n\n\n", "file_path": "src/core/format/raw_address.rs", "rank":...
Rust
rust-app/bin-src/main_nanos.rs
obsidiansystems/ledger-app-kadena
d68a96597b74e8cb013e4332d1404bfdf4dadc2b
use kadena::implementation::*; use kadena::interface::*; use kadena::settings::*; use ledger_parser_combinators::interp_parser::set_from_thunk; use nanos_sdk::io; use nanos_sdk::buttons::{ButtonEvent}; use nanos_ui::ui::{SingleMessage}; nanos_sdk::set_panic!(nanos_sdk::exiting_panic); use ledger_parser_combinators::...
use kadena::implementation::*; use kadena::interface::*; use kadena::settings::*; use ledger_parser_combinators::interp_parser::set_from_thunk; use nanos_sdk::io; use nanos_sdk::buttons::{ButtonEvent}; use nanos_ui::ui::{SingleMessage}; nanos_sdk::set_panic!(nanos_sdk::exiting_panic); use ledger_parser_combinators::...
#[inline(never)] fn handle_apdu(comm: &mut io::Comm, ins: Ins, parser: &mut ParsersState) -> Result<(), Reply> { info!("entering handle_apdu with command {:?}", ins); if comm.rx == 0 { return Err(io::StatusWords::NothingReceived.into()); } match ins { Ins::GetVersion => { ...
fn run_parser_apdu<P: InterpParser<A, Returning = ArrayVec<u8, 128>>, A>( states: &mut ParsersState, get_state: fn(&mut ParsersState) -> &mut <P as InterpParser<A>>::State, parser: &P, comm: &mut io::Comm, ) -> Result<(), Reply> { let cursor = comm.get_data()?; loop { trace!("Parsing AP...
function_block-full_function
[ { "content": "pub fn set_settings(v: &u8) {\n\n let settings = unsafe { SETTINGS.get_mut() };\n\n settings.update(&v);\n\n}\n", "file_path": "rust-app/src/settings.rs", "rank": 1, "score": 129148.55849886857 }, { "content": "pub fn reset_parsers_state(state: &mut ParsersState) {\n\n ...
Rust
src/tests/function/lpad_rpad.rs
Snowapril/gluesql
eaca157102aca8ad05c4f73c0d25349169d9fb8f
use crate::*; test_case!(lpad_rpad, async move { use Value::{Null, Str}; let test_cases = vec![ ("CREATE TABLE Item (name TEXT)", Ok(Payload::Create)), ( r#"INSERT INTO Item VALUES ("hello")"#, Ok(Payload::Insert(1)), ), ( "CREATE TABLE NullN...
use crate::*; test_case!(lpad_rpad, async move { use Value::{Null, Str}; let test_cases = vec![ ("CREATE TABLE Item (name TEXT)", Ok(Payload::Create)), ( r#"INSERT INTO Item VALUES ("hello")"#, Ok(Payload::Insert(1)), ), ( "CREATE TABLE NullN...
name: "LPAD".to_string(), expected_minimum: 2, expected_maximum: 3, found: 4, } .into()), ), ( "SELECT RPAD(name, 10, 'ab', 'cd') FROM Item", Err(TranslateError::FunctionArgsLengthNotWithinRange...
10)" Str | Str; " hello".to_owned() "hello ".to_owned() )), ), ( "SELECT LPAD(name, 10, 'ab'), RPAD(name, 10, 'ab') FROM Item", Ok(select!( "LPAD(name, 10, 'ab')" | "RPAD(name, 10, 'ab')...
random
[ { "content": "pub fn build_index_key(table_name: &str, index_name: &str, value: Value) -> Result<Vec<u8>> {\n\n Ok(build_index_key_prefix(table_name, index_name)\n\n .into_iter()\n\n .chain(value.to_cmp_be_bytes()?)\n\n .collect::<Vec<_>>())\n\n}\n", "file_path": "src/storages/sled_s...
Rust
rafx-assets/src/assets/image/assets.rs
superdump/rafx
0f4bb085b513ea50a660719e7f434d20ba65f1b3
use crate::assets::upload::ImageUploadOpResult; use crate::distill_impl::{AssetResource, ResourceAssetLoader}; use crate::{ AssetLookup, AssetManager, AssetTypeHandler, AssetTypeHandlerFactory, DynAssetLookup, LoadQueues, }; use rafx_api::{RafxResourceType, RafxResult, RafxTexture}; use rafx_framework::{ImageRe...
use crate::assets::upload::ImageUploadOpResult; use crate::distill_impl::{AssetResource, ResourceAssetLoader}; use crate::{ AssetLookup, AssetManager, AssetTypeHandler, AssetTypeHandlerFactory, DynAssetLookup, LoadQueues, }; use rafx_api::{RafxResourceType, RafxResult, RafxTexture}; use rafx_framework::{ImageRe...
ults { match result { ImageUploadOpResult::UploadComplete(load_op, result_tx, texture) => { log::trace!("Uploading image {:?} complete", load_op.load_handle()); let loaded_asset = finish_load_image(asset_manager, texture); crate::as...
Self { ImageAssetBasisCompressionSettings { compression_type: ImageAssetBasisCompressionType::Etc1S, quality: basis_universal::ETC1S_QUALITY_DEFAULT, } } } #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub enum ImageAssetDataFormat { RawRGBA32, BasisCompress...
random
[ { "content": "//\n\n// Static functions\n\n//\n\npub fn handle_load_result<AssetT: Clone>(\n\n load_op: AssetLoadOp,\n\n loaded_asset: RafxResult<AssetT>,\n\n asset_lookup: &mut AssetLookup<AssetT>,\n\n result_tx: Sender<AssetT>,\n\n) {\n\n match loaded_asset {\n\n Ok(loaded_asset) => {\n\...
Rust
src/main.rs
legion-labs/project-init
cc0dfeb5ea764d9d352b578e5854e4687f80c325
use std::fs::read_dir; use std::fs::File; use std::io::Write; use args::Args; use args::Subcommands; use clap::StructOpt; use git2::Repository; use tempdir::TempDir; use tracing::error; use tracing_subscriber::FmtSubscriber; use types::Config; use types::Project; use crate::constants::{ GITHUB_URL, GLOBAL_CONFI...
use std::fs::read_dir; use std::fs::File; use std::io::Write; use args::Args; use args::Subcommands; use clap::StructOpt; use git2::Repository; use tempdir::TempDir; use tracing::error; use tracing_subscriber::FmtSubscriber; use types::Config; use types::Project; use crate::constants::{ GITHUB_URL, GLOBAL_CONFI...
async fn main() -> Result<(), Box<dyn std::error::Error>> { tracing::subscriber::set_global_default(FmtSubscriber::default())?; let args = Args::parse(); let home = dirs::home_dir().ok_or("Couldn't determine home directory")?; let config = Config::from_path(&home.join(GLOBAL_CONFIG_FILENAME)); m...
function_block-full_function
[ { "content": "# {{ project }}\n\n\n\n## Installation\n\n\n\n## Configuration\n", "file_path": "src/includes/README.md", "rank": 0, "score": 27427.655960196564 }, { "content": "use lazy_static::lazy_static;\n\nuse url::Url;\n\n\n\nlazy_static! {\n\n pub static ref GITHUB_URL: Url = \"https...
Rust
crate/src/conv.rs
sunny4381/photon
a72e15964384d5ded91e8ee841cdebf73ff10f9a
extern crate image; use crate::helpers; use crate::PhotonImage; use wasm_bindgen::prelude::*; fn conv(mut photon_image: &mut PhotonImage, kernel: Vec<f32>) { let mut img = helpers::dyn_image_from_raw(&photon_image); img = image::ImageRgb8(img.to_rgb()); let mut filtered_img = img.filter3x3(&kernel); ...
extern crate image; use crate::helpers; use crate::PhotonImage; use wasm_bindgen::prelude::*; fn conv(mut photon_image: &mut PhotonImage, kernel: Vec<f32>) { let mut img = helpers::dyn_image_from_raw(&photon_image); img = image::ImageRgb8(img.to_rgb());
#[wasm_bindgen] pub fn noise_reduction(photon_image: &mut PhotonImage) { let kernel = vec![0.0f32, -1.0, 7.0, -1.0, 5.0, 9.0, 0.0, 7.0, 9.0]; conv(photon_image, kernel) } #[wasm_bindgen] pub fn sharpen(photon_image: &mut PhotonImage) { let kernel = vec![0.0f32, -1.0, 0.0, -1.0, 5.0, -1.0, 0.0, -1.0, 0.0]...
let mut filtered_img = img.filter3x3(&kernel); filtered_img = image::ImageRgba8(filtered_img.to_rgba()); photon_image.raw_pixels = filtered_img.raw_pixels(); }
function_block-function_prefix_line
[ { "content": "#[wasm_bindgen]\n\npub fn obsidian(img: &mut PhotonImage) {\n\n monochrome::grayscale(img);\n\n adjust_contrast(img, 25.0);\n\n}\n", "file_path": "crate/src/filters.rs", "rank": 1, "score": 232088.6147131713 }, { "content": "#[wasm_bindgen]\n\npub fn grayscale(img: &mut P...
Rust
old/siyo/src/shared/wasm/mod.rs
plopgrizzly/aldaron
442baeafdc462deca73b778c525061d8a3213b99
/*use std::cell::RefCell; use std::rc::Rc; mod webgl_rendering_context; use stdweb::unstable::TryInto; use stdweb::web::{document, window, IEventTarget, IHtmlElement, IParentNode, TypedArray}; use stdweb::web::event::ResizeEvent; use stdweb::web::html_element::CanvasElement; use self::webgl_rendering_context::{WebG...
/*use std::cell::RefCell; use std::rc::Rc; mod webgl_rendering_context; use stdweb::unstable::TryInto; use stdweb::web::{document, window, IEventTarget, IHtmlElement, IParentNode, TypedArray}; use stdweb::web::event::ResizeEvent; use stdweb::web::html_element::CanvasElement; use self::webgl_rendering_context::{WebG...
r); context.use_program(Some(&shader_program)); let mov_matrix = [ 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., ]; let mut view_matrix = [ 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., ]; // translating z view_matrix[14] -= 6.; //zoom ...
self.context.viewport(0, 0, w as i32, h as i32); self.context .clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT); self.context .uniform_matrix4fv(Some(&self.p_matrix), false, &proj_matrix[..]); self.context .uniform_matrix4fv(Some(&self.v_matrix), false, &s...
random
[ { "content": "fn rotate_z(m: &mut [f32], angle: f32) {\n\n let (s, c) = angle.sin_cos();\n\n let (mv0, mv4, mv8) = (m[0], m[4], m[8]);\n\n\n\n m[0] = c*m[0]-s*m[1];\n\n m[4] = c*m[4]-s*m[5];\n\n m[8] = c*m[8]-s*m[9];\n\n\n\n m[1]=c*m[1]+s*mv0;\n\n m[5]=c*m[5]+s*mv4;\n\n m[9]=c*m[9]+s*mv8...
Rust
src/file.rs
TheDaemoness/editorconfig-core-rs
610df2d6aa2332cb688d26c420cb225d60a5649c
use std::path::{Path, PathBuf}; use crate::{ConfigParser, Error, ParseError, Properties, PropertiesSource, Section}; pub struct ConfigFile { pub path: PathBuf, pub reader: ConfigParser<std::io::BufReader<std::fs::File>>, } impl ConfigFile { pub fn open(path: impl Into<PathBuf>) -> Result<ConfigFile, Par...
use std::path::{Path, PathBuf}; use crate::{ConfigParser, Error, ParseError, Properties, PropertiesSource, Section}; pub struct ConfigFile { pub path: PathBuf, pub reader: ConfigParser<std::io::BufReader<std::fs::File>>, } impl ConfigFile { pub fn open(path: impl Into<PathBuf>) -> Result<ConfigFile, Par...
} pub struct ConfigFiles(Vec<ConfigFile>); impl ConfigFiles { pub fn open( path: impl AsRef<Path>, config_path_override: Option<impl AsRef<std::path::Path>>, ) -> Result<ConfigFiles, Error> { use std::borrow::Cow; let filename = config_path_override .as_ref() .map(|f| f.as_ref()) .un...
ath.as_ref() }; match self.reader.apply_to(props, path) { Ok(()) => Ok(()), Err(crate::Error::Parse(e)) => Err(self.add_error_context(e)), Err(e) => panic!("unexpected error variant {:?}", e), } }
function_block-function_prefixed
[ { "content": "/// Retrieves the [Properties] for a file at the given path.\n\n///\n\n/// This is the simplest way to use this library in an EditorConfig integration or plugin.\n\n///\n\n/// This function does not canonicalize the path,\n\n/// but will join relative paths onto the current working directory.\n\n/...
Rust
src/layer_four/mod.rs
dexterdarwich/toms-data-onion-rust
a795db5173e05491c89a64493533395e2e0f4949
use anyhow::Result; use crate::helpers; /* ==[ Layer 4/6: Network Traffic ]============================ When computers send data over a network like the internet, the data is broken up and placed within packets. As well as containing the data being sent, packets contain extra data like the destination address (where...
use anyhow::Result; use crate::helpers; /* ==[ Layer 4/6: Network Traffic ]============================ When computers send data over a network like the internet, the data is broken up and placed within packets. As well as containing the data being sent, packets contain extra data like the destination address (where...
ocol is being used. Protocols are specifications that define exactly how senders should format packet data before it is sent over the network, and exactly how receivers should interpret the data that has come from the network. At the moment, the networking protocol that most computers use is TCP/IP, which is a combinat...
l service, packets are a similar concept to envelopes. A letter (data) is placed inside an envelope (packet). The destination address is written on the envelope, probably accompanied by a return address and a stamp. The people and machines that make up the postal system use the information on the envelope to relay it t...
random
[]
Rust
src/auto/texture.rs
angular-rust/clutter-rs
122b376d6c6132d865aefc6a9096f0ab4965180b
use crate::{Actor, Animatable, Container}; use glib::{ object as gobject, object::{Cast, IsA}, signal::{connect_raw, SignalHandlerId}, translate::*, StaticType, Value, }; use std::boxed::Box as Box_; use std::{fmt, mem::transmute}; glib_wrapper! { pub struct Texture(Object<ffi::ClutterTexture,...
use crate::{Actor, Animatable, Container}; use glib::{ object as gobject, object::{Cast, IsA}, signal::{connect_raw, SignalHandlerId}, translate::*, StaticType, Value, }; use std::boxed::Box as Box_; use std::{fmt, mem::transmute}; glib_wrapper! { pub struct Texture(Object<ffi::ClutterTexture,...
fn set_property_repeat_x(&self, repeat_x: bool) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"repeat-x\0".as_ptr() as *const _, Value::from(&repeat_x).to_glib_none().0, ); ...
0".as_ptr() as *const _, value.to_glib_none_mut().0, ); value .get() .expect("Return Value for property `repeat-x` getter") .unwrap() } }
function_block-function_prefixed
[ { "content": "/// Trait containing all `Animatable` methods.\n\n///\n\n/// # Implementors\n\n///\n\n/// [`Actor`](struct.Actor.html), [`Animatable`](struct.Animatable.html), [`Box`](struct.Box.html), [`Clone`](struct.Clone.html), [`Group`](struct.Group.html), [`Rectangle`](struct.Rectangle.html), [`ScrollActor`...
Rust
frontend/apps/crates/entry/dev/scratch/001/src/page.rs
RickyLB/ji-cloud
f0805af606007d4163ee52f09e42f7710fdb6823
#![allow(unused_imports)] #![allow(dead_code)] use std::rc::Rc; use dominator::{clone, events, html, Dom}; use futures_signals::{ signal::{Mutable, SignalExt}, signal_vec::SignalVecExt, }; use components::{ color_select, image::search::{ self as image_search, callbacks::Callbacks as I...
#![allow(unused_imports)] #![allow(dead_code)] use std::rc::Rc; use dominator::{clone, events, html, Dom}; use futures_signals::{ signal::{Mutable, SignalExt}, signal_vec::SignalVecExt, }; use components::{ color_select, image::search::{ self as image_
.child(color_select::dom::render( Rc::new(state), None )) }) } pub fn render_text_editor_controls(state: Rc<text_editor::state::State>) -> Dom { html!("div", { .style("grid-row", "1 / -1") .style("padding", "10px") .style("width", "492px") .c...
search, callbacks::Callbacks as ImageSearchCallbacks, state::{ImageSearchKind, ImageSearchOptions}, }, text_editor, }; use utils::{prelude::*, themes::ThemeId}; pub struct Page {} impl Page { pub fn render() -> Dom { render_image_search() } } struct State { pub current_st...
random
[ { "content": "pub fn mixin_sticker_button(dom: DomBuilder<HtmlElement>) -> DomBuilder<HtmlElement> {\n\n dom.style(\"cursor\", \"pointer\")\n\n .style(\"user-select\", \"none\")\n\n .style(\"-webkit-user-select\", \"none\")\n\n}\n\n\n\npub enum StickerRenderOptions {\n\n Sprite(SpriteRenderO...
Rust
io-engine/src/grpc/v1/host.rs
openebs/MayaStor
a6424b565ea4023acc7896e591e9c71f832eba3f
use crate::{ bdev::{nexus, NvmeControllerState}, core::{BlockDeviceIoStats, CoreError, MayastorFeatures}, grpc::{ controller_grpc::{ controller_stats, list_controllers, NvmeControllerInfo, }, rpc_submit, GrpcClientContext, GrpcResul...
use crate::{ bdev::{nexus, NvmeControllerState}, core::{BlockDeviceIoStats, CoreError, MayastorFeatures}, grpc::{ controller_grpc::{ controller_stats, list_controllers, NvmeControllerInfo, }, rpc_submit, GrpcClientContext, GrpcResul...
} impl From<resource::Usage> for rpc::ResourceUsage { fn from(usage: resource::Usage) -> Self { let rusage = usage.0; Self { soft_faults: rusage.ru_minflt, hard_faults: rusage.ru_majflt, swaps: rusage.ru_nswap, in_block_ops: rusage.ru_inblock, ...
tition) -> Self { Self { parent: p.parent, number: p.number, name: p.name, scheme: p.scheme, typeid: p.typeid, uuid: p.uuid, } }
function_block-function_prefixed
[ { "content": "pub fn rpc_submit<F, R, E>(\n\n future: F,\n\n) -> Result<Receiver<Result<R, E>>, tonic::Status>\n\nwhere\n\n E: Send + Debug + Display + 'static,\n\n F: Future<Output = Result<R, E>> + 'static,\n\n R: Send + Debug + 'static,\n\n{\n\n Mthread::get_init()\n\n .spawn_local(futu...
Rust
src/clients/fem.rs
rconan/dos-actors
356228a3fbe4430671ec1225952789d620914ec9
/*! # GMT Finite Element Model client The module implements the client interface for the [GMT FEM Rust API](https://docs.rs/gmt-fem) *The client is enabled with the `fem` feature.* # Example Simulation of the FEM and the mount controller together (requires the `fem`, `mount-ctrl` and `apache-arrow` features): ```no...
/*! # GMT Finite Element Model client The module implements the client interface for the [GMT FEM Rust API](https://docs.rs/gmt-fem) *The client is enabled with the `fem` feature.* # Example Simulation of the FEM and the mount controller together (requires the `fem`, `mount-ctrl` and `apache-arrow` features): ```no...
ew(data))) } } #[cfg(feature = "mount-ctrl")] impl<S> Get<crate::clients::mount::MountEncoders> for DiscreteModalSolver<S> where S: Solver + Default, { fn get(&self) -> Option<Vec<f64>> { let mut encoders = <DiscreteModalSolver<S> as Get<fem_io::OSSAzEncoderAngle>>::get(self)?; encoders.ext...
fem_io::*, FEM, }; let sim_sampling_frequency = 1000; let sim_duration = 4_usize; let n_step = sim_sampling_frequency * sim_duration; let state_space = { let fem = FEM::from_env()?.static_from_env()?; let n_io = (fem.n_inputs(), fem.n_outputs()); DiscreteModalSolver::<ExponentialMatrix>::from_fem(fem)...
random
[ { "content": "use std::vec::IntoIter;\n\n\n\n#[allow(dead_code)]\n\n#[derive(Debug, Default)]\n\npub struct GmtState {\n\n m1_rbm: Option<IntoIter<Vec<f64>>>,\n\n m2_rbm: Option<IntoIter<Vec<f64>>>,\n\n m1_mode: Option<IntoIter<Vec<f64>>>,\n\n}\n\n#[cfg(feature = \"apache-arrow\")]\n\nimpl From<crate::...
Rust
src/rgb.rs
JeronAldaron/pix
4b3fba180ace29611bcbf216fdc2783a638a0ad4
use crate::alpha::{ self, AChannel, Mode as _, Opaque, Premultiplied, Straight, Translucent, }; use crate::gamma::{self, Linear}; use crate::{Ch16, Ch32, Ch8, Channel, ColorModel, Pixel}; use std::marker::PhantomData; use std::ops::Mul; #[derive(Clone, Copy, Debug, Default, PartialEq)] #[repr(C)] pub struct Rgb<...
use crate::alpha::{ self, AChannel, Mode as _, Opaque, Premultiplied, Straight, Translucent, }; use crate::gamma::{self, Linear}; use crate::{Ch16, Ch32, Ch8, Channel, ColorModel, Pixel}; use std::marker::PhantomData; use std::ops::Mul; #[derive(Clone, Copy, Debug, Default, PartialEq)] #[repr(C)] pub struct Rgb<...
let b = if self.blue() > rhs.blue() { self.blue() - rhs.blue() } else { rhs.blue() - self.blue() }; let a = if self.alpha() > rhs.alpha() { self.alpha() - rhs.alpha() } else { rhs.alpha() - self.alpha() }; Rgb::with...
let g = if self.green() > rhs.green() { self.green() - rhs.green() } else { rhs.green() - self.green() };
assignment_statement
[ { "content": "type GrayAlpha<C, A> = Gray<C, A, Straight, Linear>;\n\n/// [Gray](struct.Gray.html) 8-bit [straight](alpha/struct.Straight.html) alpha\n\n/// [linear](gamma/struct.Linear.html) gamma [pixel](trait.Pixel.html) format.\n\npub type GrayAlpha8 = GrayAlpha<Ch8, Translucent<Ch8>>;\n\n/// [Gray](struct....
Rust
src/openssl/test.rs
pinkforest/future-aio
df04a4e36d3116c41da7c357b7cd996d8afb4d96
use std::io::Error as IoError; use std::net::SocketAddr; use std::time; use bytes::BufMut; use bytes::Bytes; use bytes::BytesMut; use futures_lite::future::zip; use futures_lite::stream::StreamExt; use futures_util::SinkExt; use log::debug; use tokio_util::codec::BytesCodec; use tokio_util::codec::Framed; use tokio_ut...
use std::io::Error as IoError; use std::net::SocketAddr; use std::time; use bytes::BufMut; use bytes::Bytes; use bytes::BytesMut; use futures_lite::future::zip; use futures_lite::stream::StreamExt; use futures_util::SinkExt; use log::debug; use tokio_util::codec::BytesCodec; use tokio_util::codec::Framed; use tokio_ut...
async fn run_test(acceptor: TlsAcceptor, connector: TlsConnector) -> Result<(), IoError> { let addr = "127.0.0.1:19988".parse::<SocketAddr>().expect("parse"); let server_ft = async { debug!("server: binding"); let listener = TcpListener::bind(&addr).await.expect("listener failed"); de...
certs/test-certs/client.key", )? .with_ca_from_pem_file(CA_PATH)? .build(), ) .await .expect("client cert test fail"); Ok(()) }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n}", "file_path": "async-test-derive/ui-tests/pass_async.rs", "rank": 0, "score": 110194.86860294557 }, { "content": "#[test]\n\nfn derive_ui() {\n\n let t = trybuild::TestCases::check_only();\n\n\n\n t.pass(\"ui-tests/pass_*.rs\");\n\n t.compile_fail(\"u...
Rust
grep-regex/src/strip.rs
tpai/ripgrep
09108b7fda7af6db7c1c4f0366301f9a21cc485d
use grep_matcher::LineTerminator; use regex_syntax::hir::{self, Hir, HirKind}; use error::{Error, ErrorKind}; pub fn strip_from_match( expr: Hir, line_term: LineTerminator, ) -> Result<Hir, Error> { if line_term.is_crlf() { let expr1 = strip_from_match_ascii(expr, b'\r')?; strip_from_match...
use grep_matcher::LineTerminator; use regex_syntax::hir::{self, Hir, HirKind}; use error::{Error, ErrorKind}; pub fn strip_from_match( expr: Hir, line_term: LineTerminator, ) -> Result<Hir, Error> { if line_term.is_crlf() { let expr1 = strip_from_match_ascii(expr, b'\r')?; strip_from_match...
Hir::alternation(xs) } }) } #[cfg(test)] mod tests { use regex_syntax::Parser; use error::Error; use super::{LineTerminator, strip_from_match}; fn roundtrip(pattern: &str, byte: u8) -> String { roundtrip_line_term(pattern, LineTerminator::byte(byte)).unwrap() } ...
let xs = xs.into_iter() .map(|e| strip_from_match_ascii(e, byte)) .collect::<Result<Vec<Hir>, Error>>()?;
assignment_statement
[ { "content": "/// Return a confirmed set of non-matching bytes from the given expression.\n\npub fn non_matching_bytes(expr: &Hir) -> ByteSet {\n\n let mut set = ByteSet::full();\n\n remove_matching_bytes(expr, &mut set);\n\n set\n\n}\n\n\n", "file_path": "grep-regex/src/non_matching.rs", "rank...
Rust
src/net/old/connection.rs
jrawsthorne/rust-bitcoin-node
a4e5d6c11dc47249cd37486dbdd2b2358c64b9fb
use super::Peer; use bitcoin::{ consensus::{deserialize_partial, serialize}, network::message::{NetworkMessage, RawNetworkMessage}, Network, }; use bytes::Buf; use bytes::BytesMut; use failure::format_err; use log::debug; use std::sync::Arc; use std::time::Duration; use tokio::prelude::*; use tokio::task::J...
use super::Peer; use bitcoin::{ consensus::{deserialize_partial, serialize}, network::message::{NetworkMessage, RawNetworkMessage}, Network, }; use bytes::Buf; use bytes::BytesMut; use failure::format_err; use log::debug; use std::sync::Arc; use std::time::Duration; use tokio::prelude::*; use tokio::task::J...
; if let Err(error) = writer.write_all(&bytes).await { peer.handle_error(&error.into()); break; } if let Err(error) = writer.flush().await { peer.handle_error(&error.into()); break; ...
serialize(&RawNetworkMessage { magic: network.magic(), payload: message, })
call_expression
[ { "content": "// TODO: Async stream for event_rx\n\npub fn create_connection(\n\n addr: SocketAddr,\n\n stream: TcpStream,\n\n network: Network,\n\n) -> (\n\n WriteHandle,\n\n MessageReceiver,\n\n (DisconnectSender, DisconnectReceiver),\n\n) {\n\n let (writer_tx, writer_rx) = mpsc::unbounde...
Rust
ui-rs/crates/mines_mogwai/src/routes/game_list.rs
bryanjswift/the-mines-challenge
46a6028bbdc26a287550e39cbf4e9ba9c464e28e
use crate::{api, Route}; use mogwai::prelude::*; use std::rc::Rc; pub fn game_list(dispatch: Transmitter<Route>) -> ViewBuilder<HtmlElement> { let component = GameList::new(dispatch, vec![]); Gizmo::from(component).view_builder() } struct GameList { dispatch: Transmitter<Route>, game_ids: Rc<Vec<api::...
use crate::{api, Route}; use mogwai::prelude::*; use std::rc::Rc; pub fn game_list(dispatch: Transmitter<Route>) -> ViewBuilder<HtmlElement> { let component = GameList::new(dispatch, vec![]); Gizmo::from(component).view_builder() } struct GameList { dispatch: Transmitter<Route>, game_ids: Rc<Vec<api::...
#[allow(unused_braces)] fn view( &self, tx: &Transmitter<GameListModel>, rx: &Receiver<GameListView>, ) -> ViewBuilder<HtmlElement> { let dispatch = tx.clone(); let contents = GameList::game_ul(&dispatch, self.game_ids.as_ref()); let rx_patch = rx.branch_map...
end(&GameListView { game_ids: self.game_ids.clone(), }); } GameListModel::Navigate { game_id } => { self.dispatch.send(&Route::Game { game_id: game_id.clone(), }); } } }
function_block-function_prefixed
[ { "content": "#[allow(unused_braces)]\n\npub fn home(dispatch: Transmitter<Route>) -> ViewBuilder<HtmlElement> {\n\n // Create a transmitter to send button clicks into.\n\n let tx_click = Transmitter::new();\n\n let rx_org = Receiver::new();\n\n let main_component = Gizmo::from(Main {\n\n dif...
Rust
kube-runtime/src/finalizer.rs
zhrebicek/kube-rs
b2109e2401175573b5b25bf1cbd90c5aca5dcabc
use crate::controller::ReconcilerAction; use futures::{TryFuture, TryFutureExt}; use json_patch::{AddOperation, PatchOperation, RemoveOperation, TestOperation}; use kube_client::{ api::{Patch, PatchParams}, Api, Resource, ResourceExt, }; use serde::{de::DeserializeOwned, Serialize}; use std::{error::Error as S...
use crate::controller::ReconcilerAction; use futures::{TryFuture, TryFutureExt}; use json_patch::{AddOperation, PatchOperation, RemoveOperation, TestOperation}; use kube_client::{ api::{Patch, PatchParams}, Api, Resource, ResourceExt, }; use serde::{de::DeserializeOwned, Serialize}; use std::{error::Error as S...
t)?, &PatchParams::default(), &Patch::Json(patch), ) .await .map_err(Error::AddFinalizer)?; Ok(ReconcilerAction { requeue_after: None }) } FinalizerState { finalizer_index: None, is_delet...
h: "/metadata/finalizers".to_string(), value: vec![finalizer_name].into(), }), ] } else { vec![PatchOperation::Add(AddOperation { path: "/metadata/finalizers/-".to_string(), value: finalizer_n...
random
[ { "content": "/// Watch a single named object for updates\n\n///\n\n/// Emits `None` if the object is deleted (or not found), and `Some` if an object is updated (or created/found).\n\n///\n\n/// Compared to [`watcher`], `watch_object` does not return return [`Event`], since there is no need for an atomic\n\n///...
Rust
actors/market/src/balance_table.rs
rllola/builtin-actors
5185c8e598cd0d8f41f30d2dfcde792e109fb8f2
use cid::Cid; use fvm_ipld_hamt::Error as HamtError; use fvm_shared::address::Address; use fvm_shared::bigint::bigint_ser::BigIntDe; use fvm_shared::blockstore::Blockstore; use fvm_shared::econ::TokenAmount; use num_traits::{Signed, Zero}; use fil_actors_runtime::{make_empty_map, make_map_with_root_and_bitwidth, Map...
use cid::Cid; use fvm_ipld_hamt::Error as HamtError; use fvm_shared::address::Address; use fvm_shared::bigint::bigint_ser::BigIntDe; use fvm_shared::blockstore::Blockstore; use fvm_shared::econ::TokenAmount; use num_traits::{Signed, Zero}; use fil_actors_runtime::{make_empty_map, make_map_with_root_and_bitwidth, Map...
pub fn subtract_with_minimum( &mut self, key: &Address, req: &TokenAmount, floor: &TokenAmount, ) -> Result<TokenAmount, HamtError> { let prev = self.get(key)?; let available = std::cmp::max(TokenAmount::zero(), prev - floor); let sub: Tok...
pub fn add(&mut self, key: &Address, value: &TokenAmount) -> Result<(), HamtError> { let prev = self.get(key)?; let sum = &prev + value; if sum.is_negative() { Err(format!("New balance in table cannot be negative: {}", sum).into()) } else if sum.is_zero() && !prev.is_zero() {...
function_block-full_function
[ { "content": "#[inline]\n\npub fn make_empty_map<BS, V>(store: &'_ BS, bitwidth: u32) -> Map<'_, BS, V>\n\nwhere\n\n BS: Blockstore,\n\n V: DeserializeOwned + Serialize,\n\n{\n\n Map::<_, V>::new_with_bit_width(store, bitwidth)\n\n}\n\n\n\n/// Create a map with a root cid.\n", "file_path": "actors/...
Rust
src/display.rs
cgm616/punda
62f3550006a1b4771105bd7213689bef0a07620d
use cortex_m::interrupt::Mutex; use hal::gpio::gpio::{ PIN, PIN10, PIN11, PIN12, PIN13, PIN14, PIN15, PIN4, PIN5, PIN6, PIN7, PIN8, PIN9, }; use hal::gpio::{Output, PushPull}; use hal::prelude::*; use alloc::boxed::Box; use core::cell::RefCell; use core::ops::{Deref, DerefMut}; use core::sync::atomic::AtomicBool;...
use cortex_m::interrupt::Mutex; use hal::gpio::gpio::{ PIN, PIN10, PIN11, PIN12, PIN13, PIN14, PIN15, PIN4, PIN5, PIN6, PIN7, PIN8, PIN9, }; use hal::gpio::{Output, PushPull}; use hal::prelude::*; use alloc::boxed::Box; use core::cell::RefCell; use core::ops::{Deref, DerefMut}; use core::sync::atomic::AtomicBool;...
pub fn run_animation(mut animator: impl animation::Animate + 'static, block: bool) { if let Some(frame) = animator.next_screen() { cortex_m::interrupt::free(|cs| { if let (Some(ref mut display), Some(ref mut scheduler)) = ( DISPLAY.borrow(cs).borrow_mut().deref_mut(), ...
o().into()); scheduler.unset_interrupt(RTCInterrupt::Tick); scheduler .set_agnostic_interrupt(RTCInterrupt::Tick, refresh_display) .unwrap(); } }); }
function_block-function_prefixed
[ { "content": "/// The `measure_temp_rational` function takes a `TEMP` peripheral and returns\n\n/// an integer temperature measured in quarters of a degree Celsius.\n\n///\n\n/// For example, if this function returns `88`, the temperature recorded is\n\n/// actually 88 divided by four; that is, 22 degrees Celsi...
Rust
libdougvm/src/lib.rs
dougabugg/doug-script
e450a06be9a01153ab823c83c223d92ae7b75c8d
use std::mem::swap; pub mod bytecode; pub mod datamodel; use crate::bytecode::{OpAction, OpError, Operation}; use crate::datamodel::{Function, Value}; pub struct CallFrame { pub parent: Option<Box<CallFrame>>, pub function: Function, pub cursor: usize, pub stack: CallStack, } impl CallFrame { pu...
use std::mem::swap; pub mod bytecode; pub mod datamodel; use crate::bytecode::{OpAction, OpError, Operation}; use crate::datamodel::{Function, Value}; pub struct Ca
rent { Some(mut parent) => { parent.push(val); self.frame = Some(parent); } None => { self.frame = None; return Ok(VmState::Exited(val)); } ...
llFrame { pub parent: Option<Box<CallFrame>>, pub function: Function, pub cursor: usize, pub stack: CallStack, } impl CallFrame { pub fn new(function: Function) -> CallFrame { let mut stack = CallStack::new(); stack.store(0, function.module.clone().into()); CallFrame { ...
random
[]
Rust
src/bridge.rs
shisoft/HomeBridge
6f0c7c79501b9919a3dbc401d0e03a24fc9f5c68
use bytes::{Buf, BufMut, Bytes, BytesMut}; use core::sync::atomic::Ordering::AcqRel; use futures::{SinkExt, StreamExt}; use lightning::map::{Map, ObjectMap, WordMap}; use log::*; use std::error::Error; use std::io; use std::net::SocketAddr; use std::sync::{atomic::AtomicU64, Arc}; use tokio::net::{TcpListener, TcpStrea...
use bytes::{Buf, BufMut, Bytes, BytesMut}; use core::sync::atomic::Ordering::AcqRel; use futures::{SinkExt, StreamExt}; use lightning::map::{Map, ObjectMap, WordMap}; use log::*; use std::error::Error; use std::io; use std::net::SocketAddr; use std::sync::{atomic::AtomicU64, Arc}; use tokio::net::{TcpListener, TcpStrea...
} fn remove(&self, serv_id: u64) { if let Some(_) = self.conns.remove(&(serv_id as usize)) { debug!("Removed server with id {}", serv_id) } } } impl ServerConnection { async fn new( id: u64, bridge: &Arc<Bridge>, stream: TcpStream, addr: Soc...
if let Some(server_conn) = ServerConnection::new(serv_id, bridge, stream, addr).await { info!("New server connection {:?}, id {}", addr, serv_id); self.conns .insert(&(serv_id as usize), Arc::new(server_conn)); } else { error!("Cannot establish server connecti...
if_condition
[ { "content": "pub fn unix_timestamp() -> u64 {\n\n let start = SystemTime::now();\n\n let since_the_epoch = start\n\n .duration_since(UNIX_EPOCH)\n\n .expect(\"Time went backwards\");\n\n since_the_epoch.as_secs() * 1000 + since_the_epoch.subsec_nanos() as u64 / 1_000_000\n\n}\n", "fi...
Rust
crates/phactory/src/contracts/balances.rs
ndkazu/guessNumber-vs-Bot
6e756977ce849137c62edb0716df6926583da9b2
use std::collections::BTreeMap; use std::string::ToString; use anyhow::Result; use core::fmt; use log::info; use parity_scale_codec::{Decode, Encode}; use phala_mq::MessageOrigin; use super::{TransactionError, TransactionResult}; use crate::contracts; use crate::contracts::{AccountId, NativeContext}; extern crate run...
use std::collections::BTreeMap; use std::string::ToString; use anyhow::Result; use core::fmt; use log::info; use parity_scale_codec::{Decode, Encode}; use phala_mq::MessageOrigin; use super::{TransactionError, TransactionResult}; use crate::contracts; use crate::contracts::{AccountId, NativeContext}; extern crate run...
: Option<&chain::AccountId>, req: Request) -> Response { let inner = || -> Result<Response> { match req { Request::FreeBalance { account } => { if origin == None || origin.unwrap() != &account { return Err(anyhow::Error::msg(Error::NotAutho...
elf, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::NotAuthorized => write!(f, "not authorized"), Error::Other(e) => write!(f, "{}", e), } } } #[derive(Encode, Decode, Debug, Clone)] pub enum Request { FreeBalance { account: AccountId }, TotalIssuan...
random
[ { "content": "type Command = AssetCommand<chain::AccountId, chain::Balance>;\n\n\n\nextern crate runtime as chain;\n\n\n\n#[derive(Encode, Decode, Debug, Clone)]\n\npub struct AssetMetadata {\n\n owner: AccountId,\n\n total_supply: u128,\n\n symbol: String,\n\n id: u32,\n\n}\n\n\n\n#[derive(Encode, ...
Rust
tests/test_cargo_rustdoc.rs
akiss77/cargo
1af03beaffe9be40ae81ca39431c1f1651ef6b02
use std::path::MAIN_SEPARATOR as SEP; use support::{execs, project}; use support::{COMPILING, RUNNING, DOCUMENTING}; use hamcrest::{assert_that}; fn setup() { } test!(rustdoc_simple { let p = project("foo") .file("Cargo.toml", r#" [package] name = "foo" version = "0.0.1...
use std::path::MAIN_SEPARATOR as SEP; use support::{execs, project}; use support::{COMPILING, RUNNING, DOCUMENTING}; use hamcrest::{assert_that}; fn setup() { } test!(rustdoc_simple { let p = project("foo") .file("Cargo.toml", r#" [package] name = "foo" version = "0.0.1...
at(p.cargo_process("rustdoc").arg("-v").arg("--").arg("--no-defaults"), execs() .with_status(0) .with_stdout(format!("\ {documenting} foo v0.0.1 ({url}) {running} `rustdoc src{sep}lib.rs --crate-name foo \ -o {dir}{sep}target{sep}doc \ --no-defaults \ ...
()))); }); test!(rustdoc_args { let p = project("foo") .file("Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] "#) .file("src/lib.rs", r#" "#); assert_th
random
[ { "content": "fn names<P: ToPkgId>(names: &[P]) -> Vec<PackageId> {\n\n names.iter().map(|name| name.to_pkgid()).collect()\n\n}\n\n\n", "file_path": "tests/resolve.rs", "rank": 0, "score": 245464.54754854098 }, { "content": "/// Add an empty file with executable flags (and platform-depend...
Rust
src/usb0_ch0/hcintmsk.rs
austinglaser/xmc4700
12e1d2b638af5ff0e7088605a4299590a2cd60eb
#[doc = "Reader of register HCINTMSK"] pub type R = crate::R<u32, super::HCINTMSK>; #[doc = "Writer for register HCINTMSK"] pub type W = crate::W<u32, super::HCINTMSK>; #[doc = "Register HCINTMSK `reset()`'s with value 0"] impl crate::ResetValue for super::HCINTMSK { type Type = u32; #[inline(always)] fn re...
#[doc = "Reader of register HCINTMSK"] pub type R = crate::R<u32, super::HCINTMSK>; #[doc = "Writer for register HCINTMSK"] pub type W = crate::W<u32, super::HCINTMSK>; #[doc = "Register HCINTMSK `reset()`'s with value 0"] impl crate::ResetValue for super::HCINTMSK { type Type = u32; #[inline(always)] fn re...
W { FRMOVRUNMSK_W { w: self } } #[doc = "Bit 10 - Data Toggle Error Mask"] #[inline(always)] pub fn data_tgl_err_msk(&mut self) -> DATATGLERRMSK_W { DATATGLERRMSK_W { w: self } } #[doc = "Bit 11 - BNA (Buffer Not Available) Interrupt mask register"] #[inline(always)] pub ...
LMSK_R { STALLMSK_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - NAK Response Received Interrupt Mask"] #[inline(always)] pub fn nak_msk(&self) -> NAKMSK_R { NAKMSK_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - ACK Response Received/Transmitted Interrupt Ma...
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/alert.rs
chandero/patternfly-yew
7b0377936b79af5d2b8d942c76c43ad6470fe562
use crate::{Action, Button, Icon, Variant}; use yew::prelude::*; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Type { Default, Info, Success, Warning, Danger, } impl Default for Type { fn default() -> Self { Self::Default } } impl Type { pub fn as_classes(&self) -> Ve...
use crate::{Action, Button, Icon, Variant}; use yew::prelude::*; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Type { Default, Info, Success, Warning, Danger, } impl Default for Type { fn default() -> Self { Self::Default } } impl Type { pub fn as_classes(&self) -> Ve...
} #[derive(Clone, PartialEq, Properties)] pub struct GroupProps { #[prop_or_default] pub children: ChildrenWithProps<Alert>, #[prop_or_default] pub toast: bool, } pub struct AlertGroup { props: GroupProps, } impl Component for AlertGroup { type Message = (); type Properties = GroupProps;...
if self.props.inline { classes.push("pf-m-inline"); } if self.props.truncate { classes.push("pf-m-truncate"); } let t = self.props.r#type; let actions = if self.props.actions.is_empty() { html! {} } else { html! { ...
function_block-function_prefix_line
[ { "content": "pub fn random_id() -> String {\n\n uuid::Uuid::new_v4().to_string()\n\n}\n", "file_path": "src/utils/mod.rs", "rank": 0, "score": 160440.77609408207 }, { "content": "fn far(name: &str) -> Classes {\n\n let mut classes = Classes::new();\n\n classes.push(\"far\");\n\n ...
Rust
backend/src/iso/reader.rs
zsrtp/romhack-compiler
5eac224fb4824a009c4ed7d669fbb347e6738578
use super::virtual_file_system::{Directory, File, Node}; use super::{consts::*, FstEntry, FstNodeType}; use byteorder::{ByteOrder, BE}; use failure::{Error, ResultExt}; use std::fs; use std::io::{Read, Result as IOResult}; use std::path::Path; use std::str; use wii_crypto::wii_disc::{Partition, Partitions}; pub fn loa...
use super::virtual_file_system::{Directory, File, Node}; use super::{consts::*, FstEntry, FstNodeType}; use byteorder::{ByteOrder, BE}; use failure::{Error, ResultExt}; use std::fs; use std::io::{Read, Result as IOResult}; use std::path::Path; use std::str; use wii_crypto::wii_disc::{Partition, Partitions}; pub fn loa...
sys_data .children .push(Node::File(File::new("iso.hdr", &buf[partition_offset..partition_offset + HEADER_LENGTH]))); let dol_offset = (BE::read_u32(&buf[partition_offset + OFFSET_DOL_OFFSET..]) as usize) << (if is_wii {2} else {0}); sys_data.children.push(Node::File(File::new( "...
if let Some(parts) = parts_opt { sys_data.children.push(Node::File(File::new("w_iso.hdr", &buf[..0x50000]))); for (i, part) in parts.partitions.iter().enumerate() { sys_data.children.push(Node::File(File::new(format!("w_part{}.prt", i).as_str(), &buf[part.part_offset ..][.. part.header.data_...
if_condition
[ { "content": "pub fn parse_disc(buf: &mut [u8]) -> Result<Option<Partitions>, WiiCryptoError> {\n\n let header = disc_get_header(buf);\n\n if header.wii_magic != 0x5D1C9EA3 {\n\n return Err(WiiCryptoError::NotWiiDisc{magic: header.wii_magic})\n\n }\n\n // if header.disable_disc_encrypt == 1 |...
Rust
BigInt.rs
MPTGits/RustPlayground
86bc51052cc11cc328d07fc20777c4b3be45285f
use std::str::FromStr; use std::cmp::Ordering; fn bigint(s: &str) -> Bigint { Bigint::from_str(s).unwrap() } #[test] fn test_basic() { assert_eq!(Bigint::new(), bigint("0")); assert!(Bigint::from_str("foobar").is_err()); assert!(bigint("1").is_positive()); assert!(bigint("-1").is_negative()); ...
use std::str::FromStr; use std::cmp::Ordering; fn bigint(s: &str) -> Bigint { Bigint::from_str(s).unwrap() } #[test] fn test_basic() { assert_eq!(Bigint::new(), bigint("0")); assert!(Bigint::from_str("foobar").is_err()); assert!(bigint("1").is_positive()); assert!(bigint("-1").is_negative()); ...
let digits = &s[starting_index..s.chars().count()]; if digits.chars().all(char::is_numeric){ return Ok(Bigint::from_components(Bigint::convert_str_to_vec(digits), sign)); } Err(ParseError) } } impl PartialOrd for Bigint { fn partial_cmp(&self, other: ...
if s.as_bytes()[0] as char == '+' || s.as_bytes()[0] as char == '-'{ sign = if s.as_bytes()[0] as char == '+' {1} else {-1}; starting_index = 1; }
if_condition
[ { "content": "/// Търси следващото срещане на символа `target` в низа `input`. Връща низа до този символ и низа\n\n/// от този символ нататък, в двойка.\n\n///\n\n/// Ако не намери `target`, връща оригиналния низ и празен низ като втори елемент в двойката.\n\n///\n\n/// take_until(\" foo/bar \", '/') //=> (\" f...
Rust
src/wave.rs
alexcarol/synthrs
1e5573c3e8b608b1cccf9cf80e7ecc072ad3fd98
use std::collections::VecDeque; use std::f64::consts::PI; use crate::filter::envelope; pub fn sine_wave(frequency: f64) -> impl Fn(f64) -> f64 { move |t| (t * frequency * 2.0 * PI).sin() } pub fn square_wave(frequency: f64) -> impl Fn(f64) -> f64 { move |t| { let sin_wave = sine_wave(frequency); ...
use std::collections::VecDeque; use std::f64::consts::PI; use crate::filter::envelope; pub fn sine_wave(frequency: f64) -> impl Fn(f64) -> f64 { move |t| (t * frequency * 2.0 * PI).sin() } pub fn square_wave(frequency: f64) -> impl Fn(f64) -> f64 { move |t| { let sin_wave = sine_wave(frequency); ...
t).abs() - 0.25) * 4.0 } } pub fn tangent_wave(frequency: f64) -> impl Fn(f64) -> f64 { move |t| { (((t * frequency * PI) - 0.5).tan() / 4.0) .max(-1.0) .min(1.0) } } pub fn bell(frequency: f64, attack: f64, decay: f64) -> impl Fn(f64) -> f64 { move |t| { ...
frequency: f64) -> impl Fn(f64) -> f64 { move |t| { let sawtooth_wave = sawtooth_wave(frequency); (sawtooth_wave(
function_block-random_span
[ { "content": "/// Returns the cutoff fraction for a given cutoff frequency at a sample rate, which can be\n\n/// used for filter creation.\n\npub fn cutoff_from_frequency(frequency: f64, sample_rate: usize) -> f64 {\n\n frequency / sample_rate as f64\n\n}\n\n\n", "file_path": "src/filter.rs", "rank":...
Rust
examples/blockchain/chain/mod.rs
hangsiahong/BanklessBFT
00d2c970cd4bb473219e59fc8ece799a4930f1d1
use crate::network::NetworkData; use bankless_bft::NodeIndex; use codec::{Decode, Encode}; use futures::{ channel::{ mpsc::{UnboundedReceiver, UnboundedSender}, oneshot, }, FutureExt, StreamExt, }; use futures_timer::Delay; use log::{debug, info}; use parking_lot::Mutex; use std::{ sync:...
use crate::network::NetworkData; use bankless_bft::NodeIndex; use codec::{Decode, Encode}; use futures::{ channel::{ mpsc::{UnboundedReceiver, UnboundedSender}, oneshot, }, FutureExt, StreamExt, }; use futures_timer::Delay; use log::{debug, info}; use parking_lot::Mutex; use std::{ sync:...
, pub(crate) blocktime_ms: u64, pub(crate) init_delay_ms: u64, pub(crate) authorship_plan: BlockPlan, } pub(crate) fn gen_chain_config( node_ix: NodeIndex, n_members: usize, data_size: usize, blocktime_ms: u64, init_delay_ms: u64, ) -> ChainConfig { let authorshi...
(0..size) .map(|i| ((i + i / 999 + (i >> 12)) % 8) as u8) .collect(); debug!(target: "Blockchain-chain", "Finished creating block {:?}", num); Block { num, data } } } pub(crate) type BlockPlan = Arc<dyn Fn(BlockNum) -> NodeIndex + Sync + Send + 'static>; pub(crate) struct ...
random
[ { "content": "type Data = u64;\n", "file_path": "examples/dummy_honest.rs", "rank": 1, "score": 172946.56115171837 }, { "content": "pub fn complete_oneshot<T: std::fmt::Debug>(t: T) -> oneshot::Receiver<T> {\n\n let (tx, rx) = oneshot::channel();\n\n tx.send(t).unwrap();\n\n rx\n\n}...
Rust
src/testserver.rs
nico-abram/ureq
b246f0a9d2e6150b29b5504924edc090d2bf9168
use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; use std::time::Duration; use std::{ io::{self, BufRead, BufReader, Write}, net::ToSocketAddrs, }; use crate::{Agent, AgentBuilder}; pub(crate) fn test_agent() -> Agent { ...
use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; use std::time::Duration; use std::{ io::{self, BufRead, BufReader, Write}, net::ToSocketAddrs, }; use crate::{Agent, AgentBuilder}; pub(crate) fn test_agent() -> Agent { ...
pub struct TestServer { pub port: u16, pub done: Arc<AtomicBool>, } pub struct TestHeaders(Vec<String>); #[allow(dead_code)] impl TestHeaders { pub fn path(&self) -> &str { if self.0.is_empty() { "" } else { &self.0[0].split(' ').nth(1).unwrap() } ...
n")?; stream.write_all(b"\r\n")?; stream.write_all(b"7\r\n")?; stream.write_all(b"success\r\n")?; stream.write_all(b"0\r\n")?; stream.write_all(b"\r\n")?; } Ok(()) }); AgentBuilder::new() .resolver(move |h: &str| ...
function_block-function_prefixed
[ { "content": "#[cfg(feature = \"cookies\")]\n\nfn extract_cookies(agent: &Agent, url: &Url) -> Option<Header> {\n\n let header_value = agent\n\n .state\n\n .cookie_tin\n\n .get_request_cookies(url)\n\n .iter()\n\n .map(|c| c.encoded().to_string())\n\n .collect::<Vec<...
Rust
src/bin/fasten_trim.rs
lskatz/ROSS.rs
6dfc202ac7e2b94769657f53c450954daa7ce267
extern crate fasten; extern crate statistical; extern crate getopts; extern crate threadpool; use std::fs::File; use std::io::BufReader; use std::cmp::min; use threadpool::ThreadPool; use std::sync::mpsc::channel; use fasten::fasten_base_options; use fasten::fasten_base_options_matches; use fasten::logmsg; use fas...
extern crate fasten; extern crate statistical; extern crate getopts; extern crate threadpool; use std::fs::File; use std::io::BufReader; use std::cmp::min; use threadpool::ThreadPool; use std::sync::mpsc::channel; use fasten::fasten_base_options; use fasten::fasten_base_options_matches; use fasten::logmsg; use fas...
fn trim_worker(seqs:Vec<Seq>, first_base:usize, last_base:usize, tx:std::sync::mpsc::Sender<String> ){ let blank_seq = Seq::blank(); for seq in seqs{ if seq.id == blank_seq.id && seq.seq == blank_seq.seq && seq.qual == blank_seq.qual { continue; } let last_base_tmp = match last_base ...
fn main(){ let mut opts = fasten_base_options(); opts.optopt("f","first-base","The first base to keep (default: 0)","INT"); opts.optopt("l","last-base","The last base to keep. If negative, counts from the right. (default: 0)","INT"); let matches = fasten_base_options_matches("Blunt-end trims usin...
function_block-full_function
[ { "content": "/// a function that reads an options object and adds fasten default options.\n\npub fn fasten_base_options() -> Options{\n\n let mut opts = Options::new();\n\n opts.optflag(\"h\", \"help\", \"Print this help menu.\");\n\n opts.optopt(\"n\",\"numcpus\",\"Number of CPUs (default: 1)\",\"INT...
Rust
zenoh_flow_simulator/src/lib.rs
autocore-ai/zenoh_flow_autoware
8b5320fe95cfeb3d0573d7f520a6bab925ff6208
mod ffi; use autoware_auto::msgs::ffi::{ AutowareAutoMsgsVehicleControlCommand, AutowareAutoMsgsVehicleStateCommand, GeometryMsgsPoseWithCovarianceStamped, }; use derive::{zf_default_node, DefaultSendAndSync}; use ffi::ffi::{ get_kinematic_state, get_state_report, init_simulator, is_initialized, set_cont...
mod ffi; use autoware_auto::msgs::ffi::{ AutowareAutoMsgsVehicleControlCommand, AutowareAutoMsgsVehicleStateCommand, GeometryMsgsPoseWithCovarianceStamped, }; use derive::{zf_default_node, DefaultSendAndSync}; use ffi::ffi::{ get_kinematic_state, get_state_report, init_simulator, is_initialized, set_cont...
.try_get::<AutowareAutoMsgsVehicleControlCommand>()?; set_control_cmd(node, msg); } STATE_CMD_MODE => { let mut data_msgs = inputs .remove(IN_STATE_CMD) .ok_or_else(|| ZFError::InvalidData("No data".to_string())...
{ Some(v) => v, None => NativeConfig::default().steer_lim, }; let steer_rate_lim = match config["steer_rate_lim"].as_f64() { Some(v) => v, None => NativeConfig::default().steer_rate_lim, }; let acc_time_delay...
random
[ { "content": "#[proc_macro_attribute]\n\npub fn zf_default_node(attr: TokenStream, item: TokenStream) -> TokenStream {\n\n if attr.clone().into_iter().next().is_none() {\n\n panic!(\"#[zf_default_node(..)] init fn missing\");\n\n }\n\n let in_args = parse_macro_input!(attr as AttributeArgs);\n\n...
Rust
src/mutex.rs
faern/parking_lot
bbbb57633f74ae27fc23cf4b6aee24e9d3449a10
use crate::raw_mutex::RawMutex; use lock_api; pub type Mutex<T> = lock_api::Mutex<RawMutex, T>; pub type MutexGuard<'a, T> = lock_api::MutexGuard<'a, RawMutex, T>; pub type MappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawMutex, T>; #[cfg(test)] mod tests { use crate::{Condvar, Mutex}; use std:...
use crate::raw_mutex::RawMutex; use lock_api; pub type Mutex<T> = lock_api::Mutex<RawMutex, T>; pub type MutexGuard<'a, T> = lock_api::MutexGuard<'a, RawMutex, T>; pub type MappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawMutex, T>; #[cfg(test)] mod tests { use crate::{Condvar, Mutex}; use std:...
#[test] fn test_mutex_unsized() { let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); { let b = &mut *mutex.lock(); b[0] = 4; b[2] = 5; } let comp: &[i32] = &[4, 2, 5]; assert_eq!(&*mutex.lock(), comp); } #[test] fn test_m...
let _u = Unwinder { i: arc2 }; panic!(); }) .join(); let lock = arc.lock(); assert_eq!(*lock, 2); }
function_block-function_prefix_line
[ { "content": "fn run_benchmark<M: Mutex<f64> + Send + Sync + 'static>(\n\n num_threads: usize,\n\n work_per_critical_section: usize,\n\n work_between_critical_sections: usize,\n\n seconds_per_test: usize,\n\n) -> Vec<usize> {\n\n let lock = Arc::new(([0u8; 300], M::new(0.0), [0u8; 300]));\n\n ...
Rust
ruma-client-api/src/r0/session/login.rs
zecakeh/ruma
3ce549e3ee38015d2d4110408ca53a5fb5f2c324
use ruma_api::ruma_api; use ruma_common::thirdparty::Medium; use ruma_identifiers::{DeviceId, DeviceIdBox, ServerNameBox, UserId}; use ruma_serde::Outgoing; use serde::{Deserialize, Serialize}; ruma_api! { metadata: { description: "Login to the homeserver.", method: POST, name: "login", ...
use ruma_api::ruma_api; use ruma_common::thirdparty::Medium; use ruma_identifiers::{DeviceId, DeviceIdBox, ServerNameBox, UserId}; use ruma_serde::Outgoing; use serde::{Deserialize, Serialize}; ruma_api! { metadata: { description: "Login to the homeserver.", method: POST, name: "login", ...
}
fn serialize_login_request_body() { let req: http::Request<Vec<u8>> = Request { login_info: LoginInfo::Token { token: "0xdeadbeef" }, device_id: None, initial_device_display_name: Some("test"), } .try_into_http_request("https://homeserver.tld", None) ....
function_block-full_function
[]
Rust
moment/src/period.rs
ZhuanzhiAI/rustling-ontology
88327cd97cbcb81a3c4b99aae688a1862abfe1a0
use std::ops; use vec_map::VecMap; enum_from_primitive! { #[derive(Debug,PartialEq,Copy,Clone,Eq,Ord,PartialOrd, Hash)] pub enum Grain { Year = 0, Quarter = 1, Month = 2, Week = 3, Day = 4, Hour = 5, Minute = 6, Second = 7, } } impl Grain { ...
use std::ops; use vec_map::VecMap; enum_from_primitive! { #[derive(Debug,PartialEq,Copy,Clone,Eq,Ord,PartialOrd, Hash)] pub enum Grain { Year = 0, Quarter = 1, Month = 2, Week = 3, Day = 4, Hour = 5, Minute = 6, Second = 7, } } impl Grain { ...
pub fn half_period(&self) -> Option<PeriodComp> { match self { &Grain::Year => Some(PeriodComp::months(6)), &Grain::Quarter => Some(PeriodComp::days(45)), &Grain::Month => Some(PeriodComp::days(15)), &Grain::Week => Some(PeriodComp::days(4)), &Gr...
Grain::Hour => Grain::Minute, &Grain::Minute => Grain::Second, &Grain::Second => Grain::Second, } }
function_block-function_prefix_line
[ { "content": "pub fn hour_minute_second(h: u32,\n\n m: u32,\n\n s: u32,\n\n is_12_clock: bool)\n\n -> RuleResult<TimeValue> {\n\n Ok(hour_minute(h, m, is_12_clock)?\n\n ...
Rust
src/game/object/level/pattern.rs
Luminarys/Nishikaku
68a80cb363aab0aa0be38be2c9be21bd7917c972
use nalgebra::{angle_between, Vector2}; use game::object::enemy::PosFetcher; use game::object::level::path::RotationDirection; use engine::util::ToCartesian; #[derive(Clone, Debug)] pub struct Pattern { pub time_int: f32, pos_fetcher: Option<PosFetcher>, repeat: usize, repeat_delay: f32, amount: us...
use nalgebra::{angle_between, Vector2}; use game::object::enemy::PosFetcher; use game::object::level::path::RotationDirection; use engine::util::ToCartesian; #[derive(Clone, Debug)] pub struct Pattern { pub time_int: f32, pos_fetcher: Option<PosFetcher>, repeat: usize, repeat_delay: f32, amount: us...
}
ay, active_patterns: vec![PatternState { amount_left: self.amount, cur_angle: sa, int_time: 0.0, wobble_angle: 0.0 }], rep_time: 0.0, pos_fetcher: None, cur_wobble_time: 0.0, wobble_angle: self.wobble_angle, wobble_time: self.wobble_time, ...
function_block-function_prefixed
[ { "content": "pub fn load_assets(engine: &mut Engine<Object>) {\n\n println!(\"Loading assets!\");\n\n load_char(engine);\n\n load_bullet(engine);\n\n load_sound(engine);\n\n load_fonts(engine);\n\n}\n\n\n", "file_path": "src/game/asset/mod.rs", "rank": 0, "score": 132304.7550187313 ...
Rust
liblumen_alloc/src/erts/exception/runtime.rs
mlwilkerson/lumen
048df6c0840c11496e2d15aa9af2e4a8d07a6e0f
use std::convert::TryFrom; use std::sync::Arc; use thiserror::Error; use crate::erts::process::alloc::TermAlloc; use crate::erts::process::trace::Trace; use crate::erts::term::prelude::*; use super::{ArcError, ErlangException, Exception, SystemException, UnexpectedExceptionError}; #[derive(Error, Debug, Clone)] pub...
use std::convert::TryFrom; use std::sync::Arc; use thiserror::Error; use crate::erts::process::alloc::TermAlloc; use crate::erts::process::trace::Trace; use crate::erts::term::prelude::*; use super::{ArcError, ErlangException, Exception, SystemException, UnexpectedExceptionError}; #[derive(Error, Debug, Clone)] pub...
#[test] fn with_arguments_stores_some() { let reason = atom!("badarg"); let arguments = Term::NIL; let error = error!(reason, arguments, Trace::capture()); assert_eq!(error.reason(), reason); assert_eq!( error.class(), ...
fn without_arguments_stores_none() { let reason = atom!("badarg"); let error = error!(reason, Trace::capture()); assert_eq!(error.reason(), reason); assert_eq!(error.class(), Class::Error { arguments: None }); }
function_block-full_function
[ { "content": "pub fn has_heap_message(process: &Process, data: Term) -> bool {\n\n process\n\n .mailbox\n\n .lock()\n\n .borrow()\n\n .iter()\n\n .any(|message| match message {\n\n Message::HeapFragment(message::HeapFragment {\n\n data: message_dat...
Rust
src/cli_helpers.rs
nadesai/tin-summer
9962ef73137d77e8d127765f3c388af149f8ed17
use clap::Values; use colored::*; use error::*; use nom::IResult; use regex::Regex; use std::path::PathBuf; use std::process::exit; use utils::get_processors; pub fn get_excludes(cli_excludes: Option<&str>) -> Regex { match cli_excludes { Some(s) => { let mut x = "(".to_string(); x....
use clap::Values; use colored::*; use error::*; use nom::IResult; use regex::Regex; use std::path::PathBuf; use std::process::exit; use utils::get_processors; pub fn get_excludes(cli_excludes: Option<&str>) -> Regex { match cli_excludes { Some(s) => { let mut x = "(".to_string(); x....
fn to_u64(nums: Vec<char>, size_tag: &[u8]) -> u64 { let pre: String = nums.into_iter().collect(); let n = if let Ok(n) = pre.parse::<u64>() { n } else { eprintln!("{}", Internal::ParseNum); exit(0x0f01); }; match size_tag { b"G" | b"g" => n * 1073741824, b...
fn pre_threshold(t_from_cli: &str) -> u64 { match get_threshold(t_from_cli.as_bytes()) { IResult::Done(_, n) => n, _ => { eprintln!( "{}: failed to parse threshold. defaulting to 1M", "Warning".yellow() ); 1048576 } } }
function_block-full_function
[ { "content": "/// Check that the user-supplied regex is valid. If not, fail gracefully.\n\npub fn check_regex(re: &str) -> Regex {\n\n if let Ok(r) = Regex::new(re) {\n\n r\n\n } else if let Err(x) = Regex::new(re) {\n\n eprintln!(\"{}: Invalid regex:\\n {}\", \"Error\".red(), x);\n\n ...
Rust
src/transport/sendmail/mod.rs
xtuc/lettre
e1d3778329b5280d2c281241e29b0cdc5dea4f8d
pub use self::error::Error; #[cfg(feature = "async-std1")] use crate::AsyncStd1Executor; #[cfg(feature = "tokio1")] use crate::Tokio1Executor; use crate::{address::Envelope, Transport}; #[cfg(any(feature = "async-std1", feature = "tokio1"))] use crate::{AsyncTransport, Executor}; #[cfg(any(feature = "async-std1", fea...
pub use self::error::Error; #[cfg(feature = "async-std1")] use crate::AsyncStd1Executor; #[cfg(feature = "tokio1")] use crate::Tokio1Executor; use crate::{address::Envelope, Transport}; #[cfg(any(feature = "async-std1", feature = "tokio1"))] use crate::{AsyncTransport, Executor}; #[cfg(any(feature = "async-std1", fea...
}
t .map_err(error::client)?; let output = process.wait_with_output().await.map_err(error::client)?; if output.status.success() { Ok(()) } else { let stderr = String::from_utf8(output.stderr).map_err(error::response)?; Err(error::client(stderr)) ...
function_block-function_prefixed
[ { "content": "struct Inner {\n\n kind: Kind,\n\n source: Option<BoxError>,\n\n}\n\n\n\nimpl Error {\n\n pub(crate) fn new<E>(kind: Kind, source: Option<E>) -> Error\n\n where\n\n E: Into<BoxError>,\n\n {\n\n Error {\n\n inner: Box::new(Inner {\n\n kind,\n\n...
Rust
src/models/r4/Reference.rs
itsbalamurali/rust-fhir
be43a387214586b6d8c5c5bf1d1f082a15c362b0
#![allow(unused_imports, non_camel_case_types)] use crate::models::r4::Element::Element; use crate::models::r4::Extension::Extension; use crate::models::r4::Identifier::Identifier; use serde_json::json; use serde_json::value::Value; use std::borrow::Cow; #[derive(Debug)] pub struct Reference<'a> { pub(crate) valu...
#![allow(unused_imports, non_camel_case_types)] use crate::models::r4::Element::Element; use crate::models::r4::Extension::Extension; use crate::models::r4::Identifier::Identifier; use serde_json::json; use serde_json::value::Value; use std::borrow::Cow; #[derive(Debug)] pub struct Reference<'a> { pub(crate) valu...
pub fn fhir_type(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("type") { return Some(string); } return None; } pub fn validate(&self) -> bool { if let Some(_val) = self._display() { ...
e(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("reference") { return Some(string); } return None; }
function_block-function_prefixed
[ { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct ClassReference {\n\n #[serde(rename = \"$ref\")]\n\n fhir_ref: String,\n\n}\n\n\n", "file_path": "build_script.rs", "rank": 0, "score": 136466.43613408215 }, { "content": "#[derive(...
Rust
src/lib.rs
NicolasLagaillardie/mqtt_test
1855275b60e7b62c4d4fa94da631d7a6ac101ac8
extern crate futures; extern crate env_logger; extern crate paho_mqtt as mqtt; extern crate openssl; extern crate sys_info; use futures::future::Future; use std::{ fs::File, io::{prelude::*, BufReader}, path::Path, str, }; use uuid::Uuid; use std::{env, process, thread}; use std::time::Duration; us...
extern crate futures; extern crate env_logger; extern crate paho_mqtt as mqtt; extern crate openssl; extern crate sys_info; use futures::future::Future; use std::{ fs::File, io::{prelude::*, BufReader}, path::Path, str, }; use uuid::Uuid; use std::{env, process, thread}; use std::time::Duration; us...
}
if let Err(_e) = tok.wait() { thread::sleep(Duration::from_millis(1000)); first_connection(&cli, &uuid); } else { println!("Sending ID: {:?}", uuid.to_string()); }
if_condition
[]
Rust
src/hci/le/connection.rs
TimYorke/btle
3faed14b19d77225eb2e7d42380683a29a7561ce
use crate::hci::command::Command; use crate::hci::event::{CommandComplete, CommandStatus, ReturnParameters}; use crate::hci::le::{LEControllerOpcode, MetaEventCode}; use crate::hci::{ErrorCode, Opcode}; use crate::le::advertiser::PeerAddressType; use crate::le::connection::{ CELength, ConnectionHandle, ConnectionIn...
use crate::hci::command::Command; use crate::hci::event::{CommandComplete, CommandStatus, ReturnParameters}; use crate::hci::le::{LEControllerOpcode, MetaEventCode}; use crate::hci::{ErrorCode, Opcode}; use crate::le::advertiser::PeerAddressType; use crate::le::connection::{ CELength, ConnectionHandle, ConnectionIn...
fn unpack_from(buf: &[u8]) -> Result<Self, PackError> where Self: Sized, { PackError::expect_length(Self::BYTE_LEN, buf)?; todo!("implement unpack from for CreateConnection") } } #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug, Hash)] pub struct ConnectionCompleteEv...
fn pack_into(&self, buf: &mut [u8]) -> Result<(), PackError> { PackError::expect_length(Self::BYTE_LEN, buf)?; buf[0..2].copy_from_slice(u16::from(self.le_scan_interval).to_le_bytes().as_ref()); buf[2..4].copy_from_slice(u16::from(self.le_scan_window).to_le_bytes().as_ref()); buf[4] = se...
function_block-full_function
[ { "content": "#[cfg(unix)]\n\npub fn dump_bluez(adapter_id: u16) -> Result<(), Box<dyn std::error::Error>> {\n\n use btle::error::StdError;\n\n let manager = btle::hci::socket::Manager::new().map_err(StdError)?;\n\n let socket = match manager.get_adapter_socket(btle::hci::socket::AdapterID(adapter_id))...
Rust
src/service.rs
seanyoung/tower-lsp
03daa1603fc9b1326af81de126228742c31c9c1b
use std::error::Error; use std::fmt::{self, Debug, Display, Formatter}; use std::future::Future; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use futures::channel::mpsc::{self, Receiver}; use futures::stream::FusedStream; use futures::{future, FutureExt, Stream}; use log::trace; use tower_s...
use std::error::Error; use std::fmt::{self, Debug, Display, Formatter}; use std::future::Future; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use futures::channel::mpsc::{self, Receiver}; use futures::stream::FusedStream; use futures::{future, FutureExt, Stream}; use log::trace; use tower_s...
celed))); assert_eq!(cancel_response, Ok(None)); } }
e, messages) } } impl Service<Incoming> for LspService { type Response = Option<Outgoing>; type Error = ExitedError; type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> { if self...
random
[ { "content": "#[proc_macro_attribute]\n\npub fn rpc(attr: TokenStream, item: TokenStream) -> TokenStream {\n\n let attr_args = parse_macro_input!(attr as AttributeArgs);\n\n\n\n match attr_args.as_slice() {\n\n [] => {}\n\n [NestedMeta::Meta(meta)] if meta.path().is_ident(\"name\") => return...
Rust
cryptoki/src/functions/slot_token_management.rs
tgonzalezorlandoarm/rust-cryptoki
c05e91f27f57e2a21124d2de616ab96bada28134
use crate::types::function::Rv; use crate::types::mechanism::{MechanismInfo, MechanismType}; use crate::types::slot_token::{Slot, SlotInfo, TokenInfo}; use crate::Pkcs11; use crate::Result; use crate::Session; use crate::{get_pkcs11, label_from_str}; use cryptoki_sys::{CK_MECHANISM_INFO, CK_SLOT_INFO, CK_TOKEN_INFO};...
use crate::types::function::Rv; use crate::types::mechanism::{MechanismInfo, MechanismType}; use crate::types::slot_token::{Slot, SlotInfo, TokenInfo}; use crate::Pkcs11; use crate::Result; use crate::Session; use crate::{get_pkcs11, label_from_str}; use cryptoki_sys::{CK_MECHANISM_INFO, CK_SLOT_INFO, CK_TOKEN_INFO};...
pub fn get_mechanism_list(&self, slot: Slot) -> Result<Vec<MechanismType>> { let mut mechanism_count = 0; unsafe { Rv::from(get_pkcs11!(self, C_GetMechanismList)( slot.try_into()?, std::ptr::null_mut(), &mut mechanism_count, ...
o)( slot.try_into()?, &mut token_info, )) .into_result()?; Ok(TokenInfo::new(token_info)) } }
function_block-function_prefixed
[ { "content": "pub fn init_pins() -> (Pkcs11, Slot) {\n\n let pkcs11 = Pkcs11::new(\n\n env::var(\"PKCS11_SOFTHSM2_MODULE\")\n\n .unwrap_or_else(|_| \"/usr/local/lib/softhsm/libsofthsm2.so\".to_string()),\n\n )\n\n .unwrap();\n\n\n\n // initialize the library\n\n pkcs11.initializ...
Rust
src/parser/expression/loops.rs
looplanguage/loop
82a2706356741b833558bc39c6b0170a87bdae68
use crate::lexer::token::{create_token, TokenType}; use crate::parser::expression::identifier::{parse_identifier, Identifier}; use crate::parser::expression::Precedence::Lowest; use crate::parser::expression::{Expression, Precedence}; use crate::parser::program::Node; use crate::parser::statement::block::{parse_block, ...
use crate::lexer::token::{create_token, TokenType}; use crate::parser::expression::identifier::{parse_identifier, Identifier}; use crate::parser::expression::Precedence::Lowest; use crate::parser::expression::{Expression, Precedence}; use crate::parser::program::Node; use crate::parser::statement::block::{parse_block, ...
p.throw_exception(create_token(TokenType::To, "to".to_string()), Some(message)); } p.lexer.next_token(); if !p.current_token_is(TokenType::Integer) { let message = "Syntax -> for (<condition>) { <code> }\nExample -> for (i < 3) { println(i) }" .to_string(); p.th...
function_block-function_prefix_line
[ { "content": "pub fn parse_block(p: &mut Parser) -> Block {\n\n let mut statements: Vec<Statement> = Vec::new();\n\n\n\n while p.lexer.get_current_token().unwrap().token != TokenType::RightBrace\n\n && p.lexer.get_current_token().unwrap().token != TokenType::Eof\n\n {\n\n let stmt = p.par...
Rust
src/thread_local.rs
Pyroglyph/odbc-iter
c960edf7eecb9d6a4965a2efc04c882998949275
use log::debug; use std::cell::RefCell; use crate::query::Connection; use crate::{Odbc, OdbcError}; thread_local! { static DB: RefCell<Option<Connection>> = RefCell::new(None); } pub fn connection_with<O>( connection_string: &str, f: impl Fn(Result<Connection, OdbcError>) -> (Option<Connection>, O), ) ->...
use log::debug; use std::cell::RefCell; use crate::query::Connection; use crate::{Odbc, OdbcError}; thread_local! { static DB: RefCell<Option<Connection>> = RefCell::new(None); } pub fn connection_with<O>( connection_string: &str, f: impl Fn(Result<Connection, OdbcError>) -> (Option<Connection>, O), ) ->...
#[cfg(feature = "test-monetdb")] #[test] fn test_connection_with_nested() { connection_with( crate::tests::monetdb_connection_string().as_str(), |result| { let mut monetdb = result.expect("connect to MonetDB"); let data = monetdb ...
connection_with( crate::tests::monetdb_connection_string().as_str(), |result| { let mut monetdb = result.expect("connect to MonetDB"); let data = monetdb .handle() .query::<ValueRow>("SELECT 'foo'") .expe...
function_block-function_prefix_line
[]
Rust
src/main.rs
gourlaysama/dcamctl
d5da7da014923bce13bcca0115380d82b081d9c7
use std::path::Path; use anyhow::*; use dcamctl::{cli::ProgramOptions, config::*}; use dcamctl::{show, AdbServer, AudioSupport, Dcam}; use directories_next::ProjectDirs; use env_logger::{Builder, Env}; use log::*; use structopt::StructOpt; use tokio::runtime; type ReturnCode = i32; static DEFAULT_CONFIG: &str = incl...
use std::path::Path; use anyhow::*; use dcamctl::{cli::ProgramOptions, config::*}; use dcamctl::{show, AdbServer, AudioSupport, Dcam}; use directories_next::ProjectDirs; use env_logger::{Builder, Env}; use log::*; use structopt::StructOpt; use tokio::runtime; type ReturnCode = i32; static DEFAULT_CONFIG: &str = incl...
es"); }; fn set_conf_from_options( conf: &mut config::Config, option: &Option<String>, key: &str, ) -> Result<()> { if let Some(value) = option { conf.set(key, Some(value.as_str()))?; } Ok(()) } set_conf_from_options(&mut conf, &options....
print_version(true); } return Ok(()); } let mut b = Builder::default(); b.format_timestamp(None); b.format_suffix("\r\n"); b.filter_level(LevelFilter::Warn); b.parse_env(Env::from("DCAMCTL_LOG")); if let Some(level) = option...
random
[ { "content": "fn main() {\n\n if let Some(v) = version_check::Version::read() {\n\n println!(\"cargo:rustc-env=BUILD_RUSTC={}\", v)\n\n }\n\n\n\n if let Some(hash) = get_commit_hash().or_else(|| env::var(\"BUILD_ID\").ok()) {\n\n println!(\"cargo:rustc-env=BUILD_ID={}\", hash);\n\n }\n...
Rust
c2rust-refactor/src/select/visitor.rs
mtlll/c2rust
402d157f7e6b25ea3d27da580a6561bca8d40d13
use std::collections::HashSet; use syntax::ast::*; use syntax::source_map::Span; use syntax::visit::{self, FnKind, Visitor}; use crate::command::CommandState; use crate::select::filter::{self, AnyNode}; use crate::select::Filter; use crate::RefactorCtxt; struct ChildMatchVisitor<'a, 'tcx: 'a> { st: &'a CommandS...
use std::collections::HashSet; use syntax::ast::*; use syntax::source_map::Span; use syntax::visit::{self, FnKind, Visitor}; use crate::command::CommandState; use crate::select::filter::{self, AnyNode}; use crate::select::Filter; use crate::RefactorCtxt; struct ChildMatchVisitor<'a, 'tcx: 'a> { st: &'a CommandS...
e, cx: &'a RefactorCtxt<'a, 'tcx>, old: HashSet<NodeId>, new: HashSet<NodeId>, filt: &'a Filter, } impl<'ast, 'a, 'tcx> FilterVisitor<'a, 'tcx> { fn matches(&self, node: AnyNode) -> bool { filter::matches_filter(self.st, self.cx, node, self.filt) } fn walk_args(&mut self, x: &'ast ...
} fn visit_impl_item(&mut self, x: &'ast ImplItem) { if self.in_old && self.matches(AnyNode::ImplItem(x)) { self.new.insert(x.id); } self.maybe_enter_old(x.id, |v| { if let ImplItemKind::Method(ref sig, ..) = x.node { v.walk_args(&sig.decl.inputs); ...
random
[ { "content": "/// Rewrite types in the crate to types that are transmute-compatible with the original.\n\n/// Automatically inserts `transmute` calls as needed to make the types line up after rewriting.\n\n/// \n\n/// This function currently handles only direct function calls. Creation and use of function\n\n/...
Rust
crates/sfc/src/script/mod.rs
IWANABETHATGUY/vue-template-compiler
9e910157b1756bb9e286b9650ede62c0040d6bce
use smallvec::SmallVec; use rslint_parser::{SyntaxNodeExt, parse_module}; use compiler::BindingMetadata; use crate::{SfcDescriptor, SfcScriptBlock, SfcTemplateCompileOptions}; pub struct SfcScriptCompileOptions<'a> { pub id: String, pub is_prod: bool, pub source_map: bool, ...
use smallvec::SmallVec; use rslint_parser::{SyntaxNodeExt, parse_module}; use compiler::BindingMetadata; use crate::{SfcDescriptor, SfcScriptBlock, SfcTemplateCompileOptions}; pub struct SfcScriptCompileOptions<'a> { pub id: String, pub is_prod: bool, pub source_map: bool, ...
(module); script.bindings = Some(bindings); apply_ref_transform(); inject_css_vars(); Some(script) } fn analyze_script_bindings(_module: rslint_parser::ast::Module) -> BindingMetadata<'static> { todo!() } fn process_setup_scripts<'a>( scripts: &mut SmallVec<[SfcScriptBlock; 1]>, ) ->...
let has_uniform_lang = scripts.len() == 1 || scripts[0].get_lang() == scripts[1].get_lang(); if !has_uniform_lang { return None; } if !scripts.iter().any(|s| s.is_setup()) { process_single_script(&mut scripts) } else { process_setup_scripts(&mut scripts) } ...
random
[ { "content": "#[inline(always)]\n\npub fn write_json_string<W: Write>(string: &str, mut w: W) -> Ret {\n\n w.write_char('\"')?;\n\n\n\n for (index, ch) in string.bytes().enumerate() {\n\n if ESCAPED[ch as usize] != __ {\n\n return write_string_complex(w, string, index);\n\n }\n\n ...
Rust
tests/extension.rs
conradludgate/async-graphql
a278cc14123140a94ee57873b949261fe874dd13
use std::sync::Arc; use async_graphql::extensions::{ Extension, ExtensionContext, ExtensionFactory, NextExecute, NextParseQuery, NextPrepareRequest, NextRequest, NextResolve, NextSubscribe, NextValidation, ResolveInfo, }; use async_graphql::futures_util::stream::BoxStream; use async_graphql::parser::types::Exe...
use std::sync::Arc; use async_graphql::extensions::{ Extension, ExtensionContext, ExtensionFactory, NextExecute, NextParseQuery, NextPrepareRequest, NextRequest, NextResolve, NextSubscribe, NextValidation, ResolveInfo, }; use async_graphql::futures_util::stream::BoxStream; use async_graphql::parser::types::Exe...
async fn parse_query( &self, ctx: &ExtensionContext<'_>, query: &str, variables: &Variables, next: NextParseQuery<'_>, ) -> ServerResult<ExecutableDocument> { self.calls.lock().await.push("parse_query_start"); let res ...
it.push("prepare_request_start"); let res = next.run(ctx, request).await; self.calls.lock().await.push("prepare_request_end"); res }
function_block-function_prefixed
[ { "content": "pub fn referenced_variables(value: &Value) -> Vec<&str> {\n\n let mut vars = Vec::new();\n\n referenced_variables_to_vec(value, &mut vars);\n\n vars\n\n}\n\n\n", "file_path": "src/validation/utils.rs", "rank": 0, "score": 305928.8907785468 }, { "content": "fn reference...
Rust
src/quoth/quotes.rs
Ninjani/quoth
f06c37ffc2705aa1a2b47f78f6d1695c4bc46057
use anyhow::Error; use bincode; use chrono::{DateTime, Utc}; use console::{Alignment, pad_str, style}; use path_abs::{FileRead, PathFile}; use serde_json; use textwrap::{termwidth, Wrapper}; use crate::utils; #[derive(Serialize, Deserialize, Debug)] pub struct Quote { pub index: usize, pub book: Str...
use anyhow::Error; use bincode; use chrono::{DateTime, Utc}; use console::{Alignment, pad_str, style}; use path_abs::{FileRead, PathFile}; use serde_json; use textwrap::{termwidth, Wrapper}; use crate::utils; #[derive(Serialize, Deserialize, Debug)] pub struct Quote { pub index: usize, pub book: Str...
; let mut quote_text = utils::user_input( "Quote (<RET> to edit in external editor)", Some("\n"), false, )?; if quote_text.is_empty() { quote_text = utils::external_editor_input(default_text.as_deref())?; } Ok(Quote::new(index, &tit...
match default_date { Some(_) => { utils::parse_date(&utils::user_input("Date", default_date.as_deref(), true)?)? .and_hms(0, 0, 0) } None => Utc::now(), }
if_condition
[ { "content": "pub fn parse_date(date_string: &str) -> Result<Date<Utc>, Error> {\n\n if date_string.to_ascii_lowercase() == \"today\" {\n\n Ok(Utc::now().date())\n\n } else {\n\n Ok(parse_date_string(date_string, Utc::now(), Dialect::Uk)?.date())\n\n }\n\n}\n\n\n", "file_path": "src/u...
Rust
src/tests.rs
hixio-mh/apt-sources-lists
0df4611ec7293010551f95659f28f1b1da9cc0c8
pub use super::*; use std::str::FromStr; const SOURCE_LIST: &str = r#" # deb cdrom:[Pop_OS 18.04 _Bionic Beaver_ - Release amd64 (20180916)]/ bionic main restricted deb http://us.archive.ubuntu.com/ubuntu/ disco restricted multiverse universe main deb-src http://us.archive.ubuntu.com/ubuntu/ disco restricted multivers...
pub use super::*; use std::str::FromStr; const SOURCE_LIST: &str = r#" # deb cdrom:[Pop_OS 18.04 _Bionic Beaver_ - Release amd64 (20180916)]/ bionic main restricted deb http://us.archive.ubuntu.com/ubuntu/ disco restricted multiverse universe main deb-src http://us.archive.ubuntu.com/ubuntu/ disco restricted multivers...
for source in &options { assert_eq!( SourceLine::from_str(source).unwrap(), SourceLine::Entry(SourceEntry { enabled: true, source: false, url: "http://apt.pop-os.org/proprietary".into(), suite: "cosmic".into(), ...
let options = [ "deb [ arch=amd64 ] http://apt.pop-os.org/proprietary cosmic main", "deb [arch=amd64 ] http://apt.pop-os.org/proprietary cosmic main", "deb [ arch=amd64] http://apt.pop-os.org/proprietary cosmic main", "deb [arch=amd64]http://apt.pop-os.org/proprietary cosmic main", ...
assignment_statement
[ { "content": "fn add_modified(modified: &mut Vec<u16>, list: u16) {\n\n if !modified.iter().any(|&v| v == list) {\n\n modified.push(list);\n\n }\n\n}\n", "file_path": "src/sources_list.rs", "rank": 0, "score": 104884.21852786287 }, { "content": "pub fn main() {\n\n let list =...
Rust
src/hla.rs
Irrationone/scHLAcount
9d5bdd70faa113d4cb151ce61d1be26ccfb2302a
use bio::io::fasta; use debruijn::dna_string::DnaString; use debruijn_mapping::build_index::build_index; use debruijn_mapping::config::KmerType; use failure::Error; use itertools::Itertools; use regex::Regex; use serde::Serialize; use std::collections::{HashMap, HashSet}; use std::fmt; use std::io::Read; use std::pa...
use bio::io::fasta; use debruijn::dna_string::DnaString; use debruijn_mapping::build_index::build_index; use debruijn_mapping::config::KmerType; use failure::Error; use itertools::Itertools; use regex::Regex; use serde::Serialize; use std::collections::{HashMap, HashSet}; use std::fmt; use std::io::Read; use std::pa...
#[cfg(test)] mod test { use super::*; const T1: &str = "A*01:01:01:01"; #[test] fn test_parse1() { let parser = AlleleParser::new(); let al = parser.parse(T1).unwrap(); assert_eq!(String::from_utf8(al.gene).unwrap(), "A"); assert_eq!(al.f1, 1); assert_eq!(al.f...
Found {} \"Confirmed\" + \"Full\" + \"gDNA\" + non-Null alleles in allele status file", allele_set.len() ); let fasta = fasta::Reader::from_file(hla_fasta)?; let (seqs, tx_names) = read_hla_cds(fasta, allele_set, true)?; let tx_gene_map = HashMap::new(); let index = build_index::<KmerType>(&...
function_block-function_prefix_line
[ { "content": "pub fn check_inputs_exist_hla_idx(path: &str) -> Result<(), Error> {\n\n if !Path::new(&path).exists() {\n\n return Err(format_err!(\n\n \"Pseudoalignment index {} does not exist. Omit parameter -i to generate automatically.\",\n\n path\n\n ));\n\n }\n\n ...
Rust
src/cache.rs
jcaesar/rust-users-stub
b4929961a9789e025d0a2f656e502f11f4ba9a47
use super::{uid_t, gid_t}; use std::cell::{Cell, RefCell}; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::HashMap; use std::ffi::OsStr; use std::sync::Arc; use base::{User, Group, all_users}; use traits::{Users, Groups}; pub struct UsersCache { users: BiMap<uid_t, User>, g...
use super::{uid_t, gid_t}; use std::cell::{Cell, RefCell}; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::HashMap; use std::ffi::OsStr; use std::sync::Arc; use base::{User, Group, all_users}; use traits::{Users, Groups}; pub struct UsersCache { users: BiMap<uid_t, User>, g...
pied(e) => { return (*e.get()).and_then(|uid| { let users_forward = self.users.forward.borrow_mut(); users_forward[&uid].as_ref().map(Arc::clone) }) } }; if let Some(user) = super::get_user_by_name(username) { ...
t mut users_backward = self.users.backward.borrow_mut(); let entry = match users_backward.entry(Arc::from(username.as_ref())) { Vacant(e) => e, Occu
function_block-random_span
[ { "content": "/// nop, returns a `SwitchUserGuard`, it's nop on drop, too\n\npub fn switch_user_group(uid: uid_t, gid: gid_t) -> io::Result<SwitchUserGuard> {\n\n Ok(SwitchUserGuard {})\n\n}\n", "file_path": "src/switch.rs", "rank": 0, "score": 152588.064898338 }, { "content": "/// const ...
Rust
benches/common.rs
cberner/redb
1a0bb4e0628c3160a7364df200e5daaa527de928
use redb::ReadableTable; pub trait BenchDatabase { type W: for<'a> BenchWriteTransaction<'a>; type R: for<'a> BenchReadTransaction<'a>; fn db_type_name() -> &'static str; fn write_transaction(&mut self) -> Self::W; fn read_transaction(&self) -> Self::R; } pub trait BenchWriteTransaction<'a> { ...
use redb::ReadableTable; pub trait BenchDatabase { type W: for<'a> BenchWriteTransaction<'a>; type R: for<'a> BenchReadTransaction<'a>; fn db_type_name() -> &'static str; fn write_t
} } pub struct LmdbRkvBenchInserter<'a> { db: lmdb::Database, txn: &'a lmdb::RwTransaction<'a>, } impl BenchInserter for LmdbRkvBenchInserter<'_> { fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), ()> { let mut_txn = unsafe { &mut *(self.txn as *const lmdb::Rw...
ransaction(&mut self) -> Self::W; fn read_transaction(&self) -> Self::R; } pub trait BenchWriteTransaction<'a> { type T: BenchInserter + 'a; fn get_inserter(&'a self) -> Self::T; fn commit(self) -> Result<(), ()>; } pub trait BenchInserter { fn insert(&mut self, key: &[u8], value: &[u8]) -> Res...
random
[ { "content": "pub trait RedbValue {\n\n // TODO: need GATs, so that we can replace all this HRTB stuff\n\n type View: for<'a> WithLifetime<'a>;\n\n type ToBytes: for<'a> AsBytesWithLifetime<'a>;\n\n\n\n /// Deserializes data\n\n /// Implementations may return a view over data, or an owned type\n\...
Rust
pallets/utxo/src/sign.rs
muursh/core-1
ebee9ff587d72a5d5e6100d0560bf9b69e8bfb03
use crate::{Transaction, TransactionOutput}; use chainscript::context::ParseResult; pub use chainscript::sighash::SigHash; use chainscript::sighash::{InputMode, OutputMode}; use codec::{Decode, DecodeAll, Encode}; use frame_support::sp_io::crypto; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use sp_c...
use crate::{Transaction, TransactionOutput}; use chainscript::context::ParseResult; pub use chainscript::sighash::SigHash; use chainscript::sighash::{InputMode, OutputMode}; use codec::{Decode, DecodeAll, Encode}; use frame_support::sp_io::crypto; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use sp_c...
} pub trait Scheme: Sized { type Signature: Decode; fn verify_raw(&self, sig: &Self::Signature, msg: &[u8]) -> bool; fn parse_sig(self, sig: &[u8]) -> Option<SignatureDataFor<Self>> { let mut input = sig; let signature = Decode::decode(&mut input).ok()?; let sighas...
pub fn construct<AcctId: Encode>( sighash: SigHash, tx: &Transaction<AcctId>, spending: &[TransactionOutput<AcctId>], index: u64, codesep_idx: u32, ) -> Self { let idx = index as usize; assert!(spending.len() == tx.inputs.len()); assert!(idx < tx.input...
function_block-full_function
[]
Rust
src/emu/dcdcmiscctrl.rs
BogdanOlar/efm32pg1b-pac
02d8d0e95676db162b5a44450a2cd0e87851d998
#[doc = "Reader of register DCDCMISCCTRL"] pub type R = crate::R<u32, super::DCDCMISCCTRL>; #[doc = "Writer for register DCDCMISCCTRL"] pub type W = crate::W<u32, super::DCDCMISCCTRL>; #[doc = "Register DCDCMISCCTRL `reset()`'s with value 0x3330_7700"] impl crate::ResetValue for super::DCDCMISCCTRL { type Type = u3...
#[doc = "Reader of register DCDCMISCCTRL"] pub type R = crate::R<u32, super::DCDCMISCCTRL>; #[doc = "Writer for register DCDCMISCCTRL"] pub type W = crate::W<u32, super::DCDCMISCCTRL>; #[doc = "Register DCDCMISCCTRL `reset()`'s with value 0x3330_7700"] impl crate::ResetValue for super::DCDCMISCCTRL { type Type = u3...
#[doc = "Checks if the value of the field is `BIAS0`"] #[inline(always)] pub fn is_bias0(&self) -> bool { *self == LPCMPBIAS_A::BIAS0 } #[doc = "Checks if the value of the field is `BIAS1`"] #[inline(always)] pub fn is_bias1(&self) -> bool { *self == LPCMPBIAS_A::BIAS1 }...
pub fn variant(&self) -> LPCMPBIAS_A { match self.bits { 0 => LPCMPBIAS_A::BIAS0, 1 => LPCMPBIAS_A::BIAS1, 2 => LPCMPBIAS_A::BIAS2, 3 => LPCMPBIAS_A::BIAS3, _ => unreachable!(), } }
function_block-function_prefix_line
[ { "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
cli/src/zkp_verify.rs
sec-bit/zkp-toolkit
3ebd4342386285864ff9116c8eef41bc902ab2d5
use std::env; use std::path::PathBuf; use zkp_toolkit::{verify, verify_from_bytes, Curve, GadgetProof, Proof, Scheme}; const SETUP_DIR: &'static str = "./trusted_setup"; fn print_common() { println!(""); println!("scheme:"); println!(" groth16 -- Groth16 zero-knowledge proof system. [Default]"); ...
use std::env; use std::path::PathBuf; use zkp_toolkit::{verify, verify_from_bytes, Curve, GadgetProof, Proof, Scheme}; const SETUP_DIR: &'static str = "./trusted_setup"; fn print_common() { println!(""); println!("scheme:"); println!(" groth16 -- Groth16 zero-knowledge proof system. [Default]"); ...
nwrap(); let s = Scheme::from_str(s_str).unwrap(); let c = Curve::from_str(c_str).unwrap(); let p = match g_str { "mimc" => GadgetProof::MiMC( from_hex(params[0].as_str().unwrap()).unwrap(), from_hex(p_str).unwrap(), ...
function_block-function_prefixed
[ { "content": "pub fn handle_args() -> Result<(Gadget, Scheme, Curve, String, bool), String> {\n\n let args: Vec<_> = env::args().collect();\n\n if args.len() < 2 {\n\n print_help();\n\n\n\n return Err(\"Params invalid!\".to_owned());\n\n }\n\n\n\n let is_pp = args.contains(&\"--prepare...
Rust
src/main.rs
teovoinea/spot-client
c0c6ac978aa791706a96f2e92875cc2c04a109b7
#[macro_use] extern crate stdweb; #[macro_use] extern crate serde_derive; extern crate bincode; use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::u8::MAX; use std::i64; use bincode::{serialize, deserialize}; use stdweb::traits::*; use stdweb::unstable::TryInto; use stdweb::...
#[macro_use] extern crate stdweb; #[macro_use] extern crate serde_derive; extern crate bincode; use std::rc::Rc; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::u8::MAX; use std::i64; use bincode::{serialize, deserialize}; use stdweb::traits::*; use stdweb::unstable::TryInto; use stdweb::...
y_buffer(&ab).unwrap(); } })); stdweb::event_loop(); }
ason())); })); ws.add_event_listener( enclose!( (context, output_msg) move |event: SocketMessageEvent| { let data: Vec<u8> = Vec::from(event.data().into_array_buffer().unwrap()); let decoded_pixel: PaintPixel = deserialize(&data).unwrap(); let mut hex_color: String = String::from("#...
random
[ { "content": "[![Build Status](https://travis-ci.org/teovoinea/spot-client.svg?branch=master)](https://travis-ci.org/teovoinea/spot-client)\n\n[![Build status](https://ci.appveyor.com/api/projects/status/ld3b3u2wa9rw6m7j?svg=true)](https://ci.appveyor.com/project/teovoinea/spot-client)\n\n[![dependency status](...
Rust
sql/mysql/src/main.rs
simoneromano96/db-engines-benchmark
386c3f18b3ec3a3f94ff270fe27ebdf3d6967511
#[macro_use] extern crate mysql; use mysql as my; use uuid::Uuid; use rust_decimal::Decimal; use fake::faker::internet::raw::*; use fake::faker::name::raw::*; use fake::locales::EN; use fake::Fake; #[derive(Debug)] struct Customer { id: Uuid, first_name: String, last_name: String, email: String, } ...
#[macro_use] extern crate mysql; use mysql as my; use uuid::Uuid; use rust_decimal::Decimal; use fake::faker::internet::raw::*; use fake::faker::name::raw::*; use fake::locales::EN; use fake::Fake; #[derive(Debug)] struct Customer { id: Uuid, first_name: String, last_name: String, email: String, } ...
` will map each `row` to `Payment` result.map(|x| x.unwrap()).map(|row| { // ⚠️ Note that from_row will panic if you don't follow your schema let (customer_id, amount, account_name) = my::from_row(row); Payment { customer_id: customer_id, amoun...
"id" => customer.id.to_string(), "first_name" => &customer.first_name, "last_name" => &customer.last_name, "email" => &customer.email, }) .unwrap(); } } /* // Let's create payment table. // Un...
random
[ { "content": "#[derive(Debug)]\n\nstruct OrderItem {\n\n order_id: Uuid,\n\n item_id: Uuid,\n\n quantity: i8,\n\n}\n\n\n\n// Routes\n", "file_path": "sql/postgres/src/main.rs", "rank": 3, "score": 110883.8763227282 }, { "content": "#[derive(Debug)]\n\nstruct OrderItem {\n\n order...
Rust
base_layer/common_types/src/types/fixed_hash.rs
AaronFeickert/tari
5e55bf22110ac40ffc0dea88d88ba836982591eb
use std::{ convert::TryFrom, ops::{Deref, DerefMut}, }; use digest::{consts::U32, generic_array, Digest}; use serde::{Deserialize, Serialize}; use tari_utilities::hex::{Hex, HexError}; use crate::types::HashDigest; const ZERO_HASH: [u8; FixedHash::byte_size()] = [0u8; FixedHash::byte_size()]; #[derive(thi...
use std::{ convert::TryFrom, ops::{Deref, DerefMut}, }; use digest::{consts::U32, generic_array, Digest}; use serde::{Deserialize, Serialize}; use tari_utilities::hex::{Hex, HexError}; use crate::types::HashDigest; const ZERO_HASH: [u8; FixedHash::byte_size()] = [0u8; FixedHash::byte_size()]; #[derive(thi...
} impl From<generic_array::GenericArray<u8, U32>> for FixedHash { fn from(hash: generic_array::GenericArray<u8, U32>) -> Self { Self(hash.into()) } } impl PartialEq<[u8]> for FixedHash { fn eq(&self, other: &[u8]) -> bool { self.0[..].eq(other) } } impl PartialEq<FixedHash> for [u8] ...
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> { if bytes.len() != FixedHash::byte_size() { return Err(FixedHashSizeError); } let mut buf = [0u8; FixedHash::byte_size()]; buf.copy_from_slice(bytes); Ok(Self(buf)) }
function_block-full_function
[ { "content": "pub fn copy_into_fixed_array<T: Default + Copy, const SZ: usize>(elems: &[T]) -> Result<[T; SZ], ByteArrayError> {\n\n if elems.len() != SZ {\n\n return Err(ByteArrayError::IncorrectLength);\n\n }\n\n let mut buf = [T::default(); SZ];\n\n buf.copy_from_slice(&elems[0..SZ]);\n\n ...
Rust
src/usb/gotgctl.rs
pablo-mansanet-bluefruit/efm32gg11b-hal
61a359e544b9dac336f58e51697d248daf658d59
#[doc = "Reader of register GOTGCTL"] pub type R = crate::R<u32, super::GOTGCTL>; #[doc = "Writer for register GOTGCTL"] pub type W = crate::W<u32, super::GOTGCTL>; #[doc = "Register GOTGCTL `reset()`'s with value 0x0001_0000"] impl crate::ResetValue for super::GOTGCTL { type Type = u32; #[inline(always)] f...
#[doc = "Reader of register GOTGCTL"] pub type R = crate::R<u32, super::GOTGCTL>; #[doc = "Writer for register GOTGCTL"] pub type W = crate::W<u32, super::GOTGCTL>; #[doc = "Register GOTGCTL `reset()`'s with value 0x0001_0000"] impl crate::ResetValue for super::GOTGCTL { type Type = u32; #[inline(always)] f...
&'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `HSTSETHNPEN`"] pub type HSTSETHNPEN_R =...
a> AVALIDOVEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)...
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/util/parse.rs
tipulabs/tipu
acf62ed78f92ceae6969e1e97d6c503ae4497462
use unicode_segmentation::UnicodeSegmentation; use std::collections::HashMap; #[derive(Clone, Debug)] pub enum Token { Path(String), Arg(String), Text(String), Whitespace(String), Escape, DoubleQuote, SingleQuote, EOL, } impl Token { pub fn to_text(&self) -> Result<Token, String> ...
use unicode_segmentation::UnicodeSegmentation; use std::collections::HashMap; #[derive(Clone, Debug)] pub enum Token { Path(String), Arg(String), Text(String), Whitespace(String), Escape, DoubleQuote, SingleQuote, EOL, } impl Token { pub fn to_text(&self) -> Result<Token, String> ...
| Path(path) | Arg(path) => Ok(Path(path.clone())), _ => Err("couldn't convert to Token::Path".to_owned()), } } pub fn to_arg(&self) -> Result<Token, String> { use Token::*; return match self { Text(arg) | Path(arg) | Arg(arg) => Ok(Arg(arg.clone())), ...
xt("\\".to_owned())), DoubleQuote => Ok(Text("\"".to_owned())), SingleQuote => Ok(Text("'".to_owned())), _ => Err("couldn't convert to Token::Text".to_owned()), } } pub fn to_path(&self) -> Result<Token, String> { use Token::*; return match self { ...
random
[ { "content": "fn eval_input(input: &str) -> Option<(String, Vec<String>)> {\n\n match parse::parse(input) {\n\n Ok(mut expr) => {\n\n let args = expr\n\n .split_off(1)\n\n .iter()\n\n .map(|x| x.unwrap())\n\n .collect();\n\n ...
Rust
clipper-sys/generated/bindings.rs
OMG-ICFP-FTW/icfp2021
91b87968ce3fc6a8b6d6c6e362433f6de2463345
/* automatically generated by rust-bindgen 0.58.1 */ pub type size_t = ::std::os::raw::c_ulong; pub const ClipType_ctIntersection: ClipType = 0; pub const ClipType_ctUnion: ClipType = 1; pub const ClipType_ctDifference: ClipType = 2; pub const ClipType_ctXor: ClipType = 3; pub type ClipType = ::std::os::raw::c_uint; p...
/* automatically generated by rust-bindgen 0.58.1 */ pub type size_t = ::std::os::raw::c_ulong; pub const ClipType_ctIntersection: ClipType = 0; pub const ClipType_ctUnion: ClipType = 1; pub const ClipType_ctDifference: ClipType = 2; pub const ClipType_ctXor: ClipType = 3; pub type ClipType = ::std::os::raw::c_uint; p...
Polygon { pub paths: *mut Path, pub paths_count: size_t, pub type_: PolyType, } #[test] fn bindgen_test_layout_Polygon() { assert_eq!( ::std::mem::size_of::<Polygon>(), 24usize, concat!("Size of: ", stringify!(Polygon)) ); assert_eq!( ::std::mem::align_of::<Polygo...
t, } #[test] fn bindgen_test_layout_Path() { assert_eq!( ::std::mem::size_of::<Path>(), 24usize, concat!("Size of: ", stringify!(Path)) ); assert_eq!( ::std::mem::align_of::<Path>(), 8usize, concat!("Alignment of ", stringify!(Path)) ); assert_eq!( ...
random
[ { "content": "struct static_const\n\n{\n\n static constexpr T value{};\n\n};\n\n\n\ntemplate<typename T>\n\nconstexpr T static_const<T>::value;\n\n\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/meta/identity_tag.hpp>\n\n\n\n\n\nnamespace nlohmann\n\n{\n\nnamespace ...
Rust
examples/spawn-chain/src/elixir/chain/create_processes_2/label_2.rs
xtian/lumen
20a3095697ce05c860f825ae573fa4e70e740026
use std::convert::TryInto; use std::sync::Arc; use liblumen_alloc::borrow::clone_to_process::CloneToProcess; use liblumen_alloc::erts::exception::system::Alloc; use liblumen_alloc::erts::message::{self, Message}; use liblumen_alloc::erts::process::code::stack::frame::{Frame, Placement}; use liblumen_alloc::erts::proce...
use std::convert::TryInto; use std::sync::Arc; use liblumen_alloc::borrow::clone_to_process::CloneToProcess; use liblumen_alloc::erts::exception::system::Alloc; use liblumen_alloc::erts::message::{self, Message}; use liblumen_alloc::erts::process::code::stack::frame::{Frame, Placement}; use liblumen_alloc::erts::proce...
fn frame(process: &Process) -> Frame { let module_function_arity = process.current_module_function_arity().unwrap(); Frame::new(module_function_arity, code) }
fn code(arc_process: &Arc<Process>) -> code::Result { let received = { let mailbox_guard = arc_process.mailbox.lock(); let mut mailbox = mailbox_guard.borrow_mut(); let seen = mailbox.seen(); let mut found_position = None; for (position, message) in mailbox.iter().enume...
function_block-full_function
[ { "content": "pub fn closure(process: &Process, output: Term) -> std::result::Result<Term, Alloc> {\n\n process.closure_with_env_from_slice(\n\n module_function_arity(),\n\n code,\n\n process.pid_term(),\n\n &[output],\n\n )\n\n}\n\n\n\n// Private\n\n\n", "file_path": "exam...
Rust
crates/nu_plugin_inc/src/nu/tests.rs
ammkrn/nushell
b403fb12752af76b4fc1ddcce0dd18b111e4bca7
mod integration { use crate::inc::{Action, SemVerAction}; use crate::Inc; use nu_errors::ShellError; use nu_plugin::test_helpers::{plugin, CallStub}; use nu_protocol::{Primitive, UntaggedValue}; use nu_test_support::value::column_path; use nu_value_ext::ValueExt; #[test] fn picks_up...
mod integration { use crate::inc::{Action, SemVerAction}; use crate::Inc; use nu_errors::ShellError; use nu_plugin::test_helpers::{plugin, CallStub}; use nu_protocol::{Primitive, UntaggedValue}; use nu_test_support::value::column_path; use nu_value_ext::ValueExt; #[test] fn picks_up...
#[test] fn picks_up_major_flag() { plugin(&mut Inc::new()) .args(CallStub::new().with_long_flag("major").create()) .setup(|plugin, _| { let sem_version_part = SemVerAction::Major; plugin.expect_action(Action::SemVerAction(sem_version_part)) ...
s| { let actual = format!("{}", returned_values.unwrap_err()); assert!(actual.contains("can only apply one")); assert_eq!(plugin.error, Some("can only apply one".to_string())); }); }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn one_arg() {\n\n let actual = nu!(\n\n cwd: \"tests/fixtures/formats\", pipeline(\n\n r#\"\n\n = 1\n\n \"#\n\n ));\n\n\n\n assert_eq!(actual.out, \"1\");\n\n}\n\n\n", "file_path": "crates/nu-command/tests/commands/math/mod.rs", "rank": ...
Rust
src/client/transitions.rs
stuck-overflow/obws
6b71ed39bfacb66bbb3050b300e97ac2be2efa44
use chrono::Duration; use serde::Serialize; use super::Client; use crate::requests::RequestType; use crate::responses; use crate::{Error, Result}; pub struct Transitions<'a> { pub(super) client: &'a Client, } impl<'a> Transitions<'a> { pub async fn get_transition_list(&self) -> Result<responses::Transit...
use chrono::Duration; use serde::Serialize; use super::Client; use crate::requests::RequestType; use crate::responses; use crate::{Error, Result}; pub struct Transitions<'a> { pub(super) client: &'a Client, } impl<'a> Transitions<'a> { pub async fn get_transition_list(&self) -> Result<responses::Transit...
pub async fn set_transition_settings<T>( &self, transition_name: &str, transition_settings: &T, ) -> Result<serde_json::Value> where T: Serialize, { self.client .send_message::<responses::TransitionSettings>(RequestType::SetTransi...
pub async fn get_transition_settings( &self, transition_name: &str, ) -> Result<serde_json::Value> { self.client .send_message::<responses::TransitionSettings>(RequestType::GetTransitionSettings { transition_name, }) .await .map...
function_block-full_function
[ { "content": "pub fn duration_millis<'de, D>(deserializer: D) -> Result<Duration, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n deserializer.deserialize_i64(DurationMillisVisitor)\n\n}\n\n\n", "file_path": "src/de.rs", "rank": 0, "score": 143953.47773434693 }, { "content": "pub...
Rust
src/solve/constraint/vector_preemptive_set.rs
camsteffen/kenny
8c9b54bca810e72b9a845a3b958edaf283e94580
use itertools::Itertools; use super::Constraint; use crate::collections::iterator_ext::IteratorExt; use crate::collections::square::Square; use crate::collections::square::{IsSquare, Vector}; use crate::puzzle::{CellId, Puzzle}; use crate::solve::markup::{PuzzleMarkup, PuzzleMarkupChanges}; use crate::solve::CellVaria...
use itertools::Itertools; use super::Constraint; use crate::collections::iterator_ext::IteratorExt; use crate::collections::square::Square; use crate::collections::square::{IsSquare, Vector}; use crate::puzzle::{CellId, Puzzle}; use crate::solve::markup::{PuzzleMarkup, PuzzleMarkupChanges}; use crate::solve::CellVaria...
ons(max_domain_size) { if let Some(domain) = unify_domain(cell_variables, &cells, max_domain_size) { count += found_preemptive_set(cell_variables, change, vector, &cells, &domain); break 'domain_sizes; } } } count } fn unify_domain( cell_varia...
count(); if unsolved_count < 3 { return 0; } let max_domain = unsolved_count - 1; let mut cells_by_domain_size = vec![Vec::new(); max_domain - 2]; for (index, variable) in cell_variables.vector(vector).indexed() { if let Some(domain) = variable.unsolved() { if domai...
function_block-random_span
[ { "content": "fn reduce_cage(puzzle: &Puzzle, cage: CageRef<'_>, changes: &mut CellChanges) {\n\n match cage.operator() {\n\n Operator::Add => reduce_cage_add(puzzle, cage, changes),\n\n Operator::Multiply => reduce_cage_multiply(puzzle, cage, changes),\n\n Operator::Subtract => reduce_c...
Rust
crate/src/hex.rs
kvsari/wasm-dicey
d2745d72adb07fd246e87b28d90f57792b545894
use wasm_bindgen::prelude::*; use crate::primitive::{Colour, Colours, Point}; #[wasm_bindgen] pub fn pointy_hex_corner(center: &Point, radius: u32, corner: u8) -> Point { let corner: f64 = corner.into(); let radius: f64 = radius.into(); let corner: f64 = corner.into(); let degrees = 60_f64 *...
use wasm_bindgen::prelude::*; use crate::primitive::{Colour, Colours, Point}; #[wasm_bindgen]
#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Blank { points: [Point; 6], center: Point, } impl Blank { pub fn new(center: &Point, radius: u32) -> Self { Blank { points: [ pointy_hex_corner(center, radius, 1), pointy_hex_corner(center, radius,...
pub fn pointy_hex_corner(center: &Point, radius: u32, corner: u8) -> Point { let corner: f64 = corner.into(); let radius: f64 = radius.into(); let corner: f64 = corner.into(); let degrees = 60_f64 * corner - 30_f64; let radians = std::f64::consts::PI / 180_f64 * degrees; let new_x = (cen...
function_block-full_function
[ { "content": "export const css_colour_from_num = (num) => {\n\n switch (num) {\n\n case 0: return 'black';\n\n case 1: return 'white';\n\n case 2: return 'lightblue';\n\n case 3: return 'blue';\n\n case 4: return 'darkblue';\n\n case 5: return 'lightgreen';\n\n case 6: return 'green';\n\...
Rust
crates/pewter-stockfish-comparer/src/main.rs
Joey9801/pewter
b867bfcecebb67a4274fe895afb0a6b7a7875b2f
use std::io::Write; use std::path::PathBuf; use std::{ collections::HashSet, io::{BufRead, BufReader}, path::Path, process::{Child, Command, Stdio}, }; use anyhow::{Context, Result}; use clap::Parser; use pewter_core::{ io::fen::{format_fen, parse_fen}, Move, State, }; fn parse_stockfish_perf...
use std::io::Write; use std::path::PathBuf; use std::{ collections::HashSet, io::{BufRead, BufReader}, path::Path, process::{Child, Command, Stdio}, }; use anyhow::{Context, Result}; use clap::Parser; use pewter_core::{ io::fen::{format_fen, parse_fen}, Move, State, }; fn parse_stockfish_perf...
fn perft(&mut self, state: State, depth: u8) -> Vec<(Move, usize)> { self.set_state(state); let stdin = self .child .stdin .as_mut() .expect("Expected stockfish handle to have a stdin"); write!(stdin, "go perft {}\n", depth).expect("Failed ...
fn set_state(&mut self, state: State) { let stdin = self .child .stdin .as_mut() .expect("Expected stockfish handle to have a stdin"); let fen_str = format_fen(&state); write!(stdin, "position fen {}\n", fen_str).expect("Failed to write to stockfi...
function_block-function_prefix_line
[ { "content": "fn parse_san_move(state: &State, move_str: &str) -> Result<Move, PgnParseError> {\n\n if !move_str.is_ascii() || move_str.len() < 2 {\n\n return Err(PgnParseError::BadMoveString);\n\n }\n\n\n\n let mut move_str = move_str.as_bytes();\n\n\n\n // Strip redundant metadata that this...
Rust
bot/src/api/spotify.rs
osurce/setmod
397d252bc61f62fee399920c44868ab723f4102f
use crate::{oauth2, prelude::*}; use bytes::Bytes; use failure::Error; use reqwest::{ header, r#async::{Client, Decoder}, Method, StatusCode, Url, }; use rspotify::spotify::model::search; pub use rspotify::spotify::{ model::{ artist::SimplifiedArtist, context::FullPlayingContext, ...
use crate::{oauth2, prelude::*}; use bytes::Bytes; use failure::Error; use reqwest::{ header, r#async::{Client, Decoder}, Method, StatusCode, Url, }; use rspotify::spotify::model::search; pub use rspotify::spotify::{ model::{ artist::SimplifiedArtist, context::FullPlayingContext, ...
pub fn page_as_stream<T>(&self, page: Page<T>) -> PageStream<T> where T: 'static + Send + serde::de::DeserializeOwned, { self.page_stream(future::ok(page)) } fn page_stream<T>( &self, future: impl Future<Output = Result<Page<T>, Error>> + Send + 'static, ...
h"]) .query_param("type", "track") .query_param("q", &q) .execute::<search::SearchTracks>() .await .map(|r| r.tracks) }
function_block-function_prefixed
[ { "content": "/// Tokenize the given word.\n\npub fn tokenize(word: &str) -> String {\n\n let word = word.to_lowercase();\n\n inflector::string::singularize::to_singular(&word)\n\n}\n\n\n", "file_path": "bot/src/db/words.rs", "rank": 0, "score": 299800.1980897748 }, { "content": "/// C...
Rust
tests/isahc/asynk/header.rs
beltram/asserhttp
292261acfa5f1a3b629902d7b3766044baa61e4e
use isahc::get_async; use asserhttp::*; mod eq { use super::*; #[async_std::test] #[stubr::mock("header/one.json")] async fn should_expect_header() { get_async(stubr.uri()).await.unwrap().expect_header("x-a", "a"); } #[async_std::test] #[stubr::mock("header/one.json")] async ...
use isahc::get_async; use asserhttp::*; mod eq { use super::*; #[async_std::test] #[stubr::mock("header/one.json")] async fn should_expect_header() { get_async(stubr.uri()).await.unwrap().expect_header("x-a", "a"); } #[async_std::test] #[stubr::mock("header/one.json")] async ...
equal to 'text/plain' but was 'application/xml'")] #[stubr::mock("header/xml.json")] #[async_std::test] async fn result_expect_header_should_panic_when_wrong_value() { get_async(stubr.uri()).await.expect_content_type_text(); } }
ect_header_should_panic_when_wrong_key() { get_async(stubr.uri()).await.expect_header("x-b", "a"); } #[should_panic(expected = "expected header 'x-a' to be equal to 'b' but was 'a'")] #[stubr::mock("header/one.json")] #[async_std::test] async fn result_expect_header_should_panic_when_wrong_...
random
[ { "content": "pub fn assert_json_body_eq<B>(actual: B, expected: B) where B: DeserializeOwned + Serialize + PartialEq + Debug + Unpin {\n\n assert_eq!(actual, expected, \"expected json body '{}' to be equal to '{}' but was not\",\n\n to_json_string(&actual),\n\n to_json_string(&ex...
Rust
contracts/periphery/oracle/src/contract.rs
akropolisio/astroport
9b7bbf80b977c7e803174aa3a6d659556438d579
use crate::error::ContractError; use crate::querier::{query_cumulative_prices, query_pair_info, query_prices}; use crate::state::{Config, PriceCumulativeLast, CONFIG, PRICE_LAST}; use astroport::asset::{addr_validate_to_lower, Asset, AssetInfo}; use astroport::oracle::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};...
use crate::error::ContractError; use crate::querier::{query_cumulative_prices, query_pair_info, query_prices}; use crate::state::{Config, PriceCumulativeLast, CONFIG, PRICE_LAST}; use astroport::asset::{addr_validate_to_lower, Asset, AssetInfo}; use astroport::oracle::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};...
.unwrap() .return_amount; Uint256::from(price).multiply_ratio(Uint256::from(amount), Uint256::from(one)) } else { let price_precision = Uint256::from(10_u128.pow(TWAP_PRECISION.into())); Uint256::from(amount) * price_average / Decimal256::from_uint256(price_precision) }...
query_prices( &deps.querier, config.pair.contract_addr, Asset { info: token, amount: one, }, )
call_expression
[ { "content": "pub fn pool_info(deps: Deps, config: Config) -> StdResult<([Asset; 2], Uint128)> {\n\n let contract_addr = config.pair_info.contract_addr.clone();\n\n let pools: [Asset; 2] = config.pair_info.query_pools(&deps.querier, contract_addr)?;\n\n let total_share: Uint128 = query_supply(&deps.que...
Rust
darknet-config/src/config/darknet.rs
jerry73204/yolo-dl
35fde79c70d62fc70f045acc8fee7aa85555298b
use super::*; pub use darknet::*; mod darknet { use super::*; #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(try_from = "Items")] pub struct Darknet { pub net: Net, pub layers: Vec<Layer>, } impl Darknet { pub fn load<P>(config_file: P) -...
use super::*; pub use darknet::*; mod darknet { use super::*; #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(try_from = "Items")] pub struct Darknet { pub net: Net, pub layers: Vec<Layer>, } impl Darknet { pub fn load<P>(config_file: P) -...
r::Softmax(layer) => layer.output_shape(input_shape.single()?).into(), Layer::Yolo(layer) => layer.output_shape(input_shape.single_dim3()?)?, Layer::GaussianYolo(layer) => layer.output_shape(input_shape.single_dim3()?)?, Layer::Cost(_layer) => unimplemented!(), Layer::Cro...
UpSample(UpSample), BatchNorm(BatchNorm), Dropout(Dropout), Softmax(Softmax), Cost(Cost), Crop(Crop), AvgPool(AvgPool), Yolo(Yolo), GaussianYolo(GaussianYolo), Unimplemented(UnimplementedLayer), } impl From<UnimplementedLayer> for Layer { fn from(v: UnimplementedLayer) -> Self ...
random
[ { "content": "fn hash_vec<T, H>(layers: &IndexSet<T>, state: &mut H)\n\nwhere\n\n T: Hash,\n\n H: Hasher,\n\n{\n\n let layers: Vec<_> = layers.iter().collect();\n\n layers.hash(state);\n\n}\n\n\n\n// fn hash_vec_indexset<T, H>(set: &IndexSet<T>, state: &mut H)\n\n// where\n\n// T: Hash,\n\n// ...
Rust
crate/stdio_input/src/system/stdin_system.rs
azriel91/autexousious
223f767c2b51ce223958b16956f493b32a6fc7e9
use std::thread; use amethyst::{ core::SystemDesc, ecs::{ReadExpect, System, World, Write}, shred::{ResourceId, SystemData}, shrev::EventChannel, }; use application_input::ApplicationEvent; use crossbeam_channel::{Receiver, TryRecvError}; use derivative::Derivative; use derive_new::new; use log::{debug...
use std::thread; use amethyst::{ core::SystemDesc, ecs::{ReadExpect, System, World, Write}, shred::{ResourceId, SystemData}, shrev::EventChannel, }; use application_input::ApplicationEvent; use crossbeam_channel::{Receiver, TryRecvError}; use derivative::Derivative; use derive_new::new; use log::{debug...
Err(e) => error!("Failed to parse command. Error: `{}`.", e), } }); } Err(TryRecvError::Empty) => { trace!("No message from StdinReader"); } Err(TryRecvError::Disconnec...
(rx: Receiver<String>, reader_spawn_fn: F) -> Self where F: FnOnce(), { reader_spawn_fn(); StdinSystem { rx } } } impl<'s> System<'s> for StdinSystem { type SystemData = StdinSystemData<'s>; fn run( &mut self, StdinSystemData { state_id, ...
random
[ { "content": "/// Generates the `FrameComponentData` implementation.\n\npub fn frame_component_data_impl(\n\n mut ast: DeriveInput,\n\n args: ComponentDataAttributeArgs,\n\n) -> TokenStream {\n\n let ComponentDataAttributeArgs {\n\n component_path,\n\n component_copy,\n\n to_owned_...
Rust
src/mixer.rs
Chris--B/comms-rs
8b9278e698c4c817a77449f74fa5ffed3f5c5425
use crate::prelude::*; use std::f64::consts::PI; extern crate num; use num::complex::Complex; use num::Num; use num_traits::NumCast; use crate::util::math; pub struct Mixer { phase: f64, dphase: f64, } impl Mixer { ...
use crate::prelude::*; use std::f64::consts::PI; extern crate num; use num::complex::Complex; use num::Num; use num_traits::NumCast; use crate::util::math; pub struct Mixer { phase: f64, dphase: f64, } impl Mixer { ...
elf.state[i].im, truth.im); } } else { self.state.push(input); } Ok(()) } } let mut check_node = CheckNode::new(); connect_nodes!(source, output, mixer, input); connect_nodes!(mixer, out...
x::new(2.628189174, 10.300127265), Complex::new(7.468436663, 5.022196114), ]; for (i, truth) in truth.iter().enumerate() { assert_approx_eq!(self.state[i].re, truth.re); assert_approx_eq!(s
function_block-random_span
[ { "content": "/// Calculates a phase estimate from the input QAM symbol vector.\n\n///\n\n/// Result is in radians, and the estimator assumes the input symbol vector is\n\n/// the output from a matched filter. It additionally assumes the vector has\n\n/// already gone through accurate timing recovery.\n\n///\...
Rust
src/enc/reader.rs
Nemo157/rust-brotli
458f5780a37674c3bae38212e11166b22d3198b1
#![cfg_attr(not(feature="std"), allow(unused_imports))] use super::combined_alloc::BrotliAlloc; use super::encode::{BrotliEncoderCreateInstance, BrotliEncoderDestroyInstance, BrotliEncoderParameter, BrotliEncoderSetParameter, BrotliEncoderOperation, BrotliEncoderStateStruct, Bro...
#![cfg_attr(not(feature="std"), allow(unused_imports))] use super::combined_alloc::BrotliAlloc; use super::encode::{BrotliEncoderCreateInstance, BrotliEncoderDestroyInstance, BrotliEncoderParameter, BrotliEncoderSetParameter, BrotliEncoderOperation, BrotliEncoderStateStruct, Bro...
pub fn with_params(r: R, buffer_size: usize, params: &BrotliEncoderParams) -> Self { let mut reader = Self::new(r, buffer_size, params.quality as u32, params.lgwin as u32); (reader.0).0.state.0.params = params.clone(); reader } pub fn get_ref(&self) -> &R { self.0.get_ref() } pub fn into_...
r, alloc, q, lgwin)) }
function_block-function_prefixed
[ { "content": "pub fn BrotliEncoderCopyInputToRingBuffer<Alloc: BrotliAlloc>(s: &mut BrotliEncoderStateStruct<Alloc>,\n\n input_size: usize,\n\n input_buffer: &[u8]) {\n\n CopyInputToRingBuffer(s, input_size, input_buffer);\n\n}\n...
Rust
libgraffiti/src/viewport.rs
cztomsik/stain
54c34677db1594f2a29243f26d5f83b2ca3a120b
use crate::{ convert::{container_style, layout_style}, css::{MatchingContext, Style}, layout::{self, LayoutEngine, LayoutResult, LayoutStyle, LayoutTree, Size}, renderer::{ContainerStyle, Rect, RenderEdge, Renderer}, Document, NodeId, NodeType, }; use skia_safe::{ textlayout::{FontCollection, Pa...
use crate::{ convert::{container_style, layout_style}, css::{MatchingContext, Style}, layout::{self, LayoutEngine, LayoutResult, LayoutStyle, LayoutTree, Size}, renderer::{ContainerStyle, Rect, RenderEdge, Renderer}, Document, NodeId, NodeType, }; use skia_safe::{ textlayout::{FontCollection, Pa...
fn update(&mut self, doc: &Document, size: (i32, i32) /*, dirty_nodes */) { self.resolved_styles = HashMap::new(); self.layout_styles = HashMap::new(); self.layout_results = vec![LayoutResult::default(); 100]; self.layout_styles .insert(Document::ROOT, layout_style(&St...
fn new() -> Self { Self { resolved_styles: HashMap::new(), paragraphs: HashMap::new(), layout_styles: HashMap::new(), layout_results: Vec::new(), render_tree: Vec::new(), } }
function_block-full_function
[ { "content": "pub fn layout_style(style: &Style) -> LayoutStyle {\n\n let mut res = LayoutStyle::default();\n\n\n\n for prop in style.props() {\n\n use StyleProp::*;\n\n\n\n match prop {\n\n // size\n\n &Width(v) => res.size.width = dimension(v),\n\n &Height(...
Rust
tetris-sdl/src/draw.rs
aelred/tetris
484f4b5835dbe4d9c0973235b18279661921663f
use std::i16; use std::i32; use lazy_static::lazy_static; use sdl2::pixels::Color; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::render::Canvas; use sdl2::render::TextureQuery; use sdl2::ttf::Font; use sdl2::video::Window; use tetris::Board; use tetris::Game; use tetris::GameOver; use tetris::HighScores; use...
use std::i16; use std::i32; use lazy_static::lazy_static; use sdl2::pixels::Color; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::render::Canvas; use sdl2::render::TextureQuery; use sdl2::ttf::Font; use sdl2::video::Window; use tetris::Board; use tetris::Game; use tetris::GameOver; use tetris::HighScores; use...
} lazy_static! { static ref PREVIEW_VIEW: Rect = Rect::new(PREVIEW_X, PREVIEW_Y, PREVIEW_WIDTH, PREVIEW_HEIGHT); static ref SCORE_VIEW: Rect = Rect::new(SCORE_X, PAD, PREVIEW_WIDTH, BOARD_HEIGHT); static ref BOARD_BORDER_VIEW: Rect = Rect::new( 0, 0, BOARD_WIDTH + BOARD_BORDER * 2,...
f .score .draw(text.color(Color::RGB(255, 255, 100))) .reset_color(); } for score in lower_scores { text = score.draw(text); } text.under().offset(-SCORE_OFFSET, ...
function_block-function_prefixed
[ { "content": "pub fn draw<W: Write>(stdout: &mut W, state: &mut State) -> Result<()> {\n\n let mut buffer = io::BufWriter::new(stdout);\n\n\n\n match state {\n\n State::Title(_) => {\n\n draw_title(&mut buffer)?;\n\n }\n\n State::Play(game) => {\n\n draw_game(&mu...
Rust
jvmkill/src/jmx/memory_pool_mxbean.rs
cloudfoundry/jvmkill
d1d7f104f94227e3c97166b633ec3ddb8e6c39fe
/* * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
/* * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
}
fn get_usage() { let mut jni = MockJNI::new(); let mut seq = Sequence::new(); let c_memory_pool_mxbean = jni_type!(jclass); let i_memory_pool_mxbean = jni_type!(jobject); let m_get_usage = jni_type!(jmethodID); jni .expect_get_method() .withf_st(...
function_block-full_function
[ { "content": "#[test]\n\nfn print_memory_usage_0() {\n\n let r = Runner {\n\n class: \"org.cloudfoundry.jvmkill.ThreadExhaustion\",\n\n arguments: \"=printMemoryUsage=0\",\n\n std_out: vec!(),\n\n std_err: vec!(\"jvmkill is killing current process\"),\n\n };\n\n\n\n r.run()\...
Rust
tezos/context/src/initializer.rs
simplestaking/tezos-rs
d859dff0a8db4f5adb4885e4885217d5284f7861
use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; use ipc::IpcError; use ocaml_interop::BoxRoot; use parking_lot::RwLock; pub use tezos_context_api::ContextKvStoreConfiguration; use tezos_context_api::TezosContextTezEdgeStorageConfiguration; use thiserror::Error; use crate::kv_store::in_memo...
use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; use ipc::IpcError; use ocaml_interop::BoxRoot; use parking_lot::RwLock; pub use tezos_context_api::ContextKvStoreConfiguration; use tezos_context_api::TezosContextTezEdgeStorageConfiguration; use thiserror::Error; use crate::kv_store::in_memo...
pub fn initialize_tezedge_index( configuration: &TezosContextTezEdgeStorageConfiguration, patch_context: Option<BoxRoot<PatchContextFunction>>, ) -> Result<TezedgeIndex, IndexInitializationError> { let repository: Arc<RwLock<ContextKeyValueStore>> = match configuration.backend { ContextKvStoreConf...
let clone_repo = repository.clone(); let mut repository = repository.write(); if let Err(e) = sender.send(()) { elog!("Failed to notify main thread that repo is locked: {:?}", e); } repository.store_own_repository(clone_repo); if let Err(e) = repository.re...
function_block-function_prefix_line
[ { "content": "pub fn reload_context_readonly(context_path: String) -> Result<Persistent, Error> {\n\n let sizes_file = File::<{ TAG_SIZES }>::try_new(&context_path, true)?;\n\n let sizes = FileSizes::make_list_from_file(&sizes_file).unwrap_or_default();\n\n assert!(!sizes.is_empty(), \"sizes.db is inva...
Rust
compiler/src/scanner/mod.rs
themisir/project-e
e1f676b5a0e7dfa1091eaae6ecdf03dea2f5bf93
use crate::scanner::pos::{Pos, PosRange}; use crate::scanner::token::*; use std::borrow::Borrow; use std::fmt::{Display, Formatter}; use std::str::FromStr; pub mod pos; pub mod token; pub struct Scanner { source: String, start: usize, current: usize, start_pos: Pos, current_pos: Pos, } #[derive(D...
use crate::scanner::pos::{Pos, PosRange}; use crate::scanner::token::*; use std::borrow::Borrow; use std::fmt::{Display, Formatter}; use std::str::FromStr; pub mod pos; pub mod token; pub struct Scanner { source: String, start: usize, current: usize, start_pos: Pos, current_pos: Pos, } #[derive(D...
} else { Ok(self.make_token(TokenType::Star)) } } '"' => self.string(), _ => Err(self.token_error("Unexpected character")), } } fn identifier(&mut self) -> Result<Token, ScannerError> { loop { let...
} pub fn scan_token(&mut self) -> Result<Token, ScannerError> { self.skip_whitespace()?; self.start = self.current; self.start_pos = self.current_pos; if self.at_end() { return Ok(self.make_token(TokenType::EOF)); } let c = self.advance(); i...
random
[ { "content": "use crate::scanner::pos::*;\n\nuse phf::phf_map;\n\n\n\n#[derive(Debug, Clone)]\n\npub enum Literal {\n\n Null,\n\n Boolean(bool),\n\n Integer(i64),\n\n Float(f64),\n\n String(String),\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Token {\n\n pub token_type: TokenType,\n\n ...
Rust
src/bin/p124.rs
babygau/projecteuler-rust
0e9adcc4ef2d084b6520a63f41110c91c7165309
#![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate prime; use std::collections::BinaryHeap; use std::cmp::Ordering; use prime::PrimeSet; struct Multiple(u64, u64); impl PartialEq for...
#![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate prime; use std::collections::BinaryHeap; use std::cmp::Ordering; use prime::PrimeSet; struct Multiple(u64, u64); impl PartialEq for...
let mut v = facts.clone(); v.push(p); self.heap.push(RadValue(n * p, v, i + 1)); } if !facts.is_empty() { let last = *facts.last().unwrap(); let mut next_facts = facts.clone(); let len = n...
heap = BinaryHeap::new(); heap.push(Multiple(base, 0)); Multiples { facts: facts, heap: heap, } } } impl Iterator for Multiples { type Item = u64; #[inline] fn next(&mut self) -> Option<u64> { self.heap.pop().map(|Multiple(n, i)| { i...
random
[ { "content": "fn bench<T, F: FnOnce() -> T>(f: F) -> (u64, T) {\n\n let start_time = time::precise_time_ns();\n\n let result = f();\n\n let end_time = time::precise_time_ns();\n\n let nsec = end_time - start_time;\n\n (nsec, result)\n\n}\n\n\n", "file_path": "src/common.rs", "...
Rust
zkvm/src/prover.rs
payshares-labs/slingshot
4a9ec80a5a65f54a63626aaee4c0daad4d627029
use bulletproofs::r1cs; use bulletproofs::r1cs::ConstraintSystem; use bulletproofs::{BulletproofGens, PedersenGens}; use curve25519_dalek::ristretto::CompressedRistretto; use merlin::Transcript; use std::collections::VecDeque; use crate::constraints::Commitment; use crate::contract::ContractID; use crate::encoding::En...
use bulletproofs::r1cs; use bulletproofs::r1cs::ConstraintSystem; use bulletproofs::{BulletproofGens, PedersenGens}; use curve25519_dalek::ristretto::CompressedRistretto; use merlin::Transcript; use std::collections::VecDeque; use crate::constraints::Commitment; use crate::contract::ContractID; use crate::encoding::En...
fn next_instruction( &mut self, run: &mut Self::RunType, ) -> Result<Option<Instruction>, VMError> { Ok(run.program.pop_front()) } fn new_run(&self, data: ProgramItem) -> Result<Self::RunType, VMError> { Ok(ProverRun { program: data.to_program()?.to_vec().i...
fn process_tx_signature( &mut self, pred: Predicate, contract_id: ContractID, ) -> Result<(), VMError> { self.signtx_items.push((pred, contract_id)); Ok(()) }
function_block-full_function
[ { "content": "// Creates program: `<qty> commit <flv> commit borrow => -V +V`\n\nfn borrow_value(p: &mut Program, v: Value) {\n\n p.push(v.qty).commit().push(v.flv).commit().borrow();\n\n}\n\n\n", "file_path": "paychan/src/lib.rs", "rank": 0, "score": 185112.61987025058 }, { "content": "/...
Rust
2020/day-05-binary-boarding/src/main.rs
kenpratt/advent-of-code
0ba184df88b3ecebc3786dc9937638ff7adec6e7
use std::fs; fn main() { println!("part 1 result: {:?}", part1(&read_input_file())); println!("part 2 result: {:?}", part2(&read_input_file())); } fn read_input_file() -> String { return fs::read_to_string("input.txt").expect("Something went wrong reading the file"); } fn parse_input(input: &str) -> Vec<...
use std::fs; fn main() { println!("part 1 result: {:?}", part1(&read_input_file())); println!("part 2 result: {:?}", part2(&read_input_file())); } fn read_input_file() -> String { return fs::read_to_string("input.txt").expect("Something went wrong reading the file"); } fn parse_input(input: &str) -> Vec<...
} #[derive(Debug)] struct BinarySpacePartition { offset: usize, size: usize, } impl BinarySpacePartition { fn new(offset: usize, size: usize) -> BinarySpacePartition { return BinarySpacePartition { offset: offset, size: size, } } fn take_left(&mut self) { ...
panic!("Unexpected character") } } println!("row result: {:?}, {:?}", row_bsp, row_bsp.result()); let row = row_bsp.result().unwrap(); let mut column_bsp = BinarySpacePartition::new(0, 8); for c in input[7..10].chars() { match c { ...
function_block-function_prefix_line
[ { "content": "fn part1(input: &str, moves: usize) -> String {\n\n let mut game = Game::parse(input, None);\n\n game.run(moves);\n\n game.labels_from_reference_point(1)\n\n}\n\n\n", "file_path": "2020/day-23-crab-cups/src/main.rs", "rank": 1, "score": 458418.4665618867 }, { "content"...
Rust
proc/src/shader/glsl.rs
termhn/sierra
7a2217197fdb4825c7fb88b3d162382cb74a1bf1
use { crate::descriptors::{ buffer, parse::{FieldType, Input}, }, proc_macro2::TokenStream, sierra_types::Stage, std::fmt::Write as _, syn::spanned::Spanned as _, }; pub fn generate_glsl_shader_input(shader_input: &Input) -> TokenStream { let vertex = code_for_stage(shader_i...
use { crate::descriptors::{ buffer, parse::{FieldType, Input}, }, proc_macro2::TokenStream, sierra_types::Stage, std::fmt::Write as _, syn::spanned::Spanned as _, };
fn code_for_stage(shader_input: &ShaderInput, stage: Stage) -> TokenStream { let mut deps = Vec::new(); let mut args = Vec::new(); let code = shader_input .fields .iter() .filter(|input| input.stages.contains(&stage)) .map(|input| { let descriptor_field = quote...
pub fn generate_glsl_shader_input(shader_input: &Input) -> TokenStream { let vertex = code_for_stage(shader_input, Stage::Vertex); let tessellation_control = code_for_stage(shader_input, Stage::TessellationControl); let tessellation_evaluation = code_for_stage(shader_input, Stage::TessellationEvaluation); ...
function_block-full_function
[ { "content": "fn generate_input_impl(input: &Input) -> TokenStream {\n\n let ident = &input.item_struct.ident;\n\n let layout_ident = layout_type_name(input);\n\n let instance_ident = instance_type_name(input);\n\n\n\n quote::quote! {\n\n impl ::sierra::DescriptorsInput for #ident {\n\n ...
Rust
src/snmp_usm/src/pos_finder.rs
afics/modern_snmp
84cbae0ef8d18354a4d9a5b8ca270c3536d02555
use crate::{SecurityError, SecurityResult}; use std::ops::Range; use yasna::{tags, Tag, TagClass}; const TAG_CLASSES: [TagClass; 4] = [ TagClass::Universal, TagClass::Application, TagClass::ContextSpecific, TagClass::Private, ]; const TAG_CLASS_POS: u8 = 6; const TAG_TYPE_POS: u8 = 5; const TAG_NUM_MA...
use crate::{SecurityError, SecurityResult}; use std::ops::Range; use yasna::{tags, Tag, TagClass}; const TAG_CLASSES: [TagClass; 4] = [ TagClass::Universal, TagClass::Application, TagClass::ContextSpecific, TagClass::Private, ]; const TAG_CLASS_POS: u8 = 6; const TAG_TYPE_POS: u8 = 5; const TAG_NUM_MA...
}
fn it_returns_error_when_reading_end_of_buf() { let buf = []; let mut finder = PosFinder::new(&buf); let result = finder.read_u8(); assert_eq!(result, Err(SecurityError::MalformedMsg)); }
function_block-full_function
[ { "content": "#[test]\n\nfn it_decodes_scoped_pdu_with_extra_bytes_at_the_end() -> MsgProcessingResult<()> {\n\n let encoded_scoped_pdu = vec![\n\n 0x30, 0x33, 0x04, 0x11, 0x80, 0x00, 0x1F, 0x88, 0x80, 0xFA, 0xA8, 0x11, 0x60, 0x0F, 0xA2,\n\n 0xC5, 0x5E, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xA0,...
Rust
src/ws/responses.rs
Ungutvecklare/nginx-obs-automatic-low-bitrate-switching
89d970e6fba883aabce692ba29206d3bff474402
use serde::Serialize; use crate::config; #[derive(Serialize)] pub struct ResponseMessage<'a> { #[serde(flatten)] pub response: Response<'a>, #[serde(skip_serializing_if = "Option::is_none")] pub nonce: Option<String>, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] #[serde(tag = "type...
use serde::Serialize; use crate::config; #[derive(Serialize)] pub struct ResponseMessage<'a> { #[serde(flatten)] pub response: Response<'a>, #[serde(skip_serializing_if = "Option::is_none")] pub nonce: Option<String>, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] #[serde(tag = "type...
#[test] fn error_response_with_reason() { let message = ResponseMessage { response: Response::Error(ResponseError::Deserialize(Some( "Couldn't deserialize...".to_string(), ))), nonce: None, }; let json = serde_json::to_string(&messag...
fn error_response() { let message = ResponseMessage { response: Response::Error(ResponseError::AuthFailed), nonce: Some("1".to_string()), }; let json = serde_json::to_string(&message).unwrap(); println!("{}", json); let expected = r#"{"type":"error","dat...
function_block-full_function
[]
Rust
src/solutions/year2020/day16.rs
enigma/aoc
dac9598447b9c7637c99a75b85bf4d58e4c8d7e7
use super::*; use std::collections::{BTreeMap, BTreeSet}; use std::ops::RangeInclusive; type Input = String; pub fn part1( _my_ticket: &Vec<usize>, tickets: &Vec<Vec<usize>>, rules: &BTreeMap<&str, (RangeInclusive<usize>, RangeInclusive<usize>)>, ) -> usize { tickets .iter() .flatten...
use super::*; use std::collections::{BTreeMap, BTreeSet}; use std::ops::RangeInclusive; type Input = String; pub fn part1( _my_ticket: &Vec<usize>, tickets: &Vec<Vec<usize>>, rules: &BTreeMap<&str, (RangeInclusive<usize>, RangeInclusive<usize>)>, ) -> usize { tickets .iter() .flatten...
.entry(rule_type) .or_insert(BTreeSet::new()) .insert(col); } } } while !candidates.iter().any(|(_, v)| v.len() > 1) { let sets = candidates.clone(); for (&k1, v1) in sets { if v1.len() == 1 { ...
e]> = Vec::new(); for ticket in tickets { let mut pass = false; for field in ticket { pass = false; for (range1, range2) in rules.values() { if range1.contains(&field) || range2.contains(&field) { pass = true; break; ...
random
[ { "content": "pub fn part2(_x: &ParsedData) -> String {\n\n \"25!\".to_string()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn example() {\n\n let str_input = \"1=-0-2\n\n12111\n\n2=0=\n\n21\n\n2=01\n\n111\n\n20012\n\n112\n\n1=-1=\n\n1-12\n", "file_path":...