lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/crawler.rs
parallaxisjones/crawlrs
e9844344feb36152758fd810b03b9cca58be4abd
use crate::api::crawl::CrawlOpts; use crate::client::FetchProvider; use crate::session_stats::SessionStats; use std::collections::HashSet; pub struct Crawler { pub options: CrawlOpts, client: Box<dyn FetchProvider>, visited: Box<HashSet<String>>, stats: SessionStats, } impl Crawler { pub fn new(cl...
use crate::api::crawl::CrawlOpts; use crate::client::FetchProvider; use crate::session_stats::SessionStats; use std::collections::HashSet; pub struct Crawler { pub options: CrawlOpts, client: Box<dyn FetchProvider>, visited: Box<HashSet<String>>, stats: SessionStats, } impl Crawler { pub fn new(cl...
self.visited.extend(self.options.urls.iter().cloned()); self.stats.add_visit(Some(self.options.urls.len() as u64)); let mut new_urls = found_urls .difference(&self.visited) .map(|x| x.to_string()) .collect::<HashSet<String>>(); while !new_urls.is_empt...
let mut found_urls = self .options .urls .iter() .map(|url| { let root_node = self.client.fetch(&url, &self.options).unwrap(); let links = root_node.get_links_from_html(); links }) .f...
assignment_statement
[ { "content": "pub fn crawl(craw_opts: CrawlOpts) {\n\n let client = Box::new(CrawlrsClient::new());\n\n let mut session = Crawler::new(client, craw_opts);\n\n let links = session.crawl();\n\n let mut sorted = links.iter().cloned().collect::<Vec<String>>();\n\n sorted.sort();\n\n serde_json::to...
Rust
backend/src/service/server.rs
flyingblackshark/blog-rs
fd11213cd89b188643ec2bba5013b3d56d234e16
use std::vec::Vec; use std::{collections::HashMap, convert::Infallible, net::SocketAddr}; use futures::future::Future; use hyper::{header::HeaderValue, HeaderMap, Uri}; use password_hash::Output; use tokio::sync::oneshot::Receiver; use warp::{self, reject, Filter, Rejection, Reply, Server, TlsServer}; use blog_common...
use std::vec::Vec; use std::{collections::HashMap, convert::Infallible, net::SocketAddr}; use futures::future::Future; use hyper::{header::HeaderValue, HeaderMap, Uri}; use password_hash::Output; use tokio::sync::oneshot::Receiver; use warp::{self, reject, Filter, Rejection, Reply, Server, TlsServer}; use blog_common...
routes.recover(facade::handle_rejection) }
let routes = index .or(asset) .or(get_upload) .or(management_settings) .or(management_login) .or(management_update_settings) .or(user_logout) .or(user_info) .or(verify_image) .or(random_title_image) .or(post_list) .or(tags_all) ...
assignment_statement
[]
Rust
src/connectivity/wlan/lib/mlme/rust/src/buffer.rs
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
use { crate::error::Error, std::{ ffi::c_void, ops::{Deref, DerefMut}, ptr, slice, }, }; #[repr(C)] pub struct BufferProvider { get_buffer: unsafe extern "C" fn(min_len: usize) -> InBuf, } impl BufferProvider { pub fn get_buffer(&self, min_len: usize) -> Re...
use { crate::error::Error, std::{ ffi::c_void, ops::{Deref, DerefMut}, ptr, slice, }, }; #[repr(C)] pub struct BufferProvider { get_buffer: unsafe extern "C" fn(min_len: usize) -> InBuf, } impl BufferProvider { pub fn get_buffer(&self, min_len: usize) -> Re...
#[test] fn as_slice_null_data() { let buf = InBuf { free_buffer: default_free_buffer, raw: 42 as *mut c_void, data: ptr::null_mut(), len: 10, }; assert_eq!(buf.as_slice(), []); } #[test] fn as_slice() { let mut data =...
fn return_out_of_scope_buffer() { static mut RETURNED_RAW_BUFFER: *mut c_void = ptr::null_mut(); unsafe extern "C" fn assert_free_buffer(raw: *mut c_void) { RETURNED_RAW_BUFFER = raw; } { InBuf { free_buffer: assert_free_buffer, ...
function_block-full_function
[]
Rust
crates/vx_client/src/debug.rs
vilunov/vx_bevy
7cfffc9a4a97e89ceb0c9bc9e7d235b77b585537
use crate::{input::Action, player::PlayerController, render::CHUNK_MESHING_TIME}; use bevy::{ diagnostic::{DiagnosticId, Diagnostics, FrameTimeDiagnosticsPlugin}, ecs::system::EntityCommands, prelude::*, }; use enum_iterator::IntoEnumIterator; use vx_core::{ config::GlobalConfig, world::{ChunkEntity...
use crate::{input::Action, player::PlayerController, render::CHUNK_MESHING_TIME}; use bevy::{ diagnostic::{DiagnosticId, Diagnostics, FrameTimeDiagnosticsPlugin}, ecs::system::EntityCommands, prelude::*, }; use enum_iterator::IntoEnumIterator; use vx_core::{ config::GlobalConfig, world::{ChunkEntity...
fn update_debug_values( mut counters: Query<(&mut Text, &DebugValue)>, player: Query<(&PlayerController, &Transform)>, config: Res<GlobalConfig>, ) { for (mut text, debug_cnt) in counters.iter_mut() { for (_, transform) in player.single() { match &debug_cnt { &Debug...
fn update_diagnostic_counters( diagnostics: ResMut<Diagnostics>, mut counter: Query<(&mut Text, &DiagnosticCounter)>, ) { for (mut text, counter) in counter.iter_mut() { if let Some(diag) = diagnostics.get(counter.0) { if let Some(avg) = diag.average() { text.sections[2]....
function_block-full_function
[ { "content": "fn setup(mut commands: Commands) {\n\n commands\n\n .spawn_bundle(PerspectiveCameraBundle {\n\n transform: Transform::from_xyz(0., 150.0, 0.0),\n\n ..Default::default()\n\n })\n\n .insert(Player)\n\n .insert(PlayerController::default());\n\n}\n"...
Rust
src/solution.rs
jgrosspietsch/nonogram-rs
477e211126c81b247ba112ebc7ba99f051dd1646
extern crate ndarray; use ndarray::Array1; use std::collections::{HashSet, VecDeque}; #[path = "state_grid.rs"] mod state_grid; #[path = "state_row.rs"] mod state_row; pub use state_grid::StateGrid; pub use state_row::StateRow; #[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)] pub enum CellState { Unknown, ...
extern crate ndarray; use ndarray::Array1; use std::collections::{HashSet, VecDeque}; #[path = "state_grid.rs"] mod state_grid; #[path = "state_row.rs"] mod state_row; pub use state_grid::StateGrid; pub use state_row::StateRow; #[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)] pub enum CellState { Unknown, ...
#[cfg(test)] mod tests { use super::{ common_row_indexes, enumerate_row_states, filter_invalid_row_states, CellState, StateRow, }; use ndarray::arr1; #[test] fn enumerate_row_states1() { let states = enumerate_row_states(5, &[1, 1, 1]); assert_eq!(states.len(), 1); } ...
pub fn common_row_indexes(states: &[StateRow]) -> Vec<(usize, CellState)> { let mut common_empty: Array1<usize> = Array1::zeros(states[0].0.len()); let mut common_filled: Array1<usize> = Array1::zeros(states[0].0.len()); for state in states { for i in 0..state.0.len() { match state.0[i]...
function_block-full_function
[ { "content": "fn build_clue(row: ArrayView1<u8>) -> Vec<usize> {\n\n let mut clue: Vec<usize> = Vec::new();\n\n\n\n row.into_iter()\n\n .cloned()\n\n .collect::<Vec<u8>>()\n\n .split(|cell| *cell == 0u8)\n\n .for_each(|segment| {\n\n if !segment.is_empty() {\n\n ...
Rust
src/database.rs
sacooper/Copper
0240a0060fb2f84b3026d2aff4f07b5c843b2308
use rustc_serialize::json::{self, Json, ToJson}; use rand::{thread_rng, Rng}; use mmap::{MemoryMap, MapOption}; use std::fs; use std::io::{Write, SeekFrom, Seek}; use std::io::Error as IOError; use std::os::unix::prelude::AsRawFd; use std::collections::{HashMap, VecDeque, BTreeMap}; use std::mem; use std::sync::{Arc,...
use rustc_serialize::json::{self, Json, ToJson}; use rand::{thread_rng, Rng}; use mmap::{MemoryMap, MapOption}; use std::fs; use std::io::{Write, SeekFrom, Seek}; use std::io::Error as IOError; use std::os::unix::prelude::AsRawFd; use std::collections::{HashMap, VecDeque, BTreeMap}; use std::mem; use std::sync::{Arc,...
log.push_back(Entry::Insert(obj)); Ok(()) } fn gen_random_id() -> String { thread_rng().gen_ascii_chars().filter(|c| c.is_alphanumeric()).take(15).collect::<String>() } fn load_datab...
if let Json::Object(ref mut map) = obj { map.insert("_id".to_string(), Json::String(Database::gen_random_id())); } else { unimplemented!(); }
if_condition
[ { "content": "fn copy_log(temp_lock: &mut Arc<RwLock<File>>, log: &mut Box<VecDeque<Entry>>){\n\n let mut temp = temp_lock.write().unwrap();\n\n for entry in log.iter() {\n\n temp.write(&(json::encode(entry).unwrap().into_bytes()));\n\n temp.write(\"\\n\".as_bytes());\n\n }\n\n}\n\n\n", ...
Rust
tests/direnv/direnvtestcase.rs
sveitser/lorri
e68e0f51a864b746372555b7f5482977c6e9556d
use lorri::{ build_loop::{BuildError, BuildLoop, BuildResults}, ops::direnv, project::Project, roots::Roots, }; use std::collections::HashMap; use std::fs::File; use std::io::Write; use std::path::PathBuf; use std::process::Command; use tempfile::{tempdir, TempDir}; pub struct DirenvTestCase { te...
use lorri::{ build_loop::{BuildError, BuildLoop, BuildResults}, ops::direnv, project::Project, roots::Roots, }; use std::collections::HashMap; use std::fs::File; use std::io::Write; use std::path::PathBuf; use std::process::Command; use tempfile::{tempdir, TempDir}; pub struct DirenvTestCase { te...
let result = allow.status().expect("Failed to run direnv allow"); assert!(result.success()); } let mut env = self.direnv_cmd(); env.args(&["export", "json"]); let result = env.output().expect("Failed to run direnv allow"); assert!(result.status.success()...
ect_root.join(".envrc")) .unwrap() .write_all(shell.as_bytes()) .unwrap(); { let mut allow = self.direnv_cmd(); allow.arg("allow");
random
[ { "content": "/// See the documentation for lorri::cli::Command::Shell for more\n\n/// details.\n\npub fn main(project: Project) -> OpResult {\n\n let (tx, rx) = channel();\n\n let root_nix_file = &project.expression();\n\n let roots = Roots::new(project.gc_root_path().unwrap(), project.id());\n\n l...
Rust
tests/integration.rs
Windfisch/mcp49xx-rs
2127940b6954626f5f90d3d3f7870e2a085edf1a
extern crate mcp49xx; use mcp49xx::{Channel, Command, Error}; extern crate embedded_hal_mock as hal; use self::hal::spi::Transaction as SpiTrans; mod base; use base::{ new_mcp4801, new_mcp4802, new_mcp4811, new_mcp4812, new_mcp4821, new_mcp4822, new_mcp4901, new_mcp4902, new_mcp4911, new_mcp4912, new_mcp4921, n...
extern crate mcp49xx; use mcp49xx::{Channel, Command, Error}; extern crate embedded_hal_mock as hal; use self::hal::spi::Transaction as SpiTrans; mod base; use base::{ new_mcp4801, new_mcp4802, new_mcp4811, new_mcp4812, new_mcp4821, new_mcp4822, new_mcp4901, new_mcp4902, new_mcp4911, new_mcp4912, new_mcp4921, n...
(Command::default().buffered()), BufferingNotSupported ); dev.destroy().0.done(); } } }; } for_all_ics_without_buffering!(invalid_buffering_test); macro_rules! send_buffered_test { ($name:ident, $create:ident) => { mod $name { ...
assert_error!(result, InvalidValue); } #[should_panic] #[test] fn can_fail() { let result: Result<(), Error<()>> = Ok(()); assert_error!(result, InvalidValue); } macro_rules! common { ($name:ident, $create:ident) => { mod $name { use super::*; test!( s...
random
[ { "content": "extern crate mcp49xx;\n\nuse mcp49xx::{interface, marker, Mcp49xx};\n\nextern crate embedded_hal_mock as hal;\n\nuse self::hal::spi::{Mock as SpiMock, Transaction as SpiTrans};\n\n\n\npub struct DummyOutputPin;\n\n\n\nimpl embedded_hal::digital::OutputPin for DummyOutputPin {\n\n fn set_low(&mu...
Rust
src/client/commands/submit.rs
Dotnester/hyperqueue
cf5227c2157ab431ee7018a40bbbf0558afe4f27
use std::io::BufRead; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{fs, io}; use anyhow::anyhow; use bstr::BString; use clap::Clap; use hashbrown::HashMap; use tako::common::resources::{CpuRequest, ResourceRequest}; use tako::messages::common::{ProgramDefinition, StdioDef}; use crate::client::comma...
use std::io::BufRead; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{fs, io}; use anyhow::anyhow; use bstr::BString; use clap::Clap; use hashbrown::HashMap; use tako::common::resources::{CpuRequest, ResourceRequest}; use tako::messages::common::{ProgramDefinition, StdioDef}; use crate::client::comma...
} struct StdioArg(StdioDef); impl FromStr for StdioArg { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(StdioArg(match s { "none" => StdioDef::Null, _ => StdioDef::File(s.into()), })) } } #[derive(Clap)] #[clap(setting = clap::AppS...
r { key: s[..position].into(), value: s[position + 1..].into(), }, None => ArgEnvironmentVar { key: s.into(), value: Default::default(), }, }; Ok(var) }
function_block-function_prefixed
[ { "content": "pub fn deserialize_key(key: &str) -> anyhow::Result<SecretKey> {\n\n let data = hex::decode(key).context(\"Could not deserialize secret key\")?;\n\n let key = SecretKey::from_slice(&data).context(\"Could not create secret key from slice\")?;\n\n Ok(key)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tes...
Rust
src/display/text_runs.rs
kas-gui/kas-text
818515e319bf50a81306b8f64e2f19de6ba6e1f1
use super::TextDisplay; use crate::conv::{to_u32, to_usize}; use crate::fonts::{fonts, FontId}; use crate::format::FormattableText; use crate::{shaper, Action, Direction, Range}; use unicode_bidi::{BidiInfo, Level, LTR_LEVEL, RTL_LEVEL}; use xi_unicode::LineBreakIterator; #[derive(Clone, Copy, Debug, PartialEq)] pub...
use super::TextDisplay; use crate::conv::{to_u32, to_usize}; use crate::fonts::{fonts, FontId}; use crate::format::FormattableText; use crate::{shaper, Action, Direction, Range}; use unicode_bidi::{BidiInfo, Level, LTR_LEVEL, RTL_LEVEL}; use xi_unicode::LineBreakIterator; #[derive(Clone, Copy, Debug, PartialEq)] pub...
; let mut levels = vec![]; let mut level: Level; if bidi || default_para_level.is_none() { levels = BidiInfo::new(text.as_str(), default_para_level).levels; assert_eq!(text.str_len(), levels.len()); level = levels.get(0).cloned().unwrap_or(LTR_LEVEL); ...
match dir { Direction::Auto => None, Direction::LR => Some(LTR_LEVEL), Direction::RL => Some(RTL_LEVEL), }
if_condition
[ { "content": "/// Access the [`FontLibrary`] singleton\n\npub fn fonts() -> &'static FontLibrary {\n\n &*LIBRARY\n\n}\n\n\n", "file_path": "src/fonts/library.rs", "rank": 0, "score": 114531.3921757481 }, { "content": "/// Text, optionally with formatting data\n\n///\n\n/// Any `F: Formatt...
Rust
src/cmd.rs
deinferno/nl80211
c4caba12ebdd3337fb121b5d061ac742cb895aa2
use neli::consts::Cmd; use neli::{impl_var, impl_var_base, impl_var_trait}; impl_var_trait!( Nl80211Cmd, u8, Cmd, CmdUnspec => 0, CmdGetWiphy => 1, CmdSetWiphy => 2, CmdNewWiphy => 3, CmdDelWiphy => ...
use neli::consts::Cmd; use neli::{impl_var, impl_var_base, impl_var_trait}; impl_var_trait!( Nl80211Cmd, u8, Cmd, CmdUnspec => 0, CmdGetWiphy => 1, CmdSetWiphy => 2, CmdNewWiphy => 3, CmdDelWiphy => ...
37, CmdAssociate => 38, CmdDeauthenticate => 39, CmdDisassociate => 40, CmdMichaelMicFailure => 41, CmdRegBeaconHint => 42, CmdJoinIbss => 43, CmdLeaveIbss => 44, CmdTestmode => 45, CmdConne...
CmdSetMpath => 22, CmdNewMpath => 23, CmdDelMpath => 24, CmdSetBss => 25, CmdSetReg => 26, CmdReqSetReg => 27, CmdGetMeshConfig => 28, CmdSetMeshConfig => 29, CmdSetMgmtExtraI...
random
[ { "content": "/// Parse a vec of bytes as u8\n\npub fn parse_u8(input: &Vec<u8>) -> u8 {\n\n let to_array =\n\n |slice: &[u8]| -> [u8; 1] { slice.try_into().expect(\"slice with incorrect length\") };\n\n\n\n u8::from_le_bytes(to_array(input))\n\n}\n\n\n", "file_path": "src/parse_attr.rs", "...
Rust
src/backend/vulkan/swapchain.rs
arcana-engine/sierra
42c0d7822cf707dcb9111d74d29176afd91363a6
use super::{ convert::ToErupt as _, device::{Device, WeakDevice}, physical::surface_capabilities, surface::{surface_error_from_erupt, Surface}, unexpected_result, }; use crate::{ format::Format, image::{Image, ImageInfo, ImageUsage, Samples}, out_of_host_memory, semaphore::Semaphore,...
use super::{ convert::ToErupt as _, device::{Device, WeakDevice}, physical::surface_capabilities, surface::{surface_error_from_erupt, Surface}, unexpected_result, }; use crate::{ format::Format, image::{Image, ImageInfo, ImageUsage, Samples}, out_of_host_memory, semaphore::Semaphore,...
}
res.release; Ok(SwapchainImage { image: &image_and_semaphores.image, wait, signal, owner: self.device.clone(), handle: inner.handle, supported_families: self.surface_capabilities.supported_families.clone(), acquired_counter: &i...
function_block-function_prefixed
[ { "content": "pub fn combined_stages_flags(stages: impl Iterator<Item = Stage>) -> u32 {\n\n stages.fold(0, |flags, stage| flags | stage.bit())\n\n}\n\n\n\nimpl Stages {\n\n pub fn bits(&self) -> u32 {\n\n combined_stages_flags(self.flags.iter().copied())\n\n }\n\n}\n\n\n", "file_path": "pro...
Rust
src/util.rs
ashtuchkin/rypt
6cfe9ad1908f3563d2af954fd952c2f906cae8e8
use failure::{Fail, Fallible}; use prost::Message; use std::fs::Metadata; use std::time::Duration; static SCALES: &[&str; 7] = &["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]; pub fn human_file_size(val: usize) -> String { let filled_bits = (0usize.leading_zeros() - val.leading_zeros()) as i32; let scale_idx...
use failure::{Fail, Fallible}; use prost::Message; use std::fs::Metadata; use std::time::Duration; static SCALES: &[&str; 7] = &["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"];
pub fn human_duration(dur: Duration) -> String { let mut time = dur.as_secs(); let secs = time % 60; time /= 60; let mins = time % 60; time /= 60; let hrs = time; if hrs > 0 { format!("{}:{:02}:{:02}", hrs, mins, secs) } else { format!("{}:{:02}", mins, secs) } } p...
pub fn human_file_size(val: usize) -> String { let filled_bits = (0usize.leading_zeros() - val.leading_zeros()) as i32; let scale_idx = std::cmp::max(filled_bits - 1, 0) / 10; let divider = 2.0f64.powi(scale_idx * 10); let places = if scale_idx == 0 { 0 } else { 2 }; let scale = SCALES[(scale_idx ...
function_block-full_function
[ { "content": "pub fn print_help(output: OutputStream, program_name: &str) -> Fallible<()> {\n\n let mut stdout = output.open(false)?;\n\n writeln!(\n\n stdout,\n\n \"\\\n\nUsage: {program_name} [OPTION].. [FILE]..\n\nEncrypt/decrypt FILE-s using passwords and/or public keys. \n\n\n\nCommands...
Rust
src/error.rs
not-a-seagull/porcupine
72e9857086f9a5f62f29048025ba8aea20e00df6
/* ----------------------------------------------------------------------------------- * src/error.rs - Common error type to keep things simple. * porcupine - Safe wrapper around the graphical parts of Win32. * Copyright © 2020 not_a_seagull * * This project is licensed under either the Apache 2.0 license or the M...
/* ----------------------------------------------------------------------------------- * src/error.rs - Common error type to keep things simple. * porcupine - Safe wra
E. * ----------------------------------------------------------------------------------- * Apache 2.0 License Declaration: * * 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...
pper around the graphical parts of Win32. * Copyright © 2020 not_a_seagull * * This project is licensed under either the Apache 2.0 license or the MIT license, at * your option. For more information, please consult the LICENSE-APACHE or LICENSE-MIT * files in the repository root. * -------------------------------...
random
[ { "content": "type DropHandler = fn(NonNull<()>);\n\n\n\n/// The data stored in the extra memory of a window class.\n\n#[repr(C)]\n\npub(crate) struct ClassData<F> {\n\n /// The drop handler for the event handler.\n\n ///\n\n /// Putting this first allows us to drop the class data regardless of the\n\n...
Rust
components/tikv_util/src/quota_limiter.rs
maxshuang/tikv
9a43faf4da20389a4e2c262ee8ab8b369a3bfec4
use std::time::Duration; use super::config::ReadableSize; use super::time::Limiter; use super::timer::GLOBAL_TIMER_HANDLE; use cpu_time::ThreadTime; use futures::compat::Future01CompatExt; const CPU_TIME_FACTOR: f64 = 0.8; const MAX_QUOTA_DELAY: Duration = Duration::from_secs(1); #[derive(Debug)] pub struct Quot...
use std::time::Duration; use super::config::ReadableSize; use super::time::Limiter; use super::timer::GLOBAL_TIMER_HANDLE; use cpu_time::ThreadTime; use futures::compat::Future01CompatExt; const CPU_TIME_FACTOR: f64 = 0.8; const MAX_QUOTA_DELAY: Duration = Duration::from_secs(1); #[derive(Debug)] pub struct Quot...
pub fn new_sample(&self) -> Sample { Sample { read_bytes: 0, write_bytes: 0, cpu_time: Duration::ZERO, enable_cpu_limit: !self.cputime_limiter.speed_limit().is_infinite(), } } pub async fn async_consume(&self, sample: Sample) ...
let read_bandwidth_limiter = if read_bandwidth.0 == 0 { Limiter::new(f64::INFINITY) } else { Limiter::new(read_bandwidth.0 as f64) }; Self { cputime_limiter, write_bandwidth_limiter, read_bandwidth_limiter, } }
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn duration_to_sec(d: Duration) -> f64 {\n\n let nanos = f64::from(d.subsec_nanos());\n\n d.as_secs() as f64 + (nanos / 1_000_000_000.0)\n\n}\n\n\n\n/// Converts Duration to microseconds.\n", "file_path": "components/tikv_util/src/time.rs", "rank": 0, "score": 37...
Rust
src/expr/src/linear.rs
gjlondon/materialize
29efdc9d7f50891c461ffdd2727ab5d748c2a2a7
use serde::{Deserialize, Serialize}; use crate::{scalar::EvalError, RelationExpr, ScalarExpr}; use repr::{Datum, Row, RowArena, RowPacker}; #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)] pub struct MapFilterProject { pub expressions: Vec<ScalarExpr>, ...
use serde::{Deserialize, Serialize}; use crate::{scalar::EvalError, RelationExpr, ScalarExpr}; use repr::{Datum, Row, RowArena, RowPacker}; #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)] pub struct MapFilterProject { pub expressions: Vec<ScalarExpr>, ...
pub fn filter<I>(mut self, predicates: I) -> Self where I: IntoIterator<Item = ScalarExpr>, { for mut predicate in predicates { predicate.permute(&self.projection[..]); let max_support = predicate ...
pub fn project<I>(mut self, columns: I) -> Self where I: IntoIterator<Item = usize> + std::fmt::Debug, { self.projection = columns.into_iter().map(|c| self.projection[c]).collect(); self }
function_block-full_function
[ { "content": "/// Number of bytes required by the datum.\n\n///\n\n/// This is used to optimistically pre-allocate buffers for packing rows.\n\npub fn datum_size(datum: &Datum) -> usize {\n\n match datum {\n\n Datum::Null => 1,\n\n Datum::False => 1,\n\n Datum::True => 1,\n\n Datu...
Rust
src/diagnostics/report.rs
olson-sean-k/wax
22c4221bdee7417ed93fa5ebabdda49673460adf
#![cfg(feature = "diagnostics-report")] use miette::{Diagnostic, LabeledSpan, SourceSpan}; use std::borrow::Cow; use std::cmp; use std::path::PathBuf; use thiserror::Error; use vec1::Vec1; use crate::token::{self, TokenKind, Tokenized}; pub type BoxedDiagnostic<'t> = Box<dyn Diagnostic + 't>; #[cfg_attr(docsrs, doc...
#![cfg(feature = "diagnostics-report")] use miette::{Diagnostic, LabeledSpan, SourceSpan}; use std::borrow::Cow; use std::cmp; use std::path::PathBuf; use thiserror::Error; use vec1::Vec1; use crate::token::{self, TokenKind, Tokenized}; pub type BoxedDiagnostic<'t> = Box<dyn Diagnostic + 't>; #[cfg_attr(docsrs, doc...
}
let glob = Glob::new("**/foo/").unwrap(); let diagnostics: Vec<_> = glob.diagnostics().collect(); assert!(diagnostics.iter().any(|diagnostic| diagnostic .code() .map(|code| code.to_string() == CODE_TERMINATING_SEPARATOR) .unwrap_or(false))); }
function_block-function_prefix_line
[ { "content": "pub fn components<'i, 't, A, I>(tokens: I) -> impl Iterator<Item = Component<'i, 't, A>>\n\nwhere\n\n 't: 'i,\n\n A: 't,\n\n I: IntoIterator<Item = &'i Token<'t, A>>,\n\n I::IntoIter: Clone,\n\n{\n\n tokens.into_iter().batching(|tokens| {\n\n let mut first = tokens.next();\n\...
Rust
src/blockchain/esplora.rs
dspicher/magical-bitcoin-wallet
462d413b02ec05b401d25dd7acb3237fcb522b4a
use std::collections::{HashMap, HashSet}; use futures::stream::{self, StreamExt, TryStreamExt}; #[allow(unused_imports)] use log::{debug, error, info, trace}; use serde::Deserialize; use reqwest::{Client, StatusCode}; use bitcoin::consensus::{deserialize, serialize}; use bitcoin::hashes::hex::ToHex; use bitcoin::h...
use std::collections::{HashMap, HashSet}; use futures::stream::{self, StreamExt, TryStreamExt}; #[allow(unused_imports)] use log::{debug, error, info, trace}; use serde::Deserialize; use reqwest::{Client, StatusCode}; use bitcoin::consensus::{deserialize, serialize}; use bitcoin::hashes::hex::ToHex; use bitcoin::h...
self) -> Result<usize, EsploraError> { let req = self .client .get(&format!("{}/api/blocks/tip/height", self.url)) .send() .await?; Ok(req.error_for_status()?.text().await?.parse()?) } async fn _script_get_history( &self, script: ...
k_or(Error::OfflineClient)? ._get_tx(txid))?) } fn broadcast(&self, tx: &Transaction) -> Result<(), Error> { Ok(await_or_block!(self .0 .as_ref() .ok_or(Error::OfflineClient)? ._broadcast(tx))?) } fn get_height(&self) -> Result<usize,...
random
[ { "content": "pub fn get_checksum(desc: &str) -> Result<String, Error> {\n\n let mut c = 1;\n\n let mut cls = 0;\n\n let mut clscount = 0;\n\n for ch in desc.chars() {\n\n let pos = INPUT_CHARSET\n\n .find(ch)\n\n .ok_or(Error::InvalidDescriptorCharacter(ch))? as u64;\n\...
Rust
examples/track-rs/ta/src/main.rs
zank0201/incubator-teaclave-trustzone-sdk
0d379dae74cb2ebc356fa0d611721716ea43eb91
#![feature(restricted_std)] #![no_main] use optee_utee::{ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, }; use optee_utee::{AlgorithmId, Mac}; use optee_utee::{AttributeId, AttributeMemref, TransientObject, TransientObjectType}; use optee_utee::{Error, ErrorKind, Parame...
#![feature(restricted_std)] #![no_main] use optee_utee::{ ta_close_session, ta_create, ta_destroy, ta_invoke_command, ta_open_session, trace_println, }; use optee_utee::{AlgorithmId, Mac}; use optee_utee::{AttributeId, AttributeMemref, TransientObject, TransientObjectType}; use optee_utee::{Error, ErrorKind, Parame...
umber_generate(_params); } _ => { return Err(Error::new(ErrorKind::BadParameters)); } } } const TA_FLAGS: u32 = 0; const TA_DATA_SIZE: u32 =96 * 1024; const TA_STACK_SIZE: u32 = 6 * 1024; const TA_VERSION: &[u8] = b"0.1\0"; const TA_DESCRIPTION: &[u8] = b"This is an HOTP example...
te}; use ta_keygen::generate_key; pub const SHA1_HASH_SIZE: usize = 20; pub const MAX_KEY_SIZE: usize = 64; pub const MIN_KEY_SIZE: usize = 10; pub const DBC2_MODULO: u32 = 100000000; #[ta_create] fn create() -> Result<()> { trace_println!("[+] TA create"); Ok(()) } #[ta_open_session] fn open_session(_params...
random
[ { "content": "pub fn get_hotp(hotp: &mut Operations, params: &mut Parameters) -> Result<()> {\n\n let mut mac: [u8; SHA1_HASH_SIZE] = [0x0; SHA1_HASH_SIZE];\n\n\n\n hotp.counter = get_time(hotp);\n\n hmac_sha1(hotp, &mut mac)?;\n\n trace_println!(\"[+] Hmac value = {:?}\",&mac);\n\n\n\n let hotp_...
Rust
src/lib.rs
Aetf/fit2
e6b9ce05444e65c641291e32ec6347727e6989a1
use futures::future::poll_fn; use lambda_http::{ request::{ApiGatewayRequestContext, ApiGatewayV2RequestContext, Http, RequestContext}, Body as LambdaBody, Context, Request as LambdaRequest, RequestExt as _, Response, }; use hyper::service::Service as _; use routerify::RequestServiceBuilder; use simple_logger:...
use futures::future::poll_fn; use lambda_http::{ request::{ApiGatewayRequestContext, ApiGatewayV2RequestContext, Http, RequestContext}, Body as LambdaBody, Context, Req
str { let paths: &ApiGatewayPath = self.extensions().get().expect("no apigateway path"); &paths.base_path } } struct ApiGatewayPath { base_path: String, } impl ApiGatewayPath { pub fn from_req(req: &LambdaRequest) -> Self { let base_path = match req.request_context() { ...
uest as LambdaRequest, RequestExt as _, Response, }; use hyper::service::Service as _; use routerify::RequestServiceBuilder; use simple_logger::SimpleLogger; use std::net::{Ipv4Addr, SocketAddr}; mod adaptor; mod core; pub mod error; mod ext; mod route; use adaptor::prelude::*; use error::*; use crate::ext::Query; ...
random
[ { "content": "pub trait IntoHyperBody: Sized {\n\n fn into_bytes(self) -> Bytes;\n\n fn into_hyper_body(self) -> hyper::Body {\n\n self.into_bytes().into()\n\n }\n\n}\n\n\n", "file_path": "src/adaptor.rs", "rank": 3, "score": 17238.46736061178 }, { "content": "pub fn router()...
Rust
src/content_set.rs
PoignardAzur/disney-streaming-clone
200ecf50f4fcbc3e28040d8dbb2b2bf35f830918
use smallvec::{smallvec, SmallVec}; use tracing::{trace_span, Span}; use widget_cruncher::promise::PromiseToken; use widget_cruncher::widget::prelude::*; use widget_cruncher::widget::{AsWidgetPod, ClipBox, Flex, Label, SizedBox, Spinner, WidgetPod}; use widget_cruncher::Point; use crate::thumbnail::{Thumbnail, THUMBN...
use smallvec::{smallvec, SmallVec}; use tracing::{trace_span, Span}; use widget_cruncher::promise::PromiseToken; use widget_cruncher::widget::prelude::*; use widget_cruncher::widget::{AsWidgetPod, ClipBox, Flex, Label, SizedBox, Spinner, WidgetPod}; use widget_cruncher::Point; use crate::thumbnail::{Thumbnail, THUMBN...
_state, ClipBox::new(titles).constrain_vertical(true), ); }, ); ctx.skip_child(&mut self.children); return; ...
o_iter().enumerate() { titles = titles.with_child(Thumbnail::new(row, column, child)); } flex.add_child( flex
random
[ { "content": "// Loads and parses https://cd-static.bamgrid.com/dp-117731241344/home.json\n\nfn load_collection(url: &str) -> Result<Vec<ContentSetMetadata>, reqwest::Error> {\n\n let json: serde_json::Value = reqwest::blocking::get(url)?.json()?;\n\n let containers = json[\"data\"][\"StandardCollection\"...
Rust
src/ui/no_yaml.rs
eppixx/reel-moby
b6dbcd8ebac2aa0220455883b723d785b4ceb6c4
use std::{io, thread}; use termion::event::Key; use termion::raw::IntoRawMode; use tui::backend::TermionBackend; use tui::layout::{Constraint, Direction, Layout}; use tui::Terminal; use crate::widget::details; use crate::widget::info; use crate::widget::repo_entry; use crate::widget::tag_list; use crate::Opt; #[deri...
use std::{io, thread}; use termion::event::Key; use termion::raw::IntoRawMode; use tui::backend::TermionBackend; use tui::layout::{Constraint, Direction, Layout}; use tui::Terminal; use crate::widget::details; use crate::widget::info; use crate::widget::repo_entry; use crate::widget::tag_list; use crate::Opt; #[deri...
} pub struct NoYaml { state: State, repo: repo_entry::RepoEntry, tags: tag_list::TagList, details: details::Details, info: info::Info, } impl NoYaml { pub fn run(opt: &Opt) { let (repo, load_repo) = match &opt.repo { None => ( repo_entry::RepoEntry::new( ...
fn next(&mut self) -> Option<Self::Item> { match self { State::EditRepo => *self = State::SelectTag, State::SelectTag => *self = State::EditRepo, } Some(self.clone()) }
function_block-full_function
[ { "content": "/// checks the repo name and may add a prefix for official images\n\npub fn check_repo(name: &str) -> Result<String, Error> {\n\n let repo = match repo::split_tag_from_repo(name) {\n\n Err(e) => return Err(Error::Converting(format!(\"{}\", e))),\n\n Ok((name, _)) => name,\n\n }...
Rust
src/targets/mod.rs
sunshowers/cfg-expr
caa5d74415ea53bf439d4bb623a4ceb3c13719ec
use crate::error::Reason; mod list; pub use list::ALL_TARGETS as ALL; macro_rules! target_enum { ( $(#[$outer:meta])* pub enum $kind:ident { $( $(#[$inner:ident $($args:tt)*])* $name:ident $(= $value:expr)?, )+ } ) => { $...
use crate::error::Reason; mod list; pub use list::ALL_TARGETS as ALL; macro_rules! target_enum { ( $(#[$outer:meta])* pub enum $kind:ident { $( $(#[$inner:ident $($args:tt)*])* $name:ident $(= $value:expr)?, )+ } ) => { $...
); } }
6, super::ALL .iter() .filter(|ti| ti.os == Some(super::Os::ios)) .count()
function_block-random_span
[ { "content": "#[test]\n\nfn target_family() {\n\n let matches_any_family = Expression::parse(\"any(unix, target_family = \\\"windows\\\")\").unwrap();\n\n let impossible = Expression::parse(\"all(windows, target_family = \\\"unix\\\")\").unwrap();\n\n\n\n for target in all {\n\n match target.fam...
Rust
src/metadata.rs
stegaBOB/metabob
37567e4c628e3a7570280700fd5fc91d2f847e1c
use crate::limiter::create_rate_limiter; use crate::{ constants::{MAX_NAME_LENGTH, MAX_SYMBOL_LENGTH, MAX_URI_LENGTH, USE_RATE_LIMIT}, parse::parse_solana_config, }; use anyhow::Result; use indicatif::ParallelProgressIterator; use log::{error, info}; use mpl_token_metadata::{ instruction::sign_metadata, sta...
use crate::limiter::create_rate_limiter; use crate::{ constants::{MAX_NAME_LENGTH, MAX_SYMBOL_LENGTH, MAX_URI_LENGTH, USE_RATE_LIMIT}, parse::parse_solana_config, }; use anyhow::Result; use indicatif::ParallelProgressIterator; use log::{error, info}; use mpl_token_metadata::{ instruction::sign_metadata, sta...
; let sig = res?; Ok(sig) }
retry( Exponential::from_millis_with_factor(250, 2.0).take(3), || client.send_and_confirm_transaction(&tx), )
call_expression
[ { "content": "pub fn decode_metadata_account(account: &Account) -> Result<Metadata, DecodeError> {\n\n let account_data = account.data.as_slice();\n\n let metadata: Result<Metadata, Error> = try_from_slice_unchecked(account_data);\n\n let token_metadata = match metadata {\n\n Ok(m) => m,\n\n ...
Rust
src/shell.rs
afnanenayet/Enayet-Shell
6509126a05755ae6c64a9271379047ea079afd63
use std::path::PathBuf; use std::env; use parser; #[derive(Debug)] #[derive(Default)] pub struct Shell { working_dir: PathBuf, input_history: Vec<String>, output_count: u64, paths: Vec<String>, } impl Shell { fn default() -> Shell { Shell { ...
use std::path::PathBuf; use std::env; use parser; #[derive(Debug)] #[derive(Default)] pub struct Shell { working_dir: PathBuf, input_history: Vec<String>, output_count: u64, paths: Vec<String>, } impl Shell { fn default() -> Shell { Shell { ...
"); let mut shell = Shell::default(); let def_paths_vec = create_default_path_vec(); let fp_str = tmp_dir.as_path().to_str().unwrap(); parser::config::create_default_config(&fp_str, &def_paths_vec); shell.load_paths(Some(&fp_str), &def_paths_vec); assert!(shell....
r::config::create_default_config; fn create_default_path_vec() -> Vec<String> { vec![ "/usr/bin".to_string(), "/usr/local/bin".to_string(), "/bin/".to_string(), ] } #[test] fn test_default_shell_init() { let shell = Shell::defa...
random
[ { "content": "// Checks to see if path/file exists. Returns whether path string is\n\n// valid and points to something the shell can access\n\npub fn verify_path(path: &str) -> bool {\n\n let full_path = expand_path(path);\n\n Path::new(full_path.as_str()).exists()\n\n}\n\n\n", "file_path": "src/parse...
Rust
src/cluster.rs
andrewvy/axiom
6c5c41b5a58d7ff75ffd62d45e30d18d7ab3e083
use crate::prelude::*; use log::{error, info}; use secc::*; use std::collections::HashMap; use std::io::prelude::*; use std::io::{BufReader, BufWriter}; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, RwLock}; use std::sync::{Condvar, Mutex}; use...
use crate::prelude::*; use log::{error, info}; use secc::*; use std::collections::HashMap; use std::io::prelude::*; use std::io::{BufReader, BufWriter}; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, RwLock}; use std::sync::{Condvar, Mutex}; use...
let system = self.data.system.clone(); let address = self.data.listen_address.clone(); let manager = self.clone(); thread::spawn(move || { system.init_current(); let sys_uuid = system.uuid(); let listener = TcpListener::bind(address).unwrap(); inf...
ad::JoinHandle; use std::time::Duration; use uuid::Uuid; struct ConnectionData { pub system_uuid: Uuid, pub address: SocketAddr, pub sender: SeccSender<WireMessage>, pub receiver: SeccReceiver<WireMessage>, pub tx_handle: JoinHandle<()>, pub rx_handle: JoinHandle<(...
random
[ { "content": "//! Implements the [`ActorSystem`] and related types of Axiom.\n\n//!\n\n//! When the [`ActorSystem`] starts up, a number of Reactors will be spawned that will iterate over\n\n//! Actor's inbound messages, processing them asynchronously. Actors will be ran as many times as\n\n//! they can over a g...
Rust
src/traits/json.rs
rsnodgrass/helium-wallet-rs
620ef5cd9cf5fe7f8bb830c22a177dd3262a2f1b
use crate::{ keypair::PublicKey, result::{anyhow, Result}, traits::B64, }; use helium_proto::*; use serde_json::json; pub(crate) fn maybe_b58(data: &[u8]) -> Result<Option<String>> { if data.is_empty() { Ok(None) } else { Ok(Some(PublicKey::from_bytes(data)?.to_string())) } } p...
use crate::{ keypair::PublicKey, result::{anyhow, Result}, traits::B64, }; use helium_proto::*; use serde_json::json; pub(crate) fn maybe_b58(data: &[u8]) -> Result<Option<String>> { if data.is_empty() { Ok(None) } else { Ok(Some(PublicKey::from_bytes(data)?.to_string())) } } p...
} fn vec_to_strings(vec: &[Vec<u8>]) -> Result<Vec<String>> { let mut seq = Vec::with_capacity(vec.len()); for entry in vec { seq.push(String::from_utf8(entry.to_vec())?); } Ok(seq) } fn vec_to_b58s(vec: &[Vec<u8>]) -> Result<Vec<String>> { let mut seq = Vec::with_capacity(vec.len()); ...
to_json(&self) -> Result<serde_json::Value> { let mut seq = Vec::with_capacity(self.len()); for entry in self { seq.push(entry.to_json()?) } Ok(json!(seq)) }
function_block-function_prefixed
[]
Rust
cynthia/src/utils/read_buf.rs
nephele-rs/cynthia
c512a88e51c9723b4b9b9d8addb9dfc4aa118f5e
#![allow(clippy::transmute_ptr_to_ptr)] use std::fmt; use std::mem::{self, MaybeUninit}; pub struct ReadBuf<'a> { buf: &'a mut [MaybeUninit<u8>], filled: usize, initialized: usize, } impl<'a> ReadBuf<'a> { #[inline] pub fn new(buf: &'a mut [u8]) -> ReadBuf<'a> { let initialized = buf.len(...
#![allow(clippy::transmute_ptr_to_ptr)] use std::fmt; use std::mem::{self, MaybeUninit}; pub struct ReadBuf<'a> { buf: &'a mut [MaybeUninit<u8>], filled: usize, initialized: usize, } impl<'a> ReadBuf<'a> { #[inline] pub fn new(buf: &'a mut [u8]) -> ReadBuf<'a> {
unsafe { mem::transmute::<&[MaybeUninit<u8>], &[u8]>(slice) } } #[inline] pub fn filled_mut(&mut self) -> &mut [u8] { let slice = &mut self.buf[..self.filled]; unsafe { mem::transmute::<&mut [MaybeUninit<u8>], &mut [u8]>(slice) } } #[inline] pub fn take(&mut self, n: usi...
let initialized = buf.len(); let buf = unsafe { mem::transmute::<&mut [u8], &mut [MaybeUninit<u8>]>(buf) }; ReadBuf { buf, filled: 0, initialized, } } #[inline] pub fn uninit(buf: &'a mut [MaybeUninit<u8>]) -> ReadBuf<'a> { ReadBu...
random
[ { "content": "pub fn repeat(byte: u8) -> Repeat {\n\n Repeat { byte }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Repeat {\n\n byte: u8,\n\n}\n\n\n\nimpl AsyncRead for Repeat {\n\n #[inline]\n\n fn poll_read(self: Pin<&mut Self>, _: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize>> {\n\n ...
Rust
day_12/src/main.rs
Sousa99/AdventOfCode2020
f8ce5008e688d50d818eabfea13e4da47e934744
use std::fs::File; use std::io::{BufRead, BufReader}; type CoordinateUnit = f32; type Coordinates = (CoordinateUnit, CoordinateUnit); #[derive(Copy, Clone)] enum Operation { MoveNorth, MoveSouth, MoveEast, MoveWest, RotateLeft, RotateRight, MoveForward, } struct Ferry { position...
use std::fs::File; use std::io::{BufRead, BufReader}; type CoordinateUnit = f32; type Coordinates = (CoordinateUnit, CoordinateUnit); #[derive(Copy, Clone)] enum Operation { MoveNorth, MoveSouth, MoveEast, MoveWest, RotateLeft, RotateRight, MoveForward, } struct Ferry { position...
} fn get_operation_to_code(code : &str) -> Operation { let operation : Operation = match code { "N" => Operation::MoveNorth, "S" => Operation::MoveSouth, "E" => Operation::MoveEast, "W" => Operation::MoveWest, "L" => Operation::RotateLeft, "R" => Operation::RotateR...
fn run_operation(&mut self, operation : Operation, value : CoordinateUnit) { match operation { Operation::MoveNorth => self.move_north(value), Operation::MoveSouth => self.move_south(value), Operation::MoveEast => self.move_east(value), Operation::MoveWest => self...
function_block-full_function
[ { "content": "type Coordinates = (CoordinateUnit, CoordinateUnit);\n\n\n", "file_path": "day_24/src/main.rs", "rank": 2, "score": 117577.64285189944 }, { "content": "type Coordinates4D = (CoordinateUnit, CoordinateUnit, CoordinateUnit, CoordinateUnit);\n\n\n\n// -------------- State --------...
Rust
src/ipv6/network.rs
little-dude/ipaddr
4836a0c8d6dc115d5a60314ba2d95e3900e9c1dc
use std::fmt; use std::str::FromStr; use {Ipv6Address, Ipv6Mask, ParsingFailed}; #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub struct Ipv6Network(Ipv6Address, Ipv6Mask); impl Ipv6Network { pub fn new(ip: Ipv6Address, mask: Ipv6Mask) -> Self { Ipv6Network(ip, mask) } pub fn host(&self) -> ...
use std::fmt; use std::str::FromStr; use {Ipv6Address, Ipv6Mask, ParsingFailed}; #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub struct Ipv6Network(Ipv6Address, Ipv6Mask); impl Ipv6Network { pub fn new(ip: Ipv6Address, mask: Ipv6Mask) -> Self { Ipv6Network(ip, mask) } pub fn host(&self) -> ...
fn get_net(prefix: u8) -> Ipv6Network { Ipv6Network::new(IP.into(), Ipv6Mask::from_prefixlen(prefix).unwrap()) } #[test] fn test_network() { assert_eq!( get_net(16).network(), Ipv6Address::from_str("fe80::").unwrap() ); assert_eq!( g...
let s = "fe80::aef4:1242:24e6:c81/ffff:ffff:ffff:ffff::"; assert_eq!(Ipv6Network::from_str(s).unwrap(), expected); let s = "fe80::aef4:1242:24e6:c81/0"; let expected = Ipv6Network::new(IP.into(), Ipv6Mask::try_from(0).unwrap()); assert_eq!(Ipv6Network::from_str(s).unwrap(), expected); ...
function_block-function_prefix_line
[ { "content": "/// Check whether the given integer represents a valid IPv6 mask.\n\n// see https://codereview.stackexchange.com/a/197138/118470\n\nfn is_valid_mask(value: u128) -> bool {\n\n value.count_zeros() == value.trailing_zeros()\n\n}\n\n\n\n#[derive(Copy, Clone, PartialEq, Eq, Hash)]\n\npub struct Ipv...
Rust
iroha_logger/src/lib.rs
EmelianPiker/iroha
d6097b81572554444b2e9a9a560c581006fc895a
use chrono::prelude::*; use log::{Level, Log, Metadata, Record, SetLoggerError}; use std::sync::RwLock; const RED: u8 = 31; const GREEN: u8 = 32; const YELLOW: u8 = 33; const BLUE: u8 = 34; const MAGENTA: u8 = 35; lazy_static::lazy_static! { static ref LOGGER_SET: RwLock<bool> = RwLock::new(false); } #[derive(De...
use chrono::prelude::*; use log::{Level, Log, Metadata, Record, SetLoggerError}; use std::sync::RwLock; const RED: u8 = 31; const GREEN: u8 = 32; const YELLOW: u8 = 33; const BLUE: u8 = 34; const MAGENTA: u8 = 35; lazy_static::lazy_static! { static ref LOGGER_SET: RwLock<bool> = RwLock::new(false); } #[derive(De...
}
fn init_logger() { init(&LoggerConfiguration { max_log_level: LevelFilter::Trace, terminal_color_enabled: true, date_time_format: "%Y-%m-%d %H:%M:%S:%f".to_string(), }) .expect("Failed to initialize logger."); println!("Max level: {}", log::max_level()...
function_block-full_function
[ { "content": "pub fn new(configuration: &Configuration) -> Self {\n\n Client {\n\n torii_url: configuration.torii_url.clone(),\n\n //TODO: The `public_key` from `configuration` will be different. Fix this inconsistency.\n\n key_pair: KeyPair::generate().expect(\"Failed to generate KeyPai...
Rust
link-types/src/lib.rs
Vociferix/sniffle
aa0ad27d4317e4ca9b760ae3c623775fe8004733
#![doc = include_str!("../README.md")] use std::hash::Hash; #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] #[repr(transparent)] pub struct LinkType(pub u16); macro_rules! link_type { ($name:ident, $val:literal) => { pub const $name: LinkType = LinkType($val); }; } #[macro_export] macro_rules! fo...
#![doc = include_str!("../README.md")] use std::hash::Hash; #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] #[repr(transparent)] pub struct LinkType(pub u16); macro_rules! link_type { ($name:ident, $val:literal) => { pub const $name: LinkType = LinkType($val); }; } #[macro_export] macro_rules! fo...
SO_14443, 264); link_type!(RDS, 265); link_type!(USB_DARWIN, 266); link_type!(SDLC, 268); link_type!(LORATAP, 270); link_type!(VSOCK, 271); link_type!(NORDIC_BLE, 272); link_type!(DOCSIS31_XRA31, 273); link_type!(ETHERNET_MPACKET, 274); link_type!(DISPLAYPORT_AUX, 275); link_type...
; link_type!(IEEE802_11_RADIOTAP, 127); link_type!(ARCNET_LINUX, 129); link_type!(APPLE_IP_OVER_IEEE1394, 138); link_type!(MTP2_WITH_PHDR, 139); link_type!(MTP2, 140); link_type!(MTP3, 141); link_type!(SCCP, 142); link_type!(DOCSIS, 143); link_type!(LINUX_IRDA, 144); link_type!(U...
random
[ { "content": "pub trait AsDeviceName {\n\n fn as_device_name(&self) -> &str;\n\n}\n\n\n\nimpl AsDeviceName for Device {\n\n fn as_device_name(&self) -> &str {\n\n self.name()\n\n }\n\n}\n\n\n\nimpl<T: AsRef<str>> AsDeviceName for T {\n\n fn as_device_name(&self) -> &str {\n\n self.as_r...
Rust
src/spis0.rs
cvetaevvitaliy/nrf52840-pac
bf07243a5a043883d915999f0f8ccd6cbf6229b8
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 36usize], #[doc = "0x24 - Acquire SPI semaphore"] pub tasks_acquire: TASKS_ACQUIRE, #[doc = "0x28 - Release SPI semaphore, enabling the SPI slave to acquire it"] pub tasks_release: TASKS_RELEASE, _reserved1: [u8; ...
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { _reserved0: [u8; 36usize], #[doc = "0x24 - Acquire SPI semaphore"] pub tasks_acquire: TASKS_ACQUIRE, #[doc = "0x28 - Release SPI semaphore, enabling the SPI slave to acquire it"] pub tasks_release: TASKS_RELEASE, _reserved1: [u8; ...
c = "Semaphore status register"] pub struct SEMSTAT { register: ::vcell::VolatileCell<u32>, } #[doc = "Semaphore status register"] pub mod semstat; #[doc = "Status from last transaction"] pub struct STATUS { register: ::vcell::VolatileCell<u32>, } #[doc = "Status from last transaction"] pub mod status; #[doc = ...
; 244usize], #[doc = "0x400 - Semaphore status register"] pub semstat: SEMSTAT, _reserved7: [u8; 60usize], #[doc = "0x440 - Status from last transaction"] pub status: STATUS, _reserved8: [u8; 188usize], #[doc = "0x500 - Enable SPI slave"] pub enable: ENABLE, _reserved9: [u8; 4usize],...
random
[ { "content": "#[doc = \"RXD data pointer\"]\n\npub struct PTR {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"RXD data pointer\"]\n\npub mod ptr;\n\n#[doc = \"Maximum number of bytes in receive buffer\"]\n\npub struct MAXCNT {\n\n register: ::vcell::VolatileCell<u32>,\n\n}\n\n#[doc = \"Maxim...
Rust
src/config.rs
jessebraham/camper
25f0dfd2f153be50937b8abde6bfd9a9a2cf07dc
use std::{ fmt::{Display, Formatter, Result as FmtResult}, fs, io::Write as _, path::PathBuf, }; use anyhow::{bail, Context, Result}; use directories::UserDirs; use serde::{Deserialize, Serialize}; use crate::format::Format; #[derive(Debug, Default, Clone, Deserialize, Serialize)] pub struct Config {...
use std::{ fmt::{Display, Formatter, Result as FmtResult}, fs, io::Write as _, path::PathBuf, }; use anyhow::{bail, Context, Result}; use directories::UserDirs; use serde::{Deserialize, Serialize}; use crate::format::Format; #[derive(Debug, Default, Clone, Deserialize, Serialize)] pub struct Config {...
pub fn is_valid(&self) -> bool { let fan_id_cfgd = match self.fan_id { Some(id) if id > 0 => true, _ => false, }; let identity_cfgd = match &self.identity { Some(ident) if !ident.is_empty() => true, _ => false, }; let librar...
f !path.exists() { fs::File::create(&path).with_context(|| { format!("unable to create configuration file '{}'", path.display()) })?; } let mut file = fs::OpenOptions::new().write(true).open(&path)?; let toml = toml::to_string(self)?; write!(file...
function_block-function_prefixed
[]
Rust
necsim/impls/no-std/src/decomposition/equal/test.rs
MomoLangenstein/necsim-rust
d19045e2e36afdd33b254ad5fbcd10daa9ccbaf7
use core::{convert::TryFrom, num::NonZeroU32}; use hashbrown::HashMap; use necsim_core::cogs::{Backup, Habitat}; use necsim_core_maths::IntrinsicsMathsCore; use necsim_partitioning_core::partition::Partition; use crate::{ cogs::habitat::{non_spatial::NonSpatialHabitat, spatially_implicit::SpatiallyImplicitHabita...
use core::{convert::TryFrom, num::NonZeroU32}; use hashbrown::HashMap; use necsim_core::cogs::{Backup, Habitat}; use necsim_core_maths::IntrinsicsMathsCore; use necsim_partitioning_core::partition::Partition; use crate::{ cogs::habitat::{non_spatial::NonSpatialHabitat, spatially_implicit::SpatiallyImplicitHabita...
local, 8, meta, partition, decomposition, indices.len(), indices, ); let num_indices = u32::try_from(indices.len()).expect(&assert_message); ...
(num_indices, partition, "{}", &assert_message); } else { assert!(num_indices > 0, "{}", assert_message); assert!(num_indices < partition, "{}", assert_message); assert!( u64::from(num_indices) == (u64::from(width) * u64...
random
[ { "content": "// Fix dispersal by removing dispersal to/from non-habitat\n\n// Fix dispersal by adding self-dispersal when no dispersal exists from habitat\n\nfn fix_dispersal_map(habitat: &Array2D<u32>, dispersal: &mut Array2D<NonNegativeF64>) {\n\n let size = habitat.num_rows() * habitat.num_columns();\n\n...
Rust
src/process.rs
reaandrew/shtats
940a23bb9192869d0038f35f987257e65734f66d
use std::fs::File; use std::io::{ BufReader, Read, Write}; use std::path::Path; use std::process::{ChildStdout, Command, Stdio}; use serde_json::{Value}; use crate::collectors::commits_by_day::CommitsByDayCollector; use crate::collectors::commits_by_file_extension::CommitsByFileExtension; use crate::collectors::files_b...
use std::fs::File; use std::io::{ BufReader, Read, Write}; use std::path::Path; use std::process::{ChildStdout, Command, Stdio}; use serde_json::{Value}; use crate::collectors::commits_by_day::CommitsByDayCollector; use crate::collectors::commits_by_file_extension::CommitsByFileExtension; use crate::collectors::files_b...
} impl GitExecutor for ProcessGitExecutor { fn execute(&self, args: Vec<String>, path: &Path) -> result::Result<GitCommitIterator> { let stdout = self.execute_git(args, path)?; let buf_reader = BufReader::new(stdout); let reader = StdoutGitLogReader { stdout: buf_reader }; Ok(GitCo...
h)?; let child = Command::new("git") .current_dir(path) .args(args) .stdout(Stdio::piped()) .spawn()?; let stdout = child.stdout.unwrap(); Ok(stdout) }
function_block-function_prefixed
[ { "content": "pub fn git_log(path: &PathBuf){\n\n let mut git_log = Command::new(\"git\");\n\n git_log.args(vec![\n\n \"log\",\n\n \"--oneline\"\n\n ]);\n\n git_log.stdout(Stdio::piped());\n\n let _output = git_log.current_dir(\n\n &path\n\n ).output().expect(\"failed to e...
Rust
src/shader/uniform.rs
seventh-chord/gondola
4122966e5cf2cdd7947b2891c1906dfdf71406f2
use std::fmt; use gl; use gl::types::*; use cable_math::{Mat4, Vec2, Vec3, Vec4}; pub struct UniformBinding { pub name: String, pub location: GLint, pub kind: UniformKind, } pub trait UniformValue: Sized { const KIND: UniformKind; unsafe fn set_uniform(data: &Self, location: GLint); unsafe...
use std::fmt; use gl; use gl::types::*; use cable_math::{Mat4, Vec2, Vec3, Vec4}; pub struct UniformBinding { pub name: String, pub location: GLint, pub kind: UniformKind, } pub trait UniformValue: Sized { const KIND: UniformKind; unsafe fn set_uniform(data: &Self, location: GLint); unsafe...
}
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::UniformKind::*; let name = match *self { F32 => "f32", VEC2_F32 => "Vec2<f32>", VEC3_F32 => "Vec3<f32>", VEC4_F32 => "Vec4<f32>", MAT4_F32 => "Mat4<f32>", I32 ...
function_block-full_function
[ { "content": "/// Enables/disables the OpenGL scissor test. The given region is in screen space, that is, in the\n\n/// same coordinate system as [`viewport`]. Anything drawn outside this region will be discarded.\n\n///\n\n/// `gl::Scissor` takes integers as parameters the given regions coordinates will be ca...
Rust
ed25519-jni/src/lib.rs
Concordium/concordium-java-sdk
4de276479acb99ef1fb5ccea615921acd7ae25a0
use core::convert::Into; use core::slice; use ed25519_dalek::*; use jni::objects::JClass; use jni::sys::{jbyteArray, jint}; use jni::JNIEnv; use std::convert::{From, TryFrom}; const SUCCESS: i32 = 0; const NATIVE_CONVERSION_ERROR: i32 = 1; const MALFORMED_SECRET_KEY: i32 = 2; const MALFORMED_PUBLIC_KEY: i32 = 3; const...
use core::convert::Into; use core::slice; use ed25519_dalek::*; use jni::objects::JClass; use jni::sys::{jbyteArray, jint}; use jni::JNIEnv; use std::convert::{From, TryFrom}; const SUCCESS: i32 = 0; const NATIVE_CONVERSION_ERROR: i32 = 1; const MALFORMED_SECRET_KEY: i32 = 2; const MALFORMED_PUBLIC_KEY: i32 = 3; const...
nvert_byte_array(sig_bytes) { Ok(x) => x, _ => return NATIVE_CONVERSION_ERROR, }; let signature: Signature = match Signature::try_from(&signature_bytes[..]) { Ok(sig) => sig, _ => return NATIVE_CONVERSION_ERROR, }; match public_key.verify(&message_bytes, &signature) { ...
_crypto_ed25519_ED25519_verify( env: JNIEnv, _class: JClass, pub_key_bytes: jbyteArray, msg_bytes: jbyteArray, sig_bytes: jbyteArray, ) -> jint { let public_key_bytes = match env.convert_byte_array(pub_key_bytes) { Ok(x) => x, _ => return NATIVE_CONVERSION_ERROR, }; let p...
function_block-random_span
[ { "content": " private final boolean success;\n", "file_path": "concordium-sdk/src/main/java/com/concordium/sdk/responses/transactionstatus/ResumedResult.java", "rank": 0, "score": 89515.34426715277 }, { "content": " private final Map<Index, Map<Index, byte[]>> signatures = new TreeMap...
Rust
src/main.rs
benjione/iot_webhook_server
2e35274013821d2513a3d82a3fb0fd3a4b232ebb
#[macro_use] extern crate diesel; use actix::*; use actix_files as fs; use actix_identity::Identity; use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_web::{error, get, http, web, App, Error, HttpResponse, HttpServer}; use diesel::SqliteConnection; use tera::Context; use tera::Tera; mod api; mod...
#[macro_use] extern crate diesel; use actix::*; use actix_files as fs; use actix_identity::Identity; use actix_identity::{CookieIdentityPolicy, IdentityService}; use actix_web::{error, get, http, web, App, Error, HttpResponse, HttpServer}; use diesel::SqliteConnection; use tera::Context; use tera::Tera; mod api; mod...
#[get("/profile")] async fn profile( id: Identity, tmpl: web::Data<tera::Tera>, pool: web::Data<Pool>, ) -> Result<HttpResponse, Error> { match only_allowed_for_logged_in_user(&id) { Some(ret) => return Ok(ret), _ => {} }; let mut context = Context::new(); context = check_l...
let mut context = Context::new(); context = check_logged_in_user(&id, context); context.insert("title", &"signup"); let s = tmpl .render("signup.html", &context) .map_err(|_| error::ErrorInternalServerError("Template error"))?; Ok(HttpResponse::Ok().content_type("text/html").body(s)) }
function_block-function_prefix_line
[ { "content": "type Pool = diesel::r2d2::Pool<diesel::r2d2::ConnectionManager<SqliteConnection>>;\n\n\n\n#[derive(Serialize, Deserialize, Queryable)]\n\npub struct Device {\n\n pub id: i32, // id of the device, unique\n\n pub registration_id: String, // Unique ID generated for registration ...
Rust
src/output/time.rs
dbrumbaugh/exa
1489f3ea833dcc67efffcddf8238864c30a35f12
use std::time::{SystemTime, UNIX_EPOCH}; use datetime::{LocalDateTime, TimeZone, DatePiece, TimePiece}; use datetime::fmt::DateFormat; use lazy_static::lazy_static; use unicode_width::UnicodeWidthStr; #[derive(PartialEq, Debug, Copy, Clone)] pub enum TimeFormat { DefaultFormat, ...
use std::time::{SystemTime, UNIX_EPOCH}; use datetime::{LocalDateTime, TimeZone, DatePiece, TimePiece}; use datetime::fmt::DateFormat; use lazy_static::lazy_static; use unicode_width::UnicodeWidthStr; #[derive(PartialEq, Debug, Copy, Clone)] pub enum TimeFormat { DefaultFormat, ...
#[allow(trivial_numeric_casts)] fn iso_local(time: SystemTime) -> String { let date = LocalDateTime::at(systemtime_epoch(time)); if is_recent(&date) { format!("{:02}-{:02} {:02}:{:02}", date.month() as usize, date.day(), date.hour(), date.minute()) } else { ...
ffset; let local = LocalDateTime::at(systemtime_epoch(time)); let date = zone.to_zoned(local); let offset = Offset::of_seconds(zone.offset(local) as i32).expect("Offset out of range"); format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09} {:+03}{:02}", date.year(), date.month() as usize, date....
function_block-function_prefixed
[]
Rust
src/write.rs
winstonewert/thread_io
85dfd37d3868914020d3c7f69704d37c12622755
use std::io::{self, Write}; use std::mem::replace; #[cfg(feature = "crossbeam_channel")] use crossbeam::channel::{unbounded as channel, Receiver, Sender}; #[cfg(not(feature = "crossbeam_channel"))] use std::sync::mpsc::{channel, Receiver, Sender}; use crossbeam; #[derive(Debug)] enum Message { Buffer(io::Curso...
use std::io::{self, Write}; use std::mem::replace; #[cfg(feature = "crossbeam_channel")] use crossbeam::channel::{unbounded as channel, Receiver, Sender}; #[cfg(not(feature = "crossbeam_channel"))] use std::sync::mpsc::{channel, Receiver, Sender}; use crossbeam; #[derive(Debug)] enum Message { Buffer(io::Curso...
} else { self.get_errors()?; Err(io::Error::from(io::ErrorKind::BrokenPipe)) } } #[inline] fn done(&mut self) -> io::Result<()> { self.send_to_background()?; self.full_send.send(Message::Done).ok(); Ok(()) ...
t<Box<[u8]>>>, full_send: Sender<Message>, bufsize: usize, ) -> Self { let buffer = io::Cursor::new(vec![0; bufsize].into_boxed_slice()); Writer { empty_recv, full_send, buffer, } } #[inline] fn send_to_background(&mut self) -...
random
[ { "content": "#[derive(Clone)]\n\nstruct Writer {\n\n cache: Vec<u8>,\n\n data: Vec<u8>,\n\n write_fails: bool,\n\n flush_fails: bool,\n\n bufsize: usize,\n\n}\n\n\n\nimpl Writer {\n\n fn new(write_fails: bool, flush_fails: bool, bufsize: usize) -> Writer {\n\n Writer {\n\n c...
Rust
src/borrow/cell_borrow.rs
ten3roberts/hecs-schedule
d23e1c197211f8809cdce7b5e9b1e17d8df82dbb
use std::{ any::type_name, marker::PhantomData, ops::{Deref, DerefMut}, ptr::NonNull, }; pub type Borrows = SmallVec<[Access; 8]>; use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use smallvec::{smallvec, SmallVec}; use crate::{Access, Context, Error, Result}; use super::ComponentBorrow...
use std::{ any::type_name, marker::PhantomData, ops::{Deref, DerefMut}, ptr::NonNull, }; pub type Borrows = SmallVec<[Access; 8]>; use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use smallvec::{smallvec, SmallVec}; use crate::{Access, Context, Error, Result}; use super::ComponentBorrow...
} impl<'a, T> Deref for Write<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a, T> DerefMut for Write<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } struct BorrowMarker<T> { marker: PhantomData<T>, } pub trait Context...
pub(crate) fn try_from_untyped(cell: &'a AtomicRefCell<NonNull<u8>>) -> Result<Self> { cell.try_borrow_mut() .map_err(|_| Error::BorrowMut(type_name::<T>())) .map(|cell| { Self(AtomicRefMut::map(cell, |val| unsafe { val.cast().as_mut() ...
function_block-full_function
[ { "content": "/// Lifetime erasure in waiting of GAT\n\npub trait IntoBorrow {\n\n /// The borrow type\n\n type Borrow: for<'x> ContextBorrow<'x>;\n\n}\n\n\n\n/// Macro for implementing lifetime eliding IntoBorrow\n\n#[macro_export]\n\nmacro_rules! impl_into_borrow {\n\n ($generic: tt, $name: tt => $bo...
Rust
src/weight_functions.rs
JohannesEller/feos-dft
161d93c723102c697d771401936dc6267a5c622a
use ndarray::*; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_3, PI}; use std::ops::Mul; #[derive(Clone)] pub struct WeightFunction<T> { pub prefactor: Array1<T>, pub kernel_radius: Array1<T>, pub shape: WeightFunctionShape, } impl<T: DualNum<f64>> WeightFunction<T> { pub ...
use ndarray::*; use num_dual::DualNum; use std::f64::consts::{FRAC_PI_3, PI}; use std::ops::Mul; #[derive(Clone)] pub struct WeightFunction<T> { pub prefactor: Array1<T>, pub kernel_radius: Array1<T>, pub shape: WeightFunctionShape, } impl<T: DualNum<f64>> WeightFunction<T> { pub ...
} impl<T> WeightFunctionInfo<T> { pub fn new(component_index: Array1<usize>, local_density: bool) -> Self { Self { component_index, local_density, scalar_component_weighted_densities: Vec::new(), vector_component_weighted_densities: Vec::new(), ...
if self.local_density { segments } else { 0 }) + self.scalar_component_weighted_densities.len() * segments + self.vector_component_weighted_densities.len() * segments * dimensions + self.scalar_fmt_weighted_densities.len() + self.vector_fmt_weighted_densities.len() * dime...
function_block-function_prefix_line
[ { "content": "#[pymodule]\n\npub fn feos_dft(py: Python<'_>, m: &PyModule) -> PyResult<()> {\n\n m.add_class::<PyExternalPotential>()?;\n\n m.add_class::<PyGeometry>()?;\n\n m.add_class::<PyDFTSolver>()?;\n\n\n\n m.add_class::<PyFMTVersion>()?;\n\n m.add_class::<PyFMTFunctional>()?;\n\n\n\n m....
Rust
crates/rune-cli/src/run/runecoral_inference.rs
ferrous-systems/rune
11d752759003ee2707efb904f596cbe8f9ee07a6
use std::{borrow::Cow, cell::Cell, convert::TryInto, path::Path, sync::Mutex}; use anyhow::{Context, Error}; use hotg_rune_core::{Shape, TFLITE_MIMETYPE, reflect::Type}; use hotg_runicos_base_runtime::{BaseImage, Model, ModelFactory}; use hotg_runecoral::{ElementType, InferenceContext, RuneCoral, Tensor, TensorDescrip...
use std::{borrow::Cow, cell::Cell, convert::TryInto, path::Path, sync::Mutex}; use anyhow::{Context, Error}; use hotg_rune_core::{Shape, TFLITE_MIMETYPE, reflect::Type}; use hotg_runicos_base_runtime::{BaseImage, Model, ModelFactory}; use hotg_runecoral::{ElementType, InferenceContext, RuneCoral, Tensor, TensorDescrip...
} struct RuneCoralModel { ctx: Mutex<InferenceContext>, inputs: Vec<Shape<'static>>, input_descriptors: Vec<TensorDescriptor<'static>>, outputs: Vec<Shape<'static>>, output_descriptors: Vec<TensorDescriptor<'static>>, } impl Model for RuneCoralModel { unsafe fn infer( &mut self, ...
Ok(match *rune_type { Type::i8 => ElementType::Int8, Type::u8 => ElementType::UInt8, Type::i16 => ElementType::Int16, Type::i32 => ElementType::Int32, Type::i64 => ElementType::Int64, Type::f32 => ElementType::Float32, Type::f64 => ElementType::Float64, Ty...
call_expression
[ { "content": "fn copy_docs(ctx: &Context) -> Result<(), Error> {\n\n let Context {\n\n project_root, dist, ..\n\n } = ctx;\n\n\n\n std::fs::copy(project_root.join(\"README.md\"), dist.join(\"README.md\"))\n\n .context(\"Unable to copy the README across\")?;\n\n\n\n BulkCopy::new(&[\"*....
Rust
rsp2/tests/force-constants.rs
colin-daniels/agnr-ml
fc936cb8b6a68c37dfaf64c74796e0cf795c1bb8
#[macro_use] extern crate rsp2_assert_close; #[macro_use] extern crate rsp2_integration_test; #[macro_use] extern crate serde_derive; type FailResult<T> = Result<T, ::failure::Error>; use rsp2_integration_test::{resource, filetypes::Primitive}; use rsp2_dynmat::SuperForceConstants; use rsp2_array_types::{M33, V3, Un...
#[macro_use] extern crate rsp2_assert_close; #[macro_use] extern crate rsp2_integration_test; #[macro_use] extern crate serde_derive; type FailResult<T> = Result<T, ::failure::Error>; use rsp2_integration_test::{resource, filetypes::Primitive}; use rsp2_dynmat::SuperForceConstants; use rsp2_array_types::{M33, V3, Un...
absolute: 1e-12 }, ).unwrap() } #[test] fn graphene_sparseforce_771() { check( "primitive/graphene.json", "force-constants/graphene-771-sparse.super.json", Some("force-constants/graphene-771.fc.json.xz"), "force-constants/graphene-ga...
"force-constants/graphene-gamma.dynmat.json", V3::zero(), Tolerances { relative: 1e-10,
function_block-random_span
[ { "content": "/// Given dims `[a, b, c]`, makes a supercell of size `[2a + 1, 2b + 1, 2c + 1]`.\n\npub fn centered_diagonal(extra_images: [u32; 3]) -> Builder {\n\n let extra_images = V3(extra_images);\n\n\n\n Builder {\n\n diagonal: (extra_images * 2 + V3([1; 3])).0,\n\n offset: extra_image...
Rust
src/game_over.rs
yopox/LD49
ec170a997bcc844c833951c5d58e1b3672fff706
use bevy::prelude::*; use bevy_kira_audio::Audio; use crate::{AppState, HEIGHT, PlayerData, WIDTH, MySelf}; use crate::fight::fight_screen::FightBackup; use crate::data::font::TextStyles; use crate::data::loading::{AudioAssets, TextureAssets}; use crate::ui::StateBackground; use crate::ui::card_overlay::NewCard; use c...
use bevy::prelude::*; use bevy_kira_audio::Audio; use crate::{AppState, HEIGHT, PlayerData, WIDTH, MySelf}; use crate::fight::fight_screen::FightBackup; use crate::data::font::TextStyles; use crate::data::loading::{AudioAssets, TextureAssets}; use crate::ui::StateBackground; use crate::ui::card_overlay::NewCard; use c...
e: ResMut<State<AppState>>, btn: Res<Input<MouseButton>>, ) { if btn.just_released(MouseButton::Left) { app_state.set(AppState::Title).unwrap(); } }
transform: Transform { translation: Vec3::new(WIDTH / 2., HEIGHT / 4., 1.), ..Default::default() }, ..Default::default() }).insert(Over); commands.spawn_bundle(Text2dBundle { text: Text::with_section(if won.0 { "You won!" } else { "You lost!" }, ...
random
[ { "content": "pub fn card_transform(x: f32, y: f32) -> Transform {\n\n return Transform {\n\n translation: Vec3::new(x, y, 2.),\n\n scale: Vec3::new(CARD_SCALE, CARD_SCALE, 1.),\n\n ..Default::default()\n\n };\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 18...
Rust
grin/src/adapters.rs
AmarRSingh/grin
2caa0b79e04722011814b1adf2a8a449b05799f2
use std::net::SocketAddr; use std::sync::{Arc, RwLock}; use std::sync::atomic::{AtomicBool, Ordering}; use chain::{self, ChainAdapter}; use core::core::{self, Output}; use core::core::block::BlockHeader; use core::core::hash::{Hash, Hashed}; use core::core::target::Difficulty; use p2p; use pool; use util::secp::pede...
use std::net::SocketAddr; use std::sync::{Arc, RwLock}; use std::sync::atomic::{AtomicBool, Ordering}; use chain::{self, ChainAdapter}; use core::core::{self, Output}; use core::core::block::BlockHeader; use core::core::hash::{Hash, Hashed}; use core::core::target::Difficulty; use p2p; use pool; use util::secp::pede...
or[1..].to_vec()) } else { Some(header) } } else { self.find_common_header(locator[1..].to_vec()) } }, Err(chain::Error::StoreErr(store::Error::NotFoundErr, _)) => { self.find_common_header(locator[1..].to_vec()) }, Err(e) => { error!(LOGGER, "Could not build header loca...
ed block {} at {} from network, going to process.", bhash, b.header.height, ); let res = self.chain.process_block(b, self.chain_opts()); if let &Err(ref e) = &res { debug!(LOGGER, "Block {} refused by chain: {:?}", bhash, e); if e.is_bad_block() { return false; ...
random
[ { "content": "/// Using transaction merkle_inputs_outputs to calculate a deterministic hash;\n\n/// this hashing mechanism has some ambiguity issues especially around range\n\n/// proofs and any extra data the kernel may cover, but it is used initially\n\n/// for testing purposes.\n\npub fn transaction_identifi...
Rust
MixxNet/deployments/rainbow-bridge/contracts/near/eth-prover/tests/utils.rs
GigameshGarages/MezzooNet
d1a1115feacbc9776167f5d17a5e2b1fcf29bea4
#![allow(dead_code)] use borsh::{BorshDeserialize, BorshSerialize}; use eth_types::*; use hex::FromHex; use near_crypto::{InMemorySigner, KeyType, Signer}; use near_primitives::{ account::{AccessKey, Account}, errors::{RuntimeError, TxExecutionError}, hash::CryptoHash, transaction::{ExecutionOutcome, Ex...
#![allow(dead_code)] use borsh::{BorshDeserialize, BorshSerialize}; use eth_types::*; use hex::FromHex; use near_crypto::{InMemorySigner, KeyType, Signer}; use near_primitives::{ account::{AccessKe
_static! { static ref ETH_PROVER_WASM_BYTES: &'static [u8] = include_bytes!("../../res/eth_prover.wasm").as_ref(); static ref ETH_CLIENT_WASM_BYTES: &'static [u8] = include_bytes!("../../res/eth_client.wasm").as_ref(); } pub fn ntoy(near_amount: Balance) -> Balance { near_amount * 10u128.pow(24) } pub str...
y, Account}, errors::{RuntimeError, TxExecutionError}, hash::CryptoHash, transaction::{ExecutionOutcome, ExecutionStatus, Transaction}, types::{AccountId, Balance}, }; use near_runtime_standalone::init_runtime_and_signer; pub use near_runtime_standalone::RuntimeStandalone; pub use near_sdk::VMContext; u...
random
[ { "content": "-- This view needs to handle 'normal' subgraphs and the fake subgraphs that\n", "file_path": "GixxNet/store/postgres/migrations/2020-12-12-000004_sharded_deployment_detail/up.sql", "rank": 0, "score": 86155.60445825255 }, { "content": "-- Before proceeding and throwing away dat...
Rust
librustuv/src/pipe.rs
alexcrichton/green-rs
b7e17fc19bb90d0bb53914e66251e68cc15594e4
use std::c_str::CString; use std::io; use std::mem; use std::rt::task::BlockedTask; use std::sync::Arc; use std::time::Duration; use libc; use access::Access; use homing::{HomingIO, HomeHandle}; use raw::Handle; use stream::Stream; use timeout::{Pusher, AcceptTimeout, ConnectCtx, AccessTimeout}; use {raw, uvll, tcp,...
use std::c_str::CString; use std::io; use std::mem; use std::rt::task::BlockedTask; use std::sync::Arc; use std::time::Duration; use libc; use access::Access; use homing::{HomingIO, HomeHandle}; use raw::Handle; use stream::Stream; use timeout::{Pusher, AcceptTimeout, ConnectCtx, AccessTimeout}; use {raw, uvll, tcp,...
} impl Drop for PipeListener { fn drop(&mut self) { let _m = self.fire_homing_missile(); unsafe { self.handle.close_and_free() } } } impl PipeAcceptor { pub fn accept(&mut self) -> UvResult<Pipe> { let m = self.fire_homing_missile(); let uv_loop = self.data.listener.handle...
use raw::Stream; let mut handle = listener.handle; let client = try!(Pipe::new(&handle.uv_loop(), listener.home.clone())); try!(handle.accept(client.data.handle)); Ok(client) }
function_block-function_prefix_line
[ { "content": "pub fn slice_to_uv_buf(v: &[u8]) -> uvll::uv_buf_t {\n\n let data = v.as_ptr();\n\n uvll::uv_buf_t { base: data as *mut u8, len: v.len() as uvll::uv_buf_len_t }\n\n}\n\n\n", "file_path": "librustuv/src/raw/mod.rs", "rank": 0, "score": 263456.35914425325 }, { "content": "/...
Rust
leint/src/lib.rs
gianlucamazza/proofmarshal
8b7181e669067d731b52829777d7f22e9b6a9967
use core::cmp; use core::fmt; use core::hash::{Hash, Hasher}; use core::mem; use core::num::{ NonZeroU16, NonZeroI16, NonZeroU32, NonZeroI32, NonZeroU64, NonZeroI64, NonZeroU128, NonZeroI128, }; use core::slice; #[repr(packed)] pub struct Le<T: sealed::ToFromLe>(T); mod sealed { use super::*;...
use core::cmp; use core::fmt; use core::hash::{Hash, Hasher}; use core::mem; use core::num::{ NonZeroU16, NonZeroI16, NonZeroU32, NonZeroI32, NonZeroU64, NonZeroI64, NonZeroU128, NonZeroI128, }; use core::slice; #[repr(packed)] pub struct Le<T: sealed::ToFromLe>(T); mod sealed { use super::*;...
=> i64; NonZeroU128 => u128; NonZeroI128 => i128; ); #[cfg(test)] mod tests { use super::*; #[test] fn alignment() { assert_eq!(mem::align_of::<Le<u16>>(), 1); assert_eq!(mem::align_of::<Le<u32>>(), 1); assert_eq!(mem::align_of::<Le<u64>>(), 1); assert_eq!(mem::al...
( $( $t:ident, )+ ) => { $( impl_tofromle!($t, $t); )+ }; } /* unsafe impl<T: NonZero + ToFromLe> NonZero for Le<T> {} */ macro_rules! impl_nonzero_ints { ( $( $t:ident => $inner:ident; )+ ) => { $( impl_tofromle!($t, $inner); )+ }; } macro_rules! ...
random
[ { "content": "pub trait EncodePrimitive : for<'a> Encode<'a, !, State=(), Encoded=Self> {\n\n #[inline(always)]\n\n fn encode_primitive_blob<W: WriteBlob>(&self, dst: W) -> Result<W::Ok, W::Error> {\n\n self.encode_blob(&(), dst)\n\n }\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! impl_encode_for_...
Rust
examples/hello_world/src/main.rs
second-state/pickledb-rs
2fc235986cc377c62df62c289f8562a86fad2008
use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod}; use serde::{Deserialize, Serialize}; use std::fmt::{self, Display, Formatter}; #[derive(Serialize, Deserialize)] struct Rectangle { width: i32, length: i32, } impl Display for Rectangle { fn fmt(&self, f: &mut Formatter) -> fmt::Result {...
use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod}; use serde::{Deserialize, Serialize}; use std::fmt::{self, Display, Formatter}; #[derive(Serialize, Deserialize)] struct Rectangle { width: i32, length: i32, } impl Display for Rectangle { fn fmt(&self, f: &mut Formatter) -> fmt::Result {...
kv.get_key(), kv.get_value::<Vec<i32>>().unwrap() ), "key5" => println!( "Value of {} is: {}", kv.get_key(), kv.get_value::<Rectangle>().unwrap() ), _ => (), } } }
), "key3" => println!( "Value of {} is: {}", kv.get_key(), kv.get_value::<String>().unwrap() ), "key4" => println!( "Value of {} is: {:?}",
random
[ { "content": "#[rstest_parametrize(ser_method_int, case(0), case(1), case(2), case(3))]\n\nfn remove_values_from_list(ser_method_int: i32) {\n\n test_setup!(\"remove_values_from_list\", ser_method_int, db_name);\n\n\n\n let mut db = PickleDb::new(\n\n &db_name,\n\n PickleDbDumpPolicy::AutoDu...
Rust
src/model.rs
Lemmih/cargo-criterion
81c56c6c6e776216fff0231658ae7cf30e6dfca5
use crate::connection::Throughput; use crate::estimate::{ChangeEstimates, Estimates}; use crate::report::{BenchmarkId, ComparisonData, MeasurementData}; use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use linked_hash_map::LinkedHashMap; use std::collections::HashSet; use std::ffi::OsStr; use std::fs...
use crate::connection::Throughput; use crate::estimate::{ChangeEstimates, Estimates}; use crate::report::{BenchmarkId, ComparisonData, MeasurementData}; use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use linked_hash_map::LinkedHashMap; use std::collections::HashSet; use std::ffi::OsStr; use std::fs...
fn load_stored_benchmark(&mut self, benchmark_path: &Path) -> Result<()> { if !benchmark_path.is_file() { return Ok(()); } let mut benchmark_file = File::open(&benchmark_path) .with_context(|| format!("Failed to open benchmark file {:?}", benchmark_path))?; ...
w(), history_id, history_description, }; for entry in WalkDir::new(&model.data_directory) .into_iter() .filter_map(::std::result::Result::ok) .filter(|entry| entry.file_name() == OsStr::new("benchmark.cbor")) { ...
function_block-function_prefixed
[ { "content": "/// Call `cargo criterion` and parse the output to get the path to the target directory.\n\nfn get_target_directory_from_metadata() -> Result<PathBuf> {\n\n let out = Command::new(\"cargo\")\n\n .args(&[\"metadata\", \"--format-version\", \"1\"])\n\n .output()?;\n\n\n\n #[deriv...
Rust
src/lib.rs
ajfrantz/wait-around
608c2a2c93de516b6668584dfdf61f50ca708282
#[cfg(feature = "no_std")] extern crate alloc; #[cfg(not(feature = "no_std"))] extern crate std as alloc; use alloc::{rc::Rc, vec::Vec}; use core::{cell::RefCell, pin::Pin}; use futures::{ io::Error, prelude::*, task::{Context, Poll, Waker}, }; pub struct RingBuffer { data: Vec<u8>, read_idx: usiz...
#[cfg(feature = "no_std")] extern crate alloc; #[cfg(not(feature = "no_std"))] extern crate std as alloc; use alloc::{rc::Rc, vec::Vec}; use core::{cell::RefCell, pin::Pin}; use futures::{ io::Error, prelude::*, task::{Context, Poll, Waker}, }; pub struct RingBuffer { data: Vec<u8>, read_idx: usiz...
}
_idx < self.read_idx { write_idx += 2 * capacity; } let remaining_space = capacity - (write_idx - self.read_idx); let space_before_end = capacity - self.wrap(self.write_idx); remaining_space.min(space_before_end) } fn park(&mut self, waker: &Waker) { self.wa...
random
[ { "content": "# async/await-friendly circular buffer\n\n\n\nThis library provides a [circular\n\nbuffer](https://en.wikipedia.org/wiki/Circular_buffer) that implements\n\n`AsyncRead` and `AsyncWrite`. It's meant to be useful to embedded applications\n\nwhich want to use async/await but for which the full might...
Rust
src/message_formats/json.rs
ccleve/cargo-criterion
c4003934318015a06a6c48e8e6e9d855662c0485
use crate::connection::Throughput as ThroughputEnum; use crate::estimate::Estimate; use crate::model::BenchmarkGroup; use crate::report::{ compare_to_threshold, BenchmarkId, ComparisonResult, MeasurementData, Report, ReportContext, }; use crate::value_formatter::ValueFormatter; use anyhow::Result; use serde...
use crate::connection::Throughput as ThroughputEnum; use crate::estimate::Estimate; use crate::model::BenchmarkGroup; use crate::report::{ compare_to_threshold, BenchmarkId, ComparisonResult, MeasurementData, Report, ReportContext, }; use crate::value_formatter::ValueFormatter; use anyhow::Result; use serde...
} #[derive(Serialize)] struct Throughput { per_iteration: u64, unit: String, } impl From<&ThroughputEnum> for Throughput { fn from(other: &ThroughputEnum) -> Self { match other { ThroughputEnum::Bytes(bytes) => Throughput { per_iteration: *bytes, ...
fn from_percent(estimate: &Estimate) -> ConfidenceInterval { ConfidenceInterval { estimate: estimate.point_estimate, lower_bound: estimate.confidence_interval.lower_bound, upper_bound: estimate.confidence_interval.upper_bound, unit: "%".to_owned(), }...
function_block-full_function
[ { "content": "pub fn make_filename_safe(string: &str) -> String {\n\n let mut string = string.replace(\n\n &['?', '\"', '/', '\\\\', '*', '<', '>', ':', '|', '^'][..],\n\n \"_\",\n\n );\n\n\n\n // Truncate to last character boundary before max length...\n\n truncate_to_character_bounda...
Rust
src/cron_parser.rs
j5ik2o/chronos-parser-rs
171f8f4f701de591e0a8da8d5ff0f07f66c9da69
use pom::parser::*; use crate::Expr; use crate::Expr::{ AnyValueExpr, CronExpr, LastValueExpr, ListExpr, NoOp, PerExpr, RangeExpr, ValueExpr, }; fn min_digit<'a>() -> Parser<'a, u8, Expr> { (one_of(b"12345") + one_of(b"0123456789")).map(|(e1, e2)| ValueExpr((e1 - 48) * 10 + e2 - 48)) | (sym(b'0') * one_of(b"0...
use pom::parser::*; use crate::Expr; use crate::Expr::{ AnyValueExpr, CronExpr, LastValueExpr, ListExpr, NoOp, PerExpr, RangeExpr, ValueExpr, }; fn min_digit<'a>() -> Parser<'a, u8, Expr> { (one_of(b"12345") + one_of(b"0123456789")).map(|(e1, e2)| ValueExpr((e1 - 48) * 10 + e2 - 48)) | (sym(b'0') * one_of(b"0...
let s: &str = &format!("{:<02}", n); let result: Expr = (month_digit() - end()).parse(s.as_bytes()).unwrap(); assert_eq!(result, ValueExpr(n)); } let result = (month_digit() - end()).parse(b"13"); assert_eq!(result.is_err(), true); } }
if n < 10 { let s: &str = &n.to_string(); let result: Expr = (month_digit() - end()).parse(s.as_bytes()).unwrap(); assert_eq!(result, ValueExpr(n)); }
if_condition
[ { "content": "fn get_days_from_month(year: i32, month: u32) -> i64 {\n\n NaiveDate::from_ymd(\n\n match month {\n\n 12 => year + 1,\n\n _ => year,\n\n },\n\n match month {\n\n 12 => 1,\n\n _ => month + 1,\n\n },\n\n 1,\n\n )\n\n .signed_duration_since(NaiveDate::from_ymd(ye...
Rust
src/code/mod.rs
aesir-vanir/libtyr
a3de0f4186ffc71080082e31908d5c6bfde879c5
use dam::{ColumnMetadata, RowsMetadata, TablesMetadata}; use error::{ErrorKind, Result}; use inflector::cases::pascalcase::to_pascal_case; use inflector::cases::snakecase::to_snake_case; use mustache; use std::fs::{self, File}; use std::io::BufWriter; use std::path::PathBuf; mod tmpl; use self::tmpl::{Derive, Deriv...
use dam::{ColumnMetadata, RowsMetadata, TablesMetadata}; use error::{ErrorKind, Result}; use inflector::cases::pascalcase::to_pascal_case; use inflector::cases::snakecase::to_snake_case; use mustache; use std::fs::{self, File}; use std::io::BufWriter; use std::path::PathBuf; mod tmpl; use self::tmpl::{Derive, Deriv...
} pub fn mod_gen(path: &PathBuf, tables_metadata: &TablesMetadata) -> Result<()> { let template = mustache::compile_str(MOD_RS)?; let mut table_mods = Vec::new(); for table_name in tables_metadata.keys() { let lc_table_name: String = table_name.chars().map(|c| c.to_lowercase().to_string()).collec...
fs::create_dir_all(&self.module_path)?; mod_gen(&self.module_path, tables_metadata)?; for (table_name, rows) in tables_metadata { table_gen(&self.module_path, table_name, rows)? } Ok(()) }
function_block-function_prefix_line
[ { "content": "/// Pretty print table metadata.\n\npub fn pretty_print(tables: &TablesMetadata) -> Result<()> {\n\n for (table, rows) in tables {\n\n let mut t = term::stdout().ok_or_else(|| ErrorKind::Stdout)?;\n\n t.attr(term::Attr::Bold)?;\n\n t.fg(term::color::GREEN)?;\n\n let ...
Rust
src/master/mobility.rs
Dash83/MeshSim
a273cc62af1686b2696ebdd20311333bcb6c79f7
use crate::backend::{stop_all_workers, update_worker_vel, select_workers_at_destination, stop_workers, update_worker_target}; use crate::MeshSimError; use crate::worker::Worker; use crate::master::test_specification::Area; use diesel::pg::PgConnection; use slog::Logger; use std::collections::HashMap; use rand::{rngs::S...
use crate::backend::{stop_all_workers, update_worker_vel, select_workers_at_destination, stop_workers, update_worker_target}; use crate::MeshSimError; use crate::worker::Worker; use crate::master::test_specification::Area; use diesel::pg::PgConnection; use slog::Logger; use std::collections::HashMap; use rand::{rngs::S...
} impl MobilityHandler for IncreasedMobility { fn handle_iteration(&mut self,) -> Result<Vec<NodeState>, MeshSimError> { let workers = select_workers_at_destination(&self.conn)?; let newly_arrived: Vec<NodeState> = workers.into_iter() .filter(|n| !self.paused_workers.con...
a.width); let height_dist = Uniform::new_inclusive(0., simulation_area.height); IncreasedMobility { paused_workers, velocity_increase: vel_incr, area_width_dist: width_dist, area_height_dist: height_dist, pause_time, conn, ...
function_block-function_prefixed
[]
Rust
src/json_schema/validators/of.rs
swarkentin/valico
f6aed770ef3b0f1215636b29c696c2a69e29f92b
use serde_json::Value; use std::borrow::Cow; use super::super::errors; use super::super::scope; #[allow(missing_copy_implementations)] pub struct AllOf { pub schemes: Vec<url::Url>, } impl super::Validator for AllOf { fn validate(&self, val: &Value, path: &str, scope: &scope::Scope) -> super::ValidationState...
use serde_json::Value; use std::borrow::Cow; use super::super::errors; use super::super::scope; #[allow(missing_copy_implementations)] pub struct AllOf { pub schemes: Vec<url::Url>, } impl super::Validator for AllOf { fn validate(&self, val: &Value, path: &str, scope: &scope::Scope) -> super::ValidationState...
} #[allow(missing_copy_implementations)] pub struct OneOf { pub schemes: Vec<url::Url>, } impl super::Validator for OneOf { fn validate(&self, val: &Value, path: &str, scope: &scope::Scope) -> super::ValidationState { let mut state = super::ValidationState::new(); let mut val = Cow::Borrowed(...
else { states.push(result) } } else { state.missing.push(url.clone()) } } if !valid { state.errors.push(Box::new(errors::AnyOf { path: path.to_string(), states, })) ...
function_block-function_prefix_line
[ { "content": "pub fn parse_url_key(key: &str, obj: &Value) -> Result<Option<Url>, schema::SchemaError> {\n\n match obj.get(key) {\n\n Some(value) => match value.as_str() {\n\n Some(string) => Url::parse(string)\n\n .map(Some)\n\n .map_err(schema::SchemaError::U...
Rust
src/ethernet/ethernet_rx.rs
faern/rips-old
abff3837894a404895c6c2dc11ec45377f6dc811
use {RxResult, RxError}; use ethernet::EtherType; use pnet::packet::Packet; use pnet::packet::ethernet::EthernetPacket; use rx::RxListener; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::sync::mpsc::Sender; use std::time::SystemTime; pub trait EthernetListener: Send { fn rec...
use {RxResult, RxError}; use ethernet::EtherType; use pnet::packet::Packet; use pnet::packet::ethernet::EthernetPacket; use rx::RxListener; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::sync::mpsc::Sender; use std::time::SystemTime; pub trait EthernetListener: Send { fn rec...
} } #[cfg(test)] mod tests { use super::*; use RxError; use ethernet::{EtherType, EtherTypes}; use pnet::packet::Packet; use pnet::packet::ethernet::{EthernetPacket, MutableEthernetPacket}; use rx::RxListener; use std::sync::mpsc::{self, Receiver}; use std::time::SystemTime; ...
match self.listeners.get_mut(&ethertype) { Some(listener) => listener.recv(time, packet), None => Err(RxError::NoListener(format!("Ethernet: No listener for {}", ethertype))), }
if_condition
[ { "content": "pub trait RxListener: Send {\n\n fn recv(&mut self, time: SystemTime, packet: &EthernetPacket) -> RxResult;\n\n}\n\n\n", "file_path": "src/rx.rs", "rank": 0, "score": 142827.39647350827 }, { "content": "/// Trait that must be implemented by any struct who want to receive Icm...
Rust
src/value.rs
gemmaro/csa-rs
1dbc6ae2ee577613eaa4f8de6df92cfff971b7a6
use chrono::{NaiveDate, NaiveTime}; use std::fmt; use std::time::Duration; #[derive(Default, Debug, PartialEq, Eq)] pub struct GameRecord { pub black_player: Option<String>, pub white_player: Option<String>, pub event: Option<String>, pub site: Option<String>, pub start_time: Option<Time>, pub ...
use chrono::{NaiveDate, NaiveTime}; use std::fmt; use std::time::Duration; #[derive(Default, Debug, PartialEq, Eq)] pub struct GameRecord { pub black_player: Option<String>, pub white_player: Option<String>, pub event: Option<String>, pub site: Option<String>, pub start_time: Option<Time>, pub ...
t_eq!(&PieceType::Silver.to_string(), "GI"); assert_eq!(&PieceType::Gold.to_string(), "KI"); assert_eq!(&PieceType::Bishop.to_string(), "KA"); assert_eq!(&PieceType::Rook.to_string(), "HI"); assert_eq!(&PieceType::King.to_string(), "OU"); assert_eq!(&PieceType::ProPawn.to_string(...
one, Copy)] pub enum Action { Move(Color, Square, Square, PieceType), Toryo, Chudan, Sennichite, TimeUp, IllegalMove, IllegalAction(Color), Jishogi, Kachi, Hikiwake, Matta, Tsumi, Fuzumi, Error, } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Form...
random
[]
Rust
src/webp.rs
joppuyo/pio
63c12ddca1d47f8459d19f74daca07ad39f1014b
use libwebp_sys::*; use rgb::RGBA8; use std::mem::MaybeUninit; use crate::common::{exif_orientation, orient_image, CompressResult, Image, ReadResult}; use crate::profile::{is_srgb, SRGB_PROFILE}; pub fn read(buffer: &[u8]) -> ReadResult { unsafe { let data = WebPData { bytes: buffer.as_ptr()...
use libwebp_sys::*; use rgb::RGBA8; use std::mem::MaybeUninit; use crate::common::{exif_orientation, orient_image, CompressResult, Image, ReadResult}; use crate::profile::{is_srgb, SRGB_PROFILE}; pub fn read(buffer: &[u8]) -> ReadResult { unsafe { let data = WebPData { bytes: buffer.as_ptr()...
4 * image.width * image.height, (4 * image.width) as i32, ); if ret.is_null() { WebPDataClear(&mut output); return Err("Failed to decode image data".to_string()); } let buffer = std::slice::from_raw_parts(output.bytes, output.size as usize).t...
if config.lossless == 1 || config.use_sharp_yuv == 1 || config.preprocessing > 0 { pic.use_argb = 1; } let stride = image.width as i32 * 4; let ret = WebPPictureImportRGBA(&mut pic, image.as_bytes().as_ptr(), stride); if ret == 0 { WebPPi...
function_block-random_span
[ { "content": "pub fn read(buffer: &[u8]) -> ReadResult {\n\n let mut decoder = lodepng::Decoder::new();\n\n decoder.remember_unknown_chunks(true);\n\n decoder.info_raw_mut().colortype = lodepng::ColorType::RGBA;\n\n\n\n let mut png = match decoder.decode(&buffer) {\n\n Ok(lodepng::Image::RGBA...
Rust
src/executor/evaluate/evaluated.rs
silathdiir/gluesql
036080b7c5155a2bb6b8a26bdaa6a26805019e53
use std::cmp::Ordering; use std::convert::{TryFrom, TryInto}; use sqlparser::ast::Value as AstValue; use crate::data; use crate::data::Value; use crate::result::{Error, Result}; use super::EvaluateError; #[derive(std::fmt::Debug)] pub enum Evaluated<'a> { LiteralRef(&'a AstValue), Literal(AstValue), Str...
use std::cmp::Ordering; use std::convert::{TryFrom, TryInto}; use sqlparser::ast::Value as AstValue; use crate::data; use crate::data::Value; use crate::result::{Error, Result}; use super::EvaluateError; #[derive(std::fmt::Debug)] pub enum Evaluated<'a> { LiteralRef(&'a AstValue), Literal(AstValue), Str...
4>() .map_or_else( |_| v.parse::<f64>().map(|v| AstValue::Number((-v).to_string())), |v| Ok(AstValue::Number((-v).to_string())), ) .map_err(|_| EvaluateError::LiteralUnaryMinusOnNonNumeric.into()), AstValue::Null => Ok(AstValue::Null), ...
function_block-function_prefixed
[]
Rust
src/v8_finder/v8_platform.rs
EightM/v8find4rs
9c97adbb68bba53e6dd909eed6384fbd927cbe7d
use crate::v8_app::{V8Arch, V8AppType}; use std::path::PathBuf; use std::cmp::Ordering; use crate::v8_finder::v8_dir::V8Dir; use itertools::Itertools; use std::{env, io}; use std::fs::File; use std::io::{Read, Error, ErrorKind}; use regex::Regex; use encoding_rs_io::DecodeReaderBytes; use lazy_static::lazy_static; laz...
use crate::v8_app::{V8Arch, V8AppType}; use std::path::PathBuf; use std::cmp::Ordering; use crate::v8_finder::v8_dir::V8Dir; use itertools::Itertools; use std::{env, io}; use std::fs::File; use std::io::{Read, Error, ErrorKind}; use regex::Regex; use encoding_rs_io::DecodeReaderBytes; use lazy_static::lazy_static; laz...
fn v8_windows_paths() -> Result<Vec<V8Dir>, io::Error> { let all_users_starter = get_starter_path_windows("ALLUSERSPROFILE")?; let mut v8_paths_all_users = read_locations_from_starter( all_users_starter)?; let local_user_starter = get_starter_path_windows("APPDATA")?; let mut v8_paths_local_u...
fn v8_macos_paths() -> Result<Vec<V8Dir>, io::Error> { let starter_cfg_path = PathBuf::from("~/.1C/1cestart"); let mut locations_from_starter = read_locations_from_starter(starter_cfg_path)?; let mut default_v8_paths = read_default_macos_paths(); let mut v8_all_paths = Vec::new(); v8_all_paths.appe...
function_block-function_prefix_line
[ { "content": "fn get_v8s_suffix() -> &'static str {\n\n let current_os = env::consts::OS;\n\n match current_os {\n\n \"windows\" => r\"bin\\1cv8s.exe\",\n\n _ => \"1cv8s\",\n\n }\n\n}\n", "file_path": "src/v8_app.rs", "rank": 9, "score": 52139.56261356953 }, { "content...
Rust
src/database/dataset.rs
Nilix007/betree_storage_stack
cd3334794b98b45a3ab24022db6e51b42dcd7dde
use super::errors::*; use super::Database; use super::{ds_data_key, fetch_ds_data, DatasetData, DatasetId, DatasetTree, Generation}; use crate::cow_bytes::{CowBytes, SlicedCowBytes}; use crate::tree::{DefaultMessageAction, Tree, TreeBaseLayer, TreeLayer}; use std::borrow::Borrow; use std::collections::HashSet; use std:...
use super::errors::*; use super::Database; use super::{ds_data_key, fetch_ds_data, DatasetData, DatasetId, DatasetTree, Generation}; use crate::cow_bytes::{CowBytes, SlicedCowBytes}; use crate::tree::{DefaultMessageAction, Tree, TreeBaseLayer, TreeLayer}; use std::borrow::Borrow; use std::collections::HashSet; use std:...
} pub fn close_dataset(&mut self, ds: Dataset) -> Result<()> { self.sync_ds(ds.id, &ds.tree)?; self.open_datasets.remove(&ds.id); self.root_tree .dmu() .handler() .last_snapshot_generation .write() .remove(&ds.id); ...
Ok(self.root_tree.range(low..high)?.map(move |result| { let (b, _) = result?; let len = b.len() as u32; Ok(b.slice(1, len - 1)) }))
call_expression
[ { "content": "fn ss_data_key_max(mut ds_id: DatasetId) -> [u8; 9] {\n\n ds_id.0 += 1;\n\n let mut key = [0; 9];\n\n key[0] = 4;\n\n key[1..9].copy_from_slice(&ds_id.pack());\n\n key\n\n}\n\n\n", "file_path": "src/database/mod.rs", "rank": 0, "score": 322620.1202356167 }, { "co...
Rust
packages/ffi-qrcode/src/lib.rs
TianLiangZhou/php-ffi-packages
febbf15dc22c1e1bd4ca597bb40782058057b9a5
use qrcode::{QrCode, EcLevel}; use image::{Rgba, Pixel as ImagePixel, GenericImageView}; use qrcode::render::{Renderer as QrRenderer, svg::Color, Pixel, unicode::Dense1x2}; use std::ffi::{CStr, CString}; use std::{ptr, slice}; use std::cell::RefCell; use std::error::Error; use std::os::raw::{c_int, c_char}; use image::...
use qrcode::{QrCode, EcLevel}; use image::{Rgba, Pixel as ImagePixel, GenericImageView}; use qrcode::render::{Renderer as QrRenderer, svg::Color, Pixel, unicode::Dense1x2}; use std::ffi::{CStr, CString}; use std::{ptr, slice}; use std::cell::RefCell; use std::error::Error; use std::os::raw::{c_int, c_char}; use image::...
ogo_w = logo_image_rgba.width(); let logo_h = logo_image_rgba.height(); let start_x = (w - logo_w) / 2; let start_y = (h - logo_h) / 2; for (x, y, p) in image.enumerate_pixels_mut() { if x >= start_x && y >= start_y && x - start_x <= logo_w - 1 && y - start_y <= logo_h - 1 {...
ustomRender for QrRenderer<'a, &str> { fn render(&mut self, _cfg: Cfg) -> String { self.build() } fn set_color(&mut self, bg: &'static str, fg: &'static str) { if bg.len() > 0 { self.light_color(bg); } if fg.len() > 0 { self.dark_color(fg); } ...
random
[ { "content": "fn const_to_str(str: *const c_char) -> &'static str {\n\n return unsafe { CStr::from_ptr(str) }.to_str().unwrap();\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::ffi::CStr;\n\n use crate::{Mode, to_pinyin, to_pinyin_array};\n\n\n\n #[test]\n\n fn it_works() {\n\n\n\n le...
Rust
azul-core/display_list.rs
niklasha/azul
dad5345942b82ed0273c48140a931bbbf81deae7
use std::fmt; use azul_css::{ LayoutPoint, LayoutSize, LayoutRect, StyleBackgroundRepeat, StyleBackgroundPosition, ColorU, BoxShadowClipMode, LinearGradient, RadialGradient, BoxShadowPreDisplayItem, StyleBackgroundSize, CssPropertyValue, StyleBorderTopWidth, StyleBorderRightWidth, StyleBorderBottom...
use std::fmt; use azul_css::{ LayoutPoint, LayoutSize, LayoutRect, StyleBackgroundRepeat, StyleBackgroundPosition, ColorU, BoxShadowClipMode, LinearGradient, RadialGradient, BoxShadowPreDisplayItem, StyleBackgroundSize, CssPropertyValue, StyleBorderTopWidth, StyleBorderRightWidth, StyleBorderBottom...
} #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ImageRendering { Auto, CrispEdges, Pixelated, } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum AlphaType { Alpha, PremultipliedAlpha, } #[derive(Default, Copy, Clone, PartialEq, Eq, Parti...
DisplayListFrame { tag: None, clip_rect: None, rect: LayoutRect { origin: LayoutPoint { x: 0.0, y: 0.0 }, size: dimensions, }, border_radius: StyleBorderRadius::default(), content: vec![], children: vec![...
function_block-function_prefix_line
[ { "content": "pub trait GetTextLayout { fn get_text_layout(&mut self, text_layout_options: &ResolvedTextLayoutOptions) -> InlineTextLayout; }\n\n\n\n#[derive(Debug, Clone, PartialEq, PartialOrd)]\n\npub struct SolvedUi {\n\n pub solved_rects: NodeDataContainer<PositionedRectangle>,\n\n}\n\n\n\n#[derive(Debug...
Rust
crates/mun_codegen/src/ir/type_table.rs
parasyte/mun
73d0839380a711c61885735320de78c4639691f8
use super::types as ir; use crate::ir::dispatch_table::{DispatchTable, FunctionPrototype}; use crate::type_info::{TypeGroup, TypeInfo}; use crate::value::{AsValue, CanInternalize, Global, IrValueContext, IterAsIrValue, Value}; use crate::IrDatabase; use hir::{Body, ExprId, InferenceResult}; use inkwell::module::Linkage...
use super::types as ir; use crate::ir::dispatch_table::{DispatchTable, FunctionPrototype}; use crate::type_info::{TypeGroup, TypeInfo}; use crate::value::{AsValue, CanInternalize, Global, IrValueContext, IterAsIrValue, Value}; use crate::IrDatabase; use hir::{Body, ExprId, InferenceResult}; use inkwell::module::Linkage...
pub fn collect_fn(&mut self, hir_fn: hir::Function) { if !hir_fn.data(self.db).visibility().is_private() || self.dispatch_table.contains(hir_fn) { let fn_sig = hir_fn.ty(self.db).callable_sig(self.db).unwrap(); for ty in fn_sig.params().iter() { ...
lf, expr_id: ExprId, body: &Arc<Body>, infer: &InferenceResult) { let expr = &body[expr_id]; expr.walk_child_exprs(|expr_id| self.collect_expr(expr_id, body, infer)) }
function_block-function_prefixed
[ { "content": "/// Returns the LLVM IR type of the specified struct\n\npub fn struct_ty_query(db: &impl IrDatabase, s: hir::Struct) -> StructType {\n\n let name = s.name(db).to_string();\n\n for field in s.fields(db).iter() {\n\n // Ensure that salsa's cached value incorporates the struct fields\n\n...
Rust
hatch/src/generators/tup/tests/builder.rs
CachedNerds/Hatch
fc25adcda0dded3ad630aa3850d615aa13527975
use generators::project_asset::ProjectAsset; use generators::tup::builder::Builder as AssetBuilder; use generators::tup::tests::fixtures; use project::ProjectKind; use std::path::PathBuf; #[test] fn add_asset() { let project = fixtures::project(ProjectKind::HeaderOnly); let mut asset_builder = AssetBuilder::ne...
use generators::project_asset::ProjectAsset; use generators::tup::builder::Builder as AssetBuilder; use generators::tup::tests::fixtures; use project::ProjectKind; use std::path::PathBuf; #[test] fn add_asset() { let project = fixtures::project(ProjectKind::HeaderOnly); let mut asset_builder = AssetBuilder::ne...
#[test] fn build_tupfile_asset() { let project = fixtures::project(ProjectKind::Shared); let asset_builder = AssetBuilder::new(PathBuf::from("./"), &project); let actual_asset = asset_builder.add_tupfile(); let expected_contents = String::from( "include config.tup include_rules : foreach $(...
TEST = test TEST_TARGET = $(TEST)/$(TARGET) TEST_FILES = $(TEST)/$(SOURCE)/*.cpp TEST_OBJ_FILES = $(TEST_TARGET)/*.o # macros !compile = |> $(CC) $(CFLAGS) %f -o %o |> !archive = |> ar crs %o %f |> !link = |> $(CC) $(LINKFLAGS) %f -o %o |> # includes the STATIC and SHARED variables for the target platform include @(T...
function_block-function_prefix_line
[ { "content": "pub fn project(kind: ProjectKind) -> Project {\n\n let compiler_options = CompilerOptions::new(\n\n String::from(\"g++\"),\n\n vec![String::from(\"-c\"), String::from(\"--std=c++1z\")].join(' '.to_string().as_str()),\n\n vec![String::from(\"-v\")].join(' '.to_string().as_st...
Rust
examples/qrnn.rs
usamec/cntk-rs
cb4895d222768d5cbc8619d71fb02e5f14bc7c86
#[macro_use] extern crate cntk; extern crate rand; use cntk::{Variable, Function, Value, Learner, Trainer, DoubleParameterSchedule, DataMap, Axis}; use cntk::ParameterInitializer; use cntk::ReplacementMap; use cntk::Shape; use cntk::ops::*; use cntk::DeviceDescriptor; use rand::distributions::{IndependentSample, Range...
#[macro_use] extern crate cntk; extern crate rand; use cntk::{Variable, Function, Value, Learner, Trainer, DoubleParameterSchedule, DataMap, Axis}; use cntk::ParameterInitializer; use cntk::ReplacementMap; use cntk::Shape; use cntk::ops::*; use cntk::DeviceDescriptor; use rand::distributions::{IndependentSample, Range...
println!("training end"); }
tch_num*batch_size..(batch_num+1)*batch_size], DeviceDescriptor::cpu()); let datamap = datamap!{&x => &value, &y => &ovalue}; let mut outdatamap = outdatamap!{&output, &loss}; trainer.train_minibatch(&datamap, &mut outdatamap, DeviceDescriptor::cpu()); let _output_val = ...
function_block-random_span
[ { "content": "fn linear_layer<T: Into<Variable>>(input: T, input_size: usize, output_size: usize) -> Function {\n\n let w = Variable::parameter(&Shape::new(&vec!(output_size, input_size)), &ParameterInitializer::glorot_uniform(), DeviceDescriptor::cpu());\n\n let b = Variable::parameter(&Shape::new(&vec!(...
Rust
src/rules_parser/rule_action.rs
mcdobr/yawaf
5238f99789ec972a14049d3b8eb0399674bc3a1d
use nom::IResult; use nom::sequence::{tuple, separated_pair, delimited}; use nom::error::context; use nom::character::complete::{alpha1, multispace0}; use nom::combinator::{opt}; use nom::bytes::complete::{tag, is_not}; use nom::multi::{separated_list1}; #[derive(Clone, Debug, PartialEq)] pub struct RuleAction { p...
use nom::IResult; use nom::sequence::{tuple, separated_pair, delimited}; use nom::error::context; use nom::character::complete::{alpha1, multispace0}; use nom::combinator::{opt}; use nom::bytes::complete::{tag, is_not}; use nom::multi::{separated_list1}; #[derive(Clone, Debug, PartialEq)] pub struct RuleAction { p...
#[test] fn parse_actions_should_extract_all_actions() { assert_eq!(vec![ RuleAction { action_type: RuleActionType::Nolog, argument: None, }, RuleAction { action_type: RuleActionType::Id, argument: Some("99".to_string()), }, Ru...
fn parse_action_should_extract_action() { assert_eq!(RuleAction { action_type: RuleActionType::Append, argument: Some("'<hr>Footer'".to_string()), }, parse_action("append:'<hr>Footer'").unwrap().1) }
function_block-full_function
[ { "content": "pub fn parse_rule(input: &str) -> IResult<&str, Rule> {\n\n context(\n\n \"rule\",\n\n delimited(\n\n multispace0,\n\n tuple((\n\n rule_directive::parse_directive,\n\n multispace1,\n\n rule_variable::parse_variable...
Rust
src/path64/cubic64.rs
vmx/tiny-skia
58001e98b1ae267b5cd60dd681c88bb00a97ed16
use super::Scalar64; use super::point64::{Point64, SearchAxis}; use super::quad64; pub const POINT_COUNT: usize = 4; const PI: f64 = 3.141592653589793; pub struct Cubic64Pair { pub points: [Point64; 7], } pub struct Cubic64 { pub points: [Point64; POINT_COUNT], } impl Cubic64 { pub fn new(points: [Poi...
use super::Scalar64; use super::point64::{Point64, SearchAxis}; use super::quad64; pub const POINT_COUNT: usize = 4; const PI: f64 = 3.141592653589793; pub struct Cubic64Pair { pub points: [Point64; 7], } pub struct Cubic64 { pub points: [Point64; POINT_COUNT], } impl Cubic64 { pub fn new(points: [Poi...
c[2].x, t); let cd = interp(src[2].x, src[3].x, t); let abc = interp(ab, bc, t); let bcd = interp(bc, cd, t); let abcd = interp(abc, bcd, t); dst[0].x = src[0].x; dst[1].x = ab; dst[2].x = abc; dst[3].x = abcd; dst[4].x = bcd; dst[5].x = cd; dst[6].x = src[3].x; } fn interp...
return -1.0; } let more_dist = more_pt.axis_coord(x_axis) - axis_intercept; let ok = if calc_dist > 0.0 { calc_dist <= more_dist } else { calc_dist >= more_dist }; if ok { continue; } t = next_t; ...
random
[ { "content": "pub fn vertical_intersect(cubic: &Cubic64, axis_intercept: f64, roots: &mut [f64; 3]) -> usize {\n\n let (a, b, c, mut d) = cubic64::coefficients(&cubic.as_f64_slice());\n\n d -= axis_intercept;\n\n let mut count = cubic64::roots_valid_t(a, b, c, d, roots);\n\n let mut index = 0;\n\n ...
Rust
piet-gpu/bin/winit.rs
Vurich/piet-gpu
a41b6684d09d0205d6d8c80f5a8d186bebf65e6d
use piet_gpu::{render_scene, PietGpuRenderContext, Renderer, HEIGHT, WIDTH}; use std::iter; use winit::{ event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; fn main() -> Result<(), Box<dyn std::error::Error>> { let event_loop = EventLoop::new(); le...
use piet_gpu::{render_scene, PietGpuRenderContext, Renderer, HEIGHT, WIDTH}; use std::iter; use winit::{ event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; fn main() -> Result<(), Box<dyn std::error::Error>> { let event_loop = EventLoop::new(); le...
, Event::MainEventsCleared => { window.request_redraw(); } Event::RedrawRequested(window_id) if window_id == window.id() => { let swap_frame = swapchain.get_current_frame().unwrap(); let mut cmd_buf = device.create_c...
match event { WindowEvent::CloseRequested => { *control_flow = ControlFlow::Exit; } WindowEvent::Resized(size) => { let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, ...
if_condition
[ { "content": "pub fn render_scene(rc: &mut impl RenderContext) {\n\n render_tiger(rc);\n\n}\n\n\n", "file_path": "piet-gpu/src/lib.rs", "rank": 0, "score": 153520.9568348133 }, { "content": "fn main() {\n\n let mod_name = std::env::args()\n\n .skip(1)\n\n .next()\n\n ...
Rust
matrix_sdk_appservice/src/webserver/actix.rs
fisherdarling/matrix-rust-sdk
0fb3dedd1cd3b0766fa7378754480d52d38e8ef2
use std::pin::Pin; pub use actix_web::Scope; use actix_web::{ dev::Payload, error::PayloadError, get, put, web::{self, BytesMut, Data}, App, FromRequest, HttpRequest, HttpResponse, HttpServer, }; use futures::Future; use futures_util::TryStreamExt; use ruma::api::appservice as api; use crate::{e...
use std::pin::Pin; pub use actix_web::Scope; use actix_web::{ dev::Payload, error::PayloadError, get, put, web::{self, BytesMut, Data}, App, FromRequest, HttpRequest, HttpResponse, HttpServer, }; use futures::Future; use futures_util::TryStreamExt; use ruma::api::appservice as api; use crate::{e...
}) } }
Ok(IncomingRequest { access_token, incoming: ruma::api::IncomingRequest::try_from_http_request(request)?, })
call_expression
[ { "content": "pub fn keys_query(c: &mut Criterion) {\n\n let runtime = Builder::new_multi_thread().build().expect(\"Can't create runtime\");\n\n let machine = OlmMachine::new(&alice_id(), &alice_device_id());\n\n let response = keys_query_response();\n\n let uuid = Uuid::new_v4();\n\n\n\n let cou...
Rust
src/command/windows.rs
cosmo0920/grnenv-rs
138d53e5037cd17f9ce40ee9f06bd9bba9f5a528
use std::borrow::Cow; use std::env; use std::fs; use std::io; use std::process; use clap::ArgMatches; use kuchiki; use tempdir::TempDir; use config::Config; use downloader; use extractor; use profile; use reqwest::{Client, Proxy, Url}; pub fn init() { let config = Config::new(); if config.install_dir.exists(...
use std::borrow::Cow; use std::env; use std::fs; use std::io; use std::process; use clap::ArgMatches; use kuchiki; use tempdir::TempDir; use config::Config; use downloader; use e
uninstall(m: &ArgMatches) { let config = Config::from_matches(m); let mut choice = String::new(); let arch = match config.arch.unwrap() { Cow::Borrowed(s) => s.to_owned(), Cow::Owned(s) => s, }; let groonga_dir = format!("groonga-{}-{}", config.version.unwrap(), arch); if config...
xtractor; use profile; use reqwest::{Client, Proxy, Url}; pub fn init() { let config = Config::new(); if config.install_dir.exists() || config.shim_dir.exists() { println!("Already initalized. Reinitializing...."); } fs::create_dir_all(&config.install_dir).expect("Could not create installation ...
random
[ { "content": "pub fn file_download<'a>(\n\n client: &'a Client,\n\n url: &str,\n\n mut base_dir: PathBuf,\n\n filename: &'a str,\n\n) -> Result<PathBuf, GrnEnvError> {\n\n let mut res = client\n\n .get(url)\n\n .header(Connection::close())\n\n .header(UserAgent::new(format!(\...
Rust
src/timm/calls.rs
kumo/callog_bot
cd549d1ae2f7ef967be56ca647fab7580309a4e6
use chrono::{NaiveDateTime, Utc}; use std::fmt::{Display, Formatter}; use visdom::Vis; #[derive(Eq, PartialEq, Debug, Clone)] pub struct PhoneCall { pub who: String, pub when: NaiveDateTime, } impl PhoneCall { pub fn is_today(&self) -> bool { Utc::now() .naive_utc() .signed...
use chrono::{NaiveDateTime, Utc}; use std::fmt::{Display, Formatter}; use visdom::Vis; #[derive(Eq, PartialEq, Debug, Clone)] pub struct PhoneCall { pub who: String, pub when: NaiveDateTime, } impl PhoneCall { pub fn is_today(&self) -> bool { Utc::now() .naive_utc() .signed...
} impl Display for PhoneCall { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let diff = Utc::now().naive_utc() - self.when; if diff.num_hours() > 1 { write!( f, "☎️ {}\n👉 {}", self.who, self.when.fo...
pub fn is_recent(&self) -> bool { Utc::now() .naive_utc() .signed_duration_since(self.when) .num_minutes() <= 20 }
function_block-full_function
[ { "content": "fn parse_int(input: &str) -> Option<u32> {\n\n input\n\n .chars()\n\n .skip_while(|ch| !ch.is_digit(10))\n\n .take_while(|ch| ch.is_digit(10))\n\n .fold(None, |acc, ch| {\n\n ch.to_digit(10).map(|b| acc.unwrap_or(0) * 10 + b)\n\n })\n\n}\n\n\n\nimpl...
Rust
src/views/results.rs
Ace4896/typetest
b2d682ca96be09d8ef157761615aaca7761fe9d8
use iced::{button, scrollable, Align, Button, Column, HorizontalAlignment, Row, Scrollable, Text}; use typetest_core::stats::TestStats; use typetest_themes::ApplicationTheme; use super::Action; pub struct ResultsState { stats: TestStats, show_missed_words: bool, retry_button: button::State, next_tes...
use iced::{button, scrollable, Align, Button, Column, HorizontalAlignment, Row, Scrollable, Text}; use typetest_core::stats::TestStats; use typetest_themes::ApplicationTheme; use super::Action; pub struct ResultsState { stats: TestStats, show_missed_words: bool, retry_button: button::State, next_tes...
pub fn update_stats(&mut self, stats: TestStats) { self.stats = stats; } } #[inline] fn format_time_mm_ss(seconds: u64) -> String { format!("{:0>2}:{:0>2}", seconds / 60, seconds % 60) }
if self.stats.get_missed_words().is_empty() { tmp } else { tmp.on_press(ResultsMessage::ToggleMissedWords) } }; let controls = Row::new() .align_items(Align::Center) .spacing(10) .push(next_test_button) ...
function_block-function_prefix_line
[ { "content": "/// Converts a [DisplayedWord] to an [iced::Text].\n\nfn displayed_word(word: &DisplayedWord, theme: &Box<dyn ApplicationTheme>) -> Text {\n\n let theme = theme.word_palette();\n\n let color = match word.status {\n\n WordStatus::NotTyped => theme.default,\n\n WordStatus::Correc...
Rust
examples/neopixel.rs
blueluna/circuit-playground-bluefruit
53f05f169541c5f1b537803d72e3f102f76a0d7f
#![no_main] #![no_std] #[allow(unused_imports)] use panic_semihosting; use cortex_m_semihosting::{hprintln}; use rtfm::app; use nrf52840_hal::{gpio, prelude::*, uarte, }; use nrf52840_pac as pac; const PWM_FALLING_EDGE: u16 = 0x8000; const NEOPIXEL_COUNTER_TOP: u16 = 20; const NEOPIXEL_TIME_0_HIGH: u16 = 6 | PW...
#![no_main] #![no_std] #[allow(unused_imports)] use panic_semihosting; use cortex_m_semihosting::{hprintln}; use rtfm::app; use nrf52840_hal::{gpio, prelude::*, uarte, }; use nrf52840_pac as pac; const PWM_FALLING_EDGE: u16 = 0x8000; const NEOPIXEL_COUNTER_TOP: u16 = 20; const NEOPIXEL_TIME_0_HIGH: u16 = 6 | PW...
#[task(binds = TIMER0, resources = [pwm, counter, timer])] fn timer(cx: timer::Context) { let pwm = cx.resources.pwm; let counter = cx.resources.counter; cx.resources.timer.events_compare[0].reset(); let mut colours = [0u8; 30]; let mut pwm_words = [0x8000u16; 30 * 8 + ...
e()._32bit()); timer.shorts.write(|w| w.compare0_clear().enabled().compare0_stop().disabled()); timer.prescaler.write(|w| unsafe { w.prescaler().bits(4) }); timer.cc[0].write(|w| unsafe { w.bits(50_000) }); timer.intenset.write(|w| w.compare0().set()); timer.tasks_clear.write(|w|...
function_block-function_prefixed
[ { "content": "# Rust experiments on the Adafruit Circuit Playground Bluefruit\n\n\n\n## The Setup\n\n\n\nFollowing setup was used when running these examples.\n\n\n\nThe Adafruit Circuit Playground Bluefruit (CPB) is connected to a J-Link EDU\n\nthrough the SWD interface on the back of the CPB. A USB-to-serial ...
Rust
src/main.rs
glapa-grossklag/rle
f6809704b27f9dc07617c2fe54918332d8a685b4
use std::fs::File; use std::io::prelude::*; use clap::App; fn main() { let yaml = clap::load_yaml!("clap.yml"); let matches = App::from_yaml(yaml).get_matches(); if let Some(matches) = matches.subcommand_matches("encode") { let mut bytes_read: usize = 0; let mut bytes_w...
use std::fs::File; use std::io::prelude::*; use clap::App; fn main() { let yaml = clap::load_yaml!("clap.yml"); let matches = App::from_yaml(yaml).get_matches(); if let Some(matches) = matches.subcommand_matches("encode") { let mut bytes_read: usize = 0; let mut bytes_w...
fn encode(data: Vec<u8>) -> Vec<u8> { if data.is_empty() { return Vec::new(); } let mut encoded: Vec<u8> = Vec::new(); let mut previous: u8 = data[0]; let mut len: u8 = 0; for current in data { if current == previous && len < u8::MAX { len += 1; } else { ...
ile).unwrap(); match output.write_all(&encoded) { Err(why) => panic!("Cannot write: {}", why), Ok(_) => bytes_written += encoded.len(), } if matches.is_present("verbose") { let compression_ratio = 1.0 - (bytes_written as f64 / bytes_read as f64); ...
function_block-function_prefixed
[ { "content": "# Run-Length Encoding\n\n\n\nRun-length encoding (RLE) is one of the simplest and most intuitive compression\n\nmethods. In short, RLE encodes repeating strings of symbols as the length of the\n\nrun. An example illustrates this best. Let's say we have the following data:\n\n\n\n\tOh noooooo!\n\n\...
Rust
src/main.rs
dextero/vrms-rs
ce72bc8017200641e9d8cdd214be56d54526dcd4
#[macro_use] #[cfg(test)] extern crate matches; extern crate regex; #[macro_use] extern crate error_chain; extern crate colored; use std::collections::HashSet; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::process::Command; use std::process; use regex::Regex; use colored::*; error_chain!...
#[macro_use] #[cfg(test)] extern crate matches; extern crate regex; #[macro_use] extern crate error_chain; extern crate colored; use std::collections::HashSet; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::process::Command; use std::process; use regex::Regex; use colored::*; error_chain!...
#[test] fn license_parse_or() { assert_eq!(License::Or( vec!(License::License("a".to_owned()), License::License("b".to_owned()))), License::parse("a or b").unwrap()); assert_eq!(License::Or( vec!(License::License("a".to_owned()), ...
fn license_parse_trivial() { assert_eq!(License::License("trivial".to_owned()), License::parse("trivial").unwrap()); assert_eq!(License::License("with spaces".to_owned()), License::parse("with spaces").unwrap()); assert_eq!(License::License("spaces around".to_owned()), ...
function_block-full_function
[ { "content": "# vrms-rs\n\n\n\nYet another clone of *vrms* (\"virtual Richard M. Stallman\") utility, inspired by [vrms-rpm](https://github.com/dextero/vrms-rpm) project by Suve and the [RIIR movement](https://transitiontech.ca/random/RIIR).\n", "file_path": "README.md", "rank": 22, "score": 1.52058...
Rust
src/search.rs
ZackPierce/syn-select
6c9489df2147bfeabe4800eb54cae96ebf1c16d0
use crate::{util, Selector}; use crate::selector::SelectorSegment; use syn::visit::Visit; use syn::{ self, Attribute, Ident, Item, ItemConst, ItemFn, ItemTrait, ItemType, Stmt, TraitItem, Visibility, }; trait Name { fn name(&self) -> Option<&Ident>; fn is_named(&self, ident: &impl PartialEq<...
use crate::{util, Selector}; use crate::selector::SelectorSegment; use syn::visit::Visit; use syn::{ self, Attribute, Ident, Item, ItemConst, ItemFn, ItemTrait, ItemType, Stmt, TraitItem, Visibility, }; trait Name { fn name(&self) -> Option<&Ident>; fn is_named(&self, ident: &impl PartialEq<...
pub fn search_file(&mut self, file: &syn::File) { self.visit_file(file) } fn term(&self) -> &SelectorSegment { self.query.part(self.depth) } fn can_match(&self) -> bool { self.depth == self.query.len() - 1 } fn search_deeper(&self, item: &syn::Item) -> ...
pub fn new(query: &'a Selector) -> Self { Self { query, depth: 0, results: vec![], } }
function_block-full_function
[ { "content": "/// Parse a path, then search a file for all results that exactly match the specified\n\n/// path.\n\n///\n\n/// # Returns\n\n/// This function can find multiple items if:\n\n///\n\n/// 1. There is a module and a function of the same name\n\n/// 2. The same path is declared multiple times, differi...
Rust
sway-core/src/asm_generation/mod.rs
FuelLabs/sway
0190b5dac4735fd2a34528e48cc2e0c9606b5ce8
use crate::{ asm_lang::{ allocated_ops::AllocatedRegister, virtual_register::*, Label, Op, OrganizationalOp, VirtualImmediate12, VirtualOp, }, parse_tree::Literal, }; use std::{collections::BTreeSet, fmt}; use either::Either; mod abstract_instruction_set; pub(crate) mod checks; pub(crate) ...
use crate::{ asm_lang::{ allocated_ops::AllocatedRegister, virtual_register::*, Label, Op, OrganizationalOp, VirtualImmediate12, VirtualOp, }, parse_tree::Literal, }; use std::{collections::BTreeSet, fmt}; use either::Either; mod abstract_instruction_set; pub(crate) mod checks; pub(crate) ...
} } impl SwayAsmSet { pub(crate) fn remove_unnecessary_jumps(self) -> JumpOptimizedAsmSet { match self { SwayAsmSet::ScriptMain { data_section, program_section, } => JumpOptimizedAsmSet::ScriptMain { data_section, ...
match self { SwayAsmSet::ScriptMain { data_section, program_section, } => write!(f, "{}\n{}", program_section, data_section), SwayAsmSet::PredicateMain { data_section, program_section, } => write!(f, "{}\n{}"...
if_condition
[ { "content": "/// cleans whitespace, including newlines\n\npub fn clean_all_whitespace(iter: &mut Peekable<Enumerate<Chars>>) {\n\n while let Some((_, next_char)) = iter.peek() {\n\n if next_char.is_whitespace() {\n\n iter.next();\n\n } else {\n\n break;\n\n }\n\n ...
Rust
src/parse/callgrind.rs
pganssle/cargo-profiler
b2b84463dd86af42146f34fb365311c31291d1a7
use crate::err::ProfError; use crate::profiler::Profiler; use lazy_static::lazy_static; use regex::Regex; use std::ffi::OsStr; use std::process::Command; pub trait CallGrindParser { fn callgrind_cli(&self, binary: &str, binargs: &[&OsStr]) -> Result<String, ProfError>; fn callgrind_parse<'b>(&'b self, output: ...
use crate::err::ProfError; use crate::profiler::Profiler; use lazy_static::lazy_static; use regex::Regex; use std::ffi::OsStr; use std::process::Command; pub trait CallGrindParser { fn callgrind_cli(&self, binary: &str, binargs: &[&OsStr]) -> Result<String, ProfError>; fn callgrind_parse<'b>(&'b self, output: ...
} #[cfg(test)] mod test { use super::CallGrindParser; use crate::profiler::Profiler; #[test] fn test_callgrind_parse_1() { let output = "==6072== Valgrind's memory management: out of memory:\n ==6072== \ Whatever the reason, Valgrind cannot continue. Sorry."; ...
let data_row = match elems[0].trim().replace(",", "").parse::<f64>() { Ok(rep) => rep, Err(_) => return Err(ProfError::RegexError), }; data_vec.push(data_row); let path = elems[1].split(' ').collect::<Vec<_>>(); ...
function_block-function_prefix_line
[ { "content": "/// match the binary argument\n\npub fn get_binary<'a>(matches: &'a ArgMatches) -> Result<&'a str, ProfError> {\n\n // read binary argument, make sure it exists in the filesystem\n\n match matches.value_of(\"binary\") {\n\n Some(z) => {\n\n if !Path::new(z).exists() {\n\n ...
Rust
src/read.rs
Stupremee/rarchive
7510b6a3d94c686ea14996c1a5b34d251354e801
use crate::{Archive, Error, ErrorOrIo, Filter, Format, Result}; use rarchive_sys::archive; use std::{path::Path, ptr::NonNull}; pub struct ReadArchive { inner: NonNull<archive>, } impl ReadArchive { pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, ErrorOrIo> { let mut archive = Self...
use crate::{Archive, Error, ErrorOrIo, Filter, Format, Result}; use rarchive_sys::archive; use std::{path::Path, ptr::NonNull}; pub struct ReadArchive { inner: NonNull<archive>, } impl ReadArchive { pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self, ErrorOrIo> { let mut archive = Self...
fn set_format_option(&mut self, module: &str, option: &str, value: &str) -> Result<()> { Error::from_code(self, || unsafe { rarchive_sys::archive_read_set_format_option( self.as_mut_ptr(), module.as_ptr() as _, option.as_ptr() as _, ...
fn set_filter_option(&mut self, module: &str, option: &str, value: &str) -> Result<()> { Error::from_code(self, || unsafe { rarchive_sys::archive_read_set_filter_option( self.as_mut_ptr(), module.as_ptr() as _, option.as_ptr() as _, val...
function_block-full_function
[ { "content": "/// Common trait that is implemented for [`ReadArchive`] and [`WriteArchive`]\n\n/// to provide common operations.\n\n///\n\n/// [`ReadArchive`]: ./struct.ReadArchive.html\n\n/// [`WriteArchive`]: ./struct.WriteArchive.html\n\npub trait Archive {\n\n /// Returns a pointer to the underlying raw ...
Rust
src/constants.rs
Alex6323/iota-lz4-udp
7d0c234ff9cc99463d58170fc2e5d0b564df0626
use lazy_static::lazy_static; use regex::Regex; type Field = (usize, usize, usize, usize, usize, usize); pub const SIGNATURE_FRAGMENTS: Field = (0, 6561, 0, 2187, 0, 1458); pub const EXTRA_DATA_DIGEST: Field = (6561, 243, 2187, 81, 1458, 54); pub const ADDRESS: Field = (6804, 243, 2268, 81, 1512, 54); pub const VALUE:...
use lazy_static::lazy_static; use regex::Regex; type Field = (usize, usize, usize, usize, usize, usize); pub const SIGNATURE_FRAGMENTS: Field = (0, 6561, 0, 2187, 0, 1458); pub const EXTRA_DATA_DIGEST: Field = (6561, 243, 2187, 81, 1458, 54); pub const ADDRESS: Field = (6804, 243, 2268, 81, 1512, 54); pub const VALUE:...
assert_eq!(sum, TRANSACTION_SIZE_TRYTES); } #[test] fn test_transaction_tryte_offset_constants() { assert_eq!(SIGNATURE_FRAGMENTS.0 / 3, SIGNATURE_FRAGMENTS.2); assert_eq!(EXTRA_DATA_DIGEST.0 / 3, EXTRA_DATA_DIGEST.2); assert_eq!(ADDRESS.0 / 3, ADDRESS.2); assert_e...
let sum = SIGNATURE_FRAGMENTS.3 + EXTRA_DATA_DIGEST.3 + ADDRESS.3 + VALUE.3 + ISSUANCE_TIMESTAMP.3 + TIMELOCK_LOWER_BOUND.3 + TIMELOCK_UPPER_BOUND.3 + BUNDLE_NONCE.3 + TRUNK_HASH.3 + BRANCH_HASH.3 + T...
assignment_statement
[ { "content": "pub fn from_i64_fixed9(number: i64) -> [Tryte; 9] {\n\n let is_positive = number > 0;\n\n let mut trytes = [TRYTE_TO_ASCII[0]; 9];\n\n let mut number = number.abs();\n\n let mut remainder;\n\n\n\n for t in trytes.iter_mut() {\n\n remainder = number % 27;\n\n number = i...
Rust
relm-examples/tests/references2.rs
RadicalZephyr/relm
925a738fb8299bd1497adaf0752919475cf9bc92
/* * Copyright (c) 2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy,...
/* * Copyright (c) 2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy,...
ilder::new().label("Remove").build(); remove_button.set_widget_name("remove_button"); connect!(relm, remove_button, connect_clicked(_), Msg::Remove); vbox.pack_start(&remove_button, false, false, 0); root.show_all(); RelmWidget { root, vbox, l...
fn view(relm: &relm::Relm<Self>, _model: Self::Model) -> Self { let root = gtk::Window::new(gtk::WindowType::Toplevel); root.set_size_request(400, 400); connect!( relm, root, connect_delete_event(_, _), return (Some(Msg::Quit), gtk::Inhibit(fal...
random
[ { "content": "/// After `duration` ms, emit `msg`.\n\npub fn timeout<F: Fn() -> MSG + 'static, MSG: 'static>(stream: &StreamHandle<MSG>, duration: u32, constructor: F) {\n\n let stream = stream.clone();\n\n glib::timeout_add_local(std::time::Duration::from_millis(duration as u64), move || {\n\n let...
Rust
shell/src/shell_automaton_manager.rs
simplestaking/tezos-rs
d859dff0a8db4f5adb4885e4885217d5284f7861
use std::collections::HashSet; use std::env; use std::iter::FromIterator; use std::net::SocketAddr; use std::str::FromStr; use std::sync::Arc; use std::time::{Duration, SystemTime}; use rand::{rngs::StdRng, Rng, SeedableRng as _}; use slog::{info, warn, Logger}; use storage::{PersistentStorage, StorageInitInfo}; us...
use std::collections::HashSet; use std::env; use std::iter::FromIterator; use std::net::SocketAddr; use std::str::FromStr; use std::sync::Arc; use std::time::{Duration, SystemTime}; use rand::{rngs::StdRng, Rng, SeedableRng as _}; use slog::{info, warn, Logger}; use storage::{PersistentStorage, StorageInitInfo}; us...
pub fn shell_automaton_sender(&self) -> ShellAutomatonSender { self.shell_automaton_sender.clone() } pub fn send_shutdown_signal(&self) { if let Err(err) = self .shell_automaton_sender .send(ShellAutomatonMsg::Shutdown) { warn!(self.log, "Failed...
self.shell_automaton_thread_handle.take() { let shell_automaton_thread_handle = std::thread::Builder::new() .name("shell-automaton".to_owned()) .spawn(move || { shell_automaton.init(); while !shell_automaton.is_shu...
function_block-function_prefix_line
[ { "content": "#[allow(dead_code)]\n\npub fn logger(empty: bool, level: Level) -> Logger {\n\n use std::io::{self, Write};\n\n\n\n use slog::Record;\n\n use slog_term::{CountingWriter, RecordDecorator, ThreadSafeTimestampFn};\n\n\n\n pub fn print_msg_header(\n\n fn_timestamp: &dyn ThreadSafeTi...
Rust
pipelined/bevy_pbr2/src/render/light.rs
bch29/bevy
c53efeed6fb8b1e41737ea4502051fa4cf535784
use crate::{render::MeshViewBindGroups, ExtractedMeshes, PointLight}; use bevy_ecs::{prelude::*, system::SystemState}; use bevy_math::{Mat4, Vec3, Vec4}; use bevy_render2::{ color::Color, core_pipeline::Transparent3dPhase, pass::*, pipeline::*, render_graph::{Node, NodeRunError, RenderGraphContext, ...
use crate::{render::MeshViewBindGroups, ExtractedMeshes, PointLight}; use bevy_ecs::{prelude::*, system::SystemState}; use bevy_math::{Mat4, Vec3, Vec4}; use bevy_render2::{ color::Color, core_pipeline::Transparent3dPhase, pass::*, pipeline::*, render_graph::{Node, NodeRunError, RenderGraphContext, ...
} impl Node for ShadowPassNode { fn input(&self) -> Vec<SlotInfo> { vec![SlotInfo::new(ShadowPassNode::IN_VIEW, SlotType::Entity)] } fn update(&mut self, world: &mut World) { self.main_view_query.update_archetypes(world); self.view_light_query.update_archetypes(world); } ...
pub fn new(world: &mut World) -> Self { Self { main_view_query: QueryState::new(world), view_light_query: QueryState::new(world), } }
function_block-full_function
[ { "content": "/// Internally, `bevy_render` uses hashes to identify vertex attribute names.\n\npub fn get_vertex_attribute_name_id(name: &str) -> u64 {\n\n let mut hasher = bevy_utils::AHasher::default();\n\n hasher.write(&name.as_bytes());\n\n hasher.finish()\n\n}\n", "file_path": "pipelined/bevy_...
Rust
src/actors.rs
thomaslienbacher/Moving-Tower
adfaf169a8dc85993dd90507db9b8d702ba71f4f
use sfml::graphics::*; use sfml::system::Vector2f; use sfml::window::*; use sfml::window::mouse::Button; use crate::AssetManager; use super::{WIN_HEIGHT, WIN_WIDTH}; pub trait Actor { fn update(&mut self, d: f32); fn draw(&self, win: &mut RenderWindow); fn events(&mut self, evt: Event); } struct Circl...
use sfml::graphics::*; use sfml::system::Vector2f; use sfml::window::*; use sfml::window::mouse::Button; use crate::AssetManager; use super::{WIN_HEIGHT, WIN_WIDTH}; pub trait Actor { fn update(&mut self, d: f32); fn draw(&self, win: &mut RenderWindow); fn events(&mut self, evt: Event); } struct Circl...
Circle::new(position.x, position.y, sprite.texture_rect().width as f32 / 2.0) }; Tower { sprite, teleport_circle, hitbox, position, rotation: 0.0, bullet_sprite, bullets: Vec::new(), dead: false, ...
NER, 36); c.set_position(position); c.set_outline_thickness(TOWER_OUTER - TOWER_INNER); c.set_origin(Vector2f::new(TOWER_INNER, TOWER_INNER)); c.set_fill_color(&Color::TRANSPARENT); c.set_outline_color(&Color::rgba(255, 255, 255, 50)); c }...
random
[ { "content": "pub trait Scene {\n\n fn update(&mut self, d: f32) -> Option<State>; //returns the new state if we need to change\n\n\n\n fn draw(&self, win: &mut RenderWindow);\n\n\n\n fn events(&mut self, evt: Event);\n\n}\n\n\n\npub struct MenuScene<'a> {\n\n title_text: Text<'a>,\n\n help_text:...
Rust
src/line.rs
RoguishStudios/hexgrid
5d19f73a56a7210ac883bb3d001b4fc60e2f49c7
use crate::{Coordinate, Float, Integer, Position}; use std::iter; #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, PartialEq, Debug, PartialOrd)] pub struct LineGenIter<I: Integer, F: Float> { origin: Position<F>, target: Position<F>, n: I, i: I, } impl<I:...
use crate::{Coordinate, Float, Integer, Position}; use std::iter; #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, PartialEq, Debug, PartialOrd)] pub struct LineGenIter<I: Integer, F: Float> { origin: Position<F>, target: Position<F>, n: I, i: I, } impl<I:...
fn size_hint(&self) -> (usize, Option<usize>) { self.0.size_hint() } } impl<I: Integer, F: Float> iter::FusedIterator for LineIterWithEdgeDetection<I, F> {} impl<I: Integer, F: Float> iter::ExactSizeIterator for LineIterWithEdgeDetection<I, F> {}
fn next(&mut self) -> Option<Self::Item> { let delta: F = F::from(0.000001).unwrap(); self.0.next().map(|p| { ( Position::from_axial(p.q + delta, p.r + delta).into_coordinate(), Position::from_axial(p.q - delta, p.r - delta).into_coordinate(), ) ...
function_block-full_function
[ { "content": "/// Float trait used by this library\n\npub trait Float:\n\n num::Signed\n\n + num::Float\n\n + num::ToPrimitive\n\n + num::FromPrimitive\n\n + num::NumCast\n\n + num::One\n\n + num::Zero\n\n + std::marker::Copy\n\n + std::ops::AddAssign\n\n + std::default::Default\n\...
Rust
client/tests/tests/add_asset.rs
satu-n/iroha
97e63b3895fb1469d5420e16ec7a4563b61cdf76
#![allow(clippy::restriction)] use std::{convert::TryFrom, thread}; use eyre::Result; use iroha_client::client; use iroha_core::config::Configuration; use iroha_data_model::{fixed::Fixed, prelude::*}; use test_network::{Peer as TestPeer, *}; #[test] fn client_add_asset_quantity_to_existing_asset_should_increase_asse...
#![allow(clippy::restriction)] use std::{convert::TryFrom, thread}; use eyre::Result; use iroha_client::client; use iroha_core::config::Configuration; use iroha_data_model::{fixed::Fixed, prelude::*}; use test_network::{Peer as TestPeer, *}; #[test] fn client_add_asset_quantity_to_existing_asset_should_increase_asse...
= MintBox::new( Value::Fixed(quantity), IdBox::AssetId(AssetId::new( asset_definition_id.clone(), account_id.clone(), )), ); test_client.submit_till( mint, client::asset::by_account_id(account_id.clone()), |result| { result.ite...
ifiable_box = IdentifiableBox::from(AssetDefinition::with_precision(asset_definition_id.clone())); let create_asset = RegisterBox::new(identifiable_box); test_client.submit(create_asset)?; thread::sleep(pipeline_time * 2); let quantity: Fixed = Fixed::try_from(123.45_f64).unwrap(); le...
random
[ { "content": "fn mint_asset(quantity: u32, asset: &str, account: &str) -> Instruction {\n\n Instruction::Mint(MintBox::new(\n\n Value::U32(quantity),\n\n AssetId::from_names(asset, DOMAIN, account, DOMAIN),\n\n ))\n\n}\n\n#[tokio::test]\n\nasync fn find_asset() {\n\n AssertSet::new()\n\n ...
Rust
src/renderer/wgpu_renderer.rs
takahirox/wgpu-rust-renderer
38dd6b0e60563229384bd33140b1bd51e09f23fc
use winit::window::Window; use crate::{ geometry::{ attribute::Attribute, geometry::Geometry, index::Index, }, material::material::Material, renderer::{ wgpu_attributes::WGPUAttributes, wgpu_bindings::WGPUBindings, wgpu_indices::WGPUIndices, wgpu_render_pipeline::WGPURenderPipelines, wgpu_samplers:...
use winit::window::Window; use crate::{ geometry::{ attribute::Attribute, geometry::Geometry, index::Index, }, material::material::Material, renderer::{ wgpu_attributes::WGPUAttributes, wgpu_bindings::WGPUBindings, wgpu_indices::WGPUIndices, wgpu_render_pipeline::WGPURenderPipelines, wgpu_samplers:...
if let Some(rid) = geometry.borrow_attribute("position") { self.attributes.update(&self.device, pools, rid); } if let Some(rid) = geometry.borrow_attribute("normal") { self.attributes.update(&self.device, pools, rid); } if let Some(rid) = geometry.borrow_attribute("uv") { self.attribute...
let material = match material_pool.borrow(mesh.borrow_material()) { Some(material) => material, None => continue, };
assignment_statement
[ { "content": "pub fn get_window_device_pixel_ratio() -> f64 {\n\n\tlet window = web_sys::window().unwrap();\n\n\twindow.device_pixel_ratio()\n\n}\n\n\n", "file_path": "web/examples/utils/window.rs", "rank": 0, "score": 218816.77958122682 }, { "content": "pub fn get_window_inner_size() -> (f6...
Rust
src/bxdf/bsdf.rs
joeftiger/Rust-V
bac9029eba6eefcff2d831acdc91a99168622382
use crate::bxdf::{same_hemisphere, world_to_bxdf, BxDF, BxDFSample, BxDFSampleResult, Type}; use crate::debug_utils::is_normalized; use crate::samplers::Sample; use crate::*; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Default)] pub struct BSDF { #[serde(default)] bxdfs: Vec<Box<dyn B...
use crate::bxdf::{same_hemisphere, world_to_bxdf, BxDF, BxDFSample, BxDFSampleResult, Type}; use crate::debug_utils::is_normalized; use crate::samplers::Sample; use crate::*; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Default)] pub struct BSDF { #[serde(default)] bxdfs: Vec<Box<dyn B...
pub fn evaluate_bxdf_light_wave( bxdf: &dyn BxDF, normal: Vector3, incident_world: Vector3, outgoing_world: Vector3, light_wave_index: usize, ) -> Float { let rotation = world_to_bxdf(normal); let incident = rotation * incident_world; let outgoin...
s &= !Type::REFLECTION; } self.bxdfs .iter() .filter_map(|bxdf| { if bxdf.is_type(types) { Some(bxdf.evaluate_wavelength(incident, outgoing, light_wave_index)) } else { None } }) ...
function_block-function_prefixed
[ { "content": "#[inline(always)]\n\npub fn flip(mut v: Vector3) -> Vector3 {\n\n debug_assert!(is_finite(v));\n\n\n\n v.y = -v.y;\n\n v\n\n}\n\n\n", "file_path": "src/bxdf/mod.rs", "rank": 0, "score": 314455.87686131534 }, { "content": "/// Computes the Fresnel reflection for dielect...
Rust
sentry/src/hash.rs
agaviria/oxide
bb0b274da172a3223283280f6b213673f4c54dc4
use std::str::FromStr; use argonautica::{ self, config::{Variant, Version}, {Hasher, Verifier}, input::SecretKey, }; use crate::error::{Error, ErrorKind, ParseError}; use failure::format_err; const SALT_SIZE : usize = 32; enum HashVersion { V1, } impl HashVersion { pub fn from_hash(hash: &str) -> Option<HashV...
use std::str::FromStr; use argonautica::{ self, config::{Variant, Version}, {Hasher, Verifier}, input::SecretKey, }; use crate::error::{Error, ErrorKind, ParseError}; use failure::format_err; const SALT_SIZE : usize = 32; enum HashVersion { V1, } impl HashVersion { pub fn from_hash(hash: &str) -> Option<HashV...
pub fn from_bytes<B: AsRef<[u8]>, C: AsRef<[u8]>>(b0: B, b1: C) -> Result<Self, ParseError> { let salt_byte = b0.as_ref(); let hash_byte= b1.as_ref(); validate!( salt_byte.len() != 32 || hash_byte.len() != 32, ParseError::InvalidLen ); let mut salt = [0u8; 32]; let mut hash = [0u8; 32];...
pub fn check(&self, password: &str) -> Result<bool, Error> { let key = load_env_var("SECRET_KEY")?; let mut verifier = Verifier::new(); let is_valid = if verifier .with_secret_key(&key) .with_password(password) .verify() .is_ok() { true } else { false }; Ok(is_valid) }
function_block-full_function
[ { "content": "/// decrypt_aud() takes in AES 256-bit base64 encoded string and decrypts it.\n\npub fn decrypt_aud(audience_identifier: &str) -> Result<String, Error> {\n\n\tlet key: Option<&String> = MASTER_ASAP_KEY.get();\n\n\tlet mut secret: MagicCrypt = new_magic_crypt!(key.unwrap().as_str(), 256);\n\n\tlet ...
Rust
operators/src/util/input/multi_raster_or_vector.rs
koerberm/geoengine
61e0ec7a0c1136b4360b0f9c6306c34198e8ac3a
use crate::engine::{OperatorDatasets, RasterOperator, VectorOperator}; use geoengine_datatypes::dataset::DatasetId; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum MultiRasterOrVectorOperator { Raster(Vec<Box<dyn RasterOperator>>), Vector(Box<dyn...
use crate::engine::{OperatorDatasets, RasterOperator, VectorOperator}; use geoengine_datatypes::dataset::DatasetId; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum MultiRasterOrVectorOperator { Raster(Vec<Box<dyn RasterOperator>>), Vector(Box<dyn...
}
attribute_projection": null, } }) .to_string(); let raster_or_vector_operator: MultiRasterOrVectorOperator = serde_json::from_str(&workflow).unwrap(); assert!(raster_or_vector_operator.is_vector()); assert!(!raster_or_vector_operator.is_raster()); }
function_block-function_prefix_line
[ { "content": "// TODO: move test helper somewhere else?\n\npub fn add_ndvi_dataset(ctx: &mut MockExecutionContext) -> DatasetId {\n\n let id: DatasetId = InternalDatasetId::new().into();\n\n ctx.add_meta_data(id.clone(), Box::new(create_ndvi_meta_data()));\n\n id\n\n}\n\n\n", "file_path": "operator...
Rust
9-smoke-basin/src/main.rs
coreyja/advent-of-code-2021
cea92fda8a849918dbbe26d007d57d5bc824d3ee
use anyhow::{anyhow, Result}; use itertools::{iproduct, Itertools}; #[derive(Debug)] struct Board { cells: Vec<Vec<i32>>, } impl Board { fn get(&self, pos: &Pos) -> i32 { self.cells[pos.0 as usize][pos.1 as usize] } } #[derive(Debug, Clone)] struct Pos(i32, i32); impl Pos { fn new(x: i32, y:...
use anyhow::{anyhow, Result}; use itertools::{iproduct, Itertools}; #[derive(Debug)] struct Board { cells: Vec<Vec<i32>>, } impl Board { fn get(&self, pos: &Pos) -> i32 { self.cells[pos.0 as usize][pos.1 as usize] } } #[derive(Debug, Clone)] struct Pos(i32, i32); impl Pos { fn new(x: i32, y:...
} fn parse_input(s: &str) -> Result<Board> { fn parse_line(s: &str) -> Result<Vec<i32>> { s.trim() .chars() .map(|s| s.to_string().parse().map_err(|_| anyhow!("Parse error"))) .collect() } let cells = s .trim() .lines() .map(parse_line) ...
e][pos.1 as usize] = true; let value = board.get(&pos); if value != 9 { size += 1; for n in pos.get_neighbours(board).into_iter() { queue.push(n); } } } size }
function_block-function_prefixed
[ { "content": "fn part2_ans(s: &str) -> Result<(usize, u32, u32)> {\n\n let nums = parse_input(s)?;\n\n\n\n (0..nums.len())\n\n .map(|i| {\n\n (\n\n i,\n\n sum_of_additions_diff(&nums, i as u32),\n\n sum_of_diff(&nums, i as u32),\n\n ...
Rust
src/parser/parameters.rs
hoodie/icalendar-rs
c0ffee24858e0739b9964395d0ae61f6a582aa94
use nom::{ branch::alt, bytes::complete::{tag, take_till1}, character::complete::space0, combinator::{eof, map, opt}, error::{convert_error, ContextError, ParseError, VerboseError}, multi::many0, sequence::{preceded, separated_pair, tuple}, Finish, IResult, }; #[cfg(test)] use nom::erro...
use nom::{ branch::alt, bytes::complete::{tag, take_till1}, character::complete::space0, combinator::{eof, map, opt}, error::{convert_error, ContextError, ParseError, VerboseError}, multi::many0, sequence::{preceded, separated_pair, tuple}, Finish, IResult, }; #[cfg(test)] use nom::erro...
), remove_empty_string_parsed, ), )), |(key, val)| Parameter { key, val }, )(input) } #[test] pub fn parse_parameter_list() { assert_parser!( parameters, ";KEY=VALUE", vec![Parameter::new_ref("KEY", Some("VALUE"))] ); assert_parser!( ...
preceded( tag("="), map( alt((eof, take_till1(|x| x == ';' || x == ':'))), ParseString::from, ), )
call_expression
[ { "content": "pub fn valid_key_sequence_cow<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n\n input: &'a str,\n\n) -> IResult<&'a str, ParseString<'a>, E> {\n\n map(\n\n take_while(|c: char| {\n\n c == '.' || c == ',' || c == '/' || c == '_' || c == '-' || c.is_alphanumeric()\n\n ...
Rust
crates/noirc_frontend/src/hir/type_check/mod.rs
guipublic/noir
f581f68795c8c4fa04daece8e0461211c4fab417
mod errors; mod expr; mod stmt; use errors::TypeCheckError; use expr::type_check_expression; use crate::node_interner::{FuncId, NodeInterner}; pub fn type_check_func(interner: &mut NodeInterner, func_id: FuncId) -> Result<(), TypeCheckError> { let meta = interner.function_meta(&func_id); let d...
mod errors; mod expr; mod stmt; use errors::TypeCheckError; use expr::type_check_expression; use crate::node_interner::{FuncId, NodeInterner}; pub fn type_check_func(interner: &mut NodeInterner, func_id: FuncId) -> Result<(), TypeCheckError> { let meta = interner.function_meta(&func_id); let d...
#[test] fn basic_call_expr() { let src = r#" fn main(x : Field) { priv _z = x + foo(x); } fn foo(x : Field) -> Field { x } "#; type_check_src_code(src, vec![String::from("main"), String::from("foo")]); ...
fn basic_index_expr() { let src = r#" fn main(x : Field) { let k = [x,x]; priv _z = x + k[0]; } "#; type_check_src_code(src, vec![String::from("main")]); }
function_block-function_prefix_line
[ { "content": "fn parse_let_statement(parser: &mut Parser) -> Result<LetStatement, ParserErrorKind> {\n\n let generic_stmt = parse_generic_decl_statement(parser)?;\n\n\n\n let stmt = LetStatement {\n\n identifier: generic_stmt.identifier,\n\n r#type: generic_stmt.typ.unwrap_or(Type::Unspecifi...
Rust
etk-asm/src/disasm.rs
Sheikh-A/etk
f22319ecd69bad0dd84124a47b506d0bdc8d2866
mod error { use snafu::{Backtrace, Snafu}; use super::Offset; #[derive(Debug, Snafu)] #[snafu(visibility = "pub(super)")] #[non_exhaustive] pub enum Error { #[non_exhaustive] Truncated { remaining: Offset<Vec<u8>>, ...
mod error { use snafu::{Backtrace, Snafu}; use super::Offset; #[derive(Debug, Snafu)] #[snafu(visibility = "pub(super)")] #[non_exhaustive] pub enum Error { #[non_exhaustive] Truncated { remaining: Offset<Vec<u8>>, ...
}
fn push5() { let input = hex!("640102030405"); let expected = [Offset::new(0, Op::Push5(hex!("0102030405").into()))]; let mut dasm = Disassembler::new(); dasm.write_all(&input).unwrap(); let actual: Vec<_> = dasm.ops().collect(); assert_eq!(expected, actual.as_slice())...
function_block-full_function
[ { "content": "#[doc(hidden)]\n\npub trait Immediate<const N: usize>: Debug + Clone + Eq + PartialEq {\n\n fn extra_len() -> usize {\n\n N\n\n }\n\n}\n\n\n\nimpl<T, const N: usize> Immediate<N> for [T; N] where T: Debug + Clone + Eq + PartialEq {}\n\nimpl<const N: usize> Immediate<N> for Imm<[u8; N]...
Rust
src/main.rs
Nukesor/geil
a536173698885d0e98689d2efd195a90493e0114
use std::collections::HashMap; use std::env::vars; use anyhow::Result; use clap::Parser; use indicatif::{ProgressBar, ProgressStyle}; use log::error; use rayon::prelude::*; use simplelog::{Config, LevelFilter, SimpleLogger}; mod cli; mod display; mod git; mod process; mod repository_info; mod state; use cli::*; use ...
use std::collections::HashMap; use std::env::vars; use anyhow::Result; use clap::Parser; use indicatif::{ProgressBar, ProgressStyle}; use log::error; use rayon::prelude::*; use simplelog::{Config, LevelFilter, SimpleLogger}; mod cli; mod display; mod git; mod process; mod repository_info; mod state; use cli::*; use ...
fn main() -> Result<()> { let opt = CliArguments::parse(); let level = match opt.verbose { 0 => LevelFilter::Error, 1 => LevelFilter::Warn, 2 => LevelFilter::Info, _ => LevelFilter::Debug, }; SimpleLogger::init(level, Config::default()).unwrap(); let mut s...
function_block-full_function
[ { "content": "pub fn format_state(state: &RepositoryState) -> Cell {\n\n match state {\n\n RepositoryState::Updated => Cell::new(\"Updated\").fg(Color::Green),\n\n RepositoryState::UpToDate => Cell::new(\"Up to date\").fg(Color::DarkGreen),\n\n RepositoryState::Fetched => Cell::new(\"Fet...
Rust
src/frontend/server.rs
neofight78/chrust
bfc1cb762b7b2859a02d5ada6fd995a70961772a
use super::{ responses::{SettingsResponse, ValidateResponse}, }; use crate::{ frontend::responses::MoveOptionsResponse, game::chessgame::{is_valid, process_fen, valid_moves}, state::programstate::ProgramState, }; use rocket::{ get, http::ContentType, post, response::{ content::{C...
use super::{ responses::{SettingsResponse, ValidateResponse}, }; use crate::{ frontend::responses::MoveOptionsResponse, game::chessgame::{is_valid, process_fen, valid_moves}, state::programstate::ProgramState, }; use rocket::{ get, http::ContentType, post, response::{ content::{C...
.mount("/chrust/api", routes![validate]) .mount("/chrust/api", routes![settings]) .launch() .await }
tings { program_state: Mutex::from(ps), }) .manage(ImageMap { map: init_image_map(), }) .mount("/chrust", routes![index]) .mount("/chrust/js", routes![javascript]) .mount("/chrust/css", routes![css]) .mount("/img", routes![chesspiece]) ...
function_block-random_span
[ { "content": "pub fn get_args() -> Result<ProgramState, Box<dyn std::error::Error>> {\n\n let matches = App::new(\"Chrust\")\n\n .version(\"0.2.0\")\n\n .author(\"John YB. <jyenterbriars@gmail.com>\")\n\n .about(\"Simple Chess Engine\")\n\n .arg(\n\n Arg::new(\"viz\")\n...