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/migration/mod.rs
s-panferov/deuterium-orm
ee8b98773005dfda5271a3720cc1166744f1f2a7
use num::ToPrimitive; use time::now_utc; use std::io::Write; use std::fs; use std::path; use postgres; use std::collections; pub fn gen_timecode() -> String { now_utc().strftime("%y%m%d%H%M%S").unwrap().to_string() } pub fn gen_full_name(name: &str) -> String { format!("_{}_{}", gen_timecode(), name) } pub f...
use num::ToPrimitive; use time::now_utc; use std::io::Write; use std::fs; use std::path; use postgres; use std::collections; pub fn gen_timecode() -> String { now_utc().strftime("%y%m%d%H%M%S").unwrap().to_string() } pub fn gen_full_name(name: &str) -> String { format!("_{}_{}", gen_timecode(), name) } pub f...
n().to_i64().unwrap(), cn); println!("Migration reverted: {} {}", migration.version(), migration.name()); } }
&Migrations, cn: &postgres::Connection) { ensure_schema_migrations(cn); let db_versions = get_versions_as_hash(cn); let migrations_to_run: MigrationRefs = migrations.iter().filter(|m| { let version = m.version().to_i64().unwrap(); !db_versions.contains_key(&version) }).collect(); f...
random
[ { "content": "fn generate_lookup_predicate(struct_name: &String, primary_key: &Vec<String>) -> String {\n\n let keys: Vec<String> = primary_key.iter().map(|pk| {\n\n format!(\"({}::{}_f().is(self.get_{}().clone()))\",\n\n struct_name,\n\n pk,\n\n pk\n\n )\n\n ...
Rust
src/widget/button.rs
pthariensflame/conrod
4683a5f00ba08454dda25127783d1334c06df516
use { Align, Color, Colorable, FontSize, Borderable, Labelable, Rect, Positionable, Scalar, UiCell, Widget, }; use widget; #[derive(Clone)] pub struct Button<'a, S> { common: widget::CommonBuilder, maybe_label: Option<&'a str>, pub show: S, pub st...
use { Align, Color, Colorable, FontSize, Borderable, Labelable, Rect, Positionable, Scalar, UiCell, Widget, }; use widget; #[derive(Clone)] pub struct Button<'a, S> { common: widget::CommonBuilder, maybe_label: Option<&'a str>, pub show: S, pub st...
.and(|b| match align { Align::Start => b.mid_left_with_margin_on(rectangle_idx, font_size as Scalar), Align::Middle => b.middle_of(rectangle_idx), Align::End => b.mid_right_with_margin_on(rectangle_idx, font_size as Scalar), }) ...
- border_color: Color { theme.border_color } - label_color: Color { theme.label_color } - label_font_size: FontSize { theme.font_size_medium } - label_x_align: Align { Align::Middle } } } pub trait Show: Sized { fn show(self, _button_idx: widget::Index, _...
random
[ { "content": "/// In the case that a position hasn't been given for one of the axes, we must first check to see\n\n/// if we can infer the missing axis position from the other axis.\n\n///\n\n/// This is used within the impl of **Positionable** for **Widget**.\n\nfn infer_position_from_other_position(other_pos:...
Rust
examples/server/src/administrator.rs
FakeMyAS/rocket-server
2eb82435dc520836b0032e52389456bf388eaf43
use rocket::{Request, Outcome}; use rocket::request::FromRequest; use std::collections::HashMap; use std::io::Read; extern crate crypto; use crypto::digest::Digest; use crypto::sha3::Sha3; use auth::authorization::*; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AdministratorCookie { pub userid: u32,...
use rocket::{Request, Outcome}; use rocket::request::FromRequest; use std::collections::HashMap; use std::io::Read; extern crate crypto; use crypto::digest::Digest; use crypto::sha3::Sha3; use auth::authorization::*; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AdministratorCookie { pub userid: u32,...
me::Forward(()) } } }
cid = AdministratorCookie::cookie_id(); let mut cookies = request.cookies(); match cookies.get_private(cid) { Some(cookie) => { if let Some(cookie_deserialized) = AdministratorCookie::retrieve_cookie(cookie.value().to_string()) { Outcome::Success(...
random
[ { "content": "/// Used to remove all non-hexadecimal characters from passwords\n\n/// Passwords must be only hex characters as it is expecting a hash, like sha-256 or md5 for example\n\npub fn sanitize_password(string: &str) -> String {\n\n filter_non_characters(string)\n\n}\n\n\n", "file_path": "src/san...
Rust
tests/clean_unref.rs
Spaceface16518/cargo-cache
cc7cf75d6849a2fc1386b32fc48280573eed8660
#[path = "../src/test_helpers.rs"] mod test_helpers; use std::path::PathBuf; use std::process::Command; use regex::Regex; use crate::test_helpers::bin_path; #[test] #[cfg_attr(feature = "offline_tests", ignore)] fn clean_unref() { const CARGO_HOME: &str = "target/clean_unref_CARGO_HOME/"; const INIT...
#[path = "../src/test_helpers.rs"] mod test_helpers; use std::path::PathBuf; use std::process::Command; use regex::Regex; use crate::test_helpers::bin_path; #[test] #[cfg_attr(feature = "offline_tests", ignore)] fn clean_unref() { const CARGO_HOME: &str = "target/clean_unref_CARGO_HOME/"; const INIT...
intln!("OUT {:?}", stdout); assert!(stdout.matches("would remove").count() > 10); let cargo_cache_command = Command::new(bin_path()) .arg("clean-unref") .arg("--manifest-path") .arg(ACTUAL_TOML) .env("CARGO_HOME", CARGO_HOME) .output(); let status = carg...
function_block-function_prefixed
[ { "content": "#[allow(non_snake_case)]\n\n#[test]\n\n#[cfg_attr(feature = \"offline_tests\", ignore)]\n\nfn CARGO_HOME_subdirs_are_known() {\n\n // stuff is inconsistent until cargo 0.41.0 hits stable\n\n // https://github.com/rust-lang/cargo/commit/f7b29716ed0e2d67b38bee23e5acddfc11ea0952\n\n let carg...
Rust
http/src/v0/bootstrap.rs
irinazheltisheva/rust-ipfs
fbaebc5f52f68a39ede4ce571120ac50bbf3ad7a
use crate::v0::support::{with_ipfs, MaybeTimeoutExt, StringError, StringSerialized}; use ipfs::{Ipfs, IpfsTypes, MultiaddrWithPeerId}; use serde::{Deserialize, Serialize}; use warp::{query, Filter, Rejection, Reply}; #[derive(Debug, Serialize)] #[serde(rename_all = "PascalCase")] struct Response { peers: Vec<Strin...
use crate::v0::support::{with_ipfs, MaybeTimeoutExt, StringError, StringSerialized}; use ipfs::{Ipfs, IpfsTypes, MultiaddrWithPeerId}; use serde::{Deserialize, Serialize}; use warp::{query, Filter, Rejection, Reply}; #[derive(Debu
erialize)] pub struct BootstrapAddQuery { arg: Option<StringSerialized<MultiaddrWithPeerId>>, default: Option<bool>, timeout: Option<StringSerialized<humantime::Duration>>, } async fn restore_helper<T: IpfsTypes>( ipfs: Ipfs<T>, timeout: &Option<StringSerialized<humantime::Duration>>, ) -> Result<V...
g, Serialize)] #[serde(rename_all = "PascalCase")] struct Response { peers: Vec<String>, } #[derive(Debug, Deserialize)] pub struct BootstrapQuery { timeout: Option<StringSerialized<humantime::Duration>>, } async fn bootstrap_query<T: IpfsTypes>( ipfs: Ipfs<T>, query: BootstrapQuery, ) -> Result<impl ...
random
[ { "content": "/// Filter to perform custom `warp::query<RefsOptions>`\n\nfn refs_options() -> impl Filter<Extract = (RefsOptions,), Error = Rejection> + Clone {\n\n warp::filters::query::raw().and_then(|q: String| {\n\n let res = RefsOptions::try_from(q.as_str())\n\n .map_err(StringError::f...
Rust
src/aabb.rs
aganders3/wasm-ray
abd264ce5feeadf77330433eff9e2ccb86b2fd33
use itertools::izip; use crate::ray::Ray; use crate::vec3::Point; use crate::wobject::{Elemental, Hit, Wobject, sort_on_random_axis}; #[derive(Debug)] pub struct AxisAlignedBoundingBox { pub min: Point, pub max: Point, } impl AxisAlignedBoundingBox { fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> bo...
use itertools::izip; use crate::ray::Ray; use crate::vec3::Point; use crate::wobject::{Elemental, Hit, Wobject, sort_on_random_axis}; #[derive(Debug)] pub struct AxisAlignedBoundingBox { pub min: Point, pub max: Point, } impl AxisAlignedBoundingBox { fn hit(&self, ray: &Ray, t_min: f32, t_max: f32) -> bo...
impl BVHNode { pub fn closest_hit(&self, ray: &Ray, depth: u32) -> Option<Hit> { if !self.bb.hit(ray, 0.001, f32::INFINITY) { return None } if let Some(wobject) = self.wobject { return wobject.hit(ray, 0.001, f32::INFINITY) } let left_hit ...
n<Hit>) -> Option<Hit> { if let Some(h1) = hit1 { if let Some(h2) = hit2 { if h1.t < h2.t { return hit1 } else { return hit2 } } return hit1 } return hit2 }
function_block-function_prefixed
[ { "content": "pub fn sort_on_random_axis(wobjects: &mut [Elemental]) {\n\n let mut rng = rand::thread_rng();\n\n let axis = rng.gen::<f32>();\n\n if axis < 0.333 {\n\n wobjects.sort_by(|a, b| a.center().x.partial_cmp(&b.center().x).unwrap());\n\n } else if axis < 0.666 {\n\n wobjects.s...
Rust
builder-derive/src/generics.rs
zyxw59/builder
271f03afe2974cd7f498ab5e34c8c1b622185f43
use convert_case::{Case, Casing}; use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ConstParam, Ident, LifetimeDef, TypeParam, WherePredicate}; pub struct Generics<'a> { lifetimes: Vec<&'a LifetimeDef>, types: Vec<Generic<'a>>, consts: Vec<&'a ConstParam>, where_predic...
use convert_case::{Case, Casing}; use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ConstParam, Ident, LifetimeDef, TypeParam, WherePredicate}; pub struct Generics<'a> { lifetimes: Vec<&'a LifetimeDef>, types: Vec<Generic<'a>>, consts: Vec<&'a ConstParam>, where_predic...
} pub struct Generic<'a> { param: &'a TypeParam, field_type: TokenStream, field_name: Ident, } impl<'a> Generic<'a> { fn impl_generic(&self) -> TokenStream { let TypeParam { attrs, ident, colon_token, bounds, .. } = self.para...
fn from(generics: &'a syn::Generics) -> Self { Generics { lifetimes: generics.lifetimes().collect(), types: generics.type_params().map(Generic::from).collect(), consts: generics.const_params().collect(), where_predicates: generics .where_clause ...
function_block-full_function
[ { "content": "#[proc_macro_derive(Builder, attributes(builder))]\n\npub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n\n let input = syn::parse_macro_input!(input as DeriveInput);\n\n let builder = StructAttrs::try_from(&input).unwrap();\n\n let builder_with_callback = builder...
Rust
contracts/luna-unbond-handler/src/commands.rs
White-Whale-Defi-Platform/contracts
c112d283057aff300a41499c687cfa88f5c4f7e3
use cosmwasm_std::{ coins, from_binary, to_binary, BankMsg, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Response, Uint128, WasmMsg, }; use cw20::Cw20ReceiveMsg; use terraswap::asset::{Asset, AssetInfo}; use terraswap::querier::query_balance; use white_whale::anchor::{anchor_bluna_unbond_msg, anchor_withdraw...
use cosmwasm_std::{ coins, from_binary, to_binary, BankMsg, CosmosMsg, Decimal, DepsMut, Env, MessageInfo, Response, Uint128, WasmMsg, }; use cw20::Cw20ReceiveMsg; use terraswap::asset::{Asset, AssetInfo}; use terraswap::querier::query_balance; use white_whale::anchor::{anchor_bluna_unbond_msg, anchor_withdraw...
a_vault_addr = ADMIN .get(deps.as_ref())? .ok_or(UnbondHandlerError::NotAdminSet {})?; let vault_fees = query_luna_vault_fees(deps.as_ref(), &luna_vault_addr)?; let liquidation_fee_amount = match triggered_by != owner && env.block.time.seconds() > expiration_time { true => re...
r_validate(&memory_contract)?; attrs.push(("new_memory_contract", memory_contract)); } STATE.save(deps.storage, &state)?; Ok(Response::new().add_attributes(attrs)) } pub(crate) fn handle_callback( deps: DepsMut, env: Env, info: MessageInfo, msg: CallbackMsg, ) -> UnbondHandlerResul...
random
[ { "content": "pub fn handle_buyback_whale(deps: DepsMut, _env: Env, msg_info: MessageInfo, amount_to_buy: Uint128) -> BuyBackResult {\n\n let state = BASESTATE.load(deps.storage)?;\n\n let config: State = STATE.load(deps.storage)?;\n\n\n\n // Check if caller is trader.\n\n if msg_inf...
Rust
src/assembler/resource/operand/base.rs
Drumato/x64_asm
b840961b72b56ab09d8f8f505dee72d974238940
use crate::assembler::resource::{ AddressingMode, Displacement, GeneralPurposeRegister, Immediate, RegisterSize, SIBByte, }; #[allow(dead_code)] #[derive(Eq, Ord, PartialOrd, PartialEq, Debug, Clone)] pub enum Operand { GENERALREGISTER(GeneralPurposeRegister), A...
use crate::assembler::resource::{ AddressingMode, Displacement, GeneralPurposeRegister, Immediate, RegisterSize, SIBByte, }; #[allow(dead_code)] #[derive(Eq, Ord, PartialOrd, PartialEq, Debug, Clone)] pub enum Operand { GENERALREGISTER(GeneralPurposeRegister), A...
pub fn is_expanded(&self) -> bool { match self { Operand::ADDRESSING { base: base_reg, index: _, disp: _, scale: _, } => base_reg.is_expanded(), Operand::GENERALREGISTER(gpr) => gpr.is_expanded(), ...
pub fn is_addressing(&self) -> bool { match self { Operand::ADDRESSING { base: _, index: _, disp: _, scale: _, } => true, _ => false, } }
function_block-full_function
[ { "content": "/// parse AT&T syntax assembly.\n\npub fn parse_atandt(source: String) -> IndexMap<String, Symbol> {\n\n let lines_iter = source.lines();\n\n let mut context = Context {\n\n state: State::TopLevel,\n\n syms: Default::default(),\n\n };\n\n\n\n // 各行に対して処理を行う\n\n for l i...
Rust
fri/src/verifier/mod.rs
Silur/winterfell
cc0852f04d3d751a7e664772912c4977103a203d
use crate::{folding::quartic, utils}; use math::{ field::{FieldElement, StarkField}, polynom, utils::get_power_series_with_offset, }; use std::mem; mod context; pub use context::VerifierContext; mod channel; pub use channel::{DefaultVerifierChannel, VerifierChannel}; mod errors; pub use errors::Verifie...
use crate::{folding::quartic, utils}; use math::{ field::{FieldElement, StarkField}, polynom, utils::get_power_series_with_offset, }; use std::mem; mod context; pub use context::VerifierContext; mod channel; pub use channel::{DefaultVerifierChannel, VerifierChannel}; mod errors; pub use errors::Verifie...
if evaluations != query_values { return Err(VerifierError::LayerValuesNotConsistent(depth)); } let mut xs = Vec::with_capacity(folded_positions.len()); for &i in folded_positions.iter() { let xe = domain_generator.exp((i as u32).into()) * domain_offset;...
let query_values = get_query_values( &layer_values, &positions, &folded_positions, domain_size, context.folding_factor(), );
assignment_statement
[ { "content": "/// Computes a[i] + b[i] * c for all i and saves result into a.\n\npub fn mul_acc<B, E>(a: &mut [E], b: &[B], c: E)\n\nwhere\n\n B: FieldElement,\n\n E: FieldElement + From<B>,\n\n{\n\n assert!(\n\n a.len() == b.len(),\n\n \"number of values must be the same for both slices\...
Rust
src/main.rs
KeenS/irc_log
255f6c90c36ff4f880abb72d14a8bd74a369fb45
#[macro_use] extern crate log; extern crate env_logger; extern crate time; extern crate r2d2; extern crate r2d2_sqlite; extern crate rusqlite; use std::str::from_utf8; use std::io::BufReader; use std::io::BufRead; use std::fs; use std::path::Path; use std::os::unix::prelude::OsStrExt; use std::sync::Arc; use std::threa...
#[macro_use] extern crate log; extern crate env_logger; extern crate time; extern crate r2d2; extern crate r2d2_sqlite; extern crate rusqlite; use std::str::from_utf8; use std::io::BufReader; use std::io::BufRead; use std::fs; use std::path::Path; use std::os::unix::prelude::OsStrExt; use std::sync::Arc; use std::threa...
d2::Pool::new(config, manager).unwrap()); let paths = fs::read_dir("/home/kim/log").unwrap(); for path in paths { let path = path.unwrap().path(); on_channel_dir(&path, pool.clone()); } }
function_block-function_prefixed
[ { "content": "CREATE TABLE servers(\n\n id INTEGER PRIMARY KEY,\n\n name TEXT NOT NULL UNIQUE,\n\n address TEXT\n\n );\n\n\n", "file_path": "etc/schema.sql", "rank": 3, "score": 11895.601219039387 }, { "content": "CREATE TABLE entries(\n\n id INTEGER PRI...
Rust
server/src/lib.rs
ryanpbrewster/grpc-filesystem
3fe6536a3e6d72483a81dc6aaa0b9e759ed4c1a2
use log::{trace, warn}; use std::collections::BTreeMap; use std::sync::{Arc, RwLock}; use tonic::{Code, Request, Response, Status}; pub mod proto { tonic::include_proto!("fs"); } pub use crate::proto::file_system_server::{FileSystem, FileSystemServer}; use crate::proto::{ ExecRequest, ExecResponse, GetRequest...
use log::{trace, warn}; use std::collections::BTreeMap; use std::sync::{Arc, RwLock}; use tonic::{Code, Request, Response, Status}; pub mod proto { tonic::include_proto!("fs"); } pub use crate::proto::file_system_server::{FileSystem, FileSystemServer}; use crate::proto::{ ExecRequest, ExecResponse, GetRequest...
_| { Status::new( Code::InvalidArgument, "could not find exported function 'entrypoint'", ) })?; let n = entrypoint.call().map_err(|_| { Status::new(Code::FailedPrecondition, "execution error in provided wasm") ...
fn mkdir( &self, request: Request<MkdirRequest>, ) -> Result<Response<MkdirResponse>, Status> { trace!("[MKDIR] request = {:?}", request); let msg = request.into_inner(); let path = msg.path; let mut segs = segments(&path); let name = segs .pop()...
random
[ { "content": " write(path, content) {\n\n return new Promise((resolve, reject) => {\n\n this.underlying.write({ path, content }, (err, resp) => {\n\n if (err) {\n\n reject(err);\n\n } else {\n\n resolve(resp);\n\n }\n\n });\n\n });\n", "file_path": "ma...
Rust
src/access.rs
dubiousjim/nix-extra
967cc07a6c57eafa9a1eaaafb1ad511561299556
#![allow(dead_code)] use nix::{errno::Errno, /*Error,*/ NixPath, Result}; use std::os::unix::io::RawFd; use crate::open::Symlink; pub use nix::unistd::AccessFlags; use std::path::PathBuf; pub fn get_accmode(fd: RawFd, want_read: bool, want_write: bool) -> Result<bool> { /* use nix::fcntl::{fcntl, FcntlArg, OFla...
#![allow(dead_code)] use nix::{errno::Errno, /*Error,*/ NixPath, Result}; use std::os::unix::io::RawFd; use crate::open::Symlink; pub use nix::unistd::AccessFlags; use std::path::PathBuf; pub fn get_accmode(fd: RawFd, want_read: bool, want_write: bool) -> Result<bool> { /* use nix::fcntl::{fcntl, FcntlArg, OFla...
as usize]; let res = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) }; if res == -1 { None } else { let len = buf.iter().position(|&c| c == 0).unwrap(); buf.truncate(len as usize); buf.shrink_to_fit(); Some(PathBuf::from(OsString::from_vec(buf))) } } #[cfg(not...
et mut buf = Vec::with_capacity(libc::PATH_MAX as usize); let mut path_vec = path.into_os_string().into_vec(); path_vec.push(0); let res = unsafe { let cstr = CStr::from_bytes_with_nul_unchecked(&path_vec); libc::readlink(cstr.as_ptr(), buf.as_mut_ptr() as *mut c_char, buf.capacity() as size_t) ...
function_block-random_span
[ { "content": "pub fn mkdirat<P: ?Sized + NixPath>(dirfd: Option<RawFd>, path: &P, mode: Mode, recursive: bool) -> Result<()> {\n\n path\n\n .with_nix_path(|cstr| {\n\n use std::os::unix::ffi::OsStrExt;\n\n let path = Path::new(OsStr::from_bytes(cstr.to_bytes()));\n\n match dirfd {\n\n ...
Rust
safe-api/src/api/app/helpers.rs
frabrunelle/safe-api
c7bd21e02a29d92879cd24f5c6277686f70b6282
use super::common::{parse_hex, sk_from_hex}; use crate::{Error, Result}; use chrono::{DateTime, SecondsFormat, Utc}; use safe_core::ipc::{decode_msg, resp::AuthGranted, BootstrapConfig, IpcMsg, IpcResp}; use safe_nd::{Coins, Error as SafeNdError, PublicKey as SafeNdPublicKey, XorName}; use std::str::{self, FromStr}; ...
use super::common::{parse_hex, sk_from_hex}; use crate::{Error, Result}; use chrono::{DateTime, SecondsFormat, Utc}; use safe_core::ipc::{decode_msg, resp::AuthGranted, BootstrapConfig, IpcMsg, IpcResp}; use safe_nd::{Coins, Error as SafeNdError, PublicKey as SafeNdPublicKey, XorName}; use std::str::{self, FromStr}; ...
#[allow(clippy::large_enum_variant)] pub enum AuthResponseType { Registered(AuthGranted), Unregistered(BootstrapConfig), } pub fn decode_ipc_msg(ipc_msg: &str) -> Result<AuthResponseType> { let msg = decode_msg(&ipc_msg) .map_err(|e| Error::InvalidInput(format!("Failed to decode the credentials: ...
amount_str, Coins::from_nano(MAX_COINS_VALUE) )), SafeNdError::LossOfPrecision => { Error::InvalidAmount(format!("Invalid safecoins amount '{}', the minimum possible amount is one nano coin (0.000000001)", amount_str)) } SafeNdError::FailedToParse(msg) => ...
function_block-function_prefix_line
[ { "content": "// Unwrap secret key string provided, otherwise prompt user to provide it\n\npub fn get_secret_key(key_xorurl: &str, sk: Option<String>, msg: &str) -> Result<String, String> {\n\n let mut sk = sk.unwrap_or_else(|| String::from(\"\"));\n\n\n\n if sk.is_empty() {\n\n let msg = if key_xo...
Rust
llmalloc/benches/benchmark.rs
matthieu-m/llmalloc
42b5972bd0568e6c2eeedb0ef61b8e6a0ebc1c06
use std::{ alloc::Layout, cmp, collections::VecDeque, ptr::NonNull, sync::atomic::{AtomicU64, Ordering}, time::{Duration, Instant}, }; use criterion::{BatchSize, Criterion, black_box, criterion_group, criterion_main}; use llmalloc::LLAllocator; use llmalloc_test::BurstyBuilder; static LL_ALLO...
use std::{ alloc::Layout, cmp, collections::VecDeque, ptr::NonNull, sync::atomic::{AtomicU64, Ordering}, time::{Duration, Instant}, }; use criterion::{BatchSize, Criterion, black_box, criterion_group, criterion_main}; use llmalloc::LLAllocator; use llmalloc_test::BurstyBuilder; static LL_ALLO...
hreaded_batch_allocation, multi_threaded_batch_allocation_allocation, multi_threaded_batch_allocation_deallocation ); criterion_main!( single_threaded_single_allocation, single_threaded_batch_allocation, multi_threaded_batch_allocation ); fn bench_function_worst_of_parallel<F, S, T, V, Z>( nam...
ber_consumers >= number_cpus { return; } bencher::<SysVec>( &format!("PC BA Deallocation {}C - sys", number_consumers), number_consumers, c ); bencher::<LLVec>( &format!("PC BA Deallocation {}C - ll", number_consumers), ...
random
[ { "content": "fn read_number_from_environment(name: &str, default: usize) -> usize {\n\n for (n, value) in env::vars() {\n\n if n == name {\n\n if let Ok(result) = value.parse() {\n\n println!(\"read_number_from_environment - {}: {}\", name, result);\n\n return...
Rust
src/card.rs
yishn/recall-cli
6c27e491ce3153b8e045a8418fecdd1a1896b6ab
use chrono::{offset::Utc, DateTime, Duration, TimeZone}; use crate::list::List; use std::{path::PathBuf, fmt::Display, collections::HashMap, io::Result}; use colored::{ColoredString, Colorize}; #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum Proficiency { Inactive, Apprentice, Guru, ...
use chrono::{offset::Utc, DateTime, Duration, TimeZone}; use crate::list::List; use std::{path::PathBuf, fmt::Display, collections::HashMap, io::Result}; use colored::{ColoredString, Colorize}; #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum Proficiency { Inactive, Apprentice, Guru, ...
lists.get_mut(&path) }; if let (Some((_, cards)), Some(line_number)) = (list_entry, card.line_number) { if cards.contains_key(&line_number) { cards.insert(line_number, card); } } } for (_, (list, cards)) in lists.into_iter() { let mut cards = cards.into_iter().collect::...
if !lists.contains_key(&path) { let list = List::new(&path); let cards = if let Some(list) = list.as_ref() { Some( list.cards()? .filter_map(|card| card.line_number.map(|x| (x, card))) .collect::<HashMap<_, _>>() ) } else { None ...
if_condition
[ { "content": "pub fn progress_bar(progress: f64, width: u32) -> impl Display {\n\n let percent = (progress * 100.0).round() as u32;\n\n let completed = ((width as f64 * progress).round() as u32).min(width);\n\n let incomplete = width - completed;\n\n let mut result = String::new();\n\n\n\n result += \"[\";...
Rust
oak_idl/src/lib.rs
andrisaar/oak
f7841d590e479dbc5b9eae05f9909a437d626505
use serde::{Deserialize, Serialize}; #[derive(Debug)] pub enum ClientError { InvalidRequest, InvalidResponse, TransportError(TransportError), } impl From<TransportError> for ClientError { fn from(e: TransportError) -> Self { ClientError::TransportError(e) } } #[derive(Debug)] pub enum T...
use serde::{Deserialize, Serialize}; #[derive(Debug)] pub enum ClientError { InvalidRequest, InvalidResponse, TransportError(TransportError), } impl From<TransportError> for ClientError { fn from(e: TransportError) -> Self { ClientError::TransportError(e) } } #[derive(Debug)] pub enum T...
Ok(response_message) } } fn invoke(_channel_handle: u32, _request: &[u8]) -> Result<Vec<u8>, TransportError> { unimplemented!() } #[macro_export] macro_rules! service { ( $name:ident { $( $method_id:literal => fn $method:ident ( $request_arg:ident : $request_type:ty ) -> $res...
if response_message.header.transaction_id != transaction_id { return Err(TransportError::InvalidTransactionId); }
if_condition
[ { "content": "/// Deserializes an attestation message from a serialized `input` and wraps in a\n\n/// [`MessageWrapper`].\n\npub fn deserialize_message(input: &[u8]) -> anyhow::Result<MessageWrapper> {\n\n if input.is_empty() {\n\n return Err(anyhow!(\"Empty input\"));\n\n }\n\n match input[0] {...
Rust
src/solver/linesearch/backtracking.rs
s-arash/argmin
89be6e21b65ed8367d6d6010a3d32fe963f3a37f
use crate::prelude::*; use crate::solver::linesearch::condition::*; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone)] pub struct BacktrackingLineSearch<P, L, F> { init_param: P, init_cost: F, init_grad: P, search_directi...
use crate::prelude::*; use crate::solver::linesearch::condition::*; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone)] pub struct BacktrackingLineSearch<P, L, F> { init_param: P, init_cost: F, init_grad: P, search_directi...
clone().unwrap(), self.alpha, ) { TerminationReason::LineSearchConditionMet } else { TerminationReason::NotTerminated } } } #[cfg(test)] mod tests { use super::*; use crate::core::MinimalNoOperator; use crate::test_trait_impl; test_trait_...
tate.get_cost(), state.get_grad().unwrap_or_default(), self.init_cost, self.init_grad.clone(), self.search_direction.
function_block-random_span
[ { "content": "/// Load a checkpoint from disk\n\npub fn load_checkpoint<T: DeserializeOwned, P: AsRef<Path>>(path: P) -> Result<T, Error> {\n\n let path = path.as_ref();\n\n if !path.exists() {\n\n return Err(ArgminError::CheckpointNotFound {\n\n text: path.to_str().unwrap().to_string(),...
Rust
src/parsing/expression/value_literal.rs
mangolang/compiler
a33d5886c7536fa7d3c0365879fd8e250a8d84f4
use crate::lexeme::Lexeme; use crate::parselet::terminal::LiteralParselet; use crate::parselet::ExpressionParselets; use crate::parsing::expression::grouping::parse_parenthesised_group; use crate::parsing::util::cursor::ParseCursor; use crate::parsing::util::ParseRes; pub fn parse_value_literal(cursor: ParseCursor) ->...
use crate::lexeme::Lexeme; use crate::parselet::terminal::LiteralParselet; use crate::parselet::ExpressionParselets; use crate::parsing::expression::grouping::parse_parenthesised_group; use crate::parsing::util::cursor::ParseCursor; use crate::parsing::util::ParseRes; pub fn parse_value_literal(cursor: ParseCursor) ->...
#[test] fn leftover_other() { let lexemes = builder().literal_int(37).comma().file(); let cursor = lexemes.cursor(); let (cursor, parselet) = parse_value_literal(cursor).unwrap(); assert_eq!(literal(literal_int(37)), parselet); assert_eq!(Ok(lexemes.last()), cursor.peek...
let lexemes = builder().literal_int(37).literal_bool(true).file(); let cursor = lexemes.cursor(); let (cursor, parselet) = parse_value_literal(cursor).unwrap(); assert_eq!(literal(literal_int(37)), parselet); assert_eq!(Ok(lexemes.last()), cursor.peek()); }
function_block-function_prefix_line
[ { "content": "pub fn parse_file(mut cursor: ParseCursor) -> ParseRes<FileParselet> {\n\n let mut imports = vec![];\n\n cursor.skip_while(|lexeme| matches!(lexeme, Lexeme::Newline(_)));\n\n while let Ok((import_cursor, import)) = parse_import(cursor.fork()) {\n\n imports.push(import);\n\n ...
Rust
did-tezos/src/explorer.rs
fairingrey/ssi
130cbeee171ea11c141fdca93fe2a041a9a6ca3f
use anyhow::Result; use serde::Deserialize; use ssi::did::{Service, ServiceEndpoint, VerificationMethod, DIDURL}; use ssi::one_or_many::OneOrMany; use ssi::USER_AGENT; use std::convert::TryFrom; use url::Url; pub async fn retrieve_did_manager(tzkt_url: &str, address: &str) -> Result<Option<String>> { let client = ...
use anyhow::Result; use serde::Deserialize; use ssi::did::{Service, ServiceEndpoint, VerificationMethod, DIDURL}; use ssi::one_or_many::OneOrMany; use ssi::USER_AGENT; use std::convert::TryFrom; use url::Url; pub async fn retrieve_did_manager(tzkt_url: &str, address: &str) -> Result<Option<String>> { let client = ...
panic!("Impossible format."), }; } }
::DIDURL(did_url) => { assert_eq!( did_url.to_string(), format!("did:pkh:tz:{}#TezosMethod2021", LIVE_TZ1) ) } _ =>
random
[ { "content": "/// <https://www.w3.org/TR/json-ld11/#the-rdf-json-datatype>\n\npub fn canonicalize_json_string(string: &str) -> String {\n\n let mut out = String::with_capacity(string.len() + 6);\n\n out.push('\"');\n\n for c in string.chars() {\n\n match c {\n\n '\\t' => out.push_str(...
Rust
fuzzers/frida_libpng/build.rs
dsjlzh/LibAFL
30155f5c3f5febc295ac63c9a6ed292c2815c0c7
use std::{ env, path::Path, process::{exit, Command}, }; use which::which; const LIBPNG_URL: &str = "https://deac-fra.dl.sourceforge.net/project/libpng/libpng16/1.6.37/libpng-1.6.37.tar.xz"; fn build_dep_check(tools: &[&str]) { for tool in tools { println!("Checking for build tool {}......
use std::{ env, path::Path, process::{exit, Command}, }; use which::which; const LIBPNG_URL: &str = "https://deac-fra.dl.sourceforge.net/project/libpng/libpng16/1.6.37/libpng-1.6.37.tar.xz"; fn build_dep_check(tools: &[&str]) { for tool in tools { println!("Checking for build tool {}......
rmat!("{}/.libs/libpng16.a", &libpng)) .arg("-l") .arg("z") .status() .unwrap(); assert!(status.success()); }
function_block-function_prefixed
[ { "content": "fn main() {\n\n cc::Build::new().file(\"src/gettls.c\").compile(\"libgettls.a\");\n\n\n\n // Force linking against libc++\n\n println!(\"cargo:rustc-link-lib=dylib=c++\");\n\n}\n", "file_path": "libafl_frida/build.rs", "rank": 2, "score": 250611.51512698742 }, { "conte...
Rust
query/src/datasources/table/fuse/table.rs
CNLHC/databend
fad0df2843c148c9c74793dadd38a9e5db274a36
use std::any::Any; use std::sync::Arc; use common_datavalues::DataSchemaRef; use common_exception::ErrorCode; use common_exception::Result; use common_flights::StoreClient; use common_planners::InsertIntoPlan; use common_planners::Partitions; use common_planners::ReadDataSourcePlan; use common_planners::ScanPlan; us...
use std::any::Any; use std::sync::Arc; use common_datavalues::DataSchemaRef; use common_exception::ErrorCode; use common_exception::Result; use common_flights::StoreClient; use common_planners::InsertIntoPlan; use common_planners::Partitions; use common_planners::ReadDataSourcePlan; use common_planners::ScanPlan; us...
name, schema, storage_scheme, meta_client, local: true, }; Ok(Box::new(res)) } } #[async_trait::async_trait] impl<T> Table for FuseTable<T> where T: MetaApi + Send + Sync + 'static { fn name(&self) -> &str { &self.name } f...
ate::datasources::table::fuse::parse_storage_scheme; use crate::datasources::table::fuse::project_col_idx; use crate::datasources::table::fuse::range_filter; use crate::datasources::table::fuse::read_part; use crate::datasources::table::fuse::read_table_snapshot; use crate::datasources::table::fuse::segment_info_locati...
random
[ { "content": "-- {ErrorCode 3, but it not work, because it's trimed in msql-srv}\n\nUSE not_exists_db;\n\nUSE default;\n\nUSE system;\n", "file_path": "tests/suites/0_stateless/07_0000_use_database.sql", "rank": 0, "score": 55561.241246059326 }, { "content": "use common_streams::SendableData...
Rust
gateway/src/shard/processor/compression/mod.rs
LeSeulArtichaut/twilight
79702d5b6d48363881862ba5d2d864700b8a05a5
#[cfg(feature = "compression")] mod inflater; use super::r#impl::ReceivingEventError; #[cfg(feature = "compression")] use inflater::Inflater; #[derive(Debug)] pub struct Compression { #[cfg(feature = "compression")] inner: Inflater, #[cfg(not(feature = "compression"))] inner: Vec<u8>, } im...
#[cfg(feature = "compression")] mod inflater; use super::r#impl::ReceivingEventError; #[cfg(feature = "compression")] use inflater::Inflater; #[derive(Debug)] pub struct Compression { #[cfg(feature = "compression")] inner: Inflater, #[cfg(not(feature = "compression"))] inner: Vec<u8>, } im...
}
fn test_add_url_features() { let mut buf = String::new(); super::add_url_feature(&mut buf); #[cfg(feature = "compression")] { assert_eq!("&compress=zlib-stream", buf); } #[cfg(not(feature = "compression"))] assert!(buf.is_empty()); }
function_block-full_function
[ { "content": "pub fn nickname(value: impl AsRef<str>) -> bool {\n\n _nickname(value.as_ref())\n\n}\n\n\n", "file_path": "http/src/request/validate.rs", "rank": 1, "score": 236364.6791374869 }, { "content": "pub fn username(value: impl AsRef<str>) -> bool {\n\n // <https://discordapp.co...
Rust
src/plot/plotters_backend/pdf.rs
ccleve/cargo-criterion
c4003934318015a06a6c48e8e6e9d855662c0485
use crate::plot::plotters_backend::{Colors, DEFAULT_FONT, POINT_SIZE, SIZE}; use crate::plot::{FilledCurve, Line, Points, Size, VerticalLine}; use crate::report::BenchmarkId; use crate::stats::univariate::Sample; use plotters::data::float::pretty_print_float; use plotters::prelude::*; use plotters::style::RGBACol...
use crate::plot::plotters_backend::{Colors, DEFAULT_FONT, POINT_SIZE, SIZE}; use crate::plot::{FilledCurve, Line, Points, Size, VerticalLine}; use crate::report::BenchmarkId; use crate::stats::univariate::Sample; use plotters::data::float::pretty_print_float; use plotters::prelude::*; use plotters::style::RGBACol...
y (a.u.)") .x_desc(format!("Average Time ({})", unit)) .x_label_formatter(&|&x| pretty_print_float(x, true)) .y_label_formatter(&|&y| pretty_print_float(y, true)) .x_labels(5) .draw() .unwrap(); chart .draw_series(AreaSeries::new( base_p...
function_block-function_prefixed
[ { "content": "pub fn time(ns: f64) -> String {\n\n if ns < 1.0 {\n\n format!(\"{:>6} ps\", short(ns * 1e3))\n\n } else if ns < 10f64.powi(3) {\n\n format!(\"{:>6} ns\", short(ns))\n\n } else if ns < 10f64.powi(6) {\n\n format!(\"{:>6} us\", short(ns / 1e3))\n\n } else if ns < 10...
Rust
rafx-plugins/src/features/text/jobs/prepare.rs
aclysma/renderer_prototype
a274b82c873c0ec7f9d6c3376cd054bfccfe3895
use rafx::render_feature_prepare_job_predule::*; use super::*; use crate::phases::UiRenderPhase; use crate::shaders::text::{text_frag, text_vert}; use rafx::api::{RafxBufferDef, RafxDeviceContext}; use rafx::base::resource_map::WriteBorrow; use rafx::framework::ResourceContext; pub struct TextPrepareJob<'prepare> { ...
use rafx::render_feature_prepare_job_predule::*; use super::*; use crate::phases::UiRenderPhase; use crate::shaders::text::{text_frag, text_vert}; use rafx::api::{RafxBufferDef, Raf
submit_data .draw_call_buffers .push(TextDrawCallBuffers { vertex_buffer, index_buffer, }); } context .submit_packet() .per_frame_submit_data() .set(per_frame_submit_data); } ...
xDeviceContext}; use rafx::base::resource_map::WriteBorrow; use rafx::framework::ResourceContext; pub struct TextPrepareJob<'prepare> { font_atlas_cache: TrustCell<WriteBorrow<'prepare, FontAtlasCache>>, resource_context: ResourceContext, device_context: RafxDeviceContext, } impl<'prepare> TextPrepareJob<...
random
[ { "content": "use super::BasicPipelineRenderOptions;\n\nuse crate::phases::PostProcessRenderPhase;\n\nuse crate::pipelines::basic::BasicPipelineOutputColorSpace;\n\nuse rafx::api::RafxSwapchainColorSpace;\n\nuse rafx::framework::{MaterialPassResource, ResourceArc};\n\nuse rafx::graph::*;\n\nuse rafx::render_fea...
Rust
src/libnative/io/mod.rs
P1start/rust
d64b4103d688f38c2e9e2daf966d50beeb383f1e
#![allow(non_snake_case)] use libc::{mod, c_int}; use std::c_str::CString; use std::os; use std::rt::rtio::{mod, IoResult, IoError}; use std::num; pub use self::file::FileDesc; pub use self::process::Process; mod helper_thread; pub mod addrinfo; pub mod net; pub mod process; mod util; #[cfg(unix)] #[path = "file...
#![allow(non_snake_case)] use libc::{mod, c_int}; use std::c_str::CString; use std::os; use std::rt::rtio::{mod, IoResult, IoError}; use std::num; pub use self::file::FileDesc; pub use self::process::Process; mod helper_thread; pub mod addrinfo; pub mod net; pub mod process; mod util; #[cfg(unix)]
ol(ret: libc::c_int) -> IoResult<()> { if ret == 0 { Err(last_error()) } else { Ok(()) } } #[cfg(windows)] #[inline] fn retry<I> (f: || -> I) -> I { f() } #[cfg(unix)] #[inline] fn retry<I: PartialEq + num::One + Neg<I>> (f: || -> I) -> I { let minus_one = -num::one::<I>(); loop {...
#[path = "file_unix.rs"] pub mod file; #[cfg(windows)] #[path = "file_windows.rs"] pub mod file; #[cfg(target_os = "macos")] #[cfg(target_os = "ios")] #[cfg(target_os = "freebsd")] #[cfg(target_os = "dragonfly")] #[cfg(target_os = "android")] #[cfg(target_os = "linux")] #[path = "timer_unix.rs"] pub mod timer; #[cfg(...
random
[ { "content": "#[cfg(windows)]\n\npub fn set_nonblocking(fd: net::sock_t, nb: bool) -> IoResult<()> {\n\n let mut set = nb as libc::c_ulong;\n\n if unsafe { c::ioctlsocket(fd, c::FIONBIO, &mut set) != 0 } {\n\n Err(last_error())\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path"...
Rust
inplace_common/src/hash/digest/hmac.rs
teawithsand/inplace
c4c36737d0cb5a2c503d980de2044034460b97a2
use digest::{BlockInput, FixedOutput, Reset, Update}; use generic_array::{ArrayLength, GenericArray}; use hmac::{Hmac, Mac, NewMac}; use typenum::Unsigned; use inplace::{Error, ErrorCause}; use inplace::sign_hash::{SigningAlgorithmInfo, SigningAlgorithmKind, SigningOutputSize}; use inplace::sign_hash::{InPlaceOutputFi...
use digest::{BlockInput, FixedOutput, Reset, Update}; use generic_array::{ArrayLength, GenericArray}; use hmac::{Hmac, Mac, NewMac}; use typenum::Unsigned; use inplace::{Error, ErrorCause}; use inplace::sign_hash::{SigningAlgorithmInfo, SigningAlgorithmKind, SigningOutputSize}; use inplace::sign_hash::{InPlaceOutputFi...
}
let hash = self.finalize_output_in_place()?; if !constant_time_compare(&hash[..], &sign[..]) { return Err(ErrorCause::SignInvalid.into()); } Ok(()) }
function_block-function_prefix_line
[]
Rust
src/sieve.rs
VladMoldoveanu/SSoZ
0219d6271ef98bf73d6e5270f3584efb1ba1edb7
use super::precalculated_values::*; use std::sync::{Arc, mpsc}; use std::thread; use num::integer::sqrt; use memsec::memzero; pub fn largest_twin_prime_before(max : usize) -> (usize, usize) { let num = (max - 1) | 1; let (modpg, res_cnt, pairs_cnt, bn , residues, res_twins, res_inv) = select_pg(n...
use super::precalculated_values::*; use std::sync::{Arc, mpsc}; use std::thread; use num::integer::sqrt; use memsec::memzero; pub fn largest_twin_prime_before(max : usize) -> (usize, usize) { let num = (max - 1) | 1; let (modpg, res_cnt, pairs_cnt, bn , residues, res_twins, res_inv) = select_pg(n...
fn select_pg(num: usize) -> (usize, usize, usize, usize, Vec<usize>, Vec<usize>, Arc<Vec<usize>>) { if num < 100_000usize { return (PARAMETERS_P5.0 , PARAMETERS_P5.1, PARAMETERS_P5.2, 16, PARAMETERS_P5.3.to_vec(), PARAMETERS_P5.4.to_vec(), Arc::new(PARAMETERS_P5.5.to_vec())); } i...
fn next_p_init(r_hi: usize, modpg: usize, primes: Arc<Vec<usize>>, p_cnt: usize, res_inv: Arc<Vec<usize>>, pos: Arc<Vec<usize>>) -> Vec<usize> { let mut next_p = vec![0usize; p_cnt * 2]; let r_lo = r_hi - 2; let (row_lo, row_hi) = (0usize, p_cnt); for (i, prime) in primes.iter().enumerat...
function_block-full_function
[ { "content": "//Generate parameters at \"compile time\"\n\n//(i.e. write to file and paste to 'precalculated_values.rs'\n\npub fn _gen_pg_parameters(prime: u64) -> String {\n\n println!(\"Generating pg parameters for prime: {}\", prime);\n\n let primes = vec![2u64, 3, 5, 7, 11, 13, 17, 19, 23];\n\n let...
Rust
src/rust/engine/fs/store/src/remote.rs
christophermaier/pants
652df2cb5138eb01a6be7935023c56e36563b1cd
use std::cmp::min; use std::collections::{BTreeMap, HashSet}; use std::convert::TryInto; use std::fmt; use std::sync::Arc; use std::time::{Duration, Instant}; use bazel_protos::gen::build::bazel::remote::execution::v2 as remexec; use bazel_protos::gen::google::bytestream::byte_stream_client::ByteStreamClient; use baze...
use std::cmp::min; use std::collections::{BTreeMap, HashSet}; use std::convert::TryInto; use std::fmt; use std::sync::Arc; use std::time::{Duration, Instant}; use bazel_protos::gen::build::bazel::remote::execution::v2 as remexec; use bazel_protos::gen::google::bytestream::byte_stream_client::ByteStreamClie
ult<Digest, String> { let len = bytes.len(); let digest = Digest::of_bytes(&bytes); let resource_name = format!( "{}/uploads/{}/blobs/{}/{}", self.instance_name.clone().unwrap_or_default(), uuid::Uuid::new_v4(), digest.hash, digest.size_bytes, ); let workunit_name = for...
nt; use bazel_protos::{self}; use bytes::{Bytes, BytesMut}; use futures::future::TryFutureExt; use futures::Future; use futures::StreamExt; use grpc_util::headers_to_interceptor_fn; use hashing::Digest; use itertools::{Either, Itertools}; use log::Level; use remexec::content_addressable_storage_client::ContentAddressab...
random
[ { "content": "// TODO(tonic): Replace uses of this method with `.into` or equivalent.\n\nfn to_bazel_digest(digest: Digest) -> remexec::Digest {\n\n remexec::Digest {\n\n hash: digest.hash.to_hex(),\n\n size_bytes: digest.size_bytes as i64,\n\n }\n\n}\n\n\n", "file_path": "src/rust/engine/fs/store/s...
Rust
native_implemented/otp/src/macros/number.rs
mlwilkerson/lumen
048df6c0840c11496e2d15aa9af2e4a8d07a6e0f
macro_rules! number_infix_operator { ($left:ident, $right:ident, $process:ident, $checked:ident, $infix:tt) => {{ use anyhow::*; use num_bigint::BigInt; use liblumen_alloc::erts::exception::*; use liblumen_alloc::erts::process::trace::Trace; use liblumen_alloc::erts::term::p...
macro_rules! number_infix_operator { ($left:ident, $right:ident, $process:ident, $checked:ident, $infix:tt) => {{ use anyhow::*; use num_bigint::BigInt; use liblumen_alloc::erts::exception::*; use liblumen_alloc::erts::process::trace::Trace; use liblumen_alloc::erts::term::p...
} }; }
igInteger(left_big_integer), TypedTerm::BigInteger(right_big_integer)) => { let left_big_int: &BigInt = left_big_integer.as_ref().into(); let right_big_int: &BigInt = right_big_integer.as_ref().into(); BigInts(left_big_int.clone(), right_big_int.clone()) } ...
random
[ { "content": "fn f64_cmp_f64(left: f64, right: f64) -> Ordering {\n\n match left.partial_cmp(&right) {\n\n Some(ordering) => ordering,\n\n // Erlang doesn't support the floats that can't be compared\n\n None => unreachable!(),\n\n }\n\n}\n\n\n\nunsafe fn integral_f64_to_big_int(integr...
Rust
src/rayon.rs
Nugine/indicatif
a7685ffc00a48b6706808ce68ebcd5da31c18c54
use crate::{ProgressBar, ProgressBarIter}; use rayon::iter::{ plumbing::{Consumer, Folder, Producer, ProducerCallback, UnindexedConsumer}, IndexedParallelIterator, ParallelIterator, }; use std::convert::TryFrom; pub trait ParallelProgressIterator where Self: Sized + ParallelIterator, { fn progress...
use crate::{ProgressBar, ProgressBarIter}; use rayon::iter::{ plumbing::{Consumer, Folder, Producer, ProducerCallback, UnindexedConsumer}, IndexedParallelIterator, ParallelIterator, }; use std::convert::TryFrom; pub trait ParallelProgressIterator where Self: Sized + ParallelIterator, { fn progress...
} struct ProgressProducer<T> { base: T, progress: ProgressBar, } impl<T, P: Producer<Item = T>> Producer for ProgressProducer<P> { type Item = T; type IntoIter = ProgressBarIter<P::IntoIter>; fn into_iter(self) -> Self::IntoIter { ProgressBarIter { it: self.base.into_iter(), ...
progress: self.progress, }; self.callback.callback(producer) } } }
function_block-function_prefix_line
[ { "content": "/// Wraps an iterator to display its progress.\n\npub trait ProgressIterator\n\nwhere\n\n Self: Sized + Iterator,\n\n{\n\n /// Wrap an iterator with default styling. Uses `Iterator::size_hint` to get length.\n\n /// Returns `Some(..)` only if `size_hint.1` is `Some`. If you want to create...
Rust
src/libsyntax/ext/deriving/cmp/ord.rs
pshc/rust
d07d465cf60033e35eba16b9e431471d54c712f4
use ast; use ast::{MetaItem, Expr}; use codemap::Span; use ext::base::{ExtCtxt, Annotatable}; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use ptr::P; pub fn expand_deriving_ord(cx: &mut ExtCtxt, span: Span,...
use ast; use ast::{MetaItem, Expr}; use codemap::Span; use ext::base::{ExtCtxt, Annotatable}; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use ptr::P; pub fn expand_deriving_ord(cx: &mut ExtCtxt, span: Span,...
, mitem, item, push) } pub fn ordering_collapsed(cx: &mut ExtCtxt, span: Span, self_arg_tags: &[ast::Ident]) -> P<ast::Expr> { let lft = cx.expr_ident(span, self_arg_tags[0]); let rgt = cx.expr_addr_of(span, cx.expr_ident(span, self_arg_tags[1])); cx.expr...
otatable, push: &mut FnMut(Annotatable)) { let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::cmp::Ord), ...
random
[ { "content": "/// Extract a string literal from the macro expanded version of `expr`,\n\n/// emitting `err_msg` if `expr` is not a string literal. This does not stop\n\n/// compilation on error, merely emits a non-fatal error and returns None.\n\npub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_m...
Rust
src/commands/voice/mod.rs
iriie/maki
32ee4280a7f1c62400bc3e77415d16510fbb46d1
pub mod play; pub mod sources; use std::{collections::{HashMap, hash_map::RandomState}, sync::Arc}; use serenity::{model::id::GuildId, async_trait, http::Http, model::prelude::ChannelId, framework::standard::{Args, CommandOptions, Reason, macros::check}}; use serenity::model::prelude::*; use serenity::prelude::*; us...
pub mod play; pub mod sources; use std::{collections::{HashMap, hash_map::RandomState}, sync::Arc}; use serenity::{model::id::GuildId, async_trait, http::Http, model::prelude::ChannelId, framework::standard::{Args, CommandOptions, Reason, macros::check}}; use serenity::model::prelude::*; use serenity::prelude::*; us...
}
n())) ); println!( "Audio packet sequence {:05} has {:04} bytes (decompressed from {}), SSRC {}", data.packet.sequence.0, audio.len() * std::mem::size_of::<i16>(), data.packet.payload....
function_block-function_prefixed
[ { "content": "struct ReturnSource {\n\n title: String,\n\n artist: String, \n\n source_url: String,\n\n thumbnail: String,\n\n duration: Duration\n\n}\n\n\n\n\n\nasync fn audius_track(artist: String, slug: String, id: i64) {\n\nconst AUDIUS_PROVIDER: &str = \"https://dn-usa.audius.metadata.fyi/\"...
Rust
rs/crypto/internal/crypto_service_provider/src/types/conversions.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
use super::{ CspDealing, CspDkgTranscript, CspPop, CspPublicCoefficients, CspPublicKey, CspSecretKey, CspSignature, MultiBls12_381_Signature, SigConverter, ThresBls12_381_Signature, }; use ic_crypto_internal_basic_sig_ecdsa_secp256k1::types as ecdsa_secp256k1_types; use ic_crypto_internal_basic_sig_ecdsa_secp...
use super::{ CspDealing, CspDkgTranscript, CspPop, CspPublicCoefficients, CspPublicKey, CspSecretKey, CspSignature, MultiBls12_381_Signature, SigConverter, ThresBls12_381_Signature, }; use ic_crypto_internal_basic_sig_ecdsa_secp256k1::types as ecdsa_secp256k1_types; use ic_crypto_internal_basic_sig_ecdsa_secp...
} } impl From<&CspDkgTranscript> for CspPublicCoefficients { fn from(csp_dkg_transcript: &CspDkgTranscript) -> Self { match csp_dkg_transcript { CspDkgTranscript::Secp256k1(clib_transcript) => { CspPublicCoefficients::Bls12_381(clib_transcript.public_coefficients.clone()) ...
match public_key { CspPublicKey::EcdsaP256(_) => AlgorithmId::EcdsaP256, CspPublicKey::EcdsaSecp256k1(_) => AlgorithmId::EcdsaSecp256k1, CspPublicKey::Ed25519(_) => AlgorithmId::Ed25519, CspPublicKey::MultiBls12_381(_) => AlgorithmId::MultiBls12_381, CspPublic...
if_condition
[]
Rust
tokio-postgres/src/proto/typeinfo.rs
CoreRabbit/rust-postgres
73ee31e522c6c2c5bcee2940070a737390a4157c
use futures::stream::{self, Stream}; use futures::{Async, Future, Poll}; use state_machine_future::RentToOwn; use error::{Error, SqlState}; use next_statement; use proto::client::Client; use proto::prepare::PrepareFuture; use proto::query::QueryStream; use proto::statement::Statement; use proto::typeinfo_composite::Ty...
use futures::stream::{self, Stream}; use futures::{Async, Future, Poll}; use state_machine_future::RentToOwn; use error::{Error, SqlState}; use next_statement; use proto::client::Client; use proto::prepare::PrepareFuture; use proto::query::QueryStream; use proto::statement::Statement; use proto::typeinfo_composite::Ty...
} else { Kind::Simple }; let ty = Type::_new(name.to_string(), state.oid, kind, schema.to_string()); transition!(CachingType { ty, oid: state.oid, client: state.client, }) } fn poll_querying_enum_variants<'a>( state: &'a...
ew(TypeinfoFuture::new(elem_oid, state.client)), name, oid: state.oid, schema, }) } else if relid != 0 { transition!(QueryingCompositeFields { future: TypeinfoCompositeFuture::new(relid, state.client), name, ...
function_block-random_span
[ { "content": "#[inline]\n\npub fn oid_from_sql(mut buf: &[u8]) -> Result<Oid, StdBox<Error + Sync + Send>> {\n\n let v = buf.read_u32::<BigEndian>()?;\n\n if !buf.is_empty() {\n\n return Err(\"invalid buffer size\".into());\n\n }\n\n Ok(v)\n\n}\n\n\n\n/// Serializes an `INT8` value.\n", "...
Rust
lusion-db/src/users.rs
Dokuro-YH/lusion
63d8275e467551a3c1ee7ed752223ffc1281f878
use chrono::prelude::*; use diesel::prelude::*; use uuid::Uuid; use crate::error::DbError; use crate::pg::PgConn; use crate::schema::users; #[derive(Debug, PartialEq, Queryable, Insertable, Serialize)] #[table_name = "users"] pub struct User { pub id: Uuid, pub username: String, #[serde(skip_serializing)...
use chrono::prelude::*; use diesel::prelude::*; use uuid::Uuid; use crate::error::DbError; use crate::pg::PgConn; use crate::schema::users; #[derive(Debug, PartialEq, Queryable, Insertable, Serialize)] #[table_name = "users"] pub struct User { pub id: Uuid, pub username: String, #[serde(skip_serializing)...
), )) .execute(self)?) } fn delete_user(&self, user_id: &Uuid) -> Result<usize, DbError> { Ok(diesel::delete(users::table.find(user_id)).execute(self)?) } } #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; #[test] fn test_find_users_should...
: String, pub avatar_url: String, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc>, } #[derive(Debug, Deserialize)] pub struct CreateUser { pub username: String, pub password: String, pub nickname: String, pub avatar_url: String, } #[derive(Debug, Deserialize)] pub struct Updat...
random
[ { "content": "#[derive(Deserialize)]\n\nstruct PutPassword {\n\n old_password: String,\n\n new_password: String,\n\n}\n\n\n\npub async fn put_user_password<Pool>(mut cx: Context<Pool>) -> EndpointResult\n\nwhere\n\n Pool: DbPool,\n\n Pool::Connection: UserRepository,\n\n{\n\n let user_id = cx.par...
Rust
clapi_macros/src/arg.rs
Neo-Ciber94/clapi-rs
bfcbee023ca5f6767d135cbcef3fc7a5329e099a
#![allow(clippy::len_zero, clippy::redundant_closure)] use crate::command::{is_option_bool_flag, FnArgData}; use crate::macro_attribute::{Value, MacroAttribute, display_lit}; use crate::utils::pat_type_to_string; use crate::var::ArgumentType; use crate::{consts, LitExtensions, TypeExt}; use proc_macro2::TokenStream; us...
#![allow(clippy::len_zero, clippy::redundant_closure)] use crate::command::{is_option_bool_flag, FnArgData}; use crate::macro_attribute::{Value, MacroAttribute, display_lit}; use crate::utils::pat_type_to_string; use crate::var::ArgumentType; use crate::{consts, LitExtensions, TypeExt}; use proc_macro2::TokenStream; us...
fn check_same_type(values: &[Lit]) -> Result<(), &Lit> { if values.len() <= 1 { Ok(()) } else { let comp = &values[0]; for value in &values[1..] { if std::mem::discriminant(comp) != std::mem::discriminant(value) { return Err(value); } } ...
fn lit_variant_to_string(lit: &Lit) -> &'static str { match lit { Lit::Str(_) => "string", Lit::ByteStr(_) => "string", Lit::Byte(_) => "byte", Lit::Char(_) => "char", Lit::Int(_) => "integer", Lit::Float(_) => "float", Lit::Bool(_) => "bool", Lit::Ver...
function_block-full_function
[ { "content": "#[doc(hidden)]\n\npub fn split_into_args_with_quote_escape(value: &str, quote_escape: char) -> Vec<String> {\n\n const DOUBLE_QUOTE : char = '\"';\n\n\n\n let mut result = Vec::new();\n\n let mut buffer = String::new();\n\n let mut chars = value.chars().peekable();\n\n let mut in_qu...
Rust
src/query/delete.rs
SeaQL/Sea-Query
6c9527ae08e32c55490ae510be41f646e030c2a2
use crate::{ backend::QueryBuilder, prepare::*, query::{condition::*, OrderedStatement}, types::*, value::*, QueryStatementBuilder, QueryStatementWriter, ReturningClause, SubQueryStatement, WithClause, WithQuery, }; #[derive(Debug, Clone)] pub struct DeleteStatement { pub(crate) table: ...
use crate::{ backend::QueryBuilder, prepare::*, query::{condition::*, OrderedStatement}, types::*, value::*, QueryStatementBuilder, QueryStatementWriter, ReturningClause, SubQueryStatement, WithClause, WithQuery, }; #[derive(Debug, Clone)] pub struct DeleteStatement { pub(crate) table: ...
rderedStatement for DeleteStatement { fn add_order_by(&mut self, order: OrderExpr) -> &mut Self { self.orders.push(order); self } } impl ConditionalStatement for DeleteStatement { fn and_or_where(&mut self, condition: LogicalChainOper) -> &mut Self { self.wherei.add_and_or(condition...
#[allow(clippy::wrong_self_convention)] pub fn from_table<T>(&mut self, tbl_ref: T) -> &mut Self where T: IntoTableRef, { self.table = Some(Box::new(tbl_ref.into_table_ref())); self } ...
random
[ { "content": "#[allow(clippy::many_single_char_names)]\n\n#[cfg(feature = \"with-json\")]\n\n#[cfg_attr(docsrs, doc(cfg(feature = \"with-json\")))]\n\npub fn sea_value_to_json_value(value: &Value) -> Json {\n\n use crate::{CommonSqlQueryBuilder, QueryBuilder};\n\n\n\n match value {\n\n Value::Bool(...
Rust
examples/server.rs
aprilwade/embedded-websocket
407131f0cda81a219cbb7dbc12687256b6a3b577
use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::str::Utf8Error; use std::thread; use embedded_websocket as ws; use ws::{ HttpHeader, WebSocketReceiveMessageType, WebSocketSendMessageType, WebSocketServer, WebSocketState, }; type Result<T> = std::result::Result<T, WebServerError>...
use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::str::Utf8Error; use std::thread; use embedded_websocket as ws; use ws::{ HttpHeader, WebSocketReceiveMessageType, WebSocketSendMessageType, WebSocketServer, WebSocketState, }; type Result<T> = std::result::Result<T, WebServerError>...
:Ping => { let to_send = web_socket.write( WebSocketSendMessageType::Pong, true, &ws_buffer[..ws_result.len_to], tcp_buffer, )?; write_to_stream(stream, &tcp_buffer[..to_send])?; Ok(true) } We...
e request"); let to_send = web_socket.server_accept(&websocket_context.sec_websocket_key, None, buffer2)?; write_to_stream(stream, &buffer2[..to_send])?; Ok(true) } else { println!("Received file request: {}", http_header.path.as_str()); match http_heade...
random
[ { "content": "// NOTE: this function is re-exported\n\n/// Reads a buffer and extracts the HttpHeader information from it, including websocket specific information.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// use embedded_websocket as ws;\n\n/// let client_request = \"GET /chat HTTP/1.1\n\n/// Host: myserver.exa...
Rust
src/types/column_flag_type.rs
cosmo0920/ruroonga_command
9664094a5992c687d2a446d2747b11b81d6855d1
use std::fmt; use std::str::FromStr; use std::convert::AsRef; use self::ColumnFlagType::{Scalar, Vector, Index, WithSection, WithWeight, WithPosition, ExtColumnFlagType}; #[cfg(feature="unstable")] use self::ColumnFlagType::{CompressZlib, CompressLz4}; #[cfg(all(feature="unstable", feature="g...
use std::fmt; use std::str::FromStr; use std::convert::AsRef; use self::ColumnFlagType::{Scalar, Vector, Index, WithSection, WithWeight, WithPosition, ExtColumnFlagType}; #[cfg(feature="unstable")] use self::ColumnFlagType::{CompressZlib, CompressLz4}; #[cfg(all(feature="unstable", feature="g...
} } } impl fmt::Display for ColumnFlagType { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(match *self { Scalar => "COLUMN_SCALAR", Vector => "COLUMN_VECTOR", Index => "COLUMN_INDEX", WithSection => "WITH_SECTION", ...
Ok(match s { "Scalar" | "ColumnScalar" | "COLUMN_SCALAR" => Scalar, "Vector" | "ColumnVector" | "COLUMN_VECTOR" => Vector, "Index" | "ColumnsIndex" | "COLUMN_INDEX" => Index, "WithSection" | "WITH_SECTION" => WithSection, "WithWeight" | "WI...
call_expression
[ { "content": "pub fn tokenize(tokenizer: TokenizerType, string: String) -> TokenizeCommand {\n\n TokenizeCommand::new(tokenizer, string)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use tokenize::TokenizeCommand;\n\n use types::tokenizer_type::TokenizerType;\n\n\n\n #[test]\n\n ...
Rust
src/mp/tags.rs
manbu-00/wx-sdk
ee707e3ee9afda5f2a28b95bda83a6d860d9c069
use serde::{Deserialize, Serialize}; use crate::{ error::{CommonError, CommonResponse}, wechat::WxApiRequestBuilder, SdkResult, }; use self::members::MembersModule; #[derive(Debug, Serialize, Deserialize)] #[serde(rename = "tag")] pub struct Tag { pub tag: TagValue, } #[derive(Debug, Serialize, Deser...
use serde::{Deserialize, Serialize}; use crate::{ error::{CommonError, CommonResponse}, wechat::WxApiRequestBuilder, SdkResult, }; use self::members::MembersModule; #[derive(Debug, Serialize, Deserialize)] #[serde(rename = "tag")] pub struct Tag { pub tag: TagValue, } #[derive(Debug, Serialize, Deser...
pub async fn get(&self) -> SdkResult<Tags> { let base_url = "https://api.weixin.qq.com/cgi-bin/tags/get"; let sdk = self.0; let builder = sdk.wx_get(base_url).await?; let tag: CommonResponse<Tags> = builder.send().await?.json().await?; tag.into() } pub async fn get...
pub async fn delete(&self, tag_id: i32) -> SdkResult<()> { let base_url = "https://api.weixin.qq.com/cgi-bin/tags/delete"; let sdk = self.0; let res: CommonError = sdk .wx_post(base_url) .await? .json(&serde_json::json!({ "tag": { "id": tag_id } })) ...
function_block-full_function
[]
Rust
src/librustc_typeck/check/coercion.rs
aepsil0n/rust
8025bc964c0f31726636811d97f9f46cd0d4c40f
use check::{autoderef, FnCtxt, LvaluePreference, UnresolvedTypeAction}; use middle::infer::{self, Coercion}; use middle::traits::{self, ObligationCause}; use middle::traits::{predicate_for_trait_def, report_selection_error}; use middle::ty::{AutoDerefRef, AdjustDerefRef}; use middle::ty::{self, mt, Ty}; use middle::...
use check::{autoderef, FnCtxt, LvaluePreference, UnresolvedTypeAction}; use middle::infer::{self, Coercion}; use middle::traits::{self, ObligationCause}; use middle::traits::{predicate_for_trait_def, report_selection_error}; use middle::ty::{AutoDerefRef, AdjustDerefRef}; use middle::ty::{self, mt, Ty}; use middle::...
let adjustment = try!(coerce.coerce(expr, a, b)); unsizing_obligations = coerce.unsizing_obligations.into_inner(); Ok(adjustment) }) })); if let Some(AdjustDerefRef(auto)) = adjustment { if auto.unsize.is_some() { for obligation in unsizing_obligations { ...
ing_obligations.borrow_mut(); assert!(obligations.is_empty()); *obligations = leftover_predicates; let adjustment = AutoDerefRef { autoderefs: if reborrow.is_some() { 1 } else { 0 }, autoref: reborrow, unsize: Some(target) }; debug!("Success, ...
random
[ { "content": "fn parse_mt_<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, conv: &mut F) -> ty::mt<'tcx> where\n\n F: FnMut(DefIdSource, ast::DefId) -> ast::DefId,\n\n{\n\n let m = parse_mutability(st);\n\n ty::mt { ty: parse_ty_(st, conv), mutbl: m }\n\n}\n\n\n", "file_path": "src/librustc/metadata/tydeco...
Rust
vm/src/obj/objsuper.rs
josalmi/RustPython
de7ef551c06d1f470a2344e4c2afc9d696fd6eb5
/*! Python `super` class. See also: https://github.com/python/cpython/blob/50b48572d9a90c5bb36e2bef6179548ea927a35a/Objects/typeobject.c#L7663 */ use super::objstr::PyStrRef; use super::objtype::{self, PyType, PyTypeRef}; use crate::function::OptionalArg; use crate::pyobject::{ BorrowValue, IdProtocol, PyClassI...
/*! Python `super` class. See also: https://github.com/python/cpython/blob/50b48572d9a90c5bb36e2bef6179548ea927a35a/Objects/typeobject.c#L7663 */ use super::objstr::PyStrRef; use super::objtype::{self, PyType, PyTypeRef}; use crate::function::OptionalArg; use crate::pyobject::{ BorrowValue, IdProtocol, PyClassI...
pub fn init(context: &PyContext) { let super_type = &context.types.super_type; PySuper::extend_class(context, super_type); let super_doc = "super() -> same as super(__class__, <first argument>)\n\ super(type) -> unbound super object\n\ super(type, obj) -> bound s...
let class_attr = vm.get_attribute(obj, "__class__")?; if let Ok(cls) = class_attr.downcast::<PyType>() { if !cls.is(&ty) && objtype::issubclass(&cls, &ty) { return Ok(cls); } } Err(vm .new_type_error("super(type, obj): obj must be an instance or subtype of type".to_owned(...
function_block-function_prefix_line
[ { "content": "#[inline]\n\nfn get_class_magic(zelf: &PyObjectRef, name: &str) -> PyObjectRef {\n\n zelf.get_class_attr(name).unwrap()\n\n\n\n // TODO: we already looked up the matching class but lost the information here\n\n // let cls = zelf.lease_class();\n\n // let attrs = cls.attributes.read();\...
Rust
tests/by-util/test_id.rs
youknowone/coreutils
44713356097bcf23c98190e6717d9e4577667567
use crate::common::util::*; fn skipping_test_is_okay(result: &CmdResult, needle: &str) -> bool { if !result.succeeded() { println!("result.stdout = {}", result.stdout_str()); println!("result.stderr = {}", result.stderr_str()); if is_ci() && result.stderr_str().contains(needle) { ...
use crate::common::util::*; fn skipping_test_is_okay(result: &CmdResult, needle: &str) -> bool { if !result.succeeded() { println!("result.stdout = {}", result.stdout_str()); println!("result.stderr = {}", result.stderr_str()); if is_ci() && result.stderr_str().contains(needle) { ...
#[test] fn test_id_group() { let scene = TestScenario::new(util_name!()); let mut result = scene.ucmd().arg("-g").succeeds(); let s1 = result.stdout_str().trim(); assert!(s1.parse::<f64>().is_ok()); result = scene.ucmd().arg("--group").succeeds(); let s1 = result.stdout_str().trim(); ass...
sername_whoami = return_whoami_username(); if username_whoami.is_empty() { return; } assert_eq!(username_id, username_whoami); }
function_block-function_prefixed
[ { "content": "// Apparently some CI environments have configuration issues, e.g. with 'whoami' and 'id'.\n\n// If we are running inside the CI and \"needle\" is in \"stderr\" skipping this test is\n\n// considered okay. If we are not inside the CI this calls assert!(result.success).\n\n//\n\n// From the Logs: \...
Rust
src/dataflow-types/src/client/controller.rs
jeschkies/materialize
9611cc69528eee6228fe17e931340b1bb91e5684
use std::collections::BTreeMap; use differential_dataflow::lattice::Lattice; use timely::progress::frontier::{Antichain, AntichainRef}; use timely::progress::Timestamp; use crate::client::{ Client, Command, ComputeCommand, ComputeInstanceId, ComputeResponse, Response, StorageResponse, }; use crate::logging::Log...
use std::collections::BTreeMap; use differential_dataflow::lattice::Lattice; use timely::progress::frontier::{Antichain, AntichainRef}; use timely::progress::Timestamp; use crate::client::{ Client, Command, ComputeCommand, ComputeInstanceId, ComputeResponse, Response, StorageResponse, }; use crate::logging::Log...
impl ReadPolicy<mz_repr::Timestamp> { pub fn lag_writes_by(lag: mz_repr::Timestamp) -> Self { Self::LagWriteFrontier(Arc::new(move |upper| { if upper.is_empty() { Antichain::from_elem(Timestamp::minimum()) } else { ...
esponse { Response::Compute(ComputeResponse::FrontierUppers(updates), instance) => { self.compute(*instance) .expect("Reference to absent instance") .update_write_frontiers(updates) ...
random
[ { "content": "pub fn read_long<R: Read>(reader: &mut R) -> Result<i64, AvroError> {\n\n zag_i64(reader)\n\n}\n\n\n", "file_path": "src/avro/src/util.rs", "rank": 0, "score": 409481.7616315404 }, { "content": "pub fn zag_i64<R: Read>(reader: &mut R) -> Result<i64, AvroError> {\n\n let z...
Rust
src/circuit_generators/rand_mirror.rs
MichalReznak/quep
dacab9f5678080dfc973e2fa6c0aa849b09c2aff
use std::fmt::Write; use async_trait::async_trait; use derive_more::Constructor; use log::debug; use rand::distributions::{Distribution, Uniform}; use crate::traits::CircuitGenerator; use crate::Error; const CIRCUIT_TEMPLATE: &str = r#" OPENQASM 2.0; include "qelib1.inc"; qreg q[%WIDTH%]; creg c[%WIDTH%]; %RESET% ...
use std::fmt::Write; use async_trait::async_trait; use derive_more::Constructor; use log::debug; use rand::distributions::{Distribution, Uniform}; use crate::traits::CircuitGenerator; use crate::Error; const CIRCUIT_TEMPLATE: &str = r#" OPENQASM 2.0; include "qelib1.inc"; qreg q[%WIDTH%]; creg c[%WIDTH%]; %RESET% ...
}
async fn generate(&self, i: i32, j: i32) -> Result<Option<String>, Error> { let pauli_gates = ["id", "x", "y", "z"]; let clifford_gates = ["h", "s", "id", "x", "y", "z"]; let clifford_gates_inv = ["h", "sdg", "id", "x", "y", "z"]; let clifford_gates_2 = ["cx", "cz", "swap"]; ...
function_block-full_function
[ { "content": "#[throws]\n\npub fn get_dir(s: &str) -> String {\n\n dunce::canonicalize(s)?.to_str().context(\"Cannot to string\")?.to_owned()\n\n}\n", "file_path": "tests/common/mod.rs", "rank": 0, "score": 55262.844679403795 }, { "content": "#[derive(Serialize, Deserialize, TypedBuilder,...
Rust
src/main.rs
rbutoi/starship
a670e01c229cd71529a7313f1d5b96ae3e0cd69d
use std::time::SystemTime; #[macro_use] extern crate clap; #[macro_use] extern crate pest_derive; mod bug_report; mod config; mod configs; mod configure; mod context; mod formatter; mod init; mod module; mod modules; mod print; mod segment; mod utils; use crate::module::ALL_MODULES; use clap::{App, AppSettings, Arg,...
use std::time::SystemTime; #[macro_use] extern crate clap; #[macro_use] extern crate pest_derive; mod bug_report; mod config; mod configs; mod configure; mod context; mod formatter; mod init; mod module; mod modules; mod print; mod segment; mod utils; use crate::module::ALL_MODULES; use clap::{App, AppSettings, Arg,...
fn main() { pretty_env_logger::init(); let status_code_arg = Arg::with_name("status_code") .short("s") .long("status") .value_name("STATUS_CODE") .help("The status code of the previously run command") .takes_value(true); let path_arg = Arg::with_name("path") ...
function_block-full_function
[]
Rust
futures/tests_disabled/ready_queue.rs
gferon/futures-rs
64529405aada4e209fe29995c5b80fc4e40f79ef
use futures::executor::{block_on, block_on_stream}; use futures::Async::*; use futures::future; use futures::stream::FuturesUnordered; use futures::channel::oneshot; use std::panic::{self, AssertUnwindSafe}; mod support; trait AssertSendSync: Send + Sync {} impl AssertSendSync for FuturesUnordered<()> {} #[test] fn ...
use futures::executor::{block_on, block_on_stream}; use futures::Async::*; use futures::future; use futures::stream::FuturesUnordered; use futures::channel::oneshot; use std::panic::{self, AssertUnwindSafe}; mod support; trait AssertSendSync: Send + Sync {} impl AssertSendSync for FuturesUnordered<()> {} #[test] fn ...
#[test] fn resolving_errors() { block_on(future::lazy(move |cx| { let mut queue = FuturesUnordered::new(); let (tx1, rx1) = oneshot::channel(); let (tx2, rx2) = oneshot::channel(); let (tx3, rx3) = oneshot::channel(); queue.push(rx1); queue.push(rx2); queue...
t (tx1, rx1) = oneshot::channel(); let (tx2, rx2) = oneshot::channel(); let (tx3, rx3) = oneshot::channel(); queue.push(rx1); queue.push(rx2); queue.push(rx3); assert!(!queue.poll_next(cx).unwrap().is_ready()); tx2.send("hello").unwrap(); assert_eq!(Re...
function_block-function_prefixed
[ { "content": "trait AssertSendSync: Send + Sync {}\n\nimpl AssertSendSync for ThreadPool {}\n\n\n", "file_path": "futures-executor/src/thread_pool.rs", "rank": 1, "score": 305617.97736329166 }, { "content": "trait AssertKinds: Send + Sync + Clone {}\n\nimpl AssertKinds for UnboundedSender<u3...
Rust
transports/dns/src/lib.rs
c410-f3r/rust-libp2p
8c119269d620f7de3956590ab45a14c9f5acd266
use futures::{future::{self, Either, FutureResult, JoinAll}, prelude::*, stream, try_ready}; use libp2p_core::{ Transport, multiaddr::{Protocol, Multiaddr}, transport::{TransportError, ListenerEvent} }; use log::{debug, trace, log_enabled, Level}; use std::{error, fmt, io, marker::PhantomData, net::IpAddr...
use futures::{future::{self, Either, FutureResult, JoinAll}, prelude::*, stream, try_ready}; use libp2p_core::{ Transport, multiaddr::{Protocol, Multiaddr}, transport::{TransportError, ListenerEvent} }; use log::{debug, trace, log_enabled, Level}; use std::{error, fmt, io, marker::PhantomData, net::IpAddr...
if !contains_dns { trace!("Pass-through address without DNS: {}", addr); let inner_dial = self.inner.dial(addr).map_err(|err| err.map(DnsErr::Underlying))?; return Ok(Either::A(inner_dial.map_err(DnsErr::Underlying))); } let resolver = self.resolver; ...
let contains_dns = addr.iter().any(|cmp| match cmp { Protocol::Dns4(_) => true, Protocol::Dns6(_) => true, _ => false, });
assignment_statement
[ { "content": "type Buffer = VecDeque<ListenerEvent<FutureResult<TcpTransStream, io::Error>>>;\n\n\n\n/// Incoming connection stream which pauses after errors.\n", "file_path": "transports/tcp/src/lib.rs", "rank": 0, "score": 325343.25832221244 }, { "content": "#[inline]\n\npub fn boxed<T>(tr...
Rust
crates/rpc-server/src/registry.rs
bitrocks/godwoken
7a99b65f9ddc6a45b9bbcd51d1f6ebc05f4ceb0d
use anyhow::Result; use ckb_types::prelude::{Builder, Entity}; use gw_common::{state::State, H256}; use gw_jsonrpc_types::{ blockchain::Script, ckb_jsonrpc_types::{JsonBytes, Uint128, Uint32}, godwoken::{L2BlockView, RunResult}, }; use gw_store::{ state_db::{StateDBTransaction, StateDBVersion}, Stor...
use anyhow::Result; use ckb_types::prelude::{Builder, Entity}; use gw_common::{state::State, H256}; use gw_jsonrpc_types::{ blockchain::Script, ckb_jsonrpc_types::{JsonBytes, Uint128, Uint32}, godwoken::{L2BlockView, RunResult}, }; use gw_store::{ state_db::{StateDBTransaction, StateDBVersion}, Stor...
async fn get_data( Params(data_hash): Params<JsonH256>, store: Data<Store>, ) -> Result<Option<JsonBytes>> { let db = store.begin_transaction(); let tip_hash = db.get_tip_block_hash()?; let state_db = StateDBTransaction::from_version(&db, StateDBVersion::from_block_hash(tip_hash))?; let ...
function_block-full_function
[ { "content": "pub fn build_data_hash_key(data_hash: &[u8]) -> H256 {\n\n let mut key: [u8; 32] = H256::zero().into();\n\n let mut hasher = new_blake2b();\n\n hasher.update(&GW_DATA_HASH_PREFIX);\n\n hasher.update(data_hash);\n\n hasher.finalize(&mut key);\n\n key.into()\n\n}\n\n\n\npub struct ...
Rust
cachoeira_core/src/transform/components/local_transform.rs
tiagosr/cachoeira
9e9b114dfeab641c3c2f05fd0d4ea194b284c688
use cgmath::{ Angle, Array, Basis2, Deg, Rad, ElementWise, EuclideanSpace, Euler, InnerSpace, Matrix3, Matrix4, One, Zero, Point2, Point3, Quaternion, Rotation, Rotation2, Rotation3, Transform as CgTransform, Vector2, Vector3, Vector4, }; use orientation::Orientation; use specs::prelude::{ Component, Den...
use cgmath::{ Angle, Array, Basis2, Deg, Rad, ElementWise, EuclideanSpace, Euler, InnerSpace, Matrix3, Matrix4, One, Zero, Point2, Point3, Quaternion, Rotation, Rotation2, Rotation3, Transform as CgTransform, Vector2, Vector3, Vector4, }; use orientation::Orientation; use specs::prelude::{ Component, Den...
} impl CgTransform<Point2<f32>> for Transform { fn one() -> Self { Default::default() } fn look_at(_eye: Point2<f32>, _center: Point2<f32>, _up: Vector2<f32>) -> Self { panic!("Can't compute look at for 2D") } fn transform_vector(&self, vec: Vector2<f32>) -> Vector2<f32> { let rot: Basis2<f32> = Rotation2::fr...
fn inverse_transform(&self) -> Option<Self> { if ulps_eq!(self.scale, Vector3::zero()) { None } else { let scale = 1. / self.scale; let rotation = self.rotation.invert(); let translation = rotation.rotate_vector(self.translation).mul_element_wise(-scale); Some(Self { translation, rotation, scale }) ...
function_block-full_function
[ { "content": "// f32 (in seconds) -> Duration\n\npub fn secs_to_duration(secs: f32) -> Duration {\n\n\tDuration::new(secs as u64, ((secs % 1.0) * 1.0e9) as u32)\n\n}\n\n\n", "file_path": "cachoeira_core/src/timing.rs", "rank": 0, "score": 136674.83585138572 }, { "content": "// Duration -> f3...
Rust
nekoton-derive/tests/map.rs
broxus/nekoton
1c54cc64a2b4b266a9ba8b677fbf7542bc13bd2a
use std::str::FromStr; use std::collections::BTreeMap; use ton_abi::{ParamType, TokenValue}; use ton_abi::{Token, Uint}; use ton_block::{MsgAddress, MsgAddressInt}; use nekoton_abi::*; #[derive(UnpackAbi, KnownParamType, Debug, PartialEq)] struct VestingsComponents { #[abi(uint32, name = "remainingAmount")] ...
use std::str::FromStr; use std::collections::BTreeMap; use ton_abi::{ParamType, TokenValue}; use ton_abi::{Token, Uint}; use ton_block::{MsgAddress, MsgAddressInt}; use nekoton_abi::*; #[derive(UnpackAbi, KnownParamType, Debug, PartialEq)] struct VestingsComponents { #[abi(uint32, name = "remainingAmount")] ...
fn test() -> ParticipantInfo { let total = Token::new("total", TokenValue::Uint(Uint::new(100, 64))); let withdraw_value = Token::new("withdrawValue", TokenValue::Uint(Uint::new(30, 32))); let reinvest = Token::new("reinvest", TokenValue::Bool(true)); let reward = Token::new("reward", TokenValue::Uint...
i)? } _ => return Err(UnpackerError::InvalidAbi), }; map.insert(key, value); } Ok(map) } _ => Err(UnpackerError::InvalidAbi), } }
function_block-function_prefixed
[ { "content": "fn cache_expired(now: u32, phase: ConfigCachePhase) -> bool {\n\n match phase {\n\n ConfigCachePhase::WaitingKeyBlock => true,\n\n ConfigCachePhase::WaitingElectionsEnd { deadline }\n\n | ConfigCachePhase::WainingNextValidatorsSet { deadline } => now > deadline,\n\n }\n\...
Rust
src/main.rs
susytech/susy-rocksdb
2ca57972fb6661863c72c1bf8549d63122305be6
extern crate susy_rocksdb as rocksdb; use rocksdb::{DB, MergeOperands, Options, Writable}; #[cfg(not(feature = "valgrind"))] fn main() { let path = "/tmp/rust-rocksdb"; let db = DB::open_default(path).unwrap(); assert!(db.put(b"my key", b"my value").is_ok()); match db.get(b"my key") { Ok(Some...
extern crate susy_rocksdb as rocksdb; use rocksdb::{DB, MergeOperands, Options, Writable}; #[cfg(not(feature = "valgrind"))] fn main() { let path = "/tmp/rust-rocksdb"; let db = DB::open_default(path).unwrap(); assert!(db.put(b"my key", b"my value").is_ok()); match db.get(b"my key") { Ok(Some...
fn concat_merge(_: &[u8], existing_val: Option<&[u8]>, operands: &mut MergeOperands) -> Vec<u8> { let mut result: Vec<u8> = Vec::with_capacity(operands.size_hint().0); match existing_val { Some(v) => { for e in v { result.push...
Ok(None) => panic!("value not present!"), Err(e) => println!("error retrieving value: {}", e), } assert!(db.delete(b"my key").is_ok()); custom_merge(); }
function_block-function_prefix_line
[ { "content": " private native boolean useDirectReads(long handle);\n", "file_path": "susy-rocksdb-sys/rocksdb/java/src/main/java/org/rocksdb/DBOptions.java", "rank": 0, "score": 303348.26779534767 }, { "content": " private native void setUseDirectReads(long handle, boolean useDirectReads);...
Rust
third_party/rust_crates/vendor/backtrace/src/symbolize/mod.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use core::{fmt, str}; cfg_if::cfg_if! { if #[cfg(feature = "std")] { use std::path::Path; use std::prelude::v1::*; } } use crate::backtrace::Frame; use crate::types::BytesOrWideString; use core::ffi::c_void; use rustc_demangle::{try_demangle, Demangle}; #[cfg(feature = "std")] pub fn resolve<...
use core::{fmt, str}; cfg_if::cfg_if! { if #[cfg(feature = "std")] { use std::path::Path; use std::prelude::v1::*; } } use crate::backtrace::Frame; use crate::types::BytesOrWideString; use core::ffi::c_void; use rustc_demangle::{try_demangle, Demangle}; #[cfg(feature = "std")] pub fn resolve<...
pub fn as_str(&self) -> Option<&'a str> { self.demangled .as_ref() .map(|s| s.as_str()) .or_else(|| str::from_utf8(self.bytes).ok()) } pub fn as_bytes(&self) -> &'a [u8] { self.bytes } } fn format_symbol_name( fmt: fn(&str, ...
bytes = str::from_utf8(bytes).ok(); let demangled = str_bytes.and_then(|s| try_demangle(s).ok()); let cpp = if demangled.is_none() { OptionCppSymbol::parse(bytes) } else { OptionCppSymbol::none() }; SymbolName { bytes: bytes, dema...
function_block-function_prefixed
[]
Rust
src/assassin/quote.rs
dseevr/assassin
e0e1390316a5b7fd5b507a2cfaca263201aed68b
use std::rc::Rc; extern crate chrono; use self::chrono::prelude::*; extern crate greenback; use greenback::Greenback as Money; #[derive(Clone)] pub struct Quote { symbol: Rc<str>, expiration_date: DateTime<Utc>, ask: Money, bid: Money, last_price: Money, call: bool, strike_price: Money, ...
use std::rc::Rc; extern crate chrono; use self::chrono::prelude::*; extern crate greenback; use greenback::Greenback as Money; #[derive(Clone)] pub struct Quote { symbol: Rc<str>, expiration_date: DateTime<Utc>, ask: Money, bid: Money, last_price: Money, call: bool, strike_price: Money, ...
} } #[allow(dead_code)] pub fn extrinsic_value(&self) -> Money { self.midpoint_price() - self.intrinsic_value() } #[allow(dead_code)] pub fn value_ratio(&self) -> f32 { let extrinsic = self.extrinsic_value().raw_value() as f32; let intrinsic ...
if self.underlying_price < self.strike_price { self.strike_price - self.underlying_price } else { Money::zero() }
if_condition
[ { "content": "pub fn n_strikes_above(quotes: Vec<&Quote>, strikes: i32, price: Money) -> Option<&Quote> {\n\n if strikes < 1 {\n\n panic!(\"strikes must be > 0 (got: {})\", strikes);\n\n }\n\n\n\n let mut found = false;\n\n let mut count = 0;\n\n\n\n for q in &quotes {\n\n // if we ...
Rust
src/backend/blt.rs
fitzgibbon/cursive-anycolor
985f6c933fe4477e17c099d1ec8c44974fe92aae
extern crate bear_lib_terminal; use self::bear_lib_terminal::Color as BltColor; use self::bear_lib_terminal::geometry::Size; use self::bear_lib_terminal::terminal::{self, Event as BltEvent, KeyCode}; use backend; use event::{Event, Key}; use std::collections::BTreeMap; use theme::{BaseColor, Color, ColorStyle, Effect}...
extern crate bear_lib_terminal; use self::bear_lib_terminal::Color as BltColor; use self::bear_lib_terminal::geometry::Size; use self::bear_lib_terminal::terminal::{self, Event as BltEvent, KeyCode}; use backend; use event::{Event, Key}; use std::collections::BTreeMap; use theme::{BaseColor, Color, ColorStyle, Effect}...
fn blt_keycode_to_key(kc: KeyCode) -> Key { match kc { KeyCode::F1 => Key::F1, KeyCode::F2 => Key::F2, KeyCode::F3 => Key::F3, KeyCode::F4 => Key::F4, KeyCode::F5 => Key::F5, KeyCode::F6 => Key::F6, KeyCode::F7 => Key::F7, KeyCode::F8 => Key::F8, ...
KeyCode::Space => ' ', KeyCode::NumDivide => '/', KeyCode::NumMultiply => '*', KeyCode::NumMinus => '-', KeyCode::NumPlus => '+', KeyCode::NumPeriod => '.', KeyCode::Num1 => '1', KeyCode::Num2 => '2', KeyCode::Num3 => '3', KeyCode::Num4 => '4', ...
function_block-function_prefix_line
[ { "content": "/// Computes the length (number of bytes) and width of a suffix that fits in the given `width`.\n\n///\n\n/// Breaks between any two graphemes.\n\npub fn simple_suffix(text: &str, width: usize) -> Prefix {\n\n suffix(text.graphemes(true), width, \"\")\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n...
Rust
amethyst_renderer/src/pass/pbm/separate.rs
Rhuagh/amethyst
257e8e86c96db9425d040f0e35be14da2c90dec4
use std::mem; use amethyst_assets::AssetStorage; use amethyst_core::cgmath::{Matrix4, One, SquareMatrix}; use amethyst_core::transform::Transform; use gfx::pso::buffer::ElemStride; use specs::{Fetch, Join, ReadStorage}; use super::*; use cam::{ActiveCamera, Camera}; use error::Result; use light::{DirectionalLight, ...
use std::mem; use amethyst_assets::AssetStorage; use amethyst_core::cgmath::{Matrix4, One, SquareMatrix}; use amethyst_core::transform::Transform; use gfx::pso::buffer::ElemStride; use specs::{Fetch, Join, ReadStorage}; use super::*; use cam::{ActiveCamera, Camera}; use error::Result; use light::{DirectionalLight, ...
}
ReadStorage<'a, Transform>, ReadStorage<'a, Light>, ), ) { let camera: Option<(&Camera, &Transform)> = active .and_then(|a| { let cam = camera.get(a.entity); let transform = global.get(a.entity); cam.into_iter().zip(transform.in...
function_block-function_prefix_line
[ { "content": "fn run(&mut self, (mut lights, time, camera, mut transforms, mut state, mut ui_text, fps_counter): Self::SystemData){\n\n let light_angular_velocity = -1.0;\n\n let light_orbit_radius = 15.0;\n\n let light_z = 6.0;\n\n\n\n let camera_angular_velocity = 0.1;\n\n\n\n ...
Rust
engine/src/conversion/codegen_cpp/type_to_cpp.rs
johnperry-math/autocxx
1ebfe2073275cec9569b53026a4ba52da1905678
use crate::{ conversion::{apivec::ApiVec, AnalysisPhase, ConvertError}, types::QualifiedName, }; use indexmap::map::IndexMap as HashMap; use itertools::Itertools; use quote::ToTokens; use std::iter::once; use syn::{Token, Type}; pub(crate) type CppNameMap = HashMap<QualifiedName, String>; pub(crate) fn orig...
use crate::{ conversion::{apivec::ApiVec, AnalysisPhase, ConvertError}, types::QualifiedName, }; use indexmap::map::IndexMap as HashMap; use itertools::Itertools; use quote::ToTokens; use std::iter::once; use syn::{Token, Type}; pub(crate) type CppNameMap = HashMap<QualifiedName, String>; pub(crate) fn orig...
p) => Ok(format!( "{}{}*", get_mut_string(&typp.mutability), type_to_cpp(typp.elem.as_ref(), cpp_name_map)? )), Type::Array(_) | Type::BareFn(_) | Type::Group(_) | Type::ImplTrait(_) | Type::Infer(_) | Type::Macro(_) | T...
None => Ok(root), Some(suffix) => Ok(format!("{}<{}>", root, suffix)), } } Type::Reference(typr) => match &*typr.elem { Type::Path(typ) if typ.path.is_ident("str") => Ok("rust::Str".into()), _ => Ok(format!( "{}{}&", ...
function_block-random_span
[ { "content": "fn preprocess(args: &ArgMatches) -> Result<(), Error> {\n\n let (_, mut book) = CmdPreprocessor::parse_input(io::stdin())?;\n\n\n\n env_logger::builder().init();\n\n let mut test_cases = Vec::new();\n\n\n\n Book::for_each_mut(&mut book, |sec| {\n\n if let mdbook::BookItem::Chapt...
Rust
src/lab.rs
litchipi/Petridish
972288135673e8cf9771aadef93042e7b06ee921
use crate::algo::{Algo, AlgoConfiguration, AlgoID, AlgoResult}; use crate::cell::{random_genome, Cell, CellData, Genome}; use crate::dataset::DatasetHandler; use crate::errors::Errcode; use crate::genalgomethods::{GenalgoMethod, GenalgoMethodsAvailable}; use crate::utils::{JsonData, MeanCompute}; use serde::{Deseriali...
use crate::algo::{Algo, AlgoConfiguration, AlgoID, AlgoResult}; use crate::cell::{random_genome, Cell, CellData, Genome}; use crate::dataset::DatasetHandler; use crate::errors::Errcode; use crate::genalgomethods::{GenalgoMethod, GenalgoMethodsAvailable}; use crate::utils::{JsonData, MeanCompute}; use serde::{Deseriali...
, pop as u32, elite as u32, &mut genomes, )?; for gene in genomes.iter() { self.cells .get_mut(id) .unwrap() .push(self.algos.get(id).unwrap().create_cell_from_genome(gene...
datasets: &mut Vec<Box<dyn DatasetHandler>>, ) -> Result<CellData, Errcode> { for dataset in datasets.iter_mut() { self.__run_on_dataset(dataset)?; } let mut results: Vec<AlgoResult> = vec![]; for id in 0..self.algos.len() { results.push(AlgoResult::new( ...
random
[ { "content": "pub fn __genome_to_json(genome: Genome, key_list: &Vec<&str>) -> JsonData {\n\n assert_eq!(genome.len(), key_list.len());\n\n let mut result: HashMap<&str, f64> = HashMap::new();\n\n for (nb, key) in key_list.into_iter().enumerate() {\n\n result.insert(key, genome[nb]);\n\n }\n\...
Rust
packages/std/src/encoding.rs
puneet2019/cosmwasm
8cf9c302e408ce175852ad6a2ab153d426b43bdd
use std::fmt; use schemars::JsonSchema; use serde::{de, ser, Deserialize, Deserializer, Serialize}; use crate::errors::{invalid_base64, StdResult}; #[derive(Clone, Default, Debug, PartialEq, JsonSchema)] pub struct Binary(#[schemars(with = "String")] pub Vec<u8>); impl Binary { pub fn from_base64(enco...
use std::fmt; use schemars::JsonSchema; use serde::{de, ser, Deserialize, Deserializer, Serialize}; use crate::errors::{invalid_base64, StdResult}; #[derive(Clone, Default, Debug, PartialEq, JsonSchema)] pub struct Binary(#[schemars(with = "String")] pub Vec<u8>); impl Binary { pub fn from_base64(enco...
} #[cfg(test)] mod test { use super::*; use crate::errors::StdError; use crate::serde::{from_slice, to_vec}; #[test] fn encode_decode() { let binary: &[u8] = b"hello"; let encoded = Binary::from(binary).to_base64(); assert_eq!(8, encoded.len()); let decoded = Binar...
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: de::Error, { match Binary::from_base64(v) { Ok(binary) => Ok(binary), Err(_) => Err(E::custom(format!("invalid base64: {}", v))), } }
function_block-full_function
[ { "content": "pub fn from_slice<T: DeserializeOwned>(value: &[u8]) -> StdResult<T> {\n\n serde_json_wasm::from_slice(value).map_err(|e| parse_err(type_name::<T>(), e))\n\n}\n\n\n", "file_path": "packages/std/src/serde.rs", "rank": 0, "score": 349689.87454241194 }, { "content": "pub fn fro...
Rust
clap_generate/src/generators/shells/powershell.rs
AimainaHito/clap
06b9b32d664802a7c0493c59e66d53f67cb54181
use std::io::Write; use crate::Generator; use crate::INTERNAL_ERROR_MSG; use clap::*; pub struct PowerShell; impl Generator for PowerShell { fn file_name(name: &str) -> String { format!("_{}.ps1", name) } fn generate(app: &App, buf: &mut dyn Write) { let bin_name = app.get_bin_name().un...
use std::io::Write; use crate::Generator; use crate::INTERNAL_ERROR_MSG; use clap::*; pub struct PowerShell; impl Generator for PowerShell { fn file_name(name: &str) -> String { format!("_{}.ps1", name) } fn generate(app: &App, buf: &mut dyn Write) { let bin_name = app.get_bin_name().un...
let tooltip = get_tooltip(flag.help, data); completions.push_str(&preamble); completions.push_str( format!( "'--{}', '{}', {}, '{}')", data, data, "[CompletionResultType]::ParameterName", tooltip ) .as_str()...
function_block-function_prefixed
[ { "content": "/// Generate a completions file for a specified shell at runtime.\n\n///\n\n/// Until `cargo install` can install extra files like a completion script, this may be\n\n/// used e.g. in a command that outputs the contents of the completion script, to be\n\n/// redirected into a file by the user.\n\n...
Rust
src/vendor/mdbook/src/parse/summary.rs
ryoon/rustc-1.19.0
4ca47e69f710b93580101782576ebad2bef64749
use std::path::PathBuf; use std::fs::File; use std::io::{Read, Result, Error, ErrorKind}; use book::bookitem::{BookItem, Chapter}; pub fn construct_bookitems(path: &PathBuf) -> Result<Vec<BookItem>> { debug!("[fn]: construct_bookitems"); let mut summary = String::new(); try!(try!(File::open(path)).read_to_...
use std::path::PathBuf; use std::fs::File; use std::io::{Read, Result, Error, ErrorKind}; use book::bookitem::{BookItem, Chapter}; pub fn construct_bookitems(path: &PathBuf) -> Result<Vec<BookItem>> { debug!("[fn]: construct_bookitems"); let mut summary = String::new(); try!(try!(File::open(path)).read_to_...
elements can only exist before any chapter and there can be \ no chapters after suffix elements.")) }, BookItem::Affix(_) if section[0] > 0 => { section[0] = -1; ...
mut section: Vec<i32>) -> Result<Vec<BookItem>> { debug!("[fn]: parse_level"); let mut items: Vec<BookItem> = vec![]; while !summary.is_empty() { let item: BookItem; let level = try!(level(summary[0], 4)); if level < current_level { brea...
random
[]
Rust
orma/src/db_anti_corruption/connection.rs
kiuma/rust-orma
982685c48d8075ef031d12757f78107e96d3587e
use super::{DbError, Row, SimpleQueryMessage, Statement, ToSql, ToStatement}; use tokio_postgres::Client; pub struct Connection { client: Client, transaction_n: u32, } impl From<Client> for Connection { fn from(client: Client) -> Self { Self { client, transaction_n: 0, ...
use super::{DbError, Row, SimpleQueryMessage, Statement, ToSql, ToStatement}; use tokio_postgres::Client; pub struct Connection { client: Client, transaction_n: u32, } impl From<Client> for Connection { fn from(client: Client) -> Self { Self { client, transaction_n: 0, ...
pub async fn query<T>( &self, statement: &T, params: &[&(dyn ToSql + Sync)], ) -> Result<Vec<Row>, DbError> where T: ?Sized + ToStatement, { let statement = &statement.__convert().into_statement(self).await?; self....
pub async fn simple_query(&self, query: &str) -> Result<Vec<SimpleQueryMessage>, DbError> { self.client .simple_query(query) .await .map(|rows| rows.into_iter().map(SimpleQueryMessage::from).collect()) .map_err(DbError::from) }
function_block-full_function
[ { "content": "/// Helper function to create the a SQL ORDER BY statement.\n\n///\n\n/// *order_by* clauses are joined by \", \" and *alias* is prepended with \".\"\n\n/// to each *order_by* element.\n\npub fn make_sort_statement(order_by: &[&str], alias: Option<&str>) -> String {\n\n match alias {\n\n ...
Rust
mythril/src/acpi/mod.rs
barkera/mythril
b7b45fe08a05c5b66317bbf13fdd4fcf10c428d2
#![deny(missing_docs)] use crate::error::{Error, Result}; use byteorder::{ByteOrder, NativeEndian}; use core::convert::TryFrom; use num_enum::TryFromPrimitive; use raw_cpuid::CpuId; pub mod hpet; pub mod madt; pub mod rsdp; pub mod rsdt; mod offsets { use core::ops::Range; pub const GAS_ADDRESS_SPACE: us...
#![deny(missing_docs)] use crate::error::{Error, Result}; use byteorder::{ByteOrder, NativeEndian}; use core::convert::TryFrom; use num_enum::TryFromPrimitive; use raw_cpuid::CpuId; pub mod hpet; pub mod madt; pub mod rsdp; pub mod rsdt; mod offsets { use core::ops::Range; pub const GAS_ADDRESS_SPACE: us...
}
return Err(Error::InvalidValue(format!( "Invalid number of bytes for GAS: {} != {}", bytes.len(), GAS_SIZE ))); } let address_space = AddressSpaceID::try_from(bytes[offsets::GAS_ADDRESS_SPACE])?; let bit_width = bytes[offs...
function_block-function_prefix_line
[ { "content": "pub fn check_vm_insruction(rflags: u64, error: String) -> Result<()> {\n\n let rflags = rflags::RFlags::from_bits_truncate(rflags);\n\n\n\n if rflags.contains(RFlags::FLAGS_CF) {\n\n Err(Error::VmFailInvalid(error))\n\n } else if rflags.contains(RFlags::FLAGS_ZF) {\n\n let e...
Rust
puddle-pi/src/devices/hv507.rs
thequicksort/puddle
9dbed5e5aec5df98275298e31778e0a1c3876bcc
use std::time::{Duration, Instant}; use log::*; use serde::Deserialize; use rppal::gpio::{Gpio, Level, OutputPin, Pin}; use rppal::pwm::{self, Pwm}; use crate::{Error, Result}; const N_PINS: usize = 128; #[derive(Debug, Deserialize)] pub struct Settings { pub frequency: f64, pub duty_cycle: f64, pub pi...
use std::time::{Duration, Instant}; use log::*; use serde::Deserialize; use rppal::gpio::{Gpio, Level, OutputPin, Pin}; use rppal::pwm::{self, Pwm}; use crate::{Error, Result}; const N_PINS: usize = 128; #[derive(Debug, Deserialize)] pub struct Settings { pub frequency: f64, pub duty_cycle: f64, pub pi...
Pwm1, n => return Err(Error::InvalidPwmChannel(n)), }; let enabled = true; let pol = match self.default_polarity { DefaultLevel::Low => pwm::Polarity::Normal, DefaultLevel::High => pwm::Polarity::Inverse, }; let pwm = Pwm::with_frequency(chan,...
"initializing pin {}...", pin); gpio.get(pin).map(Pin::into_output) }; let chan = match self.pins.polarity_pwm_channel { 0 => pwm::Channel::Pwm0, 1 => pwm::Channel::
random
[ { "content": "pub fn mk_rng() -> impl Rng {\n\n Pcg32::seed_from_u64(\n\n env::var(\"PUDDLE_SEED\")\n\n .map(|seed| {\n\n seed.parse()\n\n .expect(\"Couldn't parse the seed into a number!\")\n\n })\n\n .unwrap_or(0),\n\n )\n\n}\n\n\...
Rust
libs/frontend/src/source.rs
Ralakus/mod-language
1e10f949129cf9c3e460a53831541c8a88d0b14b
use std::{ io::{ Error as IOError, Result as IOResult, }, fmt::{ Display, Debug, Formatter, Result as FMTResult, }, fs::read_to_string, cell::{ UnsafeCell, }, path::{ Path, PathBuf, }, }; use mod_ansi as ansi; use mod_utils::{ make_key_type, Either, Unref, collections::{ SlotMap, BiMap, }, }; ...
use std::{ io::{ Error as IOError, Result as IOResult, }, fmt::{ Display, Debug, Formatter, Result as FMTResult, }, fs::read_to_string, cell::{ UnsafeCell, }, path::{ Path, PathBuf, }, }; use mod_ansi as ansi; use mod_utils::{ make_key_type, Either, Unref, collections::{ SlotMap, BiMap, }, }; ...
terior> { &mut *self.0.get() } #[allow(clippy::mut_from_ref)] fn source_map (&self) -> &mut SlotMap<SourceKey, Source> { let inner = unsafe { self.inner() }; &mut inner.as_mut().expect("Internal error: SourceManager not initialized").source_map } #[allow(clippy::mut_from_ref)] fn as...
impl Debug for SourceRegion { fn fmt (&self, f: &mut Formatter) -> FMTResult { if let Some(source) = SOURCE_MANAGER.get_source(self.source) { write!(f, "{}:{}", source.path.display(), self.start)?; if self.end != self.start && !(self.end.line == self.start.line && self.end.column == sel...
random
[ { "content": "/// Parse either a single Path or Identifier\n\npub fn path (parser: &mut Parser) -> Option<Either<Path, (Identifier, SourceRegion)>> {\n\n if let Some(token) = parser.curr_tok() {\n\n let start_region = token.origin;\n\n\n\n let absolute = if let TokenData::Operator(DoubleColon) = token.da...
Rust
crates/core/src/source.rs
nott/cobalt.rs
250c792842805dc3531feeac9345aca0c655283d
use crate::Result; use crate::Status; #[derive(Debug, Clone)] pub struct Source { root: std::path::PathBuf, ignore: ignore::gitignore::Gitignore, } impl Source { pub fn new<'i>( root: &std::path::Path, ignores: impl IntoIterator<Item = &'i str>, ) -> Result<Self> { let mut igno...
use crate::Result; use crate::Status; #[derive(Debug, Clone)] pub struct Source { root: std::path::PathBuf, ignore: ignore::gitignore::Gitignore, } impl Source { pub fn new<'i>( root: &std::path::Path, ignores: impl IntoIterator<Item = &'i str>, ) -> Result<Self> { let mut igno...
pub fn root(&self) -> &std::path::Path { &self.root } pub fn includes_file(&self, file: &std::path::Path) -> bool { let is_dir = false; self.includes_path(file, is_dir) } pub fn includes_dir(&self, dir: &std::path::Path) -> bool { let is_dir = true; self.i...
let ignore = ignore .build() .map_err(|e| Status::new("Invalid ignore entry").with_source(e))?; let source = Self { root: root.to_owned(), ignore, }; Ok(source) }
function_block-function_prefix_line
[ { "content": "pub fn split_ext(name: &str) -> (&str, Option<&str>) {\n\n name.rsplit_once('.')\n\n .map(|(n, e)| (n, Some(e)))\n\n .unwrap_or_else(|| (name, None))\n\n}\n\n\n\nstatic DATE_PREFIX_REF: once_cell::sync::Lazy<regex::Regex> = once_cell::sync::Lazy::new(|| {\n\n regex::Regex::new(...
Rust
rita_common/src/simulated_txfee_manager/mod.rs
althea-net/althea_rs
49e8e4886a9f40bda8b45afe88cd3862c2fc5c82
use crate::payment_controller::TRANSACTION_SUBMISSION_TIMEOUT; use crate::rita_loop::get_web3_server; use crate::usage_tracker::update_payments; use althea_types::Identity; use althea_types::PaymentTx; use async_web30::client::Web3; use clarity::Transaction; use num256::Uint256; use num_traits::{Signed, Zero}; use s...
use crate::payment_controller::TRANSACTION_SUBMISSION_TIMEOUT; use crate::rita_loop::get_web3_server; use crate::usage_tracker::update_payments; use althea_types::Identity; use althea_types::PaymentTx; use async_web30::client::Web3; use clarity::Transaction; use num256::Uint256; use num_traits::{Signed, Zero}; use s...
let tx = Transaction { nonce, gas_price, gas_limit: "21000".parse().unwrap(), to: simulated_transaction_fee_address, value: amount_to_pay.clone(), data: Vec::new(), signature: None, }; let transaction_signed = tx.sign( &eth_private_key.expect("No p...
function_block-function_prefix_line
[ { "content": "pub fn payment_succeeded(to: Identity, amount: Uint256) -> Result<(), Error> {\n\n let mut dk = DEBT_DATA.write().unwrap();\n\n add_tx_to_total(amount.clone());\n\n dk.payment_succeeded(&to, amount)\n\n}\n\n\n\npub struct Traffic {\n\n pub from: Identity,\n\n pub amount: Int256,\n\n...
Rust
src/camera/arc_ball.rs
gijs-s/kiss3d
7d3d2e106b43264e7058495bdcea5c7ff2bb48ed
use crate::camera::Camera; use crate::event::{Action, Key, Modifiers, MouseButton, WindowEvent}; use crate::resource::ShaderUniform; use crate::window::Canvas; use na::{self, Isometry3, Matrix4, Perspective3, Point3, Unit, UnitQuaternion, Vector2, Vector3}; use std::f32; #[derive(Clone, Debug)] pub struct ArcBall { ...
use crate::camera::Camera; use crate::event::{Action, Key, Modifiers, MouseButton, WindowEvent}; use crate::resource::ShaderUniform; use crate::window::Canvas; use na::{self, Isometry3, Matrix4, Perspective3, Point3, Unit, UnitQuaternion, Vector2, Vector3}; use std::f32; #[derive(Clone, Debug)] pub struct ArcBall { ...
canvas: &Canvas, event: &WindowEvent) { match *event { WindowEvent::CursorPos(x, y, modifiers) => { let curr_pos = Vector2::new(x as f32, y as f32); if let Some(rotate_button) = self.rotate_button { if canvas.get_mouse_button(rotate_button) == Ac...
pub fn look_at(&mut self, eye: Point3<f32>, at: Point3<f32>) { let dist = (eye - at).norm(); let view_eye = self.coord_system.rotation_to_y_up * eye; let view_at = self.coord_system.rotation_to_y_up * at; let pitch = ((view_eye.y - view_at.y) / dist).acos(); let yaw = (vi...
random
[ { "content": "fn parse_v_or_vn(l: usize, mut ws: Words) -> Vector3<f32> {\n\n let sx = ws\n\n .next()\n\n .unwrap_or_else(|| error(l, \"3 components were expected, found 0.\"));\n\n let sy = ws\n\n .next()\n\n .unwrap_or_else(|| error(l, \"3 components were expected, found 1.\"...
Rust
jetsocat/tests/socks5-to-jmux.rs
Devolutions/devolutions-jet
35756e332ebd34606367e1e8cd332c3537df0899
use anyhow::Context as _; use futures_util::FutureExt; use proptest::prelude::*; use test_utils::{ find_unused_ports, read_assert_payload, small_payload, transport_kind, write_payload, Payload, TransportKind, }; use tokio::io::{AsyncReadExt, AsyncWriteExt}; const NB_TARGETS: usize = 3; #[derive(Debug)] struct C...
use anyhow::Context as _; use futures_util::FutureExt; use proptest::prelude::*; use test_utils::{ find_unused_ports, read_assert_payload, small_payload, transport_kind, write_payload, Payload, TransportKind, }; use tokio::io::{AsyncReadExt, AsyncWriteExt}; const NB_TARGETS: usize = 3; #[derive(Debug)] struct C...
; let filtering_rule = FilteringRule::host("127.0.0.1").or(FilteringRule::host_and_port("rust-lang.org", 80)); let cfg = jetsocat::JmuxProxyCfg { pipe_mode, proxy_cfg: None, listener_modes: Vec::new(), pipe_timeout: None, watch_process: None, jmux_cfg: Jmux...
match kind { TransportKind::Tcp => PipeMode::TcpListen { bind_addr: format!("127.0.0.1:{}", port), }, TransportKind::Ws => PipeMode::WebSocketListen { bind_addr: format!("127.0.0.1:{}", port), }, }
if_condition
[ { "content": "fn write_addr(addr: &DestAddr, mut addr_buf: &mut [u8]) -> io::Result<usize> {\n\n let initial_len = addr_buf.len();\n\n\n\n match addr {\n\n DestAddr::Ip(SocketAddr::V4(addr)) => {\n\n addr_buf.write_all(&[1])?;\n\n addr_buf.write_all(&u32::from(*addr.ip()).to_b...
Rust
src/backend/curses/n.rs
T045T/Cursive
5094f49219e6efedc2b26874dd76be9f5044e4c1
extern crate ncurses; use self::ncurses::mmask_t; use self::super::{find_closest, split_i32}; use backend; use event::{Event, Key, MouseButton, MouseEvent}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::io::{stdout, Write}; use theme::{Color, ColorPair, Effect}; use utf8; use vec::Vec2; pub ...
extern crate ncurses; use self::ncurses::mmask_t; use self::super::{find_closest, split_i32}; use backend; use event::{Event, Key, MouseButton, MouseEvent}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::io::{stdout, Write}; use theme::{Color, ColorPair, Effect}; use utf8; use vec::Vec2; pub ...
fn get_or_create(&self, pair: ColorPair) -> i16 { let mut pairs = self.pairs.borrow_mut(); if pairs.contains_key(&pair) { pairs[&pair] } else { self.insert_color(&mut *pairs, pair) } } fn set_colors(&self, pair: ColorPair...
e { let target = n - 1; pairs.retain(|_, &mut v| v != target); target }; pairs.insert(pair, target); ncurses::init_pair( target, find_closest(&pair.front), find_closest(&pair.back), ); ...
function_block-function_prefixed
[ { "content": "fn fill_key_codes<F>(target: &mut HashMap<i32, Event>, f: F)\n\nwhere\n\n F: Fn(i32) -> Option<String>,\n\n{\n\n let key_names = hashmap!{\n\n \"DC\" => Key::Del,\n\n \"DN\" => Key::Down,\n\n \"END\" => Key::End,\n\n \"HOM\" => Key::Home,\n\n \"IC\" => Key:...
Rust
tests/tcp/binary.rs
NicolasLagaillardie/mpst_rust_github
48acf2bb054ff48bc05942d04aa60805bf7acacc
use mpstthree::binary::close::close_tcp; use mpstthree::binary::fork::fork_tcp; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthree::transport::tcp::recv::recv_tcp; use mpstthree::transport::tcp::send::send_tcp; use mpstthree::{choose_tcp, offer_tcp}; use std::error...
use mpstthree::binary::close::close_tcp; use mpstthree::binary::fork::fork_tcp; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthree::transport::tcp::recv::recv_tcp; use mpstthree::transport::tcp::send::send_tcp; use mpstthree::{choose_tcp, offer_tcp}; use std::error...
} }, } } Err(_) => { stream.shutdown(Shutdown::Both).unwrap_or(()); panic!("An error occurred during read") } } {} Ok(()) } fn tcp_server(listener: TcpListener) -> Result<(), Box<dyn Error>> { 'outer: for stream in l...
let mut index = 0; while match stream.read(&mut data) { Ok(0) => { stream.shutdown(Shutdown::Both).unwrap_or(()); panic!("Buffer size: 0") } Ok(size) => { match stream.write(&data[0..size]) { Ok(0) => { s...
random
[ { "content": "fn tcp_client_aux(mut sessions: Vec<RecursB>, stream: TcpStream) -> Result<(), Box<dyn Error>> {\n\n for i in 0..SIZE {\n\n let mut temp = Vec::new();\n\n\n\n for s in sessions {\n\n let copy_stream = stream.try_clone()?;\n\n let elt = binary_b_to_a(choose_tc...
Rust
druid/examples/flex.rs
Dmitry-Borodin/druid
69f8f05492262ee088d1495f7d0cc370c33f69a8
use druid::widget::prelude::*; use druid::widget::{ Button, Checkbox, CrossAxisAlignment, Flex, Label, MainAxisAlignment, ProgressBar, RadioGroup, SizedBox, Slider, Stepper, Switch, TextBox, WidgetExt, }; use druid::{ AppLauncher, Color, Data, Lens, LensExt, LocalizedString, PlatformError, WidgetId, Windo...
use druid::widget::prelude::*; use druid::widget::{ Button, Checkbox, CrossAxisAlignment, Flex, Label, MainAxisAlignment, ProgressBar, RadioGroup, SizedBox, Slider, Stepper, Switch, TextBox, WidgetExt, }; use druid::{ AppLauncher, Color, Data, Lens, LensExt, LocalizedString, PlatformError, WidgetId, Windo...
} fn layout( &mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, data: &AppState, env: &Env, ) -> Size { self.inner.layout(ctx, bc, data, env) } fn paint(&mut self, ctx: &mut PaintCtx, data: &AppState, env: &Env) { self.inner.paint(ctx, dat...
if !old_data.params.same(&data.params) { self.rebuild_inner(data); ctx.children_changed(); } else { self.inner.update(ctx, old_data, data, env); }
if_condition
[ { "content": "fn op_button_label(op: char, label: String) -> impl Widget<CalcState> {\n\n let painter = Painter::new(|ctx, _, env| {\n\n let bounds = ctx.size().to_rect();\n\n\n\n ctx.fill(bounds, &env.get(theme::PRIMARY_DARK));\n\n\n\n if ctx.is_hot() {\n\n ctx.stroke(bounds....
Rust
storage-proofs/post/src/rational/circuit.rs
hooops/filecoin
8f455e24babcab0eb67fa660dc2fdccb97a8536d
use std::marker::PhantomData; use bellperson::gadgets::num; use bellperson::{Circuit, ConstraintSystem, SynthesisError}; use paired::bls12_381::{Bls12, Fr}; use storage_proofs_core::{ compound_proof::CircuitComponent, error::Result, gadgets::constraint, gadgets::por::PoRCircuit, gadgets::variables...
use std::marker::PhantomData; use bellperson::gadgets::num; use bellperson::{Circuit, ConstraintSystem, SynthesisError}; use paired::bls12_381::{Bls12, Fr}; use storage_proofs_core::{ compound_proof::CircuitComponent, error::Result, gadgets::constraint, gadgets::por::PoRCircuit, gadgets::variables...
}
s_count, sector_size, &sectors, &seed, &faults).unwrap(); let comm_r_lasts_raw = vec![tree1.root(), tree2.root()]; let comm_r_lasts: Vec<_> = challenges .iter() .map(|c| comm_r_lasts_raw[u64::from(c.sector) as usize]) .collect(); let comm_cs: Vec<<Tree::Hashe...
function_block-function_prefixed
[ { "content": "fn seal_lifecycle<Tree: 'static + MerkleTreeTrait>(sector_size: u64) -> Result<()> {\n\n let rng = &mut XorShiftRng::from_seed(TEST_SEED);\n\n let prover_fr: DefaultTreeDomain = Fr::random(rng).into();\n\n let mut prover_id = [0u8; 32];\n\n prover_id.copy_from_slice(AsRef::<[u8]>::as_r...
Rust
lumen_runtime/src/otp/erlang/is_record_2/test.rs
bitwalker/lumen
7d286b93d1a839aa7de5fed7020bafc1bc39f300
use proptest::prop_assert_eq; use proptest::strategy::{Just, Strategy}; use proptest::test_runner::{Config, TestRunner}; use crate::otp::erlang::is_record_2::native; use crate::scheduler::with_process_arc; use crate::test::strategy; #[test] fn without_tuple_returns_false() { run!( |arc_process| { ...
use proptest::prop_assert_eq; use proptest::strategy::{Just, Strategy}; use proptest::test_runner::{Config, TestRunner}; use crate::otp::erlang::is_record_2::native; use crate::scheduler::with_process_arc; use crate::test::strategy; #[test] fn without_tuple_returns_false() { run!( |arc_process| { ...
fn with_non_empty_tuple_with_atom_with_record_tag_returns_ok() { run!( |arc_process| { ( Just(arc_process.clone()), strategy::term::atom(), proptest::collection::vec( strategy::term(arc_process.clone()), stra...
function_block-full_function
[ { "content": "#[test]\n\nfn with_tuple_without_atom_errors_badarg() {\n\n run!(\n\n |arc_process| {\n\n (\n\n strategy::term::tuple(arc_process.clone()),\n\n strategy::term::is_not_atom(arc_process.clone()),\n\n strategy::term::is_integer(arc_pro...
Rust
jlrs/tests/kw_func.rs
gobuki/jlrs
1867022ec178df83f9a29cc5c25b705e649599dc
use jlrs::prelude::*; use jlrs::util::JULIA; #[test] fn call_no_kw() { JULIA.with(|j| { let mut jlrs = j.borrow_mut(); jlrs.frame(2, |global, frame| { let a_value = Value::new(frame, 1isize)?; let func = Module::main(global) .submodule("JlrsTests")? ...
use jlrs::prelude::*; use jlrs::util::JULIA; #[test] fn call_no_kw() { JULIA.with(|j| { let mut jlrs = j.borrow_mut(); jlrs.frame(2, |global, frame| { let a_value = Value::new(frame, 1isize)?; let func = Module::main(global) .submodule("JlrsTests")? ...
#[test] fn call_with_kw_and_3_vararg() { JULIA.with(|j| { let mut jlrs = j.borrow_mut(); jlrs.frame(7, |global, frame| { let a_value = Value::new(frame, 1isize)?; let b_value = Value::new(frame, 10isize)?; let c_value = Value::new(frame, 5isize)?; l...
e| { let a_value = Value::new(frame, 1isize)?; let b_value = Value::new(frame, 10isize)?; let c_value = Value::new(frame, 5isize)?; let func = Module::main(global) .submodule("JlrsTests")? .function("funcwithkw")?; let kw = nam...
function_block-function_prefixed
[]
Rust
relay-server/src/middlewares.rs
armenzg/relay
ead06529004ea80e7feae49d70b99edab02d968b
#![allow(deprecated)] use std::borrow::Cow; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use std::time::Instant; use actix_web::error::Error; use actix_web::middleware::{Finished, Middleware, Response, Started}; use actix_web::{http::header, Body, HttpMessage, HttpRequest, HttpResponse}; use failure::Fail; us...
#![allow(deprecated)] use std::borrow::Cow; use std::cell::RefCell; use std::sync::{Arc, Mutex}; use std::time::Instant; use actix_web::error::Error; use actix_web::middleware::{Finished, Middleware, Response, Started}; use actix_web::{http::header, Body, HttpMessage, HttpRequest, HttpResponse}; use failure::Fail; us...
} else { Ok(Response::Done(resp)) } } } pub struct ReadRequestMiddleware; impl<S> Middleware<S> for ReadRequestMiddleware { fn response(&self, req: &HttpRequest<S>, resp: HttpResponse) -> Result<Response, Error> { let future = SharedPayload::get(req) .for_each(...
Ok(Response::Done( resp.into_builder() .json(ApiErrorResponse::with_detail(reason)), ))
call_expression
[ { "content": "pub fn normalize_request(request: &mut Request) -> ProcessingResult {\n\n request.method.apply(normalize_method)?;\n\n normalize_url(request);\n\n normalize_data(request);\n\n normalize_cookies(request);\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nuse crate::protocol::PairList;\n\n\n\n#[...
Rust
service/contentful/src/query_builder.rs
DanielWilliamClarke/cujo
9ee7410790d5241a7758bfd7043acdb3f32dfc63
use std::collections::HashMap; pub struct QueryBuilder { query_string_values: HashMap<String, String>, } impl QueryBuilder { pub fn new() -> QueryBuilder { QueryBuilder { query_string_values: HashMap::new(), } } pub fn content_type_is(mut self, content_type_id: &str) -> ...
use std::collections::HashMap; pub struct QueryBuilder { query_string_values: HashMap<String, String>, } impl QueryBuilder { pub fn new() -> QueryBuilder { QueryBuilder { query_string_values: HashMap::new(), } } pub fn content_type_is(mut self, content_type_id: &str) -> ...
self } }
(), id.into(), ""); self } pub fn links_to_asset(mut self, id: &str) -> QueryBuilder { self = self.add_field_restriction("links_to_asset".into(), id.into(), ""); self } pub fn build(&self) -> String { let mut query_string = String::new(); let mut has_query = fal...
random
[ { "content": "pub fn merge(v: &Value, fields: &HashMap<String, Value>) -> Value {\n\n match v {\n\n Value::Object(m) => {\n\n let mut m = m.clone();\n\n for (k, v) in fields {\n\n m.insert(k.clone(), v.clone());\n\n }\n\n Value::Object(m)\n\n ...
Rust
src/packages/alpine.rs
sbchaos/cake
ee91fbda401cb4004da754e1c462675f368e9745
use crate::ofs::ofs::OverlayFs; use crate::packages::deps::{Cache, Package, PackageManager}; use crate::packages::util::{get_file_from_image, get_single_version_in_dir}; use log::trace; use std::cmp::Ordering; use std::option::Option::Some; const CACHE_DIR: &str = "/var/cache/apk/"; const INSTALLED_FILE: &str = "/lib/...
use crate::ofs::ofs::OverlayFs; use crate::packages::deps::{Cache, Package, PackageManager}; use crate::packages::util::{get_file_from_image, get_single_version_in_dir}; use log::trace; use std::cmp::Ordering; use std::option::Option::Some; const CACHE_DIR: &str = "/var/cache/apk/"; const INSTALLED_FILE: &str = "/lib/...
} } } let package = Package { name: name.to_string(), version: version.to_string(), optional: false, size, }; packages.push(package) } packages } impl<'a> PackageManager for AlpinePackageManager<'a> { ...
if p.starts_with("P:") { name = p.strip_prefix("P:").unwrap(); } else if p.starts_with("V:") { version = p.strip_prefix("V:").unwrap(); } else if p.starts_with("I:") { size = p.strip_prefix("I:").unwrap().par...
if_condition
[ { "content": "pub fn get_single_version_in_dir(ofs: &OverlayFs, path: &str) -> u64 {\n\n let mut wasted: u64 = 0;\n\n if let Some(dir) = ofs.get_dir(path) {\n\n for e in dir.get_entries() {\n\n if e.versions.is_empty() {\n\n wasted += e.size;\n\n }\n\n }\...
Rust
language/move-compiler/src/compiled_unit.rs
rahxephon89/move
98ed299a7e3a9223019c9bdf4dd92fea9faef860
use crate::{ diag, diagnostics::Diagnostics, expansion::ast::{ModuleIdent, ModuleIdent_, SpecId}, hlir::ast as H, parser::ast::{FunctionName, ModuleName, Var}, shared::{unique_map::UniqueMap, Name, NumericalAddress}, }; use move_binary_format::file_format as F; use move_bytecode_source_map::so...
use crate::{ diag, diagnostics::Diagnostics, expansion::ast::{ModuleIdent, ModuleIdent_, SpecId}, hlir::ast as H, parser::ast::{FunctionName, ModuleName, Var}, shared::{unique_map::UniqueMap, Name, NumericalAddress}, }; use move_binary_format::file_format as F; use move_bytecode_source_map::so...
} pub fn loc(&self) -> &Loc { match self { Self::Module(AnnotatedCompiledModule { loc, .. }) | Self::Script(AnnotatedCompiledScript { loc, .. }) => loc, } } } impl CompiledUnit { pub fn name(&self) -> Symbol { match self { Self::Module(Named...
match self { Self::Module(AnnotatedCompiledModule { named_module: module, .. }) => CompiledUnitEnum::Module(module), Self::Script(AnnotatedCompiledScript { named_script: script, .. }) => CompiledUnitEnum::Scr...
if_condition
[]
Rust
clippy_lints/src/match_str_case_mismatch.rs
tamaroning/rust-clippy
39231b4b503955626c1ccf965b8328ac67c523bb
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::ty::is_type_diagnostic_item; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::intravisit::{walk_expr, Visitor}; use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind}; use rustc_lint::{LateContext, LateLintPass}; use ru...
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::ty::is_type_diagnostic_item; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::intravisit::{walk_expr, Visitor}; use rustc_hir::{Arm, Expr, ExprKind, MatchSource, PatKind}; use rustc_lint::{LateContext, LateLintPass}; use ru...
span_lint_and_sugg( cx, MATCH_STR_CASE_MISMATCH, bad_case_span, "this `match` arm has a differing case than its expression", &*format!("consider changing the case of this arm to respect `{}`", method_str), format!("\"{}\"", suggestion), Applicability::Machin...
let (method_str, suggestion) = match case_method { CaseMethod::LowerCase => ("to_lowercase", bad_case_str.to_lowercase()), CaseMethod::AsciiLowerCase => ("to_ascii_lowercase", bad_case_str.to_ascii_lowercase()), CaseMethod::UpperCase => ("to_uppercase", bad_case_str.to_uppercase()), Case...
assignment_statement
[ { "content": "#[must_use]\n\npub fn expr_visitor<'tcx>(cx: &LateContext<'tcx>, f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {\n\n struct V<'tcx, F> {\n\n hir: Map<'tcx>,\n\n f: F,\n\n }\n\n impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<'tcx, F> {\n\n...
Rust
src/sinks/kafka.rs
shanlashari/vector
d7f736cf0745e5c6d1f791c001d2ff8e3c9b4c65
use crate::{ buffers::Acker, event::{self, Event}, sinks::util::tls::TlsOptions, sinks::util::MetadataFuture, topology::config::{DataType, SinkConfig, SinkContext, SinkDescription}, }; use futures::{ future::{self, poll_fn, IntoFuture}, stream::FuturesUnordered, Async, AsyncSink, Future,...
use crate::{ buffers::Acker, event::{self, Event}, sinks::util::tls::TlsOptions, sinks::util::MetadataFuture, topology::config::{DataType, SinkConfig, SinkContext, SinkDescription}, }; use futures::{ future::{self, poll_fn, IntoFuture}, stream::FuturesUnordered, Async, AsyncSink, Future,...
fn kafka_happy_path(server: &str, tls: Option<KafkaSinkTlsConfig>) { let topic = format!("test-{}", random_string(10)); let tls_enabled = tls .as_ref() .map(|tls| tls.enabled.unwrap_or(false)) .unwrap_or(false); let config = KafkaSinkConfig { ...
Some(KafkaSinkTlsConfig { enabled: Some(true), options: TlsOptions { ca_path: Some(TEST_CA.into()), ..Default::default() }, }), ); }
function_block-function_prefix_line
[ { "content": "fn maybe_set_id(key: Option<impl AsRef<str>>, doc: &mut serde_json::Value, event: &Event) {\n\n if let Some(val) = key.and_then(|k| event.as_log().get(&k.as_ref().into())) {\n\n let val = val.to_string_lossy();\n\n\n\n doc.as_object_mut()\n\n .unwrap()\n\n .i...
Rust
src/components/span.rs
veeso/tui-realm-stdlib
1501393e8b2c0574dcae75a19dbfe4749c125601
/** * MIT License * * tui-realm - Copyright (C) 2021 Christian Visintin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights...
/** * MIT License * * tui-realm - Copyright (C) 2021 Christian Visintin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights...
fn query(&self, attr: Attribute) -> Option<AttrValue> { self.props.get(attr) } fn attr(&mut self, attr: Attribute, value: AttrValue) { self.props.set(attr, value) } fn state(&self) -> State { State::None } fn perform(&mut self, _cmd: Cmd) -> CmdResult { C...
fn view(&mut self, render: &mut Frame, area: Rect) { if self.props.get_or(Attribute::Display, AttrValue::Flag(true)) == AttrValue::Flag(true) { let foreground = self .props .get_or(Attribute::Foreground, AttrValue::Color(Color::Reset)) ...
function_block-full_function
[ { "content": "/// ### use_or_default_styles\n\n///\n\n/// Returns the styles to be used; in case in span are default, use props'.\n\n/// The values returned are `(foreground, background, modifiers)`\n\npub fn use_or_default_styles(props: &Props, span: &TextSpan) -> (Color, Color, Modifier) {\n\n (\n\n ...
Rust
tests/cli-exact.rs
heartsucker/rustup.rs
92d0d1e9eca600166adde9170848f09d31bb1007
extern crate rustup_dist; extern crate rustup_mock; extern crate tempdir; extern crate rustup_utils; use rustup_mock::clitools::{self, Config, Scenario, expect_ok, expect_ok_ex, expect_err_ex, this_host_triple, change_dir}; ...
extern crate rustup_dist; extern crate rustup_mock; extern crate tempdir; extern crate rustup_utils; use rustup_mock::clitools::{self, Config, Scenario, expect_ok, expect_ok_ex, expect_err_ex, this_host_triple, change_dir}; ...
#[test] fn list_targets() { setup(&|config| { let trip = this_host_triple(); let mut sorted = vec![format!("{} (default)", &*trip), format!("{} (installed)", clitools::CROSS_ARCH1), clitools::CROSS_ARCH2.to_string()]; sorted.sort(...
expect_err_ex(config, &["rustup", "default", "nightly-2016-03-1"], r"", r"info: syncing channel updates for 'nightly-2016-03-1' info: latest update on 2015-01-02, rust version 1.3.0 error: target not found: '2016-03-1' "); }); }
function_block-function_prefix_line
[ { "content": "fn unpack_without_first_dir<R: Read>(archive: &mut tar::Archive<R>, path: &Path) -> Result<()> {\n\n let entries = try!(archive.entries().chain_err(|| ErrorKind::ExtractingPackage));\n\n for entry in entries {\n\n let mut entry = try!(entry.chain_err(|| ErrorKind::ExtractingPackage));...
Rust
lib/filetests/src/concurrent.rs
brson/cretonne
9384d3d7363246245b2ffd1a09938e4028f620a2
use cretonne_codegen::timing; use num_cpus; use std::panic::catch_unwind; use std::path::{Path, PathBuf}; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use {runone, TestResult}; struct Request(usize, PathBuf); pub enum Reply { Starting {...
use cretonne_codegen::timing; use num_cpus; use std::panic::catch_unwind; use std::path::{Path, PathBuf}; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use {runone, TestResult}; struct Request(usize, PathBuf); pub enum Reply { Starting {...
fn worker_thread( thread_num: usize, requests: Arc<Mutex<Receiver<Request>>>, replies: Sender<Reply>, ) -> thread::JoinHandle<timing::PassTimes> { thread::Builder::new() .name(format!("worker #{}", thread_num)) .spawn(move || { loop { let Re...
fn heartbeat_thread(replies: Sender<Reply>) -> thread::JoinHandle<()> { thread::Builder::new() .name("heartbeat".to_string()) .spawn(move || { while replies.send(Reply::Tick).is_ok() { thread::sleep(Duration::from_secs(1)); } }) .unwrap() }
function_block-full_function
[ { "content": "/// Load `path` and run the test in it.\n\n///\n\n/// If running this test causes a panic, it will propagate as normal.\n\npub fn run(path: &Path) -> TestResult {\n\n let _tt = timing::process_file();\n\n dbg!(\"---\\nFile: {}\", path.to_string_lossy());\n\n let started = time::Instant::n...
Rust
examples/stopwatch-with-ssd1306-and-interrupts.rs
chemicstry/stm32f4xx-hal
41d8dd93a5a9e90dc7afbe70b99f8b8496ea4a55
#![allow(clippy::empty_loop)] #![no_std] #![no_main] use panic_semihosting as _; use stm32f4xx_hal as hal; use crate::hal::{ delay::Delay, fugit::{CounterUs, Event, Timer}, gpio::{gpioc::PC13, Edge, Input, PullUp}, i2c::I2c, interrupt, pac, prelude::*, rcc::{Clocks, Rcc}, }; use core::c...
#![allow(clippy::empty_loop)] #![no_std] #![no_main] use panic_semihosting as _; use stm32f4xx_hal as hal; use crate::hal::{ delay::Delay, fugit::{CounterUs, Event, Timer}, gpio::{gpioc::PC13, Edge, Input, PullUp}, i2c::I2c, interrupt, pac, prelude::*, rcc::{Clocks, Rcc}, }; use core::c...
fn setup_clocks(rcc: Rcc) -> Clocks { rcc.cfgr .hclk(48.mhz()) .sysclk(48.mhz()) .pclk1(24.mhz()) .pclk2(24.mhz()) .freeze() } fn stopwatch_start(cs: &CriticalSection) { ELAPSED_MS.borrow(cs).replace(0); unsafe { pac::NVIC::unmask(hal::pac::Interrupt::TIM2)...
fn EXTI15_10() { free(|cs| { let mut btn_ref = BUTTON.borrow(cs).borrow_mut(); if let Some(ref mut btn) = btn_ref.deref_mut() { btn.clear_interrupt_pending_bit(); let state = STATE.borrow(cs).get(); match state ...
function_block-full_function
[ { "content": "#[entry]\n\nfn main() -> ! {\n\n if let (Some(dp), Some(_cp)) = (\n\n pac::Peripherals::take(),\n\n cortex_m::peripheral::Peripherals::take(),\n\n ) {\n\n // Set up the LED. On the Mini-F4 it's connected to pin PC13.\n\n let gpioc = dp.GPIOC.split();\n\n le...
Rust
src/io_mux/u0rxd.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
#[doc = "Reader of register U0RXD"] pub type R = crate::R<u32, super::U0RXD>; #[doc = "Writer for register U0RXD"] pub type W = crate::W<u32, super::U0RXD>; #[doc = "Register U0RXD `reset()`'s with value 0x0a00"] impl crate::ResetValue for super::U0RXD { type Type = u32; #[inline(always)] fn reset_value() -...
#[doc = "Reader of register U0RXD"] pub type R = crate::R<u32, super::U0RXD>; #[doc = "Writer for register U0RXD"] pub type W = crate::W<u32, super::U0RXD>; #[doc = "Register U0RXD `reset()`'s with value 0x0a00"] impl crate::ResetValue for super::U0RXD { type Type = u32; #[inline(always)] fn reset_value() -...
lf.w } } #[doc = "Reader of field `SLP_OE`"] pub type SLP_OE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SLP_OE`"] pub struct SLP_OE_W<'a> { w: &'a mut W, } impl<'a> SLP_OE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(tru...
eld `FUN_IE`"] pub struct FUN_IE_W<'a> { w: &'a mut W, } impl<'a> FUN_IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { ...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
crates/nu-command/src/date/format.rs
hustcer/nushell
cb66d2bcad6db50a71d0accba0f76afe0ec12cac
use chrono::Local; use chrono::{DateTime, TimeZone}; use nu_engine::CallExt; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use std::fmt::{Display, Write}; use super::utils::parse_date_from_...
use chrono::Local; use chrono::{DateTime, TimeZone}; use nu_engine::CallExt; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use std::fmt::{Display, Write}; use super::utils::parse_date_from_...
fn format_helper_rfc2822(value: Value, span: Span) -> Value { match value { Value::Date { val, span: _ } => Value::String { val: val.to_rfc2822(), span, }, Value::String { val, span: val_span, } => { let dt = parse_date_fr...
matter_span), Value::String { val, .. } => { let dt = parse_date_from_string(&val, formatter_span); match dt { Ok(x) => format_from(x, formatter, formatter_span), Err(e) => e, } } Value::Nothing { .. } => { let dt =...
function_block-function_prefixed
[ { "content": "pub fn convert_string_to_value(string_input: String, span: Span) -> Result<Value, ShellError> {\n\n let result: Result<toml::Value, toml::de::Error> = toml::from_str(&string_input);\n\n match result {\n\n Ok(value) => Ok(convert_toml_to_value(&value, span)),\n\n\n\n Err(_x) => ...
Rust
generator/src/c_parse.rs
sjb3d/spark
224ef9af014b49ebca183cbb19a5b3ac4e7cbb73
use nom::{ branch::alt, bytes::complete::{tag, take_while1}, character::complete::{char, digit1, hex_digit1, multispace0}, combinator::{all_consuming, map, map_res, not, opt, peek}, error::VerboseError, multi::{many0, separated_list1}, number::complete::float, sequence::{delimited, prece...
use nom::{ branch::alt, bytes::complete::{tag, take_while1}, character::complete::{char, digit1, hex_digit1, multispace0}, combinator::{all_consuming, map, map_res, not, opt, peek}, error::VerboseError, multi::{many0, separated_list1}, number::complete::float, sequence::{delimited, prece...
t(f) } } #[derive(Debug, Clone, Copy)] pub enum CArraySize<'a> { Literal(usize), Ident(&'a str), } impl fmt::Display for CArraySize<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { CArraySize::Literal(n) => n.fmt(f), CArraySize::Ident(s) => s.fm...
t { let s = match self { CDecoration::None | CDecoration::Const => "", CDecoration::Pointer => "* mut ", CDecoration::PointerToConst => "* const ", CDecoration::PointerToPointer => "* mut *mut ", CDecoration::PointerToConstPointerToConst => "*const *co...
function_block-random_span
[ { "content": "#[allow(clippy::float_cmp)]\n\n#[cfg_attr(target_os = \"android\", ndk_glue::main(backtrace = \"on\"))]\n\npub fn main() {\n\n // this example only requires Vulkan 1.0.0\n\n let version = Default::default();\n\n\n\n // load the Vulkan lib\n\n let instance = {\n\n let loader = Lo...
Rust
src/rust/engine/testutil/src/data.rs
foursquare/pants
f0627cfa6ab05fc9a10686a499d1fb1d6ebdb68b
use bazel_protos; use bytes; use digest::FixedOutput; use hashing; use protobuf::Message; use sha2::{self, Digest}; pub struct TestData { string: String, } impl TestData { pub fn empty() -> TestData { TestData::new("") } pub fn roland() -> TestData { TestData::new("European Burmese") } pub fn ca...
use bazel_protos; use bytes; use digest::FixedOutput; use hashing; use protobuf::Message; use sha2::{self, Digest}; pub struct TestData { string: String, } impl TestData { pub fn empty() -> TestData { TestData::new("") } pub fn roland() -> TestData { TestData::new("European Burmese") } pub fn ca...
erprint { hash(&self.bytes()) } pub fn digest(&self) -> hashing::Digest { hashing::Digest(self.fingerprint(), self.bytes().len()) } } fn hash(bytes: &bytes::Bytes) -> hashing::Fingerprint { let mut hasher = sha2::Sha256::default(); hasher.input(bytes); hashing::Fingerprint::from_bytes_unsafe(hashe...
ion::Directory::new(); directory.mut_files().push({ let mut file = bazel_protos::remote_execution::FileNode::new(); file.set_name("roland".to_owned()); file.set_digest((&TestData::roland().digest()).into()); file.set_is_executable(false); file }); TestDirectory { directory } ...
random
[ { "content": "pub fn digest_from_filepath(str: &str) -> Result<Digest, String> {\n\n let mut parts = str.split(\"-\");\n\n let fingerprint_str = parts\n\n .next()\n\n .ok_or_else(|| format!(\"Invalid digest: {} wasn't of form fingerprint-size\", str))?;\n\n let fingerprint = Fingerprint::from_hex_strin...
Rust
src/cli.rs
lqc/rover
c8783b80ac920e9fe55d834015b7c3dbdf14412f
use camino::Utf8PathBuf; use reqwest::blocking::Client; use serde::Serialize; use structopt::{clap::AppSettings, StructOpt}; use crate::command::output::JsonOutput; use crate::command::{self, RoverOutput}; use crate::utils::{ client::StudioClientConfig, env::{RoverEnv, RoverEnvKey}, stringify::option_from_...
use camino::Utf8PathBuf; use reqwest::blocking::Client; use serde::Serialize; use structopt::{clap::AppSettings, StructOpt}; use crate::command::output::JsonOutput; use crate::command::{self, RoverOutput}; use crate::utils::{ client::StudioClientConfig, env::{RoverEnv, RoverEnvKey}, stringify::option_from_...
; let config = self.get_rover_config()?; Ok(StudioClientConfig::new( override_endpoint, config, is_sudo, self.get_reqwest_client(), )) } pub(crate) fn get_install_override_path(&self) -> Result<Option<Utf8PathBuf>> { Ok(self ...
if let Some(fire_flower) = self.env_store.get(RoverEnvKey::FireFlower)? { let fire_flower = fire_flower.to_lowercase(); fire_flower == "true" || fire_flower == "1" } else { false }
if_condition
[ { "content": "/// check for newer versions of rover.\n\n///\n\n/// If this fn is run explicitly from a user-facing command, we pass `force` to\n\n/// check for newer versions, even if we recently checked for updates.\n\n///\n\n/// If `force` is not passed, we check for updates every day at most\n\npub fn check_...
Rust
src/app/components/search/search.rs
GabMus/spot
0af7ea9f379505e4f67a4f5f4d4fdf90e8ff2c6a
use super::SearchResultsModel; use crate::app::components::{Album, Component, EventListener}; use crate::app::dispatch::Worker; use crate::app::models::AlbumModel; use crate::app::state::{AppEvent, BrowserEvent}; use gio::prelude::*; use gladis::Gladis; use gtk::prelude::*; use std::cell::Cell; use std::rc::Rc; struct...
use super::SearchResultsModel; use crate::app::components::{Album, Component, EventListener}; use crate::app::dispatch::Worker; use crate::app::models::AlbumModel; use crate::app::state::{AppEvent, BrowserEvent
f(); if let Some(cell) = source_clone.upgrade() { cell.set(None); } glib::Continue(false) }); if let Some(previous_source) = self.0.replace(Some(new_source)) { glib::source_remove(previous_source); } } } #[derive(Gladis, Clone)...
}; use gio::prelude::*; use gladis::Gladis; use gtk::prelude::*; use std::cell::Cell; use std::rc::Rc; struct Debouncer(Rc<Cell<Option<glib::source::SourceId>>>); impl Debouncer { fn new() -> Self { Self(Rc::new(Cell::new(None))) } fn debounce<F: Fn() + 'static>(&self, interval_ms: u32, f: F) { ...
random
[ { "content": "pub trait ListenerComponent: Component + EventListener {}\n\nimpl<T> ListenerComponent for T where T: Component + EventListener {}\n", "file_path": "src/app/components/mod.rs", "rank": 0, "score": 35276.15148207394 }, { "content": "pub trait Component {\n\n fn get_root_widge...
Rust
examples/011-coordinate-basics.rs
rust-tutorials/learn-opengl
3a1e850ed7a96063fc0137775a31302ea05dfb6b
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![allow(unused_imports)] #![allow(clippy::single_match)] #![allow(clippy::zero_ptr)] const WINDOW_TITLE: &str = "Coordinate Basics"; const WINDOW_WIDTH: u32 = 800; const WINDOW_HEIGHT: u32 = 800; use beryllium::*; use core::{ convert::{TryFrom, Try...
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![allow(unused_imports)] #![allow(clippy::single_match)] #![allow(clippy::zero_ptr)] const WINDOW_TITLE: &str = "Coordinate Basics"; const WINDOW_WIDTH: u32 = 800; const WINDOW_HEIGHT: u32 = 800; use beryllium::*; use core::{ convert::{TryFrom, Try...
let projection_loc = unsafe { let name = null_str!("projection").as_ptr().cast(); glGetUniformLocation(shader_program.0, name) }; let view = Mat4::from_translation(Vec3::new(0.0, 0.0, -1.0)); unsafe { glUniformMatrix4fv(view_loc, 1, GL_FALSE, view.as_ptr()) }; let projection = ultraviolet::projecti...
let view_loc = unsafe { let name = null_str!("view").as_ptr().cast(); glGetUniformLocation(shader_program.0, name) };
assignment_statement
[ { "content": "type Vertex = [f32; 3];\n", "file_path": "examples/005-shader-uniforms.rs", "rank": 1, "score": 230523.6434028041 }, { "content": "type Vertex = [f32; 3 + 2];\n\n/// Draw this with glDrawArrays(GL_TRIANGLES, 0, 36)\n\nconst CUBE_VERTICES: [Vertex; 6 * 6] = [\n\n // panel 1\n\n...
Rust
src/lib.rs
ha-shine/infix-calculator
b28b25391a63a20e48b2eedbadafb73055c04da8
#[macro_use] extern crate lazy_static; use std::collections::HashMap; pub struct RPNQueue(pub Vec<String>); lazy_static! { static ref PRECEDENCE: HashMap<String, u8> = { let mut result = HashMap::new(); result.insert("+".to_string(), 1); result.insert("-".to_string(), 1); result.i...
#[macro_use] extern crate lazy_static; use std::collections::HashMap; pub struct RPNQueue(pub Vec<String>); lazy_static! { static ref PRECEDENCE: HashMap<String, u8> = { let mut result = HashMap::new(); result.insert("+".t
{ pub fn from_infix_string(input: &str) -> Result<Self, String> { let mut output = RPNQueue(Vec::new()); let mut stack = Vec::new(); let mut buffer = String::new(); for token in input.chars() { match token { ...
o_string(), 1); result.insert("-".to_string(), 1); result.insert("*".to_string(), 2); result.insert("/".to_string(), 2); result }; } impl RPNQueue
random
[ { "content": "extern crate infix_calculator;\n\n\n\nuse std::io::{self, Write};\n\nuse infix_calculator::RPNQueue;\n\n\n", "file_path": "src/main.rs", "rank": 3, "score": 3.719508871736992 } ]
Rust
pnet_datalink/src/bpf.rs
beruzebabu/libpnet
c1ee67d11d6dc616540e4a173c5957aba1716959
use crate::bindings::bpf; use crate::{DataLinkReceiver, DataLinkSender, NetworkInterface}; use pnet_sys; use std::collections::VecDeque; use std::ffi::CString; use std::io; use std::mem; use std::ptr; use std::sync::Arc; use std::time::Duration; static ETHERNET_HEADER_SIZE: usize = 14; #[derive(Clone, Copy, Debug...
use crate::bindings::bpf; use crate::{DataLinkReceiver, DataLinkSender, NetworkInterface}; use pnet_sys; use std::collections::VecDeque; use std::ffi::CString; use std::io; use std::mem; use std::ptr; use std::sync::Arc; use std::time::Duration; static ETHERNET_HEADER_SIZE: usize = 14; #[derive(Clone, Copy, Debug...
#[cfg(any(target_os = "freebsd", target_os = "netbsd"))] fn set_feedback(fd: libc::c_int) -> io::Result<()> { if unsafe { bpf::ioctl(fd, bpf::BIOCFEEDBACK, &1) } == -1 { let err = io::Error::last_os_error(); unsafe { libc::close(fd); } re...
fn get_fd(attempts: usize) -> libc::c_int { for i in 0..attempts { let fd = unsafe { let file_name = format!("/dev/bpf{}", i); libc::open( CString::new(file_name.as_bytes()).unwrap().as_ptr(), libc::O_RDWR, 0...
function_block-full_function
[ { "content": "/// Create a data link channel backed by FIFO queues. Useful for debugging and testing.\n\n/// See `Config` for how to inject and read packets on this fake network.\n\npub fn channel(_: &NetworkInterface, config: Config) -> io::Result<super::Channel> {\n\n let sender = Box::new(MockDataLinkSend...
Rust
third_party/rust_crates/vendor/miniz_oxide_c_api/src/lib.rs
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
extern crate crc; #[cfg(not(any(feature = "libc_stub", all(target_arch = "wasm32", not(target_os = "emscripten")))))] extern crate libc; #[cfg(any(feature = "libc_stub", all(target_arch = "wasm32", not(target_os = "emscripten"))))] mod libc { #![allow(non_camel_case_types)] use std::alloc::{alloc as rust_alloc...
extern crate crc; #[cfg(not(any(feature = "libc_stub", all(target_arch = "wasm32", not(target_os = "emscripten")))))] extern crate libc; #[cfg(any(feature = "libc_stub", all(target_arch = "wasm32", not(target_os = "emscripten"))))] mod libc { #![allow(non_camel_case_types)] use std::alloc::{alloc as rust_alloc...
} extern crate miniz_oxide; use std::{cmp, ptr, slice}; use std::panic::{catch_unwind, AssertUnwindSafe}; use crc::{Hasher32, crc32}; use libc::{c_int, c_uint, c_ulong, c_void, size_t}; use miniz_oxide::{MZError, MZResult}; #[allow(bad_style)] pub use tdef::tdefl_compressor; pub use miniz_oxide::mz_adler32_oxide; ...
pub unsafe fn free(ptr: *mut c_void) { let ptr = (ptr as *mut size_t).offset(-1); let size = *ptr.offset(0); let align = mem::size_of::<size_t>(); let layout = Layout::from_size_align_unchecked(size, align); rust_dealloc(ptr as *mut _, layout); }
function_block-full_function
[]
Rust
src/regexp.rs
waldyrious/grex
efd6b3ffcdf9d48906f8d679333c82a1983e2ce4
/* * Copyright © 2019-2020 Peter M. Stahl pemistahl@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
/* * Copyright © 2019-2020 Peter M. Stahl pemistahl@gmail.com * * 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
.iter() .map(|&it| { if self.is_output_colorized { it.green().bold() } else { it.clear() } }) .collect_tuple() .unwrap(); match self.ast { Expression::Alternation...
copy of the License at * * http://www.apache.org/licenses/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 expressed or implied. * See the License for the ...
random
[ { "content": "fn obtain_input(cli: &CLI) -> Result<Vec<String>, Error> {\n\n if !cli.input.is_empty() {\n\n Ok(cli.input.clone())\n\n } else if let Some(file_path) = &cli.file_path {\n\n match std::fs::read_to_string(&file_path) {\n\n Ok(file_content) => Ok(file_content.lines().ma...
Rust
libindy_vdr/src/state_proof/node.rs
domwoe/indy-vdr
07f03c4609ceed34bc163f83160c609562c34997
use std::collections::HashMap; use rlp::{DecoderError as RlpDecoderError, Prototype as RlpPrototype, RlpStream, UntrustedRlp}; use sha3::{ digest::{generic_array::GenericArray, Digest, OutputSizeUser}, Sha3_256, }; use crate::common::error::prelude::*; #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] ...
use std::collections::HashMap; use rlp::{DecoderError as RlpDecoderError, Prototype as RlpPrototype, RlpStream, UntrustedRlp}; use sha3::{ digest::{generic_array::GenericArray, Digest, OutputSizeUser}, Sha3_256, }; use crate::common::error::prelude::*; #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] ...
} impl rlp::Decodable for Node { fn decode(rlp: &UntrustedRlp) -> Result<Self, RlpDecoderError> { match rlp.prototype()? { RlpPrototype::List(Node::PAIR_SIZE) => { let path: Vec<u8> = rlp.at(0)?.as_val()?; if path[0] & Node::IS_LEAF_MASK == Node::IS_LEAF_MASK { ...
if let Some(ref value) = node.value { s.append(value); } else { s.append_empty_data(); } } Node::Blank => { s.append_empty_data(); } } }
function_block-function_prefix_line
[ { "content": "#[derive(Debug)]\n\nstruct ConsensusState<K: Eq + Hash, T: Eq + Hash> {\n\n inner: HashMap<K, HashSet<T>>,\n\n}\n\n\n\nimpl<K: Eq + Hash, T: Eq + Hash> ConsensusState<K, T> {\n\n fn new() -> Self {\n\n Self {\n\n inner: HashMap::new(),\n\n }\n\n }\n\n\n\n fn ma...
Rust
src/grammar.rs
wareya/gammakit
63d217f8ebc291844b8df69db12a03b9c906bef4
use super::strings::*; use super::parser::Parser; #[derive(Clone)] pub (crate) enum GrammarToken { Name(String), OptionalName(String), OptionalNameList(String), SpecialNameList{text: String, subtype: String}, SeparatorNameList{text: String, separator: String}, Plain(String), Regex(String), ...
use super::strings::*; use super::parser::Parser; #[derive(Clone)] pub (crate) enum GrammarToken { Name(String), OptionalName(String), OptionalNameList(String), SpecialNameList{text: String, subtype: String}, SeparatorNameList{text: String, separator: String}, Plain(String), Regex(String), ...
}
pub (crate) fn new(line : &str, parser : &mut Parser, intoken : bool) -> Result<GrammarForm, String> { let re = &mut parser.internal_regexes; let mut ret = GrammarForm { tokens : Vec::new() }; let tokens : Vec<&str> = line.split(' ').collect(); for token in &tokens { ...
function_block-full_function
[ { "content": "fn minierr(mystr : &'static str) -> String\n\n{\n\n mystr.to_string()\n\n}\n", "file_path": "src/interpreter.rs", "rank": 0, "score": 148126.25653067103 }, { "content": "fn plainerr<T>(mystr : &'static str) -> Result<T, String>\n\n{\n\n Err(minierr(mystr))\n\n}\n", "f...
Rust
packages/core/src/mutations.rs
BarryYan/dioxus
aa2d6b8d1148a5eaabdfa9f5044c8e8bc493e923
use crate::innerlude::*; use std::{any::Any, fmt::Debug}; pub struct Mutations<'a> { pub edits: Vec<DomEdit<'a>>, pub dirty_scopes: FxHashSet<ScopeId>, pub refs: Vec<NodeRefMutation<'a>>, } impl Debug for Mutations<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f....
use crate::innerlude::*; use std::{any::Any, fmt::Debug}; pub struct Mutations<'a> { pub edits: Vec<DomEdit<'a>>, pub dirty_scopes: FxHashSet<ScopeId>, pub refs: Vec<NodeRefMutation<'a>>, } impl Debug for Mutations<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f....
} pub(crate) fn create_placeholder(&mut self, id: ElementId) { let id = id.as_u64(); self.edits.push(CreatePlaceholder { root: id }); } pub(crate) fn new_event_listener(&mut self, listener: &Listener, scope: ScopeId) { let Listener { event, mou...
match ns { Some(ns) => self.edits.push(CreateElementNs { root: id, ns, tag }), None => self.edits.push(CreateElement { root: id, tag }), }
if_condition
[ { "content": "/// This hould only be used once per app\n\n///\n\n/// You can manually parse the route if you want, but the derived `parse` method on `Routable` will also work just fine\n\npub fn use_router<R: Routable>(cx: &ScopeState, mut parse: impl FnMut(&str) -> R + 'static) -> &R {\n\n // for the web, a...