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/parser/statements/switch.rs
mozilla/rust-cpp-parser
24b06d1c481efa2265c99f78a741fd617541b98e
use std::rc::Rc; use termcolor::StandardStreamLock; use super::{Statement, StatementParser}; use crate::lexer::lexer::{TLexer, Token}; use crate::parser::attributes::Attributes; use crate::parser::declarations::{DeclOrExpr, DeclOrExprParser}; use crate::parser::dump::Dump; use crate::parser::errors::ParserError; use...
use std::rc::Rc; use termcolor::StandardStreamLock; use super::{Statement, StatementParser}; use crate::lexer::lexer::{TLexer, Token}; use crate::parser::attributes::Attributes; use crate::parser::declarations::{DeclOrExpr, DeclOrExprParser}; use crate::parser::dump::Dump; use crate::parser::errors::ParserError; use...
ault", prefix, last, stdout, attributes); } } pub struct DefaultStmtParser<'a, L: TLexer> { lexer: &'a mut L, } impl<'a, L: TLexer> DefaultStmtParser<'a, L> { pub(super) fn new(lexer: &'a mut L) -> Self { Self { lexer } } pub(super) fn parse( self, attributes: Option<Attri...
tion, cases); } } pub struct SwitchStmtParser<'a, L: TLexer> { lexer: &'a mut L, } impl<'a, L: TLexer> SwitchStmtParser<'a, L> { pub(super) fn new(lexer: &'a mut L) -> Self { Self { lexer } } pub(super) fn parse( self, attributes: Option<Attributes>, context: &mut ...
random
[ { "content": "pub fn extend_with_u32(buf: &mut Vec<u8>, n: u32) {\n\n // TODO: can be optimized using \"Three Optimization Tips for C++\" talk\n\n let mut n = n;\n\n let mut s = vec![0; 11];\n\n let mut i = 10;\n\n loop {\n\n *s.get_mut(i).unwrap() = (n % 10) as u8 + b'0';\n\n if n ...
Rust
erc1155/src/lib.rs
coderighter2/whnft
802881ff910d42717a7840e3dc9d92c9235d88ef
#![warn(missing_docs)] #![no_std] extern crate alloc; mod address; mod balances; pub mod constants; mod detail; pub mod entry_points; mod error; mod operators; mod total_supply; use alloc::string::{String, ToString}; use alloc::vec::Vec; use once_cell::unsync::OnceCell; use casper_contract::{ contract_api::{r...
#![warn(missing_docs)] #![no_std] extern crate alloc; mod address; mod balances; pub mod constants; mod detail; pub mod entry_points; mod error; mod operators; mod total_supply; use alloc::string::{String, ToString}; use alloc::vec::Vec; use once_cell::unsync::OnceCell; use casper_contract::{ contract_api::{r...
#[doc(hidden)] pub fn install_custom( uri: String, contract_key_name: &str, entry_points: EntryPoints, ) -> Result<ERC1155, Error> { let balances_uref = storage::new_dictionary(BALANCES_KEY_NAME).unwrap_or_revert(); let operators_u...
y.checked_sub(amount).ok_or(Error::Overflow)? }; self.write_balance(owner, &id, new_balance); self.write_total_supply(&id, new_total_supply); Ok(()) }
function_block-function_prefixed
[ { "content": "#[inline]\n\nfn make_dictionary_item_key(id: &str, account: Address) -> String {\n\n let mut preimage = Vec::new();\n\n preimage.append(&mut id.to_bytes().unwrap_or_revert());\n\n preimage.append(&mut account.to_bytes().unwrap_or_revert());\n\n\n\n let key_bytes = runtime::blake2b(&pre...
Rust
tests/object_type.rs
christoph-heiss/rust-oracle
50a776444a826712363f8869bfb090c490d74313
mod common; use oracle::sql_type::{ObjectType, OracleType}; use oracle::{Result, Version}; #[test] fn invalid_obj() -> Result<()> { let conn = common::connect()?; let err = conn.object_type("DUMMY_OBJECT").unwrap_err(); if Version::client()?.major() >= 12 { assert_eq!( err.to_string(...
mod common; use oracle::sql_type::{ObjectType, OracleType}; use oracle::{Result, Version}; #[test] fn invalid_obj() -> Result<()> { let conn = common::connect()?; let err = conn.object_type("DUMMY_OBJECT").unwrap_err(); if Version::client()?.major() >= 12 { assert_eq!( err.to_string(...
ssert_eq!(attrtype.attributes().len(), 0); } _ => assert!(false), } } fn assert_udt_subobject(oratype: &OracleType) { let username = common::main_user().to_uppercase(); match *oratype { OracleType::Object(ref attrtype) => { assert_eq!(attrtype.schema(), username); ...
ype("UDT_OBJECTDATATYPES")?; assert_udt_objectdatatypes(&objtype); Ok(()) } #[test] fn udt_objectdatatypes_in_query() -> Result<()> { let conn = common::connect()?; let mut stmt = conn.prepare("select ObjectCol from TestObjectDataTypes where 1 = 0", &[])?; let rows = stmt.query(&[])?; match ro...
random
[]
Rust
src/lib.rs
magiclen/rocket-etagged-file-response
6fddeecdbaa907c03cbc0e4547bf7746381146f5
extern crate mime_guess; extern crate crc_any; pub extern crate rocket_etag_if_none_match; extern crate rocket; use std::sync::Mutex; use std::collections::HashMap; use std::path::Path; use std::fs::{self, File}; use std::io::{self, ErrorKind, Read, BufReader}; use mime_guess::get_mime_type_str; use crc_any::CRC...
extern crate mime_guess; extern crate crc_any; pub extern crate rocket_etag_if_none_match; extern crate rocket; use std::sync::Mutex; use std::collections::HashMap; use std::path::Path; use std::fs::{self, File}; use std::io::{self, ErrorKind, Read, BufReader}; use mime_guess::get_mime_type_str; use crc_any::CRC...
pub fn new_etag_map() -> EtagMap { Mutex::from(HashMap::<String, String>::new()) } }
let path_str = path.to_str().unwrap(); let etag = etag_map.lock().unwrap().get(path_str).map(|etag| { etag.clone() }); let etag = match etag { Some(etag) => etag, None => { let mut crc64ecma = CRC::crc64ecma(); let mut buffer = [0u8; FILE_RESPON...
function_block-function_prefix_line
[ { "content": "Etagged File Response for Rocket Framework\n\n====================\n\n\n\nThis crate was deprecated, use `rocket-etagged-raw-response` instead.\n\n\n\nhttps://crates.io/crates/rocket-etagged-raw-response\n\n\n\n## License\n\n\n", "file_path": "README.md", "rank": 0, "score": 16299.1628...
Rust
src/main.rs
Celti/zero-rs
bc2d872c008c8c6fea0859179ed86837ff12b868
#![feature(int_to_from_bytes)] #![feature(tool_lints)] #![allow(proc_macro_derive_resolution_fallback)] #[macro_use] extern crate diesel; use bytes::buf::Buf; use chrono::{Duration, Utc}; use crate::db::Database; use crate::model::Item; use lazy_static::lazy_static; use mime::{Mime, BOUNDARY}; use multipart::server:...
#![feature(int_to_from_bytes)] #![feature(tool_lints)] #![allow(proc_macro_derive_resolution_fallback)] #[macro_use] extern crate diesel; use bytes::buf::Buf; use chrono::{Duration, Utc}; use crate::db::Database; use crate::model::Item; use lazy_static::lazy_static; use mime::{Mime, BOUNDARY}; use multipart::server:...
let sockets = std::env::var("LISTEN_ADDR") .expect("LISTEN_ADDR") .to_socket_addrs() .expect("parse socket addresses"); tokio::run(future::lazy(move || { tokio::spawn(timer); sockets.for_each(|sock| { let (addr, fut) = warp::serve(routes).bind_ephemeral(sock...
r = { Interval::new_interval(StdDuration::from_secs(60)) .map_err(|e| log::error!("server error: {}", e)) .for_each(move |_| { match DB.sunset_items() { Ok(0) => (), Ok(1) => log::info!("sunsetted 1 paste"), Ok(c...
random
[ { "content": "CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$\n\nBEGIN\n\n IF (\n\n NEW IS DISTINCT FROM OLD AND\n\n NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at\n\n ) THEN\n\n NEW.updated_at := current_timestamp;\n\n END IF;\n\n RETURN NEW;\n\nEND...
Rust
fuzz/fuzz_targets/sg_set.rs
meteor-lws/scapegoat
70d1b1ae8924186e7b02fcb9752340afbdd4d1c3
#![no_main] #![feature(map_first_last)] use std::collections::BTreeSet; use std::fmt::Debug; use std::iter::FromIterator; use libfuzzer_sys::{arbitrary::Arbitrary, fuzz_target}; use scapegoat::SgSet; const CAPACITY: usize = 2048; #[derive(Arbitrary, Debug)] enum SetMethod<T: Ord + Debug> { Append { other:...
#![no_main] #![feature(map_first_last)] use std::collections::BTreeSet; use std::fmt::Debug; use std::iter::FromIterator; use libfuzzer_sys::{arbitrary::Arbitrary, fuzz_target}; use scapegoat::SgSet; const CAPACITY: usize = 2048; #[derive(Arbitrary, Debug)] enum SetMethod<T: Ord + Debug> { Append { other:...
d { other } => { if other.len() > CAPACITY { continue; } let sg_set_new = SgSet::<_, CAPACITY>::from_iter(other.clone().into_iter()); let bt_set_new = BTreeSet::from_iter(other.into_iter()); assert_eq!(sg_set.cmp(&sg_s...
continue; } let sg_diff: Vec<_> = sg_set .difference(&SgSet::from_iter(other.clone())) .cloned() .collect(); let bt_diff: Vec<_> = bt_set .difference(&BTreeSet::from_iter(other)) ...
random
[]
Rust
examples/generative_design/shape/p_2_1_1_03.rs
freesig/nannou
fcd857d4ced73c8716e7641c59a72210ece95ad6
/** * changing number, color and strokeweight on diagonals in a grid * * MOUSE * position x : diagonal strokeweight * position y : number diagonals * left click : new random layout * * KEYS * s : save png * 1 : color left diagonal * 2 ...
/** * changing number, color and strokeweight on diagonals in a grid * * MOUSE * position x : diagonal strokeweight * position y : number diagonals * left click : new random layout * * KEYS * s : save png * 1 : color left diagonal * 2 ...
draw.line() .color(model.color_left) .weight(mx / 15.0) .points( pt2(pos_x + (win.w() / model.tile_count as f32) / 2.0, pos_y), pt2( pos_x + (win.w() / model.tile_count as f32), ...
ey_released) .build() .unwrap(); let alpha_left = 0.0; let alpha_right = 1.0; Model { tile_count: 1, act_random_seed: 0, color_left: hsva(0.88, 1.0, 0.77, alpha_left), color_right: hsva(0.0, 0.0, 0.0, alpha_right), alpha_left, alpha_right, ...
random
[ { "content": "fn key_pressed(_app: &App, model: &mut Model, key: Key) {\n\n match key {\n\n Key::Key1 => {\n\n model.segment_count = 360;\n\n }\n\n Key::Key2 => {\n\n model.segment_count = 45;\n\n }\n\n Key::Key3 => {\n\n model.segment_count...
Rust
thrussh-keys/src/key.rs
jdelgadoalfonso/thrussh
0e0e0bf13de76ae5cba24a95ce2fbbdc4db18a19
use cryptovec::CryptoVec; use Error; use encoding::{Encoding, Reader}; use std; use openssl; use sodium; use encoding; pub use signature::*; use openssl::pkey::{Public, Private}; pub mod ed25519 { pub use sodium::ed25519::{PublicKey, SecretKey, keypair, verify_detached, sign_detached}; } #[derive(Debug, Partial...
use cryptovec::CryptoVec; use Error; use encoding::{Encoding, Reader}; use std; use openssl; use sodium; use encoding; pub use signature::*; use openssl::pkey::{Public, Private}; pub mod ed25519 { pub use sodium::ed25519::{PublicKey, SecretKey, keypair, verify_detached, sign_detached}; } #[derive(Debug, Partial...
, hash: SignatureHash::SHA1, }); } Err(Error::CouldNotReadKey) }
OpenSSLPKey(PKey::from_rsa( Rsa::from_public_components( BigNum::from_slice(n)?, BigNum::from_slice(e)?, )? )?)
call_expression
[ { "content": "fn decode_rsa(secret: &[u8]) -> Result<key::KeyPair, Error> {\n\n Ok(key::KeyPair::RSA {\n\n key: Rsa::private_key_from_der(secret)?,\n\n hash: key::SignatureHash::SHA2_256\n\n })\n\n}\n\n\n", "file_path": "thrussh-keys/src/format/mod.rs", "rank": 1, "score": 361349...
Rust
crates/mun_runtime/src/adt.rs
redchew-fork/mun
5953a7b4288ae6ee62e3400ce9a8ae8023ff0e79
use crate::garbage_collector::{GcPtr, GcRootPtr, UnsafeTypeInfo}; use crate::{ marshal::Marshal, reflection::{ equals_argument_type, equals_return_type, ArgumentReflection, ReturnTypeReflection, }, Runtime, }; use memory::gc::{GcRuntime, HasIndirectionPtr}; use once_cell::sync::OnceCell; use std...
use crate::garbage_collector::{GcPtr, GcRootPtr, UnsafeTypeInfo}; use crate::{ marshal::Marshal, reflection::{ equals_argument_type, equals_return_type, ArgumentReflection, ReturnTypeReflection, }, Runtime, }; use memory::gc::{GcRuntime, HasIndirectionPtr}; use once_cell::sync::OnceCell; use std...
unsafe fn field_offset_unchecked<T>( &self, struct_info: &abi::StructInfo, field_idx: usize, ) -> NonNull<T> { let offset = *struct_info.field_offsets().get_unchecked(field_idx); NonNull::new_unchecked(self.raw.get_ptr().add(offset as u...
pub fn type_info(&self) -> &abi::TypeInfo { unsafe { &*self.runtime.gc.ptr_type(self.raw.0).into_inner().as_ptr() } }
function_block-full_function
[ { "content": "/// Shortcut function for creating new files.\n\npub fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> anyhow::Result<()> {\n\n let path = path.as_ref();\n\n fs::write(path, contents.as_ref()).map_err(|_| anyhow!(\"failed to write `{}`\", path.display()))\n\n}\n", "file_pat...
Rust
libsplinter/src/admin/client/reqwest.rs
rbuysse/splinter
1864eb39be8c44f910dc0ce79693fea7f136fd5a
use reqwest::{blocking::Client, header, StatusCode}; use crate::error::InternalError; use crate::rest_api::SPLINTER_PROTOCOL_VERSION; use super::{AdminServiceClient, CircuitListSlice, CircuitSlice, ProposalListSlice, ProposalSlice}; const PAGING_LIMIT: u32 = 100; #[derive(Deserialize)] struct ServerError { pu...
use reqwest::{blocking::Client, header, StatusCode}; use crate::error::InternalError; use crate::rest_api::SPLINTER_PROTOCOL_VERSION; use super::{AdminServiceClient, CircuitListSlice, CircuitSlice, ProposalListSlice, ProposalSlice}; const PAGING_LIMIT: u32 = 100; #[derive(Deserialize)] struct ServerError { pu...
res.json::<ProposalSlice>().map(Some).map_err(|_| { InternalError::with_message( "Request was successful, but received an invalid response".into(), ) }) } else if status == StatusCode::NOT_FOUND { ...
&str) -> Result<Option<ProposalSlice>, InternalError> { let request = Client::new() .get(&format!("{}/admin/proposals/{}", self.url, circuit_id)) .header("SplinterProtocolVersion", SPLINTER_PROTOCOL_VERSION) .header("Authorization", &self.auth); request ....
function_block-random_span
[ { "content": "pub fn require_header(header_key: &str, request: &HttpRequest) -> Result<String, RequestError> {\n\n let header = request.headers().get(header_key).ok_or_else(|| {\n\n RequestError::MissingHeader(format!(\"Header {} not included in Request\", header_key))\n\n })?;\n\n Ok(header\n\n...
Rust
rs/consensus/src/ecdsa/payload_verifier.rs
MikeOwino/ic
84eeabcdead353e0f59e377c02ad9c2908c81930
#![allow(unused_imports)] use super::payload_builder::{EcdsaPayloadError, InvalidChainCacheError, MembershipError}; use super::utils::EcdsaBlockReaderImpl; use crate::consensus::{ crypto::ConsensusCrypto, metrics::EcdsaPayloadMetrics, pool_reader::PoolReader, }; use crate::ecdsa::payload_builder::{ block_chai...
#![allow(unused_imports)] use super::payload_builder::{EcdsaPayloadError, InvalidChainCacheError, MembershipError}; use super::utils::EcdsaBlockReaderImpl; use crate::consensus::{ crypto::ConsensusCrypto, metrics::EcdsaPayloadMetrics, pool_reader::PoolReader, }; use crate::ecdsa::payload_builder::{ block_chai...
} } pub fn validate_summary_payload( subnet_id: SubnetId, registry_client: &dyn RegistryClient, pool_reader: &PoolReader<'_>, context: &ValidationContext, parent_block: &Block, summary_payload: Option<&ecdsa::EcdsaPayload>, ) -> ValidationResult<EcdsaValidationError> { let height = par...
validate_data_payload( subnet_id, registry_client, crypto, pool_reader, state_manager, context, parent_block, payload.as_data().ecdsa.as_ref(), )
call_expression
[ { "content": "/// Produces an arbitrary response [`Payload`].\n\npub fn response_payload() -> impl Strategy<Value = Payload> {\n\n prop_oneof![\n\n // Data payload.\n\n prop::collection::vec(any::<u8>(), 0..16).prop_flat_map(|data| Just(Payload::Data(data))),\n\n // Reject payload.\n\n ...
Rust
src/linalg/lu.rs
dfarnham/nalgebra
79ef862fe9bd5f6d97a864c36274e0eb69468025
#[cfg(feature = "serde-serialize-no-std")] use serde::{Deserialize, Serialize}; use crate::allocator::{Allocator, Reallocator}; use crate::base::{DefaultAllocator, Matrix, OMatrix, Scalar}; use crate::constraint::{SameNumberOfRows, ShapeConstraint}; use crate::dimension::{Dim, DimMin, DimMinimum}; use crate::storage::...
#[cfg(feature = "serde-serialize-no-std")] use serde::{Deserialize, Serialize}; use crate::allocator::{Allocator, Reallocator}; use crate::base::{DefaultAllocator, Matrix, OMatrix, Scalar}; use crate::constraint::{SameNumberOfRows, ShapeConstraint}; use crate::dimension::{Dim, DimMin, DimMinimum}; use crate::storage::...
al(T::one()); m } fn l_unpack_with_p( self, ) -> ( OMatrix<T, R, DimMinimum<R, C>>, PermutationSequence<DimMinimum<R, C>>, ) where DefaultAllocator: Reallocator<T, R, C, R, DimMinimum<R, C>>, { let (nrows, ncols) = self.lu.data.shape(); ...
ut m = self.lu.columns_generic(0, nrows.min(ncols)).into_owned(); m.fill_upper_triangle(T::zero(), 1); m.fill_diagon
function_block-random_span
[]
Rust
src/librustc_trans/monomorphize.rs
killerswan/rust
e703b33e3e03d1078c8825e1f64ecfb45884f5cb
use abi::Abi; use common::*; use glue; use rustc::hir::def_id::DefId; use rustc::infer::TransNormalize; use rustc::middle::lang_items::DropInPlaceFnLangItem; use rustc::traits::{self, SelectionContext, Reveal}; use rustc::ty::adjustment::CustomCoerceUnsized; use rustc::ty::fold::{TypeFolder, TypeFoldable}; use rustc...
use abi::Abi; use common::*; use glue; use rustc::hir::def_id::DefId; use rustc::infer::TransNormalize; use rustc::middle::lang_items::DropInPlaceFnLangItem; use rustc::traits::{self, SelectionContext, Reveal}; use rustc::ty::adjustment::CustomCoerceUnsized; use rustc::ty::fold::{TypeFolder, TypeFoldable}; use rustc...
pub fn resolve_drop_in_place<'a, 'tcx>( scx: &SharedCrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> { let def_id = scx.tcx().require_lang_item(DropInPlaceFnLangItem); let substs = scx.tcx().intern_substs(&[Kind::from(ty)]); resolve(scx, def_id, substs) } pub fn custom_coerce_unsiz...
pub fn resolve<'a, 'tcx>( scx: &SharedCrateContext<'a, 'tcx>, def_id: DefId, substs: &'tcx Substs<'tcx> ) -> Instance<'tcx> { debug!("resolve(def_id={:?}, substs={:?})", def_id, substs); let result = if let Some(trait_def_id) = scx.tcx().trait_of_item(def_id) { debug!(" => associa...
function_block-full_function
[]
Rust
src/main.rs
Turbo87/united-flarmnet
6eee40d8ad7fb96d21d0e94779f46ae9c96b3704
#[macro_use] extern crate tracing; use std::collections::HashMap; use std::fs::File; use std::io::BufWriter; use std::path::PathBuf; use crate::sanitize::{sanitize_record_for_lx, sanitize_record_for_xcsoar}; use tracing_subscriber::fmt::Subscriber; use tracing_subscriber::EnvFilter; mod cache; mod flarmnet; mod ogn;...
#[macro_use] extern crate tracing; use std::collections::HashMap; use std::fs::File; use std::io::BufWriter; use std::path::PathBuf; use crate::sanitize::{sanitize_record_for_lx, sanitize_record_for_xcsoar}; use tracing_subscriber::fmt::Subscriber; use tracing_subscriber::EnvFilter; mod cache; mod flarmnet; mod ogn;...
le { version: flarmnet_file.version, records: xcsoar_records, }; writer.write(&xcsoar_file)?; info!("writing united-lx.fln…"); let lx_path = PathBuf::from("united-lx.fln"); let lx_file = File::create(lx_path)?; let mut lx_writer = ::flarmnet::lx::Writer::new(BufWriter::new(lx_fi...
ion = record.registration; } if existing_record.plane_type.is_empty() { existing_record.plane_type = record.plane_type; } } } else { merged.insert(id, record); } } for (id, user) in weglide_users { ...
random
[ { "content": "pub fn sanitize_record_for_xcsoar(record: &Record) -> Record {\n\n Record {\n\n flarm_id: sanitize_for_xcsoar(&record.flarm_id),\n\n pilot_name: sanitize_for_xcsoar(&record.pilot_name),\n\n airfield: sanitize_for_xcsoar(&record.airfield),\n\n plane_type: sanitize_for...
Rust
src/server.rs
NLnetLabs/secure-routing-stats
3d1861826bd3538d22db58e8834d86f8267194c2
use crate::announcements::Announcements; use crate::vrps::Vrps; use actix_web::http::Method; use actix_web::http::StatusCode; use actix_web::pred; use actix_web::server; use actix_web::App; use actix_web::HttpResponse; use announcements; use clap::ArgMatches; use delegations; use delegations::IpDelegations; use repor...
use crate::announcements::Announcements; use crate::vrps::Vrps; use actix_web::http::Method; use actix_web::http::StatusCode; use actix_web::pred; use actix_web::server; use actix_web::App; use actix_web::HttpResponse; use announcements; use clap::ArgMatches; use delegations; use delegations::IpDelegations; use repor...
fn p404(_req: &HttpRequest) -> HttpResponse { HttpResponse::build(StatusCode::NOT_FOUND).body(NOT_FOUND) } fn details(req: &HttpRequest) -> HttpResponse { let server: &Arc<StatsServer> = req.state(); let limits = match req.query().get("scope") { None => ScopeLimits::e...
0); server .bind(address) .unwrap_or_else(|_| panic!("Cannot bind to: {}", address)) .shutdown_timeout(0) .run(); Ok(()) }
function_block-function_prefixed
[ { "content": "#[derive(Clone, Debug, Default, Serialize)]\n\nstruct AnnouncementsResult {\n\n valid: usize,\n\n invalid_asn: usize,\n\n invalid_length: usize,\n\n not_found: usize,\n\n invalids: Vec<ValidatedAnnouncement>,\n\n}\n\n\n\nimpl AnnouncementsResult {\n\n pub fn add(&mut self, ann: V...
Rust
2020/day-08-handheld-halting/src/main.rs
kenpratt/advent-of-code
0ba184df88b3ecebc3786dc9937638ff7adec6e7
use std::collections::HashSet; use std::fs; use regex::Regex; 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 ...
use std::collections::HashSet; use std::fs; use regex::Regex; 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 ...
} } fn execute_current_instruction(&mut self) { match self.instructions[self.instruction_pointer] { Instruction::Nop(_) => { self.instruction_pointer += 1; }, Instruction::Acc(argument) => { self.accumulator += argument; ...
if seen_instructions.contains(&self.instruction_pointer) { return (self.accumulator, Termination::InfiniteLoop); } else { seen_instructions.insert(self.instruction_pointer); self.execute_current_instruction(); }
if_condition
[ { "content": "fn part2(input: &str) -> Result<usize, String> {\n\n let passes = parse_input(input);\n\n\n\n let mut seat_ids: Vec<usize> = passes.iter().map(|p| p.seat_id).collect();\n\n seat_ids.sort();\n\n\n\n for i in 0..(seat_ids.len() - 2) {\n\n let seat1 = seat_ids[i];\n\n let se...
Rust
evm-adapters/src/evmodin.rs
jparklev/dapptools-rs
cf85b2b01973bfb39a828c59dffe2c5c03b7bb1e
use crate::Evm; use ethers::types::{Address, Bytes, U256}; use evmodin::{tracing::Tracer, AnalyzedCode, CallKind, Host, Message, Revision, StatusCode}; use eyre::Result; #[derive(Clone, Debug)] pub struct EvmOdin<S, T> { pub host: S, pub gas_limit: u64, pub call_kind: Option<CallKind>, pub revision:...
use crate::Evm; use ethers::types::{Address, Bytes, U256}; use evmodin::{tracing::Tracer, AnalyzedCode, CallKind, Host, Message, Revision, StatusCode}; use eyre::Result; #[derive(Clone, Debug)] pub struct EvmOdin<S, T> { pub host: S, pub gas_limit: u64, pub call_kind: Option<CallKind>, pub revision:...
#[test] #[ignore] fn evmodin_can_call_solidity_unit_test() { let revision = Revision::Istanbul; let compiled = COMPILED.get("Greeter").expect("could not find contract"); let host = MockedHost::default(); let gas_limit = 12_000_000; let evm = EvmOdin::new(host, ...
let host = MockedHost::default(); let gas_limit = 12_000_000; let evm = EvmOdin::new(host, gas_limit, revision, NoopTracer); can_call_vm_directly(evm, compiled); }
function_block-function_prefix_line
[ { "content": "// TODO: Any reason this should be an async trait?\n\n/// Low-level abstraction layer for interfacing with various EVMs. Once instantiated, one\n\n/// only needs to specify the transaction parameters\n\npub trait Evm<State> {\n\n /// The returned reason type from an EVM (Success / Revert/ Stopp...
Rust
evalbotlib/src/eval.rs
angelsl/rs-evalbot
7705d641a1279fd8f84abac77a03e7c37f92defa
use std::io::Cursor; use std::os::unix::process::ExitStatusExt; use std::process::Stdio; use std::sync::Arc; use std::time::Duration; use bytes::{Buf, BufMut, BytesMut}; use log::{debug, error, trace}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::UnixStream; use tokio::process::Command; use tokio::tim...
use std::io::Cursor; use std::os::unix::process::ExitStatusExt; use std::process::Stdio; use std::sync::Arc; use std::time::Duration; use bytes::{Buf, BufMut, BytesMut}; use log::{debug, error, trace}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::UnixStream; use tokio::process::Command; use tokio::
\n", code)); } else if let Some(code) = output.status.signal() { r.push_str(&format!( "signalled with {} ({})\n", strsig(code), strsigabbrev(code) )); } else { r.push_str("exited with unkn...
time; use crate::{ExecBackend, UnixSocketBackend}; fn strsig(sig: i32) -> &'static str { match sig { 1 => "Hangup", 2 => "Interrupt", 3 => "Quit", 4 => "Illegal instruction", 5 => "Trace/breakpoint trap", 6 => "Aborted", 7 => "Bus error", 8 => "Float...
random
[ { "content": " stream\n\n .timeout(Duration::from_secs(35))\n\n .error_delay(Duration::from_secs(30));\n\n while let Some(update) = stream.next().await {\n\n match update {\n\n Ok(update) => {\n\n tokio::spawn(handle_update(update,...
Rust
lumen_runtime/src/otp/erlang/apply_3.rs
xtian/lumen
20a3095697ce05c860f825ae573fa4e70e740026
#[cfg(test)] use std::convert::TryInto; use std::sync::Arc; use liblumen_core::locks::RwLock; #[cfg(test)] use liblumen_alloc::erts::exception::runtime; use liblumen_alloc::erts::exception::system::Alloc; #[cfg(not(test))] use liblumen_alloc::erts::exception::Exception; use liblumen_alloc::erts::process::code::stack:...
#[cfg(test)] use std::convert::TryInto; use std::sync::Arc; use liblumen_core::locks::RwLock; #[cfg(test)] use liblumen_alloc::erts::exception::runtime; use liblumen_alloc::erts::exception::system::Alloc; #[cfg(not(test))] use liblumen_alloc::erts::exception::Exception; use liblumen_alloc::erts::process::code::stack:...
fn frame() -> Frame { Frame::new(module_function_arity(), get_code()) } fn function() -> Atom { Atom::try_from_str("apply").unwrap() } pub(crate) fn module_function_arity() -> Arc<ModuleFunctionArity> { Arc::new(ModuleFunctionArity { module: super::module(), function: function(), ...
match module_atom.name() { "erlang" => match function_atom.name() { "+" => match arity { 1 => { erlang::number_or_badarith_1::place_frame_with_arguments( arc_process, Placement::Replace, argum...
function_block-function_prefix_line
[ { "content": "pub fn closure(process: &Process, module: Atom, function: Atom, arity: u8) -> Term {\n\n let creator = process.pid_term();\n\n let module_function_arity = Arc::new(ModuleFunctionArity {\n\n module,\n\n function,\n\n arity,\n\n });\n\n let code = |arc_process: &Arc<...
Rust
src/parser/parser.rs
pathivu/pathivu
09ac381630dceb578b8abc39a67030c521e404ce
/* * Copyright 2019 Balaji Jinnah and Contributors * * 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 applicabl...
/* * Copyright 2019 Balaji Jinnah and Contributors * * 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/lic
)); } parse_distinct(inner, &mut query); } Rule::average => { if query.is_aggregation_exist() { return Err(format_err!( "{}", "Only one aggregation is supported. At least for n...
enses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitatio...
random
[ { "content": "/*\n\n * Copyright 2019 Balaji Jinnah and Contributors\n\n *\n\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n\n * you may not use this file except in compliance with the License.\n\n * You may obtain a copy of the License at\n\n *\n\n * http://www.apache.org/licenses/L...
Rust
bindings/wasm/src/author/authorw.rs
Temple-of-The-Absolute-Eternal/streams
ffa921234a8c24aa82a9a61ecd1c6808bebaeaaf
use core::convert::TryInto as _; use wasm_bindgen::prelude::*; use js_sys::Array; use crate::types::PskIds as PskIdsW; use crate::types::PublicKeys as PublicKeysW; use crate::types::*; use iota_streams::{ app::transport::{ TransportOptions, tangle::{ client::Client, PAYLOAD...
use core::convert::TryInto as _; use wasm_bindgen::prelude::*; use js_sys::Array; use crate::types::PskIds as PskIdsW; use crate::types::PublicKeys as PublicKeysW; use crate::types::*; use iota_streams::{ app::transport::{ TransportOptions, tangle::{ client::Client, PAYLOAD...
#[wasm_bindgen(catch)] pub fn is_multi_branching(&self) -> Result<bool> { Ok(self.author.borrow_mut().is_multi_branching()) } #[wasm_bindgen(catch)] pub fn get_public_key(&self) -> Result<String> { Ok(hex::encode(self.author.borrow_mut().get_pk().to_bytes())) } #[wasm_bin...
pub fn channel_address(&self) -> Result<String> { to_result(self.author.borrow_mut().channel_address() .map(|addr| addr.to_string()) .ok_or("channel not created") ) }
function_block-full_function
[ { "content": "pub fn a_fetch_next_messages<T: Transport>(author: &mut Author<T>)\n\n{\n\n let mut exists = true;\n\n\n\n while exists {\n\n let msgs = author.fetch_next_msgs();\n\n exists = false;\n\n\n\n for msg in msgs {\n\n println!(\"Message exists at {}... \", &msg.lin...
Rust
src/scene.rs
mario007/sunray
9b73686c7c20c838e73f4292f9a4c2965d383ca9
use std::sync::Arc; use crate::matrix::Matrix4x4; use crate::camera::{Camera, PerspectiveCamera}; use crate::sampler::SamplerType; use crate::buffers::ColorBuffer; use crate::shapes::{Sphere, ShapeInstance, TransformShape, Mesh, ShapeType}; use crate::materials::Material; use crate::lights::Light; use crate::scene_dat...
use std::sync::Arc; use crate::matrix::Matrix4x4; use crate::camera::{Camera, PerspectiveCamera}; use crate::sampler::SamplerType; use crate::buffers::ColorBuffer; use crate::shapes::{Sphere, ShapeInstance, TransformShape, Mesh, ShapeType}; use crate::materials::Material; use crate::lights::Light; use crate::scene_dat...
pub fn set_camera_to_world(&mut self, matrix: Matrix4x4) { let camera = Arc::get_mut(&mut self.camera).expect("Camera cannot be aquired!"); camera.set_camera_to_world(matrix); } pub fn set_integrator_type(&mut self, integrator_type: IntegratorType) { let options = Arc::get_mut(&mu...
pub fn new() -> Self { Scene { output_filename: String::new(), color_buffer: ColorBuffer::new(200, 200), options: Arc::new(SceneOptions::new(200, 200, SamplerType::Sobol, 16, IntegratorType::DirectLighting)), camera: Arc::new(Camera::Perspective(PerspectiveCamera:...
function_block-full_function
[ { "content": "pub fn sobol_matrices() -> &'static [u32] {\n\n &[\n\n 0x80000000,\n\n 0x40000000,\n\n 0x20000000,\n\n 0x10000000,\n\n 0x8000000,\n\n 0x4000000,\n\n 0x2000000,\n\n 0x1000000,\n\n 0x800000,\n\n 0x400000,\n\n 0x200000,\...
Rust
attribution/src/params.rs
chuck-flowers/attribution
95d0b6df66e9b91d65550ecc34f9cbd5952e1fc4
mod keys; mod values; pub use self::keys::ParamKey; pub use self::values::ParamVal; pub use self::values::TryIntoParamValError; use crate::conversion::FromParameters; use crate::conversion::FromParametersError; use std::collections::HashMap; use std::ops::Deref; use std::ops::DerefMut; use syn::parse::Parse; use syn::...
mod keys; mod values; pub use self::keys::ParamKey; pub use self::values::ParamVal; pub use self::values::TryIntoParamValError; use crate::conversion::FromParameters; use crate::conversion::FromParametersError; use std::collections::HashMap; use std::ops::Deref; use std::ops::DerefMut; use syn::parse::Parse; use syn::...
let mut pos = 0; while !input.is_empty() { let (key, val) = parse_kv(input)?; let key = key .map(|i| ParamKey::Named(i.to_string())) .unwrap_or_else(|| ParamKey::Unnamed(pos)); params.insert(key, val); if input.peek(Token...
if input.peek(syn::token::Paren) { let content; syn::parenthesized!(content in input); let params = content.parse::<Parameters>(); if !content.is_empty() { return Err(syn::parse::Error::new( input.span(), "Superfulou...
if_condition
[ { "content": "pub fn build_struct_constructor(input_struct: &ItemStruct) -> Expr {\n\n let struct_name = &input_struct.ident;\n\n\n\n match &input_struct.fields {\n\n Fields::Named(named) => {\n\n let idents = named\n\n .named\n\n .iter()\n\n ...
Rust
src/common/obb.rs
snorrwe/blight-engine
cffd862e9e9b3964a3e4630df2b7374a75b43dbd
use super::aabb::AABB; use super::matrix::Matrix22; use super::vector2::Vector2; use std::f32::{EPSILON, MAX}; #[derive(Debug, Clone)] pub struct OBB2D { center: Vector2, local: [Vector2; 2], extents: Vector2, } impl OBB2D { pub fn new(center: Vector2, local: [Vector2; 2], radius: Vector2) -...
use super::aabb::AABB; use super::matrix::Matrix22; use super::vector2::Vector2; use std::f32::{EPSILON, MAX}; #[derive(Debug, Clone)] pub struct OBB2D { center: Vector2, local: [Vector2; 2], extents: Vector2, } impl OBB2D { pub fn new(center: Vector2, local: [Vector2; 2], radius: Vector2) -...
pub fn get_center(&self) -> &Vector2 { &self.center } pub fn get_local(&self) -> &[Vector2; 2] { &self.local } pub fn get_extents(&self) -> &Vector2 { &self.extents } pub fn rotation_matrix(&self) -> Matrix22 { Matrix22::new([ s...
local[1] = edge_orth; dimensions = [l0.abs() * 0.5, l1.abs() * 0.5]; } }); OBB2D::new(center, local, Vector2::from_array(dimensions)) }
function_block-function_prefix_line
[ { "content": "use super::vector2::Vector2;\n\n\n\n/// Axis Aligned Bounding Box\n\n#[derive(Debug, Clone)]\n\npub struct AABB {\n\n center: Vector2,\n\n radius: Vector2,\n\n}\n\n\n\nimpl AABB {\n\n pub fn new(center: Vector2, width: f32, height: f32) -> AABB {\n\n assert!(width > 0.0);\n\n ...
Rust
mcts/src/ucb.rs
dstu/thud
015af25dbc363d0b59fb512263e578be72b32a28
use crate::backprop::BackpropSelector; use crate::game::{Game, State, Statistics}; use crate::graph::{EdgeData, VertexData}; use crate::rollout::RolloutSelector; use log::{error, trace}; use rand::Rng; use search_graph; use std::cmp::Ordering; use std::error::Error; use std::f64; use std::fmt; use std::result::Resul...
use crate::backprop::BackpropSelector; use crate::game::{Game, State, Statistics}; use crate::graph::{EdgeData, VertexData}; use crate::rollout::RolloutSelector; use log::{error, trace}; use rand::Rng; use search_graph; use std::cmp::Ordering; use std::error::Error; use std::f64; use std::fmt; use std::result::Resul...
let mut sampling_count = 0u32; let mut ucb_iter = EdgeUcbIter::new( log_parent_visits, explore_bias, graph, graph.children(parent), ); let mut best: search_graph::view::EdgeRef<'id>; let mut best_ucb: f64; match ucb_iter.next().expect("vertex has no children")? { UcbSuccess::Select(e) =...
let log_parent_visits = { let mut parent_visits = 0; for child in graph.children(parent) { parent_visits += graph.edge_data(child).statistics.visits(); } if parent_visits == 0 { 0.0 } else { f64::ln(parent_visits as f64) } };
assignment_statement
[ { "content": "/// Creates a new search graph suitable for Monte Carlo tree search through the\n\n/// state space of the game `G`.\n\npub fn new_search_graph<G: Game>() -> search_graph::Graph<G::State, VertexData, EdgeData<G>> {\n\n search_graph::Graph::<G::State, VertexData, EdgeData<G>>::new()\n\n}\n\n\n\n///...
Rust
src/modules/visitor.rs
andreyrmg/rustfmt
ad5d9fba9b6d5482e504e4996e2aea54defb9ed6
use syntax::ast; use syntax::parse::token::{DelimToken, TokenKind}; use syntax::parse::{stream_to_parser_with_base_dir, Directory, ParseSess}; use syntax::symbol::kw; use syntax::visit::Visitor; use syntax_pos::Symbol; use crate::attr::MetaVisitor; pub(crate) struct ModItem { pub(crate) item: ast::Item, } pub(cr...
use syntax::ast; use syntax::parse::token::{DelimToken, TokenKind}; use syntax::parse::{stream_to_parser_with_base_dir, Directory, ParseSess}; use syntax::symbol::kw; use syntax::visit::Visitor; use syntax_pos::Symbol; use crate::attr::MetaVisitor; pub(crate) struct ModItem { pub(crate) item: ast::Item, } pub(cr...
parser.cfg_mods = false; let mut process_if_cfg = true; while parser.token.kind != TokenKind::Eof { if process_if_cfg { if !parser.eat_keyword(kw::If) { return Err("Expected `if`"); } parser .pa...
let mut parser = stream_to_parser_with_base_dir( self.parse_sess, mac.node.tts.clone(), self.base_dir.clone(), );
assignment_statement
[ { "content": "fn attr_prefix(attr: &ast::Attribute) -> &'static str {\n\n match attr.style {\n\n ast::AttrStyle::Inner => \"#!\",\n\n ast::AttrStyle::Outer => \"#\",\n\n }\n\n}\n\n\n\npub(crate) trait MetaVisitor<'ast> {\n\n fn visit_meta_item(&mut self, meta_item: &'ast ast::MetaItem) {\...
Rust
grafana-plugin-sdk-macros/tests/ui-pass/basic.rs
toddtreece/grafana-plugin-sdk-rust
dad8f8922d637d0ca6fa2e4be2cfa87a426c3e8c
#![allow(dead_code, unused_variables)] mod a { use grafana_plugin_sdk::{backend, data}; #[derive(Clone)] struct MyPlugin; #[derive(Debug)] struct QueryError { source: data::Error, ref_id: String, } impl std::fmt::Display for QueryError { fn fmt(&self, f: &mut std:...
#![allow(dead_code, unused_variables)] mod a { use grafana_plugin_sdk::{backend, data}; #[derive(Clone)] struct MyPlugin; #[derive(Debug)] struct QueryError { source: data::Error, ref_id: String, } impl std::fmt::Display for QueryError { fn fmt(&self, f: &mut std:...
type CollectMetricsError = Arc<dyn std::error::Error + Send + Sync>; async fn collect_metrics( &self, request: backend::CollectMetricsRequest, ) -> Result<backend::CollectMetricsResponse, Self::CollectMetricsError> { todo!() } } #[backend::...
async fn check_health( &self, request: backend::CheckHealthRequest, ) -> Result<backend::CheckHealthResponse, Self::CheckHealthError> { todo!() }
function_block-full_function
[ { "content": "#[derive(Debug, Error)]\n\n#[error(\"Error querying backend for query {ref_id}: {source}\")]\n\nstruct QueryError {\n\n source: data::Error,\n\n ref_id: String,\n\n}\n\n\n\nimpl backend::DataQueryError for QueryError {\n\n fn ref_id(self) -> String {\n\n self.ref_id\n\n }\n\n}\n...
Rust
examples/tabs/src/login.rs
emann/iced_aw
53e87f244766a056723fda9116cc3f662e1f9a68
use iced::{ button, text_input, Align, Button, Column, Container, Element, HorizontalAlignment, Length, Row, Text, TextInput, }; use iced_aw::TabLabel; use crate::{Icon, Message, Tab}; #[derive(Debug, Clone)] pub enum LoginMessage { UsernameChanged(String), PasswordChanged(String), ClearPressed, ...
use iced::{ button, text_input, Align, Button, Column, Container, Element, HorizontalAlignment, Length, Row, Text, TextInput, }; use iced_aw::TabLabel; use crate::{Icon, Message, Tab}; #[derive(Debug, Clone)] pub enum LoginMessage { UsernameChanged(String), PasswordChanged(String), ClearPressed, ...
} } impl Tab for LoginTab { type Message = Message; fn title(&self) -> String { String::from("Login") } fn tab_label(&self) -> TabLabel { TabLabel::IconText(Icon::User.into(), self.title()) } fn content(&mut self) -> Element<'_, Self::Message> { let cont...
match message { LoginMessage::UsernameChanged(value) => self.username = value, LoginMessage::PasswordChanged(value) => self.password = value, LoginMessage::ClearPressed => { self.username = String::new(); self.password = String::new(); } ...
if_condition
[ { "content": "/// The [`Overlay`](Overlay) of the [`FloatingButton`](crate::native::FloatingButton).\n\nstruct Overlay<'a, Message, Renderer: iced_native::button::Renderer> {\n\n /// The anchor of the button.\n\n anchor: &'a Anchor,\n\n /// The offset of the button.\n\n offset: &'a Offset,\n\n //...
Rust
src/particle.rs
ManevilleF/bevy_tickles
6d43c948db4d7f44326c388a702a005d1a6e6be3
use bevy::prelude::{Color, Mat4, Reflect, Vec3}; use bevy::reflect::FromReflect; #[derive(Debug, Clone, Reflect)] pub enum ParticleRotation { AlignToDirection { offset: f32, }, FreeRotation { rotation: f32, angular_velocity: f32, }, } #[derive(Debug, Clone, Reflect)] pub struct...
use bevy::prelude::{Color, Mat4, Reflect, Vec3}; use bevy::reflect::FromReflect; #[derive(Debug, Clone, Reflect)] pub enum ParticleRotation { AlignToDirection { offset: f32, }, FreeRotation { rotation: f32, angular_velocity: f32, }, } #[derive(Debug, Clone, Reflect)] pub struct...
lf, delta_time: f32) { self.lifetime -= delta_time; self.translation += self.velocity * delta_time; if let ParticleRotation::FreeRotation { rotation, angular_velocity, } = &mut self.rotation { *rotation += *angular_velocity * delta_time; ...
-> Self { Self { translation: Vec3::ZERO, rotation: ParticleRotation::FreeRotation { rotation: 0.0, angular_velocity: 0.0, }, size: 1.0, lifetime: 1.0, start_lifetime: 1.0, color: Default::defaul...
random
[ { "content": "pub fn emit_particles(\n\n mut query: Query<(\n\n &mut ParticleSystem,\n\n &mut ParticleEmitter,\n\n &mut ParticleRng,\n\n &ParticleParams,\n\n &GlobalTransform,\n\n )>,\n\n time: Res<Time>,\n\n) {\n\n let delta = time.delta_seconds();\n\n for (mut...
Rust
src/lib.rs
fnichol/features-rs
1c179e4433580bf7aafd109a1818b3fe8b8a2b76
#[cfg(test)] #[macro_use] extern crate bitflags; #[macro_export] macro_rules! features { (mod $mod_name:ident { $($(#[$flag_attr:meta])* const $flag:ident = $value:expr),+ }) => { #[allow(non_upper_case_globals)] mod $mod_name { features! { @_impl mod $mod_...
#[cfg(test)] #[macro_use] extern crate bitflags; #[macro_export] macro_rules! features { (mod $mod_name:ident { $($(#[$flag_attr:meta])* const $flag:ident = $value:expr),+ }) => { #[allow(non_upper_case_globals)] mod $mod_name { features! { @_impl mod $mod_...
); assert_eq!(true, f::is_enabled(f::Cool)); assert_eq!(true, f::is_enabled(f::Beans)); f::disable(f::Cool); assert_eq!(false, f::is_enabled(f::Cool)); assert_eq!(true, f::is_enabled(f::Beans)); f::disable(f::Cool); assert_eq!(false, f::is_enabled(f::Co...
$($(#[$flag_attr:meta])* const $flag:ident = $value:expr),+ }) => { #[allow(non_upper_case_globals)] pub mod $mod_name { features! { @_impl mod $mod_name { $($(#[$flag_attr])* const $flag = $value),+ } } } ...
random
[ { "content": "## Example\n\n\n\nBasic example:\n\n\n\n```rust\n\n#[macro_use]\n\nextern crate bitflags;\n\n#[macro_use]\n\nextern crate features;\n\n\n\nfeatures! {\n\n pub mod feature {\n\n const Alpha = 0b00000001,\n\n const Beta = 0b00000010\n\n }\n\n}\n\n\n\nfn main() {\n\n assert_eq!...
Rust
crates/signals-ext/src/lib.rs
silkenweb/silkenweb
47fb3389cba34e3ada6b04dc8a1be8a70bf3474b
use std::{ pin::Pin, task::{Context, Poll}, }; use futures_signals::signal::Signal; use paste::paste; use pin_project::pin_project; pub trait SignalProduct<Tuple, F> { type Output; fn signal_ref(self, f: F) -> Self::Output; } macro_rules! signal_product{ ($name:ident; $( ($index:tt, $signal_var:i...
use std::{ pin::Pin, task::{Context, Poll}, }; use futures_signals::signal::Signal; use paste::paste; use pin_project::pin_project; pub trait SignalProduct<Tuple, F> { type Output; fn signal_ref(self, f: F) -> Self::Output; } macro_rules! signal_product{ ($name:ident; $( ($index:tt, $signal_var:i...
(Some(f())) } else if all_done { Poll::Ready(None) } else { Poll::Pending } } #[pin_project] struct RefSignal<S: Signal> { #[pin] signal: Option<S>, item: Option<S::Item>, } impl<S: Signal> RefSignal<S> { pub fn new(s: S) -> Self { Self { signal: Some(s)...
{ type Output = $name<$( $signal_type , )* F>; fn signal_ref(self, f: F) -> Self::Output { $name { $( $signal_var : RefSignal::new(self.$index) , )* f, } } } #[must_use = "Signals do noth...
random
[ { "content": "pub fn animation_timestamp() -> impl Signal<Item = f64> {\n\n RENDER.with(Render::animation_timestamp)\n\n}\n\n\n\n// TODO: This should work when a microtask creates more microtasks, but needs\n\n// testing. For example a `Signal::map` that updates a `Mutable` with another\n\n// listener.\n\n//...
Rust
src/config.rs
xurtis/s4
62196a25351aa53c6533e8ad3f48d1d4d9b3a2a9
use crate::util::*; use crate::{ Flag, Platform, PlatformId, Project, ProjectId, Repository, Sel4Architecture, Setting, VariationId, }; use anyhow::{format_err, Result}; use dirs::{config_dir, home_dir}; use serde::Deserialize; use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; use std::ops::De...
use crate::util::*; use crate::{ Flag, Platform, PlatformId, Project, ProjectId, Repository, Sel4Architecture, Setting, VariationId, }; use anyhow::{format_err, Result}; use dirs::{config_dir, home_dir}; use serde::Deserialize; use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; use std::ops::De...
ter() { if self.contains_key(&key) { self.get_mut(&key).unwrap().merge(other); } else { self.insert(key, other); } } } } impl<T: Ord> Merge for BTreeSet<T> { fn merge(&mut self, other: BTreeSet<T>) { for value in other { ...
(project) .unwrap_or(NameRef::owned(Project::default(), ProjectId::auto())) } pub fn check_setting(&self, setting: &Setting) -> Result<()> { for (id, value) in setting.flags() { if let Some(flag) = self.flags.get(id) { Flag::validate(flag, setting, value)?; ...
random
[ { "content": "/// Find an app somewhere in the path or download a script from a URL\n\nfn find_or_download(app: impl AsRef<Path>, url: &str) -> Result<PathBuf> {\n\n if let Some(path) = find_app_path(&app) {\n\n Ok(path)\n\n } else {\n\n let path = tmp_app_path(&app)?;\n\n if !path.ex...
Rust
nametable_codegen/src/nametable_codegen.in.rs
crlf0710/nametable
959946977bbcd9c3251c0261bb4224fc43077b22
use syntax::codemap::{Span, respan, dummy_spanned, DUMMY_SP}; use syntax::ptr::P; use syntax::tokenstream::{TokenTree, Delimited}; use syntax::ext::hygiene::SyntaxContext; use syntax::ast::{Name, Ident, StrStyle, LitKind, Item, Visibility, Mod, ItemKind, Generics, EnumDef, Varia...
use syntax::codemap::{Span, respan, dummy_spanned, DUMMY_SP}; use syntax::ptr::P; use syntax::tokenstream::{TokenTree, Delimited}; use syntax::ext::hygiene::SyntaxContext; use syntax::ast::{Name, Ident, StrStyle, LitKind, Item, Visibility, Mod, ItemKind, Generics, EnumDef, Varia...
er = cx.new_parser_from_tts(tts); MacEager::items(process_nametables(cx, sp, parser)) }
re."); } } else { item_name.name }; artifact_items.push((item_name.name,item_string)); if !parser.eat(&Token::Comma) { break; } } if !parser.eat(&Token::CloseDelim(DelimToken::Brace)) { ...
random
[ { "content": "pub fn name_hash(str_: &str) -> u64 {\n\n let mut hasher = DefaultHasher::new();\n\n str_.hash(&mut hasher);\n\n hasher.finish()\n\n}\n\n\n", "file_path": "nametable/src/nametable.rs", "rank": 5, "score": 129870.72374112511 }, { "content": "pub trait NameTableIdx {\n\n...
Rust
entab-cli/src/main.rs
bovee/entab
8b8228d65bde0a4b1ec21fd3685c3f5a1041b71f
mod tsv_params; use std::fs::File; use std::io; use std::str; use clap::{crate_authors, crate_version, App, Arg}; #[cfg(feature = "mmap")] use memmap::Mmap; use entab::buffer::ReadBuffer; use entab::compression::decompress; use entab::readers::get_reader; use entab::EtError; use crate::tsv_params::TsvParams; pub f...
mod tsv_params; use std::fs::File; use std::io; use std::str; use clap::{crate_authors, crate_version, App, Arg}; #[cfg(feature = "mmap")] use memmap::Mmap; use entab::buffer::ReadBuffer; use entab::compression::decompress; use entab::readers::get_reader; use entab::EtError; use crate::tsv_params::TsvParams; pub f...
for field in fields.iter().skip(1) { writer.write_all(&[params.main_delimiter])?; params.write_value(&field, &mut writer)?; } writer.write_all(&params.line_delimiter)?; } } writer.flush()?; Ok(()) }
cked_stdin = stdin.lock(); let (reader, filetype, compression) = decompress(Box::new(locked_stdin))?; (ReadBuffer::new(reader)?, filetype, compression) }; let parser = matches .value_of("parser") .unwrap_or_else(|| filetype.to_parser_name()); let mut rec_reader = get_reader(p...
function_block-random_span
[ { "content": "fn generate_reader(data: &[u8]) -> Result<(), EtError> {\n\n let filetype = FileType::from_magic(&data);\n\n let rb = ReadBuffer::from_slice(&data);\n\n let mut rec_reader = get_reader(filetype.to_parser_name(), rb)?;\n\n while let Some(_) = rec_reader.next_record()? {\n\n }\n\n ...
Rust
src/fs.rs
Krysme/xshell
d195b2409335ac629f19e059f86b79baa4dec41e
use std::{ path::{Path, PathBuf}, sync::atomic::{AtomicUsize, Ordering}, }; use crate::{error::fs_err, gsl, Result}; pub fn rm_rf(path: impl AsRef<Path>) -> Result<()> { _rm_rf(path.as_ref()) } fn _rm_rf(path: &Path) -> Result<()> { let _guard = gsl::read(); if !path.exists() { return Ok((...
use std::{ path::{Path, PathBuf}, sync::atomic::{AtomicUsize, Ordering}, }; use crate::{error::fs_err, gsl, Result}; pub fn rm_rf(path: impl AsRef<Path>) -> Result<()> { _rm_rf(path.as_ref()) } fn _rm_rf(path: &Path) -> Result<()> { let _guard = gsl::read(); if !path.exists() { return Ok((...
fn with_path<T>(path: &Path, res: Result<T, std::io::Error>) -> Result<T> { res.map_err(|io_err| fs_err(path.to_path_buf(), io_err)) } #[cfg(not(windows))] fn remove_dir_all(path: &Path) -> std::io::Result<()> { std::fs::remove_dir_all(path) } #[cfg(windows)] fn remove_dir_all(path: &Path) -> std::io::Resul...
y = 0u32; loop { let cnt = CNT.fetch_add(1, Ordering::Relaxed); let path = base.join(format!("xshell-tmp-dir-{}", cnt)); match std::fs::create_dir(&path) { Ok(()) => return Ok(TempDir { path }), Err(io_err) if n_try == 1024 => return Err(fs_err(path, io_err)), ...
function_block-function_prefixed
[]
Rust
src/win/win_impl.rs
mantou132/enigo
77759d42f5de8ff15698c95d12bc1e210026fff6
use winapi; use self::winapi::shared::windef::POINT; use self::winapi::ctypes::c_int; use self::winapi::um::winuser::*; use crate::win::keycodes::*; use crate::{Key, KeyboardControllable, MouseButton, MouseControllable}; use std::mem::*; #[derive(Default)] pub struct Enigo; fn mouse_event(flags: u32, data: u32, dx:...
use winapi; use self::winapi::shared::windef::POINT; use self::winapi::ctypes::c_int; use self::winapi::um::winuser::*; use crate::win::keycodes::*; use crate::{Key, KeyboardControllable, MouseButton, MouseControllable}; use std::mem::*; #[derive(Default)] pub struct Enigo; fn mouse_event(flags: u32, data: u32, dx:...
}
fn get_layoutdependent_keycode(&self, string: String) -> u16 { let mut buffer = [0; 2]; let utf16 = string .chars() .nth(0) .expect("no valid input") .encode_utf16(&mut buffer); if utf16.len() != 1 { pani...
function_block-function_prefix_line
[ { "content": "/// Evaluate the DSL. This tokenizes the input and presses the keys.\n\npub fn eval<K>(enigo: &mut K, input: &str) -> Result<(), ParseError>\n\nwhere\n\n K: KeyboardControllable,\n\n{\n\n for token in tokenize(input)? {\n\n match token {\n\n Token::Sequence(buffer) => {\n\n...
Rust
src/mos6502_addressing_modes.rs
boki1/Nessy
123b6dad8aeadae3cc4f52c361aa595b1b1cf8ee
use crate::mos6502::{ Address, AddressingMode, AddressingModeFn, AddressingOutput, AddressingOutput::*, Byte, Cpu, CpuError, CpuError::*, Instruction, MainBus, Opcode, Word, }; use std::cell::RefCell; use std::rc::Rc; #[inline] pub fn to_fun(amode: AddressingMode) -> AddressingModeFn { return match amode ...
use crate::mos6502::{ Address, AddressingMode, AddressingModeFn, AddressingOutput, AddressingOutput::*, Byte, Cpu, CpuError, CpuError::*, Instruction, MainBus, Opcode, Word, }; use std::cell::RefCell; use std::rc::Rc; #[inline] pub fn to_fun(amode: AddressingMode) -> AddressingModeFn { return match amode ...
-> Result<AddressingOutput, CpuError> { return match read_from_operand_with_offset(cpu, 0, false) { Ok((address, value)) => Ok(Fetched { value: value, address: address, }), Err(e) => Err(e), }; } pub fn absolute_x_am(cpu: &mut Cpu) -> Result<AddressingOutput, Cpu...
, CpuError> { let offset = cpu.regset().y_index() as Address; return match read_from_operand_with_offset(cpu, offset, true) { Ok((address, value)) => Ok(Fetched { value: value, address: address, }), Err(e) => Err(e), }; } fn read_from_operand_with_offset( ...
random
[ { "content": "/// **load_operand()** - For any given instruction (only the addressing mode\n\n/// is actually of importance here, fetch any operands that the instruction\n\n/// requires taking into account that the address of the instruction in memory\n\n/// is also provided.\n\npub fn load_operand(cpu: &mut Cp...
Rust
src/main.rs
Maxime2/funrpc
d04bae4eeed91546bc44c7f8b60eea8f7fe290b6
use actix_web::{actix, client, HttpMessage}; use structopt::StructOpt; #[macro_use] extern crate serde_derive; use futures::future::Future; use serde_json; #[derive(StructOpt, Debug)] #[structopt(name = "funrpc")] struct Opt { #[structopt(short = "d", long = "debug")] debug: bool, #[struct...
use actix_web::{actix, client, HttpMessage}; use structopt::StructOpt; #[macro_use] extern crate serde_derive; use futures::future::Future; use serde_json; #[derive(StructOpt, Debug)] #[structopt(name = "funrpc")] struct Opt { #[structopt(short = "d", long = "debug")] debug: bool, #[struct...
ap(); } } } Command::RawTx { doc } => { post = true; body = doc; url = format!("http://{}:{}/rawtx", opt.hostname, opt.port); if opt.verbose > 0 { println!( "Sending raw signed transaction to ...
e, opt.port); if opt.verbose > 0 { println!("Controlled accounts from {}:{}", opt.hostname, opt.port); } } Command::Account { number } => { url = format!("http://{}:{}/account/{}", opt.hostname, opt.port, number); if opt.verbose > 0 { ...
random
[ { "content": "# CLI interface to Fantom Foundation EVM.\n\n\n\n## Usage\n\n\n\n**host** and **port** specify node API end point of the EVM servicing user requests.\n\n\n\n```\n\n$funrpc --help\n\nfunrpc 0.1.0\n\nFantom Foundation <contact@fantom.foundation>\n\nLachesis node CLI interface\n\n\n\nUSAGE:\n\n fu...
Rust
src/spine/to_sexpr.rs
honzasp/spiral
ed506c02aa90a248799f6b84fb0de19ad6f396ab
use spine; use sexpr; pub fn prog_to_sexpr(prog: &spine::ProgDef) -> sexpr::Elem { sexpr::Elem::List(vec![ ident("program"), cont_name_to_sexpr(&prog.halt_cont), term_to_sexpr(&prog.body), ]) } pub fn term_to_sexpr(term: &spine::Term) -> sexpr::Elem { let mut list = vec![]; match *term { spine...
use spine; use sexpr; pub fn prog_to_sexpr(prog: &spine::ProgDef) -> sexpr::Elem { sexpr::Elem::List(vec![ ident("program"), cont_name_to_sexpr(&prog.halt_cont), term_to_sexpr(&prog.body), ]) } pub fn term_to_sexpr(term: &spine::Term) -> sexpr::Elem { let mut list = vec![]; match *term { spine...
pub fn fun_def_to_sexpr(def: &spine::FunDef) -> sexpr::Elem { sexpr::Elem::List(vec![ var_to_sexpr(&def.var), cont_name_to_sexpr(&def.ret), sexpr::Elem::List(def.captures.iter().map(var_to_sexpr).collect()), sexpr::Elem::List(def.args.iter().map(var_to_sexpr).collect()), term_to_sexpr(&def.body)...
t.push(term_to_sexpr(&**body)); }, spine::Term::Call(ref fun, ref ret, ref args) => { list.push(ident("call")); list.push(val_to_sexpr(fun)); list.push(cont_name_to_sexpr(ret)); list.extend(args.iter().map(val_to_sexpr)); }, spine::Term::ExternCall(ref ext_fun, ref ret, ref args)...
function_block-function_prefixed
[ { "content": "pub fn term_from_sexpr(elem: &sexpr::Elem) -> Result<spine::Term, String> {\n\n match *elem {\n\n sexpr::Elem::List(ref list) => \n\n match list.get(0) {\n\n Some(&sexpr::Elem::Identifier(ref head)) => match &head[..] {\n\n \"letcont\" => letcont_from_sexprs(&list[1..]),\n...
Rust
hphp/hack/src/name_index/sqlite/types.rs
compositor/hhvm
ac037244608e96b461b2d95cbc1ab95cbfa7cc88
use crate::datatypes::*; use crate::Result; use oxidized::naming_types::KindOfType; use oxidized::relative_path::RelativePath; use rusqlite::{params, Connection, OptionalExtension}; #[derive(Clone, Debug)] pub(crate) struct TypeItem { name: String, kind: KindOfType, file_info_id: i64, } pub fn create_t...
use crate::datatypes::*; use crate::Result; use oxidized::naming_types::KindOfType; use oxidized::relative_path::RelativePath; use rusqlite::{params, Connection, OptionalExtension}; #[derive(Clone, Debug)] pub(crate) struct TypeItem { name: String, kind: KindOfType, file_info_id: i64, } pub fn create_t...
pub fn get_path_case_insensitive( connection: &Connection, mut name: String, ) -> Result<Option<RelativePath>> { let select_statement = " SELECT NAMING_FILE_INFO.PATH_PREFIX_TYPE, NAMING_FILE_INFO.PATH_SUFFIX FROM NAMING_TYPES LEFT JOIN ...
let mut select_statement = connection.prepare_cached(&select_statement)?; let hash = convert::name_to_hash(typing_deps_hash::DepType::Class, &name); select_statement .query_row(params![hash], |row| { let prefix: SqlitePrefix = row.get(0)?; let suffix: SqlitePathBuf = row.get(1)?;...
function_block-function_prefix_line
[]
Rust
query-engine/core/src/schema_builder/filter_arguments.rs
forkkit/prisma-engine
6c4c4c7d16a37f56a0bfe16205465fa8148c8567
use super::*; #[derive(Debug, PartialEq, Clone, Copy)] pub struct FilterArgument { pub suffix: &'static str, pub is_list: bool, } struct StaticFilterArguments { pub base: &'static [FilterArgument], pub inclusion: &'static [FilterArgument], pub alphanumeric: &'static [FilterArgument], pub strin...
use super::*; #[derive(Debug, PartialEq, Clone, Copy)] pub struct FilterArgument { pub suffix: &'static str, pub is_list: bool, } struct StaticFilterArguments { pub base: &'static [FilterArgument], pub inclusion: &'static [FilterArgument], pub alphanumeric: &'static [FilterArgument], pub strin...
s.base, &args.inclusion, &args.alphanumeric, &args.string], TypeIdentifier::String => vec![&args.base, &args.inclusion, &args.alphanumeric, &args.string], TypeIdentifier::Int => vec![&args.base, &args.inclusion, &args.alphanumeric], TypeIdentifier::Float => vec![&args.base, &args.inc...
function_block-function_prefixed
[ { "content": "pub fn get_expected_from_error(positives: &[Rule]) -> Vec<&'static str> {\n\n positives\n\n .iter()\n\n .map(|r| rule_to_string(*r))\n\n .filter(|s| s != &\"\")\n\n .collect()\n\n}\n\n\n", "file_path": "libs/datamodel/core/src/ast/parser/mod.rs", "rank": 1, ...
Rust
src/source_file.rs
totr/ffizer
dee9570213c1e2c326dc2635dafc7dce47346ed6
use crate::files; use crate::ChildPath; use std::cmp::{Ord, Ordering}; use std::path::PathBuf; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum SourceFileMetadata { Dir, RawFile, RenderableFile { extension: &'static str }, } impl SourceFileMetadata { fn kind_idx(&self) -> usize { mat...
use crate::files; use crate::ChildPath; use std::cmp::{Ord, Ordering}; use std::path::PathBuf; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum SourceFileMetadata { Dir, RawFile, RenderableFile { extension: &'static str }, } impl SourceFileMetadata { fn kind_idx(&self) -> usize { mat...
eFile { extension: files::FILEEXT_HANDLEBARS, }, } } else { SourceFile { childpath, layer_order, metadata: SourceFileMetadata::RawFile, } } } } pub(crate) fn optimize_sourcefiles(...
eMetadata { fn cmp(&self, other: &Self) -> Ordering { self.kind_idx().cmp(&other.kind_idx()) } } impl PartialOrd for SourceFileMetadata { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct SourceFi...
random
[ { "content": "fn format_operation(op: &FileOperation) -> Cow<'static, str> {\n\n let s = match op {\n\n FileOperation::Nothing => \"do nothing\",\n\n FileOperation::Ignore => \"ignore\",\n\n FileOperation::MkDir => \"make dir\",\n\n FileOperation::AddFile => \"add file\",\n\n ...
Rust
src/lz4_block_header.rs
trazfr/lz4jb
6971accf06653ea4591dc3a9d2cf5e733ae10fc4
use crate::common::{ErrorCorruptedStream, ErrorWrongBlockSize, IoErrorKind}; use twox_hash::XxHash32; use std::convert::TryInto; use std::hash::Hasher; use std::io::{Read, Result, Write}; use std::ops::Range; use std::result::Result as StdResult; const MAGIC_HEADER: &[u8; 8] = b"LZ4Block"; const MAGIC_HEADER_RANGE: ...
use crate::common::{ErrorCorruptedStream, ErrorWrongBlockSize, IoErrorKind}; use twox_hash::XxHash32; use std::convert::TryInto; use std::hash::Hasher; use std::io::{Read, Result, Write}; use std::ops::Range; use std::result::Result as StdResult; const MAGIC_HEADER: &[u8; 8] = b"LZ4Block"; const MAGIC_HEADER_RANGE: ...
mpressed_len).to_le_bytes()); buf[DECOMPRESSED_LEN_RANGE].clone_from_slice(&(self.decompressed_len).to_le_bytes()); buf[CHECKSUM_RANGE].clone_from_slice(&(self.checksum).to_le_bytes()); writer.write(&buf) } } #[derive(Debug, Clone, Copy)] pub(crate) struct CompressionLevel { compression...
uf[MAGIC_HEADER_RANGE].clone_from_slice(MAGIC_HEADER); buf[TOKEN_INDEX] = self.compression_level.get_token() | self.compression_method.get_token(); buf[COMPRESSED_LEN_RANGE].clone_from_slice(&(self.co
function_block-random_span
[ { "content": "fn run_decompress<R: Read, W: Write>(context: Lz4Context, from: R, mut to: W) -> Result<()> {\n\n let mut from = Lz4BlockInput::with_context(from, context);\n\n io::copy(&mut from, &mut to)?;\n\n to.flush()\n\n}\n\n\n", "file_path": "cli/src/command.rs", "rank": 0, "score": 14...
Rust
src/device/tun_darwin.rs
backwardn/boringtun
362be0d9f44277c49ec465cd329ab0567f9742b4
use super::Error; use libc::*; use std::mem::size_of; use std::mem::size_of_val; use std::os::unix::io::{AsRawFd, RawFd}; use std::ptr::null_mut; pub fn errno() -> i32 { unsafe { *__error() } } pub fn errno_str() -> String { let strerr = unsafe { strerror(*__error()) }; let c_str = unsafe { std::ffi::CS...
use super::Error; use libc::*; use std::mem::size_of; use std::mem::size_of_val; use std::os::unix::io::{AsRawFd, RawFd}; use std::ptr::null_mut; pub fn errno() -> i32 { unsafe { *__error() } } pub fn errno_str() -> String { let strerr = unsafe { strerror(*__error()) }; let c_str = unsafe { std::ffi::CS...
} < 0 { unsafe { close(fd) }; let mut err_string = errno_str(); err_string.push_str("(did you run with sudo?)"); return Err(Error::Connect(err_string)); } Ok(TunSocket { fd }) } pub fn name(&self) -> Result<String, Error> { ...
connect( fd, &addr as *const sockaddr_ctl as _, size_of_val(&addr) as _, )
call_expression
[ { "content": "pub fn errno_str() -> String {\n\n let strerr = unsafe { strerror(*__errno_location()) };\n\n let c_str = unsafe { std::ffi::CStr::from_ptr(strerr) };\n\n c_str.to_string_lossy().into_owned()\n\n}\n\n\n\nconst TUNSETIFF: u64 = 0x4004_54ca;\n\n\n\n#[repr(C)]\n\nunion IfrIfru {\n\n ifru_...
Rust
src/api/r0/room_info.rs
xiaosongfu/ruma
06d7f2f5debd40637aca6c22dd50ddc444148b7c
use std::convert::TryInto; use iron::status::Status; use iron::{Chain, Handler, IronResult, Request, Response}; use ruma_events::collections::all::StateEvent; use crate::db::DB; use crate::error::ApiError; use crate::middleware::{AccessTokenAuth, MiddlewareChain, RoomIdParam}; use crate::models::event::Event; use c...
use std::convert::TryInto; use iron::status::Status; use iron::{Chain, Handler, IronResult, Request, Response}; use ruma_events::collections::all::StateEvent; use crate::db::DB; use crate::error::ApiError; use crate::middleware::{AccessTokenAuth, MiddlewareChain, RoomIdParam}; use crate::models::event::Event; use c...
#[test] fn previous_state_for_users_that_left() { let test = Test::new(); let alice = test.create_user(); let bob = test.create_user(); let room_options = format!( r#"{{ "invite": ["{}"], "initial_state": [{{ "state_key": "",...
mpty()); for e in events.iter() { if e.get("type").unwrap().as_str().unwrap() == "m.room.aliases" { let aliases = e.pointer("/content/aliases").unwrap().as_array().unwrap(); assert!(aliases.contains(&Value::String("#alias_1:ruma.test".to_string()))); ...
function_block-function_prefixed
[ { "content": "#[derive(Clone, Debug, Deserialize)]\n\nstruct InviteToRoomRequest {\n\n /// The fully qualified user ID of the invitee.\n\n pub user_id: UserId,\n\n}\n\n\n\nmiddleware_chain!(InviteToRoom, [JsonRequest, RoomIdParam, AccessTokenAuth]);\n\n\n\nimpl Handler for InviteToRoom {\n\n fn handle(...
Rust
src/main.rs
karuna/hangar
f5ac697b9301d6f4f646fecc49849a2b354d4ddf
extern crate clap; #[macro_use] extern crate lazy_static; extern crate tera; use std::process::exit; use std::env; use clap::{App, AppSettings, Arg, SubCommand}; mod build; mod db; mod help; mod new; mod run; mod generator; mod watch; fn main() { let args = generate_args(); let build_subcommand = generate_...
extern crate clap; #[macro_use] extern crate lazy_static; extern crate tera; use std::process::exit; use std::env; use clap::{App, AppSettings, Arg, SubCommand}; mod build; mod db; mod help; mod new; mod run; mod generator; mod watch; fn main() { let args = generate_args(); let build_subcommand = generate_...
push(arg), } filtered_args.extend(args); filtered_args } fn generate_build_subcommand<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("build") .about("Wrapper for cargo build") .help(help::BUILD_HELP) .setting(AppSettings::AllowExternalSubcommands) } fn generate_db_subcommand...
<karuna.murti@gmail.com>") .setting(AppSettings::ArgRequiredElseHelp) .subcommand(build_subcommand) .subcommand(db_subcommand) .subcommand(new_subcommand) .subcommand(run_subcommand) .get_matches_from(&args); let result: Result<String, String> = if let Some(matches)...
random
[ { "content": "pub fn execute<'a>(matches: &clap::ArgMatches<'a>) -> Result<String, String> {\n\n let mut setting = Setting {\n\n name: String::from(\"\"),\n\n db: String::from(\"postgresql\"),\n\n db_url: String::from(\"\"),\n\n author: String::from(\"John Doe <user@example.com>\"...
Rust
src/main.rs
Nogamara/timezonebot-mastodon
b676199e98344d97597817b416478b88b71beae1
extern crate mammut; extern crate regex; extern crate time; extern crate toml; extern crate tzbot; use std::io; use std::fs::File; use std::io::prelude::*; use mammut::{Data, Mastodon, Registration}; use mammut::apps::{AppBuilder, Scopes}; use mammut::status_builder::{StatusBuilder}; use regex::Regex; use tzbot::conv...
extern crate mammut; extern crate regex; extern crate time; extern crate toml; extern crate tzbot; use std::io; use std::fs::File; use std::io::prelude::*; use mammut::{Data, Mastodon, Registration}; use mammut::apps::{AppBuilder, Scopes}; use mammut::status_builder::{StatusBuilder}; use regex::Regex; use tzbot::conv...
fn register() -> Mastodon { let app = AppBuilder { client_name: "tzbot", redirect_uris: "urn:ietf:wg:oauth:2.0:oob", scopes: Scopes::ReadWrite, website: Some("https://github.com/nogamara"), }; let mut registration = Registration::new("https://botsin.space"); registrati...
r), } }, } } } _ => (), } println!("============================================================"); } let _ = mastodon.clear_notifications(); }
function_block-function_prefixed
[ { "content": "fn format_output(tz: String, hours: String, minutes: String, ampm: String, lookup: HashMap<String, String>, common: Vec<String>) -> String {\n\n let mut h_i = hours.parse::<i32>().unwrap();\n\n let m_i = minutes.parse::<i32>().unwrap();\n\n\n\n if &ampm == \"PM\" {\n\n h_i = h_i + ...
Rust
imnodes-wgpu-examples/src/multi_editor.rs
dbr/imnodes-rs
8dfa9ff891ed700721a96ac33d98e4730d5bb830
use imgui::{im_str, Slider, Ui}; use imnodes::{ editor, AttributeFlag, AttributeId, Context, EditorContext, IdentifierGenerator, InputPinId, LinkId, NodeId, OutputPinId, PinShape, }; pub struct MultiEditState { editor_context: EditorContext, id_gen: IdentifierGenerator, nodes: Vec<Node>, links...
use imgui::{im_str, Slider, Ui}; use imnodes::{ editor, AttributeFlag, AttributeId, Context, EditorContext, IdentifierGenerator, InputPinId, LinkId, NodeId, OutputPinId, PinShape, }; pub struct MultiEditState { editor_context: EditorContext, id_gen: IdentifierGenerator, nodes: Vec<Node>, links...
pub fn show(ui: &Ui, state: &mut MultiEditState) { let id = ui.push_id(state as *mut MultiEditState); state.editor_context.set_style_colors_classic(); let on_snap = state .editor_context .push(AttributeFlag::EnableLinkCreationOnSnap); let detach = state .editor_contex...
function_block-full_function
[]
Rust
erdos/src/configuration.rs
objorkman/erdos
13b3be477d6674e9e377a56dec484f80ba41e915
use std::net::SocketAddr; use tracing::Level; use crate::node::NodeId; #[derive(Clone)] pub struct Configuration { pub index: NodeId, pub num_threads: usize, pub data_addresses: Vec<SocketAddr>, pub control_addresses: Vec<SocketAddr>, pub graph_filename: Option<String>, ...
use std::net::SocketAddr; use tracing::Level; use crate::node::NodeId; #[derive(Clone)] pub struct Configuration { pub index: NodeId, pub num_threads: usize, pub data_addresses: Vec<SocketAddr>, pub control_addresses: Vec<SocketAddr>, pub graph_filename: Option<String>, ...
pub fn from_args(args: &clap::ArgMatches) -> Self { let num_threads = args .value_of("threads") .unwrap() .parse() .expect("Unable to parse number of worker threads"); let data_addrs = args.value_of("data-addresses").unwrap(); let mut d...
evel::DEBUG) } else { Some(Level::INFO) }; Self { index: node_index, num_threads, data_addresses, control_addresses, graph_filename: None, logging_level: log_level, } }
function_block-function_prefixed
[ { "content": "/// Defines command line arguments for running a multi-node ERDOS application.\n\npub fn new_app(name: &str) -> clap::App {\n\n App::new(name)\n\n .arg(\n\n Arg::with_name(\"threads\")\n\n .short(\"t\")\n\n .long(\"threads\")\n\n .d...
Rust
salak_factory/src/metric.rs
leptonyu/salak.rs
5987068220cfe83f3af8f2e4c2d77067fde54e71
use core::f64; pub use metrics::*; use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle, PrometheusRecorder}; use parking_lot::Mutex; use salak::*; use std::{ any::Any, collections::HashSet, net::SocketAddr, ops::Deref, sync::Arc, thread::sleep, time::{Duration, UNIX_EPOCH}...
use core::f64; pub use metrics::*; use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle, PrometheusRecorder}; use parking_lot::Mutex; use salak::*; use std::{ any::Any, collections::HashSet, net::SocketAddr, ops::Deref, sync::Arc, thread::sleep, time::{Duration, UNIX_EPOCH}...
dress: Option<SocketAddr>, #[salak(desc = "Network metrics")] networks: HashSet<String>, #[salak(default = "true")] enabled: bool, } macro_rules! set_config { ($config:expr => $builder:ident.$fn:ident) => { if let Some(val) = $config { $builder = $builder.$fn(val); } ...
work.received.errors", name ); gauge_network!(metric.nt.total_received = "network.received.total", name); gauge_network!( metric.nt.total_packets_transmitted = "network.transmitted.packets", name ...
random
[ { "content": "fn get_generic_type<'a>(ty: &'a Type, name: &str) -> (bool, &'a Type) {\n\n match ty {\n\n Type::Path(v) => {\n\n let v = v.path.segments.first().unwrap();\n\n if v.ident == name {\n\n if let PathArguments::AngleBracketed(a) = &v.arguments {\n\n ...
Rust
components/dispatch-fido/src/fido.rs
3mdeb/transmet-authenticator-firmware
b1fa4e6ff88900b570ec10032f040dfe55f63386
use core::convert::TryFrom; use iso7816::{Instruction, Status}; use apdu_dispatch::{Command, response, app}; use ctaphid_dispatch::command::Command as FidoCommand; use ctap_types::{ authenticator::Error as AuthenticatorError, authenticator::Request as AuthenticatorRequest, serde::{cbor_serialize}, ctap1...
use core::convert::TryFrom; use iso7816::{Instruction, Status}; use apdu_dispatch::{Command, response, app}; use ctaphid_dispatch::command::Command as FidoCommand; use ctap_types::{ authenticator::Error as AuthenticatorError, authenticator::Request as AuthenticatorRequest, serde::{cbor_serialize}, ctap1...
#[inline(never)] fn call_authenticator(&mut self, request: &AuthenticatorRequest, reply: &mut response::Data) -> app::Result { let result = self.authenticator.call(request); match &result { Err(error) => { info!("error {}", *error as u8); reply.push...
r(_) => { reply[0] = AuthenticatorError::Other as u8; reply.resize_default(1).unwrap(); } } } else { reply[0] = 0; reply.resize_default(1).unwrap(); } Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn piv<R>(test: impl FnOnce(&mut Piv) -> R) -> R {\n\n use trussed::Interchange as _;\n\n unsafe { trussed::pipe::TrussedInterchange::reset_claims(); }\n\n let trussed_platform = init_platform();\n\n let mut trussed_service = trussed::service::Service::new(trussed_platform);\n\n ...
Rust
util/src/bind_dnskey_to_pem.rs
makarchuk/trust-dns
98d84917aa74432fa33cd1daca20dc93072629ed
extern crate clap; extern crate data_encoding; extern crate env_logger; #[macro_use] extern crate log; extern crate openssl; extern crate trust_dns; use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, Lines, Write}; use std::str::FromStr; use clap::{App, Arg, ArgMatches}; use data_encoding::BASE64; ...
extern crate clap; extern crate data_encoding; extern crate env_logger; #[macro_use] extern crate log; extern crate openssl; extern crate trust_dns; use std::fs::{File, OpenOptions}; use std::io::{BufRead, BufReader, Lines, Write}; use std::str::FromStr; use clap::{App, Arg, ArgMatches}; use data_encoding::BASE64; ...
pub fn main() { env_logger::init(); let matches = args(); let key_path = matches.value_of("key").unwrap(); let output_path = matches.value_of("output").unwrap(); info!("Reading private key: {}", key_path); let key_file = File::open(key_path).expect("private key file could not be opened"); ...
App::new("Trust-DNS dnskey-to-pem") .version(trust_dns::version()) .author("Benjamin Fry <benjaminfry@me.com>") .about("Converts a dnskey, as generated from BIND's dnssec-keygen, into pem format") .arg( Arg::with_name("key") .value_name("PRIVATE_KEY_FILE") ...
function_block-function_prefix_line
[ { "content": "/// Generates a certificate, see root_ca() for getting a root cert\n\nfn cert(\n\n subject_name: &str,\n\n ca_pkey: &PKey<Private>,\n\n ca_name: &X509Name,\n\n _: &X509,\n\n) -> (PKey<Private>, X509, Pkcs12) {\n\n let rsa = Rsa::generate(2048).unwrap();\n\n let pkey = PKey::from_...
Rust
workflow/scripts/stacks_analyzer/src/main.rs
snakemake-workflows/rad-seq-stacks
3a20c20f2d19396b14b9e01af66504020f257955
use bio::io::fastq; use flate2::bufread::MultiGzDecoder; use std::collections::HashMap; use std::fs; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::io::BufWriter; use structopt::StructOpt; fn get_mapping( p5_path: &str, p7_path: &str, ) -> HashMap<String, (bio::io::fastq::Record...
use bio::io::fastq; use flate2::bufread::MultiGzDecoder; use std::collections::HashMap; use std::fs; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::io::BufWriter; use structopt::StructOpt; fn get_mapping( p5_path: &str, p7_path: &str, ) -> HashMap<String, (bio::io::fastq::Record...
fn assemble_mapping(p5_path: &str, p7_path: &str, tsv_path: &str, dat_path: &str, out_path: &str) { let mapping = get_mapping(p5_path, p7_path); let clusters = StacksCluster::from_csv_records(tsv_path, dat_path); assemble_clusters(mapping, clusters, out_path); } fn count_locus_sizes(tsv_path: &str, dat_p...
seq) = read; let (p5_rec, p7_rec) = mapping.get(name).unwrap(); primary_seqs.push(( std::str::from_utf8(p5_rec.seq()).unwrap(), std::str::from_utf8(p7_rec.seq()).unwrap(), )); } for read in cluster.secondary_reads.iter...
function_block-function_prefixed
[ { "content": "def read_dat_file(dat_file_path, threshold):\n\n \"\"\"Read dat files into a list. Split off everything over\n\n threshold into a separate list.\n\n \"\"\"\n\n params = dat_file_path.split(\"/\")[-2]\n\n name = os.path.splitext(os.path.basename(dat_file_path))[0]\n\n data = []\n\...
Rust
exonum/src/helpers/mod.rs
kn1k/exonum
9f253df0b0014266f6aea6453dde98b79ec7b4d5
pub use self::types::{Height, Milliseconds, Round, ValidatorId, ZeroizeOnDrop}; pub mod config; pub mod fabric; pub mod user_agent; #[macro_use] pub mod metrics; use crypto::gen_keypair; use env_logger::Builder; use log::SetLoggerError; use std::path::{Component, Path, PathBuf}; use blockchain::{GenesisConfig, Val...
pub use self::types::{Height, Milliseconds, Round, ValidatorId, ZeroizeOnDrop}; pub mod config; pub mod fabric; pub mod user_agent; #[macro_use] pub mod metrics; use crypto::gen_keypair; use env_logger::Builder; use log::SetLoggerError; use std::path::{Component, Path, PathBuf}; use blockchain::{GenesisConfig, Val...
#[test] fn test_path_relative_from() { let cases = vec![ ("/b", "/c", Some("../b".into())), ("/a/b", "/a/c", Some("../b".into())), ("/a", "/a/c", Some("../".into())), ("/a/b/c", "/a/b", Some("c".into())), ("/a/b/c", "/a/b/d", Some("../c".into())), ("./a/b", "./a/c",...
Some(PathBuf::from(path)) } else { None } } else { let mut ita = path.components(); let mut itb = base.components(); let mut comps: Vec<Component> = vec![]; loop { match (ita.next(), itb.next()) { (None, None) => break, ...
function_block-function_prefix_line
[ { "content": "pub fn new_tx_config_propose(\n\n node: &TestNode,\n\n cfg_proposal: StoredConfiguration,\n\n) -> Signed<RawTransaction> {\n\n let keypair = node.service_keypair();\n\n Propose::sign(\n\n keypair.0,\n\n str::from_utf8(cfg_proposal.into_bytes().as_slice()).unwrap(),\n\n ...
Rust
webapp/src/models/templates.rs
kikei/composion-of-onsen-server
136eea96158831c6c555ca1622376e1887a01909
use std::convert::TryFrom; use serde_json::{json, Value}; use crate::models::{Models}; use crate::template::{self, Template}; use crate::utils::elasticsearch::{ GetResult, SearchResultItem, OperationResultType, Operations, GetOptions, SearchOptions, InsertOptions, UpdateOptions, DeleteOptions }; pub struc...
use std::convert::TryFrom; use serde_json::{json, Value}; use crate::models::{Models}; use crate::template::{self, Template}; use crate::utils::elasticsearch::{ GetResult, SearchResultItem, OperationResultType, Operations, GetOptions, SearchOptions, InsertOptions, UpdateOptions, DeleteOptions }; pub struc...
} impl From<&Template> for Value { fn from(t: &Template) -> Self { let mut v = json!({ template::KEY_NAME: Value::from(t.name.as_str()), template::KEY_BODY: Value::from(t.body.as_str()) }); if let Some(id) = &t.id { v.as_object_mut().unwrap().insert(temp...
Value: {}", &value))?; let id = obj.get(template::KEY_ID) .and_then(|v| v.as_str()).map(|s| s.to_string()); let name = obj.get(template::KEY_NAME).and_then(|v| v.as_str()).unwrap(); let body = obj.get(template::KEY_BODY).and_then(|v| v.as_str()).un...
function_block-function_prefixed
[ { "content": "pub fn scrub(text: &String) -> String {\n\n // let mut yomis = vec![];\n\n let katakanas: Vec<String> = tokenize_japanese(&text);\n\n let katakanas: String = katakanas.join(\"\");\n\n let katakanas: Vec<Pron> = tokenize_katakana(&katakanas);\n\n let yomis: Vec<String> = katakana_yom...
Rust
plonky2/src/util/strided_view.rs
mfaulk/plonky2
2cedd1b02a718d19115560647ba1f741eab83260
use std::marker::PhantomData; use std::mem::size_of; use std::ops::{Index, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}; use plonky2_field::packed_field::PackedField; #[derive(Debug, Copy, Clone)] pub struct PackedStridedView<'a, P: PackedField> { start_pt...
use std::marker::PhantomData; use std::mem::size_of; use std::ops::{Index, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive}; use plonky2_field::packed_field::PackedField; #[derive(Debug, Copy, Clone)] pub struct PackedStridedView<'a, P: PackedField> { start_pt...
} impl<'a, P: PackedField> DoubleEndedIterator for PackedStridedViewIter<'a, P> { fn next_back(&mut self) -> Option<Self::Item> { debug_assert_eq!( (self.end as usize).wrapping_sub(self.start as usize) % (self.stride * size_of::<P::Scalar>()), 0, "start ...
fn next(&mut self) -> Option<Self::Item> { debug_assert_eq!( (self.end as usize).wrapping_sub(self.start as usize) % (self.stride * size_of::<P::Scalar>()), 0, "start and end pointers should be separated by a multiple of stride" ); if self.sta...
function_block-full_function
[ { "content": "pub fn reduce_with_powers<'a, P: PackedField, T: IntoIterator<Item = &'a P>>(\n\n terms: T,\n\n alpha: P::Scalar,\n\n) -> P\n\nwhere\n\n T::IntoIter: DoubleEndedIterator,\n\n{\n\n let mut sum = P::ZEROS;\n\n for &term in terms.into_iter().rev() {\n\n sum = sum * alpha + term;...
Rust
sway-fmt/src/traversal.rs
anrestbe/Bimbam
11d4f534088e9272af1399cc8a0fe417f56af5a1
use sway_core::{AstNode, AstNodeContent, Declaration, Expression, ReturnStatement, SwayParseTree}; use sway_types::span::Span; use crate::traversal_helper::{ format_data_types, format_delineated_path, format_include_statement, format_use_statement, }; #[derive(Debug)] pub struct Change { pub text: String, ...
use sway_core::{AstNode, AstNodeContent, Declaration, Expression, ReturnStatement, SwayParseTree}; use sway_types::span::Span; use crate::traversal_helper::{ format_data_types, format_delineated_path, format_include_statement, format_use_statement, }; #[derive(Debug)] pub struct Change { pub text: String, ...
} } _ => {} }; } fn handle_expression(expr: &Expression, changes: &mut Vec<Change>) { match &expr { Expression::StructExpression { struct_name: _, fields: _, span, } => changes.push(Change::new(span, ChangeType::Struct)), Expres...
match &ast_node.content { AstNodeContent::Declaration(dec) => handle_declaration(dec, ast_node, changes), AstNodeContent::ReturnStatement(ret) => handle_return_statement(ret, changes), AstNodeContent::Expression(expr) => handle_expression(expr, changes), AstNodeContent::ImplicitRet...
random
[ { "content": "pub fn traverse_node(node: AstNode, tokens: &mut Vec<Token>) {\n\n match node.content {\n\n AstNodeContent::Declaration(dec) => handle_declaration(dec, tokens),\n\n AstNodeContent::Expression(exp) => handle_expression(exp, tokens),\n\n // TODO\n\n // handle other con...
Rust
src/main.rs
Hanaasagi/httpstat-rs
dcabc26038e154967262e3bd9851c2f8c18f6277
#[macro_use] extern crate log; extern crate chrono; extern crate tempfile; extern crate serde_json; use std::io::Read; use tempfile::NamedTempFile; use serde_json::Value; use std::env; use std::process::exit; use std::process::Command; use std::collections::HashMap; mod logging; use logging::{init_logger}; mod metri...
#[macro_use] extern crate log; extern crate chrono; extern crate tempfile; extern crate serde_json; use std::io::Read; use tempfile::NamedTempFile; use serde_json::Value; use std::env; use std::process::exit; use std::process::Command; use std::collections::HashMap; mod logging; use logging::{init_logger}; mod metri...
MIT, len=body_len); if save_body { prompt = format!("{pre}, stored in: {path}", pre=prompt, path=bodyf.path().to_str().unwrap()); } println!("{}", prompt); } else { println!("{}", body); } } if !show_body && save_body{ prin...
shows remote and local IP/port address. Set to `false` to disable this feature. Default is `true`. HTTPSTAT_SHOW_SPEED Set to `true` to show download and upload speed. Default is `false`. HTTPSTAT_SAVE_BODY By default httpstat stores body in a tmp file, ...
random
[ { "content": "pub fn init_logger(level: Level) -> Result<(), SetLoggerError> {\n\n log::set_boxed_logger(Box::new(Logger{ level }))\n\n .map(|()| log::set_max_level(level.to_level_filter()))\n\n}\n\n\n", "file_path": "src/logging.rs", "rank": 0, "score": 20822.013321505394 }, { "co...
Rust
bench/src/main.rs
zakarumych/rapid-qoi
eec6e6df9a5f3d49bf2a96b0cf5c2285406a85e9
use std::{ fs::File, io::BufReader, path::Path, time::{Duration, Instant}, }; fn ns() -> Instant { Instant::now() } struct BenchmarkLibResult { size: u64, encode_time: Duration, decode_time: Duration, } struct BenchmarkResult { count: u32, px: u64, w: u32, h: u32, ...
use std::{ fs::File, io::BufReader, path::Path, time::{Duration, Instant}, }; fn ns() -> Instant { Instant::now() } struct BenchmarkLibResult { size: u64, encode_time: Duration, decode_time: Duration, } struct BenchmarkResult { count: u32, px: u64, w: u32, h: u32, ...
fn main() -> Result<(), ()> { let mut args = std::env::args(); if args.len() < 3 { eprintln!("Usage: qoibench <iterations> <directory>"); eprintln!("Example: qoibench 10 images/textures/"); return Err(()); } args.next(); let mut runs = args.next().unwrap().parse().unwrap(...
O, decode_time: Duration::ZERO, }, rapid_qoi: BenchmarkLibResult { size: 0, encode_time: Duration::ZERO, decode_time: Duration::ZERO, }, }; for path in dir { let path = path.unwrap(); let ft = path.file_type().unwrap(); ...
function_block-function_prefixed
[ { "content": "fn main() -> Result<(), ()> {\n\n let mut args = std::env::args();\n\n\n\n if args.len() < 2 {\n\n eprintln!(\"Usage: qoiconv <input-path> [<output-path>]\");\n\n eprintln!(\"Example: qoiconv images/foo.png images.foo.qoi\");\n\n return Err(());\n\n }\n\n\n\n args....
Rust
sim/src/cap.rs
balbok0/abstreet
3af15fefdb2772c83864c08724318418da8190a9
use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use geom::{Duration, Time}; use map_model::{Map, Path, PathStep, RoadID, TurnID}; use crate::mechanics::IntersectionSimState; use crate::{CarID, SimOptions, VehicleType}; type ZoneIdx = usize; #[derive(Serialize, Deserialize, Clone)] ...
use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use geom::{Duration, Time}; use map_model::{Map, Path, PathStep, RoadID, TurnID}; use crate::mechanics::IntersectionSimState; use crate::{CarID, SimOptions, VehicleType}; type ZoneIdx = usize; #[derive(Serialize, Deserialize, Clone)] ...
r.contains(&car) { avoid_roads.insert(*r); } } match map.pathfind_avoiding_roads(path.get_req().clone(), avoid_roads) { Some(path) => CapResult::Reroute(path), None => { if let Some(delay) = self.delay_trips_instead_of_cance...
path: Path, now: Time, car: CarID, intersections: &IntersectionSimState, map: &Map, ) -> CapResult { if self.cancel_drivers_delay_threshold.is_some() { if let Some((turn, delay)) = self.path_crosses_delay(now, &path, intersections, map) { ...
random
[ { "content": "fn use_parking_hints(map: &mut RawMap, path: String, timer: &mut Timer) {\n\n timer.start(\"apply parking hints\");\n\n let shapes: ExtraShapes = abstio::read_binary(path, timer);\n\n\n\n // Match shapes with the nearest road + direction (true for forwards)\n\n let mut closest: FindClo...
Rust
crates/doc/tests/reduce_annotations_test.rs
lideen999/flow
a6ac6c958c47d9102716227c0aedc25a280ddacf
#[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use(quickcheck)] extern crate quickcheck_macros; use doc::{reduce, Schema, SchemaIndexBuilder, Validation, Validator}; use itertools::{EitherOrBoth, Itertools}; use json::schema::build::build_schema; use serde::Deserialize; use serde_json::{json, Map, Value}; ...
#[cfg(test)] extern crate quickcheck; #[cfg(test)] #[macro_use(quickcheck)] extern crate quickcheck_macros; use doc::{reduce, Schema, SchemaIndexBuilder, Validation, Validator}; use itertools::{EitherOrBoth, Itertools}; use json::schema::build::build_schema; use serde::Deserialize; use serde_j
a", "sum": 1}, {"k": "ab", "sum": 3}, ]}, {"k": "b", "sum": 2}, {"k": "c", "sum": 33, "nodes": [ {"k": "cc", "fww": "foo"} ]}, ]}), ), ]; let mut lhs: Option<Value> = None; for (rhs, ...
son::{json, Map, Value}; use std::collections::BTreeMap; use url::Url; #[test] fn test_validate_then_reduce() { let schema = json!({ "properties": { "min": { "type": "integer", "reduce": {"strategy": "minimize"} }, "max": { ...
random
[ { "content": "use super::Error;\n\nuse doc::{inference, Schema as CompiledSchema};\n\nuse itertools::{EitherOrBoth, Itertools};\n\nuse json::schema::types;\n\nuse models::{self, build, tables};\n\nuse superslice::Ext;\n\nuse url::Url;\n\n\n\npub struct Shape {\n\n // Schema URL, including fragment pointer.\n...
Rust
crates/bls-crypto/src/bls/secret.rs
gtank/celo-bls-snark-rs
eca15ffed3984601cb441600ba3002d12f339e5f
use crate::{BLSError, HashToCurve, PublicKey, Signature, POP_DOMAIN, SIG_DOMAIN}; use ark_bls12_377::{Fr, G1Projective}; use ark_ec::group::Group; use ark_ff::UniformRand; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, SerializationError}; use rand::Rng; use std::io::{Read, Write}; #[derive(Clone, Debu...
use crate::{BLSError, HashToCurve, PublicKey, Signature, POP_DOMAIN, SIG_DOMAIN}; use ark_bls12_377::{Fr, G1Projective}; use ark_ec::group::Group; use ark_ff::UniformRand; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, SerializationError}; use rand::Rng; use std::io::{Read, Write}; #[derive(Clone, Debu...
#[test] fn test_pop() { let rng = &mut thread_rng(); let direct_hasher = DirectHasher; let try_and_increment = TryAndIncrement::<_, <Parameters as Bls12Parameters>::G1Parameters>::new( &direct_hasher, ); let sk = PrivateKey::generate(rng...
fn test_simple_sig_with_hasher<X: Hasher<Error = BLSError>>(hasher: X) { let rng = &mut thread_rng(); let try_and_increment = TryAndIncrement::<_, <Parameters as Bls12Parameters>::G1Parameters>::new(&hasher); for _ in 0..10 { let mut message: Vec<u8> = vec![]; ...
function_block-full_function
[ { "content": "/// Initializes the Hash To Bits and Validator Set Update circuits with random parameters\n\n/// seeded by the provided RNG over BLS12-377 and BW6_761.\n\n///\n\n/// `hashes_in_bls_12377` should be set to `true` if you're using the 2-SNARK technique,\n\n/// which will perform 2 setups, one for the...
Rust
brane-api/src/packages.rs
onnovalkering/brane
e2a0e5a8659db6454fd73d8cd99bc610b84043ea
use crate::Context; use anyhow::{Context as _, Result}; use bytes::Bytes; use flate2::read::GzDecoder; use scylla::cql_to_rust::FromCqlVal; use scylla::macros::{FromUserType, IntoUserType}; use scylla::Session; use specifications::package::PackageInfo; use std::convert::{TryFrom, TryInto}; use std::sync::Arc; use tar::...
use crate::Context; use anyhow::{Context as _, Result}; use bytes::Bytes; use flate2::read::GzDecoder; use scylla::cql_to_rust::FromCqlVal; use scylla::macros::{FromUserType, IntoUserType}; use scylla::Session; use specifications::package::PackageInfo; use std::convert::{TryFrom, TryInto}; use std::sync::Arc; use tar::...
let tar = GzDecoder::new(&temp_file); Archive::new(tar).unpack(&temp_dir).map_err(|e| { error!("An error occured while extracting a package archive: {}", e); warp::reject::reject() })?; let package_info_file = temp_dir.path().join("package.yml"); let package_info = PackageInfo::fro...
function_block-function_prefix_line
[ { "content": "/// Get the package endpoint of the Brane API.\n\npub fn get_packages_endpoint() -> Result<String> {\n\n let config_file = utils::get_config_dir().join(\"registry.yml\");\n\n let config = RegistryConfig::from_path(&config_file)\n\n .with_context(|| \"No registry configuration found, p...
Rust
src/runtime/src/core/list.rs
llogiq/koto
5de1953abe88b2decf3ba6ae2fcceb60154be68d
use { crate::{ runtime_error, value_sort::{compare_values, sort_values}, BinaryOp, Value, ValueIterator, ValueList, ValueMap, }, std::cmp::Ordering, std::ops::DerefMut, }; pub fn make_module() -> ValueMap { use Value::*; let mut result = ValueMap::new(); result.add...
use { crate::{ runtime_error, value_sort::{compare_values, sort_values}, BinaryOp, Value, ValueIterator, ValueList, ValueMap, }, std::cmp::Ordering, std::ops::DerefMut, }; pub fn make_module() -> ValueMap { use Value::*; let mut result = ValueMap::new(); result.add...
); result.add_fn("resize", |vm, args| match vm.get_args(args) { [List(l), Number(n), value] => { if *n < 0.0 { return runtime_error!("list.resize: Negative sizes aren't allowed"); } l.data_mut().resize(n.into(), value.clone()); Ok(Empty) ...
match vm.get_args(args) { [List(l), Number(n)] => { if *n < 0.0 { return runtime_error!("list.remove: Negative indices aren't allowed"); } let index: usize = n.into(); if index >= l.data().len() { return runtime_error!( ...
if_condition
[ { "content": "/// Sorts values in a slice using Koto operators for comparison.\n\npub fn sort_values(vm: &mut Vm, arr: &mut [Value]) -> Result<(), RuntimeError> {\n\n let mut error = None;\n\n\n\n arr.sort_by(|a, b| {\n\n if error.is_some() {\n\n return Ordering::Equal;\n\n }\n\n\...
Rust
rust/src/storage/mod.rs
nevi-me/delta.rs
6471b20a8798b0577829592cf54650e5a05b2e83
use chrono::{DateTime, Utc}; use rusoto_core::RusotoError; use rusoto_s3; use thiserror; pub mod file; pub mod s3; #[derive(thiserror::Error, Debug)] pub enum UriError { #[error("Invalid URI scheme: {0}")] InvalidScheme(String), #[error("Object URI missing bucket")] MissingObjectBucket, #[error("O...
use chrono::{DateTime, Utc}; use rusoto_core::RusotoError; use rusoto_s3; use thiserror; pub mod file; pub mod s3; #[derive(thiserror::Error, Debug)] pub enum UriError { #[error("Invalid URI scheme: {0}")] InvalidScheme(String), #[error("Object URI missing bucket")] MissingObjectBucket, #[error("O...
}
fn test_parse_object_uri() { let uri = parse_uri("s3://foo/bar").unwrap(); assert_eq!( uri.as_s3object().unwrap(), s3::S3Object { bucket: "foo", key: "bar", } ); }
function_block-full_function
[ { "content": "pub fn open_table_with_ds(table_path: &str, ds: &str) -> Result<DeltaTable, DeltaTableError> {\n\n let datetime = DateTime::<Utc>::from(DateTime::<FixedOffset>::parse_from_rfc3339(ds)?);\n\n let storage_backend = storage::get_backend_for_uri(table_path)?;\n\n let mut table = DeltaTable::n...
Rust
src/chart/dual_coord.rs
ahcm/plotters
ba6800785c1e906d7be2a1f7c02d272a8e61f5ce
use std::borrow::{Borrow, BorrowMut}; use std::fmt::Debug; use std::ops::{Deref, DerefMut}; use super::context::{ChartContext, SeriesAnno}; use super::mesh::SecondaryMeshStyle; use crate::coord::{CoordTranslate, Ranged, RangedCoord, ReverseCoordTranslate}; use crate::drawing::backend::{BackendCoord, DrawingBackend};...
use std::borrow::{Borrow, BorrowMut}; use std::fmt::Debug; use std::ops::{Deref, DerefMut}; use super::context::{ChartContext, SeriesAnno}; use super::mesh::SecondaryMeshStyle; use crate::coord::{CoordTranslate, Ranged, RangedCoord, ReverseCoordTranslate}; use crate::drawing::backend::{BackendCoord, DrawingBackend};...
} impl<'a, DB: DrawingBackend, CT1: CoordTranslate, CT2: CoordTranslate> Borrow<ChartContext<'a, DB, CT1>> for DualCoordChartContext<'a, DB, CT1, CT2> { fn borrow(&self) -> &ChartContext<'a, DB, CT1> { &self.primiary } } impl<'a, DB: DrawingBackend, CT1: CoordTranslate, CT2: CoordTranslate> B...
r<'b> &'b E: PointCollection<'b, (SX::ValueType, SY::ValueType)>, E: Drawable<DB>, R: Borrow<E>, S: IntoIterator<Item = R>, { self.secondary.draw_series_impl(series)?; Ok(self.primiary.alloc_series_anno()) }
function_block-function_prefixed
[ { "content": "type SeriesAnnoDrawFn<'a, DB> = dyn Fn(BackendCoord) -> DynElement<'a, DB, BackendCoord> + 'a;\n\n\n\n/// The annotations (such as the label of the series, the legend element, etc)\n\n/// When a series is drawn onto a drawing area, an series annotation object\n\n/// is created and a mutable refere...
Rust
crates/server/src/ctrl/user/me/account.rs
Lantern-chat/server
7dfc00130dd4f8ee6a7b9efac9b7866ebf067e6d
use futures::FutureExt; use sdk::models::Snowflake; use smol_str::SmolStr; use thorn::pg::ToSql; use crate::{ ctrl::{ util::validation::{validate_email, validate_password, validate_username, USERNAME_SANITIZE_REGEX}, Error, }, web::auth::Authorization, ServerState, }; use crate::ctrl::...
use futures::FutureExt; use sdk::models::Snowflake; use smol_str::SmolStr; use thorn::pg::ToSql; use crate::{ ctrl::{ util::validation::{validate_email, validate_password, validate_username, USERNAME_SANITIZE_REGEX}, Error, }, web::auth::Authorization, ServerState, }; use crate::ctrl::...
hash, Users::MfaSecret, Users::MfaBackup, ]) .and_where(Users::Id.equals(Var::of(Users::Id))) }, &[&auth.user_id], ) .await?; let user = match user { Some(user) => user, N...
function_block-function_prefixed
[ { "content": "pub fn validate_password(config: &Config, password: &str) -> Result<(), Error> {\n\n if !config.account.password_len.contains(&password.len()) || !PASSWORD_REGEX.is_match(password) {\n\n return Err(Error::InvalidPassword);\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/...
Rust
lib/codec/src/lib.rs
sudharsh/vector
8b61656965f630582187a18e04d0812484ad9196
extern crate bytes; extern crate tokio_codec; #[macro_use] extern crate tracing; use bytes::{BufMut, Bytes, BytesMut}; use std::{cmp, io, usize}; use tokio_codec::{Decoder, Encoder}; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct BytesDelimitedCodec { delim: u8, max_length: us...
extern crate bytes; extern crate tokio_codec; #[macro_use] extern crate tracing; use bytes::{BufMut, Bytes, BytesMut}; use std::{cmp, io, usize}; use tokio_co
max_length, ..BytesDelimitedCodec::new(delim) } } pub fn max_length(&self) -> usize { self.max_length } fn discard(&mut self, newline_offset: Option<usize>, read_to: usize, buf: &mut BytesMut) { let discard_to = if let Some(offset) = newline_offset { ...
dec::{Decoder, Encoder}; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct BytesDelimitedCodec { delim: u8, max_length: usize, is_discarding: bool, next_index: usize, } impl BytesDelimitedCodec { pub fn new(delim: u8) -> Self { BytesDelimitedCodec { ...
random
[ { "content": "fn default_max_line_bytes() -> usize {\n\n bytesize::kib(100u64) as usize\n\n}\n\n\n\nimpl Default for FileConfig {\n\n fn default() -> Self {\n\n Self {\n\n include: vec![],\n\n exclude: vec![],\n\n file_key: Some(\"file\".to_string()),\n\n ...
Rust
core/src/avm2/globals/flash/events/textevent.rs
dumpmemory/ruffle
dde21a2a606c479e96b454e9eba54084ae173b85
use crate::avm2::activation::Activation; use crate::avm2::class::{Class, ClassAttributes}; use crate::avm2::events::EventData; use crate::avm2::method::{Method, NativeMethodImpl}; use crate::avm2::names::{Namespace, QName}; use crate::avm2::object::{Object, TObject}; use crate::avm2::value::Value; use crate::avm2::Erro...
use crate::avm2::activation::Activation; use crate::avm2::class::{Class, ClassAttributes}; use crate::avm2::events::EventData; use crate::avm2::method::{Method, NativeMethodImpl}; use crate::avm2::names::{Namespace, QName}; use crate::avm2::object::{Object, TObject}; use crate::avm2::value::Value; use crate::avm2::Erro...
return Ok(Value::String(*text)); } } } Ok(Value::Undefined) } pub fn create_class<'gc>(mc: MutationContext<'gc, '_>) -> GcCell<'gc, Class<'gc>> { let class = Class::new( QName::new(Namespace::package("flash.events"), "TextEvent"), Some(QName::new(Namespa...
::IOError { ref mut text, .. } => { *text = text_arg; } EventData::SecurityError { ref mut text, .. } => { *text = text_arg; } _ => {} } } } Ok(Value::Undefined) } fn class_init<'gc>( ...
random
[ { "content": "pub fn root_error_handler<'gc>(activation: &mut Activation<'_, 'gc, '_>, error: Error<'gc>) {\n\n match &error {\n\n Error::ThrownValue(value) => {\n\n let message = value\n\n .coerce_to_string(activation)\n\n .unwrap_or_else(|_| \"undefined\".int...
Rust
src/ld_so/start.rs
rulibc/rulibc
fddc790cbdabcba6a469ae86a7f44fd422c6cb10
use alloc::{ borrow::ToOwned, boxed::Box, collections::BTreeMap, string::{String, ToString}, vec::Vec, }; use crate::{ c_str::CStr, header::{sys_auxv::AT_NULL, unistd}, platform::{new_mspace, types::c_char}, start::Stack, sync::mutex::Mutex, ALLOCATOR, }; use super::{ ...
use alloc::{ borrow::ToOwned, boxed::Box, collections::BTreeMap, string::{String, ToString}, vec::Vec, }; use crate::{ c_str::CStr, header::{sys_auxv::AT_NULL, unistd}, platform::{new_mspace, types::c_char}, start::Stack, sync::mutex::Mutex, ALLOCATOR, }; use super::{ ...
led to link '{}': missing entry", path); unistd::_exit(1); loop {} } }, Err(err) => { eprintln!("ld.so: failed to link '{}': {}", path, err); unistd::_exit(1); loop {} } }; if let Err(e) = linker.run_init(Non...
ap(); if phdr != 0 { let p = DSO { name: path.to_owned(), entry_point: *auxv.get(&AT_ENTRY).unwrap(), base_addr: phdr - 0x40, }; pr = Some(p); } ...
random
[ { "content": "pub fn static_init(sp: &'static Stack) {\n\n let mut phdr_opt = None;\n\n let mut phent_opt = None;\n\n let mut phnum_opt = None;\n\n\n\n let mut auxv = sp.auxv();\n\n loop {\n\n let (kind, value) = unsafe { *auxv };\n\n if kind == AT_NULL {\n\n break;\n\n ...
Rust
src/days/day12.rs
zoewithabang/rust-aoc-2018
aae2a2d03eb3df7bb149bb88df3ded5096503147
use crate::days::Day; use std::collections::BTreeMap; use std::error::Error; use std::fs; use std::str::FromStr; pub struct Day12 { input: String, } impl Day12 { pub fn new() -> Day12 { let input = fs::read_to_string("res/day12.txt").unwrap(); Day12 { input } } } impl Day for Day12 { ...
use crate::days::Day; use std::collections::BTreeMap; use std::error::Error; use std::fs; use std::str::FromStr; pub struct Day12 { input: String, } impl Day12 { pub fn new() -> Day12 { let input = fs::read_to_string("res/day12.txt").unwrap(); Day12 { input } } } impl Day for Day12 { ...
}); next_generation_pots.insert(i, next_result.clone()); }); self.number += 1; Ok(Generation::new( self.number + 1, next_generation_pots, self.transitions.clone(), )?) } fn pad_pots(&mut self) -> Result<(), Box<dyn ...
if transition .state .iter() .zip(&pot_group) .all(|(a, b)| b.is_some() && a == b.unwrap()) { next_result = transition.result.clone(); return; }
if_condition
[ { "content": "fn part2_summed_area(input: usize) -> String {\n\n const GRID_SIZE: usize = 300;\n\n\n\n let grid = SummedAreaFuelCellGrid::new(GRID_SIZE, input);\n\n let mut largest_total = 0;\n\n let mut largest_total_location = (0, 0);\n\n let mut largest_total_size = 0;\n\n\n\n for square_si...
Rust
src/patch_bin.rs
Slowerzs/pwninit
a8e665f0422a78d0bf72dd686e7b737815e6bad6
use crate::opts::Opts; use std::ffi::OsStr; use std::ffi::OsString; use std::fs; use std::io; use std::path::Path; use std::path::PathBuf; use std::process::Command; use colored::Colorize; use snafu::OptionExt; use snafu::ResultExt; use snafu::Snafu; #[derive(Debug, Snafu)] #[allow(clippy::enum_variant_names)] pub e...
use crate::opts::Opts; use std::ffi::OsStr; use std::ffi::OsString; use std::fs; use std::io; use std::path::Path; use std::path::PathBuf; use std::process::Command; use colored::Colorize; use snafu::OptionExt; use snafu::ResultExt; use snafu::Snafu; #[derive(Debug, Snafu)] #[allow(clippy::enum_variant_names)] pub e...
if let Some(libc) = &opts.libc { symlink_libc(libc)?; } let bin_patched = copy_patched(bin)?; run_patchelf(&bin_patched, opts)?; } Ok(()) }
function_block-function_prefix_line
[]
Rust
sdk/cosmos/src/requests/create_document_builder.rs
cschaible/azure-sdk-for-rust
2876e88bae97377b926cacc24e78c186b0b909ee
use crate::prelude::*; use crate::responses::CreateDocumentResponse; use crate::ResourceType; use azure_core::errors::UnexpectedHTTPResult; use azure_core::prelude::*; use azure_core::{No, ToAssign, Yes}; use chrono::{DateTime, Utc}; use http::StatusCode; use serde::Serialize; use std::convert::TryFrom; use std::marker...
use crate::prelude::*; use crate::responses::CreateDocumentResponse; use crate::ResourceType; use azure_core::errors::UnexpectedHTTPResult; use azure_core::prelude::*; use azure_core::{No, ToAssign, Yes}; use chrono::{DateTime, Utc}; use http::StatusCode; use serde::Serialize; use std::convert::TryFrom; use std::marker...
lt::new( StatusCode::CREATED, response.status(), std::str::from_utf8(response.body())?, ) .into()); } else if response.status() != StatusCode::CREATED && response.status() != StatusCode::OK { return Err(UnexpectedHTTPResult::new...
if_match_condition: self.if_match_condition, if_modified_since: self.if_modified_since, user_agent: self.user_agent, activity_id: self.activity_id, consistency_level: self.consistency_level, allow_tentative_writes: self.allow_tentative_writes, } ...
random
[ { "content": "#[inline]\n\npub fn utc_date_from_rfc2822(date: &str) -> Result<DateTime<Utc>, AzureError> {\n\n let date = DateTime::parse_from_rfc2822(date)?;\n\n Ok(DateTime::from_utc(date.naive_utc(), Utc))\n\n}\n\n\n", "file_path": "sdk/core/src/headers/utilities.rs", "rank": 0, "score": 26...
Rust
src/libstd/num/int_macros.rs
klutzy/rust
13dafa09f1a80b8b50f41cab42ac2bfd24dfa6b9
#[macro_escape]; #[doc(hidden)]; macro_rules! int_module (($T:ty, $bits:expr) => ( pub static BITS : uint = $bits; pub static BYTES : uint = ($bits / 8); pub static MIN: $T = (-1 as $T) << (BITS - 1); pub static MAX: $T = !MIN; impl CheckedDiv for $T { #[inline] fn checked_div(&self, v: &$T) -> Option<$...
#[macro_escape]; #[doc(hidden)]; macro_rules! int_module (($T:ty, $bits:expr) => ( pub static BITS : uint = $bits; pub static BYTES : uint = ($bits / 8); pub static MIN: $T = (-1 as $T) << (BITS - 1); pub static MAX: $T = !MIN; impl CheckedDiv for $T { #[inline] fn checked_div(&self, v: &$T) -> Option<$...
>("0"), Some(0 as $T)); assert_eq!(from_str::<$T>("3"), Some(3 as $T)); assert_eq!(from_str::<$T>("10"), Some(10 as $T)); assert_eq!(from_str::<i32>("123456789"), Some(123456789 as i32)); assert_eq!(from_str::<$T>("00100"), Some(100 as $T)); assert_eq!(from_str::<$T>("-1"), Some...
_eq!(0b1110 as $T, (0b1100 as $T).bitor(&(0b1010 as $T))); assert_eq!(0b1000 as $T, (0b1100 as $T).bitand(&(0b1010 as $T))); assert_eq!(0b0110 as $T, (0b1100 as $T).bitxor(&(0b1010 as $T))); assert_eq!(0b1110 as $T, (0b0111 as $T).shl(&(1 as $T))); assert_eq!(0b0111 as $T, (0b1110 as $T)...
random
[ { "content": "#[inline]\n\npub fn to_str_bytes<U>(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U {\n\n // The radix can be as low as 2, so we need at least 64 characters for a\n\n // base 2 number.\n\n let mut buf = [0u8, ..64];\n\n let mut cur = 0;\n\n strconv::int_to_str_bytes_common(n, radix, st...
Rust
src/cli/filter.rs
hhandika/segul
f573aa78fda126fee2d52944f7e14f3232311c00
use std::path::{Path, PathBuf}; use ansi_term::Colour::Yellow; use clap::ArgMatches; use crate::cli::{ConcatCli, InputCli, InputPrint, OutputCli}; use crate::core::filter::{Params, SeqFilter}; use crate::helper::finder::IDs; use crate::helper::types::{DataType, InputFmt, OutputFmt, PartitionFmt}; use crate::helper::{...
use std::path::{Path, PathBuf}; use ansi_term::Colour::Yellow; use clap::ArgMatches; use crate::cli::{ConcatCli, InputCli, InputPrint, OutputCli}; use crate::core::filter::{Params, SeqFilter}; use crate::helper::finder::IDs; use crate::helper::types::{DataType, InputFmt, OutputFmt, PartitionFmt}; use crate::helper::{...
fn count_percent_inf(&self) -> f64 { let perc_inf = self .matches .value_of("percent-inf") .expect("Failed parsing percent informative values"); perc_inf .parse::<f64>() .expect("Failed parsing percent inf to floating points") } ...
fn get_params(&mut self) { self.params = match self.matches { m if m.is_present("percent") => { self.percent = self.get_percent(); self.count_ntax(); let min_taxa = self.count_min_tax(); Params::MinTax(min_taxa) } ...
function_block-full_function
[ { "content": "pub fn create_output_fname(dir: &Path, file: &Path, output_fmt: &OutputFmt) -> PathBuf {\n\n let path = dir.join(\n\n file.file_name()\n\n .expect(\"Failed parsing filename for output file\"),\n\n );\n\n create_output_fname_from_path(&path, output_fmt)\n\n}\n\n\n", "...
Rust
base/src/context/device.rs
Houjuu-Nue/Vulkan
a69c01a6da7bf4eb7154146081e89e317ba4c5a6
mod physical; mod logical; mod queue; pub use self::logical::{VkLogicalDevice, VkQueue, LogicDevConfig}; pub use self::physical::{VkPhysicalDevice, PhysicalDevConfig}; use ash::vk; use ash::version::DeviceV1_0; use crate::ci::command::{CommandPoolCI, CommandBufferAI}; use crate::ci::pipeline::PipelineCacheCI; use c...
mod physical; mod logical; mod queue; pub use self::logical::{VkLogicalDevice, VkQueue, LogicDevConfig}; pub use self::physical::{VkPhysicalDevice, PhysicalDevConfig}; use ash::vk; use ash::version::DeviceV1_0; use crate::ci::command::{CommandPoolCI, CommandBufferAI}; use crate::ci::pipeline::PipelineCacheCI; use c...
pub(super) fn drop_self(self) { self.discard(self.transfer_cmd_pool); self.discard(self.pipeline_cache); drop(self.vma); } } impl VkDevice { #[inline] pub fn build<T>(&self, ci: &T) -> VkResult<T::ObjectType> where T: crate::ci::VkObjectBuildable...
pub fn flush_transfer(&self, recorder: VkCmdRecorder<ITransfer>) -> VkResult<()> { recorder.flush_copy_command(self.logic.queues.transfer.handle)?; unsafe { self.logic.handle.reset_command_buffer(self.transfer_command, vk::CommandBufferResetFlags::RELEASE_RESOURCES) ...
function_block-function_prefix_line
[ { "content": "pub fn get_memory_type_index(device: &VkDevice, mut type_bits: vkuint, properties: vk::MemoryPropertyFlags) -> vkuint {\n\n\n\n // Iterate over all memory types available for the device used in this example.\n\n let memories = &device.phy.memories;\n\n for i in 0..memories.memory_type_cou...
Rust
examples/runngcat.rs
jeikabu/runng_examples
d5325cb98586bf3059b4fd38eefbd218e8c44beb
use clap::{App, Arg, ArgGroup, ArgMatches}; use env_logger::{Builder, Env}; use log::info; use runng::{protocol::Subscribe, *}; use std::{thread, time::Duration}; fn connect<T>(socket: &mut T, url: &str, is_dial: bool) -> Result<()> where T: Dial + Listen, { if is_dial { socket.dial(url).and(Ok(())) ...
use clap::{App, Arg, ArgGroup, ArgMatches}; use env_logger::{Builder, Env}; use log::info; use runng::{protocol::Subscribe, *}; use std::{thread, time::Duration}; fn connect<T>(socket: &mut T, url: &str, is_dial: bool) -> Result<()> where T: Dial + Listen, { if is_dial { socket.dial(url).and(Ok(())) ...
fn handle_delay<'a>(matches: &ArgMatches<'a>) { if let Some(delay) = matches.value_of("delay") { let delay = delay.parse::<u64>().unwrap(); thread::sleep(Duration::from_secs(delay)); } } fn handle_received_msg<'a>(_matches: &ArgMatches<'a>, msg: msg::NngMsg) { info!("Received {:?}", msg);...
fn handle_data<'a>(matches: &ArgMatches<'a>) -> Result<msg::NngMsg> { let mut msg = msg::NngMsg::new()?; if let Some(data) = matches.value_of("data") { msg.append_slice(data.as_bytes())?; } Ok(msg) }
function_block-full_function
[ { "content": "fn latency(crit: &mut Criterion, url: &str) -> NngReturn {\n\n let url = url.to_owned();\n\n\n\n let parameters: Vec<usize> = vec![0, 128, 1024, 4 * 1024, 16 * 1024];\n\n\n\n let factory = Latest::default();\n\n let mut pusher = factory.pusher_open()?.listen(&url)?.create_async()?;\n\n...
Rust
tests/ef_tests/src/cases/vm.rs
lightclient/evm
714f16bdde8b458ccd1646cf92eace0a4a7c5674
use crate::cases::{Case, LoadCase}; use crate::decode::{from_hex_to_buffer, from_hex_to_u64, json_decode_file}; use crate::error::Error; use crate::fake_host::FakeHost; use fast_evm::{ account::Account, env::Environment, execute::execute, host::Host, interupt::Exit, message::{Inner as MessageBo...
use crate::cases::{Case, LoadCase}; use crate::decode::{from_hex_to_buffer, from_hex_to_u64, json_decode_file}; use crate::error::Error; use crate::fake_host::FakeHost; use fast_evm::{ account::Account, env::Environment, execute::execute, host::Host, interupt::Exit, message::{Inner as MessageBo...
nwrap(); for (address, expected) in post { let actual = host.state.get(&address); if actual.is_none() { return Err(Error::NotEqual(format!( "Couldn't load account from json: {:?}", address ))); } ...
pub post: Option<BTreeMap<H160, TestAccount>>, pub pre: BTreeMap<H160, TestAccount>, } impl Vm { pub fn pre_state(&self) -> BTreeMap<H160, Account> { let mut state = BTreeMap::<H160, Account>::new(); for (h, a) in self.pre.iter() { state.insert(h.clone(), Account::from(a)); ...
random
[ { "content": "/// Deserializes a lowercase hex string to a `Vec<u8>`.\n\npub fn from_hex_to_u64<'de, D>(deserializer: D) -> Result<u64, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n use serde::de::Error;\n\n String::deserialize(deserializer).and_then(|string| {\n\n let without_prefix = s...
Rust
src/main.rs
joaocarvalhoopen/Audio_noise_WAV_generator_in_Rust
08596c3e01ac45d8e287152d28a453c653b80796
use std::env; use std::process; use rand::Rng; use rand::rngs::ThreadRng; use hound; const BUF_SIZE: usize = 4096; static USAGE: &str = " Usage: \"audio_noise_gen [white|pink|brown] duration_in_sec filename.wav\" ."; fn main() { println!("Audio noise generator..."); let args: Vec<String> = env::args().c...
use std::env; use std::process; use rand::Rng; use rand::rngs::ThreadRng; use hound; const BUF_SIZE: usize = 4096; static USAGE: &str = " Usage: \"audio_noise_gen [white|pink|brown] duration_in_sec filename.wav\" ."; fn main() { println!("Audio noise generator..."); let args: Vec<String> = env::args().c...
for sample in &noise_buf.buf { let amplitude = i16::MAX as f32; writer.write_sample((sample * amplitude) as i16).unwrap_or_else(|err| { println!(" Error writing to file ...\n {}", err); println!("{}", USAGE); process::exit(1); ...
match config.noise_type { NoiseType::White => noise_buf.fill_with_white_noise(), NoiseType::Pink => noise_buf.fill_with_pink_noise(), NoiseType::Brown => noise_buf.fill_with_brown_noise(), }
if_condition
[ { "content": "# Audio noise WAV generator in Rust\n\nThis is a fast console program written in Rust.\n\n\n\n## Description\n\n`Audio_noise_gen` is a console program to generate a noise WAV file with n seconds. The noise can be white noise, pink noise or brown noise. This program was developed and tested on Linu...
Rust
console-frontend/src/examples/data.rs
garyedwards/drogue-cloud
f40f63ba1c876ca3221e952374e140d1debe1fec
use crate::data::{self, SharedDataBridge, SharedDataOps}; use drogue_cloud_service_api::endpoints::Endpoints; use patternfly_yew::*; use serde_json::json; use yew::prelude::*; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ExampleData { pub app_id: String, pub device_id: String, pub password: String, ...
use crate::data::{self, SharedDataBridge, SharedDataOps}; use drogue_cloud_service_api::endpoints::Endpoints; use patternfly_yew::*; use serde_json::json; use yew::prelude::*; #[derive(Clone, Debug, PartialEq, Eq)] pub struct ExampleData { pub app_id: String, pub device_id: String, pub password: String, ...
l_cert} label="Use local test certificates" label_off="Use system default certificates" on_change={ctx.link().callback(|data| Msg::SetLocalCerts(data))} /> </Card> </StackI...
etPayload(payload) => self.data_agent.update(|mut data| data.payload = payload), Msg::SetLocalCerts(local_certs) => self .data_agent .update(move |mut data| data.enable_local_cert = local_certs), Msg::SetData(data) => self.data = Some(data), } true...
random
[ { "content": "#[inline]\n\npub fn realm() -> String {\n\n \"drogue\".into()\n\n}\n\n\n", "file_path": "service-common/src/defaults.rs", "rank": 0, "score": 279175.49357108516 }, { "content": "#[inline]\n\npub fn instance() -> String {\n\n \"drogue\".into()\n\n}\n", "file_path": "se...
Rust
src/miner/state.rs
gallactic/sputnikvm-dev
095ee7d46a0dae5f16d76fda4e1b2c505e601972
use rlp; use error::Error; use block::{Receipt, Block, TotalHeader, HeaderHash, Transaction}; use trie::{MemoryDatabase}; use bigint::{H256, M256, U256, Address}; use sha3::{Digest, Keccak256}; use secp256k1::key::SecretKey; use sputnikvm::AccountChange; use sputnikvm_stateful::{MemoryStateful}; use std::collections::...
use rlp; use error::Error; use block::{Receipt, Block, TotalHeader, HeaderHash, Transaction}; use trie::{MemoryDatabase}; use bigint::{H256, M256, U256, Address}; use sha3::{Digest, Keccak256}; use secp256k1::key::SecretKey; use sputnikvm::AccountChange; use sputnikvm_stateful::{MemoryStateful}; use std::collections::...
pub fn fat_transit(&mut self, number: usize, accounts: &[AccountChange]) { while number >= self.fat_database.len() { let last = self.fat_database.last().unwrap().clone(); self.fat_database.push(last); } let database = &mut self.fat_database[number]; for acc...
ent = self.total_header_database.get(&parent_hash).unwrap().clone(); self.total_header_database.insert(hash, TotalHeader::from_parent(block.header.clone(), &parent)); self.block_hashes.push(hash); self.current_block = hash; hash }
function_block-function_prefixed
[]
Rust
src/traits.rs
binayyakbhroy/sailfish
a022abaaa86107238e53c20197b830393813793e
use crate::{ BoundaryCondition, Coordinates, Device, EquationOfState, ExecutionMode, IndexSpace, Mesh, Patch, PointMassList, StructuredMesh, }; use gridiron::adjacency_list::AdjacencyList; use gridiron::automaton::Automaton; use gridiron::rect_map::Rectangle; use std::sync::Arc; pub trait Solve { ...
use crate::{ BoundaryCondition, Coordinates, Device, EquationOfState, ExecutionMode, IndexSpace, Mesh, Patch, PointMassList, StructuredMesh, }; use gridiron::adjacency_list::AdjacencyList; use gridiron::automaton::Automaton; use gridiron::rect_map::Rectangle; use std::sync::Arc; pub trait Solve { ...
} pub trait PatchBasedBuild { type Solver: PatchBasedSolve; #[allow(clippy::too_many_arguments)] fn build( &self, time: f64, primitive: Patch, global_structured_mesh: StructuredMesh, edge_list: &AdjacencyList<Rectangle<i64>>, rk_order: usize, mode: ...
fn advance(&mut self, setup: &dyn Setup, rk_order: u32, time: f64, dt: f64) { self.new_timestep(time); match rk_order { 1 => { self.advance_rk(setup, time, 0.0, dt); } 2 => { self.advance_rk(setup, time + 0.0 * dt, 0.0, dt); ...
function_block-full_function
[ { "content": "/// Tries to construct a dynamic setup from a string key and model parameter\n\n/// string.\n\n///\n\n/// The result is put under `Arc` so it can be attached to solver instances\n\n/// and shared safely between threads. If no setup matches the given name, a\n\n/// `PrintUserInformation` error is r...
Rust
sway-core/src/control_flow_analysis/flow_graph/mod.rs
wschwab/sway
34e5b7eba04e9483ffdeaecb92c5951215a10856
use crate::{ semantic_analysis::{ast_node::TypedEnumVariant, ast_node::TypedStructField, TypedAstNode}, Ident, }; use sway_types::span::Span; use petgraph::{graph::EdgeIndex, prelude::NodeIndex}; mod namespace; use namespace::ControlFlowNamespace; pub(crate) use namespace::FunctionNamespaceEntry; pub type...
use crate::{ semantic_analysis::{ast_node::TypedEnumVariant, ast_node::TypedStructField, TypedAstNode}, Ident, }; use sway_types::span::Span; use petgraph::{graph::EdgeIndex, prelude::NodeIndex}; mod namespace; use namespace::ControlFlowNamespace; pub(crate) use namespace::FunctionNamespaceEntry; pub type...
} impl std::convert::From<&TypedAstNode> for ControlFlowGraphNode { fn from(other: &TypedAstNode) -> Self { ControlFlowGraphNode::ProgramNode(other.clone()) } } impl std::convert::From<&TypedEnumVariant> for ControlFlowGraphNode { fn from(other: &TypedEnumVariant) -> Self { ControlFlowGra...
or(s) => s.to_string(), ControlFlowGraphNode::ProgramNode(node) => format!("{:?}", node), ControlFlowGraphNode::EnumVariant { variant_name, .. } => { format!("Enum variant {}", variant_name.to_string()) } ControlFlowGraphNode::MethodDeclaration { method_na...
function_block-function_prefixed
[ { "content": "/// Performs the formatting of the `comments` section in your code.\n\n/// Takes in a function that provides the logic to handle the rest of the code.\n\nfn custom_format_with_comments<F>(text: &str, custom_format_fn: &mut F) -> String\n\nwhere\n\n F: FnMut(&str, &mut String, char, &mut Peekabl...
Rust
src/decision_makers/sequencer.rs
PsichiX/emergent
d83c9ab0822aae724399a2f5bf0f9333832fc93a
use crate::{condition::*, decision_makers::*, task::*}; pub struct SequencerState<M = ()> { condition: Box<dyn Condition<M>>, task: Box<dyn Task<M>>, } impl<M> SequencerState<M> { pub fn new<C, T>(condition: C, task: T) -> Self where C: Condition<M> + 'static, T: Task<M> + 'stat...
use crate::{condition::*, decision_makers::*, task::*}; pub struct SequencerState<M = ()> { condition: Box<dyn Condition<M>>, task: Box<dyn Task<M>>, } impl<M> SequencerState<M> { pub fn new<C, T>(condition: C, task: T) -> Self where C: Condition<M> + 'static, T: Task<M> + 'stat...
pub fn update(&mut self, memory: &mut M) { if let Some(index) = self.active_index { self.states.get_mut(index).unwrap().task.on_update(memory); } } } impl<M, K> DecisionMaker<M, K> for Sequencer<M> where K: Default, { fn decide(&mut self, memory: &mut M) -> Option<K> ...
self.states.get_mut(index).unwrap().task.on_enter(memory); self.active_index = Some(index); return true; } if let Some(index) = self.active_index { return self.states.get_mut(index).unwrap().task.on_process(memory); } false }
function_block-function_prefix_line
[ { "content": "/// Task represent unit of work, an action performed in a time.\n\n///\n\n/// Tasks can only manipulate what's in the memory passed to their life-cycle methods so common way\n\n/// of manipulating the world with tasks is to make memory type that can either command the world\n\n/// or even better, ...
Rust
tests/runner.rs
troiganto/scenarios
8f19d271b599409b86a82fc23a8472d42782bf1f
#![allow(dead_code)] use std::{ env, ffi::{OsStr, OsString}, path::{Path, PathBuf}, process::{Command, ExitStatus, Output}, }; #[cfg(windows)] static PROGRAM_NAME: &str = "scenarios.exe"; #[cfg(not(windows))] static PROGRAM_NAME: &str = "scenarios"; pub struct Runner { command: Command, te...
#![allow(dead_code)] use std::{ env, ffi::{OsStr, OsString}, path::{Path, PathBuf}, process::{Command, ExitStatus, Output}, }; #[cfg(windows)] static PROGRAM_NAME: &str = "scenarios.exe"; #[cfg(not(windows))] static PROGRAM_NAME: &st
self, filename: S) -> &mut Self { let path = self.get_scenario_file_path(filename); self.arg(path) } pub fn scenario_files<I>(&mut self, filenames: I) -> &mut Self where I: IntoIterator, I::Item: AsRef<Path>, { for filename in filenames { self.s...
r = "scenarios"; pub struct Runner { command: Command, tests_dir: PathBuf, } impl Runner { pub fn new() -> Self { Runner { command: Command::new(guess_bin_path()), tests_dir: guess_tests_dir_path(), } } pub fn arg<S: AsRef...
random
[ { "content": "/// Returns an [`App`] instance.\n\n///\n\n/// [`App`]: ../../clap/struct.App.html\n\npub fn get_app() -> clap::App<'static, 'static> {\n\n App::new(crate_name!())\n\n .version(crate_version!())\n\n .author(crate_authors!())\n\n .about(crate_description!())\n\n .usag...
Rust
benches/dispatch.rs
dekellum/blocking-perm
65f735ad65de63e2acd2a3cde529cad95524a1ad
#![cfg(any(feature = "tokio-semaphore", feature = "futures-intrusive"))] #![warn(rust_2018_idioms)] #![feature(test)] extern crate test; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; use std::time::Duration; #[cfg(feature="tangential")] use futures_executor as futr_exec; #[cfg(feature="tangentia...
#![cfg(any(feature = "tokio-semaphore", feature = "futures-intrusive"))] #![warn(rust_2018_idioms)] #![feature(test)] extern crate test; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; use std::time::Duration; #[cfg(feature="tangential")] use futures_executor as futr_exec; #[cfg(feature="tangentia...
fn expensive_comp() -> usize { let mut vals: Vec<usize> = (500..800).map(|v| (v % 101)).collect(); vals.shuffle(&mut rand::thread_rng()); vals.sort(); vals[vals.len() - 1] } fn random_sleep() -> usize { const DELAYS: [u64; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 12, 49]; thread::sleep(Duration::from_m...
fn rt_multi_thread( core: usize, blocking: Option<usize>, dispatch: Option<usize>) -> tokio::runtime::Runtime { struct AbortOnPanic; impl Drop for AbortOnPanic { fn drop(&mut self) { std::process::abort(); } } let mut bldr = tokio::runtime::Builder::new_mult...
function_block-full_function
[]
Rust
src/types/point.rs
woshilapin/wkt
1e3140b8fbe15b761d7ad54b7b408d92c41367b0
use std::fmt; use std::str::FromStr; use tokenizer::PeekableTokens; use types::coord::Coord; use {FromTokens, Geometry, WktFloat}; #[derive(Clone, Debug, Default)] pub struct Point<T: WktFloat>(pub Option<Coord<T>>); impl<T> Point<T> where T: WktFloat, { pub fn as_item(self) -> Geometry<T> { Geometr...
use std::fmt; use std::str::FromStr; use tokenizer::PeekableTokens; use types::coord::Coord; use {FromTokens, Geometry, WktFloat}; #[derive(Clone, Debug, Default)] pub struct Point<T: WktFloat>(pub Option<Coord<T>>); impl<T> Point<T> where T: WktFloat, { pub fn as_item(self) -> Geometry<T> { Geometr...
#[test] fn write_point_with_z_coord() { let point = Point(Some(Coord { x: 10.12345, y: 20.67891, z: Some(-32.56455), m: None, })); assert_eq!("POINT Z(10.12345 20.67891 -32.56455)", format!("{}", point)); } #[test] fn write_...
y: 20.67891, z: None, m: None, })); assert_eq!("POINT(10.12345 20.67891)", format!("{}", point)); }
function_block-function_prefix_line
[ { "content": "#[deprecated(since = \"0.9\", note = \"use `geometry.try_into()` instead\")]\n\npub fn try_into_geometry<T>(geometry: &Geometry<T>) -> Result<geo_types::Geometry<T>, Error>\n\nwhere\n\n T: CoordFloat,\n\n{\n\n geometry.clone().try_into()\n\n}\n\n\n\nimpl<'a, T> From<&'a LineString<T>> for ge...
Rust
src/http/common.rs
jeff-davis/rust-http
fc38f7440b85b4b520c694d0aa2b27c7d60ef6b3
/*! * Poorly categorised functions for reading things used in multiple places. * * (That is, typically, more than one of request-or-response reading-or-writing.) * * TODO: refactor all this to store things in more usefully categorised places. */ use std::num::{Zero, cast}; use std::io::{IoError, IoResult, OtherIo...
/*! * Poorly categorised functions for reading things used in multiple places. * * (That is, typically, more than one of request-or-response reading-or-writing.) * * TODO: refactor all this to store things in more usefully categorised places. */ use std::num::{Zero, cast}; use std::io::{IoError, IoResult, OtherIo...
Some(new_n) => new_n, None => return Err(bad_input()), } }, Ok(b@ASCII_LOWER_A..ASCII_LOWER_F) => { match n.checked_mul(&sixteen).and_then( |n| n.checked_add(&cast(b - ASCII_LOWER_A + 10).unwrap())) ...
mCast + Ord + CheckedMul + CheckedAdd> (reader: &mut R, expected_end: |u8| -> bool) -> IoResult<N> { let mut n: N = Zero::zero(); let mut got_content = false; let sixteen: N = cast(16).unwrap(); loop { n = match reader.read_byte() { Ok(b@...
function_block-random_span
[ { "content": "#[inline]\n\npub fn is_octet(_: u8) -> bool { true }\n\n\n\n/// CHAR: any US-ASCII character (octets 0 - 127)\n", "file_path": "src/http/rfc2616.rs", "rank": 2, "score": 227606.5836439848 }, { "content": "#[inline]\n\npub fn is_digit(octet: u8) -> bool { octet >= '0' as u8 && o...
Rust
cef/src/application/window_delegate.rs
hamaluik/cef-rs
26a7d927b01726c383e11ebd8114d478c2be44b8
use cef_ref_counting::{ref_count, RefCount}; use cef_sys::{ cef_base_ref_counted_t, cef_browser_view_t, cef_panel_delegate_t, cef_size_t, cef_view_delegate_t, cef_view_t, cef_window_delegate_t, cef_window_t, }; #[ref_count] #[derive(RefCount, Debug)] #[allow(unused)] pub struct WindowDelegate { pub window_...
use cef_ref_counting::{ref_count, RefCount}; use cef_sys::{ cef_base_ref_counted_t, cef_browser_view_t, cef_panel_delegate_t, cef_size_t, cef_view_delegate_t, cef_view_t, cef_window_delegate_t, cef_window_t, }; #[ref_count] #[derive(RefCount, Debug)] #[allow(unused)] pub struct WindowDelegate { pub window_...
unsafe extern "C" fn on_window_created( slf: *mut cef_window_delegate_t, window: *mut cef_window_t, ) { log::debug!("on_window_created, adding child view"); let slf = slf as *mut WindowDelegate; ((*window).base).add_child_view.unwrap()( &mut (*window).base, ...
e, can_maximize: None, can_minimize: None, can_close: Some(Self::can_close), on_accelerator: None, on_key_event: None, get_initial_bounds: None, get_initial_show_state: None, }, browse...
function_block-function_prefixed
[ { "content": "use std::mem::size_of;\n\n\n\nuse cef_ref_counting::{ref_count, RefCount};\n\nuse cef_sys::{\n\n cef_base_ref_counted_t, cef_browser_view_delegate_t, cef_browser_view_t, cef_view_delegate_t,\n\n cef_window_create_top_level, cef_window_delegate_t,\n\n};\n\n\n\nuse super::window_delegate::Wind...
Rust
crates/lua_parser/src/syntax_text.rs
baszalmstra/rs-lua-parser
b870aa3f6b39a8c472ab6df654a094262d8bc8b0
use std::{fmt, ops}; use crate::{SyntaxElement, SyntaxNode, TextRange, TextUnit}; #[derive(Clone)] pub struct SyntaxText<'a> { node: &'a SyntaxNode, range: TextRange, } impl<'a> SyntaxText<'a> { pub(crate) fn new(node: &'a SyntaxNode) -> SyntaxText<'a> { SyntaxText { node, ...
use std::{fmt, ops}; use crate::{SyntaxElement, SyntaxNode, TextRange, TextUnit}; #[derive(Clone)] pub struct SyntaxText<'a> { node: &'a SyntaxNode, range: TextRange, } impl<'a> SyntaxText<'a> { pub(crate) fn new(node: &'a SyntaxNode) -> SyntaxText<'a> { SyntaxText { node, ...
pub fn char_at(&self, offset: impl Into<TextUnit>) -> Option<char> { let mut start: TextUnit = 0.into(); let offset = offset.into(); for chunk in self.chunks() { let end = start + TextUnit::of_str(chunk); if start <= offset && offset < end { let off:...
pub fn slice(&self, range: impl SyntaxTextSlice) -> SyntaxText<'a> { let range = range.restrict(self.range).unwrap_or_else(|| { panic!("invalid slice, range: {:?}, slice: {:?}", self.range, range) }); SyntaxText { node: self.node, range, } }
function_block-full_function
[ { "content": "pub fn is_whitespace(c: char) -> bool {\n\n c.is_whitespace()\n\n}\n\n\n", "file_path": "crates/lua_parser/src/lexer/classes.rs", "rank": 0, "score": 158051.34655179532 }, { "content": "pub fn is_ident_continue(c: char) -> bool {\n\n (c >= 'a' && c <= 'z')\n\n || (...
Rust
src/joints/serialize/serialize_b2_friction_joint.rs
HumMan/box2d-rs
a9731ec7b3d6857c505498e1cccf154b1d688e2b
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer}; use serde::de::DeserializeSeed; use std::fmt; use std::rc::Rc; use std::cell::RefCell; use crate::b2_body::*; use crate::b2_settings::*; use crate::joints::b2_friction_joint::*;...
use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor}; use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer}; use serde::de::DeserializeSeed; use std::fmt; use std::rc::Rc; use std::cell::RefCell; use crate::b2_body::*; use crate::b2_settings::*; use crate::joints::b2_friction_joint::*;...
}
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(field_identifier, rename_all = "lowercase")] #[derive(EnumVariantNames)] #[allow(non_camel_case_types)] enum Field { ...
function_block-full_function
[ { "content": "struct B2fixtureVisitorContext<D: UserDataType> {\n\n\tpub(crate) body: BodyWeakPtr<D>,\n\n}\n\n\n\nimpl<'de, U: UserDataType> DeserializeSeed<'de> for B2fixtureVisitorContext<U> {\n\n\ttype Value = ();\n\n\n\n\tfn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>\n\n\twhere\n...
Rust
src/lib.rs
Trivernis/typemap_rev
5325517cb4f48a5d058c3f3b8b64b1d09e2cf22a
use std::any::{Any, TypeId}; use std::collections::HashMap; use std::collections::hash_map::{ Entry as HashMapEntry, OccupiedEntry as HashMapOccupiedEntry, VacantEntry as HashMapVacantEntry, }; use std::marker::PhantomData; use std::collections::hash_map::IntoIter; use std::iter::FromIterator; pub trait ...
use std::any::{Any, TypeId}; use std::collections::HashMap; use std::collections::hash_map::{ Entry as HashMapEntry, OccupiedEntry as HashMapOccupiedEntry, VacantEntry as HashMapVacantEntry, }; use std::marker::PhantomData; use std::collections::hash_map::IntoIter; use std::iter::FromIterator; pub trait ...
} #[inline] pub fn and_modify<F>(self, f: F) -> Self where F: FnOnce(&mut K::Value) { match self { Entry::Occupied(mut entry) => { f(entry.get_mut()); Entry::Occupied(entry) }, Entry::Vacant(entry) => Entry::Vacant...
match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(f()), }
if_condition
[ { "content": "# TypeMap Revitalized\n\n\n\nAn updated version of the crate [typemap](https://github.com/reem/rust-typemap) which is a hashmap whose keys are defined by types.\n\n\n\nOriginal code created by: [Acdenissk](https://github.com/acdenissk)\n\n\n\nCrate created by: [kingbri](https://github.com/bdashore...
Rust
src/token.rs
ArniDagur/rust-bdecode
ecc4ed4eb3baffd60cd68f76c5662cdacb1eb535
use std::fmt; use super::BdecodeError; const OFFSET_MASK: u64 = 0xFFFF_FFF8_0000_0000; const NEXT_ITEM_MASK: u64 = 0x0000_0007_FFFF_FFC0; const HEADER_MASK: u64 = 0x0000_0000_0000_0038; const TYPE_MASK: u64 = 0x0000_0000_0000_0007; const OFFSET_OFFSET: u64 = 35; const NEXT_ITEM_OFFSET: u64 = 6; const HEADER_OFFSET: ...
use std::fmt; use super::BdecodeError; const OFFSET_MASK: u64 = 0xFFFF_FFF8_0000_0000; const NEXT_ITEM_MASK: u64 = 0x0000_0007_FFFF_FFC0; const HEADER_MASK: u64 = 0x0000_0000_0000_0038; const TYPE_MASK: u64 = 0x0000_0000_0000_0007; const OFFSET_OFFSET: u64 = 35; const NEXT_ITEM_OFFSET: u64 = 6; const HEADER_OFFSET: ...
#[inline] pub fn offset(&self) -> usize { ((self.inner & OFFSET_MASK) >> OFFSET_OFFSET) as usize } #[inline] pub fn next_item(&self) -> usize { ((self.inner & NEXT_ITEM_MASK) >> NEXT_ITEM_OFFSET) as usize } #[inline] pub fn set_next_item(...
pub fn new( offset: usize, token_type: TokenType, next_item: usize, header: usize, ) -> Result<Token, BdecodeError> { if (offset > Self::MAX_OFFSET) || (next_item > Self::MAX_NEXT_ITEM) || (header > Self::MAX_HEADER) { return Err(Bd...
function_block-full_function
[ { "content": "#[inline]\n\npub fn decode_int(bytes: &[u8]) -> Result<i64, BdecodeError> {\n\n let (negative, integer) = match bytes[0] {\n\n b'-' => (true, decode_int_no_sign(&bytes[1..], true)?),\n\n b'0'..=b'9' => (false, decode_int_no_sign(bytes, false)?),\n\n _ => return Err(BdecodeE...
Rust
src/units/size.rs
mlange-42/print-prep
5305cbd1812322edce274108092b8d162d768363
use crate::units::length::{Length, LengthUnit}; use crate::ParseStructError; use std::error::Error; use std::fmt; use std::str::FromStr; #[derive(Debug, PartialEq, Clone)] pub struct Size { width: Option<Length>, height: Option<Length>, } impl Size { pub fn new(width: Option<Length>, height: Option<Leng...
use crate::units::length::{Length, LengthUnit}; use crate::ParseStructError; use std::error::Error; use std::fmt; use std::str::FromStr; #[derive(Debug, PartialEq, Clone)] pub struct Size { width: Option<Length>, height: Option<Length>, } impl Size { pub fn new(width: Option<Length>, height: Option<Leng...
); } Ok(Size { width, height }) } pub fn width(&self) -> &Option<Length> { &self.width } pub fn height(&self) -> &Option<Length> { &self.height } pub fn to_px(&self, dpi: f64) -> Size { self.to(&LengthUnit::Px, dpi) } pub fn to(...
ParseStructError( "Unable to create size, at least one of width or height must be given".to_string(), )
call_expression
[ { "content": "/// Converts format in cm to exact print formats in inches.\n\npub fn to_print_format(size: &FixSize) -> Result<FixSize, PrintFormatError> {\n\n let str = size.to_string();\n\n if FORMATS.contains_key::<str>(&str) {\n\n Ok(FORMATS.get::<str>(&str).unwrap().parse().unwrap())\n\n } e...
Rust
src/display/help.rs
nakidixon/klondike-rs
b017ed3cc4645df7e48f137e0197252feef44b09
use itertools::Itertools; use std::{convert::TryFrom, fmt}; use termion::color; use crate::utils::{format_str::FormattedString, str::CharacterLength}; use super::{ frame::{self, FrameWidget, Title}, geometry, Widget, }; lazy_static! { static ref MARGIN: geometry::SideOffsets2D<u16> = geometry::SideOffset...
use itertools::Itertools; use std::{convert::TryFrom, fmt}; use termion::color; use crate::utils::{format_str::FormattedString, str::CharacterLength}; use super::{ frame::{self, FrameWidget, Title}, geometry, Widget, }; lazy_static! { static ref MARGIN: geometry::SideOffsets2D<u16> = geometry::SideOffset...
} fn left_column_items(origin: geometry::Point2D<u16>) -> Vec<HelpItemWidget> { let mut coord_iter = (0..).map(|index| origin + geometry::vec2(0, index)); vec![ HelpItemWidget::Mapping { origin: coord_iter.next().unwrap(), keys: HelpItemKeys::List(vec!["h", "j", "k", "l"]), ...
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let frame_bounds = self.bounds.inner_rect(*MARGIN); let inner_bounds = frame_bounds.inner_rect(*BORDER + *PADDING); let frame_display = FrameWidget { bounds: frame_bounds, top_title: Some(Title::center("H E L P...
function_block-full_function
[ { "content": "pub trait Widget: fmt::Display {\n\n fn bounds(&self) -> geometry::Rect<u16>;\n\n}\n\n\n", "file_path": "src/display/mod.rs", "rank": 0, "score": 138494.09862247843 }, { "content": "pub fn offsets(widget: &StackWidget<'_>) -> Offsets {\n\n let details = &widget.stack.deta...
Rust
karl-host/src/net.rs
henryweng03/karl
f4699b25f57bfa47f94ec9dba8834bbc39c998fc
use tonic::{Request, Response, Status, Code}; use crate::protos::karl_controller_client::KarlControllerClient; use crate::protos::*; use karl_common::*; #[derive(Debug, Clone)] pub struct KarlHostAPI { pub controller_addr: String, pub host_token: Option<String>, } impl KarlHostAPI { pub fn new(cont...
use tonic::{Request, Response, Status, Code}; use crate::protos::karl_controller_client::KarlControllerClient; use crate::protos::*; use karl_common::*; #[derive(Debug, Clone)] pub struct KarlHostAPI { pub controller_addr: String, pub host_token: Option<String>, } impl KarlHostAPI { pub fn new(cont...
pub async fn forward_network( &self, mut req: NetworkAccess, ) -> Result<Response<()>, Status> { req.host_token = self.host_token.clone().expect("missing token"); KarlControllerClient::connect(self.controller_addr.clone()).await .map_err(|e| Status::new(Code::I...
KarlControllerClient::connect(self.controller_addr.clone()).await .map_err(|e| Status::new(Code::Internal, format!("{:?}", e)))? .heartbeat(Request::new(request)).await .map(|res| res.into_inner()) }
function_block-function_prefix_line
[ { "content": "pub fn parse_state_tag(tag: &str) -> (String, String) {\n\n let mut split = tag.split(\".\");\n\n let sensor = split.next().unwrap()[1..].to_string();\n\n let key = split.next().unwrap().to_string();\n\n (sensor, key)\n\n}\n\n\n", "file_path": "karl-common/src/state_tags.rs", "...
Rust
crates/flycheck/src/lib.rs
BGluth/rust-analyzer
9a4d02faf9c47f401b8756c3f7fcab2198f5f9cd
use std::{ fmt, io::{self, BufReader}, path::PathBuf, process::{Command, Stdio}, time::Duration, }; use crossbeam_channel::{never, select, unbounded, Receiver, Sender}; pub use cargo_metadata::diagnostic::{ Applicability, Diagnostic, DiagnosticLevel, DiagnosticSpan, DiagnosticSpanMacroExpans...
use std::{ fmt, io::{self, BufReader}, path::PathBuf, process::{Command, Stdio}, time::Duration, }; use crossbeam_channel::{never, select, unbounded, Receiver, Sender}; pub use cargo_metadata::diagnostic::{ Applicability, Diagnostic, DiagnosticLevel, DiagnosticSpan, DiagnosticSpanMacroExpans...
t!( "the command produced no valid metadata (exit code: {:?}): {:?}", exit_status, command ), )); } Ok(()) }
function_block-function_prefixed
[ { "content": "fn strange() -> bool { let _x: bool = return true; }\n\n\n", "file_path": "crates/ra_syntax/test_data/parser/ok/0035_weird_exprs.rs", "rank": 0, "score": 396121.22032675165 }, { "content": "fn punch_card() -> impl std::fmt::Debug {\n\n ..=..=.. .. .. .. .. .. .. .. .. ...
Rust
src/butcher_tableau.rs
cheshyre/rust-srg-test
1b98cda6cd7a3ba36babc571dc9cb95382c451dd
#![allow(clippy::excessive_precision, clippy::unreadable_literal)] pub struct Dopri54 { num_stages: usize, pub order: i32, a: Box<[Box<[f64]>]>, c: Box<[f64]>, d: Box<[f64]>, e: Box<[f64]>, } impl Dopri54 { pub fn new() -> Dopri54 { Dopri54 { num_stages: 7, ...
#![allow(clippy::excessive_precision, clippy::unreadable_literal)] pub struct Dopri54 { num_stages: usize, pub order: i32, a: Box<[Box<[f64]>]>, c: Box<[f64]>, d: Box<[f64]>, e: Box<[f64]>, } impl Dopri54 { pub fn new() -> Dopri54 { Dopri54 { num_stages: 7, ...
pub fn a(&self, i: usize, j: usize) -> f64 { self.a[i - 2][j - 1] } pub fn c(&self, i: usize) -> f64 { self.c[i - 1] } pub fn d(&self, i: usize) -> f64 { self.d[i - 1] } pub fn e(&self, i: usize) -> f64 { self.e[i - 1] } ...
Box::new([ 35.0 / 384.0, 0.0, 500.0 / 1113.0, 125.0 / 192.0, -2187.0 / 6784.0, 11.0 / 84.0, ]), ]), c: Box::new([0.0, 1.0 / 5.0, 3.0 / 10.0, 4.0 / 5.0, 8.0 / 9....
function_block-function_prefix_line
[ { "content": "fn check_sign(a: f64, b: f64) -> i32 {\n\n if a < b {\n\n return -1;\n\n }\n\n 1\n\n}\n\n\n", "file_path": "src/dopri5.rs", "rank": 0, "score": 49455.24606740988 }, { "content": "fn gauss_legendre(n: i32, x1: f64, x2: f64) -> (Vec<f64>, Vec<f64>) {\n\n let mu...
Rust
sdk/src/locations/store/mod.rs
vaporos/grid
9bf609f73725e63a34be8db73985e57822f2ea51
#[cfg(feature = "diesel")] pub mod diesel; mod error; use crate::paging::Paging; pub use error::LocationStoreError; #[derive(Clone, Debug, Serialize, PartialEq)] pub struct Location { pub location_id: String, pub location_address: String, pub location_namespace: String, pub owner: String, pub a...
#[cfg(feature = "diesel")] pub mod diesel; mod error; use crate::paging::Paging; pub use error::LocationStoreError; #[derive(Clone, Debug, Serialize, PartialEq)] pub struct Location { pub location_id: String, pub location_address: String, pub location_namespace: String, pub owner: String, pub a...
fn list_locations( &self, service_id: Option<&str>, offset: i64, limit: i64, ) -> Result<LocationList, LocationStoreError> { (**self).list_locations(service_id, offset, limit) } fn update_location(&self, location: Location) -> Result<(), LocationStoreError> { ...
fn fetch_location( &self, location_id: &str, service_id: Option<&str>, ) -> Result<Option<Location>, LocationStoreError> { (**self).fetch_location(location_id, service_id) }
function_block-full_function
[ { "content": "pub fn compute_gs1_location_address(gln: &str) -> String {\n\n //621ddee (grid namespace) + 04 (location namespace) + 01 (gs1 namespace)\n\n String::from(GRID_NAMESPACE)\n\n + LOCATION_PREFIX\n\n + \"01000000000000000000000000000000000000000000000\"\n\n + gln\n\n ...
Rust
src/ffi/mod.rs
rmja/drone-core
01f463ba1fd42655ed8edae79d5ba9dcb308b51b
pub mod libc; mod c_str; mod c_string; #[doc(no_inline)] pub use drone_ctypes::*; pub use self::{ c_str::{CStr, FromBytesWithNulError}, c_string::{CString, IntoStringError, NulError}, }; #[cfg(test)] mod tests { use super::*; use alloc::{ borrow::Cow::{Borrowed, Owned}, rc::Rc, ...
pub mod libc; mod c_str; mod c_string; #[doc(no_inline)] pub use drone_ctypes::*; pub use self::{ c_str::{CStr, FromBytesWithNulError}, c_string::{CString, IntoStringError, NulError}, }; #[cfg(test)] mod tests { use super::*; use alloc::{ borrow::Cow::{Borrowed, Owned}, rc::Rc, ...
#[test] fn to_str() { let data = b"123\xE2\x80\xA6\0"; let ptr = data.as_ptr() as *const c_char; unsafe { assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…")); assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…")); } let data = b"12...
ed() { unsafe { let s = CStr::from_ptr(b"12\0".as_ptr() as *const _); assert_eq!(s.to_bytes(), b"12"); assert_eq!(s.to_bytes_with_nul(), b"12\0"); } }
function_block-function_prefixed
[ { "content": "#[track_caller]\n\npub fn statemap_put(\n\n statemap: &'static BTreeMap<usize, BTreeMap<usize, AtomicUsize>>,\n\n key: usize,\n\n value: usize,\n\n) {\n\n if let Some(map) = statemap.get(&key) {\n\n if let Some(counter) = map.get(&value) {\n\n counter.fetch_add(1, Seq...