lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/ib_contract.rs
rolandgg/rust_ib_api
4abed42a199b32600b96a84a89471bfd1786d124
use crate::ib_enums; use rust_decimal::prelude::*; use crate::ib_enums::*; use crate::utils::ib_message::Encodable; use chrono::{DateTime,NaiveDateTime,Utc,TimeZone}; use chrono_tz::Tz; use chrono_tz::{UTC,US}; #[derive(Debug,Clone)] pub struct ComboLeg { pub con_id: i32, pub ratio: i32, pub action: ib_enum...
use crate::ib_enums; use rust_decimal::prelude::*; use crate::ib_enums::*; use crate::utils::ib_message::Encodable; use chrono::{DateTime,NaiveDateTime,Utc,TimeZone}; use chrono_tz::Tz; use chrono_tz::{UTC,US}; #[derive(Debug,Clone)] pub struct ComboLeg { pub con_id: i32, pub ratio: i32, pub action: ib_enum...
} #[derive(Default,Debug)] pub struct ContractDetails { pub contract: Option<Contract>, pub market_name: Option<String>, pub min_tick: Option<Decimal>, pub price_magnifier: Option<i32>, pub order_types: Option<String>, pub valid_exchanges: Option<String>, pub under_con_id: Option<i32>, ...
pub fn stock_spread_smart_usd(contract_1: &Contract, ratio_1: i32, contract_2: &Contract, ratio_2: i32) -> Option<Contract> { let mut ret = None; if let Some(con_id_1) = contract_1.con_id { if let Some(con_id_2) = contract_2.con_id { if let Some(symbol_1) = &contract_1.symbol...
function_block-full_function
[ { "content": " pub trait Encodable \n\n {\n\n fn encode(&self) -> String;\n\n }\n\n\n\n impl Encodable for f64 {\n\n fn encode(&self) -> String {\n\n self.to_string() +\"\\0\"\n\n }\n\n }\n\n impl Encodable for i32 {\n\n fn encode(&self) -> String {\n\n ...
Rust
src/handlebars_helpers.rs
jgarte/dotter
327b40797cd99931c79523eef4d3577d1ff2e453
use std::process::{Command, Stdio}; use config::{Files, Helpers, Variables}; use handlebars::{Context, Handlebars, Helper, HelperResult, Output, RenderContext, RenderError}; use meval; use toml::value::{Table, Value}; fn math_helper( h: &Helper, _: &Handlebars, _: &Context, _: &mut RenderContext, ...
use std::process::{Command, Stdio}; use config::{Files, Helpers, Variables}; use handlebars::{Context, Handlebars, Helper, HelperResult, Output, RenderContext, RenderError}; use meval; use toml::value::{Table, Value}; fn math_helper( h: &Helper, _: &Handlebars, _: &Context, _: &mut RenderContext, ...
.stderr(Stdio::null()) .status() .map(|s| s.success()) } #[cfg(windows)] fn os_shell() -> Command { let mut cmd = Command::new("cmd"); cmd.arg("/C"); cmd } #[cfg(unix)] fn os_shell() -> Command { let mut cmd = Command::new("sh"); cmd.arg("-c"); cmd } pub fn register_ru...
fn is_executable(name: &str) -> Result<bool, std::io::Error> { Command::new("which") .arg(name) .stdin(Stdio::null()) .stdout(Stdio::null())
function_block-random_span
[ { "content": "pub fn real_path(path: &Path) -> Result<PathBuf, io::Error> {\n\n let path = std::fs::canonicalize(&path)?;\n\n Ok(platform_dunce(path))\n\n}\n\n\n", "file_path": "src/filesystem.rs", "rank": 11, "score": 81662.87903831337 }, { "content": "pub fn delete_parents(path: &Pat...
Rust
examples/todomvc/src/scheduler.rs
tlively/wasm-bindgen
64e53a5502d92143ff312d461c286cc22522c8ae
use crate::controller::Controller; use crate::exit; use crate::view::View; use crate::Message; use std::cell::RefCell; use std::rc::Rc; pub struct Scheduler { controller: Rc<RefCell<Option<Controller>>>, view: Rc<RefCell<Option<View>>>, events: RefCell<Vec<Message>>, running: RefCell<bool>, } impl Sch...
use crate::controller::Controller; use crate::exit; use crate::view::View; use crate::Message; use std::cell::RefCell; use std::rc::Rc; pub struct Scheduler { controller: Rc<RefCell<Option<Controller>>>, view: Rc<RefCell<Option<View>>>, events: RefCell<Vec<Message>>, running: RefCell<bool>, } impl Sch...
eadlock"); } } } impl Drop for Scheduler { fn drop(&mut self) { exit("calling drop on Scheduler"); } }
().clone(); } else { exit("This might be a deadlock"); } } if events_len == 0 { if let Ok(mut running) = self.running.try_borrow_mut() { *running = false; } else { exit("This might be a deadlock"); ...
random
[ { "content": "/// Runs a small pass over `Module` to replace all calls to the\n\n/// `__wbindgen_throw` intrinsic with an `unreachable` instruction.\n\n///\n\n/// This pass is executed as part of the wasm interface types support. This is\n\n/// done to support debug mode executables with wasm interface types. D...
Rust
src/trec.rs
Enet4/vindicator
736d36a6eb0b5b8b3776084e44854066130d6951
use crate::{Rank, RankedSearchEntry, Score, SearchEntry}; use std::fmt; use std::io::Write; #[derive(Debug, Eq, PartialEq)] pub struct TrecEntry<'a> { pub qid: &'a str, pub docno: &'a str, pub rank: Rank, pub score: Score, pub runid: &'a str, } impl<'a> TrecEntry<'a> { ...
use crate::{Rank, RankedSearchEntry, Score, SearchEntry}; use std::fmt; use std::io::Write; #[derive(Debug, Eq, PartialEq)] pub struct TrecEntry<'a> { pub qid: &'a str, pub docno: &'a str, pub rank: Rank, pub score: Score, pub runid: &'a str, } impl<'a> TrecEntry<'a> { ...
pub fn write_all<'a, I, W>(mut writer: W, list: I) -> Result<(), std::io::Error> where I: IntoIterator<Item = TrecEntry<'a>>, W: Write, { for e in list { write(&mut writer, e)?; } Ok(()) }
function_block-full_function
[ { "content": "/// Reciprocal rank fusion algorithm\n\npub fn rrf(ranks: &[Rank]) -> Score {\n\n ranks.into_iter().map(|&r| 1. / (1. + r as f32)).map(score).sum()\n\n}\n\n\n", "file_path": "src/fuser.rs", "rank": 3, "score": 102328.30652587666 }, { "content": "/// Combines multiple ranked ...
Rust
src/selectors.rs
paolobarbolini/rsass
25a65768c8be6c4ba7413bd0193c061d31a7a4ef
use crate::css::Value; use crate::sass::SassString; use crate::value::ListSeparator; use crate::{Error, ParseError, ScopeRef}; use std::fmt; use std::io::Write; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd)] pub struct Selectors { pub s: Vec<Selector>, backref: Selector, } impl Selectors { ...
use crate::css::Value; use crate::sass::SassString; use crate::value::ListSeparator; use crate::{Error, ParseError, ScopeRef}; use std::fmt; use std::io::Write; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd)] pub struct Selectors { pub s: Vec<Selector>, backref: Selector, } impl Selectors { ...
ref arg } => { let arg = match &arg { Some(ref a) => Some(a.eval(scope.clone())?), None => None, }; Ok(SelectorPart::PseudoElement { name: name.evaluate2(scope)?, arg, }) ...
None => part.to_string(), }); } } (v, last) }, ); if let Some(last) = last { v.push(last.into()); }...
random
[]
Rust
src/config/mod.rs
johnstonskj/packpack
c750ae09a908c63a28c312a36e1fc8f26d1730f4
/*! One-line description. More detailed description, with # Example */ use crate::error::ErrorKind; use crate::name::Name; use serde::Deserialize; use std::path::PathBuf; #[derive(Clone, Debug)] pub struct Configuration { platform: CurrentPlatform, layers: Vec<Box<LayerKind>>, installers: Installers, }...
/*! One-line description. More detailed description, with # Example */ use crate::error::ErrorKind; use crate::name::Name; use serde::Deserialize; use std::path::PathBuf; #[derive(Clone, Debug)] pub struct Configuration { platform: CurrentPlatform, layers: Vec<Box<LayerKind>>, installers: Installers, }...
pub mod installers; use installers::{Installer, Installers}; pub mod layers; pub use layers::LayerKind; pub mod platforms; pub use platforms::{CurrentPlatform, Platform, Platforms}; #[cfg(test)] mod tests { use super::*; #[allow(unused_imports)] use pretty_assertions::{assert_eq, assert_ne}; #[tes...
if let Some(mut file_path) = base_path { file_path.push(&format!("{}.toml", base_name)); Some(file_path) } else { None } }
function_block-function_prefix_line
[ { "content": "pub fn get_current_platform_config() -> Result<CurrentPlatform, ErrorKind> {\n\n info!(\"get_current_platform_config()\");\n\n let mut platforms = load_config()?;\n\n if let Some(name) = current_name() {\n\n match platforms.remove(&name) {\n\n Some(platform) => Ok(Curren...
Rust
crates/syntax/src/ted.rs
JmPotato/rust-analyzer
26fdd17cc6fc79b476977c2a40a90de7095e4b45
use std::ops::RangeInclusive; use parser::T; use crate::{ast::make, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken}; #[derive(Debug)] pub struct Position { repr: PositionRepr, } #[derive(Debug)] enum PositionRepr { FirstChild(SyntaxNode), After(SyntaxElement), } impl Position { pub fn after(e...
use std::ops::RangeInclusive; use parser::T; use crate::{ast::make, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken}; #[derive(Debug)] pub struct Position { repr: PositionRepr, } #[derive(Debug)] enum PositionRepr { FirstChild(SyntaxNode), After(SyntaxElement), } impl Position { pub fn after(e...
pub fn insert_all_raw(position: Position, elements: Vec<SyntaxElement>) { let (parent, index) = match position.repr { PositionRepr::FirstChild(parent) => (parent, 0), PositionRepr::After(child) => (child.parent().unwrap(), child.index() + 1), }; parent.splice_children(index..index, elements...
elements.insert(0, ws.into()) } } if let Some(last) = elements.last() { if let Some(ws) = ws_after(&position, last) { elements.push(ws.into()) } } insert_all_raw(position, elements) }
function_block-function_prefix_line
[ { "content": "/// Returns true if the parent nodes of `node` all match the `SyntaxKind`s in `kinds` exactly.\n\nfn parents_match(mut node: NodeOrToken<SyntaxNode, SyntaxToken>, mut kinds: &[SyntaxKind]) -> bool {\n\n while let (Some(parent), [kind, rest @ ..]) = (&node.parent(), kinds) {\n\n if parent...
Rust
2021/src/day11.rs
ajitnilakantan/advent-of-code
9015ed5065a4d094387172cb4319ee80274b1138
use ndarray::Array2; use regex::Regex; use std::collections::HashSet; use std::fs; use std::fs::File; use std::io::{self, BufRead, Error}; use std::path::Path; #[allow(dead_code)] fn read_lines<P>(filename: P) -> Result<Vec<String>, Error> where P: AsRef<Path>, { let file = File::open(filename)?; let mut r...
use ndarray::Array2; use regex::Regex; use std::collections::HashSet; use std::fs; use std::fs::File; use std::io::{self, BufRead, Error}; use std::path::Path; #[allow(dead_code)] fn read_lines<P>(filename: P) -> Result<Vec<String>, Error> where P: AsRef<Path>, { let file = File::open(filename)?; let mut r...
newgrid[[j, i]] = 0; } } } (newgrid, score) } fn part1(lines: &Vec<String>) { let mut grid = create_grid(lines); let width = lines[0].len(); let height = lines.len(); let iterations = 100; let mut result = 0; for _ in 0..iterations { le...
result.push(l) } } Ok(result) } #[allow(dead_code)] fn read_chunks<P>(filename: P) -> Result<Vec<String>, Error> where P: AsRef<Path>, { let text = fs::read_to_string(filename)?; let chunks: Vec<String> = Regex::new(r"\r\n\r\n") .unwrap() .split(&text) .map(...
random
[ { "content": "// The output is wrapped in a Result to allow matching on errors\n\n// Returns an Iterator to the Reader of the lines of the file.\n\nfn read_lines<P>(filename: P) -> Result<Vec<String>, Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let file = File::open(filename)?;\n\n let mut result: Vec...
Rust
src/compiler/print.rs
basusamit/lucid_tools
0da665ad78b576c4612917b0d57482bcb5f2775c
use super::ast::*; use super::ast::Expression::*; use super::token::*; use std::fmt::Write; pub struct PrintContext { input: String, } impl PrintContext { pub fn from(text: &str) -> PrintContext { PrintContext { input: String::from(text), } } fn token(& self, token: &Tok...
use super::ast::*; use super::ast::Expression::*; use super::token::*; use std::fmt::Write; pub struct PrintContext { input: String, } impl PrintContext { pub fn from(text: &str) -> PrintContext { PrintContext { input: String::from(text), } } fn token(& self, token: &Tok...
} fn body(&self, block: &[Statement]) -> String { block.iter() .map(|x| self.statement(x)) .collect::<Vec<String>>() .join("\n") } fn module(&self, module: &ModuleBlock) -> String { let mut ret = String::new(); let _ = write!(ret, "module {}...
match s { Statement::ConstantDeclaration(c) => self.constant_declaration(c), Statement::VariableDeclaration(v) => self.variable_declaration(v), Statement::SignalDeclaration(s) => self.signal_declaration(s), Statement::FSMDeclaration(f) => self.fsm_declaration(f), ...
if_condition
[]
Rust
src/main.rs
ttomasic101/broker-server
51131f64890053a9ad15d4ab28c399c50139b4b1
#[allow(unused_imports)] use std::{ ascii, io, net::SocketAddr, path::{self, Path, PathBuf}, str, sync::Arc, }; extern crate anyhow; use anyhow::{anyhow, Result}; use futures::{StreamExt, TryFutureExt}; use structopt::{self, StructOpt}; use tracing::{error, info, info_span}; use tracing_futures::In...
#[allow(unused_imports)] use std::{ ascii, io, net::SocketAddr, path::{self, Path, PathBuf}, str, sync::Arc, }; extern crate anyhow; use anyhow::{anyhow, Result}; use futures::{StreamExt, TryFutureExt}; use structopt::{self, StructOpt}; use tracing::{error, info, info_span}; use tracing_futures::In...
}; std::process::exit(code); } async fn run(options: Opt) -> Result<()> { let mut transport_config = quinn::TransportConfig::default(); transport_config.stream_window_uni(0); let mut server_config = quinn::ServerConfig::default(); server_config.transport = Arc::new(transport_config); let...
if let Err(e) = rt.block_on(run(opt)) { eprintln!("ERROR: {}", e); 1 } else { 0 }
if_condition
[ { "content": "use std::{\n\n path::PathBuf,\n\n io,\n\n};\n\n\n\nuse tokio::fs;\n\n\n\nextern crate anyhow;\n\nuse anyhow::{bail, Context, Result};\n\nuse tracing::info;\n\n\n\npub async fn init_security(key: &Option<PathBuf>, cert: &Option<PathBuf>) -> Result<(quinn::PrivateKey, quinn::CertificateChain)>...
Rust
backend/src/topics/services.rs
zzy/blog-rs
14c33fd2d02d87cc4502595d41370279c115dd13
use futures::stream::StreamExt; use mongodb::{ Database, options::FindOptions, bson::{ oid::ObjectId, DateTime, Document, doc, to_document, from_document, }, }; use crate::util::{constant::GqlResult, common::slugify}; use crate::users; use super::models::{Topic, TopicNew, TopicArticle, TopicAr...
use futures::stream::StreamExt; use mongodb::{ Database, options::FindOptions, bson::{ oid::ObjectId, DateTime, Document, doc, to_document, from_document, }, }; use crate::util::{constant::GqlResult, common::slugify}; use crate::users; use super::models::{Topic, TopicNew, TopicArticle, TopicAr...
} } topics_articles }
let user = users::services::user_by_username(db.clone(), username).await?; self::topics_by_user_id(db, user._id).await } pub async fn topics_by_category_id( db: Database, category_id: ObjectId, published: i32, ) -> GqlResult<Vec<Topic>> { let articles = crate::articles::services::articles_by_cat...
random
[ { "content": "/// Pretty-print error.\n\nfn print_error(input: &str, mut err: EvalAltResult) {\n\n let lines: Vec<_> = input.trim().split('\\n').collect();\n\n let pos = err.take_position();\n\n\n\n let line_no = if lines.len() > 1 {\n\n if pos.is_none() {\n\n \"\".to_string()\n\n ...
Rust
src/efuse/rd_repeat_data0.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
#[doc = "Reader of register RD_REPEAT_DATA0"] pub type R = crate::R<u32, super::RD_REPEAT_DATA0>; #[doc = "Reader of field `POWER_GLITCH_DSENSE`"] pub type POWER_GLITCH_DSENSE_R = crate::R<u8, u8>; #[doc = "Reader of field `POWERGLITCH_EN`"] pub type POWERGLITCH_EN_R = crate::R<bool, bool>; #[doc = "Reader of field `BT...
#[doc = "Reader of register RD_REPEAT_DATA0"] pub type R = crate::R<u32, super::RD_REPEAT_DATA0>; #[doc = "Reader of field `POWER_GLITCH_DSENSE`"] pub type POWER_GLITCH_DSENSE_R = crate::R<u8, u8>; #[doc = "Reader of field `POWERGLITCH_EN`"] pub type POWERGLITCH_EN_R = crate::R<
ays)] pub fn btlc_gpio_enable(&self) -> BTLC_GPIO_ENABLE_R { BTLC_GPIO_ENABLE_R::new(((self.bits >> 27) & 0x03) as u8) } #[doc = "Bit 26"] #[inline(always)] pub fn vdd_spi_as_gpio(&self) -> VDD_SPI_AS_GPIO_R { VDD_SPI_AS_GPIO_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = ...
bool, bool>; #[doc = "Reader of field `BTLC_GPIO_ENABLE`"] pub type BTLC_GPIO_ENABLE_R = crate::R<u8, u8>; #[doc = "Reader of field `VDD_SPI_AS_GPIO`"] pub type VDD_SPI_AS_GPIO_R = crate::R<bool, bool>; #[doc = "Reader of field `USB_EXCHG_PINS`"] pub type USB_EXCHG_PINS_R = crate::R<bool, bool>; #[doc = "Reader of fiel...
random
[ { "content": "#[doc = \"This trait shows that register has `read` method\"]\n\n#[doc = \"\"]\n\n#[doc = \"Registers marked with `Writable` can be also `modify`'ed\"]\n\npub trait Readable {}\n", "file_path": "src/generic.rs", "rank": 0, "score": 53756.44927678981 }, { "content": "#[doc = \"T...
Rust
src/spawner.rs
Frans-Lukas/spellThief
f31953bee150d1b1b225cc861766abe5631cdb02
use std::collections::HashMap; use rltk::{RandomNumberGenerator, RGB}; use specs::prelude::*; use super::spells::fireball; use super::{ random_table::RandomTable, AreaOfEffect, BlocksTile, CombatStats, Confusion, Consumable, DestroysWalls, InflictsDamage, Item, KnownSpells, MagicStats, Monster, Name, Player, ...
use std::collections::HashMap; use rltk::{RandomNumberGenerator, RGB}; use specs::prelude::*; use super::spells::fireball; use super::{ random_table::RandomTable, AreaOfEffect, BlocksTile, CombatStats, Confusion, Consumable, DestroysWalls, InflictsDamage, Item, KnownSpells, MagicStats, Monster, Name, Player, ...
fn magic_missile_scroll(ecs: &mut World, x: i32, y: i32) { ecs.create_entity() .with(Position { x, y }) .with(Renderable { glyph: rltk::to_cp437(')'), fg: RGB::named(rltk::CYAN), bg: RGB::named(rltk::BLACK), render_order: 2, }) .with(...
fn fireball_scroll(ecs: &mut World, x: i32, y: i32) { ecs.create_entity() .with(Position { x, y }) .with(Renderable { glyph: rltk::to_cp437(')'), fg: RGB::named(rltk::ORANGE), bg: RGB::named(rltk::BLACK), render_order: 2, }) .with(Name ...
function_block-full_function
[ { "content": "fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World, world_size: Position) {\n\n let mut positions = ecs.write_storage::<Position>();\n\n let mut players = ecs.write_storage::<Player>();\n\n let mut viewsheds = ecs.write_storage::<Viewshed>();\n\n\n\n let combat_stats = ecs....
Rust
contracts/gateway/swap/src/testing/test_querier_strategy.rs
kyscott18/interest_split
e24541f6ecfb228ab1397a1f058bb45149c413a9
use crate::querier::strategy; use crate::state::{config, user}; use crate::testing::constants::TEST_USER_1; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_bignumber::{Decimal256, Uint256}; use cosmwasm_std::Api; use pylon_gateway::swap_msg::Strategy; use std::str::FromStr; #[test] fn strategy_claima...
use crate::querier::strategy; use crate::state::{config, user}; use crate::testing::constants::TEST_USER_1; use crate::testing::mock_querier::mock_dependencies; use cosmwasm_bignumber::{Decimal256, Uint256}; use cosmwasm_std::Api; use pylon_gateway::swap_msg::Strategy; use std::str::FromStr; #[test] fn strategy_claima...
#[test] fn strategy_claimable_token_of_valkyrie() { let mut deps = mock_dependencies(&[]); config::store(deps.as_mut().storage) .save(&config::Config { owner: "".to_string(), beneficiary: "".to_string(), price: Default::default(), start: 0, ...
p(), Uint256::from(0u64), ); assert_eq!( strategy::claimable_token_of(deps.as_ref(), 1, TEST_USER_1.to_string()).unwrap(), Uint256::from(2500u64), ); assert_eq!( strategy::claimable_token_of(deps.as_ref(), 2, TEST_USER_1.to_string()).unwrap(), Uint256::from(7500u6...
function_block-function_prefixed
[ { "content": "pub fn store(storage: &mut dyn Storage, owner: &CanonicalAddr, user: &User) -> StdResult<()> {\n\n let mut user_bucket: Bucket<User> = bucket(storage, PREFIX_USER);\n\n user_bucket.save(owner.as_slice(), user)\n\n}\n\n\n", "file_path": "contracts/gateway/swap/src/state/user.rs", "ran...
Rust
src/tty.rs
jac3km4/toffee
bd84f1f62eaa634dd62cc9e5aae2e2b33ab6f37b
use std::iter; use sdl2::event::Event; use sdl2::keyboard::Keycode; use crate::colors::Color; use crate::event::Events; use crate::renderer::Renderer; use crate::terminal::{Cell, Terminal}; pub trait TtyHandler { fn process(&mut self, input: String, tty: &mut TtyController); } pub struct TtyRepl<H: TtyHandler> ...
use std::iter; use sdl2::event::Event; use sdl2::keyboard::Keycode; use crate::colors::Color; use crate::event::Events; use crate::renderer::Renderer; use crate::terminal::{Cell, Terminal}; pub trait TtyHandler { fn process(&mut self, input: String, tty: &mut TtyController); } pub struct TtyRepl<H: TtyHandler> ...
fn newline(&mut self) -> String { self.reset_cursor(); let line = self.line.drain(..).collect(); self.line.resize(self.terminal.columns as usize, ' '); self.advance_row(1); self.col = 0; self.save_cursor_cell(); self.place_cursor(); line } f...
pub fn fetch_history(&mut self) -> Option<String> { let str = self.history.get(self.history_cursor)?.to_owned(); self.col = 0; for char in str.chars() { self.char(char, 1); } self.col = str.trim_end().chars().count(); self.place_cursor(); Some(str) ...
function_block-full_function
[]
Rust
src/solver/genetic/decomposition.rs
martsime/hybridcvrp
4df38aa12814d8a0eaceafad56f9be4b8f954033
use std::collections::HashSet; use ahash::RandomState; use crate::{ solver::{ genetic::{GeneticAlgorithm, Individual}, improvement::{Acceptance, IterationSchedule}, Context, Metaheuristic, }, utils::FloatCompare, }; #[derive(PartialEq)] enum State { NotInitialized, Cycle, ...
use std::collections::HashSet; use ahash::RandomState; use crate::{ solver::{ genetic::{GeneticAlgorithm, Individual}, improvement::{Acceptance, IterationSchedule}, Context, Metaheuristic, }, utils::FloatCompare, }; #[derive(PartialEq)] enum State { NotInitialized, Cycle, ...
e_global(global: &mut Individual, ctx: &Context) -> (Individual, Vec<usize>) { let mut route_for_customer = vec![0; ctx.problem.dim()]; for (route_number, route) in global.phenotype.iter().enumerate() { for &customer in route.iter() { route_for_customer[customer] = route_numb...
tialized, global_solution: Individual::new_random(ctx, 0), global_ga: GeneticAlgorithm::new(ctx), } } fn create_global_solution(&mut self, ctx: &Context) -> Individual { log::info!("Creating global solution"); let max_routes = ctx.config.borrow().num_vehicles; ...
random
[ { "content": "pub fn write_solution_file(ctx: &Context) {\n\n if let Some(solution_path) = ctx.config.borrow().solution_path.as_ref() {\n\n let mut file = OpenOptions::new()\n\n .write(true)\n\n .create(true)\n\n .truncate(true)\n\n .open(solution_path)\n\n ...
Rust
src/NR/Res.rs
nyanrus/AULTranslate-rs
3c12e706c46304c570ebe3709212e7552458b22c
use core::mem::size_of; use windows::Win32::System::SystemServices::{IMAGE_RESOURCE_DIRECTORY, IMAGE_RESOURCE_DATA_ENTRY, IMAGE_RESOURCE_DIRECTORY_ENTRY_0, IMAGE_RESOURCE_DIRECTORY_ENTRY_1}; use windows::Win32::System::SystemServices::{ IMAGE_RESOURCE_DIRECTORY_ENTRY, IMAGE_RESOURCE_DIR_STRING_U, }; use super::*; ...
use core::mem::size_of; use windows::Win32::System::SystemServices::{IMAGE_RESOURCE_DIRECTORY, IMAGE_RESOURCE_DATA_ENTRY, IMAGE_RESOURCE_DIRECTORY_ENTRY_0, IMAGE_RESOURCE_DIRECTORY_ENTRY_1}; use windows::Win32::System::SystemServices::{ IMAGE_RESOURCE_DIRECTORY_ENTRY, IMAGE_RESOURCE_DIR_STRING_U, }; use super::*; ...
OfIdEntries: IdEntries }; } pub unsafe fn MakeImgResDirEnt(refRes : &Base::Resource) -> Vec<IMAGE_RESOURCE_DIRECTORY_ENTRY> { let mut i = 0usize; let mut ImgResDirEntVec = Vec::<IMAGE_RESOURCE_DIRECTORY_ENTRY>::new(); while i < refRes.Nextptr.len() { if refRes.Nextptr[i].IsData { ...
DirDat = (*pImgResDirEnt).Anonymous2.Anonymous._bitfield & 0x7fffffff; return stAnalyzImgResDirEnt { IsName, NameId, IsDir, DirDat }; } pub struct stAnalyzImgResDirEnt { pub IsName : bool, pub NameId : u32, pub IsDir : bool, pub DirDat : u32, } pub unsafe fn NameId ( refstAnalyzImgResDirEnt ...
random
[]
Rust
plugins/crossover/src/crossover/iir.rs
robbert-vdh/nih-plug
3e1f4ce364463ca4503027c096b7cbc5e077cc74
use nih_plug::buffer::ChannelSamples; use nih_plug::debug::*; use std::simd::f32x2; use self::biquad::{Biquad, BiquadCoefficients, NEUTRAL_Q}; use crate::NUM_BANDS; pub mod biquad; #[derive(Debug)] pub struct IirCrossover { mode: IirCrossoverType, crossovers: [Crossover; NUM_BANDS - 1], ...
use nih_plug::buffer::ChannelSamples; use nih_plug::debug::*; use std::simd::f32x2; use self::biquad::{Biquad, BiquadCoefficients, NEUTRAL_Q}; use crate::NUM_BANDS; pub mod biquad; #[derive(Debug)] pub struct IirCrossover { mode: IirCrossoverType, crossovers: [Crossover; NUM_BANDS - 1], ...
ients::highpass(sample_rate, frequency, NEUTRAL_Q); crossover.update_coefficients(lp_coefs, hp_coefs); } } } self.all_passes .update_coefficients(sample_rate, num_bands, &frequencies); } pub fn reset(&mut self) { for cros...
quencies) .take(num_bands - 1) { let lp_coefs = BiquadCoefficients::lowpass(sample_rate, frequency, NEUTRAL_Q); let hp_coefs = BiquadCoeffic
random
[ { "content": "/// The same as [`hann()`], but filling an existing slice instead.\n\npub fn hann_in_place(window: &mut [f32]) {\n\n let size = window.len();\n\n\n\n // We want to scale `[0, size - 1]` to `[0, pi]`.\n\n // XXX: The `sin^2()` version results in weird rounding errors that cause spectral le...
Rust
src/common/genesis_tx.rs
elniallo/tokio-experiment
547e0ec0029605bfa12910ce200ab0c356555d97
use crate::common::address::Address; use crate::serialization::tx::GenesisTx as ProtoGenesisTx; use crate::traits::{Decode, Encode, Proto, Transaction}; use std::error::Error; use protobuf::Message as ProtoMessage; use secp256k1::{RecoverableSignature, RecoveryId}; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Ge...
use crate::common::address::Address; use crate::serialization::tx::GenesisTx as ProtoGenesisTx; use crate::traits::{Decode, Encode, Proto, Transaction}; use std::error::Error; use protobuf::Message as ProtoMessage; use secp256k1::{RecoverableSignature, RecoveryId}; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Ge...
_bad_bytes() { let seed = [0x77u8; 32]; let mut rng: StdRng = SeedableRng::from_seed(seed); let mut random_bytes = [0u8; 256]; rng.fill(&mut random_bytes); GenesisTx::decode(&random_bytes.to_vec()).unwrap(); } }
= Self::ProtoType::new(); proto_genesis_tx.set_to(self.to.to_vec()); proto_genesis_tx.set_amount(self.amount); Ok(proto_genesis_tx) } fn from_proto(_prototype: &Self::ProtoType) -> Result<Self, Box<Error>> { unimplemented!() } } impl Encode for GenesisTx { fn encode(&se...
random
[ { "content": "pub fn create_random_address<RngType>(rng: &mut RngType) -> Address\n\nwhere\n\n RngType: Rng,\n\n{\n\n let wallet = create_random_wallet(rng);\n\n Address::from_pubkey(wallet.public_key)\n\n}\n\n\n\n// pub fn create_random_block<RngType>(\n\n// previous_block: Vec<u8>,\n\n// num_...
Rust
lib/src/drop/source/git.rs
oceanpkg/ocean
9efa9290a6f21652af3e8d21fdf1fd76a364d4c5
use serde::{Serialize, Serializer}; use std::fmt; pub const OCEAN_REPO: &str = env!("CARGO_PKG_REPOSITORY"); flexible! { #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub struct Git { #[serde(alias = "repository")] pub repo: String, #[serde(flatten)] ...
use serde::{Serialize, Serializer}; use std::fmt; pub const OCEAN_REPO: &str = env!("CARGO_PKG_REPOSITORY"); flexible! { #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub struct Git { #[serde(alias = "repository")] pub repo: String, #[serde(flatten)] ...
}
match self { Self::Branch(_) => "branch", Self::Tag(_) => "tag", Self::Rev(_) => "rev", } }
function_block-function_prefixed
[ { "content": "/// Returns the UTF-8 encoded value for [`URL_ENV_VAR`] or [`DEFAULT_URL`] if it\n\n/// does not exist.\n\n///\n\n/// [`URL_ENV_VAR`]: constant.URL_ENV_VAR.html\n\n/// [`DEFAULT_URL`]: constant.DEFAULT_URL.html\n\npub fn url_str() -> Result<Cow<'static, str>, OsString> {\n\n match env::var(URL_...
Rust
lib/rust/ast/src/ast.rs
Termina1/enso
8b023e2549faa927794dcd8a419e23d4e331fc50
use app::*; use lines::*; use def::*; use name::*; use invalid::*; use num::*; use txt::*; use uuid::Uuid; pub type AnyAst = Ast<Shape>; #[derive(Debug,Clone)] pub struct Ast<T> { uid : Option<Uuid>, len : usize, off : usize, ast : T, } #[allow(missing_docs)] #[derive(Debug,Clo...
use app::*; use lines::*; use def::*; use name::*; use invalid::*; use num::*; use txt::*; use uuid::Uuid; pub type AnyAst = Ast<Shape>; #[derive(Debug,Clone)] pub struct Ast<T> { uid : Option<Uuid>, len : usize, off : usize, ast : T, } #[al
-> Self { Self {ast:ast.into(), uid: Some(Uuid::new_v4()), len:0, off:0 } } pub fn unrecognized(str:String) -> Self { Self::new(Unrecognized{str}) } pub fn blank() -> Self { Self::new(Blank{}) } pub fn var(name:String) -> Self { Self::new(Var{na...
low(missing_docs)] #[derive(Debug,Clone)] pub enum Shape { Unrecognized(invalid::Unrecognized), Blank(name::Blank), Var(name::Var), Cons(name::Cons), Opr(name::Opr), Number(num::Number), Text(txt::Text), Prefix(app::Prefix), Infix(app::Infix), Module(lines::Module), Block(lin...
random
[ { "content": " def app(ast: AST): Unit =\n\n logger.trace {\n\n current = Some(current match {\n\n case None => ast\n\n case Some(r) => AST.App.Prefix(r, off.use(), ast)\n\n })\n\n }\n\n\n", "file_path": "lib/scala/syntax/definition/src/main/scala/org/enso/syn...
Rust
src/commands/node.rs
numToStr/volt
e57179f8732896d87b15786e0c60c25f18818535
/* * Copyright 2021 Volt Contributors * * 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 appl...
/* * Copyright 2021 Volt Contributors * * 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 appl...
} todo!("Need to handle ranges"); } else { println!("Unable to download {} -- not a valid version!", v); continue; } let node_path = { let datadir = dirs::data_dir().unwrap().join("volt").join("node"); ...
if major.parse::<u8>().unwrap() >= 10 { println!("32 bit versions are not available for macos and linux after version 10.0.0!"); return Ok(()); }
if_condition
[ { "content": "/// Gets a config key from git using the git cli.\n\n/// Uses `gitoxide` to read from your git configuration.\n\npub fn get_git_config(config: &VoltConfig, key: &str) -> Result<Option<String>> {\n\n fn get_git_config_value_if_exists(\n\n config: &VoltConfig,\n\n section: &str,\n\n...
Rust
src/parsers/signature.rs
andrewhalle/pgp-rs
8372fde173f2c24a18550139c5a7fbee5be7d229
use super::utils::fold_into_string; use nom::branch::alt; use nom::bytes::complete::tag; use nom::combinator::all_consuming; use nom::combinator::{map, not, peek}; use nom::multi::many1; use nom::sequence::tuple; use nom::IResult; use super::pgp_utils::{ parse_ascii_armor_parts, parse_hash_armor_header, parse_leng...
use super::utils::fold_into_string; use nom::branch::alt; use nom::bytes::complete::tag; use nom::combinator::all_consuming; use nom::combinator::{map, not, peek}; use nom::multi::many1; use nom::sequence::tuple; use nom::IResult; use super::pgp_utils::{ parse_ascii_armor_parts, parse_hash_armor_header, parse_leng...
#[test] fn test_parse_dash_escaped_line() { let input = "- aa\nbb"; let expected = "bb"; assert_eq!(parse_dash_escaped_line(&input), Ok((expected, "aa\n"))); let input = "aa\nbb"; assert_eq!( parse_dash_escaped_line(&input), Err(nom::Err::Error(...
fn test_parse_possibly_dash_escaped_line() { let input = "- aa\nbb"; let expected = "bb"; assert_eq!( parse_possibly_dash_escaped_line(&input), Ok((expected, "aa\n")) ); let input = "aa\nbb"; let expected = "bb"; assert_eq!( pa...
function_block-full_function
[ { "content": "/// Parse a chunk of base64 encoded text.\n\npub fn parse_base64(input: &str) -> IResult<&str, String> {\n\n let (input, mut base64) = fold_into_string(input, parse_base64_line)?;\n\n\n\n if input.chars().next() == Some('=') {\n\n return Ok((input, base64));\n\n }\n\n\n\n let (i...
Rust
src/derive/core/iter.rs
taiki-e/auto_enumerate
7257ab16b2e47f3f7efbeb481626c1965169f7d6
pub(crate) mod iterator { use crate::derive::*; pub(crate) const NAME: &[&str] = &["Iterator"]; pub(crate) fn derive(data: &Data) -> Result<TokenStream> { let try_trait = quote! { #[inline] fn fold<__U, __F>(self, init: __U, f: __F) -> __U whe...
pub(crate) mod iterator { use crate::derive::*; pub(crate) const NAME: &[&str] = &["Iterator"]; pub(crate) fn derive(data: &Data) -> Result<TokenStream> {
Ok(derive_trait(data, parse_quote!(::core::iter::Iterator), None, parse_quote! { trait Iterator { type Item; #[inline] fn next(&mut self) -> ::core::option::Option<Self::Item>; #[inline] fn size_hint(&self) -> (usize, ...
let try_trait = quote! { #[inline] fn fold<__U, __F>(self, init: __U, f: __F) -> __U where __F: ::core::ops::FnMut(__U, Self::Item) -> __U; #[inline] fn find<__P>(&mut self, predicate: __P) -> ::core::option::Option<Self::Item> wher...
assignment_statement
[ { "content": "fn check_fields(data: &Data) -> Result<()> {\n\n let generics = &data.generics;\n\n let fields = data.field_types();\n\n let comma = if generics.params.empty_or_trailing() { quote!(,) } else { TokenStream::new() };\n\n\n\n if quote!(#generics).to_string() == quote!(<#(#fields),*#comma>...
Rust
src/main.rs
aloiscochard/velox
3ef95af5342d249b9db9946e757a36f81d5b39ee
extern crate colored; extern crate libc; use colored::*; use libc::{kill, SIGTERM}; use pathdiff::diff_paths; use std::fs::canonicalize; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::Ar...
extern crate colored; extern crate libc; use colored::*; use libc::{kill, SIGTERM}; use pathdiff::diff_paths; use std::fs::canonicalize; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::Ar...
d) { match rx.recv_timeout(timeout) { Ok(event) => { let path = event.path.unwrap(); let mut included: bool = true; for gi in &gitignores { included = !gi .is_excluded(&path) ...
function_block-function_prefixed
[ { "content": "velox\n\n=====\n\n\n\nA continuous development automaton.\n\n\n\n# Install\n\n\n\n## Source\n\n\n\n git clone https://github.com/aloiscochard/velox.git\n\n cd velox\n\n cargo install\n\n\n\n# Usage\n\n\n\nDo `vlx something`, in a directory where you have a `.gitignore` and every time you...
Rust
streamson-lib/src/strategy/trigger.rs
shenek/streamson
cf07074f43b68ce3415a91313c588009fd2f3292
use crate::{ error, handler::Handler, matcher::Matcher, streamer::{Streamer, Token}, }; use std::{ collections::HashSet, sync::{Arc, Mutex}, }; use super::{Output, Strategy}; #[derive(Debug)] struct StackItem { idx: usize, match_idx: usize, } type MatcherItem = (Box<dyn Ma...
use crate::{ error, handler::Handler, matcher::Matcher, streamer::{Streamer, Token}, }; use std::{ collections::HashSet, sync::{Arc, Mutex}, }; use super::{Output, Strategy}; #[derive(Debug)] struct StackItem { idx: usize, match_idx: usize, } type MatcherItem = (Box<dyn Ma...
fn terminate(&mut self) -> Result<Vec<Output>, error::General> { if self.level == 0 { let mut res = vec![]; for (_, handler) in &self.matchers { let output = handler.lock().unwrap().input_finished()?; if let Some(data) = output { ...
fn process(&mut self, input: &[u8]) -> Result<Vec<Output>, error::General> { self.streamer.feed(input); let mut inner_idx = 0; loop { match self.streamer.read()? { Token::Start(idx, kind) => { self.level += 1; ...
function_block-full_function
[ { "content": "/// Item in matcher list\n\ntype MatcherItem = (Box<dyn Matcher>, Arc<Mutex<dyn Handler>>);\n\n\n\n/// Processes data from input and triggers handler\n\npub struct Convert {\n\n /// Input idx against total idx\n\n input_start: usize,\n\n /// Currently matched path and matcher index\n\n ...
Rust
server/src/server.rs
Louis-Tarvin/draw_game
314144b3a9edeb6acdcf12261ccb230f801285c0
use actix::prelude::*; use rand::{distributions::Alphanumeric, prelude::*, rngs::ThreadRng}; use std::collections::HashMap; use std::sync::Arc; use crate::word_pack::{load_word_packs, WordPack}; use crate::Room; use log::{info, trace, warn}; #[derive(Message, Clone)] #[rtype(result = "()")] pub enum Event { ...
use actix::prelude::*; use rand::{distributions::Alphanumeric, prelude::*, rngs::ThreadRng}; use std::collections::HashMap; use std::sync::Arc; use crate::word_pack::{load_word_packs, WordPack}; use crate::Room; use log::{info, trace, warn}; #[derive(Message, Clone)] #[rtype(result = "()")] pub enum Event { ...
r non-existant room {}", session_id, key ); } } pub fn round_timeout(&mut self, key: &str, round_id: usize, ctx: &mut Context<GameServer>) { if let Some(room) = self.rooms.get_mut(key) { room.round_timeout(round_id, ctx); } else { trac...
size) { if let Some(room) = self.rooms.get_mut(key) { room.clear(session_id); } else { warn!( "User {} tried to clea
function_block-random_span
[ { "content": "pub fn load_word_packs<P: std::fmt::Debug + AsRef<std::path::Path>>(\n\n word_pack_path: P,\n\n) -> std::io::Result<Vec<WordPack>> {\n\n use std::fs;\n\n let mut tracker = std::collections::HashSet::new();\n\n trace!(\"loading wordpacks in directory `{:?}`\", word_pack_path);\n\n le...
Rust
quic/s2n-quic-core/src/crypto/key.rs
czakian/s2n-quic
c3ab570d42377e4a10084c965628d71219b1c492
use crate::crypto::CryptoError; pub trait Key: Send { fn decrypt( &self, packet_number: u64, header: &[u8], payload: &mut [u8], ) -> Result<(), CryptoError>; fn encrypt( &self, packet_number: u64, header: &[u8], payload: &mut [u8]...
use crate::crypto::CryptoError; pub trait Key: Send { fn decrypt( &self, packet_number: u64, header: &[u8], payload: &mut [u8], ) -> Result<(), CryptoError>; fn encrypt( &self, packet_number: u64, header: &[u8], payload: &mut [u8]...
fn encrypt( &self, _packet_number: u64, _header: &[u8], _payload: &mut [u8], ) -> Result<(), CryptoError> { Ok(()) } fn tag_len(&self) -> usize { 0 } fn aead_confidentiality_limi...
f, _packet_number: u64, _header: &[u8], _payload: &mut [u8], ) -> Result<(), CryptoError> { if self.fail_on_decrypt { return Err(CryptoError::DECRYPT_ERROR); } Ok(()) }
function_block-function_prefixed
[ { "content": "/// Types for which are able to perform header cryptography.\n\npub trait HeaderKey: Send {\n\n /// Derives a header protection mask from a sample buffer, to be\n\n /// used for opening a packet.\n\n ///\n\n /// The sample size is determined by the key function.\n\n fn opening_heade...
Rust
rust/src/lib.rs
msimms/LibMath
21bfb3937fb88a0791abe233be23af53452e601d
#[allow(dead_code)] pub mod distance; pub mod graphics; pub mod kmeans; pub mod peaks; pub mod powers; pub mod signals; pub mod square_matrix; pub mod statistics; pub mod vector; #[cfg(test)] mod tests { use std::fs::File; extern crate csv; struct AccelerometerData { ts: Vec<f64>, x: V...
#[allow(dead_code)] pub mod distance; pub mod graphics; pub mod kmeans; pub mod peaks; pub mod powers; pub mod signals; pub mod square_matrix; pub mod statistics; pub mod vector; #[cfg(test)] mod tests { use std::fs::File; extern crate csv; struct AccelerometerData { ts: Vec<f64>, x: V...
#[test] fn perform_signal_tests() { println!("\nSignals Tests:"); println!("--------------"); let data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]; println!("{:?}", data); println!("{:?}", crate::signals::smooth(&data, 1)); println!("{:?}", crate::signal...
fn perform_graphics_tests() { println!("\nGraphics Tests:"); println!("----------------"); let poly_csv_file_name = "../data/florida.csv"; let poly_data = read_polygon_csv(poly_csv_file_name); let mut orlando = crate::graphics::Point::new(); orlando.x = -81.38; ...
function_block-full_function
[ { "content": "// Implements the ray casting/crossing number algorithm. Returns TRUE if the point is within the bounds of the points that specify the polygon (poly is a list of points).\n\npub fn is_point_in_poly_array(test_x: f64, test_y: f64, poly: &Vec<Point>) -> bool {\n\n\n\n\t// Sanity checks.\n\n\tlet mut...
Rust
benches/darts_benchmark.rs
MnO2/rust-darts
b1a6813f52beb8f062fadfed8a2009b9fa9f6ae2
#[macro_use] extern crate criterion; extern crate darts; extern crate hashbrown; extern crate lazy_static; use darts::searcher; use criterion::Criterion; use darts::DoubleArrayTrie; use hashbrown::HashMap; use lazy_static::lazy_static; use std::fs::{read_to_string, File}; use std::io::{BufRead, BufReader}; lazy_stat...
#[macro_use] extern crate criterion; extern crate darts; extern crate hashbrown; extern crate lazy_static; use darts::searcher; use criterion::Criterion; use darts::DoubleArrayTrie; use hashbrown::HashMap; use lazy_static::lazy_static; use std::fs::{read_to_string, File}; use std::io::{BufRead, BufReader}; lazy_stat...
fn bench_dat_match_found() { DA.exact_match_search( "我是拖拉机学院手扶拖拉机专业的。不用多久,我就会升职加薪,当上CEO,走上人生巅峰。", ); } fn bench_hashbrown_match_found() { HASHMAP.contains_key( "我是拖拉机学院手扶拖拉机专业的。不用多久,我就会升职加薪,当上CEO,走上人生巅峰。", ); } fn bench_dat_match_not_found_slow_fail() { DA.exact_match_search("东湖高...
yte_start..] }; while i < word_count { if HASHMAP.contains_key(wfrag) { } i += 1; } } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n let f = File::open(\"./dict.txt\").unwrap();\n\n let mut buf = BufReader::new(f);\n\n let _ = IndexBuilder::new().build(&mut buf).unwrap();\n\n}\n", "file_path": "examples/build-dict/src/main.rs", "rank": 7, "score": 38818.18951450781 }, { "content": " ...
Rust
src/string_ptr.rs
adrien-zinger/wasmer-as
ff4f5c81f139b1c91532adc4a092b31af29bda22
use super::{Env, Memory, Read, Write}; use std::convert::{TryFrom, TryInto}; use wasmer::{Array, Value, WasmPtr}; pub type StringPtr = WasmPtr<u16, Array>; macro_rules! export_asr { ($func_name:ident, $env:expr) => { $env.$func_name .as_ref() .expect("Assembly Script Runtime not ex...
use super::{Env, Memory, Read, Write}; use std::convert::{TryFrom, TryInto}; use wasmer::{Array, Value, WasmPtr}; pub type StringPtr = WasmPtr<u16, Array>; macro_rules! export_asr { ($func_name:ident, $env:expr) => { $env.$func_name .as_ref() .expect("Assembly Script Runtime not ex...
if let Some(cell) = memory.view::<u32>().get(offset as usize / (32 / 8) - 1) { Ok(cell.get()) } else { anyhow::bail!("Wrong offset: can't read size") } }
_asr!(fn_pin, env); unpin .call(&[Value::I32(self.offset().try_into().unwrap())]) .expect("Failed to call __unpin"); let collect = export_asr!(fn_collect, env); collect.call(&[]).expect("failed to call __collect"); ...
random
[ { "content": "// if get_string throws an exception abort for some reason is being called\n\npub fn abort(env: &Env, message: StringPtr, filename: StringPtr, line: i32, col: i32) {\n\n let memory = env.memory.get_ref().expect(\"initialized memory\");\n\n let message = message.read(memory).unwrap();\n\n ...
Rust
gullery/examples/texture_cubemap.rs
Osspial/gl_raii
b747cbe5f72590d7ba42b656db14dfab0cf7f3c9
extern crate gullery; #[macro_use] extern crate gullery_macros; extern crate cgmath; extern crate glutin; extern crate png; mod helper; use gullery::{ buffer::*, framebuffer::{render_state::*, *}, geometry::D2, geometry::{GLMat4r4c, GLSLFloat, GLVec2, GLVec3}, image_format::{compressed::DXT1, Imag...
extern crate gullery; #[macro_use] extern crate gullery_macros; extern crate cgmath; extern crate glutin; extern crate png; mod helper; use gullery::{ buffer::*, framebuffer::{render_state::*, *}, geometry::D2, geometry::{GLMat4r4c, GLSLFloat, GLVec2, GLVec3}, image_format::{compressed::DXT1, Imag...
} WindowEvent::MouseInput { state: ElementState::Pressed, .. } => { window.grab_cursor(true).ok(); window.hide_cursor(true); window_focused = true; } Win...
.with_srgb(true), &events_loop, ) .unwrap(); unsafe { window.context().make_current().unwrap() }; let state = unsafe { ContextState::new(|addr| window.context().get_proc_address(addr)) }; let vertex_buffer = Buffer::with_data( BufferUsage::StaticDraw, &[ ...
random
[ { "content": "#[derive(Vertex, Clone, Copy)]\n\nstruct Vertex {\n\n pos: GLVec2<f32>,\n\n tex_coord: GLVec2<u16, Normalized>,\n\n}\n\n\n", "file_path": "gullery/examples/texture.rs", "rank": 0, "score": 164257.7143750169 }, { "content": "fn main() {\n\n let mut events_loop = EventsL...
Rust
src/iterative_repair.rs
tmetsch/rusty_planner
4cf19c79642b7943548c9976526bfcd578eacdfa
use std::collections; use crate::util; pub trait Problem { type Conflict; type Iter: Iterator<Item = (Self::Conflict, f64)>; fn find_conflicts(&self) -> Self::Iter; fn fix_conflict(&mut self, _: &Self::Conflict); } pub fn solve<PS: Problem>(ps: &mut PS, steps: i32) -> (bool, i32)...
use std::collections; use crate::util; pub trait Problem { type Conflict; type Iter: Iterator<Item = (Self::Conflict, f64)>; fn find_conflicts(&self) -> Self::Iter; fn fix_conflict(&mut self, _: &Self::Conflict); } pub fn solve<PS: Problem>(ps: &mut PS, steps: i32) -> (bool, i32)...
} } if (iden + SIZE) < self.channels.len() as i32 { if chan.iden == self.channels[&(iden + SIZE)].iden { res.push(( (*iden, (iden + SIZE)), -1.0 * (ch...
if chan.iden == self.channels[&(iden + i + 1)].iden { res.push(( (*iden, (iden + i + 1)), -1.0 * (chan.iden - self.channels[&(iden + i + 1)].iden) as f64, )); }
if_condition
[ { "content": "fn key(data: &util::StateData, h: f64) -> (f64, f64) {\n\n let mut k_0 = data.g;\n\n if data.rhs + h < k_0 {\n\n k_0 = data.rhs + h;\n\n }\n\n let mut k_1 = data.g;\n\n if data.rhs > k_1 {\n\n k_1 = data.rhs;\n\n }\n\n (k_0, k_1)\n\n}\n\n\n", "file_path": "sr...
Rust
src/cipher/chacha20poly1305.rs
posix4e/thrussh-snapshot
56a162f6882018141fd676294937a911d2b7161c
use byteorder::{ByteOrder, BigEndian}; use super::super::{Error, SSHBuffer}; use std::io::BufRead; use super::super::sodium; use sodium::chacha20; use sodium::poly1305; use sodium::randombytes; #[derive(Debug)] pub struct Cipher { k1: chacha20::Key, k2: chacha20::Key, } impl Cipher { pub fn init(key: &...
use byteorder::{ByteOrder, BigEndian}; use super::super::{Error, SSHBuffer}; use std::io::BufRead; use super::super::sodium; use sodium::chacha20; use sodium::poly1305; use sodium::randombytes; #[derive(Debug)] pub struct Cipher { k1: chacha20::Key, k2: chacha20::Key, } impl Cipher { pub fn init(key: &...
}
buffer.buffer.extend(&padding[0..padding_len]); { let buffer = buffer.buffer.as_mut_slice(); chacha20::xor_inplace(&mut buffer[offset + 4..], &nonce, 1, &self.k2); } let mut poly_key = [0; poly1305::KEYBYTES]; chacha20::stream_xor_inp...
function_block-function_prefix_line
[ { "content": "/// Fills the read buffer, and returns whether a complete message has been read.\n\n///\n\n/// It would be tempting to return either a slice of `stream`, or a\n\n/// slice of `read_buffer`, but except for a very small number of\n\n/// messages, we need double buffering anyway to decrypt in place o...
Rust
tobytes/src/lib.rs
Nicoretti/spica
1486705f7d3235ac1717e788400e6200708363be
pub trait ByteView { fn byte_at(&self, index: usize) -> Option<u8>; fn byte_size(&self) -> usize; } #[derive(Debug, Clone)] pub struct Bytes<'a, T: ByteView> { pos: usize, view: &'a T, } impl<'a, T: ByteView> Bytes<'a, T> { pub fn new(view: &'a T) -> Self { Bytes { pos: 0...
pub trait ByteView { fn byte_at(&self, index: usize) -> Option<u8>; fn byte_size(&self) -> usize; } #[derive(Debug, Clone)] pub struct Bytes<'a, T: ByteView> { pos: usize, view: &'a T, } impl<'a, T: ByteView> Bytes<'a, T> { pub fn new(view: &'a T) -> Self { Bytes { pos: 0...
); assert_eq!( vec![0xDDu8, 0xCCu8, 0xBBu8, 0xAAu8], value_le.to_bytes().collect::<Vec<u8>>() ); } #[test] fn i32_to_bytes() { let value: i32 = 0x0A0B0C0D; let value_be: i32 = value.to_be(); let value_le: i32 = value.to_le(); assert_e...
let value_le: u32 = value.to_le(); assert_eq!( vec![0xAAu8, 0xBBu8, 0xCCu8, 0xDDu8], value_be.to_bytes().collect::<Vec<u8>>()
function_block-random_span
[ { "content": "pub trait ValueType {}\n\n\n\nimpl RegisterType for u8 {}\n\nimpl RegisterType for u16 {}\n\nimpl RegisterType for u32 {}\n\nimpl RegisterType for u64 {}\n\nimpl RegisterType for usize {}\n\n\n", "file_path": "nostd/src/registers.rs", "rank": 2, "score": 149421.79326896567 }, { ...
Rust
src/transporter.rs
j5ik2o/dht-kademlia-rs
f15716b804c272a7476676f39cad71727c0158a0
use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use async_trait::async_trait; use tokio::net::UdpSocket; use tokio::sync::Mutex; use tokio::sync::mpsc::{channel, Receiver, Sender}; #[async_trait] pub trait Transporter: Send + Sync + 'stat...
use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use async_trait::async_trait; use tokio::net::UdpSocket; use tokio::sync::Mutex; use tokio::sync::mpsc::{channel, Receiver, Sender}; #[async_trait] pub trait Transporter: Send + Sync + 'stat...
clone(); tokio::spawn(async move { loop { let result = server_rx.try_recv(); if let Ok(msg) = result { let s = String::from_utf8(msg.data.clone()).unwrap(); log::debug!("server:receive: msg = {:?}", s); sever_clone.send(msg).await; } tokio::time::s...
ion<Arc<UdpSocket>>, } unsafe impl Send for UdpTransporter {} unsafe impl Sync for UdpTransporter {} #[derive(Debug, Clone)] pub struct Message { pub(crate) socket_addr: SocketAddr, pub(crate) data: Vec<u8>, } impl Message { pub fn new_with_socket_addr_and_data(socket_addr: SocketAddr, data: Vec<u8>) -> Self {...
random
[ { "content": "pub trait DataStore {\n\n fn get(&self, key: &str) -> Result<Vec<u8>>;\n\n fn put(&mut self, key: &str, value: &[u8]) -> Result<()>;\n\n fn delete(&mut self, key: &str) -> Result<()>;\n\n fn exist(&self, key: &str) -> Result<bool>;\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct InMemoryData...
Rust
src/timers.rs
ax-rwnd/lpc1347-support
fdb9746f2c77b49ed70ee4c736cd001c1a74b12f
#![allow(dead_code)] extern crate lpc1347; use lpc1347::Peripherals; use lpc1347::Interrupt::CT16B0; use lpc1347::Interrupt::CT16B1; #[derive(Copy, Clone)] pub enum Timer16 { Timer0, Timer1, } #[derive(Copy, Clone)] pub enum MatchReg { Reg0, Reg1, Reg2, Reg3, } pub fn init(syscon: &lpc1347:...
#![allow(dead_code)] extern crate lpc1347; use lpc1347::Peripherals; use lpc1347::Interrupt::CT16B0; use lpc1347::Interrupt::CT16B1; #[derive(Copy, Clone)] pub enum Timer16 { Timer0, Timer1, } #[derive(Copy, Clone)] pub enum MatchReg { Reg0, Reg1, Reg2, Reg3, } pub fn init(syscon: &lpc1347:...
} pub fn set_interrupt( ct16b0: &lpc1347::CT16B0, ct16b1: &lpc1347::CT16B1, timer: Timer16, mr: MatchReg, enabled: bool, ) { match timer { Timer16::Timer0 => match mr { MatchReg::Reg0 => { ct16b0.mcr.modify(|_, w| w.mr0i().bit(enabled)); ct16...
match timer { Timer16::Timer0 => { syscon.sysahbclkctrl.modify(|_, w| w.ct16b0().bit(true)); nvic.enable(CT16B0); } Timer16::Timer1 => { syscon.sysahbclkctrl.modify(|_, w| w.ct16b1().bit(true)); nvic.enable(CT16B1); } }
if_condition
[ { "content": "pub fn init(syscon: &lpc1347::SYSCON, nvic: &lpc1347::NVIC, timer: Timer) {\n\n match timer {\n\n Timer::Timer0 => {\n\n syscon.sysahbclkctrl.modify(|_, w| w.ct32b0().bit(true));\n\n nvic.enable(CT32B0);\n\n }\n\n Timer::Timer1 => {\n\n sysc...
Rust
src/scheduler/inner_ruba.rs
dropbox/ruba
60f3e8674f59669f827c2ea59f61c71768cb3b9d
use std::collections::{HashMap, VecDeque}; use std::mem; use std::str; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, RwLock, Condvar}; use std::thread; use disk_store::db::*; use futures::*; use futures_channel::oneshot; use ingest::input_column::InputColumn; use ingest::raw_val::RawVal; u...
use std::collections::{HashMap, VecDeque}; use std::mem; use std::str; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, RwLock, Condvar}; use std::thread; use disk_store::db::*; use futures::*; use futures_channel::oneshot; use ingest::input_column::InputColumn; use ingest::raw_val::RawVal; u...
ad().unwrap(); tables.values().map(|table| table.stats()).collect() } fn create_if_empty(&self, table: &str) { let exists = { let tables = self.tables.read().unwrap(); tables.contains_key(table) }; if !exists { { let mut tables...
Option<Vec<Batch>> { let tables = self.tables.read().unwrap(); tables.get(table).map(|t| t.snapshot()) } pub fn stop(&self) { let _ = self.task_queue.lock(); self.running.store(false, Ordering::SeqCst); self.idle_queue.notify_all(); } fn worker_loop(rub...
random
[ { "content": "pub fn start_toplevel(name: &str) -> TraceBuilder {\n\n TraceBuilder::new(name.to_owned())\n\n}\n\n\n\npub struct Trace {\n\n toplevel_span: Span,\n\n}\n\n\n\npub struct Span {\n\n name: String,\n\n start_time: u64,\n\n end_time: u64,\n\n children: Vec<Span>,\n\n}\n\n\n\nimpl Tra...
Rust
core/tests/models_user.rs
alvsanand/rnotes
5aa799ef718735ad3ba051c7e464e3948758f69a
extern crate dotenv; extern crate rnotes_core; use rnotes_core::models::db::user::*; use rnotes_core::utils::eq_no_ord; use rnotes_core::BDPool; use std::panic; use std::time::SystemTime; #[test] fn test_pool() { let pool = BDPool::new().unwrap(); pool.get().unwrap(); } #[test] fn test_user_find_all() { ...
extern crate dotenv; extern crate rnotes_core; use rnotes_core::models::db::user::*; use rnotes_core::utils::eq_no_ord; use rnotes_core::BDPool; use std::panic; use std::time::SystemTime; #[test] fn test_pool() { let pool = BDPool::new().unwrap(); pool.get().unwrap(); } #[test] fn test_user_find_all() { ...
#[test] fn test_user_find_by_email_and_password() { let pool = BDPool::new().unwrap(); let con = pool.get().unwrap(); let result = User::find_by_email_and_password( &con, "user_a@email.com".to_string(), "1464ACD6765F91FCCD3F5BF4F14EBB7CA69F53AF91B0A5790C2BBA9D8819417B".to_string()...
t expected = User { id: 1, email: "user_a@email.com".to_string(), name: "user_a".to_string(), password: "1464ACD6765F91FCCD3F5BF4F14EBB7CA69F53AF91B0A5790C2BBA9D8819417B".to_string(), create_time: SystemTime::now(), update_time: SystemTime::now(), }; assert_eq!(r...
function_block-function_prefixed
[ { "content": "#[test]\n\nfn test_pool() {\n\n let pool = BDPool::new().unwrap();\n\n pool.get().unwrap();\n\n}\n", "file_path": "core/tests/lib.rs", "rank": 3, "score": 137945.85201672453 }, { "content": "#[test]\n\nfn test_notefind_by_id_and_user_id_ok() {\n\n let pool = BDPool::ne...
Rust
rustypwn/src/io/process.rs
Escapingbug/rustypwn
a2507e4b9f2317299bf0d61d0d44350192612d6d
use super::arg::{Action, Timeout}; use super::buffer::Buffer; use super::error::{Error, ErrorKind}; use super::tube::{Tube, TubeInternal}; use rustypwn_derive::action; use std::ffi::OsString; use std::ops::Drop; use std::time::SystemTime; use subprocess::{Popen, PopenConfig, Redirection}; pub struct ProcessArg<'a> { ...
use super::arg::{Action, Timeout}; use super::buffer::Buffer; use super::error::{Error, ErrorKind}; use super::tube::{Tube, TubeInternal}; use rustypwn_derive::action; use std::ffi::OsString; use std::ops::Drop; use std::time::SystemTime; use subprocess::{Popen, PopenConfig, Redirection}; pub struct ProcessArg<'a> { ...
fn recv_once(&mut self, size: usize, timeout: Timeout) -> Result<Vec<u8>, Error> { let mut v = vec![]; let now = SystemTime::now(); loop { let (out, err) = self.p.communicate_bytes(None)?; if let Some(mut out) = out { v.append(&mut out); ...
fn send(&mut self, action: Action) -> Result<(), Error> { let _ = timeout; if let Some(exit) = self.p.poll() { return Err(Error::from_kind(ErrorKind::UnexpectedTerminate(exit))); } let input = Some(content.as_ref()); let (out, err) = self.p.communicate_bytes(input)?...
function_block-full_function
[ { "content": "#[proc_macro_attribute]\n\npub fn action(\n\n attr: proc_macro::TokenStream,\n\n input: proc_macro::TokenStream,\n\n) -> proc_macro::TokenStream {\n\n let input = parse_macro_input!(input as syn::ItemFn);\n\n let args = parse_macro_input!(attr as CommaSepIdents).idents;\n\n\n\n let ...
Rust
laria_backend/src/name_resolution/mod.rs
PatchMixolydic/laria
c2cdf8fc5e06af300109dfe1961b49a883c578d7
mod scopes; use self::scopes::Scopes; use crate::{ errors::DiagnosticsContext, parser::ast::{ Block, Expression, ExpressionKind, FunctionDecl, FunctionDef, Item, Mod, PartialArg, Path, PathSegment, Script, Statement, StatementKind, Type, TypeKind, }, }; struct ResolveState<'src> { ...
mod scopes; use self::scopes::Scopes; use crate::{ errors::DiagnosticsContext, parser::ast::{ Block, Expression, ExpressionKind, FunctionDecl, FunctionDef, Item, Mod, PartialArg, Path, PathSegment, Script, Statement, StatementKind, Type, TypeKind, }, }; struct ResolveState<'src> { ...
) => { *path = self.lookup(path); }, ExpressionKind::StructLiteral(..) => todo!("resolve struct literal"), } } } pub(crate) fn resolve(ast: &mut Script, source: &str) -> Result<(), ()> { ResolveState::new(source).resolve(ast) }
{ *name = self.add_local(name.unwrap_last_segment().to_owned(), false); if let Some(ty) = maybe_ty.as_mut() { self.resolve_type(ty); } self.resolve_expression(expr); }, } } fn resolve_expression(&mut self,...
random
[]
Rust
x86_64/src/msr.rs
google/crosvm
df929efce3261ca5383f66eea6c7041b3439eb77
use std::cell::RefCell; use std::collections::BTreeMap; use std::fs::{File, OpenOptions}; use std::os::unix::fs::FileExt; use std::rc::Rc; use anyhow::Context; use arch::{MsrAction, MsrConfig, MsrExitHandler, MsrExitHandlerError, MsrRWType, MsrValueFrom}; use base::{debug, error}; use remain::sorted; use thiserror...
use std::cell::RefCell; use std::collections::BTreeMap; use std::fs::{File, OpenOptions}; use std::os::unix::fs::FileExt; use std::rc::Rc; use anyhow::Context; use arch::{MsrAction, MsrConfig, MsrExitHandler, MsrExitHandlerError, MsrRWType, MsrValueFrom}; use base::{debug, error}; use remain::sorted; use thiserror...
}
file.is_none() && !msr_file.borrow().is_empty() { self.msr_file = Some(new_msr_file); } Ok(()) }
function_block-function_prefixed
[ { "content": "/// Write a protective MBR for a disk of the given total size (in bytes).\n\n///\n\n/// This should be written at the start of the disk, before the GPT header. It is one `SECTOR_SIZE`\n\n/// long.\n\npub fn write_protective_mbr(file: &mut impl Write, disk_size: u64) -> Result<(), Error> {\n\n /...
Rust
src/user/wallet_app_client/src/main.rs
Talentica/simpleblockchain
c2cf10052ae852bdbb433fe69babf51d017c1ee0
#[macro_use] extern crate exonum_derive; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate futures; mod wallet_app_types; use crate::wallet_app_types::{CryptoTransaction, SignedTransaction, TransactionTrait}; use exonum_crypto::{Hash, PublicKey}; use std::collections::HashMap; use s...
#[macro_use] extern crate exonum_derive; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate futures; mod wallet_app_types; use crate::wallet_app_types::{CryptoTransaction, SignedTransaction, TransactionTrait}; use exonum_crypto::{Hash, PublicKey}; use std::collections::HashMap; use s...
client.fetch_state(&input).await; } else { error!("error: invalid public_address"); } } else if input == String::from("5") { invalid_opt_count = 0; info!("Enter block index"); let is_index: Option<u...
g) -> bool { input.clear(); match io::stdin().read_line(input) { Ok(_) => { remove_trailing_newline(input); if input.len() > 0 { return true; } else { return false; } } Err(_) => return false, }; } pub f...
random
[ { "content": "pub fn get_string_input(input: &mut String) -> bool {\n\n input.clear();\n\n match io::stdin().read_line(input) {\n\n Ok(_) => {\n\n remove_trailing_newline(input);\n\n if input.len() > 0 {\n\n return true;\n\n } else {\n\n ...
Rust
libs/editor/libs/cursors/src/cursors.rs
Ryan1729IsParanoidAboutWriteAccess/rote
fbe20e4627c1b63d2af7141dcffd424563b8fe9f
#![deny(unused)] use core::cmp::{max, min}; use editor_types::{Cursor, SetPositionAction}; use panic_safe_rope::{Rope}; use vec1::{Vec1}; use macros::{d}; use rope_pos::{clamp_position, offset_pair}; #[derive(Clone, Debug, Default, Hash, PartialEq, Eq)] pub struct Cursors { cursors: Vec1<Cursor...
#![deny(unused)] use core::cmp::{max, min}; use editor_types::{Cursor, SetPositionAction}; use panic_safe_rope::{Rope}; use vec1::{Vec1}; use macros::{d}; use rope_pos::{clamp_position, offset_pair}; #[derive(Clone, Debug, Default, Hash, PartialEq, Eq)] pub struct Cursors { cursors: Vec1<Cursor...
pub fn borrow_cursors(&self) -> &Vec1<Cursor> { &self.cursors } #[perf_viz::record] pub fn get_cloned_cursors(&self) -> Vec1<Cursor> { self.cursors.clone() } pub fn len(&self) -> usize { self.cursors.len() } pub fn is_empty(&self) -> bool { self.curso...
pub fn mapped_ref<F, Out>(&self, mapper: F) -> Vec1<Out> where F: FnMut(&Cursor) -> Out, { self.cursors.mapped_ref(mapper) }
function_block-full_function
[]
Rust
language/diem-tools/writeset-transaction-generator/src/release_flow/create.rs
patcon/diem
ac8ef40ca5bb78afbc6b881773a24e6948791918
use crate::release_flow::{ hash_for_modules, load_artifact, save_release_artifact, verify::verify_payload_change, ReleaseArtifact, }; use anyhow::{bail, Result}; use diem_types::{ access_path::AccessPath, chain_id::ChainId, transaction::{ChangeSet, WriteSetPayload}, write_set::{WriteOp, WriteS...
use crate::release_flow::{ hash_for_modules, load_artifact, save_release_artifact, verify::verify_payload_change, ReleaseArtifact, }; use anyhow::{bail, Result}; use diem_types::{ access_path::AccessPath, chain_id::ChainId, transaction::{ChangeSet, WriteSetPayload}, write_set::{WriteOp, WriteS...
pub(crate) fn create_release_from_artifact( artifact: &ReleaseArtifact, remote_url: &str, release_modules: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let remote = JsonRpcDebuggerInterface::new(remote_url)?; let remote_modules = remote.get_diem_framework_modules_by_version(artifac...
pub fn create_release( chain_id: ChainId, url: String, version: u64, first_release: bool, release_modules: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let release_artifact = ReleaseArtifact { chain_id, version, stdlib_hash: hash_f...
function_block-full_function
[ { "content": "// Parse a use declaration:\n\n// UseDecl =\n\n// \"use\" <ModuleIdent> <UseAlias> \";\" |\n\n// \"use\" <ModuleIdent> :: <UseMember> \";\" |\n\n// \"use\" <ModuleIdent> :: \"{\" Comma<UseMember> \"}\" \";\"\n\nfn parse_use_decl<'input>(tokens: &mut Lexer<'input>) -...
Rust
rre-pe/src/api_set_map/v6.rs
rustrat/experiments
7e441ff43a28d82dfa9ba9b17a93243233af64ab
use crate::structs::UnicodeString; #[repr(C)] struct ValueEntry { pub flags: u32, pub origin_offset: u32, pub origin_length: u32, pub value_offset: u32, pub value_length: u32, } #[repr(C)] pub(super) struct NamespaceEntry { flags: u32, name_offset: u32, size: u32, name_length: u32,...
use crate::structs::UnicodeString; #[repr(C)] struct ValueEntry { pub flags: u32, pub origin_offset: u32, pub origin_length: u32, pub value_offset: u32, pub value_length: u32, } #[repr(C)] pub(super) struct NamespaceEntry { flags: u32, name_offset: u32, size: u32, name_length: u32,...
#[test] fn test_find_with_specific_importing_module() { let test_struct = get_test_memory(); unsafe { assert_eq!( get_actual_name( &test_struct.namespace_array, "api-test-api-l1-0", "specific.dll" ...
fn test_find_default() { let test_struct = get_test_memory(); unsafe { assert_eq!( get_actual_name( &test_struct.namespace_array, "api-api-test-l2-0", "dontcare.dll" ), Some("correct....
function_block-full_function
[ { "content": "pub fn get_fn_ptr(module: *const ImageDosHeader, fn_name: &str) -> Option<*const c_void> {\n\n let base_ptr = module as usize;\n\n\n\n unsafe {\n\n let nt_header = &*((base_ptr + (*module).e_lfanew as usize) as *const ImageNtHeaders);\n\n // ...
Rust
core/src/main.rs
dzobbe/sgxmusl-tuner
8a9a4fbf4213230879aeb0ed1cd283a88c13fd6f
extern crate rustc_serialize; extern crate rand; extern crate libc; extern crate time; extern crate ansi_term; extern crate pbr; extern crate csv; extern crate num_cpus; extern crate wait_timeout; extern crate ssh2; extern crate xml; extern crate ctrlc; extern crate zmq; extern crate yaml_rust; extern crate influent; ...
extern crate rustc_serialize; extern crate rand; extern crate libc; extern crate time; extern crate ansi_term; extern crate pbr; extern crate csv; extern crate num_cpus; extern crate wait_timeout; extern crate ssh2; extern crate xml; extern crate ctrlc; extern crate zmq; extern crate yaml_rust; extern crate influent; ...
} } impl std::str::FromStr for SolverVersion { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "seqsa" => Ok(SolverVersion::seqsa), "spisa" => Ok(SolverVersion::spisa), "mir" => Ok(SolverVersion::mir), "prsa" => O...
match s { "linear" => Ok(CoolingSchedule::linear), "exponential" => Ok(CoolingSchedule::exponential), "basic_exp_cooling" => Ok(CoolingSchedule::basic_exp_cooling), _ => Err("Cooling Schedule - not a valid value"), }
if_condition
[ { "content": "/// Check if the temperature is given by the user or if Tmin and Tmax need to be evaluated\n\npub fn eval_temperature(tuner_params: &mut TunerParameter, problem: &mut Problem) {\n\n let num_exec = 10;\n\n\n\n let t_min = tuner_params.min_temp;\n\n let t_max = tuner_params.max_temp;\n\n\n\...
Rust
pallets/ocw/src/sp_merkle.rs
04637/nextid
4314e2d227045d203150fc5626f39c7f15329d18
#![cfg_attr(not(feature = "std"), no_std)] use sp_std::fmt::{Display, Formatter}; use sp_std::vec::Vec; use sp_io::hashing::twox_64; use sp_std::collections::btree_map::BTreeMap; use sp_core::{Encode, Decode}; #[derive(Encode, Decode)] pub struct MerkleTree { pub root_hash: Vec<u8>, pub nodes: BTreeMap<V...
#![cfg_attr(not(feature = "std"), no_std)] use sp_std::fmt::{Display, Formatter}; use sp_std::vec::Vec; use sp_io::hashing::twox_64; use sp_std::collections::btree_map::BTreeMap; use sp_core::{Encode, Decode}; #[derive(Encode, Decode)] pub struct MerkleTree { pub root_hash: Vec<u8>, pub nodes: BTreeMap<V...
} } else { if let Some(left_node) = self.left(&parent.hash) { path.push((left_node.hash.clone(), true)); } } self.recur_upward(&parent.hash, path); } else { return; } } } impl Merkle...
<u8>, bool)>) { let parent = self.parent(cur_node_hash); if let Some(parent) = parent { if self.get_node(cur_node_hash).unwrap().is_left { if let Some(right_node) = self.right(&parent.hash) { path.push((right_node.hash.clone(), false)...
function_block-random_span
[ { "content": "/// Builds a new service for a full client.\n\npub fn new_full(mut config: Configuration) -> Result<TaskManager, ServiceError> {\n\n\tlet sc_service::PartialComponents {\n\n\t\tclient,\n\n\t\tbackend,\n\n\t\tmut task_manager,\n\n\t\timport_queue,\n\n\t\tmut keystore_container,\n\n\t\tselect_chain,...
Rust
src/integration_test.rs
Callum-A/staking-wrapper
b5f9e6e06d41f19644f206a8f4a0926216bb9add
#![cfg(test)] use crate::contract::{execute, instantiate, query}; use crate::msg::QueryMsg::GetDelegation; use crate::msg::{GetDelegationResponse, InstantiateMsg}; use cosmwasm_std::{ coin, to_binary, Addr, Api, Binary, BlockInfo, CustomQuery, Empty, FullDelegation, Querier, StakingMsg, StakingQuery, Storage, ...
#![cfg(test)] use crate::contract::{execute, instantiate, query}; use crate::msg::QueryMsg::GetDelegation; use crate::msg::{GetDelegationResponse, InstantiateMsg}; use cosmwasm_std::{ coin, to_binary, Addr, Api, Binary, BlockInfo, CustomQuery, Empty, FullDelegation, Querier, StakingMsg, StakingQuery, Storage, ...
&GetDelegation { validator: "abc".to_string(), }, ) .unwrap(); assert_eq!(resp.delegation.is_some(), true); }
ase")] pub struct DelegationResponse { pub delegation: Option<FullDelegation>, } impl Module for MyStaking { type ExecT = StakingMsg; type QueryT = StakingQuery; type SudoT = StakingSudo; fn execute<ExecC, QueryC>( &self, api: &dyn Api, storage: &mut dyn Storage, ro...
random
[]
Rust
etc/correctness/rng-tests/_common.rs
str4d/minimal-lexical
f6399813f02b7a55a875672c284ef3f69c2a34d6
#[inline] fn parse_sign<'a>(bytes: &'a [u8]) -> (bool, &'a [u8]) { match bytes.get(0) { Some(&b'+') => (true, &bytes[1..]), Some(&b'-') => (false, &bytes[1..]), _ => (true, bytes), } } #[inline] fn to_digit(c: u8) -> Option<u32> { (c as char).to_digit(10) } #[inline] fn add_digit...
#[inline] fn parse_sign<'a>(bytes: &'a [u8]) -> (bool, &'a [u8]) { match bytes.get(0) { Some(&b'+') => (true, &bytes[1..]), Some(&b'-') => (false, &bytes[1..]), _ => (true, bytes), } } #[inline] fn to_digit(c: u8) -> Option<u32> { (c as char).to_digit(10) } #[inline] fn add_digit...
nwrap()) { Some(v) => v, None => return i32::max_value(), }; } }, false => { for c in exponent { value = match sub_digit_i32(value, to_digit(*c).unwrap()) { Some(v) => v, ...
= bytes.iter().rev().take_while(|&&si| si == b'0').count(); let index = bytes.len() - count; &bytes[..index] } fn parse_exponent(exponent: &[u8], is_positive: bool) -> i32 { let mut value: i32 = 0; match is_positive { true => { for c in exponent { value = match ...
random
[ { "content": "#[inline]\n\nfn is_digit(c: u8) -> bool {\n\n to_digit(c).is_some()\n\n}\n\n\n\n// Split buffer at index.\n", "file_path": "examples/simple.rs", "rank": 0, "score": 262744.0614409787 }, { "content": "#[inline]\n\nfn is_digit(c: u8) -> bool {\n\n to_digit(c).is_some()\n\n}...
Rust
crates/symbolicator/src/logging.rs
yayanet/symbolicator
0e9530292d40cb39ade6b30abdac56512ef6037e
use std::env; use std::fmt; use std::io::{self, Write}; use chrono::{DateTime, Utc}; use log::{Level, LevelFilter}; use sentry::integrations::log::{breadcrumb_from_record, event_from_record}; use serde::{Deserialize, Serialize}; use crate::config::{Config, LogFormat}; fn get_rust_log(level: LevelFilter) -> &'static ...
use std::env; use std::fmt; use std::io::{self, Write}; use chrono::{DateTime, Utc}; use log::{Level, LevelFilter}; use sentry::integrations::log::{breadcrumb_from_record, event_from_record}; use serde::{Deserialize, Serialize}; use crate::config::{Config, LogFormat}; fn get_rust_log(level: LevelFilter) -> &'static ...
} pub fn ensure_log_error(error: &anyhow::Error) { if log::log_enabled!(log::Level::Error) { log::error!("{:?}", error); } else { eprintln!("{:?}", error); } }
mt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut error = self.0; write!(f, "{}", error)?; while let Some(cause) = error.source() { write!(f, "\n caused by: {}", cause)?; error = cause; } Ok(()) }
function_block-function_prefixed
[ { "content": "/// Checks if something is a safe bundle id\n\npub fn is_bundle_id(input: &str) -> bool {\n\n make_bundle_id(input) == input\n\n}\n\n\n", "file_path": "crates/symsorter/src/utils.rs", "rank": 1, "score": 226719.70028498775 }, { "content": "/// Makes a safe bundle ID from arb...
Rust
src/chromagram.rs
shybyte/chord-detection-rust
c80522862af66a41758e0aa5d9adf6d603725bf1
/** @file chromagram.rs * @brief Chromagram - a class for calculating the chromagram in real-time * @rust-implementation Marco Stahl * @copyright Copyright (C) 2018 Marco Stahl * Based on https://github.com/adamstark/Chord-Detector-and-Chromagram * @original-file Chromagram.cpp * @author Adam Stark * @c...
/** @file chromagram.rs * @brief Chromagram - a class for calculating the chromagram in real-time * @rust-implementation Marco Stahl * @copyright Copyright (C) 2018 Marco Stahl * Based on https://github.com/adamstark/Chord-Detector-and-Chromagram * @original-file Chromagram.cpp * @author Adam Stark * @c...
}
fn down_sample_frame(&mut self, input_audio_frame: &[f64]) { let b0 = 0.2929; let b1 = 0.5858; let b2 = 0.2929; let a1 = -0.0000; let a2 = 0.1716; let mut x_1 = 0.0; let mut x_2 = 0.0; let mut y_1 = 0.0; let mut y_2 = 0.0; for i in 0..self...
function_block-full_function
[ { "content": "pub fn make_mono(channel_count: usize, input: &[i16], output: &mut [i16]) {\n\n let channel_count_i64 = channel_count as i64;\n\n for (chunk, out) in input.chunks(channel_count).zip(output.iter_mut()) {\n\n let s: i64 = chunk.iter().map(|&x| x as i64).sum();\n\n *out = (s / cha...
Rust
chain-storage/src/index.rs
TenStrings/chain-libs
a3fa527aa269b5502c881666babac8db8c66ea11
use chain_core::property::Block; use std::collections::HashMap; use thiserror::Error; pub(crate) struct ChainStorageIndex<B> where B: Block, { blocks_index: DbIndex<B::Id, RowId>, blocks_by_chain_length_index: DbIndex<u64, Vec<B::Id>>, block_info_index: DbIndex<B::Id, RowId>, tags_index: DbIndex<St...
use chain_core::property::Block; use std::collections::HashMap; use thiserror::Error; pub(crate) struct ChainStorageIndex<B> where B: Block, { blocks_index: DbIndex<B::Id, RowId>, blocks_by_chain_length_index: DbIndex<u64, Vec<B::Id>>, block_info_index: DbIndex<B::Id, RowId>, tags_index: DbIndex<St...
-> Option<&RowId> { self.tags_index.get(tag) } pub fn add_tag_check(&self, block_id: &B::Id) -> IndexResult { if self.get_block(block_id).is_none() { return Err(IndexError::BlockNotFound); } Ok(()) } pub fn add_tag(&mut self, tag: String, block_id: &B::Id, ...
.blocks_by_chain_length_index .add(chain_length, vec![block_id]), } Ok(()) } pub fn get_tag(&self, tag: &str)
random
[ { "content": "pub fn update(secret: &mut SecretKey) -> Result<(), Error> {\n\n //assert!(secret.t() < secret.depth().total());\n\n let diff = usize::count_ones(secret.t() ^ (secret.t() + 1));\n\n assert!(diff >= 1);\n\n\n\n match secret.rs_pop() {\n\n None => Err(Error::KeyCannotBeUpdatedMore...
Rust
third-party/contracts/src/implementation/parse.rs
fossabot/necsim-rust
996b6a6977bc27a997a123e3e4f5a7b11e1a1aef
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use proc_macro2::{Spacing, TokenStream, TokenTree}; use syn::{Expr, ExprLit, Lit}; pub(crate) fn parse_attributes...
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use proc_macro2::{Spacing, TokenStream, TokenTree}; use syn::{Expr, ExprLit, Lit}; pub(crate) fn parse_attributes...
fn segment_input(tts: TokenStream) -> Vec<Vec<TokenTree>> { let mut groups = vec![]; let mut group = vec![]; for tt in tts { match tt { TokenTree::Punct(p) if p.as_char() == ',' && p.spacing() == Spacing::Alone => { groups.push(group); ...
x += 1; } _ => { break 'op; } } } } } } match (rhs, span) { (None, None) => lhs.into_iter().collect(), (None, ...
function_block-function_prefixed
[ { "content": "#[proc_macro_attribute]\n\npub fn requires(attr: TokenStream, toks: TokenStream) -> TokenStream {\n\n let attr = attr.into();\n\n let toks = toks.into();\n\n implementation::requires(ContractMode::Always, attr, toks).into()\n\n}\n\n\n\n/// Same as [`requires`], but uses `debug_assert!`.\n...
Rust
build/main.rs
RealKC/rust-xcb
f7e53a57d27dcb7aa47ad7024f560c99563fde30
extern crate quick_xml; mod cg; mod ir; mod output; mod parse; use std::env; use std::fs; use std::io; use std::path::{Path, PathBuf}; use cg::{CodeGen, DepInfo}; use ir::ExtInfo; use output::Output; use parse::{Event, Parser, Result}; fn is_always(name: &str) -> bool { matches!(name, "xproto" | "bigreq" | "xc_...
extern crate quick_xml; mod cg; mod ir; mod output; mod parse; use std::env; use std::fs; use std::io; use std::path::{Path, PathBuf}; use cg::{CodeGen, DepInfo}; use ir::ExtInfo; use output::Output; use parse::{Event, Parser, Result}; fn is_always(name: &str) -> bool { matches!(name, "xproto" | "bigreq" | "xc_...
fn recurse_push_depinfo(dep_info: &mut Vec<DepInfo>, xcb_mod: &str, global: &[DepInfo]) { if dep_info.iter().any(|di| di.xcb_mod == xcb_mod) { return; } let di = global .iter() .find(|di| di.xcb_mod == xcb_mod) .unwrap_or_else(|| panic!("can't find dependency {}", xcb_mod)...
filter_map(|dir| { let full_path = dir.join(&exe_name); if full_path.is_file() { Some(full_path) } else { None } }) .next() }) }
function_block-function_prefix_line
[]
Rust
src/operator/sum.rs
vmware/database-stream-processor
e702b903b8365366f31ff8d6645e23a31cf1f3b2
use crate::{ algebra::{AddAssignByRef, AddByRef, HasZero}, circuit::{ operator_traits::{NaryOperator, Operator}, Circuit, OwnershipPreference, Stream, }, NumEntries, }; use std::{ borrow::Cow, cmp::Reverse, iter::once, mem::{take, ManuallyDrop}, ops::Add, }; impl<P...
use crate::{ algebra::{AddAssignByRef, AddByRef, HasZero}, circuit::{ operator_traits::{NaryOperator, Operator}, Circuit, OwnershipPreference, Stream, }, NumEntries, }; use std::{ borrow::Cow, cmp::Reverse, iter::once, mem::{take, ManuallyDrop}, ops::Add, }; impl<P...
test { use crate::{ algebra::HasZero, circuit::{Circuit, OwnershipPreference, Root}, operator::{Generator, Inspect}, trace::{ord::OrdZSet, Batch}, zset, }; #[test] fn zset_sum() { let build_circuit = |circuit: &Circuit<()>| { let mut s = <OrdZ...
} } } self.inputs = unsafe { assert!(input_vec.is_empty()); let mut buffer = ManuallyDrop::new(input_vec); let (ptr, len, cap) = (buffer.as_mut_ptr(), buffer.len(), buffer.capacity()); Vec::from_raw_parts(ptr.cast(), len, cap) }; ...
random
[ { "content": "/// Minimal requirements for values exchanged by operators.\n\npub trait Data: Clone + 'static {}\n\n\n\nimpl<T: Clone + 'static> Data for T {}\n\n\n", "file_path": "src/circuit/operator_traits.rs", "rank": 0, "score": 256363.46727074194 }, { "content": "/// Trait that must be ...
Rust
guppy/src/diff.rs
sunshowers/cargo-guppy
d028787b0148cfa36265c697457d56f583335ab6
use crate::lockfile::{Lockfile, PackageId}; use serde::Serialize; use std::collections::HashMap; #[derive(Debug, Default)] pub struct DiffOptions; impl DiffOptions { pub fn diff(&self, old_lockfile: &Lockfile, new_lockfile: &Lockfile) -> Diff { let mut new: HashMap<_, _> = new_lockfile .pack...
use crate::lockfile::{Lockfile, PackageId}; use serde::Serialize; use std::collections::HashMap; #[derive(Debug, Default)] pub struct DiffOptions; impl DiffOptions {
} #[derive(Debug, Serialize)] pub struct Diff { updated: Vec<(PackageId, PackageId)>, removed: Vec<(PackageId, Option<Vec<PackageId>>)>, added: Vec<(PackageId, Option<Vec<PackageId>>)>, } impl ::std::fmt::Display for Diff { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ...
pub fn diff(&self, old_lockfile: &Lockfile, new_lockfile: &Lockfile) -> Diff { let mut new: HashMap<_, _> = new_lockfile .packages() .map(|p| (p.package_id(), p)) .collect(); let mut removed = old_lockfile .packages() .filter_map(|package| { ...
function_block-full_function
[ { "content": "#[derive(Debug, StructOpt)]\n\n#[structopt(about = \"Cargo.lock file analysis\")]\n\nstruct Args {\n\n #[structopt(subcommand)]\n\n cmd: Command,\n\n}\n\n\n", "file_path": "cargo-guppy/src/main.rs", "rank": 0, "score": 48792.15533699663 }, { "content": "struct NameVisitor...
Rust
build.rs
coral/ndi-sys
33e15d56079aa8a5e41028b2b62d928746723fe1
#[allow(unused_imports)] use std::io::ErrorKind; #[allow(unused_imports)] use std::path::{Path, PathBuf}; use std::{env, fs}; #[allow(dead_code)] fn find_sdk() -> Option<String> { if let Ok(path) = env::var("NDI_SDK_DIR") { if Path::new(&path).exists() { return Some(path); } ...
#[allow(unused_imports)] use std::io::ErrorKind; #[allow(unused_imports)] use std::path::{Path, PathBuf}; use std::{env, fs}; #[allow(dead_code)] fn find_sdk() -> Option<String> { if let Ok(path) = env::var("NDI_SDK_DIR") { if Path::new(&path).exists() { return Some(path); } ...
fn main() { let os = env::var("CARGO_CFG_TARGET_OS").expect("Could not get OS"); #[cfg(feature = "bindings")] { let sdk = find_sdk().expect( "Could not find the SDK to generate bindings. Please set the NDI_SDK_DIR env variable to the root of the SDK install.", ...
g()); } } #[cfg(target_os = "windows")] { let std_location = Path::new("C:/Program Files/NDI/NDI 5 SDK"); if std_location.exists() { return std_location.to_str().map(|s| s.to_string()); } } None }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn bindgen_test_layout___mbstate_t() {\n\n assert_eq!(\n\n ::std::mem::size_of::<__mbstate_t>(),\n\n 128usize,\n\n concat!(\"Size of: \", stringify!(__mbstate_t))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<__mbstate_t>(),\n\n 8usize,\n\...
Rust
edb/milevadb_query/milevadb_query_vec_aggr/src/impl_first.rs
whtcorpsinc/einsteindb-prod
3b1c63a421ff37f1ca6bef4d67ef7f4c4c78a6d7
use std::marker::PhantomData; use milevadb_query_codegen::AggrFunction; use milevadb_query_datatype::EvalType; use fidel_timeshare::{Expr, ExprType, FieldType}; use super::*; use milevadb_query_common::Result; use milevadb_query_datatype::codec::data_type::*; use milevadb_query_datatype::expr::EvalContext; use mile...
use std::marker::PhantomData; use milevadb_query_codegen::AggrFunction; use milevadb_query_datatype::EvalType; use fidel_timeshare::{Expr, ExprType, FieldType}; use super::*; use milevadb_query_common::Result; use milevadb_query_datatype::codec::data_type::*; use milevadb_query_datatype::expr::EvalContext; use mile...
} #[causet(test)] mod tests { use super::super::AggrFunction; use super::*; use milevadb_query_datatype::FieldTypeTp; use fidel_timeshare_helper::ExprDefBuilder; use crate::AggrDefinitionParser; #[test] fn test_fidelio() { let mut ctx = EvalContext::default(); let functi...
let res = if let AggrFnStateFirst::Valued(v) = self { v.clone() } else { None }; target[0].push(res); Ok(()) }
function_block-function_prefix_line
[ { "content": "#[rpn_fn(capture = [ctx])]\n\n#[inline]\n\npub fn to_seconds(ctx: &mut EvalContext, t: &DateTime) -> Result<Option<Int>> {\n\n if t.invalid_zero() {\n\n return ctx\n\n .handle_invalid_time_error(Error::incorrect_datetime_value(t))\n\n .map(|_| Ok(None))?;\n\n }\n...
Rust
src/element.rs
debris/iced
10b07b8028984ce424d714e7a799be18fde0b83a
use stretch::{geometry, result}; use crate::{Event, Hasher, Layout, MouseCursor, Node, Point, Widget}; pub struct Element<'a, Message, Renderer> { pub(crate) widget: Box<dyn Widget<Message, Renderer> + 'a>, } impl<'a, Message, Renderer> std::fmt::Debug for Element<'a, Message, Renderer> { fn fmt(&self, f: &m...
use stretch::{geometry, result}; use crate::{Event, Hasher, Layout, MouseCursor, Node, Point, Widget}; pub struct Element<'a, Message, Renderer> { pub(crate) widget: Box<dyn Widget<Message, Renderer> + 'a>, } i
event: Event, layout: Layout<'_>, cursor_position: Point, messages: &mut Vec<Message>, ) { self.element .widget .on_event(event, layout, cursor_position, messages) } fn draw( &self, renderer: &mut Renderer, layout: Layou...
mpl<'a, Message, Renderer> std::fmt::Debug for Element<'a, Message, Renderer> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Element") .field("widget", &self.widget) .finish() } } impl<'a, Message, Renderer> Element<'a, Message, Renderer> ...
random
[ { "content": "/// A component that displays information or allows interaction.\n\n///\n\n/// If you want to build a custom widget, you will need to implement this trait.\n\n/// Additionally, remember to also provide [`Into<Element>`] so your users can\n\n/// easily turn your [`Widget`] into a generic [`Element`...
Rust
src/status.rs
jan-schreib/vmctl-controller
aed4a77782f70949d77afe26b620644d96755bb5
use std::str; use std::str::FromStr; use std::process::{Command, Stdio}; use errors::{VmctlControllerError, VmctlControllerErrorCause}; #[derive(Serialize, Deserialize, Debug)] pub struct Status { pub id: u64, pub pid: String, pub vcpus: u64, pub max_mem: String, pub cur_mem: String, pub tty: ...
use std::str; use std::str::FromStr; use std::process::{Command, Stdio}; use errors::{VmctlControllerError, VmctlControllerErrorCause}; #[derive(Serialize, Deserialize, Debug)] pub struct Status { pub id: u64, pub pid: String, pub vcpus: u64, pub max_mem: String, pub cur_mem: String, pub tty: ...
#[test] fn from_shell() { let shell_output = r#" 1 - 1 2.0G - - user one 2 - 1 512M - - user two 3 - 1 2.0G - - user three 4 - 1 4.0G - - user four"#; ...
let vm1 = "1 - 1 2.0G - - user one"; let vm2 = "2 - 1 512M - - user two"; let vm3 = "3 - 1 2.0G - - user three"; let vm4 = "4 - 1 4.0G - - user four"; let vm_v...
function_block-function_prefix_line
[]
Rust
src/models/access_token.rs
xiaosongfu/ruma
06d7f2f5debd40637aca6c22dd50ddc444148b7c
use base64::encode; use chrono::{Duration, Utc}; use diesel::pg::data_types::PgTimestamp; use diesel::pg::PgConnection; use diesel::prelude::*; use diesel::result::Error as DieselError; use iron::typemap::Key; use macaroons::caveat::Caveat; use macaroons::token::Token; use macaroons::v1::V1Token; use ruma_identifiers...
use base64::encode; use chrono::{Duration, Utc}; use diesel::pg::data_types::PgTimestamp; use diesel::pg::PgConnection; use diesel::prelude::*; use diesel::result::Error as DieselError; use iron::typemap::Key; use macaroons::caveat::Caveat; use macaroons::token::Token; use macaroons::v1::V1Token; use ruma_identifiers...
fn create_macaroon(macaroon_secret_key: &[u8], user_id: &UserId) -> Result<String, ApiError> { let expiration = match Utc::now().checked_add_signed(Duration::hours(1)) { Some(datetime) => datetime, None => { return Err(ApiError::unknown( "Failed to generate access token e...
function_block-full_function
[ { "content": "/// Verifies a password with Argon2.\n\npub fn verify_password(encoded_hash: &[u8], plaintext_password: &str) -> Result<bool, ApiError> {\n\n let encoded = Encoded::from_u8(encoded_hash).map_err(ApiError::from)?;\n\n\n\n Ok(encoded.verify(plaintext_password.as_bytes()))\n\n}\n\n\n", "fil...
Rust
src/executor.rs
BobAnkh/ns3-parallel
e92e96e918821a22700f5d3d0e88ecccb96b1341
use futures::stream::FuturesUnordered; use futures::StreamExt; use pbr::MultiBar; use std::collections::HashMap; use std::path::Path; use std::process::Output; use tokio::process::Command; use tokio::task::spawn_blocking; use crate::core::*; use crate::error::Error; const DEFAULT_RETRY_LIMIT: i32 = 5; #[derive(Debug...
use futures::stream::FuturesUnordered; use futures::StreamExt; use pbr::MultiBar; use std::collections::HashMap; use std::path::Path; use std::process::Output; use tokio::process::Command; use tokio::task::spawn_blocking; use crate::core::*; use crate::error::Error; const DEFAULT_RETRY_LIMIT: i32 = 5; #[derive(Debug...
} impl<P: BuildCmd> Task<P> { pub fn read_raw(&self) -> (Vec<u8>, Vec<u8>) { let stdout = self.output.stdout.clone(); let stderr = self.output.stderr.clone(); (stdout, stderr) } pub fn read_raw_stdout(&self) -> Vec<u8> { self.output.stdout.clone() } pub fn read_ra...
Config file must be a toml file.".to_string(), )); } } None => { return Err(Error::InvalidConfig( "Config file must have a valid file extension.".to_string(), )); } } config_path =...
function_block-function_prefix_line
[ { "content": "/// # BuildParam\n\n///\n\n/// This trait is used to build the parameters for the NS3 program.\n\n///\n\n/// Implement this trait and also the `Default` trait on your own config struct.\n\n///\n\n/// ## Example\n\n///\n\n/// ```\n\n/// use serde::{Deserialize, Serialize};\n\n/// use ns3_parallel::...
Rust
src/main.rs
mrak/ipsee
ec2575e88d4753164c658e90644a43ad07187689
extern crate clap; extern crate pnet; use std::env; use std::io::ErrorKind; use std::net::IpAddr; use std::process::exit; use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; use std::thread; use std::vec::Vec; use pnet::datalink::Channel::Ethernet; use pnet::datalink::{self, NetworkInterface}; use pnet::pac...
extern crate clap; extern crate pnet; use std::env; use std::io::ErrorKind; use std::net::IpAddr; use std::process::exit; use std::sync::mpsc; use std::sync::mpsc::{Receiver, Sender}; use std::thread; use std::vec::Vec; use pnet::datalink::Channel::Ethernet; use pnet::datalink::{self, NetworkInterface}; use pnet::pac...
, None => println!("[{}] I Malformed packet", interface_name), } }
match icmp_packet.get_icmp_type() { IcmpTypes::EchoReply => {} _ => println!("[{}] I {} > {}", interface_name, source, destination,), }
if_condition
[]
Rust
src/clients/arrow_client.rs
rodrigo-romano/dos-actors
4ac802701a47617e7e77f9af2d851ef48249effb
/*! # Actor client for Apache Arrow A simulation data logger that records the data in the [Apache Arrow] format and automatically saves the data into a [Parquet] file (`data.parquet`) at the end of a simulation. The [Arrow] client is enabled with the `apache-arrow` feature. [Apache Arrow]: https://docs.rs/arrow [Par...
/*! # Actor client for Apache Arrow A simulation data logger that records the data in the [Apache Arrow] format and automatically saves the data into a [Parquet] file (`data.parquet`) at the end of a simulation. The [Arrow] client is enabled with the `apache-arrow` feature. [Apache Arrow]: https://docs.rs/arrow [Par...
}
fn read(&mut self, data: Arc<Data<Vec<T>, U>>) { /*log::debug!( "receive #{} inputs: {:?}", data.len(), data.iter().map(|x| x.len()).collect::<Vec<usize>>() );*/ self.step += 1; if (self.step - 1) % self.decimation > 0 { return;...
function_block-full_function
[ { "content": "#[cfg(feature = \"apache-arrow\")]\n\ntype MaybeData = Result<Vec<Vec<f64>>, crate::clients::arrow_client::ArrowError>;\n\n\n\n#[allow(dead_code)]\n\n#[derive(Debug, Default)]\n\npub struct GmtState {\n\n m1_rbm: Option<IntoIter<Vec<f64>>>,\n\n m2_rbm: Option<IntoIter<Vec<f64>>>,\n\n m1_m...
Rust
rust/rsnano/src/ffi/blocks/mod.rs
simpago/rsnano-node
6a59b6005b14eca1a00c362e314d1e0f6234f714
mod block_details; mod block_uniquer; mod change_block; mod open_block; mod receive_block; mod send_block; mod state_block; use std::{ convert::TryFrom, ffi::c_void, sync::{Arc, RwLock}, }; pub use block_details::*; pub use change_block::*; pub use open_block::*; pub use receive_block::*; pub use send_blo...
mod block_details; mod block_uniquer; mod change_block; mod open_block; mod receive_block; mod send_block; mod state_block; use std::{ convert::TryFrom, ffi::c_void, sync::{Arc, RwLock}, }; pub use block_details::*; pub use change_block::*; pub use open_block::*; pub use receive_block::*; pub use send_blo...
} #[no_mangle] pub extern "C" fn rsn_block_clone(handle: &BlockHandle) -> *mut BlockHandle { let cloned = handle.block.read().unwrap().clone(); Box::into_raw(Box::new(BlockHandle { block: Arc::new(RwLock::new(cloned)), })) } #[no_mangle] pub extern "C" fn rsn_block_handle_clone(handle: &BlockHand...
match block.sideband() { Some(sb) => { set_block_sideband_dto(sb, sideband); 0 } None => -1, }
if_condition
[]
Rust
ton_client/src/net/tests.rs
Psyruss77/TON-SDK
9ec6632899e813635583ec8bf96a4188eaa93da1
use tokio::sync::Mutex; use crate::abi::{CallSet, DeploySet, ParamsOfEncodeMessage, Signer}; use crate::error::ClientError; use crate::net::{ Error, ParamsOfQueryCollection, ParamsOfSubscribeCollection, ParamsOfWaitForCollection, ResultOfQueryCollection, ResultOfSubscribeCollection, ResultOfSubscription, R...
use tokio::sync::Mutex; use crate::abi::{CallSet, DeploySet, ParamsOfEncodeMessage, Signer}; use crate::error::ClientError; use crate::net::{ Error, ParamsOfQueryCollection, ParamsOfSubscribeCollection, ParamsOfWaitForCollection, ResultOfQueryCollection, ResultOfSubscribeCollection, ResultOfSubscription, R...
!({})), fields: Some(vec![FieldAggregation { field: "".into(), aggregation_fn: AggregationFn::COUNT, }]), }, ) .await .unwrap(); let count = u32::from_str_radix(result.values[0].as_str().unwrap(), 10).unwrap...
ollection = client .request_async( "net.aggregate_collection", ParamsOfAggregateCollection { collection: "accounts".to_owned(), filter: Some(json
function_block-random_span
[ { "content": "fn read(slice: &mut SliceData, commands: &Vec<CellFieldReader>) -> ClientResult<Value> {\n\n let mut values = serde_json::Map::new();\n\n for (index, command) in commands.iter().enumerate() {\n\n let name = if command.name.is_empty() { format!(\"{}\", index) } else { command.name.clon...
Rust
glutin/src/platform_impl/unix/mod.rs
wusyong/glutin
388d2adf96b18902d4e89e8647217d7c60e0b7a4
#![cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", ))] use crate::{ Api, ContextCurrentState, ContextError, CreationError, GlAttributes, NotCurrent, PixelFormat, PixelFormatRequirements, Rect, }; use tao::dpi; use t...
#![cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", ))] use crate::{ Api, ContextCurrentState, ContextError, CreationError,
Err(ContextError::FunctionUnavailable) } #[inline] pub fn swap_buffers_with_damage_supported(&self) -> bool { false } #[inline] pub fn get_pixel_format(&self) -> PixelFormat { self.pf.clone() } } unsafe impl Send for Context {} unsafe impl Sync for Context {} pub tra...
GlAttributes, NotCurrent, PixelFormat, PixelFormatRequirements, Rect, }; use tao::dpi; use tao::event_loop::EventLoopWindowTarget; use tao::window::{Window, WindowBuilder}; use tao::platform::unix::*; use gdk::GLContext; use gtk::prelude::*; use gtk::GLArea; use gtk::builders::GLAreaBuilder; use std::marker::Pha...
random
[ { "content": "fn validate_version(version: u8) -> Result<ffi::NSUInteger, CreationError> {\n\n let version = version as ffi::NSUInteger;\n\n if version >= ffi::kEAGLRenderingAPIOpenGLES1 && version <= ffi::kEAGLRenderingAPIOpenGLES3 {\n\n Ok(version)\n\n } else {\n\n Err(CreationError::Os...
Rust
src/ci.rs
m-hilgendorf/midi2
6a95a8d8b0303e6d9d67e3801ad1c61aad1b7490
use crate::muid::MUID; #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] pub struct DeviceDiscovery { pub muid: MUID, pub manufacturer: [u8; 3], pub family: [u8; 2], pub model: [u8; 2], pub revision: u32, pub ci_support: u8, pub max_sysex_size: u32, } ...
use crate::muid::MUID; #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] pub struct DeviceDiscovery { pub muid: MUID, pub manufacturer: [u8; 3], pub family: [u8; 2], pub model: [u8; 2], pub revision: u32, pub ci_support: u8, pub max_sysex_size: u32, } ...
|= 0b0000_1000; self } } #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] pub struct SetNewProtocol { pub protocol:Protocol, pub authority:u8 } impl SetNewProtocol { pub fn new(p:Protocol, a:AuthorityLevel) -> Self { Self { protocol: p, authority: a as ...
-> Self { self.preferred = p; self } } impl DeviceDiscovery { pub fn new(muid: MUID) -> Self { Self { muid, manufacturer: [0; 3], family: [0; 2], model: [0; 2], revision: 0, ci_support: 0, max_...
random
[ { "content": "#[cfg(not(feature = \"no-std\"))]\n\npub fn new_muid() -> u32 {\n\n use std::thread;\n\n use std::time;\n\n thread::sleep(time::Duration::from_millis(1));\n\n let mut id = BROADCAST;\n\n while id >= 0x0fff_fff0 {\n\n let now = (time::SystemTime::now()\n\n .duration...
Rust
benches/trying.rs
garypen/trying
c6f17f0e1db50d42c5e0731094d7bf6c16a240aa
use trying::trie::{Trie, TrieAtom, TrieValue}; use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput}; use rand::{ distributions::{Alphanumeric, Standard}, thread_rng, Rng, }; fn get_text() -> Vec<String> { use std::fs::File; use std::io::Read; const DATA: ...
use trying::trie::{Trie, TrieAtom, TrieValue}; use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput}; use rand::{ distributions::{Alphanumeric, Standard}, thread_rng, Rng, }; fn get_text() -> Vec<String> { use std::fs::File; use std::io::Read; const DATA: ...
ar, usize> = Trie::new(); for _i in 0..POPULATION_SIZE { let entry: Vec<char> = thread_rng() .sample_iter(&Alphanumeric) .take(thread_rng().gen_range(1..=size)) .map(char::from) .collect()...
2 * BASE_SIZE, 4 * BASE_SIZE, 8 * BASE_SIZE, 16 * BASE_SIZE, 32 * BASE_SIZE, 64 * BASE_SIZE, ] .iter() { group.throughput(Throughput::Bytes(*size as u64)); group.bench_with_input( BenchmarkId::new("consuming iteration (char)", size), ...
function_block-random_span
[ { "content": "fn main() {\n\n static POPULATION_SIZE: usize = 10;\n\n static SIZE: usize = 10;\n\n\n\n // Create our trie and a collection of searches\n\n let mut trie = Trie::new();\n\n let mut searches = vec![];\n\n\n\n // Store 10 random strings (char sequences)\n\n // composed of betwee...
Rust
src/read/levels.rs
Dandandan/parquet2
20a1fb9d705c827e045504a5d5cb01537ba07c27
use crate::encoding::{bitpacking, get_length, hybrid_rle}; #[inline] pub fn get_bit_width(max_level: i16) -> u32 { 16 - max_level.leading_zeros() } enum DecoderState<'a> { Bitpacking(bitpacking::Decoder<'a>), Rle { value: u32, length: usize }, Finished, } pub struct RLEDecoder<'a> { runner: hybri...
use crate::encoding::{bitpacking, get_length, hybrid_rle}; #[inline] pub fn get_bit_width(max_level: i16) -> u32 { 16 - max_level.leading_zeros() } enum DecoderState<'a> { Bitpacking(bitpacking::Decoder<'a>), Rle { value: u32, length: usize }, Finished, } pub struct RLEDecoder<'a> { runner: hybri...
} }; if next.is_none() { self.load_run() } self.length_so_far += 1; next } fn size_hint(&self) -> (usize, Option<usize>) { (self.length, Some(self.length)) } } impl<'a> ExactSizeIterator for RLEDecoder<'a> {} #[inline] pub fn split...
if *length == 0 { None } else { *length -= 1; Some(*value) }
if_condition
[ { "content": "/// # Panics\n\n/// This function panics iff `values.len() < 4`.\n\npub fn get_length(values: &[u8]) -> u32 {\n\n u32::from_le_bytes(values[0..4].try_into().unwrap())\n\n}\n\n\n\n/// Returns the ceil of value/divisor\n", "file_path": "src/encoding/mod.rs", "rank": 0, "score": 319629...
Rust
macros/src/dump.rs
nox/naam
86e83238ae4003790e31964068b66b3075470e22
use proc_macro2::{Span, TokenStream}; use quote::quote; use std::borrow::Cow; use syn::visit; use syn::{Fields, Lifetime}; use synstructure::{BindingInfo, Structure}; pub(crate) fn derive(mut s: Structure) -> TokenStream { let tape_lt = s .ast() .generics .lifetimes() .find(|def| de...
use proc_macro2::{Span, TokenStream}; use quote::quote; use std::borrow::Cow; use syn::visit; use syn::{Fields, Lifetime}; use synstructure::{BindingInfo, Structure}; pub(crate) fn derive(mut s: Structure) -> TokenStream { let tape_lt = s .ast() .generics .lifetimes() .find(|def| de...
} impl<'ast> visit::Visit<'ast> for TypeClassifier<'_> { fn visit_lifetime(&mut self, lt: &'ast Lifetime) { self.should_use_debug_bridge |= self.tape_lt == Some(lt); visit::visit_lifetime(self, lt); } }
fn has_tape_lifetime_param(&mut self, b: &BindingInfo<'_>) -> bool { if self.tape_lt.is_none() { return false; } self.should_use_debug_bridge = false; visit::Visit::visit_type(self, &b.ast().ty); self.should_use_debug_bridge }
function_block-full_function
[ { "content": "type OpaqueExec<'tape, Ram, Out> = unsafe fn(Addr<'tape>, Runner<'tape>, &mut Ram) -> Out;\n", "file_path": "src/cpu.rs", "rank": 0, "score": 77913.24652865322 }, { "content": "#[derive(Clone, Copy, Debug, Dump)]\n\nstruct Return(usize);\n\n\n\nimpl<'tape> Execute<'tape, SayItN...
Rust
src/mnemonic_type.rs
ChosunOne/bip39-rs
e9b8fc39b033c40c22efa8fbb77df9f99b01f5d9
use ::error::{Error, ErrorKind}; use std::fmt; #[derive(Debug, Copy, Clone)] pub enum MnemonicType { Type12Words, Type15Words, Type18Words, Type21Words, Type24Words } impl MnemonicType { pub fn for_word_count(size: usize) -> Result<Mnemoni...
use ::error::{Error, ErrorKind}; use std::fmt; #[derive(Debug, Copy, Clone)] pub enum MnemonicType { Type12Words, Type15Words, Type18Words, Type21Words, Type24Words } impl MnemonicType { pub fn for_word_count(size: usize) -> Result<Mnemoni...
pub fn entropy_bits(&self) -> usize { let entropy_bits: usize = match *self { MnemonicType::Type12Words => 128, MnemonicType::Type15Words => 160, MnemonicType::Type18Words => 192, MnemonicType...
e::Type15Words => 165, MnemonicType::Type18Words => 198, MnemonicType::Type21Words => 231, MnemonicType::Type24Words => 264 }; total_bits }
function_block-function_prefixed
[ { "content": "use mnemonic_type::MnemonicType;\n\n\n\nerror_chain! {\n\n foreign_links {\n\n EntropyUnavailable(::std::io::Error);\n\n DataDecode(::data_encoding::DecodeError);\n\n }\n\n\n\n errors {\n\n InvalidChecksum {\n\n description(\"invalid checksum\")\n\n ...
Rust
backend/tests/web_tests/item.rs
bsikar/pos-system
58537cc47f0373e968d4622d5d8b51110ef89536
use crate::app::web::item::{item_rest_filters, Item}; use crate::app::App as ModelApp; use actix_web::test::{self, TestRequest}; use actix_web::{web::Data, App}; use serde_json::{json, Value as JsonValue}; #[actix_rt::test] async fn web_item_list_all() { let conn = ModelApp::new().unwrap().database.establish_db_co...
use crate::app::web::item::{item_rest_filters, Item}; use crate::app::App as ModelApp; use actix_web::test::{self, TestRequest}; use actix_web::{web::Data, App}; use serde_json::{json, Value as JsonValue}; #[actix_rt::test] async fn web_item_list_all() { let conn = ModelApp::new().unwrap().database.establish_db_co...
app = App::new() .app_data(Data::new(conn)) .configure(item_rest_filters); let app = test::init_service(app).await; let resp = TestRequest::post() .uri("/api/items") .set_json(&json!({"name": "single donut hole", "price": 30, "tax": 1.0, "type": "food"})) .send_request...
.0, "type": "other"}, {"name": "painting three", "price": 7500, "tax": 1.0, "type": "other"}, ]); for i in 0..body.len() { assert_eq!(body[i].name, json[i]["name"].as_str().unwrap()); assert_eq!(body[i].price, json[i]["price"].as_i64().unwrap() as i32); assert_eq!(body[i].tax, j...
random
[ { "content": "pub fn item_rest_filters(cfg: &mut actix_web::web::ServiceConfig) {\n\n cfg.service(create);\n\n cfg.service(list);\n\n cfg.service(list_food);\n\n cfg.service(list_drink);\n\n cfg.service(list_other);\n\n cfg.service(get);\n\n cfg.service(update);\n\n cfg.service(delete);\...
Rust
src/c_vec.rs
GuillaumeGomez/c_vec-rs
abb7b41589ab8be0dedf8c45f2579ff3872bc993
use std::marker::PhantomData; use std::ops::{Index, IndexMut}; use std::slice; use crate::{CSlice, CSliceMut}; pub struct CVecIter<'a, T: 'a> { inner: &'a CVec<T>, pos: usize, } impl<'a, T> Iterator for CVecIter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { if self...
use std::marker::PhantomData; use std::ops::{Index, IndexMut}; use std::slice; use crate::{CSlice, CSliceMut}; pub struct CVecIter<'a, T: 'a> { inner: &'a CVec<T>, pos: usize, } impl<'a, T> Iterator for CVecIter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { if self...
pub unsafe fn get_unchecked(&self, ofs: usize) -> &T { &*self.base.add(ofs) } pub fn get_mut(&mut self, ofs: usize) -> Option<&mut T> { if ...
pub fn get(&self, ofs: usize) -> Option<&T> { if ofs < self.len { Some(unsafe { &*self.base.add(ofs) }) } else { None } }
function_block-full_function
[ { "content": "/// let iter = cslice.iter();\n\n/// ```\n\npub struct CSliceMutIter<'a, 'b, T> {\n\n inner: &'b CSliceMut<'a, T>,\n\n pos: usize,\n\n}\n\n\n\nimpl<'a, 'b, T> Iterator for CSliceMutIter<'a, 'b, T> {\n\n type Item = &'b T;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n if...
Rust
spanner/src/transaction_rw.rs
yoshidan/google-cloud-rust
7209a94c22f91dbb5b4efea4f86bedc7e481cf16
use std::ops::Deref; use std::ops::DerefMut; use std::sync::atomic::{AtomicI64, Ordering}; use google_cloud_gax::cancel::CancellationToken; use prost_types::Struct; use crate::session::ManagedSession; use crate::statement::Statement; use crate::transaction::{CallOptions, QueryOptions, Transaction}; use crate::value::...
use std::ops::Deref; use std::ops::DerefMut; use std::sync::atomic::{AtomicI64, Ordering}; use google_cloud_gax::cancel::CancellationToken; use prost_types::Struct; use crate::session::ManagedSession; use crate::statement::Statement; use crate::transaction::{CallOptions, QueryOptions, Transaction}; use crate::value::...
pub async fn rollback(&mut self, cancel: Option<CancellationToken>, retry: Option<RetrySetting>) { let request = RollbackRequest { transaction_id: self.tx_id.clone(), session: self.get_session_name(), }; let session = self.as_mut_session(); let result = sess...
let tx_id = self.tx_id.clone(); let mutations = self.wb.to_vec(); let session = self.as_mut_session(); return commit(session, mutations, TransactionId(tx_id), options).await; }
function_block-function_prefix_line
[ { "content": "/// update_struct returns a Mutation to update a row in a table, specified by a Go\n\n/// struct. If the row does not already exist, the write or transaction fails.\n\npub fn update_struct(table: &str, to_struct: impl ToStruct) -> Mutation {\n\n Mutation {\n\n operation: Some(Operation::...
Rust
pleco/src/board/fen.rs
MakotoE/Pleco
278a73d7e0f0e52b397e16640c1f9f73db266e2c
use super::{Board,FenBuildError}; use {BitBoard, PieceType, Player, Rank, SQ}; use super::super::core::sq::NO_SQ; pub const OPENING_POS_FEN: &str = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; #[doc(hidden)] pub static STANDARD_FENS_START_POS: [&'static str; 1] = [OPENING_POS_FEN]; #[doc(hidden)] pu...
use super::{Board,FenBuildError}; use {BitBoard, PieceType, Player, Rank, SQ}; use super::super::core::sq::NO_SQ; pub const OPENING_POS_FEN: &str = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; #[doc(hidden)] pub static STANDARD_FENS_START_POS: [&'static str; 1] = [OPENING_POS_FEN]; #[doc(hidden)] pu...
itBoard = board.piece_bb_both_players(PieceType::P) & (BitBoard::RANK_1 | BitBoard::RANK_8 ); if all_pawns.is_not_empty() { return Err(FenBuildError::PawnOnLastRow); } let white_pawns = board.count_piece(Player::White, PieceType::P); let black_pawns = board.count_piece(Player::Black,...
.type_of(); if piece_1 == PieceType::P { if piece_2 == PieceType::B || piece_2 == PieceType::N || piece_2 == PieceType::P { return Err(FenBuildError::IllegalCheckState { piece_1, piece_2 }); } } else if piece_1 == PieceType::B && (piece_2 == PieceType::P...
function_block-random_span
[ { "content": "#[inline(always)]\n\npub fn forward_rank_bb(player: Player, rank: Rank) -> BitBoard {\n\n BitBoard(boards::forward_rank_bb(player,rank))\n\n}\n\n\n\n/// Returns the `BitBoard` of all squares that can be attacked by a pawn\n\n/// of the same color when it moves along its file, starting from the\...
Rust
src/ccp/client_socket.rs
angel-manuel/curved_gear
30df6919777e893e5c71d48f7cd69eef59d1f8f7
use std::net::SocketAddr; use mioco::udp::UdpSocket; use ::Result; use identity::{Identity, Extension, RemoteServer, DomainName}; use packet::*; use keys::*; use boxes::*; use nonces::*; pub struct ClientSocket { my_extension: Extension, my_short_term_pk: client_short_term::PublicKey, precomputed_key: Pr...
use std::net::SocketAddr; use mioco::udp::UdpSocket; use ::Result; use identity::{Identity, Extension, RemoteServer, DomainName}; use packet::*; use keys::*; use boxes::*; use nonces::*; pub struct ClientSocket { my_extension: Extension, my_short_term_pk: client_short_term::PublicKey, precomputed_key: Pr...
t client_msg_packet: Packet = ClientMessagePacket { server_extension: self.server_extension.clone(), client_extension: self.my_extension.clone(), client_short_term_pk: self.my_short_term_pk.clone(), payload_box: ClientMessageBox::seal_precomputed(msg, &self.next_send_nonc...
ce, &server_long_term_pk, &my_short_term_sk), }.into(); next_send_nonce.increment(); try!(hello_packet.send(&mut sock, &server_addr)); loop { let (packet, rem_addr) = try!(Packet::recv(&mut sock)); if let Packet::Cookie(cookie_packet) = packet { ...
random
[ { "content": "pub trait PacketIO {\n\n fn recv(&mut self, buf: &mut [u8]) -> io::Result<usize>;\n\n fn send(&mut self, buf: &[u8]) -> io::Result<usize>;\n\n}\n\n\n", "file_path": "src/logic/streamer.rs", "rank": 0, "score": 48265.028796943865 }, { "content": "fn main() {\n\n env_log...
Rust
src/endpoints/users.rs
krywicki/actix-web-api-rs
6a45e9d519392fb46a7ecd091a9016a7de961dc9
use actix_web::{http::StatusCode, web, Responder}; use mongodb::{ bson::doc, options::{FindOneAndUpdateOptions, ReturnDocument}, Database, }; use serde::{Deserialize, Serialize}; use crate::{ fields::{EmailOrObjectId, FromPath}, models::User, schemas::{Page, PageBuilder}, web::Query, Mo...
use actix_web::{http::StatusCode, web, Responder}; use mongodb::{ bson::doc, options::{FindOneAndUpdateOptions, ReturnDocument}, Database, }; use serde::{Deserialize, Serialize}; use crate::{ fields::{EmailOrObjectId, FromPath}, models::User, schemas::{Page, PageBuilder}, web::Query, Mo...
) } fn mongo_filter(&self) -> Result<Option<mongodb::bson::Document>, RequestError> { Ok(None) } } } mod body { use super::*; use mongodb::options::UpdateModifications; use validator::Validate; use crate::{error::ErrorCode, validators}; #[derive(Serialize,...
Some( FindOptions::builder() .limit(self.page_params.limit) .sort(sort) .build(), )
call_expression
[ { "content": "pub fn validate_iso_8601(value: &str) -> Result<(), ValidationError> {\n\n lazy_static! {\n\n static ref RE: Regex = Regex::new(r\"^([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6]))...
Rust
src/serial/bluetooth_usart.rs
Offpics/anne-key
73f4d4e0fc542dd501afc28df8b5b332e6683ccb
use embedded_hal::digital::OutputPin; use hal::dma::dma1::{C6, C7}; use hal::gpio::gpioa::{PA1, PA2, PA3}; use hal::gpio::{Alternate, Input, Output}; use stm32l1::stm32l151::{RCC, USART2}; use crate::serial::DmaUsart; pub struct BluetoothUsart { pa1: PA1<Output>, _pa2: PA2<Alternate>, _pa3: PA3<Alternate>...
use embedded_hal::digital::OutputPin; use hal::dma::dma1::{C6, C7}; use hal::gpio::gpioa::{PA1, PA2, PA3}; use hal::gpio::{Alternate, Input, Output}; use stm32l1::stm32l151::{RCC, USART2}; use crate::serial::DmaUsart; pub struct BluetoothUsart { pa1: PA1<Output>, _pa2: PA2<Alternate>, _pa3: PA3<Alternate>...
fn is_send_ready(&mut self) -> bool { self.dma_tx.cndtr().read().ndt().bits() == 0 || self.pending_tx != 0 } fn send(&mut self, buffer: u32, len: u16) { self.dma_tx.cmar().write(|w| unsafe { w.ma().bits(buffer) }); if self.pending_tx == 0 { ...
self.dma_rx .cndtr() .modify(|_, w| unsafe { w.ndt().bits(length) }); self.dma_rx.ccr().modify(|_, w| w.en().set_bit()); }
function_block-function_prefix_line
[ { "content": "pub fn enable_tick(syst: &mut stm32l151::SYST, reload: u32) {\n\n syst.set_clock_source(cortex_m::peripheral::syst::SystClkSource::Core);\n\n syst.set_reload(reload);\n\n syst.enable_interrupt();\n\n syst.enable_counter();\n\n}\n", "file_path": "src/clock.rs", "rank": 0, "s...
Rust
conjure-codegen/src/objects/builder/mod.rs
svc-excavator-bot-org/conjure-rust
e1d90aeec1d8a8dc5d91c64778d6b7f64191ca6c
use crate::context::{CollectionSetterBounds, CollectionType, Context, SetterBounds}; use crate::types::{FieldDefinition, ObjectDefinition}; use proc_macro2::{Ident, TokenStream}; use quote::quote; use std::collections::HashSet; mod fallible; mod staged; pub fn generate(ctx: &Context, def: &ObjectDefinition) -> Toke...
use crate::context::{CollectionSetterBounds, CollectionType, Context, SetterBounds}; use crate::types::{FieldDefinition, ObjectDefinition}; use proc_macro2::{Ident, TokenStream}; use quote::quote; use std::collections::HashSet; mod fallible; mod staged;
fn field_names(ctx: &Context, def: &ObjectDefinition) -> HashSet<String> { def.fields() .iter() .map(|f| ctx.field_name(f.field_name()).to_string()) .collect() } struct Setter { name: Ident, params: TokenStream, args: Vec<SetterArg>, where_: TokenStream, op: SetterOp, ...
pub fn generate(ctx: &Context, def: &ObjectDefinition) -> TokenStream { if ctx.staged_builders() { staged::generate(ctx, def) } else { fallible::generate(ctx, def) } }
function_block-full_function
[ { "content": "fn stage_name(ctx: &Context, def: &ObjectDefinition, stage: usize) -> Ident {\n\n let mut name = format!(\"Stage{}\", stage);\n\n if ctx.type_name(def.type_name().name()) == name {\n\n name.push('_');\n\n }\n\n\n\n Ident::new(&name, Span::call_site())\n\n}\n\n\n", "file_path...
Rust
src/handlers/signup.rs
ohsayan/jotsy
9b47a4d2195d7534d5dd21dcb0489a862f5bb08e
/* * Copyright (c) 2022, Sayan Nandan <nandansayan@outlook.com> * * 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...
/* * Copyright (c) 2022, Sayan Nandan <nandansayan@outlook.com> * * 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...
; } if data.password.len() < 8 { return resp( StatusCode::UNPROCESSABLE_ENTITY, SignupPage::render_new("Passwords must have atleast 8 characters"), ); } let hash = util::bcrypt_hash(&data.password); let mut con = db.get().await?; con.switch(crate::TABLE_AU...
resp( StatusCode::UNPROCESSABLE_ENTITY, SignupPage::render_new("The passwords do not match"), )
call_expression
[ { "content": "pub fn resp(code: StatusCode, body: impl ToString) -> crate::JotsyResponse {\n\n Ok((code, Html::from(body.to_string())))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 128503.35645875099 }, { "content": "pub fn create_cookie(name: impl ToString, value: impl To...
Rust
xtask/bench/src/lib.rs
zzzgydi/tools
d5b34b19e788952b585fa0d061f4ef687b0926ff
mod features; mod utils; use rslint_parser::{parse, Syntax}; use std::fmt::{Display, Formatter}; use std::str::FromStr; use std::time::Duration; pub use crate::features::formatter::benchmark_format_lib; use crate::features::formatter::{run_format, FormatterMeasurement}; pub use crate::features::parser::benchmark_pars...
mod features; mod utils; use rslint_parser::{parse, Syntax}; use std::fmt::{Display, Formatter}; use std::str::FromStr; use std::time::Duration; pub use crate::features::formatter::benchmark_format_lib; use crate::features::formatter::{run_format, FormatterMeasurement}; pub use crate::features::parser::benchmark_pars...
} impl Display for BenchmarkSummary { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { BenchmarkSummary::Parser(result) => std::fmt::Display::fmt(&result, f), BenchmarkSummary::Formatter(result) => std::fmt::Display::fmt(&result, f), } } } fn err...
pub fn summary(&self) -> String { match self { BenchmarkSummary::Parser(result) => result.summary(), BenchmarkSummary::Formatter(result) => result.summary(), } }
function_block-full_function
[ { "content": "pub fn parse_ts_type_arguments_in_expression(p: &mut Parser) -> ParsedSyntax {\n\n // Don't parse type arguments in JS because the syntax is ambiguous\n\n // https://github.com/microsoft/TypeScript/issues/36662\n\n\n\n // test type_arguments_like_expression\n\n // ((0)<5>(6))\n\n\n\n ...
Rust
src/linux/thread_info.rs
EmbarkStudios/minidump_writer_linux
0083d50662ae298093e56029e42b9cdb9b08b55b
use crate::errors::ThreadInfoError; use nix::{errno::Errno, sys::ptrace, unistd}; use std::{ io::{self, BufRead}, path, }; type Result<T> = std::result::Result<T, ThreadInfoError>; pub type Pid = i32; cfg_if::cfg_if! { if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { mod x86; ...
use crate::errors::ThreadInfoError; use nix::{errno::Errno, sys::ptrace, unistd}; use std::{ io::{self, BufRead}, path, }; type Result<T> = std::result::Result<T, ThreadInfoError>; pub type Pid = i32; cfg_if::cfg_if! { if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] { mod x86; ...
} impl ThreadInfo { pub fn create(pid: Pid, tid: Pid) -> std::result::Result<Self, ThreadInfoError> { Self::create_impl(pid, tid) } }
fn ptrace_peek( request: ptrace::Request, pid: unistd::Pid, addr: ptrace::AddressType, data: *mut libc::c_void, ) -> nix::Result<libc::c_long> { let ret = unsafe { Errno::clear(); libc::ptrace( request as ptrace::RequestType, ...
function_block-full_function
[ { "content": "pub fn late_process_mappings(pid: Pid, mappings: &mut [MappingInfo]) -> Result<()> {\n\n // Only consider exec mappings that indicate a file path was mapped, and\n\n // where the ELF header indicates a mapped shared library.\n\n for mut map in mappings\n\n .iter_mut()\n\n .f...
Rust
crates/serenity/src/gateway/mod.rs
Kixiron/Discordant
d9a9d37d397769eca4dc0219157fc656f6f7986a
mod error; mod shard; mod ws_client_ext; pub use self::{ error::Error as GatewayError, shard::Shard, ws_client_ext::WebSocketGatewayClientExt, }; use crate::model::{gateway::Activity, user::OnlineStatus}; use serde_json::Value; use std::fmt::{Display, Formatter, Result as FmtResult}; use tungstenite::protocol::...
mod error; mod shard; mod ws_client_ext; pub use self::{ error::Error as GatewayError, shard::Shard, ws_client_ext::WebSocketGatewayClientExt, }; use crate::model::{gateway::Activity, user::OnlineStatus}; use serde_json::Value; use std::fmt::{Display, Formatter, Result as FmtResult}; use tungstenite::protocol::...
} impl Display for ConnectionStage { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { use self::ConnectionStage::*; f.write_str(match *self { Connected => "connected", Connecting => "connecting", Disconnected => "disconnected", Handshake => "hand...
pub fn is_connecting(self) -> bool { use self::ConnectionStage::*; match self { Connecting | Handshake | Identifying | Resuming => true, Connected | Disconnected => false, __Nonexhaustive => unreachable!(), } }
function_block-full_function
[ { "content": "/// Validates that a token is likely in a valid format.\n\n///\n\n/// This performs the following checks on a given token:\n\n///\n\n/// - At least one character long;\n\n/// - Contains 3 parts (split by the period char `'.'`);\n\n/// - The second part of the token is at least 6 characters long;\n...
Rust
tests/integrations/server/gc_worker.rs
Joyinqin/tikv
308c641fce76c65313f9ffa491f0b4a5be8b1f70
use grpcio::{ChannelBuilder, Environment}; use kvproto::{kvrpcpb::*, metapb, tikvpb::TikvClient}; use test_raftstore::*; use tikv_util::{collections::HashMap, HandyRwLock}; use std::sync::Arc; #[test] fn test_physical_scan_lock() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); let kv...
use grpcio::{ChannelBuilder, Environment}; use kvproto::{kvrpcpb::*, metapb, tikvpb::TikvClient}; use test_raftstore::*; use tikv_util::{collections::HashMap, HandyRwLock}; use std::sync::Arc; #[test] fn test_physical_scan_lock() { let (_cluster, client, ctx) = must_new_cluster_and_kv_client(); let kv...
register_lock_observer(c, safe_point); assert!(must_check_lock_observer(c, safe_point, true).is_empty()); }); let key = b"key0"; must_kv_prewrite( &leader_client, ctx.clone(), vec![new_mutation(Op::Put, key, &b"v".repeat(1024))], key.to_vec(), 1, ); ...
_lock_ttl(3000); lock_info.set_lock_type(Op::Put); lock_info.set_min_commit_ts(ts + 1); lock_info }) .collect(); let check_result = |got_locks: &[_], expected_locks: &[_]| { for i in 0..std::cmp::max(got_locks.len(), expected_locks.len()) { as...
random
[ { "content": "pub fn must_kv_pessimistic_rollback(client: &TikvClient, ctx: Context, key: Vec<u8>, ts: u64) {\n\n let mut req = PessimisticRollbackRequest::default();\n\n req.set_context(ctx);\n\n req.set_keys(vec![key].into_iter().collect());\n\n req.start_version = ts;\n\n req.for_update_ts = t...
Rust
rust/src/hook/closure.rs
timaghostov/exchange_sign_hook
ae993748c9c22ff10be819f232a5f7eb4f8f578a
use std::sync::Arc; use erased_serde::Serialize; use crate::hook::model::DataBinance; use crate::hook::model::DataBinancePay; use crate::hook::model::DataKraken; use crate::hook::model::Query; use crate::hook::types::AppSign; use crate::hook::types::AsyncResult; use crate::hook::types::FnClosureBinance; use crate::ho...
use std::sync::Arc; use erased_serde::Serialize; use crate::hook::model::DataBinance; use crate::hook::model::DataBinancePay; use crate::hook::model::DataKraken; use crate::hook::model::Query; use crate::hook::types::AppSign; use crate::hook::types::AsyncResult; use crate::hook::types::FnClosureBinance; use crate::ho...
, ExchangeClosure::Closure(ref closure) => (closure)(self.app.box_clone(), data), } } fn sign_kraken(&self, data: DataKraken) -> FnResult { match self.kraken { ExchangeClosure::Stub => AsyncResult::error("Kraken closure missing."), ExchangeClosure::Closure(re...
params: Box::new(params), }; let inner = Arc::clone(&self.inner); (*inner).sign_binance_pay(data) } pub fn sign_binance(&self, query: Query) -> FnResult { let data = DataBinance { query }; let inner = Arc::clone(&self.inner); (*inner).sign_binance(data) ...
random
[ { "content": "type FnClosure<Data> = Box<dyn Fn(Box<dyn AppSign>, Data) -> FnResult + Send + Sync>;\n\n\n\npub type FnClosureBinancePay = FnClosure<DataBinancePay>;\n\npub type FnClosureBinance = FnClosure<DataBinance>;\n\npub type FnClosureKraken = FnClosure<DataKraken>;\n\n\n\npub struct AsyncResult;\n\n\n\ni...
Rust
packages/sycamore/src/utils/render.rs
flowtr/syacmore
e8aed499bb5116f699cfbac1627884944011d4b4
use std::rc::Rc; use ahash::AHashMap; use wasm_bindgen::UnwrapThrowExt; use crate::generic_node::GenericNode; use crate::reactive::*; use crate::view::{View, ViewType}; pub fn insert<G: GenericNode>( ctx: ScopeRef<'_>, parent: &G, accessor: View<G>, initial: Option<View<G>>, marker: Option<&G>,...
use std::rc::Rc; use ahash::AHashMap; use wasm_bindgen::UnwrapThrowExt; use crate::generic_node::GenericNode; use crate::reactive::*; use crate::view::{View, ViewType}; pub fn insert<G: GenericNode>( ctx: ScopeRef<'_>, parent: &G, accessor: View<G>, initial: Option<View<G>>, marker: Option<&G>,...
} } let b_len = b.len(); let mut a_end = a.len(); let mut b_end = b_len; let mut a_start = 0; let mut b_start = 0; let mut map = None::<AHashMap<G, usize>>; let after = a[a_end - 1].next_sibling(); while a_start < a_end || b_start < b_end { if a_end == a_star...
if node.parent_node().as_ref() != Some(parent) { panic!( "node {} in existing nodes Vec is not a child of parent. node = {:#?}", i, node ); }
if_condition
[]
Rust
src/libos/crates/async-io/src/socket/addr/mod.rs
tatetian/ngo2
4cb6a0cd9ff1caa1825c2321c1c8d6aa4848b5a3
use std::fmt::Debug; use super::Domain; use crate::prelude::*; mod c_sock_addr; mod ipv4; mod unix; pub trait Addr: Clone + Debug + PartialEq + Send + Sync { fn domain() -> Domain where Self: Sized; fn from_c_storage(c_addr: &libc::sockaddr_storage, c_addr_len: usize) ->...
use std::fmt::Debug; use super::Domain; use crate::prelude::*; mod c_sock_addr; mod ipv4; mod unix; pub trait Addr: Clone + Debug + PartialEq + Send + Sync { fn domain() -> Domain where Self: Sized; fn from_c_storage(c_addr: &libc::sockaddr_storage, c_addr_len: usize) ->...
#[test] fn unix_unnamed_to_and_from_c() { let c_addr = libc::sockaddr_un { sun_family: libc::AF_UNIX as _, sun_path: [0; 108], }; let c_addr_len = size_of::<libc::sa_family_t>() + 0; let addr = UnixAddr::Unnamed; check_to_and_from_c(&(c_addr, c...
fn ipv4_to_and_from_c() { let addr = [127u8, 0, 0, 1]; let port = 8888u16; let c_addr = libc::sockaddr_in { sin_family: libc::AF_INET as _, sin_port: port.to_be(), sin_addr: libc::in_addr { s_addr: u32::from_be_bytes(addr).to_be(), ...
function_block-full_function
[ { "content": "pub trait Signal: Send + Sync + Debug {\n\n /// Returns the number of the signal.\n\n fn num(&self) -> SigNum;\n\n\n\n /// Returns the siginfo_t that gives more details about a signal.\n\n fn to_info(&self) -> siginfo_t;\n\n}\n", "file_path": "src/libos/src/signal/signals/mod.rs", ...
Rust
benches/membership_hash.rs
m0bi5/cpsnarks-set
f48aa4d7a9d91a3de8df3fe68e6adb09b16d3c7e
use accumulator::group::Rsa2048; use accumulator::{group::Group, AccumulatorWithoutHashToPrime}; use algebra::{ bls12_381::{Bls12_381, Fr, G1Projective}, PrimeField, }; use cpsnarks_set::{ commitments::Commitment, parameters::Parameters, protocols::{ hash_to_prime::{ snark_hash::...
use accumulator::group::Rsa2048; use accumulator::{group::Group, AccumulatorWithoutHashToPrime}; use algebra::{ bls12_381::{Bls12_381, Fr, G1Projective}, PrimeField, }; use cpsnarks_set::{ commitments::Commitment, parameters::Parameters, protocols::{ hash_to_prime::{ snark_hash::...
criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
pub fn criterion_benchmark(c: &mut Criterion) { let params = Parameters::from_curve::<Fr>().unwrap().0; println!("params: {}", params); let mut rng1 = RandState::new(); rng1.seed(&Integer::from(13)); let mut rng2 = thread_rng(); let crs = cpsnarks_set::protocols::membership::Protocol::< ...
function_block-full_function
[ { "content": "pub fn criterion_benchmark(c: &mut Criterion) {\n\n let params = Parameters::from_curve_and_small_prime_size::<Scalar>(60, 70)\n\n .unwrap()\n\n .0;\n\n println!(\"params: {}\", params);\n\n let mut rng1 = RandState::new();\n\n rng1.seed(&Integer::from(13));\n\n let mu...
Rust
src/allocator/harvester_allocator.rs
Blake-Latchford/screeps-rust
14f08b3b38d9d6f3b5d4178111025b5263f3e5e9
use log::*; use screeps::{find, prelude::*, HasId, Part, RawObjectId, Source}; use std::collections::HashMap; use crate::creeps; pub fn get_description(capacity: u32) -> Option<Vec<Part>> { if get_target_source().is_none() { return None; } let mut body = vec![Part::Move, Part::Carry]; ...
use log::*; use screeps::{find, prelude::*, HasId, Part, RawObjectId, Source}; use std::collections::HashMap; use crate::creeps; pub fn get_description(capacity: u32) -> Option<Vec<Part>> { if get_target_source().is_none() { return None; } let mut body = vec![Part::Move, Part::Carry]; ...
fn get_my_sources() -> Vec<Source> { let mut sources = Vec::new(); for room in screeps::game::rooms::values() { if let Some(controller) = room.controller() { if controller.my() { sources.extend(room.find(find::SOURCES)); } } } return s...
fn source_creep_map(creep: Vec<creeps::Creep>) -> HashMap<RawObjectId, Vec<creeps::Creep>> { let mut result = HashMap::new(); for source in get_my_sources() { result.insert(source.untyped_id(), vec![]); } for harvester in creep { if let Some(source) = harvester.get_input::<Sour...
function_block-full_function
[ { "content": "pub fn get_description(capacity: u32) -> Option<Vec<Part>> {\n\n if !can_allocate_more() {\n\n return None;\n\n }\n\n\n\n let part_set = [Part::Move, Part::Carry, Part::Work];\n\n let part_set_cost: u32 = part_set.iter().map(|part| part.cost()).sum();\n\n let number_of_part_s...
Rust
core/bin/server/tests/prover_server.rs
EPICKnowledgeSociety/zksync
a29ef962342407df14a3fb2d08f2b8c90ea529c2
use std::{net, str::FromStr, thread, time, time::Duration}; use crypto_exports::pairing::ff::{Field, PrimeField}; use futures::channel::mpsc; use circuit::witness::{deposit::DepositWitness, Witness}; use models::{ config_options::ConfigurationOptions, node::{block::Block, Address}, params::total_tokens, ...
use std::{net, str::FromStr, thread, time, time::Duration}; use crypto_exports::pairing::ff::{Field, PrimeField}; use futures::channel::mpsc; use circuit::witness::{deposit::DepositWitness, Witness}; use models::{ config_options::ConfigurationOptions, node::{block::Block, Address}, params::total_tokens, ...
#[tokio::test] #[cfg_attr(not(feature = "db_test"), ignore)] async fn api_server_publish_dummy() { let prover_timeout = time::Duration::from_secs(1); let rounds_interval = time::Duration::from_secs(10); let addr = spawn_server(prover_timeout, rounds_interval).await; let client = reqwest::Client::new(...
p { let deposit_witness = DepositWitness::apply_tx( &mut circuit_tree, &models::node::operations::DepositOp { priority_op: deposit_op, account_id: 0, }, ); let deposit_operations = deposit_witness.calculate_operations(()); ...
function_block-function_prefixed
[ { "content": "pub fn address_to_stored_string(address: &Address) -> String {\n\n format!(\"0x{:x}\", address)\n\n}\n\n\n", "file_path": "core/lib/storage/src/tokens/utils.rs", "rank": 0, "score": 385045.32753105107 }, { "content": "/// Generates EthSignData for testing (not a valid signat...
Rust
simple-crud/src/main.rs
SeaQL/sea-orm-tutorial
771705d17e05c410c8333a2bc2355743f7dfef1b
mod fruits_table; use fruits_table::prelude::*; mod suppliers_table; use suppliers_table::prelude::*; use sea_orm::{entity::Set, prelude::*, ConnectionTrait, Database, Schema}; use anyhow::Result; use chrono::Utc; #[async_std::main] async fn main() -> Result<()> { let env_database_url = include_str!("../.env").t...
mod fruits_table; use fruits_table::prelude::*; mod suppliers_table; use suppliers_table::prelude::*; use sea_orm::{entity::Set, prelude::*, ConnectionTrait, Database, Schema}; use anyhow::Result; use chrono::Utc; #[async_std::main] async fn main() -> Result<()> { let env_database_url = include_str!("../.env").t...
}", fruits_by_id?); let find_pineapple = Fruits::find() .filter(FruitsColumn::Name.contains("pineapple")) .one(&db) .await?; println!("{:?}", find_pineapple.as_ref()); if let Some(pineapple_model) = find_pineapple { let mut pineapple_active_model: FruitsActiveModel = p...
e_rows = Fruits::find().all(&db).await; println!("{:?}", fruits_table_rows?); let fruits_by_id = Fruits::find_by_id(2).one(&db).await; println!("{:?
random
[ { "content": "pub mod prelude;\n\n\n\npub mod fruits;\n", "file_path": "simple-crud/src/fruits_table/mod.rs", "rank": 0, "score": 89167.64913137417 }, { "content": "pub use super::fruits::{\n\n ActiveModel as FruitsActiveModel, Column as FruitsColumn, Entity as Fruits,\n\n Model as Fru...
Rust
quic/s2n-quic-transport/src/stream/incoming_connection_flow_controller.rs
czakian/s2n-quic
c3ab570d42377e4a10084c965628d71219b1c492
use crate::{ contexts::{OnTransmitError, WriteContext}, sync::{IncrementalValueSync, ValueToFrameWriter}, transmission, }; use alloc::rc::Rc; use core::cell::RefCell; use s2n_quic_core::{ ack, frame::max_data::MaxData, packet::number::PacketNumber, stream::StreamId, transport, varint::VarInt, }; ...
use crate::{ contexts::{OnTransmitError, WriteContext}, sync::{IncrementalValueSync, ValueToFrameWriter}, transmission, }; use alloc::rc::Rc; use core::cell::RefCell; use s2n_quic_core::{ ack, frame::max_data::MaxData, packet::number::PacketNumber, stream::StreamId, transport, varint::VarInt, }; ...
} #[derive(Debug)] struct IncomingConnectionFlowControllerImpl { pub(super) read_window_sync: IncrementalValueSync<VarInt, MaxDataToFrameWriter>, pub(super) desired_flow_control_window: u32, pub(super) acquired_window: VarInt, pub(super) consumed_window: VarInt, } impl I...
fn write_value_as_frame<W: WriteContext>( &self, value: VarInt, _stream_id: StreamId, context: &mut W, ) -> Option<PacketNumber> { context.write_frame(&MaxData { maximum_data: value, }) }
function_block-full_function
[ { "content": "#[derive(Copy, Clone, Debug)]\n\nstruct Transmission {\n\n /// The range of data that was sent in this transmission\n\n offset: VarInt,\n\n /// The length of data that was sent in the transmission\n\n len: u16,\n\n /// An optional next transmission in the same packet\n\n next: Op...
Rust
escrow/src/contract.rs
puneet2019/cosmwasm-examples
ebb0012409656c14544aaa9879336ddf6423da53
use cosmwasm_std::{ generic_err, log, unauthorized, Api, BankMsg, Binary, CanonicalAddr, Coin, CosmosMsg, Env, Extern, HandleResponse, HandleResult, InitResponse, InitResult, Querier, StdResult, Storage, }; use crate::msg::{HandleMsg, InitMsg, QueryMsg}; use crate::state::{config, config_read, State}; pub fn ...
use cosmwasm_std::{ generic_err, log, unauthorized, Api, BankMsg, Binary, CanonicalAddr, Coin, CosmosMsg, Env, Extern, HandleResponse, HandleResult, InitResponse, InitResult, Querier, StdResult, Storage, }; use crate::msg::{HandleMsg, InitMsg, QueryMsg}; use crate::state::{config, config_read, State}; pub fn ...
pub fn query<S: Storage, A: Api, Q: Querier>( _deps: &Extern<S, A, Q>, msg: QueryMsg, ) -> StdResult<Binary> { match msg {} } #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies, mock_env}; use cosmwasm_std::{coins, Api, HumanAddr, StdError}; fn init...
fn send_tokens<A: Api>( api: &A, from_address: &CanonicalAddr, to_address: &CanonicalAddr, amount: Vec<Coin>, action: &str, ) -> HandleResult { let from_human = api.human_address(from_address)?; let to_human = api.human_address(to_address)?; let log = vec![log("action", action), log("to"...
function_block-full_function
[ { "content": "pub fn init<S: Storage, A: Api, Q: Querier>(\n\n deps: &mut Extern<S, A, Q>,\n\n env: Env,\n\n _msg: InitMsg,\n\n) -> InitResult {\n\n let state = State {\n\n owner: env.message.sender,\n\n };\n\n\n\n config(&mut deps.storage).save(&state)?;\n\n\n\n Ok(InitResponse::def...
Rust
components/hab/src/command/studio.rs
rrxtns/habitat
0ed0a22d8906cc7e55ca1bc2dbed7c6d4045587d
use std::env; use std::ffi::OsString; use common::ui::UI; use hcore::crypto::CACHE_KEY_PATH_ENV_VAR; use hcore::env as henv; use hcore::fs::CACHE_KEY_PATH; use hcore::os::users; use config; use error::Result; pub fn start(ui: &mut UI, args: Vec<OsString>) -> Result<()> { try!(inner::rerun_with_sudo_if_needed(u...
use std::env; use std::ffi::OsString; use common::ui::UI; use hcore::crypto::CACHE_KEY_PATH_ENV_VAR; use hcore::env as henv; use hcore::fs::CACHE_KEY_PATH; use hcore::os::users; use config; use error::Result; pub fn start(ui: &mut UI, args: Vec<OsString>) -> Result<()> { try!(inner::rerun_with_sudo_if_needed(u...
} #[cfg(not(target_os = "linux"))] mod inner { use std::env; use std::ffi::OsString; use std::process::{Command, Stdio}; use common::ui::UI; use hcore::crypto::default_cache_key_path; use hcore::env as henv; use hcore::fs::{CACHE_KEY_PATH, find_command}; use hcore::os::process; u...
Ok(try!(process::become_command(sudo_prog, args))) } None => { try!(ui.warn(format!("Could not find the `{}' command, is it in your PATH?", SUDO_CMD))); try!(ui.warn("Running Habitat Studio requires root or administrator privil...
function_block-function_prefix_line
[ { "content": "pub fn start(ui: &mut UI, args: Vec<OsString>) -> Result<()> {\n\n inner::start(ui, args)\n\n}\n\n\n\n#[cfg(target_os = \"linux\")]\n\nmod inner {\n\n use std::ffi::OsString;\n\n use std::path::PathBuf;\n\n use std::str::FromStr;\n\n\n\n use common::ui::UI;\n\n use hcore::crypto:...
Rust
components/backup/src/errors.rs
guo-shaoge/tikv
225bbdd70ea128040827a9a45d18c8518315ff12
use std::io::Error as IoError; use std::{error, result}; use engine_traits::Error as EngineTraitError; use kvproto::brpb::Error as ErrorPb; use kvproto::errorpb::{Error as RegionError, ServerIsBusy}; use kvproto::kvrpcpb::KeyError; use thiserror::Error; use tikv::storage::kv::{Error as KvError, ErrorInner as EngineE...
use std::io::Error as IoError; use std::{error, result}; use engine_traits::Error as EngineTraitError; use kvproto::brpb::Error as ErrorPb; use kvproto::errorpb::{Error as RegionError, ServerIsBusy}; use kvproto::kvrpcpb::KeyError; use thiserror::Error; use tikv::storage::kv::{Error as KvError, ErrorInner as EngineE...
vccError( box MvccErrorInner::KeyIsLocked(info), )))) => { BACKUP_RANGE_ERROR_VEC .with_label_values(&["key_is_locked"]) .inc(); let mut e = KeyError::default(); e.set_locked(info); err.se...
Error as MvccError, ErrorInner as MvccErrorInner}; use tikv::storage::txn::{Error as TxnError, ErrorInner as TxnErrorInner}; use tokio::sync::AcquireError; use crate::metrics::*; impl From<Error> for ErrorPb { fn from(e: Error) -> ErrorPb { let mut err = ErrorPb::default(); match e { ...
random
[ { "content": "pub fn extract_region_error<T>(res: &Result<T>) -> Option<errorpb::Error> {\n\n match *res {\n\n // TODO: use `Error::cause` instead.\n\n Err(Error(box ErrorInner::Kv(KvError(box KvErrorInner::Request(ref e)))))\n\n | Err(Error(box ErrorInner::Txn(TxnError(box TxnErrorInner...
Rust
src/app/components/search/search.rs
przebor/spot
2752dfa330e7263ecf81ea94c47bf21896db9a19
use gettextrs::*; use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::CompositeTemplate; use std::rc::Rc; use crate::app::components::utils::{wrap_flowbox_item, Debouncer}; use crate::app::components::{AlbumWidget, ArtistWidget, Component, EventListener}; use crate::app::dispatch::Worker; use crate::app::mode...
use gettextrs::*; use gtk::prelude::*; use gtk::subclass::prelude::*; use gtk::CompositeTemplate; use std::rc::Rc; use crate::app::components::utils::{wrap_flowbox_item, Debouncer}; use crate::app::components::{AlbumWidget, ArtistWidget, Component, EventListener}; use crate::app::dispatch::Worker; use crate::app::mode...
self.update_results(); } _ => {} } } }
rker, store: &gio::ListStore, on_artist_pressed: F) where F: Fn(&String) + Clone + 'static, { imp::SearchResultsWidget::from_instance(self) .artist_results .bind_model(Some(store), move |item| { wrap_flowbox_item(item, |artist_model| { ...
random
[ { "content": "pub fn display_add_css_provider(resource: &'static str) {\n\n CSS_ADDED.with(|set| {\n\n if set.borrow().contains(resource) {\n\n return;\n\n }\n\n\n\n set.borrow_mut().insert(resource);\n\n\n\n let provider = gtk::CssProvider::new();\n\n provider.l...
Rust
src/librustc_trans/cabi_x86_64.rs
timotree3/rust
1a8282a9b4c7cfc120dd5d3a8ea29338ff0116d0
use abi::{ArgType, CastTarget, FnType, LayoutExt, Reg, RegKind}; use context::CrateContext; use rustc::ty::layout::{self, TyLayout, Size}; #[derive(Clone, Copy, PartialEq, Debug)] enum Class { None, Int, Sse, SseUp } #[derive(Clone, Copy, Debug)] struct Memory; const LARGEST_VECTOR_SIZE: usize = 5...
use abi::{ArgType, CastTarget, FnType, LayoutExt, Reg, RegKind}; use context::CrateContext; use rustc::ty::layout::{self, TyLayout, Size}; #[derive(Clone, Copy, PartialEq, Debug)] enum Class { None, Int, Sse, SseUp } #[derive(Clone, Copy, Debug)] struct Memory; const LARGEST_VECTOR_SIZE: usize = 5...
e() { x86_64_ty(&mut fty.ret, false); } for arg in &mut fty.args { if arg.is_ignore() { continue; } x86_64_ty(arg, true); } }
function_block-function_prefixed
[]
Rust
rust-src/aux_functions.rs
Concordium/concordium-node-sdk-js
17342bb24692f2891075f7d746388db1aedae809
use crate::{helpers::*, types::*}; use crypto_common::{types::TransactionTime, *}; use dodis_yampolskiy_prf as prf; use pairing::bls12_381::{Bls12, G1}; use serde_json::{from_str, Value as SerdeValue}; use std::collections::BTreeMap; type ExampleCurve = G1; use serde::{Deserialize as SerdeDeserialize, Serialize as Serd...
use crate::{helpers::*, types::*}; use crypto_common::{types::TransactionTime, *}; use dodis_yampolskiy_prf as prf; use pairing::bls12_381::{Bls12, G1}; use serde_json::{from_str, Value as SerdeValue}; use std::collections::BTreeMap; type ExampleCurve = G1; use serde::{Deserialize as SerdeDeserialize, Serialize as Serd...
ec.insert(tag, att.clone()).is_some() { bail!("Cannot reveal an attribute more than once.") } } else { bail!("Cannot reveal an attribute which is not part of the attribute list.") } } let policy = Policy { valid_to: id_object.alist.valid_to, ...
sult<String> { let v: SerdeValue = from_str(input)?; let ip_info: IpInfo<Bls12> = try_get(&v, "ipInfo")?; let ars_infos: BTreeMap<ArIdentity, ArInfo<ExampleCurve>> = try_get(&v, "arsInfos")?; let global_context: GlobalContext<ExampleCurve> = try_get(&v, "global")?; let id_object: IdentityObject<B...
random
[ { "content": "/// Try to extract a field with a given name from the JSON value.\n\npub fn try_get<A: serde::de::DeserializeOwned>(v: &SerdeValue, fname: &str) -> Result<A> {\n\n match v.get(fname) {\n\n Some(v) => Ok(from_value(v.clone())?),\n\n None => Err(anyhow!(\"Field {} not present, but s...