lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/signature.rs
agrinman/samael
e654fa62b3a61b88ace3ec1ee7880e0f3d2534c9
use crate::key_info::KeyInfo; use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event}; use quick_xml::Writer; use serde::Deserialize; use std::io::Cursor; const NAME: &str = "ds:Signature"; const SCHEMA:(&str, &str) = ("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); #[derive(Clone, Debug, Deserialize)] pub...
use crate::key_info::KeyInfo; use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event}; use quick_xml::Writer; use serde::Deserialize; use std::io::Cursor; const NAME: &str = "ds:Signature"; const SCHEMA:(&str, &str) = ("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#"); #[derive(Clone, Debug, Deserialize)] pub...
f())); writer.write_event(Event::Empty(root))?; Ok(String::from_utf8(write_buf)?) } } const SIGNATURE_METHOD_NAME: &str = "ds:SignatureMethod"; const HMAC_OUTPUT_LENGTH_NAME: &str = "ds:HMACOutputLength"; #[derive(Clone, Debug, Deserialize)] pub struct SignatureMethod { #[serde(rename = "Algor...
String, Box<dyn std::error::Error>> { let mut write_buf = Vec::new(); let mut writer = Writer::new(Cursor::new(&mut write_buf)); let mut root = BytesStart::borrowed( CANONICALIZATION_METHOD.as_bytes(), CANONICALIZATION_METHOD.len(), ); root.push_attribute(...
function_block-random_span
[ { "content": "pub fn gen_saml_response_id() -> String {\n\n format!(\"id{}\", uuid::Uuid::new_v4().to_string())\n\n}\n\n\n", "file_path": "src/crypto.rs", "rank": 0, "score": 129148.68708450932 }, { "content": "pub fn gen_saml_assertion_id() -> String {\n\n format!(\"_{}\", uuid::Uuid:...
Rust
src/openid.rs
drogue-iot/cli
42ca5af78ee3eca0eb4f2e2729ffb007c155507a
use oauth2::basic::{BasicClient, BasicTokenResponse}; use oauth2::reqwest::http_client; use oauth2::{ AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope, TokenResponse, TokenUrl, }; use anyhow::Error; use anyhow::Result; use tiny_http::{Response, Server}; use qstring::QStr...
use oauth2::basic::{BasicClient, BasicTokenResponse}; use oauth2::reqwest::http_client; use oauth2::{ AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope, TokenResponse, TokenUrl, }; use anyhow::Error; use anyhow::Result; use tiny_http::{Response, Server}; use qstring::QStr...
?, None => get_token(auth_url.clone(), token_url.clone())?, }; let token_exp_date = calculate_token_expiration_date(&token)?; log::info!("Token successfully obtained."); log::debug!("{:?}", token); let config = Context { name: context_name, drogue_cloud_url: api_endpoint, ...
exchange_token( auth_url.clone(), token_url.clone(), &oauth2::RefreshToken::new(refresh_token_val.to_string()), )
call_expression
[ { "content": "pub fn get_drogue_console_endpoint(context: &Context) -> Result<Url> {\n\n let endpoints = get_drogue_endpoints_authenticated(context)?;\n\n let ws = endpoints[\"console\"]\n\n .as_str()\n\n .context(\"No `console` service in drogue endpoints list\")?;\n\n\n\n url_validation...
Rust
gilrs/src/ev/state.rs
temportalflux/gilrs-fork
b2b5c4a428eb00a0ce19d01a6b18b087858b0db6
use crate::ev::Code; use fnv::FnvHashMap; use std::collections::hash_map; use std::iter::Iterator; use std::time::SystemTime; #[derive(Clone, Debug)] pub struct GamepadState { buttons: FnvHashMap<Code, ButtonData>, axes: FnvHashMap<Code, AxisData>, } impl GamepadState { pub(crate) fn new() -...
use crate::ev::Code; use fnv::FnvHashMap; use std::collections::hash_map; use std::iter::Iterator; use std::time::SystemTime; #[derive(Clone, Debug)] pub struct GamepadState { buttons: FnvHashMap<Code, ButtonData>, axes: FnvHashMap<Code, AxisData>, } impl GamepadState { pub(crate) fn new() -...
self .buttons .entry(btn) .or_insert_with(|| ButtonData::new(value, false, false, counter, timestamp)); data.value = value; data.counter = counter; data.last_event_ts = timestamp; } pub(crate) fn update_axis(&mut self, axis: Code, data: AxisData) { ...
n axes(&self) -> AxisDataIter<'_> { AxisDataIter(self.axes.iter()) } pub fn button_data(&self, btn: Code) -> Option<&ButtonData> { self.buttons.get(&btn) } pub fn axis_data(&self, axis: Code) -> Option<&AxisData> { self.axes.get(&axis) } pub(crate) fn set_btn...
random
[ { "content": "pub fn clamp(x: f32, min: f32, max: f32) -> f32 {\n\n x.max(min).min(max)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn t_clamp() {\n\n assert_eq!(clamp(-1.0, 0.0, 1.0), 0.0);\n\n assert_eq!(clamp(0.5, 0.0, 1.0), 0.5);\n\n assert_...
Rust
src/lib/ui/carnelian/src/app/strategies/framebuffer.rs
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
use crate::{ app::{ strategies::base::AppStrategy, FrameBufferPtr, InternalSender, MessageInternal, RenderOptions, }, geometry::IntSize, input::{self, listen_for_user_input, DeviceId, InputReportHandler}, view::{ strategies::{ base::{ViewStrategyParams, ViewStra...
use crate::{ app::{ strategies::base::AppStrategy, FrameBufferPtr, InternalSender, MessageInternal, RenderOptions, }, geometry::IntSize, input::{self, listen_for_user_input, DeviceId, InputReportHandler}, view::{ strategies::{ base::{ViewStrategyParams, ViewStra...
let strat_ptr = FrameBufferViewStrategy::new( key, render_options, &strategy_params.size, strategy_params.pixel_format, app_sender.clone(), strategy_params.frame_buffer.clone(), ) .await?; Ok(strat_ptr) } f...
let strategy_params = match strategy_params { ViewStrategyParams::FrameBuffer(params) => params, _ => bail!( "Incorrect ViewStrategyParams passed to create_view_strategy for frame buffer" ), };
assignment_statement
[]
Rust
src/linter/tests/dim_assign_use_in_expr.rs
ngeor/rusty-basic
865bbdf424931c0360e62cc139eba15c733d60ee
use crate::assert_linter_err; use crate::assert_linter_ok_top_level_statements; use crate::common::*; use crate::linter::test_utils::*; use crate::parser::{ BareName, BuiltInStyle, DimName, DimType, Element, ElementType, Expression, ExpressionType, PrintNode, Statement, TopLevelToken, TypeQualifier, }; #[test]...
use crate::assert_linter_err; use crate::assert_linter_ok_top_level_statements; use crate::common::*; use crate::linter::test_utils::*; use crate::parser::{ BareName, BuiltInStyle, DimName, DimType, Element, ElementType, Expression, ExpressionType, PrintNode, Statement, TopLevelToken, TypeQualifier, }; #[test]...
] ); } #[test] fn user_defined_type_integer_element() { let input = r#" TYPE Card Value AS INTEGER Suit AS STRING * 9 END TYPE DIM A AS Card A.Value = 42 PRINT A.Value "#; assert_linter_ok_top_level_statements!( input, Statement::Dim( ...
ral(42).at_rc(3, 9) )) .at_rc(3, 5), TopLevelToken::Statement(Statement::Print(PrintNode::one( Expression::var_resolved("A!").at_rc(4, 11) ))) .at_rc(4, 5) ] ); } #[test] fn compact_string() { let program = r#" DIM A$ A...
random
[ { "content": "/// Parses DIM statement\n\npub fn dim_p<R>() -> impl Parser<R, Output = Statement>\n\nwhere\n\n R: Reader<Item = char, Err = QError> + HasLocation + 'static,\n\n{\n\n keyword_followed_by_whitespace_p(Keyword::Dim)\n\n .and_opt(keyword_followed_by_whitespace_p(Keyword::Shared))\n\n ...
Rust
src/terrain/dem.rs
RustWorks/terra
67e8e436831583b35038b02595796255c4b62444
use crate::terrain::raster::{GlobalRaster, Raster, RasterSource}; use anyhow::{ensure, Error}; use lazy_static::lazy_static; use std::str::FromStr; use std::{collections::HashSet, path::Path}; use std::{ io::{Cursor, Read}, path::PathBuf, }; use thiserror::Error; use zip::ZipArchive; #[derive(Debug, Error)] #[...
use crate::terrain::raster::{GlobalRaster, Raster, RasterSource}; use anyhow::{ensure, Error}; use lazy_static::lazy_static; use std::str::FromStr; use std::{collections::HashSet, path::Path}; use std::{ io::{Cursor, Read}, path::PathBuf, }; use thiserror::Error; use zip::ZipArchive; #[derive(Debug, Error)] #[...
_) => SRTM3_FILES.contains(&*self.tile_name(latitude, longitude)), DemSource::Nasadem(_) => NASADEM_FILES.contains(&*self.tile_name(latitude, longitude)), } } pub(crate) fn filename(&self, latitude: i16, longitude: i16) -> PathBuf { match self { DemSource::Srtm90m(p) | De...
, } } fn tile_name(&self, latitude: i16, longitude: i16) -> String { let n_or_s = if latitude >= 0 { 'n' } else { 's' }; let e_or_w = if longitude >= 0 { 'e' } else { 'w' }; match *self { DemSource::Srtm90m(_) => { format!("{}{:02}_{}{:03}.hgt.sz", n_...
random
[]
Rust
relay-general/src/store/event_error.rs
timfish/relay
b036848850f80ea7b7054b720a9569768a31d781
use crate::processor::{ProcessValue, ProcessingState, Processor}; use crate::protocol::{Event, EventProcessingError}; use crate::types::{Annotated, Meta, ProcessingResult}; pub struct EmitEventErrors { errors: Vec<EventProcessingError>, } impl EmitEventErrors { pub fn new() -> Self { EmitEventErrors {...
use crate::processor::{ProcessValue, ProcessingState, Processor}; use crate::protocol::{Event, EventProcessingError}; use crate::types::{Annotated, Meta, ProcessingResult}; pub struct EmitEventErrors { errors: Vec<EventProcessingError>, } impl EmitEventErrors { pub fn new() -> Self { EmitEventErrors {...
#[test] fn test_multiple_errors() { let mut meta = Meta::from_error(ErrorKind::InvalidData); meta.add_error(ErrorKind::MissingAttribute); let mut event = Annotated::from(Event { id: Annotated(None, meta), ..Event::default() }); process_value( &mut event, &mut Emit...
fn test_nested_errors() { use crate::protocol::{Breadcrumb, Values}; let mut event = Annotated::from(Event { breadcrumbs: Annotated::from(Values::new(vec![Annotated::from(Breadcrumb { ty: Annotated::from_error(ErrorKind::InvalidData, None), ..Breadcrumb::default() })])),...
function_block-full_function
[ { "content": "/// Prompts for a value that has a default.\n\npub fn prompt_value<V: FromStr + Display>(name: &str, v: &mut V) -> Result<(), Error>\n\nwhere\n\n <V as FromStr>::Err: Display,\n\n{\n\n loop {\n\n let s = Input::with_theme(get_theme())\n\n .with_prompt(name)\n\n ....
Rust
tests/arc_str.rs
AngelOfSol/arcstr
e82f9b1f69a63871f788d50dbee25172d075833b
#![allow( clippy::redundant_clone, clippy::cmp_owned, )] use arcstr::ArcStr; #[test] fn test_various_partial_eq() { macro_rules! check_partial_eq { (@eq1; $a:expr, $b:expr) => {{ assert!($a == $b); assert!(!($a != $b)); assert!($b == $...
#![allow( clippy::redundant_clone, clippy::cmp_owned, )] use arcstr::ArcStr; #[test] fn test_various_partial_eq() { macro_rules! check_partial_eq { (@eq1; $a:expr, $b:expr) => {{ assert!($a == $b); assert!(!($a != $b)); assert!($b == $...
let nonstatic = ArcStr::from("Grounded..."); assert_eq!(ArcStr::as_static(&nonstatic), None); } #[test] fn test_static_arcstr_include_bytes() { const APACHE: ArcStr = arcstr::literal!(include_str!("../LICENSE-APACHE")); assert!(APACHE.len() > 10000); assert!(APACHE.trim_start().starts_with("Apache ...
, Some("Shocking!")); assert_eq!(ArcStr::as_static(&still_static.clone()), Some("Shocking!")); assert_eq!( ArcStr::as_static(&still_static.clone().clone()), Some("Shocking!") ); ArcStr::as_static(&still_static).unwrap() }; assert_eq!(st, "Shocking...
function_block-random_span
[ { "content": "#[test]\n\nfn test_various_partial_eq() {\n\n macro_rules! check_partial_eq {\n\n (@eq1; $a:expr, $b:expr) => {{\n\n // Note: intentionally not assert_eq.\n\n assert!($a == $b);\n\n assert!(!($a != $b));\n\n assert!($b == $a);\n\n as...
Rust
miner/src/lib.rs
xielong/starcoin
14faf39ea7231d6a24780a87f847584824e7ff18
use crate::metrics::MINER_METRICS; use crate::task::MintTask; use anyhow::Result; use consensus::Consensus; use futures::executor::block_on; use logger::prelude::*; use starcoin_config::NodeConfig; use starcoin_service_registry::{ ActorService, EventHandler, ServiceContext, ServiceFactory, ServiceHandler, Service...
use crate::metrics::MINER_METRICS; use crate::task::MintTask; use anyhow::Result; use consensus::Consensus; use futures::executor::block_on; use logger::prelude::*; use starcoin_config::NodeConfig; use starcoin_service_registry::{ ActorService, EventHandler, ServiceContext, ServiceFactory, ServiceHandler, Service...
pub fn finish_task( &mut self, nonce: u32, extra: BlockHeaderExtra, minting_blob: Vec<u8>, ctx: &mut ServiceContext<MinerService>, ) -> Result<()> { match self.current_task.as_ref() { None => { debug!( "MintTask is...
let strategy = block_template.strategy; let number = block_template.number; let task = MintTask::new(block_template); let mining_blob = task.minting_blob.clone(); if let Some(current_task) = self.current_task.as_ref() { debug!( "force s...
function_block-function_prefix_line
[ { "content": "pub fn event_handle_generator_struct_tag() -> StructTag {\n\n StructTag {\n\n address: CORE_CODE_ADDRESS,\n\n module: event_module_name().to_owned(),\n\n name: event_handle_generator_struct_name().to_owned(),\n\n type_params: vec![],\n\n }\n\n}\n", "file_path"...
Rust
src/tls_api/rustls.rs
dvtomas/mio_httpc
739cec6ed68c0011f863b5af66da51885c9a3e53
extern crate webpki; extern crate webpki_roots; use std::cell::RefCell; use std::fmt; use std::io; use std::result; use std::str; use std::sync::Arc; use rustls; use tls_api; use tls_api::rustls::rustls::Session; use tls_api::{Error, Result}; thread_local!(static CLIENT_CFG: RefCell<Arc<rustls::ClientConfig>> = RefC...
extern crate webpki; extern crate webpki_roots; use std::cell::RefCell; use std::fmt; use std::io; use std::result; use std::str; use std::sync::Arc; use rustls; use tls_api; use tls_api::rustls::rustls::Session; use tls_api::{Error, Result}; thread_local!(static CLIENT_CFG: RefCell<Arc<rustls::ClientConfig>> = RefC...
} fn connect<S>( &self, domain: &str, stream: S, ) -> result::Result<tls_api::TlsStream<S>, tls_api::HandshakeError<S>> where S: io::Read + io::Write + fmt::Debug + Send + 'static, { let cfg = CLIENT_CFG.with(|cfg| (*cfg.borrow()).clone()); if let Ok...
if CLIENT_CFG_SEALED.with(|f| *f.borrow()) { Ok(TlsConnectorBuilder(None)) } else { Ok(TlsConnectorBuilder(Some(rustls::ClientConfig::new()))) }
if_condition
[ { "content": "pub trait MidHandshakeTlsStreamImpl<S>: fmt::Debug + Sync + Send + 'static {\n\n fn handshake(&mut self) -> result::Result<TlsStream<S>, HandshakeError<S>>;\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct MidHandshakeTlsStream<S>(Box<MidHandshakeTlsStreamImpl<S> + 'static>);\n\n\n\nimpl<S: 'static> ...
Rust
crates/holochain_logging/src/color.rs
hector0513/holochain-logging
aecdae207e2bd7e9a85dc9ac03a9b9c5b5f55000
use std::str::FromStr; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Color { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, BrightBlack, BrightRed, BrightGreen, BrightYellow, BrightBlue, BrightMagenta, BrightCyan, BrightWhite, } impl Co...
use std::str::FromStr; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Color { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, BrightBlack, BrightRed, BrightGreen, BrightYellow, BrightBlue, BrightMagenta, BrightCyan, BrightWhite, } impl Co...
} } impl Default for ColoredLevelConfig { fn default() -> Self { ColoredLevelConfig { error: Color::Red, warn: Color::Yellow, info: Color::Blue, debug: Color::Magenta, ...
match level { Level::Error => self.error, Level::Warn => self.warn, Level::Info => self.info, Level::Debug => self.debug, Level::Trace => self.trace, }
if_condition
[ { "content": "/// Initialize a simple logging instance with [Info](Level::Info) log level verbosity or retrieve\n\n/// the level from the *RUST_LOG* environment variable and no rule filtering.\n\npub fn init_simple() -> Result<FastLogger, SetLoggerError> {\n\n FastLoggerBuilder::new().build()\n\n}\n\n\n", ...
Rust
src/render/mod.rs
Nilirad/bevy_canvas
42f8460105a63bed8779cea3ba0507eaf2f2dc30
use std::mem::size_of; use bevy::{ asset::{Assets, Handle, HandleUntyped}, core::cast_slice, ecs::world::World, reflect::TypeUuid, render::{ camera::ActiveCameras, pass::{ LoadOp, Operations, PassDescriptor, RenderPassColorAttachment, RenderPassDepthStencilAt...
use std::mem::size_of; use bevy::{ asset::{Assets, Handle, HandleUntyped}, core::cast_slice, ecs::world::World, reflect::TypeUuid, render::{ camera::ActiveCameras, pass::{ LoadOp, Operations, PassDescriptor, RenderPassColorAttachment, RenderPassDepthStencilAt...
strip_index_format: None, front_face: FrontFace::Cw, cull_mode: None, polygon_mode: PolygonMode::Fill, clamp_depth: false, conservative: false, }, depth_stencil: Some(DepthStencilState { format: TextureFormat::Depth32Float, ...
name: "CanvasVertexBuffer".into(), stride: size_of::<Vertex>() as u64, step_mode: InputStepMode::Vertex, attributes: vec![ VertexAttribute { name: "position".into(), offset: 0, ...
random
[ { "content": "type IndexType = u32;\n\npub(crate) type BufferPair = tess::VertexBuffers<Vertex, IndexType>;\n\n\n\npub(crate) struct VertexConstructor {\n\n pub color: Color,\n\n}\n\n\n\nimpl FillVertexConstructor<Vertex> for VertexConstructor {\n\n fn new_vertex(&mut self, vertex: FillVertex) -> Vertex {...
Rust
src/k8-client/tests/service.rs
simlay/k8-api
3a69671c469c46757e489f4ab6919f6601e0e514
#[cfg(feature = "k8")] mod integration_tests { use std::collections::HashMap; use std::time::Duration; use futures_util::future::join; use futures_util::StreamExt; use once_cell::sync::Lazy; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use tracing::debug; use...
#[cfg(feature = "k8")] mod integration_tests { use std::collections::HashMap; use std::time::Duration; use futures_util::future::join; use futures_util::StreamExt; use once_cell::sync::Lazy; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use tracing::debug; use...
} } async fn verify_client(client: &K8Client) { let services = client .retrieve_items::<ServiceSpec, _>(NS) .await .expect("services"); let version = services.metadata.resource_version.clone(); debug!("using version: {} ",...
); sleep(DELAY).await; let mut update_item_2 = updated_item.as_input(); update_item_2.metadata.annotations.insert( "test-annotations".to_owned(), "test-annotations-value".to_owned(), ); debug!("updati...
random
[ { "content": "/// items uri\n\npub fn item_uri<S>(host: &str, name: &str, namespace: &str, sub_resource: Option<&str>) -> Uri\n\nwhere\n\n S: Spec,\n\n{\n\n let ns = if S::NAME_SPACED {\n\n NameSpace::Named(namespace.to_owned())\n\n } else {\n\n NameSpace::All\n\n };\n\n let crd = S...
Rust
jlrs/src/error.rs
gobuki/jlrs
1867022ec178df83f9a29cc5c25b705e649599dc
use crate::value::array::Dimensions; use std::error::Error; use std::fmt::{Display, Formatter, Result as FmtResult}; pub type JlrsResult<T> = Result<T, Box<JlrsError>>; #[derive(Debug)] pub enum JlrsError { Other(Box<dyn Error + Send + Sync>), Exception(String), AlreadyInitialized, ConstAlreadyExist...
use crate::value::array::Dimensions; use std::error::Error; use std::fmt::{Display, Formatter, Result as FmtResult}; pub type JlrsResult<T> = Result<T, Box<JlrsError>>; #[derive(Debug)] pub enum JlrsError { Other(Box<dyn Error + Send + Sync>), Exception(String), AlreadyInitialized, ConstAlreadyExist...
!( formatter, "Cannot access value at index {} because the number of values is {}", idx, sz ), JlrsError::InvalidIndex(idx, sz) => write!( formatter, "Index {} is not valid for array with shape {}", i...
nSVec => write!(formatter, "This is not a simple vector"), JlrsError::NotAnSSAValue => write!(formatter, "This is not an SSA value"), JlrsError::NotATypeName => write!(formatter, "This is not a typename"), JlrsError::NotATypeVar => write!(formatter, "This is not a type var"), ...
random
[]
Rust
src/lib.rs
MaulingMonkey/lokacore
7ce53e93847b2a2003a16508cfc39a95071f4e4d
#![no_std] #![warn(missing_docs)] use core::{ marker::PhantomData, mem::{align_of, size_of}, num::*, ptr::NonNull, }; pub mod arch; mod marker; pub use marker::*; #[macro_export] macro_rules! branchless_abs { ($x:expr, $u:ty) => {{ let mask = $x >> ((core::mem::size_of::<$u>() * 8) - 1); ($x as $u...
#![no_std] #![warn(missing_docs)] use core::{ marker::PhantomData, mem::{align_of, size_of}, num::*, ptr::NonNull, }; pub mod arch; mod marker; pub use marker::*; #[macro_export] macro_rules! branchless_abs { ($x:expr, $u:ty) => {{ let mask = $x >> ((core::mem::size_of::<$u>() * 8) - 1); ($x as $u...
}
if core::mem::size_of_val(a) % size_of::<B>() == 0 { let new_len = core::mem::size_of_val(a) / size_of::<B>(); Ok(unsafe { core::slice::from_raw_parts_mut(a.as_ptr() as *mut B, new_len) }) } else { Err(PodCastError::OutputSliceWouldHaveSlop) }
if_condition
[ { "content": "#[allow(bad_style)]\n\n#[inline(always)]\n\npub fn prefetch_T2(p: *const impl Sized) {\n\n unsafe { _mm_prefetch(p as *const i8, _MM_HINT_T2) }\n\n}\n\n\n\n/// Non-temporal prefetch hint.\n\n///\n\n/// This is the least amount of hinting, but can avoid polluting the cache\n\n/// accidentally (eg:...
Rust
src/render/portable/utils.rs
koesterlab/datavzrd
1d1f1c0d5ea30f0072189640f03114f5f6a0942d
use crate::spec::ItemsSpec; use anyhow::Result; use std::fs; use std::fs::File; use std::io::Write; use std::path::Path; use tera::{Context, Tera}; pub(crate) fn render_static_files<P: AsRef<Path>>(path: P) -> Result<()> { let path = Path::new(path.as_ref()).join("static"); fs::create_dir(&path)?; let file...
use crate::spec::ItemsSpec; use anyhow::Result; use std::fs; use std::fs::File; use std::io::Write; use std::path::Path; use tera::{Context, Tera}; pub(crate) fn render_static_files<P: AsRef<Path>>(path: P) -> Result<()> {
/../../static/showdown.min.js"), ), ( "bootstrap-select.min.js", include_str!("../../../static/bootstrap-select.min.js"), ), ( "bootstrap-select.min.css", include_str!("../../../static/bootstrap-select.min.css"), ), ]; for ...
let path = Path::new(path.as_ref()).join("static"); fs::create_dir(&path)?; let files = vec![ ( "bootstrap.bundle.min.js", include_str!("../../../static/bootstrap.bundle.min.js"), ), ( "bootstrap-table.min.js", include_str!("../../../stati...
random
[ { "content": "fn main() -> Result<()> {\n\n let opt = cli::Datavzrd::from_args();\n\n let _ = SimpleLogger::init(LevelFilter::Warn, Config::default());\n\n let config = ItemsSpec::from_file(&opt.config)?;\n\n config.validate()?;\n\n\n\n if !opt.output.exists() {\n\n std::fs::create_dir(&op...
Rust
crates/ruma-api-macros/src/api/parse.rs
Frinksy/ruma
0ad2e79b84556d85da7f5df0cd2b2b77fcc595e7
use std::{collections::BTreeSet, mem}; use syn::{ braced, parse::{Parse, ParseStream}, spanned::Spanned, visit::Visit, Attribute, Field, Ident, Lifetime, Token, Type, }; use super::{ attribute::{Meta, MetaNameValue}, request::{RequestField, RequestFieldKind, RequestLifetimes}, response...
use std::{collections::BTreeSet, mem}; use syn::{ braced, parse::{Parse, ParseStream}, spanned::Spanned, visit::Visit, Attribute, Field, Ident, Lifetime, Token, Type, }; use super::{ attribute::{Meta, MetaNameValue}, request::{RequestField, RequestFieldKind, RequestLifetimes}, response...
Ok(Response { attributes, fields }) } fn has_lifetime(ty: &Type) -> bool { let mut lifetimes = BTreeSet::new(); collect_lifetime_idents(&mut lifetimes, ty); !lifetimes.is_empty() } fn collect_lifetime_idents(lifetimes: &mut BTreeSet<Lifetime>, ty: &Type) { struct Visitor<'lt>(&'lt mut BTreeSet<L...
if newtype_body_field.is_some() && fields.iter().any(|f| f.is_body()) { return Err(syn::Error::new_spanned( response_kw, "Can't have both a newtype body field and regular body fields", )); }
if_condition
[ { "content": "fn set_field<T: ToTokens>(field: &mut Option<T>, value: T) -> syn::Result<()> {\n\n match field {\n\n Some(existing_value) => {\n\n let mut error = syn::Error::new_spanned(value, \"duplicate field assignment\");\n\n error.combine(syn::Error::new_spanned(existing_val...
Rust
src/packet.rs
wfdewith/embedded-mqtt
551e052b9661dae739763c0c577500464f3b0fd2
use core::{cmp::min, convert::TryFrom, default::Default, result::Result}; use crate::{ codec::{Decodable, Encodable}, error::{DecodeError, EncodeError}, fixed_header::{self, FixedHeader}, payload::{self, Payload}, qos, status::Status, variable_header::{self, VariableHeader}, }; #[derive(De...
use core::{cmp::min, convert::TryFrom, default::Default, result::Result}; use crate::{ codec::{Decodable, Encodable}, error::{DecodeError, EncodeError}, fixed_header::{self, FixedHeader}, payload::{self, Payload}, qos, status::Status, variable_header::{self, VariableHeader}, }; #[derive(De...
pub fn fixed_header(&self) -> &FixedHeader { &self.fixed_header } pub fn variable_header(&self) -> &Option<VariableHeader> { &self.variable_header } pub fn payload(&self) -> &Payload { &self.payload } } impl<'a> Decodable<'a> for Packet<'a> {...
Self { fixed_header: FixedHeader::new(r#type, flags, len), variable_header, payload, }) }
function_block-function_prefixed
[ { "content": "pub fn encode_u8(value: u8, bytes: &mut [u8]) -> Result<usize, EncodeError> {\n\n if bytes.is_empty() {\n\n return Err(EncodeError::OutOfSpace);\n\n }\n\n\n\n bytes[0] = value;\n\n Ok(1)\n\n}\n\n\n", "file_path": "src/codec/values.rs", "rank": 0, "score": 131955.5399...
Rust
src/config_core/methods.rs
exogress/exogress
643ac113066ce0d517929f518c6ca47f1ec23b35
use crate::{ config_core::rule::MethodWrapper, entities::schemars::{gen::SchemaGenerator, schema::Schema}, }; use schemars::JsonSchema; use core::fmt; use http::Method; use schemars::schema::{ArrayValidation, InstanceType, SchemaObject, StringValidation}; use serde::{ de, de::{SeqAccess, Visitor}, ...
use crate::{ config_core::rule::MethodWrapper, entities::schemars::{gen::SchemaGenerator, schema::Schema}, }; use schemars::JsonSchema; use core::fmt; use http::Method; use schemars::schema::{ArrayValidation, InstanceType, SchemaObject, StringValidation}; use serde::{ de, de::{SeqAccess, Visitor}, ...
}
pub fn test_parsing_star() { const YAML: &str = r#"--- "*" "#; let parsed = serde_yaml::from_str::<MethodMatcher>(YAML).unwrap(); assert_eq!(parsed, MethodMatcher::All); let s = serde_json::to_string(&parsed).unwrap(); assert_eq!(s, "\"*\""); }
function_block-full_function
[ { "content": "pub fn validate_schema(yaml_data: impl AsRef<[u8]>, schema_file_name: &str) -> anyhow::Result<()> {\n\n let cfg: serde_yaml::Value = serde_yaml::from_slice(yaml_data.as_ref())?;\n\n let version = cfg\n\n .get(\"version\")\n\n .ok_or_else(|| anyhow!(\"no version supplied\"))\n\n...
Rust
src/hook.rs
nsoudee/weechat-discord
a571a1c6ab519cfd09d5e9ceb9eb94bc34db8c18
use crate::{ buffers, discord, discord::DISCORD, ffi::{self, *}, plugin_print, }; use dirs; use serenity::{ model::{ channel::Channel, id::{ChannelId, GuildId}, }, prelude::RwLock, CACHE, }; use std::{fs, ptr, sync::Arc, thread, time::Duration}; static mut MAIN_COMMAND_H...
use crate::{ buffers, discord, discord::DISCORD, ffi::{self, *}, plugin_print, }; use dirs; use serenity::{ model::{ channel::Channel, id::{ChannelId, GuildId}, }, prelude::RwLock, CACHE, }; use std::{fs, ptr, sync::Arc, thread, time::Duration}; static mut MAIN_COMMAND_H...
unsafe { MAIN_COMMAND_HOOK = Box::into_raw(Box::new(main_cmd_hook)); BUFFER_SWITCH_CB = Box::into_raw(Box::new(buffer_switch_hook)); TIMER_HOOK = Box::into_raw(Box::new(timer_hook)); QUERY_CMD_HOOK = Box::into_raw(Box::new(query_hook)); NICK_CMD_HOOK = Box::into_raw(Box::new(ni...
weechat_cmd::ARGS, weechat_cmd::ARGDESC, weechat_cmd::COMPLETIONS, move |buffer, input| run_command(&buffer, input), )?; let query_hook = ffi::hook_command_run("/query", handle_query)?; let nick_hook = ffi::hook_command_run("/nick", handle_nick)?; let buffer_switch_hook = ff...
function_block-random_span
[ { "content": "pub fn hook_command<F: FnMut(Buffer, &str) + 'static>(\n\n cmd: &str,\n\n desc: &str,\n\n args: &str,\n\n argdesc: &str,\n\n compl: &str,\n\n func: F,\n\n) -> Option<HookCommand> {\n\n type CB = FnMut(Buffer, &str);\n\n extern \"C\" {\n\n fn wdc_hook_command(\n\n ...
Rust
src/rqpoly.rs
shubho/Cupcake
0abda2783d028734a4b1991659dae069ad2749ef
use crate::integer_arith::{SuperTrait, ArithUtils}; use crate::polyarith::lazy_ntt::{lazy_ntt_u64, lazy_inverse_ntt_u64}; use crate::integer_arith::util::compute_harvey_ratio; use crate::utils::reverse_bits_perm; use std::sync::Arc; use crate::traits::*; #[derive(Debug)] pub struct RqPolyContext<T> { pub n: us...
use crate::integer_arith::{SuperTrait, ArithUtils}; use crate::polyarith::lazy_ntt::{lazy_ntt_u64, lazy_inverse_ntt_u64}; use crate::integer_arith::util::compute_harvey_ratio; use crate::utils::reverse_bits_perm; use std::sync::Arc; use crate::traits::*; #[derive(Debug)] pub struct RqPolyContext<T> { pub n: us...
.is_ntt_form } fn set_ntt_form(&mut self, value: bool) { self.is_ntt_form = value; } fn forward_transform(&mut self) { self.lazy_ntt() } fn inverse_transform(&mut self) { self.lazy_inverse_ntt() } } impl<T> FastPolyMultiply<T> for RqPoly<T> where T: SuperTrait<T>{...
; s = T::modulus(&s, &self.q); let mut spow = T::pow_mod(&s, &power, &self.q); let max_iter = 100; let mut iter = 0; while T::pow_mod(&spow, &bign, &self.q) != q_minus_one && iter < max_iter { s = T::add_mod(&s, &one, &self.q); spow = T::pow_m...
random
[ { "content": "pub fn lazy_inverse_ntt_u64(vec: &mut [u64], invroots: &[u64], scaled_invroots: &[u64], q: u64){\n\n let twoq = q << 1; \n\n\n\n let mut t = 1;\n\n let mut m = vec.len();\n\n while m > 1 {\n\n let mut j1 = 0;\n\n let h = m >> 1;\n\n for i in 0..h {\n\n l...
Rust
src/footprint/de.rs
racklet/kicad-parse-gen
83c14bd9468089f4796f005423b9223ed26c911f
use Sexp; use footprint; use footprint::data::*; use wrap; use symbolic_expressions::iteratom::*; use symbolic_expressions::SexpError; #[derive(Debug)] enum Part { Thickness(f64), Net(footprint::Net), SolderPasteMargin(f64), SolderMaskMargin(f64), Clearance(f64), ThermalGap(f64), ThermalW...
use Sexp; use footprint; use footprint::data::*; use wrap; use symbolic_expressions::iteratom::*; use symbolic_expressions::SexpError; #[derive(Debug)] enum Part { Thickness(f64), Net(footprint::Net), SolderPasteMargin(f64), SolderMaskMargin(f64), Clearance(f64), ThermalGap(f64), ThermalW...
} impl FromSexp for FpArc { fn from_sexp(s: &Sexp) -> Result<FpArc, SexpError> { let mut i = IterAtom::new(s, "fp_arc")?; let mut fp_arc = FpArc::default(); if let Some(xy) = i.maybe_t::<Xy>() { if xy.t == XyType::Start { fp_arc.start = xy; } ...
y; } } if let Some(xy) = i.maybe_t::<Xy>() { if xy.t == XyType::End { fp_circle.end = xy; } } if let Some(layer) = i.maybe_t::<Layer>() { fp_circle.layer = layer; } if let Some(width) = i.maybe_f_in_list("wid...
function_block-function_prefixed
[ { "content": "fn wrap<X, Y, F, G>(s: &Sexp, make: F, wrapper: G) -> result::Result<Y,SexpError>\n\nwhere\n\n F: Fn(&Sexp) -> result::Result<X,SexpError>,\n\n G: Fn(X) -> Y,\n\n{\n\n Ok(wrapper(make(s)?))\n\n}\n\n\n\n#[derive(Debug)]\n\n/// A bounding box\n\npub struct Bound {\n\n /// smaller x\n\n ...
Rust
tests/core/conversion.rs
tvincent2/nalgebra
3aeb2549d85a9847f6d4d334fc0a8eb142808809
#![cfg(feature = "arbitrary")] use alga::linear::Transformation; use na::{ self, Vector1, Vector2, Vector3, Vector4, Vector5, Vector6, RowVector1, RowVector2, RowVector3, RowVector4, RowVector5, RowVector6, Matrix2, Matrix3, Matrix4, Matrix5, Matrix6, Matrix2x3, Matrix2x4, Matrix2x5, Matrix2x6, ...
#![cfg(feature = "arbitrary")] use alga::linear::Transformation; use na::{ self, Vector1, Vector2, Vector3, Vector4, Vector5, Vector6, RowVector1, RowVector2, RowVector3, RowVector4, RowVector5, RowVector6, Matrix2, Matrix3, Matrix4, Matrix5, Matrix6, Matrix2x3, Matrix2x4, Matrix2x5, Matrix2x6, ...
atrix_conversion_3_2, Matrix3x2, (3, 2); array_matrix_conversion_3_3, Matrix3, (3, 3); array_matrix_conversion_3_4, Matrix3x4, (3, 4); array_matrix_conversion_3_5, Matrix3x5, (3, 5); array_matrix_conversion_3_6, Matrix3x6, (3, 6); array_matrix_conversion_4_2, Matrix4x2, (4, 2); array_matrix_c...
iso * p, epsilon = 1.0e-7) && relative_eq!(r * p, sim * p, epsilon = 1.0e-7) && r * p == aff * p && r * p == prj * p && r * p == tr * p } fn unit_quaternion_conversion(uq: UnitQuaternion<f64>, v: Vector3<f64>, p: Point3<f64>) -> bool { let rot: Rotation3<f64> = na::c...
random
[ { "content": "/// Returns the component-wise comparison of `|x - y| < epsilon`.\n\n///\n\n/// True if this expression is not satisfied.\n\npub fn not_equal_columns_eps<N: Number, R: Dimension, C: Dimension>(x: &TMat<N, R, C>, y: &TMat<N, R, C>, epsilon: N) -> TVec<bool, C>\n\n where DefaultAllocator: Alloc<N...
Rust
crates/vm/src/module.rs
ggreif/wasminspect
28d7f7628a0ee67c57bdff9a4056a327dc702249
use super::address::*; use super::export::{ExportInstance, ExternalValue}; use std::collections::HashMap; use std::hash::Hash; #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)] pub struct ModuleIndex(pub u32); pub enum ModuleInstance { Defined(DefinedModuleInstance), Host(HostModuleInstance), } impl Module...
use super::address::*; use super::export::{ExportInstance, ExternalValue}; use std::collections::HashMap; use std::hash::Hash; #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)] pub struct ModuleIndex(pub u32); pub enum ModuleInstance { Defined(DefinedModuleInstance), Host(HostModuleInstance), } impl Module...
xport { Some(e) => match e.value() { ExternalValue::Memory(addr) => Ok(Some(addr.clone())), _ => Err(DefinedModuleError::TypeMismatch( "memory", e.value().ty().to_string(), )), }, None => Ok(None)...
d_memory(&self, name: String) -> DefinedModuleResult<Option<MemoryAddr>> { let export = self.exported_by_name(name); match e
function_block-random_span
[ { "content": "fn read_name_section(reader: wasmparser::NameSectionReader) -> Result<HashMap<u32, String>> {\n\n // let mut module_name = None;\n\n let mut func_names = HashMap::new();\n\n // let mut locals_names = HashMap::new();\n\n for i in reader.into_iter() {\n\n match i? {\n\n ...
Rust
src/httprequest.rs
allthingssecurity/wasmrust
cc93f2da56f33ad9b6f0bd4dd73c5948ab90253c
use std::collections::HashMap; #[derive(Debug, PartialEq)] pub enum Resource { Path(String), } #[derive(Debug)] pub struct HttpRequest { pub method: Method, pub version: Version, pub resource: Resource, pub headers: HashMap<String, String>, pub msg_body: String, } impl From<String> for HttpRe...
use std::collections::HashMap; #[derive(Debug, PartialEq)] pub enum Resource { Path(String), } #[derive(Debug)] pub struct HttpRequest { pub method: Method, pub version: Version, pub resource: Resource, pub headers: HashMap<String, String>, pub msg_body: String, } impl From<String> for HttpRe...
} fn process_req_line(s: &str) -> (Method, Resource, Version) { let mut words = s.split_whitespace(); let method = words.next().unwrap(); let resource = words.next().unwrap(); let version = words.next().unwrap(); ( method.into(), Resource::Path(resource.to_stri...
fn from(req: String) -> Self { let mut parsed_method = Method::Uninitialized; let mut parsed_version = Version::V1_1; let mut parsed_resource = Resource::Path("".to_string()); let mut parsed_headers = HashMap::new(); let mut parsed_msg_body = ""; for line in req...
function_block-full_function
[ { "content": "pub fn runs_wapc_guest(guest:&WapcHost,body:&String) -> Result<String, Box<dyn Error>> {\n\n//let guest = WapcHost::new(Box::new(*engine), move |_a, _b, _c, _d, _e| Ok(vec![]))?;\n\n/* let args: Vec<String> = env::args().collect();\n\n\n\n let wasmpath= &args[1];\n\n let key = &args[2];\n\nl...
Rust
src/rendering/font.rs
Ynscription/livesplit-core
1027a92faaf8eeb14ce8be8a32ce8d3f202bc664
use super::glyph_cache::GlyphCache; use super::{decode_color, Backend, Pos, Transform}; use crate::settings::Color; use rusttype::{point, Codepoint, Font, GlyphId, PositionedGlyph, Scale}; use smallvec::SmallVec; #[derive(Copy, Clone)] pub struct ScaledFont<'f, 'fd> { font: &'f Font<'fd>, scale: Scale, } pub ...
use super::glyph_cache::GlyphCache; use super::{decode_color, Backend, Pos, Transform}; use crate::settings::Color; use rusttype::{point, Codepoint, Font, GlyphId, PositionedGlyph, Scale}; use smallvec::SmallVec; #[derive(Copy, Clone)] pub struct ScaledFont<'f, 'fd> { font: &'f Font<'fd>, scale: Scale, } pub ...
g.into_unpositioned() .positioned(point(pos.x - offset, pos.y)) }) } pub fn layout_numbers<'i: 'fd, 'fd>( font: ScaledFont<'i, 'fd>, text: &'i str, [mut x, y]: Pos, ) -> impl Iterator<Item = PositionedGlyph<'fd>> + Clone + 'i { let scale = font.scale; let mut digits = [Gly...
if is_first { if pos.x - offset < min_x { offset = pos.x - min_x; } is_first = false; }
if_condition
[ { "content": "pub fn text<R, F, E>(reader: &mut Reader<R>, buf: &mut Vec<u8>, f: F) -> Result<(), E>\n\nwhere\n\n R: BufRead,\n\n F: FnOnce(Cow<'_, str>),\n\n E: From<Error> + From<string::FromUtf8Error> + From<str::Utf8Error>,\n\n{\n\n text_err(reader, buf, |t| {\n\n f(t);\n\n Ok(())\...
Rust
2022/postgresql_insert_performance/rust/src/main.rs
sthagen/skerkour-kerkour.com
eab659e57dd3a84973a74e88d15d913a1acaf1c5
mod db; use chrono::{DateTime, Utc}; use db::DB; use futures::{stream, StreamExt}; use rand::distributions::Alphanumeric; use rand::Rng; use serde::{Deserialize, Serialize}; use sqlx::types::Json; use std::time::{Duration, Instant}; use uuid::Uuid; const CONCURRENCY: u32 = 100; const EXECUTIONS: u64 = 50_000; const R...
mod db; use chrono::{DateTime, Utc}; use db::DB; use futures::{stream, StreamExt}; use rand::distributions::Alphanumeric; use rand::Rng; use serde::{Deserialize, Serialize}; use sqlx::types::Json; use std::time::{Duration, Instant}; use uuid::Uuid; const CONCURRENCY: u32 = 100; const EXECUTIONS: u64 = 50_000; const R...
payload: Json(payload), } } async fn insert_normalized(db: &DB) { const QUERY: &str = "INSERT INTO normalized (id, type, timestamp, received_at, payload) VALUES ($1, $2, $3, $4, $5)"; let stream = stream::iter(0..EXECUTIONS); let base_event = generate_event(); stream .for_each_co...
_| 0).collect(); let something_else2 = (0..500).into_iter().map(|_| 0).collect(); let something = rng .sample_iter(&Alphanumeric) .take(500) .map(char::from) .collect(); let payload = Payload { something, something_else, something_else2, }; E...
function_block-random_span
[ { "content": "#[derive(sqlx::FromRow, Serialize, Debug, Clone, Deserialize)]\n\nstruct KeyValueEvent {\n\n key: uuid::Uuid,\n\n value: Vec<u8>,\n\n}\n\n\n", "file_path": "blog/2022/postgresql_insert_performance/rust/src/main.rs", "rank": 0, "score": 207799.61378877048 }, { "content": "...
Rust
src/ignore_directives.rs
ross-weir/deno_lint
e1b3541ac732ddaaa485d1ad58800b701b1334a7
use crate::diagnostic::{LintDiagnostic, Position}; use once_cell::sync::Lazy; use regex::Regex; use std::collections::HashMap; use swc_common::comments::Comment; use swc_common::comments::CommentKind; use swc_common::BytePos; use swc_common::SourceMap; use swc_common::Span; static IGNORE_COMMENT_CODE_RE: Lazy<Regex> ...
use crate::diagnostic::{LintDiagnostic, Position}; use once_cell::sync::Lazy; use regex::Regex; use std::collections::HashMap; use swc_common::comments::Comment; use swc_common::comments::CommentKind; use swc_common::BytePos; use swc_common::SourceMap; use swc_common::Span; static IGNORE_COMMENT_CODE_RE: Lazy<Regex> ...
des, vec!["no-explicit-any", "no-empty", "no-debugger"]); let d = &directives[3]; assert_eq!( d.position, Position { line: 17, col: 3, byte_pos: 388 } ); assert_eq!(d.codes, vec!["ban-types"]); } }
-any, no-empty, no-debugger function foo(): any {} // deno-lint-ignore no-explicit-any,no-empty,no-debugger function foo(): any {} export function deepAssign( target: Record<string, any>, ...sources: any[] ): // deno-lint-ignore ban-types object | undefined {} "#; let ast_parser = AstParser::new(); let (_pr...
function_block-random_span
[ { "content": "pub fn assert_lint_ok<T: LintRule + 'static>(source: &str) {\n\n let rule = T::new();\n\n let diagnostics = lint(rule, source);\n\n if !diagnostics.is_empty() {\n\n panic!(\n\n \"Unexpected diagnostics found:\\n{:#?}\\n\\nsource:\\n{}\\n\",\n\n diagnostics, source\n\n );\n\n }\...
Rust
src/v5/mod.rs
alexkirsz/socksv5
07c4af6ab288332d7664c5f3ceefd8a443a5904c
use byteorder::{BigEndian, ByteOrder}; #[cfg(not(feature = "tokio"))] use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use thiserror::Error; #[cfg(feature = "tokio")] use tokio_compat::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; mod types; use crate::SocksVersion; pub use types::*;...
use byteorder::{BigEndian, ByteOrder}; #[cfg(not(feature = "tokio"))] use futures::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use thiserror::Error; #[cfg(feature = "tokio")] use tokio_compat::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; mod types; use crate::SocksVersion; pub use types::*;...
pub async fn read_handshake_skip_version<Reader>(mut reader: Reader) -> SocksV5HandshakeResult where Reader: AsyncRead + Unpin, { let mut nmethods = [0u8]; reader.read_exact(&mut nmethods).await?; let nmethods = nmethods[0]; if nmethods == 0 { return Err(SocksV5HandshakeError::InvalidHand...
pub async fn read_handshake<Reader>(mut reader: Reader) -> SocksV5HandshakeResult where Reader: AsyncRead + Unpin, { let mut version = [0u8]; reader.read_exact(&mut version).await?; let version = version[0]; if version != SocksVersion::V5.to_u8() { return Err(SocksV5HandshakeError::InvalidV...
function_block-full_function
[ { "content": " pub(crate) fn to_u8(&self) -> u8 {\n\n match self {\n\n SocksV5AuthMethod::Noauth => 0x00,\n\n SocksV5AuthMethod::Gssapi => 0x01,\n\n SocksV5AuthMethod::UsernamePassword => 0x02,\n\n SocksV5AuthMethod::NoAcceptableMethod => 0xff,\n\n ...
Rust
tb_ecs/src/system/data.rs
moca-f/toybox
af71ef26b2530f3339118a0c1b0010bd58d98573
use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; pub(crate) use crate::system::data::access_order::AccessOrder; use crate::world::{Resource, ResourceId}; use crate::World; pub trait SystemData<'r> { unsafe fn fetch(world: &'r World) -> Self; fn reads_before_write() -> V...
use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; pub(crate) use crate::system::data::access_order::AccessOrder; use crate::world::{Resource, ResourceId}; use crate::World; pub trait SystemData<'r> { unsafe fn fetch(world: &'r World) -> Self; fn reads_before_write() -> V...
fn reads_before_write() -> Vec<ResourceId> { vec![ResourceId::new::<R>()] } } impl<'r, R: Resource> SystemData<'r> for Write<'r, R> { unsafe fn fetch(world: &'r World) -> Self { Write { resource: world.fetch_mut(), _phantom: Default::default(), } } ...
unsafe fn fetch(world: &'r World) -> Self { RBW { resource: world.fetch(), _phantom: Default::default(), } }
function_block-function_prefix_line
[ { "content": "pub trait Resource: 'static + Sync {}\n\n\n\nimpl<R: 'static + Sync> Resource for R {}\n\n\n\npub struct ResourceChangeEvent {}\n\n\n\nimpl ResourceChangeEvent {\n\n fn new() -> Self {\n\n Self {}\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::World;\n\n\n\n struct...
Rust
src/lib.rs
msiglreith/raw-window-handle
b59a774f2990edeb30fad64b56f7be3b4bb05740
#![cfg_attr(feature = "nightly-docs", feature(doc_cfg))] #![no_std] #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "android")))] #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "android"))] pub mod android; #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "ios")))] #[cfg_attr(not(feature ...
#![cfg_attr(feature = "nightly-docs", feature(doc_cfg))] #![no_std] #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "android")))] #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "android"))] pub mod android; #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "ios")))] #[cfg_attr(not(feature ...
] pub enum RawWindowHandle { #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "ios")))] #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "ios"))] IOS(ios::IOSHandle), #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "macos")))] #[cfg_attr(not(feature = "nightly-docs"), cfg(...
mod ios; #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "macos")))] #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "macos"))] pub mod macos; #[cfg_attr( feature = "nightly-docs", doc(cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", ...
random
[ { "content": "use core::ptr;\n\nuse libc::c_void;\n\n\n\n/// Raw window handle for Android.\n\n///\n\n/// ## Construction\n\n/// ```\n\n/// # use raw_window_handle::android::AndroidHandle;\n\n/// let handle = AndroidHandle {\n\n/// /* fields */\n\n/// ..AndroidHandle::empty()\n\n/// };\n\n/// ```\n\n#[d...
Rust
rust/pact_mock_server/src/server_manager.rs
milleniumbug/pact-reference
e96dca8186e21829eb1ddbf1b5b6d27684625a06
use mock_server::MockServer; use pact_matching::models::{Pact}; use std::collections::BTreeMap; pub struct ServerManager { runtime: tokio::runtime::Runtime, mock_servers: BTreeMap<String, Box<MockServer>> } impl ServerManager { pub fn new() -> ServerManager { ServerManager { ...
use mock_server::MockServer; use pact_matching::models::{Pact}; use std::collections::BTreeMap; pub struct ServerManager { runtime: tokio::runtime::Runtime, mock_servers: BTreeMap<String, Box<MockServer>> } impl ServerManager { pub fn new() -> ServerManager { ServerManager { ...
pub fn shutdown_mock_server_by_port(&mut self, port: u16) -> bool { debug!("Shutting down mock server with port {}", port); let result = self.mock_servers.iter() .find(|ms| ms.1.addr.port() == port) .map(|ms| ms.1.id.clone()); if let Some(id) = result { ...
match mock_server.shutdown() { Ok(()) => true, Err(_) => false } }, None => false } }
function_block-function_prefix_line
[ { "content": "/// Starts a mock server with the given ID, pact and port number. The ID needs to be unique. A port\n\n/// number of 0 will result in an auto-allocated port by the operating system. Returns the port\n\n/// that the mock server is running on wrapped in a `Result`.\n\n///\n\n/// # Errors\n\n///\n\n/...
Rust
static-events/src/events.rs
Lymia/static-events
8dd14c96c6f7e5a72e283dd8ff8d277847f0045e
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub enum EventResult { EvOk, EvCancelStage, EvCancel, } impl Default for EventResult { fn default() -> Self { EventResult::EvOk } } impl From<()> for EventResult { fn from(_: ()) -> Self { E...
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub enum EventResult { EvOk, EvCancelStage, EvCancel, } impl Default for EventResult { fn default() -> Self { EventResult::EvOk } } impl From<()> for EventResult { fn from(_: ()) -> Self { E...
f, state: T::State) -> T::State { state } } pub trait VoidEvent: Sized { } impl <T : VoidEvent> SimpleEvent for T { type State = (); fn starting_state(&self) { } }
: &mut T::State, result: EventResult) -> EventResult { result } fn to_return_value(self, state: T::State) -> T::RetVal { SimpleInterfaceEvent::to_return_value(self, state) } } pub trait SimpleEvent: Sized { type State: Send; fn starting_state(&self) -> Self:...
random
[ { "content": "/// The base trait used to mark asynchronous event dispatchers.\n\npub trait AsyncEvents: Events + Sync + Send { }\n\nimpl <T: AsyncEvents> AsyncEvents for Arc<T> { }\n\n\n\npub use static_events_derive::*;\n\n\n", "file_path": "static-events/src/handlers.rs", "rank": 2, "score": 13213...
Rust
tests/support/mod.rs
Shuenhoy/gluon_language-server
d7322580afcd55f1c124178d126aea83704a3bf7
#![allow(unused)] use std::{ collections::VecDeque, env, io::{self, BufRead, Write}, marker::Unpin, str, sync::{ mpsc::{sync_channel, Receiver, SyncSender, TryRecvError}, Arc, }, }; use { futures::{compat::*, prelude::*}, jsonrpc_core::{ id::Id, para...
#![allow(unused)] use std::{ collections::VecDeque, env, io::{self, BufRead, Write}, marker::Unpin, str, sync::{ mpsc::{sync_channel, Receiver, SyncSender, TryRecvError}, Arc, }, }; use { futures::{compat::*, prelude::*}, jsonrpc_core::{ id::Id, para...
pub fn send_rpc<F>(f: F) where F: for<'a> FnOnce( &'a mut (dyn AsyncWrite + Send + Unpin), &'a mut (dyn AsyncBufRead + Send + Unpin), ) -> futures::future::BoxFuture<'a, ()> + Send + ::std::panic::UnwindSafe + 'static, { run_no_panic_catch(async move { ...
stdout(Stdio::piped()) .spawn() .unwrap(); ServerHandle { stdin: Box::new(child.stdin.expect("stdin")), stdout: Box::new(BufReader::new(child.stdout.expect("stdout"))), } }
function_block-function_prefix_line
[ { "content": "pub fn write_message_str<W>(mut output: W, response: &str) -> io::Result<()>\n\nwhere\n\n W: Write,\n\n{\n\n debug!(\"Respond: {}\", response);\n\n write!(\n\n output,\n\n \"Content-Length: {}\\r\\n\\r\\n{}\",\n\n response.len(),\n\n response\n\n )?;\n\n ...
Rust
src/lazy.rs
Luro02/source-span
858cbd5f094277d7c4ec492ce34af5cb2741ca69
use std::cell::RefCell; use std::io::{Error, Result}; use crate::{Position, Span}; pub struct Buffer<I: Iterator<Item = Result<char>>> { p: RefCell<Inner<I>>, } struct Inner<I: Iterator<Item = Result<char>>> { input: I, error: Option<Error>, data: Vec<char>, lines...
use std::cell::RefCell; use std::io::{Error, Result}; use crate::{Position, Span}; pub struct Buffer<I: Iterator<Item = Result<char>>> { p: RefCell<Inner<I>>, } struct Inner<I: Iterator<Item = Result<char>>> { input: I, error: Option<Error>, data: Vec<char>, lines...
fn get(&mut self, i: usize) -> Option<Result<char>> { while i >= self.data.len() && self.read_line() {} if i >= self.data.len() { let mut error = None; std::mem::swap(&mut error, &mut self.error); match error { Some...
fn index_at(&mut self, pos: Position) -> Option<Result<usize>> { if pos < self.span.start() { None } else { while pos >= self.span.end() && self.read_line() {} if pos >= self.span.end() { let mut error = None; std::mem::swap(&mut error...
function_block-full_function
[ { "content": "/// A single line of [`Char`] in the formatted output.\n\nstruct Line {\n\n data: Vec<Char>,\n\n offset: usize,\n\n margin_color: Color,\n\n}\n\n\n\nimpl Line {\n\n #[must_use]\n\n fn new(margin: usize, margin_color: Color) -> Self {\n\n let mut data = Vec::new();\n\n ...
Rust
src/lib.rs
mrmekon/hn-rs
38595886a86a6e8a754f99ab61f274bf26050257
extern crate time; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; extern crate futures; extern crate serde_json; #[macro_use] extern crate serde_derive; use futures::future::Future; use futures::future::Either; use futures::stream::Stream; use std::str::FromStr; use std::time::Duration; use st...
extern crate time; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; extern crate futures; extern crate serde_json; #[macro_use] extern crate serde_derive; use futures::future::Future; use futures::future::Either; use futures::stream::Stream; use std::str::FromStr; use std::time::Duration; use st...
fn update_item_cache(client: &Client<HttpsConnector<HttpConnector>>, handle: &Handle, top: &RwLock<Vec<u64>>, cache: &Cache) { let stories = top.read().unwrap(); let stories: Vec<&u64> = stories.iter().filter(|s| { ...
o::ErrorKind::TimedOut, "Timed out requesting top list", ))) } Err(Either::A((error, _timeout))) => Err(error), Err(Either::B((timeout_error, _get))) => Err(From::from(timeout_error)), }); let got = core.run(timed_request)?; ...
function_block-function_prefixed
[ { "content": "fn main() {\n\n let hn = HackerNews::new();\n\n let ui_hn = hn.clone();\n\n let ui_thread = thread::spawn(move || {\n\n let hn = ui_hn;\n\n loop {\n\n println!(\"Refresh:\");\n\n for item in hn.into_iter() {\n\n println!(\"item: {}\", ite...
Rust
src/cli/handlers/download.rs
devmatteini/dra
3d559f627c081fd5c9666aeae7f061f899db13d8
use std::cmp; use std::fs::File; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use crate::cli::get_env; use crate::cli::handlers::common::{check_has_assets, fetch_release_for}; use crate::cli::handlers::{HandlerError, HandlerResult}; use crate::cli::progress_bar::ProgressBar; use crate::cli::select; use ...
use std::cmp; use std::fs::File; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use crate::cli::get_env; use crate::cli::handlers::common::{check_has_assets, fetch_release_for}; use crate::cli::handlers::{HandlerError, HandlerResult}; use crate::cli::progress_bar::ProgressBar; use crate::cli::select; use ...
pinner.stop(); Ok(()) } pub fn choose_output_path(&self, asset_name: &str) -> PathBuf { if self.install { return crate::cli::temp_file::temp_file(); } self.output .as_ref() .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(asse...
); let mut destination = Self::create_file(output_path)?; let mut downloaded = 0; let mut buffer = [0; 1024]; while let Ok(bytes_read) = stream.read(&mut buffer) { if bytes_read == 0 { break; } destination .write(&buffer...
random
[ { "content": "pub fn exec_command(name: &str, command: &mut Command) -> Result<(), String> {\n\n command\n\n .output()\n\n .map_err_with(format!(\"An error occurred executing '{}'\", name))\n\n .and_then(|output| handle_command_output(name, output))\n\n}\n\n\n", "file_path": "src/ins...
Rust
pkmnapi-db/src/db/pokemon_name.rs
kevinselwyn/pkmnapi
170e6b6c9a74e85c377137bc086793898c415125
use crate::error::Result; use crate::patch::*; use crate::string::*; use crate::PkmnapiDB; use std::collections::HashMap; impl PkmnapiDB { pub fn get_pokemon_name_all(&self, pokedex_ids: &Vec<u8>) -> Result<HashMap<u8, PokemonName>> { self.get_all(pokedex_ids, |id| self.get_pokemon_name(id)) } ...
use crate::error::Result; use crate::patch::*; use crate::string::*; use crate::PkmnapiDB; use std::collections::HashMap; impl PkmnapiDB { pub fn get_pokemon_name_all(&self, pokedex_ids: &Vec<u8>) -> Result<HashMap<u8
s usize) * 0x0A); let pokemon_name = PokemonName::from(&self.rom[offset..(offset + 0x0A)]); Ok(pokemon_name) } pub fn set_pokemo...
, PokemonName>> { self.get_all(pokedex_ids, |id| self.get_pokemon_name(id)) } pub fn get_pokemon_name(&self, pokedex_id: &u8) -> Result<PokemonName> { let internal_id = self.pokede...
random
[ { "content": "#[allow(non_snake_case)]\n\npub fn load_rom() -> PkmnapiDB {\n\n let PKMN_ROM = env::var(\"PKMN_ROM\")\n\n .expect(\"Set the PKMN_ROM environment variable to point to the ROM location\");\n\n\n\n let rom = fs::read(PKMN_ROM).unwrap();\n\n\n\n PkmnapiDB::new(&rom).build().unwrap()\n...
Rust
whisper/src/diff.rs
GiantPlantsSociety/graphite-rs
d2657ae3ddf110023417ec255f5192ac8fa83bfc
use super::*; use crate::interval::Interval; use std::fmt; use std::io; use std::path::Path; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct DiffPoint { #[serde(rename = "timestamp")] pub interval: u32, #[serde(rename = "value_a")] pub value1: Option<f64>, #[serde(rename = "va...
use super::*; use crate::interval::Interval; use std::fmt; use std::io; use std::path::Path; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct DiffPoint { #[serde(rename = "timestamp")] pub interval: u32, #[serde(rename = "value_a")] pub value1: Option<f64>, #[serde(rename = "va...
} #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct DiffArchiveShort { #[serde(rename = "archive")] pub index: usize, pub total: usize, pub points: usize, } impl From<DiffArchive> for DiffArchiveShort { fn from(w: DiffArchive) -> DiffArchiveShort { DiffArchiveShort { ...
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if f.alternate() { write!( f, "{:>7} {:>11} {:>13} {:>13}", "archive", "timestamp", "value_a", "value_b" )?; } else { write!(f, "archive timestamp value_a value_...
function_block-full_function
[ { "content": "pub fn parse_duration(s: &str) -> Result<u32, String> {\n\n lazy_static! {\n\n static ref RETENTION_DEF_RE: Regex = Regex::new(r#\"(?i)^\\s*(\\d+)([a-z]*)\\s*$\"#).unwrap();\n\n }\n\n\n\n let captures = RETENTION_DEF_RE\n\n .captures(s)\n\n .ok_or_else(|| format!(\"In...
Rust
crates/webview/src/app/toolbar_view.rs
ivanceras/diwata
5b9d1efc623d6bc40b867fb45983238ef484ab01
use crate::widgets; use sauron::{ html::{attributes::*, events::*, units::*, *}, Cmd, Component, Node, }; use sqlparser::{dialect::GenericSqlDialect, sqlparser::Parser}; #[derive(Debug, PartialEq, Clone)] pub enum Msg { ToggleShowQuery, ToggleShowRelatedTabs, ChangeQuickFind(String), QueryChang...
use crate::widgets; use sauron::{ html::{attributes::*, events::*, units::*, *}, Cmd, Component, Node, }; use sqlparser::{dialect::GenericSqlDialect, sqlparser::Parser}; #[derive(Debug, PartialEq, Clone)] pub enum Msg { ToggleShowQuery, ToggleShowRelatedTabs, ChangeQuickFind(String), QueryChang...
), styles(vec![ ("width", px(self.run_query_button_width())), ("height", px(self.run_query_button_height())), ]), ], vec![text("...
vec![ header( vec![class("toolbar")], vec![ widgets::quick_find(35, oninput(|input| Msg::ChangeQuickFind(input.value))), button(vec![], vec![text("Create new record")]), button(vec![],...
random
[ { "content": "pub fn quick_find<MSG>(h: i32, event: Attribute<MSG>) -> Node<MSG>\n\nwhere\n\n MSG: Clone,\n\n{\n\n div(\n\n vec![class(\"quick_find_widget\")],\n\n vec![\n\n div(\n\n vec![class(\"quick_search_icon\")],\n\n vec![assets::svg_search_icon...
Rust
src/window.rs
K-C-DaCosta/fluffl
60d21a50515af351c0e1f798fb6e15916602c562
use std::cell::{Ref, RefCell, RefMut}; use std::collections::HashMap; use std::fmt; use std::sync::Arc; use super::parsers::xml::*; use crate::audio::FlufflAudioContext; use crate::FlufflError; use glow::*; pub use event_util::FlufflEvent; pub use glow; pub use window_util::*; pub mod event_util; #[cfg(feature = "d...
use std::cell::{Ref, RefCell, RefMut}; use std::collections::HashMap; use std::fmt; use std::sync::Arc; use super::parsers::xml::*; use crate::audio::FlufflAudioContext; use crate::FlufflError; use glow::*; pub use event_util::FlufflEvent; pub use glow; pub use window_util::*; pub mod event_util; #[cfg(feature = "d...
}
fn get_touch_displacement(id: i32, new_pos: [f32; 2]) -> [f32; 2] { let touch_table = Self::get_tracker_mut(); let old_pos = touch_table .get(&id) .map(|&x| x.prev_pos) .unwrap_or([0., 0.]); let disp = [new_pos[0] - old_pos[0], new_pos[1] - old_pos[1]]; ...
function_block-full_function
[ { "content": "/// # Description \n\n/// fetches entire file, but instead user has to read contents through a callback\n\n/// this is done to avoid blocking if one doesn't need it \n\n/// this function only really does non-blocking reads in wasm target AFAICT\n\npub fn load_file_cb<F>(file_path: &str,mut cb:F)\n...
Rust
noria/src/view.rs
harksin/noria
5b8e96f4181379e8a1c2991d4382aba44521b0ba
use crate::channel::rpc::RpcClient; use crate::data::*; use crate::error::TransportError; use crate::{ExclusiveConnection, SharedConnection}; use nom_sql::ColumnSpecification; use petgraph::graph::NodeIndex; use std::cell::RefCell; use std::collections::HashMap; use std::io; use std::net::SocketAddr; use std::rc::Rc; ...
use crate::channel::rpc::RpcClient; use crate::data::*; use crate::error::TransportError; use crate::{ExclusiveConnection, SharedConnection}; use nom_sql::ColumnSpecification; use petgraph::graph::NodeIndex; use std::cell::RefCell; use std::collections::HashMap; use std::io; use std::net::SocketAddr; use std::rc::Rc; ...
} else { assert!(keys.iter().all(|k| k.len() == 1)); let mut shard_queries = vec![Vec::new(); self.shards.len()]; for key in keys { let shard = crate::shard_by(&key[0], self.shards.len()); shard_queries[shard].push(key); } ...
match reply { ReadReply::Normal(Ok(rows)) => Ok(rows), ReadReply::Normal(Err(())) => Err(ViewError::NotYetAvailable), _ => unreachable!(), }
if_condition
[]
Rust
src/raw.rs
Cassy343/quartz_nbt
5f4d752e8de683cd628131c3c82bbfa60fe4c8ec
use crate::{io::NbtIoError, NbtTag}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::{ io::{Read, Result, Write}, mem::ManuallyDrop, ptr, result::Result as StdResult, slice, }; #[inline] pub const fn id_for_tag(tag: Option<&NbtTag>) -> u8 { match tag { None => 0x0, ...
use crate::{io::NbtIoError, NbtTag}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::{ io::{Read, Result, Write}, mem::ManuallyDrop, ptr, result::Result as StdResult, slice, }; #[inline] pub const fn id_for_tag(tag: Option<&NbtTag>) -> u8 { match tag { None => 0x0, ...
#[inline] unsafe fn convert_be_int_array_in_place<I, const SIZE: usize>( mut bytes: Vec<u8>, convert: fn([u8; SIZE]) -> I, ) -> Vec<I> { let mut buf: [u8; SIZE]; let mut read = bytes.as_ptr() as *const [u8; SIZE]; let mut write = bytes.as_mut_ptr() as *mut I; let end = bytes.as_ptr().add(byte...
reader.read_exact(&mut bytes)?; Ok(unsafe { convert_be_int_array_in_place::<i64, 8>(bytes, i64::from_be_bytes) }) }
function_block-function_prefix_line
[ { "content": "#[inline]\n\nfn read_tag_body_const<R: Read, const TAG_ID: u8>(reader: &mut R) -> Result<NbtTag, NbtIoError> {\n\n let tag = match TAG_ID {\n\n 0x1 => NbtTag::Byte(raw::read_i8(reader)?),\n\n 0x2 => NbtTag::Short(raw::read_i16(reader)?),\n\n 0x3 => NbtTag::Int(raw::read_i32...
Rust
pr47-core/src/data/mod.rs
CousinZe/Pr47
fce3c0239f5db79e93945db474cbeb5ce718da30
pub mod exception; pub mod generic; pub mod traits; pub mod tyck; pub mod value_typed; pub mod wrapper; use std::marker::PhantomData; use std::mem::{MaybeUninit, transmute}; use unchecked_unwrap::UncheckedUnwrap; use xjbutil::mem::move_to_heap; use xjbutil::unchecked::UnsafeFrom; use xjbutil::void::Void; use xjbutil:...
pub mod exception; pub mod generic; pub mod traits; pub mod tyck; pub mod value_typed; pub mod wrapper; use std::marker::PhantomData; use std::mem::{MaybeUninit, transmute}; use unchecked_unwrap::UncheckedUnwrap; use xjbutil::mem::move_to_heap; use xjbutil::unchecked::UnsafeFrom; use xjbutil::void::Void; use xjbutil:...
} #[cfg(any(test, feature = "bench"))] impl Debug for Value { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { if self.is_value() { unsafe { match ValueTypeTag::unsafe_from((self.vt_data.tag as u8) & VALUE_TYPE_TAG_MASK) { ValueTypeTag::Int => writ...
d() ); #[cfg(not(debug_assertions))] dyn_base.as_mut().unchecked_unwrap().move_out( &mut maybe_uninit as *mut _ as *mut () ); maybe_uninit.assume_init() }
function_block-function_prefixed
[ { "content": "pub fn create_test_container_vt<T: 'static>(tyck_info_pool: &mut TyckInfoPool) -> GenericTypeVT\n\n where Void: StaticBase<T>\n\n{\n\n let elem_tyck_info: NonNull<TyckInfo> = <Void as StaticBase<T>>::tyck_info(tyck_info_pool);\n\n let tyck_info: NonNull<TyckInfo> =\n\n tyck_info_po...
Rust
rust/src/day16.rs
bwestlin/advent-of-code-2015-retro
2b5a3f4d04e327416647d59f08e661e8413f1d1d
extern crate utils; use std::env; use std::str::FromStr; use std::num::ParseIntError; use std::io::{self, BufReader}; use std::io::prelude::*; use std::fs::File; use utils::*; type Input = Vec<Sue>; #[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] enum Component { Children, Cats, Samoyeds, Pomeranians, Akitas,...
extern crate utils; use std::env; use std::str::FromStr; use std::num::ParseIntError; use std::io::{self, BufReader}; use std::io::prelude::*; use std::fs::File; use utils::*; type Input = Vec<Sue>; #[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] enum Component { Children, Cats, Samoyeds, Pomeranians, Akitas,...
} } matches } } impl FromStr for Sue { type Err = ParseIntError; fn from_str(s: &str) -> Result<Self, Self::Err> { let (n, c) = s.split_at(s.find(':').unwrap()); let c = &c[2..]; let mut components = Components::new(); for p in c.split(',') { ...
if match_fns[i2](c, self.components.0[i], other.components.0[i]) { matches[i2] += 1; }
if_condition
[ { "content": "fn part2(input: &mut Input) -> i32 {\n\n input.add_yourself();\n\n max_happiness_change(input)\n\n}\n\n\n", "file_path": "rust/src/day13.rs", "rank": 0, "score": 217500.3859756544 }, { "content": "fn part2(input: &Input, steps: usize) -> i32 {\n\n simulate(input, steps...
Rust
src/backend/dx12/src/internal.rs
MaikKlein/gfx-rs
829515bf51853462c436d647ec55a62c41b84882
use hal::backend::FastHashMap; use hal::pso; use spirv_cross::hlsl; use std::{mem, ptr}; use std::sync::Mutex; use d3d12; use winapi::Interface; use winapi::shared::{dxgiformat, dxgitype, winerror}; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::um::d3d12::*; use wio::com::ComPtr; use {device}; #[derive(C...
use hal::backend::FastHashMap; use hal::pso; use spirv_cross::hlsl; use std::{mem, ptr}; use std::sync::Mutex; use d3d12; use winapi::Interface; use winapi::shared::{dxgiformat, dxgitype, winerror}; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::um::d3d12::*; use wio::com::ComPtr; use {device}; #[derive(C...
self.device.CreateRootSignature( 0, (*signature_raw).GetBufferPointer(), (*signature_raw).GetBufferSize(), &d3d12::ID3D12RootSignature::uuidof(), &mut signature as *mut *mut _ as *mut *mut _, ); (*signa...
if !error.is_null() { let error_output = (*error).GetBufferPointer(); let message = ::std::ffi::CStr::from_ptr(error_output as *const _ as *const _); error!("D3D12SerializeRootSignature error: {:?}", message.to_str().unwrap()); (*error).Re...
if_condition
[ { "content": "pub fn resize_swap_chain<Cf>(&mut self, factory: &mut Factory, width: Size, height: Size)\n\n -> Result<h::RenderTargetView<Resources, Cf>, winapi::HRESULT>\n\nwhere Cf: format::RenderFormat\n\n{\n\n let result = unsafe {\n\n (*self.swap_chain).ResizeBuffers(0,...
Rust
scheduler/tests/collective_team_scheduling.rs
omid/nettu-scheduler
27a2728882842222085ee4e17c952ec215fd683e
mod helpers; use chrono::{Duration, Utc}; use helpers::setup::spawn_app; use helpers::utils::{assert_equal_user_lists, format_datetime}; use nettu_scheduler_domain::{BusyCalendar, ServiceMultiPersonOptions, TimePlan, ID}; use nettu_scheduler_sdk::{ AddBusyCalendar, AddServiceUserInput, Calendar, CreateBookingInten...
mod helpers; use chrono::{Duration, Utc}; use helpers::setup::spawn_app; use helpers::utils::{assert_equal_user_lists, format_datetime}; use nettu_scheduler_domain::{BusyCalendar, ServiceMultiPersonOptions, TimePlan, ID}; use nettu_scheduler_sdk::{ AddBusyCalendar, AddServiceUserInput, Calendar, CreateBookingInten...
.dates; let available_slot_after_first_full_booking = bookingslots[0].slots[0].start; assert_ne!(available_slot, available_slot_after_first_full_booking); } } #[actix_web::main] #[test] async fn test_collective_team_scheduling_is_collective() { let (app, sdk, address) = spawn_app().a...
admin_client .event .create(host.id.clone(), service_event) .await .expect("To create service event"); } let input = CreateBookingIntendInput { service_id: service.id.clone(), host_user_ids: None, ...
random
[]
Rust
day14/src/lib.rs
vescoc/AdventOfCode2019
ddd6b56d97749e8f47922e814c162d2267207c5f
#![feature(test)] extern crate test; #[macro_use] extern crate lazy_static; use std::cmp::Ordering; use std::collections::HashMap; use regex::Regex; pub mod fast; pub mod simple; lazy_static! { static ref RE: Regex = Regex::new(r"(\d+)\s+([A-Z]+)").unwrap(); static ref REACTIONS: Reactions<'static> = parse...
#![feature(test)] extern crate test; #[macro_use] extern crate lazy_static; use std::cmp::Ordering; use std::collections::HashMap; use regex::Regex; pub mod fast; pub mod simple; lazy_static! { static ref RE: Regex = Regex::new(r"(\d+)\s+([A-Z]+)").unwrap(); static ref REACTIONS: Reactions<'static> = parse...
#[allow(clippy::unreadable_literal)] fn solve_2(reactions: &Reactions, solve_1: fn(&Reactions, ReactionPart<'static>) -> u64) -> u64 { const TARGET: u64 = 1000000000000; let step = solve_1(reactions, (1, "FUEL")); let mut lower = TARGET / step; loop { match TARGET.cmp(&solve_1(reactions, (lo...
pub fn parse(data: &str) -> Reactions { data.lines() .map(|l| { let mut parts = l.split("=>"); (parts.next().unwrap(), parts.next().unwrap()) }) .map(|(lhs, rhs)| { let rhs = parse_part(rhs); ( rhs.1, Reaction::n...
function_block-full_function
[]
Rust
src/message.rs
michaelr524/actix-lua
f69d88f66a910257ae94eeef350121ed84f4942e
use actix::dev::{MessageResponse, ResponseChannel}; use actix::prelude::*; use regex::Regex; use rlua::Result as LuaResult; use rlua::{FromLua, Lua, ToLua, Value}; use std::collections::HashMap; #[derive(Debug, PartialEq, Clone)] pub enum LuaMessage { String(String), Integer(i64), Number(f64), Boolean...
use actix::dev::{MessageResponse, ResponseChannel}; use actix::prelude::*; use regex::Regex; use rlua::Result as LuaResult; use rlua::{FromLua, Lua, ToLua, Value}; use std::collections::HashMap; #[derive(Debug, PartialEq, Clone)] pub enum LuaMessage { String(String), Integer(i64), Number(f64), Boolean...
#[test] fn from_lua() { let lua = Lua::new(); assert_eq!( discriminant(&LuaMessage::from_lua(Value::Integer(42), &lua).unwrap()), discriminant(&LuaMessage::Integer(42)) ); assert_eq!( discriminant(&LuaMessage::from_lua(Value::Number(...
discriminant(&Value::Boolean(true)) ); assert_eq!( discriminant(&LuaMessage::Nil.to_lua(&lua).unwrap()), discriminant(&Value::Nil) ); let mut t = HashMap::new(); t.insert("bar".to_string(), LuaMessage::from("abc")); assert_eq!( discrim...
function_block-function_prefixed
[ { "content": "fn build_message(path: Path<String>, method: &str) -> LuaMessage {\n\n let mut t = HashMap::new();\n\n t.insert(\"path\".to_string(), LuaMessage::from(path.into_inner()));\n\n t.insert(\"method\".to_string(), LuaMessage::from(method.to_string()));\n\n\n\n LuaMessage::from(t)\n\n}\n\n\n...
Rust
src/wrapper/signature.rs
thomcc/jni-rs
0373715c1e777010dbfa37e299b135930651f85e
use combine::*; use combine::stream::state::State; use errors::*; use std::str::FromStr; #[allow(missing_docs)] #[derive(Eq, PartialEq, Debug, Clone, Copy)] pub enum Primitive { Boolean, Byte, Char, Double, Float, Int, Long, Short, Void, } impl ::std::...
use combine::*; use combine::stream::state::State; use errors::*; use std::str::FromStr; #[allow(missing_docs)] #[derive(Eq, PartialEq, Debug, Clone, Copy)] pub enum Primitive { Boolean, Byte, Char, Double, Float, Int, Long, Short, Void, } impl ::std::...
fn format_error_message<E: ::std::fmt::Display>(err: &E, input_string: &str) -> String { format!("{}Input: {}", err, input_string) } #[cfg(test)] mod test { use super::*; #[test] fn test_parser() { let inputs = [ "(Ljava/lang/String;I)V", "[Lherp;", "(IBVZ...
fn parse_sig<S: Stream<Item = char>>(input: &mut S) -> ParseResult<JavaType, S> where S::Error: ParseError<char, S::Range, S::Position> { (parser(parse_args), parser(parse_type)) .map(|(a, r)| TypeSignature { args: a, ret: r }) .map(|sig| JavaType::Method(Box::new(sig))) .parse_stream(in...
function_block-full_function
[ { "content": "#[test]\n\npub fn new_primitive_array_ok() {\n\n let env = attach_current_thread();\n\n const SIZE: jsize = 16;\n\n\n\n let result = env.new_boolean_array(SIZE);\n\n assert!(result.is_ok());\n\n assert!(!result.unwrap().is_null());\n\n\n\n let result = env.new_byte_array(SIZE);\n...
Rust
common/src/types/v0/store/registry.rs
Abhinandan-Purkait/mayastor-control-plane
73390a0e61dd93d1fb7c2735ebac579b7bb88434
use crate::types::v0::store::definitions::{ObjectKey, StorableObject, StorableObjectType}; use serde::{Deserialize, Serialize}; use std::fmt::Debug; #[derive(Serialize, Deserialize, Debug)] pub struct CoreRegistryConfig { id: CoreRegistryConfigKey, registration: NodeRegistration, #[serd...
use crate::types::v0::store::definitions::{ObjectKey, StorableObject, StorableObjectType}; use serde::{Deserialize, Serialize}; use std::fmt::Debug; #[derive(Serialize, Deserialize, Debug)] pub struct CoreRegistryConfig { id: CoreRegistryConfigKey, registration: NodeRegistration, #[serd...
pub fn mayastor_compat_v1(&self) -> bool { self.mayastor_compat_v1.unwrap_or(false) } pub fn node_registration(&self) -> &NodeRegistration { &self.registration } } #[derive(Serialize, Deserialize, Debug, PartialEq)] pub enum NodeRegistration { Manual, ...
pub fn new(registration: NodeRegistration) -> Self { Self { id: CoreRegistryConfigKey::default(), registration, mayastor_compat_v1: None, } }
function_block-full_function
[ { "content": "#[async_trait]\n\npub trait StorableObject: Serialize + Sync + Send + DeserializeOwned {\n\n type Key: ObjectKey;\n\n\n\n fn key(&self) -> Self::Key;\n\n}\n\n\n\n/// All types of objects which are storable in our store\n\n#[derive(Display, Copy, Clone, Debug)]\n\npub enum StorableObjectType ...
Rust
src/l20n/parse.rs
zbraniecki/message-format.rs
ec8b68edbe6f00068f940d643f7302c800077a22
#![allow(missing_docs)] use std::error::Error; use std::fmt; use std::str; use super::ast::*; pub fn parse(source: &str) -> Result<Vec<Entry>, ParseError> { let mut p = Parser::new(source); p.parse() } #[derive(Debug)] pub struct ParseError { pub error_message: String, } impl ParseError { pub fn n...
#![allow(missing_docs)] use std::error::Error; use std::fmt; use std::str; use super::ast::*; pub fn parse(source: &str) -> Result<Vec<Entry>, ParseError> { let mut p = Parser::new(source); p.parse() } #[derive(Debug)] pub struct ParseError { pub error_message: String, } impl ParseError { pub fn n...
Ok(Identifier { name: name }) } fn get_pattern(&mut self) -> Result<Value, ParseError> { let mut buffer = String::new(); let mut source = String::new(); let mut content = vec![]; let mut quote_delimited: bool = false; let mut first_line = true; if self.ch_is...
et ch = match self.ch { Some(c) => c, None => return Err(ParseError::new("Unexpected end of input.")), }; match ch { 'a'...'z' | 'A'...'Z' | '_' => name.push(ch), _ => return Ok(Identifier { name: name }), } self.bump(); while let...
function_block-random_span
[ { "content": "/// Parse some text and hopefully return a [`Message`].\n\n///\n\n/// [`Message`]: ../struct.Message.html\n\npub fn parse(message: &str) -> Result<Message, ParseError> {\n\n match message_parser(message) {\n\n IResult::Error(_) |\n\n IResult::Incomplete(_) => Err(ParseError::NotIm...
Rust
tokera/src/opt/instance.rs
tokera-com/ate
42c4ce5a0c0aef47aeb4420cc6dc788ef6ee8804
use std::net::IpAddr; use clap::Parser; use url::Url; use super::purpose::*; #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Tokera Pty Ltd <info@tokera.com>")] pub struct OptsInstance { #[clap(subcommand)] pub purpose: OptsInstanceFor, #[clap(short, long)] pu...
use std::net::IpAddr; use clap::Parser; use url::Url; use super::purpose::*; #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Tokera Pty Ltd <info@tokera.com>")] pub struct OptsInstance { #[clap(subcommand)] pub purpose: OptsInstanceFor, #[clap(short, long)] pu...
} #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceDetails { #[clap(index = 1)] pub name: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceCreate { #[clap(index = 1)] pub name: Option<String>, #[clap(short, long)] pub force: bool, } #[derive(Parser,...
pub fn name(&self) -> Option<String> { match self { OptsInstanceAction::List => None, OptsInstanceAction::Create(_) => None, OptsInstanceAction::Details(opts) => Some(opts.name.clone()), OptsInstanceAction::Kill(opts) => Some(opts.name.clone()), OptsIn...
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\npub fn is_public_domain(domain: &str) -> bool {\n\n match domain {\n\n \"gmail.com\" => true,\n\n \"zoho.com\" => true,\n\n \"outlook.com\" => true,\n\n \"hotmail.com\" => true,\n\n \"mail.com\" => true,\n\n \"yahoo.com\" => true,...
Rust
src/sources/node/tcpstat.rs
f1shl3gs/vertex
8dc1e7e2291f80460a3baae2026aa61491ca0ec1
use event::{tags, Metric}; use netlink_packet_sock_diag::{ constants::*, inet::{ExtensionFlags, InetRequest, SocketId, StateFlags}, NetlinkHeader, NetlinkMessage, NetlinkPayload, SockDiagMessage, NLM_F_DUMP, NLM_F_REQUEST, }; use netlink_sys::{protocols::NETLINK_SOCK_DIAG, AsyncSocket, AsyncSocketExt, Tokio...
use event::{tags, Metric}; use netlink_packet_sock_diag::{ constants::*, inet::{ExtensionFlags, InetRequest, SocketId, StateFlags}, NetlinkHeader, NetlinkMessage, NetlinkPayload, SockDiagMessage, NLM_F_DUMP, NLM_F_REQUEST, }; use netlink_sys::{protocols::NETLINK_SOCK_DIAG, AsyncSocket, AsyncSocketExt, Tokio...
} NetlinkPayload::Done => { break 'RECV; } NetlinkPayload::Error(_) | NetlinkPayload::Overrun(_) | _ => { panic!("error or overrun") } } offset += pkt.header.length as usize;...
match resp.header.state { TCP_ESTABLISHED => stats.established += 1, TCP_SYN_SENT => stats.syn_sent += 1, TCP_SYN_RECV => stats.syn_recv += 1, TCP_FIN_WAIT1 => stats.fin_wait1 += 1, TCP_FIN_WAIT2 => s...
if_condition
[ { "content": "// fmt_int formats v into the tail of buf.\n\n// It returns the index where the output begins.\n\nfn fmt_int(buf: &mut [u8], mut v: u64) -> usize {\n\n let mut w = buf.len();\n\n if v == 0 {\n\n w -= 1;\n\n buf[w] = b'0';\n\n } else {\n\n while v > 0 {\n\n ...
Rust
lib/vrl/stdlib/src/parse_csv.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use ::value::Value; use csv::ReaderBuilder; use vrl::prelude::*; fn parse_csv(csv_string: Value, delimiter: Value) -> Resolved { let csv_string = csv_string.try_bytes()?; let delimiter = delimiter.try_bytes()?; if delimiter.len() != 1 { return Err("delimiter must be a single character".into()); ...
use ::value::Value; use csv::ReaderBuilder; use vrl::prelude::*; fn parse_csv(csv_string: Value, delimiter: Value) -> Resolved { let csv_string = csv_string.try_bytes()?; let delimiter = delimiter.try_bytes()?; if delimiter.len() != 1 { return Err("delimiter must be a single character".into()); ...
fn call_by_vm(&self, _ctx: &mut Context, args: &mut VmArgumentList) -> Resolved { let value = args.required("value"); let delimiter = args .optional("delimiter") .unwrap_or_else(|| Value::from(",")); parse_csv(value, delimiter) } } #[derive(Debug, Clone)] stru...
S, required: true, }, Parameter { keyword: "delimiter", kind: kind::BYTES, required: false, }, ] }
function_block-function_prefixed
[ { "content": "/// Compile a given source into the final [`Program`].\n\npub fn compile(source: &str, fns: &[Box<dyn Function>]) -> compiler::Result {\n\n let mut state = state::ExternalEnv::default();\n\n\n\n compile_with_state(source, fns, &mut state)\n\n}\n\n\n", "file_path": "lib/vrl/vrl/src/lib.rs...
Rust
src/main.rs
chrisjsimpson/amber
65e6c6ec8ee0669df71b9b56e6e3ab924e0d3fc2
mod cli; mod config; mod exec; mod mask; use std::io::Read; use anyhow::*; use exec::CommandExecExt; use serde::Serialize; #[derive(Serialize)] struct KeyValue<'a> { key: &'a str, value: &'a str, } impl<'a, K, V> From<&'a (K, V)> for KeyValue<'a> where K: AsRef<str>, V: AsRef<str>, { fn from((ke...
mod cli; mod config; mod exec; mod mask; use std::io::Read; use anyhow::*; use exec::CommandExecExt; use serde::Serialize; #[derive(Serialize)] struct KeyValue<'a> { key: &'a str, value: &'a str, } impl<'a, K, V> From<&'a (K, V)> for KeyValue<'a> where K: AsRef<str>, V: AsRef<str>, { fn from((ke...
match style { cli::PrintStyle::SetEnv => pairs .iter() .for_each(|(key, value)| println!("export {}={:?}", key, value)), cli::PrintStyle::Json => { let secrets = to_objs(&pairs); serde_json::to_writer(std::io::stdout(), &secrets)?; } c...
a (K, V)>, K: AsRef<str> + 'a, V: AsRef<str> + 'a, { p.into_iter().map(KeyValue::from).collect::<Vec<_>>() }
function_block-function_prefixed
[ { "content": "/// Run the given command with stdout and stderr values masked.\n\npub fn run_masked(mut cmd: Command, secrets: &[impl AsRef<[u8]>]) -> Result<()> {\n\n // Unfortunately LeftmostLongest isn't supported by the streaming interface\n\n // let ac = AhoCorasickBuilder::new().auto_configure(secret...
Rust
src/frontend/gui/renderstate.rs
TimeToogo/wezterm
d36afd90ceb5c17e425f94e7a4d893df33a0cb62
use super::glyphcache::{CachedGlyph, GlyphCache}; use super::quad::*; use super::utilsprites::{RenderMetrics, UtilSprites}; use crate::config::{configuration, TextStyle}; use crate::font::{FontConfiguration, GlyphInfo}; use ::window::bitmaps::ImageTexture; use ::window::glium::backend::Context as GliumContext; use ::wi...
use super::glyphcache::{CachedGlyph, GlyphCache}; use super::quad::*; use super::utilsprites::{RenderMetrics, UtilSprites}; use crate::config::{configuration, TextStyle}; use crate::font::{FontConfiguration, GlyphInfo}; use ::window::bitmaps::ImageTexture; use ::window::glium::backend::Context as GliumContext; use ::wi...
pub fn cached_software_glyph( &self, info: &GlyphInfo, style: &TextStyle, ) -> anyhow::Result<Rc<CachedGlyph<ImageTexture>>> { if let RenderState::Software(software) = self { software.glyph_cache.borrow_mut().cached_glyph(info, style) } else { ba...
if let RenderState::GL(gl) = self { gl.advise_of_window_size_change(metrics, pixel_width, pixel_height)?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn feature_from_string(s: &str) -> Result<hb_feature_t, Error> {\n\n unsafe {\n\n let mut feature = mem::zeroed();\n\n ensure!(\n\n hb_feature_from_string(\n\n s.as_ptr() as *const i8,\n\n s.len() as i32,\n\n &mut feature...
Rust
src/feed_util.rs
boustrophedon/rss-torrent-rs
be1c8bf176ef2d3530914803634e44160573999b
use std::collections::HashSet; use std::error::Error; use std::path::Path; use std::fs::{File, OpenOptions}; use std::io::Write; use chrono::{DateTime, FixedOffset}; use csv; use reqwest::Url; pub type Feeds = HashSet<Feed>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Feed { pub url: Url, pub ...
use std::collections::HashSet; use std::error::Error; use std::path::Path; use std::fs::{File, OpenOptions}; use std::io::Write; use chrono::{DateTime, FixedOffset}; use csv; use reqwest::Url; pub type Feeds = HashSet<Feed>; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Feed { pub url: Url, pub ...
DATA MAY BE CORRUPTED!"); e }) .and_then(|_| { db_file.set_len(buf.len() as u64) }); Ok(result?) }
ing>; match self.filters { Some(f) => filters = f, None => filters = Vec::new(), } Ok(Feed { url: url, last_update: self.last_update, filters: filters, }) } } const FEED_DB_FILENAME: &str = "feeds.csv"; fn open_or_create_...
random
[ { "content": "pub fn delete_feed(delete: RTDelete, config: &RTConfig) {\n\n unimplemented!();\n\n}\n", "file_path": "src/delete.rs", "rank": 2, "score": 51664.08974768853 }, { "content": "pub fn add_feed(cmd: RTAdd, config: &RTConfig) {\n\n let result = Url::parse(&cmd.url_or_alias);\n...
Rust
pikelet/src/lang/core.rs
pikelet-lang/pikelet
8752087d4b8d4dafae4ac3c051df49b993a28ed2
use fxhash::FxHashMap; use std::fmt; use std::sync::Arc; use crate::lang::Located; pub mod marshall; pub mod semantics; pub mod typing; #[derive(Clone, Debug, PartialEq)] pub enum Constant { U8(u8), U16(u16), U32(u32), U64(u64), S8(i8), S16(...
use fxhash::FxHashMap; use std::fmt; use std::sync::Arc; use crate::lang::Located; pub mod marshall; pub mod semantics; pub mod typing; #[derive(Clone, Debug, PartialEq)] pub enum Constant { U8(u8), U16(u16), U32(u32), U64(u64), S8(i8), S16(...
} #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct VarIndex(u32); impl VarIndex { pub fn to_usize(self) -> usize { self.0 as usize } } pub fn var_indices() -> impl Iterator<Item = VarIndex> { (0..).map(VarIndex) } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct VarLevel(u32)...
function_type(global("U32"), function_type(type_type(), type_type())), None, ), ); entries.insert( "List".to_owned(), (function_type(type_type(), type_type()), None), ); Globals::new(entries) }
function_block-function_prefix_line
[ { "content": "#[debug_ensures(values.size() == old(values.size()))]\n\npub fn normalize(globals: &Globals, values: &mut Env<Arc<Value>>, term: &Term) -> Term {\n\n let value = eval(globals, values, term);\n\n read_back(globals, values.size(), Unfold::Always, &value)\n\n}\n\n\n\n/// Evaluate a [`Term`] int...
Rust
src/oneshot.rs
DoumanAsh/slave-pool
d7b1288953666a4ea611528ec8f202e2dbd8552d
use core::{time, ptr, task, pin}; use core::cell::UnsafeCell; use core::mem::MaybeUninit; use core::sync::atomic::{Ordering, AtomicU8}; use core::future::Future; const UNINIT: u8 = 0; const READY: u8 = 0b0001; const WAKER_SET: u8 = 0b0010; const SEND_CLOSED: u8 = 0b0100; const CONSUMED: u8 = 0b1000; use super::JoinEr...
use core::{time, ptr, task, pin}; use core::cell::UnsafeCell; use core::mem::MaybeUninit; use core::sync::atomic::{Ordering, AtomicU8}; use core::future::Future; const UNINIT: u8 = 0; const READY: u8 = 0b0001; const WAKER_SET: u8 = 0b0010; const SEND_CLOSED: u8 = 0b0100; const CONSUMED: u8 = 0b1000; use super::JoinEr...
pub fn recv(self) -> Result<T, JoinError> { let state = self.payload.state.load(Ordering::Acquire); if state & CONSUMED == CONSUMED { return Err(JoinError::AlreadyConsumed); } else if state & READY == READY { return Ok(self.consume()); } else if state & SEN...
fn consume(&self) -> T { self.payload.state.fetch_or(CONSUMED, Ordering::Release); let mut result = MaybeUninit::uninit(); unsafe { ptr::swap(result.as_mut_ptr(), self.payload.value().as_mut_ptr()); result.assume_init() } }
function_block-full_function
[ { "content": "struct State {\n\n send: crossbeam_channel::Sender<Message>,\n\n recv: crossbeam_channel::Receiver<Message>,\n\n}\n\n\n\nunsafe impl Sync for ThreadPool {}\n\n\n\n///Thread pool that allows to change number of threads at runtime.\n\n///\n\n///On `Drop` it instructs threads to shutdown, but d...
Rust
kernel/src/lapic.rs
woppopo/xv6-rs
6aa51958a0fa137b9899b3ad65b0f458460ddcf7
struct LocalApic { head: *mut u32, } impl LocalApic { pub const REG_ID: usize = 0x0020; pub const REG_VER: usize = 0x0030; pub const REG_TPR: usize = 0x0080; pub const REG_EOI: usize = 0x00B0; pub const REG_SVR: usize = 0x00F0; pub const REG_ESR: usize = 0x0280; pub const REG_ICRL...
struct LocalApic { head: *mut u32, } impl LocalApic { pub const REG_ID: usize = 0x0020; pub const REG_VER: usize = 0x0030; pub const REG_TPR: usize = 0x0080; pub const REG_EOI: usize = 0x00B0; pub const REG_SVR: usize = 0x00F0; pub const REG_ESR: usize = 0x0280; pub const REG_ICRL...
pub fn lapiceoi() { unsafe { LAPIC .as_ref() .map(|lapic| lapic.write(LocalApic::REG_EOI, 0)); } } pub fn microdelay(_ms: u32) {} pub fn lapicstartap(apicid: u8, addr: u32) { use crate::memlayout::p2v; use crate::x86::outb; const CMOS_PORT: u16 = 0x70; const ...
lapicid() -> u32 { unsafe { LAPIC .as_ref() .map(|lapic| lapic.read(LocalApic::REG_ID) >> 24) .unwrap_or(0) } }
function_block-function_prefixed
[]
Rust
src/vdom/mod.rs
thomaseizinger/ruukh
5e6d212c8758ce4cae826a6531979a2c776d85e1
use crate::{ component::Render, dom::DOMPatch, vdom::{ vcomponent::VComponent, velement::VElement, vlist::VList, vtext::VText }, MessageSender, Shared }; use std::{ borrow::Cow, fmt::{self, Display, Formatter} }; use wasm_bindgen::prelude::JsValue; use ...
use crate::{ component::Render, dom::DOMPatch, vdom::{ vcomponent::VComponent, velement::VElement, vlist::VList, vtext::VText }, MessageSender, Shared }; use std::{ borrow::Cow, fmt::{self, Display, Formatter} }; use wasm_bindgen::prelude::JsValue; use ...
fn reorder(&self, parent: &Node, next: Option<&Node>) -> Result<(), JsValue> { match self { VNode::Text(txt) => txt.reorder(parent, next), VNode::Element(el) => el.reorder(parent, next), VNode::List(li) => li.reorder(parent, next), VNode::Component(comp) => ...
fn patch( &mut self, old: Option<&mut Self>, parent: &Self::Node, next: Option<&Self::Node>, render_ctx: Shared<Self::RenderContext>, rx_sender: MessageSender, ) -> Result<(), JsValue> { match self { VNode::Element(ref mut new_el) => { ...
function_block-full_function
[ { "content": "pub fn is_self_closing(inp: ParseStream<'_>) -> bool {\n\n inp.peek(Token![<])\n\n && (is_self_closing!(\n\n inp is\n\n [area, base, br, col, embed, hr, img, input, link, meta, param, source, track, wbr]\n\n ))\n\n}\n", "file_path": "codegen/src/html/kw.r...
Rust
src/ai/mod.rs
roSievers/sogo
5f678a3706ed183d0a7b6a426632be8e9de5dded
pub mod random; pub mod mc; pub mod tree; pub mod value; mod mctree; use game; use game::Position2; use std::sync::Arc; pub trait StatelessAI { fn action(&self, state: &game::State) -> Position2; } #[derive(Clone, Copy, Debug)] pub enum Constructor { Random, MonteCarlo { endurance: usize }, Tree { ...
pub mod random; pub mod mc; pub mod tree; pub mod value; mod mctree; use game; use game::Position2; use std::sync::Arc; pub trait StatelessAI { fn action(&self, state: &game::State) -> Position2; } #[derive(Clone, Copy, Debug)] pub enum Constructor { Random, MonteCarlo { endurance: usize }, Tree { ...
fn random_best_move<T: Iterator<Item = (Position2, i32)>>(mut tuples: T) -> Position2 { use rand::{thread_rng, Rng}; let (initial_action, initial_value) = tuples.next().unwrap(); let mut best_actions = vec![initial_action]; let mut best_value = initial_value; while let Some((action, value)) = tup...
function_block-full_function
[ { "content": "pub fn random_playout(mut state: game::State) -> VictoryState {\n\n let mut rng = thread_rng();\n\n while state.victory_state == VictoryState::Undecided {\n\n let legal_actions: Vec<Position2> = state.legal_actions().collect();\n\n let action = *rng.choose(&legal_actions).unwra...
Rust
imxrt1062-pac/imxrt1062-flexspi/src/iptxfcr.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register IPTXFCR"] pub type R = crate::R<u32, super::IPTXFCR>; #[doc = "Writer for register IPTXFCR"] pub type W = crate::W<u32, super::IPTXFCR>; #[doc = "Register IPTXFCR `reset()`'s with value 0"] impl crate::ResetValue for super::IPTXFCR { type Type = u32; #[inline(always)] fn reset_va...
#[doc = "Reader of register IPTXFCR"] pub type R = crate::R<u32, super::IPTXFCR>; #[doc = "Writer for register IPTXFCR"] pub type W = crate::W<u32, super::IPTXFCR>; #[doc = "Register IPTXFCR `reset()`'s with value 0"] impl crate::ResetValue for super::IPTXFCR { type Type = u32; #[inline(always)] fn reset_va...
fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 2)) | (((value as u32) & 0x0f) << 2); self.w } } impl R { #[doc = "Bit 0 - Clear all valid data entries in IP TX FIFO."] #[inline(always)] pub fn clriptxf(&self) -> CLRIPTXF_R { CLRIPTXF_R::new((self.b...
self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "IP TX FIFO filling by DMA enabled.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXDMAEN_A { #[doc = "0: IP TX FIFO would be filled by processor."] TXDMAEN_0 = 0, #[doc = "1: IP TX FIFO would be filled...
random
[ { "content": "/// Migrate the `lib.rs` of the PAC subscrate, adding\n\n/// our necessary header to the top of the file.\n\nfn write_lib<R: Read>(crate_path: &Path, mut src: R) {\n\n static LIB_PRELUDE: &str = r#\"#![deny(warnings)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(clippy::all)]\n\n#![no_std]\n\...
Rust
src/ai/mod.rs
seryj/wasm-boa
883a3e0cd9a8cd6a028ade17da8ea472232dba43
use crate::{GameState, GameError, LENGTH_OF_FIELD}; use wasm_bindgen::JsValue; use std::time::Instant; use rand::Rng; use wasm_bindgen::prelude::*; pub fn get_random_number(from: usize, to: usize) -> usize { #[cfg(not(target_arch = "wasm32"))] { let mut rng = rand::thread_rng(); re...
use crate::{GameState, GameError, LENGTH_OF_FIELD}; use wasm_bindgen::JsValue; use std::time::Instant; use rand::Rng; use wasm_bindgen::prelude::*; pub fn get_random_number(from: usize, to: usize) -> usize { #[cfg(not(target_arch = "wasm32"))] { let mut rng = rand::thread_rng(); re...
} pub fn random_playout(state: GameState) -> Result<u8, GameError> { let mut newstate: GameState = state; let mut abort_counter = 100000; loop { assert!( abort_counter > 0, format!("Could not complete the playout.") ); abort_counter -= 1; if let Som...
pub fn evaluate_state_for_next_move( &self, state: &GameState, num_rounds: i32, max_time_to_think_in_millis: u32, ) -> Result<*const i32, JsValue> { let curr_player = state.curr_player; let result = if num_rounds > 0 || max_time_to_think_in_millis <= 0 { i...
function_block-full_function
[ { "content": "#[wasm_bindgen]\n\npub fn init_panic_hook() {\n\n console_error_panic_hook::set_once();\n\n}\n\n\n\n#[wasm_bindgen]\n\nimpl OnePlayersField {\n\n fn new(direction: Direction) -> Self {\n\n OnePlayersField {\n\n direction: direction,\n\n cells: [2; 2 * LENGTH_OF_F...
Rust
crates/tm4c129x/src/epi0/eisc.rs
m-labs/ti2svd
30145706b658136c35c90290701de3f02a4b8ef2
#[doc = "Reader of register EISC"] pub type R = crate::R<u32, super::EISC>; #[doc = "Writer for register EISC"] pub type W = crate::W<u32, super::EISC>; #[doc = "Register EISC `reset()`'s with value 0"] impl crate::ResetValue for super::EISC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register EISC"] pub type R = crate::R<u32, super::EISC>; #[doc = "Writer for register EISC"] pub type W = crate::W<u32, super::EISC>; #[doc = "Register EISC `reset()`'s with value 0"] impl crate::ResetValue for super::EISC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
] pub fn rstall(&mut self) -> RSTALL_W { RSTALL_W { w: self } } #[doc = "Bit 2 - Write FIFO Full Error"] #[inline(always)] pub fn wtfull(&mut self) -> WTFULL_W { WTFULL_W { w: self } } #[doc = "Bit 3 - Read uDMA Interrupt Clear"] #[inline(always)] pub fn dmardic(&mut ...
f) -> WTFULL_R { WTFULL_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - Read uDMA Interrupt Clear"] #[inline(always)] pub fn dmardic(&self) -> DMARDIC_R { DMARDIC_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Write uDMA Interrupt Clear"] #[inline(always)...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
crates/proc_macro_api/src/lib.rs
nabakin/rust-analyzer
6c51ecad5b2421ce2d47c7c165e3e34ed24149db
pub mod msg; mod process; mod version; use paths::AbsPathBuf; use std::{ ffi::OsStr, fmt, io, sync::{Arc, Mutex}, }; use serde::{Deserialize, Serialize}; use tt::Subtree; use crate::{ msg::{ExpandMacro, FlatTree, PanicMessage}, process::ProcMacroProcessSrv, }; pub use version::{read_dylib_info...
pub mod msg; mod process; mod version; use paths::AbsPathBuf; use std::{ ffi::OsStr, fmt, io, sync::{Arc, Mutex}, }; use serde::{Deserialize, Serialize}; use tt::Subtree; use crate::{ msg::{ExpandMacro, FlatTree, PanicMessage}, process::ProcMacroProcessSrv, }; pub use version::{read_dylib_info...
Ok(MacroDylib { path }) } } #[derive(Debug, Clone)] pub struct ProcMacro { process: Arc<Mutex<ProcMacroProcessSrv>>, dylib_path: AbsPathBuf, name: String, kind: ProcMacroKind, } impl Eq for ProcMacro {} impl PartialEq for ProcMacro { fn eq(&self, other: &Self) -> bool { self....
if info.version.0 < 1 || info.version.1 < 47 { let msg = format!("proc-macro {} built by {:#?} is not supported by Rust Analyzer, please update your rust version.", path.display(), info); return Err(io::Error::new(io::ErrorKind::InvalidData, msg)); }
if_condition
[ { "content": "fn punch_card() -> impl std::fmt::Debug {\n\n ..=..=.. .. .. .. .. .. .. .. .. .. .. ..=.. ..\n\n ..=.. ..=.. .. .. .. .. .. .. .. .. ..=..=..=..\n\n ..=.. ..=.. ..=.. ..=.. .. ..=..=.. .. ..=.. ..\n\n ..=..=.. .. ..=.. ..=.. ..=.. .. .. .. ..=.. ..\...
Rust
src/monitor/help_window.rs
markatk/serial-unit-testing
b620937a2503ccb7ef9a2822ef3035aafe10e98d
/* * File: src/monitor/help_window.rs * Date: 31.10.2019 * Author: MarkAtk * * MIT License * * Copyright (c) 2019 MarkAtk * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without ...
/* * File: src/monitor/help_window.rs * Date: 31.10.2019 * Author: MarkAtk * * MIT License * * Copyright (c) 2019 MarkAtk * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without ...
fn handle_key_event(&mut self, event: KeyEvent) -> EventResult { match event { KeyEvent { code: KeyCode::Esc, modifiers: _ } => { self.should_close = true; }, KeyEvent { code: KeyCode::Left, modifiers: _ } => { if self.page > 0 { ...
fn render(&mut self, terminal: &mut Terminal<CrosstermBackend<std::io::Stdout>>) -> Result<(), std::io::Error> { let help_entries = &self.help_entries; let page_count = &mut self.page_count; let page = &mut self.page; terminal.draw(|mut f| { let chunks = Layout::default() ...
function_block-full_function
[ { "content": "/// Add newline characters to the end of the string.\n\n///\n\n/// The newline characters will be added in the given text format.\n\npub fn add_newline(text: &mut String, text_format: TextFormat, newline_format: NewlineFormat) {\n\n if newline_format == NewlineFormat::None {\n\n return;\...
Rust
crates/volta-core/src/run/mod.rs
felipecrs/volta
5b4ed58dbb555f337bcf548ce15fb7923b249b26
use std::collections::HashMap; use std::env::{self, ArgsOs}; use std::ffi::{OsStr, OsString}; use std::path::Path; use std::process::ExitStatus; use crate::error::{ErrorKind, Fallible}; use crate::platform::{CliPlatform, Image, Sourced}; use crate::session::Session; use log::debug; use semver::Version; pub mod binary...
use std::collections::HashMap; use std::env::{self, ArgsOs}; use std::ffi::{OsStr, OsString}; use std::path::Path; use std::process::ExitStatus; use crate::error::{ErrorKind, Fallible}; use crate::platform::{CliPlatform, Image, Sourced}; use crate::session::Session; use log::debug; use semver::Version; pub mod binary...
} else { match exe.to_str() { Some("volta-shim") => Err(ErrorKind::RunShimDirectly.into()), Some("node") => node::command(args, session), Some("npm") => npm::command(args, session), Some("npx") => npx::command(args, session), Some("yarn") => yarn:...
Ok(executor::ToolCommand::new( exe, args, None, executor::ToolKind::Bypass(exe.to_string_lossy().to_string()), ) .into())
call_expression
[ { "content": "pub fn resolve(matching: VersionSpec, session: &mut Session) -> Fallible<Version> {\n\n let hooks = session.hooks()?.yarn();\n\n match matching {\n\n VersionSpec::Semver(requirement) => resolve_semver(requirement, hooks),\n\n VersionSpec::Exact(version) => Ok(version),\n\n ...
Rust
webhooky/src/main.rs
oxidecomputer/cio
47ccb9224cab8f7077941914bff85b4b52837eb5
mod event_types; mod github_types; mod handlers; mod handlers_auth; mod handlers_cron; mod handlers_github; mod repos; mod sagas; mod server; mod slack_commands; mod tracking_numbers; #[macro_use] extern crate serde_json; use std::env; use anyhow::{bail, Result}; use cio_api::{companies::Companys, db::Database}; use ...
mod event_types; mod github_types; mod handlers; mod handlers_auth; mod handlers_cron; mod handlers_github; mod repos; mod sagas; mod server; mod slack_commands; mod tracking_numbers; #[macro_use] extern crate serde_json; use std::env; use anyhow::{bail, Result}; use cio_api::{companies::Companys, db::Database}; use ...
async fn run_cmd(opts: Opts, logger: slog::Logger) -> Result<()> { sentry::configure_scope(|scope| { scope.set_tag("command", &format!("{:?}", opts.subcmd)); }); match opts.subcmd { SubCommand::Server(s) => { crate::server::server(s, logger).await?; } SubCommand:...
function_block-full_function
[ { "content": "pub fn update_state(content: &str, state: &str, is_markdown: bool) -> Result<String> {\n\n // TODO: there is probably a better way to do these regexes.\n\n let mut re = Regex::new(r\"(?m)(:state:.*$)\")?;\n\n // Asciidoc starts with a colon.\n\n let mut pre = \":\";\n\n if is_markdo...
Rust
examples/imgui/src/main.rs
setzer22/rend3
c42f758d07e1d9c650d2d5239527bd97f7111cb8
use std::sync::Arc; struct ImguiExampleData { _object_handle: rend3::types::ObjectHandle, _directional_handle: rend3::types::DirectionalLightHandle, imgui: imgui::Context, platform: imgui_winit_support::WinitPlatform, imgui_routine: rend3_imgui::ImguiRenderRoutine, frame_start: instant::Instan...
use std::sync::Arc; struct ImguiExampleData { _object_handle: rend3::types::ObjectHandle, _directional_handle: rend3::types::DirectionalLightHandle, imgui: imgui::Context, platform: imgui_winit_support::WinitPlatform, imgui_routine: rend3_imgui::ImguiRenderRoutine, frame_start: instant::Instan...
} fn handle_event( &mut self, window: &winit::window::Window, renderer: &Arc<rend3::Renderer>, routines: &Arc<rend3_framework::DefaultRoutines>, base_rendergraph: &rend3_routine::base::BaseRenderGraph, surface: Option<&Arc<rend3::types::Surface>>, resolu...
Some(ImguiExampleData { _object_handle, _directional_handle, imgui, platform, imgui_routine, frame_start, demo_window_open: true, })
call_expression
[ { "content": "fn compute_projection_matrix(data: Camera, handedness: Handedness, aspect_ratio: f32) -> Mat4 {\n\n match data.projection {\n\n CameraProjection::Orthographic { size } => {\n\n let half = size * 0.5;\n\n if handedness == Handedness::Left {\n\n Mat4::o...
Rust
sprattus-derive/src/lib.rs
Termonoid/sprattus
28476f483154cc0f2a59375233a4258fa5873fe0
extern crate proc_macro; mod from_sql; mod functions; mod to_sql; use crate::from_sql::SqlField; use crate::functions::*; use crate::to_sql::*; use proc_macro2::{Literal, TokenTree::Group}; use quote::quote; use syn::export::TokenStream2; use syn::{parse_macro_input, Data::Struct, DeriveInput}; #[proc_macro_derive(T...
extern crate proc_macro; mod from_sql; mod functions; mod to_sql; use crate::from_sql::SqlField; use crate::functions::*; use crate::to_sql::*; use proc_macro2::{Literal, TokenTree::Group}; use quote::quote; use syn::export::TokenStream2; use syn::{parse_macro_input, Data::Struct, DeriveInput}; #[proc_macro_derive(T...
continue 'attribute_loop; } } } if let Some(ident) = &field.ident { let name = &ident.to_string(); fields.push(SqlField { rust_name: ident.clone(), sql_name: Litera...
match &field.ident { Some(ident) => { if key.eq("name") { let sql_name = match value { None => Literal::string(ident.t...
random
[ { "content": "///\n\n/// Generates a string of prepared statement placeholder arguments.\n\n///\n\nfn generate_prepared_arguments_list(item_length: usize, no_of_items: usize) -> String {\n\n let mut arguments_list: String = String::new();\n\n let range_end = item_length * no_of_items + 1;\n\n\n\n compl...
Rust
chazi/src/lib.rs
patr0nus/chazi
cc114f82b6d67d8655304923433c9526a8889093
#![doc = include_str!("../README.md")] use std::io::{BufRead, BufReader, Read}; use std::process::{Command, Stdio}; use std::sync::atomic::Ordering; use std::time::Duration; pub use ::chazi_macros::test; use crate::probe::{generate_probe, parse_probe}; use crate::reached::{parse_reach_info, ReachLineInfo, CHECK_REAC...
#![doc = include_str!("../README.md")] use std::io::{BufRead, BufReader, Read}; use std::process::{Command, Stdio}; use std::sync::atomic::Ordering; use std::time::Duration; pub use ::chazi_macros::test; use crate::probe::{generate_probe, parse_probe}; use crate::reached::{parse_reach_info, ReachLineInfo, CHECK_REAC...
} #[allow(missing_docs)] #[doc(hidden)] pub fn fork_in_test(test_fn_module_path: &str, test_name: &str, impl_fn: fn(), config: TestConfig) { if std::env::var(CHILD_MARK_ENV_NAME).is_ok() { if config.check_reach { CHECK_REACH.store(true, Ordering::Relaxed); } match config.expect...
fn default() -> Self { Self { ignore: false, timeout: Duration::from_secs(5), check_reach: false, expected_result: TestResult::ExitCode(0), parent_should_panic: false, } }
function_block-full_function
[ { "content": "pub fn never() {\n\n assert_check_reach();\n\n write_reach_probe(ReachLineInfo::Never)\n\n}\n\n\n\npub(crate) fn validate_reaches(reach_lines: &[ReachLineInfo]) {\n\n let mut last_reach_line: Option<ReachLineInfo> = None;\n\n use ReachLineInfo::{Last, Never, Nth};\n\n for reach_line...
Rust
build.rs
curldivergence/rusty-d3d12
850d7c67e4e0f2fa6c1a74e346a194a4aa6f5910
extern crate bindgen; use regex::Regex; use std::env; use std::path::PathBuf; const D3D12_AGILITY_SDK_INCLUDE_PATH: &str = "extern\\D3D12AgilitySDK\\include"; const D3D12_AGILITY_SDK_LIB_PATH: &str = "extern\\D3D12AgilitySDK\\bin"; #[cfg(feature = "pix")] const PIX_INCLUDE_PATH: &str = "extern\\WinPixEventRuntime\\i...
extern crate bindgen; use regex::Regex; use std::env; use std::path::PathBuf; const D3D12_AGILITY_SDK_INCLUDE_PATH: &str = "extern\\D3D12AgilitySDK\\include"; const D3D12_AGILITY_SDK_LIB_PATH: &str = "extern\\D3D12AgilitySDK\\bin"; #[cfg(feature = "pix")] const PIX_INCLUDE_PATH: &str = "extern\\WinPixEventRuntime\\i...
#[cfg(feature = "devel")] fn generate_pix_bindings() { let workspace_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); cc::Build::new() .cpp(true) .include(workspace_dir.join(PIX_INCLUDE_PATH)) .include(workspace_dir.join(D3D12_AGILITY_SDK_INCLUDE_PATH)) .incl...
fn generate_bindings() { println!("cargo:rerun-if-changed=generation\\d3d12_wrapper.h"); let workspace_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()) .to_str() .expect("Workspace path is not valid UTF-8") .to_owned(); let bindings = bindgen::Builder::default() ...
function_block-full_function
[ { "content": " DXGI_FORMAT Format;\n", "file_path": "extern/D3D12AgilitySDK/include/d3d12.h", "rank": 0, "score": 219653.02471857212 }, { "content": " DXGI_FORMAT Format;\n", "file_path": "extern/D3D12AgilitySDK/include/d3d12video.h", "rank": 1, "score": 207243.76860341054 ...
Rust
tests/fd.rs
tormol/posixmq
72fe32c9aa84a6f66c48bd31a19dbcdd3f503c65
extern crate posixmq; use posixmq::{PosixMq, remove_queue}; use std::io::ErrorKind; #[test] fn is_cloexec() { let mq = PosixMq::create("/is_cloexec").unwrap(); let _ = remove_queue("/is_cloexec"); if cfg!(not(any(target_os="illumos", target_os="solaris"))) { assert!(mq.is_cloexec().unwrap()); ...
extern crate posixmq; use posixmq::{PosixMq, remove_queue}; use std::io::ErrorKind; #[test] fn is_cloexec() { let mq = PosixMq::create("/is_cloexec").unwrap(); let _ = remove_queue("/is_cloexec"); if cfg!(not(any(target_os="illumos", target_os="solaris"))) { assert!(mq.is_cloexec().unwrap()); ...
poll.registry().register(&mut &mq_a, Token(0), Interest::READABLE) .expect("cannot register message queue with poll"); mq_a.send(3, b"mio a a").unwrap(); poll.poll(&mut events, None).expect("cannot poll"); let mut iter = events.iter(); assert_eq!(iter.next().unwrap().token(), Token(0)...
ap(); poll.poll(&mut events, None).expect("cannot poll"); let mut iter = events.iter(); assert_eq!(iter.next().unwrap().token(), Token(0)); assert!(iter.next().is_none()); mq_a.recv(&mut[0;10]).unwrap(); assert_eq!(mq_a.recv(&mut[0;10]).unwrap_err().kind(), ErrorKind::WouldBlock); ...
random
[ { "content": "/// Create smaller queues to avoid running into the total queues size limit.\n\n/// Several of the tests also require a capacity of 1.\n\nfn tmp_mq(name: &str) -> PosixMq {\n\n let mq = OpenOptions::readwrite()\n\n .capacity(1)\n\n .max_msg_len(64)\n\n .create()\n\n ...
Rust
src/client/mod.rs
judy2k/mongo-rust-driver
f39251fce6ede7ad712cca26e00f0b09fef6e085
pub mod auth; mod executor; pub mod options; use std::{sync::Arc, time::Duration}; use time::PreciseTime; use bson::{Bson, Document}; use derivative::Derivative; #[cfg(test)] use crate::options::StreamAddress; use crate::{ concern::{ReadConcern, WriteConcern}, db::Database, error::{ErrorKind, Result}, ...
pub mod auth; mod executor; pub mod options; use std::{sync::Arc, time::Duration}; use time::PreciseTime; use bson::{Bson, Document}; use derivative::Derivative; #[cfg(test)] use crate::options::StreamAddress; use crate::{ concern::{ReadConcern, WriteConcern}, db::Database, error::{ErrorKind, Result}, ...
pub(crate) fn emit_command_event(&self, emit: impl FnOnce(&Arc<dyn CommandEventHandler>)) { if let Some(ref handler) = self.inner.options.command_event_handler { emit(handler); } } pub fn selection_criteria(&self) -> Option<&SelectionCriteria> { self.inner.options...
pub fn with_options(options: ClientOptions) -> Result<Self> { options.validate()?; let inner = Arc::new(ClientInner { topology: Topology::new(options.clone())?, options, }); Ok(Self { inner }) }
function_block-full_function
[ { "content": "fn validate_userinfo(s: &str, userinfo_type: &str) -> Result<()> {\n\n if s.chars().any(|c| USERINFO_RESERVED_CHARACTERS.contains(&c)) {\n\n return Err(ErrorKind::ArgumentError {\n\n message: format!(\"{} must be URL encoded\", userinfo_type),\n\n }\n\n .into());...
Rust
src/header/dlfcn/mod.rs
rulibc/rulibc
fddc790cbdabcba6a469ae86a7f44fd422c6cb10
use core::{ ptr, sync::atomic::{AtomicUsize, Ordering}, }; use crate::platform::types::*; #[cfg(not(target_os = "windows"))] use crate::{c_str::CStr, ld_so::tcb::Tcb}; pub const RTLD_LAZY: c_int = 0x0001; pub const RTLD_NOW: c_int = 0x0002; pub const RTLD_GLOBAL: c_int = 0x0100; pub const RTLD_LOCAL: c_int...
use core::{ ptr, sync::atomic::{AtomicUsize, Ordering}, }; use crate::platform::types::*; #[cfg(not(target_os = "windows"))] use crate::{c_str::CStr, ld_so::tcb::Tcb}; pub const RTLD_LAZY: c_int = 0x0001; pub const RTLD_NOW: c_int = 0x0002; pub const RTLD_GLOBAL: c_int = 0x0100; pub const RTLD_LOCAL: c_int...
return -1; }; (cbs.unload)(&mut linker, handle as usize); 0 } #[cfg(target_os = "windows")] #[no_mangle] pub unsafe extern "C" fn dlclose(handle: *mut c_void) -> c_int { unimplemented!(); } #[no_mangle] pub extern "C" fn dlerror() -> *mut c_char { ERROR.swap(0, Ordering::SeqCst) as *mut c_char }...
ull() { None } else { Some(str::from_utf8_unchecked( CStr::from_ptr(cfilename).to_bytes(), )) }; let tcb = match Tcb::current() { Some(tcb) => tcb, None => { eprintln!("dlopen: tcb not found"); ERROR.store(ERROR_NOT_SUPPORTED.as_pt...
random
[ { "content": "type pte_osThreadEntryPoint = unsafe extern \"C\" fn(params: *mut c_void) -> *mut c_void;\n\n\n\n#[repr(C)]\n\n#[derive(Eq, PartialEq)]\n\n#[allow(dead_code)]\n\npub enum pte_osResult {\n\n PTE_OS_OK = 0,\n\n PTE_OS_NO_RESOURCES,\n\n PTE_OS_GENERAL_FAILURE,\n\n PTE_OS_TIMEOUT,\n\n P...
Rust
src/ui/tags.rs
fernandobatels/blitz-money
bd11e87a82320c4c0e2db67c8f521e2f2a67bd34
use backend::tags::Tag; use backend::storage::Storage; use ui::ui::*; use i18n::*; pub struct Tags {} impl Tags { pub fn list(mut storage: Storage, _params: Vec<String>, is_csv: bool) { let tags = Tag::get_tags(&mut storage); let mut table = Output::new_table(); table.set_titles(...
use backend::tags::Tag; use backend::storage::Storage; use ui::ui::*; use i18n::*; pub struct Tags {} impl Tags { pub fn list(mut storage: Storage, _params: Vec<String>, is_csv: bool) { let tags = Tag::get_tags(&mut storage); let mut table = Output::new_table(); table.set_titles(...
.expect(&I18n::text("tags_not_found")); tag.name = Input::read(I18n::text("tags_name"), true, Some(tag.name)); Tag::store_tag(&mut storage, tag); } else { println!("{}", I18n::text("tags_how_to_use_update")); } } pub fn rm(mut storage:...
lone(), 2); } else { panic!(I18n::text("field_not_found")); } Tag::store_tag(&mut storage, tag); } else if params.len() > 0 && params[0] == "-i" { let id = Input::read("#id".to_string(), true, None); let mut tag = Tag::...
random
[ { "content": "pub trait Model {\n\n\n\n // For set data into struct\n\n fn new(row: JsonValue, uuid: String, storage: &mut Storage, can_recursive: bool) -> Self;\n\n\n\n // Parse to storage data\n\n fn to_save(self) -> (String, bool, JsonValue);\n\n}\n\n\n\n// Representation of a metadata section\n\...
Rust
src/player.rs
BrickShack-Studios/vectorspace
6e7f2bc7ae6d0bff1ad661910b88391d814dbf2d
extern crate sdl2; #[path = "./entity.rs"] mod e; #[path = "./functions.rs"] mod f; use sdl2::render::{Texture}; use sdl2::rect::{Rect}; use std::time::{Instant}; pub struct Controller { pub up: bool, pub down: bool, pub left: bool, pub right: bool, pub shift: bool, pub space: bool } pub str...
extern crate sdl2; #[path = "./entity.rs"] mod e; #[path = "./functions.rs"] mod f; use sdl2::render::{Texture}; use sdl2::rect::{Rect}; use std::time::{Instant}; pub struct Controller { pub up: bool, pub down: bool, pub left: bool, pub right: bool, pub shift: bool, pub space: bool } pub str...
}
pub fn titlescreen_move(&mut self, meteors: Vec<Point>) { let point_bias = 0.1; let meteor_bias = 1000000.0; let falloff = 2.4; let now = Instant::now().elapsed().as_millis() as f32; let position = vec![0f32, 0f32]; let point = vec![500.0 + (100.0 * (now / 1000.0).cos(...
function_block-full_function
[ { "content": "pub fn sub_vector(v1: Vec<f32>, v2: Vec<f32>) -> Vec<f32> {\n\n add_vector(v1, flip_vector(v2))\n\n}\n\n\n", "file_path": "src/functions.rs", "rank": 0, "score": 94355.79765418169 }, { "content": "pub fn add_vector(v1: Vec<f32>, v2: Vec<f32>) -> Vec<f32> {\n\n vec![v2[0] ...
Rust
src/bindable_thread_pool.rs
filecoin-github/thread_binder
e220f478b9a0cb985531e91f9a81664e121cb8aa
extern crate hwloc2; extern crate libc; extern crate rayon; use hwloc2::{ObjectType, Topology, TopologyObject, CpuBindFlags, CpuSet}; use std::sync::{ Arc, Mutex, }; use log::trace; pub struct ThreadPoolBuilder { builder: rayon::ThreadPoolBuilder, bind_policy: Policy, core_set: Arc<Vec<usize>>, } imp...
extern crate hwloc2; extern crate libc; extern crate rayon; use hwloc2::{ObjectType, Topology, TopologyObject, CpuBindFlags, CpuSet}; use std::sync::{ Arc, Mutex, }; use log::trace; pub struct ThreadPoolBuilder { builder: rayon::ThreadPoolBuilder, bind_policy: Policy, core_set: Arc<Vec<usize>>, } imp...
pub fn new_with_core_set(core_set: Arc<Vec<usize>>) -> Self { trace!("new pool with cores: {:?}", core_set); let topo = Arc::new(Mutex::new(Topology::new().unwrap())); print_set(&core_set.clone(), &topo); let core_set_clone = core_set.clone(); ThreadPoolBuilder { ...
pub fn new() -> Self { let topo = Arc::new(Mutex::new(Topology::new().unwrap())); ThreadPoolBuilder { builder: rayon::ThreadPoolBuilder::new().start_handler(move |thread_id| { bind_numa(thread_id, &topo); }), bind_policy: Policy::RoundRobinNuma, ...
function_block-full_function
[ { "content": "// let's have a slow computation so you can take time checking\n\n// the binding with htop\n\npub fn fibonacci_recursive(n: u64) -> u64 {\n\n match n {\n\n 0 | 1 => n,\n\n _ => fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2),\n\n }\n\n}\n\n\n", "file_path": "example...
Rust
bin/src/gui/core_ui/audio_slider.rs
atsuzaki/ravetable
3177f519fcbf896baf6656bb0a845ac48e7dfb9c
use tuix::*; pub struct AudioSlider { label: String, value: f32, min: f32, max: f32, on_change: Option<Box<dyn Fn(f32) -> Event>>, round_label: bool, slider: Entity, textbox: Entity, } impl AudioSlider { pub fn new<T: Into<String>>(label: T, min: f32, max: f32, starting_va...
use tuix::*; pub struct AudioSlider { label: String, value: f32, min: f32, max: f32, on_change: Option<Box<dyn Fn(f32) -> Event>>, round_label: bool, slider: Entity, textbox: Entity, } impl AudioSlider { pub fn new<T: Into<String>>(label: T, min: f32, max: f32, starting_va...
}
fn on_event(&mut self, state: &mut State, entity: Entity, event: &mut Event) { if let Some(ev) = event.message.downcast::<SliderEvent>() { match ev { SliderEvent::ValueChanged(v) => { if event.target == self.slider { self.value = *v; ...
function_block-full_function
[ { "content": "pub fn get_sample_rate() -> f32 {\n\n SAMPLE_RATE.get().unwrap().0 as f32\n\n}\n\n\n", "file_path": "effects/src/lib.rs", "rank": 0, "score": 59376.088970092445 }, { "content": "pub fn set_effects_sample_rate(sample_rate: SampleRate) {\n\n SAMPLE_RATE.set(sample_rate).unw...
Rust
tests/remove_empty_subdirs.rs
zhangkaizhao/remove_empty_subdirs
c7d3dbfe5f5d1e0df389242d3e3dd7cd23237d8b
extern crate tempfile; extern crate walkdir; extern crate remove_empty_subdirs; use std::fs::{self, create_dir_all, File}; use tempfile::tempdir; use walkdir::WalkDir; use remove_empty_subdirs::remove_empty_subdirs; #[test] fn normal() { let dir = tempdir().unwrap(); let dir_1 = dir.path().join(...
extern crate tempfile; extern crate walkdir; extern crate remove_empty_subdirs; use std::fs::{self, create_dir_all, File}; use tempfile::tempdir; use walkdir::WalkDir; use remove_empty_subdirs::remove_empty_subdirs; #[test] fn normal() { let dir = tempdir().unwrap(); let dir_1 = dir.path().join(...
ths: Vec<String> = WalkDir::new(&dir) .into_iter() .filter_map(|err| err.ok()) .map(|entry| entry.path().to_str().unwrap().to_string()) .collect::<Vec<_>>(); let mut expected_subpaths: Vec<String> = [ dir.path().to_path_buf(), dir.path().join("normal_dir"), di...
_permission_denied_1_clone .metadata() .unwrap() .permissions(); assert_eq!(permissions.mode(), 0o40644); remove_empty_subdirs(dir.path()).unwrap(); let mut subpa
random
[ { "content": "/// Try to recursively remove empty directories upwards.\n\nfn _try_to_remove_empty_dir(dir: &Path, top_dir: &Path) -> bool {\n\n if dir == top_dir {\n\n // No need to remove top directory.\n\n return true;\n\n }\n\n // Try to remove empty directory.\n\n match fs::remove_...
Rust
tests/dl_from_snippet.rs
ndmitchell/annotate-snippets-rs
448b80421b5a9c39c3ed1a708636014aec82eac1
use annotate_snippets::display_list::DisplayList; use annotate_snippets::{display_list as dl, formatter::get_term_style, snippet}; #[test] fn test_format_title() { let input = snippet::Snippet { title: Some(snippet::Annotation { id: Some("E0001"), label: Some("This is a title"), ...
use annotate_snippets::display_list::DisplayList; use annotate_snippets::{display_list as dl, formatter::get_term_style, snippet}; #[test] fn test_format_title() { let input = snippet::Snippet { title: Some(snippet::Annotation { id: Some("E0001"), label: Some("This is a title"), ...
#[test] fn test_format_slices_continuation() { let src_0 = "This is slice 1"; let src_0_len = src_0.len(); let src_1 = "This is slice 2"; let src_1_len = src_1.len(); let input = snippet::Snippet { title: None, footer: vec![], slices: vec![ snippet::Slice { ...
e { lineno: None, inline_marks: vec![], line: dl::DisplaySourceLine::Empty, }, ], stylesheet: get_term_style(input.opt.color), anonymized_line_numbers: input.opt.anonymized_line_numbers, margin: None, }; assert_eq!(dl::D...
function_block-function_prefixed
[ { "content": "fn fold_body(mut body: Vec<DisplayLine<'_>>) -> Vec<DisplayLine<'_>> {\n\n enum Line {\n\n Fold(usize),\n\n Source(usize),\n\n }\n\n\n\n let mut lines = vec![];\n\n let mut no_annotation_lines_counter = 0;\n\n\n\n for (idx, line) in body.iter().enumerate() {\n\n ...
Rust
libtransact/src/state/merkle/sql/operations/get_or_create_tree.rs
leebradley/transact
6aca715a5cd5b89e08e2906e48e046f210c56387
/* * Copyright 2021 Cargill Incorporated * * 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 applicable law or a...
/* * Copyright 2021 Cargill Incorporated * * 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 applicable law or a...
assert_eq!( nodes[0], postgres::MerkleRadixTreeNode { hash: "test_root".into(), tree_id: 2, leaf_id: None, children: vec![None; 256], } ); let id = operations...
Ok(tree_id) }) } } #[cfg(test)] mod test { use super::*; #[cfg(feature = "state-merkle-sql-postgres-tests")] use crate::state::merkle::sql::backend::postgres::test::run_postgres_test; #[cfg(feature = "sqlite")] use crate::state::merkle::sql::migration::sqlite::run_migrations; ...
random
[ { "content": "/// Compute a state address for a given contract.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `name` - the name of the contract\n\n/// * `version` - the version of the contract\n\npub fn compute_contract_address(name: &str, version: &str) -> Result<Vec<u8>, AddressingError> {\n\n let s = String::...
Rust
httpbis/src/common/stream_queue_sync.rs
agentydragon/rust-http2
421d12ad936ec14c7f3ad0eb3fb914dbd78635ca
#![allow(dead_code)] use futures::channel::mpsc::unbounded; use futures::channel::mpsc::UnboundedReceiver; use futures::channel::mpsc::UnboundedSender; use futures::stream::Stream; use std::task::Poll; use crate::error; use crate::client::stream_handler::ClientResponseStreamHandler; use crate::client::types::ClientT...
#![allow(dead_code)] use futures::channel::mpsc::unbounded; use futures::channel::mpsc::UnboundedReceiver; use futures::channel::mpsc::UnboundedSender; use futures::stream::Stream; use std::task::Poll; use crate::error; use crate::client::stream_handler::ClientResponseStreamHandler; use crate::client::types::ClientT...
end_stream: bool) -> result::Result<()> { self.send(Ok(DataOrHeadersWithFlag { content: DataOrHeaders::Headers(headers), last: end_stream, })) } fn data_frame(&mut self, data: Bytes, end_stream: bool) -> result::Result<()> { self.send(Ok(DataOrHeadersWithFlag { ...
::ErrorCode; use crate::Headers; use bytes::Bytes; use futures::task::Context; use std::marker; use std::pin::Pin; pub(crate) struct StreamQueueSyncSender<T: Types> { sender: UnboundedSender<Result<DataOrHeadersWithFlag, error::Error>>, _marker: marker::PhantomData<T>, } pub(crate) struct StreamQueueSyncRecei...
random
[ { "content": "use crate::codec::http_decode_read::HttpFrameDecodedOrGoaway;\n\nuse crate::common::conn::Conn;\n\nuse crate::common::conn_write::ConnWriteSideCustom;\n\nuse crate::common::init_where::InitWhere;\n\nuse crate::common::stream::DroppedData;\n\nuse crate::common::stream::HttpStreamCommon;\n\nuse crat...
Rust
build/src/lib.rs
nikhilm/ninja-rs
c87f0f522d60bfd60d27d51ea836554c05d09cf6
/* * Copyright 2020 Nikhil Marathe <nsm.nikhil@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
/* * Copyright 2020 Nikhil Marathe <nsm.nikhil@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
ngMTimeRebuilder<DiskDirtyCache<SystemDiskInterface>> { CachingMTimeRebuilder::new(DiskDirtyCache::new(SystemDiskInterface {})) }
let mut visited = HashSet::new(); while !queue.is_empty() { let key = queue.pop_front().unwrap(); if let Some((key, task)) = task_map.get_key_value(&key) { let source = add_or_get_node(&mut keys_to_nodes, &mut graph, key); if !visited...
random
[ { "content": "pub fn run(config: Config) -> anyhow::Result<()> {\n\n if let Some(dir) = &config.execution_dir {\n\n std::env::set_current_dir(&dir).with_context(|| format!(\"changing to {} for -C\", &dir))?;\n\n }\n\n\n\n let metrics_enabled = config.debug_modes.iter().any(|v| v == &DebugMode::S...
Rust
src/iter.rs
sapir/hecs-hierarchy
19fb9f0a3dbc07891436470642cfa6df6c7c6c96
use std::{collections::VecDeque, marker::PhantomData}; use hecs::{Entity, World}; use crate::{Child, Hierarchy, Parent}; pub struct ChildrenIter<'a, T> { world: &'a World, remaining: usize, current: Entity, marker: PhantomData<T>, } impl<'a, T> ChildrenIter<'a, T> { pub(crate) fn new(world: &'a ...
use std::{collections::VecDeque, marker::PhantomData}; use hecs::{Entity, World}; use crate::{Child, Hierarchy, Parent}; pub struct ChildrenIter<'a, T> { world: &'a World, remaining: usize, current: Entity, marker: PhantomData<T>, } impl<'a, T> ChildrenIter<'a, T> { pub(crate) fn new(world: &'a ...
} #[derive(Debug)] struct StackFrame { current: Entity, remaining: usize, } pub struct DepthFirstIterator<'a, T> { world: &'a World, marker: PhantomData<T>, stack: Vec<StackFrame>, } impl<'a, T: 'static + Send + Sync> DepthFirstIterator<'a, T> { pub(crate) fn new(world: &'a World, root: Enti...
fn next(&mut self) -> Option<Self::Item> { self.world.get::<Child<T>>(self.current).ok().map(|child| { self.current = child.parent; child.parent }) }
function_block-full_function
[ { "content": "fn print_tree<T: 'static + Send + Sync>(world: &World, root: Entity) {\n\n fn internal<T: 'static + Send + Sync>(world: &World, parent: Entity, depth: usize) {\n\n for child in world.children::<T>(parent) {\n\n let name = world.get::<&str>(child).unwrap();\n\n print...
Rust
transaction/processor/src/parser.rs
zhzy0077/Accounting
a42c311a376ef3399a621710141f62704549e0be
use crate::Parser; use crate::Result; use chrono::{NaiveDate, NaiveDateTime}; use csv::{StringRecord, Trim}; use entities::Transaction; pub trait CsvParser { fn map_row(&self, record: StringRecord) -> Option<Transaction>; } impl<T: CsvParser> Parser for T { fn parse(&self, content: String) -> Result<Vec<Trans...
use crate::Parser; use crate::Result; use chrono::{NaiveDate, NaiveDateTime}; use csv::{StringRecord, Trim}; use entities::Transaction; pub trait CsvParser { fn map_row(&self, record: StringRecord) -> Option<Transaction>; } impl<T: CsvParser> Parser for T { fn parse(&self, content: String) -> Result<Vec<Trans...
}) } else { Some(Transaction { datetime: timestamp, from: self.account_name.clone(), to: "".to_owned(), amount: (amount * 100.0) as i64, description: description.to_string(), }) ...
w(&self, record: StringRecord) -> Option<Transaction> { let date = NaiveDate::parse_from_str(record.get(0)?, "%Y-%m-%d").ok()?; let description = record.get(1)?; let amount = record.get(3)?.parse::<f64>().ok()?; let timestamp = date.and_hms(0, 0, 0).timestamp(); if amount > 0.0...
function_block-random_span
[ { "content": "fn detect_encoding(content: &[u8]) -> Result<String> {\n\n let (charset, confidence, _) = chardet::detect(content);\n\n\n\n if confidence < ENCODING_DETECT_CONFIDENCE_THRESHOLD {\n\n Err(Error::Encoding {\n\n best_match: charset,\n\n })\n\n } else {\n\n let...
Rust
examples/app.rs
bjornpaulstrom/RustEmbeddedHidDevice
79674b717218570e238eba010fcb875b4a23b71e
#![no_std] #![feature(plugin)] #![plugin(interpolate_idents)] #![feature(const_fn)] extern crate jap; extern crate hal_core; use hal_core::*; use hal_core::itm_driver::*; use core::fmt::Write; extern crate stm32f401; use stm32f401::base::*; use stm32f401::gpioa::*; use stm32f401::rcc::*; extern crate cortex_m; use...
#![no_std] #![feature(plugin)] #![plugin(interpolate_idents)] #![feature(const_fn)] extern crate jap; extern crate hal_core; use hal_core::*; use hal_core::itm_driver::*; use core::fmt::Write; extern crate stm32f401; use stm32f401::base::*; use stm32f401::gpioa::*; use stm32f401::rcc::*; extern crate cortex_m; use...
pub extern "C" fn exti1_handler() { println!("exti1_handler"); } pub extern "C" fn exti2_handler() { println!("exti2_handler"); } pub extern "C" fn exti3_handler() { println!("exti3_handler"); } #[no_mangle] pub static _EXCEPTIONS: exceptions::Handlers = exceptions::Handlers { ..exceptions::DEFAULT...
fn main() { let bp = unsafe { register::basepri::read(); }; claim!(A, a, { nvic().set_priority(interrupts::Interrupt::Exti1, hw_prio!(16) as u8); nvic().set_priority(interrupts::Interrupt::Exti2, hw_prio!(15) as u8); nvic().set_priority(interrupts::Inter...
function_block-full_function
[ { "content": "pub fn gpioa() -> &'static mut Gpioa {\n\n unsafe { &mut *(GPIOA_BASE as *mut Gpioa) }\n\n}\n\n\n", "file_path": "examples/interrupt.rs", "rank": 0, "score": 231739.7513592727 }, { "content": "pub fn rcc() -> &'static mut Rcc {\n\n unsafe { &mut *(RCC_BASE as *mut Rcc) }\...
Rust
node/src/service.rs
rezamtbcp/standard-substrate
0e7ab74f7cad952e8121d9bcd886639402f7c46f
use std::sync::Arc; use std::time::Duration; use sc_client_api::{ExecutorProvider, RemoteBackend}; use node_template_runtime::{self, opaque::Block, RuntimeApi}; use sc_service::{error::Error as ServiceError, Configuration, RpcHandlers, TaskManager}; use sp_inherents::InherentDataProviders; use sc_executor::native_exe...
use std::sync::Arc; use std::time::Duration; use sc_client_api::{ExecutorProvider, RemoteBackend}; use node_template_runtime::{self, opaque::Block, RuntimeApi}; use sc_service::{error::Error as ServiceError, Configuration, RpcHandlers, TaskManager}; use sp_inherents::InherentDataProviders; use sc_executor::native_exe...
, transaction_pool, )) } pub fn new_light(config: Configuration) -> Result<TaskManager, ServiceError> { new_light_base(config).map(|(task_manager, _, _, _, _)| task_manager) }
})?; network_starter.start_network(); if config.offchain_worker.enabled { sc_service::build_offchain_workers( &config, backend.clone(), task_manager.spawn_handle(), client.clone(), network.clone(), ); } let light_deps ...
function_block-random_span
[ { "content": "pub fn development_config() -> Result<ChainSpec, String> {\n\n\tlet wasm_binary = WASM_BINARY.ok_or(\"Development wasm binary not available\".to_string())?;\n\n\tlet prop_map: serde_json::map::Map<std::string::String, serde_json::value::Value> =\n\n\tserde_json::from_str(PROPERTIES).map_err(|err|f...
Rust
src/processor/amqp.rs
gplanchat/kairoi
b98b36020f4bf1000a446f219890614d08d2de8e
use amiquip::Channel; use amiquip::Connection; use amiquip::Error as AmqpError; use amiquip::Publish; use crossbeam_channel::Receiver as CrossbeamReceiver; use crossbeam_channel::Sender as CrossbeamSender; use log::debug; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::VecDeq...
use amiquip::Channel; use amiquip::Connection; use amiquip::Error as AmqpError; use amiquip::Publish; use crossbeam_channel::Receiver as CrossbeamReceiver; use crossbeam_channel::Sender as CrossbeamSender; use log::debug; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::collections::VecDeq...
match result { Ok(_) => {}, Err(error) => { debug!("AMQP runner failed to publish {:?} ({:?}).", &request, &error); self.client.drop(&request.dsn); producer.send(Response { identifier: request.identifier, ...
let result = || -> Result<(), Error> { let channel = match self.client.open(&request.dsn) { Ok((_, channel)) => channel, Err(error) => return Err(error), }; let exchange = match channel.exchange_declare_passive(&request.exchange) { Ok(e...
assignment_statement
[ { "content": "fn argument<'a>() -> impl FnMut(&'a str) -> IResult<&'a str, String> {\n\n let space_before = take_while(|c| c == ' ');\n\n let space_after = take_while(|c| c == ' ');\n\n // Parse a simple string like 123.it's_an_example (only space, newline and double quote characters are not allowed).\...
Rust
src/details_page/data_widget/collection_form.rs
Pfeil/Fairris
24ca3dfb60215087f7a782ee512822f475a385a5
use yew::{agent::Dispatcher, prelude::*}; use yewtil::NeqAssign; use crate::{ app_state::{data::DataID, data_manager, data_manager::DataManager}, collection_service::{self, Etag, MaybeEtag}, collection_service::{collection::Collection, CollectionService}, }; pub struct CollectionForm { link: Component...
use yew::{agent::Dispatcher, prelude::*}; use yewtil::NeqAssign; use crate::{ app_state::{data::DataID, data_manager, data_manager::DataManager}, collection_service::{self, Etag, MaybeEtag}, collection_service::{collection::Collection, CollectionService}, }; pub struct CollectionForm { link: Component...
fn change(&mut self, props: Self::Properties) -> ShouldRender { let changed_id = self.props.id != props.id; let etag_exists = self .etag .clone() .map_or(false, |(id, _)| id == self.props.id); let changed = self.props.neq_assign(props);...
fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::DescriptionChanged(description) => { if description.is_empty() { self.props.collection.description = None; } else { self.props.collection.description = ...
function_block-full_function
[ { "content": "#[wasm_bindgen(start)]\n\npub fn run_app() {\n\n console_error_panic_hook::set_once();\n\n wasm_logger::init(wasm_logger::Config::default());\n\n App::<Model>::new().mount_to_body();\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 72686.13054143843 }, { "conten...
Rust
src/is_master.rs
NBSquare/mongo-rust-driver
2b7175eb20cfab3608ea0bcc1d1e1e3c406508c4
use std::time::{Duration, Instant}; use serde::Deserialize; use crate::{ bson::{doc, oid::ObjectId, DateTime, Document, Timestamp}, client::{ options::{ServerAddress, ServerApi}, ClusterTime, }, cmap::{Command, Connection}, error::{ErrorKind, Result}, sdam::ServerType, sele...
use std::time::{Duration, Instant}; use serde::Deserialize; use crate::{ bson::{doc, oid::ObjectId, DateTime, Document, Timestamp}, client::{ options::{ServerAddress, ServerApi}, ClusterTime, }, cmap::{Command, Connection}, error::{ErrorKind, Result}, sdam::ServerType, sele...
} else if let Some(true) = self.is_replica_set { ServerType::RsGhost } else { ServerType::Standalone } } } #[derive(Debug, Clone, PartialEq, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct LastWrite { pub last_write_date: DateTime, } #[derive...
if let Some(true) = self.secondary { ServerType::RsSecondary } else if let Some(true) = self.arbiter_only { ServerType::RsArbiter } else { ServerType::RsOther }
if_condition
[ { "content": "fn normalize_write_concern_doc(mut write_concern_doc: Document) -> Document {\n\n if let Some(w_timeout) = write_concern_doc.remove(\"wtimeout\") {\n\n write_concern_doc.insert(\"wtimeoutMS\", w_timeout);\n\n }\n\n\n\n if let Some(j) = write_concern_doc.remove(\"j\") {\n\n w...
Rust
src/fruchterman_reingold.rs
mneumann/graph-layout-rs
8261dcfb673f5812653f7f884f34c94b561f5d2d
use super::{P2d, Vector}; #[inline] fn attractive_force<V>(p1: &V, p2: &V, k_s: f32) -> V where V: Vector<Scalar = f32> { let force = p1.sub(p2); let length = force.length_squared().sqrt(); let strength = length / k_s; return force.scale(strength); } #[inline] fn repulsive_force<V>(p1: &V, p2: &...
use super::{P2d, Vector}; #[inline] fn attractive_force<V>(p1: &V, p2: &V, k_s: f32) -> V where V: Vector<Scalar = f32> { let force = p1.sub(p2); let length = force.length_squared().sqrt(); let strength = length / k_s; return force.scale(strength); } #[inline] fn repulsive_force<V>(p1: &V, p2: &...
pub trait ForceDirected<V> where V: Vector<Scalar = f32> { fn reset_forces(&mut self); fn update_force_each_node_pair<F: Fn(&V, &V) -> V>(&mut self, f: F); fn update_force_each_edge<F: Fn(&V, &V) -> V>(&mut self, f: F); fn update_positions<F: FnMut(&V, &V) -> V>(&mut self, f: F); } fn it...
length_squared(); if length_squared > 0.0 { let strength = k_r / length_squared; return force.scale(strength); } return force; }
function_block-function_prefixed
[ { "content": "fn draw_graph(g: graph_generators::Graph, filename: &str, l: Option<f32>) {\n\n let mut node_positions: Vec<P2d> = g.nodes\n\n .iter()\n\n .map(|_| {\n\n P2d(random::<Closed0...
Rust
tools/repl/src/repl.rs
fluencelabs/fce
7b0686ab2e70e6a92d6bd81b3cd49221704037a8
/* * Copyright 2020 Fluence Labs Limited * * 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 applicable law or a...
/* * Copyright 2020 Fluence Labs Limited * * 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 applicable law or a...
fn show_fs<'args>(&mut self, mut args: impl Iterator<Item = &'args str>) { next_argument!(module_name, args, "Module name should be specified"); match self.app_service.get_wasi_state(module_name) { Ok(wasi_state) => print_fs_state(wasi_state), Err(e) => println!("{}", e), ...
fn show_envs<'args>(&mut self, mut args: impl Iterator<Item = &'args str>) { next_argument!(module_name, args, "Module name should be specified"); match self.app_service.get_wasi_state(module_name) { Ok(wasi_state) => print_envs(module_name, wasi_state), Err(e) => println!("{}", ...
function_block-full_function
[ { "content": "pub fn extract_from_path<P>(wasm_module_path: P) -> ModuleInfoResult<Option<semver::Version>>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let module = ModuleConfig::new()\n\n .parse_file(wasm_module_path)\n\n .map_err(ModuleInfoError::CorruptedWasmFile)?;\n\n\n\n extract_from_modu...
Rust
game/src/bw_scr/shader_replaces.rs
joel-rich/ShieldBattery
6a58811873d7e524d89a13bd3df2d9c32b6195c9
use super::scr; #[cfg(debug_assertions)] use std::path::{Path, PathBuf}; #[cfg(debug_assertions)] use std::time::{Duration, Instant, SystemTime}; #[cfg(debug_assertions)] use parking_lot::Mutex; const fn pixel_sm4(wrapper: &[u8]) -> scr::PrismShader { scr::PrismShader { api_type: scr::PRISM_SHADER_API_S...
use super::scr; #[cfg(debug_assertions)] use std::path::{Path, PathBuf}; #[cfg(debug_assertions)] use std::time::{Duration, Instant, SystemTime}; #[cfg(debug_assertions)] use parking_lot::Mutex; const fn pixel_sm4(wrapper: &[u8]) -> scr::PrismShader { scr::PrismShader { api_type: scr::PRISM_SHADER_API_S...
} } } } shaders.iter().map(|&(id, data, _)| (id, data)).collect::<Vec<_>>() }; result.into_iter() } pub fn has_changed(&self) -> bool { let now = Instant::now(); let mut last_check = self.update...
if let Some((shader, new_time)) = compile_shader_retry_on_err(&path) { debug!("Recompiled shader {}", path.display()); *data = shader; *time = new_time; ...
if_condition
[ { "content": "/// Output disassembly if needed for debugging.\n\n/// Not necessary for actually building.\n\nfn disasm_shader(shader_bytes: &[u8], out_path: &Path) -> Result<(), Error> {\n\n let disasm = compile_shaders::disassemble(shader_bytes)?;\n\n fs::write(&out_path, &disasm)\n\n .with_contex...
Rust
sdk/src/product/store/diesel/mod.rs
leebradley/grid
2001cec0ff1951f953ee345f4d030ce42a68aac3
pub(in crate::product) mod models; mod operations; pub(in crate) mod schema; use crate::error::ResourceTemporarilyUnavailableError; use operations::{ add_product::AddProductOperation, delete_product::DeleteProductOperation, get_product::GetProductOperation, list_products::ListProductsOperation, update_p...
pub(in crate::product) mod models; mod operations; pub(in crate) mod schema; use crate::error::ResourceTemporarilyUnavailableError; use operations::{ add_product::AddProductOperation, delete_product::DeleteProductOperation, get_product::GetProductOperation, list_products::ListProductsOperation, update_p...
ProductStoreOperations::new(&*self.connection_pool.get().map_err(|err| { ProductStoreError::ResourceTemporarilyUnavailableError( ResourceTemporarilyUnavailableError::from_source(Box::new(err)), ) })?) .list_products(service_id, offset, limit) } fn u...
<(), ProductStoreError> { ProductStoreOperations::new(&*self.connection_pool.get().map_err(|err| { ProductStoreError::ResourceTemporarilyUnavailableError( ResourceTemporarilyUnavailableError::from_source(Box::new(err)), ) })?) .add_product(product) } ...
random
[ { "content": "/// Returns a vector of TradeItem objects from a path to an XML file containing\n\n/// a gridTradeItems XML element. An error will be returned if the XML file\n\n/// fails to validate against the GridTradeItems.xsd schema, or if the file\n\n/// does not contain well-formed XML.\n\n///\n\n/// View ...
Rust
wgpu-hal/examples/raw-gles.rs
ghishadow/wgpu
77b2c25684f971daa977596403f01c71d32ea685
extern crate wgpu_hal as hal; #[cfg(target_arch = "wasm32")] fn main() {} #[cfg(not(target_arch = "wasm32"))] fn main() { use hal::{Adapter as _, CommandEncoder as _, Device as _, Queue as _}; env_logger::init(); println!("Initializing external GL context"); let event_loop = glutin::event_loop::Ev...
extern crate wgpu_hal as hal; #[cfg(target_arch = "wasm32")] fn main() {} #[cfg(not(target_arch = "wasm32"))] fn main() { use hal::{Adapter as _, CommandEncoder as _, Device as _, Queue as _}; env_logger::init(); println!("Initializing external GL context"); let event_loop = glutin::event_loop::Ev...
ent3d { width: inner_size.width, height: inner_size.height, depth_or_array_layers: 1, }, sample_count: 1, color_attachments: &[hal::ColorAttachment { target: hal::Attachment { view: &view, usage: hal::TextureUses::CO...
oder(&hal::CommandEncoderDescriptor { label: None, queue: &od.queue, }) .unwrap() }; let rp_desc = hal::RenderPassDescriptor { label: None, extent: wgt::Ext
function_block-random_span
[ { "content": "pub fn map_texture_usage(usage: crate::TextureUses) -> mtl::MTLTextureUsage {\n\n use crate::TextureUses as Tu;\n\n\n\n let mut mtl_usage = mtl::MTLTextureUsage::Unknown;\n\n\n\n mtl_usage.set(\n\n mtl::MTLTextureUsage::RenderTarget,\n\n usage.intersects(Tu::COLOR_TARGET | T...
Rust
components/backup/src/softlimit.rs
lroolle/tikv
f3f02d7fc6cf7e94abcf8cdb9b9ff52b110a72ba
use std::cell::RefCell; use std::cmp::Ordering as CmpOrder; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use super::Result; use collections::HashMap; use crossbeam::channel::{Receiver, Sender}; use tikv_util::error; use tikv_util::metrics::ThreadInfoStatistics; use tikv_util::sys::SysQuota; ...
use std::cell::RefCell; use std::cmp::Ordering as CmpOrder; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use super::Result; use collections::HashMap; use crossbeam::channel::{Receiver, Sender}; use tikv_util::error; use tikv_util::metrics::ThreadInfoStatistics; use tikv_util::sys::SysQuota; ...
} fn should_satify_in(d: Duration, name: &str, mut f: impl FnMut() -> bool + Send + 'static) { should_finish_in(d, name, move || { while !f() { thread::sleep(d.div_f32(50.0)); } }) } #[test] fn test_current_idle() { let mut cpu ...
match rx.recv_timeout(d) { Ok(()) => {} Err(e) => panic!( "test failed: execution of {} timed out or disconnected. (timeout = {:?}, error = {})", name, d, e ), }
if_condition
[ { "content": "/// A trait of all types that can be used during evaluation (eval type).\n\npub trait Evaluable: Clone + std::fmt::Debug + Send + Sync + 'static {\n\n const EVAL_TYPE: EvalType;\n\n\n\n /// Borrows this concrete type from a `ScalarValue` in the same type;\n\n /// panics if the varient mis...
Rust
src/lib.rs
jpernst/alternate-future
fba9eaedeeada61c74e73d4b87125d14a1d060b3
#![feature(fnbox)] extern crate spin; extern crate num_cpus; #[macro_use] extern crate lazy_static; use std::sync::Arc; use std::thread::{self, Thread}; use std::boxed::FnBox; use std::mem; use std::error::Error; use std::fmt::{self, Display}; use spin::Mutex as SpinMutex; use threadpool::ThreadPool; mod threadpo...
#![feature(fnbox)] extern crate spin; extern crate num_cpus; #[macro_use] extern crate lazy_static; use std::sync::Arc; use std::thread::{self, Thread}; use std::boxed::FnBox; use std::mem; use std::error::Error; use std::fmt::{self, Display}; use spin::Mutex as SpinMutex; use threadpool::ThreadPool; mod threadpo...
} else { lock.0 = PromiseValue::Present(val); if let Some(ref thread) = lock.2 { thread.unpark(); } } } } impl <T, E> Promise<Result<T, E>> where T : Send + 'static, E : Send + 'static { #[inline] pub fn ok (self, val : T) { ...
if self.1 { cont.call_box((val,)); } else { POOL.lock().execute(move|| cont.call_box((val,))); }
if_condition
[ { "content": "type Thunk <'a> = Box<FnBox + Send + 'a>;\n\n\n\n\n", "file_path": "src/threadpool.rs", "rank": 1, "score": 64248.140580266714 }, { "content": "fn spawn_in_pool (jobs : Arc<Mutex<Receiver<Thunk<'static>>>>)\n\n{\n\n thread::spawn (move|| {\n\n let sentinel = Sentinel:...