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
render/src/textstate.rs
pdf-rs/pdf_view
a170a2c5711ed8bb8034cc227c2c4421256f5bdf
use pathfinder_geometry::{ vector::Vector2F, transform2d::Transform2F, }; use pathfinder_renderer::scene::Scene; use pathfinder_content::{ fill::FillRule, }; use font::GlyphId; use super::{ BBox, fontentry::{FontEntry, TextEncoding}, graphicsstate::{GraphicsState, DrawMode}, }; use std::convert:...
use pathfinder_geometry::{ vector::Vector2F, transform2d::Transform2F, }; use pathfinder_renderer::scene::Scene; use pathfinder_content::{ fill::FillRule, }; use font::GlyphId; use super::{ BBox, fontentry::{FontEntry, TextEncoding}, graphicsstate::{GraphicsState, DrawMode}, }; use std::convert:...
pub fn reset_matrix(&mut self) { self.set_matrix(Transform2F::default()); } pub fn translate(&mut self, v: Vector2F) { let m = self.line_matrix * Transform2F::from_translation(v); self.set_matrix(m); } pub fn next_line(&mut self) { self.translate(Vector2F::...
pub fn new() -> TextState { TextState { text_matrix: Transform2F::default(), line_matrix: Transform2F::default(), char_space: 0., word_space: 0., horiz_scale: 1., leading: 0., font_entry: None, font_size: 0., ...
function_block-full_function
[ { "content": "fn cmyk2rgb((c, m, y, k): (f32, f32, f32, f32)) -> (f32, f32, f32) {\n\n let clamp = |f| if f > 1.0 { 1.0 } else { f };\n\n (\n\n 1.0 - clamp(c + k),\n\n 1.0 - clamp(m + k),\n\n 1.0 - clamp(y + k),\n\n )\n\n}\n", "file_path": "render/src/renderstate.rs", "rank...
Rust
tests/test_max_size.rs
willi-kappler/msg_box
cb6eeed59289c82fe3c5e90cc35ae3e6d237efed
use msg_box::{new_msg_box, add_new_receiver, send_message, get_next_message, MsgData}; #[test] fn test_max_size1_1() { let mb = new_msg_box(1); add_new_receiver(&mb, "receiver01").unwrap(); send_message(&mb, "sender01", "receiver01", MsgData::Mu8(16)).unwrap(); let result = get_next_message(&mb, "re...
use msg_box::{new_msg_box, add_new_receiver, send_message, get_next_message, MsgData}; #[test] fn test_max_size1_1() { let mb = new_msg_box(1); add_new_receiver(&mb, "receiver01").unwrap(); send_message(&mb, "sender01", "receiver01", MsgData::Mu8(16)).unwrap(); let result = get_next_message(&mb, "re...
nwrap(); send_message(&mb, "sender01", "receiver01", MsgData::Mu8(16)).unwrap(); send_message(&mb, "sender01", "receiver01", MsgData::Mu8(17)).unwrap(); send_message(&mb, "sender01", "receiver01", MsgData::Mu8(18)).unwrap(); let result = get_next_message(&mb, "receiver01").unwrap(); assert_eq!(res...
sender01".to_string(), MsgData::Mu8(17)))); } #[test] fn test_max_size1_3() { let mb = new_msg_box(1); add_new_receiver(&mb, "receiver01").unwrap(); send_message(&mb, "sender01", "receiver01", MsgData::Mu8(16)).unwrap(); send_message(&mb, "sender01", "receiver01", MsgData::Mu8(17)).unwrap(); send...
random
[ { "content": "#[test]\n\nfn test_group1() {\n\n let mb = new_msg_box(64);\n\n\n\n add_new_receiver(&mb, \"receiver01\").unwrap();\n\n add_new_receiver(&mb, \"receiver02\").unwrap();\n\n add_new_receiver(&mb, \"receiver03\").unwrap();\n\n\n\n add_new_group(&mb, \"group1\").unwrap();\n\n add_rec...
Rust
tendermint/src/net.rs
DaviRain-Su/tendermint-rs
f0b307cb9e94f5a316bcdcdfc827383fc1ac810b
use crate::{ error::{Error, Kind}, node, }; use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer}; use std::{ fmt::{self, Display}, path::PathBuf, str::{self, FromStr}, }; use url::Url; pub const TCP_PREFIX: &str = "tcp://"; pub const UNIX_PREFIX: &str = "unix://"; #[de...
use crate::{ error::{Error, Kind}, node, }; use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer}; use std::{ fmt::{self, Display}, path::PathBuf, str::{self, FromStr}, }; use url::Url; pub const TCP_PREFIX: &str = "tcp://"; pub const UNIX_PREFIX: &str = "unix://"; #[de...
#[test] fn parse_tcp_ipv6_addr() { let addr = EXAMPLE_TCP_IPV6_ADDR.parse::<Address>().unwrap(); let addr_without_prefix = EXAMPLE_TCP_IPV6_ADDR[TCP_PREFIX.len()..] .parse::<Address>() .unwrap(); for addr in &[addr, addr_without_prefix] { match addr ...
se_unix_addr() { let addr = EXAMPLE_UNIX_ADDR.parse::<Address>().unwrap(); match addr { Address::Unix { path } => { assert_eq!(path.to_str().unwrap(), "/tmp/node.sock"); } other => panic!("unexpected address type: {:?}", other), } }
function_block-function_prefixed
[]
Rust
src/pins.rs
antoinevg/nucleo-h7xx
1e3aa9bae284da845c5f7a76c2ce192cf91d91ef
pub use stm32h7xx_hal as hal; pub type A0 = hal::gpio::gpioa::PA3<hal::gpio::Analog>; pub type A1 = hal::gpio::gpioc::PC0<hal::gpio::Analog>; pub type A2 = hal::gpio::gpioc::PC3<hal::gpio::Analog>; pub type A3 = hal::gpio::gpiob::PB1<hal::gpio::Analog>; pub type A4 = hal::gpio::gpioc::PC2<hal::gpio::Analog>; pub type ...
pub use stm32h7xx_hal as hal; pub type A0 = hal::gpio::gpioa::PA3<hal::gpio::Analog>; pub type A1 = hal::gpio::gpioc::PC0<hal::gpio::Analog>; pub type A2 = hal::gpio::gpioc::PC3<hal::gpio::Analog>; pub type A3 = hal::gpio::gpiob::PB1<hal::gpio::Analog>; pub type A4 = hal::gpio::gpioc::PC2<hal::gpio::Analog>; pub type ...
}
pub fn new(gpioa: hal::gpio::gpioa::Parts, gpiob: hal::gpio::gpiob::Parts, gpioc: hal::gpio::gpioc::Parts, gpiod: hal::gpio::gpiod::Parts, gpioe: hal::gpio::gpioe::Parts, gpiof: hal::gpio::gpiof::Parts, gpiog: hal::gpio::gpiog::Pa...
function_block-full_function
[ { "content": "type AlternateFunction11 = hal::gpio::Alternate<hal::gpio::AF11>;\n\n\n\n// Also see: https://github.com/stm32-rs/stm32-eth/blob/master/src/setup.rs\n\n\n\nuse hal::gpio::gpioa;\n\nuse hal::gpio::gpiob;\n\nuse hal::gpio::gpioc;\n\nuse hal::gpio::gpiog;\n\n\n\npub struct Pins {\n\n pub ref_clk: ...
Rust
src/trace/server_timing/mod.rs
felippemr/http-types
f77c653d6703192430b4ba8fb016fe17ba8d457f
mod metric; mod parse; pub use metric::Metric; use parse::parse_header; use std::convert::AsMut; use std::fmt::Write; use std::iter::Iterator; use std::option; use std::slice; use crate::headers::{HeaderName, HeaderValue, Headers, ToHeaderValues, SERVER_TIMING}; #[derive(Debug)] pub struct ServerTiming { timi...
mod metric; mod parse; pub use metric::Metric; use parse::parse_header; use std::convert::AsMut; use std::fmt::Write; use std::iter::Iterator; use std::option; use std::slice; use crate::headers::{HeaderName, HeaderValue, Headers, ToHeaderValues, SERVER_TIMING}; #[derive(Debug)] pub struct ServerTiming { timi...
r".to_owned(), None, None)?); let mut headers = Headers::new(); timings.apply(&mut headers); let timings = ServerTiming::from_headers(headers)?.unwrap(); let entry = timings.iter().next().unwrap(); assert_eq!(entry.name(), "server"); Ok(()) } #[test] fn bad...
g)] pub struct Iter<'a> { inner: slice::Iter<'a, Metric>, } impl<'a> Iterator for Iter<'a> { type Item = &'a Metric; fn next(&mut self) -> Option<Self::Item> { self.inner.next() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } #[deriv...
random
[ { "content": "#[inline]\n\npub fn powered_by(mut headers: impl AsMut<Headers>, value: Option<HeaderValue>) {\n\n let name = HeaderName::from_lowercase_str(\"X-Powered-By\");\n\n match value {\n\n Some(value) => {\n\n headers.as_mut().insert(name, value);\n\n }\n\n None => {...
Rust
src/app/test_helpers.rs
jacderida/sn_api
c7f81887856710be47fb42461cd06160cf369477
use crate::{ipc::NodeConfig, Safe}; use anyhow::{bail, Context, Result}; use rand::{distributions::Alphanumeric, rngs::OsRng, thread_rng, Rng}; use safe_network::types::{Keypair, PublicKey}; use std::{collections::BTreeSet, env::var, fs, net::SocketAddr, sync::Once}; use tracing_subscriber::{fmt, EnvFilter}; const T...
use crate::{ipc::NodeConfig, Safe}; use anyhow::{bail, Context, Result}; use rand::{distributions::Alphanumeric, rngs::OsRng, thread_rng, Rng}; use safe_network::types::{Keypair, PublicKey}; use std::{collections::BTreeSet, env::var, fs, net::SocketAddr, sync::Once}; use tracing_subscriber::{fmt, EnvFilter}; const T...
fn get_bootstrap_contacts() -> Result<NodeConfig> { let (genesis_key_hex, bootstrap_contacts) = match var(TEST_BOOTSTRAPPING_PEERS) { Ok(val) => serde_json::from_str(&val).with_context(|| { format!( "Failed to parse bootstraping contacts list from {} env var", T...
serde_json::from_str(&raw_json).with_context(|| { format!( "Failed to parse bootstraping contacts list from file: {:?}", &default_peer_file ) })?; Ok(info) }
function_block-function_prefix_line
[ { "content": "fn get_media_type(path: &Path, meta: &fs::Metadata) -> String {\n\n // see: https://stackoverflow.com/questions/18869772/mime-type-for-a-directory\n\n // We will use the FreeDesktop standard for directories and symlinks.\n\n // https://specifications.freedesktop.org/shared-mime-info-spe...
Rust
ts_json_subset/src/declarations/interface.rs
impero-com/ts_export
850f28f2286714e47ddc9179c56718b634cef279
use crate::types::{ObjectType, TypeParameters, TypeReference}; use crate::{common::filters, ident::StrictTSIdent}; use askama::Template; #[derive(Debug, Clone, PartialEq, Template)] #[template(source = r#"{{ identifiers|join(", ") }}"#, ext = "txt")] pub struct InterfaceTypeList { pub identifiers: Vec<TypeReferenc...
use crate::types::{ObjectType, TypeParameters, TypeReference}; use crate::{common::filters, ident::StrictTSIdent}; use askama::Template; #[derive(Debug, Clone, PartialEq, Template)] #[template(source = r#"{{ identifiers|join(", ") }}"#, ext = "txt")] pub struct InterfaceTypeList { pub identifiers: Vec<TypeReferenc...
#[test] fn display_interface_declaration() { assert_eq!( InterfaceDeclaration { ident: StrictTSIdent::from_str("MyInterface").unwrap(), extends_clause: None, type_params: None, obj_type: ObjectType { body: ...
m_str("Test").unwrap(), args: None, }, TypeReference { name: StrictTSIdent::from_str("TestOther").unwrap(), args: None, } ], } ...
function_block-function_prefixed
[ { "content": "pub fn fetch_crate_name_for_source_file(source_file_path: &Path) -> Result<String, Error> {\n\n let cargo_toml_path = find_cargo_toml_for_source_file(source_file_path)?;\n\n let manifest = cargo_toml::Manifest::from_path(&cargo_toml_path)?;\n\n let package = manifest\n\n .package\n...
Rust
src/sinks/util/retries2.rs
mdfranz/vector
8e7a3674ffca11b13a3a87dcf69d7254f2083e98
use crate::Error; use futures::FutureExt; use std::{ cmp, future::Future, pin::Pin, task::{Context, Poll}, time::Duration, }; use tokio::time::{delay_for, Delay}; use tower03::{retry::Policy, timeout::error::Elapsed}; pub enum RetryAction { Retry(String), DontRetry(String), ...
use crate::Error; use futures::FutureExt; use std::{ cmp, future::Future, pin::Pin, task::{Context, Poll}, time::Duration, }; use tokio::time::{delay_for, Delay}; use tower03::{retry::Policy, timeout::error::Elapsed}; pub enum RetryAction { Retry(String), DontRetry(String), ...
#[tokio::test] async fn service_error_no_retry() { trace_init(); let policy = FixedRetryPolicy::new( 5, Duration::from_secs(1), Duration::from_secs(10), SvcRetryLogic, ); let (mut svc, mut handle) = mock::spawn_layer(RetryLayer:...
async fn service_error_retry() { time::pause(); trace_init(); let policy = FixedRetryPolicy::new( 5, Duration::from_secs(1), Duration::from_secs(10), SvcRetryLogic, ); let (mut svc, mut handle) = mock::spawn_layer(RetryLayer::new(...
function_block-full_function
[ { "content": "pub fn wait_for_sync(mut f: impl FnMut() -> bool) {\n\n let wait = std::time::Duration::from_millis(5);\n\n let limit = std::time::Duration::from_secs(5);\n\n let mut attempts = 0;\n\n while !f() {\n\n std::thread::sleep(wait);\n\n attempts += 1;\n\n if attempts * ...
Rust
ntex/src/web/ws.rs
BrightOpen/ntex
187b34e02fabed8345cd64c7e37bbb278bf0132a
use std::{ error::Error as StdError, marker::PhantomData, pin::Pin, task::Context, task::Poll, }; use bytes::Bytes; use futures_core::Stream; use futures_sink::Sink; pub use crate::ws::{CloseCode, CloseReason, Frame, Message}; use crate::http::body::{Body, BoxedBodyStream}; use crate::http::error::PayloadError; ...
use std::{ error::Error as StdError, marker::PhantomData, pin::Pin, task::Context, task::Poll, }; use bytes::Bytes; use futures_core::Stream; use futures_sink::Sink; pub use crate::ws::{CloseCode, CloseReason, Frame, Message}; use crate::http::body::{Body, BoxedBodyStream}; use crate::http::error::PayloadError; ...
pin_project_lite::pin_project! { struct MapStream<S, I, E>{ #[pin] stream: S, _t: PhantomData<(I, E)>, } } impl<S, I, E> Stream for MapStream<S, I, E> where S: Stream<Item = Result<I, E>>, E: StdError + 'static, { type Item = Result<I, Box<dyn StdError>>; fn poll_next...
T::Service: 'static, F: IntoServiceFactory<T>, S: Stream<Item = Result<Bytes, PayloadError>> + Unpin + 'static, Err: From<T::InitError>, Err: From<HandshakeError>, Tx: Sink<Result<Bytes, Box<dyn StdError>>> + Clone + Unpin + 'static, Tx::Error: StdError, Rx: Stream<Item = Result<Bytes, Box<d...
function_block-function_prefix_line
[ { "content": "/// Create `Service` for mut function that can act as a `Service`\n\npub fn fn_mut_service<F, Fut, Req, Res, Err>(f: F) -> FnMutService<F, Fut, Req, Res, Err>\n\nwhere\n\n F: FnMut(Req) -> Fut,\n\n Fut: Future<Output = Result<Res, Err>>,\n\n{\n\n FnMutService::new(f)\n\n}\n\n\n\n#[inline]...
Rust
factory/src/config.rs
malte-v/rendy
56d040f6e9060cf0da960aa65423fcb27bc7a81f
use std::cmp::min; use crate::{ command::FamilyId, memory::{DynamicConfig, HeapsConfig, LinearConfig}, util::DeviceId, }; #[derive(Clone, derivative::Derivative)] #[derivative(Debug, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Config<D = BasicDevicesCo...
use std::cmp::min; use crate::{ command::FamilyId, memory::{DynamicConfig, HeapsConfig, LinearConfig}, util::DeviceId, }; #[derive(Clone, derivative::Derivative)] #[derivative(Debug, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Config<D = BasicDevicesCo...
}
fn pick<B>(&self, adapters: &[gfx_hal::adapter::Adapter<B>]) -> usize where B: gfx_hal::Backend, { adapters .iter() .enumerate() .min_by_key(|(_, adapter)| match adapter.info.device_type { gfx_hal::adapter::DeviceType::DiscreteGpu => 0, ...
function_block-full_function
[ { "content": "/// Calculate automatic `Chains` for nodes.\n\n/// This function tries to find the most appropriate schedule for nodes execution.\n\npub fn collect<Q>(nodes: Vec<Node>, max_queues: Q) -> Chains\n\nwhere\n\n Q: Fn(gfx_hal::queue::QueueFamilyId) -> usize,\n\n{\n\n // Resolve nodes into a form ...
Rust
rs/tests/src/orchestrator/node_reassignment_test.rs
3cL1p5e7/ic
2b6011291d900454cedcf86ec41c8c1994fdf7d9
/* tag::catalog[] Title:: Node reassignment test Goal:: Verify that nodes can be removed from a subnet and later assigned to a different subnet Runbook:: . Set up two subnets with four nodes each . Install a universal canister in both . Verify that the canisters can be updated and the modifications queried . Reassign...
/* tag::catalog[] Title:: Node reassignment test Goal:: Verify that nodes can be removed from a subnet and later assigned to a different subnet Runbook:: . Set up two subnets with four nodes each . Install a universal canister in both . Verify that the canisters can be updated and the modifications queried . Reassign...
pub async fn can_read_msg_with_retries( log: &slog::Logger, url: &Url, canister_id: Principal, msg: &str, mut retries: usize, ) -> bool { let bytes = msg.as_bytes(); let agent = match create_agent(url.as_str()).await { Ok(val) => val, Err(e) => { info!(log, "Could...
function_block-full_function
[]
Rust
ethers-contract/ethers-contract-abigen/src/contract/methods.rs
SamWilsn/ethers-rs
fc4b3e4ce49f67a9d0f8155902a4e750411e1174
use super::{types, util, Context}; use ethers_core::{ abi::{Function, FunctionExt, Param, StateMutability}, types::Selector, }; use anyhow::{anyhow, Context as _, Result}; use inflector::Inflector; use proc_macro2::{Literal, TokenStream}; use quote::quote; use syn::Ident; impl Context { pub(crate) fn meth...
use super::{types, util, Context}; use ethers_core::{ abi::{Function, FunctionExt, Param, StateMutability}, types::Selector, }; use anyhow::{anyhow, Context as _, Result}; use inflector::Inflector; use proc_macro2::{Literal, TokenStream}; use quote::quote; use syn::Ident; impl Context { pub(crate) fn meth...
pub(crate) fn expand_inputs_call_arg(inputs: &[Param]) -> TokenStream { let names = inputs .iter() .enumerate() .map(|(i, param)| util::expand_input_name(i, &param.name)) .collect::<Vec<TokenStream>>(); match names.len() { 0 => quote! { () }, 1 => quote! { #( #n...
m]) -> Result<TokenStream> { let params = inputs .iter() .enumerate() .map(|(i, param)| { let name = util::expand_input_name(i, &param.name); let kind = types::expand(&param.kind)?; Ok(quote! { #name: #kind }) }) .collect::<Result<Vec<_>>>(...
function_block-function_prefixed
[ { "content": "/// Expands a positional identifier string that may be empty.\n\n///\n\n/// Note that this expands the parameter name with `safe_ident`, meaning that\n\n/// identifiers that are reserved keywords get `_` appended to them.\n\npub fn expand_input_name(index: usize, name: &str) -> TokenStream {\n\n ...
Rust
src/track/constraint/audio.rs
jelmansouri-legion/media
5d1dfd9419c316f054b3b32877a3c3a886a9ca68
use std::fmt::Debug; use derive_builder::Builder; use crate::track::{ constraint::{fitness::Fitness, NonNumeric, Numeric}, setting::audio as setting, }; use super::Merge; pub type SampleRate = Numeric<setting::SampleRate>; pub type SampleSize = Numeric<setting::SampleSize>; pub type EchoCancellation = NonNu...
use std::fmt::Debug; use derive_builder::Builder; use crate::track::{ constraint::{fitness::Fitness, NonNumeric, Numeric}, setting::audio as setting, }; use super::Merge; pub type SampleRate = Numeric<setting::SampleRate>; pub type SampleSize = Numeric<setting::SampleSize>; pub type EchoCancellation = NonNu...
#[test] fn fitness_distance() { let constraint = Audio::builder() .sample_rate(SampleRate::at_least(44_100, None)) .auto_gain_control(AutoGainControl::exactly(setting::AutoGainControl::On)) .channel_count(ChannelCount::within(2, 5, Some(2))) .build() ...
echo_cancellation: None, auto_gain_control: Some(AutoGainControl::exactly(setting::AutoGainControl::On)), noise_suppression: None, latency: None, channel_count: Some(ChannelCount::within(2, 5, Some(2))), } ); }
function_block-function_prefix_line
[ { "content": "fn benchmark_from(c: &mut Criterion) {\n\n type Sample = i32;\n\n let channels = 4;\n\n let frames = 100_000;\n\n let deinterleaved_buffer: Buffer<Sample, Deinterleaved> = {\n\n let samples = (0..(channels * frames)).map(|i| i as i32).collect();\n\n Buffer::new(samples, c...
Rust
src/developer/ffx/lib/fidl-fuchsia-developer-bridge-ext/src/repo.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { camino::Utf8PathBuf, fidl_fuchsia_developer_bridge as fidl, serde::{Deserialize, Serialize}, std::convert::{TryFrom, TryInto}, thiserror::Error, }; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum RepositorySpec { ...
use { camino::Utf8PathBuf, fidl_fuchsia_developer_bridge as fidl, serde::{Deserialize, Serialize}, std::convert::{TryFrom, TryInto}, thiserror::Error, }; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum RepositorySpec { ...
singRepositoryName => RepositoryError::MissingRepositoryName, fidl::RepositoryError::NoMatchingRepository => RepositoryError::NoMatchingRepository, fidl::RepositoryError::TargetCommunicationFailure => { RepositoryError::TargetCommunicationFailure } fidl::R...
RepositorySpec::Pm { path: path.into() }) } fidl::RepositorySpec::Http(http_spec) => { let metadata_repo_url = http_spec .metadata_repo_url .ok_or(RepositoryError::MissingRepositorySpecField)?; let blob_repo_url = ...
random
[]
Rust
native/src/widget/image/viewer.rs
RDambrosio016/iced
08f5591148a74fecf3920357ce8ecba6036925a7
use crate::event::{self, Event}; use crate::image; use crate::layout; use crate::mouse; use crate::{ Clipboard, Element, Hasher, Layout, Length, Point, Rectangle, Size, Vector, Widget, }; use std::hash::Hash; #[allow(missing_debug_implementations)] pub struct Viewer<'a> { state: &'a mut State, paddin...
use crate::event::{self, Event}; use crate::image; use crate::layout; use crate::mouse; use crate::{ Clipboard, Element, Hasher, Layout, Length, Point, Rectangle, Size, Vector, Widget, }; use std::hash::Hash; #[allow(missing_debug_implementations)] pub struct Viewer<'a> { state: &'a mut State, paddin...
fn draw( &self, renderer: &mut Renderer, _defaults: &Renderer::Defaults, layout: Layout<'_>, cursor_position: Point, _viewport: &Rectangle, ) -> Renderer::Output { let bounds = layout.bounds(); let image_size = self.image_size(renderer, bounds.s...
fn on_event( &mut self, event: Event, layout: Layout<'_>, cursor_position: Point, renderer: &Renderer, _clipboard: &mut dyn Clipboard, _messages: &mut Vec<Message>, ) -> event::Status { let bounds = layout.bounds(); let is_mouse_over = bounds.c...
function_block-full_function
[ { "content": "struct Explain<'a, Message, Renderer: crate::Renderer> {\n\n element: Element<'a, Message, Renderer>,\n\n color: Color,\n\n}\n\n\n\nimpl<'a, Message, Renderer> Explain<'a, Message, Renderer>\n\nwhere\n\n Renderer: crate::Renderer,\n\n{\n\n fn new(element: Element<'a, Message, Renderer>...
Rust
src/geometry/collider_components.rs
tpdickso/rapier
3bac79ecacdeaa18de19127b7a6c82cbfab29d14
use crate::dynamics::{CoefficientCombineRule, MassProperties, RigidBodyHandle}; use crate::geometry::{InteractionGroups, SAPProxyIndex, Shape, SharedShape, SolverFlags}; use crate::math::{Isometry, Real}; use crate::parry::partitioning::IndexedData; use std::ops::Deref; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash...
use crate::dynamics::{CoefficientCombineRule, MassProperties, RigidBodyHandle}; use crate::geometry::{InteractionGroups, SAPProxyIndex, Shape, SharedShape, SolverFlags}; use crate::math::{Isometry, Real}; use crate::parry::partitioning::IndexedData; use std::ops::Deref; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash...
(self) -> bool { self.intersects( ColliderChanges::PARENT | ColliderChanges::POSITION | ColliderChanges::SHAPE, ) } pub fn needs_narrow_phase_update(self) -> bool { self.bits() > 1 } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde-seriali...
elf { Self(crate::data::arena::Index::from_raw_parts(id, generation)) } pub fn invalid() -> Self { Self(crate::data::arena::Index::from_raw_parts( crate::INVALID_U32, crate::INVALID_U32, )) } } impl IndexedData for ColliderHandle { fn default() -> S...
random
[ { "content": "pub fn init_world(testbed: &mut Testbed) {\n\n /*\n\n * World\n\n */\n\n let mut bodies = RigidBodySet::new();\n\n let mut colliders = ColliderSet::new();\n\n let joints = JointSet::new();\n\n /*\n\n * Ground.\n\n */\n\n let ground_size = 20.0;\n\n let ground_h...
Rust
serialization/src/types/uint.rs
cronosun/liquesco-rust
2f15507ba5d8b7a971cae8d0a97a4780b1632439
use crate::core::ContentDescription; use crate::core::DeSerializer; use crate::core::LqReader; use crate::core::LqWriter; use crate::core::Serializer; use crate::major_types::TYPE_UINT; use liquesco_common::error::LqError; use std::convert::TryFrom; pub struct UInt128; impl<'a> DeSerializer<'a> for UInt128 { type...
use crate::core::ContentDescription; use crate::core::DeSerializer; use crate::core::LqReader; use crate::core::LqWriter; use crate::core::Serializer; use crate::major_types::TYPE_UINT; use liquesco_common::error::LqError; use std::convert::TryFrom; pub struct UInt128; impl<'a> DeSerializer<'a> for UInt128 { type...
:from(*item)) } }
id length for unsigned integer type"), } } } impl Serializer for UInt128 { type Item = u128; fn serialize<W: LqWriter>(writer: &mut W, item: &Self::Item) -> Result<(), LqError> { let deref_item = *item; match deref_item { 0 => writer.write_content_description(TYPE_UINT,...
random
[ { "content": "#[inline]\n\nfn begin_de_serialize<'a, R: LqReader<'a>>(reader: &mut R) -> Result<Type, LqError> {\n\n let type_header = reader.read_header_byte()?;\n\n let content_description = reader.read_content_description_given_header_byte(type_header)?;\n\n\n\n if type_header.major_type() != TYPE_F...
Rust
src/roblox_web_api.rs
ZoteTheMighty/tarmac
364cd3f9f32cde68508442ab545b54e7e97ff2d9
use std::{fs, path::Path}; use reqwest::{ header::{HeaderValue, COOKIE}, multipart::{Form, Part}, Client, Request, Response, StatusCode, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone)] pub struct ImageUploadData<'a> { pub image_data: Vec<u8>, pub name: &'a str, pub description:...
use std::{fs, path::Path}; use reqwest::{ header::{HeaderValue, COOKIE}, multipart::{Form, Part}, Client, Request, Response, StatusCode, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone)] pub struct ImageUploadData<'a> { pub image_data: Vec<u8>, pub name: &'a str, pub description:...
}
apple": { "description": "I tried.", "name": "Apple", "type": "Image" } }"#, ) .file_name("config.json") .mime_str("application/json")?; let buffer = fs::read(pa...
function_block-function_prefix_line
[ { "content": "#[cfg(windows)]\n\npub fn get_auth_cookie() -> Option<String> {\n\n use winreg::{enums::HKEY_CURRENT_USER, RegKey};\n\n\n\n let hkcu = RegKey::predef(HKEY_CURRENT_USER);\n\n let cookies = hkcu\n\n .open_subkey(\"Software\\\\Roblox\\\\RobloxStudioBrowser\\\\roblox.com\")\n\n ...
Rust
boa/src/builtins/value/operations.rs
tylermorten/boa
fc169a94166aa1f23cb347e1a3a5f9910b3abda1
use super::*; impl Add for Value { type Output = Self; fn add(self, other: Self) -> Self { match (self.data(), other.data()) { (ValueData::String(ref s), ref o) => { Self::string(format!("{}{}", s.clone(), &o.to_string())) } (ValueData::BigInt(ref n1)...
use super::*; impl Add for Value { type Output = Self; fn add(self, other: Self) -> Self { match (self.data(), other.data()) { (ValueData::String(ref s), ref o) => { Self::string(format!("{}{}", s.clone(), &o.to_string())) } (ValueData::BigInt(ref n1)...
} } impl Rem for Value { type Output = Self; fn rem(self, other: Self) -> Self { match (self.data(), other.data()) { (ValueData::BigInt(ref a), ValueData::BigInt(ref b)) => { Self::bigint(a.clone() % b.clone()) } (a, b) => Self::rational(a.to_numb...
match (self.data(), other.data()) { (ValueData::BigInt(ref a), ValueData::BigInt(ref b)) => { Self::bigint(a.clone() / b.clone()) } (a, b) => Self::rational(a.to_number() / b.to_number()), }
if_condition
[ { "content": "#[test]\n\nfn get_types() {\n\n let realm = Realm::create();\n\n let mut engine = Interpreter::new(realm);\n\n\n\n assert_eq!(\n\n forward_val(&mut engine, \"undefined\").unwrap().get_type(),\n\n Type::Undefined\n\n );\n\n assert_eq!(\n\n forward_val(&mut engine...
Rust
rumqttlog/src/logs/mod.rs
anirudh-chhangani/rumq
3c69a6b5d51552ff44a53785308a94bcc5f5e163
mod connections; mod data; mod topics; use crate::{Config, Data, DataRequest}; use bytes::Bytes; use std::sync::Arc; pub use connections::ConnectionsLog; pub use topics::TopicsLog; type Id = usize; pub struct DataLog { id: Id, commitlog: [data::DataLog; 3], } impl DataLog { pub fn new(id...
mod connections; mod data; mod topics; use crate::{Config, Data, DataRequest}; use bytes::Bytes; use std::sync::Arc; pub use connections::ConnectionsLog; pub use topics::TopicsLog; type Id = usize; pub struct DataLog { id: Id, commitlog: [data::DataLog; 3], } impl DataLog { pub fn new(id...
}
pub(crate) fn extract_all_data(&mut self, request: &DataRequest) -> Option<Data> { let topic = &request.topic; let mut last_retain = request.last_retain; let mut cursors = [(0, 0); 3]; let mut payload = Vec::new(); for (i, commitlog) in self.commitlog.iter_mut().enumera...
function_block-full_function
[ { "content": "fn write_records(segment: &mut Segment, payload_size: u64, count: u64) -> Result<(), io::Error> {\n\n let record = benchmarks::generate_payload(payload_size);\n\n let guard = pprof::ProfilerGuard::new(100).unwrap();\n\n let start = Instant::now();\n\n for _i in 0..count {\n\n se...
Rust
crates/tanoshi-web/src/common/reader_settings.rs
mathroc/tanoshi
aaf37c22fcea69442c235ca892b860c2711aed3a
use dominator::{clone, events, html, Dom}; use futures_signals::{ map_ref, signal::{self, Mutable, Signal, SignalExt}, }; use serde::{Deserialize, Serialize}; use std::rc::Rc; use crate::utils::{document, local_storage}; const KEY: &str = "settings:reader"; #[derive(PartialEq, Copy, Clone, Serialize, Deseria...
use dominator::{clone, events, html, Dom}; use futures_signals::{ map_ref, signal::{self, Mutable, Signal, SignalExt}, }; use serde::{Deserialize, Serialize}; use std::rc::Rc; use crate::utils::{document, local_storage}; const KEY: &str = "settings:reader"; #[derive(PartialEq, Copy, Clone, Serialize, Deseria...
pub fn render_header(settings: Rc<Self>) -> Dom { html!("div", { .style("display", "flex") .style("justify-content", "space-between") .style("margin-bottom", "0.5rem") .visible_signal(signal::always(settings.use_modal)) .children(&mut [ ...
pub fn render_apply_button(settings: Rc<Self>) -> Dom { html!("button", { .text("Save") .event(clone!(settings => move |_: events::Click| { settings.save(); })) }) }
function_block-full_function
[ { "content": "pub fn document() -> Document {\n\n DOCUMENT.with(|d| d.clone())\n\n}\n\n\n", "file_path": "crates/tanoshi-web/src/utils.rs", "rank": 0, "score": 204273.58005653962 }, { "content": "pub fn encrypt_url(key: &str, url: &str) -> Result<String, Box<dyn std::error::Error>> {\n\n ...
Rust
src/core/config.rs
86667/loquaz
41ac1ed721d2ba6b1267f3d7ae857ea720634bd5
use secp256k1::schnorrsig::PublicKey; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, fs::{self, File}, io::{BufReader, Error}, path::PathBuf, }; const NOSTR_DIR_NAME: &str = r".nostr_chat"; const CONFIG_FILENAME: &str = "config.json"; #[derive(Clone)] pub struct ConfigProvider ...
use secp256k1::schnorrsig::PublicKey; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, fs::{self, File}, io::{BufReader, Error}, path::PathBuf, }; const NOSTR_DIR_NAME: &str = r".nostr_chat"; const CONFIG_FILENAME: &str = "config.json"; #[derive(Clone)] pub struct ConfigProvider ...
fn get_config_path() -> PathBuf { let mut path = Self::get_path(); path.push(CONFIG_FILENAME); path } fn get_path() -> PathBuf { let dir = match home::home_dir() { Some(path) => { let mut nostr_dir_path = PathBuf::new(); nostr_dir...
contacts, relays_url, } } Err(_) => Self::new(), } }
function_block-function_prefix_line
[ { "content": "fn new_contact() -> impl Widget<AppState> {\n\n let alias_input = TextBox::new()\n\n .with_placeholder(\"Contact alias\")\n\n .expand_width()\n\n .padding(5.0)\n\n .lens(AppState::new_contact_alias);\n\n\n\n let pk_input = TextBox::new()\n\n .with_placehold...
Rust
src/search/repos.rs
phansch/hubcaps
721866c197eb144dc70665c6747e91f019729895
use std::collections::HashMap; use url::form_urlencoded; use std::fmt; use {Future, SortDirection, Stream}; use super::{Search, SearchResult}; use hyper::client::connect::Connect; use users::User; #[derive(Clone, Copy, Debug, PartialEq)] pub enum ReposSort { Stars, Forks, Updated, } impl ...
use std::collections::HashMap; use url::form_urlencoded; use std::fmt; use {Future, SortDirection, Stream}; use super::{Search, SearchResult}; use hyper::client::connect::Connect; use users::User; #[derive(Clone, Copy, Debug, PartialEq)] pub enum ReposSort { Stars, Forks, Updated, } impl ...
pub fn list<Q>(&self, q: Q, options: &SearchReposOptions) -> Future<SearchResult<ReposItem>> where Q: Into<String>, { self.search .search::<ReposItem>(&self.search_uri(q, options)) } } #[derive(Default)] pub struct SearchReposOptions { params: HashMap<&'...
pub fn iter<Q>(&self, q: Q, options: &SearchReposOptions) -> Stream<ReposItem> where Q: Into<String>, { self.search.iter::<ReposItem>(&self.search_uri(q, options)) }
function_block-full_function
[ { "content": "fn next_link(l: &Link) -> Option<String> {\n\n l.values()\n\n .into_iter()\n\n .find(|v| v.rel().unwrap_or(&[]).get(0) == Some(&RelationType::Next))\n\n .map(|v| v.link().to_owned())\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 123530.44766100547 ...
Rust
rust/starlane-resources/src/property.rs
mechtronium/starlane
d0938ba2f0684c311be87a8548b9887d1880fdc8
use crate::{SkewerCase, Resource, ResourceIdentifier, ResourceSelector, ResourceStub, FieldSelection, ResourcePath, ConfigSrc}; use std::str::FromStr; use crate::error::Error; use crate::data::{DataSet, BinSrc, Meta}; use serde::{Serialize,Deserialize}; use std::collections::HashMap; use crate::parse::{parse_resource_p...
use crate::{SkewerCase, Resource, ResourceIdentifier, ResourceSelector, ResourceStub, FieldSelection, ResourcePath, ConfigSrc}; use std::str::FromStr; use crate::error::Error; use crate::data::{DataSet, BinSrc, Meta}; use serde::{Serialize,Deserialize}; use std::collections::HashMap; use crate::parse::{parse_resource_p...
portion: '{}'", s,leftover ).into()) } else { result } } } #[derive(Debug,Clone, Serialize, Deserialize)] pub enum ResourceProperty { Registry(ResourceRegistryProperty) } #[derive(Debug,Clone, Serialize, Deserialize)] pub enum ResourceRegistryProperty { Config(ConfigSrc) } impl T...
RegistryPropertyValueSelector, Self::Error> { match self { Self::Registry(registry) => { Ok(registry) } what => { Err(format!("'{}' is not a Registry Resource Property",what.to_string()).into()) } } } } #[derive(Debug, C...
random
[ { "content": "pub fn parse_resource_property_value_selector(input: &str) -> Res<&str, Result<ResourcePropertyValueSelector,Error>> {\n\n context(\n\n \"parse_resource_property_value_selector\",\n\n tuple(\n\n (parse_skewer,opt(tuple( (alt( (parse_skewer,parse_aspect_mapping) ), opt(p...
Rust
packed_struct/src/types_tuples.rs
Devlyn-Nelson/packed_struct_128
5f93e673ec8245fe3e479117cbb593c62258814f
use crate::internal_prelude::v1::*; use crate::{PackedStructSlice, PackingError, PackingResult, lib_get_mut_slice, lib_get_slice}; #[derive(Debug, Copy, Clone, PartialEq)] enum StructLength { Empty, Dynamic, Static(usize) } struct StructLengthBuilder { lengths: [StructLength; 16], i: usize } i...
use crate::internal_prelude::v1::*; use crate::{PackedStructSlice, PackingError, PackingResult, lib_get_mut_slice, lib_get_slice}; #[derive(Debug, Copy, Clone, PartialEq)] enum StructLength { Empty, Dynamic, Static(usize) } struct StructLengthBuilder { lengths: [StructLength; 16], i: usize } i...
fn get_ranges(&self) -> PackingResult<&[Range<usize>]> { lib_get_slice(&self.ranges, ..self.len) } } macro_rules! tuple_impls { () => {}; (($idx:tt => $typ:ident), $( ($nidx:tt => $ntyp:ident), )*) => { /* * Invoke recursive reversal of list that ends in the macro expansion...
0..0, 0..0, 0..0, 0..0, 0..0, 0..0, 0..0, 0..0, 0..0, 0..0, 0..0 , 0..0, 0..0, 0..0, 0..0]; let mut n = 0; for i in 0..len { let l = lib_get_slice(&lengths, i)?; let ranges_out = lib_get_mut_slice(&mut ranges, i)?; *ranges_out = n..(n+l); n += l; }...
function_block-function_prefixed
[]
Rust
config/src/cache.rs
shekhirin/foundry
fc534d9f17883519118ea54e0894b6f8ff5a8083
use crate::chain::Chain; use number_prefix::NumberPrefix; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::{fmt, fmt::Formatter, str::FromStr}; #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct StorageCachingConfig { pub chains: CachedChains, ...
use crate::chain::Chain; use number_prefix::NumberPrefix; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::{fmt, fmt::Formatter, str::FromStr}; #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct StorageCachingConfig { pub chains: CachedChains, ...
} impl<'de> Deserialize<'de> for CachedChains { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] #[serde(untagged)] enum Chains { All(String), Chains(Vec<Chain>), } mat...
f { CachedChains::All => serializer.serialize_str("all"), CachedChains::None => serializer.serialize_str("none"), CachedChains::Chains(chains) => chains.serialize(serializer), } }
function_block-function_prefixed
[ { "content": "/// Get the gas used, accounting for refunds\n\npub fn gas_used(spec: SpecId, spent: u64, refunded: u64) -> u64 {\n\n let refund_quotient = if SpecId::enabled(spec, SpecId::LONDON) { 5 } else { 2 };\n\n spent - (refunded).min(spent / refund_quotient)\n\n}\n", "file_path": "evm/src/execut...
Rust
components/content/src/section.rs
phil-opp/zola
380a8077839c2a6b0eb32aa734d780eabf410fe4
use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::result::Result as StdResult; use tera::{Tera, Context as TeraContext}; use serde::ser::{SerializeStruct, self}; use config::Config; use front_matter::{SectionFrontMatter, split_section_content}; use errors::{Result, ResultExt}; use utils::fs::rea...
use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::result::Result as StdResult; use tera::{Tera, Context as TeraContext}; use serde::ser::{SerializeStruct, self}; use config::Config; use front_matter::{SectionFrontMatter, split_section_content}; use errors::{Result, ResultExt}; use utils::fs::rea...
pub fn is_index(&self) -> bool { self.file.components.is_empty() } pub fn all_pages_path(&self) -> Vec<PathBuf> { let mut paths = vec![]; paths.extend(self.pages.iter().map(|p| p.file.path.clone())); paths.extend(self.ignored_pages.iter().map(|p| p.file.path.clon...
ent_path", &self.path); render_template(&tpl_name, tera, &context, config.theme.clone()) .chain_err(|| format!("Failed to render section '{}'", self.file.path.display())) }
function_block-function_prefixed
[ { "content": "pub fn markdown_to_html(content: &str, context: &Context) -> Result<(String, Vec<Header>)> {\n\n // We try to be smart about highlighting code as it can be time-consuming\n\n // If the global config disables it, then we do nothing. However,\n\n // if we see a code block in the content, we...
Rust
packages/agent/src/agent_config.rs
playit-cloud/playit-agent
18e692e513437c792c4b56977b72db33342a22c4
use std::net::{IpAddr, SocketAddr, SocketAddrV4}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use rand::Rng; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::lookup_host; use tokio::sync::RwLock; use agent_common::agent_config::{AgentConfig, DEFAULT_API}; ...
use std::net::{IpAddr, SocketAddr, SocketAddrV4}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use rand::Rng; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::lookup_host; use tokio::sync::RwLock; use agent_common::agent_config::{AgentConfig, DEFAULT_API}; ...
; match lookup_host(control.clone()).await { Ok(mut v) => v.next(), Err(error) => { tracing::error!(?error, address=%control, "failed to lookup control address"); None } } } } #[derive(Debug, Clone)] pub enum AgentConfigStatus { ...
match &self.config.read().await.control_address { Some(v) => v.clone(), None => "control.playit.gg:5523".to_string(), }
if_condition
[ { "content": "fn get_match_ip(ip: IpAddr) -> Ipv6Addr {\n\n match ip {\n\n IpAddr::V4(ip) => {\n\n let mut octs = [0u8; 16];\n\n octs[15] = ip.octets()[3];\n\n octs.into()\n\n }\n\n IpAddr::V6(ip) => {\n\n let mut ip = ip.octets();\n\n\n\n ...
Rust
src/test/instruction_tests/instr_vmaskmovpd.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vmaskmovpd_1() { run_test( &Instruction { mnemonic: Mnemonic::VMASKMOVPD, ...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vmaskmovpd_1() { run_test( &Instruction { mnemonic: Mnemonic::VMASKMOVPD, ...
EDX, Eight, 220319468, Some(OperandSize::Ymmword), None, )), operand2: Some(Direct(YMM4)), operand3: Some(Direct(YMM4)), operand4: None, lock: false, rounding_mode: None, ...
operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None, }, &[196, 226, 121, 47, 147, 157, 156, 50, 101], OperandSize::Qword, ) } #[test] fn vmaskmovpd_7() { run_t...
random
[ { "content": "fn encode16_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
scheme/src/spartan/r1cs.rs
Vawheter/clink_mpc
74368ed3e360ad35cf84bf6915f58450ca81b6c2
use math::{log2, Field, One, PairingEngine, Zero}; use crate::{BTreeMap, String, Vec}; use crate::r1cs::{ ConstraintSynthesizer, ConstraintSystem, Index, LinearCombination, SynthesisError, Variable, }; #[derive(Clone, Serialize, Deserialize)] pub struct R1CSInstance<E: PairingEngine> { pub num_inputs: usize,...
use math::{log2, Field, One, PairingEngine, Zero}; use crate::{BTreeMap, String, Vec}; use crate::r1cs::{ ConstraintSynthesizer, ConstraintSystem, Index, LinearCombination, SynthesisError, Variable, }; #[derive(Clone, Serialize, Deserialize)] pub struct R1CSInstance<E: PairingEngine> { pub num_inputs: usize,...
pub fn generate_r1cs<E: PairingEngine, C: ConstraintSynthesizer<E::Fr>>( circuit: C, ) -> Result<R1CSInstance<E>, SynthesisError> { let mut r1cs = R1CSInstance { num_inputs: 0, num_aux: 0, num_constraints: 0, a_matrix: vec![], b_matrix: vec![], c_matrix: vec![],...
d>( l: LinearCombination<F>, constraints: &mut [Vec<(F, Index)>], this_constraint: usize, ) { for (var, coeff) in l.as_ref() { match var.get_unchecked() { Index::Input(i) => constraints[this_constraint].push((*coeff, Index::Input(i))), Index::Aux(i) => constraints[this_co...
function_block-function_prefixed
[ { "content": "// Q (vector, zQ) * Qxn (matrix, WL, WR, WO) = n (vector, zQW)\n\npub fn vector_product<F: Field>(v: &Vec<F>, ms: &Vec<F>, m: usize, n: usize) -> Vec<F> {\n\n let zero = F::zero();\n\n let mut out = vec![zero; m];\n\n assert_eq!(v.len(), n, \"len of v and m must be equal\");\n\n\n\n fo...
Rust
tools/cargo-gnaw/src/target.rs
Prajwal-Koirala/fuchsia
ca7ae6c143cd4c10bad9aa1869ffcc24c3e4b795
use { crate::gn::add_version_suffix, crate::types::*, camino::{Utf8Path, Utf8PathBuf}, cargo_metadata::{Package, PackageId, Version}, std::borrow::Cow, std::cmp::Ordering, std::collections::{hash_map::DefaultHasher, HashMap}, std::hash::{Hash, Hasher}, std::path::Path, }; #[derive...
use { crate::gn::add_version_suffix, crate::types::*, camino::{Utf8Path, Utf8PathBuf}, cargo_metadata::{Package, PackageId, Version}, std::borrow::Cow, std::cmp::Ordering, std::collections::{hash_map::DefaultHasher, HashMap}, std::hash::{Hash, Hasher}, std::path::Path, }; #[derive...
pub fn package_root(&self, project_root: &Path) -> Utf8PathBuf { let mut package_root = self.crate_root; while !package_root.join("Cargo.toml").exists() { package_root = package_root .parent() .expect("searching up from the crate root we must find a car...
ty => panic!("Don't know how to represent this type \"{:?}\" in GN", ty), }; add_version_suffix(&prefix, &self.version) }
function_block-function_prefix_line
[]
Rust
src/interop/llvm_sys/target.rs
davnavr/llvm-model
fa6f19cb93bbb832882bd145a40976dd47f4c34b
use crate::identifier; use crate::interop::llvm_sys as interop; use crate::target; use std::borrow::Cow; use std::ptr; pub use llvm_sys::{ target::LLVMTargetDataRef, target_machine::{ LLVMCodeGenOptLevel, LLVMCodeModel, LLVMRelocMode, LLVMTargetMachineRef, LLVMTargetRef, }, }; pub unsafe fn iden...
use crate::identifier; use crate::interop::llvm_sys as interop; use crate::target; use std::borrow::Cow; use std::ptr; pub use llvm_sys::{ target::LLVMTargetDataRef, target_machine::{ LLVMCodeGenOptLevel, LLVMCodeModel, LLVMRelocMode, LLVMTargetMachineRef, LLVMTargetRef, }, }; pub unsafe fn iden...
} } impl TryFrom<target::Machine> for TargetMachine { type Error = InvalidTripleError; fn try_from(target_machine: target::Machine) -> Result<Self, Self::Error> { Ok(Self { reference: unsafe { let target_triple = TargetTriple::new(Cow::Borrowe...
Ok(Self { reference: llvm_sys::target_machine::LLVMCreateTargetMachine( host_triple.reference(), host_triple .triple() .to_triple_string()? .into_c_string() ...
call_expression
[ { "content": "fn block_name(block: &BasicBlock, f: &mut Formatter) -> std::fmt::Result {\n\n write!(f, \"B{:X}\", block as *const BasicBlock as usize)\n\n}\n\n\n", "file_path": "src/block.rs", "rank": 0, "score": 53199.50089226585 }, { "content": "//! Contains code for converting from `ll...
Rust
zephyrus/src/context.rs
AlvaroMS25/zephyrus
ce4b568edeb00d86058a9a987119a801ec387060
use crate::{ builder::WrappedClient, command::CommandResult, message::Message, twilight_exports::*, waiter::{WaiterReceiver, WaiterSender}, }; use parking_lot::Mutex; pub struct AutocompleteContext<'a, D> { pub http_client: &'a WrappedClient, pub data: &'a D, pub user_input: Option<Stri...
use crate::{ builder::WrappedClient, command::CommandResult, message::Message, twilight_exports::*, waiter::{WaiterReceiver, WaiterSender}, }; use parking_lot::Mutex; pub struct AutocompleteContext<'a, D
{ fn clone(&self) -> Self { SlashContext { http_client: &self.http_client, application_id: self.application_id, interaction_client: self.http_client.inner().interaction(self.application_id), data: &self.data, waiters: &self.waiters, int...
> { pub http_client: &'a WrappedClient, pub data: &'a D, pub user_input: Option<String>, pub interaction: &'a mut ApplicationCommandAutocomplete, } impl<'a, D> AutocompleteContext<'a, D> { pub(crate) fn new( http_client: &'a WrappedClient, data: &'a D, user_input: Option<Str...
random
[ { "content": "struct Variant {\n\n value: String,\n\n ident: Ident,\n\n index: usize,\n\n}\n\n\n\nimpl Variant {\n\n fn parse_tokens(&self, tokens: &mut TokenStream2) {\n\n let index = &self.index;\n\n let ident = &self.ident;\n\n tokens.extend(quote::quote! {\n\n #in...
Rust
src/lib.rs
alirez/snifos
97a51b36b0ef4694e3dafd4135c9a3599013cdc5
#[macro_use] extern crate lazy_static; use clap::ArgMatches; use converter::TextToPcapConverter; use parser::PacketContext; use parser::PacketGenerator; use regex::RegexSet; use std::{ fs::{File, OpenOptions}, io::BufWriter, }; use thiserror::Error; pub mod converter; pub mod parser; const MAX_FILES: u32 = 2...
#[macro_use] extern crate lazy_static; use clap::ArgMatches; use converter::TextToPcapConverter; use parser::PacketContext; use parser::PacketGenerator; use regex::RegexSet; use std::{ fs::{File, OpenOptions}, io::BufWriter, }; use thise
Err(ConversionError::TooManyFilesError) } else { Ok(format!("{}-{}.pcapng", output_path, file_num)) } } fn make_converter( split: bool, raw_interfaces: Option<RegexSet>, output_path: &str, file_num: &mut u32, ) -> Result<TextToPcapConverter<Box<dyn std::io::Write>>> { let out...
rror::Error; pub mod converter; pub mod parser; const MAX_FILES: u32 = 20; #[derive(Error, Debug)] pub enum ConversionError { #[error("Parsing failed")] ParsingError(#[from] parser::ParsingError), #[error("Conversion to pcapng failed")] ConverterError(#[from] converter::ConverterError), #[error("...
random
[ { "content": "use anyhow::{Context, Result};\n\nuse clap::{crate_version, App, Arg};\n\nuse snifos::run;\n\n\n", "file_path": "src/main.rs", "rank": 2, "score": 5.626618501641368 }, { "content": "use crate::parser::{Packet, PacketSet};\n\nuse pcapng_writer::blocks::options::{\n\n BlockOpt...
Rust
cmd/starcoin/src/view.rs
fengzeyan/starcoin
6518ed5f16cf3c6111e0c2523a7f774f88658061
use anyhow::format_err; use serde::{Deserialize, Serialize}; use starcoin_account_api::AccountInfo; use starcoin_crypto::HashValue; use starcoin_rpc_api::types::{ StrView, TransactionEventView, TransactionOutputAction, TransactionOutputView, TransactionVMStatus, }; use starcoin_types::account_address::Account...
use anyhow::format_err; use serde::{Deserialize, Serialize}; use starcoin_account_api::AccountInfo; use starcoin_crypto::HashValue; use starcoin_rpc_api::types::{ StrView, TransactionEventView, TransactionOutputAction, TransactionOutputView, TransactionVMStatus, }; use starcoin_types::account_address::Account...
ue>, } impl ExecutionOutputView { pub fn new(txn_hash: HashValue) -> Self { Self { txn_hash, block_number: None, block_id: None, } } } #[derive(Debug, Serialize)] pub struct MoveExplainView { pub category_code: u64, pub category_name: Option<String>,...
arcoin_vm_types::account_config::events::accept_token_payment::AcceptTokenEvent; use starcoin_vm_types::account_config::{BlockRewardEvent, ProposalCreatedEvent, VoteChangedEvent}; use starcoin_vm_types::event::EventKey; use starcoin_vm_types::move_resource::MoveResource; use std::collections::HashMap; #[derive(Debug, ...
random
[ { "content": "/// A predicate detailing whether the compiled versions of scripts and the stdlib should be used or\n\n/// not. The default is that the compiled versions of the stdlib and transaction scripts should be\n\n/// used.\n\npub fn use_compiled() -> bool {\n\n std::env::var(NO_USE_COMPILED).is_err()\n...
Rust
research/gaia/pegasus/network/src/lib.rs
varinic/GraphScope
b8cb7c404ed38841d46bf2cd35d8fe3fa812bf21
#[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] extern crate enum_dispatch; use crate::config::ConnectionParams; use crossbeam_utils::sync::ShardedLock; use pegasus_common::codec::*; use std::collections::HashMap; use std::net::{SocketAddr, ToSocketAddrs}; use std::sync::atomic::{A...
#[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] extern crate enum_dispatch; use crate::config::ConnectionParams; use crossbeam_utils::sync::ShardedLock; use pegasus_common::codec::*; use std::collections::HashMap; use std::net::{SocketAddr, ToSocketAddrs}; use std::sync::atomic::{A...
pub fn ipc_channel_recv<T: Codec + 'static>( channel_id: u128, local: u64, targets: &[u64], ) -> Result<IPCReceiver<T>, NetError> { if channel_id == 0 { return Err(NetError::IllegalChannelId); } crate::receive::register_remotes_receiver(channel_id, local, targets) }
pub fn ipc_channel_send<T: Codec + 'static>( channel_id: u128, local: u64, remotes: &[u64], ) -> Result<Vec<IPCSender<T>>, NetError> { if channel_id == 0 { return Err(NetError::IllegalChannelId); } crate::send::fetch_remote_sender::<T>(channel_id, local, remotes) }
function_block-full_function
[]
Rust
tests/it/io/csv/write.rs
Amdahl-rr/arrow2
9066298b531054ad7c0253827dd421797bf5684c
use std::io::Cursor; use arrow2::array::*; use arrow2::chunk::Chunk; use arrow2::datatypes::*; use arrow2::error::Result; use arrow2::io::csv::write::*; fn data() -> Chunk<Box<dyn Array>> { let c1 = Utf8Array::<i32>::from_slice(["a b", "c", "d"]); let c2 = Float64Array::from([Some(123.564532), None, Some(-556...
use std::io::Cursor; use arrow2::array::*; use arrow2::chunk::Chunk; use arrow2::datatypes::*; use arrow2::error::Result; use arrow2::io::csv::write::*; fn data() -> Chunk<Box<dyn Array>> { let c1 = Utf8Array::<i32>::from_slice(["a b", "c", "d"]); let c2 = Float64Array::from([Some(123.564532), None, Some(-556...
local_buf() { for payload in [ "bar,1234567890123456789012345678901234567890123456789012345678900293480293847", "This is the mail system at host smtp.sciprofiles.com.I'm sorry to have to inform you that your message could notbe delivered to one or more recipients. It's attached below.For furthe...
2019-04-18T03:45:55.555000001+01:00", ]; test_array( columns, expected, SerializeOptions { timestamp_format: Some("%Y-%m-%dT%H:%M:%S%.f%:z".to_string()), ..Default::default() }, ) } #[test] #[cfg(feature = "chrono-tz")] fn write_tz_timezone_formatted_...
random
[ { "content": "fn string_arrays(data: &[Option<&str>], options: SortOptions, expected_data: &[Option<&str>]) {\n\n let input = Utf8Array::<i32>::from(data);\n\n let expected = Utf8Array::<i32>::from(expected_data);\n\n let output = sort(&input, &options, None).unwrap();\n\n assert_eq!(expected, outpu...
Rust
geo/src/algorithm/vincenty_distance.rs
ewth126/geo
d040fe2a6c606f43c2037210eb0a40d48d316454
use crate::{CoordFloat, Point, EARTH_FLATTENING, EQUATORIAL_EARTH_RADIUS, POLAR_EARTH_RADIUS}; use num_traits::FromPrimitive; use std::{error, fmt}; pub trait VincentyDistance<T, Rhs = Self> { ...
use crate::{CoordFloat, Point, EARTH_FLATTENING, EQUATORIAL_EARTH_RADIUS, POLAR_EARTH_RADIUS}; use num_traits::FromPrimitive; use std::{error, fmt}; pub trait VincentyDistance<T, Rhs = Self> { ...
#[test] fn test_vincenty_distance_coincident() { let a = Point::<f64>::new(12.3, 4.56); let b = Point::<f64>::new(12.3, 4.56); assert_relative_eq!(a.vincenty_distance(&b).unwrap(), 0.0, epsilon = 1.0e-3); } #[test] fn test_vincenty_distance_antipodal() { let a = Po...
fn test_vincenty_distance_equatorial() { let a = Point::<f64>::new(0.0, 0.0); let b = Point::<f64>::new(100.0, 0.0); assert_relative_eq!( a.vincenty_distance(&b).unwrap(), 11131949.079, epsilon = 1.0e-3 ); }
function_block-full_function
[ { "content": "/// Find the closest `Point` between a given geometry and an input `Point`.\n\n/// The closest point may intersect the geometry, be a single\n\n/// point, or be indeterminate, as indicated by the value of the returned enum.\n\n///\n\n/// # Examples\n\n///\n\n/// We have a horizontal line which goe...
Rust
bindings/wasm/src/did/wasm_service.rs
Dr-Electron/identity.rs
acddd76dc02f05b9403181150ea564d7ad639a02
use crate::common::deserialize_map_or_any; use crate::common::MapStringAny; use identity::did::ServiceEndpoint; use identity::iota_core::IotaDIDUrl; use identity::iota_core::IotaService; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use crate::did::WasmDIDUrl; use crate::error::Result; use crate::error::Wa...
use crate::common::deserialize_map_or_any; use crate::common::MapStringAny; use identity::did::ServiceEndpoint; use identity::iota_core::IotaDIDUrl; use identity::iota_core::IotaService; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use crate::did::WasmDIDUrl; use crate::error::Result; use crate::error::Wa...
#[wasm_bindgen] pub fn properties(&self) -> Result<MapStringAny> { MapStringAny::try_from(self.0.properties()) } #[wasm_bindgen(js_name = toJSON)] pub fn to_json(&self) -> Result<JsValue> { JsValue::from_serde(&self.0).wasm_result() } #[wasm_bindgen(js_name = fromJSON)] pub fn from_...
pub fn service_endpoint(&self) -> UServiceEndpoint { match self.0.service_endpoint() { ServiceEndpoint::One(url) => JsValue::from_str(url.as_str()).unchecked_into::<UServiceEndpoint>(), ServiceEndpoint::Set(set) => set .iter() .map(|url| JsValue::from_str(url.as_str())) ...
function_block-full_function
[ { "content": "pub fn encode_b64(data: impl AsRef<[u8]>) -> String {\n\n base64::encode_config(data.as_ref(), base64::URL_SAFE_NO_PAD)\n\n}\n\n\n", "file_path": "libjose/src/utils/base64.rs", "rank": 0, "score": 264466.2925405088 }, { "content": "pub fn encode_b64_into(data: impl AsRef<[u8]>...
Rust
crates/macaw_editor/src/undo.rs
tlein/kiln
4561988f53137cc24f8ecb6581eb02cd1bbbac85
use macaw_data::{Library, Record, RecordId, Watermark}; use std::{boxed::Box, fmt::Debug, marker::PhantomData}; trait Undoable: Debug { fn undo(&mut self, library: &Library); fn redo(&mut self, library: &Library); fn lsn(&self) -> u64; } #[derive(Debug)] struct UndoRecord<R> where R: Record, { pub...
use macaw_data::{Library, Record, RecordId, Watermark}; use std::{boxed::Box, fmt::Debug, marker::PhantomData}; trait Undoable: Debug { fn undo(&mut self, library: &Library); fn redo(&mut self, library: &Library); fn lsn(&self) -> u64; } #[derive(Debug)] struct UndoRecord<R> where R: Record, { pub...
#[test] fn test_combine_scope() { let library = Library::default(); library.register::<Person>(); let mut undo_redo = UndoRedo::new(library.clone()); undo_redo.watch::<Person>(); let catalog = library.checkout::<Person>(); let id = catalog.create(Person::new(29...
let mut write = person.value.clone(); write.name = String::from("2"); catalog.commit(&person, write); } undo_redo.undo(); assert_eq!(String::from("0"), catalog.get(id).name); undo_redo.redo(); assert_eq!(String::from("1"), catalog.get(id).name); }
function_block-function_prefix_line
[ { "content": "pub trait Record: 'static + Clone + Debug + Default + Send + Sync {\n\n fn type_name() -> &'static str;\n\n fn proto_update(&self, old_prototype: &Self, new_prototype: &Self) -> Self;\n\n}\n\n\n\n#[derive(Debug)]\n\npub(crate) struct RecordWrapper<R>\n\nwhere\n\n R: Record,\n\n{\n\n pu...
Rust
crates/btc-relay/src/types.rs
gregdhill/interbtc
88e53a7d46c437fdd58ef232973388469186ecf9
use crate::{Error, ACCEPTED_MAX_TRANSACTION_OUTPUTS}; use bitcoin::types::{BlockHeader, H256Le, Transaction, Value}; pub use bitcoin::Address as BtcAddress; use codec::{Decode, Encode}; use frame_support::{dispatch::DispatchError, ensure}; use sp_core::H256; use sp_std::{convert::TryFrom, vec::Vec}; #[derive(Encode, D...
use crate::{Error, ACCEPTED_MAX_TRANSACTION_OUTPUTS}; use bitcoin::types::{BlockHeader, H256Le, Transaction, Value}; pub use bitcoin::Address as BtcAddress; use codec::{Decode, Encode}; use frame_support::{dispatch::DispatchError, ensure}; use sp_core::H256; use sp_std::{convert::TryFrom, vec::Vec}; #[derive(Encode, D...
let paid_amount = self .payments .iter() .find_map(|&(amount, address)| if address == recipient { Some(amount) } else { None }) .ok_or(Error::<T>::InvalidPayment)?; ensure!(paid_amount == expected_amount, Error::<T>::InvalidPaymentAmount); ...
if let Some(op_return) = op_return { ensure!(op_return == self.op_return, Error::<T>::InvalidPayment); }
if_condition
[ { "content": "fn build_dummy2_transaction_with(output_addresses: Vec<(i64, BtcAddress)>, op_return: H256) -> Transaction {\n\n let mut builder = TransactionBuilder::new();\n\n builder.with_version(1).add_input(\n\n TransactionInputBuilder::new()\n\n .with_coinbase(false)\n\n ....
Rust
database/src/models/case.rs
Graficzekk/custom
4a9280005bab90aa530d270e1317d043776953b8
use std::sync::Arc; use mongodb::bson::DateTime; use twilight_model::datetime::Timestamp; use serde::{Serialize, Deserialize}; use twilight_http::Client; use twilight_model::channel::embed::{Embed, EmbedAuthor, EmbedField, EmbedFooter}; use twilight_model::guild::Member; use twilight_model::id::Id; use twilight_model::...
use std::sync::Arc; use mongodb::bson::DateTime; use twilight_model::datetime::Timestamp; use serde::{Serialize, Deserialize}; use twilight_http::Client; use twilight_model::channel::embed::{Embed, EmbedAuthor, EmbedField, EmbedFooter}; use twilight_model::guild::Member; use twilight_model::id::Id; use twilight_model::...
}
d { inline: false, name: format ! ("**Case #{} - {}**", self.index, action.to_string()), value: reason } }
function_block-function_prefixed
[]
Rust
lesson-25-x-image-gen/render_gl/src/flatlander/buffers.rs
MerHS/rust-and-opengl-lessons
a7d78b852b62f2aab559b533c03293399298c468
use crate::na; use crate::data; use crate::buffer::Buffer; use crate::buffer::VertexArray; #[derive(VertexAttribPointers, Copy, Clone, Debug)] #[repr(C, packed)] pub struct FlatlanderVertex { #[location = "0"] pub pos: data::f16_f16, #[location = "1"] pub normal: data::f16_f16, } #[deriv...
use crate::na; use crate::data; use crate::buffer::Buffer; use crate::buffer::VertexArray; #[derive(VertexAttribPointers, Copy, Clone, Debug)] #[repr(C, packed)] pub struct FlatlanderVertex { #[location = "0"] pub pos: data::f16_f16, #[location = "1"] pub normal: data::f16_f16, } #[deriv...
} impl Buffers { pub fn new(gl: &gl::Gl) -> Buffers { let vertices = Buffer::new_array(&gl); let indices = Buffer::new_element_array(&gl); let indirect = Buffer::new_draw_indirect(&gl); let draw_id = Buffer::new_array(&gl); let lines_vao = VertexArray::new(gl); ...
f, items_len: usize, items: I) { if items_len > 0 { let should_recreate_buffer = self.len < items_len; self.buffer.bind(); if should_recreate_buffer { self.buffer.stream_draw_data_null::<T>(items_len); } if let Some(mut buf...
function_block-function_prefixed
[]
Rust
src/layers.rs
GothAck/layeredconf
d5b314d766822fe67a8351bfec5d988dd67eb61b
use std::{ collections::HashSet, env::current_dir, path::{Path, PathBuf}, sync::{Arc, Mutex}, }; use clap::Parser; use crate::{map_canonicalization_error, map_io_error, Error}; use super::{LayeredConfLayer, LayeredConfMerge, LayeredConfSolid, LayeredConfSolidify, Result}; #[derive(Debug)] pub stru...
use std::{ collections::HashSet, env::current_dir, path::{Path, PathBuf}, sync::{Arc, Mutex}, }; use clap::Parser; use crate::{map_canonicalization_error, map_io_error, Error}; use super::{LayeredConfLayer, LayeredConfMerge, LayeredConfSolid, LayeredConfSolidify, Result}; #[derive(Debug)] pub stru...
} fn auto_format(&self, path: &Path, format: &Format) -> Result<Format> { match format { Format::Auto => { let extension = path.extension().map(|s| s.to_str()).flatten(); match extension { Some("json") => Ok(Format::Json), ...
Ok(match format { Format::Auto => return Err(Error::AutoFormatFailed), Format::Json => serde_json::from_str(string)?, Format::Toml => toml::from_str(string)?, Format::Yaml => serde_yaml::from_str(string)?, })
call_expression
[ { "content": "#[test]\n\nfn test_struct_level_default() -> anyhow::Result<()> {\n\n use serde_json::json;\n\n #[derive(LayeredConf, Deserialize, Serialize, Clone, Debug)]\n\n #[layered(default)]\n\n struct Config {\n\n #[clap(long)]\n\n config: String,\n\n #[clap(long)]\n\n ...
Rust
src/ser/mod.rs
srijs/rust-gob
ce00ee66ec9cf1802f08d2f33d48ce527afabc7f
use std::io::Write; use serde::ser::{self, Impossible}; use serde::Serialize; use serde_schema::SchemaSerialize; use internal::ser::{FieldValueSerializer, SerializationCtx, SerializeVariantValue}; use internal::utils::Bow; use error::Error; pub use schema::{Schema, TypeId}; mod output; pub use self::output::{Outp...
use std::io::Write; use serde::ser::{self, Impossible}; use serde::Serialize; use serde_schema::SchemaSerialize; use internal::ser::{FieldValueSerializer, SerializationCtx, SerializeVariantValue}; use internal::utils::Bow; use error::Error; pub use schema::{Schema, TypeId}; mod output; pub use self::output::{Outp...
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { Err(ser::Error::custom("not implemented yet")) } fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> { Err(ser::Error::custom("not implemented yet")) } fn serialize_unit_variant( s...
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Serialize, { value.serialize(self) }
function_block-full_function
[ { "content": "fn output_buffer(bench: &mut Bencher) {\n\n let rpc_response = RpcResponse {\n\n service_method: \"Function.Invoke\",\n\n seq: 1,\n\n error: None,\n\n };\n\n let invoke_response = InvokeResponse {\n\n payload: \"\\\"Hello world!\\\"\",\n\n };\n\n\n\n let ...
Rust
src/libsyntax/owned_slice.rs
cburgdorf/rust
60b4a97de70b9b40550a576b11c5670899be00c4
use std::default::Default; use std::hash::Hash; use std::{mem, raw, ptr, slice}; use serialize::{Encodable, Decodable, Encoder, Decoder}; #[unsafe_no_drop_flag] pub struct OwnedSlice<T> { data: *mut T, len: uint, } #[unsafe_destructor] impl<T> Drop for OwnedSlice<T> { fn drop(&mut self) { ...
use std::default::Default; use std::hash::Hash; use std::{mem, raw, ptr, slice}; use serialize::{Encodable, Decodable, Encoder, Decoder}; #[unsafe_no_drop_flag] pub struct OwnedSlice<T> { data: *mut T, len: uint, } #[unsafe_destructor] impl<T> Drop for OwnedSlice<T> { fn drop(&mut self) { ...
pub fn as_slice<'a>(&'a self) -> &'a [T] { static PTR_MARKER: u8 = 0; let ptr = if self.data.is_null() { &PTR_MARKER as *u8 as *T } else { self.data as *T }; let slice: &[T] = unsafe {mem::transmute(raw::Slice { data: ptr, ...
pub fn into_vec(self) -> Vec<T> { unsafe { let ret = Vec::from_raw_parts(self.len, self.len, self.data); mem::forget(self); ret } }
function_block-full_function
[ { "content": "pub fn walk_explicit_self<E: Clone, V: Visitor<E>>(visitor: &mut V,\n\n explicit_self: &ExplicitSelf,\n\n env: E) {\n\n match explicit_self.node {\n\n SelfStatic | SelfValue | SelfUniq => ...
Rust
src/commands/init.rs
iqlusioninc/synchronicity
6a84ccdc462116204ffca02bfb5097ae83fcdfe8
use crate::{config::CONFIG_FILE, prelude::*}; use abscissa_core::{Command, Options, Runnable}; use std::{ fs, path::{Path, PathBuf}, process::exit, }; use synchro::config::{self, peer_info, KeySeed}; pub const DERIVATION_COMPONENT: &[u8] = b"synchronicity"; #[derive(Command, Debug, Options)] pub struct ...
use crate::{config::CONFIG_FILE, prelude::*}; use abscissa_core::{Command, Options, Runnable}; use std::{ fs, path::{Path, PathBuf}, process::exit, }; use synchro::config::{self, peer_info, KeySeed}; pub const DERIVATION_COMPONENT: &[u8] = b"synchronicity"; #[derive(Command, Debug, Options)] pub struct ...
let base_dir = self.base_dir[0].canonicalize().unwrap_or_else(|e| { status_err!("couldn't canonicalize base dir: {}", e); exit(1); }); fs::create_dir_all(base_dir.join("scratch")).unwrap_or_else(|e| { status_err!("couldn't create base dir: {}", e);...
if self.base_dir.len() != 1 { status_err!("usage: synchronicity init /path/to/syncronicity/base/dir"); exit(1); }
if_condition
[ { "content": "/// App config reader\n\npub fn app_config() -> config::Reader<SynchronicityApp> {\n\n config::Reader::new(&APPLICATION)\n\n}\n\n\n\n/// Synchronicity Application\n\n#[derive(Debug)]\n\npub struct SynchronicityApp {\n\n /// Application configuration.\n\n config: Option<SynchronicityConfig...
Rust
src/client_server/state.rs
prototypefund/conduit
faa0cdb595f9d398f4a209027f1a596a4f870a39
use std::sync::Arc; use crate::{ database::DatabaseGuard, pdu::PduBuilder, ConduitResult, Database, Error, Result, Ruma, }; use ruma::{ api::client::{ error::ErrorKind, r0::state::{get_state_events, get_state_events_for_key, send_state_event}, }, events::{ room::{ ca...
use std::sync::Arc; use crate::{ database::DatabaseGuard, pdu::PduBuilder, ConduitResult, Database, Error, Result, Ruma, }; use ruma::{ api::client::{ error::ErrorKind, r0::state::{get_state_events, get_state_events_for_key, send_state_event}, }, events::{ room::{ ca...
.push(alias); } for alias in aliases { if alias.server_name() != db.globals.server_name() || db .rooms .id_from_alias(&alias)? .filter(|room| room == room_id) .is_none() { ...
.rooms .room_state_full(&body.room_id)? .values() .map(|pdu| pdu.to_state_event()) .collect(), } .into()) } #[cfg_attr( feature = "conduit_bin", get("/_matrix/client/r0/rooms/<_>/state/<_>/<_>", data = "<body>") )] #[tracing::instrument(skip(db,...
random
[ { "content": "#[tracing::instrument(skip(db, body))]\n\npub fn get_room_state_route(\n\n db: DatabaseGuard,\n\n body: Ruma<get_room_state::v1::Request<'_>>,\n\n) -> ConduitResult<get_room_state::v1::Response> {\n\n if !db.globals.allow_federation() {\n\n return Err(Error::bad_config(\"Federation...
Rust
src/io/ipc/read/common.rs
Veeupup/arrow2
9b7118b30800c294d1d070d8316abd73d00e45c6
use std::collections::VecDeque; use std::io::{Read, Seek}; use std::sync::Arc; use arrow_format::ipc; use arrow_format::ipc::Schema::MetadataVersion; use crate::array::*; use crate::chunk::Chunk; use crate::datatypes::{DataType, Field}; use crate::error::{ArrowError, Result}; use crate::io::ipc::{IpcField, IpcSchema}...
use std::collections::VecDeque; use std::io::{Read, Seek}; use std::sync::Arc; use arrow_format::ipc; use arrow_format::ipc::Schema::MetadataVersion; use crate::array::*; use crate::chunk::Chunk; use crate::datatypes::{DataType, Field}; use crate::error::{ArrowError, Result}; use crate::io::ipc::{IpcField, IpcSchema}...
}
fn project_iter() { let iter = 1..6; let iter = ProjectionIter::new(&[0, 2, 4], iter); let result: Vec<_> = iter.collect(); use ProjectionResult::*; assert_eq!( result, vec![ Selected(1), NotSelected(2), Sele...
function_block-full_function
[ { "content": "/// Reads parquets' metadata syncronously.\n\npub fn read_metadata<R: Read + Seek>(reader: &mut R) -> Result<FileMetaData> {\n\n Ok(_read_metadata(reader)?)\n\n}\n\n\n\n/// Reads parquets' metadata asynchronously.\n\npub async fn read_metadata_async<R: AsyncRead + AsyncSeek + Send + Unpin>(\n\n...
Rust
core/src/events/event.rs
kzantow-rust/tuix
b4a57fd304dcc85b4d81115e686f654adb26d5d3
use crate::{Entity, State}; use std::any::{Any, TypeId}; use std::fmt::Debug; #[derive(Debug, Clone, PartialEq)] pub enum Propagation { Down, Up, DownUp, Fall, Direct, All, } pub trait Message: Any { fn as_any(&self) -> &dyn Any; fn equals_a(&s...
use crate::{Entity, State}; use std::any::{Any, TypeId}; use std::fmt::Debug; #[derive(Debug, Clone, PartialEq)] pub enum Propagation { Down, Up, DownUp, Fall, Direct, All, } pub trait Message: Any { fn as_any(&self) -> &dyn Any; fn equals_a(&s...
pub fn target(mut self, entity: Entity) -> Self { self.target = entity; self } pub fn origin(mut self, entity: Entity) -> Self { self.origin = entity; self } pub fn unique(mut self) -> Self { self.unique = true; self } ...
where M: Message, { Event { origin: Entity::null(), target: Entity::null(), propagation: Propagation::Up, consumable: true, consumed: false, unique: true, order: 0, message: Box::new(message), } ...
function_block-function_prefix_line
[ { "content": "pub fn apply_z_ordering(state: &mut State, tree: &Tree) {\n\n for entity in tree.into_iter() {\n\n if entity == Entity::root() {\n\n continue;\n\n }\n\n\n\n let parent = tree.get_parent(entity).unwrap();\n\n\n\n if let Some(z_order) = state.style.z_order.g...
Rust
cert/aziot-certd/src/est.rs
scb01/iot-identity-service
9a12cd33ef27f82a5524c0d0d58938ec797fa852
use http_common::MaybeProxyConnector; pub(crate) async fn create_cert( csr: &[u8], url: &url::Url, basic_auth: Option<(&str, &str)>, client_cert: Option<(&[u8], &openssl::pkey::PKeyRef<openssl::pkey::Private>)>, trusted_certs: Vec<openssl::x509::X509>, proxy_uri: Option<hyper::Uri>, ) -> Resu...
use http_common::MaybeProxyConnector; pub(crate) async fn create_cert( csr: &[u8], url: &url::Url, basic_auth: Option<(&str, &str)>, client_cert: Option<(&[u8], &openssl::pkey::PKeyRef<openssl::pkey::Private>)>, trusted_certs: Vec<openssl::x509::X509>, proxy_uri: Option<hyper::Uri>, ) -> Resu...
async fn get_pkcs7_response( client: &hyper::Client< MaybeProxyConnector<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>>, >, request: Result<hyper::Request<hyper::Body>, http::Error>, ) -> Result<Vec<u8>, crate::Error> { let request = request .map_err(|err| crate::Error::I...
let simple_enroll_request = simple_enroll_request .header(hyper::header::CONTENT_TYPE, "application/pkcs10") .header("content-transfer-encoding", "base64") .body(csr.to_owned().into()); let ca_certs_request = ca_certs_request.body(Default::default()); let (simple_enroll_response, ca_ce...
function_block-function_prefixed
[ { "content": "fn request<TUri, TRequest, TResponse>(\n\n stream: &mut http_common::Stream,\n\n method: &http::Method,\n\n uri: TUri,\n\n body: Option<&TRequest>,\n\n) -> std::io::Result<TResponse>\n\nwhere\n\n TUri: std::fmt::Display,\n\n TRequest: serde::Serialize,\n\n TResponse: serde::de...
Rust
rust/app/src/parser/operations/endorsement.rs
Zondax/ledger-tezos
ac5b6fab1c5d093bb9f8edf3f8a1e3b30ab359be
/******************************************************************************* * (c) 2021 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/lic...
/******************************************************************************* * (c) 2021 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/lic...
#[test] fn endorsement() { const INPUT_HEX: &str = "fffffed4"; let input = hex::decode(INPUT_HEX).expect("invalid input hex"); let (rem, parsed) = Endorsement::from_bytes(&input).expect("failed to parse endorsement"); assert_eq!(rem.len(), 0); let expected = Endorsem...
code(INPUT_HEX).expect("invalid input hex"); let (rem, parsed) = EndorsementWithSlot::from_bytes(&input).expect("failed to parse endorsement"); assert_eq!(rem.len(), 0); let (len, branch) = Operation::base58_branch(parsed.branch).expect("couldn't encode branch to base58...
function_block-function_prefixed
[ { "content": "#[inline(never)]\n\npub fn handle_ui_message(item: &[u8], out: &mut [u8], page: u8) -> Result<u8, ViewError> {\n\n crate::sys::zemu_log_stack(\"handle_ui_message\\x00\");\n\n let m_len = out.len() - 1; //null byte terminator\n\n if m_len <= item.len() {\n\n let chunk = item\n\n ...
Rust
mayastor/src/bdev/nexus/nexus_channel.rs
dsavitskiy/mayastor
e3e5f1fa3062a30d7d2c3367634149feb3da7fc9
use std::{ffi::c_void, fmt::Debug, ptr::NonNull}; use futures::channel::oneshot; use spdk_sys::{ spdk_for_each_channel, spdk_for_each_channel_continue, spdk_io_channel, spdk_io_channel_iter, spdk_io_channel_iter_get_channel, spdk_io_channel_iter_get_ctx, spdk_io_channel_iter_get_io_devic...
use std::{ffi::c_void, fmt::Debug, ptr::NonNull}; use futures::channel::oneshot; use spdk_sys::{ spdk_for_each_channel, spdk_for_each_channel_continue, spdk_io_channel, spdk_io_channel_iter, spdk_io_channel_iter_get_channel, spdk_io_channel_iter_get_ctx, spdk_io_channel_iter_get_io_devic...
pub extern "C" fn reconfigure( device: *mut c_void, ctx: Box<ReconfigureCtx>, _event: &DrEvent, ) { unsafe { spdk_for_each_channel( device, Some(NexusChannel::refresh_io_channels), Box::into_raw(ctx).cast(), ...
pub(crate) extern "C" fn destroy(device: *mut c_void, ctx: *mut c_void) { let nexus = unsafe { Nexus::from_raw(device) }; debug!("{} Destroying IO channels", nexus.bdev.name()); let inner = NexusChannel::from_raw(ctx).inner_mut(); inner.writers.clear(); inner.readers.clear(); ...
function_block-full_function
[ { "content": "type IoDeviceCreateCb = unsafe extern \"C\" fn(*mut c_void, *mut c_void) -> i32;\n", "file_path": "mayastor/src/core/io_device.rs", "rank": 0, "score": 502741.92827510426 }, { "content": "type IoDeviceDestroyCb = unsafe extern \"C\" fn(*mut c_void, *mut c_void);\n\n\n\n/// Abst...
Rust
gdk-pixbuf/src/auto/pixbuf_animation.rs
pop-os/gtk-rs
0a0e50a2f5ea8f816c005bd8c3d145a5a9581d8c
use crate::Pixbuf; use glib::object::IsA; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::pin::Pin; use std::ptr; glib::wrapper! { pub struct PixbufAnimation(Object<ffi::GdkPixbufAnimation, ffi::GdkPixbufAnimationClass>); match fn { get_type => || ffi::gdk_pixbuf_animatio...
use crate::Pixbuf; use glib::object::IsA; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::pin::Pin; use std::ptr; glib::wrapper! { pub struct PixbufAnimation(Object<ffi::GdkPixbufAnimation, ffi::GdkPixbufAnimationClass>); match fn { get_type => || ffi::gdk_pixbuf_animatio...
.0, &mut error, ); if error.is_null() { Ok(from_glib_full(ret)) } else { Err(from_glib_full(error)) } } } pub fn new_from_stream_async< P: IsA<gio::InputStream>, Q: IsA<gio::Cancellable>, ...
let ret = ffi::gdk_pixbuf_animation_new_from_stream( stream.as_ref().to_glib_none().0, cancellable.map(|p| p.as_ref()).to_glib_none()
function_block-random_span
[ { "content": "pub fn dbus_address_get_stream_sync<P: IsA<Cancellable>>(\n\n address: &str,\n\n cancellable: Option<&P>,\n\n) -> Result<(IOStream, Option<glib::GString>), glib::Error> {\n\n unsafe {\n\n let mut out_guid = ptr::null_mut();\n\n let mut error = ptr::null_mut();\n\n let...
Rust
exonum/src/encoding/float.rs
fossabot/exonum
9246edd56a33721da1ddae055657b05bda8059ab
use byteorder::{ByteOrder, LittleEndian}; use serde_json::value::{Number, Value}; use std::error::Error; use std::mem; use super::Error as EncodingError; use super::Result as EncodingResult; use encoding::serialize::WriteBufferWrapper; use encoding::serialize::json::{ExonumJson, ExonumJsonDeserialize}; use encoding...
use byteorder::{ByteOrder, LittleEndian}; use serde_json::value::{Number, Value}; use std::error::Error; use std::mem; use super::Error as EncodingError; use super::Result as EncodingResult; use encoding::serialize::WriteBufferWrapper; use encoding::serialize::json::{ExonumJson, ExonumJsonDeserialize}; use encoding...
} } impl<'a> Field<'a> for F64 { fn field_size() -> Offset { mem::size_of::<Self>() as Offset } unsafe fn read(buffer: &'a [u8], from: Offset, to: Offset) -> Self { Self::new(LittleEndian::read_f64(&buffer[from as usize..to as usize])) } fn write(&self, buffer: &mut Vec<u8>, ...
match Self::try_from(value) { Some(_) => Ok(latest_segment), None => Err(EncodingError::UnsupportedFloat { position: from, value: f64::from(value), }), }
if_condition
[ { "content": "#[derive(Clone, Debug)]\n\nstruct HexField<T: AsRef<[u8]> + Clone>(pub T);\n\n\n\nimpl<T> Deref for HexField<T>\n\nwhere\n\n T: AsRef<[u8]> + Clone,\n\n{\n\n type Target = T;\n\n\n\n fn deref(&self) -> &T {\n\n &self.0\n\n }\n\n}\n\n\n\nimpl<T> Serialize for HexField<T>\n\nwhere...
Rust
src/virtual_dom/vcomp.rs
rharriso/yew
8448e00fb2dad766562716e12bad66bd507a9565
use super::{Transformer, VDiff, VNode}; use crate::html::{Component, ComponentUpdate, HiddenScope, NodeRef, Scope}; use crate::utils::document; use cfg_if::cfg_if; use std::any::TypeId; use std::fmt; use std::mem::swap; use std::rc::Rc; cfg_if! { if #[cfg(feature = "std_web")] { use stdweb::web::{Element,...
use super::{Transformer, VDiff, VNode}; use crate::html::{Component, ComponentUpdate, HiddenScope, NodeRef, Scope}; use crate::utils::document; use cfg_if::cfg_if; use std::any::TypeId; use std::fmt; use std::mem::swap; use std::rc::Rc; cfg_if! { if #[cfg(feature = "std_web")] { use stdweb::web::{Element,...
} impl<COMP> VChild<COMP> where COMP: Component, { pub fn new(props: COMP::Properties, node_ref: NodeRef) -> Self { Self { props, node_ref } } } impl<COMP> From<VChild<COMP>> for VComp where COMP: Component, { fn from(vchild: VChild<COMP>) -> Self { VComp::new::<COMP>(vchild....
f) -> Self { VChild { props: self.props.clone(), node_ref: self.node_ref.clone(), } }
function_block-function_prefixed
[ { "content": "enum ComponentState<COMP: Component> {\n\n Empty,\n\n Ready(ReadyState<COMP>),\n\n Created(CreatedState<COMP>),\n\n Processing,\n\n Destroyed,\n\n}\n\n\n\nimpl<COMP: Component> fmt::Display for ComponentState<COMP> {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\...
Rust
src/sys/lib/runner/src/log.rs
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
use { async_trait::async_trait, fuchsia_async as fasync, fuchsia_zircon as zx, futures::{ io::{self, AsyncRead}, prelude::*, ready, task::{Context, Poll}, }, std::{boxed::Box, cell::RefCell, pin::Pin}, thiserror::Error, }; const NEWLINE: u8 = b'\n'; thread_loc...
use { async_trait::async_trait, fuchsia_async as fasync, fuchsia_zircon as zx, futures::{ io::{self, AsyncRead}, prelude::*, ready, task::{Context, Poll}, }, std::{boxed::Box, cell::RefCell, pin::Pin}, thiserror::Error, }; const NEWLINE: u8 = b'\n'; thread_loc...
#[fasync::run_singlethreaded(test)] async fn logger_stream_captures_utf8_msg() -> Result<(), Error> { let (tx, rx) = zx::Socket::create(zx::SocketOpts::STREAM).context("Failed to create socket")?; let stream = LoggerStream::new(rx).context("Failed to create LoggerStream")?; ...
async fn logger_stream_captures_simple_msg() -> Result<(), Error> { let (tx, rx) = zx::Socket::create(zx::SocketOpts::STREAM).context("Failed to create socket")?; let stream = LoggerStream::new(rx).context("Failed to create LoggerStream")?; write_to_socket!(tx, join_lines!("Hello Wor...
function_block-full_function
[]
Rust
simtap/src/dnsresolv.rs
kglavin/universal-agent
1999bcc1ed6ba3aaf255b1596cc886736ab2245b
use hermes::dns::client::DnsClient; use hermes::dns::protocol::{DnsPacket, DnsRecord, QueryType,TransientTtl}; use hermes::dns::cache::Cache; use crate::nat::NatMap; use std::net::Ipv4Addr; pub struct DNSCache { cache: hermes::dns::cache::Cache, } impl DNSCache { pub fn new() -> Self { let cache = Cache::new...
use hermes::dns::client::DnsClient; use hermes::dns::protocol::{DnsPacket, DnsRecord, QueryType,TransientTtl}; use hermes::dns::cache::Cache; use crate::nat::NatMap; use std::net::Ipv4Addr; pub struct DNSCache { cache: hermes::dns::cache::Cache, } impl DNSCache { pub fn new() -> Self { let cache = Cache::new...
println!("ran dnsresolv::create_cache") } #[test] fn csv_dns() { let _dns_cache = DNSCache::new(); let mut rdr = csv::Reader::from_path("/Users/kglavin/Documents/GitHub/universal-agent/simtap/domains.csv").unwrap(); for result in rdr.records() { let record = result.u...
if let Some(packet) = dns_cache.lookup("www.google.com", QueryType::A) { assert_eq!(ResultCode::NOERROR, packet.header.rescode); }
if_condition
[ { "content": "fn process_icmp(ip: &etherparse::Ipv4Header, _cm: &mut ConnectionManager, recv_buf: &[u8], len: usize, send_buf: &mut[u8]) -> usize { \n\n\t// doing no processing at moment, just copy udp payload from in to out\n\n\tsend_buf[..len].copy_from_slice(&recv_buf[..len]);\n\n\tlen\n\n}\n\n\n", "file...
Rust
src/daemon/mod.rs
ebbflow-io/ebb-client
0f1bfc988bedba7dee93e90e523cdacf1fb13ccb
pub mod connection; pub mod health; use crate::daemon::connection::{run_connection, EndpointConnectionArgs, EndpointConnectionType}; use crate::dns::DnsResolver; use crate::{ certs::ROOTS, config::{ConcreteHealthCheck, HealthCheck, HealthCheckType}, messagequeue::MessageQueue, signal::{SignalReceiver, ...
pub mod connection; pub mod health; use crate::daemon::connection::{run_connection, EndpointConnectionArgs, EndpointConnectionType}; use crate::dns::DnsResolver; use crate::{ certs::ROOTS, config::{ConcreteHealthCheck, HealthCheck, HealthCheckType}, messagequeue::MessageQueue, signal::{SignalReceiver, ...
Arc::new(EndpointMeta::new(sender, maybe_hc.clone())); let metac1 = meta.clone(); let endpoint = args.endpoint.clone(); let message_queue = args.message_queue.clone(); args.idleconns = std::cmp::min(args.idleconns, MAX_IDLE); let m = format!("Endpoint {} is enabled", endpoint); info!("{}", m...
, Ordering}; use std::sync::Arc; use std::{collections::VecDeque, time::Duration}; use tokio::{ sync::Semaphore, time::{delay_for, timeout}, }; use tokio_rustls::TlsConnector; const EBBFLOW_DNS: &str = "s.ebbflow.io"; const EBBFLOW_PORT: u16 = 443; const MAX_IDLE: usize = 1000; pub struct SharedInfo { dns...
random
[ { "content": "pub fn config_reload(\n\n) -> BoxFuture<'static, Result<(Option<EbbflowDaemonConfig>, Option<String>), ConfigError>> {\n\n Box::pin(async {\n\n debug!(\"Will read config file, {}\", config_file_full());\n\n let cfg = match EbbflowDaemonConfig::load_from_file().await {\n\n ...
Rust
vendor/tracing/src/level_filters.rs
mcheshkov/icfpc2020
337a94d648e517a0358ffdb86fe0d468a7462939
use crate::stdlib::cmp::Ordering; use tracing_core::Level; #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] pub struct LevelFilter(Option<Level>); impl From<Level> for LevelFilter { #[inline] fn from(level: Level) -> Self { Self::from_level(level) } } impl LevelFilter { ...
use crate::stdlib::cmp::Ordering; use tracing_core::Level; #[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] pub struct LevelFilter(Option<Level>); impl From<Level> for LevelFilter { #[inline] fn from(level: Level) -> Self { Self::from_level(level) } } impl LevelFilter { ...
for (filter, level) in mapping.iter() { assert_eq!(filter.clone().into_level(), *level); if let Some(level) = level { assert_eq!(LevelFilter::from_level(level.clone()), *filter); } } } }
let mapping = [ (LevelFilter::OFF, None), (LevelFilter::ERROR, Some(Level::ERROR)), (LevelFilter::WARN, Some(Level::WARN)), (LevelFilter::INFO, Some(Level::INFO)), (LevelFilter::DEBUG, Some(Level::DEBUG)), (LevelFilter::TRACE, Some(Level::TRACE)), ...
assignment_statement
[ { "content": "fn eq(x: i64) -> impl Fn(i64) -> dyn Fn(i64) {\n\n return move |y| if x == y {t} else {f};\n\n}\n\n*/\n\n\n\n\n", "file_path": "app/fn_rust.rs", "rank": 0, "score": 131889.53669779957 }, { "content": "fn replace_matching<F: FnMut(&Action) -> bool>(\n\n bindings: Bindings,...
Rust
escrow/src/contract.rs
webmaster128/cosmwasm-examples
12bae859ef32bfab28dfbb7432a11e80fd82db49
use serde::{Deserialize, Serialize}; use snafu::{OptionExt, ResultExt}; use cosmwasm::errors::{ContractErr, ParseErr, Result, SerializeErr, Unauthorized}; use cosmwasm::serde::{from_slice, to_vec}; use cosmwasm::storage::Storage; use cosmwasm::types::{Coin, CosmosMsg, Params, Response}; #[derive(Serialize, Deserializ...
use serde::{Deserialize, Serialize}; use snafu::{OptionExt, ResultExt}; use cosmwasm::errors::{ContractErr, ParseErr, Result, SerializeErr, Unauthorized}; use cosmwasm::serde::{from_slice, to_vec}; use cosmwasm::storage::Storage; use cosmwasm::types::{Coin, CosmosMsg, Params, Response}; #[derive(Serialize, Deserializ...
es = init(&mut store, params, msg).unwrap(); assert_eq!(0, res.messages.len()); let data = store.get(CONFIG_KEY).expect("no data stored"); let state: State = from_slice(&data).unwrap(); assert_eq!(state.arbiter, String::from("verifies")); assert_eq!(state.recipient, Str...
ckStorage::new(); let msg = init_msg(1000, 0); let params = mock_params_height("creator", &coin("1000", "earth"), &[], 876, 0); let r
function_block-random_span
[ { "content": "fn init_msg(height: i64, time: i64) -> Vec<u8> {\n\n to_vec(&InitMsg {\n\n arbiter: String::from(\"verifies\"),\n\n recipient: String::from(\"benefits\"),\n\n end_height: height,\n\n end_time: time,\n\n })\n\n .unwrap()\n\n}\n\n\n", "file_path": "escrow/tes...
Rust
actix-web-httpauth/src/extractors/bearer.rs
gabucito/actix-extras
aa6e6910095b783d4d635664f496360b223ffce1
use std::borrow::Cow; use std::default::Default; use actix_web::dev::{Payload, ServiceRequest}; use actix_web::http::header::Header; use actix_web::{FromRequest, HttpRequest}; use futures_util::future::{ready, Ready}; use super::config::AuthExtractorConfig; use super::errors::AuthenticationError; use super::AuthExt...
use std::borrow::Cow; use std::default::Default; use actix_web::dev::{Payload, ServiceRequest}; use actix_web::http::header::Header; use actix_web::{FromRequest, HttpRequest}; use futures_util::future::{ready, Ready}; use super::config::AuthExtractorConfig; use super::errors::AuthenticationError; use super::AuthExt...
onfig>() .map(|config| config.0.clone()) .unwrap_or_else(Default::default); AuthenticationError::new(bearer) }), ) } } impl AuthenticationError<bearer::Bearer> { pub fn with_error(mut self, kind: Er...
dy<Result<Self, Self::Error>>; type Error = AuthenticationError<bearer::Bearer>; fn from_service_request(req: &ServiceRequest) -> Self::Future { ready( authorization::Authorization::<authorization::Bearer>::parse(req) .map(|auth| BearerAuth(auth.into_scheme())) ...
random
[ { "content": "/// Tries to quote the quotes in the passed `value`\n\npub fn put_quoted(buf: &mut BytesMut, value: &str) {\n\n for part in Quoted::new(value) {\n\n buf.extend_from_slice(part.as_bytes());\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::str;\n\n\n\n use actix_web::web...
Rust
src/union.rs
achreto/cgen-rs
cb11f7e85f98c1093f86bc722859a83006324107
use std::fmt::{self, Display, Write}; use crate::{Doc, Field, Formatter, Type}; #[derive(Debug, Clone)] pub struct Union { name: String, fields: Vec<Field>, doc: Option<Doc>, attributes: Vec<String>, } impl Union { pub fn new(name: &str) -> Self { Union::with...
use std::fmt::{self, Display, Write}; use crate::{Doc, Field, Formatter, Type}; #[derive(Debug, Clone)] pub struct Union { name: String, fields: Vec<Field>, doc: Option<Doc>, attributes: Vec<String>, } impl Union { pub fn new
&mut Self { self.fields.push(item); self } pub fn field_by_name(&self, name: &str) -> Option<&Field> { self.fields.iter().find(|f| f.name() == name) } pub fn field_by_name_mut(&mut self, name: &str) -> Option<&mut Field> { self.fields.iter_mut().find(|f| f.na...
(name: &str) -> Self { Union::with_string(String::from(name)) } pub fn with_string(name: String) -> Self { Self { name, fields: Vec::new(), doc: None, attributes: Vec::new(), } } pub fn with_fields(name: &str, ...
random
[ { "content": "#[test]\n\nfn test_fields_docs() {\n\n let t = Type::new(BaseType::UInt8);\n\n assert_eq!(t.to_string(), \"uint8_t\");\n\n\n\n let mut f = Field::new(\"my_field\", t);\n\n f.push_doc_str(\"my documentation\");\n\n assert_eq!(f.to_string(), \"/// my documentation\\nuint8_t my_field;\...
Rust
src/ocf.rs
arcnmx/encage-runtime
d983e6656d6d4de919f16352c36d6aca30d60f4e
extern crate ocf; use std::borrow::Cow; use std::ffi::CString; use nix; use super::*; impl From<ocf::linux::NamespaceKind> for NamespaceKind { fn from(kind: ocf::linux::NamespaceKind) -> Self { match kind { ocf::linux::NamespaceKind::PID => NamespaceKind::PID, ocf::linux::Namespace...
extern crate ocf; use std::borrow::Cow; use std::ffi::CString; use nix; use super::*; impl From<ocf::linux::NamespaceKind> for NamespaceKind {
} quick_error! { #[derive(Clone, Debug)] pub enum OcfError { UnsupportedPlatform { description("unsupported platform") } UnsupportedArchitecture { description("unsupported architecture") } InvalidConfiguration(err: &'static str) { des...
fn from(kind: ocf::linux::NamespaceKind) -> Self { match kind { ocf::linux::NamespaceKind::PID => NamespaceKind::PID, ocf::linux::NamespaceKind::Network => NamespaceKind::Network, ocf::linux::NamespaceKind::Mount => NamespaceKind::Mount, ocf::linux::NamespaceKind:...
function_block-full_function
[ { "content": "fn capbset_drop(cap: usize) -> nix::Result<()> {\n\n extern {\n\n fn prctl(opt: c_int, arg2: c_ulong, arg3: c_ulong, arg4: c_ulong, arg5: c_ulong) -> c_int;\n\n }\n\n\n\n const PR_CAPBSET_DROP: c_int = 24;\n\n\n\n let res = unsafe {\n\n prctl(PR_CAPBSET_DROP, cap as c_ulo...
Rust
paddlers-frontend/src/game/map/map_tesselation.rs
jakmeier/paddlers-browser-game
6c7afbb1ac13467ed94c418a5515fcf98224149e
use crate::game::map::map_segment::MapSegment; use crate::gui::utils::*; use ::lyon::{math::point, path::Path, tessellation::*}; use paddle::*; use paddlers_shared_lib::game_mechanics::map::MAP_H; impl MapSegment { pub fn tesselate_rivers(&mut self) { self.water_mesh.clear(); let area = Re...
use crate::game::map::map_segment::MapSegment; use crate::gui::utils::*; use ::lyon::{math::point, path::Path, tessellation::*}; use paddle::*; use paddlers_shared_lib::game_mechanics::map::MAP_H; impl MapSegment { pub fn tesselate_rivers(&mut self) { self.water_mesh.clear(); let area = Re...
fn stream_path(points: &[Vector]) -> Path { let mut builder = Path::builder(); let p0 = points[0]; builder.begin(point(p0.x, p0.y)); for slice in points[1..].windows(2) { match slice { &[p, q] => { let r = (p + q) / 2.0; builder.quadratic_bezier_to(p...
0)); builder.quadratic_bezier_to(point(x + 3.0 * dx, y0 - dy), point(x + 4.0 * dx, y0)); } builder.end(false); builder.build() }
function_block-function_prefixed
[]
Rust
src/main.rs
zmedico/socket-burst-dampener-rust
a4c2a74f4e16702e831a4c086604e016a9a115cc
use async_std::sync::{channel, Sender, Receiver}; use tokio::spawn; use tokio::net::TcpListener; static LOGGER: BasicLogger = BasicLogger; struct BasicLogger; impl log::Log for BasicLogger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::max_level() } fn log(&self...
use async_std::sync::{channel, Sender, Receiver}; use tokio::spawn; use tokio::net::TcpListener; static LOGGER: BasicLogger = BasicLogger; struct BasicLogger; impl log::Log for BasicLogger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::max_level() } fn log(&self...
; ! contents.find("0").is_some() } #[tokio::main(basic_scheduler)] async fn main() -> Result<(), ErrorType> { use clap::value_t; let matches = parse_args(); let verbosity = matches.occurrences_of("v"); log::set_logger(&LOGGER).unwrap(); if verbosity > 0 { if verbosity >= 2 { ...
match std::fs::read_to_string("/proc/sys/net/ipv6/bindv6only") { Ok(contents) => contents, Err(_) => return true, }
if_condition
[ { "content": "# socket-burst-dampener\n\n\n\nA daemon that spawns a specified command to handle each connection, and\n\ndampens connection bursts.\n\n\n\n## Motivation\n\nIt is typical to configure a forking daemon such as rsync so that it\n\nwill respond with an error when a maximum number of concurrent\n\ncon...
Rust
tests/test_similarity.rs
lambdaxymox/cglinalg
33a50331f22fc234366b65c962c74a89aca84706
extern crate cglinalg; #[cfg(test)] mod similarity2_tests { use cglinalg::{ Similarity2, Isometry2, Rotation2, Translation2, Vector2, Point2, Degrees, Radians, Matrix3x3, Angle, }; use approx::{ relative_eq, }; ...
extern crate cglinalg; #[cfg(test)] mod similarity2_tests { use cglinalg::{ Similarity2, Isometry2, Rotation2, Translation2, Vector2, Point2, Degrees, Radians, Matrix3x3, Angle, }; use approx::{ relative_eq, }; ...
let point = Point3::new(1_f64, 2_f64, 3_f64); let expected = point; let transformed_point = similarity.transform_point(&point); let result = similarity.inverse_transform_point(&transformed_point); assert!(relative_eq!(result, expected, epsilon = 1e-8)); } #[test] fn tes...
ted); } #[test] fn test_from_translation() { let distance = Vector3::new(5_f64, 5_f64, 5_f64); let translation = Translation3::from_vector(&distance); let similarity = Similarity3::from_translation(&translation); let point = Point3::new(1_f64, 2_f64, 3_f64); ass...
random
[ { "content": "#[test]\n\nfn test_vector3_unit_vectors() {\n\n let unit_x: Vector3<f64> = Vector3::unit_x();\n\n let unit_y: Vector3<f64> = Vector3::unit_y();\n\n let unit_z: Vector3<f64> = Vector3::unit_z();\n\n\n\n let (unit_unit_x, norm_unit_x) = Unit::from_value_with_magnitude(unit_x); \n\n le...
Rust
src/consumer/builder.rs
estk/kafka-rust
88ca68df1f0e31627f9d676fa444bd23d3e51bf9
use crate::client::GroupOffsetStorage; use std::collections::HashMap; use std::time::Duration; use crate::client::{self, FetchOffset, KafkaClient, SecurityConfig}; use crate::error::{ErrorKind, Result}; use super::assignment; use super::config::Config; use super::state::State; use super::{Consumer, DEFAULT_FALLBACK_O...
use crate::client::GroupOffsetStorage; use std::collections::HashMap; use std::time::Duration; use crate::client::{self, FetchOffset, KafkaClient, SecurityConfig}; use crate::error::{ErrorKind, Result}; use super::assignment; use super::config::Config; use super::state::State; use super::{Consumer, DEFAULT_FALLBACK_O...
b } impl Builder { pub fn with_group(mut self, group: String) -> Builder { self.group = group; self } pub fn with_topic(mut self, topic: String) -> Builder { self.assignments.insert(topic, Vec::new()); ...
if let Some(ref c) = b.client { b.fetch_max_wait_time = c.fetch_max_wait_time(); b.fetch_min_bytes = c.fetch_min_bytes(); b.fetch_max_bytes_per_partition = c.fetch_max_bytes_per_partition(); b.fetch_crc_validation = c.fetch_crc_validation(); b.group_offset_storage = c.group_offse...
if_condition
[ { "content": "/// Safely converts a Duration into the number of milliseconds as a\n\n/// i32 as often required in the kafka protocol.\n\npub fn to_millis_i32(d: Duration) -> Result<i32> {\n\n use std::i32;\n\n let m = d\n\n .as_secs()\n\n .saturating_mul(1_000)\n\n .saturating_add(u64...
Rust
kravl-parser/src/syntax/ast.rs
nilq/aywa
ac2222d3e1c8f1177aa93019d780d3823eab83fb
use syntax::tokens::{ TokenType, Token, BinOp, }; use syntax::lexer::Lexer; #[derive(Debug, Clone)] pub enum Statement { If(Box<Expression>, Box<Statement>), IfElse(Box<Expression>, Box<Statement>, Box<Statement>), Variable(String, Box<Expression>), Block(Box<Vec<Statement>>), Expressi...
use syntax::tokens::{ TokenType, Token, BinOp, }; use syntax::lexer::Lexer; #[derive(Debug, Clone)] pub enum Statement { If(Box<Expression>, Box<Statement>), IfElse(Box<Expression>, Box<Statement>, Box<Statement>), Variable(String, Box<Expression>), Block(Box<Vec<Statement>>), Expressi...
if opened_dos == 0 { break } block_tokens.push(self.lexer.current_token().clone()); } try!(self.lexer.match_current_token(TokenType::End)); Parser::parse_from_tokens(block_tokens) } fn parse_expression(&mut self) -> Result<Express...
if self.lexer.current_token().token_type == TokenType::Do { opened_dos += 1; } else if self.lexer.current_token().token_type == TokenType::End { opened_dos -= 1; }
if_condition
[ { "content": " Lt,\n\n Gt,\n\n LtEqual,\n\n GtEqual,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Token {\n\n pub token_type: TokenType,\n\n pub content: String,\n\n pub row: u32,\n\n pub col: u32,\n\n}\n\n\n\nimpl Token {\n\n pub fn new(token_type: TokenType, co...
Rust
r1cs-std/src/lib.rs
weikengchen/zexe-with-to-constraint-field
8a768874dc9457ce2214670471284f84b2c063f0
#![cfg_attr(not(feature = "std"), no_std)] #![deny(unused_import_braces, unused_qualifications, trivial_casts)] #![deny(trivial_numeric_casts, variant_size_differences, unreachable_pub)] #![deny(non_shorthand_field_patterns, unused_attributes, unused_imports)] #![deny(unused_extern_crates, renamed_and_removed_lints, un...
#![cfg_attr(not(feature = "std"), no_std)] #![deny(unused_import_braces, unused_qualifications, trivial_casts)] #![deny(trivial_numeric_casts, variant_size_differences, unreachable_pub)] #![deny(non_shorthand_field_patterns, unused_attributes, unused_imports)] #![deny(unused_extern_crates, renamed_and_removed_lints, un...
> { fn get(self) -> Result<T, r1cs_core::SynthesisError>; } impl<T> Assignment<T> for Option<T> { fn get(self) -> Result<T, r1cs_core::SynthesisError> { self.ok_or(r1cs_core::SynthesisError::AssignmentMissing) } } pub trait ToConstraintFieldGadget<ConstraintF: algebra::PrimeField> { fn to_cons...
map_or(true, |cs| cs == r1cs_core::ConstraintSystemRef::None) } fn value(&self) -> Result<Self::Value, r1cs_core::SynthesisError>; } impl<F: Field, T: R1CSVar<F>> R1CSVar<F> for [T] { type Value = Vec<T::Value>; fn cs(&self) -> Option<r1cs_core::ConstraintSystemRef<F>> { let mut res...
random
[ { "content": "pub trait ToBitsGadget<F: Field> {\n\n /// Outputs the canonical little-endian bit-wise representation of `self`.\n\n ///\n\n /// This is the correct default for 99% of use cases.\n\n fn to_bits_le(&self) -> Result<Vec<Boolean<F>>, SynthesisError>;\n\n\n\n /// Outputs a possibly non...
Rust
library/core/src/iter/adapters/chain.rs
anirudhb/rust
178108bf81606a0e25b1066568c2b8c8e0648617
use crate::iter::{DoubleEndedIterator, FusedIterator, Iterator, TrustedLen}; use crate::ops::Try; #[derive(Clone, Debug)] #[must_use = "iterators are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] pub struct Chain<A, B> { a: Option<A>, ...
use crate::iter::{DoubleEndedIterator, FusedIterator, Iterator, TrustedLen}; use crate::ops::Try; #[derive(Clone, Debug)] #[must_use = "iterators are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] pub struct Chain<A, B> { a: Option<A>, ...
dIterator<Item = A::Item>, { } #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl<A, B> TrustedLen for Chain<A, B> where A: TrustedLen, B: TrustedLen<Item = A::Item>, { }
let a_count = match self.a { Some(a) => a.count(), None => 0, }; let b_count = match self.b { Some(b) => b.count(), None => 0, }; a_count + b_count } fn try_fold<Acc, F, R>(&mut self, mut acc: Acc, mut f: F) -> R where...
random
[]
Rust
test-server/src/lib.rs
jesskfullwood/actix-web
c96068e78df609bc1bc01a41caae1237ed5e0d54
use std::cell::RefCell; use std::sync::mpsc; use std::{net, thread, time}; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_rt::{Runtime, System}; use actix_server::{Server, StreamServiceFactory}; use awc::{error::PayloadError, ws, Client, ClientRequest, ClientResponse, Connector}; use bytes::Bytes; use fu...
use std::cell::RefCell; use std::sync::mpsc; use std::{net, thread, time}; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_rt::{Runtime, System}; use actix_server::{Server, StreamServiceFactory}; use awc::{error::PayloadError, ws, Client, ClientRequest, ClientResponse, Connector}; use bytes::Bytes; use fu...
) .unwrap(); System::set_current(system); TestServerRuntime { addr, rt, client } } pub fn unused_addr() -> net::SocketAddr { let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap(); let socket = TcpBuilder::new_v4().unwrap(); socket.bind(&addr).unwrap...
lazy(move || { let connector = { #[cfg(feature = "ssl")] { use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode}; let mut builder = SslConnector::builder(SslMethod::tls()).unwrap(); ...
call_expression
[ { "content": "/// Runs the provided function, with runtime enabled.\n\n///\n\n/// Note that this function is intended to be used only for testing purpose.\n\n/// This function panics on nested call.\n\npub fn run_on<F, R>(f: F) -> R\n\nwhere\n\n F: FnOnce() -> R,\n\n{\n\n RT.with(move |rt| {\n\n rt...
Rust
src/split_reader.rs
Logicalshift/rust-ndfa
0d3ec62ed6ed4141db501e70239eff40ab3a0665
use std::cell::*; use std::rc::*; use std::collections::*; use super::symbol_reader::*; pub struct SplitSymbolReader<'a, Symbol: Clone+'a> { buffer: Rc<RefCell<SplitSymbolReaderBuffer<'a, Symbol>>>, reader_id: usize } struct SplitSymbolReaderBuffer<'a, Symbol: 'a> { symbol_reader: &'a m...
use std::cell::*; use std::rc::*; use std::collections::*; use super::symbol_reader::*; pub struct SplitSymbolReader<'a, Symbol: Clone+'a> { buffer: Rc<RefCell<SplitSymbolReaderBuffer<'a, Symbol>>>, reader_id: usize } struct SplitSymbolReaderBuffer<'a, Symbol: 'a> { symbol_reader: &'a m...
am.split(); assert!(first.next_symbol() == Some(1)); assert!(second.next_symbol() == Some(1)); assert!(first.next_symbol() == Some(2)); assert!(second.next_symbol() == Some(2)); assert!(first.next_symbol() == Some(3)); assert!(second.next_symbol() == Some(3)); as...
nterleaved() { let source = vec![1,2,3]; let mut stream = source.read_symbols(); let (mut first, mut second) = stre
function_block-random_span
[ { "content": "///\n\n/// A symbol reader reads one symbol at a time from a source\n\n///\n\npub trait SymbolReader<Symbol> {\n\n ///\n\n /// Reads the next symbol from this reader\n\n ///\n\n fn next_symbol(&mut self) -> Option<Symbol>;\n\n}\n\n\n", "file_path": "src/symbol_reader.rs", "rank...
Rust
tests/common/mod.rs
pyohannes/newrelic-telemetry-sdk-rust
54a31820c7ed9f85f25a5b4a083848c3497f5e70
use flate2::read::GzDecoder; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Server}; use rand::seq::SliceRandom; use rand::thread_rng; use std::collections::HashMap; use std::io::Read; use std::net::{SocketAddr, TcpListener}; use std::str; use std::sync::{Arc, Mutex}; use std::thread; u...
use flate2::read::GzDecoder; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Request, Server}; use rand::seq::SliceRandom; use rand::thread_rng; use std::collections::HashMap; use std::io::Read; use std::net::{SocketAddr, TcpListener}; use std::str; use std::sync::{Arc, Mutex}; use std::thread; u...
urn Err(Error::new("Timeout: no request received")); } } } pub fn next_payload(&mut self) -> Result<Payload, Error> { let mut lock = self.chan_payloads.lock().unwrap(); match lock.pop() { Some(p) => Ok(p), None => Err(Error::new("No payload received"...
temTime::now(); loop { let lock = self.chan_responses.lock().unwrap(); if lock.len() < len { return Ok(()); } let duration = SystemTime::now().duration_since(start).unwrap(); if duration.as_millis() > self.timeout_ms { ...
random
[ { "content": "#[derive(Debug)]\n\nstruct Endpoint {\n\n // The host name or address of the endpoint.\n\n host: String,\n\n\n\n // The port of the endpoint. This is optional, if not given it will default\n\n // to the standard HTTPS port.\n\n port: Option<u16>,\n\n\n\n // The path for the endpo...
Rust
src/primitives/mesh.rs
DarkAce65/raytracer
0d06ccc21306c0d5a8d63d5d51df70b9d23844e0
use super::{Object3D, RaytracingObject, Triangle}; use crate::core::{Material, Transform}; use nalgebra::{Point3, Unit, Vector2, Vector3}; use num_traits::identities::Zero; use serde::Deserialize; use std::path::Path; use tobj::{load_obj, LoadOptions}; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub st...
use super::{Object3D, RaytracingObject, Triangle}; use crate::core::{Material, Transform}; use nalgebra::{Point3, Unit, Vector2, Vector3}; use num_traits::identities::Zero; use serde::Deserialize; use std::path::Path; use tobj::{load_obj, LoadOptions}; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub st...
pub fn load_assets(&mut self, asset_base: &Path) { let (models, _) = load_obj( &asset_base.join(&self.file), &LoadOptions { triangulate: true, single_index: true, ignore_lines: true, ignore_points: true,...
let mut objects: Vec<Box<dyn RaytracingObject>> = Vec::new(); if let Some(children) = self.children { for child in children { let child_objects: Vec<Box<dyn RaytracingObject>> = child.flatten_to_world(&transform); objects.extend(child_objects); ...
function_block-function_prefix_line
[ { "content": "// Sample a hemisphere with a cosine weight in the direction of the given direction using Malley's method\n\npub fn cosine_sample_hemisphere(direction: &Unit<Vector3<f64>>) -> Unit<Vector3<f64>> {\n\n let p = concentric_sample_disk();\n\n let p = Point3::from([p.x, p.y, (1.0 - p.x * p.x - p....
Rust
opentelemetry/src/api/trace/span_context.rs
willroberts/opentelemetry-rust
5192fba4a978be48b56708eed991babe4e0d8186
#[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use std::collections::VecDeque; use std::str::FromStr; pub const TRACE_FLAG_NOT_SAMPLED: u8 = 0x00; pub const TRACE_FLAG_SAMPLED: u8 = 0x01; pub const TRACE_FLAG_DEFERRED: u8 = 0x02; pub const TRACE_FLAG_DEBUG: u8 = 0x04; lazy_static::lazy_static...
#[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use std::collections::VecDeque; use std::str::FromStr; pub const TRACE_FLAG_NOT_SAMPLED: u8 = 0x00; pub const TRACE_FLAG_SAMPLED: u8 = 0x01; pub const TRACE_FLAG_DEFERRED: u8 = 0x02; pub const TRACE_FLAG_DEBUG: u8 = 0x04; lazy_static::lazy_static...
to_hex(), test_case.1); assert_eq!(test_case.0.to_byte_array(), test_case.2); assert_eq!(test_case.0, SpanId::from_hex(test_case.1)); assert_eq!(test_case.0, SpanId::from_byte_array(test_case.2)); } } #[test] fn test_trace_state() { for test_case in trac...
for test_case in trace_id_test_data() { assert_eq!(test_case.0.to_hex(), test_case.1); assert_eq!(test_case.0.to_byte_array(), test_case.2); assert_eq!(test_case.0, TraceId::from_hex(test_case.1)); assert_eq!(test_case.0, TraceId::from_byte_array(test_case.2)); ...
random
[ { "content": "fn compare_export(exporter: &PrometheusExporter, mut expected: Vec<&'static str>) {\n\n let mut output = Vec::new();\n\n let encoder = TextEncoder::new();\n\n let metric_families = exporter.registry().gather();\n\n encoder.encode(&metric_families, &mut output).unwrap();\n\n let outp...
Rust
src/widgets.rs
foldu/iv2
160735ee4c3f8fecb0e7f47ef7feed460db008aa
use std::convert::TryFrom; use cascade::cascade; use euclid::{vec2, Vector2D}; use gtk::prelude::*; use crate::{events::UserEvent, math::Pixels}; pub struct Main { vbox: gtk::Box, bottom_bar: BottomBar, pub image: ScrollableImage, } impl AsRef<gtk::Box> for Main { fn as_ref(&self) -> &gtk::Box { ...
use std::convert::TryFrom; use cascade::cascade; use euclid::{vec2, Vector2D}; use gtk::prelude::*; use crate::{events::UserEvent, math::Pixels}; pub struct Main { vbox: gtk::Box, bottom_bar: BottomBar, pub image: ScrollableImage, } impl AsRef<gtk::Box> for Main { fn as_ref(&self) -> &gtk::Box { ...
pub fn set_image(&self, img: Option<&gdk_pixbuf::Pixbuf>) { self.image.image.set_from_pixbuf(img); } pub fn image_allocation(&self) -> Vector2D<i32, Pixels> { let alloc = self.image.scroll.get_allocation(); vec2(alloc.width, alloc.height) } pub fn scroll(&self, scroll: Sc...
pack_start(image.as_ref(), true, true, 0); ..add(bottom_bar.as_ref()); }; Self { image, bottom_bar, vbox, } }
function_block-function_prefix_line
[ { "content": "#[derive(Snafu, Debug)]\n\nenum Error {\n\n #[snafu(display(\"Can't init gtk\"))]\n\n InitGtk,\n\n\n\n #[snafu(display(\"Can't read config: {}\", source))]\n\n ReadConfig { source: cfgen::Error },\n\n\n\n #[snafu(display(\"Bad status_format in config: {}\", source))]\n\n Format {...
Rust
pcid/src/pci/cap.rs
redox-os/drivers
36b3af426260cb1bd740426f5fb8a07a5f37e4c5
use super::func::ConfigReader; use serde::{Serialize, Deserialize}; pub struct CapabilityOffsetsIter<'a, R> { offset: u8, reader: &'a R, } impl<'a, R> CapabilityOffsetsIter<'a, R> { pub fn new(offset: u8, reader: &'a R) -> Self { Self { offset, reader, } } } impl...
use super::func::ConfigReader; use serde::{Serialize, Deserialize}; pub struct CapabilityOffsetsIter<'a, R> { offset: u8, reader: &'a R, } impl<'a, R> CapabilityOffsetsIter<'a, R> { pub fn new(offset: u8, reader: &'a R) -> Self { Self { offset, reader, } } } impl...
} } pub struct CapabilitiesIter<'a, R> { pub inner: CapabilityOffsetsIter<'a, R>, } impl<'a, R> Iterator for CapabilitiesIter<'a, R> where R: ConfigReader { type Item = (u8, Capability); fn next(&mut self) -> Option<Self::Item> { let offset = self.inner.next()?; Some((offset, uns...
if capability_id == CapabilityId::MsiX as u8 { Self::parse_msix(reader, offset) } else if capability_id == CapabilityId::Pcie as u8 { Self::parse_pcie(reader, offset) } else if capability_id == CapabilityId::PwrMgmt as u8{ Self::parse_pwr(reader, offset) } els...
if_condition
[ { "content": "pub fn read<E>(offset: u64, blksize: u32, mut buf: &mut [u8], block_bytes: &mut [u8], mut read: impl FnMut(u64, &mut [u8]) -> Result<(), E>) -> Result<usize, E> {\n\n // TODO: Yield sometimes, perhaps after a few blocks or something.\n\n use std::ops::{Add, Div, Rem};\n\n\n\n fn div_round...
Rust
tests/web.rs
kije/three-d-gltf-import
093e284ca49860cee9584d889cb84b0806eeda83
#![cfg(target_arch = "wasm32")] extern crate wasm_bindgen_test; use gltf::Gltf; use js_sys::{Function, Object}; use std::path::PathBuf; use three_d::Loader; use three_d_gltf_import::import::{GltfImporter, ImportedGltfModel}; use wasm_bindgen::JsValue; use wasm_bindgen_futures::JsFuture; use wasm_bindgen_test::*; wa...
#![cfg(target_arch = "wasm32")] extern crate wasm_bindgen_test; use gltf::Gltf; use js_sys::{Function, Object}; use std::path::PathBuf; use three_d::Loader; use three_d_gltf_import::import::{GltfImporter, ImportedGltfModel}; use wasm_bindgen::JsValue; use wasm_bindgen_futures::JsFuture; use wasm_bindgen_test::*; wa...
} #[wasm_bindgen_test] async fn test_import_triangle_model() { let promise = js_sys::Promise::new(&mut |resolve: Function, reject: Function| { let base = PathBuf::from(format!("{}/{}", "..", "sample_models/2.0/Triangle/glTF")); Loader::load(&[base.join("Triangle.gltf")], move |loaded| { ...
if imported.images().len() != expected_images { reject.call1( &JsValue::from_str(&format!( "Expected number of images to be {:?}, found {:?}", expected_images, imported.images().len(), )), &Object::new(), ); } else {...
if_condition
[ { "content": "enum BufferImport {\n\n Loaded {\n\n index: usize,\n\n data: Vec<u8>,\n\n length: usize,\n\n },\n\n NeedsLoading {\n\n index: usize,\n\n path: PathBuf,\n\n length: usize,\n\n },\n\n}\n\n\n\nimpl GltfImporter {\n\n /// Imports a provided gltf...
Rust
src/qspi/addrconf.rs
kaspar030/nrf52840-pac
9be467d088fd4b41e4a2e952ac62dd25eb50d542
#[doc = "Reader of register ADDRCONF"] pub type R = crate::R<u32, super::ADDRCONF>; #[doc = "Writer for register ADDRCONF"] pub type W = crate::W<u32, super::ADDRCONF>; #[doc = "Register ADDRCONF `reset()`'s with value 0xb7"] impl crate::ResetValue for super::ADDRCONF { type Type = u32; #[inline(always)] fn...
#[doc = "Reader of register ADDRCONF"] pub type R = crate::R<u32, super::ADDRCONF>; #[doc = "Writer for register ADDRCONF"] pub type W = crate::W<u32, super::ADDRCONF>; #[doc = "Register ADDRCONF `reset()`'s with value 0xb7"] impl crate::ResetValue for super::ADDRCONF { type Type = u32; #[inline(always)] fn...
#[doc = "Checks if the value of the field is `NOINSTR`"] #[inline(always)] pub fn is_no_instr(&self) -> bool { *self == MODE_A::NOINSTR } #[doc = "Checks if the value of the field is `OPCODE`"] #[inline(always)] pub fn is_opcode(&self) -> bool { *self == MODE_A::OPCODE }...
pub fn variant(&self) -> MODE_A { match self.bits { 0 => MODE_A::NOINSTR, 1 => MODE_A::OPCODE, 2 => MODE_A::OPBYTE0, 3 => MODE_A::ALL, _ => unreachable!(), } }
function_block-full_function
[ { "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
conduit/src/conduit.rs
alexmccord/luau-explorer
36669b02312e7c694c8e3377306895c9786f7779
use std::io::Write; use std::process::{Child, Command, Stdio}; pub enum ConduitRequest { VM { code: String }, Lint { code: String }, Check { code: String }, Json { code: String }, Hydrate { code: String }, } impl ConduitRequest { fn discriminant(&se...
use std::io::Write; use std::process::{Child, Command, Stdio}; pub enum ConduitRequest { VM { code: String }, Lint { code: String }, Check { code: String }, Json { code: String }, Hydrate { code: String }, } impl ConduitRequest { fn discriminant(&se...
{ code } => { bytestr.extend(format!("{:0>10}", code.len() as i32).as_bytes()); bytestr.extend(code.as_bytes()); } ConduitRequest::Hydrate { code } => { bytestr.extend(format!("{:0>10}", code.len() as i32).as_bytes()); bytestr.exte...
onduitRequest::Hydrate { .. } => 5, } } fn into_bytes(self) -> Vec<u8> { self.into() } } impl Into<Vec<u8>> for ConduitRequest { fn into(self) -> Vec<u8> { let mut bytestr = Vec::new(); bytestr.push(self.discriminant()); match self { ...
random
[ { "content": "#[test]\n\nfn encode_some_code() {\n\n let request = ConduitRequest::Json {\n\n code: \"local x: string = 5\".into(),\n\n };\n\n\n\n let result = Conduit::dispatch(request).unwrap();\n\n\n\n assert_eq!(\n\n result,\n\n Output {\n\n status: Some(0),\n\n ...
Rust
core/src/pcap.rs
qiujiangkun/capsule
aeab9eb3f5ae309491587529f4fe42cef6437e88
/* * Copyright 2019 Comcast Cable Communications Management, LLC * * 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 applicab...
/* * Copyright 2019 Comcast Cable Communications Management, LLC * * 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 applicab...
raw_parts_mut(pkts, num_pkts as usize), ); num_pkts } unsafe extern "C" fn append_and_write_tx( _port_id: u16, _queue_id: u16, pkts: *mut *mut ffi::rte_mbuf, num_pkts: u16, user_param: *mut raw::c_void, ) -> u16 { append_and_write( (user_param as *const raw::c_char).as_str(), ...
pkts: *mut *mut ffi::rte_mbuf, num_pkts: u16, _max_pkts: u16, user_param: *mut raw::c_void, ) -> u16 { append_and_write( (user_param as *const raw::c_char).as_str(), "rx", std::slice::from_
random
[ { "content": "/// Initializes the Environment Abstraction Layer (EAL).\n\npub fn eal_init(args: Vec<String>) -> Result<()> {\n\n debug!(arguments=?args);\n\n\n\n let len = args.len() as raw::c_int;\n\n let args = args\n\n .into_iter()\n\n .map(|s| s.into_cstring())\n\n .collect::<V...
Rust
client/io_engine/src/disk_cache_store.rs
ydh12356890/yigfs
46b9d03675fea59c97094803850bb63c054caf12
use crate::{cache_store::CacheStatResult, io_thread_pool::IoThreadPool, types::{MsgFileStatOp, MsgFileStatResult}}; use crate::types::{MsgFileOp, MsgFileOpenOp, MsgFileWriteOp, MsgFileReadOp, MsgFileCloseOp, MsgFileOpResp}; use crate::cache_store::{CacheStore, CacheStoreFactory, CacheStoreConfig, CacheWriteResult}; us...
use crate::{cache_store::CacheStatResult, io_thread_pool::IoThreadPool, types::{MsgFileStatOp, MsgFileStatResult}}; use crate::types::{MsgFileOp, MsgFileOpenOp, MsgFileWriteOp, MsgFileReadOp, MsgFileCloseOp, MsgFileOpResp}; use crate::cache_store::{CacheStore, CacheStoreFactory, CacheStoreConfig, CacheWriteResult}; us...
fn close(&self, id0: u64, id1: u64) -> Errno{ let worker = self.disk_pool.get_thread(id0, id1); let msg = MsgFileCloseOp{ id0: id0, id1: id1, name: String::new(), }; let ret = worker.do_io(MsgFileOp::OpClose(msg)); if !ret.is_success(){ ...
size: ret.size, }); } Err(err) => { error!("disk_cache_store::stat failed to receive stat result for seg: id0: {}, id1: {}, err: {}", id0, id1, err); return Err(Errno::Eintr); } } }
function_block-function_prefix_line
[]
Rust
src/llvm-wrap/tests/e2e_main_sum.rs
d3lio/degu-lang
e0273fd33cae9dcc6ef070c7afc922cbab57eb79
use llvm::core::*; use llvm_wrap::execution_engine::initialize_jit; use llvm_wrap::intern::CStringInternPool; use llvm_wrap::llvm_ref::LlvmRef; use llvm_wrap::prelude::{BasicBlock, Context, ExecutionEngine, Function, Module, Type}; fn create_function( pool: &mut CStringInternPool, module: &mut Module, nam...
use llvm::core::*; use llvm_wrap::execution_engine::initialize_jit; use llvm_wrap::intern::CStringInternPool; use llvm_wrap::llvm_ref::LlvmRef; use llvm_wrap::prelude::{BasicBlock, Context, ExecutionEngine, Function, Module, Type}; fn create_function( pool: &mut CStringInternPool, module: &mut Module, nam...
p = builder.build_add(&temp, &params[2], Some(pool.intern("temp"))); builder.build_ret(&temp); sum_three_f }; println!("build main"); { let main_f = create_function( &mut pool, &mut module, "main", context.void_type(), &[]...
function_block-function_prefixed
[ { "content": "pub fn verify_function(f: &Function, action: VerifierFailureAction) -> bool {\n\n unsafe {\n\n LLVMVerifyFunction(f.llvm_ref(), action.to_llvm()) != 0\n\n }\n\n}\n\n\n", "file_path": "src/llvm-wrap/src/analysis.rs", "rank": 1, "score": 114972.88749480859 }, { "cont...
Rust
examples/gameroom/daemon/src/rest_api/routes/notification.rs
vaporos/splinter
934e69a2c41b05e050a7a27d35775ab206f97825
use std::collections::HashMap; use std::time::{Duration, SystemTime}; use actix_web::{error, web, Error, HttpResponse}; use gameroom_database::{helpers, models::GameroomNotification, ConnectionPool}; use crate::rest_api::RestApiResponseError; use super::{ get_response_paging_info, validate_limit, ErrorResponse...
use std::collections::HashMap; use std::time::{Duration, SystemTime}; use actix_web::{error, web, Error, HttpResponse}; use gameroom_database::{helpers, models::GameroomNotification, ConnectionPool}; use crate::rest_api::RestApiResponseError; use super::{ get_response_paging_info, validate_limit, ErrorResponse...
pub async fn list_unread_notifications( pool: web::Data<ConnectionPool>, query: web::Query<HashMap<String, usize>>, ) -> Result<HttpResponse, Error> { let offset: usize = query .get("offset") .map(ToOwned::to_owned) .unwrap_or_else(|| DEFAULT_OFFSET); let limit: usize = query ...
d)? { return Ok(ApiNotification::from(notification)); } Err(RestApiResponseError::NotFound(format!( "Notification with id {} was not found", id ))) }
function_block-function_prefixed
[ { "content": "pub fn get_authorization_token(request: &HttpRequest) -> Result<String, RequestError> {\n\n let auth_header = require_header(\"Authorization\", &request)?;\n\n Ok(auth_header\n\n .split_whitespace()\n\n .last()\n\n .ok_or_else(|| {\n\n RequestError::InvalidHea...
Rust
block-production-albatross/src/lib.rs
terorie/nimiq-core-rs-albatross
56a214cd91d2230bc48693d0777cb5e88dd8a303
extern crate nimiq_block_albatross as block; extern crate nimiq_blockchain_albatross as blockchain; extern crate nimiq_bls as bls; extern crate nimiq_collections as collections; extern crate nimiq_database as database; extern crate nimiq_genesis as genesis; extern crate nimiq_hash as hash; extern crate nimiq_keys as ke...
extern crate nimiq_block_albatross as block; extern crate nimiq_blockchain_albatross as blockchain; extern crate nimiq_bls as bls; extern crate nimiq_collections as collections; extern crate nimiq_database as database; extern crate nimiq_genesis as genesis; extern crate nimiq_hash as hash; extern crate nimiq_keys as ke...
*vec![signed_precommit; TWO_THIRD_SLOTS as usize]), signers, }; let tendermint_proof = TendermintProof { round: 0, sig: multisig }; MacroBlock { header, body, justification: Some(tendermint_proof), } } ...
TendermintIdentifier { block_number: header.block_number, round_number: 0, step: TendermintStep::PreCommit, }, validator_merkle_root, }; let signed_precommit = keypair.secret_key.sign(&precommit); let mut...
function_block-random_span
[ { "content": "pub fn verify_transaction_signature(transaction: &Transaction, validator_key: &BlsPublicKey, signature: &BlsSignature) -> Result<(), TransactionError> {\n\n let key = validator_key.uncompress().map_err(|_| TransactionError::InvalidProof)?;\n\n let sig = signature.uncompress().map_err(|_| Tra...
Rust
demo/billing/src/mz.rs
benLogN/materialize
944d0e7c3b3268c5232d3b060be986cbd09c6afd
use std::path::PathBuf; use std::time::Duration; use anyhow::{bail, Context, Error, Result}; use csv::Writer; use ore::retry; use rand::Rng; use tokio_postgres::Client; use test_util::mz_client; pub async fn create_proto_source( mz_client: &Client, descriptor: &[u8], kafka_url: &impl std::fmt::Display,...
use std::path::PathBuf; use std::time::Duration; use anyhow::{bail, Context, Error, Result}; use csv::Writer; use ore::retry; use rand::Rng; use tokio_postgres::Client; use test_util::mz_client; pub async fn create_proto_source( mz_client: &Client, descriptor: &[u8], kafka_url: &impl std::fmt::Display,...
_agg_by_month.sum as execution_time_ms, billing_agg_by_month.cpu_num, billing_agg_by_month.memory_gb, floor((billing_agg_by_month.sum * ((billing_agg_by_month.cpu_num * billing_prices.price_per_cpu_ms) + (billing_agg_by_month.memory_gb * billing_prices.price_per_gb_ms)))) as monthly_bill FROM billing_ag...
let count_input_view: i64 = mz_client .query_one(&*count_input_view_query, &[]) .await? .get(0); if count_check_sink != count_input_view { bail!( "Expected check_sink view to have {} rows, found {}", count_input_view, ...
random
[ { "content": "fn write_value_ref(schema: &Schema, value: &Value, buffer: &mut Vec<u8>) -> Result<(), Error> {\n\n if !value.validate(schema.top_node()) {\n\n return Err(ValidationError::new(\"value does not match schema\").into());\n\n }\n\n encode_ref(value, schema.top_node(), buffer);\n\n O...
Rust
tensorflow/src/ops/math/max.rs
42bio/tract
4eb64acbf3923bc484c49da4b3b5153ed665e98b
use tract_core::internal::*; use crate::model::ParsingContext; use crate::tfpb::node_def::NodeDef; #[derive(Debug, Clone, new)] pub struct Max { t: DatumType, t_idx: DatumType, keep_dims: bool, } pub fn max(_ctx: &ParsingContext, pb: &NodeDef) -> TractResult<Box<dyn InferenceOp>> { let t = pb.get_att...
use tract_core::internal::*; use crate::model::ParsingContext; use crate::tfpb::node_def::NodeDef; #[derive(Debug, Clone, new)] pub struct Max { t: DatumType, t_idx: DatumType, keep_dims: bool, } pub fn max(_ctx: &ParsingContext, pb: &NodeDef) -> TractResult<Box<dyn InferenceOp>> { let t = pb.get_att...
.rank, &outputs[0].rank, &inputs[1].value, move |s, irank, orank, axes| { let axes: TVec<usize> = axes .cast_to::<i32>()? .as_slice::<i32>()? .iter() .map(|&ax| if ax > 0 { ax } else { ax ...
self.keep_dims { s.equals(&inputs[0].rank, &outputs[0].rank)?; } else { s.equals( inputs[0].rank.bex().to_dim(), inputs[1].shape[0].bex() + outputs[0].rank.bex().to_dim(), )?; } s.given_3( &inputs[0]
function_block-random_span
[ { "content": "pub fn strides(pb: &NodeDef) -> TractResult<Vec<usize>> {\n\n let strides: Vec<usize> = pb.get_attr_list_int(\"strides\")?;\n\n if strides.len() != 4 || strides[0] != 1 && strides[3] != 1 {\n\n Err(format!(\"strides must be of the form [1, h, v, 1], found {:?}\", strides))?\n\n };\...
Rust
src/tree.rs
spielrs/spielrs-diff
37417252603311a4e48c998b70035cb3a056f4bb
use async_trait::async_trait; use futures::StreamExt; use std::iter::FromIterator; use tokio::fs; #[async_trait] pub trait TreeBuilder { async fn build_tree( dir_path: String, excluding: Option<Vec<String>>, recursive_excluding: bool, ) -> Vec<Tree>; fn tree_diff(dir_tree:...
use async_trait::async_trait; use futures::StreamExt; use std::iter::FromIterator; use tokio::fs; #[async_trait] pub trait TreeBuilder { async fn build_tree( dir_path: String, excluding: Option<Vec<String>>, recursive_excluding: bool, ) -> Vec<Tree>; fn tree_diff(dir_tree:...
.await; let content_five = Tree::get_content_files(dir_five).await; assert_eq!(Tree::compare_dir_content(content_one, content_five), false); }
c!["purpose".to_string()]), true, ) .await; let content_five = Tree::get_content_files(dir_five).await; assert_eq!(Tree::compare_dir_content(content_one, content_five), true); } #[tokio::test] async fn should_return_false_if_both_dir_tree_have_different_subdir_excluded_not_recursively() { ...
random
[ { "content": "print(\"This line will be printed.\")", "file_path": "mocks/dir_four/hello.py", "rank": 4, "score": 44084.72107580901 }, { "content": "print(\"This line will be printed.\")", "file_path": "mocks/dir_two/hello.py", "rank": 5, "score": 44084.72107580901 }, { "...
Rust
src/plot/pareto_front.rs
hvy/kurobako
35b24596cea73148a9fa942c283e88238a313ef4
use super::{execute_gnuplot, normalize_filename}; use crate::record::StudyRecord; use indicatif::{ProgressBar, ProgressStyle}; use kurobako_core::{Error, ErrorKind, Result}; use std::collections::BTreeMap; use std::fs; use std::io::Write as _; use std::path::PathBuf; use structopt::StructOpt; use tempfile::{NamedTempF...
use super::{execute_gnuplot, normalize_filename}; use crate::record::StudyRecord; use indicatif::{ProgressBar, ProgressStyle}; use kurobako_core::{Error, ErrorKind, Result}; use std::collections::BTreeMap; use std::fs; use std::io::Write as _; use std::path::PathBuf; use structopt::StructOpt; use tempfile::{NamedTempF...
}
e!()); let budget = end_step as f64 / problem_steps as f64; track_writeln!(temp_file, "{} {} {}", budget, vs[1], vs[0])?; } } } Ok(temp_file.into_temp_path()) }
function_block-function_prefixed
[ { "content": "fn execute_gnuplot(script: &str) -> Result<()> {\n\n let output = track!(Command::new(\"gnuplot\")\n\n .args(&[\"-e\", script])\n\n .output()\n\n .map_err(Error::from))?;\n\n if !output.status.success() {\n\n if let Ok(err) = String::from_utf8(output.stderr) {\n\n...
Rust
src/rule_trainer/mod.rs
barafael/snarky-parrot
42d53c56885923b024402b87183e5c25e7a6b848
use crate::{error::Error, MarkovChainRule}; use std::{ collections::{BTreeMap, HashMap}, iter::once, slice, }; #[cfg(test)] mod test; pub fn generate_rule_from_data_unsafe( content: &str, key_size: usize, ) -> Result<MarkovChainRule, Error> { if key_size < 1 { return Err(Error::Invalid...
use crate::{error::Error, MarkovChainRule}; use std::{ collections::{BTreeMap, HashMap}, iter::once, slice, }; #[cfg(test)] mod test; pub fn generate_rule_from_data_unsafe( content: &str, key_size: usize, ) -> Result<MarkovChainRule, Error> { if key_size < 1 { return Err(Error::Invalid...
pub fn generate_rule_from_data_vec( content: &str, key_size: usize, ) -> Result<HashMap<Vec<&str>, Vec<&str>>, Error> { if key_size < 1 { return Err(Error::InvalidKeySize); } let words: Vec<&str> = content.split_whitespace().collect(); let mut dict: HashMap<Vec<&str>, Vec<&str>> = Ha...
pub fn generate_rule_from_data(content: &str, key_size: usize) -> Result<MarkovChainRule, Error> { if key_size < 1 { return Err(Error::InvalidKeySize); } let space_indices = content .char_indices() .filter_map(|(pos, c)| c.is_whitespace().then(|| pos)) .chain(once(content.le...
function_block-full_function
[ { "content": "pub fn generate_text(rule: &HashMap<Vec<&str>, Vec<&str>>, length: usize) -> String {\n\n if rule.is_empty() {\n\n return String::new();\n\n }\n\n\n\n let mut rng = thread_rng();\n\n\n\n // unwrap: rule is checked for emptiness above.\n\n let start = rule.keys().choose(&mut r...
Rust
src/vendor/toml/src/decoder/mod.rs
utkarshkukreti/rust
0807104c8fa90b084748940f7a7980b5a765264e
use std::error; use std::fmt; use std::collections::{btree_map, BTreeMap}; use std::iter::Peekable; use Value; use self::DecodeErrorKind::*; #[cfg(feature = "rustc-serialize")] mod rustc_serialize; #[cfg(feature = "serde")] mod serde; pub struct Decoder { pub toml: Option<Value>, cur_field: Option<...
use std::error; use std::fmt; use std::collections::{btree_map, BTreeMap}; use std::iter::Peekable; use Value; use self::DecodeErrorKind::*; #[cfg(feature = "rustc-serialize")] mod rustc_serialize; #[cfg(feature = "serde")] mod serde; pub struct Decoder { pub toml: Option<Value>, cur_field: Option<...
fn sub_decoder(&self, toml: Option<Value>, field: &str) -> Decoder { Decoder { toml: toml, cur_field: if field.len() == 0 { self.cur_field.clone() } else { match self.cur_field { None => Some(format!("{}", field)), ...
pub fn new(toml: Value) -> Decoder { Decoder { toml: Some(toml), cur_field: None, leftover_map: BTreeMap::new(), cur_map: BTreeMap::new().into_iter().peekable(), } }
function_block-full_function
[ { "content": "pub fn deprecated_attributes() -> Vec<&'static (&'static str, AttributeType, AttributeGate)> {\n\n BUILTIN_ATTRIBUTES.iter().filter(|a| a.2.is_deprecated()).collect()\n\n}\n\n\n\n// Attributes that have a special meaning to rustc or rustdoc\n\npub const BUILTIN_ATTRIBUTES: &'static [(&'static s...
Rust
DataStructures/expr3/main.rs
duinomaker/LearningStuff
34f8e3338dd2322013d519c19230c12fcb7897d4
use std::collections::{HashMap, HashSet, VecDeque}; enum Graph { AdjacencyList(HashMap<usize, HashSet<usize>>), AdjacencyMatrix(Vec<Vec<bool>>), } #[derive(Eq, Hash, Clone)] struct Edge { beginning: usize, ending: usize, } impl PartialEq for Edge { fn eq(&self, other: &Self) -> bool { sel...
use std::collections::{HashMap, HashSet, VecDeque}; enum Graph { AdjacencyList(HashMap<usize, HashSet<usize>>), AdjacencyMatrix(Vec<Vec<bool>>), } #[derive(Eq, Hash, Clone)] struct Edge { beginning: usize, ending: usize, } impl PartialEq for Edge { fn eq(&self, other: &Self) -> bool { se
d.insert(*v, true); recursion(*v, graph, visited); } } } for v in vertices.iter() { if !visited[v] { visited.insert(*v, true); recursion(*v, graph, &mut visited); } } println!(); } fn shortest_path(attributed_graph: &Attributed...
lf.beginning == other.beginning && self.ending == other.ending } } impl Graph { fn list_new() -> Self { Self::AdjacencyList(Default::default()) } fn matrix_new() -> Self { Self::AdjacencyMatrix(Default::default()) } fn insert_edge(&mut self, edge: &Edge) { ...
random
[ { "content": "fn multiplicative_inverse(n: usize, m: usize) -> usize {\n\n let temp = ext_euclid(n, m).1 % m as isize;\n\n if temp < 0 {\n\n (temp + m as isize) as usize\n\n } else {\n\n temp as usize\n\n }\n\n}\n\n\n", "file_path": "Cryptography/classic.rs", "rank": 4, "sc...
Rust
network/netcore/src/transport/proxy_protocol.rs
BlockSuite/libra
27c125594ee82c8edb361f0c4cf79c9fa101dd68
use diem_types::network_address::NetworkAddress; use futures::io::{AsyncRead, AsyncReadExt}; use std::{ convert::TryInto, io, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, }; const PPV2_SIGNATURE: [u8; 12] = [ 0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A, ]; const PPV2_LOC...
use diem_types::network_address::NetworkAddress; use futures::io::{AsyncRead, AsyncReadExt}; use std::{ convert::TryInto, io, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, }; const PPV2_SIGNATURE: [u8; 12] = [ 0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A, ]; const PPV2_LOC...
R_SIZE).await?; sender.write_all(IPV6_ADDR_1).await?; sender.write_all(IPV6_ADDR_2).await?; sender.write_all(PORT_80).await?; sender.write_all(PORT_80).await?; sender.write_all(TEST_DATA).await } #[test] fn test_ipv4_proxy_protocol() { let (mut sender, ...
RE).await?; sender.write_all(&[PPV2_PROXY]).await?; sender.write_all(&[TCP_IPV6]).await?; sender.write_all(IPV6_ADD
function_block-random_span
[ { "content": "/// parse the `&[Protocol]` into the `\"/memory/<port>\"` prefix and unparsed\n\n/// `&[Protocol]` suffix.\n\npub fn parse_memory(protos: &[Protocol]) -> Option<(u16, &[Protocol])> {\n\n protos\n\n .split_first()\n\n .and_then(|(first, suffix)| match first {\n\n Protoco...
Rust
src/arch/mod.rs
cynecx/libfringe
ee573ffa253d32aae6b1f740e90f4736836a7968
use core::ptr::NonNull; #[cfg_attr(target_arch = "x86_64", path = "x86_64.rs")] mod imp; pub use self::imp::*; #[derive(Debug, Clone, Copy)] #[repr(transparent)] pub struct StackPointer(NonNull<usize>); impl StackPointer { #[inline(always)] pub unsafe fn push(&mut self, val: usize) { self.0 = NonNull::ne...
use core::ptr::NonNull; #[cfg_attr(target_arch = "x86_64", path = "x86_64.rs")] mod imp; pub use self::imp::*; #[derive(Debug, Clone, Copy)] #[repr(transparent)] pub struct StackPointer(NonNull<usize>); impl StackPointer { #[inline(always)] pub unsafe fn push(&mut self, val: usize) { self.0 = NonNull::ne...
} #[test] #[should_panic(expected = "arg=0")] fn panic_after_start() { unsafe { let stack = OsStack::new(4 << 20).unwrap(); let stack_ptr = arch::init(stack.base(), do_panic); arch::swap_link(0, stack_ptr, stack.base()); } } #[test] #[should_panic(expected = "arg=1")] fn pa...
match arg { 0 => panic!("arg=0"), 1 => { arch::swap(0, stack_ptr); panic!("arg=1"); } _ => unreachable!(), }
if_condition
[ { "content": "#[inline]\n\npub fn unwind_arg(_stack_base: *mut u8) -> usize {\n\n unreachable!();\n\n}\n", "file_path": "src/no_unwind.rs", "rank": 0, "score": 143690.26098904252 }, { "content": "#[inline]\n\npub fn unwind_arg(stack_base: *mut u8) -> usize {\n\n let marker = UnwindMarker {...
Rust
src/spi.rs
pineapplehunter/gd32vf103-hal
4362794336e24b0b35177da86fc3c9af85e1763b
use crate::gpio::gpioa::*; use crate::gpio::gpiob::*; use crate::gpio::{Alternate, Floating, Input, Output, PushPull}; use crate::pac::{SPI0, SPI1, SPI2}; use crate::rcu::{Clocks, APB1, APB2}; use crate::unit::Hertz; use embedded_hal::spi::nb::FullDuplex; use embedded_hal::spi::{Mode, Phase, Polarity}; #[derive(Debug...
use crate::gpio::gpioa::*; use crate::gpio::gpiob::*; use crate::gpio::{Alternate, Floating, Input, Output, PushPull}; use crate::pac::{SPI0, SPI1, SPI2}; use crate::rcu::{Clocks, APB1, APB2}; use crate::unit::Hertz; use embedded_hal::spi::nb::FullDuplex; use embedded_hal::spi::{Mode, Phase, Polarity}; #[derive(Debug...
fn read(&mut self) -> nb::Result<u8, Self::Error> { if self.spi.stat.read().rbne().bit_is_clear() { Err(nb::Error::WouldBlock) } else { let rx_byte = self.spi.data.read().spi_data().bits(); Ok...
} Spi { spi, pins } } pub fn free(self) -> ($SPIX, (SCK, MISO, MOSI, NSS)) { (self.spi, self.pins) } } impl<PINS> FullDuplex<u8> for Spi<$SPIX, PINS> { type Error = em...
random
[ { "content": "pub trait Pins {\n\n // private::Sealed; internal use only\n\n #[doc(hidden)]\n\n const REMAP: u8;\n\n\n\n type TX;\n\n\n\n type RX;\n\n\n\n type RTS;\n\n\n\n type CTS;\n\n\n\n type CK;\n\n}\n\n\n\nimpl Pins for USART0 {\n\n const REMAP: u8 = 0;\n\n\n\n type TX = PA9<...
Rust
src/main.rs
nilq/snail
73a83d3ac16c014dfb67665fe7e244d8a61f7cad
extern crate hlua; use hlua::Lua; extern crate rustyline; use rustyline::error::ReadlineError; use std::rc::Rc; use std::io; use std::io::BufRead; mod snail; use snail::*; use std::io::prelude::*; use std::error::Error; use std::fs; use std::fs::File; use std::fs::metadata; use std::env; use std::path::Path; use...
extern crate hlua; use hlua::Lua; extern crate rustyline; use rustyline::error::ReadlineError; use std::rc::Rc; use std::io; use std::io::BufRead; mod snail; use snail::*; use std::io::prelude::*; use std::error::Error; use std::fs; use std::fs::File; use std::fs::metadata; use std::env; use std::path::Path; use...
let symtab = Rc::new(SymTab::new_global()); let typetab = Rc::new(TypeTab::new_global()); add_lua_standard(&symtab, &typetab); match parser.parse() { Err(why) => println!("error: {}", why), Ok(stuff) => { for s in stuff.iter() { ...
} else { println!("{}: can't execute folder", path_str) } } fn file(path: &str) -> Option<Rc<String>> { let path = Path::new(path); let display = path.display(); let mut file = match File::open(&path) { Err(why) => panic!("failed to open {}: {}", display, why.description()), ...
random
[ { "content": "pub fn get_type(v: &str) -> Option<Type> {\n\n match v {\n\n \"str\" => Some(Type::Str),\n\n \"num\" => Some(Type::Num),\n\n \"bool\" => Some(Type::Bool),\n\n \"idc\" => Some(Type::Any),\n\n _ => None,\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Partia...
Rust
tower/tests/buffer/main.rs
rcoh/tower
287a26be162f11a77e6e5ceff255d60e28923101
#![cfg(feature = "buffer")] #[path = "../support.rs"] mod support; use std::thread; use tokio_test::{assert_pending, assert_ready, assert_ready_err, assert_ready_ok, task}; use tower::buffer::{error, Buffer}; use tower::{util::ServiceExt, Service}; use tower_test::{assert_request_eq, mock}; fn let_worker_work() { ...
#![cfg(feature = "buffer")] #[path = "../support.rs"] mod support; use std::thread; use tokio_test::{assert_pending, assert_ready, assert_ready_err, assert_ready_ok, task}; use tower::buffer::{error, Buffer}; use tower::{util::ServiceExt, Service}; use tower_test::{assert_request_eq, mock}; fn let_worker_work() { ...
#[tokio::test(flavor = "current_thread")] async fn when_inner_fails() { use std::error::Error as StdError; let _t = support::trace_init(); let (mut service, mut handle) = new_service(); handle.allow(0); handle.send_error("foobar"); assert_ready_ok!(service.poll_ready()); let mut re...
e.poll_request()); handle.allow(1); assert_request_eq!(handle, "hello").send_response("world"); let_worker_work(); assert_eq!(assert_ready_ok!(res1.poll()), "world"); }
function_block-function_prefixed
[ { "content": "fn new_service<F, U>(f: F) -> (AsyncFilter<Mock, F>, Handle)\n\nwhere\n\n F: Fn(&String) -> U,\n\n U: Future<Output = Result<(), Error>>,\n\n{\n\n let (service, handle) = mock::pair();\n\n let service = AsyncFilter::new(service, f);\n\n (service, handle)\n\n}\n", "file_path": "t...
Rust
pc-list/src/lib.rs
libreca/LibreCA
de3122697da1d8adc4aecf34f6c5c4fcd47657c6
#![cfg_attr(test, feature(test))] #![allow(incomplete_features)] #![feature(adt_const_params)] #![feature(generic_const_exprs)] #![deny(missing_docs, rustdoc::missing_crate_level_docs, future_incompatible)] use common::{Number, UVec}; #[cfg(test)] mod test_gen; #[derive(Clone)] pub struct PCList<ParameterId: Numbe...
#![cfg_attr(test, feature(test))] #![allow(incomplete_features)] #![feature(adt_const_params)] #![feature(generic_const_exprs)] #![deny(missing_docs, rustdoc::missing_crate_level_docs, future_incompatible)] use common::{Number, UVec}; #[cfg(test)] mod test_gen; #[derive(Clone)] pub struct PCList<ParameterId: Numbe...
let mut res: usize = 1; if strength > at_parameter - strength { strength = at_parameter - strength; } for i in 0..strength { res *= at_parameter - i; res /= i + 1; } res }
function_block-function_prefix_line
[ { "content": "/// This trait allows for the switching of various IPOG extension methods.\n\npub trait Extension<ValueId: Number, ParameterId: Number, LocationsType: Number, const STRENGTH: usize> where [(); STRENGTH - 1]:, [(); STRENGTH - 2]: {\n\n /// Used for debugging purposes.\n\n const NAME: &'static...
Rust
mqtt/mqtt-bridge/src/upstream/rpc/local.rs
hiroyha1/iotedge
53ff15b8ce1c619e2bf32da63ab9eba0c718d00f
use std::collections::HashSet; use async_trait::async_trait; use bson::{doc, Document}; use bytes::buf::BufExt; use lazy_static::lazy_static; use mqtt3::{Event, ReceivedPublication, SubscriptionUpdateEvent}; use regex::Regex; use serde::{Deserialize, Serialize}; use crate::{ client::{Handled, MqttEventHandler}, ...
use std::collections::HashSet; use async_trait::async_trait; use bson::{doc, Document}; use bytes::buf::BufExt; use lazy_static::lazy_static; use mqtt3::{Event, ReceivedPublication, SubscriptionUpdateEvent}; use regex::Regex; use serde::{Deserialize, Serialize}; use crate::{ client::{Handled, MqttEventHandler}, ...
d")) .map(|command_id| command_id.as_str().into()) } #[derive(Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", tag = "version")] enum VersionedRpcCommand { V1(RpcCommand), } #[cfg(test)] mod tests { use bson::{bson, spec::BinarySubtype}; use bytes::Bytes; use matche...
static ref RPC_TOPIC_PATTERN: Regex = Regex::new("\\$upstream/rpc/(?P<command_id>[^/ ]+)$") .expect("failed to create new Regex from pattern"); } RPC_TOPIC_PATTERN .captures(topic_name) .and_then(|captures| captures.name("command_i
function_block-random_span
[ { "content": "/// Returns all of the listeners for a file descriptor name.\n\npub fn listeners_name(name: &str) -> Result<Vec<Socket>, Error> {\n\n debug!(\"Finding sockets for name: {}\", name);\n\n let sockets = listen_fds_with_names(false, LISTEN_FDS_START)?;\n\n let sockets = sockets.get(name).ok_o...