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/apartment/interactable.rs
TheRealTeamFReSh/MurderUserDungeon
a4a8d6d326cf69bb51e6213fd0235616b85b9cad
use crate::apartment::{animation::BasicAnimationComponent, player::PlayerComponent}; use bevy::prelude::*; use bevy_rapier2d::prelude::*; use serde::Deserialize; use std::collections::HashMap; use super::INTERACTABLE_ICON_Z; const INTERACTABLE_ICON_SPRITE_SCALE: f32 = 2.5; const INTERACTABLE_ICON_Y_OFFSET: f32 = 6.0;...
use crate::apartment::{animation::BasicAnimationComponent, player::PlayerComponent}; use bevy::prelude::*; use bevy_rapier2d::prelude::*; use serde::Deserialize; use std::collections::HashMap; use super::INTERACTABLE_ICON_Z; const INTERACTABLE_ICON_SPRITE_SCALE: f32 = 2.5; const INTERACTABLE_ICON_Y_OFFSET: f32 = 6.0;...
&rapier_config, ); } } else { for interactable_icon_entity in interactable_icon_query.iter() { commands.entity(interactable_icon_entity).despawn(); } } } } } pub struct Inter...
urce, &asset_server, &mut texture_atlases, &rapier_config, ); spawn_interact_icon( "textures/c_key_press.png", PEEPHOLE_ICON_X_OFFSET, &...
random
[ { "content": "/// Spawns an open door (no collider)\n\npub fn spawn_pizza_interactable(\n\n commands: &mut Commands,\n\n interactables_resource: &InteractablesResource,\n\n) {\n\n // spawn door\n\n let interactable_type = InteractableType::Pizza;\n\n let interactable_data = &interactables_resourc...
Rust
crates/github_scbot_database/src/models/review/adapter.rs
sharingcloud/github-scbot
953ba1ae7f3bb06c37084756458a1ddb53c8fa65
use async_trait::async_trait; use diesel::prelude::*; use github_scbot_utils::Mock; use tokio_diesel::AsyncRunQueryDsl; use super::{ReviewCreation, ReviewModel, ReviewUpdate}; use crate::{ models::{PullRequestModel, RepositoryModel}, schema::review, DatabaseError, DbPool, Result, }; #[async_trait] pub tra...
use async_trait::async_trait; use diesel::prelude::*; use github_scbot_utils::Mock; use tokio_diesel::AsyncRunQueryDsl; use super::{ReviewCreation, ReviewModel, ReviewUpdate}; use crate::{ models::{PullRequestModel, RepositoryModel}, schema::review, DatabaseError, DbPool, Result, }; #[async_trait] pub tra...
} pub struct DummyReviewDbAdapter { pub create_response: Mock<ReviewCreation, Result<ReviewModel>>, pub list_response: Mock<(), Result<Vec<ReviewModel>>>, pub list_from_pull_request_id_response: Mock<i32, Result<Vec<ReviewModel>>>, pub get_from_pull_request_and_username_response: ...
async fn update(&self, entry: &mut ReviewModel, update: ReviewUpdate) -> Result<()> { *entry = diesel::update(review::table.filter(review::id.eq(entry.id))) .set(update) .get_result_async(&self.pool) .await .map_err(DatabaseError::from)?; Ok(()) }
function_block-full_function
[ { "content": "/// Run migrations.\n\npub fn run_migrations(pool: &DbPool) -> Result<()> {\n\n embedded_migrations::run(&*pool.get()?)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/github_scbot_database/src/lib.rs", "rank": 0, "score": 262524.15925659804 }, { "content": "fn create_pool...
Rust
tests/support/mod.rs
cookpad/ecamo
8d0cee55402c1501674f920a58f3a0e2fd977877
use ecamo::error::Error; use ecamo::test; use jwt_simple::prelude::ECDSAP256PublicKeyLike; lazy_static::lazy_static! { pub static ref TEST_GIF: Vec<u8> = { let mut path = std::path::PathBuf::from(std::env!("CARGO_MANIFEST_DIR")); path.push("tests/test.gif"); std::fs::read(path).unwrap() ...
use ecamo::error::Error; use ecamo::test; use jwt_simple::prelude::ECDSAP256PublicKeyLike; lazy_static::lazy_static! { pub static ref TEST_GIF: Vec<u8> = { let mut path = std::path::PathBuf::from(std::env!("CARGO_MANIFEST_DIR")); path.push("tests/test.gif"); std::fs::read(path).unwrap() ...
Token::decode_metadata(token)?; let kid = metadata .key_id() .ok_or_else(|| Error::MissingClaimError("kid".to_owned()))?; if kid != "prv" { return Err(Error::UnknownKeyError("kid != prv".to_owned())); } let mut verification = jwt_simple::common::Veri...
ap(); let mut url = reqwest::Url::parse("http://localhost:0").unwrap(); url.set_ip_host(listener.local_addr().unwrap().ip()) .unwrap(); url.set_port(Some(listener.local_addr().unwrap().port())) .unwrap(); let server = ecamo::app::run(test_config.app_config.clone(), listener, true) ...
random
[ { "content": "pub fn encode_url_token(\n\n key: &jwt_simple::algorithms::ES256KeyPair,\n\n payload: crate::token::UrlToken,\n\n iss: &str,\n\n) -> String {\n\n let mut claims = jwt_simple::claims::Claims::with_custom_claims(\n\n payload,\n\n std::time::Duration::new(0, 0).into(),\n\n ...
Rust
src/lib.rs
WanzenBug/rustsync
69517f8bf7d96fa21252cec6dc674a4a6765bd0d
extern crate walkdir; #[macro_use] extern crate derive_error; mod util; pub mod local; pub mod error; pub mod source; pub mod drain; pub use drain::{DrainSyncable, Drain, DrainNotExist, DrainPathStatus}; pub use source::{Source, SourceSyncable, MultiSource}; pub use error::{Error, Result}; use std::pat...
extern crate walkdir; #[macro_use] extern crate derive_error; mod util; pub mod local; pub mod error; pub mod source; pub mod drain; pub use drain::{DrainSyncable, Drain, DrainNotExist, DrainPathStatus}; pub use source::{Source, SourceSyncable, MultiSource}; pub use error::{Error, Result}; use std::pat...
} }
match *self { SyncableInfo::File { components: ref x, .. } | SyncableInfo::Directory(ref x) => x.as_ref() }
if_condition
[ { "content": "pub fn path_to_str(p: &Path) -> Result<&str> {\n\n p.to_str().ok_or_else(|| Error::EncodingError(format!(\"Path {:?} could not be encoded using UTF-8\", p)))\n\n}", "file_path": "src/util.rs", "rank": 3, "score": 140009.68694779312 }, { "content": "pub trait Drain {\n\n t...
Rust
benches/chunks_iter.rs
elrnv/flatk
e9ff70425467ffa132745bb750f418dfad34c920
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; /** * This module benchmarks the performance of iterating over chunks of data vs. reinterpreting an * array as chunked data. */ use rand::distributions::{Distribution, Standard}; use rand::prelude::*; use rayon::prelude::*; static SEED: [u8; ...
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; /** * This module benchmarks the performance of iterating over chunks of data vs. reinterpreting an * array as chunked data. */ use rand::distributions::{Distribution, Standard}; use rand::prelude::*; use rayon::prelude::*; static SEED: [u8; ...
#[inline] fn chunks_exact_par(v: &mut Vec<f64>) { v.par_chunks_exact_mut(3).for_each(|a| { let res = compute(a[0], a[1], a[2]); a[0] = res[0]; a[1] = res[1]; a[2] = res[2]; }); } #[inline] fn chunked3(v: &mut Vec<f64>) { use flatk::Chunked3; for a in Chunked3::from_fla...
3) { let res = compute(a[0], a[1], a[2]); a[0] = res[0]; a[1] = res[1]; a[2] = res[2]; } }
function_block-function_prefixed
[ { "content": "fn chunks_iter(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"Isolate vs Iter Mut\");\n\n\n\n // Make sure all of the functions being benchmarked are doing the same thing.\n\n let mut a = make_random_chunked::<f64>(900_000);\n\n let mut b = make_random_chunked::<f64>(900_...
Rust
src/users.rs
Lavish-Garg/trow
dc24c6b1f9b7cc99a0d78c5ed6e7f926a6a61c04
use argon2::{self, Config}; use bytes::Bytes; use data_encoding::HEXUPPER; use failure; use rand; use rusqlite::NO_PARAMS; use rusqlite::{params, Connection}; use std::env; pub struct User { pub name: String, pub salt: String, pub hash: String, pub active: i32, } const CREDENTIAL_LEN: usize = 512; fn...
use argon2::{self, Config}; use bytes::Bytes; use data_encoding::HEXUPPER; use failure; use rand; use rusqlite::NO_PARAMS; use rusqlite::{params, Connection}; use std::env; pub struct User { pub name: String, pub salt: String, pub hash: String, pub active: i32, } const CREDENTIAL_LEN: usize = 512; fn...
} Err(_) => { assert!(false, "Failed to get hash from password"); } } } #[test] fn test_create_and_get() { env::set_var("DB_FILE", "test.db"); assert!( User::new("spazzy".to_string(), "Password1".to_string()).is_ok(), ...
match verify_password(String::from("Password2"), hash) { Ok(invalid) => assert!(!invalid, "Expected password to fail verification"), _ => {} }
if_condition
[ { "content": "#[cfg(test)]\n\n#[allow(dead_code)]\n\npub fn gen_rand_blob(size: usize) -> Vec<u8> {\n\n let mut rng = rand::thread_rng();\n\n let mut blob = Vec::with_capacity(size);\n\n for _ in 0..size {\n\n blob.push(rng.gen::<u8>());\n\n }\n\n blob\n\n}\n\n\n\n// https://stackoverflow....
Rust
game_plugin/src/food.rs
ramirezmike/not_snake_game
3ba37672e7665ca8303ead4b93bd1437a19a1117
use bevy::prelude::*; use crate::{level, level::Level, Position, EntityType, GameObject, dude, snake}; #[derive(Component)] pub struct Food { pub is_bonus: bool } #[derive(Component)] pub struct FoodInnerMesh { } pub struct FoodEatenEvent(pub Entity, pub bool); #[derive(Component)] pub struct FoodSpawnParticle { ...
use bevy::prelude::*; use crate::{level, level::Level, Position, EntityType, GameObject, dude, snake}; #[derive(Component)] pub struct Food { pub is_bonus: bool } #[derive(Component)] pub struct FoodInnerMesh { } pub struct FoodEatenEvent(pub Entity, pub bool); #[derive(Component)] pub struct FoodSpawnParticle { ...
pub fn update_food( mut commands: Commands, mut foods: Query<(Entity, &Position, &Food)>, mut position_change_event_reader: EventReader<level::PositionChangeEvent>, mut food_eaten_event_writer: EventWriter<FoodEatenEvent>, ) { for position_change in position_change_event_reader.iter() { if l...
function_block-full_function
[ { "content": "pub fn handle_food_eaten(\n\n mut food_eaten_event_reader: EventReader<FoodEatenEvent>,\n\n mut body_part_writer: EventWriter<AddBodyPartEvent>,\n\n snakes: Query<Entity, With<Snake>>,\n\n mut sound_writer: EventWriter<sounds::SoundEvent>,\n\n) {\n\n for eater in food_eaten_event_re...
Rust
src/bin/ross-programmer/bin.rs
linasdev/ross-firmware
edc6bda58c6fbebbe09339484ed0c8c5d722fb81
#![no_std] #![no_main] #![feature(alloc_error_handler)] extern crate alloc; use panic_itm as _; use alloc::rc::Rc; use alloc_cortex_m::CortexMHeap; use core::alloc::Layout; use core::cell::RefCell; use cortex_m_rt::entry; use stm32f1xx_hal_bxcan::pac::{CorePeripherals, Peripherals}; use stm32f1xx_hal_bxcan::prelude:...
#![no_std] #![no_main] #![feature(alloc_error_handler)] extern crate alloc; use panic_itm as _; use alloc::rc::Rc; use alloc_cortex_m::CortexMHeap; use core::alloc::Layout; use core::cell::RefCell; use cortex_m_rt::entry; use stm32f1xx_hal_bxcan::pac::{CorePeripherals, Peripherals}; use stm32f1xx_hal_bxcan::prelude:...
#[alloc_error_handler] fn oom(_: Layout) -> ! { loop {} }
r, "Loaded device information from EEPROM ({:?}).", device_info ); let can_protocol = Rc::new(RefCell::new(setup_can_protocol( config.unwrap_can_config(), &device_info, clocks, gpioa.pa11.into_floating_input(&mut gpioa.crh), gpioa.pa12.into_alternate_push...
function_block-function_prefixed
[]
Rust
src/api/quote/models.rs
SierraSoftworks/bender
b842a95b7efcee126682b40b26fba766dd248001
use crate::models::Quote; use actix_web::{HttpRequest, HttpResponse, Responder, http::header, http::header::Header}; use tracing::Span; #[derive(Serialize, Deserialize)] pub struct QuoteV1 { pub quote: String, pub who: String, } impl Into<Quote> for QuoteV1 { fn into(self) -> Quote { Quote { ...
use crate::models::Quote; use actix_web::{HttpRequest, HttpResponse, Responder, http::header, http::header::Header}; use tracing::Span; #[derive(Serialize, Deserialize)] pub struct QuoteV1 { pub quote: String, pub who: String, } impl Into<Quote> for QuoteV1 { fn into(self) -> Quote { Quote { ...
}} figcaption {{ margin-left: 2em; font-size: 0.8em; font-weight: bold; }} figcaption::before {{ ...
ce_str() == "text/html" { return "text/html" } else if a.item.essence_str() == "text/plain" { return "text/plain" } } "application/json" }).unwrap_or("application/json"); Span::current().record("http.conten...
random
[ { "content": "pub fn configure(cfg: &mut web::ServiceConfig) {\n\n cfg\n\n .service(quote_v1)\n\n .service(quote_by_v1);\n\n}\n\n\n\n#[instrument(err, skip(state), fields(otel.kind = \"internal\"))]\n\n#[get(\"/api/v1/quote\")]\n\npub async fn quote_v1(state: web::Data<GlobalState>) -> Result<m...
Rust
src/providers/cloudflare.rs
RyanSquared/k8s-ares
8c033d3f05125344171eb6738d8061eb4be54de3
use anyhow::{anyhow, Result}; use serde::{Serialize, Deserialize}; use serde_json::value::{Value, Index, from_value}; use reqwest::header; use super::util::{ProviderBackend, SubDomainName, FullDomainName, ZoneDomainName, Record}; use crate::reqwest_client_builder; use crate::xpathable::XPathable; use std::convert::...
use anyhow::{anyhow, Result}; use serde::{Serialize, Deserialize}; use serde_json::value::{Value, Index, from_value}; use reqwest::header; use super::util::{ProviderBackend, SubDomainName, FullDomainName, ZoneDomainName, Record}; use crate::reqwest_client_builder; use crate::xpathable::XPathable; use std::convert::...
async fn _delete_record(&self, domain: &ZoneDomainName, record: &Record) -> Result<()> { unimplemented!(); } }
t .xpath("/result/0/id")? .as_str() .ok_or(anyhow!("Unable to convert zone ID to string"))?; let result: Value = client.get(format!("{}/zones/{}/dns_records?name={}", BASE_URL, zone_id, name).as_str()) .send...
random
[ { "content": "enum Index<'a> {\n\n Number(usize),\n\n String(&'a str),\n\n}\n\n\n", "file_path": "src/xpathable.rs", "rank": 0, "score": 67459.99990452509 }, { "content": "pub trait XPathable<T> where Self: std::fmt::Debug {\n\n fn xpath(&self, path: &str) -> Result<&Self> {\n\n ...
Rust
src/main.rs
jannic/ifwifi
55de9d982b0f5701085e814eaa7d1df24de7b68a
/*- * SPDX-License-Identifier: BSD-2-Clause * * BSD 2-Clause License * * Copyright (c) 2021, Marcelo Araujo <araujobsdport@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * *...
/*- * SPDX-License-Identifier: BSD-2-Clause * * BSD 2-Clause License * * Copyright (c) 2021, Marcelo Araujo <araujobsdport@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * *...
fn is_root() -> bool { match env::var("USER") { Err(e) => { println!("Something went very wrong: {:?}", e); false } Ok(name) => { if name != "root" { println!("{}", "You must be root!".red().bold().blink()); false ...
fn dBm_signal_measure(signal: f32) -> SignalMeasure { if signal >= -30.00 { return SignalMeasure::Maximum; } else if signal < -30.00 && signal >= -50.00 { return SignalMeasure::Excellent; } else if signal < -50.00 && signal >= -60.00 { return SignalMeasure::Good; } else if signal...
function_block-full_function
[ { "content": "## ifwifi - A simple wrapper over nmcli using [wifiscanner](https://crates.io/crates/wifiscanner) made in [rust](https://www.rust-lang.org/).\n\nI felt bothered because I never remember the long and tedious command line to setup my wifi interface. So, I wanted to develop something using rust to si...
Rust
examples/livi-jack.rs
ctsexton/livi-rs
6298c026275df495ccd6b886be4c87c12ef08320
use livi::event::LV2AtomSequence; use log::{debug, error, info, warn}; use std::convert::TryFrom; use structopt::StructOpt; #[derive(StructOpt, Debug)] struct Configuration { #[structopt( long = "plugin-uri", default_value = "http://drobilla.net/plugins/mda/EPiano" )] plugin_uri...
use livi::event::LV2AtomSequence; use log::{debug, error, info, warn}; use std::convert::TryFrom; use structopt::StructOpt; #[derive(StructOpt, Debug)] struct Configuration { #[structopt( long = "plugin-uri", default_value = "http://drobilla.net/plugins/mda/EPiano" )] plugin_uri...
} impl jack::ProcessHandler for Processor { fn process(&mut self, _: &jack::Client, ps: &jack::ProcessScope) -> jack::Control { for (src, dst) in &mut self.event_inputs.iter_mut() { copy_midi_in_to_atom_sequence(src, dst, ps, self.midi_urid) } let ports = livi::PortConnections...
collect(); let cv_outputs: Vec<jack::Port<jack::AudioOut>> = plugin .ports_with_type(livi::PortType::CVOutput) .inspect(|p| info!("Initializing cv output {}.", p.name)) .map(|p| { client .register_port(&format!("CV: {}", p.name), jack::Audi...
function_block-function_prefix_line
[ { "content": "struct PortsDebug<'a> {\n\n plugin: &'a Plugin,\n\n}\n\n\n\nimpl<'a> Debug for PortsDebug<'a> {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n f.debug_list().entries(self.plugin.ports()).finish()\n\n }\n\n}\n\n\n\n/// An instance of a plugin that can p...
Rust
src/main.rs
nicklauri/restaff-acp
635ca91ef7e5fcc27b01aef4bd93182781fcd4c5
#![allow(warnings)] use reqwest::{ blocking::{Client, Response}, header::CONTENT_TYPE, Body, ClientBuilder, }; use std::{ error::Error, io::{self, Write}, }; use structopt::StructOpt; trait ToIoError where Self: Sized + Send + Sync + 'static, Self: Into<Box<(dyn std::error::Error + Send + S...
#![allow(warnings)] use reqwest::{ blocking::{Client, Response}, header::CONTENT_TYPE, Body, ClientBuilder, }; use std::{ error::Error, io::{self, Write}, }; use structopt::StructOpt; trait ToIoError where Self: Sized + Send + Sync + 'static, Self: Into<Box<(dyn std::error::Error + Send + S...
fn main() { let mut args = Args::from_args(); let claim_type = args.claim_type; let api_server = args.api_server.to_string(); let mut is_using_input_token = true; let token = if let Some(token) = args.token { is_using_input_token = false; token } else if let Some(token_file) ...
fn acquire_token(mut args: Args) -> Option<String> { let mut username = args.username.unwrap_or(String::new()); let password = if let Some(pw) = args.password { pw } else if let Some(pf) = args.password_file { let content = match std::fs::read_to_string(&pf) { Ok(s) => s, ...
function_block-full_function
[ { "content": "# restaff-acp — Auto claim points on Restaff newsfeed page.\n\n\n\nBuild instructions:\n\n 1. Install Rust via [rustup](https://rustup.rs/) by downloading from the page or running `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh` if you're on bash.\n\n 2. Get source code Restaff-A...
Rust
src/blocking_display.rs
bread-graphics/breadx-blocking
185f155ed01f0a7929c2a341722f43ff09a7b9d7
use super::spawn_blocking; use breadx::{ display::{AsyncDisplay, Display, DisplayBase, PendingItem, PollOr, RequestInfo, StaticSetup}, event::Event, XID, }; use std::{ future::Future, num::NonZeroU32, pin::Pin, task::{Context, Poll, Waker}, }; pub struct BlockingDisplay<T> { display: ...
use super::spawn_blocking; use breadx::{ display::{AsyncDisplay, Display, DisplayBase, PendingIt
me(display) = self.display.take() { display } else if let Some(wait) = self.wait.take() { let (_, display) = wait.await; display } else { let send_request = self .send_request .take() .unwrap_or_else(|| panic...
em, PollOr, RequestInfo, StaticSetup}, event::Event, XID, }; use std::{ future::Future, num::NonZeroU32, pin::Pin, task::{Context, Poll, Waker}, }; pub struct BlockingDisplay<T> { display: Option<T>, wait: Option<Pin<Box<dyn Future<Output = (breadx::Result, T)> + Send + Sync + 'st...
random
[ { "content": "# breadx-blocking\n\n\n\nProvides something similar to `blocking::Unblock`, but for `breadx` displays.\n\n\n\n## License\n\n\n\nMIT/Apache2 License\n", "file_path": "README.md", "rank": 14, "score": 9907.999013358272 }, { "content": "// MIT/Apache2 License\n\n\n\nuse super::{no...
Rust
server/src/main.rs
AlecGoncharow/project-name-tbd
ca5139424f7f6c34e5f50d096a37f55d799f2d83
use atlas::message::{Complex, GameMessage}; use hermes::tokio; use hermes::Message; use hermes::ServerInterface; use atlas::entity::cube::Cuboid; use atlas::entity::sun::Sun; use atlas::entity::EntityKind; use atlas::Color; use atlas::proc_gen; use proc_gen::color::ColorGenerator; use proc_gen::noise::Perlin; use pro...
use atlas::message::{Complex, GameMessage}; use hermes::tokio; use hermes::Message; use hermes::ServerInterface; use atlas::entity::cube::Cuboid; use atlas::entity::sun::Sun; use atlas::entity::EntityKind; use atlas::Color; use atlas::proc_gen; use proc_gen::color::ColorGenerator; use proc_gen::noise::Perlin; use pro...
#[tokio::main] async fn main() { let mut state = ServerState::new(); let mut server: ServerInterface<GameMessage> = ServerInterface::new(8080); server.start().await; let mut connection_count: usize = 0; generate_cubes(&mut state); loop { let curr_connection_count: usize = se...
new( vec![ (201, 178, 99).into(), (135, 184, 82).into(), (80, 171, 93).into(), (120, 120, 120).into(), (200, 200, 210).into(), ], 0.45, ); let terrain_gen = TerrainGenerator::new(perlin, color_gen); let terrain_size = if cf...
function_block-function_prefixed
[ { "content": "pub fn init_shared(ctx: &mut Context) {\n\n let padding_bgl = ctx\n\n .device\n\n .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {\n\n entries: &[],\n\n label: Some(\"padding for no pass bgl and some draw call bgl\"),\n\n });\n\n let _ha...
Rust
witchcraft-server/src/service/tls.rs
palantir/witchcraft-rust-server
e585ef6108d0d56ba13e4d06157b2db65ce81838
use crate::service::hyper::NewConnection; use crate::service::{Layer, Service, ServiceBuilder}; use conjure_error::Error; use futures_util::ready; use openssl::rand; use openssl::ssl::{ self, AlpnError, Ssl, SslContext, SslFiletype, SslMethod, SslOptions, SslVerifyMode, SslVersion, }; use pin_project::pin_project...
use crate::service::hyper::NewConnection; use crate::service::{Layer, Service, ServiceBuilder}; use conjure_error::Error; use futures_util::ready; use openssl::rand; use openssl::ssl::{ self, AlpnError, Ssl, SslContext, SslFiletype, SslMethod, SslOptions, SslVerifyMode, SslVersion, }; use pin_project::pin_project...
} impl<S> Layer<S> for TlsLayer { type Service = TlsService<S>; fn layer(self, inner: S) -> Self::Service { TlsService { inner: Arc::new(inner), context: self.context, } } } pub struct TlsService<S> { inner: Arc<S>, context: SslContext, } impl<S, R, L> Se...
map_err(Error::internal_safe)?; let ciphersuites = convert_suites(TLS13_CIPHER_SUITES); builder .set_ciphersuites(&ciphersuites) .map_err(Error::internal_safe)?; if config.server().http2() { builder.set_alpn_select_callback(|_, client| { ssl:...
function_block-function_prefix_line
[ { "content": "pub fn init() -> Result<(), Error> {\n\n notify_crash()?;\n\n install_handler()?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "witchcraft-server/src/crash.rs", "rank": 0, "score": 211389.90406764304 }, { "content": "fn with_error(mut tokens: TokenStream, error: Error) -> ...
Rust
src/bounded/spsc.rs
KyleMayes/npnc
8fb7d470752e14f2a8a449bf1df391453b60e3a9
use std::cell::{Cell}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::*; use {ConsumeError, ProduceError, POINTERS}; use buffer::{Buffer}; #[derive(Debug)] pub struct Consumer<T>(Arc<Queue<T>>); impl<T> Consumer<T> { pub fn consume(&self) -> Re...
use std::cell::{Cell}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::*; use {ConsumeError, ProduceError, POINTERS}; use buffer::{Buffer}; #[derive(Debug)] pub struct Consumer<T>(Arc<Queue<T>>); impl<T> Consumer<T> { pub fn consume(&self) -> Re...
unsafe { self.buffer.wrapping_set(write, item); } self.write.store(write.wrapping_add(1), Release); Ok(()) } fn consume(&self) -> Result<T, ConsumeError> { let read = self.read.load(Acquire); if read == self.write_copy.get() { self.write_c...
if write.wrapping_sub(self.read_copy.get()) == self.buffer.size() { self.read_copy.set(self.read.load(Acquire)); if write.wrapping_sub(self.read_copy.get()) == self.buffer.size() { return Err(ProduceError::Full(item)); } }
if_condition
[ { "content": "/// Returns a producer and consumer for an unbounded MPMC lock-free queue.\n\n///\n\n/// The value of `clones` indicates the maximum number of clones allowed of the initial producer\n\n/// and consumer. Both types of clones count towards this total.\n\npub fn channel<T>(clones: usize) -> (Producer...
Rust
client/src/libusb_impl/usbcom.rs
ischeinkman/Nx-Usb
b80a1040f6e389724df835eacddca60bbddf0fe5
use interface::ClientDevice; use libusb::{Context, Device, DeviceDescriptor, DeviceHandle, TransferType}; use nxusb::prefixes::{CommandPrefix, Prefixes}; use std::time::Duration; #[derive(Debug, Copy, Clone)] struct Endpoint { config: u8, iface: u8, setting: u8, address: u8, } #[derive(Debug, Copy, Cl...
use interface::ClientDevice; use libusb::{Context, Device, DeviceDescriptor, DeviceHandle, TransferType}; use nxusb::prefixes::{CommandPrefix, Prefixes}; use std::time::Duration; #[derive(Debug, Copy, Clone)] struct Endpoint { config: u8, iface: u8, setting: u8, address: u8, } #[derive(Debug, Copy, Cl...
nt_desc.direction() == libusb::Direction::In); if read_endpoints.len() != 1 || write_endpoints.len() != 1 { continue; } let read_desc = read_endpoints.pop().unwrap(); let read_endpoint = Endpoint { config : config_de...
fig_desc = match device.config_descriptor(config_idx) { Ok(c) => c, Err(_) => continue, }; println!("Checking config {} -> {:?}", config_idx, config_desc); for interface in config_desc.interfaces() { for interface_desc in interface.descriptors() { ...
random
[ { "content": "#[inline]\n\nfn extract_bytes_u16(inp: u16) -> (u8, u8) {\n\n let first = ((inp & 0xFF00) >> 8) as u8;\n\n let second = (inp & 0x00FF) as u8;\n\n (first, second)\n\n}\n\n\n", "file_path": "src/prefixes.rs", "rank": 2, "score": 189136.56984179196 }, { "content": "#[inli...
Rust
src/lib.rs
depp/simpleargs
c003b7060c0e8ef06426b87c42564fdfb53555f5
#![deny(missing_docs)] pub mod arg; mod error; use std::ffi::OsStr; pub use arg::{ArgString, ParsedArg}; pub use error::{OptionError, UsageError}; pub struct Args<T> { args: T, allow_options: bool, } impl<T> Args<T> { pub fn from(args: T) ->...
#![deny(missing_docs)] pub mod arg; mod error; use std::ffi::OsStr; pub use arg::{ArgString, ParsedArg}; pub use error::{OptionError, UsageError}; pub struct Args<T> { args: T, allow_options: bool, } impl<T> Args<T> { pub fn from(args: T) ->...
} pub fn as_osstr(self) -> Result<&'a OsStr, OptionError> { self.value().map(ArgString::to_osstr) } } #[cfg(test)] mod test { use super::*; use std::str::FromStr; #[derive(Debug, PartialEq, Eq)] struct Parsed { positional: Vec<String>, ...
sult<&'a str, OptionError> { match self.value()?.to_str() { Some(x) => Ok(x), None => Err(OptionError::InvalidUnicode), }
function_block-random_span
[ { "content": "fn is_arg_name(c: char) -> bool {\n\n match c {\n\n 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => true,\n\n _ => false,\n\n }\n\n}\n\n\n\nimpl ArgString for String {\n\n fn parse_arg(self) -> Result<ParsedArg<String>, String> {\n\n let mut chars = self.chars();\n\n...
Rust
crates/unbase/src/entity.rs
dnorman/pandaemon
4cfdd26859333ea0b1187ce6ce85fc647a04ad16
use crate::{ context::Context, error::{ RetrieveError, WriteError, }, head::Head, slab::{ EdgeSet, EntityId, EntityType, MemoBody, MemoId, RelationSet, SlabHandle, SlotId, }, }; use futures::channel::mpsc; use std::...
use crate::{ context::Context, error::{ RetrieveError, WriteError, }, head::Head, slab::{ EdgeSet, EntityId, EntityType, MemoBody, MemoId, RelationSet, SlabHandle, SlotId, }, }; use futures::channel::mpsc; use std::...
} impl fmt::Debug for Entity { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Entity") .field("entity_id", &self.id) .field("head", &self.head) .finish() } } impl Drop for Entity { fn drop(&mut self) { } }...
d> { let (mut tx, rx) = mpsc::channel(1000); tx.try_send(self.head.clone()) .expect("Haven't implemented queue backpressure yet"); self.context.slab.observe_entity(self.id, tx); rx }
function_block-function_prefixed
[ { "content": "#[wasm_bindgen]\n\npub fn greet(name: &str) {\n\n info!(\"Hello, {}!\", name)\n\n // use web_sys::console;\n\n // console::log_1(&JsValue::from_str(format!(\"Hello, {}!\", name).as_str()));\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n fn it_works() {\n\n asse...
Rust
src/models/comment.rs
librewiki/librebbs
dc28c6ce4d2df94f5e4dfc891a4ecb43812d08fe
use crate::models::Topic; use crate::schema::comments; use anyhow::Result; use chrono::{DateTime, NaiveDateTime, Utc}; use diesel::prelude::*; use std::convert::TryInto; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; #[derive(Serialize, Deserialize, Queryable, Identifiable, AsChangeset, Debug)] pub struct Comment { p...
use crate::models::Topic; use crate::schema::comments; use anyhow::Result; use chrono::{DateTime, NaiveDateTime, Utc}; use diesel::prelude::*; use std::convert::TryInto; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; #[derive(Serialize, Deserialize, Queryable, Identifiable, AsChangeset, Debug)] pub struct Comment { p...
} #[cfg(test)] mod tests { use super::*; use crate::db::create_connection; use crate::models::Board; #[test] fn test_topic() { use std::str::FromStr; let conn = create_connection(); conn.test_transaction::<_, diesel::result::Error, _>(|| { let boards = Board::g...
else { let arr: &[u8; 4] = x[0..4].try_into().unwrap(); Ipv4Addr::from(*arr).to_string() } }
function_block-function_prefix_line
[ { "content": "fn decode(token: &str) -> Result<Claims, DecodeError> {\n\n let mut validation = Validation::new(Algorithm::RS256);\n\n validation.validate_exp = false;\n\n validation.set_audience(&[env::var(\"OAUTH_CLIENT_ID\").expect(\"OAUTH_CLIENT_ID must be set\")]);\n\n let token_data = jsonwebto...
Rust
tests/src/income_cell_type/income_create.rs
zhiiker/das-contracts
7717330047772f51855d79bd67b77dede34d0bf8
use crate::util::{constants::*, error::Error, template_generator::*, template_parser::TemplateParser}; use ckb_testtool::context::Context; use super::common::init; #[test] fn gen_income_create() { let mut template = init("create_income"); template.push_signall_cell( "0x0000000000000000000000000000000...
use crate::util::{constants::*, error::Error, template_generator::*, template_parser::TemplateParser}; use ckb_testtool::context::Context; use super::common::init; #[test]
test_with_template!(test_income_create, "income_create.json"); challenge_with_generator!( challenge_income_create_capacity_not_equal, Error::IncomeCellCapacityError, || { let mut template = init("create_income"); template.push_signall_cell( "0x00000000000000000000000000000000...
fn gen_income_create() { let mut template = init("create_income"); template.push_signall_cell( "0x0000000000000000000000000000000000000000", 20_000_000_000, Source::Input, ); let income_records = vec![IncomeRecordParam { belong_to: "0x00000000000000000000000000000000000...
function_block-full_function
[ { "content": "#![allow(dead_code)]\n\n\n\nuse std::env;\n\nuse std::fs;\n\nuse std::path::PathBuf;\n\nuse std::str::FromStr;\n\n\n\nuse ckb_tool::ckb_types::bytes;\n\n\n\n#[cfg(test)]\n\n#[macro_use]\n\nmod util;\n\n\n\n#[cfg(test)]\n\nmod account_cell_type;\n\n#[cfg(test)]\n\nmod account_sale_cell_type;\n\n#[c...
Rust
crates/runtime/src/types.rs
yutiansut/tensorbase
627b93e4a5b0673db7996454c7111ac30ae2a2e0
use std::{convert::TryFrom, fmt::Debug, intrinsics::copy_nonoverlapping, slice}; use arrow::{array::LargeStringArray, datatypes::DataType, record_batch::RecordBatch}; use base::{codec::encode_varint64, datetimes::TimeZoneId}; use bytes::{Buf, BufMut, BytesMut}; use client::prelude::{types::SqlType, ServerBlock}; use ...
use std::{convert::TryFrom, fmt::Debug, intrinsics::copy_nonoverlapping, slice}; use arrow::{array::LargeStringArray, datatypes::DataType, record_batch::RecordBatch}; use base::{codec::encode_varint64, datetimes::TimeZoneId}; use bytes::{Buf, BufMut, BytesMut}; use client::prelude::{types::SqlType, ServerBlock}; use ...
}; blk.columns.push(BaseColumn { name, data: BaseChunk { btype, size: col.len(), data, null_map, offset_map: offsets, ...
if fields[i].is_nullable() { BaseDataBlock::null_map_from_data(&btype, offsets.as_ref(), &data) } else { None }
if_condition
[ { "content": "#[inline(always)]\n\npub fn encode_varint64(mut value: u64, buf: &mut [u8]) -> usize {\n\n fn iter(value: &mut u64, byte: &mut u8) -> bool {\n\n if (*value & !0x7F) > 0 {\n\n *byte = ((*value & 0x7F) | 0x80) as u8;\n\n *value >>= 7;\n\n true\n\n } ...
Rust
src/mempool_elem.rs
ideasman42/block-array-cow
b4659061937c454680435f14419fc10f51ec7d0b
#![allow(dead_code)] use std::ptr; use plain_ptr::{ PtrConst, PtrMut, }; pub trait MemPoolElemUtils { fn default_chunk_size() -> usize; fn free_ptr_get(&self) -> *mut Self; fn free_ptr_set(&mut self, ptr: *mut Self); fn free_ptr_test(&self) -> bool; } pub trait MemElem: MemPoolEle...
#![allow(dead_code)] use std::ptr; use plain_ptr::{ PtrConst, PtrMut, }; pub trait MemPoolElemUtils { fn default_chunk_size() -> usize; fn free_ptr_get(&self) -> *mut Self; fn free_ptr_set(&mut self, ptr: *mut Self); fn free_ptr_test(&self) -> bool; } pub trait MemElem: MemPoolEle...
ng_sub(pos_max), count_final)), ); } } pub fn iter_mut(&mut self) -> MemPoolIterMut<TElem> { let pos = self.iter_find_first(); MemPoolIterMut { pool: self, pos: pos, } } pub fn iter(&self) -> MemPoolIterConst<TElem> { ...
() && pos.data_index < self.chunk_size); return unsafe { self.chunks.get_unchecked_mut( pos.chunk_index).data.get_unchecked_mut( pos.data_index) as *mut TElem }; } fn iter_impl_elem_from_index_const(&self, pos: &IterPos) -> *const TElem { ...
random
[ { "content": "#[allow(non_snake_case)]\n\npub fn PtrConst<T>(ptr: *const T) -> PtrConst<T> {\n\n PtrConst::new(ptr)\n\n}\n", "file_path": "src/plain_ptr.rs", "rank": 1, "score": 142471.32149988235 }, { "content": "#[allow(non_snake_case)]\n\npub fn PtrMut<T>(ptr: *mut T) -> PtrMut<T> {\n\...
Rust
packages/agent/src/api_client.rs
playit-cloud/playit-agent
18e692e513437c792c4b56977b72db33342a22c4
use std::net::{SocketAddr, SocketAddrV6}; use hyper::{Body, header, Method, Request}; use hyper::body::Buf; use hyper::client::HttpConnector; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; use serde::{Deserialize, Serialize}; use tracing::instrument::WithSubscriber; use agent_common::{AgentRegistered, Tun...
use std::net::{SocketAddr, SocketAddrV6}; use hyper::{Body, header, Method, Request}; use hyper::body::Buf; use hyper::client::HttpConnector; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; use serde::{Deserialize, Serialize}; use tracing::instrument::WithSubscriber; use agent_common::{AgentRegistered, Tun...
} } } #[derive(Debug)] pub enum ApiError { HttpError(u16, String), ParseError(serde_json::Error), RequestError(hyper::Error), UnexpectedResponse(AgentApiResponse), } impl From<hyper::Error> for ApiError { fn from(error: hyper::Error) -> Self { ApiError::RequestError(error) } }...
r() .uri(&self.api_base) .method(Method::POST); if let Some(secret) = &self.agent_secret { builder = builder.header( header::AUTHORIZATION, format!("agent-key {}", secret), ); } let request = builder .b...
random
[ { "content": "struct QueuedRequest {\n\n resend_at: u64,\n\n attempt: u64,\n\n request: RpcMessage<SignedRpcRequest<TunnelRequest>>,\n\n handler: OneshotSender<TunnelResponse>,\n\n}\n\n\n\nimpl TunnelClient {\n\n pub async fn new(\n\n api: ApiClient,\n\n new_client_tx: Sender<NewCli...
Rust
src/input.rs
aengusmcmillin/Gouda
4aed65c94ad4147372d71c08622dacf01f5eac4e
#[derive(Default, Clone)] pub struct GameButtonState { pub half_transition_count: i32, pub ended_down: bool, } #[derive(Enum, Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum LetterKeys { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } use self::LetterKeys::*; use...
#[derive(Default, Clone)] pub struct GameButtonState { pub half_transition_count: i32, pub ended_down: bool, } #[derive(Enum, Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum LetterKeys { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, } use self::LetterKeys::*; use...
}
pub fn from(old_input: &GameInput) -> GameInput { GameInput { seconds_to_advance_over_update: old_input.seconds_to_advance_over_update, mouse: Mouse::from(&old_input.mouse), keyboard: KeyboardInput::from(&old_input.keyboard), controllers: [ GameCon...
function_block-full_function
[ { "content": "pub fn win32_process_keyboard(keyboard: &mut KeyboardInput, vkcode: i32, was_down: bool, is_down: bool) {\n\n if was_down != is_down {\n\n if vkcode == VK_UP {\n\n win32_process_keyboard_message(\n\n &mut keyboard.special_keys[SpecialKeys::UpArrow],\n\n ...
Rust
src/eve.rs
nickmass/mass-raytrace
3ddeaa42937cc8e2c8171df34a55395bf1eab687
use std::path::Path; use std::sync::Arc; use crate::material::{Background, CubeMap, Lambertian, Material, Mix, Specular}; use crate::math::{V2, V3}; use crate::obj_loader::ObjGroupFilter; use crate::texture::{BlendMode, TextureBlend}; use crate::texture::{SolidColor, Surface, Texture, WrapMode, YCbCrTexture}; pub str...
use std::path::Path; use std::sync::Arc; use crate::material::{Background, CubeMap, Lambertian, Material, Mix, Specular}; use crate::math::{V2, V3}; use crate::obj_loader::ObjGroupFilter; use crate::texture::{BlendMode, TextureBlend}; use crate::texture::{SolidColor, Surface, Texture, WrapMode, YCbCrTexture}; pub str...
models/mf4_t1/MF4_TShape1.obj"; (material, model) } Hull::Astero => { let material = EveMaterial::new( "models/soef1_t1/soef1_t1_no.png", "models/soef1_t1/soef1_t1_ar.png", "models/soef1_t1/soef1_t1_pmdg.png", EveMat...
d_png(no, WrapMode::Repeat)?; let albedo_roughness = Texture::load_png(ar, WrapMode::Repeat)?; let pmdg = Texture::load_png(pmdg, WrapMode::Repeat)?; let inner = InnerEveMaterial { normal_occlusion, albedo_roughness, pmdg, colors, }; ...
random
[ { "content": "pub trait Surface: Send + Sync {\n\n fn width(&self) -> u32;\n\n fn height(&self) -> u32;\n\n\n\n fn get_f(&self, index: V2) -> V4;\n\n}\n\n\n\npub type SharedTexture = Arc<Texture>;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Texture {\n\n width: u32,\n\n height: u32,\n\n pixel...
Rust
plugins/c8y_configuration_plugin/src/main.rs
initard/thin-edge.io
30efb357aca2f6fd446336713629ab1d6f0d38dc
mod config; mod download; mod error; mod upload; use crate::config::PluginConfig; use crate::download::handle_config_download_request; use crate::upload::handle_config_upload_request; use anyhow::Result; use c8y_api::http_proxy::{C8YHttpProxy, JwtAuthHttpProxy}; use c8y_smartrest::smartrest_deserializer::{ SmartRe...
mod config; mod download; mod error; mod upload; use crate::config::PluginConfig; use crate::download::handle_config_download_request; use crate::upload::handle_config_upload_request; use anyhow::Result; use c8y_api::http_proxy::{C8YHttpProxy, JwtAuthHttpProxy}; use c8y_smartrest::smartrest_deserializer::{ SmartRe...
async fn run( mqtt_port: u16, http_client: &mut impl C8YHttpProxy, tmp_dir: PathBuf, config_file_path: &Path, ) -> Result<(), anyhow::Error> { let mut plugin_config = PluginConfig::new(config_file_path); let mut mqtt_client = create_mqtt_client(mqtt_port).await?; let msg = plugin_co...
let tedge_config_location = tedge_config::TEdgeConfigLocation::from_custom_root(config_plugin_opt.config_dir); let config_repository = tedge_config::TEdgeConfigRepository::new(tedge_config_location.clone()); let tedge_config = config_repository.load()?; let mqtt_port = tedge_config.query(MqttPortSe...
function_block-function_prefix_line
[ { "content": "pub fn get_file_change_notification_message(file_path: &str, config_type: &str) -> Message {\n\n let notification = json!({ \"path\": file_path }).to_string();\n\n let topic = Topic::new(format!(\"{CONFIG_CHANGE_TOPIC}/{config_type}\").as_str())\n\n .unwrap_or_else(|_err| {\n\n ...
Rust
src/main.rs
Kixunil/eclair-rpc-proxy
ee231388c9d105ac7b292f798f75fb8e0b576357
extern crate serde; extern crate serde_derive; extern crate serde_json; extern crate hyper; extern crate futures; #[macro_use] extern crate enum_future; extern crate tokio_core; #[macro_use] extern crate slog; extern crate slog_term; extern crate slog_async; #[macro_use] extern crate configure_me; include_config!(); ...
extern crate serde; extern crate serde_derive; extern crate serde_json; extern crate hyper; extern crate futures; #[macro_use] extern crate enum_future; extern crate tokio_core; #[macro_use] extern crate slog; extern crate slog_term; extern crate slog_async; #[macro_use] extern crate configure_me; include_config!(); ...
fn send_internal_error() -> impl Future<Item=Response, Error=hyper::Error> { const INTERNAL_ERROR: &str = "{ \"error\" : \"internal server error\" }"; futures::future::ok(Response::new() .with_status(StatusCode::InternalServerError) .with_header(ContentL...
fn send_unauthorized() -> impl Future<Item=Response, Error=hyper::Error> { const UNAUTHORIZED: &str = "{ \"error\" : \"unauthorized\" }"; futures::future::ok(Response::new() .with_status(StatusCode::Unauthorized) .with_header(ContentLength(UNAUTHORIZED.len() as u6...
function_block-full_function
[ { "content": "fn main() {\n\n if let Some(man_dir) = std::env::var_os(\"MAN_DIR\") {\n\n let mut man_dir: std::path::PathBuf = man_dir.into();\n\n std::fs::create_dir_all(&man_dir).expect(\"Failed to create directory target/man\");\n\n man_dir.push(\"btc_rpc_proxy.1\");\n\n config...
Rust
src/status.rs
serbe/rpc
1bd77c2a4b2ee5cd16b270df502ce6c5212261b4
use std::{convert::TryFrom, fmt, str::FromStr}; use crate::{Error, Version}; #[derive(PartialEq, Debug, Clone)] pub struct Status { version: Version, code: StatusCode, reason: String, } impl Status { pub fn status_code(&self) -> StatusCode { self.code } pub fn version(&self) -> Versi...
use std::{convert::TryFrom, fmt, str::FromStr}; use crate::{Error, Version}; #[derive(PartialEq, Debug, Clone)] pub struct Status { version: Version, code: StatusCode, reason: String, } impl Status { pub fn status_code(&self) -> StatusCode { self.code } pub fn version(&self) -> Versi...
i in (0..1000).filter(|&i| i < 200 || i >= 300) { assert!(!StatusCode(i).is_success()) } } #[test] fn status_code_redirect() { for i in 300..400 { assert!(StatusCode(i).is_redirect()) } for i in (0..1000).filter(|&i| i < 300 || i >= 400) { ...
416 => Some("Range Not Satisfiable"), 417 => Some("Expectation Failed"), 418 => Some("I'm a teapot"), 421 => Some("Misdirected Request"), 422 => Some("Unprocessable Entity"), 423 => Some("Locked"), 424 => Some("Failed Dependency"), ...
random
[ { "content": "pub fn get<U: IntoUrl>(url: U) -> Result<ClientBuilder, Error> {\n\n Ok(ClientBuilder::new().get(&url.into_url()?))\n\n}\n\n\n", "file_path": "src/client_builder.rs", "rank": 0, "score": 96700.08505598833 }, { "content": "pub fn delete<U: IntoUrl>(url: U) -> Result<ClientBui...
Rust
phasicj/agent/conf/src/test.rs
dwtj/phasicj
72ab8a168b526c62ee6448dffd14e6221924f49f
#![cfg(test)] mod test_parser { use phasicj_agent_conf::parser::Rule; fn parse_flat_rule_vec(s: &str) -> Vec<Rule> { use phasicj_agent_conf::parser::PjAgentConfParser; use pest::Parser; let pairs = PjAgentConfParser::parse(Rule::agent_options_list, s).unwrap_or_else(|e| panic!("{}", e...
#![cfg(test)] mod test_parser { use phasicj_agent_conf::parser::Rule; fn parse_flat_rule_vec(s: &str) -> Vec<Rule> { use phasicj_agent_conf::parser::PjAgentConfParser; use pest::Parser; let pairs = PjAgentConfParser::parse(Rule::agent_options_list, s).unwrap_or_else(|e| panic!("{}", e...
assert_eq!(conf.debug_dump_classes_before_instr, false); } #[test] fn test_phasicj_exec_option() { let path = "My Path/to/phasicj-exec"; let to_parse = format!(r#"phasicj_exec="{}""#, path); let conf = PjAgentConf::new_from_agent_options_list_str(&to_parse); assert_...
let conf = PjAgentConf::new_from_agent_options_list_str( "debug_dump_classes_before_instr=true,debug_dump_classes_before_instr=false" );
assignment_statement
[ { "content": "fn svm_test_class_data() -> Vec<u8> {\n\n let mut vec = vec!(0; SVM_TEST_CLASS_DATA.len());\n\n vec[..].copy_from_slice(SVM_TEST_CLASS_DATA);\n\n return vec;\n\n}\n\n\n", "file_path": "phasicj/agent/experimental/svm/rust/test.rs", "rank": 0, "score": 162413.36739967906 }, ...
Rust
src/framework/mod.rs
noituri/poise
45f27a86990a9443077c0cb457bd7600af625b3b
mod dispatch; mod builder; pub use builder::*; use crate::{serenity_prelude as serenity, BoxFuture}; pub use dispatch::dispatch_message; pub struct Framework<U, E> { user_data: once_cell::sync::OnceCell<U>, options: crate::FrameworkOptions<U, E>, application_id: serenity::ApplicationId, ...
mod dispatch; mod builder; pub use builder::*; use crate::{serenity_prelude as serenity, BoxFuture}; pub use dispatch::dispatch_message; pub struct Framework<U, E> { user_data: once_cell::sync::OnceCell<U>, options: crate::FrameworkOptions<U, E>, application_id: serenity::ApplicationId, ...
} }) } let mut map = CommandMap::new(); for command in &self.options().prefix_options.commands { get_command(&mut map, &command.command.id).prefix = Some(command); } for command in &self.options().application_options.commands { match ...
mandDefinitionRef<'s, U, E>>; fn get_command<'a, 's, U, E>( map: &'a mut CommandMap<'s, U, E>, id: &std::sync::Arc<crate::CommandId>, ) -> &'a mut crate::CommandDefinitionRef<'s, U, E> { map.get_or_insert_with(std::sync::Arc::as_ptr(id) as _, || { cra...
function_block-random_span
[ { "content": "type BoxErrorSendSync = Box<dyn std::error::Error + Send + Sync>;\n\n\n\n/// An error handler that prints the error into the console and also into the Discord chat.\n\n/// If the user invoked the command wrong\n\n/// (i.e. an [`crate::ArgumentParseError`]), the command help is displayed and the us...
Rust
src/main.rs
sethm/we32dis
8595ed5bc2d62640219eb37f251d350c8bc6ba4f
extern crate clap; #[macro_use] extern crate bitflags; use std::error::Error; use std::fs::File; use std::io::Read; use std::path::Path; use std::vec::Vec; use clap::{Arg, App}; use crate::coff::FileContainer; mod errors; mod coff; mod decoder; enum FileAction { Header, Info, Symbols, Disassemble...
extern crate clap; #[macro_use] extern crate bitflags; use std::error::Error; use std::fs::File; use std::io::Read; use std::path::Path; use std::vec::Vec; use clap::{Arg, App}; use crate::coff::FileContainer; mod errors; mod coff; mod decoder; enum FileAction { Header, Info, Symbols, Disassemble...
fn main() { let matches = App::new("WE32100 Disassembler") .version("0.2") .author("Seth J. Morabito <web@loomcom.com>") .about("WE32100 Disassembler") .arg(Arg::with_name("SECTION") .value_name("SECTION") .short("n") .long("named section") ...
if let Err(e) = container.dump_relocation_table(sec_num) { println!("Error: Couldn't dump relocation table: {:?}", e); } if let Err(e) = container.dump_section_data(sec_num) { println!("Error: Couldn't dump section ...
function_block-function_prefix_line
[ { "content": "fn buf_to_str(buf: &[u8]) -> Result<&str, std::str::Utf8Error> {\n\n let nul = buf.iter().position( |&c| c == b'\\0').unwrap_or(buf.len());\n\n str::from_utf8(&buf[0..nul])\n\n}\n\n\n\nimpl FileHeader {\n\n ///\n\n /// Read a FileHeader from the current cursor position.\n\n ///\n\n\...
Rust
src/cli/editor.rs
HallerPatrick/civa
8c639a200fa26f480e961393ec180089638d7f9b
use std::borrow::Cow::{self, Borrowed, Owned}; use std::cell::RefCell; use crate::config::ContextManager; use log::info; use rcalc::{Calculator, RuntimeItem, Value}; use rustyline::completion::{Completer, FilenameCompleter, Pair}; use rustyline::config::OutputStreamType; use rustyline::error::ReadlineError; use rustyl...
use std::borrow::Cow::{self, Borrowed, Owned}; use std::cell::RefCell; use crate::config::ContextManager; use log::info; use rcalc::{Calculator, RuntimeItem, Value}; use rustyline::completion::{Completer, FilenameCompleter, Pair}; use rustyline::config::OutputStreamType; use rustyline::error::ReadlineError; use rustyl...
ccesfully"); } rl }
s: usize) -> Cow<'l, str> { self.highlighter.highlight(line, pos) } fn highlight_char(&self, line: &str, pos: usize) -> bool { self.highlighter.highlight_char(line, pos) } } impl Validator for MyHelper { fn validate( &self, ctx: &mut validate::ValidationContext, ) -...
random
[ { "content": "pub fn handle_commands(command_string: &str, ctx: &ContextManager) -> Vec<Command> {\n\n let mut commands: Vec<Command> = Vec::new();\n\n\n\n // Only splits sequential commands, not pipes\n\n let raw_commands: CommandTokenCollection = split_commands(command_string);\n\n\n\n for mut com...
Rust
src/game_logic/piece.rs
heartlabs/megachess
ffa8475ec70d9033feb1d86a30d5a96cd683dffa
use crate::game_logic::ranges::*; use nanoserde::{DeBin, SerBin}; use std::fmt::Debug; #[derive(Debug, Copy, Clone, PartialEq, SerBin, DeBin)] pub enum EffectKind { Protection, } impl Move { pub fn new(direction: Direction, steps: u8) -> Move { Move { range: Range::new(direction, steps), ...
use crate::game_logic::ranges::*; use nanoserde::{DeBin, SerBin}; use std::fmt::Debug; #[derive(Debug, Copy, Clone, PartialEq, SerBin, DeBin)] pub enum EffectKind { Protection, } impl Move { pub fn new(direction: Direction, steps: u8) -> Move { Move { range: Range::new(direction, steps), ...
pub fn can_move(&self) -> bool { match &self.strategy { ExhaustionStrategy::Special => false, ExhaustionStrategy::Move | ExhaustionStrategy::Both => !self.moved, ExhaustionStrategy::Either => !self.moved && !self.used_special, } } pub fn can_attack(&sel...
pub(crate) fn new_rested(strategy: ExhaustionStrategy) -> Exhaustion { Exhaustion { moved: false, used_special: false, strategy, } }
function_block-full_function
[ { "content": "pub fn join_match(client: &mut ApiClient) {\n\n if let Some(error) = client.error().clone() {\n\n panic!(\"{}\", error)\n\n } else {\n\n let token = client.matchmaker_token.clone().unwrap();\n\n info!(\"Joining match with token {}\", token);\n\n client.socket_join...
Rust
diny_core/src/backend/wrapper/macros.rs
dbdeviant/diny
b355eb96000c3555f9c0d94fb907f82d5d212701
macro_rules! wrapper_encode_def { () => { pub struct Encoder<F, T>(T::Encoder::<F>) where F: backend::FormatEncode, T: backend::Encodable, ; }; } macro_rules! wrapper_encode_impl_deref { () => { impl<F, T> backend::Encode for Encoder<F, T> wh...
macro_rules! wrapper_encode_def { () => { pub struct Encoder<F, T>(T::Encoder::<F>) where F: backend::FormatEncode, T: backend::Encodable, ; }; } macro_rules! wrapper_encode_impl_deref { () => { impl<F, T> backend::Encode for Encoder<F, T> wh...
}; } macro_rules! wrapper_async_deserialize_impl { () => { impl<T> backend::AsyncDeserialize for Data<T> where T: backend::AsyncDeserialize, { type Future<'r, F, R> where F: 'r + backend::FormatDeserialize, R: 'r + io::...
ere W: io::AsyncWrite + Unpin, { self.0.poll_encode(format, writer, data, cx) } } }; } macro_rules! wrapper_encodable_impl { () => { impl<T> backend::Encodable for Data<T> where T: backend::Encodable, { ...
random
[ { "content": "/// Creates a new [Serializer] from the specified [format](backend::FormatEncode)\n\n/// and [writer](io::AsyncWrite)\n\npub fn serializer<F, W>(format: F, writer: W) -> Serializer<F, W> {\n\n Serializer::new(format, writer)\n\n}\n\n\n\n/// A wrapper type around a specific [format](backend::For...
Rust
src/main.rs
zhangyuan/aws-auth
e030c76a237d4cd4cb8fc250962490b0dd524246
use std::path::Path; use url::Url; pub mod aws; pub mod http_client; pub mod okta; pub mod saml; pub mod ui; use aws_sdk_sts::{Credentials}; use aws_config::meta::region::RegionProviderChain; use okta::Okta; use ui::{StdUI, UI}; use std::env; #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::i...
use std::path::Path; use url::Url; pub mod aws; pub mod http_client; pub mod okta; pub mod saml; pub mod ui; use aws_sdk_sts::{Credentials}; use aws_config::meta::region::RegionProviderChain; use okta::Okta; use ui::{StdUI, UI}; use std::env; #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::i...
fn load_settings() -> anyhow::Result<config::Config> { let local_config_path = Path::new(".aws-auth.toml").to_path_buf(); let home = std::env::var("HOME").unwrap(); let global_config_path = Path::new(&home).join(".aws-auth.toml"); let config_path = if local_config_path.is_file() { local_conf...
t, base_uri: &identify_base_uri, app_link: &app_link, }; let saml_assertion = okta.get_saml_assertion().await?; let roles = saml_assertion.extract_roles()?; let selected_role = stdui.get_aws_role(&roles); let credentials = aws::get_credentials_by_assume_role_with_saml(aws_...
function_block-function_prefixed
[ { "content": "pub fn lookup_credentials(\n\n credentials_config: &mut config::Config,\n\n) -> Option<aws_sdk_sts::Credentials> {\n\n let maybe_credentials = if let Ok(default_credentials) = credentials_config.get_table(\"default\")\n\n {\n\n if default_credentials.contains_key(\"aws_access_key_i...
Rust
src/route.rs
auula/poem
b3d15f83e994389b97ccd614d9361d48e3730002
use std::{collections::HashMap, sync::Arc}; use crate::{ error::ErrorNotFound, http::Method, route_recognizer::Router, Endpoint, Error, Request, Response, Result, }; #[derive(Default)] pub struct Route { router: Router<Box<dyn Endpoint>>, } impl Route { ...
use std::{collections::HashMap, sync::Arc}; use crate::{ error::ErrorNotFound, http::Method, route_recognizer::Router, Endpoint, Error, Request, Response, Result, }; #[derive(Default)] pub struct Route { router: Router<Box<dyn Endpoint>>, } impl Route { ...
tp::uri::Builder::new() .path_and_query("/") .build() .unwrap(), ); self.0.call(req).await } } assert!( path.find('*').is_none(), "wildcards are not allowed in the...
lue) .build() .unwrap(), ); self.0.call(req).await } } struct Root<T>(T); #[async_trait::async_trait] impl<E: Endpoint> Endpoint for Root<E> { async fn call(&self, mut req: Request) ...
function_block-random_span
[]
Rust
tests/rayon.rs
RalfJung/atone
45ae1e42deaaaaa9a919957ade49982a7ac4655b
#![cfg(feature = "rayon")] #[macro_use] extern crate lazy_static; use atone::Vc; use rayon_::iter::{ IntoParallelIterator, IntoParallelRefIterator, IntoParallelRefMutIterator, ParallelExtend, ParallelIterator, }; macro_rules! assert_eq3 { ($e1:expr, $e2:expr, $e3:expr) => {{ assert_eq!($e1, $e2);...
#![cfg(feature = "rayon")] #[macro_use] extern crate lazy_static; use atone::Vc; use rayon_::iter::{ IntoParallelIterator, IntoParallelRefIterator, IntoParallelRefMutIterator, ParallelExtend, ParallelIterator, }; macro_rules! assert_eq3 { ($e1:expr, $e2:expr, $e3:expr) => {{ assert_eq!($e1, $e2);...
let expected = VC.clone(); let mut vc_seq = VC_EXISTING.clone(); let mut vc_par = VC_EXISTING.clone(); vc_seq.extend(VC_EXTENSION.iter().cloned()); vc_par.par_extend(VC_EXTENSION.par_iter().cloned()); assert_eq3!(vc_seq, vc_par, expected); }
t_eq!($e1, $e3); assert_eq!($e2, $e3); }}; } lazy_static! { static ref VC_EMPTY: Vc<u32> = Vc::new(); static ref VC: Vc<u32> = { let mut vc = Vc::new(); vc.push(20); vc.push(10); vc.push(30); vc.push(50); vc.push(60); vc.push(40); vc ...
random
[ { "content": "//! This module contains the parallel iterator types for double `Vc<T>`.\n\n//! You will rarely need to interact with it directly\n\n//! unless you have need to name one of the iterator types.\n\n\n\nuse crate::Vc;\n\n\n\nuse alloc::collections::LinkedList;\n\nuse rayon_::collections::vec_deque;\n...
Rust
src/audio_file.rs
jws121295/dansible
4c32335b048560352135480ab0216ff5be6bd8fa
use bit_set::BitSet; use byteorder::{ByteOrder, BigEndian}; use eventual; use std::cmp::min; use std::sync::{Arc, Condvar, Mutex}; use std::sync::mpsc::{self, TryRecvError}; use std::fs; use std::io::{self, Read, Write, Seek, SeekFrom}; use tempfile::NamedTempFile; use util::{FileId, IgnoreExt}; use session::Session; ...
use bit_set::BitSet; use byteorder::{ByteOrder, BigEndian}; use eventual; use std::cmp::min; use std::sync::{Arc, Condvar, Mutex}; use std::sync::mpsc::{self, TryRecvError}; use std::fs; use std::io::{self, Read, Write, Seek, SeekFrom}; use tempfile::NamedTempFile; use util::{FileId, IgnoreExt}; use session::Session; ...
} }
eek(pos)); self.seek.send(self.position).ignore(); Ok(self.position as u64)
function_block-random_span
[ { "content": "pub fn create_session(matches: &getopts::Matches) -> Session {\n\n info!(\"librespot {} ({}). Built on {}.\",\n\n version::short_sha(),\n\n version::commit_date(),\n\n version::short_now());\n\n\n\n let appkey = load_appkey(matches.opt_str(\"a\"));\n\n ...
Rust
src/cache.rs
olksdr/mem-stash
9e8f12781a799aab80ce1ee947358e7ed1c9b0ce
use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use memmap2; pub type Result<T, E = Box<dyn std::error::Error + Sync + Send>> = std::result::Result<T, E>; const PAGE_SIZE: usize = 65536; #[derive(Debug, Clone)] pub struct Cache { inner: Arc<Mutex<CacheInner>>, } impl Cach...
use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use memmap2; pub type Result<T, E = Box<dyn std::error::Error + Sync + Send>> = std::result::Result<T, E>; const PAGE_SIZE: usize = 65536; #[derive(Debug, Clone)] pub struct Cache { inner: Arc<Mutex<CacheInner>>, } impl Cach...
bounds, max available index = {}", index, self.elements_count ) .into()); } let mut buf = [0u8; std::mem::size_of::<u64>()]; unsafe { self.memmap .as_ptr() .add(Cache::get_location(in...
_err(|e| { format!( "Cannot get the shared reference to the mmap allocation: {:?}", e ) })?; f(reader) } pub fn with_writer<F>(&self, f: F) -> Result...
random
[ { "content": "# Mem Stash\n\n\n\nThis is a test Project, which inspired by https://github.com/nyurik/osm-node-cache (as of [`71e9965`](https://github.com/nyurik/osm-node-cache/tree/71e9965d64182feb4375b59f11e862704425adf2))\n\n\n\nIt's a simple re-implementation of the mmap backed cache for u64's, using the Mut...
Rust
libs/frontend/src/lexer/lexlets.rs
Ralakus/mod-language
1e10f949129cf9c3e460a53831541c8a88d0b14b
use mod_common::{ Identifier, Constant, Number, IDENTIFIER_VALUES, SYM_OPERATOR_VALUES, }; use crate::{ source::{ SourceRegion, }, token::{ Token, TokenData, }, }; use super::{ Lexer, }; pub struct InvalidLexicalSymbol { pub symbol: char, pub origin: SourceRegion, } pub enum LexletRe...
use mod_common::{ Identifier, Constant, Number, IDENTIFIER_VALUES, SYM_OPERATOR_VALUES, }; use crate::{ source::{ SourceRegion, }, token::{ Token, TokenData, }, }; use super::{ Lexer, }; pub struct InvalidLexicalSymbol { pub symbol: char, pub origin: SourceRegion, } pub enum LexletRe...
) })), lexer.pop_marker_region().unwrap() )) }, _ => LexletResult::None } } fn lex_operator (lexer: &mut Lexer) -> LexletResult { lexer.push_marker(); 'op_loop: for (substr, operator) in SYM_OPERATOR_VALUES { lexer.save_locale(); for op_char in substr.ch...
match builder.as_ref().parse::<u64>() { Ok(i) => i, Err(e) => { lexer.error(format!("Failed to parse integer decimal literal: {}", e)); 0 } }
if_condition
[ { "content": "#[must_use = \"sync_predicate::* functions return a synchronization predicate that must be passed to the Parser in a synchronization call, and do not perform the synchronization themselves\"]\n\npub fn token_data (data: TokenData) -> impl SyncPredicate {\n\n move |token: &Token| token.data == dat...
Rust
src/config.rs
LeSeulArtichaut/gpio-utils
282ea12416d2ad29a3f4c8612fa56c14cd569c2c
use glob::glob; use std::collections::{BTreeSet, HashMap}; use std::fmt; use std::fs::{self, File}; use std::io; use std::io::prelude::*; use std::path::Path; use std::str::FromStr; use sysfs_gpio; use toml; const DEFAULT_SYMLINK_ROOT: &str = "/var/run/gpio"; #[derive(Debug, PartialEq, Clone)] pub struct Direction(...
use glob::glob; use std::collections::{BTreeSet, HashMap}; use std::fmt; use std::fs::{self, File}; use std::io; use std::io::prelude::*; use std::path::Path; use std::str::FromStr; use sysfs_gpio; use toml; const DEFAULT_SYMLINK_ROOT: &str = "/var/run/gpio"; #[derive(Debug, PartialEq, Clone)] pub struct Direction(...
} impl GpioConfig { fn validate(&self) -> Result<(), Error> { let mut all_names: HashMap<&str, &PinConfig> = HashMap::new(); for pin in &self.pins { for name in &pin.names { if let Some(other_pin) = all_names.get(&name[..]) { retu...
t cfg = toml::from_str(&config); match cfg { Ok(cfg) => { let val_config: GpioConfig = toml::from_str(&config).unwrap(); val_config.validate()?; Ok(cfg) } Err(e) => Err(Error::ParserErrors(e)), } }
function_block-function_prefixed
[ { "content": "/// Export the pin specified in the provided config\n\n///\n\n/// Exporting a pin (in this context) involves, a few different\n\n/// actions:\n\n///\n\n/// 1. The GPIO pin itself is exported (via /sys/class/gpio/export)\n\n/// 2. For each GPIO name/alias, a symlink is created from\n\n/// `/var...
Rust
src/main.rs
theodore-s-beers/ahd-scrape
a518f70809218340d88c6d497bc844e7978eda06
use std::io::Write; use std::path::PathBuf; use std::process::Command; use std::{fs, str}; use anyhow::{anyhow, Context}; use clap::{crate_version, App, Arg}; use directories::ProjectDirs; use indicatif::{ProgressBar, ProgressStyle}; use isahc::prelude::*; use regex::Regex; use rusqlite::{Connection, Result}; use scra...
use std::io::Write; use std::path::PathBuf; use std::process::Command; use std::{fs, str}; use anyhow::{anyhow, Context}; use clap::{crate_version, App, Arg}; use directories::ProjectDirs; use indicatif::{ProgressBar, ProgressStyle}; use isahc::prelude::*; use regex::Regex; use rusqlite::{Connection, Result}; use scra...
fn update_cache( cache_hit: bool, db_path: PathBuf, desired_word: &str, etym_mode: bool, final_output: &str, force_fetch: bool, ) -> Result<(), rusqlite::Error> { let db_conn = Connection::open(db_path)?; if force_fetch && cache_hit { if etym_mode { db_co...
esired_word: &str, etym_mode: bool, ) -> Result<String, rusqlite::Error> { let mut query = String::new(); if etym_mode { query.push_str("SELECT * FROM etymology WHERE word = '"); } else { query.push_str("SELECT * FROM dictionary WHERE word = '"); } query.push_str(desired_w...
function_block-function_prefixed
[ { "content": "# gloss-word\n\n\n\nThis is a simple CLI utility for looking up the definition or (with flag `-e`)\n\nthe etymology of an English word. Definitions are drawn from the\n\n[_American Heritage Dictionary_](https://en.wikipedia.org/wiki/The_American_Heritage_Dictionary_of_the_English_Language),\n\nas ...
Rust
src/light/sphere_light.rs
johannesvollmer/psychopath
21cd04ce95deea631ef2c7ce50e200215668a3c0
use std::f64::consts::PI as PI_64; use kioku::Arena; use crate::{ bbox::BBox, boundable::Boundable, color::{Color, SpectralSample}, lerp::lerp_slice, math::{coordinate_system_from_vector, dot, Matrix4x4, Normal, Point, Vector}, ray::{RayBatch, RayStack}, sampling::{uniform_sample_cone, uni...
use std::f64::consts::PI as PI_64; use kioku::Arena; use crate::{ bbox::BBox, boundable::Boundable, color::{Color, SpectralSample}, lerp::lerp_slice, math::{coordinate_system_from_vector, dot, Matrix4x4, Normal, Point, Vector}, ray::{RayBatch, RayStack}, sampling::{uniform_sample_cone, uni...
fn is_delta(&self) -> bool { false } fn approximate_energy(&self) -> f32 { self.colors .iter() .fold(0.0, |a, &b| a + b.approximate_energy()) / self.colors.len() as f32 } } impl<'a> Surface for SphereLight<'a> { fn intersect_rays( &self...
let pdf = 1.0 / (4.0 * PI_64); let spectral_sample = col.to_spectral_sample(wavelength) * surface_area_inv as f32; return ( spectral_sample, (sample_point, normal, sample_point_err), pdf as f32, ); } }
function_block-function_prefix_line
[ { "content": "/// Samples a solid angle defined by a cone originating from (0,0,0)\n\n/// and pointing down the positive z-axis.\n\n///\n\n/// `u`, `v`: sampling variables, should each be in the interval [0,1]\n\n/// `cos_theta_max`: cosine of the max angle from the z-axis, defining\n\n/// the ...
Rust
runtime/src/kitties.rs
yz89/substrate-kitties
a1b35830c380190ba010a18027e7c90bf562564a
use parity_codec::{Decode, Encode, Input, Output}; use rstd::result; use runtime_io::blake2_128; use runtime_primitives::traits::{Bounded, Member, One, SimpleArithmetic}; use support::{ decl_event, decl_module, decl_storage, dispatch::Result, ensure, traits::Currency, Parameter, StorageMap, StorageValue, }; use...
use parity_codec::{Decode, Encode, Input, Output}; use rstd::result; use runtime_io::blake2_128; use runtime_primitives::traits::{Bounded, Member, One, SimpleArithmetic}; use support::{ decl_event, decl_module, decl_storage, dispatch::Result, ensure, traits::Currency, Parameter, StorageMap, StorageValue, }; use...
fn do_transfer( sender: &T::AccountId, recipient: &T::AccountId, kitty_id: T::KittyIndex, ) -> Result { let transfer_kitty = Self::kitty(kitty_id); ensure!(transfer_kitty.is_some(), "Invalid transfer kitty"); ensure!( <OwnedKitties...
fn do_breed( sender: &T::AccountId, kitty_id_1: T::KittyIndex, kitty_id_2: T::KittyIndex, ) -> result::Result<T::KittyIndex, &'static str> { let kitty1 = Self::kitty(kitty_id_1); let kitty2 = Self::kitty(kitty_id_2); ensure!(kitty1.is_some(), "Invalid kitty_id_1"); ...
function_block-full_function
[ { "content": "/// The module's configuration trait.\n\npub trait Trait: system::Trait {\n\n\t// TODO: Add other types and constants required configure this module.\n\n\n\n\t/// The overarching event type.\n\n\ttype Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;\n\n}\n\n\n\n/// This module's st...
Rust
src/backend.rs
teervo/soi
554ed7bbd3de96a1e8838bdd4a52c7a83c59d1b4
use crate::song::Song; use crate::traits::{AudioPlaybin, PathToURI, UnwrappedMutex}; use anyhow::Result; use glib::{source::Priority, MainContext}; use gst::prelude::*; use std::sync::{Arc, Mutex}; use std::time::Duration; #[derive(Clone)] pub struct Backend { playbin: gst::Element, next_uri: Arc<Mutex<Opt...
use crate::song::Song; use crate::traits::{AudioPlaybin, PathToURI, UnwrappedMutex}; use anyhow::Result; use glib::{source::Priority, MainContext}; use gst::prelude::*; use std::sync::{Arc, Mutex}; use std::time::Duration; #[derive(Clone)] pub struct Backend { playbin: gst::Element, next_uri: Arc<Mutex<Opt...
pub fn dequeue(&self) { if let Some(uri) = &*self.next_uri.lockk() { self.playbin .set_property("uri", uri) .expect("Unable to set playbin URI"); self.main_tx .send(BackendMessage::ReachedEndOfSong) .expect("Unabl...
sage to main()"), gst::MessageView::Error(e) => glib::g_debug!("song", "{}", e.error()), _ => (), } glib::Continue(true) })) .expect("Failed to connect to GStreamer message bus"); let thi...
random
[ { "content": "/// This trait provides a `lockk()` method for Mutex to be used\n\n/// as a shorthand for the boilerplate `lock().unwrap()`.\n\npub trait UnwrappedMutex<T> {\n\n fn lockk(&self) -> MutexGuard<'_, T>;\n\n}\n\n\n\nimpl<T> UnwrappedMutex<T> for Mutex<T> {\n\n fn lockk(&self) -> MutexGuard<'_, T...
Rust
tests/namespaces.rs
Katsutoshii/kataru
d029f728a4fa976778ac25cb07d6acfe38d65361
use kataru::{Bookmark, Command, Dialogue, Line, LoadYaml, Runner, Story, Validator, Value}; #[macro_use] extern crate linear_map; #[test] fn test_namespaces() { let story: Story = Story::load_yml("./tests/data/namespaces").unwrap(); let mut bookmark: Bookmark = Bookmark::load_yml("./tests/data/bookmark.yml").u...
use kataru::{Bookmark, Command, Dialogue, Line, LoadYaml, Runner, Story, Validator, Value}; #[macro_use] extern crate linear_map; #[test] fn test_namespaces() { let story: Story = Story::load_yml("./tests/data/namespaces").unwrap(); let mut bookmark: Bookmark = Bookmark::load_yml("./tests/data/bookmark.yml").u...
amespace2 start 1 time(s)".to_string(), ..Dialogue::default() }), ), ]; for (input, line) in &tests { assert_eq!(&runner.next(input).unwrap(), line); } }
name: "namespace1:LocalCharacter.GlobalMethod".to_string(), params: linear_map! { "param".to_string() => Value::String("".to_string())}, }), ), ( "", Line::Command(Command { name: "GlobalCharacter.Globa...
random
[ { "content": "fn run_command(runner: &mut Runner, command: &str, _params: &LinearMap<String, Value>) {\n\n match command {\n\n \"ClearScreen\" => print!(\"{}[2J\", 27 as char),\n\n \"SaveSnapshot\" => {\n\n runner.save_snapshot(\"test\");\n\n println!(\"Snapshot saved.\");...
Rust
src/main.rs
bauripalash/CamDumper
a69b944a8968be9505fb2f880bf021a911f29317
use std::io::Read; use std::io::Write; use std::net::Ipv4Addr; use std::net::TcpListener; use std::net::TcpStream; use std::net::UdpSocket; use std::process::exit; use std::str::FromStr; use std::thread; use std::time; use std::io::BufWriter; #[allow(dead_code)] #[derive(Debug)] struct PHeader { magic: (u8, u8), ...
use std::io::Read; use std::io::Write; use std::net::Ipv4Addr; use std::net::TcpListener; use std::net::TcpStream; use std::net::UdpSocket; use std::process::exit; use std::str::FromStr; use std::thread; use std::time; use std::io::BufWriter; #[allow(dead_code)] #[derive(Debug)] struct PHeader { magic: (u8, u8), ...
other: if input.len() > 8 { Some(input[8..].to_owned()) } else { None }, }) } else { Err(false) } } fn login_payload() -> Vec<u8> { let username_bytes: Vec<u8> = "admin".as_bytes().to_vec(); let password_bytes: Vec<u8> = "1234...
4..6]; let _msg = &input[6..8]; Ok(PHeader { magic: (_magic[0], _magic[1]), len: (_len[0], _len[1]), msg: (_msg[0], _msg[1]),
function_block-random_span
[ { "content": "## A program to connect to my SJcam 4000Air actioncamera and capture live feed\n\n\n\n**It is very early stage prototype**\n\n\n\n### Information\n\nThis program connects to my sjcam 4000 air actioncamera, fetches live stream (raw headless h264 data) and dumps it in the current working directory. ...
Rust
day14/src/main.rs
CheaterCodes/AoC2020
c9dd90c97c60107bbe533fe84da4d5323c25904f
use std::{collections::HashMap, env, error::Error, str::FromStr}; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; macro_rules! error { ($($arg:tt)*) => {{ let res = format!($($arg)*); Box::<dyn Error>::from(res) }}; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Line {...
use std::{collections::HashMap, env, error::Error, str::FromStr}; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; macro_rules! error { ($($arg:tt)*) => {{ let res = format!($($arg)*); Box::<dyn Error>::from(res) }}; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Line {...
} struct Memory { memory: HashMap<u64, u64>, set_mask: u64, clear_mask: u64, float_mask: u64 } impl Memory { fn new() -> Self { Memory { memory: HashMap::new(), set_mask: 0, clear_mask: 0, float_mask: 0 } } fn apply(&mut sel...
fn from_str(s: &str) -> Result<Self, Self::Err> { let mut parts = s.split(" = "); match parts.next() { Some("mask") => { let mask = parts.next().ok_or(error!("Missing value!"))?; let set_mask = u64::from_str_radix(mask.replace("X", "0").as_str(), 2)?; ...
function_block-full_function
[ { "content": "fn count_trees(lines: &Vec<Line>, step_col: usize, step_row: usize) -> u64 {\n\n let mut row = 0;\n\n let mut col = 0;\n\n let mut trees = 0;\n\n\n\n loop {\n\n col += step_col;\n\n if col >= lines[row].trees.len() {\n\n col -= lines[row].trees.len();\n\n ...
Rust
rust/backend/src/reply/json_stream.rs
katyo/literium
57d89b3822e5eace481b02ea05b2dd7d95e51dad
use super::ReplyStreamError; use futures::{Async, Poll, Stream}; use http::StatusCode; use httplib::Response; use hyper::{Body, Chunk}; use serde::Serialize; use serde_json::{to_string, Error as JsonError}; use std::error::Error; use std::fmt::Display; use std::mem::replace; use warp::Reply; const MIME_TYPE: &str = "a...
use super::ReplyStreamError; use futures::{Async, Poll, Stream}; use http::StatusCode; use httplib::Response; use hyper::{Body, Chunk}; use serde::Serialize; use serde_json::{to_string, Error as JsonError}; use std::error::Error; use std::fmt::Display; use std::mem::replace; use warp::Reply; const MIME_TYPE: &str = "a...
} impl<S, N, T> Stream for JsonObjectStream<S> where S: Stream<Item = (N, T)>, N: Display, T: Serialize, { type Item = Chunk; type Error = ReplyStreamError<S::Error, JsonError>; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { if self.nchunk.is_some() { let ch...
JsonObjectStream { stream, state: StreamState::Initial, nchunk: None, dchunk: None, } }
function_block-function_prefix_line
[ { "content": "pub fn sse_x_json<N, I, T, S, E, K>(stream: S, state: K) -> impl Reply\n\nwhere\n\n N: Display + Send + 'static,\n\n I: Display + Send + 'static,\n\n T: Serialize,\n\n S: Stream<Item = ServerEvent<N, I, T>, Error = E> + Send + 'static,\n\n E: Error + Send + Sync + 'static,\n\n K:...
Rust
src/test/instruction_tests/instr_vrcp28pd.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vrcp28pd_1() { run_test( &Instruction { mnemonic: Mnemonic::VRCP28PD, o...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vrcp28pd_1() { run_test( &Instruction { mnemonic: Mnemonic::VRCP28PD, o...
} #[test] fn vrcp28pd_4() { run_test( &Instruction { mnemonic: Mnemonic::VRCP28PD, operand1: Some(Direct(ZMM4)), operand2: Some(Direct(ZMM19)), operand3: None, operand4: None, lock: false, rounding_mode: None, ...
run_test( &Instruction { mnemonic: Mnemonic::VRCP28PD, operand1: Some(Direct(ZMM0)), operand2: Some(IndirectScaledIndexed( ECX, ESI, Two, Some(OperandSize::Qword), None, )), ...
call_expression
[ { "content": "fn encode16_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
chatroom/src/bin/client/protocol/handler.rs
KuangjuX/RustChat
7bff0485de4b76e275cccc9234888433b9778f93
use std::fs; use std::io::prelude::*; use crate::MESSAGE_SIZE; use audio::{ SAMPLE_RATE, Audio }; use std::str::FromStr; use crate::client::{ help, Client }; use chatroom::{ NMTP, NFTP, NVOIP, duplicate_filename }; pub fn parse_protocol(message: &mut String) -> Option<Vec<u8>>{ if message.as_str().starts_w...
use std::fs; use std::io::prelude::*; use crate::MESSAGE_SIZE; use audio::{ SAMPLE_RATE, Audio }; use std::str::FromStr; use crate::client::{ help, Client }; use chatroom::{ NMTP, NFTP, NVOIP, duplicate_filename }; pub fn parse_protocol(message: &mut String) -> Option<Vec<u8>>{ if message.as_str().starts_w...
sage == "help" { help(); None }else{ println!("message: {}",message); panic!("Error Protocol!"); } } pub fn mtp_handler(message: &mut String){ let s:Vec<&str> = message.split(NMTP).collect(); *message = format!( "{}: {}", "NMTP", s[1] ...
dler(message); Some(sound) }else if message == "exit"{ *message = String::from("exit"); None }else if mes
function_block-random_span
[ { "content": "// solve duplicate filename problem\n\npub fn duplicate_filename(filename: &mut String, mut num: usize){\n\n let mut clone_filename = filename.clone();\n\n while Path::new(&clone_filename).exists(){\n\n if filename.find(\".\") != None {\n\n num += 1;\n\n let s:Ve...
Rust
src/render/mesh.rs
krooq/maple
e771cb371fb082f484a4197f212e835d950b95f1
use super::math::*; use std::mem; use std::ops::Range; fn quad_vertices(transform_index: u32, w: f32, h: f32) -> Vec<Vertex> { let l = -w * 0.5; let r = w * 0.5; let t = h * 0.5; let b = -h * 0.5; vertices( transform_index, &[[l, t, 0.0], [r, t, 0.0], [r, b, 0.0], [l, b, 0.0]], ...
use super::math::*; use std::mem; use std::ops::Range; fn quad_vertices(transform_index: u32, w: f32, h: f32) -> Vec<Vertex> { let l = -w * 0.5; let r = w * 0.5; let t = h * 0.5; let b =
{} unsafe impl bytemuck::Zeroable for Transform {}
-h * 0.5; vertices( transform_index, &[[l, t, 0.0], [r, t, 0.0], [r, b, 0.0], [l, b, 0.0]], ) } fn quad_indices(v0: usize) -> Vec<u32> { let i0 = v0 as u32; vec![i0, i0 + 2, i0 + 1, i0, i0 + 3, i0 + 2] } #[derive(Clone, Debug)] pub struct Mesh { pub vertex_range: Range<usize>, ...
random
[ { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n use glsl_to_spirv::ShaderType;\n\n\n\n // Tell the build script to only run again if we change our source shaders\n\n println!(\"cargo:rerun-if-changed=src/render/shader\");\n\n\n\n // Create destination path if necessary\n\n ...
Rust
src/hal/uart.rs
andreytkachenko/opencm
fc4b1990be41317cde9c9e55b61df8d94fc873d2
use core::ops::Deref; use common::VolatileCell; use common::asm; use hal::rcc; #[derive(Copy, Clone, PartialEq, Eq)] pub struct Uart { regs: *const Registers } impl Uart { const fn new(addr: usize) -> Uart { Uart { regs: addr as *const Registers } } } impl Deref for Uart { ...
use core::ops::Deref; use common::VolatileCell; use common::asm; use hal::rcc; #[derive(Copy, Clone, PartialEq, Eq)] pub struct Uart { regs: *const Registers } impl Uart { const fn new(addr: usize) -> Uart { Uart { regs: addr as *const Registers } } } impl Deref for Uart { ...
fn set_baudrate(dev: Uart, baud: u32) { let clock = if dev == USART1 || dev == USART6 { rcc::apb2_frequency() } else { rcc::apb1_frequency() }; dev.brr.set(((clock << 1) + baud) / (baud << 1)); } fn set_databits(dev: Uart, bits: u32) { if bits == 8 { dev.cr1.uncheck(flags...
pub fn enable(dev: Uart, baud_rate: u32, stop_bits: StopBits, parity: Parity, flow_control: bool) { set_baudrate(dev, baud_rate); set_parity(dev, parity); set_stopbits(dev, stop_bits); set_flow_control(dev, if flow_control {FlowControl::RtsAndCts} else {FlowControl::None}); enable_interrupts(dev)...
function_block-full_function
[ { "content": "pub fn nop() {\n\n unsafe {asm!(\"nop\")}\n\n}", "file_path": "src/common/asm.rs", "rank": 7, "score": 103618.24590271655 }, { "content": "pub fn set_clock(base_clock: CrystalClock, target_clock: Clock) {\n\n\tlet scale = CLOCK_SCALE[base_clock as usize][target_clock as usiz...
Rust
src/synth/engine.rs
icsga/Yazz
593103400a53008e61a66237ca8c05656b2ceffc
extern crate cpal; extern crate failure; use super::UiMessage; use super::synth::Synth; use cpal::traits::{DeviceTrait, EventLoopTrait, HostTrait}; use crossbeam_channel::Sender; use log::error; use std::sync::{Arc, Mutex}; use std::time::SystemTime; pub struct Engine { sample_rate: u32, } impl Engine { pu...
extern crate cpal; extern crate failure; use super::UiMessage; use super::synth::Synth; use cpal::traits::{DeviceTrait, EventLoopTrait, HostTrait}; use crossbeam_channel::Sender; use log::error; use std::sync::{Arc, Mutex}; use std::time::SystemTime; pub struct Engine { sample_rate: u32, } impl Engine { pu...
iMessage::EngineSync(idle, busy)).unwrap(); locked_synth.update(); } }); }); Ok(()) } /* fn enumerate() { println!("\rSupported hosts:\n\r {:?}", cpal::ALL_HOSTS); let available_hosts = cpal::available_hosts(); print...
eamData::Output { buffer: cpal::UnknownTypeOutputBuffer::F32(mut buffer) } = data { let locked_synth = &mut synth.lock().unwrap(); let idle = time.elapsed().expect("Went back in time"); time = SystemTime::now(); for sample in buffer.chunk...
function_block-random_span
[ { "content": "fn setup_audio() -> Result<(Engine, u32), ()> {\n\n println!(\"\\rSetting up audio engine...\");\n\n let result = Engine::new();\n\n let engine = match result {\n\n Ok(e) => e,\n\n Err(()) => {\n\n error!(\"Failed to start audio engine\");\n\n println!(...
Rust
backend/src/actor.rs
Kruptein/theblackrose
8e874db23fb4bb038deabb176e760ad18bfc443f
use std::{collections::HashSet, env, sync::Arc, time::Duration}; use actix::{prelude::*, spawn}; use chrono::TimeZone; use riven::{consts::Region, models::match_v4::Match, models::match_v4::MatchReference, RiotApi}; use sqlx::{Error, PgPool}; use tokio::sync::Mutex; use crate::{ handlers::connections::get_summone...
use std::{collections::HashSet, env, sync::Arc, time::Duration}; use actix::{prelude::*, spawn}; use chrono::TimeZone; use riven::{consts::Region, models::match_v4::Match, models::match_v4::MatchReference, RiotApi}; use sqlx::{Error, PgPool}; use tokio::sync::Mutex; use crate::{ handlers::connections::get_summone...
} async fn update_connections( db: PgPool, api: Arc<RiotApi>, game_processing_lock: Arc<Mutex<HashSet<i64>>>, ) { match get_unique_connections(&db).await { Ok(connections) => { for connection in connections { update_connection( db.clone(), ...
fn handle(&mut self, msg: SummonerUpdateMessage, _: &mut Context<GameFetchActor>) { let db = self.db.clone(); let api = self.riot_api.clone(); let game_processing_lock = self.game_processing_lock.clone(); spawn(async { update_summoner(db, msg.summoner, api, game_processing_lock).await })...
function_block-full_function
[ { "content": "pub fn create_riot_api() -> RiotApi {\n\n let api_key = env::var(\"RGAPI_KEY\").expect(\"RGAPI_KEY is not set as an environment variable!\");\n\n RiotApi::with_key(api_key)\n\n}\n", "file_path": "backend/src/rito.rs", "rank": 1, "score": 162533.01997026324 }, { "content":...
Rust
src/days/day25.rs
emlun/adventofcode-2019
95eaf35e777d4cddc4e498a9b12e2e8f3f5d4e4d
use crate::common::Solution; use crate::intcode::IntcodeComputer; use std::collections::VecDeque; use std::io::Read; type Point = (i8, i8); type Direction = (i8, i8); #[derive(Clone, Copy, Debug)] enum AlgorithmStage { Collect, Navigate, Unlock, Done, } use AlgorithmStage::{Collect, Done, Navigate, Un...
use crate::common::Solution; use crate::intcode::IntcodeComputer; use std::collections::VecDeque; use std::io::Read; type Point = (i8, i8); type Direction = (i8, i8); #[derive(Clone, Copy, Debug)] enum AlgorithmStage { Collect, Navigate, Unlock, Done, } use AlgorithmStage::{Collect, Done, Navigate, Un...
fn move_to_point(pos: Point, move_command: &str) -> Point { let dir = match move_command { "north" => (0, 1), "east" => (1, 0), "south" => (0, -1), "west" => (-1, 0), _ => unreachable!(), }; (pos.0 + dir.0, pos.1 + dir.1) } fn initialize(mut state: State, output: S...
m); } state.explore(room.doors) } } Navigate => state.navigate(), Unlock => state.unlock(parse_room(output)), _ => unreachable!(), } }
function_block-function_prefixed
[ { "content": "fn step(moons: &mut Vec<Moon>) {\n\n for mooni in 0..moons.len() {\n\n moons[mooni].vel += moons\n\n .iter()\n\n .map(|gravmoon| gravity(&moons[mooni], gravmoon))\n\n .sum::<i64>();\n\n }\n\n for moon in moons {\n\n moon.pos += moon.vel;\n\n ...
Rust
src/escape.rs
atthecodeface/hml-rs
8d9e427243b72bd6a33c320607d40dfd2d38f9eb
#![warn(missing_docs)] #![warn(missing_doc_code_examples)] /*! # Escape handling This module is not ready for use This module provides escape handling for XML and entity replacement !*/ use std::collections::HashMap; pub type Result<T> = std::result::Result<T, std::io::Error>; pub const ESCAPE_QUOTE: usize = 1;...
#![warn(missing_docs)] #![warn(missing_doc_code_examples)] /*! # Escape handling This module is not ready for use This module provides escape handling for XML and entity replacement !*/ use std::collections::HashMap; pub type Result<T> = std::result::Result<T, std::io::Error>; pub const ESCAPE_QUOTE: usize = 1;...
#[test] fn test_entities() { let e = Entities::xml(); check_ok(e.replace_entities(true, "fred"), None); check_ok(e.replace_entities(true, "&amp;&AMP;"), Some("&&")); check_ok(e.replace_entities(true, "&lt;&LT;&GT;&gt;"), Some("<<>>")); check_ok(e.replace_entities(true, "...
pe("\u{1f600}", ESCAPE_ATTR), None); check_ok(escape("\u{1f600} <", ESCAPE_ATTR), Some("\u{1f600} &lt;")); check_ok( escape("\u{1f600} < \u{1f600} ", ESCAPE_ATTR), Some("\u{1f600} &lt; \u{1f600} "), ); }
function_block-function_prefixed
[ { "content": "//a Useful functions\n\n//fp hex_of_byte\n\nfn hex_of_byte(reason: &str, b: u8) -> Result<u32> {\n\n let value = {\n\n if b >= b'0' && b <= b'9' {\n\n b - b'0'\n\n } else if b >= b'a' && b <= b'f' {\n\n 10 + (b - b'a')\n\n } else if b >= b'A' && b <= b...
Rust
src/gl/draw_timer.rs
leod/webglee
7b9e27b5bea9ef260bd811b492836f7174bc7fb9
use std::{collections::VecDeque, rc::Rc, time::Duration}; use glow::HasContext; use instant::Instant; use super::Context; const MAX_POLL_QUERIES: usize = 100; pub struct DrawTimer { gl: Rc<Context>, max_age: Duration, is_supported: bool, last_query: Option<(Instant, glow::Query)>, poll_queries:...
use std::{collections::VecDeque, rc::Rc, time::Duration}; use glow::HasContext; use instant::Instant; use super::Context; const MAX_POLL_QUERIES: usize = 100; pub struct DrawTimer { gl: Rc<Context>, max_age: Duration, is_supported: bool, last_query: Option<(Instant, glow::Query)>, poll_queries:...
nos = unsafe { self.gl.get_query_parameter_u32(available_query, glow::QUERY_RESULT) }; self.samples.push_back((time, Duration::from_nanos(nanos as u64))); unsafe { self.gl.delete_query(available_query); } self.poll_queries.pop_front(); } } ...
min: Duration, pub max: Duration, } impl DrawTimer { pub fn new(gl: Rc<Context>, max_age: Duration) -> Self { let is_supported = gl .supported_extensions() .contains("EXT_disjoint_timer_query_webgl2"); log::info!("{:?}", gl.supported_extensions()); Self { ...
random
[ { "content": "pub fn draw<U, V, E, const S: usize>(\n\n program: &Program<U::UniformBlockDecls, V, S>,\n\n uniforms: U,\n\n samplers: [&Texture; S],\n\n draw_unit: DrawUnit<V, E>,\n\n draw_params: &DrawParams,\n\n) where\n\n U: UniformBuffers,\n\n V: Vertex,\n\n E: Element,\n\n{\n\n a...
Rust
src/dovi/rpu/rpu_data.rs
synacktic/dovi_tool
952236e2dae7c75a1843d801c15406e2e0f25763
use super::{ add_start_code_emulation_prevention_3_byte, rpu_data_header, vdr_dm_data::{self, ExtMetadataBlockLevel5}, vdr_rpu_data, BitVecReader, BitVecWriter, }; use super::prelude::*; use crc::{Crc, CRC_32_MPEG_2}; use rpu_data_header::RpuDataHeader; use vdr_dm_data::VdrDmData; use vdr_rpu_data::{NlqDat...
use super::{ add_start_code_emulation_prevention_3_byte, rpu_data_header, vdr_dm_data::{self, ExtMetadataBlockLevel5}, vdr_rpu_data, BitVecReader, BitVecWriter, }; use super::prelude::*; use crc::{Crc, CRC_32_MPEG_2}; use rpu_data_header::RpuDataHeader; use vdr_dm_data::VdrDmData; use vdr_rpu_data::{NlqDat...
#[inline(always)] pub fn read_rpu_data(bytes: Vec<u8>, end_byte: u8) -> DoviRpu { let mut dovi_rpu = DoviRpu::new(bytes); dovi_rpu.last_byte = end_byte; let reader = &mut dovi_rpu.reader; dovi_rpu.header = RpuDataHeader::rpu_data_header(reader); dovi_rpu.dovi...
pub fn new(bytes: Vec<u8>) -> DoviRpu { DoviRpu { reader: BitVecReader::new(bytes), ..Default::default() } }
function_block-full_function
[ { "content": "pub fn _parse_file(input: PathBuf) -> (Vec<u8>, DoviRpu) {\n\n let mut f = File::open(input).unwrap();\n\n let metadata = f.metadata().unwrap();\n\n\n\n let mut original_data = vec![0; metadata.len() as usize];\n\n f.read_exact(&mut original_data).unwrap();\n\n\n\n let dovi_rpu = pa...
Rust
ctre/src/canifier.rs
auscompgeek/ctre-rs
eb1fd8bcfd8745c391e7dfbb96757dc5e9d522dc
pub use ctre_data::canifier::*; use ctre_sys::canifier::*; pub use ctre_sys::canifier::{CANifierControlFrame, CANifierStatusFrame, GeneralPin}; use std::mem::{self, MaybeUninit}; use super::{CustomParam, ErrorCode, ParamEnum, Result}; pub type ControlFrame = CANifierControlFrame; pub type StatusFrame = CANifierStat...
pub use ctre_data::canifier::*; use ctre_sys::canifier::*; pub use ctre_sys::canifier::{CANifierControlFrame, CANifierStatusFrame, GeneralPin}; use std::mem::{self, MaybeUninit}; use super::{CustomParam, ErrorCode, ParamEnum, Result}; pub type ControlFrame = CANifierControlFrame; pub type StatusFrame = CANifierStat...
0. <= duty_cycle && duty_cycle <= 1., "Duty cycle should be within [0,1] (got {}).", duty_cycle ); let duty_cyc_10bit = 1023. * duty_cycle.max(0.).min(1.); unsafe { self.set_pwm_output_unchecked(pwm_channel as u32, duty_cyc_10bit as u32) } } #[doc(hidden)]...
bool { self.0 != 0 } } impl_binary_fmt!(StickyFaults); /** * CTRE CANifier * * Device for interfacing common devices to the CAN bus. */ #[derive(Debug)] pub struct CANifier { handle: Handle, } impl CANifier { pub fn new(device_number: i32) -> Self { let handle = unsafe { c_CAN...
random
[ { "content": "pub fn main() {\n\n let base = wpilib::RobotBase::new().expect(\"Could not initialise HAL\");\n\n let ds = base.make_ds();\n\n let mut talon = TalonSRX::new(3);\n\n let joy = Joystick {\n\n ds: &ds,\n\n port: ds::JoystickPort::new(0).unwrap(),\n\n };\n\n\n\n // firs...
Rust
src/second_chance.rs
pkhuong/kismet-cache
67bb4a0cfd619a0f501a36c07c08c152393c4f2b
pub trait Entry { type Rank: Ord; fn rank(&self) -> Self::Rank; fn accessed(&self) -> bool; } pub struct Update<T: Entry> { pub to_evict: Vec<T>, pub to_move_back: Vec<T...
pub trait Entry { type Rank: Ord; fn rank(&self) -> Self::Rank; fn accessed(&self) -> bool; } pub struct Update<T: Entry> { pub to_evict: Vec<T>, pub to_move_back: Vec<T...
#[test] fn evict_first_entry_unsorted() { let result = Update::new( vec![TestEntry(2, false), TestEntry(1, true), TestEntry(0, false)], 2, ); assert_eq!(result.to_evict, vec![TestEntry(0, false)]); assert_eq!(result.to_move_back, Vec::new()); }...
fn evict_first_entry() { let result = Update::new( vec![TestEntry(0, false), TestEntry(1, true), TestEntry(2, false)], 2, ); assert_eq!(result.to_evict, vec![TestEntry(0, false)]); assert_eq!(result.to_move_back, Vec::new()); }
function_block-full_function
[ { "content": "/// Attempts to prune the contents of `cache_dir` down to at most\n\n/// `capacity` files, with a second chance policy.\n\n///\n\n/// On success, returns an estimate of the number of files remaining\n\n/// in `cache_dir` and the number of files deleted.\n\n///\n\n/// Ignores any subdirectory of `c...
Rust
components/epaxos/src/replica/exec.rs
openacid/celeritasdb
061d71e5e6305b6e3782530433ad082680c9fc14
use std::cell::RefCell; use std::collections::HashMap; use std::time::SystemTime; use crate::qpaxos::{Deps, Instance, InstanceId, InstanceIdVec, OpCode}; use crate::replica::ExecRst; use crate::replica::Replica; use crate::InstanceIds; use crate::Record; use crate::ReplicaStatus; use crate::StorageAPI; use storage::Wr...
use std::cell::RefCell; use std::collections::HashMap; use std::time::SystemTime; use crate::qpaxos::{Deps, Instance, InstanceId, InstanceIdVec, OpCode}; use crate::replica::ExecRst; use crate::replica::Replica; use crate::InstanceIds; use crate::Record; use crate::ReplicaStatus; use crate::StorageAPI; use storage::Wr...
pub async fn insert_tx(&self, iid: InstanceId, tx: Sender<ExecRst>) { let mut wrpls = self.waiting_replies.lock().await; wrpls.insert(iid, tx); } pub async fn execute_commands( &self, mut insts: Vec<Instance>, mut executed: InstanceIds, ) -> Result<Vec<Instance...
rpls = self.waiting_replies.lock().await; while let Some((iid, r)) = replies.pop() { let tx = match wrpls.remove(&iid) { Some(t) => t, None => continue, }; if let Err(_) = tx.send(r) { println!("the receiver dropped for {:?}", i...
function_block-function_prefixed
[ { "content": "fn _handle_prepare_request(iid: (i64, i64), mut inst: Instance, req_inst: Instance) {\n\n let replica = new_foo_replica(1, new_mem_sto(), &[(iid, inst.clone())]);\n\n\n\n let req = MakeRequest::prepare(1, &req_inst, &vec![false]);\n\n let req: PrepareRequest = req.phase.unwrap().try_into(...
Rust
tests/integ.rs
webern/midi
aa9f8b4913cb8161ee97a4d1af82d095a45eba4a
mod utils; use midi_file::core::{Clocks, Control, DurationName, Message}; use midi_file::file::{Division, Event, Format, MetaEvent, QuarterNoteDivision}; use midi_file::MidiFile; use std::fs::File; use std::io::Read; use utils::{enable_logging, test_file, AVE_MARIS_STELLA}; #[test] fn ave_maris_stella_finale_export()...
mod utils; use midi_file::core::{Clocks, Control, DurationName, Message}; use midi_file::file::{Division, Event, Format, MetaEvent, QuarterNoteDivision}; use midi_file::MidiFile; use std::fs::File; use std::io::Read; use utils::{enable_logging, test_file, AVE_MARIS_STELLA}; #[test]
fn ave_maris_stella_finale_export() { enable_logging(); let midi_file = MidiFile::load(test_file(AVE_MARIS_STELLA)).unwrap(); assert_eq!(*midi_file.header().format(), Format::Multi); assert_eq!( *midi_file.header().division(), Division::QuarterNote(QuarterNoteDivision::new(1024)) ); ...
function_block-full_function
[ { "content": "#![allow(dead_code)]\n\n\n\nuse log::LevelFilter;\n\nuse std::io::Write;\n\nuse std::path::PathBuf;\n\nuse std::sync::Once;\n\n\n\npub const ADESTE_FIDELES: &str = \"adeste_fideles.mid\";\n\npub const ALS_DIE_ROEMER: &str = \"als_die_roemer.mid\";\n\npub const AVE_MARIS_STELLA: &str = \"ave_maris_...
Rust
src/main.rs
deciduously/conway
a6c9b5c299c20567a7a9fda4f01edaff29cda9bf
use std::{env, thread, time}; use std::fs::File; use std::io::prelude::*; type World = Vec<Vec<bool>>; #[derive(Debug)] struct Coord { x: usize, y: usize, } fn show_world(w: &World) { println!(""); for row in w.iter() { for cell in row.iter() { if *cell { print!(" ...
use std::{env, thread, time}; use std::fs::File; use std::io::prelude::*; type World = Vec<Vec<bool>>; #[derive(Debug)] struct Coord { x: usize, y: usize, } fn show_world(w: &World) { println!(""); for row in w.iter() { for cell in row.iter() { if *cell { print!(" ...
fn advance_and_show(w: &World) -> World { let next = tick_world(w); show_world(&next); thread::sleep(time::Duration::from_millis(100)); next } fn open_world() -> (String, usize) { let args: Vec<String> = env::args().collect(); let mut f = File::open(&args[1]).expect("not found!"); l...
fn tick_world(w: &World) -> World { let s = w.len(); let mut ret = vec![vec![false; s]; s]; for (x, row) in w.iter().enumerate() { for (y, _) in row.iter().enumerate() { ret[x][y] = tick_cell(&Coord{x: x, y: y}, w); } } ret }
function_block-full_function
[ { "content": "# Conway's Game of Life\n\nLoops forever - use ctrl-c to end.\n\n\n\ninvoke with the desired world file: `cargo run blinker` or `cargo run glider`\n\nWorld files must be square, any non-'0' char is parsed as \"true\" for the starting state.\n\n\n\nIncluded examples are a 3x3 blinker, 9x9 world wit...
Rust
op-core/src/proto/proc/proc.rs
opereon/opereon
f230a4ce9e756249a38d1ed8e8480e4fb7200868
use super::*; use std::sync::{Arc, Mutex, MutexGuard}; #[derive(Debug, Serialize, Deserialize)] pub struct ProcExec { created: DateTime<Utc>, name: String, label: String, kind: ProcKind, curr_model: RevInfo, #[serde(skip_serializing_if = "Option::is_none", default)] prev_model: Option<RevI...
use super::*; use std::sync::{Arc, Mutex, MutexGuard}; #[derive(Debug, Serialize, Deserialize)] pub struct ProcExec { created: DateTime<Utc>, name: String, label: String, kind: ProcKind, curr_model: RevInfo, #[serde(skip_serializing_if = "Option::is_none", default)] prev_model: Option<RevI...
for host in hosts { let step = StepExec::create(model, proc, s, &host, self) .map_err_as_cause(|| ProtoErrorDetail::StepExecCreate)?; self.add_step(step); } } Ok(()) } pub fn add_step(&mut self, step: StepExec) { ...
if hosts.is_empty() { warn!(verb=0, "Procedure '{name}', label: '{label}' will not be executed, there is no target hosts!", name=&self.name, label=&self.label); }
if_condition
[ { "content": "/// Resolve path defined in model.\n\n/// # Arguments\n\n///\n\n/// * `path` - path to resolve\n\n/// * `current_dir` - directory to resolve relative paths\n\n/// * `model_dir` - absolute path to model directory\n\n///\n\n/// # Returns\n\n/// Absolute path\n\n///\n\n/// # Example\n\n/// ```\n\n///...
Rust
src/commands/quizizz.rs
ThatAnnoyingKid/pikadick-rs
234c0ca715a4326770da4ba8f4a0864e9b90a1a7
use crate::{ checks::ENABLED_CHECK, util::LoadingReaction, ClientDataKey, }; use anyhow::Context as _; use serenity::{ framework::standard::{ macros::command, Args, CommandResult, }, model::prelude::*, prelude::*, }; use std::{ collections::BinaryHeap, sync::A...
use crate::{ checks::ENABLED_CHECK, util::LoadingReaction, ClientDataKey, }; use anyhow::Context as _; use serenity::{ framework::standard::{ macros::command, Args, CommandResult, }, model::prelude::*, prelude::*, }; use std::{ collections::BinaryHeap, sync::A...
(Some(code_str)) => { info!("located quizizz code '{}'", code_str); loading.send_ok(); msg.channel_id .say(&ctx.http, format!("Located quizizz code: {}", code_str)) .await?; } Ok(None) => { info!("quizziz finder reached limi...
(); ret } } impl Default for QuizizzClient { fn default() -> Self { Self::new() } } #[derive(Debug)] pub struct CodeCache { cache: BinaryHeap<(std::cmp::Reverse<Instant>, String)>, } impl CodeCache { pub fn new() -> Self { Self { cache: BinaryHeap...
random
[ { "content": "type BoxedError = Box<dyn std::error::Error + Send + Sync + 'static>;\n\n\n\n/// Error\n\n#[derive(Debug, thiserror::Error)]\n\npub enum Error {\n\n /// Rusqlite error\n\n #[error(transparent)]\n\n Rusqlite(#[from] rusqlite::Error),\n\n\n\n /// Tokio Join Error\n\n #[error(transpare...
Rust
src/gl_basic/object.rs
wmww/Rust-on-Android-test
0fea157162df88c7cb7c0a086f78e32d67e2ab29
extern crate gl; use std; use std::mem; use std::rc::Rc; use gl_basic; use gl_basic::types; use gl_basic::types::GlType; pub struct Object { program: Rc<gl_basic::Program>, vertex_array_id: gl::types::GLuint, vertex_buffer_id: gl::types::GLuint, element_buffer_id: gl::types::GLuint, tri_count: u3...
extern crate gl; use std; use std::mem; use std::rc::Rc; use gl_basic; use gl_basic::types; use gl_basic::types::GlType; pub struct Object { program: Rc<gl_basic::Program>, vertex_array_id: gl::types::GLuint, vertex_buffer_id: gl::types::GLuint, element_buffer_id: gl::types::GLuint, tri_count: u3...
vertex_array_id: vertex_array, vertex_buffer_id: vertex_buffer, element_buffer_id: element_buffer, tri_count: 0, }) } } pub fn set_attribs(&mut self, attribs: Vec<types::Attrib>) { unsafe { gl::BindVertexArray(s...
gl::GenBuffers(1, &mut vertex_buffer); let mut element_buffer = mem::uninitialized(); gl::GenBuffers(1, &mut element_buffer); gl::BindVertexArray(vertex_array); gl::BindBuffer(gl::ARRAY_BUFFER, vertex_buffer); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER...
function_block-random_span
[ { "content": "pub trait GlType {\n\n fn gl_type() -> gl::types::GLenum;\n\n fn element_count() -> gl::types::GLint;\n\n}\n\n\n", "file_path": "src/gl_basic/types.rs", "rank": 0, "score": 44851.59502973132 }, { "content": "fn byte_size_of_gl_type(gl_type: gl::types::GLenum) -> gl::types...
Rust
src/main.rs
stream-audio/udp-jitter-test-linux
622f0479c418905972733191427a8862750cffae
#![deny(unused_must_use)] #[macro_use] mod macros; mod error; mod merge_futures; mod statistic; use crate::merge_futures::FuturesMergerMemoryOwner; use async_std::{ net::UdpSocket, task::{self, sleep}, }; use error::Error; use futures::try_join; use libc; use log::{error, info, warn}; use rand::{self, rngs::S...
#![deny(unused_must_use)] #[macro_use] mod macros; mod error; mod merge_futures; mod statistic; use crate::merge_futures::FuturesMergerMemoryOwner; use async_std::{ net::UdpSocket, task::{self, sleep}, }; use error::Error; use futures::try_join; use libc; use log::{error, info, warn}; use rand::{self, rngs::S...
async fn send_packet_to_all(&mut self) -> Result<(), Error> { if self.clients.is_empty() { return Ok(()); } self.pkt.gen_next_pkt()?; let mut futs = self.send_futures.borrow()?; futs.reserve(self.clients.len()); let (clients, socket, pkt) = (self.clie...
async fn send_loop(&mut self) -> Result<(), Error> { const INTERVAL: Duration = Duration::from_millis(20); loop { let pkt_send_time = Instant::now(); self.send_packet_to_all().await?; let sleep_dur = INTERVAL .checked_sub(pkt_send_time.elapsed()) ...
function_block-full_function
[ { "content": "type RawVoidPtr = Option<NonNull<u8>>;\n\n\n\n/// `FuturesMergerMemoryOwner`, `FuturesMerger` allows you to `.await` on multiple futures\n\n/// without unnecessary memory allocations.\n\n/// Memory is initially allocated to store futures in an array, but later can be reused.\n\n///\n\n/// `Futures...
Rust
src/lib.rs
fc1943s/rust-userscripts
f1dc049aab165d5d947e28a40890ed0627ff2506
use gloo::timers::callback::Interval; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{console, Document, HtmlElement, Window}; fn get_window() -> Window { web_sys::window().expect("no global `window` exists") } fn get_document() -> Document { get_window() .document() ....
use gloo::timers::callback::Interval; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys::{console, Document, HtmlElement, Window}; fn get_window() -> Window { web_sys::window().expect("no global `window` exists") } fn get_document() -> Document { get_window() .document() ....
pub fn expand_as_director_timer() { let mut as_director_expanded = false; Interval::new(200, move || { if !as_director_expanded { as_director_expanded = is_as_director_expanded(); } if as_director_expanded { console::log_1(&"parse_list".into()); ...
t(); let class_list = collect_dom_token_list(&dom_token_list); console::log_1(&format!("class_list: {:?}", class_list).into()); if class_list.contains(&"see-more".into()) { button.click(); } if class_list.contains(&"see-less".into()) { console::log_1(&f...
function_block-function_prefixed
[ { "content": "#[wasm_bindgen_test]\n\nfn pass() {\n\n assert_eq!(1 + 1, 2);\n\n}\n", "file_path": "tests/web.rs", "rank": 4, "score": 33340.85364825873 }, { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `s...
Rust
src/main.rs
popravich/adventofcode2021
9cb3c6089f52cf053e4f01f8dd4fe48c7b763dbb
use std::env; use advent::{ day1, day2, day3, day4, day5, day6, day7, day8, day9, day10, day11, day12, day13, day14, day15, day16, day17, day18, }; static DAY1: &str = include_str!("./input/day1.txt"); static DAY2: &str = include_str!("./input/da...
use std::env; use advent::{ day1, day2, day3, day4, day5, day6, day7, day8, day9, day10, day11, day12, day13, day14, day15, day16, day17, day18, }; static DAY1: &str = include_str!("./input/day1.txt"); static DAY2: &str = include_str!("./input/da...
12 => { let (result1, result2) = day12::main(DAY12)?; println!("Result1: {}", result1); println!("Result2: {}", result2); } 13 => { let (result1, result2) = day13::main(DAY13)?; println!("Result1: {}", result1); println!("Result2: {...
function_block-function_prefix_line
[ { "content": "pub fn main(input: &str) -> Result<(usize, usize), String> {\n\n let data = parse_input(input);\n\n\n\n let mut min_pos = usize::MAX;\n\n let mut min_fuel = usize::MAX;\n\n let mut min_pos2 = usize::MAX;\n\n let mut min_fuel2 = usize::MAX;\n\n let unique: HashSet<_> = data.iter()...
Rust
examples/hero_wavelength_sampling.rs
anderslanglands/colorspace-rs
257824880ef777412a094329ba875b8bc9a868cf
#![allow(non_snake_case)] use colorspace::*; use rand::prelude::*; const NUM_SAMPLES: usize = 16384; const SPD_START: f64 = 360.0; const SPD_END: f64 = 780.0; const SPD_RANGE: f64 = SPD_END - SPD_START; fn main() { let x_bar = InterpolatorSprague::<f64>::new(&cmf::CIE_1931_2_DEGREE.x_bar); let y_bar = Interpo...
#![allow(non_snake_case)] use colorspace::*; use rand::prelude::*; const NUM_SAMPLES: usize = 16384; const SPD_START: f64 = 360.0; const SPD_END: f64 = 780.0; const SPD_RANGE: f64 = SPD_END - SPD_START; fn main() { let x_bar = InterpolatorSprague::<f64>::new(&cmf::CIE_1931_2_DEGREE.x_bar); let y_bar = Interpo...
e in colorchecker::NAMES.iter() { let rgb_ref = colorchecker::SRGB_LINEAR[*name]; let mut xyz = XYZf64::from_scalar(0.0); let mut xyz_w = XYZf64::from_scalar(0.0); for i in 0..NUM_SAMPLES { let x = ((i as f64) + rng.gen::<f64>()) / NUM_SAMPLES as f64; ...
function_block-function_prefixed
[ { "content": "fn criterion_benchmark(c: &mut Criterion) {\n\n c.bench_function(\"convert checker vspd\", |b| b.iter(|| convert_checker_vspd()));\n\n c.bench_function(\"convert checker spd\", |b| b.iter(|| convert_checker_spd()));\n\n c.bench_function(\"convert checker spd AVX\", |b| b.iter(|| convert_c...
Rust
src/utils.rs
bifrost-codes/substrate-rpc-client
b1cd17fbd9cfb3f80d1100abed3be1a35d9e8e7e
use hex::FromHexError; use primitive_types::U256; use primitives::{blake2_256, H256 as Hash, twox_128}; fn storage_key_hash_vec(module: &str, storage_key_name: &str, param: Option<Vec<u8>>) -> Vec<u8> { let mut key = [module, storage_key_name].join(" ").as_bytes().to_vec(); match param { Some(par) =>...
use hex::FromHexError; use primitive_types::U256; use primitives::{blake2_256, H256 as Hash, twox_128}; fn storage_key_hash_vec(module: &str, storage_key_name: &str, param: Option<Vec<u8>>) -> Vec<u8> { let mut key = [module, storage_key_name].join(" ").as_bytes().to_vec(); match param { Some(par) =>...
pub fn hexstr_to_u256(hexstr: String) -> Result<U256, FromHexError> { let unhex = hexstr_to_vec(hexstr); match unhex { Ok(vec) => { match vec.len() { 1|2|4|8|16|32 => { Ok(U256::from_little_endian(&vec[..])) }, _ => { ...
pub fn hexstr_to_u64(hexstr: String) -> Result<u64, FromHexError> { let unhex = hexstr_to_vec(hexstr); match unhex { Ok(vec) => { match vec.len() { 1|2|4|8 => { let mut h: [u8; 8] = Default::default(); h[..vec.len()].copy_from_slice(&ve...
function_block-full_function
[ { "content": "pub fn state_subscribe_storage(key: &str) -> Value {\n\n state_subscribe_storage_with_id(key, 1)\n\n}\n\n\n", "file_path": "src/rpc/json_req.rs", "rank": 7, "score": 130124.3847026878 }, { "content": "pub fn state_get_storage(key_hash: &str) -> Value {\n\n state_get_stora...
Rust
src/notification.rs
eggerk/audio_tools
60f23583c2156c954a78678bbdd9854076713c11
use std::process; use std::str; use failure::{bail, Error}; use log::{debug, error}; use notify_rust::Notification; use crate::volume::VolumeInfo; use crate::volume_control::Interface; struct NotificationWrapper { id: Option<u32>, default_summary: String, } impl NotificationWrapper { fn new(id: Option<u...
use std::process; use std::str; use failure::{bail, Error}; use log::{debug, error}; use notify_rust::Notification; use crate::volume::VolumeInfo; use crate::volume_control::Interface; struct NotificationWrapper { id: Option<u32>, default_summary: String, } impl NotificationWrapper { fn new(id: Option<u...
fn get_id(&self) -> Option<u32> { self.id } } pub struct VolumeNotification { notification_handle: NotificationWrapper, } impl VolumeNotification { pub fn new(id: Option<u32>) -> Self { Self { notification_handle: NotificationWrapper::new(id, String::from("Volume")), ...
let mut notification = notification.summary(summary).body(&body).finalize(); let notification = match self.id { Some(id) => notification.id(id).finalize(), None => notification, }; match notification.show() { Err(e) => bail!("{:?}", e), Ok(handle) ...
function_block-function_prefix_line
[ { "content": "fn main() -> Result<(), Error> {\n\n setup_log()?;\n\n let (volume_notification_id, sink_notification_id) =\n\n load_data_from_file().unwrap_or((None, None));\n\n\n\n let mut interface = Interface::new(volume_notification_id, sink_notification_id);\n\n\n\n let command = parse_ar...
Rust
src/mqttoptions.rs
SpirosMakris/rumqtt
460c55bbdde9b7e056520c46f51441a9f5269658
use mqtt311::LastWill; use std::time::Duration; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum ReconnectOptions { Never, AfterFirstSuccess(u64), Always(u64), } #[derive(Clone, Debug)] pub enum SecurityOptions { None, UsernamePassword(String, Str...
use mqtt311::LastWill; use std::time::Duration; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum ReconnectOptions { Never, AfterFirstSuccess(u64), Always(u64), } #[derive(Clone, Debug)] pub enum SecurityOptions { None, UsernamePassword(String, Str...
pub fn broker_address(&self) -> (String, u16) { (self.broker_addr.clone(), self.port) } pub fn set_ca(mut self, ca: Vec<u8>) -> Self { self.ca = Some(ca); self } pub fn ca(&self) -> Option<Vec<u8>> { self.ca.clone() } pub fn set_client_auth(mut self,...
s { let id = id.into(); if id.starts_with(' ') || id.is_empty() { panic!("Invalid client id") } MqttOptions { broker_addr: host.into(), port, keep_alive: Duration::from_secs(60), clean_session: true, connec...
function_block-function_prefixed
[ { "content": "fn resolve(host: &str, port: u16) -> Result<SocketAddr, io::Error> {\n\n use std::net::ToSocketAddrs;\n\n\n\n (host, port).to_socket_addrs()\n\n .and_then(|mut addrs| {\n\n addrs.next().ok_or_else(|| {\n\n let err_msg = format!(\"invalid hostname '{}'\", host...
Rust
src/uci.rs
namib-project/namib_enforcer
4e93c1a376691bf5ad88ec5b80ba90ae3b6e08d7
#[cfg(not(feature = "uci"))] pub use mock::*; #[cfg(feature = "uci")] pub use rust_uci::*; #[cfg(not(feature = "uci"))] #[allow(clippy::unused_self)] mod mock { use crate::error::{self, Result}; pub struct Uci {} impl Uci { pub fn new() -> Result<Self> { Ok(Self {}) } ...
#[cfg(not(feature = "uci"))] pub use mock::*; #[cfg(feature = "uci")] pub use rust_uci::*; #[cfg(not(feature = "uci"))] #[allow(clippy::unused_self)] mod mock { use crate::error::{self, Result}; pub struct Uci {} impl Uci { pub fn new() -> Result<Self> { Ok(Self {}) } ...
#[test] fn test_writing_key() -> Result<()> { let mut uci = init()?; File::create("tests/config/new_network")?; uci.set("new_network.a", "alias")?; uci.set("new_network.a.interface", "lan")?; uci.set("new_network.b", "alias")?; uci.set("new_network.b.interface...
k.@interface[0].proto")?, "static"); assert_eq!(uci.get("broken.a").is_err(), true); assert_eq!(uci.get("broken.a.b").is_err(), true); assert_eq!(uci.get("inexistant.c").is_err(), true); assert_eq!(uci.get("inexistant.c.d").is_err(), true); Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn discover_controllers(reg_type: &str) -> impl Stream<Item=Result<ScopedSocketAddr>> {\n\n async_dnssd::browse(reg_type)\n\n .timeout(SEARCH_TIMEOUT)\n\n .try_filter_map(|service| {\n\n future::ok({\n\n let added = service.flags.contains(async_dnssd:...
Rust
libs/calypso_parsing/src/lexer/scan.rs
tbmreza/calypso
b2d56c911add03701ea8cdc485be3d7077223e11
use super::helpers::is_ident_start; use super::{Lexer, Token, TokenType}; use calypso_ast::expr::Radix; use calypso_base::streams::Stream; use calypso_diagnostic::diagnostic::{EnsembleBuilder, LabelStyle}; use calypso_diagnostic::prelude::*; impl<'lex> Lexer<'lex> { ...
use super::helpers::is_ident_start; use super::{Lexer, Token, TokenType}; use calypso_ast::expr::Radix; use calypso_base::streams::Stream; use calypso_diagnostic::diagnostic::{EnsembleBuilder, LabelStyle}; use calypso_diagnostic::prelude::*; impl<'lex> Lexer<'lex> { ...
}
d, self.new_span(), ) }) .build(), ); TokenType::Unexpected } }; Ok(self.new_token(token_type)) }
function_block-function_prefixed
[ { "content": "#[must_use]\n\npub fn process(tok: Token) -> Tok {\n\n match tok.value_owned() {\n\n (TokenType::Int { suffix, radix }, string) => {\n\n Tok::Number(trim_number(string, radix), radix, suffix)\n\n }\n\n (TokenType::Float, string) => Tok::Number(\n\n tri...
Rust
rust/backend/src/filters/sealed_auth.rs
katyo/literium
57d89b3822e5eace481b02ea05b2dd7d95e51dad
use futures::{ future::{err, result, Either}, Future, }; use auth::{ AuthData, AuthError, HasSessionStorage, HasUserAuth, IsSessionData, IsSessionStorage, IsUserAuth, }; use crypto::{CanDecrypt, HasSecretKey}; use user::{HasUserStorage, IsUserStorage}; use warp::{any, header, reject::custom, Filter, Re...
use futures::{ future::{err, result, Either}, Future, }; use auth::{ AuthData, AuthError, HasSessionStorage, HasUserAuth, IsSessionData, IsSessionStorage, IsUserAuth, }; use crypto::{CanDecrypt, HasSecretKey}; use user::{HasUserStorage, IsUserStorage}; use warp::{any, header, reject::custom, Filter, Re...
fn proc_user_auth<S>( state: &S, auth: String, ) -> impl Future<Item = S::UserAuth, Error = AuthError> + Send where S: HasSecretKey + HasUserStorage + HasSessionStorage + HasUserAuth + Send + Clone, { let state = state.clone(); result( (state.as_ref() as &S::SecretKey) .open_js...
and_then(move |auth: Option<String>| { auth.map(|auth| Either::A(proc_user_auth(&state, auth))) .unwrap_or_else(|| { Either::B(result( S::UserAuth::new_none_auth().ok_or_else(|| AuthError::MissingAuth), )) }).map...
function_block-function_prefix_line
[ { "content": "/// Handle auth requests\n\npub fn do_user_auth<S>(state: &S) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone\n\nwhere\n\n S: HasPublicKey\n\n + HasSecretKey\n\n + HasUserStorage\n\n + HasUserAuth\n\n + HasSessionStorage\n\n + HasAuthMethod\...
Rust
src/main.rs
Yuri6037/bin2c
25eaf6d716d0de988c970afa7c9c3731e89d6ef1
#![allow(irrefutable_let_patterns)] use std::fs::File; use std::io::prelude::*; use std::process; use std::path::Path; use std::io; use clap::clap_app; const MAX_BYTES_PER_BUFFER: usize = 2097152; fn write_header(const_name: &str, output: &str, count: u32, total_len: usize, write_blocks_heading: bool) -> io::Resul...
#![allow(irrefutable_let_patterns)] use std::fs::File; use std::io::prelude::*; use std::process; use std::path::Path; use std::io; use clap::clap_app; const MAX_BYTES_PER_BUFFER: usize = 2097152; fn write_header(const_name: &str, output: &str, count: u32, total_len: usize, write_blocks_heading: bool) -> io::Resul...
fn main() { let matches = clap_app!(bin2c => (version: "1.0") (author: "Yuri6037 <https://github.com/Yuri6037/bin2c>") (about: "A cross platform Rust version of the UNIX tool bin2c") (@arg INPUT: +required "The input file to convert to a C file") (@arg OUTPUT: +required "The ...
function_block-full_function
[ { "content": "extern const size_t BINARY_DATA_SIZE;\n", "file_path": "test.h", "rank": 4, "score": 11414.636024885578 }, { "content": "const size_t BINARY_DATA_SIZE = 8304;\n", "file_path": "test.c", "rank": 5, "score": 11414.636024885578 } ]
Rust
contracts/factory/src/contract.rs
nymlab/vectis
91403d84be1b5b36b07f04f3a30e9a5994f2116e
use crate::error::ContractError; use crate::helpers::{ ensure_enough_native_funds, ensure_has_govec, ensure_is_admin, ensure_is_valid_migration_msg, ensure_is_valid_threshold, ensure_is_wallet, }; use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg, WalletListResponse}; use crate::state::{ ADDR_PREFIX, AD...
use crate::error::ContractError; use crate::helpers::{ ensure_enough_native_funds, ensure_has_govec, ensure_is_admin, ensure_is_valid_migration_msg, ensure_is_valid_threshold, ensure_is_wallet, }; use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg, WalletListResponse}; use crate::state::{ ADDR_PREFIX, AD...
pub fn query_code_id(deps: Deps, ty: CodeIdType) -> StdResult<u64> { let id = match ty { CodeIdType::Proxy => PROXY_CODE_ID.load(deps.storage)?, CodeIdType::Multisig => PROXY_MULTISIG_CODE_ID.load(deps.storage)?, }; Ok(id) } pub fn query_govec_addr(deps: Deps) -> StdResult<Addr> { dep...
range(deps.storage, start, None, Order::Ascending) .take(limit) .map(|key| deps.api.addr_humanize(&CanonicalAddr::from(key?.0))) .collect(); Ok(WalletListResponse { wallets: wallets? }) }
function_block-function_prefix_line
[ { "content": "#[cfg(feature = \"migration\")]\n\n#[cfg_attr(not(feature = \"library\"), entry_point)]\n\npub fn migrate(deps: DepsMut, _env: Env, msg: ProxyMigrateMsg) -> Result<Response, ContractError> {\n\n CODE_ID.save(deps.storage, &msg.new_code_id)?;\n\n Ok(Response::default())\n\n}\n", "file_pat...
Rust
token-entangler/program/tests/entangler_lifecycle_test.rs
CalebEverett/metaplex-program-library
df36da5a78fb17e1690247b8041b761d27c83b1b
use anchor_lang::{ prelude::{Pubkey, Rent}, InstructionData, ToAccountMetas, }; use mpl_token_metadata::{instruction::create_metadata_accounts, pda::find_metadata_account}; use solana_program_test::ProgramTest; use solana_sdk::{ instruction::Instruction, program_pack::Pack, signature::Keypair, signer::Signe...
use anchor_lang::{ prelude::{Pubkey, Rent}, InstructionData, ToAccountMetas, }; use mpl_token_metadata::{instruction::create_metadata_accounts, pda::find_metadata_account}; use solana_program_test::ProgramTest; use solana_sdk::{ instruction::Instruction, program_pack::Pack, signature::Keypair, signer::Signe...
.unwrap(), Instruction { program_id: mpl_token_entangler::id(), accounts: accounts.to_account_metas(None), data: instruction.data(), }, revoke( &spl_token::id(), &token_b, &pa...
approve( &spl_token::id(), &token_b, &transfer_authority.pubkey(), &payer.pubkey(), &[], 1, )
call_expression
[ { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn revoke_use_authority(\n\n program_id: Pubkey,\n\n use_authority_record: Pubkey,\n\n user: Pubkey,\n\n owner: Pubkey,\n\n owner_token_account: Pubkey,\n\n metadata: Pubkey,\n\n mint: Pubkey,\n\n) -> Instruction {\n\n Instruction...
Rust
src/hdw/cpu/ops/modes.rs
stachetheoverlord/rs6502
3ade3487cd93ddda597a631535bdad741b30bbcb
use hdw::cpu::Cpu; pub fn accumulator(cpu: &mut Cpu) -> data { cpu.pc = cpu.pc.wrapping_add(1); data::A } pub fn absolute(cpu: &mut Cpu) -> data { let address = ((cpu.mem.get(cpu.pc.wrapping_add(2)) as u16) << 8) | (cpu.mem.get(cpu.pc.wrapping_add(1)) as u16); cpu.pc = cpu.pc.wrapping_add(3);...
use hdw::cpu::Cpu; pub fn accumulator(cpu: &mut Cpu) -> data { cpu.pc = cpu.pc.wrapping_add(1); data::A } pub fn absolute(cpu: &mut Cpu) -> data { let address = ((cpu.mem.get(cpu.pc.wrapping_add(2)) as u16) << 8) | (cpu.mem.get(cpu.pc.wrapping_add(1)) as u16); cpu.pc = cpu.pc.wrapping_add(3);...
pub enum data { A, Memory(u16), Value(u8), Implied, } impl data { pub fn get(&self, cpu: &mut Cpu) -> u8 { match self { &data::A => cpu.a, &data::Memory(address) => cpu.mem.get(address.clone()), &data::Value(val) => val.clone(), &data::Impli...
let arg = cpu.mem.get(cpu.pc.wrapping_add(1)); let result = arg.wrapping_add(cpu.y.into()); cpu.pc = cpu.pc.wrapping_add(2); data::Memory(result.into()) }
function_block-function_prefix_line
[ { "content": "fn main() {\n\n let fps = 3;\n\n\n\n let memory = mem::Mem {\n\n data: vec![Cell::new(0); 65536],\n\n };\n\n\n\n memory.load_file(\"nestest.nes\", 0xbff0, 0x4000);\n\n memory.load_file(\"nestest.nes\", 0x7ff0, 0x4000);\n\n // memory.load(vec![0x4a, 0], 0xc000, 0xc000);\n\n...
Rust
simplifier/src/simplifications/if_constraint_prop.rs
Robbepop/stevia
5f0132ef8fa0826a4cadfe07622cd594c31c57e9
use stevia_ast::{ prelude::*, ty::{ Type, HasType as _, }, iter::ChildrenMut, transformer::{ AnyExprTransformer, TransformOutcome, TransformEffect, TransformEvent, }, }; use std::collections::HashMap; #[derive(Debug, Default, Copy, Clone, PartialE...
use stevia_ast::{ prelude::*, ty::{ Type, HasType as _, }, iter::ChildrenMut, transformer::{ AnyExprTransformer, TransformOutcome, TransformEffect, TransformEvent, }, }; use std::collections::HashMap; #[derive(Debug, Default, Copy, Clone, PartialE...
#[cfg(test)] mod tests { use super::*; use crate::prelude::*; use crate::simplifications; modular_ast_transformer! { #[derive(Default)] struct ModularIfConstraintPropagator { _0: IfConstraintPropagator, _1: simplifications::BoolConstPropagator, _2: ...
let mut effect = TransformEffect::Identity; for child in cond.children_mut() { effect |= propagate_if_constraint(child, seen) } return effect } let mut effect = TransformEffect::Identity; for child in expr.children_mut() { effect |= propagate_if_constrai...
function_block-function_prefix_line
[ { "content": "/// Writes the given expression tree into the given writer in the SMTLib2 syntax format.\n\npub fn write_smtlib2<'e, E>(ctx: &Context, out: &mut fmt::Write, expr: E)\n\n where E: Into<&'e AnyExpr>\n\n{\n\n let expr = expr.into();\n\n SMTLibWriter::new(ctx, out).write_expr(expr)\n\n}\n\n\n...
Rust
pipewire/src/loop_.rs
FossoresLP/pipewire-rs
d519624d28a8b7f5b8d2584b09abf0ff6f48bb82
use std::{convert::TryInto, os::unix::prelude::*, ptr, time::Duration}; use libc::{c_int, c_void}; use signal::Signal; use spa::{flags::IoFlags, result::SpaResult, spa_interface_call_method}; use crate::utils::assert_main_thread; pub trait Loop { unsafe fn as_ptr(&self) -> *mut pw_sys::pw_loop; ...
use std::{convert::TryInto, os::unix::prelude::*, ptr, time::Duration}; use libc::{c_int, c_void}; use signal::Signal; use spa::{flags::IoFlags, result::SpaResult, spa_interface_call_method}; use crate::utils::assert_main_thread; pub trait Loop { unsafe fn as_ptr(&self) -> *mut pw_sys::pw_loop; ...
#[must_use] fn add_event<F>(&self, callback: F) -> EventSource<Self> where F: Fn() + 'static, Self: Sized, { unsafe extern "C" fn call_closure<F>(data: *mut c_void, _count: u64) where F: Fn(), { let callback = (data as *mut...
fn add_signal_local<F>(&self, signal: Signal, callback: F) -> SignalSource<Self> where F: Fn() + 'static, Self: Sized, { assert_main_thread(); unsafe extern "C" fn call_closure<F>(data: *mut c_void, _signal: c_int) where F: Fn(), { let cal...
function_block-full_function
[ { "content": "/// Implementors of this trait can be serialized into pods that always have the same size.\n\n/// This lets them be used as elements in `Array` type SPA Pods.\n\n///\n\n/// Implementors of this automatically implement [`PodSerialize`].\n\n///\n\n/// Serialization is accomplished by having the type...
Rust
src/manager.rs
ImJasonH/controller-rs
541431c30d90fa532b5474293b47973b9591b861
use crate::{telemetry, Error, Result}; use chrono::prelude::*; use futures::{future::BoxFuture, FutureExt, StreamExt}; use kube::{ api::{Api, ListParams, Patch, PatchParams, Resource}, client::Client, CustomResource, }; use kube_runtime::controller::{Context, Controller, ReconcilerAction}; use maplit::hashm...
use crate::{telemetry, Error, Result}; use chrono::prelude::*; use futures::{future::BoxFuture, FutureExt, StreamExt}; use kube::{ api::{Api, ListParams, Patch, PatchParams, Resource}, client::Client, CustomResource, }; use kube_runtime::controller::{Context, Controller, ReconcilerAction}; use maplit::hashm...
ed_events.inc(); info!( "Reconciled Foo \"{}\" in namespace \"{}\" in {}", name, ns, duration ); Ok(ReconcilerAction { requeue_after: Some(RESYNC), }) } fn error_policy(error: &Error, _ctx: Context<Data>) -> ReconcilerAction { warn!("reconcile failed: {:?}", error); ...
Version": "imjasonh.com/v1alpha1", "kind": "Foo", "status": FooStatus { conditions: vec![Condition { type_: Type::Good, status: Status::False, severity: Severity::Error, reason: "NotGood".to_string(),...
function_block-random_span
[ { "content": "/// Fetch an opentelemetry::trace::TraceId as hex through the full tracing stack\n\npub fn get_trace_id() -> String {\n\n use opentelemetry::trace::TraceContextExt; // opentelemetry::Context -> opentelemetry::trace::Span\n\n use tracing_opentelemetry::OpenTelemetrySpanExt; // tracing::Span ...
Rust
src/displayer.rs
Cobrand/toyunda-player-rs-old
85fe011e2249a58c7d3777bc030f20bd1843d225
extern crate sdl2; extern crate sdl2_ttf; use sdl2::render::{Renderer, TextureQuery, BlendMode}; use sdl2::rect::Rect; use sdl2::pixels::Color; use std::vec::Vec; use std::cmp::Ordering; use std::path::Path; use std::ops::Index; use std::ops::DerefMut; pub struct FontSet { font_size: u16, font_regular: sdl2_t...
extern crate sdl2; extern crate sdl2_ttf; use sdl2::render::{Renderer, TextureQuery, BlendMode}; use sdl2::rect::Rect; use sdl2::pixels::Color; use std::vec::Vec; use std::cmp::Ordering; use std::path::Path; use std::ops::Index; use std::ops::DerefMut; pub struct FontSet { font_size: u16, font_regular: sdl2_t...
} else { Ok(font_set_max) } } } } } } } pub struct Displayer<'a> { fonts: FontList, renderer: Renderer<'a>, ttf_context: sdl2_ttf::Sdl2TtfContext, } impl<'a> Displayer<'a> { pub fn new(mut...
ont_set_max = &self.fonts[index]; if (font_set_max.font_size - font_size > font_size - font_set_min.font_size) { Ok(font_set_min)
function_block-random_span
[ { "content": "fn get_mpv_gl(mpv: &mpv::Mpv, video_subsystem: &mut sdl2::VideoSubsystem) -> mpv::OpenglContext {\n\n let ptr = video_subsystem as *mut _ as *mut libc::c_void;\n\n mpv.get_opengl_context(Some(do_pote), ptr).unwrap()\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 1, "score": 468...
Rust
src/triangle.rs
andystanton/raytracer-rs
e000aeba06479636275df18899859b803097b4c9
use hitable::{ Hitable, HitRecord, }; use ray::Ray3; use aabb::AABB; use material::Material; use cgmath::{ Point3, Vector3, InnerSpace, }; use std::time::Instant; pub struct Triangle { vertices: [Point3<f32>; 3], surface_normal: Vector3<f32>, material: Material, } impl Triangle { ...
use hitable::{ Hitable, HitRecord, }; use ray::Ray3; use aabb::AABB; use material::Material; use cgmath::{ Point3, Vector3, InnerSpace, }; use std::time::Instant; pub struct Triangle { vertices: [Point3<f32>; 3], surface_normal: Vector3<f32>, material: Material, } impl Triangle { ...
} pub struct NormalTriangle { vertices: [Point3<f32>; 3], normals: [Vector3<f32>; 3], material: Material, } impl NormalTriangle { pub fn new(vertices: [Point3<f32>; 3], normals: [Vector3<f32>; 3], material: Material) -> Self { Self { vertices, normals, material } } } impl Hitable for Nor...
fn bounding_box(&self, _: Instant, _: Instant) -> Option<AABB> { let mut min = Point3::new(self.vertices[0].x.min(self.vertices[1].x), self.vertices[0].y.min(self.vertices[1].y), self.vertices[0].z.min(self.vertices[1].z)); min = Point3::new(min.x.min(self.vertices[2].x), min.y.min(self.vertices[2].y), ...
function_block-full_function
[ { "content": "fn reflect(v: Vector3<f32>, n: Vector3<f32>) -> Vector3<f32> {\n\n v - 2.0 * v.dot(n) * n\n\n}\n\n\n", "file_path": "src/material.rs", "rank": 0, "score": 153677.49299765177 }, { "content": "fn refract(v: Vector3<f32>, n: Vector3<f32>, ni_over_nt: f32) -> (Vector3<f32>, bool...
Rust
src/uart.rs
imxrt-rs/imxrt-ccm
85934e0b078c16c70743a954c95bc8d4acf8ec98
use super::{set_clock_gate, ClockGate, ClockGateLocation, ClockGateLocator, Instance}; use crate::register::{Field, Register}; use core::marker::PhantomData; const CLOCK_FREQUENCY_HZ: u32 = super::OSCILLATOR_FREQUENCY_HZ; const DEFAULT_CLOCK_DIVIDER: u32 = 1; pub struct UARTClock<C>(PhantomData<C>); impl<C> UARTCl...
use super::{set_clock_gate, ClockGate, ClockGateLocation, ClockGateLocator, Instance}; use crate::register::{Field, Register}; use core::marker::PhantomData; const CLOCK_FREQUENCY_HZ: u32 = super::OSCILLATOR_FREQUENCY_HZ; const DEFAULT_CLOCK_DIVIDER: u32 = 1; pub struct UARTClock<C>(PhantomData<C>); impl<C> UARTCl...
#[test] fn uart_divider_lower_bound() { let mut mem: u32 = 0; unsafe { let reg = register(&mut mem); configure_(0, &reg); assert_eq!(frequency_(&reg), CLOCK_FREQUENCY_HZ); } } #[test] fn uart_divider() { let mut mem: u32 = 0; ...
fn uart_divider_upper_bound() { let mut mem: u32 = 0; unsafe { let reg = register(&mut mem); configure_(65, &reg); assert_eq!(frequency_(&reg), CLOCK_FREQUENCY_HZ / 64); } }
function_block-full_function
[ { "content": "#[inline(always)]\n\nfn frequency_(reg: &Register) -> u32 {\n\n let divider = reg.divider() + 1;\n\n CLOCK_FREQUENCY_HZ / divider\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n use super::{\n\n configure_, frequency_, Register, CLOCK_FREQUENCY_HZ, LPI2C_CLK_PODF, LPI2C_CLK_SEL,\n\...
Rust
basic/basic-interpreter-rust/src/casting.rs
talesporto/dockerfiles
b205e53df9f13475da3445e75bdadb4842603c75
use crate::parser::TypeQualifier; use crate::variant; use crate::variant::Variant; trait QBNumberCast<T> { fn try_cast(&self) -> Result<T, String>; } impl QBNumberCast<f64> for f32 { fn try_cast(&self) -> Result<f64, String> { Ok(*self as f64) } } impl QBNumberCast<i32> for f32 { fn try_cast(...
use crate::parser::TypeQualifier; use crate::variant; use crate::variant::Variant; trait QBNumberCast<T> { fn try_cast(&self) -> Result<T, String>; } impl QBNumberCast<f64> for f32 { fn try_cast(&self) -> Result<f64, String> { Ok(*self as f64) } } impl QBNumberCast<i32> for f32 { fn try_cast(...
#[test] fn to_long() { assert_eq!( cast(Variant::from(1.0_f32), TypeQualifier::AmpersandLong).unwrap(), Variant::from(1_i64) ); } } mod from_double { use super::*; #[test] fn to_float() { asse...
assert_eq!( cast(Variant::from(1.0_f32), TypeQualifier::PercentInteger).unwrap(), Variant::from(1) ); }
function_block-function_prefix_line
[ { "content": "fn val(s: String) -> std::result::Result<Variant, String> {\n\n let mut is_positive = true;\n\n let mut value: f64 = 0.0;\n\n let mut frac_power: i32 = 0;\n\n\n\n const STATE_INITIAL: u8 = 0;\n\n const STATE_SIGN: u8 = 1;\n\n const STATE_INT: u8 = 2;\n\n const STATE_DOT: u8 = ...
Rust
src/gen/evaluated.rs
Edgeworth/memega
46bc77638229e0630e947625163f729f109eaf00
use derive_more::Display; use eyre::{eyre, Result}; use rand::prelude::SliceRandom; use crate::eval::{Evaluator, State}; use crate::evolve::cfg::{ Crossover, Duplicates, EvolveCfg, Mutation, Replacement, Selection, Survival, }; use crate::evolve::evolver::RandState; use crate::gen::member::Member; use crate::gen::...
use derive_more::Display; use eyre::{eyre, Result}; use rand::prelude::SliceRandom; use crate::eval::{Evaluator, State}; use crate::evolve::cfg::{ Crossover, Duplicates, EvolveCfg, Mutation, Replacement, Selection, Survival, }; use crate::evolve::evolver::RandState; use crate::gen::member::Member; use crate::gen::...
size as f64 - new_mems.len() as f64; (prop * remaining).ceil().max(0.0) as usize } }; for _ in 0..num { new_mems.push(Member::new::<E>((*genfn)(), cfg)); } } const NUM_TRIES: usize = 3; for...
daptive => { let lrate = 1.0 / (self.mems.len() as f64).sqrt(); mutate_rate(&mut s.params.mutation, 1.0, |v| { mutate_lognorm(v, lrate).clamp(0.0, 1.0) }); } }; Self::check_weights(&s.params...
random
[ { "content": "// Whole arithmetic recombination with a random combination multiplier.\n\npub fn crossover_arith(s1: &mut [f64], s2: &mut [f64]) {\n\n let mut r = rand::thread_rng();\n\n crossover_arith_alpha(s1, s2, r.gen());\n\n}\n\n\n", "file_path": "src/ops/crossover.rs", "rank": 0, "score"...
Rust
build.rs
rnleach/eccodes-sys
edf033c2d9fca75efc09509fa6b12b260a64e4a2
use flate2::read::GzDecoder; use std::{ env, error::Error, fs::File, path::{Path, PathBuf}, }; use tar::Archive; const VERSION: &str = include_str!("version"); const EXTRACTED_LIB: &str = concat!("eccodes-", include_str!("version"), "-Source"); const ARCHIVED_LIB: &str = concat!("eccodes-", include_st...
use flate2::read::GzDecoder; use std::{ env, error::Error, fs::File, path::{Path, PathBuf}, }; use tar::Archive; const VERSION: &str = include_str!("version"); const EXTRACTED_LIB: &str = concat!("eccodes-", include_str!("version"), "-Source"); const ARCHIVED_LIB: &str = concat!("eccodes-", include_st...
fn install_eccodes_c_libs<P: AsRef<Path>>(home_dir_install: P) -> Result<(), Box<dyn Error>> { let mut arch_path = PathBuf::new(); arch_path.push("."); arch_path.push("lib"); let arch_path = arch_path.join(ARCHIVED_LIB); let tmp_dir = tempdir::TempDir::new("eccodes_install")?; let src_path = ...
RROR INSTALLING ECCODES C LIB"); pkg_config::Config::new() .atleast_version(VERSION) .probe("eccodes") .expect("UNABLE TO FIND ECCODES C LIB AFTER INSTALLING") } Err(err) => panic!("FATAL ERROR: {}", err), }; let header_path =...
function_block-function_prefixed
[ { "content": "#![allow(non_upper_case_globals)]\n\n#![allow(non_camel_case_types)]\n\n#![allow(non_snake_case)]\n\n\n\ninclude!(concat!(env!(\"OUT_DIR\"), \"/bindings.rs\"));\n", "file_path": "src/lib.rs", "rank": 2, "score": 11979.949600948996 }, { "content": "# eccodes-sys\n\nRust bindings...
Rust
jelly/src/accounts/token_generator.rs
delneg/bitcoin-address-generator-api
2c9802cdcecf2da337b40885d8f7239a47455c7c
use std::env; use sha2::Sha256; use radix::RadixNum; use hmac::{Hmac, Mac, NewMac}; use chrono::{Utc, TimeZone}; use constant_time_eq::constant_time_eq; use crate::error::Error; type HmacSha256 = Hmac<Sha256>; const KEY_SALT: &str = "com.jelly.accounts.token_generator"; fn num_seconds() -> i64 { let now = Utc:...
use std::env; use sha2::Sha256; use radix::RadixNum; use hmac::{Hmac, Mac, NewMac}; use chrono::{Utc, TimeZone}; use constant_time_eq::constant_time_eq; use crate::error::Error; type HmacSha256 = Hmac<Sha256>; const KEY_SALT: &str = "com.jelly.accounts.token_generator"; fn num_seconds() -> i64 { let now = Utc:...
return false; } let timeout = match env::var("PASSWORD_RESET_TIMEOUT") { Ok(v) => { if let Ok(t) = v.parse::<usize>() { t } else { ...
(); if split.len() != 2 { return false; } if let Ok(timestamp) = RadixNum::from_str(split[0], 36) { if let Ok(ts) = timestamp.as_decimal() { let value = self.hash_value(); let cmp_token = hash(&value, ts as u64); if cmp_toke...
random
[ { "content": "/// Generates a random password and returns it hashed.\n\npub fn make_random_password() -> String {\n\n let mut rng = thread_rng();\n\n\n\n let password: String = (0..PASSWORD_LEN).map(|_| {\n\n let idx = rng.gen_range(0..CHARSET.len());\n\n CHARSET[idx] as char\n\n }).colle...
Rust
src/main.rs
jamesmcm/rust_ses_example
13cb8f6f3f8858c1d5f91962ede2e49f2d8ae290
mod csv_serde; mod email; mod s3; #[cfg(test)] mod tests; use crate::csv_serde::{deserialize_csv, validate_all_records}; use crate::email::{send_email, Attachment}; use crate::s3::{get_file_from_s3, write_file_to_s3}; use anyhow::Result; use csv::Writer; use lambda_runtime::error::HandlerError; use log::{error, info, ...
mod csv_serde; mod email; mod s3; #[cfg(test)] mod tests; use crate::csv_serde::{deserialize_csv, validate_all_records}; use crate::email::{send_email, Attachment}; use crate::s3::{get_file_from_s3, write_file_to_s3}; use anyhow::Result; use csv::Writer; use lambda_runtime::error::HandlerError; use log::{error, info, ...
?; Ok(()) }
send_email( RECIPIENT, "File updated successfully!", "File updated successfully!\nAttached for reference.", None, Some(Attachment::new( file, attachment_name, "text/csv; charset=utf8".to_string(), )), ses_client, rt, ...
call_expression
[ { "content": "fn validate_record(r: &Entry) -> Result<()> {\n\n if r.start_date > r.end_date {\n\n Err(anyhow!(\n\n \"Start date after end date for entry: {}, {}, {}\",\n\n r.id,\n\n r.start_date,\n\n r.end_date\n\n ))\n\n } else {\n\n Ok(()...
Rust
vendor/yaml-merge-keys/src/test.rs
riscv-android-src/toolchain-rustc
bcf972c0208490b0eb3ce3c170c2db486ba945b3
use crates::yaml_rust::Yaml; use merge_keys::{merge_keys, MergeKeyError}; fn assert_yaml_idempotent(doc: Yaml) { assert_eq!(merge_keys(doc.clone()).unwrap(), doc); } fn merge_key() -> Yaml { Yaml::String("<<".into()) } macro_rules! yaml_hash { [ $( $pair:expr ),* $(,)* ] => { Yaml::Hash([...
use crates::yaml_rust::Yaml; use merge_keys::{merge_keys, MergeKeyError}; fn assert_yaml_idempotent(doc: Yaml) { assert_eq!(merge_keys(doc.clone()).unwrap(), doc); } fn merge_key() -> Yaml { Yaml::String("<<".into()) } macro_rules! yaml_hash { [ $( $pair:expr ),* $(,)* ] => { Yaml::Hash([...
#[test] fn test_merge_key_array() { let hash = yaml_hash![ ( merge_key(), Yaml::Array(vec![ yaml_hash![(Yaml::Integer(15), Yaml::Integer(10))], yaml_hash![(Yaml::Integer(20), Yaml::Integer(10))], ]), ), (Yaml::Integer(10),...
fn test_merge_key_precedence() { let hash = yaml_hash![ ( merge_key(), yaml_hash![(Yaml::Integer(10), Yaml::Integer(10))], ), (Yaml::Integer(10), Yaml::Null), (Yaml::Integer(100), Yaml::String("string".into())), ]; let expected = yaml_hash![ (Y...
function_block-full_function
[]
Rust
src/read/page_iterator.rs
Dandandan/parquet2
20a1fb9d705c827e045504a5d5cb01537ba07c27
use std::{io::Read, sync::Arc}; use parquet_format::{CompressionCodec, PageHeader as ParquetPageHeader, PageType}; use thrift::protocol::TCompactInputProtocol; use crate::error::Result; use crate::metadata::ColumnDescriptor; use super::page::CompressedPage; use super::page::PageHeader; use super::page_dict::{read_pa...
use std::{io::Read, sync::Arc}; use parquet_format::{CompressionCodec, PageHeader as ParquetPageHeader, PageType}; use thrift::protocol::TCompactInputProtocol; use crate::error::Result; use crate::metadata::ColumnDescriptor; use super::page::CompressedPage; use super::page::PageHeader; use super::page_dict::{read_pa...
fn build_page<R: Read>( reader: &mut PageIterator<R>, buffer: &mut Vec<u8>, ) -> Result<Option<CompressedPage>> { let page_header = reader.read_page_header()?; let read_size = page_header.compressed_page_size as usize; if read_size > 0 { buffer.resize(read_size, 0); reader.reader....
fn next_page<R: Read>( reader: &mut PageIterator<R>, buffer: &mut Vec<u8>, ) -> Result<Option<CompressedPage>> { let total_values = reader.total_num_values; let mut seen_values = reader.seen_num_values; if seen_values >= total_values { return Ok(None); }; while seen_values < total_v...
function_block-full_function
[ { "content": "/// Reads a file's metadata.\n\n// Layout of Parquet file\n\n// +---------------------------+-----+---+\n\n// | Rest of file | B | A |\n\n// +---------------------------+-----+---+\n\n// where A: parquet footer, B: parquet metadata.\n\n//\n\n// The reader first reads DEFAULT_FOOTER_...
Rust
src/bin/day4.rs
kevinbader/advent-of-code-2021
73cb0a57d7900812bc1be156864d6a3a4e35894e
use std::{collections::HashMap, fs, num::ParseIntError}; use anyhow::Context; fn main() { let input = fs::read_to_string("./input/day4.txt").expect("failed to read input file"); let (boards, drawn_numbers) = parse(&input).unwrap(); match play_to_win(boards, drawn_numbers) { BingoResult::Bingo { b...
use std::{collections::HashMap, fs, num::ParseIntError}; use anyhow::Context; fn main() { let input = fs::read_to_string("./input/day4.txt").expect("failed to read input file"); let (boards, drawn_numbers) = parse(&input).unwrap(); match play_to_win(boards, drawn_numbers) { BingoResult::Bingo { b...
core } = board.mark(num) { return BingoResult::Bingo { board_no: i + 1, score, }; } } } BingoResult::NoBingo } fn play_to_lose(mut boards: Vec<Board>, drawn_numbers: DrawnNumbers) -> BingoResult { for num in drawn_n...
let drawn_numbers = DrawnNumbers::try_from(lines.next().map(|l| l.trim()).expect("no lines to parse")) .context("Failed to parse the first line")?; let boards = lines .map(|l| l.trim()) .filter(|l| !l.is_empty()) .collect::<Vec<&str>>() .chunks_exact(5) ...
random
[ { "content": "pub fn parse(input: &str) -> Vec<Lanternfish> {\n\n input\n\n .trim()\n\n .split(',')\n\n .map(|n| Lanternfish {\n\n timer: n.parse::<usize>().unwrap(),\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "src/day6.rs", "rank": 0, "score": 6...
Rust
rust/origen/src/core/file_handler.rs
Origen-SDK/o2
5b0f9a6d113ddebc73c7ee224931e8b2d0301794
use crate::{Error, Result}; use std::fs; use std::fs::create_dir_all; use std::fs::File as StdFile; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::sync::Mutex; use path_slash::PathBufExt; lazy_static! { static ref FILES: Mutex<Files> = Mutex::new(Files::new()); } #[derive(Debug)] pub struct ...
use crate::{Error, Result}; use std::fs; use std::fs::create_dir_all; use std::fs::File as StdFile; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::sync::Mutex; use path_slash::PathBufExt; lazy_static! { static ref FILES: Mutex<Files> = Mutex::new(Files::new()); } #[derive(Debug)] pub struct ...
} Ok(()) } } #[derive(Debug, Clone)] pub struct FileHandler { i: usize, } impl FileHandler { pub fn new() -> FileHandler { FileHandler { i: 0 } } pub fn init(&mut self, files: Vec<String>) -> Result<()> { let mut f = FILES.lock().unwrap(); f.init(files)?;...
if path.is_dir() { self.resolve_dir(&path)?; } else { self.files.push(path); }
if_condition
[ { "content": "/// Temporarily sets the current dir to the given dir for the duration of the given\n\n/// function and then restores it at the end.\n\n/// An error will be returned if there is a problem switching to the given directory,\n\n/// e.g. if it doesn't exist, otherwise the result from the given functio...
Rust
src/main.rs
zekroTJA/bulkscale
b3b29043c1f969bb1f9d0d7cde8fe37ba3af79bb
mod utils; use log; use image; use image::imageops::FilterType; use std::{fs, process, path::Path, error::Error}; use clap::Clap; use threadpool::ThreadPool; #[derive(Clap)] #[clap(version = "0.1", author = "zekro <contact@zekro.de>")] struct Args { #[clap(short, long, about = "The scale of the results")] sca...
mod utils; use log; use image; use image::imageops::FilterType; use std::{fs, process, path::Path, error::Error}; use clap::Clap; use threadpool::ThreadPool; #[derive(Clap)] #[clap(version = "0.1", author = "zekro <contact@zekro.de>")] struct Args { #[clap(short, long, about = "The scale of the results")] sca...
e) { Ok(img) => img, Err(err) => return Err(err.into()), }; let img_buffer = img.to_rgb(); let (new_width, new_height) = match scale { Some(s) => ( (img_buffer.width() as f32 * s) as u32, (img_buffer.height() as f32 * s) as u32, ), None => ( ...
function_block-function_prefixed
[ { "content": "pub fn filtertype_fromstr(val: &String) -> Result<FilterType, Box<dyn Error>> {\n\n let val = val.to_lowercase();\n\n\n\n match val.as_str() {\n\n \"nearest\" => Ok(FilterType::Nearest),\n\n \"triangle\" => Ok(FilterType::Triangle),\n\n \"catmullrom\" => Ok(FilterType::C...
Rust
lib/zap-build-engine/src/build_cache.rs
AbstractMachinesLab/crane
98e3945fc24e99b09602a54138a8b321e32452c2
use super::Sandbox; use anyhow::Context; use log::*; use std::collections::HashMap; use std::path::PathBuf; use zap_core::{ComputedTarget, Label, ZapConfig}; #[derive(Debug, Clone)] pub struct BuildCache { root: PathBuf, memcache: HashMap<String, Label>, } #[derive(Debug, Clone)] pub enum CacheHitType { M...
use super::Sandbox; use anyhow::Context; use log::*; use std::collections::HashMap; use std::path::PathBuf; use zap_core::{ComputedTarget, Label, ZapConfig}; #[derive(Debug, Clone)] pub struct BuildCache { root: PathBuf, memcache: HashMap<String, Label>, } #[derive(Debug, Clone)] pub enum CacheHitType { M...
pub fn absolute_path_by_hash(&self, hash: &str) -> PathBuf { let path = self.root.join(hash); std::fs::canonicalize(&path).unwrap_or_else(|_| { panic!( "Could not find {:?} in disk, has the cache been modified manually?", &path ) }) ...
pub fn promote_outputs( &self, node: &ComputedTarget, dst: &PathBuf, ) -> Result<(), anyhow::Error> { trace!("Promoting outputs for {}", node.target.label().to_string()); let hash = node.hash(); let hash_path = self.root.join(&hash); let mut paths: HashMap<Pa...
function_block-full_function
[]