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
examples/hello_rust_world/src/debug/screen.rs
Rusty-VitaSDK/psp2-sys
f88ad44ce8f5074cf6182e72d31be30242026cef
use core::fmt::Result; use core::fmt::Write; use core::mem::size_of; use core::slice::from_raw_parts_mut; use crate::psp2::display::sceDisplaySetFrameBuf; use crate::psp2::display::SceDisplayFrameBuf; use crate::psp2::display::SceDisplaySetBufSync::SCE_DISPLAY_SETBUF_NEXTFRAME; use crate::psp2::kernel::sysmem::sceKern...
use core::fmt::Result; use core::fmt::Write; use core::mem::size_of; use core::slice::from_raw_parts_mut; use crate::psp2::display::sceDisplaySetFrameBuf; use crate::psp2::display::SceDisplayFrameBuf; use crate::psp2::display::SceDisplaySetBufSync::SCE_DISPLAY_SETBUF_NEXTFRAME; use crate::psp2::kernel::sysmem::sceKern...
}
for col in DEBUG_FONT.width..DEBUG_FONT.size_w { vram[row * SCREEN_FB_WIDTH + col] = self.color_bg } } for row in DEBUG_FONT.height..DEBUG_FONT.size_h { for col in 0..DEBUG_FONT.size_w { vram[row * SCREEN_FB_WIDTH + col] = ...
function_block-function_prefix_line
[]
Rust
src/v2/port_mapping.rs
smurawski/compose_yml
7e8e0f47dcc41cf08e15fe082ef4c40b5f0475eb
use super::common::*; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Ports { Port(u16), Range(u16, u16), } impl From<u16> for Ports { fn from(port: u16) -> Ports { Ports::Port(port) } } impl fmt::Display for Ports { fn fmt(&self, f: &mut fmt::Formatter...
use super::common::*; #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Ports { Port(u16), Range(u16, u16), } impl From<u16> for Ports { fn from(port: u16) -> Ports { Ports::Port(port) } } impl fmt::Display for Ports { fn fmt(&self, f: &mut fmt::Formatter...
0.1").unwrap(); let map1 = PortMapping::any_to(80); let map2 = PortMapping::new(Ports::Range(8080, 8089), Ports::Range(3000, 3009)); let map3 = PortMapping { host_address: Some(localhost), ..PortMapping::new(80, 80) }; { let pairs = vec![ (map1, "80/tcp"), ...
rror::invalid_value("port mapping", ports_and_protocol)), } } impl FromStr for PortMapping { type Err = Error; fn from_str(s: &str) -> Result<Self> { let (s_without_protocol, protocol) = consume_protocol(s)?; let fields: Vec<_> = s_without_protocol.rspli...
random
[ { "content": "/// A value which can be represented as a string containing environment\n\n/// variable interpolations. We require a custom `parse` implementation,\n\n/// because we want to handle types that are not necessarily `FromStr`.\n\npub trait InterpolatableValue: Clone + Eq {\n\n /// Our equivalent o...
Rust
rust-wren-derive-backend/src/prop.rs
vangroan/rust-wren
22f911263f9bd0644de78f4693310f073b17084e
use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote, quote_spanned}; use syn::{spanned::Spanned, Field, Fields, ItemStruct, Type}; pub fn gen_class_props(class: &ItemStruct) -> syn::Result<TokenStream> { let get_set = format_ident!("getset"); let get = format_ident!("get"); let set = fo...
use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote, quote_spanned}; use syn::{spanned::Spanned, Field, Fields, ItemStruct, Type}; pub fn gen_class_props(class: &ItemStruct) -> syn::Result<TokenStream> { let get_set = format_ident!("getset"); let get = format_ident!("get"); let set = fo...
fn gen_field_assert(field_index: usize, field: &Field) -> TokenStream { let field_ident = get_field_ident(field_index, field); let field_ty = field.ty.clone(); let field_span = field_ty.span(); let assert_ident = format_ident!("_{}_AssertClone", field_ident); quote_spanned! {field_span...
e => { unimplemented!("FIXME: Tuple field accessors") } } }
function_block-function_prefixed
[ { "content": "/// Generate an implementation of `FromWren` for the given type identifier.\n\n///\n\n/// The type must be `'static` since ownership will be passed to Wren.\n\npub fn gen_from_wren_impl(class: Ident) -> TokenStream {\n\n quote! {\n\n /// Currently this implementation is only really used ...
Rust
dcc-lsystem/src/image_renderer.rs
dcchut/dcc-lsystem
0b0bde40f624e43573e68ba4a369b35b54659851
use crate::dcc_lsystem::LSystem; use crate::image::{draw_line_mut, fill_mut}; use crate::renderer::{Renderer, TurtleRenderer}; use crate::turtle::TurtleContainer; use crate::LSystemError; use gifski::progress::{NoProgress, ProgressReporter}; use gifski::{CatResult, Collector, Repeat}; use image::{ImageBuffer, Rgb}; use...
use crate::dcc_lsystem::LSystem; use crate::image::{draw_line_mut, fill_mut}; use crate::renderer::{Renderer, TurtleRenderer}; use crate::turtle::TurtleContainer; use crate::LSystemError; use gifski::progress::{NoProgress, ProgressReporter}; use gifski::{CatResult, Collector, Repeat}; use image::{ImageBuffer, Rgb}; use...
; } buffer } } pub fn save_png(buffer: &ImageBuffer<Rgb<u8>, Vec<u8>>, path: &Path) -> Result<(), LSystemError> { let file = File::create(path)?; let options = Options::new(); let mut encoder = Encoder::new(file, &options); let mut header = Header::new(); header.set_size(buffe...
draw_line_mut( &mut buffer, xp(*x1), yp(*y1), xp(*x2), yp(*y2), options.thickness, options.line_color, )
call_expression
[ { "content": "/// Modified every pixel of `buffer` to be the provided color.\n\n///\n\n/// # Example\n\n/// ```rust,no_run\n\n/// use image::{ImageBuffer, Rgb};\n\n/// use dcc_lsystem::image::fill_mut;\n\n///\n\n/// let mut buffer : ImageBuffer<Rgb<u8>, Vec<u8>> = unimplemented!();\n\n///\n\n/// // Make our i...
Rust
elsa/src/dubin/geo.rs
TilBlechschmidt/AviationEmergencyLocations
cef0d82f94212ddfec41ecf8079c35ae1131dfe3
use super::*; use ::geo::{ geodesic_distance::GeodesicDistance, point, prelude::{Bearing, EuclideanDistance, HaversineDestination, HaversineDistance}, }; use std::f64::consts::FRAC_PI_2; #[derive(Debug)] pub struct GeographicTangent { pub start: Point, pub end: Point, pub geometric_tangent: Ta...
use super::*; use ::geo::{ geodesic_distance::GeodesicDistance, point, prelude::{Bearing, EuclideanDistance, HaversineDestination, HaversineDistance}, }; use std::f64::consts::FRAC_PI_2; #[derive(Debug)] pub struct GeographicTangent { pub start: Point, pub end: Point, pub geometric_tangent: Ta...
} pub fn geometric_point_to_geographic(point: Point, geographic_origin: Point) -> Point { if point.x() == 0.0 && point.y() == 0.0 { return geographic_origin; } let geometric_origin = point!(x: 0.0, y: 0.0); let distance = point.euclidean_distance(&geometric_origin); let bearing = (point.y...
pub fn points(&self) -> impl Iterator<Item = Point> { let mut iter_a = None; let mut iter_b = None; match self { GeographicDubinPath::CSC(arc1, tangent, arc2) => { iter_a = Some( arc1.points() .chain(vec![tangent.s...
function_block-full_function
[ { "content": "fn calculate_paths(start: &DirectedPoint, end: &DirectedPoint, radius: f64) -> Vec<DubinPath> {\n\n // Build the four circles\n\n let circles = CircleSet::new(&start, &end, radius);\n\n\n\n // Calculate the shortest CSC and CCC paths\n\n let mut paths = Vec::with_capacity(4);\n\n\n\n ...
Rust
tornado-kernel/src/async_rt/executor.rs
HUST-OS/tornado-os
e086b451a0836c00bc13ab940f6a4fa55c1855c6
use super::shared::TaskState; use crate::{ hart::KernelHartInfo, syscall::get_swap_cx, task::{KernelTaskRepr, TaskResult}, trap::switch_to_user, }; use alloc::sync::Arc; use core::{ mem, task::{Context, Poll}, }; #[allow(unused)] use riscv::register::sie; use woke::waker_ref; pub fn run_until_...
use super::shared::TaskState; use crate::{ hart::KernelHartInfo, syscall::get_swap_cx, task::{KernelTaskRepr, TaskResult}, trap::switch_to_user, }; use alloc::sync::Arc; use core::{ mem, task::{Context, Poll}, }; #[allow(unused)] use riscv::register::sie; use woke::waker_ref; pub fn run_until_...
(usize) -> bool, set_task_state: impl Fn(usize, TaskState), ) { loop { ext_intr_off(); let task = peek_task(); ext_intr_on(); println!(">>> run one: next task = {:x?}", task); match task { TaskResult::Task(task_repr) => { ext_intr_off(); ...
satp, next_asid) }; switch_to_user(swap_cx, next_satp.inner(), next_asid) } TaskResult::NoWakeTask => { } TaskResult::Finished => break, } } } #[allow(unused)] pub fn run_one( add_task: impl Fn(u...
random
[ { "content": "#[no_mangle]\n\npub fn switch_to_user(context: &SwapContext, user_satp: usize, user_asid: usize) -> ! {\n\n use riscv::register::{\n\n sstatus::{self, SPP},\n\n stvec::{self, TrapMode},\n\n };\n\n // 关中断\n\n unsafe {\n\n sstatus::clear_sie();\n\n }\n\n extern...
Rust
src/allocators/mod.rs
devjobe/dsa-rs
07419c9fb5d401e8ff6ed618fffa45cd5a10ca9e
use std::{ alloc::{AllocError, Allocator, Layout}, cell::UnsafeCell, mem::MaybeUninit, ptr::NonNull, sync::atomic::{AtomicUsize, Ordering}, }; pub unsafe fn copy_grow<A: Allocator>( allocator: &A, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, A...
use std::{ alloc::{AllocError, Allocator, Layout}, cell::UnsafeCell, mem::MaybeUninit, ptr::NonNull, sync::atomic::{AtomicUsize, Ordering}, }; pub unsafe fn copy_grow<A: Allocator>( allocator: &A, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, A...
}
fn fails_allocation() { let allocator = BumpAllocator::<256>::new(); let old_layout = Layout::new::<[u8; 4]>(); let ptr: NonNull<[u8; 4]> = allocator.allocate(old_layout).unwrap().cast(); let new_layout = Layout::new::<[u8; 512]>(); assert!(allocator.allocate(new_layout).is_err...
function_block-full_function
[]
Rust
p2p/src/handshake.rs
MoaningMyrtle/grin
28b6dab21f1bc1604d11aa2b0e40b816df59a9b2
use std::collections::VecDeque; use std::net::SocketAddr; use std::sync::{Arc, RwLock}; use futures::Future; use rand::Rng; use rand::os::OsRng; use tokio_core::net::TcpStream; use core::core::target::Difficulty; use core::ser; use msg::*; use types::*; use protocol::ProtocolV1; const NONCES_CAP: usize = 100; pub...
use std::collections::VecDeque; use std::net::SocketAddr; use std::sync::{Arc, RwLock}; use futures::Future; use rand::Rng; use rand::os::OsRng; use tokio_core::net::TcpStream; use core::core::target::Difficulty; use core::ser; use msg::*; use types::*; use protocol::ProtocolV1; const NONCES_CAP: usize = 100; pub...
fn next_nonce(&self) -> u64 { let mut rng = OsRng::new().unwrap(); let nonce = rng.next_u64(); let mut nonces = self.nonces.write().unwrap(); nonces.push_back(nonce); if nonces.len() >= NONCES_CAP { nonces.pop_front(); } nonce } }
expected: vec![PROTOCOL_VERSION as u8], received: vec![hand.version as u8], })); } { let nonces = nonces.read().unwrap(); if nonces.contains(&hand.nonce) { return Err(Error::Serialization(ser::Error::UnexpectedData { expected: vec![], received: vec![], })); ...
function_block-function_prefix_line
[ { "content": "/// Future combinator to read any message where the body is a Readable. Reads\n\n/// the header first, handles its validation and then reads the Readable body,\n\n/// allocating buffers of the right size.\n\npub fn read_msg<T>(conn: TcpStream) -> Box<Future<Item = (TcpStream, T), Error = Error>>\...
Rust
src/main.rs
yumcyaWiz/chip8-emulator
6d51390520475f9aa4bc31147935b4325df3a97d
mod chip8; use chip8::Chip8; use std::fs::File; use std::io::prelude::*; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::pixels::PixelFormatEnum; use sdl2::EventPump; use clap::{AppSettings, Clap}; #[macro_use] extern crate lazy_static; #[derive(Clap)] #[clap(setting = AppS...
mod chip8; use chip8::Chip8; use std::fs::File; use std::io::prelude::*; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::pixels::PixelFormatEnum; use sdl2::EventPump; use clap::{AppSettings, Clap}; #[macro_use] extern crate lazy_static; #[derive(Clap)] #[clap(setting = AppS...
fn main() { env_logger::init(); let opts: Opts = Opts::parse(); let mut f = File::open(opts.filepath).expect("Failed to open the file"); let mut program: Vec<u8> = Vec::new(); f.read_to_end(&mut program) .expect("failed to read the file"); let sdl_context = sdl2::init...
fn read_screen_state(chip8: &Chip8, screen_state: &mut [u8; 64 * 32 * 3]) -> bool { let mut idx = 0; let mut update = false; for i in 0..(64 * 32) { let b = chip8.display[i]; let (r, g, b) = color(b).rgb(); if screen_state[idx] != r || screen_state[idx + 1] != g || screen_state[idx +...
function_block-full_function
[ { "content": " pub fn load_program(&mut self, program: Vec<u8>) {\n\n // load fonts\n\n self.memory[0..CHIP8_FONTS.len()].copy_from_slice(&CHIP8_FONTS[..]);\n\n\n\n // load program\n\n self.memory[0x200..(0x200 + program.len())].copy_from_slice(&program[..]);\n\n self.progr...
Rust
src/game/mod.rs
LFalch/shooter
fd64c348b4f8bc28d461ad45c5bd062f8a18e640
use ::*; pub mod world; use self::world::*; pub struct State { input: InputState, assets: Assets, width: u32, height: u32, mouse: Point2, lines: bool, ast_spawn_coords: Option<Point2>, fuel_spawn_coords: Option<Point2>, offset: Vector2, world: World, fuel_text: PosText, ...
use ::*; pub mod world; use self::world::*; pub struct State { input: InputState, assets: Assets, width: u32, height: u32, mouse: Point2, lines: bool, ast_spawn_coords: Option<Point2>, fuel_spawn_coords: Option<Point2>, offset: Vector2, world: World, fuel_text: PosText, ...
}
fn quit_event(&mut self, _ctx: &mut Context) -> bool { println!("Closing, auto-saving game"); save::save("autosave.sav", &self.world).unwrap(); false }
function_block-full_function
[ { "content": "/// Load the state from a file\n\npub fn load<P: AsRef<Path>>(path: P, w: &mut World) -> GameResult<()> {\n\n let mut file = File::open(path)?;\n\n let world = bincode::deserialize_from(&mut file, bincode::Infinite)\n\n .map_err(|e| GameError::UnknownError(format!(\"{:?}\", e)))?;\n\n...
Rust
rust_macro/src/generate.rs
gilengel/rust_procmap
a922af3e04b1026af85a5458fab782b9cfd1a635
use proc_macro2::TokenStream as TokenStream2; use proc_macro_error::abort; use quote::TokenStreamExt; use quote::{format_ident, quote}; use std::str::FromStr; use syn::{DataStruct, DeriveInput, Ident, Lit, LitStr, Meta}; use crate::GenericParam; use proc_macro2::Delimiter; use proc_macro2::Span; use proc_macro2::{Gro...
use proc_macro2::TokenStream as TokenStream2; use proc_macro_error::abort; use quote::TokenStreamExt; use quote::{format_ident, quote}; use std::str::FromStr; use syn::{DataStruct, DeriveInput, Ident, Lit, LitStr, Meta}; use crate::GenericParam; use proc_macro2::Delimiter; use proc_macro2::Span; use proc_macro2::{Gro...
Attribute::Hidden(_) => {} } } elements.push(quote! {</div>}); inner.append_all(elements); t.extend(vec![TokenTree::Group(Group::new(Delimiter::Brace, inner))]); let gen = quote! { fn view_options(&self, ctx: &Context<App<#generic_type>>) -> Html { #(#callbacks)* ...
#name_str } } } fn produce_enabled() -> TokenStream2 { quote! { fn enabled(&self) -> bool { *self.__enabled.as_ref().borrow() } fn enable(&mut self) { self.__enabled.replace(true); } fn disable(&mut self) { self.__ena...
random
[ { "content": "pub fn insert_classes(stack: &mut Vec<HtmlElement>, classes: &str) -> Result<(), JsValue> {\n\n let element = stack.last().unwrap();\n\n\n\n let a = Array::new();\n\n let classes: Vec<&str> = classes.split(',').collect();\n\n for class in &classes {\n\n a.push(&JsValue::from_str...
Rust
src/config/loading/secret.rs
parampavar/vector
83bd797ff6a05fb3246a2442a701db3a85e323b5
use std::{collections::HashMap, io::Read}; use bytes::BytesMut; use futures::{executor, StreamExt}; use indexmap::IndexMap; use once_cell::sync::Lazy; use regex::{Captures, Regex}; use serde::{Deserialize, Serialize}; use tokio::{io::AsyncWriteExt, process::Command, time}; use tokio_util::codec; use toml::value::Table...
use std::{collections::HashMap, io::Read}; use bytes::BytesMut; use futures::{executor, StreamExt}; use indexmap::IndexMap; use once_cell::sync::Lazy; use regex::{Captures, Regex}; use serde::{Deserialize, Serialize}; use tokio::{io::AsyncWriteExt, process::Command, time}; use tokio_util::codec; use toml::value::Table...
#[test] fn collection() { let mut keys = HashMap::<String, Vec<String>>::new(); collect_secret_keys( indoc! {r#" SECRET[first_backend.secret_key] SECRET[first_backend.another_secret_key] SECRET[second_backend.secret_key] SECRET[second...
o(), "value".into()), ("a...key".into(), "a...value".into()), ] .into_iter() .collect(); assert_eq!( Ok("value".into()), interpolate("SECRET[a.secret.key]", &secrets) ); assert_eq!( Ok("value value".into()), int...
function_block-function_prefixed
[ { "content": "pub fn prepare_input<R: std::io::Read>(mut input: R) -> Result<(String, Vec<String>), Vec<String>> {\n\n let mut source_string = String::new();\n\n input\n\n .read_to_string(&mut source_string)\n\n .map_err(|e| vec![e.to_string()])?;\n\n\n\n let mut vars = std::env::vars().c...
Rust
envoy-sdk/src/extension/filter/http/context.rs
nullpo-head/envoy-wasm-rust-sdk
97ef1839b50c620fbc8a09a95965d9d8658b0a49
use crate::abi::proxy_wasm::traits::{Context, HttpContext}; use crate::abi::proxy_wasm::types::Action; use super::{FilterDataStatus, FilterHeadersStatus, FilterTrailersStatus, HttpFilter, Ops}; use crate::extension::error::ErrorSink; use crate::extension::Error; use crate::host::http::client::{HttpClientRequestHandl...
use crate::abi::proxy_wasm::traits::{Context, HttpContext}; use crate::abi::proxy_wasm::types::Action; use super::{FilterDataStatus, FilterHeadersStatus, FilterTrailersStatus, HttpFilter, Ops}; use crate::extension::error::ErrorSink; use crate::extension::Error; use crate::host::http::client::{HttpClientRequestHandl...
} fn on_http_response_headers(&mut self, num_headers: usize, end_of_stream: bool) -> Action { match self.filter.on_response_headers( num_headers, end_of_stream, self.filter_ops.as_response_headers_ops(), ) { Ok(status) => status.as_action(), ...
match self .filter .on_request_trailers(num_trailers, self.filter_ops.as_request_trailers_ops()) { Ok(status) => status.as_action(), Err(err) => { self.error_sink .observe("failed to handle HTTP request trailers", &err); ...
if_condition
[ { "content": "/// An interface for manipulating request body.\n\npub trait RequestBodyOps: RequestFlowOps {\n\n /// Returns request data received from `Downstream`.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `offset` - offset to start reading data from.\n\n /// * `max_size` - maximum size...
Rust
src/broker.rs
86667/loquaz
41ac1ed721d2ba6b1267f3d7ae857ea720634bd5
use druid::{im::Vector, ExtEventSink, Target}; use tokio::sync::mpsc; use crate::{ core::{ config::Contact, conversations::ConvsNotifications, core::{CoreTaskHandle, CoreTaskHandleEvent}, }, data::{ app_state::AppState, state::{ config_state::ConfigState,...
use druid::{im::Vector, ExtEventSink, Target}; use tokio::sync::mpsc; use crate::{ core::{ config::Contact, conversations::ConvsNotifications, core::{CoreTaskHandle, CoreTaskHandleEvent}, }, data::{ app_state::AppState, state::{ config_state::ConfigState,...
tRelay { url } => { core_handle.disconnect_relay(url).await; } BrokerEvent::SubscribeInRelays { pk } => { core_handle.subscribe().await; } BrokerEvent::AddContact { new_contact } => { let res = core_handle.add_contact(new_c...
.messages .push_back(MessageState::from_entity(new_msg)); data.selected_conv = Some(updated_conv); } }); } } } }); while let Some(broker_event...
random
[ { "content": "pub fn set_env<T: Data>() -> impl Fn(&mut Env, &T) + 'static {\n\n |env, _state| {\n\n // env.set(druid::theme::BORDER_DARK, AA);\n\n // env.set(druid::theme::PRIMARY_LIGHT, BLUE);\n\n // env.set(druid::theme::PLACEHOLDER_COLOR, TW_GRAY_400);\n\n\n\n // env.set(druid...
Rust
src/main.rs
ButtNaked/m4mon8
017dc3e1caed191804e795c0709580f1a58ad73e
#![no_std] #![no_main] #![feature(asm)] #![feature(generators, generator_trait)] #![feature(impl_trait_in_bindings)] #![feature(const_fn)] #![feature(never_type)] #![feature(unsize)] #![allow(unused_imports)] #![allow(incomplete_features)] #![allow(dead_code)] extern crate jlink_rtt; #[cfg(debug_assertions)] extern c...
#![no_std] #![no_main] #![feature(asm)] #![feature(generators, generator_trait)] #![feature(impl_trait_in_bindings)] #![feature(const_fn)] #![feature(never_type)] #![feature(unsize)] #![allow(unused_imports)] #![allow(incomplete_features)] #![allow(dead_code)] extern crate jlink_rtt; #[cfg(debug_assertions)] extern c...
#[task(binds = USART1, resources = [&shared], priority = 3)] fn uart0(cx: uart0::Context) { cx.resources.shared.fetch_add(1, Ordering::Relaxed); rtt_print!("USART1: {}", cx.resources.shared.load(Ordering::Relaxed)); } #[task(binds = USART2, resources = [&shared], priority...
fn idle(_cx: idle::Context) -> ! { loop { rtt_print!("IDLE"); } }
function_block-full_function
[ { "content": "pub fn usb_init(clocks: &Clocks) -> () {\n\n ///assert!(clocks.usbclk_valid());\n\n\n\n let p = unsafe { cortex_m::Peripherals::steal() };\n\n let dp = unsafe { Peripherals::steal() };\n\n\n\n let mut gpioa = unsafe { dp.GPIOA.steal() };\n\n //let mut gpioc = unsafe { dp.GPIOC.steal...
Rust
src/tests/configuration.rs
CmdrMoozy/pwm
e0e6581ef3cb90ae90447c705f46106033fec7d3
use crate::configuration::*; use bdrck::testing::temp; use lazy_static::lazy_static; use std::fs; use std::path::PathBuf; use std::sync::Mutex; lazy_static! { static ref CONFIGURATION_TESTS_MUTEX: Mutex<()> = Mutex::new(()); } #[test] fn test_get_and_set() { crate::init().unwrap(); let _guard...
use crate::configuration::*; use bdrck::testing::temp; use lazy_static::lazy_static; use std::fs; use std::path::PathBuf; use std::sync::Mutex; lazy_static! { static ref CONFIGURATION_TESTS_MUTEX: Mutex<()> = Mutex::new(()); } #[test] fn test_get_and_set() { crate::init().unwrap(); let _guard...
#[test] fn test_reset() { crate::init().unwrap(); let _guard = match CONFIGURATION_TESTS_MUTEX.lock() { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), }; let file = temp::File::new_file().unwrap(); let path: PathBuf = file.path().to_owned(); fs::remove_file(...
fn test_get_value_as_str() { crate::init().unwrap(); let _guard = match CONFIGURATION_TESTS_MUTEX.lock() { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), }; let file = temp::File::new_file().unwrap(); let path: PathBuf = file.path().to_owned(); fs::remove_file...
function_block-full_function
[ { "content": "fn get_keystore_path<P: AsRef<Path>>(path: P) -> Result<PathBuf> {\n\n let repository = git::open_repository(path.as_ref(), /*create=*/ false)?;\n\n let mut path = PathBuf::from(git::get_repository_workdir(&repository)?);\n\n path.push(KEYSTORE_PATH.as_path());\n\n Ok(path)\n\n}\n\n\n"...
Rust
tests/url.rs
shssoichiro/iron-valid
65d4b15d0379d1842d0253c88b99b3206fa8a578
extern crate iron_valid; extern crate params; use iron_valid::{Rule, validate}; use params::{Map, Value}; use std::collections::BTreeMap; #[test] fn test_url_valid_prefixed() { let mut params = Map::new(); params.assign("url", Value::String("http://foobar.com".to_owned())).ok(); let mut rules = BTreeMap:...
extern crate iron_valid; extern crate params; use iron_valid::{Rule, validate}; use params::{Map, Value}; use std::collections::BTreeMap; #[test] fn test_url_valid_prefixed() { let mut params = Map::new(); params.assign("url", Value::String("http://foobar.com".to_owned())).ok(); let mut rules = BTreeMap:...
#[test] fn test_url_valid_blank() { let params = Map::new(); let mut rules = BTreeMap::new(); rules.insert("url", vec![Rule::Url]); let result = validate(&rules, params); assert!(result.is_ok()); assert_eq!(result.unwrap().find(&["url"]), None); } #[test] fn test_url_invalid_null() { l...
fn test_url_valid_empty() { let mut params = Map::new(); params.assign("url", Value::String("".to_owned())).ok(); let mut rules = BTreeMap::new(); rules.insert("url", vec![Rule::Url]); let result = validate(&rules, params); assert!(result.is_ok()); assert_eq!(result.unwrap().find(&["url"]...
function_block-full_function
[ { "content": "pub fn validate_url(values: &Map, field: &[&str]) -> Result<Option<Value>, String> {\n\n match values.find(field) {\n\n Some(&Value::String(ref value)) => {\n\n if value.is_empty() {\n\n // Allow empty values\n\n return Ok(None);\n\n }\...
Rust
src/stream/flow/fused.rs
longshorej/pantomime
aea3d7d265948b8e02741192a6ec29b04e5b4338
use crate::stream::internal::ContainedLogic; use crate::stream::{ Action, Logic, LogicEvent, StageRef, StreamContext, StreamContextAction, StreamContextType, }; use std::any::Any; use std::collections::VecDeque; use std::marker::PhantomData; const EXECUTION_STATE_ACTIVE: u8 = 0; const EXECUTION_STATE_UPSTREAM_STOP...
use crate::stream::internal::ContainedLogic; use crate::stream::{ Action, Logic, LogicEvent, StageRef, StreamContext, StreamContextAction, StreamContextType, }; use std::any::Any; use std::collections::VecDeque; use std::marker::PhantomData; const EXECUTION_STATE_ACTIVE: u8 = 0; const EXECUTION_STATE_UPSTREAM_STOP...
gicEvent::Pulled, ctx), LogicEvent::Pushed(element) => self.up_receive(LogicEvent::Pushed(element), ctx), LogicEvent::Stopped => self.up_receive(LogicEvent::Stopped, ctx), LogicEvent::Cancelled => self.down_receive(LogicEvent::Cancelled, ctx), LogicEvent::Started => {...
Stop(_, _) => { self.execution_state = EXECUTION_STATE_UPSTREAM_AND_DOWNSTREAM_STOPPED; } _ => {} } result } fn up_receive( &mut self, event: LogicEvent<A, Box<dyn Any + Send>>, ctx: &mut StreamContext<A, C, FusedMsg<A, B>>, ...
random
[ { "content": "fn upstream_stage_msg_to_stage_msg<A, B, Msg>(msg: UpstreamStageMsg) -> StageMsg<A, B, Msg>\n\nwhere\n\n A: 'static + Send,\n\n B: 'static + Send,\n\n Msg: 'static + Send,\n\n{\n\n match msg {\n\n UpstreamStageMsg::Pull(demand) => StageMsg::Pull(demand),\n\n UpstreamStage...
Rust
src/ui/ledger/mod.rs
fhaynes/backertrack
e96519e67d1c09c41ba61532ccb5cb45aa812ec4
use super::{tui_utils::Event, MainTab, OrdinaryFrame, Trans}; use crate::ledger::Ledger; use num_derive::FromPrimitive; use termion::event::Key; use tui::{ layout::{Constraint, Direction, Layout, Rect}, style::{Color, Modifier, Style}, widgets::{Block, Borders, Paragraph, SelectableList, Text, Widget}, }; ...
use super::{tui_utils::Event, MainTab, OrdinaryFrame, Trans}; use crate::ledger::Ledger; use num_derive::FromPrimitive; use termion::event::Key; use tui::{ layout::{Constraint, Direction, Layout, Rect}, style::{Color, Modifier, Style}, widgets::{Block, Borders, Paragraph, SelectableList, Text, Widget}, }; ...
) .style(Style::default().fg(Color::White)) .highlight_style(Style::default().fg(if self.active_list == LedgerList::Transactions { Color::Yellow } else { Color::Rgb(220, 140, 0) })) .render(f, chunks[1]); } else { ...
Some(*self.accounts_cursors.get(self.account_cursor).expect( "Unreachable: account cursor out of bounds in ledger for transaction listing", ))
call_expression
[ { "content": "pub fn generate_input_fields_text(ledger: &mut LedgerTab, fields: &[&str], next: &'static str) {\n\n ledger.rendered_fields.clear();\n\n ledger.rendered_fields.push(Text::raw(\"\\n\"));\n\n\n\n use crate::utils::GetOrDefault;\n\n\n\n for (i, v) in fields.iter().enumerate() {\n\n ...
Rust
src/lib.rs
zhxie/ninat
9b11d2a91e050ef3ca1fc1b6541175419a62e239
use socks::{Socks5Datagram, TargetAddr}; use std::convert::TryFrom; use std::fmt::{self, Display}; use std::io; use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket}; use std::time::Duration; pub fn lookup_host_v4(host: &str) -> io::Result<Ipv4Addr> { dns_lookup::lookup_host(host)? .into_...
use socks::{Socks5Datagram, TargetAddr}; use std::convert::TryFrom; use std::fmt::{self, Display}; use std::io; use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket}; use std::time::Duration; pub fn lookup_host_v4(host: &str) -> io::Result<Ipv4Addr> { dns_lookup::lookup_host(host)? .into_...
fn send_to(&self, buf: &[u8], addr: SocketAddrV4) -> io::Result<usize> { let size = self.datagram.send_to(buf, addr)?; Ok(size) } fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddrV4)> { let (size, addr) = self.datagram.recv_from(buf)?; return match add...
cal_addr()?; match addr { SocketAddr::V4(addr) => Ok(addr), _ => unreachable!(), } }
function_block-function_prefixed
[ { "content": "#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n\nstruct ResolvableSocketAddr {\n\n addr: SocketAddrV4,\n\n alias: Option<String>,\n\n}\n\n\n\nimpl ResolvableSocketAddr {\n\n fn addr(&self) -> SocketAddrV4 {\n\n self.addr\n\n }\n\n}\n\n\n\nimpl Display for ResolvableSocketAddr {\n...
Rust
src/tree/mod.rs
ncatelli/collections-ext
fbf6f424bb35fdce458b3330f57b5feaff3442e0
extern crate alloc; use alloc::boxed::Box; use core::ptr::NonNull; pub mod binary; pub mod redblack; trait Directional { fn direction(&self) -> Option<Direction>; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Direction { Left, Right, } pub(crate) struct NodeRef<K, V, A>(NonNull<Node<K...
extern crate alloc; use alloc::boxed::Box; use core::ptr::NonNull; pub mod binary; pub mod redblack; trait Directional { fn direction(&self) -> Option<Direction>; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Direction { Left, Right, } pub(crate) struct NodeRef<K, V, A>(NonNull<Node<K...
} #[allow(dead_code)] fn grandparent(&self) -> Option<NodeRef<K, V, A>> { self.parent.and_then(|parent| parent.as_ref().parent) } #[allow(dead_code)] fn uncle(&self) -> Option<NodeRef<K, V, A>> { self.parent.and_then(|parent| parent.as_ref().sibling()) } #[allow(dead_...
match direction { Direction::Left => parent.as_ref().right, Direction::Right => parent.as_ref().left, }
if_condition
[ { "content": "#[derive(Clone, Copy, PartialEq)]\n\nenum DeleteSuccessor<K, V> {\n\n /// Node has two children. Return the in-order successor.\n\n Double(Option<NodeRef<K, V, ()>>),\n\n /// Node has a single child.\n\n Single(NodeRef<K, V, ()>),\n\n /// Node has no children (is a leaf or root).\n\...
Rust
src/gain/classifier_gain.rs
mlondschien/changeforest
4188ba4de34e05214a8cf6a3bb88912067695c14
use crate::control::Control; use crate::gain::{ApproxGain, ApproxGainResult, Gain, GainResult}; use crate::optimizer::OptimizerResult; use crate::Classifier; use crate::ModelSelectionResult; use ndarray::{s, Array1, Array2, Axis}; use rand::{rngs::StdRng, SeedableRng}; pub struct ClassifierGain<T: Classifier> { pu...
use crate::control::Control; use crate::gain::{ApproxGain, ApproxGainResult, Gain, GainResult}; use crate::optimizer::OptimizerResult; use crate::Classifier; use crate::ModelSelectionResult; use ndarray::{s, Array1, Array2, Axis}; use rand::{rngs::StdRng, SeedableRng}; pub struct ClassifierGain<T: Classifier> { pu...
#[cfg(test)] mod tests { use super::*; use crate::optimizer::{Optimizer, TwoStepSearch}; use crate::testing::RandomClassifier; #[test] fn test_gain_from_likelihoods() { let likelihoods = ndarray::array![ [1., -1.], [1., -1.], [0.5, -1.5], [-...
mut(s![1..]) .assign(&(&likelihoods.slice(s![0, ..(n - 1)]) - &likelihoods.slice(s![1, ..(n - 1)]))); gain.accumulate_axis_inplace(Axis(0), |&prev, curr| *curr += prev); gain + likelihoods.slice(s![1, ..]).sum() }
function_block-function_prefixed
[ { "content": "pub fn array() -> Array2<f64> {\n\n let seed = 7;\n\n let mut rng = StdRng::seed_from_u64(seed);\n\n\n\n let mut X = Array::zeros((100, 5)); //\n\n\n\n X.slice_mut(s![0..25, 0]).fill(2.);\n\n X.slice_mut(s![40..80, 0]).fill(1.);\n\n X.slice_mut(s![0..40, 1]).fill(-2.);\n\n X.s...
Rust
foreignc_template/src/py_types.rs
mart368b/ffi-derive
325f42d375774419b96958263b961c8bbce59b96
use crate::*; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct StructureABI { pub self_ty: String, pub methods: Vec<FunctionABI>, pub destructor: Option<String>, pub ty: StructTypes, } impl StructureABI { pub fn from_rust(s: RustStructure, structs: &mut Vec<R...
use crate::*; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] pub struct StructureABI { pub self_ty: String, pub methods: Vec<FunctionABI>, pub destructor: Option<String>, pub ty: StructTypes, } impl StructureABI { pub fn from_rust(s: RustStructure, structs: &mut Vec<R...
Box::new(PythonTypes::from_rust(ok, structs)), Box::new(PythonTypes::from_rust(err, structs)), ), RustTypes::Primitive(s) => match s.as_str() { "i8" | "i16" | "i32" | "i64" | "u8" | "u16" | "u32" | "u64" | "char" => { PythonTypes::Primitive(f...
ch ty.as_ref() { RustTypes::Ptr(s) => { if structs.iter().find(|st| &st.self_ty == s).is_none() { structs.push(RustStructure { self_ty: s.to_owned(), methods: Vec::new(), destructor: None, ...
random
[ { "content": "pub fn convert_item_fn(self_ty: &Box<Type>, item_fn: ImplItemMethod) -> DResult<ItemFn> {\n\n let mut inputs = Vec::new();\n\n for i in &item_fn.sig.inputs {\n\n let p_ty = if let FnArg::Receiver(r) = i {\n\n PatType {\n\n attrs: Vec::new(),\n\n ...
Rust
src/syndication/atom.rs
RomainChartier/good-morning
f23334dda06abe635d80fffe0ae1b127f9dc1536
use quick_xml::events::{BytesStart, Event}; use quick_xml::Reader; use crate::common::GoodMorningError; #[derive(Debug)] pub struct Feed { pub title: String, pub link: String, pub updated: String, pub entries: Vec<Entry>, } #[derive(Debug)] pub struct Entry { pub title: String, pub link: Stri...
use quick_xml::events::{BytesStart, Event}; use quick_xml::Reader; use crate::common::GoodMorningError; #[derive(Debug)] pub struct Feed { pub title: String, pub link: String, pub updated: String, pub entries: Vec<Entry>, } #[derive(Debug)] pub struct Entry { pub title: String, pub link: Stri...
Ok(Feed { title, link, updated, entries, }) } fn extract_attr<B: std::io::BufRead>( name: &[u8], event: &BytesStart, reader: &mut Reader<B>, ) -> Result<String, GoodMorningError> { for attr in event.attributes() { let attr = attr?; if attr.key =...
if title.is_empty() || link.is_empty() || updated.is_empty() || entries.is_empty() { return Err(GoodMorningError::MissingFeedInfo); }
if_condition
[ { "content": "pub fn parse_rss_feed(xml: &str) -> Result<Feed, GoodMorningError> {\n\n let mut reader = Reader::from_str(xml);\n\n reader.trim_text(true);\n\n\n\n let mut channels = Vec::new();\n\n let mut buf = Vec::new();\n\n\n\n loop {\n\n match reader.read_event(&mut buf) {\n\n ...
Rust
src/main.rs
StarToLeft/NonaneDB
5c90be712191a23ecb4fbcff6d1bcff1fd6bcb07
#![allow(non_snake_case)] #[macro_use] extern crate serde; #[macro_use] extern crate log; pub mod database; pub mod utils; use std::{sync::atomic::Ordering, time::Duration}; use database::{ bucket::{ descriptor::BucketDescription, document::{ field::{descriptor::FieldDescriptor, fiel...
#![allow(non_snake_case)] #[macro_use] extern crate serde; #[macro_use] extern crate log; pub mod database; pub mod utils; use std::{sync::atomic::Ordering, time::Duration}; use database::{ bucket::{ descriptor::BucketDescription, document::{ field::{descriptor::FieldDescriptor, fiel...
} } impl DocumentConvert for Account { type ConvertFrom = Account; fn convert_to(self) -> Option<Document> { let first_name = Field::new("first_name", self.first_name.to_owned())?; let last_name = Field::new("last_name", self.last_name.to_string())?; let email = Field::new("email", ...
me: &str, last_name: &str, email: &str, data: Vec<u8>) -> Account { Account { first_name: first_name.to_string(), last_name: last_name.to_string(), email: email.to_string(), data, }
function_block-random_span
[]
Rust
src/config.rs
BatmanAoD/talkboy
8fbac6514e5e27a390c9239a43924b105b3a071b
use crate::archive::ArchivedRequest; use crate::archive::HarLoader; use failure::Error; use hyper::Uri; use serde_derive::Deserialize; use slog::Logger; use std::net::SocketAddr; use std::path::PathBuf; #[derive(Debug, Deserialize)] pub struct Config { #[serde(rename = "project")] projects: Vec<ProjectConfig>,...
use crate::archive::ArchivedRequest; use crate::archive::HarLoader; use failure::Error; use hyper::Uri; use serde_derive::Deserialize; use slog::Logger; use std::net::SocketAddr; use std::path::PathBuf; #[derive(Debug, Deserialize)] pub struct Config { #[serde(rename = "project")] projects: Vec<ProjectConfig>,...
pub fn try_into_playback_servers( self, recording_dir: &str, logger: Logger, ) -> Result<Vec<PlaybackServerConfig>, Error> { let logger = &logger; let mut next_port = NextUnusedPort::new(8080); self.projects .into_iter() .filter(|p| p.pla...
xtUnusedPort::new(8080); self.projects .into_iter() .filter(|p| p.record.is_some()) .map(|p| { let addr = p.addr.unwrap_or_else(|| "127.0.0.1".to_string()); let port = p.port.map(|p| next_port.observe(p)).unwrap_or_else(|| { ...
function_block-function_prefixed
[ { "content": "pub fn get_playback_servers<I: IntoIterator<Item = PlaybackServerConfig>>(\n\n logger: Logger,\n\n servers: I,\n\n) -> impl Future<Item = (), Error = ()> {\n\n let futs = servers.into_iter().map(move |s| {\n\n let req_logger = logger.new(o!(\"server\" => s.name.to_string(), \"lifec...
Rust
src/builders/words.rs
bnspalding/rust-sound
74686b681800ed4eccccf233a036667412e47809
use crate::feature_classes; use crate::phoneme::Phoneme; use crate::stress::Stress; use crate::syllable::Syllable; use crate::word::Word; use std::error::Error; use std::fmt; pub fn from_accent( accent: fn(&str) -> Option<Phoneme>, word_desc: &str, ) -> Result<Word, WordConstructorError> { let syls_as_s...
use crate::feature_classes; use crate::phoneme::Phoneme; use crate::stress::Stress; use crate::syllable::Syllable; use crate::word::Word; use std::error::Error; use std::fmt; pub fn from_accent( accent: fn(&str) -> Option<Phoneme>, word_desc: &str, ) -> Result<Word, WordConstructorError> { let syls_as_s...
} }; let mut onset = vec![]; let mut nucleus_maybe: Option<Phoneme> = None; let mut coda = vec![]; for symbol in syl_as_symbols { let phoneme = accent(&symbol).ok_or_else(|| { WordConstructorError::new(&format!( ...
Err(WordConstructorError::new( "BadSylStructure: no stress information for syllable", ))
call_expression
[ { "content": "/// word provides a constructor for syllable-structured groups of General American English\n\n/// phonemes. Given a collection of IPA symbols for the sounds of the word, return either a Word\n\n/// comprised of those phonemes or a [WordConstructorError].\n\n///\n\n/// See [from_accent] for more in...
Rust
src/identity.rs
phoniks/bs
5330de674fc2882c0441a19e3a28ed0460e437bd
use base64::{decode_config, URL_SAFE}; use crate::{Error, Result}; use diddir::DIDDir; use regex::Regex; use serde_json::{self, Value as JsonValue}; use sodiumoxide::crypto::secretbox::{ self, Key as BoxKey, KEYBYTES, Nonce as BoxNonce, NONCEBYTES }; use sodiumoxide::crypto::sign::{ PublicKey, ...
use base64::{decode_config, URL_SAFE}; use crate::{Error, Result}; use diddir::DIDDir; use regex::Regex; use serde_json::{self, Value as JsonValue}; use sodiumoxide::crypto::secretbox::{ self, Key as BoxKey, KEYBYTES, Nonce as BoxNonce, NONCEBYTES }; use sodiumoxide::crypto::sign::{ PublicKey, ...
if !json["secrets"].is_null() && !json["secrets"]["signing_key"].is_null() { Ok(Box::new(PrivateIdentity::try_from((&pkid, &json))?)) } else { Ok(Box::new(PublicIdentity::try_from((&pkid, &json))?)) } }
if !json.is_object() { return Err(Error::InvalidEncoding("Identity file contents is not a JSON map".to_string())); }
if_condition
[ { "content": "fn get_config(diddir: &Option<String>) -> Result<Config> {\n\n match diddir {\n\n Some(root) => Ok(Config::with_path(Path::new(root))),\n\n None => Ok(Config::new())\n\n }\n\n}\n\n\n", "file_path": "src/sign.rs", "rank": 2, "score": 88240.84911126073 }, { "c...
Rust
src/bin/qamd.rs
ukdataservice/qamd
3432dc9acbbeb0464b81564bcfdb297f422cca14
extern crate base64; extern crate clap; extern crate qamd; extern crate reqwest; extern crate serde; extern crate serde_json; extern crate serde_yaml; use qamd::config::{Config, Valid}; use qamd::readstat::read::read; use qamd::report::html::IntoHtml; use std::fs::{self, File}; use std::io::prelude::*; use std::io::{...
extern crate base64; extern crate clap; extern crate qamd; extern crate reqwest; extern crate serde; extern crate serde_json; extern crate serde_yaml; use qamd::config::{Config, Valid}; use qamd::readstat::read::read; use qamd::report::html::IntoHtml; use std::fs::{self, File}; use std::io::prelude::*; use std::io::{...
fn init() { let base_path = std::env::current_dir().expect(concat!( "Insufficent permissions to access the current", " directory or directory doesn't exist." )); let dirs: [&'static str; 4] = ["config", "dictionaries", "data", "data/test"]; for dir in dirs.iter() { match fs::...
subcommand(SubCommand::with_name("init").about(INIT_ABOUT_TEXT)) .subcommand( SubCommand::with_name("run") .about(RUN_ABOUT_TEXT) .arg( Arg::with_name("input") .help("Sets the input file to use.") .re...
function_block-function_prefix_line
[ { "content": "fn value_if_positive(value: i32, default: &'static str) -> Box<Render> {\n\n box_html! {\n\n @ if value <= 0 {\n\n td : default;\n\n } else {\n\n td : value;\n\n }\n\n }\n\n}\n\n\n\n// fn value_if_present(value: &Option<String>, default: String) -> ...
Rust
src/sentence.rs
k7f/ascesis
b362d25cf18bfc22805977f848ebcbad0f5d8fa3
use std::collections::HashMap; use crate::grammar::{Grammar, SymbolID, ProductionID}; #[derive(Default, Debug)] pub struct Sentence { symbols: Vec<SymbolID>, } impl Sentence { pub fn new() -> Self { Self::default() } pub fn clear(&mut self) { self.symbols.clear(); } pub fn pu...
use std::collections::HashMap; use crate::grammar::{Grammar, SymbolID, ProductionID}; #[derive(Default, Debug)] pub struct Sentence { symbols: Vec<SymbolID>, } impl Sentence { pub fn new() -> Self { Self::default() } pub fn clear(&mut self) { self.symbols.clear(); } pub fn pu...
} if prod_min[prod_id].map_or(true, |v| sum < v) { prod_min[prod_id] = Some(sum); if symbol_min[&prod.lhs()].map_or(true, |v| sum < v) { symbol_min.insert(prod.lhs(), Some(sum)); best_prod.insert(p...
if let Some(bound) = symbol_min[&element] { sum += bound; } else { continue 'outer }
if_condition
[ { "content": "fn format_location(mut pos: usize, script: &str) -> String {\n\n for (num_lines, line) in script.lines().enumerate() {\n\n match pos.checked_sub(line.len() + 1) {\n\n Some(p) => pos = p,\n\n None => return format!(\"[{}:{}]\", num_lines + 1, pos + 1),\n\n }\n...
Rust
src/hasher/slicex4.rs
EugeneGonzalez/crc_complete
f23c95ca823e2276573b9528d818a068576dbf49
use {Crc8, Crc16, Crc32, Crc64}; use polynomial::{Reflect, Yes, No, CrcPoly, CrcPolynomial}; use hasher::CrcHasher; use hasher::table_builder::CrcTableBuilder; use std::mem; pub struct Slicex4<'a, R, T> where R: 'a + Reflect, T: 'a { polynomial: &'a CrcPoly<R, T>, table: [[T; 256]; 4], } impl<'a...
use {Crc8, Crc16, Crc32, Crc64}; use polynomial::{Reflect, Yes, No, CrcPoly, CrcPolynomial}; use hasher::CrcHasher; use hasher::table_builder::CrcTableBuilder; use std::mem; pub struct Slicex4<'a, R, T> where R: 'a + Reflect, T: 'a { polynomial: &'a CrcPoly<R, T>, table: [[T; 256]; 4], } impl<'a...
#[inline] fn finalize_crc(&self, crc: Crc8) -> Crc8 { self.polynomial.finalize_crc(crc) } } impl<'a> CrcHasher<'a, Yes, Crc16> for Slicex4<'a, Yes, Crc16> where CrcPoly<Yes, Crc16>: CrcPolynomial<Crc16> { fn with(polynomial: &'a CrcPoly<Yes, Crc16>) -> Self { let mut hasher = Slic...
c; let mut ptr = bytes.as_ptr(); let mut len = bytes.len(); while len >= 4 { let one = unsafe { *ptr } ^ crc; let two = unsafe { *ptr.offset(1) }; let three = unsafe { *ptr.offset(2) }; let four = unsafe { *ptr.offset(3) }; crc = sel...
function_block-function_prefixed
[ { "content": "pub trait CrcTableBuilder<R, T>\n\n where R: Reflect,\n\n CrcPoly<R, T>: CrcPolynomial<T>\n\n{\n\n fn build_table(&mut self, polynomial: &CrcPoly<R, T>);\n\n}\n\n\n\nmacro_rules! doit_table {\n\n ($($ty:ty),*) => ($(\n\n impl CrcTableBuilder<Yes, $ty> for [$ty; 256]\n\n ...
Rust
src/main.rs
bendst/minWeb
04eccb069b2bd14cc2869a7e7e21736e9d863006
extern crate hyper; extern crate ansi_term; extern crate libc; mod args; mod util; mod cfi; use hyper::Server; use hyper::server::{Request, Response}; use hyper::uri::RequestUri; use hyper::status::StatusCode; use ansi_term::Colour::{Green, Red, Blue}; use std::env; use std::thread; use std::process::Command; use st...
extern crate hyper; extern crate ansi_term; extern crate libc; mod args; mod util; mod cfi; use hyper::Server; use hyper::server::{Request, Response}; use hyper::uri::RequestUri; use hyper::status::StatusCode; use ansi_term::Colour::{Green, Red, Blue}; use std::env; use std::thread; use std::process::Command; use st...
nt.read().expect("read lock").contains_key(&key) }; match has_key { true => content.read().expect("read lock").get(&key).unwrap().clone(), _ => { get_data(&key).map_or(StatusCode::NotFound.canonical_rea...
println!("{} {} {}.", Green.bold().paint(START), Green.bold().paint("on port"), Red.bold().paint(port.clone())); "0.0.0.0:".to_owned() + &port } }; arguments.make_daemon(thread_content); argu...
random
[]
Rust
src/main.rs
abhayk/subshift
a114303d9f22056e312a7cbc554dc9d563ede7c4
use anyhow::{Context, Result}; use chrono::{Duration, NaiveTime}; use clap::Parser; use std::{ fs, fs::File, io::{BufRead, BufReader, Write}, ops::Add, }; #[derive(Parser)] #[clap( version = "0.1.0", author = "abhayk <abhay.krishnan.dev@gmail.com>", about = r#"A tool to add or subtract offs...
use anyhow::{Context, Result}; use chrono::{Duration, NaiveTime}; use clap::Parser; use std::{ fs, fs::File, io::{BufRead, BufReader, Write}, ops::Add, }; #[derive(Parser)] #[clap( version = "0.1.0", author = "abhayk <abhay.krishnan.dev@gmail.com>", about = r#"A tool to add or subtract offs...
ile_path, input_file_path) .context("Failed while trying to replace the original file with the updated version")?; Ok(()) } fn process_duration(line: &str, offset: i8, separator: &str) -> Result<String> { let result: Vec<String> = line .split(separator) .map(|item| apply_offset(item, o...
#[clap(short, long, about = "The path to the subtitle file")] file: String, #[clap( short, long, about = "The shift offset. To increment by half a second provide +500, To decrement -500.", allow_hyphen_values = true )] offset: i8, } fn main() -> Result<()> { let opt...
random
[ { "content": "#[test]\n\nfn offsets_are_applied() -> Result<(), Box<dyn std::error::Error>> {\n\n struct TestFilePaths {\n\n original_file: PathBuf,\n\n backup_file: PathBuf,\n\n }\n\n\n\n impl Drop for TestFilePaths {\n\n fn drop(&mut self) {\n\n fs::remove_file(&self.o...
Rust
src/ast/util.rs
KeenS/webml
60f4d899d623d5872c325412054bd0d77e37c4aa
use crate::ast::*; pub trait Traverse<Ty> { fn traverse_ast(&mut self, ast: &mut Core<Ty>) { for decl in ast.0.iter_mut() { self.traverse_statement(decl) } } fn traverse_statement(&mut self, decl: &mut CoreDeclaration<Ty>) { use Declaration::*; match decl { ...
use crate::ast::*; pub trait Traverse<Ty> { fn traverse_ast(&mut self, ast: &mut Core<Ty>) { for decl in ast.0.iter_mut() { self.traverse_statement(decl) } } fn traverse_statement(&mut self, decl: &mut CoreDeclaration<Ty>) { use Declaration::*; match decl { ...
fn transform_pat_tuple(&mut self, tuple: Vec<Pattern<Ty>>) -> PatternKind<Ty> { PatternKind::Tuple { tuple: tuple .into_iter() .map(|pat| self.transform_pattern(pat)) .collect(), } } fn transform_pat_variable(&mut self, name: Sym...
fn transform_pat_constructor( &mut self, arg: Option<Box<Pattern<Ty>>>, name: Symbol, ) -> PatternKind<Ty> { PatternKind::Constructor { name, arg: arg.map(|pat| Box::new(self.transform_pattern(*pat))), } }
function_block-full_function
[ { "content": "fn take_binds(expr: Expr) -> (Expr, Vec<Val>) {\n\n use crate::hir::Expr::*;\n\n match expr {\n\n Let { bind, ret, .. } => {\n\n let (expr, mut binds) = take_binds(*ret);\n\n binds.insert(0, *bind);\n\n (expr, binds)\n\n }\n\n BuiltinCall...
Rust
src/utils.rs
ambyshframber/gladiator_war_rs_2
a46df54e0db6af4cbf1eb9ab577d349d26b3d1d7
use std::cmp::Ordering; use std::fs; use std::path::Path; use std::fmt; use std::io::{stdin, Write, stdout}; use crate::global; pub fn select_largest<T: std::cmp::PartialOrd>(a: T, b: T) -> T { match a.partial_cmp(&b) { None => a, Some(c) => { match c { Ord...
use std::cmp::Ordering; use std::fs; use std::path::Path; use std::fmt; use std::io::{stdin, Write, stdout}; use crate::global; pub fn select_largest<T: std::cmp::PartialOrd>(a: T, b: T) -> T { match a.partial_cmp(&b) { None => a, Some(c) => { match c { Ord...
fn get_last(s: &str, delim: char) -> (&str, &str) { let split: Vec<&str> = s.split(delim).collect(); let last = split[split.len() - 1]; let main = if split.len() != 1 { &s[..s.len() - (last.len() + 1)] } else { "" }; (main, last) } fn string_en...
= &full_filename { name_exists = true; break } } if !name_exists { return Ok(full_path.to_string()) } let mut iter = 1; let mut check_string; loop { check_string = format!("{}_{}.{}", filename, iter, extension); let mut name_e...
random
[ { "content": "pub fn battle(f1: &mut Fighter, f2: &mut Fighter, arena: &Arena, modifier: &Modifier, log: &mut Batlog) {\n\n let f1_stats = f1.roll_for_stats(arena, modifier);\n\n let f2_stats = f2.roll_for_stats(arena, modifier);\n\n\n\n f1.battles_fought += 1;\n\n f2.battles_fought += 1;\n\n\n\n ...
Rust
2021/24/src/lib.rs
PsypherPunk/advent-of-code
5da9cea793d0dd326d01ccaa307bfbb13ab8c06f
use std::collections::{HashMap, VecDeque}; use std::str::FromStr; #[derive(Clone, Debug)] enum IntegerVariable { Variable(char), Integer(isize), } #[derive(Clone, Debug)] enum Instruction { Inp(char), Add(char, IntegerVariable), Mul(char, IntegerVariable), Div(char, IntegerVariable), Mod...
use std::collections::{HashMap, VecDeque}; use std::str::FromStr; #[derive(Clone, Debug)] enum IntegerVariable { Variable(char), Integer(isize), } #[derive(Clone, Debug)] enum Instruction { Inp(char), Add(char, IntegerVariable), Mul(char, IntegerVariable), Div(char, IntegerVariable), Mod...
; let entry = self.processing_unit.entry(*variable).or_insert(0); *entry += value; } Instruction::Mul(variable, iv) => { let &value = match iv { IntegerVariable::Variable(v) => self.processing_unit.entry(...
match iv { IntegerVariable::Variable(v) => self.processing_unit.entry(*v).or_insert(0), IntegerVariable::Integer(i) => i, }
if_condition
[ { "content": "fn get_seating(input: &str) -> HashMap<String, HashMap<String, isize>> {\n\n let plan =\n\n Regex::new(r#\"^(\\w+) would (gain|lose) (\\d+) happiness units by sitting next to (\\w+).\"#)\n\n .unwrap();\n\n\n\n let mut seating = HashMap::new();\n\n\n\n input.trim().lines(...
Rust
xtask/src/proto.rs
mechiru/google-api-proto
7b52306ed6b905313daa70c370d2d217e7e1b053
use std::{ collections::{BTreeMap, BTreeSet}, fs, path::{Path, PathBuf}, str::Lines, }; #[derive(Debug, PartialEq)] pub struct Protos { protos: Vec<Proto>, } impl Protos { pub fn from_dir(dir: impl AsRef<Path>) -> anyhow::Result<Self> { let mut protos = Vec::new(); for entry in...
use std::{ collections::{BTreeMap, BTreeSet}, fs, path::{Path, PathBuf}, str::Lines, }; #[derive(Debug, PartialEq)] pub struct Protos { protos: Vec<Proto>, } impl Protos { pub fn from_dir(dir: impl AsRef<Path>) -> anyhow::Result<Self> { let mut protos = Vec::new(); for entry in...
} #[cfg(test)] mod test { use super::*; #[test] fn test_package_parse() -> anyhow::Result<()> { assert_eq!( Package::parse(&mut "package mechiru;".lines())?, Package { raw_name: "mechiru".into() } ); assert_eq!( Package::parse(&mut "package mech...
for proto in protos { if proto.path.ends_with(&self.raw_path) { return Ok(proto.package.as_feature()); } } Err(anyhow::anyhow!("not found imported file: {:?}", self.raw_path)) }
function_block-function_prefix_line
[]
Rust
src/render/shader.rs
Trikzon/chirp-8
d0ddd81ac3d18ecb3e067ffa94fb3598df4f5aad
use crate::render::gl; use std::collections::HashMap; use thiserror::Error; #[derive(Debug, Error)] pub enum ShaderError { #[error("combo shader is missing a type header")] MissingTypeHeader, #[error("combo shader type header: {0} is invalid")] InvalidTypeHeader(String), #[error("shader builder is ...
use crate::render::gl; use std::collections::HashMap; use thiserror::Error; #[derive(Debug, Error)] pub enum ShaderError { #[error("combo shader is missing a type header")] MissingTypeHeader, #[error("combo shader type header: {0} is invalid")] InvalidTypeHeader(String), #[error("shader builder is ...
Ok(()) } pub fn upload_uniform<S: Into<String>>( &mut self, name: S, value: &impl gl::UploadableUniform, ) -> Result<(), ShaderError> { let name = name.into(); let uniform_location = self .uniform_locations .get(&name) .ok_or...
issingShaderType( gl::ShaderType::Fragment.value(), ))?; let vertex = Self::compile_shader(gl, gl::ShaderType::Vertex, vertex_source)?; let fragment = Self::compile_shader(gl, gl::ShaderType::Fragment, fragment_source)?; let program = Self::link_shaders(gl, &[vertex, fragme...
random
[ { "content": "pub trait UploadableUniform {\n\n fn upload(&self, gl: &Gl, uniform_location: &UniformLocationId);\n\n}\n\n\n\nimpl UploadableUniform for f32 {\n\n fn upload(&self, gl: &Gl, uniform_location: &UniformLocationId) {\n\n unsafe { gl.gl.Uniform1f(uniform_location.id, *self) };\n\n }\n\...
Rust
src/usb/dcfg.rs
crawford/efm32gg11b820
390142de0a68b55a142bb16d31634cebf2289209
#[doc = "Reader of register DCFG"] pub type R = crate::R<u32, super::DCFG>; #[doc = "Writer for register DCFG"] pub type W = crate::W<u32, super::DCFG>; #[doc = "Register DCFG `reset()`'s with value 0x0800_0000"] impl crate::ResetValue for super::DCFG { type Type = u32; #[inline(always)] fn reset_value() ->...
#[doc = "Reader of register DCFG"] pub type R = crate::R<u32, super::DCFG>; #[doc = "Writer for register DCFG"] pub type W = crate::W<u32, super::DCFG>; #[doc = "Register DCFG `reset()`'s with value 0x0800_0000"] impl crate::ResetValue for super::DCFG { type Type = u32; #[inline(always)] fn reset_value() ->...
ine(always)] pub fn perfrint(&self) -> PERFRINT_R { PERFRINT_R::new(((self.bits >> 11) & 0x03) as u8) } #[doc = "Bit 13 - Enable Device OUT NAK"] #[inline(always)] pub fn endevoutnak(&self) -> ENDEVOUTNAK_R { ENDEVOUTNAK_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit ...
ets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn ...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/base.rs
fossabot/taxonomy-rs
54946f346572a0a3ef69aecdf8c9080ebb39a460
use std::collections::HashMap; use serde_derive::{Deserialize, Serialize}; use crate::rank::TaxRank; use crate::taxonomy::Taxonomy; use crate::{Result, TaxonomyError}; pub type IntTaxID = usize; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct GeneralTaxonomy { pub(crate) tax_ids: Vec<String>, pu...
use std::collections::HashMap; use serde_derive::{Deserialize, Serialize}; use crate::rank::TaxRank; use crate::taxonomy::Taxonomy; use crate::{Result, TaxonomyError}; pub type IntTaxID = usize; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct GeneralTaxonomy { pub(crate) tax_ids: Vec<String>, pu...
} fn parent(&self, tax_id: &str) -> Result<Option<(&str, f32)>> { let usize_tax_id = self.to_internal_id(&tax_id)?; if usize_tax_id == 0 { return Ok(None); } Ok(Some(( self.from_internal_id(self.parent_ids[usize_tax_id])?, self.paren...
if let Some(ref child_lookup) = self.children_lookup { let usize_tax_id = self.to_internal_id(&tax_id)?; child_lookup[usize_tax_id] .iter() .map(|x| self.from_internal_id(*x)) .collect() } else { let mu...
if_condition
[ { "content": "/// Load a Taxonomy out of the `reader` automatically trying to determine\n\n/// what subtype of the JSON types we understand it is.\n\npub fn load_json<R>(reader: R, key: Option<&str>) -> Result<GeneralTaxonomy>\n\nwhere\n\n R: Read,\n\n{\n\n let tax_json: Value = from_reader(reader)?;\n\n ...
Rust
src/main.rs
ConcurrentMarxistGC/raspivid-stream
8e53ca1d9bac92ae0127c82c2f70696786c046c7
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; extern crate env_logger; use config::Config; use std::fs::{self}; use std::mem::swap; use std::process::{self, Command}; use std::sync::RwLock; use std::thread; use std::time::Duration; use streams::*; mod ...
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; extern crate env_logger; use config::Config; use std::fs::{self}; use std::mem::swap; use std::process::{self, Command}; use std::sync::RwLock; use std::thread; use std::time::Duration; use streams::*; mod ...
fn clean_tmp_dir() { let _ = fs::remove_dir_all(STREAM_TMP_DIR); let _ = fs::create_dir(STREAM_TMP_DIR); }
mut pic_param, &mut seq_param, |mut frame: Vec<u8>, ffmpeg: &mut FFMpeg, mut pic_param: &mut Vec<u8>, mut seq_param: &mut Vec<u8>| { let unit_type = h264::get_unit_type(&frame); loop { match unit_type { 5 => { if ffmpeg.is_saturated() { let mut handle = FFMpeg::spawn(); ...
function_block-function_prefixed
[ { "content": "pub fn split_stream<F, R: Read>(input_stream: &mut R, ffmpeg: &mut FFMpeg, pic_param: &mut Vec<u8>, seq_param: &mut Vec<u8>, new_unit_handle: F) where F: Fn(Vec<u8>, &mut FFMpeg, &mut Vec<u8>, &mut Vec<u8>) {\n\n\tlet mut nulls: usize = 0;\n\n\tlet mut nal_unit: Vec<u8> = vec![];\n\n\tlet mut buff...
Rust
src/render/sky_material.rs
exjam/bevy_rose
8cbcc3ae71505b7e9b7d51f7177863967c489fcc
use std::marker::PhantomData; use bevy::{ asset::Handle, core_pipeline::Opaque3d, ecs::system::{ lifetimeless::{Read, SQuery, SRes}, SystemParamItem, }, pbr::{ DrawMesh, MeshPipeline, MeshPipelineKey, MeshUniform, SetMeshBindGroup, SetMeshViewBindGroup, }, pr...
use std::marker::PhantomData; use bevy::{ asset::Handle, core_pipeline::Opaque3d, ecs::system::{ lifetimeless::{Read, SQuery, SRes}, SystemParamItem, }, pbr::{ DrawMesh, MeshPipeline, MeshPipelineKey, MeshUniform, SetMeshBindGroup, SetMeshViewBindGroup, }, pr...
} impl FromWorld for SkyMaterialPipeline { fn from_world(world: &mut World) -> Self { let render_device = world.resource::<RenderDevice>(); let material_layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor { entries: &[ BindGroupLa...
fn specialize( &self, key: Self::Key, layout: &MeshVertexBufferLayout, ) -> Result<RenderPipelineDescriptor, SpecializedMeshPipelineError> { let mut descriptor = self.mesh_pipeline.specialize(key, layout)?; if let Some(vertex_shader) = &self.vertex_shader { descri...
function_block-full_function
[ { "content": "fn bind_buffer<T: Pod>(buffer: &BufferVec<T>, count: u64) -> BindingResource {\n\n BindingResource::Buffer(BufferBinding {\n\n buffer: buffer.buffer().expect(\"missing buffer\"),\n\n offset: 0,\n\n size: Some(NonZeroU64::new(std::mem::size_of::<T>() as u64 * count).unwrap()...
Rust
archive/poc1/src/cluster.rs
houqp/ballista
7011dec497090403ae861b6ce78ec48349755090
use std::{collections::BTreeMap, convert::TryInto}; use k8s_openapi::{ api, apimachinery::pkg::apis::meta::v1::{LabelSelector, ObjectMeta}, http, Response, ResponseBody, }; use kube::config; use crate::error::BallistaError; const CLUSTER_LABEL_KEY: &str = "ballista-cluster"; const DEFAULT_IMAGE: &str =...
use std::{collections::BTreeMap, convert::TryInto}; use k8s_openapi::{ api, apimachinery::pkg::apis::meta::v1::{LabelSelector, ObjectMeta}, http, Response, ResponseBody, }; use kube::config; use crate::error::BallistaError; const CLUSTER_LABEL_KEY: &str = "ballista-cluster"; const DEFAULT_IMAGE: &str =...
.body(body); let mut response = req.send()?; let status = response.status(); let mut r = response_body(status); r.append_slice(response.text()?.as_bytes()); Ok(r.parse()?) } pub struct Executor { pub host: String, pub port: usize, } pub fn statefulset_name(name: &str) -> String { ...
match parts.method { http::Method::GET => client.get(&uri_str), http::Method::POST => client.post(&uri_str), http::Method::DELETE => client.delete(&uri_str), http::Method::PUT => client.put(&uri_str), other => { return Err(BallistaError::General(format!("Invalid metho...
if_condition
[ { "content": "fn execute<T, F>(request: http::Request<Vec<u8>>, response_body: F) -> Result<T, BallistaError>\n\nwhere\n\n T: Response,\n\n F: Fn(http::StatusCode) -> ResponseBody<T>,\n\n{\n\n let kubeconfig = config::load_kube_config()\n\n .or_else(|_| config::incluster_config())\n\n .ma...
Rust
src/song.rs
aeshirey/bwaa-bwaa
9252e9590497e7accf176c6eac0de371659beade
use serde::{Deserialize, Serialize}; use std::collections::hash_map::DefaultHasher; use std::fmt::{Display, Formatter}; use std::hash::{Hash, Hasher}; use std::time::Duration; use crate::music_db::SortBy; #[derive(Debug, Hash, Default, Serialize, Deserialize)] pub struct Song { pub id: u64, pub path: String, ...
use serde::{Deserialize, Serialize}; use std::collections::hash_map::DefaultHasher; use std::fmt::{Display, Formatter}; use std::hash::{Hash, Hasher}; use std::time::Duration; use crate::music_db::SortBy; #[derive(Debug, Hash, Default, Serialize, Deserialize)] pub struct Song { pub id: u64, pub path: String, ...
} impl Display for Song { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, r#"<a href="{}">{}</a>"#, self.path, self.title) } } #[derive(Serialize)] pub struct SongResult { pub id: String, pub title: String, pub artist: String, pub album: String, pub year: u16...
pub fn cmp(&self, other: &Self, sort_by: SortBy) -> std::cmp::Ordering { match sort_by { SortBy::track => self .track .cmp(&other.track) .then(self.title.cmp(&other.title)) .then(self.album_lower.cmp(&other.album_lower)) ...
function_block-full_function
[ { "content": "use crate::song::{Song, SongResult};\n\nuse serde::{Deserialize, Serialize};\n\nuse std::{\n\n collections::{HashMap, HashSet},\n\n fs::File,\n\n io::{BufRead, BufReader, BufWriter, Write},\n\n path::{Path, PathBuf},\n\n};\n\n\n\nconst LIBRARY_FILE: &str = \"library.json\";\n\n\n\n#[de...
Rust
src/main.rs
sbrocket/failsafe
cb4883bc2952a7ce4c77ab3d17be0cc3910c7f0f
use crate::{guild::GuildManager, store::PersistentStoreBuilder}; use serenity::{ async_trait, model::{ gateway::Ready, guild::{Guild, GuildUnavailable}, id::GuildId, interactions::Interaction, }, prelude::*, }; use std::sync::Arc; use tracing::{debug, error, info}; use tr...
use crate::{guild::GuildManager, store::PersistentStoreBuilder}; use serenity::{ async_trait, model::{ gateway::Ready, guild::{Guild, GuildUnavailable}, id::GuildId, interactions::Interaction, }, prelude::*, }; use std::sync::Arc; use tracing::{debug, error, info}; use tr...
async fn main() { dotenv::dotenv().ok(); let env_filter: EnvFilter; let fmt_layer = tracing_subscriber::fmt::layer().with_target(true); let registry = tracing_subscriber::registry().with(fmt_layer); { #[cfg(feature = "tokio-console")] { env_filter = ...
function_block-full_function
[ { "content": "type CommandHandler = for<'fut> fn(\n\n &'fut Context,\n\n &'fut ApplicationCommandInteraction,\n\n &'fut Vec<ApplicationCommandInteractionDataOption>,\n\n) -> BoxFuture<'fut, Result<()>>;\n\n\n\n/// Definition of a leaf command, which has user-facing options and handles user interactions...
Rust
src/main.rs
Dobiasd/ray-tracer
3a32083fefecc47957e725e7e99a611da3ecf3cf
extern crate chrono; extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; extern crate simple_logger; use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::time::Instant; use log::info; use pixel_canvas::{Canvas, Image as CanvasImage}; use structopt::StructOpt; use cr...
extern crate chrono; extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; extern crate simple_logger; use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::time::Instant; use log::info; use pixel_canvas::{Canvas, Image as CanvasImage}; use structopt::StructOpt; use cr...
fn main() { simple_logger::init().unwrap(); render(load_config()); }
fn plot_pixels(image: &mut CanvasImage, pixels: &Image, scale_factor: usize) { let width = image.width(); for (y, row) in image.chunks_mut(width).enumerate() { for (x, pixel) in row.iter_mut().enumerate() { *pixel = pixels.get( x / scale_factor, y / scale_fact...
function_block-full_function
[ { "content": "pub fn sky(t_real: f64) -> Sky {\n\n let sky_factor = t_real;\n\n let day1 = Color { r: 1.0, g: 1.0, b: 1.0 };\n\n let day2 = Color { r: 0.5, g: 0.7, b: 1.0 };\n\n let night1 = Color { r: 0.8, g: 0.6, b: 0.7 };\n\n let night2 = Color { r: 0.4, g: 0.1, b: 0.15 };\n\n Sky {\n\n ...
Rust
src/core/extract.rs
hhandika/segul
f573aa78fda126fee2d52944f7e14f3232311c00
use std::fs; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use ansi_term::Colour::Yellow; use indexmap::IndexMap; use rayon::prelude::*; use regex::Regex; use crate::core::OutputPrint; use crate::helper::sequence::{SeqCheck, Sequence}; use crate::helper::types::{DataType, Header, Inp...
use std::fs; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; use ansi_term::Colour::Yellow; use indexmap::IndexMap; use rayon::prelude::*; use regex::Regex; use crate::core::OutputPrint; use crate::helper::sequence::{SeqCheck, Sequence}; use crate::helper::types::{DataType, Header, Inp...
fn print_output_info(&self, file_counts: &usize, output: &Path, output_fmt: &OutputFmt) { log::info!("{}", Yellow.paint("Output")); log::info!("{:18}: {}", "File counts", utils::fmt_num(file_counts)); log::info!("{:18}: {}", "Output dir", output.display()); self.print_output_fmt(ou...
fn get_header(&self, matrix: &SeqMatrix) -> Header { let mut seq_info = SeqCheck::new(); seq_info.check(matrix); let mut header = Header::new(); header.aligned = seq_info.is_alignment; header.nchar = seq_info.longest; header.ntax = matrix.len(); header }
function_block-full_function
[ { "content": "pub fn create_output_fname(dir: &Path, file: &Path, output_fmt: &OutputFmt) -> PathBuf {\n\n let path = dir.join(\n\n file.file_name()\n\n .expect(\"Failed parsing filename for output file\"),\n\n );\n\n create_output_fname_from_path(&path, output_fmt)\n\n}\n\n\n", "...
Rust
abi_stable/src/std_types/map/extern_fns.rs
rodrimati1992/abi_stable_crates
3cc100cba70b335c9a496159af2f86b2dc240d88
use super::*; use crate::{ pointer_trait::TransmuteElement, sabi_types::{RRef, RMut}, traits::IntoReprC, }; impl<K,V,S> ErasedMap<K,V,S> where K:Hash+Eq, S:BuildHasher, { fn run<'a,F,R>(this: RRef<'a, Self>,f:F)->R where F:FnOnce(&'a BoxedHashMap<'a,K,V,S>)->R { extern_fn_pani...
use super::*; use crate::{ pointer_trait::TransmuteElement, sabi_types::{RRef, RMut}, traits::IntoReprC, }; impl<K,V,S> ErasedMap<K,V,S> where K:Hash+Eq, S:BuildHasher, { fn run<'a,F,R>(this: RRef<'a, Self>,f:F)->R where F:FnOnce(&'a BoxedHashMap<'a,K,V,S>)->R { extern_fn_pani...
'a, Self>,key:MapQuery<'_,K>)->Option<&'a mut V>{ Self::run_mut(this, |this|unsafe{ this.map.get_mut(&key.as_mapkey()) }) } pub(super)extern "C" fn remove_entry(this: RMut<'_, Self>,key:MapQuery<'_,K>)->ROption<Tuple2<K,V>>{ Self::run_mut(this, |this|{ match th...
ansmute_into_ref::<BoxedHashMap<'a,K,V,S>>() }; f(map) } } fn run_mut<'a,F,R>(this: RMut<'a, Self>,f:F)->R where F:FnOnce(&'a mut BoxedHashMap<'a,K,V,S>)->R { extern_fn_panic_handling!{ let map = unsafe{ this.transmute_into_mut::<BoxedHashMap<'a,K,V,S>>() }; ...
random
[ { "content": "fn assert_is_vacant<K,V>(map:&mut RHashMap<K,V>,k:K)\n\nwhere\n\n K:Eq+Hash+Clone+Debug,\n\n V:Clone+Debug+PartialEq,\n\n{\n\n let mut entry=map.entry(k.clone());\n\n assert_matches!(REntry::Vacant{..}=entry);\n\n assert_eq!(entry.key(), &k);\n\n assert_eq!(entry.get().cloned(), ...
Rust
src/sema/yul/ast.rs
shekhirin/solang
5cc9c2667cdd0475a41e6c693f853e4b57159220
use crate::ast::{Parameter, Type}; use crate::sema::symtable::Symtable; use crate::sema::yul::builtin::YulBuiltInFunction; use crate::sema::Recurse; use num_bigint::BigInt; use solang_parser::pt; use solang_parser::pt::{CodeLocation, StorageLocation}; use std::sync::Arc; #[derive(Debug, Clone)] pub struct InlineAssemb...
use crate::ast::{Parameter, Type}; use crate::sema::symtable::Symtable; use crate::sema::yul::builtin::YulBuiltInFunction; use crate::sema::Recurse; use num_bigint::BigInt; use solang_parser::pt; use solang_parser::pt::{CodeLocation, StorageLocation}; use std::sync::Arc; #[derive(Debug, Clone)] pub struct InlineAssemb...
parent_sol_func: Option<usize>, pub func_no: usize, pub called: bool, pub cfg_no: usize, } #[derive(Clone, Debug)] pub enum YulStatement { FunctionCall(pt::Loc, bool, usize, Vec<YulExpression>), BuiltInCall(pt::Loc, bool, YulBuiltInFunction, Vec<YulExpression>), Block(Box<YulBlock>), Varia...
; name.to_string() } } impl CodeLocation for YulExpression { fn loc(&self) -> pt::Loc { match self { YulExpression::BoolLiteral(loc, ..) | YulExpression::NumberLiteral(loc, ..) | YulExpression::StringLiteral(loc, ..) | YulExpression::YulLocalVari...
random
[ { "content": "fn bigint_to_expression(loc: &Loc, ty: &Type, n: BigInt) -> (Expression, bool) {\n\n let n = match ty {\n\n Type::Uint(bits) => {\n\n if n.bits() > *bits as u64 {\n\n let (_, mut bs) = n.to_bytes_le();\n\n bs.truncate(*bits as usize / 8);\n\n\n\n ...
Rust
src/hir/translation/into_mir.rs
emmanuel099/specbmc
d5a8a1446f3626e7a36736cafb2615da361836a5
use crate::error::Result; use crate::expr::{Boolean, Expression, Memory}; use crate::hir; use crate::ir::TryTranslateInto; use crate::mir; const NUMBER_OF_SELF_COMPOSITIONS: usize = 2; impl TryTranslateInto<mir::Program> for hir::InlinedProgram { fn try_translate_into(&self) -> Result<mir::Program> { let ...
use crate::error::Result; use crate::expr::{Boolean, Expression, Memory}; use crate::hir; use crate::ir::TryTranslateInto; use crate::mir; const NUMBER_OF_SELF_COMPOSITIONS: usize = 2; impl TryTranslateInto<mir::Program> for hir::InlinedProgram { fn try_translate_into(&self) -> Result<mir::Program> { let ...
fn transition_condition(edge: &hir::Edge) -> Result<Expression> { let pred_exec_cond = mir::Block::execution_condition_variable_for_index(edge.head()); match edge.condition() { Some(condition) => Boolean::and(pred_exec_cond.into(), condition.clone()), None => Ok(pred_exec_cond.into()), } ...
fn translate_operation(operation: &hir::Operation) -> Result<Option<mir::Node>> { use hir::Operation::*; let node = match operation { Assign { variable, expr } => Some(mir::Node::assign(variable.clone(), expr.clone())?), Assert { condition } => Some(mir::Node::assert(condition.clone())?), ...
function_block-full_function
[ { "content": "fn low_equivalent(block: &mut Block, expr: Expression) {\n\n block.indistinguishable(expr).labels_mut().pseudo();\n\n}\n", "file_path": "src/hir/transformation/init_memory.rs", "rank": 0, "score": 323599.11429753224 }, { "content": "fn low_equivalent(block: &mut Block, expr:...
Rust
2019-05-09-wasm-sands/src/text/parser.rs
vain0x/playground
76338f96ac0e449613f3fe55082a26f65e85944d
use super::*; use std::cell::Cell; use std::cmp::min; use std::mem::replace; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) struct EventId(usize); pub(crate) enum Event { Error(String), Start { kind: SynKind }, Token, Finish, } pub(crate) enum EventData { Error(Str...
use super::*; use std::cell::Cell; use std::cmp::min; use std::mem::replace; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) struct EventId(usize); pub(crate) enum Event { Error(String), Start { kind: SynKind }, Token, Finish, } pub(crate) enum EventData { Error(Str...
lf.nth_kind(2)) } pub(crate) fn nth_text(&self, offset: usize) -> &str { let i = self.index + offset; if i >= self.tokens.len() { return ""; } let (l, r) = self.spans[i]; &self.text[l..r] } pub(crate) fn advance(&mut self, offset: usize) { l...
ndex + offset; if i >= self.tokens.len() { return TokenKind::Eof; } self.tokens[i].kind } pub(crate) fn next(&self) -> TokenKind { self.nth_kind(0) } pub(crate) fn next2(&self) -> (TokenKind, TokenKind) { (self.nth_kind(0), self.nth_kind(1)) } ...
random
[ { "content": "fn inspect<'a>(text: &'a str, tokens: &'a [Token]) -> Vec<&'a str> {\n\n let mut out = Vec::with_capacity(tokens.len());\n\n let mut r = 0;\n\n\n\n for token in tokens {\n\n let l = r;\n\n r += token.len;\n\n\n\n if token.kind == TokenKind::Whitespace || token.kind ==...
Rust
examples/drag/src/main.rs
notriddle/stdweb
9b418d98df6fafaa4d4b87b04c304d0220292055
#[macro_use] extern crate stdweb; use std::sync::{Arc, Mutex}; use stdweb::traits::*; use stdweb::web::{ document, IParentNode, }; use stdweb::web::event::{ DataTransfer, DataTransferItemKind, DragOverEvent, DragStartEvent, DragDropEvent, EffectAllowed, DropEffect, }; use stdweb::un...
#[macro_use] extern crate stdweb; use std::sync::{Arc, Mutex}; use stdweb::traits::*; use stdweb::web::{ document, IParentNode, }; use stdweb::web::event::{ DataTransfer, DataTransferItemKind, DragOverEvent, DragStartEvent, DragDropEvent, EffectAllowed, DropEffect, }; use stdweb::un...
ate_element("div").unwrap(); js!(@{div.as_ref()}.innerHTML = "content of dataTransfer.items:"); dropzone().append_child(&div); for x in e.data_transfer().unwrap().items() { let div = document().create_element("div").unwrap(); let kind_str = match x.kind() { ...
k().unwrap(), &*team_b.lock().unwrap()); } fn drop_filesystem_example() { let dropzone = || document().query_selector("#filesystem-dropzone").unwrap().unwrap(); dropzone().add_event_listener(move |e: DragOverEvent| { e.prevent_default(); js!(@{e.as_ref()}.currentTarget.style.backgroundColor = "...
random
[ { "content": "pub fn test< F: FnOnce() + 'static >( name: &str, callback: F ) {\n\n eprintln!( \"Running test '{}'...\", name );\n\n let result = js!(\n\n try {\n\n @{Once( callback )}();\n\n } catch( exception ) {\n\n process.stderr.write( exception + \"\\n\" );\n\n ...
Rust
src/graphic_interface/im_gui_wrapper.rs
erwan-b/game-of-life
02f3c19fe9b6d1ec6bbdff8f8a1a622dd5180237
use ggez::event::{ MouseButton }; use ggez::graphics; use ggez::Context; use gfx_core::{handle::RenderTargetView, memory::Typed}; use gfx_device_gl; use imgui::*; use imgui_gfx_renderer::*; use std::time::{Instant, Duration}; use std::ops::RangeInclusive; #[derive(Copy, Clone, PartialEq, Debug, Default)] struct Mou...
use ggez::event::{ MouseButton }; use ggez::graphics; use ggez::Context; use gfx_core::{handle::RenderTargetView, memory::Typed}; use gfx_device_gl; use imgui::*; use imgui_gfx_renderer::*; use std::time::{Instant, Duration}; use std::ops::RangeInclusive; #[derive(Copy, Clone, PartialEq, Debug, Default)] struct Mou...
_ => () } } pub fn update_mouse_down(&mut self, button: MouseButton) { match button { MouseButton::Left => self.mouse_state.pressed.0 = true, MouseButton::Right => self.mouse_state.pressed.1 = true, MouseButton::Middle => self.mouse_state.pressed.2 = true, ...
on { MouseButton::Left => self.mouse_state.pressed.0 = false, MouseButton::Right => self.mouse_state.pressed.1 = false, MouseButton::Middle => self.mouse_state.pressed.2 = false,
function_block-random_span
[ { "content": "pub fn create_map_from_file(file_path: &str) -> Box<Board> {\n\n let lines = fs::read_to_string(file_path)\n\n .expect(\"Something went wrong reading the file\");\n\n\n\n Box::new(Board::new(MAP_SIZE, lines.trim().lines().collect()))\n\n}\n\n\n", "file_path": "src/lib.rs", "ra...
Rust
program/tests/test_utils/mod.rs
Lightprotocol/light-protocol-program
9230a38975f6c6c279781c756f62572bfcfa847c
#[cfg(test)] #[allow(dead_code)] pub mod tests { use ark_bn254; use ark_ed_on_bn254; use ark_std::vec::Vec; use ark_ec; use ark_ff::bytes::FromBytes; use ark_ff::Fp256; use ark_ff::QuadExtField; use ark_groth16::{prepare_inputs, prepare_verifying_key}; use ark_ec::*; use light_...
#[cfg(test)] #[allow(dead_code)] pub mod tests { use ark_bn254; use ark_ed_on_bn254; use ark_std::vec::Vec; use ark_ec; use ark_ff::bytes::FromBytes; use ark_ff::Fp256; use ark_ff::QuadExtField; use ark_groth16::{prepare_inputs, prepare_verifying_key}; use ark_ec::*; use light_...
pub async fn create_and_start_program_var( accounts: &Vec<(&Pubkey, usize, Option<Vec<u8>>)>, token_accounts: Option<&mut Vec<(&Pubkey, &Pubkey, u64)>>, program_id: &Pubkey, signer_pubkey: &Pubkey, ) -> ProgramTestContext { let mut program_test = ProgramTest::new( ...
balance: u64, ) { let mut token_account_data = vec![0u8; spl_token::state::Account::LEN]; let token_account_state = spl_token::state::Account { mint, owner, amount: balance, state: spl_token::state::AccountState::Initialized, is_native: COp...
function_block-function_prefix_line
[ { "content": "pub fn init_coeffs1(r_range: &mut Vec<u8>, proof_range: &mut Vec<u8>) -> Result<(), ProgramError> {\n\n let proof_b = parse_proof_b_from_bytes(proof_range);\n\n let r: ark_ec::models::bn::g2::G2HomProjective<ark_bn254::Parameters> =\n\n ark_ec::models::bn::g2::G2HomProjective {\n\n ...
Rust
software/src/read.rs
jdisanti/FlashProgrammer
b82f9b62221d4a97389cab9777183f01cae59e5b
use std::path::Path; use std::io::prelude::*; use std::fs::File; use byteorder::ReadBytesExt; use error::*; use constants::*; use progress::ProgressReporter; use serial_port; pub fn read_rom<P: AsRef<Path>>(device: &str, output_path: P) -> Result<()> { let mut serial_port = serial_port::open(device)?; ...
use std::path::Path; use std::io::prelude::*; use std::fs::File; use byteorder::ReadBytesExt; use error::*; use constants::*; use progress::ProgressReporter; use serial_port; pub fn read_rom<P: AsRef<Path>>(device: &str, output_path: P) -> Result<()> { let mut serial_port = serial_port::open(device)?; ...
} rom_contents.extend(block.iter()); } progress_reporter.finish(""); Ok(()) } fn push_address(buffer: &mut Vec<u8>, address: usize) { buffer.push((address >> 16) as u8); buffer.push((address >> 8) as u8); buffer.push(address as u8); } fn generate_read_command(start_...
if failures < MAX_FAILURES { println!("Checksum verification failed. Retrying block"); failures += 1; } else { return Err("Failed to read block too many times. Giving up".into()); }
if_condition
[ { "content": "/// Reads the first 128KiB of a file into a Vec, or if the file is\n\n/// not that large, reads the entire file and pads it with zeroes\n\n/// until it is the desired length.\n\nfn read_rom_file<P: AsRef<Path>>(input_path: P) -> Result<Vec<u8>> {\n\n let file = File::open(input_path.as_ref())\n...
Rust
rust/k210-shared/src/board/lcd.rs
lizhirui/k210-sdk-stuff
ff064f596fae0d5494a58f8541b8ef096315a26f
use crate::soc::gpio; use crate::soc::gpiohs; use crate::soc::sleep::usleep; use crate::soc::spi::{SPI,work_mode,frame_format,aitm,tmod}; use crate::soc::dmac::{DMAC,dma_channel}; pub const SPI_CS: u32 = 3; pub const DCX_GPIONUM: u8 = 2; pub const RST_GPIONUM: u8 = 3; pub const LCD_X_MAX: u16 = 240; pub const LCD_Y_M...
use crate::soc::gpio; use crate::soc::gpiohs; use crate::soc::sleep::usleep; use crate::soc::spi::{SPI,work_mode,frame_format,aitm,tmod}; use crate::soc::dmac::{DMAC,dma_channel}; pub const SPI_CS: u32 = 3; pub const DCX_GPIONUM: u8 = 2; pub const RST_GPIONUM: u8 = 3; pub const LCD_X_MAX: u16 = 240; pub const LCD_Y_M...
fn write_word(&self, data_buf: &[u32]) { self.set_dcx_data(); self.spi.configure( work_mode::MODE0, frame_format::OCTAL, 32, /*data bits*/ 0, /*endian*/ 0, /*instruction length*/ 32, /*address length*/ 0, /*wait...
fn write_half(&self, data_buf: &[u32]) { self.set_dcx_data(); self.spi.configure( work_mode::MODE0, frame_format::OCTAL, 16, /*data bits*/ 0, /*endian*/ 0, /*instruction length*/ 16, /*address length*/ 0, /*wait cycle...
function_block-full_function
[ { "content": "pub fn set_bit(inval: u32, bit: u8, state: bool) -> u32 {\n\n if state {\n\n inval | (1 << u32::from(bit))\n\n } else {\n\n inval & !(1 << u32::from(bit))\n\n }\n\n}\n\n\n", "file_path": "rust/k210-shared/src/soc/utils.rs", "rank": 0, "score": 354508.17039940227 ...
Rust
backend/db/src/calls/bucket.rs
hgzimmerman/FullstackRustDemo
b925cf8a157dc3ef22d85324332a814dcfbc634b
use chrono::{ NaiveDateTime, }; use crate::{ calls::prelude::*, schema::{ self, buckets, junction_bucket_users, }, user::User, }; use diesel::{ self, prelude::*, }; use error::BackendResult; use identifiers::{ bucket::BucketUuid, user::UserUuid, }; use uuid:...
use chrono::{ NaiveDateTime, }; use crate::{ calls::prelude::*, schema::{ self, buckets,
&PgConnection) -> BackendResult<Bucket> { use crate::schema::buckets::dsl::{ bucket_name as table_bucket_name, buckets, }; buckets .filter(table_bucket_name.eq(bucket_name)) .first::<Bucket>(conn) .map_err(handle_err::<Bucket>) } ...
junction_bucket_users, }, user::User, }; use diesel::{ self, prelude::*, }; use error::BackendResult; use identifiers::{ bucket::BucketUuid, user::UserUuid, }; use uuid::Uuid; #[derive(Debug, Clone, Identifiable, Queryable, TypeName)] #[primary_key(uuid)] #[table_name = "buckets"] pub s...
random
[ { "content": "#[get(\"/<bucket_uuid>\")]\n\nfn get_bucket(bucket_uuid: BucketUuid, user: NormalUser, conn: Conn) -> BackendResult<Json<BucketResponse>> {\n\n // If the user isn't approved then return a 403.\n\n if !Bucket::is_user_approved(user.user_uuid, bucket_uuid, &conn) {\n\n let e = Error::No...
Rust
oars/src/constructors/bose.rs
afnanenayet/oars
7c342ffde3895643e5824e2f0ab0d7eec1f0da08
use crate::oa::{OAConstructor, OAResult, OA}; use crate::utils::{Integer, OarsError, OarsResult}; use ndarray::Array2; use num::pow; use oars_proc_macro::Checked; use primes::is_prime; #[cfg(feature = "parallel")] use rayon::prelude::*; #[cfg(feature = "parallel")] use crate::oa::ParOAConstructor; #[cfg(feature = "p...
use crate::oa::{OAConstructor, OAResult, OA}; use crate::utils::{Integer, OarsError, OarsResult}; use ndarray::Array2; use num::pow; use oars_proc_macro::Checked; use primes::is_prime; #[cfg(feature = "parallel")] use rayon::prelude::*; #[cfg(feature = "parallel")] use crate::oa::ParOAConstructor; #[cfg(feature = "p...
points .axis_iter_mut(Axis(1)) .into_par_iter() .enumerate() .for_each(|(col_idx, mut col)| { col.axis_iter_mut(Axis(0)) .into_iter() .enumerate() .for_each(|(row_idx, ...
- 2, )); initial_points .axis_iter_mut(Axis(1)) .into_par_iter() .enumerate() .for_each(|(col_idx, mut col)| { col.axis_iter_mut(Axis(0)) .into_iter() .enumerate() ...
function_block-random_span
[ { "content": "/// Given some orthogonal array struct, verify that the points are a valid orthogonal array as\n\n/// described by the parameters.\n\n///\n\n/// An orthogonal array is defined by four key parameters, and this function attempts to see\n\n/// if `points` matches up with the other parameters. This me...
Rust
src/registry/mod.rs
viccuad/policy-fetcher
b0a55566dc15d95dc97c0386a7e529c4d8e68f3f
use anyhow::{anyhow, Result}; use async_std::fs::File; use async_std::prelude::*; use async_trait::async_trait; use oci_distribution::{ client::{ Certificate as OciCertificate, CertificateEncoding, Client, ClientConfig, ClientProtocol as OciClientProtocol, ImageData, ImageLayer, }, manifest,...
use anyhow::{anyhow, Result}; use async_std::fs::File; use async_std::prelude::*; use async_trait::async_trait; use oci_distribution::{ client::{ Certificate as OciCertificate, CertificateEncoding, Client, ClientConfig, ClientProtocol as OciClientProtocol, ImageData, ImageLayer, }, manifest,...
} }
match image_content { Some(image_content) => { let mut file = File::create(destination).await?; file.write_all(&image_content[..]).await?; Ok(()) } None => Err(anyhow!("could not pull policy {}", url)), }
if_condition
[ { "content": "fn client_protocol(url: &Url, sources: &Sources) -> Result<ClientProtocol> {\n\n if let Some(certificates) = sources.source_authority(&host_and_port(url)?) {\n\n return Ok(ClientProtocol::Https(\n\n TlsVerificationMode::CustomCaCertificates(certificates),\n\n ));\n\n ...
Rust
tests/profdata.rs
xd009642/llvm-profparser
3fc9b79ebe3220adbafc10bc47873cbdefa66597
use llvm_profparser::{merge_profiles, parse, parse_bytes}; use pretty_assertions::assert_eq; use std::collections::HashSet; use std::ffi::OsStr; use std::fs::read_dir; use std::path::PathBuf; use std::process::Command; #[cfg(llvm_11)] fn get_data_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("t...
use llvm_profparser::{merge_profiles, parse, parse_bytes}; use pretty_assertions::assert_eq; use std::collections::HashSet; use std::ffi::OsStr; use std::fs::read_dir; use std::path::PathBuf; use std::process::Command; #[cfg(llvm_11)] fn get_data_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("t...
fn check_against_text(ext: &OsStr) { let data = get_data_dir(); let mut count = 0; for raw_file in read_dir(&data) .unwrap() .filter_map(|x| x.ok()) .filter(|x| x.path().extension().unwrap_or_default() == ext) { let llvm = Command::new("cargo") .current_dir(...
output() .expect("Failed to run profparser on file"); println!("{}", String::from_utf8_lossy(&rust.stderr)); assert_eq!(get_printout(&llvm.stdout), get_printout(&rust.stdout)); assert_eq!(get_printout(&llvm.stderr), get_printout(&rust.stderr)); } } if...
function_block-function_prefix_line
[ { "content": "fn parse_profile_names<'data, 'file>(\n\n section: &Section<'data, 'file>,\n\n) -> Result<Vec<String>, SectionReadError> {\n\n if let Ok(data) = section.data() {\n\n let mut bytes = &data[..];\n\n let mut res = vec![];\n\n while !bytes.is_empty() {\n\n let (ne...
Rust
src/builder.rs
DanCardin/corpus
618006d6cfa4acb056c20a7a180ebb47e5da693a
use crate::{root::RootLocation, Corpus, CorpusError}; use std::path::{Path, PathBuf}; pub struct CorpusBuilder { root_location: Option<RootLocation>, relative_path: Option<PathBuf>, name: Option<String>, extension: Option<String>, } impl Default for CorpusBuilder { fn default() -> Self { S...
use crate::{root::RootLocation, Corpus, CorpusError}; use std::path::{Path, PathBuf}; pub struct CorpusBuilder { root_location: Option<RootLocation>, relative_path: Option<PathBuf>, name: Option<String>, extension: Option<String>, } impl Default for CorpusBuilder { fn default() -> Self {
} impl CorpusBuilder { pub fn relative_to<P: Into<PathBuf>>(mut self, path: P) -> Self { self.relative_path = Some(path.into()); self } #[cfg(feature = "home")] pub fn relative_to_home(self) -> Result<Self, CorpusError> { let home_dir = ...
Self { root_location: None, relative_path: None, name: None, extension: None, } }
function_block-function_prefix_line
[ { "content": "/// Shorthand for constructing an empty builder.\n\npub fn builder() -> CorpusBuilder {\n\n CorpusBuilder::default()\n\n}\n", "file_path": "src/lib.rs", "rank": 0, "score": 56019.225437777524 }, { "content": "#[test]\n\nfn test_with_name() {\n\n let corpus = builder()\n\n...
Rust
iml-manager-cli/src/nginx.rs
intel-hpdd/-intel-manager-for-lustre
f8a6f61205b42cc62f4bbcb8d81214ad4f215cd6
use crate::error::ImlManagerCliError; use console::Term; use lazy_static::*; use regex::{Captures, Regex}; use std::{collections::HashMap, env, str}; use structopt::StructOpt; use tokio::fs; #[derive(Debug, StructOpt)] pub enum NginxCommand { #[structopt(name = "generate-config")] GenerateConfig { ...
use crate::error::ImlManagerCliError; use console::Term; use lazy_static::*; use regex::{Captures, Regex}; use std::{collections::HashMap, env, str}; use structopt::StructOpt; use tokio::fs; #[derive(Debug, StructOpt)] pub enum NginxCommand { #[structopt(name = "generate-config")] GenerateConfig { ...
#[cfg(test)] mod tests { use super::*; use insta::*; use std::collections::HashMap; #[test] fn test_replace_template_variables() { let template: &[u8] = include_bytes!("../../chroma-manager.conf.template"); let vars: HashMap<String, String> = [ ("REPO_PATH", "/var/lib...
t(); iml_tracing::tracing::debug!("Nginx Config: {}", config); term.write_line(&config).unwrap(); } } }; Ok(()) }
function_block-function_prefixed
[ { "content": "/// Gets the environment variable or panics\n\n/// # Arguments\n\n///\n\n/// * `name` - Variable to read from the environment\n\npub fn get_var(name: &str) -> String {\n\n env::var(name).unwrap_or_else(|_| panic!(\"{} environment variable is required.\", name))\n\n}\n\n\n", "file_path": "im...
Rust
program/src/instructions/deposit.rs
Wildebeest/askbid
c20250c8551f6ec079ba8835d23b0a77b0d5e0d9
use super::{ResultAccount, SearchMarketAccount, SearchMarketInstruction}; use crate::LAMPORTS_PER_TOKEN; use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ account_info::{next_account_info, AccountInfo}, clock::Clock, entrypoint::ProgramResult, instruction::{AccountMeta, Instruction}, ...
use super::{ResultAccount, SearchMarketAccount, SearchMarketInstruction}; use crate::LAMPORTS_PER_TOKEN; use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ account_info::{next_account_info, AccountInfo}, clock::Clock, entrypoint::ProgramResult, instruction::{AccountMeta, Instruction}, ...
}
async fn test_deposit() { let program_id = crate::id(); let mut program_test = ProgramTest::new("askbid", program_id, processor!(process_instruction)); let decision_authority = Keypair::new(); let market = SearchMarketAccount::new(decision_authority.pubkey(), "cy...
function_block-full_function
[ { "content": "pub fn withdraw(program_id: &Pubkey, accounts: &[AccountInfo], amount: u64) -> ProgramResult {\n\n let account_info_iter = &mut accounts.iter();\n\n let market_account_info = next_account_info(account_info_iter)?;\n\n let result_account_info = next_account_info(account_info_iter)?;\n\n ...
Rust
src/asrc/asrc_cfg.rs
ldicocco/rsl10-pac
007871e940fe30f83de1da0f15fd25b052d1f340
#[doc = "Reader of register ASRC_CFG"] pub type R = crate::R<u32, super::ASRC_CFG>; #[doc = "Writer for register ASRC_CFG"] pub type W = crate::W<u32, super::ASRC_CFG>; #[doc = "Register ASRC_CFG `reset()`'s with value 0"] impl crate::ResetValue for super::ASRC_CFG { type Type = u32; #[inline(always)] fn re...
#[doc = "Reader of register ASRC_CFG"] pub type R = crate::R<u32, super::ASRC_CFG>; #[doc = "Writer for register ASRC_CFG"] pub type W = crate::W<u32, super::ASRC_CFG>; #[doc = "Register ASRC_CFG `reset()`'s with value 0"] impl crate::ResetValue for super::ASRC_CFG { type Type = u32; #[inline(always)] fn re...
ways)] pub fn asrc_mode(&self) -> ASRC_MODE_R { ASRC_MODE_R::new((self.bits & 0x03) as u8) } } impl W { #[doc = "Bit 2 - WDF Type Selection"] #[inline(always)] pub fn wdf_type(&mut self) -> WDF_TYPE_W { WDF_TYPE_W { w: self } } #[doc = "Bits 0:1 - ASRC mode"] #[inline(alw...
32) & 0x03); self.w } } impl R { #[doc = "Bit 2 - WDF Type Selection"] #[inline(always)] pub fn wdf_type(&self) -> WDF_TYPE_R { WDF_TYPE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bits 0:1 - ASRC mode"] #[inline(al
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/track/constraint/non_numeric.rs
alugha/media
14af20bd62a02f4a9d22b93163037798b6040fe6
use crate::track::constraint::Fitness; #[derive(PartialEq, Eq, Clone, Debug)] pub enum NonNumericKind<T> { Exists { is_expected: bool }, Exactly { value: T }, AnyOf { values: Vec<T>, ideal: Option<T> }, } #[derive(PartialEq, Eq, Clone, Debug)] pub struct NonNumeric<T> { is_required: bool, kind: No...
use crate::track::constraint::Fitness; #[derive(PartialEq, Eq, Clone, Debug)] pub enum NonNumericKind<T> { Exists { is_expected: bool }, Exactly { value: T }, AnyOf { values: Vec<T>, ideal: Option<T> }, } #[derive(PartialEq, Eq, Clone, Debug)] pub struct NonNumeric<T> { is_required: bool, kind: No...
, Some("x"), false, None), 1.0); assert_eq!(fitness(vec!["x"], Some("x"), false, Some("x")), 0.0); assert_eq!(fitness(vec!["x"], Some("x"), true, None), f64::INFINITY); assert_eq!(fitness(vec!["x"], Some("x"), true, Some("x")), 0.0); assert_eq!(fitness(vec!["o"], None, false, None), 1.0)...
h actual { Some(actual) => values.contains(actual), None => false, }; (is_match, ideal.as_ref()) } }; if !is_match { if self.is_required { return f64::INFINITY; } else { ...
random
[ { "content": "#[derive(PartialEq, Clone, Debug)]\n\nenum MediaKind {\n\n Audio(audio::Audio),\n\n Video(video::Video),\n\n}\n\n\n", "file_path": "src/track/constraint/mod.rs", "rank": 0, "score": 80406.0553717463 }, { "content": "fn is_key_frame(data: &[u8]) -> bool {\n\n if data.le...
Rust
src/lib.rs
ConsoleTVs/Procedure
ed5bc784a2f783e6e59b08f3d4bdf17510ab09fb
extern crate yansi; use std::fmt::Display; use std::io::{stdout, Write}; use std::ops::FnOnce; use yansi::Paint; const DEFAULT_PADDING: usize = 12; pub struct Progress<'a> { action: &'a str, description: &'a str, padding: usize, value: u8, } impl<'a> Progress<'a> { pub f...
extern crate yansi; use std::fmt::Display; use std::io::{stdout, Write}; use std::ops::FnOnce; use yansi::Paint; const DEFAULT_PADDING: usize = 12; pub struct Progress<'a> { action: &'a str, description: &'a str, padding: usize, value: u8, } impl<'a> Progress<'a> { pub f...
} pub fn proceed<F, R, D, E>(action: &str, description: &str, function: F) -> Result<R, E> where F: FnOnce(&mut Progress) -> Result<(R, D), E>, D: Display, E: Display, { proceed_padded(action, description, function, DEFAULT_PADDING) } pub fn proceed_padded<F, R, D, E>( action: &str, descripti...
y, { println!( "\r{:>3$} [{:>3}%] {:<4$}", Paint::red(self.action), self.value, error, self.padding, self.description.len() ); }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn example() {\n\n let a = proceed(\n\n \"Download\",\n\n \"example_file.jpg\",\n\n |progress: &mut Progress| -> Result<(&str, &str), &str> {\n\n for _ in 0..100 {\n\n std::thread::sleep(std::time::Duration::from_millis(10));\n\n ...
Rust
benches/hyphenate.rs
Cryptjar/hyphenation
255b56de271df513a063b10b4179b67cd0d57de9
#[macro_use] extern crate lazy_static; extern crate bincode; extern crate criterion; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; extern crate hyphenation; use hyphenation::extended::*; use hyphenation::Language::*; ...
#[macro_use] extern crate lazy_static; extern crate bincode; extern crate criterion; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; extern crate hyphenation; use hyphenation::extended::*; use hyphenation::Language::*; ...
fn opportunities_grc_overlong(c : &mut Criterion) { lazy_static::initialize(&EN_US); c.bench_function("overlong, GRC", |b| { b.iter(|| GRC.opportunities(black_box(OVERLONG_GRC))) }); } criterion_group!(single_word, hyphenate_en_us, opportunities_en_us, ...
n) { lazy_static::initialize(&EN_US); c.bench_function("overlong, en-US", |b| { b.iter(|| EN_US.opportunities(black_box(OVERLONG_EN_US))) }); }
function_block-function_prefixed
[ { "content": "fn shifts(word : &str) -> Vec<Shift> {\n\n word.match_indices(\"İ\")\n\n .map(|(i, _)| (i, -1))\n\n .scan(0, |delta, (i, d)| {\n\n let index = i as isize + *delta;\n\n *delta += d;\n\n Some(Shift { index : index as usize, delta : *delta })\n\n ...
Rust
src/orderchaos/controller.rs
raybritton/rust_games_proto
5268bf7d37836d7e7bc1038ebbf49abdee1c649e
use crate::boards::cursor::Cursor; use crate::boards::idx_coord::BoardCoord; use crate::boards::set_board_size; use crate::constants::{AI_MOVE_DELAY, ANIMATION_DURATION}; use crate::orderchaos::ai::process; use crate::orderchaos::renderer::render; use crate::orderchaos::Square::Empty; use crate::orderchaos::{Mode, Squa...
use crate::boards::cursor::Cursor; use crate::boards::idx_coord::BoardCoord; use crate::boards::set_board_size; use crate::constants::{AI_MOVE_DELAY, ANIMATION_DURATION}; use crate::orderchaos::ai::process; use crate::orderchaos::renderer::render; use crate::orderchaos::Square::Empty; use crate::orderchaos::{Mode, Squa...
fn render(&mut self, ctx: &mut Context, mesh_helper: &mut MeshHelper) -> GameResult<()> { render(ctx, mesh_helper, &self.state) } fn play_state(&self) -> PlayState { self.state.play_state } }
te.play_state.is_computer(SelectingMove) { self.state.next_move_time -= delta; if self.state.next_move_time < 0. { self.process_move(); self.state.cursor.idx = self.state.last_human_cursor_pos; self.state.move_cursor = self.state.last_human_placed....
function_block-function_prefixed
[ { "content": "fn check_all_horz(board: &Board, start: usize, piece: Square) -> bool {\n\n check_all(board, start, start + 1, start + 2, piece)\n\n}\n", "file_path": "src/tictactoe/controller.rs", "rank": 0, "score": 292670.9500922634 }, { "content": "fn check_all_vert(board: &Board, start...
Rust
src/main.rs
niladic/csv-exec
55ac3959f67ef481c5e11b86d2fc8c7f308234e8
use anyhow::{anyhow, Context, Result}; use clap::{App, Arg}; use regex::{Captures, Regex}; use std::{fs, io, process}; include!(concat!(env!("OUT_DIR"), "/buildinfo.rs")); struct Config { pub input_path: Option<String>, pub output_path: Option<String>, pub exec: String, pub no_headers: bool, pub d...
use anyhow::{anyhow, Context, Result}; use clap::{App, Arg}; use regex::{Captures, Regex}; use std::{fs, io, process}; include!(concat!(env!("OUT_DIR"), "/buildinfo.rs")); struct Config { pub input_path: Option<String>, pub output_path: Option<String>, pub exec: String, pub no_headers: bool, pub d...
fn run(config: Config) -> Result<()> { let reader: Box<dyn io::Read> = match config.input_path { None => Box::new(io::stdin()), Some(path) => Box::new(fs::File::open(&path).context(format!("Failed to open {}", path))?), }; let writer: Box<dyn io::Write> = match config.output_path { ...
e), ) .arg( Arg::with_name("new-column-name") .long("new-column-name") .value_name("STRING") .default_value("Result") .help("Name of the new column which contains the results") .takes_value(true), ) ...
function_block-function_prefixed
[ { "content": "fn main() {\n\n let out_dir = env::var(\"OUT_DIR\").unwrap();\n\n let dest_path = Path::new(&out_dir).join(\"buildinfo.rs\");\n\n let build_consts = format!(\n\n r#\"\n\n const BUILDINFO_VERSION: &str = \"{}\";\n\n \"#,\n\n env::var(\"CARGO_PKG_VERSION\").unwra...
Rust
nog/src/platform/win/window.rs
TimUntersberger/nogv2
80f3b8b68fd4475e1e3a23afc87033c6b2eaa7a6
use std::ffi::c_void; use std::{mem, ptr}; use windows::Windows::Win32::Foundation::{HWND, LPARAM, PWSTR, RECT, WPARAM}; use windows::Windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Windows::Win32::UI::WindowsAndMessaging::{ GetClassNameW, GetClientRect, GetSystemM...
use std::ffi::c_void; use std::{mem, ptr}; use windows::Windows::Win32::Foundation::{HWND, LPARAM, PWSTR, RECT, WPARAM}; use windows::Windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Windows::Win32::UI::WindowsAndMessaging::{ GetClassNameW, GetClientRect, GetSystemM...
fn focus(&self) { unsafe { keybd_event(0, 0, Default::default(), 0); SetForegroundWindow(self.0); } } fn exists(&self) -> bool { unsafe { IsWindow(self.0).into() } } fn close(&self) { unsafe { SendNotifyMessageW(self.0, WM_SYSCO...
size.height = (size.height as isize + frame_rect.bottom - frame_rect.top) as usize; unsafe { SetWindowPos( self.0, HWND(HWND_NOTOPMOST), 0, 0, size.width as i32, size.heig...
function_block-function_prefix_line
[ { "content": "pub fn run<A, E, C, F: Fn(&winit::window::Window) + ?Sized>(\n\n settings: Settings<A::Flags>,\n\n compositor_settings: C::Settings,\n\n after_window_created: Option<Box<F>>,\n\n) -> Result<(), Error>\n\nwhere\n\n A: Application + 'static,\n\n E: Executor + 'static,\n\n C: window...
Rust
immunoprot/src/ig_like/kir_ligand.rs
bjohnnyd/fs-tool
0b9231a9c092a0cbcc2d8cfefc76947d42a47bbf
use std::collections::{HashMap, HashSet}; use std::str::FromStr; use crate::error::{HtmlParseError, IoError, NomenclatureError}; use crate::mhc::hla::ClassI; use log::info; use scraper::{Html, Selector}; type Result<T> = std::result::Result<T, NomenclatureError>; pub const IPD_KIR_URL: &str = "https://www.ebi.ac.u...
use std::collections::{HashMap, HashSet}; use std::str::FromStr; use crate::error::{HtmlParseError, IoError, NomenclatureError}; use crate::mhc::hla::ClassI; use log::info; use scraper::{Html, Selector}; type Result<T> = std::result::Result<T, NomenclatureError>; pub const IPD_KIR_URL: &str = "https://www.ebi.ac.u...
#[test] fn test_create_ligand_map() { let loci = ["A*02:07", "B*57:01", "C*01:02"]; let ligand_map = KirLigandMap::from_loci(&loci).unwrap(); let mut motifs = Vec::<LigandMotif>::new(); let mut expected: Vec<LigandMotif> = vec![ "Unclassified".parse().unwrap(), ...
fn test_connect_to_ipd() { let html = get_ipd_html("C*01:02").unwrap(); let ligand_info = read_table(&html, 1).unwrap(); let expected = KirLigandInfo::new( "C01:02:01:01".parse::<ClassI>().unwrap(), LigandMotif::C1, AlleleFreq::Common, ); asse...
function_block-full_function
[ { "content": "pub fn get_netmhc_entry_info(i: &str) -> IResult<&str, (usize, ClassI, &str)> {\n\n let (remainder, (pos, _, allele, pep_seq)) = tuple((\n\n take_first_numeric,\n\n take_until(\"HLA-\"),\n\n take_hla_allele,\n\n take_word,\n\n ))(i)?;\n\n\n\n // Shifts position...
Rust
src/config.rs
cat-in-136/sendmail-into-mbox
c1fd7ace36565f30c597840c2288ee11169efd6c
use crate::error::Error as AppError; use fs2::FileExt; use serde::Deserialize; use std::fs::OpenOptions; use std::io::Read; use std::path::Path; const DEFAULT_CONFIG_FILE_PATH: &'static str = concat!("/etc/", env!("CARGO_PKG_NAME"), ".toml"); #[derive(PartialEq, Eq, Deserialize, Debug)] pub struct Config { p...
use crate::error::Error as AppError; use fs2::FileExt; use serde::Deserialize; use std::fs::OpenOptions; use std::io::Read; use std::path::Path; const DEFAULT_CONFIG_FILE_PATH: &'static str = concat!("/etc/", env!("CARGO_PKG_NAME"), ".toml"); #[derive(PartialEq, Eq, Deserialize, Debug)] pub struct Config { p...
} Self::new_from_toml_file(&path) } pub fn new_from_toml_file<P: AsRef<Path>>(path: P) -> Result<Self, AppError> { let path = path.as_ref(); let toml_str = OpenOptions::new() .read(true) .open(path) .and_then(|mut file| { ...
if unix::is_world_writable_ancestors(&path).unwrap_or(false) { return Err(AppError::ConfigFileWorldWritable( path.clone().to_path_buf(), )); }
if_condition
[ { "content": "fn main() {\n\n sendmail_main().unwrap_or_else(|e| {\n\n eprintln!(\"Error: {}\", e);\n\n exit(1);\n\n });\n\n}\n", "file_path": "src/main.rs", "rank": 0, "score": 21269.50790559847 }, { "content": "fn sendmail_main() -> Result<(), AppError> {\n\n let con...
Rust
crates/rslint_lsp/src/provider/diagnostics.rs
zaida04/RSLint
05c9939d16aa45b24c3acd222e31917d49ad301a
use crate::core::{document::Document, session::Session}; use codespan_lsp::byte_span_to_range; use codespan_reporting::diagnostic::LabelStyle; use itertools::Itertools; use rayon::prelude::*; use rslint_core::{apply_top_level_directives, run_rule, DirectiveParser}; use rslint_parser::SyntaxNode; use std::{collections...
use crate::core::{document::Document, session::Session}; use codespan_lsp::byte_span_to_range; use codespan_reporting::diagnostic::LabelStyle; use itertools::Itertools; use rayon::prelude::*; use rslint_core::{apply_top_level_directives, run_rule, DirectiveParser}; use rslint_parser::SyntaxNode; use std::{collections...
?; related_information.push(DiagnosticRelatedInformation { location: Location { uri: uri.clone(), range, }, message: label.message.clone(), }); } if let Some(primary_label) = primary_label {...
match byte_span_to_range(&files, file_id, label.range.clone()) { Err(codespan_lsp::Error::ColumnOutOfBounds { max, .. }) => { let start = std::cmp::min(max, label.range.start); let end = std::cmp::min(max, label.range.end); byte_span_to_range(&...
if_condition
[]
Rust
nebari/src/tree/root.rs
mwatts/nebari
480ffc87d51b3fbbedc1c7415e5ec8ee8e4f4659
use std::{ any::Any, borrow::Cow, collections::HashMap, fmt::{Debug, Display}, marker::PhantomData, ops::RangeBounds, path::Path, sync::Arc, }; use crate::{ error::Error, io::{File, ManagedFile}, roots::AnyTransactionTree, transaction::{TransactionId, TransactionManager}...
use std::{ any::Any, borrow::Cow, collections::HashMap, fmt::{Debug, Display}, marker::PhantomData, ops::RangeBounds, path::Path, sync::Arc, }; use crate::{ error::Error, io::{File, ManagedFile}, roots::AnyTransactionTree, transaction::{TransactionId, TransactionManager}...
fn default_state(&self) -> Box<dyn AnyTreeState>; fn begin_transaction( &self, transaction_id: TransactionId, file_path: &Path, state: &dyn AnyTreeState, context: &Context<File::Manager>, transactions: Option<&TransactionManager<File::Manager>>, ) -> Res...
s KeyRangeBounds, args: &mut ScanArgs< Self::Value, Self::Index, Self::ReducedIndex, CallerError, NodeEvaluator, KeyEvaluator, ScanDataCallback, >, file: &mut dyn File, vault: Option<&dyn AnyVault>, ...
random
[]
Rust
src/runtime/mod.rs
alexander-jackson/mongo-rust-driver
b26f23ccaecbff427a85d009ec161de16ee18824
mod async_read_ext; mod async_write_ext; mod http; #[cfg(feature = "async-std-runtime")] mod interval; mod join_handle; mod resolver; mod stream; use std::{future::Future, net::SocketAddr, time::Duration}; pub(crate) use self::{ async_read_ext::AsyncLittleEndianRead, async_write_ext::AsyncLittleEndianWrite, ...
mod async_read_ext; mod async_write_ext; mod http; #[cfg(feature = "async-std-runtime")] mod interval; mod join_handle; mod resolver; mod stream; use std::{future::Future, net::SocketAddr, time::Duration}; pub(crate) use self::{ async_read_ext::AsyncLittleEndianRead, async_write_ext::AsyncLittleEndianWrite, ...
} }
match self { #[cfg(feature = "tokio-runtime")] Self::Tokio => { let socket_addrs = tokio::net::lookup_host(format!("{}", address)).await?; Ok(socket_addrs) } #[cfg(feature = "async-std-runtime")] Self::AsyncStd => { ...
if_condition
[ { "content": "fn default_hosts() -> Vec<StreamAddress> {\n\n vec![StreamAddress {\n\n hostname: \"localhost\".to_string(),\n\n port: Some(27017),\n\n }]\n\n}\n\n\n\nimpl Default for ClientOptions {\n\n fn default() -> Self {\n\n Self::builder().build()\n\n }\n\n}\n\n\n", "fi...
Rust
src/helpers.rs
mlang/oauth2-rs
07d32d4947095a95390b9c57dfc569ee947dbfae
use std; use serde::ser; use serde::ser::{Impossible, SerializeStructVariant, SerializeTupleVariant}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use url::Url; pub fn deserialize_untagged_enum_case_insensitive<'de, T, D>(deserializer: D) -> Result<T, D::Error> where T: Deserialize<'de>, D: ...
use std; use serde::ser; use serde::ser::{Impossible, SerializeStructVariant, SerializeTupleVariant}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use url::Url; pub fn deserialize_untagged_enum_case_insensitive<'de, T, D>(deserializer: D) -> Result<T, D::Error> where T: Deserialize<'de>, D: ...
e_newtype_variant<T: ?Sized + Serialize>( self, _name: &'static str, _variant_index: u32, variant: &'static str, _value: &T, ) -> Result<Self::Ok> { Ok(variant) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::S...
ng( String::deserialize(deserializer)?.to_lowercase(), )) .map_err(Error::custom) } pub fn deserialize_space_delimited_vec<'de, T, D>(deserializer: D) -> Result<T, D::Error> where T: Default + Deserialize<'de>, D: Deserializer<'de>, { use serde::de::Error; use serde_json::Value; if ...
random
[ { "content": "///\n\n/// Trait for adding extra fields to the `TokenResponse`.\n\n///\n\npub trait ExtraTokenFields: DeserializeOwned + Debug + Serialize {}\n\n\n\n///\n\n/// Empty (default) extra token fields.\n\n///\n\n#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]\n\npub struct EmptyExtraTokenFie...
Rust
storage/aptosdb/src/ledger_store/mod.rs
magnum6actual/aptos-core
aa4684d1f634d6b7698d508581068c4eb75ef0d6
use crate::{ change_set::ChangeSet, errors::AptosDbError, schema::{ epoch_by_version::EpochByVersionSchema, ledger_counters::LedgerCountersSchema, ledger_info::LedgerInfoSchema, transaction_accumulator::TransactionAccumulatorSchema, transaction_info::TransactionInfoSchema, }, }...
use crate::{ change_set::ChangeSet, errors::AptosDbError, schema::{ epoch_by_version::EpochByVersionSchema, ledger_counters::LedgerCountersSchema, ledger_info::LedgerInfoSchema, transaction_accumulator::TransactionAccumulatorSchema, transaction_info::TransactionInfoSchema, }, }...
pub fn get_frozen_subtree_hashes(&self, num_transactions: LeafCount) -> Result<Vec<HashValue>> { Accumulator::get_frozen_subtree_hashes(self, num_transactions) } pub fn get_startup_info(&self) -> Result<Option<StartupInfo>> { let latest_ledger_info = match self.get_latest_ledger_...
pub fn get_tree_state( &self, num_transactions: LeafCount, transaction_info: TransactionInfo, ) -> Result<TreeState> { Ok(TreeState::new( num_transactions, self.get_frozen_subtree_hashes(num_transactions)?, transaction_info.state_change_hash(), ...
function_block-full_function
[ { "content": "fn create_test_ledger_info_with_sigs(epoch: u64, version: u64) -> LedgerInfoWithSignatures {\n\n // Create a mock ledger info with signatures\n\n let ledger_info = LedgerInfo::new(\n\n BlockInfo::new(\n\n epoch,\n\n 0,\n\n HashValue::zero(),\n\n ...
Rust
tools/qemu-runner/src/main.rs
leeehui/tock
4864f0300e9ded35f0521f43baec579207f344b5
use std::process::Command; use rexpect::errors::Error; use rexpect::session::PtySession; use rexpect::spawn; fn kill_qemu(p: &mut PtySession) -> Result<(), Error> { p.send_control('a')?; p.send("x")?; p.flush()?; Ok(()) } fn hifive1() -> Result<(), Error> { let mut build = Command...
use std::process::Command; use rexpect::errors::Error; use rexpect::session::PtySession; use rexpect::spawn;
fn hifive1() -> Result<(), Error> { let mut build = Command::new("make") .arg("-C") .arg("../../boards/hifive1") .spawn() .expect("failed to spawn build"); assert!(build.wait().unwrap().success()); let mut p = spawn("make qemu -C ../../boards/hifive1", Some(...
fn kill_qemu(p: &mut PtySession) -> Result<(), Error> { p.send_control('a')?; p.send("x")?; p.flush()?; Ok(()) }
function_block-full_function
[ { "content": "use arty_e21_chip;\n\nuse core::fmt::Write;\n\nuse core::panic::PanicInfo;\n\nuse core::str;\n\nuse kernel::debug;\n\nuse kernel::debug::IoWrite;\n\nuse kernel::hil::gpio;\n\nuse kernel::hil::led;\n\nuse rv32i;\n\nuse sifive;\n\n\n\nuse crate::CHIP;\n\nuse crate::PROCESSES;\n\nuse crate::PROCESS_P...
Rust
crates/vm/src/native/java_io_UnixFileSystem.rs
douchuan/jvm
5678df31a13ec56faa0daddb561d34ae2def8f1d
#![allow(non_snake_case)] use crate::native::{new_fn, JNIEnv, JNINativeMethod, JNIResult}; use crate::oop::{Class, Oop, OopPtr}; use crate::runtime::require_class3; use crate::{new_br, util}; use std::fs; static mut FILE_PATH: usize = 0; const BA_EXISTS: i32 = 0x01; const BA_REGULAR: i32 = 0x02; const BA_DIRECTORY: ...
#![allow(non_snake_case)] use crate::native::{new_fn, JNIEnv, JNINativeMethod, JNIResult}; use crate::oop::{Class, Oop, OopPtr}; use crate::runtime::require_class3; use crate::{new_br, util}; use std::fs; static mut FILE_PATH: usize = 0; const BA_EXISTS: i32 = 0x01; const BA_REGULAR: i32 = 0x02; const BA_DIRECTORY: ...
0 } }; Ok(Some(Oop::new_int(v))) } fn get_File_path(file: &Oop) -> String { let offset = unsafe { FILE_PATH }; let path = Class::get_field_value2(file.extract_ref(), offset); OopPtr::java_lang_string(path.extract_ref()) }
.write(true) .create(true) .open(&path) { Ok(_) => 1, Err(e) => { error!("open {}, error = {:?}", path, e);
function_block-random_span
[ { "content": "pub fn new_java_lang_string2(v: &str) -> Oop {\n\n //build \"char value[]\"\n\n let chars: Vec<u16> = v.as_bytes().iter().map(|v| *v as u16).collect();\n\n let ary = Oop::char_ary_from1(chars.as_slice());\n\n\n\n //new String(char value[])\n\n let string_cls = require_class3(None, b...
Rust
src/cron_evaluator.rs
j5ik2o/chronos-parser-rs
171f8f4f701de591e0a8da8d5ff0f07f66c9da69
use chrono::{Datelike, DateTime, NaiveDate, Timelike, TimeZone}; use crate::Expr; pub struct CronEvaluator<'a, Tz: TimeZone> { instant: &'a DateTime<Tz>, } pub struct Environment { now: u8, max: u8, } impl Environment { pub fn new(now: u8, max: u8) -> Self { Self { now, max } } } fn get_days_from_mon...
use chrono::{Datelike, DateTime, NaiveDate, Timelike, TimeZone}; use crate::Expr; pub struct CronEvaluator<'a, Tz: TimeZone> { instant: &'a DateTime<Tz>, } pub struct Environment { now: u8, max: u8, } impl Environment { pub fn new(now: u8, max: u8) -> Self { Self { now, max } } } fn get_days_from_mon...
8, 12), months, ); let fday_of_weeks = self.visit0( &Environment::new(self.instant.time().minute() as u8, 7), day_of_weeks, ); fmins && fhours && fdays && fmonths && fday_of_weeks } _ => false, } } fn visit1(&self, env: &Environment, ast...
, }, 1, ) .signed_duration_since(NaiveDate::from_ymd(year, month, 1)) .num_days() } impl<'a, Tz: TimeZone> CronEvaluator<'a, Tz> { pub fn new(instant: &'a DateTime<Tz>) -> Self { Self { instant } } pub fn eval(&self, ast: &Expr) -> bool { match ast { Expr::CronExpr { box mins...
random
[ { "content": "fn month_digit<'a>() -> Parser<'a, u8, Expr> {\n\n (sym(b'1') + one_of(b\"012\")).map(|(e1, e2)| ValueExpr((e1 - 48) * 10 + e2 - 48))\n\n | (sym(b'0') * one_of(b\"123456789\")).map(|e| ValueExpr(e - 48))\n\n | one_of(b\"123456789\").map(|e| ValueExpr(e - 48))\n\n}\n\n\n", "file_path": "...
Rust
cranelift/codegen/meta/src/cdsl/regs.rs
eust-dfinity/wasmtime
8bec21c5183ccdbf2f4d4c13763c8c1777009725
use cranelift_codegen_shared::constants; use cranelift_entity::{entity_impl, EntityRef, PrimaryMap}; #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub(crate) struct RegBankIndex(u32); entity_impl!(RegBankIndex); pub(crate) struct RegBank { pub name: &'static str, pub first_unit: u8, pub uni...
use cranelift_codegen_shared::constants; use cranelift_entity::{entity_impl, EntityRef, PrimaryMap}; #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub(crate) struct RegBankIndex(u32); entity_impl!(RegBankIndex); pub(crate) struct RegBank { pub name: &'static str, pub first_unit: u8, pub uni...
re_tracking, pinned_reg, toprcs: Vec::new(), classes: Vec::new(), } } fn unit_by_name(&self, name: &'static str) -> u8 { let unit = if let Some(found) = self.names.iter().position(|&reg_name| reg_name == name) { found } else { ...
ned_reg: Option<u16>, ) -> Self { RegBank { name, first_unit, units, names, prefix, pressu
function_block-random_span
[ { "content": "pub fn is_wasi_module(name: &str) -> bool {\n\n // FIXME: this should be more conservative, but while WASI is in flux and\n\n // we're figuring out how to support multiple revisions, this should do the\n\n // trick.\n\n name.starts_with(\"wasi\")\n\n}\n\n\n", "file_path": "crates/w...
Rust
sqlx-macros/src/query/input.rs
JCapucho/sqlx
a31bd17f360c173c7814ae0e071ea10ce52e7a84
use std::fs; use proc_macro2::{Ident, Span}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::{Expr, LitBool, LitStr, Token}; use syn::{ExprArray, Type}; pub struct QueryMacroInput { pub(super) src: String, #[cfg_attr(not(feature = "offline"), allow(dead_code))] pub(super) ...
use std::fs; use proc_macro2::{Ident, Span}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::{Expr, LitBool, LitStr, Token}; use syn::{ExprArray, Type}; pub struct QueryMacroInput { pub(super) src: String, #[cfg_attr(not(feature = "offline"), allow(dead_code))] pub(super) ...
query_src = Some((QuerySrc::String(query_str), span)); } else if key == "source_file" { let lit_str = input.parse::<LitStr>()?; query_src = Some((QuerySrc::File(lit_str.value()), lit_str.span())); } else if key == "args" { let exprs =...
prs: Vec<Expr>, pub(super) checked: bool, } enum QuerySrc { String(String), File(String), } pub enum RecordType { Given(Type), Scalar, Generated, } impl Parse for QueryMacroInput { fn parse(input: ParseStream) -> syn::Result<Self> { let mut query_src: Option<(QuerySrc, Span)> = N...
random
[ { "content": "#[proc_macro_derive(Type, attributes(sqlx))]\n\npub fn derive_type(tokenstream: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(tokenstream as syn::DeriveInput);\n\n match derives::expand_derive_type_encode_decode(&input) {\n\n Ok(ts) => ts.into(),\n\n Err...
Rust
src/sources/statsd/mod.rs
nkinkade/vector
c3cc8daa82e6b464c2ecd0c47655ec1b22f4cce2
use crate::{ config::{self, GlobalOptions}, internal_events::{StatsdEventReceived, StatsdInvalidRecord, StatsdSocketError}, shutdown::ShutdownSignal, Event, Pipeline, }; use futures::{ compat::{Future01CompatExt, Sink01CompatExt}, stream, FutureExt, StreamExt, TryFutureExt, }; use futures01::Sin...
use crate::{ config::{self, GlobalOptions}, internal_events::{StatsdEventReceived, StatsdInvalidRecord, StatsdSocketError}, shutdown::ShutdownSignal, Event, Pipeline, }; use futures::{ compat::{Future01CompatExt, Sink01CompatExt}, stream, FutureExt, StreamExt, TryFutureExt, }; use futures01::Sin...
.lines() .collect::<Vec<_>>(); assert_eq!(parse_count(&lines, "vector_set"), 0); socket.send_to(b"set:0|s\nset:1|s\n", &in_addr).unwrap(); delay_for(Duration::from_millis(10)).await; delay_for...
1|s\n", &in_addr, ) .unwrap(); delay_for(Duration::from_millis(10)).await; } delay_for(Duration::from_millis(100)).await; let client = hyper::Client::new(); let response = client .get(form...
function_block-random_span
[ { "content": "fn vector_with_address(config: &str, address: SocketAddr) -> Command {\n\n let mut cmd = Command::cargo_bin(\"vector\").unwrap();\n\n cmd.arg(\"-c\")\n\n .arg(create_file(config))\n\n .arg(\"--quiet\")\n\n .env(\"VECTOR_DATA_DIR\", create_directory())\n\n .env(\"V...
Rust
data_types/src/job.rs
e-dard/influxdb_iox
38f94a309591f46b0af383f608be939fa6e9d125
use std::sync::Arc; use serde::{Deserialize, Serialize}; use crate::chunk_metadata::ChunkAddr; use crate::partition_metadata::PartitionAddr; #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum Job { Dummy { db_name: Option<Arc<str>>, nanos: Vec<u64>, }, CompactCh...
use std::sync::Arc; use serde::{Deserialize, Serialize}; use crate::chunk_metadata::ChunkAddr; use crate::partition_metadata::PartitionAddr; #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum Job { Dummy { db_name: Option<Arc<str>>, nanos: Vec<u64>, }, CompactCh...
} } #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum OperationStatus { Running, Success, Cancelled, Errored, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Operation { pub id: usize, pub total_count: u64, pub pend...
match self { Self::Dummy { .. } => "Dummy Job, for testing", Self::CompactChunk { .. } => "Compacting chunk to ReadBuffer", Self::WriteChunk { .. } => "Writing chunk to Object Storage", Self::CompactChunks { .. } => "Compacting chunks to ReadBuffer", Self::Per...
if_condition
[ { "content": "/// The db name to use for testing\n\npub fn db_name() -> &'static str {\n\n \"db1\"\n\n}\n\n\n", "file_path": "parquet_file/src/test_utils.rs", "rank": 0, "score": 268860.97636265366 }, { "content": "/// Compares the protobuf type URL found within a google.protobuf.Any\n\n/...
Rust
services/j1939d/src/main.rs
oats-center/isoblue-avena
807cbcd572a340d45ce7140828c8db5cf51a50bc
mod j1939; use anyhow::Context; use canparse::pgn::{ParseMessage, PgnLibrary}; use j1939::J1939Socket; use serde_json::json; use clap::{crate_authors, crate_description, crate_name, crate_version, App, Arg}; use prometheus::{ core::{AtomicF64, GenericGauge}, opts, register_gauge, Encoder, TextEncoder, }; us...
mod j1939; use anyhow::Context; use canparse::pgn::{ParseMessage, PgnLibrary}; use j1939::J1939Socket; use serde_json::json; use clap::{crate_authors, crate_description, crate_name, crate_version, App, Arg}; use prometheus::{ core::{AtomicF64, GenericGauge}, opts, register_gauge, Encoder, TextEncoder, }; us...
let nats_sub_prefix = matches .value_of("nats_sub_prefix") .with_context(|| "NATS subject prefix not provided?")?; let prom_listen = matches .value_of("prom_listen") .with_context(|| "Prom listen not provided?")? .to_owned(); let dbc_file = matches .v...
let nats_server = matches .value_of("nats_server") .with_context(|| "NATS connection string not provided")?;
assignment_statement
[ { "content": "fn is_u64(num: String) -> Result<(), String> {\n\n match num.parse::<u64>() {\n\n Ok(_) => Ok(()),\n\n Err(_) => Err(format!(\"Must be a positive integer\")),\n\n }\n\n}\n\n\n\n/*\n", "file_path": "services/gps-exporter/src/main.rs", "rank": 0, "score": 159608.58875...
Rust
src/atcoder.rs
mouri111/kunai
c2692a3435e264cc8e832e76a3593d2d77f64c4a
use crate::scraping::*; use reqwest::header::{HeaderMap, HeaderValue, COOKIE}; use reqwest::{self, ClientBuilder}; use scraper::{Html, Selector}; use std::io::Write; use std::path::{Path, PathBuf}; pub fn get_tests_from_html(html: &str) -> Result<Vec<(String, String)>, ()> { let document = Html::parse_document(htm...
use crate::scraping::*; use reqwest::header::{HeaderMap, HeaderValue, COOKIE}; use reqwest::{self, ClientBuilder}; use scraper::{Html, Selector}; use std::io::Write; use std::path::{Path, PathBuf}; pub fn get_tests_from_html(html: &str) -> Result<Vec<(String, String)>, ()> { let document = Html::parse_document(htm...
pub fn login(username: &str, password: &str) -> Result<(), ()> { let client = ClientBuilder::new().cookie_store(true).build().unwrap(); let mut login_page_response = client.get("https://atcoder.jp/login").send().unwrap(); let login_page_text = login_page_response.text().unwrap(); let mut cookies = vec...
esult<String, ()> { let cookies = load_session_cookie(); let client = ClientBuilder::new().cookie_store(true).build().unwrap(); let mut cookie_headers = HeaderMap::new(); for cookie in cookies { cookie_headers.insert(COOKIE, HeaderValue::from_str(&cookie).unwrap()); } let mut response = ...
function_block-function_prefixed
[ { "content": "pub fn judge(binname: &str, testdir: &PathBuf, timelimit: &Duration) -> Vec<(JudgeResult, String)> {\n\n eprintln!(\"testdir = {:?}\", testdir);\n\n let mut res = vec![];\n\n for entry in\n\n glob(&format!(\"{}/*.in\", testdir.to_str().unwrap())).expect(\"Failed to read glob patter...
Rust
src/parse.rs
m-cat/loch
f2e7674c2b4158094b7bdc9aab4e6cb4fc56b129
use lazy_static::lazy_static; use regex::Regex; pub fn get_urls(line: &str, no_http: bool) -> Vec<&str> { lazy_static! { static ref FORBIDDEN: &'static str = r##" "'<>\^`\{\|\}"##; static ref INVALID: String = { let mut invalid = FORBIDDEN.to_string(); invalid.push_str(r##"\...
use lazy_static::lazy_static; use regex::Regex; pub fn get_urls(line: &str, no_http: bool) -> Vec<&str> { lazy_static! { static ref FORBIDDEN: &'static str = r##" "'<>\^`\{\|\}"##; static ref INVALID: String = { let mut invalid = FORBIDDEN.to_string(); invalid.push_str(r##"\...
]); test_parse!( "./ test./ test.test() example.com/index", &["example.com/index"] ); test_parse!("www.google.com", none); test_parse!("https://www.google.com/", &["https://www.google.com/"]); test_parse!( "goog.com/~page~, www.google.com/....
test_parse!("[https://www.test.com]", &["https://www.test.com"]); test_parse!( "[http://test.asdfasdf/](http://www.test.com)", &["http://test.asdfasdf/", "http://www.test.com"], ); test_parse!( "(http://test)(http:///example)", &["http://test"...
random
[]
Rust
libs/csgo/src/logs.rs
rufus-stone/csgop-rs
a9dc76494581ead08ba66cc0c510ee532213621b
use std::fs::{File, Metadata}; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; pub struct Reader { log_dir_path: PathBuf, active_log: Option<PathBuf>, fm: Option<Metadata>, pos: usize, } impl Reader { pub fn new(log_dir_path: &Path) -> Reader { Reader { ...
use std::fs::{File, Metadata}; use std::io::{BufReader, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; pub struct Reader { log_dir_path: PathBuf, active_log: Option<PathBuf>, fm: Option<Metadata>, pos: usize, } impl Reader { pub fn new(log_dir_path: &Path) -> Reader { Reader { ...
}
else { log::info!( "Opened active log file '{}'", latest_file.as_ref().unwrap().display() ); self.active_log = latest_file.clone(); } let fd = match File::open(self.active_log.as_ref().unwrap()) { Ok(result) => { ...
function_block-function_prefix_line
[]
Rust
src/server/grpc.rs
seabird-irc/seabird-core
37204c2e3e6a27eb6153f291cb01044f8584352b
use std::time::{SystemTime, UNIX_EPOCH}; use futures::future::{select, Either}; use futures::StreamExt; use tonic::{Request, Response}; use crate::prelude::*; use proto::{seabird::seabird_server::Seabird, ChatEventInner, EventInner}; use super::auth::extract_auth_username; #[async_trait] impl Seabird for Arc<super...
use std::time::{SystemTime, UNIX_EPOCH}; use futures::future::{select, Either}; use futures::StreamExt; use tonic::{Request, Response}; use crate::prelude::*; use proto::{seabird::seabird_server::Seabird, ChatEventInner, EventInner}; use super::auth::extract_auth_username; #[async_trait] impl Seabird for Arc<super...
, metadata: metadata.values, })), ChatEventInner::Failed(failed) => Err(Status::unknown(failed.reason)), _ => Err(Status::internal("unexpected chat event")), } } async fn list_channels( &self, req: Request<proto::ListChannelsRequest>, ...
Some(proto::Backend { id: backend_id.to_string(), r#type: backend_id.scheme.clone(), })
call_expression
[ { "content": "pub fn extract_auth_username<T>(req: &Request<T>) -> RpcResult<String> {\n\n Ok(req\n\n .metadata()\n\n .get(X_AUTH_USERNAME)\n\n .ok_or_else(|| Status::internal(\"missing auth username\"))?\n\n .to_str()\n\n .map_err(|_| Status::internal(\"failed to decode au...
Rust
c-scape/src/fs/stat.rs
carbotaniuman/mustang
be0cb593120f6ef45956278e9690fa8b9fdd3f42
use rustix::fd::BorrowedFd; use rustix::ffi::ZStr; use rustix::fs::AtFlags; use core::convert::TryInto; use errno::{set_errno, Errno}; use libc::{c_char, c_int, time_t}; use crate::convert_res; fn rustix_stat_to_libc_stat( rustix_stat: rustix::fs::Stat, ) -> Result<libc::stat, std::num::TryFromIntError> { ...
use rustix::fd::BorrowedFd; use rustix::ffi::ZStr; use rustix::fs::AtFlags; use core::convert::TryInto; use errno::{set_errno, Errno}; use libc::{c_char, c_int, time_t}; use crate::convert_res; fn rustix_stat_to_libc_stat( rustix_stat: rustix::fs::Stat, ) -> Result<libc::stat, std::num::TryFromIntError> { ...
libc!(libc::fstat64(fd, checked_cast!(stat_))); let stat_: *mut rustix::fs::Stat = checked_cast!(stat_); match convert_res(rustix::fs::fstat(&BorrowedFd::borrow_raw(fd))) { Some(r) => { *stat_ = r; 0 } None => -1, } }
function_block-function_prefixed
[ { "content": "#[cfg(not(target_os = \"wasi\"))]\n\nfn init_from_envp(envp: *mut *mut c_char) {\n\n unsafe {\n\n environ = envp;\n\n }\n\n}\n\n\n\n#[no_mangle]\n\nstatic mut environ: *mut *mut c_char = null_mut();\n\n\n\n// Threads\n", "file_path": "c-scape/src/lib.rs", "rank": 0, "score...
Rust
src/renderer/sprite_renderer.rs
martinlindhe/rg3d
c8fd1908e6a15902a6f89c918fed3e77de683074
use crate::{ core::{math::Rect, scope_profile}, renderer::{ error::RendererError, framework::{ framebuffer::{CullFace, DrawParameters, FrameBuffer, FrameBufferTrait}, gl, gpu_program::{GpuProgram, UniformLocation, UniformValue}, gpu_texture::GpuTex...
use crate::{ core::{math::Rect, scope_profile}, renderer::{ error::RendererError, framework::{ framebuffer::{CullFace, DrawParameters, FrameBuffer, FrameBufferTrait}, gl, gpu_program::{GpuProgram, UniformLocation, UniformValue}, gpu_texture::GpuTex...
} else { white_dummy.clone() }; statistics += framebuffer.draw( geom_map.get(state, &self.surface), state, viewport, &self.shader.program, DrawParameters { cull_face:...
if let Some(texture) = textures.get(state, texture) { texture } else { white_dummy.clone() }
if_condition
[]
Rust
fog/ledger/server/src/untrusted_tx_out_service.rs
iamalwaysuncomfortable/mobilecoin
9d7f88efe181ee498c07f62767ff56aed18a032c
use core::convert::TryFrom; use grpcio::{RpcContext, RpcStatus, UnarySink}; use mc_common::logger::{log, Logger}; use mc_crypto_keys::CompressedRistrettoPublic; use mc_fog_api::{ ledger::{TxOutRequest, TxOutResponse, TxOutResult, TxOutResultCode}, ledger_grpc::FogUntrustedTxOutApi, }; use mc_ledger_db::{self...
use core::convert::TryFrom; use grpcio::{RpcContext, RpcStatus, UnarySink}; use mc_common::logger::{log, Logger}; use mc_crypto_keys::CompressedRistrettoPublic; use mc_fog_api::{ ledger::{TxOutRequest, TxOutResponse, TxOutResult, TxOutResultCode}, ledger_grpc::FogUntrustedTxOutApi, }; use mc_ledger_db::{self...
r block {} due to error {:?}", block_index, err ); (u64::MAX, TimestampResultCode::WatcherDatabaseError) } }; result.block_index = block_index; result.timestamp = timestamp; resul...
rr| { log::error!( self.logger, "Unexpected error when getting block by tx out index {}: {}", tx_out_index, err ); err })?; let (timestamp, ts_result): (u64, Time...
function_block-random_span
[ { "content": "/// Identify a sequence of blocks that are safe to append to the local node's\n\n/// ledger.\n\n///\n\n/// A \"safe\" block satisfies:\n\n/// 1. A sufficient set of peers have externalized the block (aka\n\n/// \"potentially safe\"), 2. The block is part of a chain of safe blocks,\n\n/// r...
Rust
src/api/projects/pipelines/create.rs
kalzoo/rust-gitlab
f08c301293bf8267cd01f0892a89db8dba4f8cf6
use derive_builder::Builder; use crate::api::common::NameOrId; use crate::api::endpoint_prelude::*; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PipelineVariableType { EnvVar, File, } impl Default for PipelineVariableType { fn default() -> Self { Pipe...
use derive_builder::Builder; use crate::api::common::NameOrId; use crate::api::endpoint_prelude::*; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PipelineVariableType { EnvVar, File, } impl Default for PipelineVariableType { fn default() -> Self { Pipe...
#[test] fn endpoint() { let endpoint = ExpectedUrl::builder() .method(Method::POST) .endpoint("projects/simple%2Fproject/pipeline") .content_type("application/x-www-form-urlencoded") .body_str("ref=master") .build() .unwrap(); ...
fn project_and_ref_are_sufficient() { CreatePipeline::builder() .project(1) .ref_("testref") .build() .unwrap(); }
function_block-function_prefix_line
[ { "content": "/// Escape a string for usage as a single URL path component.\n\npub fn path_escaped(input: &'_ str) -> impl fmt::Display + '_ {\n\n utf8_percent_encode(input, PATH_SEGMENT_ENCODE_SET)\n\n}\n\n\n\nimpl<'a> fmt::Display for NameOrId<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Resu...
Rust
tokio-console/src/view/mini_histogram.rs
thombles/console
01ca5c4bdb0196f16b8cf8c108dd2b16dd57481b
use std::time::Duration; use tui::{ layout::Rect, style::Style, symbols, widgets::{Block, Widget}, }; pub(crate) struct MiniHistogram<'a> { block: Option<Block<'a>>, style: Style, data: &'a [u64], metadata: HistogramMetadata, max: Option<u64>, ...
use std::time::Duration; use tui::{ layout::Rect, style::Style, symbols, widgets::{Block, Widget}, }; pub(crate) struct MiniHistogram<'a> { block: Option<Block<'a>>, style: Style,
) { let max = match self.max { Some(v) => v, None => *self.data.iter().max().unwrap_or(&1u64), }; let max_index = std::cmp::min(area.width as usize, self.data.len()); let mut data = self .data .iter() .take(max_index) ...
data: &'a [u64], metadata: HistogramMetadata, max: Option<u64>, bar_set: symbols::bar::Set, duration_precision: usize, } #[derive(Debug, Default)] pub(crate) struct HistogramMetadata { pub(crate) max_value: u64, pub(crate) min_value: u64, pub(cr...
random
[ { "content": "fn fg_style(color: Color) -> Style {\n\n Style::default().fg(color)\n\n}\n\n\n\n// === impl Config ===\n\n\n\nimpl Styles {\n\n pub fn from_config(config: config::ViewOptions) -> Self {\n\n Self {\n\n palette: config.determine_palette(),\n\n toggles: config.toggl...
Rust
crates/swc_ecma_parser/src/lib.rs
mengxy/swc
bcc3ae86ae0732979f9fbfef370ae729ba9af080
#![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(test, feature(bench_black_box))] #![cfg_attr(test, feature(test))] #![deny(unused)] pub use self::{ lexer::input::{Input, StringInput}, parser::*, }; use serde::{Deserialize, Serialize}; use swc_ecma_ast::EsVersion; #[deprecated(note = "Use `EsVersion` inste...
#![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(test, feature(bench_black_box))] #![cfg_attr(test, feature(test))] #![deny(unused)] pub use self::{ lexer::input::{Input, StringInput}, parser::*, }; use serde::{Deserialize, Serialize}; use swc_ecma_ast::EsVersion; #[deprecated(note = "Use `EsVersion` inste...
pub fn private_in_object(self) -> bool { match self { Syntax::Es(EsConfig { private_in_object, .. }) => private_in_object, Syntax::Typescript(_) => true, } } pub(crate) fn early_errors(self) -> bool { match self { Syn...
pub fn dts(self) -> bool { match self { Syntax::Typescript(t) => t.dts, _ => false, } }
function_block-full_function
[]
Rust
sudachi-cli/src/main.rs
sorami/sudachi.rs
0e3462841f281472d149140481889a265bd12dd1
/* * Copyright (c) 2021 Works Applications Co., Ltd. * * 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 applica...
/* * Copyright (c) 2021 Works Applications Co., Ltd. * * 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 applica...
ct = JapaneseDictionary::from_cfg(&config) .unwrap_or_else(|e| panic!("Failed to create dictionary: {:?}", e)); let mut tokenizer = StatefulTokenizer::create(&dict, enable_debug, mode); let checker = NonBreakChecker::new(dict.lexicon()); let splitter = SentenceSplitter::with_limit(32 * 1024).with_ch...
(from_os_str))] config_file: Option<PathBuf>, #[structopt(short = "p", long = "resource_dir", parse(from_os_str))] resource_dir: Option<PathBuf>, #[structopt(short = "m", long = "mode", default_value = "C")] mode: String, #[structopt(short = "o", long = "output", parse(from_os_...
random
[ { "content": "type Writer = BufWriter<Box<dyn Write>>;\n\n\n", "file_path": "sudachi-cli/src/output.rs", "rank": 1, "score": 158410.2999627355 }, { "content": "// Mmap stores file handle, so file field may not be needed\n\n// but let it be here for the time being\n\nstruct FileMapping {\n\n ...
Rust
leaf/src/config/external_rule.rs
scottlaw/leaf
3968dfbbfab2f5f5263caff276e95685e76c6823
use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::path::Path; use anyhow::anyhow; use anyhow::Result; use super::{geosite, internal}; pub fn load_file_or_default(filter: &str, default: &str) -> Result<(String, String)> { let parts: Vec<&str> = filter.split(':').collect(); let (fil...
use std::collections::HashMap; use std::fs::File; use std::io::Read; use std::path::Path; use anyhow::anyhow; use anyhow::Result; use super::{geosite, internal}; pub fn load_file_or_default(filter: &str, default: &str) -> Result<(String, String)> { let parts: Vec<&str> = filter.split(':').collect(); let (fil...
; let mut buf = Vec::new(); match f.read_to_end(&mut buf) { Ok(_) => (), Err(e) => { return Err(anyhow!("reading dat file {} failed: {}", &file, e)); } } let site_group_lis...
match File::open(&file) { Ok(f) => f, Err(e) => { return Err(anyhow!("open dat file {} failed: {}", &file, e)); } }
if_condition
[ { "content": "pub fn from_file(path: &str) -> Result<internal::Config> {\n\n if let Some(ext) = Path::new(path).extension() {\n\n if let Some(ext) = ext.to_str() {\n\n match ext {\n\n #[cfg(feature = \"config-json\")]\n\n \"json\" => return json::from_file(path...
Rust
pre/src/ordering.rs
easbar/osm_ch
9b5cc85cbd0940c346fdb01ef7b7bdea81e11381
use super::*; pub fn node_degree(node: NodeId, up_offset: &[EdgeId], down_offset: &[EdgeId]) -> usize { up_offset[node + 1] - up_offset[node] + down_offset[node + 1] - down_offset[node] } #[allow(clippy::too_many_arguments)] fn edge_difference( node: NodeId, mut dijkstra: &mut dijkstra::Dijkstra, shor...
use super::*; pub fn node_degree(node: NodeId, up_offset: &[EdgeId], down_offset: &[EdgeId]) -> usize { up_offset[node + 1] - up_offset[node] + down_offset[node + 1] - down_offset[node] } #[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_arguments)] pub fn calculate_single_heuristic( node: NodeId, mut dijkstra: &mut dijkstra::Dijkstra, deleted_neighbors: &[Weight], shortcut_id: &AtomicUsize, edges: &[Way], up_offset: &[EdgeId], down_offset: &[EdgeId], down_index: &[EdgeId], rank: usize, ) -...
fn edge_difference( node: NodeId, mut dijkstra: &mut dijkstra::Dijkstra, shortcut_id: &AtomicUsize, edges: &[Way], up_offset: &[EdgeId], down_offset: &[EdgeId], down_index: &[EdgeId], rank: usize, ) -> isize { let shortcuts = contraction::calc_shortcuts( node, &mut di...
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\npub fn get_up_edge_ids(node: NodeId, up_offset: &[EdgeId]) -> Vec<EdgeId> {\n\n (up_offset[node]..up_offset[node + 1]).collect()\n\n}\n\n\n\n/// get all down edge-ids from one node\n", "file_path": "web/src/graph_helper.rs", "rank": 1, "score": 98548.093984069...
Rust
src/main.rs
ntdef/groupby
6fc275a3697c9a3306db6c56524e2417853a2014
use std::fs; use std::io::{BufReader, BufRead, Write}; #[macro_use] extern crate clap; use clap::{App,Arg}; mod process; use process::{Process, Group}; mod ranges; use ranges::Range; fn linekey(s : &str, separator : &str, indices : &[Range]) -> String { let mut fields = s.split(separator); let mut bufout = ...
use std::fs; use std::io::{BufReader, BufRead, Write}; #[macro_use] extern crate clap; use clap::{App,Arg}; mod process; use process::{Process, Group}; mod ranges; use ranges::Range; fn linekey(s : &str, separator : &str, indices : &[Range]) -> String { let mut fields = s.split(separator); let mut bufout = ...
prev = cur }, None => { process.push(Group::new(prev, buf.clone())); buf.clear(); break } } } for p in process.packets() { for line in p.data.unwrap().lines() { ...
if cur == prev || prev.is_empty() { buf.push_str(&line); buf.push('\n'); } else { process.push(Group::new(prev, buf.clone())); buf.clear(); buf.push_str(&line); buf.push('\n'); }
if_condition
[ { "content": " Command::new(\"sh\")\n\n .arg(\"-c\")\n\n .arg(cmd)\n\n .stdin(Stdio::piped())\n\n .stdout(Stdio::piped())\n\n .spawn()\n\n .unwrap();\n\n process.stdin.as_mut()\n\n ...
Rust
core/bin/zksync_api/src/fee_ticker/ticker_api/coingecko.rs
smishraIOV/ri-aggregation
abcd90954335b6ee8513876de0118f567d979a32
use super::{TokenPriceAPI, REQUEST_TIMEOUT}; use crate::fee_ticker::ticker_api::PriceError; use async_trait::async_trait; use chrono::{DateTime, NaiveDateTime, Utc}; use num::rational::Ratio; use num::BigUint; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::str::FromStr; u...
use super::{TokenPriceAPI, REQUEST_TIMEOUT}; use crate::fee_ticker::ticker_api::PriceError; use async_trait::async_trait; use chrono::{DateTime, NaiveDateTime, Utc}; use num::rational::Ratio; use num::BigUint; use reqwest::Url; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::str::FromStr; u...
} #[async_trait] impl TokenPriceAPI for CoinGeckoAPI { async fn get_price(&self, token: &Token) -> Result<TokenPrice, PriceError> { let start = Instant::now(); let token_id = self.token_ids.get(&token.address).ok_or_else(|| { PriceError::token_not_found(format!( "Token ...
s.insert(address, token.id); } } } } token_ids.insert(Address::default(), String::from("ethereum")); Ok(Self { base_url, client, token_ids, }) }
function_block-function_prefixed
[ { "content": "fn signing_failed_error(err: impl ToString) -> SignerError {\n\n SignerError::SigningFailed(err.to_string())\n\n}\n\n\n\npub struct Signer<S: EthereumSigner> {\n\n pub pubkey_hash: PubKeyHash,\n\n pub address: Address,\n\n pub(crate) private_key: PrivateKey,\n\n pub(crate) eth_signe...