lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
examples/sounds.rs
StrixVaria/ggez
54683ca6dc71f6582f23706f65cfebec70d9b1f6
extern crate ggez; use ggez::audio; use ggez::audio::SoundSource; use ggez::event; use ggez::graphics; use ggez::input; use ggez::nalgebra as na; use ggez::{Context, GameResult}; use std::env; use std::path; use std::time::Duration; struct MainState { sound: audio::Source, } impl MainState { fn new(ctx: &mu...
extern crate ggez; use ggez::audio; use ggez::audio::SoundSource; use ggez::event; use ggez::graphics; use ggez::input; use ggez::nalgebra as na; use ggez::{Context, GameResult}; use std::env; use std::path; use std::time::Duration; struct MainState { sound: audio::Source, } impl MainState { fn new(ctx: &mu...
let (ctx, event_loop) = &mut cb.build()?; let state = &mut MainState::new(ctx)?; event::run(ctx, event_loop, state) }
function_block-function_prefixed
[ { "content": "/// Adds the given (absolute) path to the list of directories\n\n/// it will search to look for resources.\n\n///\n\n/// You probably shouldn't use this in the general case, since it is\n\n/// harder than it looks to make it bulletproof across platforms.\n\n/// But it can be very nice for debuggin...
Rust
lib/src/collections.rs
MingweiSamuel/spinach
622fdb841ec1130ff2c896a8ca8f87d0e3b8869b
use std::array::IntoIter; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::hash::Hash; fn bool_to_option<'a>(value: bool) -> Option<&'a ()> { if value { Some(&()) } else { None } } fn bool_to_option_mut<'a>(value: bool) -> Option<&'a mut ()> { if value { Some(Box::leak(Box::new(()))) } el...
use std::array::IntoIter; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::hash::Hash; fn bool_to_option<'a>(value: bool) -> Option<&'a ()> { if value { Some(&()) } else { None } } fn bool_to_option_mut<'a>(value: bool) -> Option<&'a mut ()> { if value { Some(Box::leak(Box::new(()))) } el...
} fn len(&self) -> usize { self.mask.iter().filter(|mask| **mask).count() } type Keys<'s> = impl Iterator<Item = &'s K>; fn keys(&self) -> Self::Keys<'_> { self.mask.iter() .zip(self.vals.iter()) .filter(|(mask, _)| **mask) .map(|(_, item)| item)...
bool_to_option_mut(self.mask.iter() .zip(self.vals.iter()) .any(|(mask, item)| *mask && item == key) )
call_expression
[ { "content": "pub fn fixed_split<O: Op, const N: usize>(op: O) -> [SplitOp<O>; N] {\n\n let splitter = Splitter::new(op);\n\n [(); N].map(|_| splitter.internal_add_split_reveal())\n\n}\n\n\n\n\n", "file_path": "lib/src/op/splitop.rs", "rank": 3, "score": 194552.13651650015 }, { "conten...
Rust
dna/zomes/todo/src/entries/item/handlers.rs
kristoferlund/hc-graphql-todo
b82b7d461b264b470bcadf01e3b8b3113378044b
use crate::utils; use crate::entries::list::handlers::*; use super::*; use juniper::FieldResult; use utils::generate_short_id; pub fn item(id: juniper::ID) -> FieldResult<Item> { Ok(Item::new_from_entry(item_entry(id)?)) } pub fn item_entry(id: juniper::ID) -> FieldResult<ItemEntry> { Ok(utils::try_get_and_c...
use crate::utils; use crate::entries::list::handlers::*; use super::*; use juniper::FieldResult; use utils::generate_short_id; pub fn item(id: juniper::ID) -> FieldResult<Item> { Ok(Item::new_from_entry(item_entry(id)?)) } pub fn item_entry(id: juniper::ID) -> FieldResult<ItemEntry> { Ok(utils::try_get_and_c...
ntry_hash(input.id)?; let links_iter = get_links(list_entry_hash.clone().into(), None)? .into_inner() .into_iter(); for item_link in links_iter { if item_link.target == item_entry_hash { delete_link(item_link.create_link_hash)?; } } let element = get(item_...
list_entry_hash = list_entry_hash(list_id)?; let item_links = get_links(list_entry_hash.into(), None)? .into_inner() .into_iter(); let mut edges = Vec::with_capacity(item_links.len()); for item_link in item_links { let item_entry: ItemEntry = utils::try_get_and_convert(item_link.target)?; ...
random
[ { "content": "pub fn generate_short_id() -> String {\n\n let bytes = random_bytes(6).unwrap();\n\n\n\n const CHARSET: &[u8] = b\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\\\n\n abcdefghijklmnopqrstuvwxyz\\\n\n 0123456789\";\n\n const CHARSET_LEN: f32 = CHARSET.len() as f32;\n\n\n\n (0..bytes.len())\n\n ...
Rust
src/bin/rbw-agent/agent.rs
niki-on-github/rbw
e2987d577a48ad8909bda7c7730c03a43615c5c5
use anyhow::Context as _; #[derive(Debug)] pub enum TimeoutEvent { Set, Clear, } pub struct State { pub priv_key: Option<rbw::locked::Keys>, pub org_keys: Option<std::collections::HashMap<String, rbw::locked::Keys>>, pub timeout_chan: tokio::sync::mpsc::UnboundedSender<TimeoutEvent>, } im...
use anyhow::Context as _; #[derive(Debug)] pub enum TimeoutEvent { Set, Clear, } pub struct State { pub priv_key: Option<rbw::locked::Keys>, pub org_keys: Option<std::collections::HashMap<String, rbw::locked::Keys>>, pub timeout_chan: tokio::sync::mpsc::UnboundedSender<TimeoutEvent>, } im...
let set_timeout = match &req.action { rbw::protocol::Action::Login => { crate::actions::login(sock, state.clone(), req.tty.as_deref()) .await?; true } rbw::protocol::Action::Unlock => { crate::actions::unlock(sock, state.clone(), req.tty.a...
let req = match req { Ok(msg) => msg, Err(error) => { sock.send(&rbw::protocol::Response::Error { error }).await?; return Ok(()); } };
assignment_statement
[ { "content": "pub fn default_lock_timeout() -> u64 {\n\n 3600\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 0, "score": 119506.90520330094 }, { "content": "pub fn default_pinentry() -> String {\n\n \"pinentry\".to_string()\n\n}\n\n\n\nimpl Config {\n\n pub fn new() -> Self {\n\...
Rust
rincon_client/src/index/types/tests.rs
haraldmaida/arangodb-rust-driver
e0bde6c78e43668c3cad0b1dd07466dfdd6fa4eb
use std::str::FromStr; use serde_json; use super::*; #[test] fn get_index_key_from_str() { let index_key = IndexKey::from_str("12341").unwrap(); assert_eq!("12341", index_key.as_str()); } #[test] fn get_index_key_from_str_with_slash_character_in_the_middle() { let result = IndexKey::from_str("mine/12341...
use std::str::FromStr; use serde_json; use super::*; #[test] fn get_index_key_from_str() { let index_key = IndexKey::from_str("12341").unwrap(); assert_eq!("12341", index_key.as_str()); } #[test] fn get_index_key_from_str_with_slash_character_in_the_middle() { let result = IndexKey::from_str("mine/12341...
x() { let index_json = r#"{ "constraint" : true, "fields" : [ "e", "f" ], "id" : "products/11491", "ignoreNull" : true, "isNewlyCreated" : true, "sparse" : true, "type" : "geo2", ...
ist_index) = index { assert_eq!("products", index_id.collection_name()); assert_eq!("11556", index_id.index_key()); assert_eq!( &vec!["a".to_owned(), "b".to_owned()][..], skip_list_index.fields() ); assert_eq!(false, skip_list_index.is_newly_created()); ...
random
[ { "content": "#[test]\n\nfn create_index_of_type_hash_for_collection() {\n\n arango_test_with_document_collection(\"index_customers04\", |conn, ref mut core| {\n\n let method = CreateIndex::new(\n\n \"index_customers04\",\n\n NewHashIndex::new(vec![\"name\".to_owned()], true, fal...
Rust
src/target/r1cs/bellman.rs
julesdesmit/circ
a9fd7888c43d01913721fd98374775a21af71754
use ::bellman::{Circuit, ConstraintSystem, LinearCombination, SynthesisError, Variable}; use ff::{PrimeField, PrimeFieldBits}; use gmp_mpfr_sys::gmp::limb_t; use log::debug; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; use std::str::FromStr; use super::*; ...
use ::bellman::{Circuit, ConstraintSystem, LinearCombination, SynthesisError, Variable}; use ff::{PrimeField, PrimeFieldBits}; use gmp_mpfr_sys::gmp::limb_t; use log::debug; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; use std::str::FromStr; use super::*; ...
impl<'a, F: PrimeField + PrimeFieldBits, S: Display + Eq + Hash + Ord> Circuit<F> for &'a R1cs<S> { fn synthesize<CS>(self, cs: &mut CS) -> std::result::Result<(), SynthesisError> where CS: ConstraintSystem<F>, { let f_mod = modulus_as_int::<F>(); assert_eq!( *self.modu...
fn modulus_as_int<F: PrimeFieldBits>() -> Integer { let mut bits = F::char_le_bits().to_bitvec(); let mut acc = Integer::from(0); while let Some(b) = bits.pop() { acc <<= 1; acc += b as u8; } acc }
function_block-full_function
[ { "content": "/// Run the tuple elimination pass.\n\npub fn scalarize_inputs(cs: &mut Computation) {\n\n let mut pass = Pass;\n\n pass.traverse(cs);\n\n #[cfg(debug_assertions)]\n\n assert_all_vars_are_scalars(cs);\n\n}\n\n\n", "file_path": "src/ir/opt/scalarize_vars.rs", "rank": 0, "sco...
Rust
src/dsn.rs
kornelski/rust-sentry-types
b25761651ca755c4a55954e67e8f24e2ece67c53
use std::fmt; use std::str::FromStr; use failure::Fail; use url::Url; use crate::auth::{auth_from_dsn_and_client, Auth}; use crate::project_id::{ParseProjectIdError, ProjectId}; #[derive(Debug, Fail)] pub enum ParseDsnError { #[fail(display = "no valid url provided")] InvalidUrl, #[fail(display...
use std::fmt; use std::str::FromStr; use failure::Fail; use url::Url; use crate::auth::{auth_from_dsn_and_client, Auth}; use crate::project_id::{ParseProjectIdError, ProjectId}; #[derive(Debug, Fail)] pub enum ParseDsnError { #[fail(display = "no valid url provided")] InvalidUrl, #[fail(display...
sn::from_str(url).unwrap(); assert_eq!("https://username:@domain:8888/42", dsn.to_string()); } #[test] fn test_dsn_http_url() { let url = "http://username:@domain:8888/42"; let dsn = Dsn::from_str(url).unwrap(); assert_eq!(url, dsn.to_string()); } #[test] #[shou...
let url = "http://username:@domain/42"; let dsn = Dsn::from_str(url).unwrap(); assert_eq!(dsn.port(), 80); assert_eq!(url, dsn.to_string()); assert_eq!( dsn.store_api_url().to_string(), "http://domain/api/42/store/" ); } #[test] fn te...
random
[ { "content": "#[test]\n\nfn test_auth_to_dsn() {\n\n let url = \"https://username:password@domain:8888/23\";\n\n let dsn = url.parse::<Dsn>().unwrap();\n\n let auth = dsn.to_auth(Some(\"sentry-rust/1.0\"));\n\n assert_eq!(auth.client_agent(), Some(\"sentry-rust/1.0\"));\n\n assert_eq!(auth.versio...
Rust
src/desktop/location.rs
jtojnar/ashpd
7cd1792916b9e169cd015f975f4f453fe5c2207c
use std::fmt::Debug; use futures::TryFutureExt; use serde::{Deserialize, Serialize}; use serde_repr::{Deserialize_repr, Serialize_repr}; use zvariant::OwnedObjectPath; use zvariant_derive::{DeserializeDict, SerializeDict, Type, TypeDict}; use super::{HandleToken, SessionProxy, DESTINATION, PATH}; use crate::{ h...
use std::fmt::Debug; use futures::TryFutureExt; use serde::{Deserialize, Serialize}; use serde_repr::{Deserialize_repr, Serialize_repr}; use zvariant::OwnedObjectPath; use zvariant_derive::{DeserializeDict, SerializeDict, Type, TypeDict}; use super::{HandleToken, SessionProxy, DESTINATION, PATH}; use crate::{ h...
} #[derive(Debug, SerializeDict, DeserializeDict, TypeDict)] struct LocationInner { #[zvariant(rename = "Accuracy")] accuracy: f64, #[zvariant(rename = "Altitude")] altitude: f64, #[zvariant(rename = "Speed")] speed: f64, #[zvariant(rename = "Heading")] heading: f64, #[zvariant(ren...
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Location") .field("accuracy", &self.accuracy()) .field("altitude", &self.altitude()) .field("speed", &self.speed()) .field("heading", &self.heading()) .field("descript...
function_block-full_function
[ { "content": "/// Check whether the application is running inside a sandbox.\n\n///\n\n/// **Note** The check is very stupid as is for now.\n\npub fn is_sandboxed() -> bool {\n\n std::path::Path::new(\"/.flatpak-info\").exists()\n\n}\n\n\n\npub use self::error::{Error, PortalError};\n", "file_path": "src...
Rust
src/lib.rs
AlpaGit/clipboard-win
678785de6c6d0bba1fb3e32e0c95543418e45294
#![cfg(windows)] #![no_std] #![warn(missing_docs)] #![cfg_attr(feature = "cargo-clippy", allow(clippy::style))] extern crate alloc; pub mod formats; pub mod raw; pub(crate) mod utils; pub use raw::{get_owner, empty, seq_num, size, is_format_avail, register_format, count_formats, EnumFormats}; pub use ...
#![cfg(windows)] #![no_std] #![warn(missing_docs)] #![cfg_attr(feature = "cargo-clippy", allow(clippy::style))] extern crate alloc; pub mod formats; pub mod raw; pub(crate) mod utils; pub use raw::{get_owner, empty, seq_num, size, is_format_avail, register_format, count_formats, EnumFormats}; pub use ...
} impl Drop for Clipboard { fn drop(&mut self) { let _ = raw::close(); } } pub trait Getter<Type> { fn read_clipboard(&self, out: &mut Type) -> SysResult<usize>; } pub trait Setter<Type> { fn write_clipboard(&self, data: &Type) -> SysResult<()>; } #[inline(alway...
pub fn new_attempts_for(owner: winapi::shared::windef::HWND, mut num: usize) -> SysResult<Self> { loop { match Self::new_for(owner) { Ok(this) => break Ok(this), Err(err) => match num { 0 => break Err(err), _ => num -= 1, ...
function_block-full_function
[ { "content": "///Retrieves size of clipboard data for specified format.\n\n///\n\n///# Pre-conditions:\n\n///\n\n///* [open()](fn.open.html) has been called.\n\n///\n\n///# Returns:\n\n///\n\n///Size in bytes if format is presents on clipboard.\n\npub fn size(format: u32) -> Option<NonZeroUsize> {\n\n let cl...
Rust
nrf-softdevice/src/ble/l2cap.rs
lulf/nrf-softdevice
71b9e4b3c20ac4fab0d14c4541b365ed48aab58b
use core::marker::PhantomData; use core::ptr; use core::ptr::NonNull; use core::sync::atomic::{AtomicBool, Ordering}; use core::u16; use crate::ble::*; use crate::raw; use crate::util::{get_union_field, Portal}; use crate::{RawError, Softdevice}; pub(crate) unsafe fn on_evt(ble_evt: *const raw::ble_evt_t) { let...
use core::marker::PhantomData; use core::ptr; use core::ptr::NonNull; use core::sync::atomic::{AtomicBool, Ordering}; use core::u16; use crate::ble::*; use crate::raw; use crate::util::{get_union_field, Portal}; use crate::{RawError, Softdevice}; pub(crate) unsafe fn on_evt(ble_evt: *const raw::ble_evt_t) { let...
Ok(Channel { conn: conn.clone(), cid, _private: PhantomData, }) } raw::BLE_L2CAP_EVTS_BLE_L2CAP_EVT_CH_SETUP_REFUSED => { let l2ca...
rtialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum TxError<P: Packet> { Disconnected, TxQueueFull(P), Raw(RawError), } impl<P: Packet> From<DisconnectedError> for TxError<P> { fn from(_err: DisconnectedError) -> Self { TxError::Disconnected } } impl<P...
random
[ { "content": "fn get_app_ram_base() -> u32 {\n\n extern \"C\" {\n\n static mut __sdata: u32;\n\n }\n\n\n\n unsafe { &mut __sdata as *mut u32 as u32 }\n\n}\n\n\n", "file_path": "nrf-softdevice/src/softdevice.rs", "rank": 0, "score": 144097.68613576095 }, { "content": "fn on_so...
Rust
crates/tm4c129x/src/sysctl/nmic.rs
m-labs/ti2svd
30145706b658136c35c90290701de3f02a4b8ef2
#[doc = "Reader of register NMIC"] pub type R = crate::R<u32, super::NMIC>; #[doc = "Writer for register NMIC"] pub type W = crate::W<u32, super::NMIC>; #[doc = "Register NMIC `reset()`'s with value 0"] impl crate::ResetValue for super::NMIC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
#[doc = "Reader of register NMIC"] pub type R = crate::R<u32, super::NMIC>; #[doc = "Writer for register NMIC"] pub type W = crate::W<u32, super::NMIC>; #[doc = "Register NMIC `reset()`'s with value 0"] impl crate::ResetValue for super::NMIC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Typ...
- External Pin NMI"] #[inline(always)] pub fn external(&mut self) -> EXTERNAL_W { EXTERNAL_W { w: self } } #[doc = "Bit 2 - Power/Brown Out Event NMI"] #[inline(always)] pub fn power(&mut self) -> POWER_W { POWER_W { w: self } } #[doc = "Bit 3 - Watch Dog Timer (WDT) 0 N...
for field `WDT0`"] pub struct WDT0_W<'a> { w: &'a mut W, } impl<'a> WDT0_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { ...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/account.rs
0xA537FD/binance-rs-async
99bd29daae8a13cf11817517b76442221485d7cd
use crate::client::*; use crate::errors::*; use crate::rest_model::*; use crate::util::*; use serde_json::from_str; use std::collections::BTreeMap; static API_V3_ACCOUNT: &str = "/api/v3/account"; static API_V3_OPEN_ORDERS: &str = "/api/v3/openOrders"; static API_V3_ALL_ORDERS: &str = "/api/v3/allOrders"; static API_V...
use crate::client::*; use crate::errors::*; use crate::rest_model::*; use crate::util::*; use serde_json::from_str; use std::collections::BTreeMap; static API_V3_ACCOUNT: &str = "/api/v3/account"; static API_V3_OPEN_ORDERS: &str = "/api/v3/openOrders"; static API_V3_ALL_ORDERS: &str = "/api/v3/allOrders"; static API_V...
indow)?; let data = self.client.get_signed(API_V3_MYTRADES, &request).await?; let trade_history: Vec<TradeHistory> = from_str(data.as_str())?; Ok(trade_history) } }
lt<Vec<TradeHistory>> where S: Into<String>, { let mut parameters: BTreeMap<String, String> = BTreeMap::new(); parameters.insert("symbol".into(), symbol.into()); let request = build_signed_request(parameters, self.recv_w
function_block-random_span
[ { "content": "pub fn build_signed_request(mut parameters: BTreeMap<String, String>, recv_window: u64) -> Result<String> {\n\n if recv_window > 0 {\n\n parameters.insert(\"recvWindow\".into(), recv_window.to_string());\n\n }\n\n\n\n if let Ok(timestamp) = get_timestamp() {\n\n parameters.i...
Rust
introspection-engine/connectors/mongodb-introspection-connector/src/lib.rs
ever0de/prisma-engines
4c9d4edf238ad9c4a706eb5b7201ee0b4ebee93e
mod error; mod sampler; mod warnings; pub use error::*; use datamodel::{common::preview_features::PreviewFeature, dml::Datamodel}; use enumflags2::BitFlags; use futures::TryStreamExt; use indoc::formatdoc; use introspection_connector::{ ConnectorError, ConnectorResult, DatabaseMetadata, ErrorKind, IntrospectionCo...
mod error; mod sampler; mod warnings; pub use error::*; use datamodel::{common::preview_features::PreviewFeature, dml::Datamodel}; use enumflags2::BitFlags; use futures::TryStreamExt; use indoc::formatdoc; use introspection_connector::{ ConnectorError, ConnectorResult, DatabaseMetadata, ErrorKind, IntrospectionCo...
} #[async_trait::async_trait] impl IntrospectionConnector for MongoDbIntrospectionConnector { async fn list_databases(&self) -> ConnectorResult<Vec<String>> { let names = self .connection .list_database_names(None, None) .await .map_err(Error::from)?; ...
on(&self) -> ConnectorResult<String> { let version = mongodb_schema_describer::version(&self.connection, &self.database) .await .map_err(crate::Error::from)?; Ok(version) }
function_block-function_prefixed
[]
Rust
pipelined/bevy_render2/src/camera/projection.rs
zarik5/bevy
9dd9fed1fe3d2044ed4b0bf0efd629c1bd3e3808
use super::DepthCalculation; use bevy_ecs::reflect::ReflectComponent; use bevy_math::Mat4; use bevy_reflect::{Reflect, ReflectDeserialize}; use serde::{Deserialize, Serialize}; pub trait CameraProjection { fn get_projection_matrix(&self) -> Mat4; fn update(&mut self, width: f32, height: f32); fn depth_calc...
use super::DepthCalculation; use bevy_ecs::reflect::ReflectComponent; use bevy_math::Mat4; use bevy_reflect::{Reflect, ReflectDeserialize}; use serde::{Deserialize, Serialize}; pub trait CameraProjection { fn get_projection_matrix(&self) -> Mat4; fn update(&mut self, width: f32, height: f32); fn depth_calc...
} #[derive(Debug, Clone, Reflect, Serialize, Deserialize)] #[reflect_value(Serialize, Deserialize)] pub enum WindowOrigin { Center, BottomLeft, } #[derive(Debug, Clone, Reflect, Serialize, Deserialize)] #[reflect_value(Serialize, Deserialize)] pub enum ScalingMode { None, WindowSize, ...
fn default() -> Self { PerspectiveProjection { fov: std::f32::consts::PI / 4.0, near: 0.1, far: 1000.0, aspect_ratio: 1.0, } }
function_block-full_function
[ { "content": "/// An ordered &str->ReflectValue mapping where &str is a \"field\".\n\n/// This corresponds to rust struct types.\n\npub trait Struct: Reflect {\n\n fn field(&self, name: &str) -> Option<&dyn Reflect>;\n\n fn field_mut(&mut self, name: &str) -> Option<&mut dyn Reflect>;\n\n fn field_at(&...
Rust
crates/notation_model/src/tab_bar.rs
theAdamColton/notation
270e8592127c8e60ff33b12b040ab55dba5c92a3
use std::fmt::Display; use std::sync::{Arc, Weak}; use notation_proto::prelude::{BarPosition, Chord, Fretboard4, Fretboard6, HandShape4, HandShape6, Note, Position, SyllableNote, TabPosition}; use crate::prelude::{ Bar, BarLane, LaneEntry, LaneKind, Pitch, Section, Signature, Syllable, Tab, TabMeta, Unit, Uni...
use std::fmt::Display; use std::sync::{Arc, Weak}; use notation_proto::prelude::{BarPosition, Chord, Fretboard4, Fretboard6, HandShape4, HandShape6, Note, Position, SyllableNote, TabPosition}; use crate::prelude::{ Bar, BarLane, LaneEntry, LaneKind, Pitch, Section, Signature, Syllable, Tab, TabMeta, Unit, Uni...
4, as_fretted4, get_fretboard4, Fretboard4, HandShape4 );
{ match in_bar_pos { None => lane.get_entry(predicate), Some(in_bar_pos) => lane.get_entry_at(in_bar_pos, predicate), } } else { None } } pub fn get_chords(&self) -> Vec<Chord> { let mut chords = Vec::new(); if l...
random
[ { "content": "pub fn get_lane_entry_<T, F: Fn(usize, &LaneEntry) -> Option<T>>(\n\n v: &[Arc<LaneEntry>],\n\n predicate: &F,\n\n) -> Option<T> {\n\n for (index, entry) in v.iter().enumerate() {\n\n if let Some(result) = predicate(index, entry.as_ref()) {\n\n return Some(result);\n\n ...
Rust
src/state/mod.rs
crrodger/relm
4ade1dc8b4530d579c81774a2910b3ce06cab0d9
/* * Copyright (c) 2017 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy,...
/* * Copyright (c) 2017 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy,...
pub fn init_component<UPDATE>(stream: &EventStream<UPDATE::Msg>, mut component: UPDATE, relm: &Relm<UPDATE>) where UPDATE: Update + 'static, UPDATE::Msg: DisplayVariant + 'static, { component.subscriptions(relm); stream.set_callback(move |event| { update_component(&mut componen...
let model = UPDATE::model(&relm, model_param); let component = UPDATE::new(&relm, model); init_component::<UPDATE>(&stream, component, &relm); stream }
function_block-function_prefix_line
[ { "content": "/// After `duration` ms, emit `msg`.\n\npub fn timeout<F: Fn() -> MSG + 'static, MSG: 'static>(stream: &EventStream<MSG>, duration: u32, constructor: F) {\n\n let stream = stream.clone();\n\n gtk::timeout_add(duration, move || {\n\n let msg = constructor();\n\n stream.emit(msg)...
Rust
types/src/lib.rs
kalexm/rethinkdb-rs
3f4601e74dae52de78721c2bf1dfae903850cc4e
use std::collections::HashMap; use std::net::IpAddr; use std::ops::Deref; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; use uuid::Uuid; #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct DateTime(pub chrono::DateTime<chrono::Utc>); #[derive(Debug, Clone...
use std::collections::HashMap; use std::net::IpAddr; use std::ops::Deref; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; use uuid::Uuid; #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct DateTime(pub chrono::DateTime<chrono::Utc>); #[derive(Debug, Clone...
TableStatus {} #[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct User {} #[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Change<O, N> { pub old_val: Option<O>, pub new_val: Option<N>, #[serde(rename = "type")]...
pped: u32, pub deleted: u32, pub errors: u32, pub first_error: Option<String>, pub generated_keys: Option<Vec<Uuid>>, pub warnings: Option<Vec<String>>, pub changes: Option<Value>, } #[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct ClusterConfig {...
random
[ { "content": "// Overrides JSON's formatting of arrays to wrap them in the `MAKE_ARRAY`\n\n// command since ReQL uses arrays for serialization\n\nstruct ReqlFormatter;\n\n\n\nimpl Formatter for ReqlFormatter {\n\n #[inline]\n\n fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> Result<()>\n\n wher...
Rust
lang/src/lang_core/env/api.rs
xueying4402/liquid
fb12fd0b5108d44132d5104376d2a65de58a27c7
use crate::lang_core::env::{ backend::Env, calldata::CallData, engine::{EnvInstance, OnInstance}, error::Result, CallMode, }; use cfg_if::cfg_if; use liquid_prelude::{string::String, vec::Vec}; use liquid_primitives::{ types::{timestamp, Address}, Topics, }; pub fn set_storage<V>(key: &[u...
use crate::lang_core::env::{ backend::Env, calldata::CallData, engine::{EnvInstance, OnInstance}, error::Result, CallMode, }; use cfg_if::cfg_if; use liquid_prelude::{string::String, vec::Vec}; use liquid_primitives::{ types::{timestamp, Address}, Topics, }; pub fn set_storage<V>(key: &[u...
nstance, addr, data) }) } pub fn finish<V>(return_value: &V) where V: scale::Encode, { <EnvInstance as OnInstance>::on_instance(|instance| { Env::finish(instance, return_value); }) } pub fn revert<V>(return...
} pub fn call<R>(addr: &Address, data: &[u8]) -> Result<R> where R: liquid_abi_codec::Decode + liquid_abi_codec::TypeInfo, { <EnvInstance as OnInstance>::on_instance(|instance| { Env::call(instance, addr, data) }) } pu...
random
[]
Rust
nll/src/loans_in_scope.rs
nikomatsakis/borrowck
d982759fa7a7ff47766164f7766938f42fdd460f
use env::{Environment, Point}; use graph::{BasicBlockIndex, FuncGraph}; use graph_algorithms::Graph; use graph_algorithms::bit_set::{BitBuf, BitSet, BitSlice}; use nll_repr::repr; use region::Region; use regionck::RegionCheck; use std::collections::HashMap; pub struct LoansInScope<'cx> { env: &'cx Environment<'cx>...
use env::{Environment, Point}; use graph::{BasicBlockIndex, FuncGraph}; use graph_algorithms::Graph; use graph_algorithms::bit_set::{BitBuf, BitSet, BitSlice}; use nll_repr::repr; use region::Region; use regionck::RegionCheck; use std::collections::HashMap; pub struct LoansInScope<'cx> { env: &'cx Environment<'cx>...
t(point) { buf.kill(loan_index); } callback(point, None, buf.as_slice()); } fn loans_not_in_scope_at<'a>(&'a self, point: Point) -> impl Iterator<Item = usize> + 'a { self.loans.iter().enumerate().filter_map( move |(loan_index, loan)| if !loan.region.may_contain(...
gion, } impl<'cx> LoansInScope<'cx> { pub fn new(regionck: &'cx RegionCheck<'cx>) -> Self { let env = regionck.env(); let loans: Vec<_> = env.reverse_post_order .iter() .flat_map(|&block| { env.graph .block_data(block) ...
random
[ { "content": "struct Dfs<'env> {\n\n stack: Vec<Point>,\n\n visited: HashSet<Point>,\n\n env: &'env Environment<'env>,\n\n}\n\n\n\nimpl<'env> Dfs<'env> {\n\n fn new(env: &'env Environment<'env>) -> Self {\n\n Dfs {\n\n stack: vec![],\n\n visited: HashSet::new(),\n\n ...
Rust
crates/ide/src/moniker.rs
komonad/rust-analyzer
af27958fd45ab44818749616ede842976e27d89b
use hir::{db::DefDatabase, Crate, Name, Semantics}; use ide_db::{ base_db::{CrateOrigin, FileId, FileLoader, FilePosition}, defs::Definition, helpers::pick_best_token, RootDatabase, }; use itertools::Itertools; use syntax::{AstNode, SyntaxKind::*, T}; use crate::{doc_links::token_as_doc_comment, Rang...
use hir::{db::DefDatabase, Crate, Name, Semantics}; use ide_db::{ base_db::{CrateOrigin, FileId, FileLoader, FilePosition}, defs::Definition, helpers::pick_best_token, RootDatabase, }; use itertools::Itertools; use syntax::{AstNode, SyntaxKind::*, T}; use crate::{doc_links::token_as_doc_comment, Rang...
; PackageInformation { name, repo, version } }, }) } #[cfg(test)] mod tests { use crate::fixture; use super::MonikerKind; #[track_caller] fn no_moniker(ra_fixture: &str) { let (analysis, position) = fixture::position(ra_fixture); if let Some(x) = analysis.monik...
match krate.origin(db) { CrateOrigin::CratesIo { repo } => (repo?, krate.version(db)?), CrateOrigin::Lang => ( "https://github.com/rust-lang/rust/".to_string(), "compiler_version".to_string(), ), CrateOrigin::Unknown...
if_condition
[ { "content": "fn def_to_nav(db: &RootDatabase, def: Definition) -> Vec<NavigationTarget> {\n\n def.try_to_nav(db).map(|it| vec![it]).unwrap_or_default()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use ide_db::base_db::FileRange;\n\n use itertools::Itertools;\n\n\n\n use crate::fixture;\n\n\n\n #[...
Rust
src/raftstore/store/worker/pd.rs
Caoming/tikv
7c25c38965692ccfc17d175fbd529d64c6695e13
use std::sync::Arc; use std::fmt::{self, Formatter, Display}; use uuid::Uuid; use kvproto::metapb; use kvproto::eraftpb::ConfChangeType; use kvproto::raft_cmdpb::{RaftCmdRequest, AdminRequest, AdminCmdType}; use kvproto::raft_serverpb::RaftMessage; use kvproto::pdpb; use util::worker::Runnable; use util::escape; u...
use std::sync::Arc; use std::fmt::{self, Formatter, Display}; use uuid::Uuid; use kvproto::metapb; use kvproto::eraftpb::ConfChangeType; use kvproto::raft_cmdpb::{RaftCmdRequest, AdminRequest, AdminCmdType}; use kvproto::raft_serverpb::RaftMessage; use kvproto::pdpb; use util::worker::Runnable; use util::escape; u...
fn handle_heartbeat(&self, region: metapb::Region, peer: metapb::Peer, down_peers: Vec<pdpb::PeerStats>, pending_peers: Vec<metapb::Peer>) { PD_REQ_COUNTER_VEC.with_label_values(&["heartbeat", "all"]).inc(); ...
lit_region_request(split_key, resp.get_new_region_id(), resp.take_new_peer_ids()); self.send_admin_request(region, peer, req); } Err(e) => debug!("[region {}] failed to ask split...
function_block-function_prefixed
[ { "content": "pub fn remove_peer(region: &mut metapb::Region, store_id: u64) -> Option<metapb::Peer> {\n\n region.get_peers()\n\n .iter()\n\n .position(|x| x.get_store_id() == store_id)\n\n .map(|i| region.mut_peers().remove(i))\n\n}\n\n\n", "file_path": "src/raftstore/store/util.rs"...
Rust
src/aux_ddi0_osc/lfoscctl.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register LFOSCCTL"] pub type R = crate::R<u32, super::LFOSCCTL>; #[doc = "Writer for register LFOSCCTL"] pub type W = crate::W<u32, super::LFOSCCTL>; #[doc = "Register LFOSCCTL `reset()`'s with value 0"] impl crate::ResetValue for super::LFOSCCTL { type Type = u32; #[inline(always)] fn re...
#[doc = "Reader of register LFOSCCTL"] pub type R = crate::R<u32, super::LFOSCCTL>; #[doc = "Writer for register LFOSCCTL"] pub type W = crate::W<u32, super::LFOSCCTL>; #[doc = "Register LFOSCCTL `reset()`'s with value 0"] impl crate::ResetValue for super::LFOSCCTL { type Type = u32; #[inline(always)] fn re...
w: self } } #[doc = "Bits 8:9 - 9:8\\] Internal. Only to be used through TI provided API."] #[inline(always)] pub fn rcosclf_rtune_trim(&mut self) -> RCOSCLF_RTUNE_TRIM_W { RCOSCLF_RTUNE_TRIM_W { w: self } } #[doc = "Bits 0:7 - 7:0\\] Internal. Only to be used through TI provided API."] ...
line(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 22)) | (((value as u32) & 0x03) << 22); self.w } } #[doc = "Reader of field `XOSCLF_CMIRRWR_RATIO`"] pub type XOSCLF_CMIRRWR_RATIO_R = crate::R<u8, u8>; #[doc = "Write proxy for field `XOSCLF_...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
dist/playground/src/app.rs
fretz12/synth
0c40456b13a30915ee6f305d456ed0b398052a02
use crate::prelude::*; use tide::{ http::headers::HeaderValue, security::{CorsMiddleware, Origin}, Body, Request, Response, }; use synth_core::{ compile::NamespaceCompiler, error::{Error as SynthError, ErrorKind as SynthErrorKind}, graph::{ArrayNode, Graph, RandomU64}, schema::Content, }; ...
use crate::prelude::*; use tide::{ http::headers::HeaderValue, security::{CorsMiddleware, Origin}, Body, Request, Response, }; use synth_core::{ compile::NamespaceCompiler, error::{Error as SynthError, ErrorKind as SynthErrorKind}, graph::{ArrayNode, Graph, RandomU64}, schema::Content, }; ...
let body = ErrorResponseBody { kind, text: synth_err.msg.clone(), }; let resp = Response::builder(400).body(Body::from_json(&body)?).build(); Ok(resp) } else if let Some(app_err) = err.downcast_ref::<Err...
let kind = match synth_err.kind { SynthErrorKind::Compilation => "compilation", SynthErrorKind::BadRequest => "schema", _ => "unknown", };
assignment_statement
[ { "content": "#[allow(dead_code)]\n\npub fn bool_from_str<'de, D: Deserializer<'de>>(d: D) -> std::result::Result<bool, D::Error> {\n\n let as_str = String::deserialize(d)?;\n\n as_str\n\n .parse()\n\n .map_err(|e| D::Error::custom(format!(\"not a boolean: {}\", e)))\n\n}\n\n\n\n#[derive(Has...
Rust
soccs/src/dl/cg_original/cipher/mibs.rs
Simula-UiB/CRHS
8f3dd34c8b99680188d9314c6897e0c790f5358f
use super::{Cipher, CipherStructure}; use super::PropertyType; use super::super::sbox::Sbox; /***************************************************************** MIBS ******************************************************************/ #[derive(Clone)] pub struct Mibs { size: usize, ...
use super::{Cipher, CipherStructure}; use super::PropertyType; use super::super::sbox::Sbox; /***************************************************************** MIBS ******************************************************************/ #[derive(Clone)] pub struct Mibs { size: usize, ...
xffffffffffffffff; let ciphertext = 0x595263b93ffe6e18; assert_eq!(plaintext, cipher.decrypt(ciphertext, &round_keys)); } #[test] fn encryption_decryption_test() { let cipher = cipher::name_to_cipher("mibs").unwrap(); let key = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0...
tructure::Feistel } fn size(&self) -> usize { self.size } fn key_size(&self) -> usize { self.key_size } fn num_sboxes(&self) -> usize { self.size / self.sbox.size_in() } fn sbox(&self, _i: usize) -> &Sbox { &self.sbox } fn sbox_pos_in(&self, i...
random
[ { "content": "/// Create an identity matrix (a matrix where only the [a,a] elements are set)\n\npub fn identity(size: usize) -> Matrix {\n\n let mut m = Matrix::new(size, size);\n\n for i in 0..size {\n\n m.rows[i].set(i, true);\n\n }\n\n m\n\n}\n\n\n", "file_path": "crush/src/algebra/mod...
Rust
src/primitive/util.rs
Vurich/collision-rs
95218b711af67b70b546549659738aef9f9030d6
use std::ops::Neg; use crate::{Aabb, Ray3}; use cgmath::{BaseFloat, BaseNum, Vector2}; use cgmath::prelude::*; use cgmath::num_traits::Float; pub(crate) fn get_max_point<'a, P: 'a, T, I>(vertices: I, direction: &P::Diff, transform: &T) -> P where P: EuclideanSpace, P::Scalar: BaseFloat, T: Transform<P>,...
use std::ops::Neg; use crate::{Aabb, Ray3}; use cgmath::{BaseFloat, BaseNum, Vector2}; use cgmath::prelude::*; use cgmath::num_traits::Float; pub(crate) fn get_max_point<'a, P: 'a, T, I>(vertices: I, direction: &P::Diff, transform: &T) -> P where P: EuclideanSpace, P::Scalar: BaseFloat, T: Transform<P>,...
pub(crate) fn cylinder_ray_quadratic_solve<S>(r: &Ray3<S>, radius: S) -> Option<(S, S)> where S: BaseFloat, { let two = S::one() + S::one(); let a = r.direction.x * r.direction.x + r.direction.z * r.direction.z; let b = two * (r.direction.x * r.origin.x + r.direction.z * r.origin.z); let c = r.or...
V::Scalar: BaseFloat, { let line = *end - *start; let line_dir = line.normalize(); let v = *point - *start; let d = v.dot(line_dir); if d < V::Scalar::zero() { *start } else if (d * d) > line.magnitude2() { *end } else { *start + line_dir * d } }
function_block-function_prefix_line
[ { "content": "fn support_point<P, T>(vertices: &[P], direction: &P::Diff, transform: &T) -> P\n\nwhere\n\n P: EuclideanSpace,\n\n P::Scalar: BaseFloat,\n\n T: Transform<P>,\n\n{\n\n let direction = transform.inverse_transform_vector(*direction).unwrap();\n\n\n\n // figure out where to start, if t...
Rust
backend/src/orri/site/http/api/new_site.rs
prasmussen/orri
396132e765eb1dfa0b8e8de7cec7746bedc471e1
use std::time::SystemTime; use std::str::FromStr; use actix_web::{web, HttpResponse}; use actix_session::Session; use serde::{Deserialize, Serialize}; use crate::orri::app_state::{AppState, Config}; use crate::orri::site::{self, Site, CreateSiteError, FileInfo}; use crate::orri::http; use crate::orri::domain::{self, Do...
use std::time::SystemTime; use std::str::FromStr; use actix_web::{web, HttpResponse}; use actix_session::Session; use serde::{Deserialize, Serialize}; use crate::orri::app_state::{AppState, Config}; use crate::orri::site::{self, Site, CreateSiteError, FileInfo}; use crate::orri::http; use crate::orri::domain::{self, Do...
} fn handle_create_site_error(err: CreateSiteError) -> HttpResponse { match err { CreateSiteError::SiteAlreadyExist() => { HttpResponse::Conflict() .json(http::Error::from_str("Site already exist")) }, CreateSiteError::AddRoute(err) => { handle_fail...
match err { site_key::Error::TooShort() => HttpResponse::BadRequest() .json(http::Error::from_str("Key is too short")), site_key::Error::TooLong() => HttpResponse::BadRequest() .json(http::Error::from_str("The key is too long")), site_key...
if_condition
[ { "content": "fn get_provided_key(request_data: &Request, session_data: &SessionData, domain: &Domain) -> Option<String> {\n\n let key_from_session = session_data.get_site_key(domain);\n\n\n\n request_data.key.clone().or(key_from_session)\n\n}\n\n\n\n\n", "file_path": "backend/src/orri/site/http/api/r...
Rust
src/alg/hmacs.rs
MicheleMinelli/jwt-compact
acf612f6188c4a7c23b9eefb56ed8bd79ad2b5d8
use anyhow::ensure; use hmac::crypto_mac::generic_array::{typenum::Unsigned, GenericArray}; use hmac::{crypto_mac, Hmac, Mac as _, NewMac}; use rand_core::{CryptoRng, RngCore}; use sha2::{ digest::{BlockInput, Digest}, Sha256, Sha384, Sha512, }; use smallvec::{smallvec, SmallVec}; use zeroize::Zeroize; use c...
use anyhow::ensure; use hmac::crypto_mac::generic_array::{typenum::Unsigned, GenericArray}; use hmac::{crypto_mac, Hmac, Mac as _, NewMac}; use rand_core::{CryptoRng, RngCore}; use sha2::{ digest::{BlockInput, Digest}, Sha256, Sha384, Sha512, }; use smallvec::{smallvec, SmallVec}; use zeroize::Zeroize; use c...
} } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct Hs384; impl Algorithm for Hs384 { type SigningKey = Hs384Key; type VerifyingKey = Hs384Key; type Signature = Hs384Signature; fn name(&self) -> Cow<'static, str> { Cow::Borrowed("HS384") } fn sign(&self, s...
lf, signature: &Self::Signature, verifying_key: &Self::VerifyingKey, message: &[u8], ) -> bool { verifying_key.hmac(message) == signature.0
function_block-random_span
[ { "content": "/// Converts type to a JS `Error`.\n\nfn to_js_error(e: impl fmt::Display) -> Error {\n\n Error::new(&e.to_string())\n\n}\n\n\n", "file_path": "e2e-tests/wasm/src/lib.rs", "rank": 0, "score": 159682.32083975547 }, { "content": "fn encode_base64_buf(source: impl AsRef<[u8]>, ...
Rust
gstreamer/src/auto/child_proxy.rs
JohnBox/gstreamer-rs
ed6fadf35160df3fd597c78c75278c68ebe59078
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::mem::transmute; glib::wrapper! { #[doc(alias = "GstChildProxy")] pub struct ChildProxy(Interface<ffi::GstChildProxy, ffi::GstChildProx...
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::mem::transmute; glib::wrapper! { #[doc(alias = "GstChildProxy")] pub struct ChildProxy(Interface<ffi::GstChildProxy, ffi::GstChildProx...
P: IsA<ChildProxy>, F: Fn(&P, &glib::Object, &str) + Send + Sync + 'static, >( this: *mut ffi::GstChildProxy, object: *mut glib::gobject_ffi::GObject, name: *mut libc::c_char, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const...
d_by_index")] #[doc(alias = "get_child_by_index")] fn child_by_index(&self, index: u32) -> Option<glib::Object>; #[doc(alias = "gst_child_proxy_get_child_by_name")] #[doc(alias = "get_child_by_name")] fn child_by_name(&self, name: &str) -> Option<glib::Object>; #[doc(alias = "gst_child_proxy_g...
random
[ { "content": "pub trait ChildProxyImpl: ObjectImpl + Send + Sync {\n\n fn child_by_name(&self, object: &Self::Type, name: &str) -> Option<glib::Object> {\n\n self.parent_child_by_name(object, name)\n\n }\n\n\n\n fn child_by_index(&self, object: &Self::Type, index: u32) -> Option<glib::Object>;\n...
Rust
crates/neon-sys/build.rs
anton-iskryzhytskyi/neon
ec46747e87b4c49ca4bde6463814fb571d2a5952
extern crate cc; extern crate regex; fn main() { build::main() } #[cfg(feature = "docs-only")] mod build { pub fn main() {} } #[cfg(not(feature = "docs-only"))] mod build { use std::process::Command; use std::env; use std::fs; use std::path::Path; use regex::Regex; pub fn main() { ...
extern crate cc; extern crate regex; fn main() { build::main() } #[cfg(feature = "docs-only")] mod build { pub fn main() {} } #[cfg(not(feature = "docs-only"))] mod build { use std::process::Command; use std::env; use std::fs; use std::path::Path; use regex::Regex; pub fn main() { ...
ode_gyp_output)); } npm(native_dir) .args(&["run", if debug() { "build-debug" } else { "build-release" }]) .status() .ok() .expect("Failed to run \"node-gyp build\" for neon-sys!"); } fn link_library(native_dir: &Path) { let...
"Failed to run \"node-gyp configure\" for neon-sys!\n Out: {}\n Err: {}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr) )); } if cfg!(windows) { let node_gyp_output = String::from_utf8_lossy(&output....
random
[ { "content": "fn main() {\n\n if let Ok(profile) = env::var(\"PROFILE\") {\n\n println!(\"cargo:rustc-cfg=neon_profile={:?}\", profile);\n\n }\n\n}\n", "file_path": "build.rs", "rank": 1, "score": 186012.49593627936 }, { "content": "pub fn return_js_string(mut cx: FunctionContex...
Rust
src/service/mod.rs
UCSBarchlab/Sprocket
c782e01b38629400360f1138be3445991db20d4c
use rtl8139; use timer; use ide; use alloc::borrow::ToOwned; pub trait Service { fn name() -> &'static str; fn start(); } const IDLE_THRESHOLD: u32 = 10; pub struct UserService; impl Service for UserService { fn name() -> &'static str { "COFFLOS HTTP Demo" } fn start() { info...
use rtl8139; use timer; use ide; use alloc::borrow::ToOwned; pub trait Service { fn name() -> &'static str; fn start(); } const IDLE_THRESHOLD: u32 = 10; pub struct UserService; impl Service for UserService { fn name() -> &'static str { "COFFLOS HTTP Demo" } fn start() { info...
}
ket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer); let mut sockets = SocketSet::new(vec![]); let tcp_handle = sockets.add(tcp_socket); let mut count = 0; loop { { let socket: &mut TcpSocket = sockets.get_mut(tcp_handle).as_socket();...
function_block-function_prefixed
[ { "content": "fn write_file<T>(fs: &mut fs::FileSystem<T>, path: &str) -> Result<(), fs::FsError>\n\n where T: fs::Disk\n\n{\n\n let mut f = File::open(path).expect(\"Could not open file\");\n\n let mut inode = fs::Inode {\n\n type_: fs::InodeType::File,\n\n device: fs::ROOT_DEV,\n\n ...
Rust
src/confirm.rs
polyswarm/rust-web3
680c3b6f00e3f5ba9d5b7fbb48c9cb1abeb51c61
use std::time::Duration; use crate::api::{CreateFilter, Eth, EthFilter, FilterStream, Namespace}; use crate::helpers::CallFuture; use crate::types::{Bytes, TransactionReceipt, TransactionRequest, H256, U64}; use crate::{Error, Transport}; use futures::stream::Skip; use futures::{Future, IntoFuture, Poll, Stream}; p...
use std::time::Duration; use crate::api::{CreateFilter, Eth, EthFilter, FilterStream, Namespace}; use crate::helpers::CallFuture; use crate::types::{Bytes, TransactionReceipt, TransactionRequest, H256, U64}; use crate::{Error, Transport}; use futures::stream::Skip; use futures::{Future, IntoFuture, Poll, Stream}; p...
&[ r#"{"from":"0x0000000000000000000000000000000000000123","gasPrice":"0x1","to":"0x0000000000000000000000000000000000000123","value":"0x1"}"#.into(), ], ); transport.assert_request("eth_newBlockFilter", &[]); transport.assert_request("eth_getFilterChanges", &...
tion_receipt)); transport.add_response(Value::Bool(true)); let confirmation = { let future = send_transaction_with_confirmation(&transport, transaction_request, poll_interval, confirmations); future.wait() }; transport.assert_request( ...
random
[ { "content": "/// Should be used to create new filter future\n\nfn create_filter<T: Transport, F: FilterInterface>(t: T, arg: Vec<rpc::Value>) -> CreateFilter<T, F::Item> {\n\n let future = CallFuture::new(t.execute(F::constructor(), arg));\n\n CreateFilter {\n\n transport: Some(t),\n\n item...
Rust
src/adsorption/fea_potential.rs
bbbursik/feos-dft
dc444184603c44f8279ba5ae79a2b20fce85fb80
use crate::profile::{CUTOFF_RADIUS, MAX_POTENTIAL}; use crate::Geometry; use feos_core::EosUnit; use gauss_quad::GaussLegendre; use ndarray::{Array1, Array2, Zip}; use ndarray_stats::SummaryStatisticsExt; use quantity::{QuantityArray2, QuantityScalar}; use std::f64::consts::PI; use std::usize; pub fn calculate_fea_pot...
use crate::profile::{CUTOFF_RADIUS, MAX_POTENTIAL}; use crate::Geometry; use feos_core::EosUnit; use gauss_quad::GaussLegendre; use ndarray::{Array1, Array2, Zip}; use ndarray_stats::SummaryStatisticsExt; use quantity::{QuantityArray2, QuantityScalar}; use std::f64::consts::PI; use std::usize; pub fn calculate_fea_pot...
n_grid[1] as f64, n_grid[1], ); let weights = Array1::from_elem(n_grid[1], system_size[2] / n_grid[1] as f64); (nodes, weights) } Geometry::Spherical => { let nodes = PI / 2.0 + Array1::from_vec(GaussLegendre::nodes_and_weig...
n => { let nodes = Array1::linspace( 0.5 * system_size[1] / n_grid[0] as f64, system_size[1] - 0.5 * system_size[1] / n_grid[0] as f64, n_grid[0], ); let weights = Array1::from_elem(n_grid[0], system_size[1] / n_grid[0] as f64); ...
random
[ { "content": "/// Evaluate the squared euclidian distance between a point and the coordinates of all solid atoms.\n\nfn calculate_distance2(point: [&f64; 3], coordinates: &Array2<f64>) -> Array1<f64> {\n\n Array1::from_shape_fn(coordinates.ncols(), |i| {\n\n let rx = coordinates[[0, i]] - point[0];\n\...
Rust
components/sst_importer/src/errors.rs
mapbased/tikv
ed7e1aa945d9ada9dc3ad3bd6420a9879d49ed44
use std::error::Error as StdError; use std::io::Error as IoError; use std::num::ParseIntError; use std::path::PathBuf; use std::result; use encryption::Error as EncryptionError; use error_code::{self, ErrorCode, ErrorCodeExt}; use futures::channel::oneshot::Canceled; use grpcio::Error as GrpcError; use kvproto::impo...
use std::error::Error as StdError; use std::io::Error as IoError; use std::num::ParseIntError; use std::path::PathBuf; use std::result; use encryption::Error as EncryptionError; use error_code::{self, ErrorCode, ErrorCodeExt}; use futures::channel::oneshot::Canceled; use grpcio::Error as GrpcError; use kvproto::impo...
}
Error::TTLNotEnabled => error_code::sst_importer::TTL_NOT_ENABLED, Error::TTLsLenNotEqualsToPairs => { error_code::sst_importer::TTLS_LEN_NOT_EQUALS_TO_PAIRS } Error::IncompatibleApiVersion => error_code::sst_importer::INCOMPATIBLE_API_VERSION, } }
function_block-function_prefix_line
[ { "content": "pub fn apply_sst_cf_file<E>(path: &str, db: &E, cf: &str) -> Result<(), Error>\n\nwhere\n\n E: KvEngine,\n\n{\n\n box_try!(db.ingest_external_file_cf(cf, &[path]));\n\n Ok(())\n\n}\n\n\n", "file_path": "components/raftstore/src/store/snap/io.rs", "rank": 0, "score": 632448.934...
Rust
kernel/src/mm/address.rs
tstree-oscomp2021/hecto-os
285141beba9d946bfdd1c15135e0f41d12eadc7f
use core::{fmt::Display, iter::Step, mem::size_of}; use crate::board::{interface::Config, ConfigImpl}; #[repr(C)] #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct PA(pub usize); #[repr(C)] #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct VA(pub usize); #[repr(C)] #[derive(Copy, C...
use core::{fmt::Display, iter::Step, mem::size_of}; use crate::board::{interface::Config, ConfigImpl}; #[repr(C)] #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct PA(pub usize); #[repr(C)] #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] pub struct VA(pub usize); #[repr(C)] #[derive(Copy, C...
use test_macros::kernel_test; use super::*; #[kernel_test] fn test_display() { println!("{}", VA(0x12345)); println!("{}", VARangeOrd(VA(0x12345)..VA(0x12345))); } }
$page_number_type(self.0 >> ConfigImpl::PAGE_SIZE_BITS) } pub const fn ceil(self) -> $page_number_type { $page_number_type( (self.0 - 1 + ConfigImpl::PAGE_SIZE) >> ConfigImpl::PAGE_SIZE_BITS, ) } ...
random
[ { "content": "#[inline]\n\npub fn get_sched_cx() -> &'static mut *const TaskContextImpl {\n\n unsafe { transmute(&mut (&mut *SCHEDULE_THREAD).task_cx) }\n\n}\n", "file_path": "kernel/src/process/schedule.rs", "rank": 0, "score": 244547.56735429235 }, { "content": "pub fn kernel_init(hart_...
Rust
akaibu/src/scheme/esc_arc2.rs
Forlos/akaibu
8be6e7bbd463e76971f64975a35732a2cbb3c967
use crate::archive::{self, FileContents}; use super::Scheme; use anyhow::Context; use bytes::BytesMut; use encoding_rs::SHIFT_JIS; use positioned_io::{RandomAccessFile, ReadAt}; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use scroll::{ctx, Pread, LE}; use std::{ fs::File, io::Write, path:...
use crate::archive::{self, FileContents}; use super::Scheme; use anyhow::Context; use bytes::BytesMut; use encoding_rs::SHIFT_JIS; use positioned_io::{RandomAccessFile, ReadAt}; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use scroll::{ctx, Pread, LE}; use std::{ fs::File, io::Write, path:...
} impl EscArc2Header { fn decrypt_header( mut unk1: u32, mut file_count: u32, unk2: u32, ) -> EscArc2Header { unk1 ^= KEY; let mut file_name_table_size = ((unk1 >> 1) ^ unk1) >> 3; let mut d = unk1.wrapping_add(unk1) ^ unk1; d = d.wrapping_add(d); ...
fn try_from_ctx( buf: &'a [u8], _ctx: (), ) -> Result<(Self, usize), Self::Error> { let off = &mut 8; let unk1 = buf.gread_with(off, LE)?; let file_count = buf.gread_with(off, LE)?; let unk2 = buf.gread_with(off, LE)?; Ok((Self::decrypt_header(unk1, file_count...
function_block-full_function
[ { "content": "fn decrypt_file_name(buf: &[u8], header: &YpfHeader) -> PathBuf {\n\n let mut result: Vec<u8> = buf.iter().map(|b| !b).collect();\n\n if header.archive_version == 500 {\n\n result.iter_mut().for_each(|b| *b ^= 0x36);\n\n }\n\n PathBuf::from(SHIFT_JIS.decode(&result).0.to_string(...
Rust
debug/src/dim2.rs
langbamit/heron
4492cc6ee51821dd01a1b0e8753f4f29a6e3b527
use std::f32::consts::PI; use bevy::asset::prelude::*; use bevy::ecs::prelude::*; use bevy::math::{Vec2, Vec3}; use bevy::sprite::prelude::*; use bevy::transform::prelude::*; use bevy_prototype_lyon::entity::ShapeBundle; use bevy_prototype_lyon::prelude::*; use bevy_prototype_lyon::shapes::RectangleOrigin; use heron_...
use std::f32::consts::PI; use bevy::asset::prelude::*; use bevy::ecs::prelude::*; use bevy::math::{Vec2, Vec3}; use bevy::sprite::prelude::*; use bevy::transform::prelude::*; use bevy_prototype_lyon::entity::ShapeBundle; use bevy_prototype_lyon::prelude::*; use bevy_prototype_lyon::shapes::RectangleOrigin; use heron_...
} }; builder }
if let Some(polygon) = shape.as_convex_polygon() { builder.add(&shapes::Polygon { points: polygon.points().into_bevy(), closed: true, }); }
if_condition
[ { "content": "fn scale_debug_entities(mut query: Query<'_, (Option<&mut Transform>, &mut GlobalTransform)>) {\n\n query\n\n .iter_mut()\n\n .filter(|(_, global)| {\n\n let scale = global.scale;\n\n !is_near(scale.x, 1.0) || !is_near(scale.y, 1.0)\n\n })\n\n ....
Rust
src/tools/clippy/clippy_lints/src/vec_init_then_push.rs
jcotton42/rust
8ccc89bc312caa65ca46b55b47492abdd5b6910a
use crate::utils::{ is_type_diagnostic_item, match_def_path, path_to_local, path_to_local_id, paths, snippet, span_lint_and_sugg, }; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, QPath, Stmt, Stm...
use crate::utils::{ is_type_diagnostic_item, match_def_path, path_to_local, path_to_local_id, paths, snippet, span_lint_and_sugg, }; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, HirId, Local, PatKind, QPath, Stmt, Stm...
fn check_block_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Block<'tcx>) { if let Some(searcher) = self.searcher.take() { searcher.display_err(cx); } } } fn get_vec_init_kind<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Option<VecInitKind> { if let ExprKind::Ca...
check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { if let Some(searcher) = self.searcher.take() { if_chain! { if let StmtKind::Expr(expr) | StmtKind::Semi(expr) = stmt.kind; if let ExprKind::MethodCall(path, _, [self_arg, _], _) = expr.kind; ...
function_block-function_prefixed
[]
Rust
crates/nu-command/src/commands/from_ics.rs
Fishrock123/nushell
e2973d2176bec6a206c37892458ef3b09146d34b
extern crate ical; use crate::prelude::*; use ical::parser::ical::component::*; use ical::property::Property; use nu_engine::WholeStreamCommand; use nu_errors::ShellError; use nu_protocol::{Primitive, Signature, TaggedDictBuilder, UntaggedValue, Value}; use std::io::BufReader; pub struct FromIcs; impl WholeStreamComm...
extern crate ical; use crate::prelude::*; use ical::parser::ical::component::*; use ical::property::Property; use nu_engine::WholeStreamCommand; use nu_errors::ShellError; use nu_protocol::{Primitive, Signature, TaggedDictBuilder, UntaggedValue, Value}; use std::io::BufReader; pub struct FromIcs; impl WholeStreamComm...
Tag, ) -> UntaggedValue { UntaggedValue::table( &transitions .into_iter() .map(|transition| { let mut row = TaggedDictBuilder::new(tag.clone()); row.insert_untagged( "properties", properties_to_value(transition....
row.insert_untagged("alarms", alarms_to_value(event.alarms, tag.clone())); row.into_value() }) .collect::<Vec<Value>>(), ) } fn alarms_to_value(alarms: Vec<IcalAlarm>, tag: Tag) -> UntaggedValue { UntaggedValue::table( &alarms .into_iter() ...
random
[ { "content": "pub fn to_sqlite(input: Vec<Value>, name_tag: Tag) -> Result<Vec<ReturnValue>, ShellError> {\n\n match sqlite_input_stream_to_bytes(input) {\n\n Ok(out) => Ok(vec![ReturnSuccess::value(out)]),\n\n _ => Err(ShellError::labeled_error(\n\n \"Expected a table with SQLite-co...
Rust
gate/src/renderer/geom.rs
nsauzede/gate
ffa72fc5e9691edf2ed2a62d8c27913c6d89458a
use std::ops::{Add, Mul}; #[derive(Copy, Clone)] pub struct Vec2 { pub x: f64, pub y: f64 } impl Vec2 { pub fn new(x: f64, y: f64) -> Vec2 { Vec2 { x, y } } pub fn zero() -> Vec2 { Vec2::new(0.0, 0.0) } pub fn len(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() } } impl Add<Vec2> for Vec2 { ...
use std::ops::{Add, Mul}; #[derive(Copy, Clone)] pub struct Vec2 { pub x: f64, pub y: f64 } impl Vec2 { pub fn new(x: f64, y: f64) -> Vec2 { Vec2 { x, y } } pub fn zero() -> Vec2 { Vec2::new(0.0, 0.0) } pub fn len(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() } } impl Add<Vec2> for Vec2 { ...
pub fn post_scale(&self, scale: f64) -> Affine { Affine { mat: scale * self.mat, offset: scale * self.offset, } } pub fn post_rotate(&self, angle: f64) -> Affine { let rotation = Mat2::rotation(angle); Affine { mat: rotation * ...
let scale = Diag2::new(scale_x, scale_y); Affine { mat: scale * self.mat, offset: scale * self.offset, } }
function_block-function_prefix_line
[ { "content": "pub fn append_sprite(r: &mut RenderBuffer, affine: &Affine, sprite_id: u16, flash_ratio: f64) {\n\n assert!(r.mode == Mode::Sprite);\n\n\n\n let img_coords = r.sprite_atlas.images[&sprite_id];\n\n let affine = affine.post_scale(r.dims.pixel_scalar);\n\n let flash_ratio = (flash_ratio a...
Rust
src/main.rs
Corecii/Project1999-Updater
60f99f36aef234df17a076851b36e3403de5df01
#[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; extern crate regex; extern crate zip; use regex::Regex; use bytes::{Bytes, IntoBuf}; use hyper_tls::HttpsConnector; use hyper::{Client}; use futures_util::TryStreamExt; use select::document::Document; use select::predicate::{Name}; us...
#[macro_use] extern crate serde_derive; #[macro_use] extern crate lazy_static; extern crate regex; extern crate zip; use regex::Regex; use bytes::{Bytes, IntoBuf}; use hyper_tls::HttpsConnector; use hyper::{Client}; use futures_util::TryStreamExt; use select::document::Document; use select::predicate::{Name}; us...
} } println!("\r100%"); Ok(()) } fn launch(close_window: bool) -> () { let mut close_window = close_window; let result = Command::new("eqgame").arg("patchme").spawn(); if result.is_err() { println!("Failed to launch game because: {}", result.unwrap_err()); close_window...
if let Some(mode) = file.unix_mode() { fs::set_permissions(&outpath, fs::Permissions::from_mode(mode)).unwrap(); }
if_condition
[ { "content": "# Project1999 Updater\n\n\n\nScans the project 1999 website for update files and applies them to the game before launching. I made this for someone who always asks me to manually update their game. I figured, \"I can automate this in a day. Isn't that easier for everyone?\"\n\n\n\nMade for windows...
Rust
src/twofish.rs
SolraBizna/rust-lsx
0ba803f0d0773349a1dcc672f15e3936afd279ff
mod tables; use tables::*; pub const BLOCKBYTES: usize = 16; #[derive(Copy,Clone)] pub struct Twofish { s: [[u32; 256]; 4], w: [u32; 8], k: [u32; 32], } fn splat(i: u8) -> [u8; 4] { [i, i, i, i] } fn unsplat(i: &[u32; 4]) -> u32 { i[0] ^ i[1] ^ i[2] ^ i[3] } #[inline(always)] fn h_128(x...
mod tables; use tables::*; pub const BLOCKBYTES: usize = 16; #[derive(Copy,Clone)] pub struct Twofish { s: [[u32; 256]; 4], w: [u32; 8], k: [u32; 32], } fn splat(i: u8) -> [u8; 4] { [i, i, i, i] } fn unsplat(i: &[u32; 4]) -> u32 { i[0] ^ i[1] ^ i[2] ^ i[3] } #[inline(always)] fn h_128(x...
#[inline(always)] fn h_256(x: [u8; 4], key: &[u8; 28]) -> [u32; 4] { h_192([ Q1[x[0] as usize] ^ key[24], Q0[x[1] as usize] ^ key[25], Q0[x[2] as usize] ^ key[26], Q1[x[3] as usize] ^ key[27], ], array_ref!(key, 0, 20)) } #[inline(always)] fn h_128_no_skip(x: [u8; 4], key: &[u...
Q1[x[1] as usize] ^ key[17], Q0[x[2] as usize] ^ key[18], Q0[x[3] as usize] ^ key[19], ], array_ref!(key, 0, 12)) }
function_block-function_prefix_line
[ { "content": "/// Calculate the SHA-256 hash of a given byte string. Useful if your entire\n\n/// message is already in contiguous memory. If it's not, you should use one\n\n/// of this module's structs instead.\n\n///\n\n/// ```rust\n\n/// # use lsx::sha256;\n\n/// assert_eq!(sha256::hash(b\"The quick brown fo...
Rust
lib/src/il.rs
coffeecup-winner/unwind-mc
e8b4563319626cf7b47b0264cce61eb308f39419
use disassembler::Reg; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone, Copy)] pub enum ILOperand { Value(i32), Register(Reg), Argument(i32), Local(i32), Pointer(Reg, Reg, u8, u32), } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone)] pub struct BinaryInstructi...
use disassembler::Reg; #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone, Copy)] pub enum ILOperand { Value(i32), Register(Reg), Argument(i32), Local(i32), Pointer(Reg, Reg, u8, u32), } #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone)] pub struct BinaryInstructi...
fn print_unary_operator(op: &ILUnaryOperator) -> &'static str { use self::ILUnaryOperator::*; match op { Negate => "neg", Not => "not", } } fn print_branch_type(type_: &BranchType) -> &'static str { use self::BranchType::*; match type_ { ...
fn print_binary_operator(op: &ILBinaryOperator) -> &'static str { use self::ILBinaryOperator::*; match op { Add => "add", And => "and", Divide => "div", Multiply => "mul", LoadAddress => "lea", Or => "or", ShiftLeft => "...
function_block-full_function
[ { "content": "pub fn invert_condition<Op: Clone + std::fmt::Debug>(\n\n mut condition: Vec<ILInstruction<Op>>,\n\n) -> UResult<Vec<ILInstruction<Op>>> {\n\n use il::ILInstruction::*;\n\n let branch = match &condition[condition.len() - 1] {\n\n Branch(br) => Branch(branch(invert(&br.type_), br.co...
Rust
src/dfx/src/commands/start.rs
jzxchiang1/sdk
f6f5322380fdc2fe9d88847494d249939fab6f03
use crate::actors; use crate::actors::icx_proxy::signals::PortReadySubscribe; use crate::actors::{ start_emulator_actor, start_icx_proxy_actor, start_replica_actor, start_shutdown_controller, }; use crate::config::dfinity::Config; use crate::lib::environment::Environment; use crate::lib::error::{DfxError, DfxResult...
use crate::actors; use crate::actors::icx_proxy::signals::PortReadySubscribe; use crate::actors::{ start_emulator_actor, start_icx_proxy_actor, start_replica_actor, start_shutdown_controller, }; use crate::config::dfinity::Config; use crate::lib::environment::Environment; use crate::lib::error::{DfxError, DfxResult...
fs::remove_dir_all(&local_dir).context(format!( "Cannot remove directory at '{}'.", local_dir.display() ))?; } Ok(()) } pub fn start_webserver_coordinator( env: &dyn Environment, network_descriptor: NetworkDescriptor, bind: SocketAddr, build_output_root: PathBuf,...
dinator::ProxyWebserverCoordinator; use crate::actors::shutdown_controller::ShutdownController; use crate::lib::network::network_descriptor::NetworkDescriptor; use crate::lib::provider::get_network_descriptor; use actix::{Actor, Addr, Recipient}; use anyhow::{anyhow, bail, Context}; use clap::Clap; use garcon::{Delay, ...
random
[ { "content": "pub fn exec(env: &dyn Environment, opts: UseOpts) -> DfxResult {\n\n let identity = opts.identity.as_str();\n\n\n\n let log = env.get_logger();\n\n info!(log, r#\"Using identity: \"{}\".\"#, identity);\n\n\n\n IdentityManager::new(env)?.use_identity_named(identity)\n\n}\n", "file_p...
Rust
src/hpack/header.rs
eaufavor/h2
ce81583cf16556f93da5263db6f73a3d46c7ab54
use super::{DecoderError, NeedMore}; use bytes::Bytes; use http::header::{HeaderName, HeaderValue}; use http::{Method, StatusCode}; use std::fmt; #[derive(Debug, Clone, Eq, PartialEq)] pub enum Header<T = HeaderName> { Field { name: T, value: HeaderValue }, Authority(BytesStr), Method(Method), Sc...
use super::{DecoderError, NeedMore}; use bytes::Bytes; use http::header::{HeaderName, HeaderValue}; use http::{Method, StatusCode}; use std::fmt; #[derive(Debug, Clone, Eq, PartialEq)] pub enum Header<T = HeaderName> { Field { name: T, value: HeaderValue }, Authority(BytesStr), Method(Method), Sc...
} } impl BytesStr { pub(crate) const fn from_static(value: &'static str) -> Self { BytesStr(Bytes::from_static(value.as_bytes())) } pub(crate) fn from(value: &str) -> Self { BytesStr(Bytes::copy_from_slice(value.as_bytes())) } #[doc(hidden)] pub fn try_from(bytes: Bytes) ...
match *self { Name::Field(ref name) => name.as_ref(), Name::Authority => b":authority", Name::Method => b":method", Name::Scheme => b":scheme", Name::Path => b":path", Name::Status => b":status", }
if_condition
[ { "content": "fn encode_not_indexed(name: usize, value: &[u8], sensitive: bool, dst: &mut BytesMut) {\n\n if sensitive {\n\n encode_int(name, 4, 0b10000, dst);\n\n } else {\n\n encode_int(name, 4, 0, dst);\n\n }\n\n\n\n encode_str(value, dst);\n\n}\n\n\n", "file_path": "src/hpack/e...
Rust
cscan/legacy/src/debugger.rs
vul337/cfi-eval
7d7801cf44cc650127d692c2a7222434375ac6aa
use super::binary::Elf; use dfuzz_os::arch::AMD64RegisterSet; use dfuzz_os::process::*; use dfuzz_os::signal::*; use dfuzz_os::spawn::*; use log::*; use std::collections::HashMap; use std::ffi::OsStr; use std::ops::Range; #[derive(Debug)] pub struct Debugger { pub process: Process, pub thread: Thread, brea...
use super::binary::Elf; use dfuzz_os::arch::AMD64RegisterSet; use dfuzz_os::process::*; use dfuzz_os::signal::*; use dfuzz_os::spawn::*; use log::*; use std::collections::HashMap; use std::ffi::OsStr; use std::ops::Range; #[derive(Debug)] pub struct Debugger { pub process: Process, pub thread: Thread, brea...
et buf: [u64; 2] = unsafe { std::mem::transmute(buf) }; rbp = buf[0]; stack.push(buf[1]); } } pub fn disasm<'a>(&self, elf: &'a Elf, addr: u64, len: usize) -> capstone::Instructions<'a> { trace!("disasm: {:#x} @ {}", addr, len); let mut buf = vec![0; len]; ...
rg4; regs.r8 = arg5; regs.r9 = arg6; regs.rip = rip; self.thread.trace_set_registers(&regs).unwrap(); let regs = self.next_event().unwrap(); self.process .trace_write_memory_force(rip, &insn_backup) .unwrap(); self.threa...
random
[ { "content": "fn run_tests(targets: &RangeSet, mut f: impl FnMut(u64) -> bool) -> RangeSet {\n\n let mut total_runs = 0u32;\n\n let mut last_runs = 0u32;\n\n let mut started = Instant::now();\n\n let total_targets = targets.len();\n\n\n\n let mut allowed_targets = RangeSet::default();\n\n for ...
Rust
fullnode/src/main.rs
abalaki6/solana
81d43c57a222320a842202f67aaf252d9f103584
use clap::{crate_description, crate_name, crate_version, App, Arg}; use log::*; use solana::cluster_info::{Node, FULLNODE_PORT_RANGE}; use solana::contact_info::ContactInfo; use solana::fullnode::{Fullnode, FullnodeConfig}; use solana::local_vote_signer_service::LocalVoteSignerService; use solana::service::Service; use...
use clap::{crate_description, crate_name, crate_version, App, Arg}; use log::*; use solana::cluster_info::{Node, FULLNODE_PORT_RANGE}; use solana::contact_info::ContactInfo; use solana::fullnode::{Fullnode, FullnodeConfig}; use solana::local_vote_signer_service::LocalVoteSignerService; use solana::service::Service; use...
file = matches.value_of("init_complete_file"); fullnode_config.blockstream = matches.value_of("blockstream").map(|s| s.to_string()); let keypair = Arc::new(keypair); let mut node = Node::new_with_external_ip(&keypair.pubkey(), &gossip_addr); node.info.rpc.set_port(rpc_port); node.info.rpc_pubsub.se...
lnode_config.rpc_config.enable_fullnode_exit = true; } fullnode_config.rpc_config.drone_addr = matches .value_of("rpc_drone_address") .map(|address| address.parse().expect("failed to parse drone address")); let gossip_addr = { let mut addr = solana_netutil::parse_port_or_addr( ...
random
[]
Rust
git-packetline/src/provider/mod.rs
baajur/gitoxide
ebf341936b22e899de88293ef377b438353d1821
use crate::PacketLine; use crate::{decode, MAX_LINE_LEN, U16_HEX_BYTES}; use bstr::ByteSlice; use std::io; mod read; pub use read::ReadWithSidebands; pub struct Provider<T> { inner: T, peek_buf: Vec<u8>, fail_on_err_lines: bool, buf: Vec<u8>, delimiters: &'static [PacketLine<'static>], is_done...
use crate::PacketLine; use crate::{decode, MAX_LINE_LEN, U16_HEX_BYTES}; use bstr::ByteSlice; use std::io; mod read; pub use read::ReadWithSidebands; pub struct Provider<T> { inner: T, peek_buf: Vec<u8>, fail_on_err_lines: bool, buf: Vec<u8>, delimiters: &'static [PacketLine<'static>], is_done...
} else { Some(Ok(Ok(line))) } } res => Some(res), } } pub fn peek_buffer_replace_and_truncate(&mut self, position: usize, replace_with: u8) { let position = position + U16_HEX_BYTES; self.peek_buf[position...
match line.check_error() { Some(err) => { self.is_done = true; Some(Err(io::Error::new(io::ErrorKind::Other, err.0.as_bstr().to_string()))) } None => Some(Ok(Ok(line))), }
if_condition
[]
Rust
src/traits.rs
DebugSteven/curve25519-dalek
cd1452742046eee1acb3b29ff25afb32bdfbc409
use core::borrow::Borrow; use subtle; use scalar::Scalar; pub trait Identity { fn identity() -> Self; } pub trait IsIdentity { fn is_identity(&self) -> bool; } impl<T> IsIdentity for T where T: subtle::ConstantTimeEq + Identity, { fn is_identity(&self) -> bool { self.ct_eq(...
use core::borrow::Borrow; use subtle; use scalar::Scalar; pub trait Identity { fn identity() -> Self; } pub trait IsIdentity { fn is_identity(&self) -> bool; } impl<T> IsIdentity for T where T: subtle::ConstantTimeEq + Identity, { fn is_identity(&self) -> bool { self.ct_eq(...
} pub(crate) trait ValidityCheck { fn is_valid(&self) -> bool; }
fn vartime_multiscalar_mul<I, J>(scalars: I, points: J) -> Self::Point where I: IntoIterator, I::Item: Borrow<Scalar>, J: IntoIterator, J::Item: Borrow<Self::Point>, Self::Point: Clone, { Self::optional_multiscalar_mul( scalars, points.into...
function_block-full_function
[ { "content": "/// Perform constant-time, variable-base scalar multiplication.\n\npub fn mul(point: &EdwardsPoint, scalar: &Scalar) -> EdwardsPoint {\n\n // Construct a lookup table of [P,2P,3P,4P,5P,6P,7P,8P]\n\n let lookup_table = LookupTable::<CachedPoint>::from(point);\n\n // Setting s = scalar, com...
Rust
src/subclass/io_stream.rs
gdesmott/gio
7bf2dfe32cc645ede974009638444fad6bc341c0
use gio_sys; use glib_sys; use glib::prelude::*; use glib::subclass::prelude::*; use glib::translate::*; use glib::Error; use Cancellable; use IOStream; use IOStreamClass; use std::mem; use std::ptr; use once_cell::sync::Lazy; pub trait IOStreamImpl: IOStreamImplExt + Send + 'static { fn get_input_stream(&s...
use gio_sys; use glib_sys; use glib::prelude::*; use glib::subclass::prelude::*; use glib::translate::*; use glib::Error; use Cancellable; use IOStream; use IOStreamClass; use std::mem; use std::ptr; use once_cell::sync::Lazy; pub trait IOStreamImpl: IOStreamImplExt + Send + 'static { fn get_input_stream(&s...
bject_sys::g_object_unref(ptr as *mut _); } gobject_sys::g_object_set_qdata_full( ptr as *mut _, OUTPUT_STREAM_QUARK.to_glib(), ret.as_ptr() as *mut _, Some(unref), ); ret.to_glib_none().0 } unsafe extern "C" fn stream_close<T: ObjectSubclass>( ptr: *mut gio_sys::GI...
; let ret = imp.get_output_stream(&wrap); let old_ptr = gobject_sys::g_object_get_qdata(ptr as *mut _, OUTPUT_STREAM_QUARK.to_glib()); if !old_ptr.is_null() { assert_eq!( old_ptr as *mut _, ret.as_ptr(), "Did not return same output stream again" ...
random
[ { "content": "pub trait DataInputStreamExtManual: 'static {\n\n fn read_line<P: IsA<Cancellable>>(\n\n &self,\n\n cancellable: Option<&P>,\n\n ) -> Result<Vec<u8>, glib::Error>;\n\n\n\n fn read_line_async<\n\n P: IsA<Cancellable>,\n\n Q: FnOnce(Result<Vec<u8>, glib::Error>) ...
Rust
apps/node_monitoring/src/main.rs
tizoc/tezedge
f44cbd00ab73e443593cb8c089cae2732acbfa81
use std::collections::HashMap; use std::collections::VecDeque; use std::sync::{Arc, RwLock}; use slog::{error, info, Drain, Level, Logger}; use tokio::signal; use tokio::time::{sleep, Duration}; use netinfo::Netinfo; use procfs::net::{tcp, tcp6, TcpState}; use procfs::process; use procfs::process::Process; use procfs...
use std::collections::HashMap; use std::collections::VecDeque; use std::sync::{Arc, RwLock}; use slog::{error, info, Drain, Level, Logger}; use tokio::signal; use tokio::time::{sleep, Duration}; use netinfo::Netinfo; use procfs::net::{tcp, tcp6, TcpState}; use procfs::process; use procfs::process::Process; use procfs...
sleep(Duration::from_secs(resource_monitor_interval)).await; } }); info!(log, "Starting rpc server on port {}", &env.rpc_port); let rpc_server_handle = rpc::spawn_rpc_server(env.rpc_port, log.clone(), storages); if let Some(slack) = slack_server { ...
if let Err(e) = resource_monitor.take_measurement().await { error!(thread_log, "Resource monitoring error: {}", e); }
if_condition
[ { "content": "fn check_deprecated_network(env: &Environment, log: &Logger) {\n\n if let Some(deprecation_notice) = env.tezos_network.check_deprecated_network() {\n\n warn!(log, \"Deprecated network: {}\", deprecation_notice);\n\n }\n\n}\n\n\n", "file_path": "light_node/src/main.rs", "rank":...
Rust
imgui-examples/examples/color_button.rs
gw2scratch/imgui-rs
dff20d5af1b1e6b8d453db8a4ed8ac04a25a1d32
use imgui::*; mod support; fn main() { let mut state = State::default(); let system = support::init(file!()); system.main_loop(move |run, ui| { example_selector(run, ui, &mut state); match state.example { 1 => example_1(ui, &mut state), 2 => example_2(ui), ...
use imgui::*; mod support; fn main() { let mut state = State::default(); let system = support::init(file!()); system.main_loop(move |run, ui| { example_selector(run, ui, &mut state); match state.example { 1 => example_1(ui, &mut state), 2 => example_2(ui), ...
w.build(ui, || { ui.text_wrapped( "The displayed color is passed to the button as four float values between \ 0.0 - 1.0 (RGBA). If you don't care about the alpha component, it can be \ disabled and it won't show up in the tooltip", ); ui.text("This but...
let w = Window::new("Example 2: Alpha component") .size([700.0, 320.0], Condition::Appearing) .position([20.0, 140.0], Condition::Appearing);
assignment_statement
[ { "content": "fn example_selector(run: &mut bool, ui: &mut Ui, state: &mut State) {\n\n let w = Window::new(\"Radio button examples\")\n\n .opened(run)\n\n .position([20.0, 20.0], Condition::Appearing)\n\n .size([700.0, 80.0], Condition::Appearing)\n\n .resizable(false);\n\n w....
Rust
sdk/storage/src/blob/mod.rs
cschaible/azure-sdk-for-rust
2876e88bae97377b926cacc24e78c186b0b909ee
pub mod blob; pub mod container; mod headers; pub mod prelude; use crate::core::Client; use azure_core::No; use http::request::Builder; use std::borrow::Borrow; create_enum!(RehydratePriority, (High, "High"), (Standard, "Standard")); pub trait RehydratePrioritySupport { type O; fn with_rehydrate_priority(sel...
pub mod blob; pub mod container; mod headers; pub mod prelude; use crate::core::Client; use azure_core::No; use http::request::Builder; use std::borrow::Borrow; create_enum!(RehydratePriority, (High, "High"), (Standard, "Standard")); pub trait RehydratePrioritySupport { type O; fn with_rehydrate_priority(sel...
} pub trait Blob<C> where C: Client, { fn get_blob<'a>(&'a self) -> blob::requests::GetBlobBuilder<'a, C, No, No>; fn get_blob_properties<'a>(&'a self) -> blob::requests::GetBlobPropertiesBuilder<'a, C, No, No>; fn put_block_blob<'a>(&'a self) -> blob::requests::PutBlockBlobBuilder<'a, C, No, ...
fn add_header(&self, mut builder: Builder) -> Builder { if let Some(rehydrate_priority) = self.rehydrate_priority() { builder = builder.header(headers::REHYDRATE_PRIORITY, rehydrate_priority.as_ref()); } builder }
function_block-full_function
[ { "content": "pub trait BlockListTypeRequired {\n\n fn block_list_type(&self) -> BlockListType;\n\n\n\n fn to_uri_parameter(&self) -> String {\n\n format!(\"blocklisttype={}\", self.block_list_type().to_str())\n\n }\n\n}\n\n\n", "file_path": "sdk/storage/src/blob/blob/mod.rs", "rank": 1,...
Rust
tests/collisions/shapes/support_map_behaviour.rs
yggie/mach
b1c15026e0f31117d0d54ee6eeaeadd3e94a3d92
extern crate quickcheck; use maths::{ApproxEq, Approximations, CrossProduct, DotProduct, UnitVec3D, Vec3D}; use collisions::shapes::{Direction, SupportMap}; pub fn support_map_behaviour<S>(subject: S, input: UnitVec3D) -> quickcheck::TestResult where S: SupportMap { let direction = Direction::from(input); qu...
extern crate quickcheck; use maths::{ApproxEq, Approximations, CrossProduct, DotProduct, UnitVec3D, Vec3D}; use collisions::shapes::{Direction, SupportMap};
fn always_produces_at_least_one_support_point<S>(subject: &S, direction: Direction) -> quickcheck::TestResult where S: SupportMap { quickcheck_assert!(subject.support_points_iter(direction).count() > 0, format!("expected at least one support point in direction {:?} but found none", direction)); quickcheck::T...
pub fn support_map_behaviour<S>(subject: S, input: UnitVec3D) -> quickcheck::TestResult where S: SupportMap { let direction = Direction::from(input); quickcheck_expect!(always_produces_at_least_one_support_point(&subject, direction)); quickcheck_expect!(computes_support_points_which_are_deterministic(&subj...
function_block-full_function
[ { "content": "pub trait Action<T>: fmt::Debug + quickcheck::Arbitrary {\n\n fn perform(&mut self, target: &mut T);\n\n}\n", "file_path": "tests/support/action.rs", "rank": 7, "score": 51587.31981746498 }, { "content": "fn has_enough_faces(polyhedron: &ConvexPolyhedron) -> quickcheck::Test...
Rust
rs_neuralnet/app/src/main/rs/deconvolve2d.rs
isabella232/style-transfer
aa15723ba01f31ff82dc32a22a2787cfe0614638
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable l...
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable l...
m() { int img_h = get_deconv_outsize(col_h, kernel_h, step_y, pad_h); int img_w = get_deconv_outsize(col_w, kernel_w, step_x, pad_w); int dim_x = col_channel * kernel_h * kernel_w; int dim_y = col_h * col_w; int h_padded = img_h + pad_h * 2; int w_padded = img_w + pad_w * 2; for (int...
col_channel; ic++) { int imgY = ic; int colYoff = ic * kernel_h * kernel_w; for (int ikh = 0; ikh < kernel_h; ikh ++) { for (int ikw = 0; ikw < kernel_w; ikw++) { int colY = colYoff + ikh * kernel_w + ikw; for (int ih = 0; ih < tile_h; ih++) { ...
random
[ { "content": " public static float[] unpadd(float[] img_padded, int img_channel,\n\n int img_h, int img_w,\n\n int pad_h, int pad_w) {\n\n int padded_h = img_h + 2 * pad_h;\n\n int padded_w = img_w + 2 * pad_w;\n\n\n\n float...
Rust
crates/ra_ide/src/goto_type_definition.rs
oli-obk/rust-analyzer
ed494d2ed1a3f127e6bf564dab9618e2927ec86c
use hir::db::AstDatabase; use ra_syntax::{ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset}; use crate::{ db::RootDatabase, display::ToNav, expand::descend_into_macros, FilePosition, NavigationTarget, RangeInfo, }; pub(crate) fn goto_type_definition( db: &RootDatabase, position: FilePosition,...
use hir::db::AstDatabase; use ra_syntax::{ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset}; use crate::{ db::RootDatabase, display::ToNav, expand::descend_into_macros, FilePosition, NavigationTarget, RangeInfo, }; pub(crate) fn goto_type_definition( db: &RootDatabase, position: FilePosition,...
1); let nav = navs.pop().unwrap(); nav.assert_match(expected); } #[test] fn goto_type_definition_works_simple() { check_goto( " //- /lib.rs struct Foo; fn foo() { let f: Foo; f<|> } ...
{ let (analysis, pos) = analysis_and_position(fixture); let mut navs = analysis.goto_type_definition(pos).unwrap().unwrap().info; assert_eq!(navs.len(),
function_block-random_span
[ { "content": "fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {\n\n let ws = match file.syntax().token_at_offset(token.text_range().start()) {\n\n TokenAtOffset::Between(l, r) => {\n\n assert!(r == *token);\n\n l\n\n }\n\n TokenAtOffset::Si...
Rust
src/config.rs
khuey/bincode
bca4b6538eb1a87eda82505ae663da72598398d1
use super::internal::{Bounded, Infinite, SizeLimit}; use ::error::Result; use byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian}; use {DeserializerAcceptor, SerializerAcceptor}; use serde; use std::io::{Write, Read}; use std::marker::PhantomData; use de::read::BincodeRead; use self::LimitOption::*; use self...
use super::internal::{Bounded, Infinite, SizeLimit}; use ::error::Result; use byteorder::{BigEndian, ByteOrder, LittleEndian, NativeEndian}; use {DeserializerAcceptor, SerializerAcceptor}; use serde; use std::io::{Write, Read}; use std::marker::PhantomData; use de::read::BincodeRead; use self::LimitOption::*; use self...
config_map!(self, opts => ::internal::serialize_into(w, t, opts)) } #[inline(always)] pub fn deserialize<'a, T: serde::Deserialize<'a>>(&self, bytes: &'a [u8]) -> Result<T> { config_map!(self, opts => ::internal::deserialize(bytes, opts)) } #[doc(hidden)] #[inline(always)] ...
n> { WithOtherEndian::new(self) } } impl<'a, O: Options> Options for &'a mut O { type Limit = O::Limit; type Endian = O::Endian; #[inline(always)] fn limit(&mut self) -> &mut Self::Limit { (*self).limit() } } impl<T: Options> OptionsExt for T {} impl DefaultOptions { fn n...
random
[ { "content": "#[derive(Clone)]\n\nstruct CountSize<L: SizeLimit> {\n\n total: u64,\n\n other_limit: L,\n\n}\n\n\n\npub(crate) fn serialize_into<W, T: ?Sized, O>(writer: W, value: &T, mut options: O) -> Result<()>\n\nwhere\n\n W: Write,\n\n T: serde::Serialize,\n\n O: Options,\n\n{\n\n if optio...
Rust
mqtt/mqtt-edgehub/src/settings.rs
ArchanaMSFT/iotedge
fb546e31a1e73eeb765fb08a22500583edd56341
use std::{ env, path::{Path, PathBuf}, }; use config::{Config, ConfigError, Environment, File, FileFormat}; use lazy_static::lazy_static; use serde::Deserialize; use mqtt_broker::{settings::Enable, BrokerConfig}; pub const DEFAULTS: &str = include_str!("../config/default.json"); lazy_static! { static re...
use std::{ env, path::{Path, PathBuf}, }; use config::{Config, ConfigError, Environment, File, FileFormat}; use lazy_static::lazy_static; use serde::Deserialize; use mqtt_broker::{settings::Enable, BrokerConfig}; pub const DEFAULTS: &str = include_str!("../config/default.json"); lazy_static! { static re...
uthConfig { &self.auth } } impl Default for Settings { fn default() -> Self { DEFAULT_CONFIG.clone() } } fn convert_to_old_env_variable() { if let Ok(val) = env::var("mqttBroker__max_queued_messages") { env::set_var("BROKER__SESSION__max_queued_messages", val); } if le...
artialEq, Deserialize)] #[serde(rename_all = "snake_case")] pub struct Settings { listener: ListenerConfig, broker: BrokerConfig, auth: AuthConfig, } impl Settings { pub fn new() -> Result<Self, ConfigError> { convert_to_old_env_variable(); let mut config = Config::new(); confi...
random
[ { "content": "pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) -> Result<EnvVar<K>, VarError> {\n\n let old_value = std::env::var_os(key.as_ref());\n\n std::env::set_var(key.as_ref(), value);\n\n\n\n Ok(EnvVar::new(key, old_value))\n\n}\n\n\n\npub struct EnvVar<K: AsRef<OsStr>> {\n\n ...
Rust
src/protocol/message/request/get.rs
Tracreed/vndb.rs
e97d084d52d1f190629980114776bf03ff921132
use core::fmt; #[derive(Clone)] pub struct Flags { flags: u16, } impl Flags { const BASIC: u16 = 0b000_000_000_000_01; const DETAILS: u16 = 0b000_000_000_000_10; const ANIME: u16 = 0b000_000_000_001_00; const RELATIONS: u16 = 0b000_000_000_010_00; const TAGS: u16 = 0b000_000_000_100_00; ...
use core::fmt; #[derive(Clone)] pub struct Flags { flags: u16, } impl Flags { const BASIC: u16 = 0b000_000_000_000_01; const DETAILS: u16 = 0b000_000_000_000_10; const ANIME: u16 = 0b000_000_000_001_00; const RELATIONS: u16 = 0b000_000_000_010_00; const TAGS: u16 = 0b000_000_000_100_00; ...
{ if has_prev { write!(f, ",")?; } has_prev = true; write!(f, "{}", name)?; } } Ok(()) } } #[derive(Clone)] pub struct Type { inner: &'static str } impl Type { pub const fn vn() -> Self ...
(Flags::MEAS, "meas"), (Flags::TRAITS, "traits"), (Flags::VNS, "vns"), (Flags::VOICED, "voiced"), ]; for (flag, name) in FLAGS.iter() { if self.flags & flag > 0
random
[ { "content": "#[test]\n\nfn parse_response_error() {\n\n let message = \"error {\\\"id\\\":\\\"parse\\\", \\\"msg\\\":\\\"Invalid command or argument\\\"}\";\n\n\n\n let result = message::Response::from_str(message).expect(\"To parse\");\n\n match result {\n\n message::Response::Error(error) => ...
Rust
chalk-ir/src/visit.rs
audunhalland/chalk
f47846deac8e48df2ba41d4224702e4424a1d6b6
use std::fmt::Debug; use std::ops::ControlFlow; use crate::{ BoundVar, Const, ConstValue, DebruijnIndex, DomainGoal, Goal, InferenceVar, Interner, Lifetime, LifetimeData, PlaceholderIndex, ProgramClause, Ty, TyKind, WhereClause, }; mod binder_impls; mod boring_impls; pub mod visitors; pub use visitors::Visi...
use std::fmt::Debug; use std::ops::ControlFlow; use crate::{ BoundVar, Const, ConstValue, DebruijnIndex, DomainGoal, Goal, InferenceVar, Interner, Lifetime, LifetimeData, PlaceholderIndex, ProgramClause, Ty, TyKind, WhereClause, }; mod binder_impls; mod boring_impls; pub mod visitors; pub use visitors::Visi...
fn forbid_free_placeholders(&self) -> bool { false } fn visit_free_placeholder( &mut self, universe: PlaceholderIndex, _outer_binder: DebruijnIndex, ) -> ControlFlow<Self::BreakTy> { if self.forbid_free_placeholders() { panic!("u...
fn visit_free_var( &mut self, bound_var: BoundVar, outer_binder: DebruijnIndex, ) -> ControlFlow<Self::BreakTy> { if self.forbid_free_vars() { panic!( "unexpected free variable `{:?}` with outer binder {:?}", bound_var, outer_binder ...
function_block-full_function
[ { "content": "// yields the types \"contained\" in `app_ty`\n\nfn constituent_types<I: Interner>(db: &dyn RustIrDatabase<I>, ty: &TyKind<I>) -> Vec<Ty<I>> {\n\n let interner = db.interner();\n\n\n\n match ty {\n\n // For non-phantom_data adts we collect its variants/fields\n\n TyKind::Adt(ad...
Rust
src/storage.rs
djc/rpki-validator
a133f7dad930290ad51d65dbecf862d7063099f0
use std::collections::HashMap; use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::sync::Arc; use std::path::PathBuf; use ipnetwork::IpNetwork; use rpki::asres::AsId; #[derive(Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub struct TrustAnchor { name: String, } impl TrustAnchor ...
use std::collections::HashMap; use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::sync::Arc; use std::path::PathBuf; use ipnetwork::IpNetwork; use rpki::asres::AsId; #[derive(Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub struct TrustAnchor { name: String, } impl TrustAnchor ...
} #[cfg(test)] mod tests { use super::*; #[test] fn find_records_ipv4() { let mut storage = RecordStorage::new(); let records = vec![ Record::new(IpNetwork::V4("1.2.3.0/24".parse().unwrap()), AsId::from(1), 24), Record::new(IpNetwork::V4("3.3.3.0/24".parse().unwrap...
if last_tuple != Some(current_tuple) { output.push(Record::new(*prefix, metadata.origin, metadata.max_length)); } last_tuple = Some(current_tuple); } } output }
function_block-function_prefix_line
[ { "content": "fn default_cache_path() -> String {\n\n env::var(\"CACHE_PATH\").unwrap_or(\"/tmp/rpki-validator-cache\".to_string())\n\n}\n\n\n\n// TalConfig\n\n\n\n#[derive(Deserialize)]\n\npub struct TalConfig {\n\n #[serde(default = \"default_tal_directory\")]\n\n pub directory: String,\n\n}\n\n\n\ni...
Rust
src/opentracing/tracer.rs
mr1sunshine/dd-opentracing-rs
6ea4378f5799fce87acc77a7223dcdf000a09456
use super::{Span, SpanContext, SpanReferenceType, TextMapReader, TextMapWriter}; use eyre::Result; use serde_json::Value; use std::{ rc::Rc, time::{Instant, SystemTime}, }; pub(crate) struct StartSpanOptions { pub start_system_time: SystemTime, pub start_steady_time: ...
use super::{Span, SpanContext, SpanReferenceType, TextMapReader, TextMapWriter}; use eyre::Result; use serde_json::Value; use std::{ rc::Rc, time::{Instant, SystemTime}, }; pub(crate) struct StartSpanOptions { pub start_system_time: SystemTime, pub start_steady_time: ...
options .references .push((self.span_ref_type.clone(), self.referenced.clone())); } } pub(crate) fn child_of(sc: Rc<dyn SpanContext>) -> SpanReference { SpanReference::new(SpanReferenceType::ChildOfRef, sc) } pub(crate) fn follows_from(sc: Rc<dyn SpanContext>) -> SpanReference ...
span_ref_type: SpanReferenceType, referenced: Rc<dyn SpanContext>, } impl SpanReference { pub fn new(span_ref_type: SpanReferenceType, referenced: Rc<dyn SpanContext>) -> Self { Self { span_ref_type, referenced, } } } impl StartSpanOption for SpanReference { ...
random
[ { "content": "use std::collections::{HashMap, HashSet};\n\n\n\nuse super::PropagationStyle;\n\n\n\npub struct TracerOptions {\n\n pub agent_host: String,\n\n pub agent_port: u16,\n\n pub service: String,\n\n pub service_type: String,\n\n pub environment: String,\n\n pub sample_rate: f32,\n\n ...
Rust
controller/k8s/index/src/node.rs
isabella232/polixy
25af9b5e1667b7ee7c503b55ea244b72b83eb8e4
use crate::Index; use anyhow::{anyhow, Context, Result}; use polixy_controller_core::IpNet; use polixy_controller_k8s_api::{self as k8s, ResourceExt}; use std::{ collections::{hash_map::Entry as HashEntry, HashMap, HashSet}, net::IpAddr, sync::Arc, }; use tracing::{debug, instrument, trace, warn}; #[deri...
use crate::Index; use anyhow::{anyhow, Context, Result}; use polixy_controller_core::IpNet; use polixy_controller_k8s_api::{self as k8s, ResourceExt}; use std::{ collections::{hash_map::Entry as HashEntry, HashMap, HashSet}, net::IpAddr, sync::Arc, }; use tracing::{debug, instrument, trace, warn}; #[deri...
}
r"))?; let ip = Self::try_from_cidr(cidr)?; vec![ip] } else { spec.pod_cidrs .into_iter() .map(Self::try_from_cidr) .collect::<Result<Vec<_>>>()? }; Ok(Self(addrs.into())) }
function_block-function_prefixed
[ { "content": "fn mk_node(name: impl Into<String>, pod_net: IpNet) -> k8s::Node {\n\n k8s::Node {\n\n metadata: k8s::ObjectMeta {\n\n name: Some(name.into()),\n\n ..Default::default()\n\n },\n\n spec: Some(k8s::api::core::v1::NodeSpec {\n\n pod_cidr: Some(...
Rust
libtransact/src/execution/adapter/test_adapter.rs
leebradley/transact
6aca715a5cd5b89e08e2906e48e046f210c56387
/* * Copyright 2019 Bitwise IO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
/* * Copyright 2019 Bitwise IO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agree...
fn register(&mut self, name: &str, version: &str) { if let Some(registry) = &mut self.registry { self.available = true; let tf = TransactionFamily::new(name.to_string(), version.to_string()); registry.register_transaction_family(tf); } } fn unregister(&...
self, transaction_pair: TransactionPair, context_id: ContextId, on_done: Box< dyn Fn(Result<ExecutionTaskCompletionNotification, ExecutionAdapterError>) + Send, >, ) { on_done(if self.available { Ok(ExecutionTaskCompletionNotification::Valid( ...
function_block-function_prefix_line
[ { "content": "/// Compute a state address for a given contract.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `name` - the name of the contract\n\n/// * `version` - the version of the contract\n\npub fn compute_contract_address(name: &str, version: &str) -> Result<Vec<u8>, AddressingError> {\n\n let s = String::...
Rust
src/core/codec/postings/skip_writer.rs
unix1986/rucene
bf4de84dafb58eeedfc2b975556890ed3e5dc1f6
use std::cmp::min; use core::store::io::{DataOutput, IndexOutput, RAMOutputStream}; use core::util::{fill_slice, log, DocId}; use error::Result; const SKIP_MULTIPLIER: u32 = 8; pub struct Lucene50SkipWriter { last_skip_doc: Vec<i32>, last_skip_doc_pointer: Vec<i64>, last_skip_pos_pointer: Vec<i64>, ...
use std::cmp::min; use core::store::io::{DataOutput, IndexOutput, RAMOutputStream}; use core::util::{fill_slice, log, DocId}; use error::Result; const SKIP_MULTIPLIER: u32 = 8; pub struct Lucene50SkipWriter { last_skip_doc: Vec<i32>, last_skip_doc_pointer: Vec<i64>, last_skip_pos_pointer: Vec<i64>, ...
load_byte_upto = payload_byte_upto; self.buffer_skip_levels(num_docs) } fn buffer_skip_levels(&mut self, df: u32) -> Result<()> { debug_assert_eq!(df % self.skip_interval, 0); let mut num_levels = 1; let mut df = df / self.skip_interval; loop { ...
field_has_payloads: bool, ) { self.field_has_positions = field_has_positions; self.field_has_offsets = field_has_offsets; self.field_has_payloads = field_has_payloads; } pub fn reset_skip(&mut self, doc_fp: i64, pos_fp: i64, pay_fp: i64) { self.last_doc_fp = doc_fp; ...
random
[ { "content": "pub fn log(mut x: i64, base: i32) -> i32 {\n\n debug_assert!(base > 1);\n\n\n\n let base = i64::from(base);\n\n let mut ret = 0;\n\n while x >= base {\n\n x /= base;\n\n ret += 1;\n\n }\n\n\n\n ret\n\n}\n\n\n", "file_path": "src/core/util/math.rs", "rank": 0...
Rust
src/bin/day13/main.rs
MattiasBuelens/advent-of-code-2019
01a88977bc7b6471bdc84aebd41e1e8d3920946d
use std::cmp::Ordering; use std::collections::HashMap; use std::io; use std::io::BufRead; use advent_of_code_2019::input::parse_list; use advent_of_code_2019::intcode::*; use advent_of_code_2019::vector2d::Vector2D; fn main() { let program: Vec<i64> = parse_list(include_str!("input"), ','); println!("Answer t...
use std::cmp::Ordering; use std::collections::HashMap; use std::io; use std::io::BufRead; use advent_of_code_2019::input::parse_list; use advent_of_code_2019::intcode::*; use advent_of_code_2019::vector2d::Vector2D; fn main() { let program: Vec<i64> = parse_list(include_str!("input"), ','); println!("Answer t...
} type Screen = HashMap<Vector2D, Tile>; fn part1(program: &Vec<i64>) -> usize { let mut screen: Screen = HashMap::new(); let mut machine = ProgramMachine::new(program.clone(), vec![]); loop { let x = match machine.run_to_output() { Some(value) => value, None => { ...
Tile::WALL => "#", Tile::BLOCK => "X", Tile::PADDLE => "_", Tile::BALL => "O", } }
function_block-function_prefix_line
[ { "content": "pub fn lcm(a: i32, b: i32) -> i32 {\n\n (a * b).abs() / gcd(a, b)\n\n}\n\n\n", "file_path": "src/math.rs", "rank": 0, "score": 58733.559386696674 }, { "content": "pub fn gcd(mut a: i32, mut b: i32) -> i32 {\n\n while a != 0 {\n\n let old_a = a;\n\n a = b % a...
Rust
server/src/server.rs
carrolita/shelfdb
d8b887fb572aeddb15574fe1ab1eb6108eded831
use crate::{ admin::{ Mutation as AdminMutation, Query as AdminQuery, Schema as AdminSchema, }, client::{ build_root_node_from_schemas, Schema as ClientSchema, }, context::Context, util::{ graphql_get, graphql_post, playground, ...
use crate::{ admin::{ Mutation as AdminMutation, Query as AdminQuery, Schema as AdminSchema, }, client::{ build_root_node_from_schemas, Schema as ClientSchema, }, context::Context, util::{ graphql_get, graphql_post, playground, ...
pub fn stop(self) { (self.handle)(); } }
q.method(), req.uri().path()) { (&Method::GET, "/") => playground("/graphql"), (&Method::GET, "/graphql") => { graphql_get(Arc::clone(&admin_root_node), context).await } (&Method::POST, "/graphql") => { graphql_post(...
function_block-function_prefixed
[ { "content": "/// Takes care of rendering the playground graphql explorer\n\n///\n\n/// # Arguments\n\n///\n\n/// * `graphql_endpoint` - The absolute path the graphql endpoint is located at\n\npub fn playground(graphql_endpoint: &str) -> Result<Response<Body>, Infallible> {\n\n let mut resp = Response::new(B...
Rust
chronicle-node/src/main.rs
JakeSCahill/chronicle.rs
ac526a9348e648d3e97451d9bcecc47abb7ab3b5
use chronicle_api::api::ApiBuilder; use chronicle_broker::broker::BrokerBuilder; use chronicle_storage::storage::StorageBuilder; use chronicle_common::{ launcher, logger::{ logger_init, LoggerConfigBuilder, }, }; use log::*; use chronicle_broker::importer::ImporterBuilder; use chronicle_s...
use chronicle_api::api::ApiBuilder; use chronicle_broker::broker::BrokerBuilder; use chronicle_storage::storage::StorageBuilder; use chronicle_common::{ launcher, logger::{ logger_init, LoggerConfigBuilder, }, }; use log::*; use chronicle_broker::importer::ImporterBuilder; use chronicle_s...
info!("Welcome to Chronicle Permanode Alpha v0.1.0"); let apps = AppsBuilder::new().build(config); runtime.block_on(async { apps.function(|apps| { tokio::spawn(ctrl_c(apps.tx.clone())); }) .await .storage() .await .api() ...
let mut runtime = Builder::new() .threaded_scheduler() .core_threads(config.tokio.core_threads) .enable_io() .thread_name("chronicle") .thread_stack_size(3 * 1024 * 1024) .build() .unwrap();
assignment_statement
[ { "content": "pub fn query(address: &Trytes81) -> Vec<u8> {\n\n let Query(payload) = Query::new()\n\n .version()\n\n .flags(MyCompression::flag())\n\n .stream(0)\n\n .opcode()\n\n .length()\n\n .statement(\"SELECT tx, extra FROM tangle.edge WHERE vertex = ? AND kind ...
Rust
cli-uno-server/src/main.rs
elftausend/cli-uno
e5dbccda6eec1f24c2d89cc367b57fffe9f95c4c
use std::sync::Arc; use rand::Rng; use tokio::{net::{TcpListener, TcpStream}, sync::{Mutex, RwLock}, io::{AsyncWriteExt, AsyncReadExt}}; const IPPORT: &str = "172.23.1.152:11000"; const MIN_USERS: usize = 4; pub const COLOR_ARRAY: [&str; 4] = ["r", "b", "y", "g"]; pub const CARD_COUNT: usize = 5; pub fn rand_card()...
use std::sync::Arc; use rand::Rng; use tokio::{net::{TcpListener, TcpStream}, sync::{Mutex, RwLock}, io::{AsyncWriteExt, AsyncReadExt}}; const IPPORT: &str = "172.23.1.152:11000"; const MIN_USERS: usize = 4; pub const COLOR_ARRAY: [&str; 4] = ["r", "b", "y", "g"]; pub const CARD_COUNT: usize = 5; pub fn rand_card()...
} ready = check_for_ready(players.clone()).await; } let mut pre_shown = card; loop { let players_guard = players.read().await; let a = players_guard.clone(); drop(players_guard); for player in a.iter() { let username = player.lock()...
layer in players.write().await.iter_mut() { bytes.push(vec![11]); player.lock().await.stream.write_all(&bytes.concat()).await.unwrap(); wait_till_clear(&mut player.lock().await.stream).await; } } async fn send_current_player(players: Players, username: &str) { for player in players.w...
random
[ { "content": "fn set_cards(player: &mut Player, a: String) {\n\n let mut cards = a.split('|').map(|card| card.to_string()).collect::<Vec<String>>();\n\n cards.remove(cards.len()-1);\n\n\n\n print!(\"Your cards:\");\n\n for card in cards.iter() {\n\n colored_card_print(card, \" | \");\n\n }...
Rust
fantoch_ps/src/protocol/common/synod/gc.rs
vitorenesduarte/planet_sim
aea6e324fdce7802976cbafa88a516ed40609ce9
use fantoch::id::ProcessId; use fantoch::trace; use fantoch::HashMap; use threshold::{AboveExSet, EventSet}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct GCTrack { process_id: ProcessId, n: usize, committed: AboveExSet, all_but_me: HashMap<ProcessId, u64>, previous_stable: u64, } impl GCTrack...
use fantoch::id::ProcessId; use fantoch::trace; use fantoch::HashMap; use threshold::{AboveExSet, EventSet}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct GCTrack { process_id: ProcessId, n: usize, committed: AboveExSet, all_but_me: HashMap<ProcessId, u64>, previous_stable: u64, } impl GCTrack...
}
1); gc2.commit(3); gc.committed_by(2, gc2.committed()); assert_eq!(gc.committed(), 2); assert_eq!(gc.stable_slot(), 1); assert_eq!(slots(gc.stable()), vec![1]); assert_eq!(gc.stable_slot(), 1); assert_eq!(slots(gc.stable()), Vec::<u64>::new());...
function_block-function_prefixed
[ { "content": "/// Converts a reprentation of dots to the actual dots.\n\npub fn dots(repr: Vec<(ProcessId, u64, u64)>) -> impl Iterator<Item = Dot> {\n\n repr.into_iter().flat_map(|(process_id, start, end)| {\n\n (start..=end).map(move |event| Dot::new(process_id, event))\n\n })\n\n}\n\n\n", "f...
Rust
src/impls.rs
Polkadex-Substrate/bitcoin_hashes-parity-codec
2281dc4ab712ebc74e8618e8e334460bf18cd04c
#[cfg(feature = "std")] use std::{error, io}; #[cfg(not(feature = "std"))] use core2::{error, io}; use {hex, sha1, sha256, sha512, ripemd160, siphash24, hmac}; use HashEngine; use Error; impl error::Error for Error { #[cfg(feature = "std")] fn cause(&self) -> Option<&error::Error> { None } #[cfg(featur...
#[cfg(feature = "std")] use std::{error, io}; #[cfg(not(feature = "std"))] use core2::{error, io}; use {hex, sha1, sha256, sha512, ripemd160, siphash24, hmac}; use HashEngine; use Error; impl error::Error for Error { #[cfg(feature = "std")] fn cause(&self) -> Option<&error::Error> { None } #[cfg(featur...
}
t!("{}", hmac::Hmac::from_engine(engine)), "59c9aca10c81c73cb4c196d94db741b6bf2050e0153d5a45f2526bff34675ac5" ); let mut engine = hmac::HmacEngine::<sha256::Hash>::new(&[0xde, 0xad, 0xbe, 0xef]); engine.write_all(&[99; 64000]).unwrap(); assert_eq!( format!("{}", ...
function_block-function_prefixed
[ { "content": "fn chars_to_hex(hi: u8, lo: u8) -> Result<u8, Error> {\n\n let hih = (hi as char)\n\n .to_digit(16)\n\n .ok_or(Error::InvalidChar(hi))?;\n\n let loh = (lo as char)\n\n .to_digit(16)\n\n .ok_or(Error::InvalidChar(lo))?;\n\n\n\n let ret = (hih << 4) + loh;\n\n ...
Rust
serde_derive/src/internals/ast.rs
hgzimmerman/serde
4aba6fae78e8be5f9c52dc125c97054e5fbe54c7
use internals::attr; use internals::check; use internals::{Ctxt, Derive}; use syn; use syn::punctuated::Punctuated; pub struct Container<'a> { pub ident: syn::Ident, pub attrs: attr::Container, pub data: Data<'a>, pub generics: &'a syn::Generics, pub original: &'a syn::De...
use internals::attr; use internals::check; use internals::{Ctxt, Derive}; use syn; use syn::punctuated::Punctuated; pub struct Container<'a> { pub ident: syn::Ident, pub attrs: attr::Container, pub data: Data<'a>, pub generics: &'a syn::Generics, pub original: &'a syn::De...
fault), ty: &field.ty, original: field, }) .collect() }
ant| { let attrs = attr::Variant::from_ast(cx, variant); let (style, fields) = struct_from_ast(cx, &variant.fields, Some(&attrs), container_default); Variant { ident: variant.ident.clone(), attrs: attrs, style: style, ...
random
[ { "content": "pub fn get_serde_meta_items(cx: &Ctxt, attr: &syn::Attribute) -> Result<Vec<syn::NestedMeta>, ()> {\n\n if attr.path != SERDE {\n\n return Ok(Vec::new());\n\n }\n\n\n\n match attr.parse_meta() {\n\n Ok(List(meta)) => Ok(meta.nested.into_iter().collect()),\n\n Ok(other...
Rust
src/methods.rs
caranatar/rudeboy-derive
934bd3ad1850ea4933ffe1ab825cafcf39b19036
use proc_macro2::TokenStream as TokenStream2; use quote::{quote, quote_spanned}; use syn; use syn::spanned::Spanned; enum Params<'a> { None, One { name: &'a syn::Ident, ty: Box<syn::Type>, }, Multi { names: Vec<&'a syn::Ident>, tys: Vec<Box<syn::Type>>, }, } struct ...
use proc_macro2::TokenStream as TokenStream2; use quote::{quote, quote_spanned}; use syn; use syn::spanned::Spanned; enum Params<'a> { None, One { name: &'a syn::Ident, ty: Box<syn::Type>, }, Multi { names: Vec<&'a syn::Ident>, tys: Vec<Box<syn::Type>>, }, } struct ...
let self_ty = &ast.self_ty; quote! { #ast impl ::rudeboy::RudeboyMethods for #self_ty { fn generate_methods<'lua, M: ::rlua::UserDataMethods<'lua, Self>>(_methods: &mut M) { #( #mqs )* } } } } pub(crate) fn impl_methods_attr_macro(item: syn...
let mqs: Vec<_> = methods .drain(..) .map(|m| { let call = if m.is_mut { quote! { _methods.add_method_mut } } else { quote! { _methods.add_method } }; ...
assignment_statement
[ { "content": "fn operator_method(name: TokenStream2, rlua_enum: TokenStream2, operator: TokenStream2) -> TokenStream2 {\n\n quote! {\n\n fn #name<'lua, M: ::rlua::UserDataMethods<'lua, Self>>(methods: &mut M) {\n\n methods.add_meta_method(::rlua::MetaMethod::#rlua_enum, |ctx, data, other: S...
Rust
rust/ballista/src/serde/from_proto.rs
houqp/ballista
7011dec497090403ae861b6ce78ec48349755090
use crate::error::{ballista_error, BallistaError}; use crate::plan::Action; use crate::protobuf; use crate::logicalplan::{Expr, LogicalPlan, LogicalPlanBuilder, Operator, ScalarValue}; use arrow::datatypes::{DataType, Field, Schema}; use std::convert::TryInto; impl TryInto<LogicalPlan> for protobuf::LogicalPlanNode...
use crate::error::{ballista_error, BallistaError}; use crate::plan::Action; use crate::protobuf; use crate::logicalplan::{Expr, LogicalPlan, LogicalPlanBuilder, Operator, ScalarValue}; use arrow::datatypes::{DataType, Field, Schema}; use std::convert::TryInto; impl TryInto<LogicalPlan> for protobuf::LogicalPlanNode...
().try_into(), None => Err(ballista_error("Missing required expression")), } }
![parse_required_expr(aggregate_expr.expr)?], return_type: DataType::Boolean, }) } else { Err(ballista_error(&format!( "Unsupported logical expression '{:?}'", self ))) } } } impl TryInto<Action> for protobuf::Acti...
random
[ { "content": "/// Create field meta-data from an expression, for use in a result set schema\n\npub fn exprlist_to_fields(expr: &[Expr], input_schema: &Schema) -> Result<Vec<Field>> {\n\n expr.iter()\n\n .map(|e| expr_to_field(e, input_schema))\n\n .collect()\n\n}\n\n\n", "file_path": "rust/...
Rust
db/src/models/organization_venues.rs
taritom/bn-api
6fbf05bf426c4ddd3d5f50378ac9b51f3ebf2a3f
use chrono::NaiveDateTime; use diesel; use diesel::prelude::*; use models::*; use schema::{organization_venues, organizations, venues}; use utils::errors::DatabaseError; use utils::errors::ErrorCode; use utils::errors::*; use utils::pagination::Paginate; use uuid::Uuid; #[derive(AsChangeset, Associations, Debug, Ident...
use chrono::NaiveDateTime; use diesel; use diesel::prelude::*; use models::*; use schema::{organization_venues, organizations, venues}; use utils::errors::DatabaseError; use utils::errors::ErrorCode; use utils::errors::*; use utils::pagination::Paginate; use uuid::Uuid; #[derive(AsChangeset, Associations, Debug, Ident...
pub fn find_by_venue( venue_id: Uuid, page: Option<u32>, limit: Option<u32>, conn: &PgConnection, ) -> Result<Payload<OrganizationVenue>, DatabaseError> { let limit = limit.unwrap_or(100); let page = page.unwrap_or(0); let (organization_venues, record_co...
nues::table .filter(organization_venues::id.eq(id)) .get_result(conn) .to_db_error(ErrorCode::QueryError, "Could not load organizations") }
function_block-function_prefixed
[ { "content": "ALTER TABLE venues ADD organization_id UUID references organizations(id);\n\n\n", "file_path": "db/migrations/20200206183617_add_organization_venues/down.sql", "rank": 0, "score": 435283.53519720293 }, { "content": "pub fn create_urls(front_url: &String, slug_ids: Vec<Uuid>, ur...
Rust
wechaty/src/user/room.rs
7sDream/rust-wechaty
8f0ae0443fe38deb3cdc91ba9f998fe2cc1df965
use std::fmt; use log::{debug, error}; use wechaty_puppet::{PayloadType, PuppetImpl, RoomMemberQueryFilter, RoomPayload}; use crate::{Contact, Entity, WechatyContext, WechatyError}; pub type Room<T> = Entity<T, RoomPayload>; impl<T> Room<T> where T: 'static + PuppetImpl + Clone + Unpin + Send + Sync, { pub(...
use std::fmt; use log::{debug, error}; use wechaty_puppet::{PayloadType, PuppetImpl, RoomMemberQueryFilter, RoomPayload}; use crate::{Contact, Entity, WechatyContext, WechatyError}; pub type Room<T> = Entity<T, RoomPayload>; impl<T> Room<T> where T: 'static + PuppetImpl + Clone + Unpin + Send + Sync, { pub(...
}
d() } } None => "loading...".to_owned(), }; write!(fmt, "{}", room_info) }
function_block-function_prefixed
[ { "content": "pub trait IntoAsyncFnPtr<Payload, Context, Result>\n\nwhere\n\n Payload: 'static,\n\n{\n\n fn into(self) -> AsyncFnPtr<Payload, Context, Result>;\n\n}\n\n\n\nimpl<F, Payload, Context, Result, Fut> IntoAsyncFnPtr<Payload, Context, Result> for F\n\nwhere\n\n F: Fn(Payload, Context) -> Fut +...
Rust
src/units.rs
LaudateCorpus1/rust-battery
de0994cb651d02fc1f88df24a7595d0ca6306663
#![allow(unused_macros)] pub use uom::si::f32::{ ElectricCharge, ElectricCurrent, ElectricPotential, Energy, Power, Ratio, ThermodynamicTemperature, Time, }; pub use uom::si::Unit; pub use uom::si::{ electric_charge, electric_current, electric_potential, energy, power, ratio, thermodynamic_temperature, time,...
#![allow(unused_macros)] pub use uom::si::f32::{ ElectricCharge, ElectricCurrent, ElectricPotential, Energy, Power, Ratio, The
croampere_hour, $value) }; } macro_rules! milliwatt_hour { ($value:expr) => { unit!($crate::units::energy::milliwatt_hour, $value) }; } macro_rules! microwatt_hour { ($value:expr) => { unit!($crate::units::energy::microwatt_hour, $value) }; } macro_rules! milliampere { ($value...
rmodynamicTemperature, Time, }; pub use uom::si::Unit; pub use uom::si::{ electric_charge, electric_current, electric_potential, energy, power, ratio, thermodynamic_temperature, time, }; use num_traits::ToPrimitive; pub(crate) trait IntoQuantity<T> where T: ToPrimitive, { type Quantity; fn from_primi...
random
[ { "content": "/// Read µW value from the `power_` file and convert into `Power` type.\n\npub fn power<T: AsRef<Path>>(path: T) -> Result<Option<Power>> {\n\n let path = path.as_ref();\n\n debug_assert!(path.file_name().unwrap().to_string_lossy().starts_with(\"power_\"));\n\n\n\n match get::<f32, _>(pat...
Rust
violetabftstore/src/store/metrics.rs
whtcorpsinc/einsteindb-prod
3b1c63a421ff37f1ca6bef4d67ef7f4c4c78a6d7
use prometheus::*; use prometheus_static_metric::*; make_auto_flush_static_metric! { pub label_enum PerfContextType { write_wal_time, write_delay_time, write_scheduling_flushes_compactions_time, db_condition_wait_nanos, write_memBlock_time, pre_and_post_process, ...
use prometheus::*; use prometheus_static_metric::*; make_auto_flush_static_metric! { pub label_enum PerfContextType { write_wal_time, write_delay_time, write_scheduling_flushes_compactions_time, db_condition_wait_nanos, write_memBlock_time, pre_and_post_process, ...
abft_entries_caches", "Total memory size of violetabft entries caches." ).unwrap(); pub static ref APPLY_PENDING_BYTES_GAUGE: IntGauge = register_int_gauge!( "edb_violetabftstore_apply_plightlikeing_bytes", "The bytes plightlikeing in the channel of apply FSMs." ) .unwrap();...
register_histogram_vec!( "edb_violetabftstore_event_duration", "Duration of violetabft store events.", &["type"], exponential_buckets(0.001, 1.59, 20).unwrap() ).unwrap(); pub static ref VIOLETABFT_EVENT_DURATION: VioletaBftEventDuration = aut...
random
[ { "content": "// When we bootstrap the brane we must call this to initialize brane local state first.\n\npub fn write_initial_violetabft_state<W: VioletaBftLogBatch>(violetabft_wb: &mut W, brane_id: u64) -> Result<()> {\n\n let mut violetabft_state = VioletaBftLocalState::default();\n\n violetabft_state.l...
Rust
src/test/instruction_tests/instr_vpmovusdb.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 vpmovusdb_1() { run_test( &Instruction { mnemonic: Mnemonic::VPMOVUSDB, ...
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 vpmovusdb_1() { run_test( &Instruction { mnemonic: Mnemonic::VPMOVUSDB, ...
operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None, }, &[98, 242, 126, 169, 17, 200], OperandSiz...
lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 162, 126, 142, 17, 197], OperandSize::Qword, ) } #[test] fn vpmovusdb_4() { run_tes...
random
[ { "content": "fn encode16_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
milli/src/heed_codec/roaring_bitmap/cbo_roaring_bitmap_codec.rs
Samyak2/milli
11a056d1161e10a649673a603707c4142618612f
use std::borrow::Cow; use std::io; use std::mem::size_of; use byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; use roaring::RoaringBitmap; pub const THRESHOLD: usize = 7; pub struct CboRoaringBitmapCodec; impl CboRoaringBitmapCodec { pub fn serialized_size(roaring: &RoaringBitmap) -> usize { if r...
use std::borrow::Cow; use std::io; use std::mem::size_of; use byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt}; use roaring::RoaringBitmap; pub const THRESHOLD: usize = 7; pub struct CboRoaringBitmapCodec; impl CboRoaringBitmapCodec { pub fn serialized_size(roaring: &RoaringBitmap) -> usize { if r...
pub fn serialize_into(roaring: &RoaringBitmap, vec: &mut Vec<u8>) { if roaring.len() <= THRESHOLD as u64 { for integer in roaring { vec.write_u32::<NativeEndian>(integer).unwrap(); } } else { ro...
s u64 { roaring.len() as usize * size_of::<u32>() } else { roaring.serialized_size() } }
function_block-function_prefixed
[ { "content": "/// Divides one slice into an array and the tail at an index,\n\n/// returns `None` if `N` is out of bounds.\n\npub fn try_split_array_at<T, const N: usize>(slice: &[T]) -> Option<([T; N], &[T])>\n\nwhere\n\n [T; N]: for<'a> TryFrom<&'a [T]>,\n\n{\n\n let (head, tail) = try_split_at(slice, N...
Rust
src/unix/mod.rs
TKGgunter/circuit_lab
bfb2f6029177b479da53a991f26e7137eb4f62e6
#![cfg(target_os = "linux")] #![allow(warnings, unused)] use crate::lab_sims::*; use crate::ui_tools::ui_test; use crate::x11::xlib; use x11::xlib::*;/*{XOpenDisplay, XDefaultScreen, XBlackPixel, XWhitePixel, XNextEvent, XCreateSimpleWindow, XSetStandardProperties, XSelectInput, XEvent, ...
#![cfg(target_os = "linux")] #![allow(warnings, unused)] use crate::lab_sims::*; use crate::ui_tools::ui_test; use crate::x11::xlib; use x11::xlib::*;/*{XOpenDisplay, XDefaultScreen, XBlackPixel, XWhitePixel, XNextEvent, XCreateSimpleWindow, XSetStandardProperties, XSelectInput, XEvent, ...
pub fn make_window() {unsafe{ let window_width = 1000; let window_height = 550; let dis = XOpenDisplay(null()); let screen = XDefaultScreen(dis); let black = XBlackPixel(dis, screen); let white = XWhitePixel(dis, screen); let win = XCreateSimpleWindow(dis, XDefaultRootWi...
fn _set_icon( dis: *mut x11::xlib::_XDisplay, win: x11::xlib::Window, bmp: &TGBitmap ){unsafe{ use std::ffi::CString; let net_wm_icon = x11::xlib::XInternAtom(dis, CString::new("_NET_WM_ICON").expect("net_wm_icon").into_raw(), x11::xlib::False); let cardinal = x11::xlib::XInternAtom(dis, CString::new("C...
function_block-full_function
[ { "content": "#[inline]\n\npub fn DWRITE_MAKE_OPENTYPE_TAG(a: u8, b: u8, c: u8, d: u8) -> u32 {\n\n ((d as u32) << 24) | ((c as u32) << 16) | ((b as u32) << 8) | (a as u32)\n\n}\n\nRIDL!{#[uuid(0x739d886a, 0xcef5, 0x47dc, 0x87, 0x69, 0x1a, 0x8b, 0x41, 0xbe, 0xbb, 0xb0)]\n", "file_path": "winapi-0.3.8/src...
Rust
crates/aptos/src/common/utils.rs
gregnazario/aptos-core
fcf8f8ccfcb0d4141aa95428ec0870d8537edcf3
use crate::{ common::types::{CliError, CliTypedResult}, CliResult, }; use aptos_crypto::{ed25519::Ed25519PrivateKey, PrivateKey}; use aptos_rest_client::{Client, Transaction}; use aptos_sdk::{transaction_builder::TransactionFactory, types::LocalAccount}; use aptos_telemetry::constants::APTOS_CLI_PUSH_METRICS;...
use crate::{ common::types::{CliError, CliTypedResult}, CliResult, }; use aptos_crypto::{ed25519::Ed25519PrivateKey, PrivateKey}; use aptos_rest_client::{Client, Transaction}; use aptos_sdk::{transaction_builder::TransactionFactory, types::LocalAccount}; use aptos_telemetry::constants::APTOS_CLI_PUSH_METRICS;...
fn collect_metrics(command: &str, successful: bool, error: &str) -> HashMap<String, String> { let mut metrics = HashMap::new(); metrics.insert("Command".to_string(), command.to_string()); metrics.insert("Successful".to_string(), successful.to_string()); metrics.insert("Error".to_string(), error.to_str...
metrics, ) .await; let result: ResultWrapper<T> = result.into(); let string = serde_json::to_string_pretty(&result).unwrap(); if is_err { Err(string) } else { Ok(string) } }
function_block-function_prefix_line
[ { "content": "/// Loads an account arg and allows for naming based on profiles\n\npub fn load_account_arg(str: &str) -> Result<AccountAddress, CliError> {\n\n if str.starts_with(\"0x\") {\n\n AccountAddress::from_hex_literal(str).map_err(|err| {\n\n CliError::CommandArgumentError(format!(\"...
Rust
src/main.rs
janeczku/policy-server
dde3b5246a25a2a344329a7ce1492c113857bf9d
extern crate k8s_openapi; extern crate kube; use clap::{App, Arg}; use std::{ net::SocketAddr, process, sync::{ atomic::{AtomicBool, Ordering}, Arc, Barrier, }, thread, }; use tokio::{runtime::Runtime, sync::mpsc::channel}; use tracing::{debug, error, info}; use tracing_subscriber::...
extern crate k8s_openapi; extern crate kube; use clap::{App, Arg}; use std::{ net::SocketAddr, process, sync::{ atomic::{AtomicBool, Ordering}, Arc, Barrier, }, thread, }; use tokio::{runtime::Runtime, sync::mpsc::channel}; use tracing::{debug, error, info}; use tracing_subscriber::...
; unreachable!(); } }; let sources = matches .value_of("sources") .map(|sources_file| match read_sources_file(sources_file) { Ok(sources) => sources, Err(err) => { fatal_error(format!( "error while loading sources f...
fatal_error(format!( "error while loading policies from {}: {}", policies_file, err ))
call_expression
[ { "content": "fn read_request_file(path: &str) -> Result<serde_json::Value> {\n\n let file = File::open(path)?;\n\n let reader = BufReader::new(file);\n\n\n\n let v = serde_json::from_reader(reader)?;\n\n\n\n Ok(v)\n\n}\n\n\n", "file_path": "crates/policy-testdrive/src/main.rs", "rank": 0, ...
Rust
rust-app/src/crypto_helpers.rs
jmininger/ledger-app-kadena
49bea91e58fabbaf3d943b588f92d0562cdc39de
use core::default::Default; use core::fmt; use nanos_sdk::bindings::*; use nanos_sdk::io::SyscallError; use ledger_log::*; use base64; pub const BIP32_PATH: [u32; 5] = nanos_sdk::ecc::make_bip32_path(b"m/44'/535348'/0'/0/0"); pub fn bip32_derive_eddsa(path: &[u32]) -> Result<[u8; 32], SyscallError> { let mut raw_...
use core::default::Default; use core::fmt; use nanos_sdk::bindings::*; use nanos_sdk::io::SyscallError; use ledger_log::*; use base64; pub const BIP32_PATH: [u32; 5] = nanos_sdk::ecc::make_bip32_path(b"m/44'/535348'/0'/0/0"); pub fn bip32_derive_eddsa(path: &[u32]) -> Result<[u8; 32], SyscallError> { let mut raw_...
pub fn get_pubkey_from_privkey(ec_k: &mut nanos_sdk::bindings::cx_ecfp_private_key_t) -> Result<nanos_sdk::bindings::cx_ecfp_public_key_t, SyscallError> { let mut pubkey = cx_ecfp_public_key_t::default(); info!("Calling generate_pair_no_throw"); call_c_api_function!(cx_ecfp_generate_pair_no_throw(CX_CURV...
pub fn get_pubkey(path: &[u32]) -> Result<nanos_sdk::bindings::cx_ecfp_public_key_t, SyscallError> { info!("Getting private key"); let mut ec_k = get_private_key(path).unwrap(); info!("Getting public key"); get_pubkey_from_privkey(&mut ec_k) }
function_block-full_function
[ { "content": "#[inline]\n\npub fn to_hex(m: &[u8]) -> Result<[u8; 64], ()> {\n\n if 2 * m.len() > 64 {\n\n return Err(());\n\n }\n\n let mut hex = [0u8; 64];\n\n let mut i = 0;\n\n for c in m {\n\n let c0 = char::from_digit((c >> 4).into(), 16).unwrap();\n\n let c1 = char::fr...
Rust
src/math/linear_sieve.rs
viktor-vidineev/Rust
cdc7f28ae8d8cee8f972b6bb726f4bbe6f75a29b
/* Linear Sieve algorithm: Time complexity is indeed O(n) with O(n) memory, but the sieve generally runs slower than a well implemented sieve of Eratosthenes. Some use cases are: - factorizing any number k in the sieve in O(log(k)) - calculating arbitrary multiplicative functions on sieve numbers without increasing t...
/* Linear Sieve algorithm: Time complexity is indeed O(n) with O(n) memory, but the sieve generally runs slower than a well implemented sieve of Eratosthenes. Some use cases are: - factorizing any number k in the sieve in O(log(k)) - calculating arbitrary multiplicative functions on sieve numbers without increasing t...
#[test] fn check_factorization() { let mut ls = LinearSieve::new(); ls.prepare(1000).unwrap(); for i in 1..=1000 { let factorization = ls.factorize(i).unwrap(); let mut product = 1usize; for (idx, p) in factorization.iter().enumerate() { ...
fn divisible_by_mpf() { let mut ls = LinearSieve::new(); ls.prepare(1000).unwrap(); for i in 2..=1000 { let div = i / ls.minimum_prime_factor[i]; assert_eq!(i % ls.minimum_prime_factor[i], 0); if div == 1 { assert!(ls.primes.bi...
function_block-full_function
[ { "content": "pub fn nqueens(board_width: i64) -> Result<Vec<i64>, &'static str> {\n\n let mut board_rows = vec![0; board_width as usize];\n\n let mut conflict;\n\n let mut current_row = 0;\n\n\n\n //Process by row up to the current active row\n\n loop {\n\n conflict = false;\n\n\n\n ...
Rust
tsos/tests/lib.rs
FlashSystems/TSoS
a34d8a88bb3f6e4db0da39503c10c4558b91458d
use std::io::Write; use std::path::PathBuf; use std::fs::File; use std::thread::sleep; use std::time::Duration; use std::process::Command; use temp_testdir::TempDir; const CARGO_ARGS: &[&str] = &[ "run", "-q", "--" ]; const BIN_CAT: &str = "/usr/bin/cat"; const BIN_ID: &str = "/usr/bin/id"; const BIN_SLEEP: &str = "/...
use std::io::Write; use std::path::PathBuf; use std::fs::File; use std::thread::sleep; use std::time::Duration; use std::process::Command; use temp_testdir::TempDir; const CARGO_ARGS: &[&str] = &[ "run", "-q", "--" ]; const BIN_CAT: &str = "/usr/bin/cat"; const BIN_ID: &str = "/usr/bin/id"; const BIN_SLEEP: &str = "/...
assert_ne!(mount_before, mount_child); } #[test] fn single_provider() { let tmp = TempDir::default(); let source = to_file(&tmp, "source1.conf", "s1"); let toml_file = to_file(&tmp, "test.toml", &format!(r#" exec = "{bin}" search_path = [ "{path}" ] [secrets] provider = [ "{source}" ] "#, bin = BIN...
nv_search() { let tmp = TempDir::default(); let source = to_file(&tmp, "source.conf", "s1"); let toml_file = to_file(&tmp, "test.toml", &format!(r#" exec = "{bin}" search_path = [ "{path}/a" ] [secrets] provider = [ "{source}" ] "#, bin = BIN_CAT, path = PROV_PATH, source = source.to_string_lossy())); ...
random
[ { "content": "fn find_provider(search_path: &[PathBuf], provider_name: &OsStr) -> Option<PathBuf> {\n\n\tfor path in search_path {\n\n\t\tif path.is_dir() {\n\n\t\t\tlet mut provider_path = PathBuf::from(path);\n\n\t\t\tprovider_path.push(provider_name);\n\n\n\n\t\t\tdebug!(\"Trying {} as secret provider...\", ...
Rust
src/entries.rs
Bigalan09/hmm
57c8dcede02e6e92d53caff520ab8ae4e3c82584
use super::{entry::Entry, seek, Result}; use chrono::prelude::*; use rand::distributions::{Distribution, Uniform}; use std::convert::TryInto; use std::io::{BufRead, Read, Seek, SeekFrom}; pub struct Entries<T: Seek + Read + BufRead> { f: T, buf: String, } impl<T: Seek + Read + BufRead> Entries<T> { pub fn...
use super::{entry::Entry, seek, Result}; use chrono::prelude::*; use rand::distributions::{Distribution, Uniform}; use std::convert::TryInto; use std::io::{BufRead, Read, Seek, SeekFrom}; pub struct Entries<T: Seek + Read + BufRead> { f: T, buf: String, } impl<T: Seek + Read + BufRead> Entries<T> { pub fn...
#[test_case("2020-01-01T00:01:00.899849209+00:00" => Some("1".to_owned()))] #[test_case("2020-02-12T23:08:40.987613062+00:00" => Some("2".to_owned()))] #[test_case("2020-03-12T00:00:00.000000000+00:00" => Some("3".to_owned()))] #[test_case("2020-04-12T23:28:45.726598931+00:00" => Some("4".to_owne...
s())); Entries::new(r) .at(pos) .unwrap() .map(|e| e.message().to_owned()) }
function_block-function_prefixed
[ { "content": "pub fn start_of_prev_line<T: Seek + Read>(f: &mut T) -> Result<Option<u64>> {\n\n start_of_current_line(f)?;\n\n\n\n let mut buf = [0; 1];\n\n let mut pos = f.seek(SeekFrom::Current(0))?;\n\n\n\n if pos == 0 {\n\n return Ok(None);\n\n }\n\n\n\n pos -= 1;\n\n f.seek(Seek...
Rust
src/main.rs
Asriel/Se621
8b409897bd076c9af8825b55c0ce952c002685ff
mod e621; use e621::download; use e621::file; use e621::scraper; use e621::unit; use std::collections::VecDeque; extern crate clap; use clap::{App, Arg}; pub const APP_USER_AGENT: &str = "Se621/0.5.1"; pub const MAX_CHAN_COUNT_TRY: usize = 20; pub const BANNER: &str = " _____ ______ ________ ___\n / ___// __...
mod e621; use e621::download; use e621::file; use e621::scraper; use e621::unit; use std::collections::VecDeque; extern crate clap; use clap::{App, Arg}; pub const APP_USER_AGENT: &str = "Se621/0.5.1"; pub const MAX_CHAN_COUNT_TRY: usize = 20; pub const BANNER: &str = " _____ ______ ________ ___\n / ___// __...
async fn main() { let matches = App::new("Se621") .version("0.5") .author("Asriel <Asriel@dismail.de>") .about("Downloads images from e621/e926 concurrently") .arg( Arg::with_name("tag-file") .short("f") .long("tag-file") ...
function_block-full_function
[ { "content": "/// Function that handles finding or creating the tags file\n\npub fn check_file_path(tag_file: Option<&str>) -> path::PathBuf {\n\n let mut tag_filepath = path::PathBuf::new();\n\n\n\n if tag_file.is_none() {\n\n tag_filepath = env::current_dir().expect(\"Couldn't get current directo...
Rust
auction/program/src/ringbuf.rs
Reisen/solana-program-library
da060ecd116a53d95c19adeba4b444db90ccd3c8
use alloc::{sync::Arc, vec::Vec}; use borsh::{BorshDeserialize, BorshSerialize}; use core::{ cmp::min, mem::{self}, ptr::{self, copy}, }; use crate::{consumer::Consumer, producer::Producer}; #[repr(C)] #[derive(Clone, BorshSerialize, BorshDeserialize, PartialEq)] pub struct RingBuffer<T: Sized> { pu...
use alloc::{sync::Arc, vec::Vec}; use borsh::{BorshDeserialize, BorshSerialize}; use core::{ cmp::min, mem::{self}, ptr::{self, copy}, }; use crate::{consumer::Consumer, producer::Producer}; #[repr(C)] #[derive(Clone, BorshSerialize, BorshDeserialize, PartialEq)] pub struct RingBuffer<T: Sized> { pu...
} else { dst.0.shift(k); } m += k } m }) }) } }
if k == 0 { break; } copy(src.0.ptr, dst.0.ptr, k); if src.0.len == k { src.0 = src.1; src.1 = SlicePtr::null(); } else { src.0.shift(k); ...
random
[ { "content": "/// A more efficient `copy_from_slice` implementation.\n\nfn fast_copy(mut src: &[u8], mut dst: &mut [u8]) {\n\n while src.len() >= 8 {\n\n #[allow(clippy::ptr_offset_with_cast)]\n\n let (src_word, src_rem) = array_refs![src, 8; ..;];\n\n #[allow(clippy::ptr_offset_with_cas...
Rust
projectpad/src/widgets/wintitlebar.rs
emmanueltouzery/projectpad-cli
84770d1b62509c03f9d636eb3a800680840f0fd2
use super::dialogs::import_export_dlg::ImportExportDialog; use super::dialogs::import_export_dlg::Msg as ImportExportMsg; use super::dialogs::preferences::Msg as PreferencesMsg; use super::dialogs::preferences::Preferences; use super::dialogs::standard_dialogs; use super::search_engine::PROJECT_FILTER_PREFIX; use crate...
use super::dialogs::import_export_dlg::ImportExportDialog; use super::dialogs::import_export_dlg::Msg as ImportExportMsg; use super::dialogs::preferences::Msg as PreferencesMsg; use super::dialogs::preferences::Preferences; use super::dialogs::standard_dialogs; use super::search_engine::PROJECT_FILTER_PREFIX; use crate...
view! { #[name="header_bar"] gtk::HeaderBar { show_close_button: true, title: Some("Projectpad"), #[name="menu_button"] gtk::MenuButton { image: Some(&gtk::Image::from_icon_name(Some("open-menu-symbolic"), gtk::IconSize::Menu)), ...
n(); self.widgets.search_entry.set_position(start_idx as i32); let end_idx = cur_text[start_idx..] .find(' ') .map(|i| (start_idx + i) as i32) .unwrap_or(-1); self.widgets .search_entry .select_region(sta...
function_block-function_prefixed
[ { "content": "pub fn display_error_str(msg: &str, e: Option<String>) {\n\n let builder = gtk::builders::MessageDialogBuilder::new()\n\n .buttons(gtk::ButtonsType::Ok)\n\n .message_type(gtk::MessageType::Error)\n\n .modal(true)\n\n .text(msg);\n\n let dlg = if let Some(err) = e ...
Rust
src/pool/spawn.rs
BusyJay/yatp
6dc4a84646868c51104bc8ba8860d7b6cd0464c3
use crate::pool::SchedConfig; use crate::queue::{LocalQueue, Pop, TaskCell, TaskInjector}; use parking_lot_core::{ParkResult, ParkToken, UnparkToken}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; const SHUTDOWN_BIT: usize = 1; const WORKER_COUNT_SHIFT: usize = 1; const WORKER_COUNT_BASE: usize...
use crate::pool::SchedConfig; use crate::queue::{LocalQueue, Pop, TaskCell, TaskInjector}; use parking_lot_core::{ParkResult, ParkToken, UnparkToken}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; const SHUTDOWN_BIT: usize = 1; const WORKER_COUNT_SHIFT: usize = 1; const WORKER_COUNT_BASE: usize...
let (global, locals) = f(config.max_thread_count); let core = Arc::new(QueueCore::new(global, config)); let l = locals .into_iter() .enumerate() .map(|(i, l)| Local::new(i + 1, l, core.clone())) .collect(); let g = Remote::new(core); (g, l) }
function_block-function_prefix_line
[ { "content": "/// Creates a task queue that allows given number consumers.\n\npub fn simple<T>(local_num: usize) -> (TaskInjector<T>, Vec<LocalQueue<T>>) {\n\n let (injector, locals) = simple::create(local_num);\n\n (\n\n TaskInjector(InjectorInner::Simple(injector)),\n\n locals\n\n ...
Rust
src/props/props_health_2010.rs
mzdyhrave/legaliosrust
3549604bf7ad5e30f3b14ddf371ffe8ece730c34
use rust_decimal::Decimal; use crate::factories::provider_factory::{BoxHealthProps}; use crate::props::particy_results::{ParticyHealthResult, ParticyHealthTarget}; use crate::props::props::IProps; use crate::props::props_health_base::{IPropsHealth, PropsHealthBase}; use crate::service::contract_terms::WorkHealthTerms; ...
use rust_decimal::Decimal; use crate::factories::provider_factory::{BoxHealthProps}; use crate::props::particy_results::{ParticyHealthResult, ParticyHealthTarget}; use crate::props::props::IProps; use crate::props::props_health_base::{IPropsHealth, PropsHealthBase}; use crate::service::contract_terms::WorkHealthTerms; ...
ded_employer_paym(&self, basis_result: i32) -> i32 { return self.props.rounded_employer_paym(basis_result); } fn annuals_basis_cut(&self, income_list: &Vec<ParticyHealthTarget>, annuity_basis: i32) -> (i32, i32, Vec<ParticyHealthResult>) { return self.props.annuals_basis_cut(income_list, annui...
return self.props.value_equals(other_health); } fn has_particy(&self, term: &WorkHealthTerms, income_term: i32, income_spec: i32) -> bool { return self.props.has_particy_with_adapters(term, income_term, income_spec, Self::has_term_exemption_particy, ...
random
[ { "content": "pub trait IPropsHealth : IProps {\n\n fn min_monthly_basis(&self) -> i32;\n\n fn max_annuals_basis(&self) -> i32;\n\n fn lim_monthly_state(&self) -> i32;\n\n fn lim_monthly_dis50(&self) -> i32;\n\n fn factor_compound(&self) -> Decimal;\n\n fn factor_employee(&self) -> Decimal;\n\...
Rust
src/nav_grid.rs
PsichiX/navmesh
e670bd276f3d7e074812092e8f4d8ac6b7d13b9d
use crate::{Error, NavResult, Scalar}; use petgraph::{ algo::{astar, tarjan_scc}, graph::NodeIndex, visit::EdgeRef, Directed, Graph, Undirected, }; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; #[cfg(not(feature = "scalar64"))] use std::f32::MAX as SCALAR_MAX; #[cfg(feat...
use crate::{Error, NavResult, Scalar}; use petgraph::{ algo::{astar, tarjan_scc}, graph::NodeIndex, visit::EdgeRef, Directed, Graph, Undirected, }; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; #[cfg(not(feature = "scalar64"))] use std::f32::MAX as SCALAR_MAX; #[cfg(feat...
if connection.to.0 >= cols || connection.to.1 >= rows { return Err(Error::InvalidCellCoordinate( connection.to.0, connection.to.1, cols, rows, )); } } let costs = vec!...
if connection.from.0 >= cols || connection.from.1 >= rows { return Err(Error::InvalidCellCoordinate( connection.from.0, connection.from.1, cols, rows, )); }
if_condition
[ { "content": " /// (cols count, rows count)\n\n EmptyCells(usize, usize),\n\n /// Trying to use cell coordinate out of bounds.\n\n /// (col, row, cols count, rows count)\n\n InvalidCellCoordinate(usize, usize, usize, usize),\n\n}\n\n\n\n/// Result data.\n\npub type NavResult<T> = StdResult<T, Err...
Rust
crates/hir_expand/src/builtin_attr_macro.rs
ihciah/rust-analyzer
494fab202a7ec00f79636dcece8ca5e2742efff0
use itertools::Itertools; use syntax::ast; use crate::{ db::AstDatabase, name, AstId, CrateId, ExpandResult, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind, }; macro_rules! register_builtin { ( $(($name:ident, $variant:ident) => $expand:ident),* ) => { #[derive(Debug, Clone, Copy, PartialE...
use itertools::Itertools; use syntax::ast; use crate::{ db::AstDatabase, name, AstId, CrateId, ExpandResult, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind, }; macro_rules! register_builtin { ( $(($name:ident, $variant:ident) => $expand:ident),* ) => { #[derive(Debug, Clone, Copy, PartialE...
fn dummy_attr_expand( _db: &dyn AstDatabase, _id: MacroCallId, tt: &tt::Subtree, ) -> ExpandResult<tt::Subtree> { ExpandResult::ok(tt.clone()) } fn derive_attr_expand( db: &dyn AstDatabase, id: MacroCallId, tt: &tt::Subtree, ) -> ExpandResult<tt::Subtree> { let loc = db.lookup_intern_...
pub fn find_builtin_attr( ident: &name::Name, krate: CrateId, ast_id: AstId<ast::Macro>, ) -> Option<MacroDefId> { let expander = BuiltinAttrExpander::find_by_name(ident)?; Some(MacroDefId { krate, kind: MacroDefKind::BuiltInAttr(expander, ast_id), local_inner: false, }) ...
function_block-full_function
[ { "content": "fn eq_expand(db: &dyn AstDatabase, id: MacroCallId, tt: &tt::Subtree) -> ExpandResult<tt::Subtree> {\n\n let krate = find_builtin_crate(db, id);\n\n expand_simple_derive(tt, quote! { #krate::cmp::Eq })\n\n}\n\n\n", "file_path": "crates/hir_expand/src/builtin_derive_macro.rs", "rank":...
Rust
src/main.rs
hw0lff/serial-console
75452b6d95c81dfb606932eb9efb2817786bf2a1
use std::io::{self, stdin, stdout, Read, Write}; use std::sync::mpsc::{channel, Receiver, TryRecvError}; use std::thread; use std::time::Duration; use clap::Parser; use serialport::{DataBits, FlowControl, Parity, SerialPort, SerialPortBuilder, StopBits}; use termion::raw::{IntoRawMode, RawTerminal}; use termion::scree...
use std::io::{self, stdin, stdout, Read, Write}; use std::sync::mpsc::{channel, Receiver, TryRecvError}; use std::thread; use std::time::Duration; use clap::Parser; use serialport::{DataBits, FlowControl, Parity, SerialPort, SerialPortBuilder, StopBits}; use termion::raw::{IntoRawMode, RawTerminal}; use termion::scree...
e::ProcessCMD; return NextStep::LoopContinue; } b'\r' => { *escape_state = EscapeState::WaitForEC; } _ => { *escape_state = EscapeState::WaitForEnter; } }, EscapeState::ProcessCMD => match *charac...
(); let mut screen = AlternateScreen::from(stdout().into_raw_mode().unwrap()); write_start_screen_msg(&mut screen); let (tx, rx) = channel::<([u8; 512], usize)>(); let _terminal_stdin = thread::spawn(move || loop { let mut data = [0; 512]; let n = stdin.read(&mut data[..]).unwrap...
random
[ { "content": "# Scip - Serial Console Interfacing Program\n\nA command line tool to communicate with a serial console written in [Rust](https://rust-lang.org)\n\n\n\n# Usage example\n\n```bash\n\nscip /dev/ttyUSB0 115200\n\n# show help for more options\n\nscip -h\n\n```\n\n\n\n# Installation \n\n```bash\n\ncarg...
Rust
src/solutions/day19.rs
fspoettel/advent-of-code-2021
26136926e5f3b79028f520a0f5fe884081e66c6d
use itertools::Itertools; use std::{ collections::HashSet, ops::{Add, Sub}, }; #[derive(Clone, Copy, Eq, Hash, PartialEq)] struct Point(i32, i32, i32); impl Add for Point { type Output = Self; fn add(self, other: Self) -> Self { Self(self.0 + other.0, self.1 + other.1, self.2 + other.2) }...
use itertools::Itertools; use std::{ collections::HashSet, ops::{Add, Sub}, }; #[derive(Clone, Copy, Eq, Hash, PartialEq)] struct Point(i32, i32, i32); impl Add for Point { type Output = Self; fn add(self, other: Self) -> Self { Self(self.0 + other.0, self.1 + other.1, self.2 + other.2) }...
ttan_distance(b)) .max() .unwrap() } #[cfg(test)] mod tests { use super::*; #[test] fn test_part_one() { use aoc::read_file; let input = read_file("examples", 19); assert_eq!(part_one(&input), 79); } #[test] fn test_part_two() { use aoc::read_fi...
ances[b]).next().unwrap(); let (c0, c1) = find_pair_by_distance(&aligned[a], *common_distance); let (t0, t1) = find_pair_by_distance(&reports[b], *common_distance); let mut alignment: Option<Point> = None; let mut rot = 0; while rot < 24 { let r0 = t0.rotate(rot); ...
random
[ { "content": "fn parse_point(l: &str) -> Point {\n\n let mut coords = l.split(',');\n\n let x: usize = coords.next().unwrap().parse().unwrap();\n\n let y: usize = coords.next().unwrap().parse().unwrap();\n\n Point(x, y)\n\n}\n\n\n", "file_path": "src/solutions/day13.rs", "rank": 3, "scor...
Rust
src/webservices.rs
risoflora/fiscalidade
0bc1f92b2ac77c4d8ab7ff8bb42e9c5bdd51816f
use std::{io, path::Path, result}; use thiserror::Error; use tokio::fs; use toml::{de::Error as TomlError, Value as TomlValue}; use crate::tipos::{self, Ambiente, Modelo, Servico, Uf}; #[derive(Error, Debug)] pub enum WebServicesError { #[error(transparent)] Io(#[from] io::Error), #[error(trans...
use std::{io, path::Path, result}; use thiserror::Error; use tokio::fs; use toml::{de::Error as TomlError, Value as TomlValue}; use crate::tipos::{self, Ambiente, Modelo, Servico, Uf}; #[derive(Error, Debug)] pub enum WebServicesError { #[error(transparent)] Io(#[from] io::Error), #[error(trans...
if servico == Servico::ConsultaCadastro && (uf == Uf::Pa || uf == Uf::Am || uf == Uf::Al || uf == Uf::Ap || uf == Uf::Df || uf == Uf::Pi || uf == Uf::Rj || uf == Uf::Ro ||...
(mut self, contingencia: bool) -> Self { self.contingencia = contingencia; self } pub fn build(self) -> WebServicesBuilderResult { let toml = self.toml.ok_or(WebServicesBuilderError::TomlNaoInformado)?; let modelo = self .modelo .ok_or(WebServicesBuilderE...
random
[ { "content": "#[inline]\n\npub fn validar_uf(uf: &str) -> bool {\n\n Uf::from_str(uf).is_some()\n\n}\n\n\n\n/// Valida se Ambiente é está presente na lista de Ambientes válidos.\n", "file_path": "src/util.rs", "rank": 0, "score": 131619.99570128458 }, { "content": "#[inline]\n\npub fn val...
Rust
rust/template/src/main.rs
blp/differential-datalog
83a9053c55dc673d4a49527c179c75d1dbf58b6a
#![allow(dead_code, non_snake_case)] use std::convert::TryFrom; use std::io::stdout; use std::io::Write; use std::sync::Arc; use std::sync::Mutex; use std::thread::sleep; use std::time::Duration; use api::{updcmd2upd, HDDlog}; use cmd_parser::*; use datalog_example_ddlog::*; use differential_datalog::ddval::*; use ...
#![allow(dead_code, non_snake_case)] use std::convert::TryFrom; use std::io::stdout; use std::io::Write; use std::sync::Arc; use std::sync::Mutex; use std::thread::sleep; use std::time::Duration; use api::{updcmd2upd, HDDlog}; use cmd_parser::*; use datalog_example_ddlog::*; use differential_datalog::ddval::*; use ...
#[allow(clippy::redundant_closure)] fn main() -> Result<(), String> { let parser = opts! { synopsis "DDlog CLI interface."; auto_shorts false; opt store:bool=true, desc:"Do not store relation state (for benchmarking only)."; opt delta:bool=true, desc:"Do not record changes."; ...
fn run(mut hddlog: HDDlog, print_deltas: bool) -> Result<(), String> { let upds = Arc::new(Mutex::new(Vec::new())); interact(|cmd, interactive| { handle_cmd( &hddlog, print_deltas, interactive, &mut upds.lock().unwrap(), cmd, ) })?;...
function_block-full_function
[]
Rust
magro/src/discovery.rs
lo48576/magro
6335aba9c2d2bc9f6a81c9a537ed62c21d695b8b
use std::{ fs, io, iter, path::{Path, PathBuf}, }; use anyhow::anyhow; use git2::{Repository, RepositoryOpenFlags}; use thiserror::Error as ThisError; use crate::vcs::Vcs; #[derive(Debug, ThisError)] #[error(transparent)] pub struct Error { source: anyhow::Error, } impl Error { #[inline]...
use std::{ fs, io, iter, path::{Path, PathBuf}, }; use anyhow::anyhow; use git2::{Repository, RepositoryOpenFlags}; use thiserror::Error as ThisError; use crate::vcs::Vcs; #[derive(Debug, ThisError)] #[error(transparent)] pub struct Error { source: anyhow::Error, } impl Error { #[inline]...
return Ok(Some(RepoEntry::new(Vcs::Git, entry.into_path()))); } Err(e) => { log::debug!( "Directory {:?} is neither a git directory nor a bare repository: {}", path, ...
if workdir == Some(parent) { log::trace!( "Skipping {:?} as it is the working directory of {:?}", parent, path ); ...
if_condition
[ { "content": "/// Sets the path to the collection directory.\n\nfn set_path(context: &mut Context, name: &CollectionName, path: &Path) -> anyhow::Result<()> {\n\n context\n\n .config_mut()\n\n .collections_mut()\n\n .get_mut(name)\n\n .ok_or_else(|| anyhow!(\"Collection named `{}`...
Rust
examples/shared/shader_lib.rs
thomcc/bad3d
e8ecd7f4f37444c8336480d3ae754e5a83204d01
use super::watched_file::WatchedFile; use failure::ResultExt; use glium::backend::Facade; use std::collections::HashMap; use std::path::{Path, PathBuf}; #[derive(Debug, Clone)] pub struct ShaderConf { pub repo_relative_path: &'static str, pub override_env_var: Option<&'static str>, pub preamble_file: Optio...
use super::watched_file::WatchedFile; use failure::ResultExt; use glium::backend::Facade; use std::collections::HashMap; use std::path::{Path, PathBuf}; #[derive(Debug, Clone)] pub struct ShaderConf { pub repo_relative_path: &'static str, pub override_env_var: Option<&'static str>, pub preamble_file: Optio...
est = &parts[i..]; if !rest.is_empty() { let path = rest.join("/"); subdirs_to_search.push(path); } } for (what, how, search_parents) in to_search { let mut d = match how() { Ok(d) => d, Err(e) => { ...
h_interval(std::time::Duration::from_millis(250)), }; self.items.insert(name, shader_info); } Ok(()) } fn find_path(conf: &ShaderConf) -> Option<PathBuf> { let to_search: &[(&str, fn() -> std::io::Result<PathBuf>, bool)] = &[ ("current_dir", std::env:...
random
[ { "content": "pub fn compute_hull(verts: &mut [V3]) -> Option<(Vec<[u16; 3]>, usize)> {\n\n compute_hull_bounded(verts, 0)\n\n}\n\n\n", "file_path": "src/hull.rs", "rank": 3, "score": 212391.86479704268 }, { "content": "pub fn convex_hit_check(planes: impl Iterator<Item = Plane>, p0: V3, ...
Rust
crates/tm4c129x/src/watchdog0/ctl.rs
m-labs/ti2svd
30145706b658136c35c90290701de3f02a4b8ef2
#[doc = "Reader of register CTL"] pub type R = crate::R<u32, super::CTL>; #[doc = "Writer for register CTL"] pub type W = crate::W<u32, super::CTL>; #[doc = "Register CTL `reset()`'s with value 0"] impl crate::ResetValue for super::CTL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
#[doc = "Reader of register CTL"] pub type R = crate::R<u32, super::CTL>; #[doc = "Writer for register CTL"] pub type W = crate::W<u32, super::CTL>; #[doc = "Register CTL `reset()`'s with value 0"] impl crate::ResetValue for super::CTL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { ...
} impl<'a> WRC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the fie...
es raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `INTTYPE`"] pub type INTTYPE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `IN...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...