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
game_plugin/src/actions.rs
NiklasEi/ld49
1fc925339de6d0aa64983d31186cf1ba932c595c
use crate::GameState; use bevy::prelude::*; pub struct ActionsPlugin; impl Plugin for ActionsPlugin { fn build(&self, app: &mut AppBuilder) { app.init_resource::<Actions>().add_system_set( SystemSet::on_update(GameState::InLevel).with_system(set_movement_actions.system()), ); } } ...
use crate::GameState; use bevy::prelude::*; pub struct ActionsPlugin; impl Plugin for ActionsPlugin { fn build(&self, app: &mut AppBuilder) { app.init_resource::<Actions>().add_system_set( SystemSet::on_update(GameState::InLevel).with_system(set_movement_actions.system()), ); } } ...
actions.head_balance = Some(head_balance); } else { actions.head_balance = None; } actions.jump = GameControl::Jump.just_pressed(&keyboard_input); actions.restart = GameControl::Restart.just_pressed(&keyboard_input); } enum GameControl { BalanceForward, BalanceBackward, Padd...
= actions.head_balance.unwrap_or(0.); if GameControl::BalanceForward.just_released(&keyboard_input) || GameControl::BalanceBackward.just_released(&keyboard_input) { if GameControl::BalanceForward.pressed(&keyboard_input) { head_balance = 1.; } else if ...
function_block-random_span
[ { "content": "fn jump(\n\n actions: Res<Actions>,\n\n mut wheel_query: Query<\n\n (Entity, &mut RigidBodyVelocity, &Transform),\n\n (With<Wheel>, Without<Body>),\n\n >,\n\n mut jump_block: ResMut<JumpBlock>,\n\n mut body_query: Query<&Transform, (With<Body>, Without<Wheel>)>,\n\n ...
Rust
src/librustc_incremental/persist/dirty_clean.rs
killerswan/rust
e703b33e3e03d1078c8825e1f64ecfb45884f5cb
use super::directory::RetracedDefIdDirectory; use super::load::DirtyNodes; use rustc::dep_graph::{DepGraphQuery, DepNode}; use rustc::hir; use rustc::hir::def_id::DefId; use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::hir::intravisit; use rustc::ich::{Fingerprint, ATTR_DIRTY, ATTR_CLEAN, ATTR_DIRTY_METADAT...
use super::directory::RetracedDefIdDirectory; use super::load::DirtyNodes; use rustc::dep_graph::{DepGraphQuery, DepNode}; use rustc::hir; use rustc::hir::def_id::DefId; use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::hir::intravisit; use rustc::ich::{Fingerprint, ATTR_DIRTY, ATTR_CLEAN, ATTR_DIRTY_METADAT...
} pub struct FindAllAttrs<'a, 'tcx:'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, attr_names: Vec<&'static str>, found_attrs: Vec<&'tcx Attribute>, } impl<'a, 'tcx> FindAllAttrs<'a, 'tcx> { fn is_active_attr(&mut self, attr: &Attribute) -> bool { for attr_name in &self.attr_names { if attr.c...
if let Some(value) = item.value_str() { value } else { let msg = if let Some(name) = item.name() { format!("associated value expected for `{}`", name) } else { "expected an associated value".to_string() }; tcx.sess.span_fatal(item.span, &msg); }
if_condition
[]
Rust
src/graphics/camera.rs
fossegutten/tetra
ebdccc242680786482a8622dbb3f76f1fc0ab00c
use super::Rectangle; use crate::input; use crate::math::{Mat4, Vec2, Vec3}; use crate::window; use crate::Context; #[derive(Debug, Clone)] pub struct Camera { pub position: Vec2<f32>, pub rotation: f32, pub zoom: f32, ...
use super::Rectangle; use crate::input; use crate::math::{Mat4, Vec2, Vec3}; use crate::window; use crate::Context; #[derive(Debug, Clone)] pub struct Camera { pub position: Vec2<f32>, pub rotation: f32, pub zoom: f32, ...
= camera.unproject(proj_zoomed); assert_eq!(proj_zoomed, Vec2::new(-16.0, -48.0)); assert_eq!(unproj_zoomed, Vec2::zero()); camera.rotation = std::f32::consts::FRAC_PI_2; let proj_rotated = camera.project(Vec2::zero()); let unproj_rotated = camera.unproject(proj_rotated); ...
() > f32::EPSILON { let mut top_left = Vec2::new(-half_viewport_width, -half_viewport_height); let mut bottom_left = Vec2::new(-half_viewport_width, half_viewport_height); top_left.rotate_z(self.rotation); bottom_left.rotate_z(self.rotation); ...
random
[ { "content": "/// Sets the transform matrix.\n\n///\n\n/// This can be used to apply global transformations to subsequent draw calls.\n\npub fn set_transform_matrix(ctx: &mut Context, matrix: Mat4<f32>) {\n\n flush(ctx);\n\n\n\n ctx.graphics.transform_matrix = matrix;\n\n}\n\n\n", "file_path": "src/gr...
Rust
src/rtl/tree.rs
GuillaumeDIDIER/C-teel
4e46a6623dc3ce669e7525cff7069dbdeaa4043b
use common::ops; pub use parse::ast::Ident; use std::collections::{HashMap, HashSet}; use std::fmt::Display; use std::fmt; use common::register::Register; use common::label::Label; use common::label::LabelAllocator; use common::register::RegisterAllocator; #[derive(Debug)] pub enum Instruction { Const(i64, Regist...
use common::ops; pub use parse::ast::Ident; use std::collections::{HashMap, HashSet}; use std::fmt::Display; use std::fmt; use common::register::Register; use common::label::Label; use common::label::LabelAllocator; use common::register::RegisterAllocator; #[derive(Debug)] pub enum Instruction { Const(i64, Regist...
ruct FuncDefinition { pub name: Ident, pub formals: Vec<Register>, pub result: Register, pub locals: HashSet<Register>, pub entry: Label, pub exit: Label, pub body: HashMap<Label, Instruction>, pub label_allocator: LabelAllocator, pub register_allocator: RegisterAllocator, } impl Fu...
goto {}", label) }, Instruction::Branch(ref branch_op, ref label1, ref label2) => { write!(f, "{} --> {}, {}", branch_op, label1, label2) }, } } } #[derive(Debug)] pub st
random
[ { "content": "pub fn convert_char(ch: &str) -> Option<i64> {\n\n if ch.len() == 1 {\n\n if let Some(c) = ch.chars().next() {\n\n Some(c as i64)\n\n } else {\n\n None\n\n }\n\n } else if ch.len() == 2 {\n\n match ch {\n\n \"\\\\\\\\\" => Some(92)...
Rust
verification/src/header_verifier.rs
liyaspawn/ckb
59a40454fd46bf3640df68591001f9d6b6491049
use crate::{ BlockVersionError, EpochError, NumberError, PowError, TimestampError, UnknownParentError, ALLOWED_FUTURE_BLOCKTIME, }; use ckb_chain_spec::consensus::Consensus; use ckb_error::Error; use ckb_pow::PowEngine; use ckb_traits::HeaderProvider; use ckb_types::core::{HeaderView, Version}; use ckb_verifica...
use crate::{ BlockVersionError, EpochError, NumberError, PowError, TimestampError, UnknownParentError, ALLOWED_FUTURE_BLOCKTIME, }; use ckb_chain_spec::consensus::Consensus; use ckb_error::Error; use ckb_pow::PowEngine; use ckb_traits::HeaderProvider; use ckb_types::core::{HeaderView, Version}; use ckb_verifica...
} .into()); } let max = self.now + ALLOWED_FUTURE_BLOCKTIME; if self.header.timestamp() > max { return Err(TimestampError::BlockTimeTooNew { max, actual: self.header.timestamp(), } .into()); } Ok((...
onsensus.block_version()).verify()?; PowVerifier::new(header, self.consensus.pow_engine().as_ref()).verify()?; let parent = self .data_loader .get_header(&header.parent_hash()) .ok_or_else(|| UnknownParentError { parent_hash: header.parent_has...
random
[]
Rust
cli/ops/os.rs
justgeek/deno
34ec3b225425cecdccf754fbc87f4a8f3728890d
use super::dispatch_json::{Deserialize, JsonOp, Value}; use crate::op_error::OpError; use crate::state::State; use deno_core::CoreIsolate; use deno_core::ZeroCopyBuf; use std::collections::HashMap; use std::env; use std::io::{Error, ErrorKind}; use url::Url; pub fn init(i: &mut CoreIsolate, s: &State) { i.register_...
use super::dispatch_json::{Deserialize, JsonOp, Value}; use crate::op_error::OpError; use crate::state::State; use deno_core::CoreIsolate; use deno_core::ZeroCopyBuf; use std::collections::HashMap; use std::env; use std::io::{Error, ErrorKind}; use url::Url;
#[derive(Deserialize)] struct GetDirArgs { kind: std::string::String, } fn op_get_dir( state: &State, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, OpError> { state.check_unstable("Deno.dir"); state.check_env()?; let args: GetDirArgs = serde_json::from_value(args)?; let path = ma...
pub fn init(i: &mut CoreIsolate, s: &State) { i.register_op("op_exit", s.stateful_json_op(op_exit)); i.register_op("op_env", s.stateful_json_op(op_env)); i.register_op("op_exec_path", s.stateful_json_op(op_exec_path)); i.register_op("op_set_env", s.stateful_json_op(op_set_env)); i.register_op("op_get_env", s....
function_block-full_function
[ { "content": "export function getRandomValues<\n\n T extends\n\n | Int8Array\n\n | Uint8Array\n\n | Uint8ClampedArray\n\n | Int16Array\n\n | Uint16Array\n\n | Int32Array\n\n | Uint32Array\n\n>(typedArray: T): T {\n\n assert(typedArray !== null, \"Input must not be null\");\n\n assert(typ...
Rust
src/metadata/media_info.rs
fengalin/media-toc-player
8fb6580419ec530329c131116c726bb176348956
use gettextrs::gettext; use gst::Tag; use lazy_static::lazy_static; use std::{ collections::HashMap, fmt, path::{Path, PathBuf}, sync::Arc, }; use super::{Duration, MediaContent}; #[derive(Debug)] pub struct SelectStreamError(Arc<str>); impl SelectStreamError { fn new(id: &Arc<str>) -> Self { ...
use gettextrs::gettext; use gst::Tag; use lazy_static::lazy_static; use std::{ collections::HashMap, fmt, path::{Path, PathBuf}, sync::Arc, }; use super::{Duration, MediaContent}; #[derive(Debug)] pub struct SelectStreamError(Arc<str>); impl SelectStreamError { fn new(id: &Arc<str>) -> Self { ...
} pub fn is_video_selected(&self) -> bool { self.cur_video_id.is_some() } pub fn selected_audio(&self) -> Option<&Stream> { self.cur_audio_id .as_ref() .and_then(|stream_id| self.audio.get(stream_id)) } pub fn selected_video(&self) -> Option<&Stream> {...
match type_ { gst::StreamType::AUDIO => &self.audio, gst::StreamType::VIDEO => &self.video, gst::StreamType::TEXT => &self.text, other => unimplemented!("{:?}", other), }
if_condition
[ { "content": "fn parse_to<T: std::str::FromStr>(i: &str) -> IResult<&str, T> {\n\n let (i, res) = digit1(i)?;\n\n\n\n res.parse::<T>()\n\n .map(move |value| (i, value))\n\n .map_err(move |_| Err::Error((i, ErrorKind::ParseTo)))\n\n}\n", "file_path": "src/metadata/mod.rs", "rank": 2, ...
Rust
src/dat/civilization.rs
vtabbott/djin
9b63973941a9f6efc327f18085c00838e02e80b7
use crate::dat::common::DeString; use crate::dat::unit::Task; use crate::dat::ResourceUsage; const RESOURCE_STORAGE_SIZE: usize = 3; const GRAPHIC_DISPLACEMENT_SIZE: usize = 3; const BUILDING_ANNEXES_SIZE: usize = 4; #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Civilizations { pub size: u16, ...
use crate::dat::common::DeString; use crate::dat::unit::Task; use crate::dat::ResourceUsage; const RESOURCE_STORAGE_SIZE: usize = 3; const GRAPHIC_DISPLACEMENT_SIZE: usize = 3; const BUILDING_ANNEXES_SIZE: usize = 4; #[derive(Protocol, Debug, Clone, PartialEq)] pub struct Civilizations { pub size: u16, ...
Creatable = 70, Building = 80, AoeTrees = 90, } #[derive(Protocol, Debug, Clone, PartialEq)] pub struct DeadFish { pub walking_graphic: i16, pub running_graphic: i16, pub rotation_speed: f32, pub old_size_class: u8, pub tracking_unit: i16, pub tracking_...
pacity: i16, pub resource_decay: f32, pub blast_defense_level: u8, pub combat_level: u8, pub interaction_mode: u8, pub minimap_mode: u8, pub interface_kind: u8, pub multiple_attribute_mode: f32, pub minimap_color: u8, pub language_dll_help: i32, pub language_dll_hot_key...
random
[ { "content": "\n\n#[derive(Protocol, Debug, Clone, PartialEq)]\n\npub struct Task {\n\n pub task_type: i16,\n\n pub id: i16,\n\n pub is_default: u8,\n\n pub action_type: i16,\n\n pub class_id: i16,\n\n pub unit_id: i16,\n\n pub terrain_id: i16,\n\n pub resource_in: i16,\n\n pub resour...
Rust
src/memfd.rs
lucab/memfd-rs
40e00f1b7a6fad816ab1394ce4cc1910c478d32a
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::{ffi, fs, os::raw}; use crate::{nr, sealing}; #[cfg(any(target_os = "android", target_os="linux"))] unsafe fn memfd_create(name: *const raw::c_char, flags: raw::c_uint) -> raw::c_int { libc::syscall(libc::SYS_memfd_create, name, flags) as raw:...
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::{ffi, fs, os::raw}; use crate::{nr, sealing}; #[cfg(any(target_os = "android", target_os="linux"))] unsafe fn memfd_create(name: *const raw::c_char, flags: raw::c_uint) -> raw::c_int { libc::syscall(libc::SYS_memfd_create, name, flags) as raw:...
pub fn create<T: AsRef<str>>(&self, name: T) -> Result<Memfd, crate::Error> { let flags = self.bitflags(); unsafe { let cname = ffi::CString::new(name.as_ref()).map_err(crate::Error::NameCStri...
if let Some(ref hugetlb) = self.hugetlb { bits |= hugetlb.bitflags(); bits |= nr::MFD_HUGETLB; } bits }
function_block-function_prefix_line
[ { "content": "/// Check if the close-on-exec flag is set for the memfd.\n\npub fn get_close_on_exec(memfd: &memfd::Memfd) -> std::io::Result<bool> {\n\n // SAFETY: The syscall called has no soundness implications (i.e. does not mess with\n\n // process memory in weird ways, checks its arguments for correc...
Rust
src/maps/perf_map_poller.rs
redcanaryco/oxidebpf
2ec84a57cf99504a484378908d295d863ff27c32
use std::{ collections::HashMap, fmt::{self, Formatter}, sync::{Arc, Condvar, Mutex}, thread, time::Duration, }; use crossbeam_channel::{Sender, TrySendError}; use mio::{unix::SourceFd, Events, Interest, Poll, Token}; use nix::errno::Errno; use slog::crit; use crate::{ maps::{PerCpu, PerfEvent...
use std::{ collections::HashMap, fmt::{self, Formatter}, sync::{Arc, Condvar, Mutex}, thread, time::Duration, }; use crossbeam_channel::{Sender, TrySendError}; use mio::{unix::SourceFd, Events, Interest, Poll, Token}; use nix::errno::Errno; use slog::crit; use crate::{ maps::{PerCpu, PerfEvent...
} pub enum InitError { Creation(std::io::Error), Registration(std::io::Error), ReadySignal(String), } impl fmt::Display for InitError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { InitError::Creation(e) => write!(f, "error creating poller: {}", e), ...
fn poll_once( &mut self, events: &mut Events, tx: &Sender<PerfChannelMessage>, ) -> Result<(), RunError> { if let Err(e) = self.poll.poll(events, Some(Duration::from_millis(100))) { match nix::errno::Errno::from_i32(nix::errno::errno()) { Errno::EINTR => r...
function_block-full_function
[ { "content": "/// Return the current memlock limit.\n\npub fn get_memlock_limit() -> Result<usize, OxidebpfError> {\n\n // use getrlimit() syscall\n\n unsafe {\n\n let mut rlim = libc::rlimit {\n\n rlim_cur: 0,\n\n rlim_max: 0,\n\n };\n\n\n\n let ret = libc::getr...
Rust
src/travis.rs
pietroalbini/travis-migrate
078cb2acfa7b685ecd2b7d9cf3d982cb7a82944f
use failure::{bail, Error}; use log::{debug, info}; use reqwest::{ header::{HeaderName, AUTHORIZATION, USER_AGENT}, Client, Method, RequestBuilder, }; use std::process::Command; #[derive(serde_derive::Deserialize)] struct PaginationLink { #[serde(rename = "@href")] href: String, } #[derive(serde_deriv...
use failure::{bail, Error}; use log::{debug, info}; use reqwest::{ header::{HeaderName, AUTHORIZATION, USER_AGENT}, Client, Method, RequestBuilder, }; use std::process::Command; #[derive(serde_derive::Deserialize)] struct PaginationLink { #[serde(rename = "@href")] href: String, } #[derive(serde_deriv...
pub(crate) fn start_migration(&self, repo: &str) -> Result<(), Error> { let _ = self .build_request( Method::POST, &format!("repo/{}/migrate", self.repo_name(repo)), ) .send()? .error_for_status()?; Ok(()) } p...
pub(crate) fn repos_to_migrate(&self, login: &str) -> Result<Vec<Repository>, Error> { let mut repos = Vec::new(); self.paginated(&Method::GET, &format!("owner/{}/repos", login), |req| { let mut resp: Repositories = req .form(&[("active_on_org", "true")]) .sen...
function_block-full_function
[ { "content": "fn app() -> Result<(), Error> {\n\n let args = CLI::from_args();\n\n\n\n match args {\n\n CLI::List { account } => {\n\n let travis_com = TravisCI::new(\"com\", std::env::var(\"TRAVIS_TOKEN_COM\").ok())?;\n\n let repos = travis_com.repos_to_migrate(&account)?;\n\...
Rust
ton_client/src/crypto/boxes/encryption_box/aes.rs
markgenuine/TON-SDK
2b49c8270a34eab1a66e2eac7764b69568e7d324
/* * Copyright 2018-2021 TON Labs LTD. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS,...
/* * Copyright 2018-2021 TON Labs LTD. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS,...
Aes128, Aes192, Aes256, BlockCipher, BlockDecrypt, BlockEncrypt, NewBlockCipher}; use block_modes::{BlockMode, Cbc}; use crate::crypto::Error; use crate::encoding::{base64_decode, hex_decode}; use crate::error::ClientResult; use super::{CipherMode, EncryptionBox, EncryptionBoxInfo}; #[derive(Serialize, Deseri...
T WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific TON DEV software governing permissions and * limitations under the License. */ use aes::{
random
[]
Rust
tezos/api/src/environment.rs
Kyras/tezedge
98bc9991765682d077347575781afb451d147492
use std::collections::HashMap; use std::str::FromStr; use enum_iterator::IntoEnumIterator; use serde::{Deserialize, Serialize}; use lazy_static::lazy_static; use crate::ffi::{GenesisChain, ProtocolOverrides}; lazy_static! { pub static ref TEZOS_ENV: HashMap<TezosEnvironment, TezosEnvironmentConfiguration> = i...
use std::collections::HashMap; use std::str::FromStr; use enum_iterator::IntoEnumIterator; use serde::{Deserialize, Serialize}; use lazy_static::lazy_static; use crate::ffi::{GenesisChain, ProtocolOverrides}; lazy_static! { pub static ref TEZOS_ENV: HashMap<TezosEnvironment, TezosEnvironmentConfiguration> = i...
} fn init() -> HashMap<TezosEnvironment, TezosEnvironmentConfiguration> { let mut env: HashMap<TezosEnvironment, TezosEnvironmentConfiguration> = HashMap::new(); env.insert(TezosEnvironment::Alphanet, TezosEnvironmentConfiguration { genesis: GenesisChain { time: "2018-11-30T15:30:56Z".to_...
fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_ascii_lowercase().as_str() { "alphanet" => Ok(TezosEnvironment::Alphanet), "babylonnet" | "babylon" => Ok(TezosEnvironment::Babylonnet), "mainnet" => Ok(TezosEnvironment::Mainnet), "zeronet" => Ok(TezosE...
function_block-full_function
[ { "content": "type OperationHash = Hash;\n", "file_path": "tezos/interop_callback/src/callback.rs", "rank": 0, "score": 165307.25237255346 }, { "content": "type ContextHash = Hash;\n", "file_path": "tezos/interop_callback/src/callback.rs", "rank": 1, "score": 165307.25237255346 ...
Rust
miniz_oxide/src/inflate/mod.rs
MichaelMcDonnell/miniz_oxide
b6ca295deaecd549c504873481ceb4e2a65a1933
use crate::alloc::boxed::Box; use crate::alloc::vec; use crate::alloc::vec::Vec; use ::core::cmp::min; use ::core::usize; pub mod core; mod output_buffer; pub mod stream; use self::core::*; const TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS: i32 = -4; const TINFL_STATUS_BAD_PARAM: i32 = -3; const TINFL_STATUS_ADLER32_M...
use crate::alloc::boxed::Box; use crate::alloc::vec; use crate::alloc::vec::Vec; use ::core::cmp::min; use ::core::usize; pub mod core; mod output_buffer; pub mod stream; use self::core::*; const TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS: i32 = -4; const TINFL_STATUS_BAD_PARAM: i32 = -3; const TINFL_STATUS_ADLER32_M...
pub fn decompress_slice_iter_to_slice<'out, 'inp>( out: &'out mut [u8], it: impl Iterator<Item = &'inp [u8]>, zlib_header: bool, ignore_adler32: bool, ) -> Result<usize, TINFLStatus> { use self::core::inflate_flags::*; let mut it = it.peekable(); let r = &mut DecompressorOxide::new(); ...
fn decompress_to_vec_inner( input: &[u8], flags: u32, max_output_size: usize, ) -> Result<Vec<u8>, TINFLStatus> { let flags = flags | inflate_flags::TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; let mut ret: Vec<u8> = vec![0; min(input.len().saturating_mul(2), max_output_size)]; let mut decomp = Bo...
function_block-full_function
[ { "content": "/// Compress the input data to a vector, using the specified compression level (0-10).\n\npub fn compress_to_vec(input: &[u8], level: u8) -> Vec<u8> {\n\n compress_to_vec_inner(input, level, 0, 0)\n\n}\n\n\n", "file_path": "miniz_oxide/src/deflate/mod.rs", "rank": 0, "score": 212970...
Rust
lib/src/config.rs
phylum-dev/cli
724395d036bc56c69acd69c0f59ea1308350a2c1
use chrono::{DateTime, Local}; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::env; use std::error::Error; use std::fs; use std::path::PathBuf; use crate::types::*; #[derive(Debug, Serialize, Deserialize)] pub struct ConnectionInfo { pub uri: String, } #[derive(Debug, Serialize, Deserialize)] pub...
use chrono::{DateTime, Local}; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::env; use std::error::Error; use std::fs; use std::path::PathBuf; use crate::types::*; #[derive(Debug, Serialize, Deserialize)] pub struct ConnectionInfo { pub uri: String, } #[derive(Debug, Serialize, Deserialize)] pub...
pub fn get_current_project() -> Option<ProjectConfig> { find_project_conf(".").and_then(|s| { log::info!("Found project configuration file at {}", s); parse_config(&s).ok() }) } #[cfg(test)] mod tests { use super::*; use std::env::temp_dir; fn write_test_config() { let co...
mpts = 0; const MAX_DEPTH: u8 = 32; loop { let search_path = path.join(PROJ_CONF_FILE); if search_path.is_file() { return Some(search_path.to_string_lossy().to_string()); } if attempts > MAX_DEPTH { return None; } path.push(".."); ...
function_block-function_prefixed
[ { "content": "/// Produces the path to a temporary file on disk.\n\nfn tmp_path(filename: &str) -> Option<String> {\n\n let tmp_loc = env::temp_dir();\n\n let path = Path::new(&tmp_loc);\n\n let tmp_path = path.join(filename);\n\n match tmp_path.into_os_string().into_string() {\n\n Ok(x) => S...
Rust
src/main.rs
advion/cartunes
83b085318b314a332d877e83c3841050b0c7699c
#![cfg_attr(not(any(test, debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::all)] use crate::framework::{ConfigHandler, Framework, UserEvent}; use crate::gpu::{Error as GpuError, Gpu}; use crate::gui::{Error as GuiError, Gui}; use crate::setup::Setups; use log::error; use std::collections::VecDeque...
#![cfg_attr(not(any(test, debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::all)] use crate::framework::{ConfigHandler, Framework, UserEvent}; use crate::gpu::{Error as GpuError, Gpu}; use crate::gui::{Error as GuiError, Gui}; use crate::setup::Setups; use log::error; use std::collections::VecDeque...
fn main() -> Result<(), Error> { #[cfg(any(debug_assertions, not(windows)))] env_logger::init(); let (event_loop, window, mut gpu, mut framework) = create_window()?; let mut input = WinitInputHelper::new(); let mut keep_config = ConfigHandler::Replace; event_loop.run(move |event, _, control_...
et framework = Framework::new( window_size, scale_factor, theme, gui, &gpu, event_loop.create_proxy(), ); (gpu, framework) }; Ok((event_loop, window, gpu, framework)) }
function_block-function_prefixed
[ { "content": "/// Configure the theme based on system settings.\n\nfn update_theme(theme: &mut Option<Theme>, ctx: &egui::CtxRef) {\n\n if let Some(theme) = theme.take() {\n\n // Set the style\n\n ctx.set_style(create_style(theme));\n\n }\n\n}\n\n\n\npub(crate) fn cache_path() -> PathBuf {\n...
Rust
src/ser.rs
sisyphe-re/libnar
9ffada39937be91518eaf7fbc27dc0002e95a3db
use std::fs::{self, File}; use std::io::{self, Error, ErrorKind, Read, Write}; use std::os::unix::fs::MetadataExt; use std::path::Path; use crate::{NIX_VERSION_MAGIC, PAD_LEN}; pub fn to_vec<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> { let mut buffer = Vec::new(); to_writer(&mut buffer, path)?; Ok(bu...
use std::fs::{self, File}; use std::io::{self, Error, ErrorKind, Read, Write}; use std::os::unix::fs::MetadataExt; use std::path::Path; use crate::{NIX_VERSION_MAGIC, PAD_LEN}; pub fn to_vec<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> { let mut buffer = Vec::new(); to_writer(&mut buffer, path)?; Ok(bu...
#[test] fn pads_non_multiple_of_eight() { let mut buffer = Vec::new(); let length = 5u64; let data = vec![1u8; length as usize]; write_padded(&mut buffer, &data[..]).unwrap(); let written_data_len = size_of::<u64>() as u64 + length + 3; assert_eq!(buffer.len() ...
write_padded(&mut buffer, &data[..]).unwrap(); let written_data_len = size_of::<u64>() as u64 + length; assert_eq!(buffer.len() as u64, written_data_len); let header_bytes = length.to_le_bytes(); assert_eq!(&buffer[..size_of::<u64>()], header_bytes); let data_bytes = [1u8; 16]...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn serializes_regular_file() {\n\n let dir = tempfile::tempdir().unwrap();\n\n let mut file = File::create(dir.path().join(\"file.txt\")).unwrap();\n\n writeln!(file, \"lorem ipsum dolor sic amet\").unwrap();\n\n\n\n let expected: Vec<u8> = std::iter::empty()\n\n .cha...
Rust
src/sys/pkg/testing/blobfs-ramdisk/src/lib.rs
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
#![deny(missing_docs)] use { anyhow::{format_err, Context as _, Error}, fdio::{SpawnAction, SpawnOptions}, fidl::endpoints::{ClientEnd, ServerEnd}, fidl_fuchsia_io::{ DirectoryAdminMarker, DirectoryAdminProxy, DirectoryMarker, DirectoryProxy, NodeProxy, }, fuchsia_component::server::S...
#![deny(missing_docs)] use { anyhow::{format_err, Context as _, Error}, fdio::{SpawnAction, SpawnOptions}, fidl::endpoints::{ClientEnd, ServerEnd}, fidl_fuchsia_io::{ DirectoryAdminMarker, DirectoryAdminProxy, DirectoryMarker, DirectoryProxy, NodeProxy, }, fuchsia_component::server::S...
; let block_device_handle_id = HandleInfo::new(HandleType::User0, 1); let fs_root_handle_id = HandleInfo::new(HandleType::User0, 0); let block_handle = ramdisk.clone_channel().context("cloning ramdisk channel")?; let (proxy, blobfs_server_end) = fidl::endpoints::create_proxy:...
match self.ramdisk { Some(ramdisk) => ramdisk, None => { let ramdisk = Ramdisk::start().context("creating backing ramdisk for blobfs")?; mkblobfs(&ramdisk)?; ramdisk } }
if_condition
[]
Rust
src/lib.rs
andreyk0/st7920
c7db218fddbc48d2054924be326cbbbefac1a1ea
#![no_std] use num_derive::ToPrimitive; use num_traits::ToPrimitive; use embedded_hal::blocking::delay::DelayUs; use embedded_hal::blocking::spi; use embedded_hal::digital::v2::OutputPin; #[derive(Debug)] pub enum Error<CommError, PinError> { Comm(CommError), Pin(PinError), } #[derive(ToPrimitive)] enum In...
#![no_std] use num_derive::ToPrimitive; use num_traits::ToPrimitive; use embedded_hal::blocking::delay::DelayUs; use embedded_hal::blocking::spi; use embedded_hal::digital::v2::OutputPin; #[derive(Debug)] pub enum Error<CommError, PinError> { Comm(CommError), Pin(PinError), } #[derive(ToPrimitive)] enum In...
t_high().map_err(Error::Pin)?; delay.delay_us(40 * 1000); Ok(()) } fn write_command(&mut self, command: Instruction) -> Result<(), Error<SPIError, PinError>> { self.write_command_param(command, 0) } fn write_command_param( &mut self, command: Instruction, ...
yn DelayUs<u32>) -> Result<(), Error<SPIError, PinError>> { self.enable_cs(delay)?; self.hard_reset(delay)?; self.write_command(Instruction::BasicFunction)?; delay.delay_us(200); self.write_command(Instruction::DisplayOnCursorOff)?; delay.delay_us(100); self.write...
random
[ { "content": "fn main() {\n\n // Put the linker script somewhere the linker can find it\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"memory.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"memory.x\"))\n\n .unwrap();\n\n println...
Rust
src/connectivity/network/testing/netemul/runner/helpers/netstack_cfg/src/main.rs
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
use { anyhow::{format_err, Context as _, Error}, fidl_fuchsia_net, fidl_fuchsia_net_stack::StackMarker, fidl_fuchsia_net_stack_ext::FidlReturn, fidl_fuchsia_netemul_network::{EndpointManagerMarker, NetworkContextMarker}, fidl_fuchsia_netstack::{InterfaceConfig, NetstackMarker}, fuchsia_asy...
use { anyhow::{format_err, Context as _, Error}, fidl_fuchsia_net, fidl_fuchsia_net_stack::StackMarker, fidl_fuchsia_net_stack_ext::FidlReturn, fidl_fuchsia_netemul_network::{EndpointManagerMarker, NetworkContextMarker}, fidl_fuchsia_netstack::{InterfaceConfig, NetstackMarker}, fuchsia_asy...
_net_interfaces_ext::wait_interface_with_id( fidl_fuchsia_net_interfaces_ext::event_stream_from_state(&interface_state)?, &mut fidl_fuchsia_net_interfaces_ext::InterfaceState::Unknown(nicid.into()), |properties| { if !opt.skip_up_check && !properties.online.unwrap_or(false) { ...
=> fidl_fuchsia_net_ext::IpAddress( std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), ), fidl_fuchsia_net::IpAddress::Ipv6(..) => fidl_fuchsia_net_ext::IpAddress( std::net::IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED), ), } .into()...
random
[]
Rust
game/src/sandbox/minimap.rs
balbok0/abstreet
3af15fefdb2772c83864c08724318418da8190a9
use abstutil::prettyprint_usize; use map_gui::tools::{MinimapControls, Navigator}; use widgetry::{ ControlState, EventCtx, GfxCtx, HorizontalAlignment, Image, Key, Line, Panel, ScreenDims, Text, VerticalAlignment, Widget, }; use crate::app::App; use crate::app::Transition; use crate::common::Warping; use crate...
use abstutil::prettyprint_usize; use map_gui::tools::{MinimapControls, Navigator}; use widgetry::{ ControlState, EventCtx, GfxCtx, HorizontalAlignment, Image, Key, Line, Panel, ScreenDims, Text, VerticalAlignment, Widget, }; use crate::app::App; use crate::app::Transition; use crate::common::Warping; use crate...
let counts = app.primary.sim.num_commuters_vehicles(); let pedestrian_details = { let tooltip = Text::from_multiline(vec![ Line("Pedestrians"), Line(format!( "Walking commuters: {}", prettyprint_usize(counts.walking_commuters) )) ...
widgetry/icons/checkbox_no_border_unchecked.svg" )) .color(RewriteColor::Change(Color::BLACK, color.alpha(0.3))); let mut row = GeomBatchStack::horizontal(vec![ checkbox.build_batch(ctx).expect("invalid svg").0, icon_batch.clone(), ]); ...
function_block-function_prefix_line
[ { "content": "fn make_btn(ctx: &EventCtx, label: &str, tooltip: &str, is_persisten_split: bool) -> Button {\n\n // If we want to make Dropdown configurable, pass in or expose its button builder?\n\n let builder = if is_persisten_split {\n\n // Quick hacks to make PersistentSplit's dropdown look a l...
Rust
crates/sipmsg/src/headers/header.rs
armatusmiles/sipcore
7e0bd478d47a53082467bb231655b6f3f5733cb2
use crate::{ common::{bnfcore::*, errorparse::SipParseError, nom_wrappers::from_utf8_nom, take_sws_token}, headers::{ parsers::ExtensionParser, traits::{HeaderValueParserFn, SipHeaderParser}, GenericParams, SipRFCHeader, SipUri, }, }; use alloc::collections::{BTreeMap, VecDeque}; use...
use crate::{ common::{bnfcore::*, errorparse::SipParseError, nom_wrappers::from_utf8_nom, take_sws_token}, headers::{ parsers::ExtensionParser, traits::{HeaderValueParserFn, SipHeaderParser}, GenericParams, SipRFCHeader, SipUri, }, }; use alloc::collections::{BTreeMap, VecDeque}; use...
nput[0] != b';' { return Ok((input, None)); } let (input, parameters) = GenericParams::parse(input)?; Ok((input, Some(parameters))) } pub fn parse( input: &'a [u8], ) -> nom::IResult<&[u8], (Option<SipRFCHeader>, VecDeque<Header<'a>>), SipParseError> { le...
in, Realm, Nonce, DigestUri, Dresponse, Algorithm, Cnonce, Opaque, Stale, QopValue, NonceCount, Number, Method, ID, Host, Port, Star, DisplayName, Seconds, Comment, Major, Minor, TimveVal, Delay, ProtocolName, Pr...
random
[ { "content": "pub fn take(input: &[u8]) -> nom::IResult<&[u8], HeaderValue, SipParseError> {\n\n let (inp, res_val) = take_while1(is_digit)(input)?;\n\n let (_, hdr_val) = HeaderValue::new(res_val, HeaderValueType::Digit, None, None)?;\n\n Ok((inp, hdr_val))\n\n}\n", "file_path": "crates/sipmsg/src...
Rust
src/peripherals.rs
tstellanova/px4flow_bsp
751151cb0c826148013b0709e7a246a9d9ca774d
/* Copyright (c) 2020 Todd Stellanova LICENSE: BSD3 (see LICENSE file) */ use p_hal::stm32 as pac; use stm32f4xx_hal as p_hal; use pac::{DCMI, RCC}; use embedded_hal::blocking::delay::{DelayMs, DelayUs}; use embedded_hal::digital::v2::{OutputPin, ToggleableOutputPin}; use embedded_hal::timer::CountDown; use embedded...
/* Copyright (c) 2020 Todd Stellanova LICENSE: BSD3 (see LICENSE file) */ use p_hal::stm32 as pac; use stm32f4xx_hal as p_hal; use pac::{DCMI, RCC}; use embedded_hal::blocking::delay::{DelayMs, DelayUs}; use embedded_hal::digital::v2::{OutputPin, ToggleableOutputPin}; use embedded_hal::timer::CountDown; use embedded...
pub type I2c1Port = p_hal::i2c::I2c< pac::I2C1, ( p_hal::gpio::gpiob::PB8<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, p_hal::gpio::gpiob::PB9<p_hal::gpio::AlternateOD<p_hal::gpio::AF4>>, ), >; pub type I2c2Port = p_hal::i2c::I2c< pac::I2C2, ( p_hal::gpio::gpiob::PB10<p_ha...
h), gpioe .pe5 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) .set_speed(Speed::VeryHigh), gpioe .pe6 .into_pull_up_input() .into_alternate_af13() .internal_pull_up(true) ...
function_block-function_prefixed
[ { "content": "fn main() {\n\n use std::env;\n\n use std::fs::File;\n\n use std::io::Write;\n\n use std::path::PathBuf;\n\n let memfile_bytes = include_bytes!(\"stm32f407_memory.x\");\n\n\n\n //stm32f427\n\n // Put the linker script somewhere the linker can find it\n\n let out = &PathBuf:...
Rust
weld/tests/dictionary_tests.rs
winding-lines/weld
beebaacabd11327dea2e51071b708de238c84386
use fnv; use std::collections::hash_map::Entry; mod common; use crate::common::*; #[repr(C)] struct I32KeyValArgs { x: WeldVec<i32>, y: WeldVec<i32>, } #[test] fn simple_for_dictmerger_loop() { let code = "|x:vec[i32], y:vec[i32]| tovec(result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,...
use fnv; use std::collections::hash_map::Entry; mod common; use crate::common::*; #[repr(C)] struct I32KeyValArgs { x: WeldVec<i32>, y: WeldVec<i32>, } #[test] fn simple_for_dictmerger_loop() { let code = "|x:vec[i32], y:vec[i32]| tovec(result(for(zip(x,y), dictmerger[i32,i32,+], |b,i,...
= ret_value.data() as *const bool; let result = unsafe { (*data).clone() }; let output = false; assert_eq!(output, result); }
clone()); let data = ret_value.data() as *const bool; let result = unsafe { (*data).clone() }; let output = true; assert_eq!(output, result); let ref conf = default_conf(); let ret_value = compile_and_run(code_false, conf, input_data.clone()); let data
function_block-random_span
[]
Rust
day22/src/main.rs
ajtribick/AdventOfCode2020
a633a31ff0d456b587dd7602a30c9d841417f3a0
use std::{ collections::VecDeque, error::Error, fs::File, io::{BufRead, BufReader}, path::{Path, PathBuf}, }; use ahash::AHashSet; #[derive(Debug, Clone, Copy)] pub enum Player { Player1, Player2, } #[derive(Debug, Clone)] pub struct Game { player1: VecDeque<u64>, player2: VecDequ...
use std::{ collections::VecDeque, error::Error, fs::File, io::{BufRead, BufReader}, path::{Path, PathBuf}, }; use ahash::AHashSet; #[derive(Debug, Clone, Copy)] pub enum Player { Player1, Player2, } #[derive(Debug, Clone)] pub struct Game { player1: VecDeque<u64>, player2: VecDequ...
er.unwrap() } else if card1 > card2 { Player::Player1 } else { Player::Player2 }; match winner { Player::Player1 => { self.player1.push_back(card1); self.player1.push_back(card2); ...
rn; } let card1 = self.player1.pop_front().unwrap(); let card2 = self.player2.pop_front().unwrap(); let winner = if self.player1.len() as u64 >= card1 && self.player2.len() as u64 >= card2 { let mut sub_game = Self::new( s...
random
[ { "content": "fn part2(lines: impl Iterator<Item = impl AsRef<str>> + Clone) {\n\n let result = SLOPES\n\n .iter()\n\n .map(|&(right_step, down_step)| count_trees(lines.clone(), right_step, down_step))\n\n .product::<u32>();\n\n println!(\"Part 2: product is {}\", result);\n\n}\n\n\n"...
Rust
jvmkill/src/heap/types.rs
cloudfoundry/jvmkill
d1d7f104f94227e3c97166b633ec3ddb8e6c39fe
/* * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
/* * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
unsafe { classes.offset(1) })) .times(1) .in_sequence(&mut seq) .return_const((String::from("bravo-type"), String::from("bravo-generic"))); jvmti .expect_set_tag() .withf_st(move |&a_class, &a_tag| { ptr::eq(a_class, unsafe { classes....
seq) .return_const((String::from("alpha-type"), String::from("alpha-generic"))); jvmti .expect_set_tag() .withf_st(move |&a_class, &a_tag| { ptr::eq(a_class, unsafe { classes.offset(1) }) && a_tag == 1 }) .times(1)...
function_block-random_span
[ { "content": "#[test]\n\nfn time_10_count_2() {\n\n let r = Runner {\n\n class: \"org.cloudfoundry.jvmkill.ThreadExhaustion\",\n\n arguments: \"=time=10,count=2,printHeapHistogram=0,printMemoryUsage=0\",\n\n std_out: vec!(),\n\n std_err: vec!(\n\n \"Resource Exhausted! ...
Rust
src/round.rs
xoac/chrono
37fb8005f196e9e67629d28c0ae84a3b9d31926a
use oldtime::Duration; use std::ops::{Add, Sub}; use Timelike; pub trait SubsecRound { fn round_subsecs(self, digits: u16) -> Self; fn trunc_subsecs(self, digits: u16) -> Self; } impl<T> SubsecRound for...
use oldtime::Duration; use std::ops::{Add, Sub}; use Timelike; pub trait SubsecRound { fn round_subsecs(self, digits: u16) -> Self; fn trunc_subsecs(self, digits: u16) -> Self; } impl<T> SubsecRound for...
#[cfg(test)] mod tests { use super::SubsecRound; use offset::{FixedOffset, TimeZone, Utc}; use Timelike; #[test] fn test_round() { let pst = FixedOffset::east(8 * 60 * 60); let dt = pst.ymd(2018, 1, 11).and_hms_nano(10, 5, 13, 084_660_684); assert_eq!(dt.round_subsecs(10)...
0 => 1_000_000_000, 1 => 100_000_000, 2 => 10_000_000, 3 => 1_000_000, 4 => 100_000, 5 => 10_000, 6 => 1_000, 7 => 100, 8 => 10, _ => 1, } }
function_block-function_prefix_line
[ { "content": "pub fn cycle_to_yo(cycle: u32) -> (u32, u32) {\n\n let (mut year_mod_400, mut ordinal0) = div_rem(cycle, 365);\n\n let delta = u32::from(YEAR_DELTAS[year_mod_400 as usize]);\n\n if ordinal0 < delta {\n\n year_mod_400 -= 1;\n\n ordinal0 += 365 - u32::from(YEAR_DELTAS[year_mod...
Rust
src/reader.rs
sayantangkhan/oxyscheme
742da72abbd719bf66898e46bd3913191f3d00fb
use crate::lexer::*; use crate::parser::{parse_datum, Datum}; use crate::*; use anyhow::Result; use std::{ fs::File, io::{BufRead, BufReader, Lines}, iter::{Enumerate, Peekable}, path::PathBuf, }; pub struct FileLexer { file: File, } impl FileLexer { pub fn new(filename: &str) -> Result<...
use crate::lexer::*; use crate::parser::{parse_datum, Datum}; use crate::*; use anyhow::Result; use std::{ fs::File, io::{BufRead, BufReader, Lines}, iter::{Enumerate, Peekable}, path::PathBuf, }; pub struct FileLexer { file: File, } impl FileLexer { pub fn new(filename: &str) -> Result<...
) } } } } pub struct DatumIterator<I> where I: Iterator<Item = Result<TokenWithPosition, CompilerError>>, { token_stream: Peekable<I>, encountered_error: bool, } impl<I> DatumIterator<I> where I: Iterator<Item = Result<TokenWithPosition, CompilerError>>, { pub fn new(t...
Err(CompilerError::LexError( String::from(&self.input_string[self.cursor_position..]), self.line_number, self.cursor_position, ))
call_expression
[ { "content": "/// Parses a single `Datum` from the token stream\n\npub fn parse_datum<I>(token_stream: &mut Peekable<I>) -> Result<Datum, CompilerError>\n\nwhere\n\n I: Iterator<Item = Result<TokenWithPosition, CompilerError>>,\n\n{\n\n match token_stream.peek() {\n\n Some(Ok(TokenWithPosition {\n\...
Rust
src/storage/assembler.rs
ProgVal/smoltcp
1bde6e7ec45684019f191714c158e2f496eb49d0
use core::fmt; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Contig { hole_size: usize, data_size: usize } impl fmt::Display for Contig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.has_hole() { write!(f, "({})", self.hole_size)?; } if self.has_hole() && self.has_d...
use core::fmt; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Contig { hole_size: usize, data_size: usize } impl fmt::Display for Contig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.has_hole() { write!(f, "({})", self.hole_size)?; } if self.has_hole() && self.has_d...
if offset >= contig.total_size() { offset = offset.saturating_sub(contig.total_size()); } else { size = (offset + size).saturating_sub(contig.total_size()); offset = 0; } } debug_assert!(size == 0); ...
if offset <= contig.hole_size && offset + size >= contig.hole_size { self.contigs[index].shrink_hole_to(offset); index += 1; } else if offset + size >= contig.hole_size { index += 1; } else if offs...
if_condition
[ { "content": "pub fn parse_middleware_options<D>(matches: &mut Matches, device: D, loopback: bool)\n\n -> FaultInjector<EthernetTracer<PcapWriter<D, Rc<PcapSink>>>>\n\n where D: for<'a> Device<'a>\n\n{\n\n let drop_chance = matches.opt_str(\"drop-chance\").map(|s| u8::from_str(&s).unwrap())\n\...
Rust
src/serde/mod.rs
soenkehahn/time
1860b1482e96e3973fbad634739eb21c5bc0190d
pub mod timestamp; use serde::de::Error as _; #[cfg(feature = "serde-human-readable")] use serde::ser::Error as _; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::error::ComponentRange; #[cfg(feature = "serde-human-readable")] use crate::{ error, format_description::{modifier, Comp...
pub mod timestamp; use serde::de::Error as _; #[cfg(feature = "serde-human-readable")] use serde::ser::Error as _; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::error::ComponentRange; #[cfg(feature = "serde-human-readable")] use crate::{ error, format_description::{modifier, Comp...
eturn serializer.serialize_str(&match self.format(&UTC_OFFSET_FORMAT) { Ok(s) => s, Err(_) => return Err(S::Error::custom("failed formatting `UtcOffset`")), }); } ( self.whole_hours(), self.minutes_past_hour(), self.seconds...
eserializer<'a>>(deserializer: D) -> Result<Self, D::Error> { #[cfg(feature = "serde-human-readable")] if deserializer.is_human_readable() { return Self::parse(<&str>::deserialize(deserializer)?, &TIME_FORMAT) .map_err(error::Parse::to_invalid_serde_value::<D>); } ...
random
[ { "content": "/// Deserialize an `OffsetDateTime` from its Unix timestamp\n\npub fn deserialize<'a, D: Deserializer<'a>>(deserializer: D) -> Result<OffsetDateTime, D::Error> {\n\n i64::deserialize(deserializer).and_then(|timestamp| {\n\n OffsetDateTime::from_unix_timestamp(timestamp)\n\n .m...
Rust
crates/kitsune_p2p/direct/src/types/kdhash.rs
mhuesch/holochain
8cade151329117c40e47533449a2f842187c373a
use crate::*; use futures::future::{BoxFuture, FutureExt}; use kitsune_p2p::*; pub use kitsune_p2p_direct_api::KdHash; pub trait KdHashExt: Sized { fn to_kitsune_space(&self) -> Arc<KitsuneSpace>; fn from_kitsune_space(space: &KitsuneSpace) -> Self; fn to_kitsune_agent(&self) -> Arc<Kit...
use crate::*; use futures::future::{BoxFuture, FutureExt}; use kitsune_p2p::*; pub use kitsune_p2p_direct_api::KdHash; pub trait KdHashExt: Sized { fn to_kitsune_space(&self) -> Arc<KitsuneSpace>; fn from_kitsune_space(space: &KitsuneSpace) -> Self; fn to_kitsune_agent(&self) -> Arc<Kit...
out) }
signature: Arc<[u8; 64]>, ) -> BoxFuture<'static, bool>; fn from_data(data: &[u8]) -> BoxFuture<'static, KdResult<Self>>; fn from_coerced_pubkey(data: [u8; 32]) -> BoxFuture<'static, KdResult<Self>>; } impl KdHashExt for KdHash { fn to_kitsune_space(&self) -> Arc<KitsuneSpace> { ...
random
[ { "content": "/// internal REPR for holo hash\n\npub fn holo_hash_encode(data: &[u8]) -> String {\n\n format!(\"u{}\", base64::encode_config(data, base64::URL_SAFE_NO_PAD),)\n\n}\n\n\n", "file_path": "crates/holo_hash/src/encode.rs", "rank": 1, "score": 254914.76057821707 }, { "content": ...
Rust
src/theorem.rs
MDeiml/attomath
4aac4dad3cd776dd2cb1602aa930c04c315d5186
use std::{cmp::Ordering, num::Wrapping}; use crate::{ dvr::DVR, error::ProofError, expression::{ is_operator, ChainSubstitution, ShiftSubstitution, Substitution, VariableSubstitution, WholeSubstitution, }, statement::OwnedStatement, types::*, }; #[derive(PartialEq, Eq, PartialO...
use std::{cmp::Ordering, num::Wrapping}; use crate::{ dvr::DVR, error::ProofError, expression::{ is_operator, ChainSubstitution, ShiftSubstitution, Substitution, VariableSubstitution, WholeSubstitution, }, statement::OwnedStatement, types::*, }; #[derive(PartialEq, Eq, PartialO...
pub fn substitute<S: Substitution>(&self, substitution: &S) -> Result<Self, ProofError> { self.substitute_skip_assumption(substitution, None) } fn substitute_skip_assumption<S: Substitution>( &self, substitution: &S, skip_assumption: Opti...
assumptions .iter() .map(|st| st.expression.variables()) .flatten(), ) .filter(|symb| !is_operator(*symb)) .max() .unwrap_or(-1) }
function_block-function_prefixed
[ { "content": "/// Tests whether the given identifier is an operator.\n\n///\n\n/// Operators occupy the range `(Identifier::MIN ..= -1)`.\n\n/// The special value `Identifier::MIN` is also an operator.\n\n///\n\n/// # Example\n\n/// ```\n\n/// use attomath::{expression::is_operator, Identifier};\n\n///\n\n/// a...
Rust
libpf-rs/src/filter.rs
kckeiks/pf-rs
608fb83a3b583eb03af63a61d90d7dba0d70d296
use std::fs::File; use std::io::Write; use std::path::Path; use anyhow::Result; use tempfile::tempdir; use crate::bpf::{BPFLink, BPFObj}; use crate::bpfcode::{ DEFINES, EVAL_BOTH_IPVER, EVAL_NOOP, EVAL_ONLY_IP4, EVAL_ONLY_IP6, INCLUDE_HEADERS, IP4RULES_MAPS, IP4_EVAL_FUNCS, IP6RULES_MAPS, IP6_EVAL_FUNCS, PARS...
use std::fs::File; use std::io::Write; use std::path::Path; use anyhow::Result; use tempfile::tempdir; use crate::bpf::{BPFLink, BPFObj}; use crate::bpfcode::{ DEFINES, EVAL_BOTH_IPVER, EVAL_NOOP, EVAL_ONLY_IP4, EVAL_ONLY_IP6, INCLUDE_HEADERS, IP4RULES_MAPS, IP4_EVAL_FUNCS, IP6RULES_MAPS, IP6_EVAL_FUNCS, PARS...
.map_err(|e| Error::Internal(e.to_string()))?; } let link = bpf_obj .attach_prog(ifindex) .map_err(|e| Error::Internal(e.to_string()))?; Ok(link) } pub fn generate_src(self) -> Result<()> { let filename = "pfdebug"; let ...
.update_map("ipv4_rules", &index, &initial_value, 0) .map_err(|e| Error::Internal(e.to_string()))?; } for (i, rule) in self.ipv6_rules.into_iter().enumerate() { let initial_value = bincode2::serialize(&rule).map_err(|e| Error::Internal(e.to_st...
random
[ { "content": "pub fn load_filter(rules: Vec<Rule>, ifindex: i32) -> Result<BPFLink> {\n\n let mut f = Filter::new();\n\n for r in rules.into_iter() {\n\n f.add_rule(r);\n\n }\n\n Ok(f.load_on(ifindex)?)\n\n}\n\n\n", "file_path": "pf-rs/src/main.rs", "rank": 0, "score": 148013.1963...
Rust
src/bin/wasmtime.rs
erights/wasmtime
a5823896b70aab5f7675c5ff7651e37324c88262
#![deny( missing_docs, trivial_numeric_casts, unused_extern_crates, unstable_features )] #![warn(unused_import_braces)] #![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../clippy.toml")))] #![cfg_attr( feature = "cargo-clippy", allow(clippy::new_without_default, clippy::new_without_d...
#![deny( missing_docs, trivial_numeric_casts, unused_extern_crates, unstable_features )] #![warn(unused_import_braces)] #![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../clippy.toml")))] #![cfg_attr( feature = "cargo-clippy", allow(clippy::new_without_default, clippy::new_without_d...
let mut flag_builder = settings::builder(); let mut features: Features = Default::default(); flag_builder.enable("avoid_div_traps")?; let debug_info = args.flag_g; if cfg!(debug_assertions) { flag_builder.enable("enable_verifier")?; } if args.flag_enabl...
if !errors.is_empty() { eprintln!("Cache initialization failed. Errors:"); for e in errors { eprintln!("-> {}", e); } exit(1); }
if_condition
[ { "content": "fn write_stats_file(path: &Path, stats: &ModuleCacheStatistics) -> bool {\n\n toml::to_string_pretty(&stats)\n\n .map_err(|err| {\n\n warn!(\n\n \"Failed to serialize stats file, path: {}, err: {}\",\n\n path.display(),\n\n err\n\n ...
Rust
src/io/read/take.rs
mvucenovic/async-std
98c79f4ff90e92de0ebec103709c9c41badc3dbd
use std::cmp; use std::pin::Pin; use crate::io::{self, BufRead, Read}; use crate::task::{Context, Poll}; #[derive(Debug)] pub struct Take<T> { pub(crate) inner: T, pub(crate) limit: u64, } impl<T> Take<T> { ...
use std::cmp; use std::pin::Pin; use crate::io::{self, BufRead, Read}; use crate::task::{Context, Poll}; #[derive(Debug)] pub struct Take<T> { pub(crate) inner: T, pub(crate) limit: u64, } impl<T> Take<T> { ...
impl<T: BufRead + Unpin> BufRead for Take<T> { fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> { let Self { inner, limit } = unsafe { self.get_unchecked_mut() }; let inner = unsafe { Pin::new_unchecked(inner) }; if *limit == 0 { return P...
pub fn take_read_internal<R: Read + ?Sized>( mut rd: Pin<&mut R>, cx: &mut Context<'_>, buf: &mut [u8], limit: &mut u64, ) -> Poll<io::Result<usize>> { if *limit == 0 { return Poll::Ready(Ok(0)); } let max = cmp::min(buf.len() as u64, *limit) as usize; match futures_core::...
function_block-full_function
[ { "content": "pub fn read_line_internal<R: BufRead + ?Sized>(\n\n reader: Pin<&mut R>,\n\n cx: &mut Context<'_>,\n\n buf: &mut String,\n\n bytes: &mut Vec<u8>,\n\n read: &mut usize,\n\n) -> Poll<io::Result<usize>> {\n\n let ret = futures_core::ready!(read_until_internal(reader, cx, b'\\n', byt...
Rust
src/simulation.rs
Phraeyll/rballistics-flat
451ec376bd22f98059d5dd22c05896d9b458133d
use crate::{ consts::{FRAC_PI_2, PI}, error::{Error, Result}, my_quantity, projectiles::ProjectileImpl, units::{ celsius, fahrenheit, foot_per_second, grain, inch, inch_of_mercury, kelvin, kilogram, meter, meter_per_second, meter_per_second_squared, mile_per_hour, pascal, radian, se...
use crate::{ consts::{FRAC_PI_2, PI}, error::{Error, Result}, my_quantity, projectiles::ProjectileImpl, units::{ celsius, fahrenheit, foot_per_second, grain, inch, inch_of_mercury, kelvin, kilogram, meter, meter_per_second, meter_per_second_squared, mile_per_hour, pascal, radian, se...
pub fn set_wind_angle(mut self, value: Angle) -> Result<Self> { let min = Angle::new::<radian>(-2.0 * PI); let max = Angle::new::<radian>(2.0 * PI); if value >= min && value <= max { self.builder.wind.yaw = value; Ok(self) } else { Err(Error::OutO...
lt<Self> { if value.is_sign_positive() { self.builder.wind.velocity = value; Ok(self) } else { Err(Error::PositiveExpected(value.get::<meter_per_second>())) } }
function_block-function_prefixed
[ { "content": "pub fn table() -> NumericMap {\n\n float_btree_map![\n\n 0.00 => 0.1710,\n\n 0.05 => 0.1719,\n\n 0.10 => 0.1727,\n\n 0.15 => 0.1732,\n\n 0.20 => 0.1734,\n\n 0.25 => 0.1730,\n\n 0.30 => 0.1718,\n\n 0.35 => 0.1696,\n\n 0.40 =...
Rust
src/stream.rs
jws121295/dansible
4c32335b048560352135480ab0216ff5be6bd8fa
use byteorder::{BigEndian, ByteOrder, ReadBytesExt}; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io::{Cursor, Seek, SeekFrom}; use session::{Session, PacketHandler}; pub enum Response<H, S = H> { Continue(H), Spawn(S), Close, } impl <H: Handler + 'static> Response<H> { ...
use byteorder::{BigEndian, ByteOrder, ReadBytesExt}; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::io::{Cursor, Seek, SeekFrom}; use session::{Session, PacketHandler}; pub enum Response<H, S = H> { Continue(H), Spawn(S), Close, } impl <H: Handler + 'static> Response<H> { ...
} impl PacketHandler for StreamManager { fn handle(&mut self, cmd: u8, data: Vec<u8>, session: &Session) { let id: ChannelId = BigEndian::read_u16(&data[0..2]); let spawn = if let Entry::Occupied(mut entry) = self.channels.entry(id) { if let Some(channel) = entry.get_mut().take() { ...
pub fn create(&mut self, handler: Box<Handler>, session: &Session) { let channel_id = self.next_id; self.next_id += 1; trace!("allocated stream {}", channel_id); match handler.box_on_create(channel_id, session) { Response::Continue(handler) => { self.channel...
function_block-full_function
[ { "content": "pub trait Handler : Sized + Send + 'static {\n\n fn on_header(self, header_id: u8, header_data: &[u8], session: &Session) -> Response<Self>;\n\n fn on_data(self, offset: usize, data: &[u8], session: &Session) -> Response<Self>;\n\n fn on_eof(self, session: &Session) -> Response<Self>;\n\n...
Rust
butane/tests/common/pg.rs
DimmKG/butane
fcf9dcddb3e55f827daa9f54a6f276a9fce84903
use butane::db::{Backend, Connection, ConnectionSpec}; use once_cell::sync::Lazy; use std::io::{BufRead, BufReader, Read, Write}; use std::path::PathBuf; use std::process::{ChildStderr, Command, Stdio}; use uuid_for_test::Uuid; pub fn pg_connection() -> (Connection, PgSetupData) { let backend = butane::db::get_bac...
use butane::db::{Backend, Connection, ConnectionSpec}; use once_cell::sync::Lazy; use std::io::{BufRead, BufReader, Read, Write}; use std::path::PathBuf; use std::process::{ChildStderr, Command, Stdio}; use uuid_for_test::Uuid; pub fn pg_connection() -> (Connection, PgSetupData) { let backend = butane::db::get_bac...
} eprintln!("createdtmp server!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); PgServerState { dir, sockdir, proc, stderr, } } static TMP_SERVER: Lazy<PgServerState> = Lazy::new(|| create_tmp_server()); pub fn pg_setup() -> PgSetupData { eprintln!("pg_setup"); ...
if proc.try_wait().unwrap().is_some() { buf.clear(); stderr.read_to_string(&mut buf).unwrap(); eprint!("{}", buf); panic!("postgres process died"); }
if_condition
[ { "content": "pub fn sql_order(order: &[Order], w: &mut impl Write) {\n\n write!(w, \" ORDER BY \").unwrap();\n\n order.iter().fold(\"\", |sep, o| {\n\n let sql_dir = match o.direction {\n\n OrderDirection::Ascending => \"ASC\",\n\n OrderDirection::Descending => \"DESC\",\n\n ...
Rust
pretend/examples/responses.rs
orzogc/pretend
75824a5638b38e93bb9fe4cf35d2a59faf1053cc
use pretend::{pretend, Json, JsonResult, Pretend, Response, Result, Url}; use pretend_reqwest::Client; use serde::Deserialize; #[derive(Clone, Debug, Deserialize)] struct Contributor { login: String, } type Contributors = Vec<Contributor>; #[derive(Clone, Debug, Deserialize)] struct GithubError { message: St...
use pretend::{pretend, Json, JsonResult, Pretend, Response, Result, Url}; use pretend_reqwest::Client; use serde::Deserialize; #[derive(Clone, Debug, Deserialize)] struct Contributor { login: String, } type Contributors = Vec<Contributor>; #[derive(Clone, Debug, Deserialize)] struct GithubError { message: St...
d.json_result_response("pretend").await.unwrap(); println!("HTTP {}, {:?}", result.status(), result.body()); let result = pretend.string("non-existing").await; assert!(result.is_err()); let result = pretend.bytes("non-existing").await; assert!(result.is_err()); let result = pretend...
function_block-function_prefixed
[ { "content": "fn create_pretend() -> impl HttpBin {\n\n let url = Url::parse(\"https://httpbin.org\").unwrap();\n\n Pretend::for_client(Client::default()).with_url(url)\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n let pretend = create_pretend();\n\n\n\n let result = pretend.post_string_ref(\"...
Rust
src/state.rs
virome/amethyst
f6cbdfe6e5c38838190e59a35b6e6d35115af0cb
use amethyst_input::is_close_requested; use ecs::prelude::World; use {GameData, StateEvent}; pub struct StateData<'a, T> where T: 'a, { pub world: &'a mut World, pub data: &'a mut T, } impl<'a, T> StateData<'a, T> where T: 'a, { pub fn new(world: &'a mut World, data: &'a mut T) ->...
use amethyst_input::is_close_requested; use ecs::prelude::World; use {GameData, StateEvent}; pub struct StateData<'a, T> where T: 'a, { pub world: &'a mut World, pub data: &'a mut T, } impl<'a, T> StateData<'a, T> where T: 'a, { pub fn new(world: &'a mut World, data: &'a mut T) ->...
pub fn update(&mut self, data: StateData<T>) { let StateData { world, data } = data; if self.running { let trans = match self.state_stack.last_mut() { Some(state) => state.update(StateData { world, data }), None => Trans::None, }; ...
pub fn fixed_update(&mut self, data: StateData<T>) { let StateData { world, data } = data; if self.running { let trans = match self.state_stack.last_mut() { Some(state) => state.fixed_update(StateData { world, data }), None => Trans::None, }; ...
function_block-full_function
[ { "content": "/// Master trait used to define animation sampling on a component\n\npub trait AnimationSampling: Send + Sync + 'static + for<'b> ApplyData<'b> {\n\n /// The interpolation primitive\n\n type Primitive: InterpolationPrimitive + Clone + Copy + Send + Sync + 'static;\n\n /// An independent g...
Rust
src/scene/mesh/vertex.rs
jackos/Fyrox
4b293733bda8e1a0a774aaf82554ac8930afdd8b
use crate::core::visitor::{Visit, VisitResult, Visitor}; use crate::{ core::algebra::{Vector2, Vector3, Vector4}, scene::mesh::buffer::{ VertexAttributeDataType, VertexAttributeDescriptor, VertexAttributeUsage, }, }; use std::hash::{Hash, Hasher}; #[derive(Copy, Clone, Debug, Default)] #[repr(C)]...
use crate::core::visitor::{Visit, VisitResult, Visitor}; use crate::{ core::algebra::{Vector2, Vector3, Vector4}, scene::mesh::buffer::{ VertexAttributeDataType, VertexAttributeDescriptor, VertexAttributeUsage, }, }; use std::hash::{Hash, Hasher}; #[derive(Copy, Clone, Debug, Default)] #[repr(C)]...
visitor)?; self.bone_indices[1].visit("BoneIndex1", visitor)?; self.bone_indices[2].visit("BoneIndex2", visitor)?; self.bone_indices[3].visit("BoneIndex3", visitor)?; visitor.leave_region() } } impl OldVertex { pub fn layout() -> &'static [VertexAttributeDescriptor] { ...
[1].visit("Weight1", visitor)?; self.bone_weights[2].visit("Weight2", visitor)?; self.bone_weights[3].visit("Weight3", visitor)?; self.bone_indices[0].visit("BoneIndex0",
function_block-random_span
[ { "content": "/// Performs hashing of a sized value by interpreting it as raw memory.\n\npub fn hash_as_bytes<T: Sized, H: Hasher>(value: &T, hasher: &mut H) {\n\n hasher.write(value_as_u8_slice(value))\n\n}\n", "file_path": "src/utils/mod.rs", "rank": 0, "score": 527698.0130796023 }, { "...
Rust
flare-agent/src/profile/tree.rs
kylixs/flare-profiler
dd27371476b1326a50b1d753a5a6e9bc4cf7c67b
use std::collections::HashMap; use std::rc::*; use std::borrow::Cow; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::sync::RwLock; use std::sync::Arc; use time::Duration; use thread::*; use log::{debug, info, warn}; use native::{JavaLong, JavaMethod}; use std::collections...
use std::collections::HashMap; use std::rc::*; use std::borrow::Cow; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::sync::RwLock; use std::sync::Arc; use time::Duration; use thread::*; use log::{debug, info, warn}; use native::{JavaLong, JavaMethod}; use std::collections...
pub fn reset_top_call_stack_node(&mut self) { self.top_call_stack_node = self.root_node; } pub fn begin_call(&mut self, method_id: &JavaMethod) -> bool { let topNode = self.get_top_node(); match topNode.find_child(method_id) { Some(child_id) => { ...
r) -> CallStackTree { CallStackTree { nodes: vec![TreeNode::newRootNode(thread_name)], root_node: NodeId { index: 0 }, top_call_stack_node: NodeId { index: 0 }, total_duration: 0, thread_id: thread_id } }
function_block-function_prefixed
[ { "content": "fn get_stack_traces(jvmenv: &Box<Environment>, thread_info_map: &mut HashMap<JavaLong, ThreadInfo>, update_cpu_time: bool) -> Result<Vec<JavaStackTrace>, NativeError> {\n\n let mut stack_traces = vec![];\n\n match jvmenv.get_all_threads() {\n\n Err(e) => {\n\n println!(\"ge...
Rust
src/arch/intel/interrupt/x2apic/local_apic.rs
VenmoTools/libarch
589bd07a2fdcd3dfc16adbbb8f6c5d720fd3cb0c
use bit_field::BitField; use crate::arch::intel::chips::flags::LocalAPICFlags; use crate::arch::intel::interrupt::ApicInfo; use crate::arch::intel::interrupt::x2apic::consts::*; use crate::arch::intel::interrupt::x2apic::register::{IpiAllShorthand, IpiDeliveryMode, IpiDestMode, LocalApicRegisters, TimerDivide, TimerM...
use bit_field::BitField; use crate::arch::intel::chips::flags::LocalAPICFlags; use crate::arch::intel::interrupt::ApicInfo; use crate::arch::intel::interrupt::x2apic::consts::*; use crate::arch::intel::interrupt::x2apic::register::{IpiAllShorthand, IpiDeliveryMode, IpiDestMode, LocalApicRegisters, TimerDivide, TimerM...
pub unsafe fn send_sipi(&mut self, vector: u8, dest: u32) { let mut icr_val = self.format_icr(vector, IpiDeliveryMode::StartUp); icr_val.set_bits(ICR_DESTINATION, u64::from(dest)); self.regs.write_icr(icr_val); } pub unsafe fn send_sipi_all(&mut self, vector: u8) { ...
let mut icr_val = self.format_icr(0, IpiDeliveryMode::NonMaskable); icr_val.set_bits(ICR_DEST_SHORTHAND, who.into()); self.regs.write_icr(icr_val); }
function_block-function_prefix_line
[ { "content": "// Gets the upper segment selector for `irq`\n\npub fn hi(irq: u8) -> u32 {\n\n lo(irq) + 1\n\n}\n\n\n\n\n\nimpl IrqMode {\n\n pub(super) fn as_u32(self) -> u32 {\n\n self as u32\n\n }\n\n}\n\n\n\n/// The IOAPIC structure.\n\n#[derive(Debug)]\n\npub struct IoApic {\n\n regs: IoA...
Rust
src/server/mod.rs
Twixes/metrobaza
edc5bfa8080b91fffdf13276ec2f79d340582963
use crate::config; use crate::constructs::components::Validatable; use crate::executor::{ExecutorPayload, QueryResult}; use crate::sql::parse_statement; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Request, Response, Server, StatusCode}; use serde::{ser::SerializeMap, Serialize, Serializ...
use crate::config; use crate::constructs::components::Validatable; use crate::executor::{ExecutorPayload, QueryResult}; use crate::sql::parse_statement; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Request, Response, Server, StatusCode}; use serde::{ser::SerializeMap, Serialize, Serializ...
) .with_graceful_shutdown(shutdown_signal()); info!("👂 Server listening on {}...", tcp_listen_address); if let Err(e) = server.await { error!("‼️ Encountered server error: {}", e); } else { debug!("⏹ Server no longer listening"); } }
make_service_fn(move |_conn| { let executor_tx = executor_tx.clone(); async move { Ok::<_, convert::Infallible>(service_fn(move |req| echo(executor_tx.clone(), req))) } })
call_expression
[ { "content": "pub fn parse_statement(input: &str) -> Result<Statement, SyntaxError> {\n\n let tokens = tokenize_statement(input);\n\n let ExpectOk {\n\n rest,\n\n outcome: found_token_first,\n\n ..\n\n } = expect_next_token(\n\n &tokens,\n\n &format!(\"{} or {}\", Key...
Rust
crates/core/src/config/mod.rs
seank-com/ajour
b4f29e4b7526a91b03e7e73388dc2f5966950968
use crate::catalog; use crate::error::FilesystemError; use crate::repository::CompressionFormat; use glob::MatchOptions; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::fs::create_dir_all; use std::path::{Path, PathBuf}; mod addons; mod wow; use c...
use crate::catalog; use crate::error::FilesystemError; use crate::repository::CompressionFormat; use glob::MatchOptions; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt::{self, Display, Formatter}; use std::fs::create_dir_all; use std::path::{Path, PathBuf}; mod addons; mod wow; use c...
} #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Hash, PartialOrd, Ord)] pub enum Language { Czech, Norwegian, English, Danish, German, French, Hungarian, Portuguese, Russian, Slovak, Swedish, Spanish, Turkish, Ukrainian, } impl std::fmt::D...
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let s = match self { SelfUpdateChannel::Stable => "Stable", SelfUpdateChannel::Beta => "Beta", }; write!(f, "{}", s) }
function_block-full_function
[ { "content": "pub fn path_add(path: PathBuf, flavor: Option<Flavor>) -> Result<()> {\n\n task::block_on(async {\n\n log::debug!(\"Adding {:?} from {:?} to known directories\", flavor, &path);\n\n let mut config = load_config().await?;\n\n config.add_wow_directories(path, flavor);\n\n ...
Rust
src/parsers/apache2/mod.rs
u-siem/usiem-apache-httpd
c19d21c8fe0bacb86ff6eebf9c4e0e708e7d8714
use chrono::prelude::{TimeZone, Utc}; use std::borrow::Cow; use usiem::components::common::LogParsingError; use usiem::events::common::{HttpMethod, WebProtocol}; use usiem::events::field::{SiemField, SiemIp}; use usiem::events::webserver::{WebServerEvent, WebServerOutcome}; use usiem::events::{SiemEvent, SiemLog}; pub...
use chrono::prelude::{TimeZone, Utc}; use std::borrow::Cow; use usiem::components::common::LogParsingError; use usiem::events::common::{HttpMethod, WebProtocol}; use usiem::events::field::{SiemField, SiemIp}; use usiem::events::webserver::{WebServerEvent, WebServerOutcome}; use usiem::events::{SiemEvent, SiemLog}; pub...
pub fn extract_http_content<'a>( message: &'a str, ) -> Result<(&'a str, &'a str, &'a str), &'static str> { let mut splited = message.split(' '); let method = match splited.next() { Some(mt) => mt, None => return Err("No method"), }; let url = match splited.next() { Some(mt...
let proto = match version.find('/') { Some(p) => &version[..p], None => version, }; match proto { "HTTP" => WebProtocol::HTTP, "WS" => WebProtocol::WS, "WSS" => WebProtocol::WSS, "FTP" => WebProtocol::FTP, _ => WebProtocol::UNKNOWN(proto.to_uppercase()), ...
function_block-function_prefix_line
[ { "content": "/// Always use JSON format. Easy ato process and with more information.\n\npub fn parse_log_json(mut log: SiemLog) -> Result<SiemLog, LogParsingError> {\n\n let mod_log = match log.event() {\n\n SiemEvent::Unknown => {\n\n //Check JSON and extract\n\n let log_line =...
Rust
src/http/ctr.rs
zaksabeast/libctr-rs
556cf4857866db512ae415fd33f17131178ab465
use super::{ get_httpc_service_raw_handle, httpc_add_post_data_ascii, httpc_add_request_header_field, httpc_begin_request, httpc_create_context, httpc_initialize_connection_session, httpc_receive_data_with_timeout, httpc_set_proxy_default, httpc_set_socket_buffer_size, DefaultRootCert, HttpContextHandle...
use super::{ get_httpc_service_raw_handle, httpc_add_post_data_ascii, httpc_add_request_header_field, httpc_begin_request, httpc_create_context, httpc_initialize_connection_session, httpc_receive_data_with_timeout, httpc_set_proxy_default, httpc_set_socket_buffer_size, DefaultRootCert, HttpContextHandle...
pub fn set_client_cert_default(&self) -> CtrResult<()> { let mut command = ThreadCommandBuilder::new(0x28u16); unsafe { command.push(self.context_handle.get_raw()) }; command.push(0x40u32); let mut parser = command.build().send_sync_request(&self.session_handle)?; ...
pub fn add_default_cert(&self, cert: DefaultRootCert) -> CtrResult<()> { let mut command = ThreadCommandBuilder::new(0x25u16); unsafe { command.push(self.context_handle.get_raw()) }; command.push(cert); let mut parser = command.build().send_sync_request(&self.session_handle)?; ...
function_block-full_function
[ { "content": "#[cfg_attr(not(target_os = \"horizon\"), mocktopus::macros::mockable)]\n\npub fn get_service_handle_direct(_name: &str) -> CtrResult<Handle> {\n\n Ok(0.into())\n\n}\n", "file_path": "src/srv/mock.rs", "rank": 0, "score": 195878.7015791129 }, { "content": "pub fn get_service_...
Rust
vendor/aho-corasick/src/packed/pattern.rs
47565647456/evtx
fbb2a713d335f5208bb6675f4f158babd6f2f389
use std::cmp; use std::fmt; use std::mem; use std::u16; use std::usize; use crate::packed::api::MatchKind; pub type PatternID = u16; #[derive(Clone, Debug)] pub struct Patterns { kind: MatchKind, by_id: Vec<Vec<u8>>, order: Vec<PatternID>, ...
use std::cmp; use std::fmt; use std::mem; use std::u16; use std::usize; use crate::packed::api::MatchKind; pub type PatternID = u16; #[derive(Clone, Debug)] pub struct Patterns { kind: MatchKind, by_id: Vec<Vec<u8>>, order: Vec<PatternID>, ...
unreachable!(), } } pub fn len(&self) -> usize { self.by_id.len() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn heap_bytes(&self) -> usize { self.order.len() * mem::size_of::<PatternID>() + self.by_id.len(...
est => { let (order, by_id) = (&mut self.order, &mut self.by_id); order.sort_by(|&id1, &id2| { by_id[id1 as usize] .len() .cmp(&by_id[id2 as usize].len()) .reverse() }); ...
function_block-random_span
[ { "content": "#[inline]\n\npub fn checksum_ieee(data: &[u8]) -> u32 {\n\n let mut hasher = Hasher::new();\n\n hasher.update(data);\n\n hasher.finalize()\n\n}\n\n\n\n// Rust runs the tests concurrently, so unless we synchronize logging access\n\n// it will crash when attempting to run `cargo test` with ...
Rust
examples/compute/main.rs
hasenbanck/asche
a205c4364b9e425d3bd6b1b73e12c949a51e1e18
use erupt::vk; use asche::{CommandBufferSemaphore, QueueConfiguration, Queues}; fn main() -> Result<(), asche::AscheError> { let event_loop = winit::event_loop::EventLoop::new(); let window = winit::window::WindowBuilder::new() .with_title("asche - compute example") .with_inner_size(winit...
use erupt::vk; use asche::{CommandBufferSemaphore, QueueConfiguration, Queues}; fn main() -> Result<(), asche::AscheError> { let event_loop = winit::event_loop::EventLoop::new(); let window = winit::window::WindowBuilder::new() .with_title("asche - compute example") .with_inner_size(winit...
t app = Application::new(device, compute_queues.pop().unwrap())?; app.compute()?; Ok(()) } #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] pub enum Lifetime { Buffer, } impl asche::Lifetime for Lifetime {} struct Application { device: asche::Device<Lifetime>, compute_queue: asche::ComputeQueu...
let instance = asche::Instance::new( &window, asche::InstanceConfiguration { app_name: "compute example", app_version: asche::Version { major: 1, minor: 0, patch: 0, }, engine_name: "engine example", ...
function_block-random_span
[ { "content": "fn main() -> Result<()> {\n\n let event_loop = winit::event_loop::EventLoop::new();\n\n let window = winit::window::WindowBuilder::new()\n\n .with_title(\"asche - raytracing example\")\n\n .with_inner_size(winit::dpi::PhysicalSize::new(1920, 1080))\n\n .build(&event_loop...
Rust
src/cargo/lib.rs
jakerr/cargo
f0762dfc1340c24ad87fa59027d5308c96867393
#![crate_name="cargo"] #![crate_type="rlib"] #![feature(macro_rules, phase)] #![feature(default_type_params)] #![deny(bad_style, unused)] extern crate libc; extern crate regex; extern crate serialize; extern crate term; extern crate time; #[phase(plugin)] extern crate regex_macros; #[phase(plugin, link)] extern crate...
#![crate_name="cargo"] #![crate_type="rlib"] #![feature(macro_rules, phase)] #![feature(default_type_params)] #![deny(bad_style, unused)] extern crate libc; extern crate regex; extern crate serialize; extern crate term; extern crate time; #[phase(plugin)] extern crate regex_macros; #[phase(plugin, link)] extern crate...
pub fn shell(verbose: bool) -> MultiShell<'static> { let tty = stderr_raw().isatty(); let stderr = box stderr() as Box<Writer>; let config = ShellConfig { color: true, verbose: verbose, tty: tty }; let err = Shell::create(stderr, config); let tty = stdout_raw().isatty(); let stdout = box std...
l) { match result { Err(e) => handle_error(e, shell), Ok(encodable) => { encodable.map(|encodable| { let encoded = json::encode(&encodable); println!("{}", encoded); }); } } }
function_block-function_prefixed
[ { "content": "pub fn upload_login(shell: &mut MultiShell, token: String) -> CargoResult<()> {\n\n let config = try!(Config::new(shell, None, None));\n\n let UploadConfig { host, token: _ } = try!(upload_configuration());\n\n let mut map = HashMap::new();\n\n let p = os::getcwd();\n\n match host {...
Rust
kernel/net/tcp_socket.rs
castarco/kerla
52b15dbfcbf537bdad5b982d4d5cae3a9c7ae743
use crate::{ arch::SpinLock, fs::{ inode::{FileLike, PollStatus}, opened_file::OpenOptions, }, net::{socket::SockAddr, RecvFromFlags}, user_buffer::UserBuffer, user_buffer::{UserBufReader, UserBufWriter, UserBufferMut}, }; use crate::{ arch::SpinLockGuard, result::{Errno,...
use crate::{ arch::SpinLock, fs::{ inode::{FileLike, PollStatus}, opened_file::OpenOptions, }, net::{socket::SockAddr, RecvFromFlags}, user_buffer::UserBuffer, user_buffer::{UserBufReader, UserBufWriter, UserBufferMut}, }; use crate::{ arch::SpinLockGuard, result::{Errno,...
fn getpeername(&self) -> Result<SockAddr> { let endpoint = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .remote_endpoint(); if endpoint.addr.is_unspecified() { return Err(Errno::ENOTCONN.into()); } Ok(endpoint.int...
fn getsockname(&self) -> Result<SockAddr> { let endpoint = SOCKETS .lock() .get::<smoltcp::socket::TcpSocket>(self.handle) .local_endpoint(); if endpoint.addr.is_unspecified() { return Err(Errno::ENOTCONN.into()); } Ok(endpoint.into()) ...
function_block-full_function
[ { "content": "pub fn read_secure_random(buf: UserBufferMut<'_>) -> Result<usize> {\n\n // TODO: Implement arch-agnostic CRNG which does not fully depends on RDRAND.\n\n\n\n UserBufWriter::from(buf).write_with(|slice| {\n\n let valid = unsafe { rdrand_slice(slice) };\n\n if valid {\n\n ...
Rust
dao_factory/lib.rs
RainbowcityFoundation/RainbowDAO-Protocol-Ink-milestone_2
82757d337bea22dcb8e08b4759c47ec02d67a140
#![cfg_attr(not(feature = "std"), no_std)] #![feature(const_fn_trait_bound)] extern crate alloc; use ink_lang as ink; #[allow(unused_imports)] #[ink::contract] mod dao_factory { use alloc::string::String; use ink_prelude::vec::Vec; use ink_prelude::collections::BTreeMap; use ink_storage::{ ...
#![cfg_attr(not(feature = "std"), no_std)] #![feature(const_fn_trait_bound)] extern crate alloc; use ink_lang as ink; #[allow(unused_imports)] #[ink::contract] mod dao_factory { use alloc::string::String; use ink_prelude::vec::Vec; use ink_prelude::collections::BTreeMap; use ink_storage::{ ...
shMap::new(), instance_map_by_owner: StorageHashMap::new(), } } #[ink(message)] pub fn init_factory (&mut self, template_code_hash: Hash, version:u128) -> bool { let salt = version.to_le_bytes(); le...
erive(Debug)] pub struct DAOInstance { id: u64, owner: AccountId, size: u64, name: String, logo: String, desc: String, dao_manager: DAOManager, dao_manager_addr: AccountId, } #[ink(storage)] pu...
random
[ { "content": "/// Returns a new dynamic storage allocation.\n\npub fn alloc() -> DynamicAllocation {\n\n init::on_instance(DynamicAllocator::alloc)\n\n}\n\n\n", "file_path": "ink/crates/storage/src/alloc/mod.rs", "rank": 0, "score": 228000.94545688984 }, { "content": "/// Implemented by t...
Rust
src/wallet/state/log.rs
SebastienGllmt/cardano-cli
2470fe2dcb036226ade6f8c80a56d0610a623767
use storage_units::{append, utils::{serialize, lock::{self, Lock}}}; use std::{path::{PathBuf}, fmt, result, io::{self, Read, Write}, error}; use cardano::{block::{BlockDate, HeaderHash, types::EpochSlotId}}; use super::{ptr::{StatePtr}, utxo::{UTxO}}; use serde; use serde_yaml; #[derive(Debug)] pub enum Error { ...
use storage_units::{append, utils::{serialize, lock::{self, Lock}}}; use std::{path::{PathBuf}, fmt, result, io::{self, Read, Write}, error}; use cardano::{block::{BlockDate, HeaderHash, types::EpochSlotId}}; use super::{ptr::{StatePtr}, utxo::{UTxO}}; use serde; use serde_yaml; #[derive(Debug)] pub enum Error { ...
:utils::read_u32(&mut reader)?; let b = serialize::utils::read_u64(&mut reader)?; debug_assert!(b == 0u64); t }; match t { 1 => Ok(Log::Checkpoint(ptr)), 2 => { let utxo = serde_yaml::from_slice(reader).map_err(|e| ...
Error::LogFormatError(format!("log format error: {:?}", e)) })?; }, Log::SpentFund(_, utxo) => { serialize::utils::write_u32(&mut writer, 3)?; serialize::utils::write_u64(&mut writer, 0)?; serde_yaml::to_writer(&mut writer, utxo).ma...
random
[ { "content": "pub fn decrypt(password: &Password, data: &[u8]) -> Option<Vec<u8>> {\n\n let mut reader = data;\n\n let mut salt = [0;SALT_SIZE];\n\n let mut nonce = [0;NONCE_SIZE];\n\n let mut key = [0;KEY_SIZE];\n\n let len = data.len() - TAG_SIZE - SALT_SIZE - NONCE_SIZE;\n\n let mut b...
Rust
src/librustc/middle/typeck/check/writeback.rs
ehsanul/rust
7156ded5bcf6831a6da22688d08f71985fdc81df
use middle::pat_util; use middle::ty; use middle::typeck::astconv::AstConv; use middle::typeck::check::FnCtxt; use middle::typeck::infer::{force_all, resolve_all, resolve_region}; use middle::typeck::infer::resolve_type; use middle::typeck::infer; use middle::typeck::{MethodCall, MethodCallee}; use middle::typeck::{v...
use middle::pat_util; use middle::ty; use middle::typeck::astconv::AstConv; use middle::typeck::check::FnCtxt; use middle::typeck::infer::{force_all, resolve_all, resolve_region}; use middle::typeck::infer::resolve_type; use middle::typeck::infer; use middle::typeck::{MethodCall, MethodCallee}; use middle::typeck::{v...
{ Err(e) => { tcx.sess.span_err( sp, format!("cannot resolve bound for closure: \ {}", infer:...
resolve_region(fcx.infcx(), r, resolve_all | force_all)
call_expression
[ { "content": "pub fn type_is_region_ptr(fcx: @FnCtxt, sp: Span, typ: ty::t) -> bool {\n\n let typ_s = structurally_resolved_type(fcx, sp, typ);\n\n return ty::type_is_region_ptr(typ_s);\n\n}\n\n\n", "file_path": "src/librustc/middle/typeck/check/mod.rs", "rank": 0, "score": 681692.0685702388 ...
Rust
src/unixuser.rs
giganteous/webdav-server-rs
3fa3e9f63f9894d4658c9c1923f416f60acf8712
use std; use std::ffi::{CStr, OsStr}; use std::io; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use tokio::task::block_in_place; #[derive(Debug)] pub struct User { pub name: String, pub passwd: String, pub gecos: String, pub uid: u32, pub gid: u32, pub groups: Vec...
use std; use std::ffi::{CStr, OsStr}; use std::io; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use tokio::task::block_in_place; #[derive(Debug)] pub struct User { pub name: String, pub passwd: String, pub gecos: String, pub uid: u32, pub gid: u32, pub groups: Vec...
impl User { pub fn by_name(name: &str, with_groups: bool) -> Result<User, io::Error> { let mut buf = [0u8; 1024]; let mut pwd: libc::passwd = unsafe { std::mem::zeroed() }; let mut result: *mut libc::passwd = std::ptr::null_mut(); let cname = match std::ffi::CString::new(name) { ...
l); User { name: cs_name.to_string_lossy().into_owned(), passwd: cs_passwd.to_string_lossy().into_owned(), gecos: cs_gecos.to_string_lossy().into_owned(), dir: cs_dir.to_path_buf(), shell: cs_shell.to_path_buf(), uid: pwd.pw_uid, gid: pwd.pw...
function_block-function_prefixed
[]
Rust
tests/get_write_configurations_util/mod.rs
jakehamtexas/constance_rs
b923d35865c5d88eb7791efccf67f2b0e0b8d8e4
use std::collections::HashMap; pub mod dotnet_object_like_enum_buffer; pub mod dotnet_object_like_enum_with_description_buffer; pub mod dotnet_simple_enum_buffer; pub mod dotnet_simple_enum_with_description_buffer; pub mod dotnet_string_enum_buffer; pub mod dotnet_string_enum_with_description_buffer; pub mod rust_simpl...
use std::collections::HashMap; pub mod dotnet_object_like_enum_buffer; pub mod dotnet_object_like_enum_with_description_buffer; pub mod dotnet_simple_enum_buffer; pub mod dotnet_simple_enum_with_description_buffer; pub mod dotnet_string_enum_buffer; pub mod dotnet_string_enum_with_description_buffer; pub mod rust_simpl...
pub fn get_table_constants_for_object_like_with_description_buffer_test() -> Vec<TableConstant> { let mut map = HashMap::new(); map.insert( ValueWithDescription { value: "test1".to_string(), description: Some("description1".to_string()), }, vec![ ( ...
Column { name: "second".to_string(), data_type: NUMBER_TYPE.to_string(), }, "1".to_string(), ), ], ); map.insert( ValueWithDescription { value: "test2".to_string(), description: None, ...
function_block-function_prefix_line
[ { "content": "fn get_constructor_for_object_like(class_name: &str, columns: &Vec<&Column>) -> String {\n\n let constructor_first_line = format!(\"private {}(\", pascal_case(class_name));\n\n let args = columns\n\n .iter()\n\n .map(|Column { data_type, name }| {\n\n format!(\n\n ...
Rust
src/sinks/util/tcp.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::{ io::ErrorKind, net::SocketAddr, pin::Pin, task::{Context, Poll}, time::Duration, }; use async_trait::async_trait; use bytes::{Bytes, BytesMut}; use futures::{stream::BoxStream, task::noop_waker_ref, SinkExt, StreamExt}; use serde::{Deserialize, Serialize}; use snafu::{ResultExt, Snafu}; ...
use std::{ io::ErrorKind, net::SocketAddr, pin::Pin, task::{Context, Poll}, time::Duration, }; use async_trait::async_trait; use bytes::{Bytes, BytesMut}; use futures::{stream::BoxStream, task::noop_waker_ref, SinkExt, StreamExt}; use serde::{Deserialize, Serialize}; use snafu::{ResultExt, Snafu}; ...
} maybe_tls }) } async fn connect_backoff(&self) -> MaybeTlsStream<TcpStream> { let mut backoff = Self::fresh_backoff(); loop { match self.connect().await { Ok(socket) => { emit!(TcpSocketConnectionEst...
if let Err(error) = maybe_tls.set_send_buffer_bytes(send_buffer_bytes) { warn!(message = "Failed configuring send buffer size on TCP socket.", %error); }
if_condition
[ { "content": "pub trait TcpSource: Clone + Send + Sync + 'static\n\nwhere\n\n <<Self as TcpSource>::Decoder as tokio_util::codec::Decoder>::Item: std::marker::Send,\n\n{\n\n // Should be default: `std::io::Error`.\n\n // Right now this is unstable: https://github.com/rust-lang/rust/issues/29661\n\n ...
Rust
delsum-lib/src/fletcher/mod.rs
8051Enthusiast/delsum
5605cd8343cb8ba3133eea31610968cd3c6444d4
mod rev; use crate::bitnum::{BitNum, Modnum}; use crate::checksum::{CheckBuilderErr, Digest, LinearCheck}; use crate::endian::{Endian, WordSpec}; use crate::keyval::KeyValIter; use num_traits::{One, Zero}; pub use rev::reverse_fletcher; #[cfg(feature = "parallel")] pub use rev::reverse_fletcher_para; use std::fmt::Di...
mod rev; use crate::bitnum::{BitNum, Modnum}; use crate::checksum::{CheckBuilderErr, Digest, LinearCheck}; use crate::endian::{Endian, WordSpec}; use crate::keyval::KeyValIter; use num_traits::{One, Zero}; pub use rev::reverse_fletcher; #[cfg(feature = "parallel")] pub use rev::reverse_fletcher_para; use std::fmt::Di...
; let fletch_op = match current_key.as_str() { "width" => usize::from_str(&current_val).ok().map(|x| fletch.width(x)), "module" => Sum::from_hex(&current_val).ok().map(|x| fletch.module(x)), "init" => Sum::from_hex(&current_val).ok().map(|x| fletch.init(x)), ...
match x { Err(key) => return Err(CheckBuilderErr::MalformedString(key)), Ok(s) => s, }
if_condition
[ { "content": "fn glue_sum(mut s1: u64, mut s2: u64, width: usize, swap: bool) -> u128 {\n\n if swap {\n\n std::mem::swap(&mut s1, &mut s2);\n\n }\n\n (s1 as u128) | ((s2 as u128) << (width / 2))\n\n}\n\n\n", "file_path": "delsum-lib/src/fletcher/rev.rs", "rank": 0, "score": 242015.56...
Rust
src/r3_port_riscv/src/timer/cfg.rs
yvt/r3
cafe6078fa8a649a6e1c5969c625c2a127a91027
use r3::kernel::InterruptNum; #[macro_export] macro_rules! use_timer { (unsafe impl PortTimer for $ty:ty) => { const _: () = { use $crate::r3::{ kernel::{cfg::CfgBuilder, PortTimer, UTicks}, utils::Init, }; use $crate::r3_portkit::tickles...
use r3::kernel::InterruptNum; #[macro_export] macro_rules! use_timer { (unsafe impl PortTimer for $ty:ty) => { const _: () = { use $crate::r3::{ kernel::{cfg::CfgBuilder, PortTimer, UTicks}, utils::Init, }; use $crate::r3_portkit::tickles...
const RESET_MTIME: bool = true; const FREQUENCY: u64; const FREQUENCY_DENOMINATOR: u64 = 1; const HEADROOM: u32 = min128( Self::FREQUENCY as u128 * 60 / Self::FREQUENCY_DENOMINATOR as u128, 0x40000000, ) as u32; ...
UTicks) { unsafe { timer::imp::pend_tick_after::<Self>(tick_count_delta) } } } impl Timer for $ty { unsafe fn init() { unsafe { timer::imp::init::<Self>() } } } ...
random
[ { "content": "#[cfg(not(arm))]\n\nfn interrupt_free<R>(_: impl FnOnce() -> R) -> R {\n\n unreachable!();\n\n}\n\n\n", "file_path": "src/arm_semihosting/src/export.rs", "rank": 0, "score": 194965.27888413682 }, { "content": "#[cfg(not(target_arch = \"arm\"))]\n\nfn interrupt_free<T>(_: imp...
Rust
rain_server/src/governor/tasks/instance.rs
baajur/rain
477948554150760164c6fe48eac27bcf06c7933b
use chrono::{DateTime, Utc}; use futures::Future; use rain_core::{comm::*, errors::*}; use error_chain::bail; use governor::graph::{ExecutorRef, TaskRef, TaskState}; use governor::rpc::executor::data_output_from_spec; use governor::state::State; use governor::tasks; pub struct TaskInstance { task_ref: TaskRef, ...
use chrono::{DateTime, Utc}; use futures::Future; use rain_core::{comm::*, errors::*}; use error_chain::bail; use governor::graph::{ExecutorRef, TaskRef, TaskState}; use governor::rpc::executor::data_output_from_spec; use governor::state::State; use governor::tasks; pub struct TaskInstance { task_ref: TaskRef, ...
terminated", task.spec.id); task.set_failed("Task terminated by server".into()); } Err((e, _)) => { task.set_failed(e.description().to_string()); } }; O...
or_ref: ExecutorRef) -> Self { KillOnDrop { executor_ref: Some(executor_ref), } } pub fn deactive(&mut self) -> ExecutorRef { ::std::mem::replace(&mut self.executor_ref, None).unwrap() } } impl Drop for KillOnDrop { fn drop(&mut self) { if let Some(ref sw) =...
random
[]
Rust
src/lua_tables.rs
perdumonocle/pm_rlua
eb09eba488249f47aaba4709a49108526f939a22
use std::marker::PhantomData; use libc; use td_clua::{self, lua_State}; use LuaGuard; use LuaPush; use LuaRead; pub struct LuaTable { table: *mut lua_State, pop: i32, index: i32, } impl LuaRead for LuaTable { fn lua_read_with_pop(lua: *mut lua_State, index: i32, pop: i32) -> Option<LuaTable> { ...
use std::marker::PhantomData; use libc; use td_clua::{self, lua_State}; use LuaGuard; use LuaPush; use LuaRead; pub struct LuaTable { table: *mut lua_State, pop: i32, index: i32, } impl LuaRead for LuaTable { fn lua_read_with_pop(lua: *mut lua_State, index: i32, pop: i32) -> Option<LuaTable> { ...
} } pub struct LuaTableIterator<'t, K, V> { table: &'t mut LuaTable, finished: bool, marker: PhantomData<(K, V)>, } impl LuaTable { pub fn into_inner(self) -> *mut lua_State { self.table } pub fn iter<K, V>(&mut self) -> LuaTableIterator<K, V> { unsafe { td_clu...
if self.pop != 0 { unsafe { td_clua::lua_pop(self.table, self.pop); }; self.pop = 0; }
if_condition
[ { "content": "///\n\npub fn read_userdata<'t, T>(lua: *mut td_clua::lua_State, index: i32) -> Option<&'t mut T>\n\nwhere\n\n T: 'static + Any,\n\n{\n\n unsafe {\n\n let expected_typeid = format!(\"{:?}\", TypeId::of::<T>());\n\n let data_ptr = td_clua::lua_touserdata(lua, index);\n\n ...
Rust
tokens/src/tests_events.rs
ajuna-network/open-runtime-module-library
070457de18d26d2daed6abdfa57d8a951a525605
#![cfg(test)] use super::*; use frame_support::assert_ok; use mock::{Event, *}; #[test] fn pallet_multicurrency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiCurrency<AccountId>>::transfer(DOT, &ALICE, &B...
#![cfg(test)] use super::*; use frame_support::assert_ok; use mock::{Event, *}; #[test] fn pallet_multicurrency_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiCurrency<AccountId>>::transfer(DOT, &ALICE, &B...
] fn pallet_fungibles_unbalanced_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiReservableCurrency<AccountId>>::reserve(DOT, &ALICE, 50)); assert_ok!(<Tokens as fungibles::Unbalanced<AccountId>>::set_balance( DOT, &ALIC...
ed_deposit_events() { ExtBuilder::default() .balances(vec![(ALICE, DOT, 100), (BOB, DOT, 100)]) .build() .execute_with(|| { assert_ok!(<Tokens as MultiCurrencyExtended<AccountId>>::update_balance( DOT, &ALICE, 500 )); System::assert_last_event(Event::Tokens(crate::Event::Deposited { currency_id:...
random
[ { "content": "fn concrete_fungible(amount: u128) -> MultiAsset {\n\n\t(MOCK_CONCRETE_FUNGIBLE_ID, amount).into()\n\n}\n\n\n", "file_path": "unknown-tokens/src/tests.rs", "rank": 0, "score": 182153.9216231135 }, { "content": "fn abstract_fungible(amount: u128) -> MultiAsset {\n\n\t(mock_abstr...
Rust
alvr/common/src/audio.rs
zarik5/ALVR
7ed89fc8525647d058fa812af8be88f23f8a17a0
use crate::*; #[cfg(windows)] use std::ptr; #[cfg(windows)] use widestring::*; #[cfg(windows)] use winapi::{ shared::{winerror::*, wtypes::VT_LPWSTR}, um::{ combaseapi::*, coml2api::STGM_READ, functiondiscoverykeys_devpkey::PKEY_Device_FriendlyName, mmdeviceapi::*, objbase::CoInitialize...
use crate::*; #[cfg(windows)] use std::ptr; #[cfg(windows)] use widestring::*; #[cfg(windows)] use winapi::{ shared::{winerror::*, wtypes::VT_LPWSTR}, um::{ combaseapi::*, coml2api::STGM_READ, functiondiscoverykeys_devpkey::PKEY_Device_FriendlyName, mmdeviceapi::*, objbase::CoInitialize...
let hr = mm_device_collection.GetCount(&count); if FAILED(hr) { return trace_str!("IMMDeviceCollection::GetCount failed: hr = 0x{:08x}", hr); } debug!("Active render endpoints found: {}", count); debug!("DefaultDevice:{} ID:{}", default_name, default_id); for i in 0...
function_block-function_prefix_line
[ { "content": "#[cfg(windows)]\n\npub fn get_windows_device_id(device: &AudioDevice) -> StrResult<String> {\n\n unsafe {\n\n let mm_device = get_windows_device(device)?;\n\n\n\n let mut id_str_ptr = ptr::null_mut();\n\n mm_device.GetId(&mut id_str_ptr);\n\n let id_str = trace_err!(...
Rust
tests/tests.rs
zhiburt/bumpalo
38054c706cda77a07a07c3eda27bbeb6ee93a706
use bumpalo::Bump; use std::alloc::Layout; use std::mem; use std::usize; #[test] fn can_iterate_over_allocated_things() { let mut bump = Bump::new(); const MAX: u64 = 131_072; let mut chunk_ends = vec![]; let mut last = None; for i in 0..MAX { let this = bump.alloc(i); assert_eq!...
use bumpalo::Bump; use std::alloc::Layout; use std::mem; use std::usize; #[test] fn can_iterate_over_allocated_things() { let mut bump = Bump::new(); const MAX: u64 = 131_072; let mut chunk_ends = vec![]; let mut last = None; for i in 0..MAX { let this = bump.alloc(i); assert_eq!...
().copied() }); assert!(pushed_values.eq(iter.clone())); } } #[test] fn with_capacity_test() { with_capacity_helper(0u8..255); with_capacity_helper(0u16..10000); with_capacity_helper(0u32..10000); with_capacity_helper(0u64..10000); with_capacity_helper(0u128..10000); } #[test] ...
ign(size, align) { Err(e) => { eprintln!("Layout::from_size_align errored: {}", e); return; } Ok(l) => l, }; bump.alloc_layout(layout); } #[test] fn force_new_chunk_fits_well() { let b = Bump::new(); b.alloc_layout(Layout::from_si...
random
[ { "content": "fn size_align<T>() -> (usize, usize) {\n\n (mem::size_of::<T>(), mem::align_of::<T>())\n\n}\n\n\n\n/// The `AllocErr` error indicates an allocation failure\n\n/// that may be due to resource exhaustion or to\n\n/// something wrong when combining the given input arguments with this\n\n/// alloca...
Rust
artichoke-backend/src/convert/fixnum.rs
Talljoe/artichoke
36ed5eba078a9fbf3cb4d5c8f7407d0a773d2d6e
use std::convert::TryFrom; use crate::convert::{BoxIntoRubyError, UnboxRubyError}; use crate::core::{Convert, TryConvert}; use crate::exception::Exception; use crate::sys; use crate::types::{Int, Ruby, Rust}; use crate::value::Value; use crate::Artichoke; impl Convert<u8, Value> for Artichoke { #[inline] fn c...
use std::convert::TryFrom; use crate::convert::{BoxIntoRubyError, UnboxRubyError}; use crate::core::{Convert, TryConvert}; use crate::exception::Exception; use crate::sys; use crate::types::{Int, Ruby, Rust}; use crate::value::Value; use crate::Artichoke; impl Convert<u8, Value> for Artichoke { #[inline] fn c...
}
fn fixnum_to_usize() { let interp = crate::interpreter().unwrap(); let value = Convert::<_, Value>::convert(&interp, 100); let value = value.try_into::<usize>(&interp).unwrap(); assert_eq!(100, value); let value = Convert::<_, Value>::convert(&interp, -100); let value = v...
function_block-full_function
[ { "content": "#[cfg(feature = \"core-math-extra\")]\n\npub fn frexp(interp: &mut Artichoke, value: Value) -> Result<(Fp, Int), Exception> {\n\n let value = value_to_float(interp, value)?;\n\n let (fraction, exponent) = libm::frexp(value);\n\n Ok((fraction, exponent.into()))\n\n}\n\n\n", "file_path"...
Rust
garnet/bin/odu/src/file_target.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use { crate::common_operations::pwrite, crate::io_packet::{IoPacket, IoPacketType, TimeInterval}, crate::operations::{OperationType, PipelineStages}, crate::target::{Error, Target, TargetOps, TargetType}, log::debug, log::error, std::{ fs::{File, OpenOptions}, ops::Range, ...
use { crate::common_operations::pwrite, crate::io_packet::{IoPacket, IoPacketType, TimeInterval}, crate::operations::{OperationType, PipelineStages}, crate::target::{Error, Target, TargetOps, TargetType}, log::debug, log::error, std::{ fs::{File, OpenOptions}, ops::Range, ...
tionType::Write | OperationType::Exit => true, _ => { error!("verify for unsupported operation"); process::abort(); } } } fn start_instant(&self) -> Instant { self.start_instant } } #[cfg(test)] mod tests { use { crate::f...
seed: u64, io_offset_range: Range<u64>, target: TargetType, ) -> IoPacketType { Box::new(FileIoPacket::new(operation_type, seq, seed, io_offset_range, target)) } fn id(&self) -> u64 { self.target_unique_id } fn supported_ops() -> &'static TargetOps where ...
random
[]
Rust
src/raytracer/ray.rs
infinityb/rust-raytracer
4177c241c4630b822a308d982894134f0751d7d2
use std::f64::INFINITY; use raytracer::Intersection; use scene::Scene; use vec3::Vec3; #[cfg(test)] use geometry::prim::Prim; #[cfg(test)] use geometry::prims::Sphere; #[cfg(test)] use light::light::Light; #[cfg(test)] use material::materials::FlatMaterial; pub struct Ray { pub origin: Vec3, pub direction: Ve...
use std::f64::INFINITY; use raytracer::Intersection; use scene::Scene; use vec3::Vec3; #[cfg(test)] use geometry::prim::Prim; #[cfg(test)] use geometry::prims::Sphere; #[cfg(test)] use light::light::Light; #[cfg(test)] use material::materials::FlatMaterial; pub struct Ray { pub origin: Vec3, pub direction: Ve...
fn it_gets_the_nearest_hit() { let lights: Vec<Box<Light+Send+Sync>> = Vec::new(); let mut prims: Vec<Box<Prim+Send+Sync>> = Vec::new(); let mat = FlatMaterial { color: Vec3::one() }; let sphere_top = Sphere { center: Vec3::zero(), radius: 1.0, material: Box::new(mat.clone()), ...
function_block-full_function
[ { "content": "pub fn get_scene() -> Scene {\n\n let mut lights: Vec<Box<Light+Send+Sync>> = Vec::new();\n\n lights.push(Box::new(SphereLight { position: Vec3 { x: 8.0, y: 8.0, z: 0.0 }, color: Vec3 { x: 1.0, y: 0.8, z: 0.4}, radius: 0.5 }));\n\n lights.push(Box::new(SphereLight { position: Vec3 { x: 8....
Rust
relm4-examples/examples/grid_factory.rs
Hofer-Julian/relm4
bc8ea3f027a801126f767e93a3b04e20df4ca714
use gtk::prelude::{BoxExt, ButtonExt, GtkWindowExt}; use relm4::factory::{Factory, FactoryPrototype, FactoryVec, GridPosition}; use relm4::Sender; use relm4::*; struct AppWidgets { main: gtk::ApplicationWindow, gen_grid: gtk::Grid, } #[derive(Debug)] enum AppMsg { Add, Remove, Clicked(usize), } s...
use gtk::prelude::{BoxExt, ButtonExt, GtkWindowExt}; use relm4::factory::{Factory, FactoryPrototype, FactoryVec, GridPosition}; use relm4::Sender; use relm4::*; struct AppWidgets { main: gtk::ApplicationWindow, gen_grid: gtk::Grid, } #[derive(Debug)] enum AppMsg { Add, Remove, Clicked(usize), } s...
fn view(&mut self, model: &AppModel, sender: Sender<AppMsg>) { model.data.generate(&self.gen_grid, sender); } fn root_widget(&self) -> gtk::ApplicationWindow { self.main.clone() } } impl AppUpdate for AppModel { fn update(&mut self, msg: AppMsg, _components: &(), _sender: Sender<...
margin_top(5) .margin_start(5) .margin_bottom(5) .row_spacing(5) .column_spacing(5) .column_homogeneous(true) .build(); let add = gtk::Button::with_label("Add"); let remove = gtk::Button::with_label("Remove"); main_box.app...
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let model = AppModel {\n\n mode: AppMode::View,\n\n };\n\n let relm = RelmApp::new(model);\n\n relm.run();\n\n}\n", "file_path": "relm4-examples/examples/components.rs", "rank": 0, "score": 212890.8310617418 }, { "content": "fn main() {\n\n ...
Rust
src/elem/wrap/ymerge_wrap.rs
dbeck/minions_rs
b731c8c5c0e6f52013cb56f20a76ecccfe94dc7f
use lossyq::spsc::{Sender}; use super::super::super::{Task, Message, ChannelWrapper, ChannelId, SenderName, ReceiverChannelId, SenderChannelId, ChannelPosition }; use super::super::connectable::{ConnectableY}; use super::super::identified_input::{IdentifiedInput}; use super::super::counter::{OutputCounter, InputCount...
use lossyq::spsc::{Sender}; use super::super::super::{Task, Message, ChannelWrapper, ChannelId, SenderName, ReceiverChannelId, SenderChannelId, ChannelPosition }; use super::super::connectable::{ConnectableY}; use super::super::identified_input::{IdentifiedInput}; use super::super::counter::{OutputCounter, InputCount...
} else { match &self.input_b_rx { &ChannelWrapper::ConnectedReceiver(ref _channel_id, ref receiver, ref _sender_name) => { receiver.seqno() }, _ => 0 } } } } impl<InputValueA: Send, InputErrorA: Send, InputValueB: Send, InputErrorB: Send, OutputValue: ...
match &self.input_a_rx { &ChannelWrapper::ConnectedReceiver(ref _channel_id, ref receiver, ref _sender_name) => { receiver.seqno() }, _ => 0 }
if_condition
[ { "content": "pub fn new<InputValueA: Send, InputErrorA: Send,\n\n InputValueB: Send, InputErrorB: Send,\n\n OutputValue: Send, OutputError: Send>(\n\n name : &str,\n\n output_q_size : usize,\n\n ymerge : Box<YMerge<InputValueA=InputValueA, InputErrorA=Input...
Rust
src/level1.rs
DGriffin91/Bevy-BakedGI-Demo
b919d7fe6e4b6a472e2a41ff25d94c1c40966ce9
use bevy::prelude::*; use crate::custom_material::{ CustomMaterial, MaterialProperties, MaterialSetProp, MaterialTexture, }; use crate::emissive_material::EmissiveMaterial; pub fn setup_room( commands: &mut Commands, custom_materials: &mut Assets<CustomMaterial>, emissive_materials: &mut Assets<Emissi...
use bevy::prelude::*; use crate::custom_material::{ CustomMaterial, MaterialProperties, MaterialSetProp, MaterialTexture, }; use crate::emissive_material::EmissiveMaterial; pub fn setup_room( commands: &mut Commands, custom_materials: &mut Assets<CustomMaterial>, emissive_materials: &mut Assets<Emissi...
let objects_lightmap = MaterialTexture::new( asset_server, "textures/scene1/objects_lightmap.jpg", "objects_lightmap", ); let building_objects = asset_server.load("models/scene1/building.glb#Mesh0/Primitive0"); let material_properties = MaterialProperties { lightm...
let reflection_texture = MaterialTexture::new( asset_server, "textures/scene1/reflection.jpg", "reflection_texture", );
assignment_statement
[ { "content": "fn player(commands: &mut Commands) {\n\n commands.spawn_bundle(UnrealCameraBundle::new(\n\n UnrealCameraController::default(),\n\n PerspectiveCameraBundle::default(),\n\n Vec3::new(-30.0, 3.0, -3.0),\n\n Vec3::new(0.0, 3.0, -3.0),\n\n ));\n\n}\n\n\n", "file_pa...
Rust
diesel/src/pg/expression/array_comparison.rs
robertmaloney/diesel
332ba12617ff05e5077fc1879caf83fe2e7fd8ff
use std::marker::PhantomData; use backend::*; use expression::{AsExpression, Expression, SelectableExpression, NonAggregate}; use pg::{Pg, PgQueryBuilder}; use query_builder::*; use query_builder::debug::DebugQueryBuilder; use result::QueryResult; use types::{Array, HasSqlType}; pub fn any<ST, T>(vals: T) -> Any<T::E...
use std::marker::PhantomData; use backend::*; use expression::{AsExpression, Expression, SelectableExpression, NonAggregate}; use pg::{Pg, PgQueryBuilder}; use query_builder::*; use query_builder::debug::DebugQueryBuilder; use result::QueryResult; use types::{Array, HasSqlType}; pub fn any<ST, T>(vals: T) -> Any<T::E...
QS>, { } impl<Expr, ST> NonAggregate for Any<Expr, ST> where Expr: NonAggregate, Any<Expr, ST>: Expression, { } #[doc(hidden)] #[derive(Debug, Copy, Clone)] pub struct All<Expr, ST> { expr: Expr, _marker: PhantomData<ST>, } impl<Expr, ST> All<Expr, ST> { fn new(expr: Expr) -> Self { All {...
impl_query_id!(Any<Expr, ST>); impl<Expr, ST, QS> SelectableExpression<QS> for Any<Expr, ST> where Pg: HasSqlType<ST>, Any<Expr, ST>: Expression, Expr: SelectableExpression<
random
[ { "content": "pub trait ArrayExpressionMethods<ST>: Expression<SqlType=Array<ST>> + Sized {\n\n /// Compares two arrays for common elements, using the `&&` operator in\n\n /// the final SQL\n\n ///\n\n /// # Example\n\n ///\n\n /// ```rust\n\n /// # #[macro_use] extern crate diesel;\n\n ...
Rust
components/zcash_address/src/kind/unified/f4jumble.rs
MixinNetwork/librustzcash
9be36f3e54127fc2e6a30a70625eddfb12367d40
use blake2b_simd::{Params as Blake2bParams, OUTBYTES}; use std::cmp::min; use std::ops::RangeInclusive; #[cfg(test)] mod test_vectors; const VALID_LENGTH: RangeInclusive<usize> = 48..=16448; macro_rules! H_PERS { ( $i:expr ) => { [ 85, 65, 95, 70, 52, 74, 117, 109, 98, 108, 101, 95, 72, 95, $...
use blake2b_simd::{Params as Blake2bParams, OUTBYTES}; use std::cmp::min; use std::ops::RangeInclusive; #[cfg(test)] mod test_vectors; const VALID_LENGTH: RangeInclusive<usize> = 48..=16448; macro_rules! H_PERS { ( $i:expr ) => { [ 85, 65, 95, 70, 52, 74, 117, 109, 98, 108, 101, 95, 72, 95, $...
#[cfg(test)] mod tests { use proptest::collection::vec; use proptest::prelude::*; use super::{f4jumble, f4jumble_inv, test_vectors::test_vectors, VALID_LENGTH}; #[test] fn h_pers() { assert_eq!(&H_PERS!(7), b"UA_F4Jumble_H_\x07\x00"); } #[test] fn g_pers() { assert_e...
pub fn f4jumble_inv(c: &[u8]) -> Option<Vec<u8>> { if VALID_LENGTH.contains(&c.len()) { let hashes = Hashes::new(c.len()); let (c, d) = c.split_at(hashes.l_l); let y = xor(c, &hashes.h(1, d)); let x = xor(d, &hashes.g(1, &y)); let mut a = xor(&y, &hashes.h(0, &x)); l...
function_block-full_function
[ { "content": "/// Compute a parent node in the Sapling commitment tree given its two children.\n\npub fn merkle_hash(depth: usize, lhs: &[u8; 32], rhs: &[u8; 32]) -> [u8; 32] {\n\n let lhs = {\n\n let mut tmp = [false; 256];\n\n for (a, b) in tmp.iter_mut().zip(lhs.as_bits::<Lsb0>()) {\n\n ...
Rust
src/peer.rs
ckampfe/manix
fd1e5cf309b125dca6a17bf3fe67c8eff0a8d17d
use crate::peer_protocol; use crate::{signals, Begin, Index, InfoHash, Length, PeerId}; use futures_util::sink::SinkExt; use futures_util::StreamExt; use std::convert::TryInto; use tokio::time::{Interval, MissedTickBehavior}; use tracing::{debug, error, info, instrument}; #[derive(Debug)] pub(crate) struct PeerOptions...
use crate::peer_protocol; use crate::{signals, Begin, Index, InfoHash, Length, PeerId}; use futures_util::sink::SinkExt; use futures_util::StreamExt; use std::convert::TryInto; use tokio::time::{Interval, MissedTickBehavior}; use tracing::{debug, error, info, instrument}; #[derive(Debug)] pub(crate) struct PeerOptions...
#[instrument(skip(self))] async fn send_request( &mut self, index: Index, begin: Begin, length: Length, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Request { index, begin, length, }) ...
ol::Bitfield, ) -> Result<(), std::io::Error> { self.send_message(peer_protocol::Message::Bitfield { bitfield }) .await }
function_block-function_prefixed
[ { "content": "fn info_hash(bencode: &nom_bencode::Bencode) -> InfoHash {\n\n match bencode {\n\n nom_bencode::Bencode::Dictionary(d) => {\n\n let info = d.get(&b\"info\".to_vec()).unwrap();\n\n let encoded = info.encode();\n\n InfoHash(hash(&encoded))\n\n }\n\n ...
Rust
src/coords.rs
mabruzzo/nmea0183
fd1a2d8a62cbcb6f3a9aeecabae88f7b81e850eb
use core::convert::TryFrom; #[derive(Debug, PartialEq, Clone)] pub enum Hemisphere { North, South, East, West, } #[derive(Debug, PartialEq, Clone)] pub struct Latitude { pub degrees: u8, pub minutes: u8, pub seconds: f32, pub hemisphere: Hemisph...
use core::convert::TryFrom; #[derive(Debug, PartialEq, Clone)] pub enum Hemisphere { North, South, East, West, } #[derive(Debug, PartialEq, Clone)] pub struct Latitude { pub degrees: u8, pub minutes: u8, pub seconds: f32, pub hemisphere: Hemisph...
} #[derive(Debug, PartialEq, Clone)] pub struct Course { pub degrees: f32, } impl From<f32> for Course { fn from(value: f32) -> Self { Course { degrees: value } } } impl Course { pub(crate) fn parse(input: Option<&str>) -> Result<Option<Self>, &'static str> { match input { ...
parse::<f32>() .map_err(|_| "Wrong speed field format") .and_then(|knots| Ok(Some(Speed { knots }))), _ => Ok(None), } }
function_block-function_prefix_line
[ { "content": "fn from_ascii(bytes: &[u8]) -> Result<&str, &'static str> {\n\n if bytes.iter().all(|b| *b < 128) {\n\n Ok(unsafe { core::str::from_utf8_unchecked(bytes) })\n\n } else {\n\n Err(\"Not an ascii!\")\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": ...
Rust
src/channel/bolt/keyset.rs
LNP-WG/lnp-core
f8a24a0a61ae7a1c0a87020fde3caf90320e2c6d
use std::collections::BTreeMap; use amplify::DumbDefault; #[cfg(feature = "serde")] use amplify::ToYamlString; use bitcoin::util::bip32::{ChildNumber, ExtendedPrivKey, KeySource}; use p2p::legacy::{AcceptChannel, ChannelType, OpenChannel}; use secp256k1::{PublicKey, Secp256k1}; use wallet::hd::HardenedIndex; use wal...
use std::collections::BTreeMap; use amplify::DumbDefault; #[cfg(feature = "serde")] use amplify::ToYamlString; use bitcoin::util::bip32::{ChildNumber, ExtendedPrivKey, KeySource}; use p2p::legacy::{AcceptChannel, ChannelType, OpenChannel}; use secp256k1::{PublicKey, Secp256k1}; use wallet::hd::HardenedIndex; use wal...
} impl DumbDefault for RemoteKeyset { fn dumb_default() -> Self { Self { funding_pubkey: dumb_pubkey!(), revocation_basepoint: dumb_pubkey!(), payment_basepoint: dumb_pubkey!(), delayed_payment_basepoint: dumb_pubkey!(), htlc_basepoint: dumb_pubk...
revocation_basepoint: DumbDefault::dumb_default(), payment_basepoint: DumbDefault::dumb_default(), delayed_payment_basepoint: DumbDefault::dumb_default(), htlc_basepoint: DumbDefault::dumb_default(), first_per_commitment_point: DumbDefault::dumb_default(), shu...
function_block-function_prefix_line
[ { "content": "fn lnp_out_channel_funding_key() -> ProprietaryKey {\n\n ProprietaryKey {\n\n prefix: PSBT_LNP_PROPRIETARY_PREFIX.to_vec(),\n\n subtype: PSBT_OUT_LNP_CHANNEL_FUNDING,\n\n key: vec![],\n\n }\n\n}\n\n\n", "file_path": "src/channel/funding.rs", "rank": 0, "score...
Rust
keymanager-lib/src/policy.rs
keks/oasis-core
37479c75e5f94ffc03222cba6edd0624c1280d25
use std::{ collections::{HashMap, HashSet}, sync::RwLock, }; use anyhow::Result; use lazy_static::lazy_static; use sgx_isa::Keypolicy; use tiny_keccak::sha3_256; use oasis_core_keymanager_api_common::*; use oasis_core_runtime::{ common::{ cbor, runtime::RuntimeId, sgx::{ ...
use std::{ collections::{HashMap, HashSet}, sync::RwLock, }; use anyhow::Result; use lazy_static::lazy_static; use sgx_isa::Keypolicy; use tiny_keccak::sha3_256; use oasis_core_keymanager_api_common::*; use oasis_core_runtime::{ common::{ cbor, runtime::RuntimeId, sgx::{ ...
te_enclave: &EnclaveIdentity, req: &RequestIds) -> bool { let may_query = match self.may_query.get(&req.runtime_id) { Some(may_query) => may_query, None => return false, }; may_query.contains(remote_enclave) } fn may_replicate_master_secret(&self, remote_enclave:...
let untrusted_policy: SignedPolicySGX = cbor::from_slice(&raw)?; let policy = untrusted_policy.verify()?; let mut cached_policy = Self::default(); cached_policy.checksum = sha3_256(&raw).to_vec(); cached_policy.serial = policy.serial; cached_policy.runtime_id = policy.id; ...
random
[ { "content": "/// Unseal a previously sealed secret to the enclave.\n\n///\n\n/// The `context` field is a domain separation tag.\n\n///\n\n/// # Panics\n\n///\n\n/// All parsing and authentication errors of the ciphertext are fatal and\n\n/// will result in a panic.\n\npub fn unseal(key_policy: Keypolicy, cont...
Rust
core_nodes/src/abc.rs
alec-deason/virtual_modular
77857488c4b573522807430855c83bfc3d588647
use generic_array::{arr, typenum::*}; use std::collections::HashMap; use virtual_modular_graph::{Node, Ports, BLOCK_SIZE}; #[derive(Clone, Debug)] pub struct ABCSequence { line: Vec<abc_parser::datatypes::MusicSymbol>, key: HashMap<char, abc_parser::datatypes::Accidental>, idx: usize, clock: u32, s...
use generic_array::{arr, typenum::*}; use std::collections::HashMap; use virtual_modular_graph::{Node, Ports, BLOCK_SIZE}; #[derive(Clone, Debug)] pub struct ABCSequence { line: Vec<abc_parser::datatypes::MusicSymbol>, key: HashMap<char, abc_parser::datatypes::Accidental>, idx: usize, clock: u32, s...
} impl Node for ABCSequence { type Input = U1; type Output = U4; #[inline] fn process(&mut self, input: Ports<Self::Input>) -> Ports<Self::Output> { let trigger = input[0]; let mut r_freq = [0.0f32; BLOCK_SIZE]; let mut r_gate = [0.0f32; BLOCK_SIZE]; let mut r_eoc = [0...
fn duration(&self, idx: usize) -> u32 { match self.line[idx] { abc_parser::datatypes::MusicSymbol::Rest(abc_parser::datatypes::Rest::Note( _length, )) => { unimplemented!() } abc_parser::datatypes::MusicSymbol::Note { length, .. } =...
function_block-full_function
[ { "content": "fn make_euclidian_rhythm(pulses: u32, len: u32, steps: &mut Vec<bool>) {\n\n steps.resize(len as usize, false);\n\n steps.fill(false);\n\n let mut bucket = 0;\n\n for step in steps.iter_mut() {\n\n bucket += pulses;\n\n if bucket >= len {\n\n bucket -= len;\n\n...
Rust
imgui/src/widget/tab.rs
eiz/imgui-rs
1ef9393f3253e4318e50219cd3c93fc98beeb578
use crate::sys; use crate::Ui; use bitflags::bitflags; use std::ptr; bitflags! { #[repr(transparent)] pub struct TabBarFlags: u32 { const REORDERABLE = sys::ImGuiTabBarFlags_Reorderable; const AUTO_SELECT_NEW_TABS = sys::ImGuiTabBarFlags_AutoSelectNewTabs; const TAB_LIST_POPUP_BUTTON ...
use crate::sys; use crate::Ui; use bitflags::bitflags; use std::ptr; bitflags! { #[repr(transparent)] pub struct TabBarFlags: u32 { const REORDERABLE = sys::ImGuiTabBarFlags_Reorderable; const AUTO_SELECT_NEW_TABS = sys::ImGuiTabBarFlags_AutoSelectNewTabs; const TAB_LIST_POPUP_BUTTON ...
if should_render { Some(TabItemToken::new(self)) } else { None } } }
let should_render = unsafe { sys::igBeginTabItem( self.scratch_txt(label), opened.map(|x| x as *mut bool).unwrap_or(ptr::null_mut()), flags.bits() as i32, ) };
assignment_statement
[ { "content": "fn show_test_window(ui: &Ui, state: &mut State, opened: &mut bool) {\n\n if state.show_app_main_menu_bar {\n\n show_example_app_main_menu_bar(ui, state)\n\n }\n\n if state.show_app_auto_resize {\n\n show_example_app_auto_resize(\n\n ui,\n\n &mut state.a...
Rust
bolero-generator/src/uniform.rs
zhassan-aws/bolero
04a73b946da7241c188816524aaaec60d60658a3
use crate::{bounded::BoundExt, driver::DriverMode}; use core::ops::{Bound, RangeBounds}; pub trait Uniform: Sized { fn sample<F: FillBytes>(fill: &mut F, min: Bound<&Self>, max: Bound<&Self>) -> Option<Self>; } pub trait FillBytes { fn mode(&self) -> DriverMode; fn fill_bytes(&mut self, bytes: &mut [u8]) ...
use crate::{bounded::BoundExt, driver::DriverMode}; use core::ops::{Bound, RangeBounds}; pub trait Uniform: Sized { fn sample<F: FillBytes>(fill: &mut F, min: Bound<&Self>, max: Bound<&Self>) -> Option<Self>; } pub trait FillBytes { fn mode(&self) -> DriverMode; fn fill_bytes(&mut self, bytes: &mut [u8]) ...
const START: u32 = 0xD800; const LEN: u32 = 0xE000 - START; fn map_to_u32(c: &char) -> u32 { match *c as u32 { c if c >= START => c - LEN, c => c, } } let lower = BoundExt::map(min, map_to_u32); let upper = match...
if fill.mode() == DriverMode::Direct { let value = u32::sample(fill, Bound::Unbounded, Bound::Unbounded)?; return char::from_u32(value); }
if_condition
[ { "content": "pub trait BoundedValue<B = Self>: Sized {\n\n fn gen_bounded<D: Driver>(driver: &mut D, min: Bound<&B>, max: Bound<&B>) -> Option<Self>;\n\n\n\n fn mutate_bounded<D: Driver>(\n\n &mut self,\n\n driver: &mut D,\n\n min: Bound<&B>,\n\n max: Bound<&B>,\n\n ) -> Op...
Rust
alacritty/src/main.rs
vitaly-zdanevich/alacritty
6b208a6958a32594cf1248f5336f8a8f79d17fe3
#![warn(rust_2018_idioms, future_incompatible)] #![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use, clippy::wrong_pub_self_convention)] #![cfg_attr(feature = "cargo-clippy", deny(warnings))] #![cfg_attr(all(test, feature = "bench"), feature(test))] #![windows_subsystem = "windows"] #[cfg(not(any(featur...
#![warn(rust_2018_idioms, future_incompatible)] #![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use, clippy::wrong_pub_self_convention)] #![cfg_attr(feature = "cargo-clippy", deny(warnings))] #![cfg_attr(all(test, feature = "bench"), feature(test))] #![windows_subsystem = "windows"] #[cfg(not(any(featur...
fn log_config_path(config: &Config) { let mut msg = String::from("Configuration files loaded from:"); for path in &config.ui_config.config_paths { msg.push_str(&format!("\n {:?}", path.display())); } info!("{}", msg); }
function_block-full_function
[ { "content": "#[cfg(not(all(feature = \"winpty\", target_env = \"msvc\")))]\n\npub fn new<C>(config: &Config<C>, size: &SizeInfo, window_id: Option<usize>) -> Pty {\n\n conpty::new(config, size, window_id).expect(\"Failed to create ConPTY backend\")\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/w...
Rust
src/engine.rs
0ncorhynchus/mictyris
5f8bffe0fb6833048bac9d240050b92f5acd9a0d
mod auxiliary; pub mod procedure; mod storage; use self::auxiliary::*; use self::procedure::*; use self::storage::*; use crate::lexer::Identifier; use crate::parser::{Datum, Formals, ListDatum, Lit}; use crate::pass::*; use std::fmt; use std::rc::Rc; use Value::*; #[derive(Clone, Debug, PartialEq)] pub enum Value { ...
mod auxiliary; pub mod procedure; mod storage; use self::auxiliary::*; use self::procedure::*; use self::storage::*; use crate::lexer::Identifier; use crate::parser::{Datum, Formals, ListDatum, Lit}; use crate::pass::*; use std::fmt; use std::rc::Rc; use Value::*; #[derive(Clone, Debug, PartialEq)] pub enum Value { ...
pub fn write(value: Value) -> CommCont { fn fmt(store: &Store, value: &Value) -> String { match value { Symbol(ident) => format!("{}", ident), Character(c) => format!("#\\{}", c), Number(n) => format!("{}", n), Pair(loc1, loc2, _) => format!( "...
function_block-full_function
[ { "content": "pub fn cdr(values: &[Value], cont: ExprCont) -> CommCont {\n\n onearg(\n\n |arg, cont| match arg.pair() {\n\n Some((_, cdr, _)) => hold(cdr, cont),\n\n None => wrong(\"non-pair argument\"),\n\n },\n\n values,\n\n cont,\n\n )\n\n}\n\n\n", ...
Rust
src/network.rs
Aloxaf/mcfly
0f50f2deeed7c8ec75d41711369c2fc927006a4e
#![allow(clippy::unreadable_literal)] use crate::node::Node; use crate::training_sample_generator::TrainingSampleGenerator; use crate::history::Features; use rand::Rng; #[derive(Debug, Copy, Clone)] pub struct Network { pub final_bias: f64, pub final_weights: [f64; 3], pub final_sum: f64, pub final_out...
#![allow(clippy::unreadable_literal)] use crate::node::Node; use crate::training_sample_generator::TrainingSampleGenerator; use crate::history::Features; use rand::Rng; #[derive(Debug, Copy, Clone)] pub struct Network { pub final_bias: f64, pub final_weights: [f64; 3], pub final_sum: f64, pub final_out...
pub fn dot(&self, features: &Features) -> f64 { let mut network_output = self.final_bias; for (node, output_weight) in self.hidden_nodes.iter().zip(self.final_weights.iter()) { let node_output = node.output(features); network_output += node_output * output_weight; }...
f.final_sum += self.hidden_node_outputs[i] * self.final_weights[i]; } self.final_output = self.final_sum.tanh(); }
function_block-function_prefixed
[ { "content": "pub fn use_tiocsti(string: &str) {\n\n for byte in string.as_bytes() {\n\n let a: *const u8 = byte;\n\n if unsafe { ioctl(0, libc::TIOCSTI as u32, a) } < 0 {\n\n panic!(\"Error encountered when calling ioctl\");\n\n }\n\n }\n\n}\n", "file_path": "src/fake_...
Rust
src/node_state/leader/follower.rs
yuezato/raftlog
12315643c559118dbe9c20625ff9e3c415bf9bb3
use futures::{Async, Future}; use std::collections::BTreeMap; use std::mem; use trackable::error::ErrorKindExt; use super::super::Common; use crate::cluster::ClusterConfig; use crate::log::{Log, LogIndex}; use crate::message::{AppendEntriesReply, SequenceNumber}; use crate::node::NodeId; use crate::{ErrorKind, Io, Res...
use futures::{Async, Future}; use std::collections::BTreeMap; use std::mem; use trackable::error::ErrorKindExt; use super::super::Common; use crate::cluster::ClusterConfig; use crate::log::{Log, LogIndex}; use crate::message::{AppendEntriesReply, SequenceNumber}; use crate::node::NodeId; use crate::{ErrorKind, Io, Res...
if reply.header.seq_no <= follower.obsolete_seq_no { return Ok(()); } follower.obsolete_seq_no = self.last_broadcast_seq_no; if common.log().tail().index <= follower.log_tail { return Ok(()); } ...
let follower = track!(self .followers .get_mut(&reply.header.sender) .ok_or_else(|| ErrorKind::InconsistentState.error()))?;
assignment_statement
[ { "content": "struct InstallSnapshot<IO: Io> {\n\n future: IO::SaveLog,\n\n summary: SnapshotSummary,\n\n}\n\nimpl<IO: Io> InstallSnapshot<IO> {\n\n pub fn new(common: &mut Common<IO>, prefix: LogPrefix) -> Self {\n\n let summary = SnapshotSummary {\n\n tail: prefix.tail,\n\n ...
Rust
state/api/src/chain_state.rs
xielong/starcoin
14faf39ea7231d6a24780a87f847584824e7ff18
use anyhow::{ensure, format_err, Result}; use merkle_tree::{blob::Blob, proof::SparseMerkleProof, RawKey}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use starcoin_crypto::HashValue; use starcoin_types::state_set::AccountStateSet; use starcoin_types::write_set::WriteSet; use starcoin_types::...
use anyhow::{ensure, format_err, Result}; use merkle_tree::{blob::Blob, proof::SparseMerkleProof, RawKey}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use starcoin_crypto::HashValue; use starcoin_types::state_set::AccountStateSet; use starcoin_types::write_set::WriteSet; use starcoin_types::...
pub fn get_balance(&self, address: &AccountAddress) -> Result<Option<u128>> { self.reader.get_balance(*address) } pub fn get_balance_by_type( &self, address: &AccountAddress, type_tag: TypeTag, ) -> Result<Option<u128>> { self.reader.get_balance_by_type(*a...
pub fn get_on_chain_config<C>(&self) -> Result<Option<C>> where C: OnChainConfig, { self.reader.get_on_chain_config() }
function_block-full_function
[ { "content": "pub fn access_path_for_module_upgrade_strategy(address: AccountAddress) -> AccessPath {\n\n AccessPath::resource_access_path(address, ModuleUpgradeStrategy::struct_tag())\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct TwoPhaseUpgradeV2Resource {\n\n config: TwoPhaseUpgrad...
Rust
multi-skill/src/systems/true_skill/normal.rs
kiwec/Elo-MMR
bf64ea75e8c0dbb946d379b9bee1753e604b388a
use super::float::{erfc, Float, MyFloat, PI, TWO, ZERO}; use overload::overload; use std::ops; #[derive(Clone, Debug)] pub struct Gaussian { pub mu: MyFloat, pub sigma: MyFloat, } pub const G_ZERO: Gaussian = Gaussian { mu: ZERO, sigma: ZERO, }; pub const G_ONE: Gaussian = Gaussian { mu: ZERO, ...
use super::float::{erfc, Float, MyFloat, PI, TWO, ZERO}; use overload::overload; use std::ops; #[derive(Clone, Debug)] pub struct Gaussian { pub mu: MyFloat, pub sigma: MyFloat, } pub const G_ZERO: Gaussian = Gaussian { mu: ZERO, sigma: ZERO, }; pub const G_ONE: Gaussian = Gaussian { mu: ZERO, ...
impl Gaussian { pub fn leq_eps(&self, eps: MyFloat) -> Gaussian { assert!(eps >= ZERO); assert!(!self.sigma.is_infinite()); let alpha = moment0(self.mu, self.sigma, -eps) - moment0(self.mu, self.sigma, eps); const FLOAT_CMP_EPS: f64 = 1e-8; let (mu, sigma) = if alpha < FL...
mu.powi(2) * moment0(ZERO, sigma, t - mu) + TWO * mu * moment1(ZERO, sigma, t - mu) + (sigma / TWO).powi(2) * (TWO * gauss_exponent(mu, sigma, t) * (t - mu) + sigma * PI.sqrt() * erfc((t - mu) / sigma)) }
function_block-function_prefix_line
[]
Rust
runtime/src/account_info.rs
luma-team/solana
b02c412d5b5c1902bd5b3616f427ffc0c9925cef
use crate::{ accounts_db::{AppendVecId, CACHE_VIRTUAL_OFFSET}, accounts_index::{IsCached, ZeroLamport}, append_vec::ALIGN_BOUNDARY_OFFSET, }; pub type Offset = usize; pub type StoredSize = u32; #[derive(Debug)] pub enum StorageLocation { AppendVec(AppendVecId, Offset), Cached, } impl StorageLo...
use crate::{ accounts_db::{AppendVecId, CACHE_VIRTUAL_OFFSET}, accounts_index::{IsCached, ZeroLamport}, append_vec::ALIGN_BOUNDARY_OFFSET, }; pub type Offset = usize; pub type StoredSize = u32; #[derive(Debug)] pub enum StorageLocation { AppendVec(AppendVecId, Offset), Cached, } impl StorageLo...
}
RTUAL_STORAGE_ID; let info = AccountInfo::new(StorageLocation::Cached, 0, 0); assert!(!info.matches_storage_location(id, offset)); }
function_block-function_prefixed
[ { "content": "pub fn is_sysvar_id(id: &Pubkey) -> bool {\n\n ALL_IDS.iter().any(|key| key == id)\n\n}\n\n\n\n/// Declares an ID that implements [`SysvarId`].\n\n#[macro_export]\n\nmacro_rules! declare_sysvar_id(\n\n ($name:expr, $type:ty) => (\n\n $crate::declare_id!($name);\n\n\n\n impl $cr...
Rust
egui/src/grid.rs
katyo/egui
02db9ee5835a522ddf04308f259025388abf0185
use crate::*; #[derive(Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] pub(crate) struct State { col_widths: Vec<f32>, row_heights: Vec<f32>, } impl State { fn set_min_col_width(&mut self, col: usize, width: f32) { self.col_widt...
use crate::*; #[derive(Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] pub(crate) struct State { col_widths: Vec<f32>, row_heights: Vec<f32>, } impl State { fn set_min_col_width(&mut self, col: usize, width: f32) { self.col_widt...
pub(crate) fn save(&self) { if self.curr_state != self.prev_state { self.ctx .memory() .id_data .insert(self.id, self.curr_state.clone()); self.ctx.request_repaint(); } } } #[must_use = "You should call .show()"] pub stru...
Rgba::from_white_alpha(0.0075) } else { Rgba::from_black_alpha(0.075) }; painter.rect_filled(rect, 2.0, color); } } }
function_block-function_prefix_line
[ { "content": "pub fn show_tooltip_under(ctx: &CtxRef, id: Id, rect: &Rect, add_contents: impl FnOnce(&mut Ui)) {\n\n show_tooltip_at(\n\n ctx,\n\n id,\n\n Some(rect.left_bottom() + vec2(-2.0, 4.0)),\n\n add_contents,\n\n )\n\n}\n\n\n", "file_path": "egui/src/containers/popu...
Rust
crates/regex/src/re_set.rs
CryZe/libtww
0b8de9f451e7d8afda7a14d618bd3a7784b1d679
macro_rules! define_set { ($name:ident, $exec_build:expr, $text_ty:ty, $as_bytes:expr) => { pub mod $name { use libtww::std::fmt; use libtww::std::iter; use libtww::std::slice; use libtww::std::vec; use error::Error; use exec::{Exec,...
macro_rules! define_set { ($name:ident, $exec_build:expr, $text_ty:ty, $as_bytes:expr) => { pub mod $name { use libtww::std::fmt; use libtww::std::iter; use libtww::std::slice; use libtww::std::vec; use error::Error; use exec::{Exec,...
dedIterator for SetMatchesIter<'a> { fn next_back(&mut self) -> Option<usize> { loop { match self.0.next_back() { None => return None, Some((_, &false)) => {} Some((i, &true)) => return Some(i), } } } } #[doc(hidden)] impl ...
<usize> { loop { match self.0.next() { None => return None, Some((_, false)) => {} Some((i, true)) => return Some(i), } } } } impl DoubleEndedIterator for SetMatchesIntoIter { fn next_back(&mut self) -> Option<usize> { ...
random
[ { "content": "/// Tests if the given regular expression matches somewhere in the text given.\n\n///\n\n/// If there was a problem compiling the regular expression, an error is\n\n/// returned.\n\n///\n\n/// To find submatches, split or replace text, you'll need to compile an\n\n/// expression first.\n\npub fn i...
Rust
src/passes/mod.rs
Kixiron/cranial-coitus
2f0b158709b23f23a4d84045846829b250779f31
mod add_sub_loop; mod associative_ops; mod canonicalize; mod const_folding; mod copy_cell; mod dataflow; mod dce; mod eliminate_const_gamma; mod equality; mod expr_dedup; mod fold_arithmetic; mod fuse_io; mod licm; mod mem2reg; mod move_cell; mod scan_loops; mod square_cell; mod symbolic_eval; mod unobserved_store; mod...
mod add_sub_loop; mod associative_ops; mod canonicalize; mod const_folding; mod copy_cell; mod dataflow; mod dce; mod eliminate_const_gamma; mod equality; mod expr_dedup; mod fold_arithmetic; mod fuse_io; mod licm; mod mem2reg; mod move_cell; mod scan_loops; mod square_cell; mod symbolic_eval; mod unobserved_store; mod...
fn visit_graph_inner( &mut self, graph: &mut Rvsdg, stack: &mut VecDeque<NodeId>, visited: &mut HashSet<NodeId>, buffer: &mut Vec<NodeId>, ) -> bool { visited.clear(); buffer.clear(); for n...
fn visit_graph(&mut self, graph: &mut Rvsdg) -> bool { let (mut stack, mut visited, mut buffer) = VISIT_GRAPH_CACHE .with(|buffers| buffers.borrow_mut().pop()) .unwrap_or_else(|| { ( VecDeque::with_capacity(graph.node_len() / 2), ...
function_block-full_function
[ { "content": "pub fn stdout_output() -> impl FnMut(u8) + 'static {\n\n move |byte| {\n\n // FIXME: Lock once, move into closure\n\n let stdout_handle = io::stdout();\n\n let mut stdout = stdout_handle.lock();\n\n\n\n tracing::trace!(\n\n \"wrote output value {byte}, hex...
Rust
garnet/bin/setui/src/tests/media_buttons_agent_tests.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use crate::agent::media_buttons; use crate::agent::Invocation; use crate::agent::Lifespan; use crate::agent::{Context, Payload}; use crate::event::{self, Event}; use crate::input::{MediaButtons, VolumeGain}; use crate::message::base::{Audience, MessengerType}; use crate::message::MessageHubUtil; use crate::service; u...
use crate::agent::media_buttons; use crate::agent::Invocation; use crate::agent::Lifespan; use crate::agent::{Context, Payload}; use crate::event::{self, Event}; use crate::input::{MediaButtons, VolumeGain}; use crate::message::base::{Audience, MessengerType}; use crate::message::MessageHubUtil; use crate::service; u...
assert!( matches!(completion_result, Some(Ok(()))), "Did not receive a completion event from the invocation message" ); fake_services .input_device_registry .lock() .await .send_media_button_event(MediaButtonsEvent { volume: Some(1), ...
if let Ok((Payload::Complete(result), _)) = reply_receptor.next_of::<Payload>().await { completion_result = Some(result); }
if_condition
[]
Rust
src/reconnectable_ws.rs
hermanodecastro/openlimits
af7b4d59c6a874c662bbc5ace9271bcb1956a8c5
use crate::errors::OpenLimitsError; use crate::exchange_ws::{CallbackHandle, ExchangeWs, OpenLimitsWs, Subscriptions}; use crate::model::websocket::{Subscription, WebSocketResponse}; use crate::shared::Result; use futures::stream::BoxStream; use std::sync::Arc; use std::thread::sleep; use tokio::sync::mpsc::{unbounded_...
use crate::errors::OpenLimitsError; use crate::exchange_ws::{CallbackHandle, ExchangeWs, OpenLimitsWs, Subscriptions}; use crate::model::websocket::{Subscription, WebSocketResponse}; use crate::shared::Result; use futures::stream::BoxStream; use std::sync::Arc; use std::thread::sleep; use tokio::sync::mpsc::{unbounded_...
pub async fn create_stream_specific( &self, subscriptions: Subscriptions<E::Subscription>, ) -> Result<BoxStream<'static, Result<E::Response>>> { self.websocket .lock() .await .create_stream_specific(subscriptions) .await } pub a...
callback(message) }) }); if futures_util::future::join_all(subscriptions) .await .iter() .all(|subscript...
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\npub trait ExchangeWs: Send + Sync + Sized {\n\n type InitParams: Clone + Send + Sync + 'static;\n\n type Subscription: From<Subscription> + Send + Sync + Sized + Clone;\n\n type Response: TryInto<WebSocketResponse<Self::Response>, Error = OpenLimitsError>\n\n + Se...
Rust
src/processes/poisson.rs
rasa200/markovian
8824ae58301e83f2b8f0278b3d321c2a4000331a
use num_traits::Float; use rand_distr::{Exp1, Exp}; use crate::{State, StateIterator}; use core::fmt::Debug; use num_traits::{sign::Unsigned, One, Zero}; use rand::Rng; use rand_distr::Distribution; use crate::errors::InvalidState; use core::mem; #[derive(Debug, Clone)] pub struct Poisson<N, T, R> where N: Floa...
use num_traits::Float; use rand_distr::{Exp1, Exp}; use crate::{State, StateIterator}; use core::fmt::Debug; use num_traits::{sign::Unsigned, One, Zero}; use rand::Rng; use rand_distr::Distribution; use crate::errors::InvalidState; use core::mem; #[derive(Debug, Clone)] pub struct Poisson<N, T, R> where N: Floa...
} impl<N, T, R> Iterator for Poisson<N, T, R> where N: Float, Exp1: Distribution<N>, T: Debug + PartialEq + Clone + One + Zero + PartialOrd + Unsigned, R: Rng, { type Item = (N, T); #[inl...
fn set_state( &mut self, mut new_state: Self::Item, ) -> Result<Option<Self::Item>, InvalidState<Self::Item>> { mem::swap(&mut self.state, &mut new_state); Ok(Some(new_state)) }
function_block-full_function
[ { "content": "pub trait State {\n\n type Item: core::fmt::Debug;\n\n\n\n #[inline]\n\n fn state(&self) -> Option<&Self::Item> {\n\n None\n\n }\n\n\n\n #[inline]\n\n fn state_mut(&mut self) -> Option<&mut Self::Item> {\n\n None\n\n }\n\n\n\n /// Changes the `state` of the st...
Rust
src/libinput.rs
harshadgavali/gnome-x11-gesture-daemon
3c5a56a5ca9cf151bcee05bb8bbc8af3309b5f12
use std::{ fs::{File, OpenOptions}, os::unix::prelude::{AsRawFd, FromRawFd, IntoRawFd, OpenOptionsExt, RawFd}, path::Path, sync::mpsc, }; use input::{ event::{ gesture::{GestureHoldEvent, GesturePinchEvent, GestureSwipeEvent}, Event, GestureEvent, }, ffi::{ libinput_...
use std::{ fs::{File, OpenOptions}, os::unix::prelude::{AsRawFd, FromRawFd, IntoRawFd, OpenOptionsExt, RawFd}, path::Path, sync::mpsc, }; use input::{ event::{ gesture::{GestureHoldEvent, GesturePinchEvent, GestureSwipeEvent}, Event, GestureEvent, }, ffi::{ libinput_...
fn close_restricted(&mut self, fd: RawFd) { unsafe { File::from_raw_fd(fd); } } } pub fn handle_swipe(swipe: GestureSwipeEvent, transmitter: &mpsc::Sender<CustomGestureEvent>) { let stage = match &swipe { GestureSwipeEvent::Begin(_) => "Begin", GestureSwipeEvent...
fn open_restricted(&mut self, path: &Path, flags: i32) -> Result<RawFd, i32> { OpenOptions::new() .custom_flags(flags) .read((flags & libc::O_RDONLY != 0) | (flags & libc::O_RDWR != 0)) .write((flags & libc::O_WRONLY != 0) | (flags & libc::O_RDWR != 0)) .open(path...
function_block-full_function
[ { "content": "struct Greeter {}\n\n\n\n#[dbus_interface(name = \"org.gestureImprovements.gestures\")]\n\nimpl Greeter {\n\n #[dbus_interface(signal)]\n\n fn touchpad_swipe(&self, event: &libinput::CustomSwipeEvent) -> zbus::Result<()>;\n\n\n\n #[dbus_interface(signal)]\n\n fn touchpad_hold(&self, ev...
Rust
src/bvh.rs
q4x3/raytracer
7ebb6e1f505dae0985a972fab2d9237cbba3cbc9
use crate::{ aabb::AABB, hittable::{HitRecord, HitTable}, ray::Ray, rtweekend::random_int, vec3::Point3, }; use std::{cmp::Ordering, sync::Arc}; #[derive(Clone)] pub struct BVHNode { left: Arc<dyn HitTable>, right: Arc<dyn HitTable>, bvhbox: AABB, } impl BVHNode { pub fn new( ...
use crate::{ aabb::AABB, hittable::{HitRecord, HitTable}, ray::Ray, rtweekend::random_int, vec3::Point3, }; use std::{cmp::Ordering, sync::Arc}; #[derive(Clone)] pub struct BVHNode { left: Arc<dyn HitTable>, right: Arc<dyn HitTable>, bvhbox: AABB, } impl BVHNode { pub fn new( ...
tor(&objects[start], &objects[start + 1]) == Ordering::Less { tmp = BVHNode { left: objects[start].clone(), right: objects[start + 1].clone(), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } else { ...
tmp = BVHNode { left: objects[start].clone(), right: objects[start].clone(), bvhbox: AABB::new(Point3::zero(), Point3::zero()), }; } else if object_span == 2 { if compara
random
[]
Rust
devices/src/virtio/video/decoder/capability.rs
aosp-riscv/platform_external_crosvm
ff681b6a18eff76336a68058c11afdc287255615
use base::warn; use std::collections::btree_map::Entry; use std::collections::BTreeMap; use crate::virtio::video::control::*; use crate::virtio::video::format::*; fn from_pixel_format( fmt: &libvda::PixelFormat, mask: u64, width_range: FormatRange, height_range: FormatRange, ) -> FormatDesc { le...
use base::warn; use std::collections::btree_map::Entry; use std::collections::BTreeMap; use crate::virtio::video::control::*; use crate::virtio::video::format::*; fn from_pixel_format( fmt: &libvda::PixelFormat, mask: u64, width_range: FormatRange, height_range: FormatRange, ) -> FormatDesc { le...
nge, height_range)) .collect(); Capability { in_fmts, out_fmts, profiles, levels, } } pub fn query_control(&self, t: &QueryCtrlType) -> Option<QueryCtrlResponse> { use QueryCtrlType::*; match *t { Profile(f...
} let levels: BTreeMap<Format, Vec<Level>> = if profiles.contains_key(&Format::H264) { vec![(Format::H264, vec![Level::H264_1_0])] .into_iter() .collect() } else { Default::default() }; ...
random
[ { "content": "/// Returns a Vec of the valid memory addresses.\n\n/// These should be used to configure the GuestMemory structure for the platfrom.\n\npub fn arch_memory_regions(size: u64) -> Vec<(GuestAddress, u64)> {\n\n vec![(GuestAddress(AARCH64_PHYS_MEM_START), size)]\n\n}\n\n\n", "file_path": "aarc...
Rust
src/vec/tests.rs
interlockledger/rust-il2-utils
1c441c609fd71a25fb3a4644b6ed9052180443a6
/* * BSD 3-Clause License * * Copyright (c) 2019-2020, InterlockLedger Network * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above c...
/* * BSD 3-Clause License * * Copyright (c) 2019-2020, InterlockLedger Network * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above c...
#[test] fn test_vecextensions_set_contents_from_slice() { let sample: [u8; 32] = [0xFA; 32]; let mut v = Vec::<u8>::new(); let old_capacity = v.capacity(); v.set_contents_from_slice(&sample[0..0]); assert!(v.is_empty()); assert_eq!(v.capacity(), old_capacity); let mut v = Vec::<u8>::new(...
fn test_vecextensions_set_capacity_to_secure() { let mut v = Vec::<u8>::new(); v.set_capacity_to_secure(10); assert_eq!(v.len(), 0); assert!(v.capacity() >= 10); v.set_capacity_to_secure(100); assert_eq!(v.len(), 0); assert!(v.capacity() >= 100); let sample: [u8; 4] = [1, 2, 3, 4]; ...
function_block-full_function
[ { "content": "#[test]\n\nfn test_defaultsharedfilelocknamebuilder_namebuilder_create_lock_file_name() {\n\n let b = DefaultSharedFileLockNameBuilder;\n\n\n\n let name = OsStr::new(\"file\");\n\n assert_eq!(b.create_lock_file_name(name), OsStr::new(\".file.lock~\"));\n\n\n\n let name = OsStr::new(\"z...
Rust
src/lib.rs
arthurhenrique/rusti-cal
5d481a8afb72827f70712caf8f7d88ddad20847a
mod locale; const REFORM_YEAR: u32 = 1099; const MONTHS: usize = 12; const WEEKDAYS: u32 = 7; const COLUMN: usize = 3; const ROWS: usize = 4; const ROW_SIZE: usize = 7; static TOKEN: &str = "\n"; fn is_leap_year(year: u32) -> bool { if year <= REFORM_YEAR { return year % 4 == 0; } (year % 4 == 0...
mod locale; const REFORM_YEAR: u32 = 1099; const MONTHS: usize = 12; const WEEKDAYS: u32 = 7; const COLUMN: usize = 3; const ROWS: usize = 4; const ROW_SIZE: usize = 7; static TOKEN: &str = "\n"; fn is_leap_year(year: u32) -> bool { if year <= REFORM_YEAR { return year % 4 == 0; } (year % 4 == 0...
let day_year = days_by_date(day, month, year, months_memoized.clone(), year_memoized); result_days.push_str(&remain_day_printable(day, day_year, starting_day)) }); result_days .split(TOKEN) .collect::<Vec<&str>>() .into_iter() .for_each(|i| result.push(i.to...
if day == 1 { let first_day = days_by_date(1, month, year, months_memoized.clone(), year_memoized); result_days.push_str(&first_day_printable(first_day, starting_day)) }
if_condition
[ { "content": "fn to_titlecase(str: &str) -> String {\n\n str.chars()\n\n .enumerate()\n\n .map(|(pos, c)| {\n\n if pos == 0 {\n\n c.to_uppercase().to_string()\n\n } else {\n\n c.to_string()\n\n }\n\n })\n\n .collect()\...
Rust
rust/game/src/schemas.rs
sisso/test-unity3d-rust
883ad1eba80a6fad2b566c170a8597dc2a7600ad
mod packages_generated; mod requests_generated; mod responses_generated; pub use requests_generated::ffi_requests; pub use responses_generated::ffi_responses; use crate::{Error, GameEvent, Request, Result}; use flatbuffers::FlatBufferBuilder; pub type RawMsg = [u8]; pub type RawMsgBuffer = Vec<u8>; pub type PackageK...
mod packages_generated; mod requests_generated; mod responses_generated; pub use requests_generated::ffi_requests; pub use responses_generated::ffi_responses; use crate::{Error, GameEvent, Request, Result}; use flatbuffers::FlatBufferBuilder; pub type RawMsg = [u8]; pub type RawMsgBuffer = Vec<u8>; pub type PackageK...
g, obj_id, x, y, )); } GameEvent::GameStarted => empty_packages.push(ffi_responses::EmptyPackage::new( ffi_responses::ResponseKind::GameStarted, ordering, )), GameE...
function_block-function_prefixed
[ { "content": "pub fn enum_name_package_kind(e: PackageKind) -> &'static str {\n\n let index = e as u16;\n\n ENUM_NAMES_PACKAGE_KIND[index as usize]\n\n}\n\n\n\n} // pub mod FfiPackages\n\n\n", "file_path": "rust/game/src/schemas/packages_generated.rs", "rank": 1, "score": 163941.63861508263 }, ...
Rust
src/handlers/theme.rs
cmarincia/miette
714334098a92c77fb6b962e627defab7e16b540d
use atty::Stream; use owo_colors::Style; /** Theme used by [`GraphicalReportHandler`](crate::GraphicalReportHandler) to render fancy [`Diagnostic`](crate::Diagnostic) reports. A theme consists of two things: the set of characters to be used for drawing, and the [`owo_colors::Style`](https://docs.rs/owo-colors/latest/...
use atty::Stream; use owo_colors::Style; /** Theme used by [`GraphicalReportHandler`](crate::GraphicalReportHandler) to render fancy [`Diagnostic`](crate::Diagnostic) reports. A theme consists of two things: the set of characters to be used for drawing, and the [`owo_colors::Style`](https://docs.rs/owo-colors/latest/...
pub fn unicode_nocolor() -> Self { Self { characters: ThemeCharacters::unicode(), styles: ThemeStyles::none(), } } pub fn none() -> Self { Self { characters: ThemeCharacters::ascii(), styles: ThemeS...
pub fn unicode() -> Self { Self { characters: ThemeCharacters::unicode(), styles: ThemeStyles::rgb(), } }
function_block-full_function
[]
Rust
cranelift-codegen/src/topo_order.rs
jgouly/cranelift-1
470372f0b55cd51199466669cb87d9e038a3f459
use crate::dominator_tree::DominatorTree; use crate::entity::EntitySet; use crate::ir::{Block, Layout}; use alloc::vec::Vec; pub struct TopoOrder { preferred: Vec<Block>, next: usize, visited: EntitySet<Block>, stack: Vec<Block>, } impl TopoOrder { pub fn new() -> Sel...
use crate::dominator_tree::DominatorTree; use crate::entity::EntitySet; use crate::ir::{Block, Layout}; use alloc::vec::Vec; pub struct TopoOrder { preferred: Vec<Block>, next: usize, visited: EntitySet<Block>, stack: Vec<Block>, } impl TopoOrder { pub fn new() -> Sel...
} } } self.stack.pop() } } #[cfg(test)] mod tests { use super::*; use crate::cursor::{Cursor, FuncCursor}; use crate::dominator_tree::DominatorTree; use crate::flowgraph::ControlFlowGraph; use crate::ir::{Function, InstBuilder}; use core::iter; ...
t(self.next).cloned() { None => return None, Some(mut block) => { self.next += 1; while self.visited.insert(block) { self.stack.push(block); match domtree.ido...
function_block-random_span
[ { "content": "/// Compute the stack frame layout.\n\n///\n\n/// Determine the total size of this stack frame and assign offsets to all `Spill` and `Explicit`\n\n/// stack slots.\n\n///\n\n/// The total frame size will be a multiple of `alignment` which must be a power of two, unless the\n\n/// function doesn't ...