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/web/websocket.rs
alecdwm/webtron
ba90a9e5d7d388dbe93228eceb1cfc656016288c
use futures::sink::{Sink, SinkExt}; use futures::stream::{Stream, StreamExt}; use log::{debug, error, trace, warn}; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use tokio::select; use tokio::sync::mpsc; use tokio::sync::mpsc::{Receiver, Sender}; use tokio::sync::Mutex; use tokio::time; use war...
use futures::sink::{Sink, SinkExt}; use futures::stream::{Stream, StreamExt}; use log::{debug, error, trace, warn}; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use tokio::select; use tokio::sync::mpsc; use tokio::sync::mpsc::{Receiver, Sender}; use tokio::sync::Mutex; use tokio::time; use war...
async fn handle_out(mut rx: Receiver<MessageOut>, tx: Arc<Mutex<impl Sink<Message> + Unpin>>) { debug!("Websocket handler (out) created"); while let Some(message) = rx.recv().await { let text = match message.to_json() { Ok(text) => text, Err(error) => { error!( ...
eIn::from_json(id, text) { Ok(message) => message, Err(error) => { warn!("Failed to parse incoming message ({}): {}", text, error); continue; } }; tx.send(message) .await .unwrap_or_else(|error| error!("Failed t...
function_block-function_prefixed
[ { "content": "pub fn embed() -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone {\n\n let index = warp::path::end().and_then(serve_index);\n\n let path = warp::path::tail().and_then(serve_path);\n\n\n\n index.or(path)\n\n}\n\n\n\nasync fn serve_index() -> Result<impl Reply, Rejection> {...
Rust
src/stats/mod.rs
hhandika/yap
95f0b06770b958afef12105c8088274684bbdae8
mod fasta; mod fastq; mod math; mod output; mod qscores; mod sequence; use std::path::PathBuf; use std::sync::mpsc::channel; use rayon::prelude::*; use walkdir::WalkDir; use crate::stats::sequence::{FastaStats, FastqStats}; pub fn process_wildcard(entries: &[&str], iscsv: bool, fastq: bool) { let files: Vec<Pat...
mod fasta; mod fastq; mod math; mod output; mod qscores; mod sequence; use std::path::PathBuf; use std::sync::mpsc::channel; use rayon::prelude::*; use walkdir::WalkDir; use crate::stats::sequence::{FastaStats, FastqStats}; pub fn process_wildcard(entries: &[&str], iscsv: bool, fastq: bool) { let files: Vec<Pat...
#[cfg(test)] mod tests { use super::*; #[test] fn tranverse_dir_test() { let input = "test_files/stats"; let files = tranverse_dir(&input, true); assert_eq!(4, files.len()) } #[test] fn match_fasta_test() { let input = vec!["test.fasta", "test.fas", "test.fa"...
files.into_par_iter().for_each_with(sender, |s, recs| { s.send(fasta::process_fasta(&recs)).unwrap(); }); let mut all_reads: Vec<FastaStats> = receiver.iter().collect(); output::write_fasta(&mut all_reads, iscsv); }
function_block-function_prefix_line
[ { "content": "pub fn write_fasta(stats: &mut [FastaStats], iscsv: bool) {\n\n stats.sort_by(|a, b| a.seqname.cmp(&b.seqname));\n\n\n\n println!(\"\\n\\x1b[1mResults:\\x1b[0m\");\n\n stats.iter().for_each(|recs| {\n\n write_fasta_console(&recs);\n\n });\n\n println!(\"Total files: {}\", sta...
Rust
examples/echo_server.rs
over-codes/oc-http
79051db0857225d437e499ef52782591a3ceca28
use std::{ error::Error }; use std::time::Duration; use log::{warn}; use env_logger::Env; use async_std::{ task, io::{ BufReader, BufWriter, }, net::{ TcpListener, }, }; use futures::{ prelude::*, AsyncRead, AsyncWrite, }; use oc_http::{ cookies::{Cooki...
use std::{ error::Error }; use std::time::Duration; use log::{warn}; use env_logger::Env; use async_std::{ task, io::{ BufReader, BufWriter, }, net::{ TcpListener, }, }; use futures::{ prelude::*, AsyncRead, AsyncWrite, }; use oc_http::{ cookies::{Cooki...
async fn get_echo<S>(mut stream: &mut S) where S: AsyncWrite + Unpin { oc_http::respond(&mut stream, oc_http::Response{ code: 200, reason: "OK", headers: vec!(), }).await.unwrap(); stream.write(b" <html> <body> <form method=\"POST\"> <input name=\"input\"></...
T" { post_echo(&mut reader, &mut writer).await; if let Some(_c) = cookies.get("Who") { writer.write(format!("You are a fool of a took!").as_bytes()).await.unwrap(); } } else { let mut res = oc_http::Response{ code: 404, reason: "NOT FOUND", ...
function_block-function_prefixed
[ { "content": "fn main() {\n\n println!(\"Hello world!\");\n\n}\n\n\n\n/*\n\nuse std::io;\n\nuse std::error::Error;\n\nuse env_logger::Env;\n\nuse async_trait::async_trait;\n\nuse async_std::{\n\n prelude::*,\n\n sync::Arc,\n\n net::{\n\n TcpListener,\n\n },\n\n};\n\n\n\n#[async_std::main]\...
Rust
contracts/mirror_staking/src/contract.rs
jaypersanchez/shade
9b7357c366dceb108a300944d66dbf6deb735c01
use cosmwasm_std::{ from_binary, log, to_binary, Api, Binary, Decimal, Env, Extern, HandleResponse, HandleResult, HumanAddr, InitResponse, MigrateResponse, MigrateResult, Querier, StdError, StdResult, Storage, Uint128, }; use mirror_protocol::staking::{ ConfigResponse, Cw20HookMsg, HandleMsg, InitMsg, ...
use cosmwasm_std::{ from_binary, log, to_binary, Api, Binary, Decimal, Env, Extern, HandleResponse, HandleResult, HumanAddr, InitResponse, MigrateResponse, MigrateResult, Querier, StdError, StdResult, Storage, Uint128, }; use mirror_protocol::staking::{ ConfigResponse, Cw20HookMsg, HandleMsg, InitMsg, ...
pub fn query_pool_info<S: Storage, A: Api, Q: Querier>( deps: &Extern<S, A, Q>, asset_token: HumanAddr, ) -> StdResult<PoolInfoResponse> { let asset_token_raw = deps.api.canonical_address(&asset_token)?; let pool_info: PoolInfo = read_pool_info(&deps.storage, &asset_token_raw)?; Ok(PoolInfoRespons...
mirror_token: deps.api.human_address(&state.mirror_token)?, mint_contract: deps.api.human_address(&state.mint_contract)?, oracle_contract: deps.api.human_address(&state.oracle_contract)?, terraswap_factory: deps.api.human_address(&state.terraswap_factory)?, base_denom: state.base_denom, ...
function_block-function_prefix_line
[ { "content": "pub fn query_reward_info<S: Storage, A: Api, Q: Querier>(\n\n deps: &Extern<S, A, Q>,\n\n staker_addr: HumanAddr,\n\n asset_token: Option<HumanAddr>,\n\n) -> StdResult<RewardInfoResponse> {\n\n let staker_addr_raw = deps.api.canonical_address(&staker_addr)?;\n\n\n\n let reward_infos...
Rust
src/message/message.rs
ddimaria/stun-server
4557238c5f05f69105c1834da09f62aad74b826e
use crate::error::{Error, Result}; use crate::message::attribute::Attribute; use crate::message::class::Class; use crate::message::method::Method; use crate::message::transaction_id::TransactionId; use bytes::{Buf, BufMut, Bytes, BytesMut}; pub(crate) const MAGIC_COOKIE: u32 = 0x2112A442; pub(crate) const MESSAGE_HEA...
use crate::error::{Error, Result}; use crate::message::attribute::Attribute; use crate::message::class::Class; use crate::message::method::Method; use crate::message::transaction_id::TransactionId; use bytes::{Buf, BufMut, Bytes, BytesMut}; pub(crate) const MAGIC_COOKIE: u32 = 0x2112A442; pub(crate) const MESSAGE_HEA...
let message_type = buffer.get_u16(); let class = Class::decode(message_type)?; let method = Method::decode(message_type); let message_length = buffer.get_u16() as usize; let magic_cookie = buffer.get_u32(); let transaction_id = TransactionId::decode(buffer)?; ...
if buffer.remaining() < MESSAGE_HEADER_LENGTH { return Err(Error::Decode(format!( "Not enough bytes in the header. Expected {}, but got {}", 20, buffer.remaining() ))); }
if_condition
[ { "content": " method.into()\n\n }\n\n}\n\n\n\nimpl From<u16> for Method {\n\n fn from(value: u16) -> Method {\n\n match value {\n\n 0x001 => Method::Binding,\n\n _ => unimplemented!(\"Only binding methods are allowed\"),\n\n }\n\n }\n\n}\n\n\n\nimpl Into<u16>...
Rust
src/graphics/camera.rs
yggie/mithril-examples
5dd264bfbe38a80bc52ba5923d2091bcfc3b7d4b
extern crate mithril; use std::f64; use std::num::Float; use self::mithril::math::{ Vector, Quaternion }; pub struct Camera { position: Vector, focus_point: Vector, up: Vector, field_of_view: f64, aspect_ratio: f64, far: f64, near: f64, anchor_point: Option<[f64; 2]>, control_point...
extern crate mithril; use std::f64; use std::num::Float; use self::mithril::math::{ Vector, Quaternion }; pub struct Camera { position: Vector, focus_point: Vector, up: Vector, field_of_view: f64, aspect_ratio: f64, far: f64, near: f64, anchor_point: Option<[f64; 2]>, control_point...
pub fn projection_matrix(&self) -> [f32; 16] { let m_11 = (1.0 / (self.field_of_view / 2.0).tan()) as f32; let m_22 = m_11 * (self.aspect_ratio as f32); let m_33 = -((self.far + self.near) / (self.far - self.near)) as f32; let m_43 = -((2.0 * self.far * self.near) / (self.far - sel...
xis[0], rot_axis[1], rot_axis[2]); let new_u_quat = rot_quat * u_quat * rot_quat.inverse(); let new_v_quat = rot_quat * v_quat * rot_quat.inverse(); let new_w_quat = rot_quat * w_quat * rot_quat.inverse(); x_view[0] = new_u_quat[1]; ...
function_block-function_prefixed
[ { "content": "pub fn import_from_obj(filepath: &str) -> (Vec<GLfloat>, Vec<GLfloat>, Vec<GLuint>) {\n\n let comments_regex = Regex::new(r\"\\A\\s*#(?s:.*)\\z\").ok().unwrap();\n\n let vertex_regex = Regex::new(r\"\\A\\s*v\\s+(\\+?-?\\d+\\.\\d+)\\s+(\\+?-?\\d+\\.\\d+)\\s+(\\+?-?\\d+\\.\\d+)\\s*\\z\").ok()....
Rust
07-rust/stm32l0x1/stm32l0x1_pac/src/adc/isr.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register ISR"] pub type R = crate::R<u32, super::ISR>; #[doc = "Writer for register ISR"] pub type W = crate::W<u32, super::ISR>; #[doc = "Register ISR `reset()`'s with value 0"] impl crate::ResetValue for super::ISR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
#[doc = "Reader of register ISR"] pub type R = crate::R<u32, super::ISR>; #[doc = "Writer for register ISR"] pub type W = crate::W<u32, super::ISR>; #[doc = "Register ISR `reset()`'s with value 0"] impl crate::ResetValue for super::ISR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } impl R { #[doc = "Bit 0 - ADC ready"] #[inline(always)] pub fn adrdy(&self) -> ADRDY_R { ADRDY_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - End of sampling flag"] ...
r field `EOCAL`"] pub struct EOCAL_W<'a> { w: &'a mut W, } impl<'a> EOCAL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { ...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
day_05_puzzle_02/src/grid.rs
simonhaisz/advent_of_code_2021
cc75f0d281a5a67b8a2e552fd240896a48a6a795
use std::collections::HashSet; use crate::line::{self, Line, Point}; pub struct Grid { lines: Vec<Line>, } impl Grid { pub fn new() -> Grid { Grid { lines: vec![], } } pub fn add_line(&mut self, line: Line) { self.lines.push(line); } pub fn overlaps(&self)...
use std::collections::HashSet; use crate::line::{self, Line, Point}; pub struct Grid { lines: Vec<Line>, } impl Grid { pub fn new() -> Grid { Grid { lines: vec![], } } pub fn add_line(&mut self, line: Line) { self.lines.push(line); }
} #[cfg(test)] mod tests { use super::*; #[test] fn test_overlaps_square() { let mut grid = Grid::new(); grid.add_line(Line::new(Point::new(1, 1), Point::new(1, 10))); grid.add_line(Line::new(Point::new(1, 1), Point::new(10, 1))); grid.add_line(Line::new(Point::new(1, 10),...
pub fn overlaps(&self) -> HashSet<Point> { let mut overlaps = HashSet::new(); let lines = self.lines.iter().collect::<Vec<&Line>>(); let mut compare_counter = 0; for outer in 0..(lines.len()-1) { for inner in (outer+1)..lines.len() { let a = lines[outer]; ...
function_block-full_function
[ { "content": "pub fn intersections_optimized(a: &Line, b: &Line) -> Vec<Point> {\n\n let mut points = vec!();\n\n\n\n if (!a.horizontal() && !a.vertical()) || (!b.horizontal() && !b.vertical()) {\n\n panic!(\"Expected lines to be either horizontal or vertical in order to determine intersections\\nl...
Rust
backend/src/integrations/lifx/utils.rs
FruitieX/homectl-rs
fc3d8e5569ce813491e7cd234b1ad774ca81ebd6
use anyhow::{anyhow, Result}; use byteorder::{ByteOrder, LittleEndian}; use homectl_types::device::{Device, DeviceColor, DeviceId, DeviceState, Light}; use homectl_types::integration::IntegrationId; use palette::Hsv; use std::net::SocketAddr; #[derive(Clone, Debug)] pub struct LifxState { pub hue: u16, pub sat...
use anyhow::{anyhow, Result}; use byteorder::{ByteOrder, LittleEndian}; use homectl_types::device::{Device, DeviceColor, DeviceId, DeviceState, Light}; use homectl_types::integration::IntegrationId; use palette::Hsv; use std::net::SocketAddr; #[derive(Clone, Debug)] pub struct LifxState { pub hue: u16, pub sat...
?; let power = if light_state.power { 65535 } else { 0 }; let transition = light_state .transition_ms .map(|transition_ms| transition_ms as u32); match light_state.color { Some(DeviceColor::Color(color)) => { let hue = ((to_lifx_hue(color.hue.to_positive...
match device.state.clone() { DeviceState::Light(Light { brightness, color, power, transition_ms, }) => Ok(Light { power, brightness, color, transition_ms, }), _ => Err(anyhow!("Unsupported dev...
if_condition
[ { "content": "fn default_device(device_id: DeviceId, name: String, integration_id: IntegrationId) -> Device {\n\n Device {\n\n id: device_id,\n\n name,\n\n integration_id,\n\n scene: None,\n\n state: DeviceState::Light(Light {\n\n power: false,\n\n bri...
Rust
src/options.rs
manuelsteiner/rcproxy
bef7ced754a5d15328ca20e6ff46ca3018b729b1
use ipnet::IpNet; use log::LevelFilter; use std::collections::HashMap; use std::process::exit; use std::result::Result::Ok; use structopt::clap::arg_enum; use structopt::StructOpt; lazy_static! { pub static ref OPT: Opt = { let mut opt = Opt::from_args(); opt.headers = match opt.header.clone() { ...
use ipnet::IpNet; use log::LevelFilter; use std::collections::HashMap; use std::process::exit; use std::result::Result::Ok; use structopt::clap::arg_enum; use structopt::StructOpt; lazy_static! { pub static ref OPT: Opt = { let mut opt = Opt::from_args(); opt.headers = match opt.header.clone() { ...
#[test] fn test_validate_and_extract_filters_error() { let filters: Vec<String> = vec!["ad:.*deny.com/.*".to_string()]; assert_eq!(validate_and_extract_filters(&filters), Err(())); } }
m/.*".to_string(), ".*deny2.com/.*".to_string()]; assert_eq!( validate_and_extract_filters(&filters), Ok((filters_allow, filters_deny)) ); }
function_block-function_prefixed
[ { "content": "fn decode_and_validate_url(encoded_url: &str, allow_https: bool) -> Result<String, ()> {\n\n let url = match hex::decode(encoded_url) {\n\n Ok(url) => url,\n\n Err(_error) => {\n\n debug!(\"URL parameter is not HEX encoded.\");\n\n\n\n match base64::decode(en...
Rust
packages/vm/src/limited.rs
venkattejaRaavi/cosmwasm
73c72d4eccd5028e18fd60e77f44d975647a13bd
use std::collections::{BTreeSet, HashSet}; use std::iter::FromIterator; pub trait LimitedDisplay { fn to_string_limited(&self, max_length: usize) -> String; } impl<E: Ord + AsRef<str>> LimitedDisplay for BTreeSet<E> { fn to_string_limited(&self, max_length: usize) -> String { collection_to...
use std::collections::{BTreeSet, HashSet}; use std::iter::FromIterator; pub trait LimitedDisplay { fn to_string_limited(&self, max_length: usize) -> String; } impl<E: Ord + AsRef<str>> LimitedDisplay for BTreeSet<E> { fn to_string_limited(&self, max_length: usize) -> String { collection_to...
#[test] fn works_for_hashset() { let set = HashSet::<String>::new(); assert_eq!(set.to_string_limited(100), "{}"); assert_eq!(set.to_string_limited(20), "{}"); assert_eq!(set.to_string_limited(2), "{}"); let fruits = HashSet::from_iter( [ "w...
cloned(), ); assert_eq!( fruits.to_string_limited(100), "{\"apple\", \"banana\", \"watermelon\"}" ); assert_eq!( fruits.to_string_limited(33), "{\"apple\", \"banana\", \"watermelon\"}" ); assert_eq!( fruits.to_st...
function_block-function_prefix_line
[ { "content": "/// Takes a comma-separated string, splits it by commas, removes empty elements and returns a set of features.\n\n/// This can be used e.g. to initialize the cache.\n\npub fn features_from_csv(csv: &str) -> HashSet<String> {\n\n HashSet::from_iter(\n\n csv.split(',')\n\n .map(...
Rust
sync/src/relayer/tests/compact_block_verifier.rs
orangemio/ckb
5b3664e162c840f421469279e7e68fe9dcad75dd
use crate::relayer::compact_block::{CompactBlock, ShortTransactionID}; use crate::relayer::compact_block_verifier::{PrefilledVerifier, ShortIdsVerifier}; use crate::relayer::error::Error; use ckb_core::transaction::{CellOutput, IndexTransaction, TransactionBuilder}; use ckb_core::Capacity; use ckb_protocol::{short_tran...
use crate::relayer::compact_block::{CompactBlock, ShortTransactionID}; use crate::relayer::compact_block_verifier::{PrefilledVerifier, ShortIdsVerifier}; use crate::relayer::error::Error; use ckb_core::transaction::{CellOutput, IndexTransaction, TransactionBuilder}; use ckb_core::Capacity; use ckb_protocol::{short_tran...
#[test] fn test_duplicated_short_ids() { let mut block = CompactBlock::default(); let mut short_ids: Vec<ShortTransactionID> = (1..5) .map(new_index_transaction) .map(|tx| { let (key0, key1) = short_transaction_id_keys(block.header.nonce(), block.nonce); short_transacti...
filled) ); let mut block = CompactBlock::default(); let prefilled: Vec<IndexTransaction> = (1..5).map(new_index_transaction).collect(); block.prefilled_transactions = prefilled; assert_eq!( PrefilledVerifier::new().verify(&block), Err(Error::CellbaseNotPrefilled), ); }
function_block-function_prefixed
[ { "content": "// Build compact block based on core block, and specific prefilled indices\n\npub fn build_compact_block_with_prefilled(block: &Block, prefilled: Vec<usize>) -> Bytes {\n\n let prefilled = prefilled.into_iter().collect();\n\n let fbb = &mut FlatBufferBuilder::new();\n\n let message = Rela...
Rust
crates/brine_voxel_v1/src/chunk_builder/plugin.rs
BGR360/brine
048656dfb3dc5c608536f14d687c6f7a9075df0a
use std::collections::hash_map::Entry; use std::{any::Any, marker::PhantomData}; use bevy::tasks::Task; use bevy::utils::{HashMap, HashSet}; use bevy::{ecs::event::Events, prelude::*, tasks::AsyncComputeTaskPool}; use futures_lite::future; use brine_asset::{api::BlockFace, MinecraftAssets}; use brine_chunk::ChunkSect...
use std::collections::hash_map::Entry; use std::{any::Any, marker::PhantomData}; use bevy::tasks::Task; use bevy::utils::{HashMap, HashSet}; use bevy::{ecs::event::Events, prelude::*, tasks::AsyncComputeTaskPool}; use futures_lite::future; use brine_asset::{api::BlockFace, MinecraftAssets}; use brine_chunk::ChunkSect...
if !texture_handles.contains(&strong_handle) { texture_handles.insert(strong_handle.clone()); } entry.insert(strong_handle.as_weak()).clone_weak() } Entry::Occupied(entry) => entry.get().clone_weak(), ...
let strong_handle = match mc_assets .get_texture_path_for_block_state_and_face(block_state_id, face) { Some(path) => asset_server.load(path), None => { debug!("No texture for {:?}:{:?}", block_state_i...
assignment_statement
[ { "content": "pub fn build_bevy_mesh(voxel_mesh: &VoxelMesh) -> Mesh {\n\n let num_vertices = voxel_mesh.quads.len() * 4;\n\n let num_indices = voxel_mesh.quads.len() * 6;\n\n let mut positions = Vec::with_capacity(num_vertices);\n\n let mut normals = Vec::with_capacity(num_vertices);\n\n let mut...
Rust
src/generator/painter/stroke.rs
zeh/art-generator
916ea37631dc9a0030187af06afad0914b0a39ff
use std::collections::HashMap; use image::{Pixel, Rgb, RgbImage}; use crate::generator::painter::Painter; use crate::generator::utils::color::BlendingMode; use crate::generator::utils::geom::find_target_draw_rect; use crate::generator::utils::pixel::{blend, blend_linear}; use crate::generator::utils::random::{ get_n...
use std::collections::HashMap; use image::{Pixel, Rgb, RgbImage}; use crate::generator::painter::Painter; use crate::generator::utils::color::BlendingMode; use crate::generator::utils::geom::find_target_draw_rect; use crate::generator::utils::pixel::{blend, blend_linear}; use crate::generator::utils::random::{ get_n...
; let offset_x2 = (x2 as f64 + noise_x) - x as f64; let alpha_x2 = if offset_x2 > 0.5 { 1.0 } else if offset_x2 < -0.5 { 0.0 } else { offset_x2 + 0.5 }; alpha_x1 * alpha_x2 }; let alpha_y = if y >= y1 + margin_ceil && y < y2 - margin_ceil { ...
if offset_x1 > 0.5 { 1.0 } else if offset_x1 < -0.5 { 0.0 } else { offset_x1 + 0.5 }
if_condition
[ { "content": "#[inline(always)]\n\npub fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {\n\n\tlet x = x1 - x2;\n\n\tlet y = y1 - y2;\n\n\t(x * x + y * y).sqrt()\n\n}\n\n\n", "file_path": "src/generator/utils/geom.rs", "rank": 0, "score": 301141.6146164706 }, { "content": "/// Parses a...
Rust
src/main.rs
wayfair-tremor/uring
483adf33d61a767a2de9a5ed4ed5cc272cc62ac2
#![recursion_limit = "2048"] mod codec; #[allow(unused)] pub mod errors; pub mod network; mod protocol; mod pubsub; pub mod raft_node; pub mod service; pub mod storage; pub mod version; use crate::network::{ws, Network, RaftNetworkMsg}; use crate::raft_node::*; use crate::service::mring::{self, placement::continuou...
#![recursion_limit = "2048"] mod codec; #[allow(unused)] pub mod errors; pub mod network; mod protocol; mod pubsub; pub mod raft_node; pub mod service; pub mod storage; pub mod version; use crate::network::{ws, Network, RaftNetworkMsg}; use crate::raft_node::*; use crate::service::mring::{self, placement::continuou...
_tx = pubsub::start(&logger); let network = ws::Network::new(&logger, id, endpoint, rest_endpoint, peers, ps_tx.clone()); task::block_on(raft_loop( id, bootstrap, ring_size, ps_tx, network, loop_logger, )); Ok(()) }
.help("The Node ID") .takes_value(true), ) .arg( Arg::with_name("bootstrap") .short("b") .long("bootstrap") .value_name("BOOTSTRAP") .help("Sets the node to bootstrap mode and become leader") .t...
function_block-random_span
[ { "content": "pub fn log(logger: &Logger) {\n\n info!(logger, \"uring version: {}\", VERSION);\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn for_coverage_only() {\n\n print();\n\n log(&slog::Logger::root(slog::Discard, o!()));\n\n }\n\n}\n", "fi...
Rust
playground/jwk/src/lib.rs
DIN-Foundation/bcs-ntnu-2021
99532334904dfce5f4c2e3fdd816be80c2f5a3c9
pub fn run(config: Config) -> Result<String, std::io::Error> { match config.cmd { CMD::Init{ path } => init(&path), CMD::Doc{ path } => doc(&path), CMD::Did{ path } => did(&path), CMD::Help => help() } } fn init(path: &str) -> Result<String, std::io::Error> { use std::io::Wr...
pub fn run(config: Config) -> Result<String, std::io::Error> { match config.cmd { CMD::Init{ path } => init(&path), CMD::Doc{ path } => doc(&path), CMD::Did{ path } => did(&path), CMD::Help => help() } } fn init(path: &str) -> Result<String, std::io::Error> { use std::io::Wr...
} fn root_path(path: &str) -> String { format!("{}/.didchat", path) } fn jwk_path(path: &str) -> String { format!("{}/.didchat/me.jwk", path) } fn publicprivatebytes_to_jwkstr(public: Vec<u8>, private: Vec<u8>) -> String { let jwk = ssi::jwk::JWK { params: ssi::jwk::Params::OKP(ssi::jwk::OctetPa...
2).unwrap_or(&default_cmd).clone(); let cmd = if args.len() < 3 { eprintln!("Command missing!"); default_cmd.clone() } else { cmd.clone() }; let cmd: CMD = match &cmd[..] { "did" => { CMD::Did{ path } }, ...
function_block-function_prefixed
[ { "content": "//\n\n// Commands\n\n//\n\nfn init(path: &str) -> Result<String, std::io::Error> {\n\n use std::io::Write;\n\n\n\n // 1. Create empty folders\n\n if !std::fs::metadata(root_path(path)).is_ok() {\n\n std::fs::create_dir_all(root_path(path))?;\n\n }\n\n if !std::fs::metadata(na...
Rust
src/libos/src/fs/file_ops/ioctl/mod.rs
qzheng527/ngo
635ce9ef2427fe1b602b40ec89aa3530b167169d
use super::*; use util::mem_util::from_user; pub use self::builtin::*; pub use self::non_builtin::{NonBuiltinIoctlCmd, StructuredIoctlArgType, StructuredIoctlNum}; #[macro_use] mod macros; mod builtin; mod non_builtin; impl_ioctl_nums_and_cmds! { TCGETS => (0x5401, mut KernelTermios), TCSET...
use super::*; use util::mem_util::from_user; pub use self::builtin::*; pub use self::non_builtin::{NonBuiltinIoctlCmd, StructuredIoctlArgType, StructuredIoctlNum}; #[macro_use] mod macros; mod builtin; mod non_builtin; impl_ioctl_nums_and_cmds! { TCGETS => (0x5401, mut KernelTermios), TCSET...
| IoctlRawCmd::SIOCGIFPFLAGS(req) | IoctlRawCmd::SIOCGIFTXQLEN(req) | IoctlRawCmd::SIOCGIFMAP(req) => { Box::new(GetIfReqWithRawCmd::new(self.cmd_num(), **req)) } _ => { return_errno!(EINVAL, "unsupported cmd"); } ...
| IoctlRawCmd::SIOCGIFBRDADDR(req) | IoctlRawCmd::SIOCGIFNETMASK(req) | IoctlRawCmd::SIOCGIFMTU(req) | IoctlRawCmd::SIOCGIFHWADDR(req) | IoctlRawCmd::SIOCGIFINDEX(req)
function_block-random_span
[ { "content": "// TODO: rename this to do_poll after the old version is removed\n\npub fn do_poll_new(poll_fds: &[PollFd], mut timeout: Option<&mut Duration>) -> Result<usize> {\n\n debug!(\"poll: poll_fds: {:?}, timeout: {:?}\", poll_fds, timeout);\n\n\n\n // Always clear the revents fields first\n\n f...
Rust
src/rugl.rs
micahscopes/rugl
bb7fefb08c7d648f41630fe515c0bb128d95de69
/*! An ergonomic macro for creating themetic stateless WebGL applications! # Syntax ```ignore rugl_main! { vertex: " precision mediump float; attribute vec2 position; void main() { gl_Position = vec4(position, 0, 1); } "; fragment: " precision mediump fl...
/*! An ergonomic macro for creating themetic stateless WebGL applications! # Syntax ```ignore rugl_main! { vertex: " precision mediump float; attribute vec2 position; void main() { gl_Position = vec4(position, 0, 1); } "; fragment: " precision mediump fl...
rm(uniform.get_name())?; } Ok((inner, context)) } match build_inner() { Ok((inner, context)) => Ok(Rugl { inner, context }), Err(err) => { log!("There was an error! {}", err.as_string().unwrap()); Err("The...
er.get_count()); Ok(()) } } #[derive(Debug)] pub struct RuglInner<'a> { pub vertex: Cow<'a, str>, pub fragment: Cow<'a, str>, pub attributes: Vec<Attribute>, pub uniforms: Vec<Uniform>, pub count: i32, } impl<'a> RuglInner<'a> { pub fn get_vertex_shader(&self) -> &str { &s...
random
[ { "content": "fn main() {\n\n let dest_path = Path::new(\"pkg\");\n\n\n\n if !dest_path.exists() {\n\n fs::create_dir(dest_path).expect(\"Unable to create directory\");\n\n }\n\n\n\n let test = Command::new(\"wasm-bindgen\")\n\n .args(&[\n\n \"target/wasm32-unknown-unknown/d...
Rust
yamux/examples/throughput_test.rs
kingwel-xie/tentacle
9efe228ee6de3577a4ac2967f1055e00ebb32a11
use bytesize::ByteSize; use futures::prelude::*; use log::{info, warn}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}, time::delay_for, }; use tokio_yamux::stream::StreamHandle; use tokio_yamux::{config::Config, session::Session}; fn main() { env_logger::init(); if s...
use bytesize::ByteSize; use futures::prelude::*; use log::{info, warn}; use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}, time::delay_for, }; use tokio_yamux::stream::StreamHandle; use tokio_yamux::{config::Config, session::Session}; fn main() { env_logger::init(); if s...
reqc_incr(); assert_eq!(data.as_ref(), STR.as_bytes()); } }); } }); } }); } fn run_client() { let num = std::env::args() .nth(1) .and_then(|s| s.parse::<usize>().ok()) .unwrap_or...
client ......"); run_client(); } } const STR: &str = "fakeu1234567890cmxcmmmmmmmmmsssmssmsmsmxcmcmcnxzlllslsllcccccsannmxmxmxmxmxmxmxmxmmsssjjkzoso."; const LEN: usize = STR.len(); static REQC: AtomicUsize = AtomicUsize::new(0); static RESPC: AtomicUsize = AtomicUsize::new(0); use std::{ str, syn...
random
[ { "content": "fn main() {\n\n init();\n\n\n\n let cycles = std::env::args()\n\n .nth(1)\n\n .and_then(|number| number.parse().ok())\n\n .unwrap_or(100);\n\n\n\n let check_point = std::env::args()\n\n .nth(2)\n\n .and_then(|number| number.parse().ok())\n\n .unwr...
Rust
app/src/core.rs
IgnusG/garlic
dd8100f035c59952ae2db43cb26c9111907f3711
use mio::tcp::{TcpStream, TcpListener}; use mio::{Poll, Token, Ready, PollOpt, Events}; use std::net; use std::net::SocketAddr; use std::sync::mpsc; use std::thread; use std::thread::{JoinHandle}; use std::io::Write; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use errors::*; use brunch::{send_m...
use mio::tcp::{TcpStream, TcpListener}; use mio::{Poll, Token, Ready, PollOpt, Events}; use std::net; use std::net::SocketAddr; use std::sync::mpsc; use std::thread; use std::thread::{JoinHandle}; use std::io::Write; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use errors::*; use brunch::{send_m...
_over_data(data: OnionTunnelPayload) -> Result<()> { unimplemented!(); } fn start_dialogue(message: &OnionTunnelBuild, conf: &config::Config, comm: &Communication) { trace_labeled_error!( "dialogue encountered a problem", { let mut peers = vec![]; for _ in 0..conf.min_hop_count { le...
eers.len() < 2 { return Ok(data) }; for peer in &peers[1..] { let request_id = NEXT_TUNNEL_ID.fetch_add(1, Ordering::SeqCst) as u32; comm.send(Auth(CipherEncrypt(AuthCipherCrypt { session_id: peers[0].session_id, request_id: request_id, cleartext: fal...
random
[ { "content": "pub fn start (conf: config::Config) -> Result<()> {\n\n status!(\"Brunch is served!\");\n\n\n\n let (tx, rx) = mpsc::channel();\n\n let (ty, ry) = mpsc::channel();\n\n\n\n let api_thread_handle = {\n\n let conf = conf.clone();\n\n let tx = tx.clone();\n\n\n\n creat...
Rust
weechat/src/hooks/commands.rs
troethe/rust-weechat
8533abf0e000659f567e404d3c8aa0d773eff685
use libc::{c_char, c_int}; use std::{borrow::Cow, ffi::CStr, os::raw::c_void, ptr}; use weechat_sys::{t_gui_buffer, t_weechat_plugin, WEECHAT_RC_OK}; use crate::{buffer::Buffer, Args, LossyCString, ReturnCode, Weechat}; use super::Hook; pub struct Command { _hook: Hook, _hook_data: Box<CommandHookData>, } ...
use libc::{c_char, c_int}; use std::{borrow::Cow, ffi::CStr, os::raw::c_void, ptr}; use weechat_sys::{t_gui_buffer, t_weechat_plugin, WEECHAT_RC_OK}; use crate::{buffer::Buffer, Args, LossyCString, ReturnCode, Weechat}; use super::Hook; pub struct Command { _hook: Hook, _hook_data: Box<CommandHookData>, } ...
pub fn description<D: Into<String>>(mut self, descritpion: D) -> Self { self.description = descritpion.into(); self } pub fn add_argument<T: Into<String>>(mut self, argument: T) -> Self { self.arguments.push(argument...
pub fn new<P: Into<String>>(name: P) -> Self { CommandSettings { name: name.into(), ..Default::default() } }
function_block-full_function
[ { "content": "/// Trait for the completion callback.\n\n///\n\n/// A blanket implementation for pure `FnMut` functions exists, if data needs to\n\npub trait CompletionCallback {\n\n /// Callback that will be called if when a completion is requested.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `...
Rust
src/cli.rs
benmaddison/rfz
d4c24a28c2178db24858943a4a29a3cbf218b0c8
use std::convert::TryInto; use std::ffi::{OsStr, OsString}; use std::io::stdout; use std::path::PathBuf; use std::result; use std::str::FromStr; use clap::{crate_authors, crate_description, crate_name, crate_version}; use directories::ProjectDirs; use crate::cmd::{ArgProvider, CmdExec}; use crate::errors::{Error, Res...
use std::convert::TryInto; use std::ffi::{OsStr, OsString}; use std::io::stdout; use std::path::PathBuf; use std::result; use std::str::FromStr; use clap::{crate_authors, crate_description, crate_name, crate_version}; use directories::ProjectDirs; use crate::cmd::{ArgProvider, CmdExec}; use crate::errors::{Error, Res...
} #[test] fn test_dummy_sync() { let defaults = DummyDefaults {}; let argv = Some(vec!["rfz", "sync", "-v"]); let cli = Cli::init_from(&defaults, argv).unwrap(); match cli.args.subcommand() { (subcommand, Some(args)) => { assert_eq!(subcommand, "...
match cli.args.subcommand() { (subcommand, Some(args)) => { assert_eq!(subcommand, "summary"); let cli_args = CliArgs::from(args); assert_eq!(cli_args.path(), PathBuf::from("/home/foo/rfz/bar.html")); } _ => panic!("Cli parsing failed")...
if_condition
[ { "content": "fn index(args: &dyn ArgProvider) -> Result<()> {\n\n let collection = match Collection::from_dir(args.dir()) {\n\n Ok(set) => set,\n\n Err(e) => return Err(e),\n\n };\n\n let _stdout = stdout();\n\n #[cfg(not(test))]\n\n let mut writer = _stdout.lock();\n\n #[cfg(te...
Rust
src/protocol/argument.rs
dylanmckay/flep
c020400f4ead85c6261dbe29bded876aad83af97
use {Error, ErrorKind}; use std::io::prelude::*; use std::ascii::AsciiExt; use std::io; pub trait Argument : Sized { fn read_with_space(read: &mut BufRead) -> Result<Self, Error> { let mut buf: [u8; 1] = [0]; assert_eq!(read.read(&mut buf)?, 1, "unexpected EOF while c...
use {Error, ErrorKind}; use std::io::prelude::*; use std::ascii::AsciiExt; use std::io; pub trait Argument : Sized { fn read_with_space(read: &mut BufRead) -> Result<Self, Error> { let mut buf: [u8; 1] = [0]; assert_eq!(read.read(&mut buf)?, 1, "unexpected EOF while c...
} fn write(&self, write: &mut Write) -> Result<(), Error> { for c in self.chars() { assert!(c.is_ascii(), "only ASCII is supported in FTP"); } write!(write, "{}", self)?; Ok(()) } } macro_rules! impl_argument_integer { ($ty:ty) => { impl Argument for $ty { ...
match String::from_utf8(bytes) { Ok(s) => Ok(s), Err(..) => Err(ErrorKind::InvalidArgument("argument is not valid UTF-8".to_owned()).into()), }
if_condition
[ { "content": "/// Runs a FTP server on a given address.\n\n///\n\n/// Sets up an FTP server locally and begins to wait for clients\n\n/// to connect.\n\npub fn run<F,A>(server: &mut F, address: A) -> Result<(), Error>\n\n where F: Server,\n\n A: ToSocketAddrs {\n\n let mut addresses = address.to_...
Rust
wincolor/src/winapi_inline.rs
crlf0710/termcolor
1059a1e540ac8ab7a2c99508e1b304fcce192705
#![allow(bad_style, overflowing_literals, unused_macros, unused_imports, dead_code)] #[macro_use] pub mod macros { macro_rules! STRUCT { (#[debug] $($rest:tt)*) => ( STRUCT!{#[cfg_attr(feature = "impl-debug", derive(Debug))] $($rest)*} ); ($(#[$attrs:meta])* struct $name:ident { $($field:ident: $ftyp...
#![allow(bad_style, overflowing_literals, unused_macros, unused_imports, dead_code)] #[macro_use] pub mod macros { macro_rules! STRUCT { (#[debug] $($rest:tt)*) => ( STRUCT!{#[cfg_attr(feature = "impl-debug", derive(Debug))] $($rest)*} ); ($(#[$attrs:meta])* struct $name:ident { $($field:ident: $ftyp...
0x00020000; pub const FILE_ATTRIBUTE_EA: DWORD = 0x00040000; pub const FILE_ATTRIBUTE_PINNED: DWORD = 0x00080000; pub const FILE_ATTRIBUTE_UNPINNED: DWORD = 0x00100000; pub const FILE_ATTRIBUTE_RECALL_ON_OPEN: DWORD = 0x00040000; pub const FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS: DW...
TION; extern "system" { pub fn GetFileInformationByHandle( hFile: HANDLE, lpFileInformation: LPBY_HANDLE_FILE_INFORMATION, ) -> BOOL; pub fn GetFileType(hFile: HANDLE) -> DWORD; } } pub mod winnt { use self::winapi::ct...
random
[ { "content": "/// Returns the file type of the given handle.\n\n///\n\n/// If there was a problem querying the file type, then an error is returned.\n\n///\n\n/// This corresponds to calling [`GetFileType`].\n\n///\n\n/// [`GetFileType`]: https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-g...
Rust
src/mimc_hash.rs
oskarth/semaphore-rs
d462a4372f1fd9c27610f2acfe4841fab1d396aa
use crate::util::keccak256; use once_cell::sync::Lazy; use zkp_u256::U256; const NUM_ROUNDS: usize = 220; static MODULUS: Lazy<U256> = Lazy::new(|| { U256::from_decimal_str( "21888242871839275222246405745257275088548364400416034343698204186575808495617", ) .unwrap() }); static ROUND_CONSTANTS: ...
use crate::util::keccak256; use once_cell::sync::Lazy; use zkp_u256::U256; const NUM_ROUNDS: usize = 220; static MODULUS: Lazy<U256> = Lazy::new(|| { U256::from_decimal_str( "21888242871839275222246405745257275088548364400416034343698204186575808495617", ) .unwrap() }); static ROUND_CONSTANTS: ...
#[test] fn test_mix() { let mut left = U256::ONE; let mut right = U256::ZERO; mix(&mut left, &mut right); assert_eq!( left, U256::from_decimal_str( "8792246410719720074073794355580855662772292438409936688983564419486782556587" ...
d_constants() { assert_eq!(ROUND_CONSTANTS[0], U256::ZERO); assert_eq!( ROUND_CONSTANTS[1], U256::from_decimal_str( "7120861356467848435263064379192047478074060781135320967663101236819528304084" ) .unwrap() ); asser...
function_block-function_prefixed
[ { "content": "// See <https://internals.rust-lang.org/t/path-to-lexical-absolute/14940>\n\nfn absolute(path: &str) -> Result<PathBuf> {\n\n let path = Path::new(path);\n\n let mut absolute = if path.is_absolute() {\n\n PathBuf::new()\n\n } else {\n\n std::env::current_dir()?\n\n };\n\n...
Rust
src/player.rs
ttempleton/rust-battleship
48d45f8c5d8c73ec399e1b6781418cdb5774fdc0
use crate::{direction::Direction, ship::Ship, space::Space}; use std::cmp; pub struct Player { is_cpu: bool, spaces: Vec<Space>, ships: Vec<Ship>, grid_size: [u8; 2], grid_cursor: [u8; 2], } impl Player { pub fn new(grid_size: [u8; 2], ship_count: usize, is_cpu: bool) -> Player { Playe...
use crate::{direction::Direction, ship::Ship, space::Space}; use std::cmp; pub struct Player { is_cpu: bool, spaces: Vec<Space>, ships: Vec<Ship>, grid_size: [u8; 2], grid_cursor: [u8; 2], } impl Player { pub fn new(grid_size: [u8; 2], ship_count: usize, is_cpu: bool) -> Player { Playe...
pub fn move_placement_ship(&mut self, direction: Direction) -> Result<(), &'static str> { let index = self.ships.len() - 1; let old_head = self.ships[index].pos()[0]; let new_head = self .movement(&old_head, direction) .ok_or("movement ...
pub fn add_ship( &mut self, head: [u8; 2], direction: Direction, length: u8, placement: bool, ) -> Result<(), &'static str> { if self.ships.len() == self.ships.capacity() { Err("tried to add ship to a player with all ships already added") } else { ...
function_block-full_function
[ { "content": " 0 => Direction::North,\n\n 1 => Direction::East,\n\n 2 => Direction::South,\n\n 3 => Direction::West,\n\n _ => unreachable!(),\n\n }\n\n }\n\n\n\n /// Returns the direction travelled from `pos1` to `pos2` if the positions\n\n ...
Rust
plugins/afl/afl_mutate/src/afl_mutate.rs
elast0ny/CROWDFUZZ
340fd0e9e03e147ebe977d456e8f6052bcf183eb
use std::mem::MaybeUninit; pub use ::afl_lib::*; pub use ::cflib::*; mod mutators; pub use mutators::*; mod bit_flip; pub use bit_flip::*; mod arithmetic; pub use arithmetic::*; mod interesting; pub use interesting::*; mod havoc; pub use havoc::*; cflib::register!(name, env!("CARGO_PKG_NAME")); cflib::register!(load...
use std::mem::MaybeUninit; pub use ::afl_lib::*; pub use ::cflib::*; mod mutators; pub use mutators::*; mod bit_flip; pub use bit_flip::*; mod arithmetic; pub use arithmetic::*; mod interesting; pub use interesting::*; mod havoc; pub use havoc::*; cflib::register!(name, env!("CARGO_PKG_NAME")); cflib::register!(load...
fn validate( core: &mut dyn PluginInterface, store: &mut CfStore, plugin_ctx: *mut u8, ) -> Result<()> { let state = box_ref!(plugin_ctx, State); unsafe { state.inputs = store.as_mutref(STORE_INPUT_LIST, Some(core))?; state.cur_input_idx = store.as_ref(STORE_INPUT_IDX, Some(c...
afl: MaybeUninit::zeroed().assume_init(), afl_queue: MaybeUninit::zeroed().assume_init(), } }); Ok(Box::into_raw(state) as _) }
function_block-function_prefix_line
[ { "content": "// Initialize our plugin\n\nfn init(core: &mut dyn PluginInterface, store: &mut CfStore) -> Result<*mut u8> {\n\n #[allow(invalid_value)]\n\n let mut s = Box::new(unsafe {\n\n State {\n\n afl: AflGlobals::default(),\n\n queue: Vec::new(),\n\n is_calibr...
Rust
kapp_platforms/src/windows/application_windows.rs
kettle11/kettlewin
36109e9ab506b9bce55da6e1cdee0d10e64e6dc4
use super::external_windows::*; use super::utils_windows::*; use std::convert::TryInto; use std::ptr::{null, null_mut}; use kapp_platform_common::*; pub static mut CURRENT_CURSOR: HCURSOR = null_mut(); pub static mut WINDOWS_TO_REDRAW: Vec<WindowId> = Vec::new(); pub struct PlatformApplication { window_class_nam...
use super::external_windows::*; use super::utils_windows::*; use std::convert::TryInto; use std::ptr::{null, null_mut}; use kapp_platform_common::*; pub static mut CURRENT_CURSOR: HCURSOR = null_mut(); pub static mut WINDOWS_TO_REDRAW: Vec<WindowId> = Vec::new(); pub struct PlatformApplication { window_class_nam...
; SetCursor(super::application_windows::CURRENT_CURSOR); let mut position = POINT { x: 0, y: 0 }; GetCursorPos(&mut position); SetCursorPos(position.x, position.y); CURRENT_CURSOR = cursor; } } fn hide_...
match cursor { Cursor::Arrow => LoadCursorW(null_mut(), IDC_ARROW), Cursor::IBeam => LoadCursorW(null_mut(), IDC_IBEAM), Cursor::PointingHand => LoadCursorW(null_mut(), IDC_ARROW), Cursor::OpenHand => LoadCursorW(null_mut(), IDC_HAND), ...
if_condition
[ { "content": "fn get_window_data(hwnd: HWND) -> Option<*mut WindowData> {\n\n let data = unsafe { GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut WindowData };\n\n if data == std::ptr::null_mut() {\n\n None\n\n } else {\n\n Some(data)\n\n }\n\n}\n", "file_path": "kapp_platforms/src/...
Rust
fix41/src/standard_message_header.rs
nappa85/serde_fix
1f11fc5484e6f7fd516c430a61241fb7070e7d4c
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)] pub struct StandardMessageHeader<const T: char> { #[serde(rename = "8")] #[serde(default)] pub begin_string: fix_common::FixVersion<1>, #[serde(deserialize_with = "fix_common::workarounds::from_str")] #[s...
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)] pub struct StandardMessageHeader<const T: char> { #[serde(rename = "8")] #[serde(default)] pub begin_string: fix_common::FixVersion<1>, #[serde(deserialize_with = "fix_common::workarounds::from_str")] #[s...
} #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum PossDupFlag { #[serde(rename = "Y")] PossibleDuplicate, #[serde(rename = "N")] OriginalTransmission, } impl Default for PossDupFlag { fn default() -> Self { PossDupFlag::PossibleDuplicate } } #[derive(Serialize, Deserialize, Clo...
8' => MsgType::ExecutionReport, '9' => MsgType::OrderCancelReject, 'A' => MsgType::Logon, 'B' => MsgType::News, 'C' => MsgType::Email, 'D' => MsgType::NewOrderSingle, 'E' => MsgType::NewOrderList, 'F' => MsgType::OrderCancelRequest, ...
function_block-function_prefix_line
[ { "content": "/// Serializes a value into a FiX `String` buffer.\n\n///\n\n/// ```\n\n/// let meal = &[\n\n/// (\"bread\", \"baguette\"),\n\n/// (\"cheese\", \"comté\"),\n\n/// (\"meat\", \"ham\"),\n\n/// (\"fat\", \"butter\"),\n\n/// ];\n\n///\n\n/// assert_eq!(\n\n/// serde_fix::to_string(...
Rust
alap_gen/src/attributes.rs
pwil3058/rs_lalr1_parsers
1cd7a8a75450f2848cbcf8048c0e92b167c3e4bb
use lexan; #[cfg(not(feature = "bootstrap"))] use crate::alap_gen::AATerminal; #[cfg(feature = "bootstrap")] use crate::bootstrap::AATerminal; use crate::production::ProductionTail; use crate::symbol::non_terminal::NonTerminal; use crate::symbol::tag::TagOrToken; use crate::symbol::{Associativity, Symbol}; use std::...
use lexan; #[cfg(not(feature = "bootstrap"))] use crate::alap_gen::AATerminal; #[cfg(feature = "bootstrap")] use crate::bootstrap::AATerminal; use crate::production::ProductionTail; use crate::symbol::non_terminal::NonTerminal; use crate::symbol::tag::TagOrToken; use crate::symbol::{Associativity, Symbol}; use std::...
h self { AttributeData::SymbolList(list) => list, _ => panic!("{:?}: Wrong attribute variant.", self), } } pub fn symbol_list_mut(&mut self) -> &mut Vec<Symbol> { match self { AttributeData::SymbolList(list) => list, _ => panic!("{:?}: Wrong attri...
e)] pub enum AttributeData { Token(lexan::Token<AATerminal>), SyntaxError(lexan::Token<AATerminal>, BTreeSet<AATerminal>), LexicalError(lexan::Error<AATerminal>, BTreeSet<AATerminal>), Number(u32), Symbol(Symbol), SymbolList(Vec<Symbol>), LeftHandSide(NonTerminal), TagOrToken(TagOrToken)...
random
[ { "content": "fn rhs_associated_precedence(symbols: &[Symbol]) -> Option<(Associativity, u16)> {\n\n for symbol in symbols.iter() {\n\n match symbol {\n\n Symbol::Terminal(token) => {\n\n return Some(token.associativity_and_precedence());\n\n }\n\n _ => ...
Rust
src/main.rs
romanz/trezor-sq
77b426a0ac54b348556fb0ed6baa2d493e8e693c
use std::ffi::OsString; use std::io; use std::path::Path; extern crate clap; extern crate fern; extern crate sequoia_openpgp as openpgp; extern crate subprocess; extern crate trezor; #[macro_use] extern crate log; use openpgp::armor; use openpgp::constants::{HashAlgorithm, PublicKeyAlgorithm}; use openpgp::crypto::...
use std::ffi::OsString; use std::io; use std::path::Path; extern crate clap; extern crate fern; extern crate sequoia_openpgp as openpgp; extern crate subprocess; extern crate trezor; #[macro_use] extern crate log; use openpgp::armor; use openpgp::constants::{HashAlgorithm, PublicKeyAlgorithm}; use openpgp::crypto::...
} fn main() { let matches = clap::App::new("OpenPGP git wrapper for TREZOR") .arg( clap::Arg::with_name("userid") .short("u") .value_name("USERID") .help("User ID for signature") .takes_value(true), ) .arg( ...
fn sign( &mut self, hash_algo: HashAlgorithm, digest: &[u8], ) -> openpgp::Result<mpis::Signature> { match hash_algo { HashAlgorithm::SHA256 | HashAlgorithm::SHA512 => (), _ => return Err(openpgp::Error::UnsupportedHashAlgorithm(hash_algo).into()), } ...
function_block-full_function
[]
Rust
src/crypto.rs
SerhoLiu/eakio
aa7366878294a2525f8c0d32dc0079c1e8c605ee
use std::fmt; use std::io; use std::result; use ring::{aead, digest, hkdf, hmac}; use ring::rand::{SecureRandom, SystemRandom}; static CIPHER: &'static aead::Algorithm = &aead::AES_256_GCM; static DIGEST: &'static digest::Algorithm = &digest::SHA256; pub type Result<T> = result::Result<T, Error>; #[derive(Clone, Co...
use std::fmt; use std::io; use std::result; use ring::{aead, digest, hkdf, hmac}; use ring::rand::{SecureRandom, SystemRandom}; static CIPHER: &'static aead::Algorithm = &aead::AES_256_GCM; static DIGEST: &'static digest::Algorithm = &digest::SHA256; pub type Result<T> = result::Result<T, Error>; #[derive(Clone, Co...
}
8]; let plain_len2: usize = 37; crypto.encrypt(&mut buf1[..], plain_len1).unwrap(); let out_len2 = crypto.encrypt(&mut buf2[..], plain_len2).unwrap(); let err = crypto.decrypt(&mut buf2[..out_len2]).unwrap_err(); assert_eq!(err, Error::Open); let mut crypto1 = Crypto::...
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn io_error(desc: &str) -> io::Error {\n\n io::Error::new(io::ErrorKind::Other, desc)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use std::env;\n\n\n\n #[test]\n\n fn test_expand_tilde_path() {\n\n let old_home = env::var(\"HOME\").ok();\n\n env::set_var(\...
Rust
artichoke-backend/src/extn/core/math/mruby.rs
Talljoe/artichoke
36ed5eba078a9fbf3cb4d5c8f7407d0a773d2d6e
use crate::extn::core::math; use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { if interp.is_module_defined::<math::Math>() { return Ok(()); } let spec = module::Spec::new(interp, "Math", None)?; module::Builder::for_spec(interp, &spec) .add_modul...
use crate::extn::core::math; use crate::extn::prelude::*; pub fn init(interp: &mut Artichoke) -> InitializeResult<()> { if interp.is_module_defined::<math::Math>() { return Ok(()); } let spec = module::Spec::new(interp, "Math", None)?; module::Builder::for_spec(interp, &spec) .add_modul...
unsafe extern "C" fn artichoke_math_cosh( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let value = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let value = Value::from(value); let result = mat...
unsafe extern "C" fn artichoke_math_cos( mrb: *mut sys::mrb_state, _slf: sys::mrb_value, ) -> sys::mrb_value { let value = mrb_get_args!(mrb, required = 1); let mut interp = unwrap_interpreter!(mrb); let mut guard = Guard::new(&mut interp); let value = Value::from(value); let result = math::...
function_block-full_function
[ { "content": "pub fn post_match(interp: &mut Artichoke, mut value: Value) -> Result<Value, Exception> {\n\n let data = unsafe { MatchData::unbox_from_value(&mut value, interp)? };\n\n let post = data.post();\n\n Ok(interp.convert_mut(post))\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core...
Rust
lumol-sim/src/output/custom.rs
Luthaf/lumol
3ef0809b421a574c3604e611372ef6644c251184
use std::error; use std::fmt; use std::fs::File; use std::io::{self, BufWriter}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use caldyn::{Context, Expr}; use caldyn::Error as CaldynError; use log::error; use log_once::{warn_once, error_once}; use super::Output; use lumol_core::{units, System}; #[deri...
use std::error; use std::fmt; use std::fs::File; use std::io::{self, BufWriter}; use std::io::prelude::*; use std::path::{Path, PathBuf}; use caldyn::{Context, Expr}; use caldyn::Error as CaldynError; use log::error; use log_once::{warn_once, error_once}; use super::Output; use lumol_core::{units, System}; #[deri...
} } impl Output for CustomOutput { fn setup(&mut self, _: &System) { writeln_or_log!(self, "# Custom output"); writeln_or_log!(self, "# {}", self.template); } fn write(&mut self, system: &System) { if let Ok(formatted) = self.args.format(system) { writeln_or_log!(s...
Ok(CustomOutput { file: BufWriter::new(File::create(filename.as_ref())?), path: filename.as_ref().to_owned(), template: template.into(), args: FormatArgs::new(template)?, })
call_expression
[ { "content": "/// Scale all velocities in the `System` such that the `system` temperature\n\n/// is `temperature`.\n\npub fn scale(system: &mut System, temperature: f64) {\n\n let instant_temperature = system.temperature();\n\n let factor = f64::sqrt(temperature / instant_temperature);\n\n for velocity...
Rust
import/src/location/record.rs
pixunil/tiny-transport
7aee05ba0303e005768e44cabd995b6413c4ce85
use std::collections::HashMap; use std::rc::Rc; use serde_derive::Deserialize; use super::{Location, LocationId, LocationImportError, LocationKind}; use crate::coord::project; #[derive(Debug, PartialEq, Deserialize)] pub(super) struct LocationRecord { stop_id: LocationId, #[serde(rename = "location_type")] ...
use std::collections::HashMap; use std::rc::Rc; use serde_derive::Deserialize; use super::{Location, LocationId, LocationImportError, LocationKind}; use crate::coord::project; #[derive(Debug, PartialEq, Deserialize)] pub(super) struct LocationRecord { stop_id: LocationId, #[serde(rename = "location_type")] ...
Ok(()) } } impl Into<Location> for LocationRecord { fn into(self) -> Location { let position = project(self.stop_lat, self.stop_lon); Location::new(self.stop_id, self.stop_name, position) } } #[cfg(test)] mod tests { use super::*; use crate::fixtures::locations; use te...
if let Err(record) = self.try_import(locations) { match record.location_kind { LocationKind::Station => { return Err(LocationImportError::StationHasParent(record)); } LocationKind::Stop | LocationKind::Entrance | LocationKind::GenericNode =...
if_condition
[ { "content": "pub fn project_back(position: Point) -> (f64, f64) {\n\n let utm = Utm::new(position.x, position.y, true, 33, 'U', false);\n\n let coord = Coord::from(utm);\n\n (coord.lat, coord.lon)\n\n}\n\n\n", "file_path": "import/src/coord.rs", "rank": 0, "score": 91804.71011538121 }, ...
Rust
idp2p-client/did/microledger.rs
idp2p/idp2p
c5dec982dd03d4c7c0ea6af605042df21f62906f
use super::{ eventlog::{EventLog, EventLogChange, EventLogPayload} }; use crate::IdentityError; use idp2p_common::{ anyhow::Result, chrono::prelude::*, encode, encode_vec, generate_json_cid, hash, IdKeyDigest, IDP2P_ED25519, Idp2pCodec, }; use serde::{Deserialize, Serialize}; use std::collections::HashMap...
use super::{ eventlog::{EventLog, EventLogChange, EventLogPayload} }; use crate::IdentityError; use idp2p_common::{ anyhow::Result, chrono::prelude::*, encode, encode_vec, generate_json_cid, hash, IdKeyDigest, IDP2P_ED25519, Idp2pCodec, }; use serde::{Deserialize, Serialize}; use std::collections::HashMap...
) -> (MicroLedger, idp2p_common::secret::EdSecret) { let secret_str = "bd6yg2qeifnixj4x3z2fclp5wd3i6ysjlfkxewqqt2thie6lfnkma"; let secret = idp2p_common::secret::EdSecret::from_str(secret_str).unwrap(); let d = secret.to_publickey_digest().unwrap(); let ledger = MicroLedger::new(&d, &d);...
), change); let proof = secret.sign(&payload); ledger.save_event(payload, &proof); let change = vec![set_assertion]; let payload = ledger.create_event(&signer, &signer, change); let proof = secret.sign(&payload); ledger.save_event(payload, &proof); let result = le...
random
[ { "content": "pub fn encode_bytes(value: &[u8]) -> Result<String> {\n\n let mb64 = multibase::encode(Base::Base64Url, value);\n\n Ok(mb64[1..].to_owned())\n\n}\n\n\n", "file_path": "idp2p-common/src/base64url.rs", "rank": 0, "score": 310203.4537153712 }, { "content": "pub fn decode_str...
Rust
src/demo.rs
Tri-stone/cosmwasm
4c3f22abdc4ec6e957abe15ac58e2eefc2751fe8
#![allow(dead_code)] use crate::traits::{ReadonlyStorage, Storage}; fn len(prefix: &[u8]) -> [u8; 2] { if prefix.len() > 0xFFFF { panic!("only supports namespaces up to length 0xFFFF") } let length_bytes = (prefix.len() as u64).to_be_bytes(); [length_bytes[6], length_bytes[7]] } fn key_pref...
#![allow(dead_code)] use crate::traits::{ReadonlyStorage, Storage}; fn len(prefix: &[u8]) -> [u8; 2] { if prefix.len() > 0xFFFF { panic!("only supports namespaces up to length 0xFFFF") } let length_bytes = (prefix.len() as u64).to_be_bytes(); [length_bytes[6], length_bytes[7]] } fn key_pref...
#[test] fn multi_level() { let mut storage = MockStorage::new(); let mut foo = PrefixedStorage::new(b"foo", &mut storage); let mut bar = PrefixedStorage::new(b"bar", &mut foo); bar.set(b"baz", b"winner"); let loader = ReadonlyPrefixedStorage::multile...
fn prefix_safe() { let mut storage = MockStorage::new(); let mut foo = PrefixedStorage::new(b"foo", &mut storage); foo.set(b"bar", b"gotcha"); assert_eq!(Some(b"gotcha".to_vec()), foo.get(b"bar")); let rfoo = ReadonlyPrefixedStorage::new(b"foo", &storage); ...
function_block-full_function
[ { "content": "pub fn do_write<T: Storage>(ctx: &mut Ctx, key: u32, value: u32) {\n\n let key = read_memory(ctx, key);\n\n let value = read_memory(ctx, value);\n\n with_storage_from_context(ctx, |store: &mut T| store.set(&key, &value));\n\n}\n\n\n", "file_path": "lib/vm/src/context.rs", "rank": ...
Rust
bee-network/bee-autopeering/src/peer/mod.rs
TeeVeeEss/bee
b98bd114e763a0cebe47ac4b8055873e8009e8e6
pub(crate) mod lists; pub mod peer_id; pub mod stores; use std::{ fmt, net::{IpAddr, SocketAddr}, }; use bytes::BytesMut; use crypto::signatures::ed25519::PublicKey; use libp2p_core::{multiaddr::Protocol, Multiaddr}; use prost::{DecodeError, EncodeError, Message}; use serde::{ de::{SeqAccess, Visitor},...
pub(crate) mod lists; pub mod peer_id; pub mod stores; use std::{ fmt, net::{IpAddr, SocketAddr}, }; use bytes::BytesMut; use crypto::signatures::ed25519::PublicKey; use libp2p_core::{multiaddr::Protocol, Multiaddr}; use prost::{DecodeError, EncodeError, Message}; use serde::{ de::{SeqAccess, Visitor},...
ip, services, } = peer; let ip_address: IpAddr = ip.parse().map_err(|_| Error::ParseIpAddr)?; let public_key = PublicKey::try_from_bytes(public_key.try_into().map_err(|_| Error::PublicKeyBytes)?) .map_err(|_| Error::PublicKeyBytes)?; let peer_id = PeerId::from...
pub fn service_socketaddr(&self, service_name: impl AsRef<str>) -> Option<SocketAddr> { self.services .get(service_name) .map(|endpoint| SocketAddr::new(self.ip_address, endpoint.port())) } pub fn service_multiaddr(&self, service_name: impl AsRef<str>) -> O...
random
[ { "content": "pub fn get_network_config_with_port(port: u16) -> NetworkConfig {\n\n let mut config = NetworkConfig::default();\n\n config.replace_port(Protocol::Tcp(port)).unwrap();\n\n config\n\n}\n\n\n", "file_path": "bee-network/bee-gossip/src/tests/common/network_config.rs", "rank": 0, ...
Rust
src/body.rs
ocornoc/gravity
1263ddc73c29a70a0fb254d41c2cb28dbc3eae63
use bevy::prelude::*; use ultraviolet::DVec3; pub struct TransformScale(pub f64); impl Default for TransformScale { fn default() -> Self { TransformScale(1e-8) } } #[derive(Clone, Copy, PartialEq, Debug, Default, PartialOrd)] pub struct Mass(pub f64); #[derive(Clone, Copy, PartialEq, Debug, Default)...
use bevy::prelude::*; use ultraviolet::DVec3; pub struct TransformScale(pub f64); impl Default for TransformScale { fn default() -> Self { TransformScale(1e-8) } } #[derive(Clone, Copy, PartialEq, Debug, Default, PartialOrd)] pub struct Mass(pub f64); #[derive(Clone, Copy, PartialEq, Debug, Default)...
, paused, } } #[allow(dead_code)] pub const fn real_time(paused: bool) -> Self { Timestep { current: Self::REALTIME, substeps: 5, current_frame_time: 0.00001, paused, } } } const SPEED_OF_LIGHT: f64 = 299792458.0; con...
s: usize) -> Self { assert_ne!(substeps, 0, "must be a positive amount of substeps"); Timestep { current: rate, substeps, current_frame_time: 0.00001
function_block-random_span
[ { "content": "/// Get a new unique color, specified by RGB components.\n\npub fn new_color() -> [f32; 3] {\n\n COLORS[COUNTER.fetch_add(1, Ordering::Relaxed) % COLORS.len()]\n\n}\n", "file_path": "src/scene/newcolor.rs", "rank": 1, "score": 51750.93467058338 }, { "content": "fn unpause_af...
Rust
src/ir/operator.rs
dan-zheng/telamon
de463284fdcea70ce29cf43a9c62f3aa2da14276
use self::Operator::*; use crate::ir::{self, AccessPattern, LoweringMap, Operand, Type}; use fxhash::FxHashSet; use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::{self, fmt}; #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)] #[repr(C)] pub enum Rounding { Exact, ...
use self::Operator::*; use crate::ir::{self, AccessPattern, LoweringMap, Operand, Type}; use fxhash::FxHashSet; use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::{self, fmt}; #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)] #[repr(C)] pub enum Rounding { Exact, ...
pub fn t(self, operand_type: ir::Type) -> ir::Type { match self { BinOp::Lt | BinOp::Leq | BinOp::Equals => ir::Type::I(1), _ => operand_type, } } fn requires_rounding(self) -> bool { match self { BinOp::Lt | BinOp::Leq | BinOp::Equals...
nOp::Sub => "sub", BinOp::Div => "div", BinOp::And => "and", BinOp::Or => "or", BinOp::Lt => "lt", BinOp::Leq => "leq", BinOp::Equals => "equals", BinOp::Max => "max", } }
function_block-function_prefixed
[ { "content": "#[allow(unused_mut)]\n\npub fn set_{{name}}(&mut self{{>args_decl}}, mut value: {{>value_type.name value_type}}) {\n\n {{#if is_symmetric~}}\n\n if {{arguments.[0].[0]}} > {{arguments.[1].[0]}} {\n\n std::mem::swap(&mut {{arguments.[0].[0]}}, &mut {{arguments.[1].[0]}});\n\n ...
Rust
src/cluster/session.rs
a1ph/cdrs-tokio
99a536e705ff1fd95be36d57d0832ddc21d7478f
use async_trait::async_trait; use bb8; use fnv::FnvHashMap; use std::iter::Iterator; use std::sync::Arc; use tokio::{io::AsyncWriteExt, sync::Mutex}; #[cfg(feature = "unstable-dynamic-cluster")] use crate::cluster::NodeTcpConfig; #[cfg(feature = "rust-tls")] use crate::cluster::{new_rustls_pool, ClusterRustlsConfig, R...
use async_trait::async_trait; use bb8; use fnv::FnvHashMap; use std::iter::Iterator; use std::sync::Arc; use tokio::{io::AsyncWriteExt, sync::Mutex}; #[cfg(feature = "unstable-dynamic-cluster")] use crate::cluster::NodeTcpConfig; #[cfg(feature = "rust-tls")] use crate::cluster::{new_rustls_pool, ClusterRustlsConfig, R...
} #[cfg(all(feature = "rust-tls", feature = "unstable-dynamic-cluster"))] async fn connect_tls_dynamic<A, LB>( node_configs: &ClusterRustlsConfig<A>, mut load_balancing: LB, compression: Compression, event_src: NodeTcpConfig<'_, A>, ) -> error::Result<Session<LB>> where A: Authenticator + ...
Ok(Session { load_balancing: Mutex::new(load_balancing), event_stream: None, responses: Mutex::new(FnvHashMap::default()), compression, })
call_expression
[ { "content": "#[async_trait]\n\npub trait CDRSTransport: Sized + AsyncRead + AsyncWriteExt + Send + Sync {\n\n /// Creates a new independently owned handle to the underlying socket.\n\n ///\n\n /// The returned TcpStream is a reference to the same stream that this object references.\n\n /// Both han...
Rust
src/utils/v6/ipv6_cidr_separator.rs
sanderv32/cidr-utils
c0f7607e086d7e3ea25b429a55041a86fe624ddd
extern crate num_traits; use std::cmp::Ordering; use crate::cidr::Ipv6Cidr; use crate::num_bigint::BigUint; use crate::utils::Ipv6CidrCombiner; use num_traits::{One, ToPrimitive}; #[derive(Debug)] pub struct Ipv6CidrSeparator; impl Ipv6CidrSeparator { pub fn divide_by(cidr: &Ipv6Cidr, n: usize) -> Option<...
extern crate num_traits; use std::cmp::Ordering; use crate::cidr::Ipv6Cidr; use crate::num_bigint::BigUint; use crate::utils::Ipv6CidrCombiner; use num_traits::{One, ToPrimitive}; #[derive(Debug)] pub struct Ipv6CidrSeparator; impl Ipv6CidrSeparator { pub fn divide_by(cidr: &Ipv6Cidr, n: usize) -> Option<...
usize::max_value()); if d <= usize_max_big_int { for ip in iter.step_by(d.to_usize().unwrap()) { output.push(Ipv6Cidr::from_prefix_and_bits(ip, bits).unwrap()); } } else { let nth = d - BigUint::one(); if let Some(ip) = iter.next() { ...
pv6CidrCombiner::with_capacity(1); combiner.push(Ipv6Cidr::from_prefix_and_bits(ip, bits).unwrap()); output.push(combiner); while let Some(ip) = iter.nth_big_uint(nth.clone()) { let mut combiner = Ipv6CidrCombiner::with_capacity(1); ...
random
[ { "content": "#[test]\n\nfn simple_test() {\n\n let mut combiner = IpCidrCombiner::new();\n\n\n\n combiner.push(IpCidr::from_str(\"192.168.1.100\").unwrap());\n\n combiner.push(IpCidr::from_str(\"192.168.1.101\").unwrap());\n\n combiner.push(IpCidr::from_str(\"192.168.1.102\").unwrap());\n\n comb...
Rust
crates/bench-api/src/lib.rs
dheaton-arm/wasmtime
86611d3bbc92b781ed136dcda7cdba9ec2c1cbee
mod unsafe_send_sync; use crate::unsafe_send_sync::UnsafeSendSync; use anyhow::{anyhow, Context, Result}; use std::os::raw::{c_int, c_void}; use std::slice; use std::{env, path::PathBuf}; use wasmtime::{Config, Engine, Instance, Linker, Module, Store}; use wasmtime_wasi::{sync::WasiCtxBuilder, WasiCtx}; pub type Ex...
mod unsafe_send_sync; use crate::unsafe_send_sync::UnsafeSendSync; use anyhow::{anyhow, Context, Result}; use std::os::raw::{c_int, c_void}; use std::slice; use std::{env, path::PathBuf}; use wasmtime::{Config, Engine, Instance, Linker, Module, Store}; use wasmtime_wasi::{sync::WasiCtxBuilder, WasiCtx}; pub type Ex...
antiate(&mut self) -> Result<()> { let module = self .module .as_ref() .expect("compile the module before instantiating it"); let host = HostState { wasi: (self.make_wasi_cx)().context("failed to create a WASI context")?, #[cfg(feature = "wasi...
<()> { assert!( self.module.is_none(), "create a new engine to repeat compilation" ); (self.compilation_start)(self.compilation_timer); let module = Module::from_binary(self.linker.engine(), bytes)?; (self.compilation_end)(self.compilation_timer); ...
random
[ { "content": "pub fn create_global(store: &mut StoreOpaque, gt: &GlobalType, val: Val) -> Result<InstanceId> {\n\n let mut module = Module::new();\n\n let mut func_imports = Vec::new();\n\n let mut externref_init = None;\n\n let mut shared_signature_id = None;\n\n\n\n let global = Global {\n\n ...
Rust
src/stream/server/ts.rs
burjee/mock-yo-stream
6161822cccb477c4f33217788078463d7cad9c7c
use std::fs::File; use mpeg2ts; use mpeg2ts::{ ts::{TsPacket, TsHeader, TsPayload, Pid, ContinuityCounter}, pes::PesHeader, }; pub struct TransportStream { video_continuity_counter: ContinuityCounter, audio_continuity_counter: ContinuityCounter, packets: Vec<TsPacket>, } impl TransportStream { ...
use std::fs::File; use mpeg2ts; use mpeg2ts::{ ts::{TsPacket, TsHeader, TsPayload, Pid, ContinuityCounter}, pes::PesHeader, }; pub struct TransportStream { video_continuity_counter: ContinuityCounter, audio_continuity_counter: ContinuityCounter, packets: Vec<TsPacket>, } impl TransportStream { ...
e::H264, elementary_pid: Pid::new(TransportStream::VIDEO_PID).unwrap(), descriptors: vec![], }, EsInfo { stream_type: StreamType::AdtsAac, elementary_pid: Pid::new(TransportStream::AUD...
:create(filename).unwrap(); let packets: Vec<_> = self.packets.drain(..).collect(); let mut writer = TsPacketWriter::new(file); writer.write_ts_packet(&TransportStream::default_pat()).unwrap(); writer.write_ts_packet(&TransportStream::default_pmt()).unwrap(); for packet in &pac...
random
[ { "content": "fn get_data_type(data_type: DataType) -> u8 {\n\n match data_type {\n\n DataType::Video => 0x09,\n\n DataType::Audio => 0x08,\n\n }\n\n}\n\n\n\n// --------------------\n\n// Flv File:\n\n// --------------------\n\n// Flv Header\n\n// Previous Tag Size 0\n\n// Tag 1\n\n// Previo...
Rust
src/options/pane_options.rs
AntonGepting/tmux-interface
7a1dea0ad658e2cb8743311480d207ad1d196a48
use crate::{Error, Switch}; use crate::{SetOption, ShowOptions}; use std::fmt; use std::str::FromStr; pub const ALLOW_RENAME: usize = 1 << 0; pub const ALTERNATE_SCREEN: usize = 1 << 1; pub const REMAIN_ON_EXIT: usize = 1 << 2; pub const WINDOW_ACTIVE_STYLE: usize = 1 << 3; pub const WINDOW_STYLE: usize = 1 << 4; pub...
use crate::{Error, Switch}; use crate::{SetOption, ShowOptions}; use std::fmt; use std::str::FromStr; pub const ALLOW_RENAME: usize = 1 << 0; pub const ALTERNATE_SCREEN: usize = 1 << 1; pub const REMAIN_ON_EXIT: usize = 1 << 2; pub const WINDOW_ACTIVE_STYLE: usize = 1 << 3; pub const WINDOW_STYLE: usize = 1 << 4; pub...
pub fn set(&self, bitflags: usize) -> Result<(), Error> { for selected_option in PANE_OPTIONS.iter().filter(|t| bitflags & t.3 == t.3) { if let Some(selected_value) = selected_option.2(&self) { SetOption::new() .pane() .option(s...
map(|t| format!("{}", t.0)) .collect::<Vec<String>>() .join(" "); let s = ShowOptions::new() .pane() .option(&selected_option) .output()? .to_string(); s.parse() }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn from_str() {\n\n use crate::Version;\n\n\n\n let examples = &[\n\n \"tmux next-3.2\",\n\n \"tmux 3.1b\",\n\n \"tmux 3.1a\",\n\n \"tmux 3.1\",\n\n \"tmux 3.0a\",\n\n \"tmux 3.0\",\n\n \"tmux 2.9a\",\n\n \"tmux 2.9\",\n\n ...
Rust
crates/fluvio-storage/src/range_map.rs
bohlmannc/fluvio
b5a3105600b6886c55d76707d369fa59f5d9673b
use std::cmp::max; use std::cmp::min; use std::collections::BTreeMap; use std::ops::Bound::Included; use std::ffi::OsStr; use tracing::debug; use tracing::trace; use tracing::error; use dataplane::Offset; use crate::segment::ReadSegment; use crate::StorageError; use crate::config::ConfigOption; use crate::util::log_...
use std::cmp::max; use std::cmp::min; use std::collections::BTreeMap; use std::ops::Bound::Included; use std::ffi::OsStr; use tracing::debug; use tracing::trace; use tracing::error; use dataplane::Offset; use crate::segment::ReadSegment; use crate::StorageError; use crate::config::ConfigOption; use crate::util::log_...
} #[cfg(test)] mod tests { use std::env::temp_dir; use std::path::PathBuf; use flv_util::fixture::ensure_new_dir; use dataplane::fixture::create_batch; use dataplane::Offset; use crate::StorageError; use crate::segment::MutableSegment; use crate::segment::ReadSegment; use crate:...
e if offset == self.min_offset { (&self.segments) .range((Included(offset), Included(offset))) .next_back() } else if offset >= self.max_offset { None } else { let range = ( Included(offset - self.max_offset + self.min_o...
function_block-function_prefixed
[ { "content": "pub fn log_path_get_offset<P>(path: P) -> Result<Offset, OffsetError>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let log_path = path.as_ref();\n\n\n\n match log_path.file_stem() {\n\n None => Err(OffsetError::InvalidPath),\n\n Some(file_name) => {\n\n if file_name.len(...
Rust
neutopia/src/lib.rs
konkers/neutopia
770dbbc3dd6a61d418f38683f43ccfb729ea1039
use std::collections::HashMap; use std::io::{prelude::*, Cursor, SeekFrom}; use failure::{format_err, Error}; pub mod interval; pub mod rom; pub mod rommap; pub mod util; pub mod verify; pub use rom::NeutopiaRom; pub use verify::{verify, RomInfo}; #[derive(Clone, Debug)] pub struct Room { pub warps: Vec<u8>, ...
use std::collections::HashMap; use std::io::{prelude::*, Cursor, SeekFrom}; use failure::{format_err, Error}; pub mod interval; pub mod rom; pub mod rommap; pub mod util; pub mod verify; pub use rom::NeutopiaRom; pub use verify::{verify, RomInfo}; #[derive(Clone, Debug)] pub struct Room { pub warps: Vec<u8>, ...
fn write_area(&self, area_idx: usize, rom_writer: &mut Cursor<Vec<u8>>) -> Result<u32, Error> { let area = &self.areas[area_idx]; let cur_offset = rom_writer.position(); let mut room_ptrs = Cursor::new(Vec::new()); let room_ptrs_offset = cur_offset; let room_data_offset = ...
pub fn update_chests(&mut self, chests: &[Chest]) -> Result<(), Error> { for chest in chests { let id = self.get_table_id_for_chest(chest)?; let entry = self.areas[chest.area as usize] .chest_table .get_mut(id as usize) .ok_or_else(|| forma...
function_block-full_function
[ { "content": "pub fn verify(data: &[u8]) -> Result<RomInfo, Error> {\n\n let expected_size = 384 * 1024;\n\n let header_size = 0x200;\n\n\n\n let (headered, buffer) = if data.len() == expected_size {\n\n (false, &data as &[u8])\n\n } else if data.len() == expected_size + header_size {\n\n ...
Rust
vm/actor/src/util/balance_table.rs
zatoichi-labs/forest
4422cddcf42fab20912d1ad1f92e2b997f1b5bda
use crate::{BytesKey, HAMT_BIT_WIDTH}; use address::Address; use cid::Cid; use ipld_blockstore::BlockStore; use ipld_hamt::{Error, Hamt}; use num_bigint::biguint_ser::BigUintDe; use num_traits::CheckedSub; use vm::TokenAmount; pub struct BalanceTable<'a, BS>(Hamt<'a, BytesKey, BS>); impl<'a, BS> BalanceTable<'a, BS>...
use crate::{BytesKey, HAMT_BIT_WIDTH}; use address::Address; use cid::Cid; use ipld_blockstore::BlockStore; use ipld_hamt::{Error, Hamt}; use num_bigint::biguint_ser::BigUintDe; use num_traits::CheckedSub; use vm::TokenAmount; pub struct BalanceTable<'a, BS>(Hamt<'a, BytesKey, BS>); impl<'a, BS> BalanceTable<'a, BS>...
pub fn remove(&mut self, key: &Address) -> Result<TokenAmount, String> { let prev = self.get(key)?; self.0.delete(&key.to_bytes())?; Ok(prev) } pub fn total(&self) -> Result<TokenAmount, String> { let mut total = TokenAmount::default(); ...
b_amt != req { return Err(format!( "Couldn't subtract value from address {} (req: {}, available: {})", key, req, sub_amt )); } Ok(()) }
function_block-function_prefixed
[ { "content": "fn mutate_balance_table<BS, F>(store: &BS, c: &mut Cid, f: F) -> Result<(), String>\n\nwhere\n\n F: FnOnce(&mut BalanceTable<BS>) -> Result<(), String>,\n\n BS: BlockStore,\n\n{\n\n let mut t = BalanceTable::from_root(store, &c)?;\n\n\n\n f(&mut t)?;\n\n\n\n *c = t.root()?;\n\n O...
Rust
src/client-rs/src/profile/profile_file.rs
vinimin/fluvio
142c050a2f1aaa83aeda19705fedd670fffaf1a1
use std::env; use std::fs::read_to_string; use std::io::Error as IoError; use std::io::ErrorKind; use std::path::{Path, PathBuf}; use dirs::home_dir; use serde::Deserialize; use types::defaults::{CLI_CONFIG_PATH, CLI_DEFAULT_PROFILE, CLI_PROFILES_DIR}; use types::defaults::{CONFIG_FILE_EXTENTION, FLV_FLUVIO_HOME}; ...
use std::env; use std::fs::read_to_string; use std::io::Error as IoError; use std::io::ErrorKind; use std::path::{Path, PathBuf}; use dirs::home_dir; use serde::Deserialize; use types::defaults::{CLI_CONFIG_PATH, CLI_DEFAULT_PROFILE, CLI_PROFILES_DIR}; use types::defaults::{CONFIG_FILE_EXTENTION, FLV_FLUVIO_HOME}; ...
expected_file_path.push(home_dir().unwrap()); expected_file_path.push(".fluvio/profiles/custom.toml"); assert_eq!(file_path.unwrap(), expected_file_path); } }
> { if let Some(mut home_dir) = home_dir() { home_dir.push(CLI_CONFIG_PATH); home_dir } else { return Err(IoError::new( ErrorKind::InvalidInput, "can't get home directory", )); ...
random
[ { "content": "// converts a host/port to SocketAddress\n\npub fn host_port_to_socket_addr(host: &str, port: u16) -> Result<SocketAddr, IoError> {\n\n let addr_string = format!(\"{}:{}\", host, port);\n\n string_to_socket_addr(&addr_string)\n\n}\n\n\n", "file_path": "src/types/src/socket_helpers.rs", ...
Rust
src/lib/redis.rs
PavelZX/rust-actix-rest-api-boilerplate
3852a2dd8b941dfe18e5f990fedb72d2665c87fe
use mobc::Pool; use mobc::async_trait; use mobc::Manager; use redis::aio::Connection; use redis::Client; use std::time::Duration; use super::error; pub struct RedisConnectionManager { client: Client, } impl RedisConnectionManager { pub fn new(c: Client) -> Self { Self { client: c } } } #[async_tr...
use mobc::Pool; use mobc::async_trait; use mobc::Manager; use redis::aio::Connection; use redis::Client; use std::time::Duration; use super::error; pub struct RedisConnectionManager { client: Client, } impl RedisConnectionManager { pub fn new(c: Client) -> Self { Self { client: c } } } #[async_tr...
} pub async fn hset<T: redis::ToRedisArgs>(key: String, item: String, value: T, pool: &mobc::Pool<RedisConnectionManager>, log: &slog::Logger) -> Result<(), error::Error> { let mut con = pool.get().await.unwrap(); let result = redis::cmd("HSET").arg(key).arg(item).arg(value).query_async::<_, i32>(&mut con as...
match result { Ok(v) => Ok(v), Err(e) => { error!(log, "{}", e); Err(error::err500()) } }
if_condition
[ { "content": "pub fn required_str(v: &Option<String>, name: &str) -> Result<String, error::Error> {\n\n not_none(v.as_ref(), name)?;\n\n\n\n let v = v.as_ref().unwrap().to_string();\n\n if v.chars().count() == 0 {\n\n return Err(error::new(400002, &format!(\"{} can not be empty\", name)[..], 422...
Rust
src/osu/versions/no_sliders_no_leniency/mod.rs
RealistikDash/akat-rust-pp
90653f6da82ff981da250a55427dd40aa6ea5b2b
#![cfg(feature = "no_sliders_no_leniency")] use super::super::DifficultyAttributes; mod difficulty_object; mod osu_object; mod skill; mod skill_kind; mod slider_state; use difficulty_object::DifficultyObject; use osu_object::OsuObject; use skill::Skill; use skill_kind::SkillKind; use slider_state::SliderState; us...
#![cfg(feature = "no_sliders_no_leniency")] use super::super::DifficultyAttributes; mod difficulty_object; mod osu_object; mod skill; mod skill_kind; mod slider_state; use difficulty_object::DifficultyObject; use osu_object::OsuObject; use skill::Skill; use skill_kind::SkillKind; use slider_state::SliderState; us...
if map.hit_objects.len() < 2 { return Strains::default(); } let radius = OBJECT_RADIUS * (1.0 - 0.7 * (attributes.cs - 5.0) / 5.0) / 2.0; let mut scaling_factor = NORMALIZED_RADIUS / radius; if radius < 30.0 { let small_circle_bonus = (30.0 - radius).min(5.0) / 50.0; scaling_fa...
function_block-function_prefix_line
[]
Rust
src/instruction.rs
kevinheavey/solders
82171e0d34b913efed9f0eb4e5421bc99d3f000e
use pyo3::{basic::CompareOp, prelude::*, types::PyBytes}; use serde::{Deserialize, Serialize}; use solana_sdk::{ instruction::{ AccountMeta as AccountMetaOriginal, CompiledInstruction as CompiledInstructionOriginal, Instruction as InstructionOriginal, }, pubkey::Pubkey as PubkeyOriginal, }; ...
use pyo3::{basic::CompareOp, prelude::*, types::PyBytes}; use serde::{Deserialize, Serialize}; use solana_sdk::{ instruction::{ AccountMeta as AccountMetaOriginal, CompiledInstruction as CompiledInstructionOriginal, Instruction as InstructionOriginal, }, pubkey::Pubkey as PubkeyOriginal, }; ...
#[getter] pub fn program_id(&self) -> Pubkey { self.0.program_id.into() } #[getter] pub fn data<'a>(&self, py: Python<'a>) -> &'a PyBytes { PyBytes::new(py, &self.0.data) } #[getter] pub fn accounts(&self) -> Vec<AccountMeta> { self.0 ...
tMeta>) -> Self { let underlying_accounts: Vec<AccountMetaOriginal> = accounts.into_iter().map(|x| x.0).collect(); let underlying = InstructionOriginal::new_with_bytes(program_id.into(), data, underlying_accounts); underlying.into() }
function_block-function_prefixed
[ { "content": "#[pyfunction]\n\npub fn transfer_many(from_pubkey: &Pubkey, to_lamports: Vec<(Pubkey, u64)>) -> Vec<Instruction> {\n\n let to_lamports_converted: Vec<(PubkeyOriginal, u64)> = to_lamports\n\n .into_iter()\n\n .map(|x| (PubkeyOriginal::from(x.0), x.1))\n\n .collect();\n\n ...
Rust
alvr/settings-schema-derive/src/lib.rs
SonicZY/ALVR
4beff45eec4af6f0683439948d0e1091ce7130c0
mod higher_order; mod ty; use darling::{ast::Fields, util::Flag, FromDeriveInput, FromField, FromMeta, FromVariant}; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{quote, ToTokens}; use std::string::ToString; use syn::{DeriveInput, Error, Ident, Lit, Type, Visibility}; type TRe...
mod higher_order; mod ty; use darling::{ast::Fields, util::Flag, FromDeriveInput, FromField, FromMeta, FromVariant}; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{quote, ToTokens}; use std::string::ToString; use syn::{DeriveInput, Error, Ident, Lit, Type, Visibility}; type TRe...
fn schema(derive_input: DeriveInput) -> TResult { if !derive_input.generics.params.is_empty() { return error("Generics not supported", &derive_input.generics); } let meta: DeriveInputMeta = FromDeriveInput::from_derive_input(&derive_input).map_err(|e| e.write_errors())?; let gui_type...
darling::ast::Style::Struct => { let default_ty_ts = suffix_ident(&suffix_ident(ident, &variant_ident.to_string()), "Default") .to_token_stream(); let SchemaData { default_fields_ts, schema_code_ts, ...
function_block-function_prefix_line
[ { "content": "fn custom_leaf_type_schema(ty_ident: &Ident, field: &FieldMeta) -> TResult {\n\n forbid_numeric_attrs(field, \"custom\")?;\n\n\n\n Ok(quote!(#ty_ident::schema(default)))\n\n}\n\n\n\n// Generate a default representation type and corresponding schema instantiation code.\n\n// This function cal...
Rust
src/lib.rs
wngr/libp2p-maybe-transport
395f519d8b9040c050c1441c8f97b36856a49fe1
#![allow(clippy::type_complexity)] use std::{fmt, marker::PhantomData, sync::Arc}; use futures::{ channel::mpsc, future::{self, BoxFuture}, stream::{self, BoxStream}, FutureExt, StreamExt, TryFutureExt, TryStreamExt, }; use libp2p::{ core::{either::EitherOutput, transport::ListenerEvent}, Multi...
#![allow(clippy::type_complexity)] use std::{fmt, marker::PhantomData, sync::Arc}; use futures::{ channel::mpsc, future::{self, BoxFuture}, stream::{self, BoxStream}, FutureExt, StreamExt, TryFutureExt, TryStreamExt, }; use libp2p::{ core::{either::EitherOutput, transport::ListenerEvent}, Multi...
; if let Some(ev) = cloned { tx.start_send(ev).unwrap(); } let ev = match ev { ListenerEvent::Upgrade { upgrade, local_addr, rem...
match &ev { ListenerEvent::NewAddress(a) => Some(ListenerEvent::NewAddress(a.clone())), ListenerEvent::AddressExpired(a) => { Some(ListenerEvent::AddressExpired(a.clone())) } ListenerEvent::Error(...
if_condition
[ { "content": "fn maybe_upgrade(r: TcpStream) -> BoxFuture<'static, Result<TcpStream, TcpStream>> {\n\n async move {\n\n let mut buffer = [0; 3];\n\n if r.0.peek(&mut buffer).await.is_ok() && buffer == *b\"GET\" {\n\n println!(\"It's probably HTTP\");\n\n Ok(r)\n\n }...
Rust
src/gfx.rs
1HPorange/maboy
e8dc60b776edc95d71c234d641aceb3ab0ce1bab
use super::hresult_error::*; use super::window::Window; use maboy::MemPixel; use std::marker::PhantomData; use std::mem::MaybeUninit; use std::pin::Pin; use std::ptr; use winapi::shared::dxgi::*; use winapi::shared::dxgiformat::*; use winapi::shared::minwindef::*; use winapi::shared::winerror::*; use winapi::shared::...
use super::hresult_error::*; use super::window::Window; use maboy::MemPixel; use std::marker::PhantomData; use std::mem::MaybeUninit; use std::pin::Pin; use std::ptr; use winapi::shared::dxgi::*; use winapi::shared::dxgiformat::*; use winapi::shared::minwindef::*; use winapi::shared::winerror::*; use winapi::shared::...
ckbuffer_rtv, ) .into_result()?; let backbuffer_rtv = ComPtr::from_raw(backbuffer_rtv); Ok(GfxWindow { device_context: self.dc.clone(), swap_chain, backbuffer, backbuffer_rtv, viewpor...
c = ComPtr::from_raw(dc); let mut dxgi_device = ptr::null_mut(); d.QueryInterface(&IDXGIDevice2::uuidof(), &mut dxgi_device) .into_result()?; let dxgi_device = ComPtr::from_raw(dxgi_device as *mut IDXGIDevice2); let mut dxgi_a...
random
[ { "content": "pub fn rlca(cpu: &mut CPU) {\n\n let old = cpu.reg.get_r8(R8::A);\n\n cpu.reg.set_r8(R8::A, old.rotate_left(1));\n\n\n\n cpu.reg.flags.remove(Flags::Z | Flags::N | Flags::H);\n\n cpu.reg.flags.set(Flags::C, old.bit(7));\n\n}\n\n\n", "file_path": "maboy/src/cpu/execute.rs", "ran...
Rust
2020/src/bin/day19.rs
sebnow/adventofcode
9193b7f9181cd2249fd889c8e6723054f4e5b789
use anyhow::{anyhow, Result}; use std::collections::HashMap; use rayon::str::ParallelString; use rayon::iter::ParallelIterator; #[derive(Clone, PartialEq, Debug)] enum Rule { Char(char), Seq(Vec<i64>), Alt(Vec<i64>, Vec<i64>), } impl std::str::FromStr for Rule { type Err = anyhow::Error; fn from_...
use anyhow::{anyhow, Result}; use std::collections::HashMap; use rayon::str::ParallelString; use rayon::iter::ParallelIterator; #[derive(Clone, PartialEq, Debug)] enum Rule { Char(char), Seq(Vec<i64>), Alt(Vec<i64>, Vec<i64>), } impl std::str::FromStr for Rule { type Err = anyhow::Error; fn from_...
}) .collect::<Result<_>>()?; Ok(RuleEngine::new(rules)) } } fn parse_input<'a>(input: &'a str) -> (RuleEngine, impl ParallelIterator<Item = &'a str> + 'a) { let mut parts = input.split("\n\n"); ( parts.next().unwrap().parse().unwrap(), parts.next().unwrap()...
Ok(( parts.next().ok_or_else(|| anyhow!("missing id"))?.parse()?, parts .next() .ok_or_else(|| anyhow!("missing definition"))? .parse()?, ))
call_expression
[ { "content": "pub fn answer_2(input: &str) -> Result<i64, failure::Error> {\n\n let map = parse_input(input);\n\n traverse(&map).map(|r| r.1)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n #[test]\n\n fn example_1() {\n\n let input = [\n\n \" | \",...
Rust
src/unix.rs
dropbox/rust-subprocess-communicate
f6d5c664d4f4210a60e113f1300230ffa6e8ff4d
#![cfg(unix)] extern crate mio; use std::mem; use mio::*; use std::io; use std::process; use std::cmp; use mio::deprecated::{TryRead, TryWrite}; use mio::deprecated::{PipeReader, PipeWriter}; #[allow(unused_imports)] use std::process::{Command, Stdio, Child}; struct SubprocessClient { stdin: Option<PipeWriter>, ...
#![cfg(unix)] extern crate mio; use std::mem; use mio::*; use std::io; use std::process; use std::cmp; use mio::deprecated::{TryRead, TryWrite}; use mio::deprecated::{PipeReader, PipeWriter}; #[allow(unused_imports)] use std::process::{Command, Stdio, Child}; struct SubprocessClient { stdin: Option<PipeWriter>, ...
fn writable(&mut self, poll: &mut Poll) -> io::Result<()> { if self.has_shutdown { return Ok(()); } let mut ok = true; match self.stdin { None => unreachable!(), Some(ref mut stdin) => match stdin.try_write(&(&self.input)[self.input_offset..]) {...
else { *bound = 0; do_extend = false; if self.stdout.is_none() || self.stdout_bound.unwrap_or(1) == 0 { match self.stdout { Some(ref sub_s...
function_block-function_prefix_line
[ { "content": "#subprocess-communicate\n\n[![crates.io](http://meritbadge.herokuapp.com/subprocess-communicate)](https://crates.io/crates/subprocess-communicate)\n\n[![Build Status](https://travis-ci.org/dropbox/rust-subprocess-communicate.svg?branch=master)](https://travis-ci.org/dropbox/rust-subprocess-communi...
Rust
liblumen_alloc/src/erts/process/alloc.rs
mlwilkerson/lumen
048df6c0840c11496e2d15aa9af2e4a8d07a6e0f
mod heap; mod iter; mod process_heap_alloc; mod semispace; mod stack_alloc; mod stack_primitives; mod term_alloc; mod virtual_alloc; mod virtual_binary_heap; pub use self::heap::{Heap, HeapAlloc}; pub use self::iter::HeapIter; pub use self::process_heap_alloc::ProcessHeapAlloc; pub use self::semispace::{GenerationalHe...
mod heap; mod iter; mod process_heap_alloc; mod semispace; mod stack_alloc; mod stack_primitives; mod term_alloc; mod virtual_alloc; mod virtual_binary_heap; pub use self::heap::{Heap, HeapAlloc}; pub use self::iter::HeapIter; pub use self::process_heap_alloc::ProcessHeapAlloc; pub use s
b unsafe fn realloc( heap: *mut Term, size: usize, new_size: usize, ) -> Result<*mut Term, AllocErr> { PROC_ALLOC.realloc_in_place(heap, size, new_size) } #[inline] pub unsafe fn free(heap: *mut Term, size: usize) { PROC_ALLOC.dealloc(heap, size) } #[inline] pub fn next_heap_size(size: usize) -> u...
elf::semispace::{GenerationalHeap, SemispaceHeap}; pub use self::stack_alloc::StackAlloc; pub use self::stack_primitives::StackPrimitives; pub use self::term_alloc::TermAlloc; pub use self::virtual_alloc::{VirtualAlloc, VirtualAllocator, VirtualHeap}; pub use self::virtual_binary_heap::VirtualBinaryHeap; use core::all...
random
[]
Rust
connectorx-python/src/pandas/types.rs
ritchie46/connector-x
89c61beb1c2d782ca07445124caa1ca3db3608df
use chrono::{DateTime, Utc}; use connectorx::errors::{ConnectorAgentError, Result}; use connectorx::impl_typesystem; use fehler::throws; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum PandasTypeSystem { F64(bool), I64(bool), Bool(bool), Char(bool), Str(bool), BoxS...
use chrono::{DateTime, Utc}; use connectorx::errors::{ConnectorAgentError, Result}; use connectorx::impl_typesystem; use fehler::throws; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum PandasTypeSystem { F64(bool), I64(bool), Bool(bool), Char(bool), Str(bool), BoxS...
} fn npdtype(&self) -> &'static str { match *self { PandasTypeSystem::I64(_) => "i8", PandasTypeSystem::F64(_) => "f8", PandasTypeSystem::Bool(_) => "b1", PandasTypeSystem::Char(_) => "O", PandasTypeSystem::Str(_) => "O", PandasTy...
match *self { PandasTypeSystem::I64(false) => "int64", PandasTypeSystem::I64(true) => "Int64", PandasTypeSystem::F64(_) => "float64", PandasTypeSystem::Bool(false) => "bool", PandasTypeSystem::Bool(true) => "boolean", PandasTypeSystem::Char(_) => "...
if_condition
[ { "content": "/// `TypeSystem` describes all the types a source or destination support\n\n/// using enum variants.\n\n/// The variant can be used to type check with a static type `T` through the `check` method.\n\npub trait TypeSystem: Copy + Clone + Send + Sync {\n\n /// Check whether T is the same type as ...
Rust
src/config.rs
theotherjimmy/lanta
2579205c210b9bc58d0636e1af3538f433eff736
use std::collections::HashMap; use std::fs::File; use std::os::raw::c_uint; use std::path::PathBuf; use std::str::FromStr; use log::warn; use miette::IntoDiagnostic; use serde::de; use serde::{Deserialize, Deserializer}; use crate::keysym::*; use crate::layout::*; use crate::{ self as lanta, cmd::Command, Border...
use std::collections::HashMap; use std::fs::File; use std::os::raw::c_uint; use std::path::PathBuf; use std::str::FromStr; use log::warn; use miette::IntoDiagnostic; use serde::de; use serde::{Deserialize, Deserializer}; use crate::keysym::*; use crate::layout::*; use crate::{ self as lanta, cmd::Command, Border...
, Command>, layouts: Vec<LayoutSelect>, borders: Borders, } pub fn load_config_yaml(config_path: PathBuf) -> miette::Result<lanta::Config> { let config_file = File::open(config_path).into_diagnostic()?; let Config { keys, layouts, borders, } = serde_yaml::from_reader(config_...
"print" => XK_Print, a => Err(format!("Could not match key {}", a))?, }; let mods = iter .map(|mod_key| match mod_key { "C" => Ok(ModKey::Control), "M" => Ok(ModKey::Mod1), "S" => Ok(ModKey::Shift), "H" => Ok(ModKey:...
random
[ { "content": "/// A single key, of the same type as the `x11::keysym` constants.\n\ntype Key = c_uint;\n\n\n\n/// A combination of zero or more mods and a key.\n\n#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n\npub struct KeyCombo {\n\n pub mod_mask: ModMask,\n\n pub keysym: Key,\n\n}\n\n\n\nimpl KeyCombo...
Rust
migration/src/audio.rs
NEU-DSG/dailp-encoding
3cbfca2538e65ab1b797e120781252368063a755
use dailp::{AudioSlice, DocumentAudioId}; use reqwest::Client; use serde::{Deserialize, Serialize}; extern crate pretty_env_logger; use itertools::Itertools; use log::{error, info}; use serde_json::Value; use std::collections::{HashMap, HashSet}; #[derive(Serialize, Deserialize, Clone, Debug)] struct DrsId(String); ...
use dailp::{AudioSlice, DocumentAudioId}; use reqwest::Client; use serde::{Deserialize, Serialize}; extern crate pretty_env_logger; use itertools::Itertools; use log::{error, info}; use serde_json::Value; use std::collections::{HashMap, HashSet}; #[derive(Serialize, Deserialize, Clone, Debug)] struct DrsId(String); ...
pub fn into_document_audio(self) -> AudioSlice { AudioSlice { resource_url: self.audio_url.clone(), parent_track: Some(DocumentAudioId("".to_string())), annotations: Some(self.into_audio_slices()), index: 0, start_time: None, end...
info!("Creating new Audio Resource"); let client = Client::new(); let audio_response = DrsRes::new(&client, audio_drs_id).await?; let annotation_response = DrsRes::new(&client, annotation_drs_id).await?; Ok(Self { audio_url: audio_response ...
function_block-function_prefix_line
[ { "content": "pub fn simple_phonetics_to_worcester(input: &str) -> String {\n\n use {\n\n lazy_static::lazy_static,\n\n regex::{Captures, Regex},\n\n };\n\n // Convert the t/th consonants to d/t\n\n lazy_static! {\n\n static ref TTH_PATTERN: Regex = Regex::new(r\"(gw|kw|j|ʔ|:)\"...
Rust
src/lib.rs
SolarLiner/buffers
43483f3e5401648babc85faf734907835280e7d3
use std::{fs, io}; use std::io::{Cursor, Error, Read, Write}; pub enum Input { Standard(io::Stdin), Memory(io::Cursor<Vec<u8>>), File(fs::File), } pub enum Output { Standard(io::Stdout), Memory(io::Cursor<Vec<u8>>), File(fs::File), } pub enum InputOutput { Standard(io::Stdin, io::Stdout...
use std::{fs, io}; use std::io::{Cursor, Error, Read, Write}; pub enum Input { Standard(io::Stdin), Memory(io::Cursor<Vec<u8>>), File(fs::File), } pub enum Output { Standard(io::Stdout), Memory(io::Cursor<Vec<u8>>), File(fs::File), } pub enum InputOutput { Standard(io::Stdin, io::Stdout...
} }
match self { InputOutput::Standard(_, stdout) => stdout.flush(), InputOutput::Memory(m) => m.flush(), InputOutput::File(f) => f.flush() }
if_condition
[ { "content": "# buffers\n\nCollection of unified buffers from stdio, file and memory buffers.\n\n\n\nThe `buffers` crate unifies standard IO, memory and file buffers into a unified type, allowing\n\nto effectively leave the type of buffer used to the user.\n\n\n\n## How to use\n\n\n\nThe `buffers` crate exposes...
Rust
src/locustdb.rs
virattara/LocustDB
42945df6f4313b9dbded35bcd2d3018a003af003
use std::str; use std::sync::Arc; use std::error::Error; use std::path::{Path, PathBuf}; use futures::channel::oneshot; use num_cpus; use crate::QueryError; use crate::QueryResult; use crate::disk_store::interface::*; use crate::disk_store::noop_storage::NoopStorage; use crate::engine::query_task::QueryTask; use crat...
use std::str; use std::sync::Arc; use std::error::Error; use std::path::{Path, PathBuf}; use futures::channel::oneshot; use num_cpus; use crate::QueryError; use crate::QueryResult; use crate::disk_store::interface::*; use crate::disk_store::noop_storage::NoopStorage; use crate::engine::query_task::QueryTask; use crat...
pub async fn run_query(&self, query: &str, explain: bool, show: Vec<usize>) -> Result<QueryResult, oneshot::Canceled> { let (sender, receiver) = oneshot::channel(); let query = match parser::parse_query(query) { Ok(query) => query, Err(err) => return Ok(Err(err)),...
unwrap_or_else(|| Arc::new(NoopStorage)); let locustdb = Arc::new(InnerLocustDB::new(disk_store, opts)); InnerLocustDB::start_worker_threads(&locustdb); LocustDB { inner_locustdb: locustdb } }
function_block-function_prefix_line
[ { "content": "fn parse_type(field_ident: &Ident, type_def: String) -> Option<(Expr, Option<FnArg>)> {\n\n lazy_static! {\n\n // E.g. `data` in `( t = \"data.nullable\" )`\n\n static ref T: Regex = Regex::new(r#\"t = \"(.*)\"\"#).unwrap();\n\n static ref BASE: Regex = Regex::new(r#\"base=...
Rust
demo/src/components/physics.rs
aclysma/atelier-legion-demo
658d1f6471cd41d48b13f7fc2db2f5ebabdb9429
use serde::{Deserialize, Serialize}; use serde_diff::SerdeDiff; use type_uuid::TypeUuid; use nphysics2d::object::DefaultBodyHandle; use legion_transaction::SpawnFrom; use crate::math::Vec2; use crate::resources::{PhysicsResource, OpenedPrefabState}; use legion::prelude::*; use std::ops::Range; use legion::storage::Comp...
use serde::{Deserialize, Serialize}; use serde_diff::SerdeDiff; use type_uuid::TypeUuid; use nphysics2d::object::DefaultBodyHandle; use legion_transaction::SpawnFrom; use crate::math::Vec2; use crate::resources::{PhysicsResource, OpenedPrefabState}; use legion::prelude::*; use std::ops::Range; use legion::storage::Comp...
}
if let Some(non_uniform_scale) = prefab_world.get_component::<NonUniformScale2DComponent>(prefab_entity) { half_extents *= *non_uniform_scale.non_uniform_scale; } let mut rotation = 0.0; if let Some(rotation_component) = pr...
function_block-function_prefix_line
[ { "content": "pub fn winit_position_to_glam(position: PhysicalPosition<f64>) -> glam::Vec2 {\n\n glam::Vec2::new(position.x as f32, position.y as f32)\n\n}\n\n\n\n#[derive(Copy, Clone, Serialize, Deserialize, Debug, PartialEq, Default)]\n\n#[repr(transparent)]\n\n#[serde(transparent)]\n\npub struct Vec2 {\n\...
Rust
src/view/root.rs
PENGUINLIONG/Writus
63f47f0730380f83cdfda69899b0aa6427c0c15a
use std::sync::Arc; use serde_json::Value as JsonValue; use pulldown_cmark::Parser; use pulldown_cmark::{Options as ParserOptions, OPTION_ENABLE_TABLES}; use writium::prelude::*; use writium_cache::{Cache, DumbCacheSource}; use api::index::Index; use super::template::*; pub struct RootView { index_templa...
use std::sync::Arc; use serde_json::Value as JsonValue; use pulldown_cmark::Parser; use pulldown_cmark::{Options as ParserOptions, OPTION_ENABLE_TABLES}; use writium::prelude::*; use writium_cache::{Cache, DumbCacheSource}; use api::index::Index; use super::template::*; pub struct RootView { index_templa...
ew(); lines .skip_while(|line| line.trim().len() == 0) .take_while(|line| line.trim().len() > 0) .for_each(|x| content += x); (title, content) } fn md_to_html(md: &str) -> String { let mut buf = String::with_capa...
.chars() .skip_while(|ch| ch == &'#') .skip_while(|ch| ch == &' ') .collect(); let mut content = String::n
function_block-random_span
[ { "content": "fn make_index(dir: &str, key: &str, index: &mut IndexCollection) {\n\n info!(\"Indexing files with key '{}'.\", key);\n\n for entry in WalkDir::new(&dir)\n\n .into_iter()\n\n .filter_map(|x| x.ok()) {\n\n // Seek for `content.md`.\n\n if !entry.file_type().is_file...
Rust
host/src/fs/cache.rs
manasrivastava/tinychain
e6082f587ac089307ca9264d90d20c3f0991da52
use std::convert::{TryFrom, TryInto}; use std::path::PathBuf; #[cfg(feature = "tensor")] use afarray::Array; use async_trait::async_trait; use destream::IntoStream; use freqache::Entry; use futures::{Future, TryFutureExt}; use log::{debug, error, info, warn}; use tokio::fs; use tokio::io::AsyncWrite; use tokio::sync...
use std::convert::{TryFrom, TryInto}; use std::path::PathBuf; #[cfg(feature = "tensor")] use afarray::Array; use async_trait::async_trait; use destream::IntoStream; use freqache::Entry; use futures::{Future, TryFutureExt}; use log::{debug, error, info, warn}; use tokio::fs; use tokio::io::AsyncWrite; use tokio::sync...
pub async fn delete(&self, path: &PathBuf) -> Option<CacheBlock> { debug!("Cache::delete {:?}", path); let mut cache = self.lfu.write().await; cache.remove(path).await } pub async fn delete_and_sync(&self, path: PathBuf) -> TCResult<()> { debug!("Cache::delete_a...
Data>(&self, path: &PathBuf) -> TCResult<Option<CacheLock<B>>> where CacheLock<B>: TryFrom<CacheBlock, Error = TCError>, CacheBlock: From<CacheLock<B>>, { debug!("Cache::read {:?}", path); let mut cache = self.lfu.write().await; if let Some(block) = cache.get(path).awai...
function_block-function_prefixed
[ { "content": "fn io_err<I: fmt::Debug + Send>(err: io::Error, info: I) -> TCError {\n\n match err.kind() {\n\n io::ErrorKind::NotFound => {\n\n TCError::internal(format!(\"host filesystem has no such entry {:?}\", info))\n\n }\n\n io::ErrorKind::PermissionDenied => TCError::in...
Rust
gcs-cxx/src/ecs_world.rs
Beliaar/godot-component-system
2e2bd9186a968853b53f447cffa34703b5ddc2a6
use std::string::String; use cxx::{type_id, ExternType}; use gcs::world::ecs_world::{create_ecs_world, ECSWorld}; use crate::component::component_data::create_component_data; use crate::component::component_data::CXXComponentData; use crate::component::component_definition::CXXComponentDefinition; use crate::compone...
use std::string::String; use cxx::{type_id, ExternType}; use gcs::world::ecs_world::{create_ecs_world, ECSWorld}; use crate::component::component_data::create_component_data; use crate::component::component_data::CXXComponentData; use crate::component::component_definition::CXXComponentDefinition; use crate::compone...
fn set_component_data( self: &mut CXXECSWorld, entity_id: &CXXEntityId, component: String, data: &CXXComponentData, ) -> Box<UnitResult> { let result = self.0.set_component_data(entity_id, component, data); Box::new(match result { Ok(_) => UnitResult...
fn register_entity(self: &mut CXXECSWorld, id: &CXXEntityId) -> Box<UnitResult> { let result = self.0.register_entity(id); Box::new(match result { Ok(_) => UnitResult::new_result(()), Err(err) => UnitResult::new_error(err.to_string()), }) }
function_block-full_function
[ { "content": "pub fn create_component_field_definition() -> ffi::CXXComponentFieldDefinition {\n\n ffi::CXXComponentFieldDefinition::default()\n\n}\n\n\n\n#[derive(Hash, Eq, PartialEq, Clone, Default)]\n\npub struct CXXComponentDefinition {\n\n pub fields: Vec<ffi::CXXComponentFieldDefinition>,\n\n}\n\n\n...
Rust
rust/src/eddsa/utils.rs
hermeznetwork/hermez_flutter_sdk
c165ba3cdb6ecfc5f7cc476e658ff3265e178312
extern crate num; extern crate num_bigint; extern crate num_traits; use num_bigint::{BigInt, ToBigInt}; use num_traits::{One, Zero}; pub fn modulus(a: &BigInt, m: &BigInt) -> BigInt { ((a % m) + m) % m } pub fn modinv(a: &BigInt, q: &BigInt) -> Result<BigInt, String> { let big_zero: BigInt = Zero::zero(); ...
extern crate num; extern crate num_bigint; extern crate num_traits; use num_bigint::{BigInt, ToBigInt}; use num_traits::{One, Zero}; pub fn modulus(a: &BigInt, m: &BigInt) -> BigInt { ((a % m) + m) % m } pub fn modinv(a: &BigInt, q: &BigInt) -> Result<BigInt, String> { let big_zero: BigInt = Zero::zero(); ...
egendre_symbol(&a, q) != 1 { return Err("not a mod p square".to_string()); } else if a == &zero { return Err("not a mod p square".to_string()); } else if q == &2.to_bigint().unwrap() { return Err("not a mod p square".to_string()); } else if q % 4.to_bigint().unwrap() == 3.to_bigint()...
old_r, &mut r); old_s -= &quotient * &s; std::mem::swap(&mut old_s, &mut s); old_t -= quotient * &t; std::mem::swap(&mut old_t, &mut t); } let _quotients = (t, s); // == (a, b) / gcd (old_r, old_s, old_t) } */ pub fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T>...
random
[ { "content": "pub fn decompress_signature(b: &[u8; 64]) -> Result<Signature, String> {\n\n let r_b8_bytes: [u8; 32] = *array_ref!(b[..32], 0, 32);\n\n let s: BigInt = BigInt::from_bytes_le(Sign::Plus, &b[32..]);\n\n let r_b8 = decompress_point(r_b8_bytes);\n\n match r_b8 {\n\n Result::Err(err...
Rust
src/packages/string_more.rs
jonnyboyC/rhai
91963d10dc6fb5ab1a0e4ffc62f5ecc2643dfff8
#![allow(non_snake_case)] use crate::any::Dynamic; use crate::def_package; use crate::engine::Engine; use crate::fn_native::FnPtr; use crate::parser::{ImmutableString, INT}; use crate::plugin::*; use crate::utils::StaticVec; #[cfg(not(feature = "unchecked"))] use crate::{result::EvalAltResult, token::Position}; use ...
#![allow(non_snake_case)] use crate::any::Dynamic; use crate::def_package; use crate::engine::Engine; use crate::fn_native::FnPtr; use crate::parser::{ImmutableString, INT}; use crate::plugin::*; use crate::utils::StaticVec; #[cfg(not(feature = "unchecked"))] use crate::{result::EvalAltResult, token::Position}; use ...
#[rhai_fn(name = "index_of")] pub fn index_of_string(s: &mut ImmutableString, find: ImmutableString) -> INT { s.find(find.as_str()) .map(|index| s[0..index].chars().count() as INT) .unwrap_or(-1 as INT) } #[rhai_fn(name = "sub_string")] pub fn sub_string(s: Immutabl...
pub fn index_of_string_starting_from( s: &mut ImmutableString, find: ImmutableString, start: INT, ) -> INT { let start = if start < 0 { 0 } else if (start as usize) >= s.chars().count() { return -1 as INT; } else { s.chars().take(st...
function_block-full_function
[ { "content": "#[export_fn]\n\npub fn test_fn(input: &mut Clonable) -> &mut bool {\n\n &mut input.d\n\n}\n\n\n", "file_path": "codegen/ui_tests/return_mut_ref.rs", "rank": 0, "score": 353556.9496434691 }, { "content": "#[export_fn]\n\npub fn add_together(x: INT, y: INT) -> INT {\n\n x +...
Rust
examples/linked_timer_rtic.rs
akashihi/stm32l0xx-hal
d53ec21dc02348ecc8351f0578ec4eee08a447cf
#![no_main] #![no_std] extern crate panic_halt; use core::fmt::Write; use rtic::app; use stm32l0xx_hal::prelude::*; use stm32l0xx_hal::{ pac, rcc::Config, serial::{self, Serial}, time, timer::{LinkedTimer, LinkedTimerPair, Timer}, }; const LOGGER_FREQUENCY: u32 = 2; #[app(device = stm32l0xx_hal...
#![no_main] #![no_std] extern crate panic_halt; use core::fmt::Write; use rtic::app; use stm32l0xx_hal::prelude::*; use stm32l0xx_hal::{ pac, rcc::Config, serial::{self, Serial}, time, timer::{LinkedTimer, LinkedTimerPair, Timer}, }; const LOGGER_FREQUENCY: u32 = 2; #[app(device = stm32l0xx_hal...
#[task(binds = TIM6, resources = [serial, timer, linked_tim2_tim3, linked_tim21_tim22])] fn logger(ctx: logger::Context) { static mut PREV_TIM2_TIM3: u32 = 0; static mut PREV_TIM21_TIM22: u32 = 0; static mut TIMES_UNTIL_RESET: u32 = 3 * LOGGER_FREQUENCY; ctx...
IM2, dp.TIM3, &mut rcc); delay.delay_ms(1000u16); writeln!(serial, "Init TIM21/TIM22...").ok(); let linked_tim21_tim22 = LinkedTimerPair::tim21_tim22(dp.TIM21, dp.TIM22, &mut rcc); let mut timer = dp.TIM6.timer(LOGGER_FREQUENCY.hz(), &mut rcc); timer.listen(); ...
function_block-function_prefixed
[ { "content": "fn delay() {\n\n // We can't use `Delay`, as that requires a frequency of at least one MHz.\n\n // Given our clock selection, the following loop should give us a nice delay\n\n // when compiled in release mode.\n\n for _ in 0..1_000 {\n\n asm::nop()\n\n }\n\n}\n", "file_p...
Rust
src/lib.rs
msakuta/rotate-enum
4a4b64a3b28bd30f961688f1462f9db57dbd6502
use core::panic; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, Data, DeriveInput}; #[proc_macro_derive(RotateEnum)] pub fn rotate_enum(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident; let variants = if let D...
use core::panic; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, Data, DeriveInput}; #[proc_macro_derive(RotateEnum)] pub fn rotate_enum(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident;
let nexts = variants .iter() .skip(1) .chain(variants.get(0)) .map(|v| (&v.ident)) .collect::<Vec<_>>(); let tokens = quote! { impl #name{ pub fn next(self) -> Self { match self { #(Self::#variants => Self::#nexts...
let variants = if let Data::Enum(data) = &input.data { data.variants.iter().collect::<Vec<_>>() } else { panic!("derive(RotateEnum) must be applied to an enum"); };
assignment_statement
[ { "content": "#[test]\n\nfn test_shift() {\n\n let up = Direction::Up;\n\n let left = Direction::Left;\n\n let down = Direction::Down;\n\n let right = Direction::Right;\n\n\n\n let mut iter = up.iter();\n\n assert!(iter.next() == Some(up));\n\n assert!(iter.next() == Some(left));\n\n ass...
Rust
src/ping.rs
FrozenDroid/esp-idf-svc
d394bc67d288b5a3b8dcdeb896adcdf1ba7f1533
use core::{mem, ptr, time::Duration}; use ::log::*; #[cfg(feature = "std")] use std::sync::*; use embedded_svc::ipv4; use embedded_svc::mutex::Mutex; use embedded_svc::ping::*; use esp_idf_sys::*; use crate::private::common::*; #[derive(Debug)] pub struct EspPing(u32); unsafe impl Send for EspPing {} unsafe impl...
use core::{mem, ptr, time::Duration}; use ::log::*; #[cfg(feature = "std")] use std::sync::*; use embedded_svc::ipv4; use embedded_svc::mutex::Mutex; use embedded_svc::ping::*; use esp_idf_sys::*; use crate::private::common::*; #[derive(Debug)] pub struct EspPing(u32); unsafe impl Send for EspPing {} unsafe impl...
id, mem::size_of_val(&total_time) as u32, ); summary.transmitted = transmitted; summary.received = received; summary.time = Duration::from_millis(total_time as u64); } } impl Ping for EspPing { type Error = EspError; fn ping(&mut self, ip: ipv4::Ipv4Addr, conf:...
lapsed_time) as u32, ); let mut recv_len: c_types::c_uint = 0; esp_ping_get_profile( handle, esp_ping_profile_t_ESP_PING_PROF_SIZE, &mut recv_len as *mut c_types::c_uint as *mut c_types::c_void, mem::size_of_val(&recv_len) as u32, ); ...
random
[ { "content": "#[cfg(feature = \"alloc\")]\n\npub fn from_cstr_ptr(ptr: *const i8) -> alloc::string::String {\n\n unsafe { CStr::from_ptr(ptr) }.to_string_lossy().to_string()\n\n}\n\n\n", "file_path": "src/private/cstr.rs", "rank": 2, "score": 71492.7575833215 }, { "content": "#[cfg(featur...
Rust
src/model/wrapper.rs
MaxOhn/bathbot-cache
c9f5f406d32bc99d31d618d69ed0db84aba4833b
use serde::ser::{Serialize, SerializeStruct, Serializer}; use twilight_model::{ channel::{ thread::{PrivateThread, PublicThread}, GuildChannel, TextChannel, }, gateway::payload::incoming::MemberUpdate, guild::{Guild, Member, PartialGuild, PartialMember, Role}, id::{ChannelId, GuildId...
use serde::ser::{Serialize, SerializeStruct, Serializer}; use twilight_model::{ channel::{ thread::{PrivateThread, PublicThread}, GuildChannel, TextChannel, }, gateway::payload::incoming::MemberUpdate, guild::{Guild, Member, PartialGuild, PartialMember, Role}, id::{ChannelId, GuildId...
member.end() } } pub struct PartialMemberWrapper<'m> { guild: GuildId, member: &'m PartialMember, user: &'m User, } impl<'m> From<(&'m PartialMember, GuildId, &'m User)> for PartialMemberWrapper<'m> { fn from((member, guild, user): (&'m PartialMember, GuildId, &'m User)) -> Self { ...
roles.is_empty() { member.serialize_field("c", &self.0.roles)?; } member.serialize_field("d", &self.0.user.id)?;
function_block-random_span
[ { "content": "fn populate_members(key: &RedisKey, members: &mut RedisMembers) {\n\n match key {\n\n RedisKey::Channel { guild, .. } => {\n\n populate_member(CHANNEL_KEYS, *key, members);\n\n\n\n if let Some(guild) = guild {\n\n populate_member(format!(\"{}:{}\", GU...
Rust
crates/modor/src/system_params/mod.rs
modor-engine/modor
447ae453030de44ed93a2ab03a66261080304ce4
use crate::storages::archetypes::EntityLocation; use crate::storages::components::ComponentTypeIdx; use crate::storages::core::CoreStorage; use crate::storages::systems::SystemProperties; use crate::system_params::internal::{QuerySystemParamWithLifetime, SystemParamWithLifetime}; use crate::{SystemData, SystemInfo}; p...
use crate::storages::archetypes::EntityLocation; use crate::storages::components::ComponentTypeIdx; use crate::storages::core::CoreStorage; use crate::storages::systems::SystemProperties; use crate::system_params::internal::{QuerySystemParamWithLifetime, SystemParamWithLifetime}; use crate::{SystemData, SystemInfo}; p...
fn get_both_mut_internal<K, T>( data: &mut TiVec<K, T>, key1: K, key2: K, ) -> (Option<&mut T>, Option<&mut T>) where K: Ord + From<usize> + Copy, usize: From<K>, { if key2 >= data.next_key() { (data.get_mut(key1), None) } else if key...
sub_data1.and_then(|d| d.get_mut(location1.pos)), sub_data2.and_then(|d| d.get_mut(location2.pos)), ) } }
function_block-function_prefix_line
[ { "content": "/// A trait for defining the main component of an entity type.\n\n///\n\n/// This trait shouldn't be directly implemented.<br>\n\n/// Instead, you can use [`entity`](macro@crate::entity) and [`singleton`](macro@crate::singleton)\n\n/// proc macros.\n\npub trait EntityMainComponent: Sized + Any + S...
Rust
src/net.rs
dejano-with-tie/stun_codec
4f15041b761eb57bb3c6aef09610ec61603c9663
use crate::constants::MAGIC_COOKIE; use crate::TransactionId; use bytecodec::bytes::{BytesDecoder, BytesEncoder}; use bytecodec::combinator::Peekable; use bytecodec::fixnum::{U16beDecoder, U16beEncoder, U8Decoder, U8Encoder}; use bytecodec::{ByteCount, Decode, Encode, Eos, ErrorKind, Result, SizedEncode}; use std::ne...
use crate::constants::MAGIC_COOKIE; use crate::TransactionId; use bytecodec::bytes::{BytesDecoder, BytesEncoder}; use bytecodec::combinator::Peekable; use bytecodec::fixnum::{U16beDecoder, U16beEncoder, U8Decoder, U8Encoder}; use bytecodec::{ByteCount, Decode, Encode, Eos, ErrorKind, Result, SizedEncode}; use std::ne...
} #[cfg(test)] mod tests { use bytecodec::{DecodeExt, EncodeExt}; use super::*; #[test] fn socket_addr_xor_works() { let transaction_id = TransactionId::new([ 0xb7, 0xe7, 0xa7, 0x01, 0xbc, 0x34, 0xd6, 0x86, 0xfa, 0x87, 0xdf, 0xae, ]); let addr: SocketAdd...
fn as_mut(&mut self) -> &mut [u8] { match self { IpBytes::V4(bytes) => bytes, IpBytes::V6(bytes) => bytes, } }
function_block-full_function
[ { "content": "#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\nstruct Type {\n\n class: MessageClass,\n\n method: Method,\n\n}\n\nimpl Type {\n\n fn as_u16(self) -> u16 {\n\n let class = self.class as u16;\n\n let method = self.method.as_u16();\n\n (method & 0b0000_0000_1111)\...
Rust
zandbox/src/zandbox/main.rs
tpscrpt/zinc
35307d3da96377b76425e03aefca97c5c10c5565
mod arguments; mod error; use std::collections::HashMap; use std::str::FromStr; use actix_web::middleware; use actix_web::web; use actix_web::App; use actix_web::HttpServer; use colored::Colorize; use rayon::iter::IntoParallelIterator; use rayon::iter::ParallelIterator; use zksync_eth_signer::PrivateKeySigner; use...
mod arguments; mod error; use std::collections::HashMap; use std::str::FromStr; use actix_web::middleware; use actix_web::web; use actix_web::App; use actix_web::HttpServer; use colored::Colorize; use rayon::iter::IntoParallelIterator; use rayon::iter::ParallelIterator; use zksync_eth_signer::PrivateKeySigner; use...
async fn main() -> Result<(), Error> { let args = Arguments::new(); zinc_logger::initialize(zinc_const::app_name::ZANDBOX, args.verbosity); log::info!("Zandbox server started"); let network = zksync::Network::from_str(args.network.as_str()).map_err(Error::InvalidNetwork)?; log::info!("In...
function_block-full_function
[ { "content": "///\n\n/// The auxiliary `main` function to facilitate the `?` error conversion operator.\n\n///\n\nfn main_inner() -> Result<(), Error> {\n\n let args = Arguments::new();\n\n\n\n zinc_logger::initialize(zinc_const::app_name::COMPILER, args.verbosity);\n\n\n\n let manifest = Manifest::try...
Rust
src/scene/save_scene.rs
atsisy/subterranean
8c844e95b47e441c43709bd7f6aefa2c15da880b
use ggez::graphics as ggraphics; use torifune::core::Clock; use torifune::graphics::drawable::*; use torifune::graphics::object::*; use crate::core::{FontID, SavableData, SoundID, SuzuContext, TextureID, TileBatchTextureID}; use crate::object::effect_object; use crate::object::save_scene_object::*; use crate::object:...
use ggez::graphics as ggraphics; use torifune::core::Clock; use torifune::graphics::drawable::*; use torifune::graphics::object::*; use crate::core::{FontID, SavableData, SoundID, SuzuContext, TextureID, TileBatchTextureID}; use crate::object::effect_object; use crate::object::save_scene_object::*; use crate::object:...
} fn post_process<'a>(&mut self, _ctx: &mut SuzuContext<'a>) -> SceneTransition { self.update_current_clock(); self.scene_transition_type } fn transition(&self) -> SceneID { self.scene_transition } fn get_current_clock(&self) -> Clock { self.clock } ...
if let Some(transition_effect) = self.scene_transition_effect.as_mut() { transition_effect.draw(ctx).unwrap(); }
if_condition
[ { "content": "pub fn clock_needle_angle(hour: u8, minute: u8) -> (f32, f32) {\n\n let hour = hour % 12;\n\n\n\n let angle_per_hour = 2.0 * std::f32::consts::PI / (12.0 * 60.0);\n\n let angle_per_minute = 2.0 * std::f32::consts::PI / 60.0;\n\n\n\n (\n\n ((hour as f32 * 60.0) + minute as f32) *...
Rust
src/lib.rs
tosus/ranpaman-core
d65943b4cb8f9d644927277c6c33d2752b559b02
use num_bigint::BigUint; use num_traits::cast::{FromPrimitive, ToPrimitive}; use orion::aead; #[allow(dead_code)] use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::io::prelude::*; use blake2::{Blake2b, Digest}; use zeroize::Zeroize; const ENCRYPTION_SALT: [u8; 64] = [ 0xe3, 0x1a, 0x0c, 0...
use num_bigint::BigUint; use num_traits::cast::{FromPrimitive, ToPrimitive}; use orion::aead; #[allow(dead_code)] use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::io::prelude::*; use blake2::{Blake2b, Digest}; use zeroize::Zeroize; const ENCRYPTION_SALT: [u8; 64] = [ 0xe3, 0x1a, 0x0c, 0...
pub fn get_password(&self, login: String, service_name: String) -> Result<String> { match self .data .get(&(service_name.to_string(), login.to_string())) { Some(settings) => { let salt: &[u8] = &[ login.as_bytes(), ...
pub fn add_account( &mut self, login: String, service_name: String, settings: Settings, ) -> Result<()> { if service_name.is_empty() || login.is_empty() || settings.password_length < 4 { } let key = (service_name, login); if self.data.cont...
function_block-full_function
[ { "content": "# ranpaman-core\n\nA library for creating MasterPassword-style password managers. Written in Rust and uses Argon2.\n\n\n\nCurrently a proof of concept and obviously insecure.\n", "file_path": "README.md", "rank": 3, "score": 7357.13440566655 } ]
Rust
server/src/server/mod.rs
JAD3N/mc-server
ce1ad57f2417f722d6c00ae21fdc3cd0efdadd7a
mod settings; mod status; mod executor; pub use settings::*; pub use status::*; pub use executor::*; use crate::core::Registries; use crate::chat::component::TextComponent; use crate::world::level::Level; use crate::network::{Listener, Connection}; use std::collections::HashMap; use std::net::SocketAddr;...
mod settings; mod status; mod executor; pub use settings::*; pub use status::*; pub use executor::*; use crate::core::Registries; use crate::chat::component::TextComponent; use crate::world::level::Level; use crate::network::{Listener, Connection}; use std::collections::HashMap; use std::net::SocketAddr;...
async fn bind(&self, addr: SocketAddr) -> anyhow::Result<Listener> { let shared = self.shared.clone(); let server = self.server.clone(); let server_tx = server.lock().await .tx.clone(); let listener = Listener::bind( server_tx, ...
e(), })) ); info!("loaded levels"); Ok(()) }
function_block-function_prefixed
[ { "content": "fn init_resource_registry<T: 'static>(name: &str) -> Arc<ResourceRegistry<T>> {\n\n let mut event = RegisterEvent(ResourceRegistry::new());\n\n\n\n // send event to all subscribers to add to registry\n\n dispatch_event!(\"main\", &mut event);\n\n\n\n // log completion\n\n info!(\"re...
Rust
sf/src/twin.rs
SetTheorist/rust-special-functions
a03ea7f07677a79dc8c80c468e90c6525b64bf96
use std::ops::{Add,Sub,Mul,Div,Rem}; use std::ops::{AddAssign,SubAssign,MulAssign,DivAssign,RemAssign}; use std::ops::{Neg}; #[derive(Clone,Copy,Debug,Default,PartialEq,PartialOrd)] pub struct Twin<F>{hi:F, lo:F} pub trait Base: Sized + Copy + Add<Output=Self> + Sub<Output=Self> + Mul<Output=Self> + Div<Outp...
use std::ops::{Add,Sub,Mul,Div,Rem}; use std::ops::{AddAssign,SubAssign,MulAssign,DivAssign,RemAssign}; use std::ops::{Neg}; #[derive(Clone,Copy,Debug,Default,PartialEq,PartialOrd)] pub struct Twin<F>{hi:F, lo:F} pub trait Base: Sized + Copy + Add<Output=Self> + Sub<Output=Self> + Mul<Output=Self> + Div<Outp...
} #[inline] fn qdadd<F:Base>(Twin{hi:xhi, lo:xlo}:Twin<F>, y:F) -> Twin<F> { let (shi, slo) = ddsum(y, xhi); let (hhi, hlo) = qtsum(shi, slo + xlo); let (hi, lo) = qtsum(hhi, hlo); Twin{hi, lo} } #[inline] fn dqadd<F:Base>(x:F, y:Twin<F>) -> Twin<F> { qdadd(y, x) } #[inline] fn qqadd<F:Base>(Twin{hi:xhi, lo...
if F::HAS_MUL_ADD() { let p = a * b; let e = a.mul_add(b, -p); (p, e) } else { let (ahi, alo) = split(a); let (bhi, blo) = split(b); let p = a * b; let e = (((ahi * bhi - p) + ahi * blo) + alo * bhi) + alo * blo; (p, e) }
if_condition
[ { "content": "pub trait Ordered: Base + PartialOrd<Self> {\n\n #[inline]\n\n fn min(self, b: Self) -> Self {\n\n if self < b { self } else { b }\n\n }\n\n #[inline]\n\n fn max(self, b: Self) -> Self {\n\n if self > b { self } else { b }\n\n }\n\n\n\n fn floor(self) -> Self;\n\n fn ceil(self) -> Se...
Rust
operators/src/processing/circle_merging_quadtree/grid.rs
koerberm/geoengine
61e0ec7a0c1136b4360b0f9c6306c34198e8ac3a
use geoengine_datatypes::primitives::{AxisAlignedRectangle, BoundingBox2D, Coordinate2D}; use super::{ circle_of_points::CircleOfPoints, circle_radius_model::CircleRadiusModel, hash_map::SeparateChainingHashMap, }; #[derive(Clone, Debug)] pub struct Grid<C: CircleRadiusModel> { offset: Coordinate2D, c...
use geoengine_datatypes::primitives::{AxisAlignedRectangle, BoundingBox2D, Coordinate2D}; use super::{ circle_of_points::CircleOfPoints, circle_radius_model::CircleRadiusModel, hash_map::SeparateChainingHashMap, }; #[derive(Clone, Debug)] pub struct Grid<C: CircleRadiusModel> { offset: Coordinate2D, c...
}
fn test_grid() { let mut grid = Grid::new( BoundingBox2D::new((0., 0.).into(), (10., 10.).into()).unwrap(), LogScaledRadius::new(2., 1.).unwrap(), ); grid.insert(CircleOfPoints::new_with_one_point( Circle::new(1., 1., 1.), TimeInterval::default(),...
function_block-full_function
[ { "content": "pub fn fn_stream() -> impl Stream<Item = usize> {\n\n let mut counter: usize = 2;\n\n\n\n stream::poll_fn(move |_| -> Poll<Option<usize>> {\n\n if counter == 0 {\n\n return Poll::Ready(None);\n\n }\n\n counter -= 1;\n\n Poll::Ready(Some(counter))\n\n ...
Rust
daemon/src/rest_api/mod.rs
peterschwarz/grid
1b3859f74faa777fe7b72edb6ae4e7d80ba5c753
pub mod error; mod routes; use std::sync::mpsc; use std::thread; use crate::database::ConnectionPool; pub use crate::rest_api::error::RestApiServerError; use crate::rest_api::routes::DbExecutor; use crate::rest_api::routes::{ fetch_agent, fetch_grid_schema, fetch_organization, fetch_product, fetch_record, f...
pub mod error; mod routes; use std::sync::mpsc; use std::thread; use crate::database::ConnectionPool; pub use crate::rest_api::error::RestApiServerError; use crate::rest_api::routes::DbExecutor; use crate::rest_api::routes::{ fetch_agent, fetch_grid_schema, fetch_organization, fetch_product, fetch_record, f...
AppState { batch_submitter, database_connection, } } } pub struct RestApiShutdownHandle { do_shutdown: Box<dyn Fn() -> Result<(), RestApiServerError> + Send>, } impl RestApiShutdownHandle { pub fn shutdown(&self) -> Result<(), RestApiServerError> { (*self....
let database_connection = SyncArbiter::start(SYNC_ARBITER_THREAD_COUNT, move || { DbExecutor::new(connection_pool.clone()) });
assignment_statement
[ { "content": "pub fn create_connection_pool(database_url: &str) -> Result<ConnectionPool, DatabaseError> {\n\n let connection_manager = ConnectionManager::<PgConnection>::new(database_url);\n\n Ok(ConnectionPool {\n\n pool: Pool::builder()\n\n .build(connection_manager)\n\n .m...
Rust
metrics/src/recorder.rs
kevyang/rpc-perf
30cad3701837cab25c156d7d76e8df10e10d23da
use crate::*; use datastructures::HistogramConfig; use datastructures::RwWrapper; use std::collections::HashSet; use std::sync::Arc; use datastructures::Wrapper; use evmap::{ReadHandle, WriteHandle}; use std::collections::HashMap; #[derive(Clone)] pub struct Recorder { data_read: ReadHandle<String, Arc<Channel...
use crate::*; use datastructures::HistogramConfig; use datastructures::RwWrapper; use std::collections::HashSet; use std::sync::Arc; use datastructures::Wrapper; use evmap::{ReadHandle, WriteHandle}; use std::collections::HashMap; #[derive(Clone)] pub struct Recorder { data_read: ReadHandle<String, Arc<Channel...
source: {:?}", name, source); let channel = Channel::new(name.clone(), source, histogram_config); if self .data_read .get_and(&name, |channel| channel.len()) .unwrap_or(0) == 0 { unsafe { (*self.data_write.get()).insert(...
rcentile)) .unwrap_or(None) } pub fn add_channel( &self, name: String, source: Source, histogram_config: Option<HistogramConfig>, ) { debug!("add channel: {}
random
[ { "content": "pub fn runner(runtime: f64, source: Source, measurement_type: MeasurementType, label: String) {\n\n for single_channel in [true, false].iter() {\n\n for i in [1, 2, 4, 8, 16, 32, 64].iter() {\n\n timed_run(\n\n *i,\n\n runtime,\n\n ...
Rust
tests/serde_tests.rs
wrobstory/brickline
16b7281242744398cfaaaae87dda3b5c3c76ba4e
extern crate brickline; use std::convert::TryFrom; use brickline::wanted::{ Color, Condition, Item, ItemID, ItemType, MaxPrice, MinQty, Notify, QtyFilled, Remarks, WantedList, }; mod common; #[cfg(test)] mod tests { use super::*; #[test] fn test_xml_to_wanted_list() { let bricklink_wan...
extern crate brickline; use std::convert::TryFrom; use brickline::wanted::{ Color, Condition, Item, ItemID, ItemType, MaxPrice, MinQty, Notify, QtyFilled, Remarks, WantedList, }; mod common; #[cfg(test)] mod tests { use super::*; #[test]
#[test] fn test_wanted_list_to_string_1() { let item_1 = Item::build_test_item( ItemType::Part, ItemID(String::from("3622")), Some(Color(11)), Some(MinQty(4)), ); let items = vec![item_1]; let wanted_list = WantedList { items: ite...
fn test_xml_to_wanted_list() { let bricklink_wanted_list: WantedList = common::resource_name_to_wanted_list("bricklink_example.xml"); let item_1 = Item { item_type: ItemType::Part, item_id: ItemID(String::from("3622")), color: Some(Color(11)), ...
function_block-full_function
[ { "content": "use brickline::wanted::{SerdeWantedList, WantedList};\n\nuse brickline::xml_to_string;\n\n\n\nuse quick_xml::de::from_str;\n\n\n\nuse std::fs::File;\n\nuse std::io::Read;\n\nuse std::path::PathBuf;\n\n\n", "file_path": "tests/common/mod.rs", "rank": 0, "score": 64840.782517102314 }, ...
Rust
pingr/src/main.rs
13ABEL/internship-application-systems
1865456b46d621637147b194322dfc5d5791a126
mod main_clap; extern crate pnet; extern crate regex; use pnet::packet::icmp::{IcmpCode, IcmpTypes, MutableIcmpPacket}; use pnet::packet::icmpv6::{Icmpv6Types, MutableIcmpv6Packet}; use pnet::packet::ip::IpNextHeaderProtocols::{Icmp, Icmpv6}; use pnet::packet::ipv4::MutableIpv4Packet; use pnet::packet::ipv6::Mutable...
mod main_clap; extern crate pnet; extern crate regex; use pnet::packet::icmp::{IcmpCode, IcmpTypes, MutableIcmpPacket}; use pnet::packet::icmpv6::{Icmpv6Types, MutableIcmpv6Packet}; use pnet::packet::ip::IpNextHeaderProtocols::{Icmp, Icmpv6}; use pnet::packet::ipv4::MutableIpv4Packet; use pnet::packet::ipv6::Mutable...
ER_WORD_LEN); ipv4_packet.set_total_length((IPV4_HEADER_LEN + icmp_packet_len) as u16); ipv4_packet.set_ttl(ttl); ipv4_packet.set_next_level_protocol(IpNextHeaderProtocols::Icmp); ipv4_packet.set_destination(dest); let mut icmp_packet = MutableIcmpPacket::new(icmp_packet_buf).expect("unable...
stions/208875/traceroute-implementation-in-rust which helped me understand I had to wrap my ICMP packet within a IP[v4/v6] packet */ fn create_ipv4_packet<'a>( dest: Ipv4Addr, ttl: u8, ip_packet_buf: &'a mut [u8], icmp_packet_buf: &'a mut [u8], icmp_packet_len: usize, ) -> MutableIpv4Packet<'a> { ...
random
[ { "content": "pub fn clap_desc() -> ArgMatches<'static> {\n\n return App::new(\"pingr\")\n\n .version(\"0.1.0\")\n\n .author(\"Richard Wei <therichardwei@gmail.com>\")\n\n .arg(\n\n Arg::with_name(ARG_ADDRESS)\n\n .index(1)\n\n .takes_value(true)\...
Rust
hive-core/src/lua/http/request.rs
hackerer1c/hive
a98ab9a97836f208646df252175283067a398b7b
use super::body::LuaBody; use super::header_map::LuaHeaderMap; use super::uri::LuaUri; use crate::path::Params; use hyper::header::{HeaderName, HeaderValue}; use hyper::http::request::Parts; use hyper::{Body, HeaderMap, Method, Request}; use mlua::{ExternalError, ExternalResult, FromLua, Lua, Table, UserData}; use std:...
use super::body::LuaBody; use super::header_map::LuaHeaderMap; use super::uri::LuaUri; use crate::path::Params; use hyper::header::{HeaderName, HeaderValue}; use hyper::http::request::Parts; use hyper::{Body, HeaderMap, Method, Request}; use mlua::{ExternalError, ExternalResult, FromLua, Lua, Table, UserData}; use std:...
} impl From<LuaRequest> for Request<Body> { fn from(x: LuaRequest) -> Self { let headers = Rc::try_unwrap(x.headers) .map(RefCell::into_inner) .unwrap_or_else(|x| x.borrow().clone()); let mut builder = Request::builder().method(x.method).uri(x.uri); *builder.headers_mut().unwrap() = headers...
try_into() .to_lua_err()?; let headers_table: Option<Table> = table.raw_get("headers")?; let mut headers = HeaderMap::new(); if let Some(headers_table) = headers_table { for entry in headers_table.pairs::<mlua::String, mlua::Value>() { let (k, v) = entry?; ...
function_block-function_prefix_line
[ { "content": "pub fn create_fn_create_uri(lua: &Lua) -> mlua::Result<Function> {\n\n lua.create_function(|_lua, s: mlua::String| {\n\n Ok(LuaUri(hyper::Uri::try_from(s.as_bytes()).to_lua_err()?))\n\n })\n\n}\n", "file_path": "hive-core/src/lua/http/uri.rs", "rank": 0, "score": 196827.6443182151...
Rust
src/main.rs
wikrsh/raytracing_in_one_weekend_rust
d752ab4cdbc67d951553797792bbd93e51aa6b39
use rand::prelude::random; use raytracing_in_one_weekend::camera::Camera; use raytracing_in_one_weekend::geometry::{Hittable, HittableList, Ray, Sphere}; use raytracing_in_one_weekend::material::{Dielectric, Lambertian, Material, Metal}; use raytracing_in_one_weekend::utils::color::{write_color, Color}; use raytracing_...
use rand::prelude::random; use raytracing_in_one_weekend::camera::Camera; use raytracing_in_one_weekend::geometry::{Hittable, HittableList, Ray, Sphere}; use raytracing_in_one_weekend::material::{Dielectric, Lambertian, Material, Metal}; use raytracing_in_one_weekend::utils::color::{write_color, Color}; use raytracing_...
fn main() -> io::Result<()> { let aspect_ratio = 3.0 / 2.0; let image_width: usize = 1200; let image_height: usize = (image_width as f64 / aspect_ratio) as usize; let samples_per_pixel = 500; let max_depth = 50; let world = random_scene(); let lookfrom = Vec3::new(13.0, 2....
world.add(Box::new(Sphere::new(center, 0.2, &sphere_material))); } } let material1: Rc<Box<dyn Material>> = Rc::new(Box::new(Dielectric::new(1.5))); world.add(Box::new(Sphere::new( Vec3::new(0.0, 1.0, 0.0), 1.0, &material1, ))); let material2: Rc<Box<dyn Material>> ...
function_block-function_prefix_line
[ { "content": "pub fn write_color<T: Write>(\n\n writer: &mut T,\n\n pixel_color: &Color,\n\n samples_per_pixels: i32,\n\n) -> io::Result<()> {\n\n // Divide the color by the number of samples and gamma-correct for gamma=2.0\n\n let scale = 1.0 / samples_per_pixels as f64;\n\n let r = (pixel_co...
Rust
src/client/protocol/keyboard.rs
lummax/wayland-client-rs
5f41fe43d8a287d0b107cc10a2cc5045d2a537b6
#![allow(unused_imports)] use std::{ptr, mem}; use std::ffi::{CStr, CString}; use std::os::unix::io::RawFd; use libc::{c_void, c_int, uint32_t}; use ffi; use client::protocol::{FromPrimitive, GetInterface}; use client::base::Proxy as BaseProxy; use client::base::{FromRawPtr, AsRawPtr, EventQueue}; #[link(name="way...
#![allow(unused_imports)] use std::{ptr, mem}; use std::ffi::{CStr, CString}; use std::os::unix::io::RawFd; use libc::{c_void, c_int, uint32_t}; use ffi; use client::protocol::{FromPrimitive, GetInterface}; use client::base::Proxy as BaseProxy; use client::base::{FromRawPtr, AsRawPtr, EventQueue}; #[link(name="way...
4 => Some(KeyboardEvent::Modifiers), 5 => Some(KeyboardEvent::RepeatInfo), _ => None } } fn from_i32(num: i32) -> Option<Self> { return Self::from_u32(num as u32); } } #[repr(C)] enum KeyboardRequest { Release = 0, _Dummy, } impl FromPrimitive for KeyboardR...
return match num { 0 => Some(KeyboardEvent::Keymap), 1 => Some(KeyboardEvent::Enter), 2 => Some(KeyboardEvent::Leave), 3 => Some(KeyboardEvent::Key),
function_block-random_span
[ { "content": "pub trait AsRawPtr<T> {\n\n fn as_mut_ptr(&mut self) -> *mut T;\n\n}\n", "file_path": "src/client/base/mod.rs", "rank": 2, "score": 128661.67143358607 }, { "content": "pub trait FromPrimitive {\n\n fn from_u32(num: u32) -> Option<Self>;\n\n fn from_i32(num: i32) -> Opt...
Rust
src/lib.rs
norse-rs/norse-billow
cfef6391371ee44137a977a44b564d5920fd2a06
/*! Allocator for SoA data layout. `billow` allows to define a [`BlockLayout`](struct.BlockLayout.html) which encodes a SoA data layout. This layout can be used to subdivide user allocated memory blocks in a tight and aligned fashion. ## Struct of Arrays Struct of Arrays (SoA) describes a deinterleaved memory layout...
/*! Allocator for SoA data layout. `billow` allows to define a [`BlockLayout`](struct.BlockLayout.html) which encodes a SoA data layout. This layout can be used to subdivide user allocated memory blocks in a tight and aligned fashion. ## Struct of Arrays Struct of Arrays (SoA) describes a deinterleaved memory layout...
} pub struct Block { range: Range<usize>, len: usize, slices: Vec<NonNull<u8>>, } impl Block { pub fn range(&self) -> Range<usize> { self.range.clone() } pub fn len(&self) -> usize { self.len } p...
n()); for layout in &self.sub_layouts { assert_eq!(offset % layout.align(), 0); offsets.push(offset); offset += layout.size() * len; } let mut slices = Vec::with_capacity(self.sub_layouts.len()); for slot in self.slot_map.values() { let o...
function_block-function_prefixed
[ { "content": "\n\n<h1 align=\"center\">billow</h1>\n\n<p align=\"center\">\n\n <a href=\"https://github.com/norse-rs\">\n\n <img src=\"https://img.shields.io/badge/project-norse-9cf.svg?style=flat-square\" alt=\"NORSE\">\n\n </a>\n\n <a href=\"LICENSE-MIT\">\n\n <img src=\"https://img.shield...
Rust
noria-server/dataflow/src/state/mk_key.rs
JustusAdam/noria
093fed9d7fec410a3f1876870ab39455d8056b78
use prelude::*; pub(super) trait MakeKey<A> { fn from_row(key: &[usize], row: &[A]) -> Self; fn from_key(key: &[A]) -> Self; } impl<A: Clone> MakeKey<A> for (A, A) { #[inline(always)] fn from_row(key: &[usize], row: &[A]) -> Self { debug_assert_eq!(key.len(), 2); (row[key[0]].clone(), ...
use prelude::*; pub(super) trait MakeKey<A> { fn from_row(key: &[usize], row: &[A]) -> Self; fn from_key(key: &[A]) -> Self; } impl<A: Clone> MakeKey<A> for (A, A) { #[inline(always)] fn from_row(key: &[usize], row: &[A]) -> Self { debug_assert_eq!(key.len(), 2); (row[key[0]].clone(), ...
} impl<A: Clone> MakeKey<A> for (A, A, A, A, A, A) { #[inline(always)] fn from_row(key: &[usize], row: &[A]) -> Self { debug_assert_eq!(key.len(), 6); ( row[key[0]].clone(), row[key[1]].clone(), row[key[2]].clone(), row[key[3]].clone(), ...
fn from_key(key: &[A]) -> Self { debug_assert_eq!(key.len(), 5); ( key[0].clone(), key[1].clone(), key[2].clone(), key[3].clone(), key[4].clone(), ) }
function_block-full_function
[ { "content": "/// Trait for implementing operations that collapse a group of records into a single record.\n\n///\n\n/// Implementors of this trait can be used as nodes in a `flow::FlowGraph` by wrapping them in a\n\n/// `GroupedOperator`.\n\n///\n\n/// At a high level, the operator is expected to work in the f...
Rust
src/config.rs
pckilgore/syngesture
fe30480f7567e802713c0f85c15f6b60a72e4d9e
use crate::events::*; use serde::Deserialize; use std::collections::BTreeMap; use std::ffi::OsStr; use std::path::{Path, PathBuf}; const PREFIX: Option<&'static str> = option_env!("PREFIX"); pub(crate) type Device = String; pub(crate) type GestureMap = BTreeMap<Gesture, Action>; type BoxedError = Box<dyn std::error:...
use crate::events::*; use serde::Deserialize; use std::collections::BTreeMap; use std::ffi::OsStr; use std::path::{Path, PathBuf}; const PREFIX: Option<&'static str> = option_env!("PREFIX"); pub(crate) type Device = String; pub(crate) type GestureMap = BTreeMap<Gesture, Action>; type BoxedError = Box<dyn std::error:...
fn try_load_config_dir(config: &mut Configuration, dir: &Path) { if let Err(e) = load_config_dir(config, &dir) { eprintln!( "Error reading from configuration directory {}: {}", dir.display(), e ); } } fn load_user_config(mut config: &mut Configuration) { ...
h: &Path) { if let Err(e) = load_config_file(config, &path) { eprintln!( "Error loading configuration file at {}: {}", path.display(), e ); } }
function_block-function_prefixed
[ { "content": "fn which(target: &str) -> Option<String> {\n\n let mut cmd = Command::new(\"which\");\n\n cmd.stdout(Stdio::piped());\n\n cmd.stderr(Stdio::null());\n\n cmd.args(&[target]);\n\n let output = match cmd.output() {\n\n Err(_) => {\n\n warn!(\"Failed to find/execute `w...
Rust
src/monadio.rs
TeaEntityLab/fpRust
5381203f823c3b0d0080d7070022379bbd525c02
/*! In this module there're implementations & tests of `MonadIO`. It's inspired by `Rx` & `MonadIO` in `Haskell` */ use std::sync::{Arc, Mutex}; #[cfg(feature = "for_futures")] use super::common::shared_thread_pool; #[cfg(feature = "for_futures")] use crate::futures::task::SpawnExt; #[cfg(feature = "for_futures")] use...
/*! In this module there're implementations & tests of `MonadIO`. It's inspired by `Rx` & `MonadIO` in `Haskell` */ use std::sync::{Arc, Mutex}; #[cfg(feature = "for_futures")] use super::common::shared_thread_pool; #[cfg(feature = "for_futures")] use crate::futures::task::SpawnExt; #[cfg(feature = "for_futures")] use...
pub fn fmap<Z: 'static + Send + Sync + Clone>( &self, func: impl FnMut(Y) -> MonadIO<Z> + Send + Sync + 'static, ) -> MonadIO<Z> { let mut _func = Arc::new(Mutex::new(func)); self.map(move |y: Y| ((_func.lock().unwrap())(y).effect.lock().unwrap())()) } pub fn subscribe(...
pub fn map<Z: 'static + Send + Sync + Clone>( &self, func: impl FnMut(Y) -> Z + Send + Sync + 'static, ) -> MonadIO<Z> { let _func = Arc::new(Mutex::new(func)); let mut _effect = self.effect.clone(); MonadIO::new_with_handlers( move || (_func.lock().unwrap())((_e...
function_block-full_function
[ { "content": "pub trait Handler: Send + Sync + 'static {\n\n /**\n\n Did this `Handler` start?\n\n Return `true` when it did started (no matter it has stopped or not)\n\n\n\n */\n\n fn is_started(&mut self) -> bool;\n\n\n\n /**\n\n Is this `Handler` alive?\n\n Return `true` when it has s...
Rust
xv7-kernel/src/memory/buddy.rs
imtsuki/xv7
edab461a6a7ceab2236e24ca726598107d346467
use crate::config::*; use crate::pretty::Pretty; use bitvec::prelude::*; use boot::PhysAddr; use core::mem; use core::ptr; use lazy_static::lazy_static; use spin::Mutex; pub use x86_64::structures::paging::{FrameAllocator, FrameDeallocator}; use x86_64::structures::paging::{PageSize, PhysFrame, Size4KiB}; pub struct B...
use crate::config::*; use crate::pretty::Pretty; use bitvec::prelude::*; use boot::PhysAddr; use core::mem; use core::ptr; use lazy_static::lazy_static; use spin::Mutex; pub use x86_64::structures::paging::{FrameAllocator, FrameDeallocator}; use x86_64::structures::paging::{PageSize, PhysFrame, Size4KiB}; pub struct B...
} unsafe fn free_frame_specific_order(&mut self, mut frame_index: usize, mut order: u8) { if order >= MAX_ORDER { return; } if self.frames[frame_index].use_status == BuddyFrameStatus::NOTUSED { println!( "BuddyFrameAllocator: free twice on frame...
if align_index_l <= align_index_r { self.free_frame_range_top_down(index_l, align_index_l, order.wrapping_sub(1)); for frame_index in (align_index_l..align_index_r).step_by(1 << order) { self.free_frame_specific_order(frame_index, order); } self.free_frame...
if_condition
[ { "content": "pub fn read(fd: usize, buf: &mut [u8]) -> Result<usize> {\n\n unsafe { syscall3(SYS_READ, fd, buf.as_mut_ptr() as usize, buf.len()) }\n\n}\n\n\n", "file_path": "xv7-usyscall/src/syscall.rs", "rank": 0, "score": 186518.74317084477 }, { "content": "pub fn read(fd: usize, buf: ...
Rust
src/sysctrl/sysctrl_lpdsp32_debug_cfg.rs
ldicocco/rsl10-pac
007871e940fe30f83de1da0f15fd25b052d1f340
#[doc = "Reader of register SYSCTRL_LPDSP32_DEBUG_CFG"] pub type R = crate::R<u32, super::SYSCTRL_LPDSP32_DEBUG_CFG>; #[doc = "Writer for register SYSCTRL_LPDSP32_DEBUG_CFG"] pub type W = crate::W<u32, super::SYSCTRL_LPDSP32_DEBUG_CFG>; #[doc = "Register SYSCTRL_LPDSP32_DEBUG_CFG `reset()`'s with value 0"] impl crate::...
#[doc = "Reader of register SYSCTRL_LPDSP32_DEBUG_CFG"] pub type R = crate::R<u32, super::SYSCTRL_LPDSP32_DEBUG_CFG>; #[doc = "Writer for register SYSCTRL_LPDSP32_DEBUG_CFG"] pub type W = crate::W<u32, super::SYSCTRL_LPDSP32_DEBUG_CFG>; #[doc = "Register SYSCTRL_LPDSP32_DEBUG_CFG `reset()`'s with value 0"] impl crate::...
} #[doc = "Checks if the value of the field is `LPDSP32_DEBUG_DISABLED`"] #[inline(always)] pub fn is_lpdsp32_debug_disabled(&self) -> bool { *self == LPDSP32_DEBUG_ENABLE_A::LPDSP32_DEBUG_DISABLED } #[doc = "Checks if the value of the field is `LPDSP32_DEBUG_ENABLED`"] #[inline(alw...
match self.bits { false => LPDSP32_DEBUG_ENABLE_A::LPDSP32_DEBUG_DISABLED, true => LPDSP32_DEBUG_ENABLE_A::LPDSP32_DEBUG_ENABLED, }
if_condition
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/component/splits/tests/mod.rs
ash2x3zb9cy/livesplit-core
9c5e9c5877f905a518461e3a0586d58d4f840fcc
use super::{ ColumnSettings, ColumnStartWith, ColumnUpdateTrigger, ColumnUpdateWith, Component, Settings, State, }; use crate::{Run, Segment, TimeSpan, Timer, TimingMethod}; pub mod column; #[test] fn zero_visual_split_count_always_shows_all_splits() { let mut run = Run::new(); for _ in 0..32 { ...
use super::{ ColumnSettings, ColumnStartWith, ColumnUpdateTrigger, ColumnUpdateWith, Component, Settings, State, }; use crate::{Run, Segment, TimeSpan, Timer, TimingMethod}; pub mod column; #[test] fn zero_visual_split_count_always_shows_all_splits() { let mut run = Run::new(); for _ in 0..32 { ...
#[test] fn unique_split_indices() { let mut run = Run::new(); run.push_segment(Segment::new("")); run.push_segment(Segment::new("")); run.push_segment(Segment::new("")); let timer = Timer::new(run).unwrap(); let mut component = Component::with_settings(Settings { visual_split_count: 2...
columns: vec![ColumnSettings { start_with: ColumnStartWith::Empty, update_with: ColumnUpdateWith::SegmentTime, update_trigger: ColumnUpdateTrigger::OnStartingSegment, ..Default::default() }], ..Default::default() }); timer.start(); timer...
function_block-function_prefix_line
[ { "content": "pub fn start_run(timer: &mut Timer) {\n\n timer.set_current_timing_method(TimingMethod::GameTime);\n\n timer.start();\n\n timer.initialize_game_time();\n\n timer.pause_game_time();\n\n timer.set_game_time(TimeSpan::zero());\n\n}\n\n\n", "file_path": "src/tests_helper.rs", "r...
Rust
src/many-macros/src/lib.rs
hansl/many-rs
6400eb6e2b30c09ee13a28d20ef16b81a2a7fe05
use inflections::Inflect; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, quote_spanned}; use serde::Deserialize; use serde_tokenstream::from_tokenstream; use syn::spanned::Spanned; use syn::PathArguments::AngleBracketed; use syn::{ AngleBracketedGenericArguments, FnArg, GenericArgument, PatType, Re...
use inflections::Inflect; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, quote_spanned}; use serde::Deserialize; use serde_tokenstream::from_tokenstream; use syn::spanned::Spanned; use syn::PathArguments::AngleBracketed; use syn::{ AngleBracketedGenericArguments, FnArg, GenericArgument, PatType, Re...
= from_tokenstream(attr)?; let many = Ident::new( attrs.many_crate.as_ref().map_or("many", String::as_str), attr.span(), ); let namespace = attrs.namespace; let span = item.span(); let tr: syn::ItemTrait = syn::parse2(item) .map_err(|_| syn::Error::new(span, "`many_module` o...
.iter() .map(|x| x.ident.to_string()) .collect::<Vec<String>>() .join("::") == "std::result::Result" { if let AngleBracketed(AngleBracketedGenericArguments { ref args, .. }) = ...
random
[ { "content": "// TODO: Change the error type\n\npub fn public_key(key: &CoseKey) -> Result<CoseKey, String> {\n\n let params = BTreeMap::from_iter(key.params.clone().into_iter());\n\n match key.alg {\n\n Some(Algorithm::Assigned(coset::iana::Algorithm::EdDSA)) => {\n\n let x = params.get...
Rust
src/types/record.rs
jmackie/fit
8103bfd7435e992d88165a1dd8c55947ab73d7c7
use bits::Bits; use byteorder::{ BigEndian, ByteOrder, LittleEndian, ReadBytesExt, }; use error::{ Error, Result, }; use profile; use std::{ collections::HashMap, convert::TryFrom, }; pub struct Record { pub header: Header, pub content: Message, } impl Record { pub(crate) ...
use bits::Bits; use byteorder::{ BigEndian, ByteOrder, LittleEndian, ReadBytesExt, }; use error::{ Error, Result, }; use profile; use std::{ collections::HashMap, convert::TryFrom, }; pub struct Record { pub header: Header, pub content: Message, } impl Record { pub(crate) ...
} #[derive(Debug, Clone)] pub struct FieldDefinition { num: u8, size: u8, _base_type_num: u8, } impl FieldDefinition { pub(super) fn decode<R: ReadBytesExt>(r: &mut R) -> Result<Self> { let num = r.read_u8().map_err(Error::reading("number"))?; let size = r.read_u...
Architecture::BigEndian => { r.read_u16::<BigEndian>() .map_err(Error::reading("global message number"))? }, }; let nfields = r.read_u8().map_err(Error::reading("number of fields"))?; let mut field_defs = Vec::with_capacity(nfields as...
function_block-function_prefix_line
[ { "content": "/// Attempt to open the types worksheet.\n\npub fn open_sheet<R>(workbook: &mut R) -> Result<Sheet>\n\nwhere\n\n R: calamine::Reader,\n\n{\n\n workbook\n\n .worksheet_range(WORKSHEET_NAME)\n\n .ok_or(Error::missing_sheet(WORKSHEET_NAME))?\n\n .map_err(Error::bad_sheet(WO...
Rust
src/matcher.rs
SpectralOps/service-policy-kit
a1d1b8eab9981b21b87349c5232b4c893a723933
use crate::data::{Cause, HeaderList, Response, Violation}; use fancy_regex::Regex; use std::collections::HashMap; pub struct RegexMatcher { pub kind: String, } impl RegexMatcher { pub fn new(kind: &str) -> Self { Self { kind: kind.to_string(), } } fn match_field( &se...
use crate::data::{Cause, HeaderList, Response, Violation}; use fancy_regex::Regex; use std::collections::HashMap; pub struct RegexMatcher { pub kind: String, } impl RegexMatcher { pub fn new(kind: &str) -> Self { Self { kind: kind.to_string(), } } fn match_field( &se...
fn match_vars( &self, wire_vars: &Option<HashMap<String, String>>, recorded_vars: &Option<HashMap<String, String>>, ) -> Option<Violation> { if let Some(recorded_vars) = recorded_vars { if wire_vars.is_none() { return Some(Violation { ...
fn match_headers( &self, wire_headers: &Option<HashMap<String, HeaderList>>, recorded_headers: &Option<HashMap<String, HeaderList>>, ) -> Option<Violation> { if let Some(recorded_headers) = recorded_headers { if wire_headers.is_none() { return Some(Violati...
function_block-full_function
[ { "content": "pub fn diff_text(expected: &str, actual: &str) -> (String, String, String) {\n\n let expected = format!(\"{:?}\", expected);\n\n let expected = &expected[1..expected.len() - 1];\n\n\n\n let actual = format!(\"{:?}\", actual);\n\n let actual = &actual[1..actual.len() - 1];\n\n\n\n le...
Rust
crates/newport_editor/src/editor.rs
PyroFlareX/newport
ca4b09e98b31d1eefed8a8a545087be8fe28913f
use crate::{ engine, graphics, math, asset, gpu, os, Context, RawInput, DrawState, View, DARK, Layout, Panel, Style, Sizing, ColorStyle, LayoutStyle, Shape, TextStyle, }; use engine::{ Module, Engine, EngineBuilder, InputEvent }; use graphics:...
use crate::{ engine, graphics, math, asset, gpu, os, Context, RawInput, DrawState, View, DARK, Layout, Panel, Style, Sizing, ColorStyle, LayoutStyle, Shape, TextStyle, }; use engine::{ Module, Engine, EngineBuilder, InputEvent }; use graphics:...
ct(); let drag = Rect::from_pos_size(drag.pos() * builder.input().dpi, drag.size() * builder.input().dpi); engine.set_custom_drag(drag); builder.layout(Layout::left_to_right(space), |builder| { let mut layout_style: LayoutStyle = build...
.button("Max").clicked() { engine.maximize(); } if builder.button("Min").clicked() { engine.minimize(); } let drag = builder.layout.available_re
random
[ { "content": "pub fn button_control(id: Id, bounds: Rect, builder: &mut Builder) -> ButtonResponse {\n\n let mut response = ButtonResponse::None;\n\n let is_over = builder.input().mouse_is_over(bounds);\n\n if is_over {\n\n if !builder.is_hovered(id) {\n\n response = ButtonResponse::H...
Rust
common/lib/esp32-c3-dkc02-bsc/src/led.rs
SuGlider/espressif-trainings
cdfb39b7fea35c0aa78e177169d55e4a1cef3379
use std::ptr::{null, null_mut}; use esp_idf_sys::{ c_types::c_void, esp, rmt_config, rmt_config_t, rmt_config_t__bindgen_ty_1, rmt_driver_install, rmt_get_counter_clock, rmt_item32_t, rmt_item32_t__bindgen_ty_1, rmt_item32_t__bindgen_ty_1__bindgen_ty_1, rmt_mode_t_RMT_MODE_TX, rmt_translator_init, rmt_...
use std::ptr::{null, null_mut}; use esp_idf_sys::{ c_types::c_void, esp, rmt_config, rmt_config_t, rmt_config_t__bindgen_ty_1, rmt_driver_install, rmt_get_counter_clock, rmt_item32_t, rmt_item32_t__bindgen_ty_1, rmt_item32_t__bindgen_ty_1__bindgen_ty_1, rmt_mode_t_RMT_MODE_TX, rmt_translator_init, rmt_...
pub fn set_pixel(&mut self, color: RGB8) -> anyhow::Result<()> { let timeout_ms = 1; unsafe { esp!(rmt_write_sample( self.config.channel, &[color.g, color.r, color.b] as *const u8, 3, true, ))?; es...
idle_output_en: true, }; let config = rmt_config_t { rmt_mode: rmt_mode_t_RMT_MODE_TX, channel: 0, gpio_num: 8, clk_div: 2, mem_block_num: 1, flags: 0, __bindgen_anon_1: rmt_config_t__bindgen_ty_1 { tx_c...
function_block-function_prefix_line
[ { "content": "fn process_message(message: EspMqttMessage, led: &mut WS2812RMT) {\n\n match message.details() {\n\n Complete(token) => {\n\n info!(\"{}\", message.topic(token));\n\n let message_data: &[u8] = &message.data();\n\n if let Ok(ColorData::BoardLed(color)) = C...