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/language.rs
Xetera/ginkou-api
48e8cea435b477d9365dc736407159f00321b1b0
use std::fs::File; use std::io; use std::io::Write; use std::path::{Path, PathBuf}; use std::string::FromUtf8Error; extern crate dirs; #[macro_use] use rusqlite::params; use rusqlite::Connection; use structopt; use structopt::StructOpt; use mecab; use mecab::Tagger; const DAKUTEN_BYTES: [u8; 3] = [227, 128, 130]; con...
use std::fs::File; use std::io; use std::io::Write; use std::path::{Path, PathBuf}; use std::string::FromUtf8Error; extern crate dirs; #[macro_use] use rusqlite::params; use rusqlite::Connection; use structopt; use structopt::StructOpt; use mecab; use mecab::Tagger; const DAKUTEN_BYTES: [u8; 3] = [227, 128, 130]; con...
#[test] fn sentences_can_be_consumed() -> rusqlite::Result<()> { let conn = conn_from_memory()?; let sentence1 = "猫を見た"; let sentence2 = "犬を見る"; consume_trimmed(&conn, sentence1)?; consume_trimmed(&conn, sentence2)?; let a_sentences = vec![sentence1.into(), sent...
fn bank_lookup_works_correctly() -> rusqlite::Result<()> { let conn = conn_from_memory()?; let sentence1 = String::from("A B"); let sentence2 = String::from("A B C"); let s1 = add_sentence(&conn, &sentence1)?; add_word(&conn, "A", s1)?; add_word(&conn, "B", s1)?; ...
function_block-full_function
[ { "content": "SELECT id, ?2 FROM WORDS WHERE word=?1 AND NOT EXISTS (SELECT 1 FROM WordSentence WHERE word_id=id AND sentence_id=?2);", "file_path": "src/sql/add_word_junction.sql", "rank": 11, "score": 86279.24715323126 }, { "content": "fn main() {\n\n rocket::ignite().mount(\"/\", routes!...
Rust
corp_bot/src/main.rs
lholznagel/eve_online
7f8cc4aa46b06c0edf64f89ff5853216cf5597b7
mod asset; use appraisal::{Appraisal, Janice}; use caph_connector::{EveAuthClient, CorporationService}; use num_format::{Locale, ToFormattedString}; use reqwest::{header::{HeaderMap, HeaderValue}, Client}; use serde::Serialize; use sqlx::{PgPool, postgres::PgPoolOptions}; use tracing_subscriber::EnvFilter; const PG_A...
mod asset; use appraisal::{Appraisal, Janice}; use caph_connector::{EveAuthClient, CorporationService}; use num_format::{Locale, ToFormattedString}; use reqwest::{header::{HeaderMap, HeaderValue}, Client}; use serde::Serialize; use sqlx::{PgPool, postgres::PgPoolOptions}; use tracing_subscriber::EnvFilter; const PG_A...
ration_service = CorporationService::new(info.corporation_id.into()); let wallets = corporation_service .wallets(&client) .await .unwrap(); Wallets { master: wallets[0].balance, moon: wallets[1].balance, alliance: wallets[2].balance, } } struct Wallets...
oken IS NOT NULL AND c.corporation_id IS NOT NULL "# ) .fetch_one(pool) .await .unwrap(); let client = EveAuthClient::new(info.refresh_token).unwrap(); let corpo
function_block-random_span
[ { "content": "/// Generates the basic SQL-Query that is required for items.\n\n///\n\n/// # Returns\n\n///\n\n/// String containing the SQL-Query.\n\n///\n\nfn sql_header() -> String {\n\n r#\"DELETE FROM items CASCADE;\"#.into()\n\n}\n\n\n", "file_path": "sde_parser/src/items.rs", "rank": 1, "sc...
Rust
sdk/src/system_transaction.rs
sunnygleason/solana
1fb9ed98372dfaf8f9a6691e7ec6d5bc5577bd2a
use crate::hash::Hash; use crate::pubkey::Pubkey; use crate::signature::Keypair; use crate::system_instruction::SystemInstruction; use crate::system_program; use crate::transaction::{Instruction, Transaction}; pub struct SystemTransaction {} impl SystemTransaction { pub fn new_program_account( from...
use crate::hash::Hash; use crate::pubkey::Pubkey; use crate::signature::Keypair; use crate::system_instruction::SystemInstruction; use crate::system_program; use crate::transaction::{Instruction, Transaction}; pub struct SystemTransaction {} impl SystemTransaction { pub fn new_program_account( from...
pub fn new_move_many( from: &Keypair, moves: &[(Pubkey, u64)], last_id: Hash, fee: u64, ) -> Transaction { let instructions: Vec<_> = moves .iter() .enumerate() .map(|(i, (_, amount))| { let spend = SystemInstructi...
last_id: Hash, fee: u64, ) -> Transaction { let move_tokens = SystemInstruction::Move { tokens }; Transaction::new( from_keypair, &[to], system_program::id(), &move_tokens, last_id, fee, ) }
function_block-function_prefix_line
[ { "content": "pub fn create_ticks(num_ticks: u64, mut hash: Hash) -> Vec<Entry> {\n\n let mut ticks = Vec::with_capacity(num_ticks as usize);\n\n for _ in 0..num_ticks {\n\n let new_tick = next_entry_mut(&mut hash, 1, vec![]);\n\n ticks.push(new_tick);\n\n }\n\n\n\n ticks\n\n}\n\n\n", ...
Rust
kvserver/src/server.rs
GITHUBear/KV_Server
a3532a91f50604c6d757891ceed0f457a34f2afd
extern crate protobuf; extern crate futures; extern crate grpcio; pub mod kvprotos; use std::io::Read; use std::sync::{Arc, RwLock}; use std::{io, thread}; use std::collections::{BTreeMap, HashMap}; use futures::sync::oneshot; use futures::Future; use grpcio::{Environment, RpcContext, ServerBuilder, UnarySink}; use ...
extern crate protobuf; extern crate futures; extern crate grpcio; pub mod kvprotos; use std::io::Read; use std::sync::{Arc, RwLock}; use std::{io, thread}; use std::collections::{BTreeMap, HashMap}; use futures::sync::oneshot; use futures::Future; use grpcio::{Environment, RpcContext, ServerBuilder, UnarySink}; use ...
:new(); for (k, v) in mutengine.read().unwrap().range(key_start.clone()..key_end.clone()){ resmap.insert(k.clone(), v.clone()); } if resmap.len() != 0 { response.set_status(ResponseStatus::kSuccess); response.set_key_value(resmap); }else{ response.set_status(ResponseStatus::...
.map_err(move |err| eprintln!("Failed to reply: {:?}", err)); ctx.spawn(f) } fn put(&mut self, ctx: RpcContext, req: PutRequest, sink: UnarySink<PutResponse>){ let mut response = PutResponse::new(); println!("Received PutRequest {{ {:?} }}", req); let mutengine = &mut self.engi...
random
[ { "content": "pub fn create_kvdb<S: Kvdb + Send + Clone + 'static>(s: S) -> ::grpcio::Service {\n\n let mut builder = ::grpcio::ServiceBuilder::new();\n\n let mut instance = s.clone();\n\n builder = builder.add_unary_handler(&METHOD_KVDB_GET, move |ctx, req, resp| {\n\n instance.get(ctx, req, re...
Rust
src/main.rs
rodneylab/cmessless
7ba78963aea19b3618c60215a55745207195960f
mod parser; mod utility; use atty::{is, Stream}; use clap::Parser; use std::{ fs, io::{self, BufRead}, path::{Path, PathBuf}, }; use watchexec::{ config::{Config, ConfigBuilder}, error::Result, pathop::PathOp, run::{watch, ExecHandler, Handler}, }; use parser::{author_name_from_cargo_pkg_a...
mod parser; mod utility; use atty::{is, Stream}; use clap::Parser; use std::{ fs, io::{self, BufRead}, path::{Path, PathBuf}, }; use watchexec::{ config::{Config, ConfigBuilder}, error::Result, pathop::PathOp, run::{watch, ExecHandler, Handler}, }; use parser::{author_name_from_cargo_pkg_a...
; if output_modified == None || input_modified == None || input_modified.unwrap() > output_modified.unwrap() { modified_files.push(String::from(input_path.to_string_lossy())); } } println!("{}", modified_files.join(" ")); } fn parse_multiple_files(mdx...
match fs::metadata(output_path) { Ok(metadata_value) => match metadata_value.modified() { Ok(value) => Some(value), Err(_) => None, }, Err(_) => None, }
if_condition
[ { "content": "pub fn parse_mdx_file(input_path: &Path, output_path: &Path, verbose: bool) {\n\n println!(\"[ INFO ] Parsing {:?}...\", input_path);\n\n let start = Instant::now();\n\n\n\n let file = File::open(input_path).expect(\"[ ERROR ] Couldn't open that file!\");\n\n let frontmatter_end_line_n...
Rust
sqlx-core/src/pool/mod.rs
broomstar/sqlx
6c8fd949dd052ddbad5c4dfe343682aed9286615
use std::{ fmt, ops::{Deref, DerefMut}, sync::Arc, time::{Duration, Instant}, }; use crate::Database; use self::inner::SharedPool; pub use self::options::Builder; use self::options::Options; mod executor; mod inner; mod options; pub struct Pool<DB>(Arc<SharedPool<DB>>) where DB: Database; str...
use std::{ fmt, ops::{Deref, DerefMut}, sync::Arc, time::{Duration, Instant}, }; use crate::Database; use self::inner::SharedPool; pub use self::options::Builder; use self::options::Options; mod executor; mod inner; mod options; pub struct Pool<DB>(Arc<SharedPool<DB>>) where DB: Database; str...
f::Target { &mut self.live.as_mut().expect(DEREF_ERR).raw } } impl<DB: Database> Drop for Connection<DB> { fn drop(&mut self) { if let Some(live) = self.live.take() { self.pool.release(live); } } }
.try_acquire().map(|conn| Connection { live: Some(conn), pool: Arc::clone(&self.0), }) } pub async fn close(&self) { self.0.close().await; } pub fn size(&self) -> u32 { self.0.size() } pub fn idle(&self) -> usize { ...
random
[ { "content": "fn is_beyond_lifetime<DB: Database>(live: &Live<DB>, options: &Options) -> bool {\n\n // check if connection was within max lifetime (or not set)\n\n options\n\n .max_lifetime\n\n .map_or(false, |max| live.created.elapsed() > max)\n\n}\n\n\n", "file_path": "sqlx-core/src/po...
Rust
src/subcommand/launch.rs
chipsenkbeil/distant
c6c07c5c2ce6ef5c1499c08ce077a14c2c558716
use crate::{ exit::{ExitCode, ExitCodeError}, msg::{MsgReceiver, MsgSender}, opt::{CommonOpt, Format, LaunchSubcommand, SessionOutput}, session::CliSession, utils, }; use derive_more::{Display, Error, From}; use distant_core::{ PlainCodec, RelayServer, Session, SessionInfo, SessionInfoFile, Tran...
use crate::{ exit::{ExitCode, ExitCodeError}, msg::{MsgReceiver, MsgSender}, opt::{CommonOpt, Format, LaunchSubcommand, SessionOutput}, session::CliSession, utils, }; use derive_more::{Display, Error, From}; use distant_core::{ PlainCodec, RelayServer, Session, SessionInfo, SessionInfoFile, Tran...
#[cfg(unix)] async fn socket_loop( socket_path: impl AsRef<Path>, info: SessionInfo, duration: Duration, fail_if_socket_exists: bool, shutdown_after: Option<Duration>, ) -> io::Result<()> { debug!("Connecting to {} {}", info.host, info.port); let addr = info.to_socket_addr().awai...
async fn keep_loop(info: SessionInfo, format: Format, duration: Duration) -> io::Result<()> { let addr = info.to_socket_addr().await?; let codec = XChaCha20Poly1305Codec::from(info.key); match Session::tcp_connect_timeout(addr, codec, duration).await { Ok(session) => { let cli_session = ...
function_block-full_function
[ { "content": "pub fn run(cmd: ActionSubcommand, opt: CommonOpt) -> Result<(), Error> {\n\n let rt = tokio::runtime::Runtime::new()?;\n\n\n\n rt.block_on(async { run_async(cmd, opt).await })\n\n}\n\n\n\nasync fn run_async(cmd: ActionSubcommand, opt: CommonOpt) -> Result<(), Error> {\n\n let method = cmd...
Rust
crates/brix_processor/tests/to_case.rs
miapolis/brix
4a3939db28fff05a7a45fa32f1a75cd9abc29be3
use lazy_static::lazy_static; use std::collections::HashMap; mod common; lazy_static! { static ref TO_CASE_CONTEXT: HashMap<String, String> = { let mut map = HashMap::new(); map.insert(String::from("one"), String::from("tHIS iS tOGGLE cASE")); map.insert(String::from("two"), String::from...
use lazy_static::lazy_static; use std::collections::HashMap; mod common; lazy_static! { static ref TO_CASE_CONTEXT: HashMap<String, String> = { let mut map = HashMap::new(); map.insert(String::from("one"), String::from("tHIS iS tOGGLE cASE")); map.insert(String::from("two"), String::from...
fn to_case() { let core = common::setup(); let context = brix_processor::create_context(TO_CASE_CONTEXT.clone()); let contents = common::load_file("case").unwrap(); let result = core.process(contents, context).unwrap(); assert!(common::line_assert(result, TO_CASE_ASSERTIONS.to_vec())) }
function_block-full_function
[ { "content": "pub fn line_assert(contents: String, assertion: Vec<&str>) -> bool {\n\n let mut itr = 0;\n\n for line in contents.lines() {\n\n if assertion[itr] != line {\n\n return false;\n\n }\n\n itr += 1;\n\n }\n\n return true;\n\n}\n", "file_path": "crates/br...
Rust
src/lib.rs
mikelma/ostrich-server
685c29502e09a5e0d668ad85cc531ea68711f1f7
use ostrich_core::*; #[macro_use] extern crate log; use tokio::sync::mpsc; use tokio::net::{TcpStream}; use tokio::io::{AsyncReadExt, AsyncWriteExt, AsyncRead}; use tokio::stream::{Stream}; use std::collections::HashMap; use std::io::{self, BufReader, prelude::*}; use std::fs::File; use core::task::{Poll, Context}; ...
use ostrich_core::*; #[macro_use] extern crate log; use tokio::sync::mpsc; use tokio::net::{TcpStream}; use tokio::io::{AsyncReadExt, AsyncWriteExt, AsyncRead}; use tokio::stream::{Stream}; use std::collections::HashMap; use std::io::{self, BufReader, prelude::*}; use std::fs::File; use core::task::{Poll, Context}; ...
trace!("Init user: {}", name); let password = match user["password"].as_str() { Some(s) => s.to_string(), None => continue, }; db.push(User {name, password}); } Ok(DataBase {db}) } ...
let name = match user["name"].as_str() { Some(n) => n.to_string(), None => continue, };
assignment_statement
[ { "content": "use serde::Deserialize;\n\nuse toml;\n\n\n\nuse std::fs::File;\n\nuse std::io::Read;\n\n\n\n#[derive(Deserialize)]\n\npub struct Config {\n\n pub ip_address: String,\n\n pub port: usize,\n\n\n\n pub logger_file: String,\n\n pub database_file: String,\n\n}\n\n\n\nimpl Config {\n\n\n\n ...
Rust
victor/src/dom/mod.rs
servo/victor
dda60efe07dd4cae0e9d93780ed661d41efb16b9
mod html; use crate::style::StyleSetBuilder; use html5ever::tendril::StrTendril; use html5ever::{Attribute, ExpandedName, LocalName, QualName}; use std::borrow::Cow; use std::fmt; pub struct Document { nodes: Vec<Node>, style_elements: Vec<NodeId>, } pub struct Node { pub(crate) parent: Option<NodeId>,...
mod html; use crate::style::StyleSetBuilder; use html5ever::tendril::StrTendril; use html5ever::{Attribute, ExpandedName, LocalName, QualName}; use std::borrow::Cow; use std::fmt; pub struct Document { nodes: Vec<Node>, style_elements: Vec<NodeId>, } pub struct Node { pub(crate) parent: Option<NodeId>,...
pub(crate) fn as_text(&self) -> Option<&StrTendril> { match self.data { NodeData::Text { ref contents } => Some(contents), _ => None, } } fn new(data: NodeData) -> Self { Node { parent: None, previous_sibling: None, next_...
ementData> { match self.data { NodeData::Element(ref data) => Some(data), _ => None, } }
function_block-function_prefixed
[ { "content": "pub fn layout(text: &str, style: &Style) -> Result<Document, FontError> {\n\n let page_size = style.page_size * Px::per_mm();\n\n let page_margin = SideOffsets::from_length_all_same(style.page_margin * Px::per_mm());\n\n let page = Rect::new(Point::origin(), page_size);\n\n let content...
Rust
panbuild/projects.rs
louib/panbuild
2cb07ebd6c21d7f4f0fb588cb8ed4570f20d1344
use serde::{Deserialize, Serialize}; use std::path::Path; use std::process::Command; pub const CORE_PROJECTS: [&'static str; 20] = [ "https://git.savannah.gnu.org/cgit/bash.git", "https://git.savannah.gnu.org/cgit/make.git", "https://git.savannah.gnu.org/cgit/diffutils.git", "https://git.savannah.gnu....
use serde::{Deserialize, Serialize}; use std::path::Path; use std::process::Command; pub const CORE_PROJECTS: [&'static str; 20] = [ "https://git.savannah.gnu.org/cgit/bash.git", "https://git.savannah.gnu.org/cgit/make.git", "https://git.savannah.gnu.org/cgit/diffutils.git", "https://git.savannah.gnu....
pub fn merge(&mut self, other_project: &SoftwareProject) { for build_system in &other_project.build_systems { self.build_systems.push(build_system.clone()); } } } #[derive(Serialize, Deserialize, Default)] pub struct ProjectVersion { pub project_id: String, pub name: ...
h crate::manifests::manifest::AbstractManifest::load_from_file(file_path.to_str().unwrap().to_string()) { Some(m) => m, None => continue, }; project.build_systems.push(abstract_manifest.get_type().unwrap().to_string()); } match crate:...
function_block-function_prefixed
[ { "content": "pub fn normalize_name(name: &String) -> String {\n\n let mut response: String = \"\".to_string();\n\n for c in name.chars() {\n\n if c.is_alphabetic() || c.is_numeric() {\n\n response.push_str(&c.to_string());\n\n continue;\n\n }\n\n // We don't wan...
Rust
crates/swift-bridge-ir/src/parse/parse_struct.rs
Jomy10/swift-bridge
4a21fd134a2fd4d2418081ba962b97e6d56b155f
use crate::bridged_type::{SharedStruct, StructFields, StructSwiftRepr}; use crate::errors::{ParseError, ParseErrors}; use proc_macro2::{Ident, TokenTree}; use syn::parse::{Parse, ParseStream}; use syn::{ItemStruct, LitStr, Token}; pub(crate) struct SharedStructDeclarationParser<'a> { pub item_struct: ItemStruct, ...
use crate::bridged_type::{SharedStruct, StructFields, StructSwiftRepr}; use crate::errors::{ParseError, ParseErrors}; use proc_macro2::{Ident, TokenTree}; use syn::parse::{Parse, ParseStream}; use syn::{ItemStruct, LitStr, Token}; pub(crate) struct SharedStructDeclarationParser<'a> { pub item_struct: ItemStruct, ...
#[test] fn parses_multiple_struct_attributes() { let tokens = quote! { #[swift_bridge::bridge] mod ffi { #[swift_bridge(swift_name = "FfiFoo", swift_repr = "class")] struct Foo { fied: u8 } } ...
let ty = module.types.types()[0].unwrap_shared_struct(); assert_eq!(ty.swift_name.as_ref().unwrap().value(), "FfiFoo"); }
function_block-function_prefix_line
[ { "content": "fn swift_calls_rust_struct_with_no_fields(arg: ffi::StructWithNoFields) -> ffi::StructWithNoFields {\n\n arg\n\n}\n\n\n", "file_path": "crates/swift-integration-tests/src/shared_types/shared_struct.rs", "rank": 0, "score": 256582.61491422064 }, { "content": "fn rust_echo_mut...
Rust
mcu/bobbin-sam/samd21/src/ext/adc.rs
thomasantony/bobbin-sdk
37375ca40351352a029aceb8b0cf17650a3624f6
use periph::adc::*; use bobbin_common::bits::*; use bobbin_hal::analog::AnalogRead; use gclk; #[derive(Debug, PartialEq, Eq, Clone, Copy)] #[repr(u8)] pub enum Resolution { Bits12 = 0x0, Bits16 = 0x1, Bits10 = 0x2, Bits8 = 0x3, } impl AdcPeriph { pub fn init(&self) { while gclk::GCLK.stat...
use periph::adc::*; use bobbin_common::bits::*; use bobbin_hal::analog::AnalogRead; use gclk; #[derive(Debug, PartialEq, Eq, Clone, Copy)] #[repr(u8)] pub enum Resolution { Bits12 = 0x0, Bits16 = 0x1, Bits10 = 0x2, Bits8 = 0x3, } impl AdcPeriph { pub fn init(&self) { while gclk::GCLK.stat...
} impl AdcPeriph { pub fn wait_busy(&self) -> &Self { while self.status().syncbusy() != ...
self.set_ctrlb(|r| r.set_prescaler(0x7).set_ressel(0x2)); self.set_sampctrl(|r| r.set_samplen(0x3f)); self.wait_busy(); self.set_inputctrl(|r| r.set_muxneg(0x18)); self.set_avgctrl(|r| r.set_samplenum(0x0).set_adjres(0x0)); ...
function_block-function_prefix_line
[ { "content": "pub fn read_peripheral<R: std::io::Read>(r: &mut EventReader<R>,\n\n attrs: &[OwnedAttribute])\n\n -> Result<Peripheral, Error> {\n\n let mut p = Peripheral::default();\n\n\n\n for a in attrs.iter() {\n\n ...
Rust
src/validate.rs
nlehuby/transport-validator
ea4ed1efd10c7a4ae91ebff92e4114bd95db1a20
use crate::{issues, metadatas, validators}; use serde::Serialize; use std::collections::BTreeMap; use std::convert::TryFrom; use std::error::Error; fn create_unloadable_model_error(error: gtfs_structures::Error) -> issues::Issue { let msg = if let Some(inner) = error.source() { format!("{}: {}", error, inn...
use crate::{issues, metadatas, validators}; use serde::Serialize; use std::collections::BTreeMap; use std::convert::TryFrom; use std::error::Error; fn create_unloadable_model_error(error: gtfs_structures::Error) -> issues::Issue { let msg = if let Some(inner) = error.source() { format!("{}: {}", error, inn...
#[derive(Serialize, Debug)] pub struct Response { pub metadata: Option<metadatas::Metadata>, pub validations: BTreeMap<issues::IssueType, Vec<issues::Issue>>, } pub fn validate_and_metadata(rgtfs: gtfs_structures::RawGtfs, max_issues: usize) -> Response { let mut validations = BTreeMap::new(); let m...
l, issues::IssueType::UnloadableModel, "A fatal error has occured while loading the model, many rules have not been checked", ) .details(&msg); if let gtfs_structures::Error::CSVError { file_name, source, line_in_error, } = error { issue.related_file ...
function_block-function_prefixed
[ { "content": "fn validate_speeds(gtfs: &gtfs_structures::Gtfs) -> Result<Vec<Issue>, gtfs_structures::Error> {\n\n let mut issues_by_stops_and_type = std::collections::HashMap::new();\n\n\n\n for trip in gtfs.trips.values() {\n\n let route = gtfs.get_route(&trip.route_id)?;\n\n for (departur...
Rust
src/conversion.rs
vilaureu/kml
6a17f7ba075e489aa6c301f9b5a3c2963e0d5b48
use std::convert::TryFrom; use crate::errors::Error; use crate::types::{ Coord, CoordType, Geometry, Kml, LineString, LinearRing, MultiGeometry, Point, Polygon, }; #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Coordinate<T>> for Coord<T> where T: CoordType, { fn from(val: ...
use std::convert::TryFrom; use crate::errors::Error; use crate::types::{ Coord, CoordType, Geometry, Kml, LineString, LinearRing, MultiGeometry, Point, Polygon, }; #[cfg_attr(docsrs, doc(cfg(feature = "geo-types")))] impl<T> From<geo_types::Coordinate<T>> for Coord<T> where T: CoordType, { fn from(val: ...
assert_eq!(quick_collection(Kml::KmlDocument(k)).unwrap(), gc); } }
let gc = geo_types::GeometryCollection(vec![ geo_types::Geometry::Point(geo_types::Point::from((1., 1.))), geo_types::Geometry::LineString(geo_types::LineString::from(vec![(1., 1.), (2., 2.)])), geo_types::Geometry::Point(geo_types::Point::from((3., 3.))), ]);
assignment_statement
[ { "content": "/// Utility method for parsing multiple coordinates according to the spec\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use kml::types::{Coord, coords_from_str};\n\n///\n\n/// let coords_str = \"1,1,0\\n\\n1,2,0 2,2,0\";\n\n/// let coords: Vec<Coord> = coords_from_str(coords_str).unwrap();\n\n...
Rust
src/search.rs
lachlan-smith/scryfall-rs
3c7a6d9258c9ad186a772094ebe5e84275e9c688
use url::Url; use crate::list::ListIter; use crate::Card; pub mod advanced; pub mod param; pub mod query; pub trait Search { fn write_query(&self, url: &mut Url) -> crate::Result<()>; #[cfg(test)] fn query_string(&self) -> crate::Result<String> { let mut url = Url::parse("http://localhost...
use url::Url; use crate::list::ListIter; use crate::Card; pub mod advanced; pub mod param; pub mod query; pub trait Search { fn write_query(&self, url: &mut Url) -> crate::Result<()>; #[cfg(test)] fn query_string(&self) -> crate::Result<String> { let mut url = Url::parse("http://localhost...
#[test] fn random_works_with_search_options() { assert!( SearchOptions::new() .query(keyword("storm")) .unique(UniqueStrategy::Art) .sort(SortOrder::Usd, SortDirection::Ascending) .extras(true) ...
e("lightning"), name("helix"), cmc(eq(2)), ])) .unique(UniqueStrategy::Prints) .search() .unwrap() .map(|c| c.unwrap()) .collect::<Vec<_>>(); assert!(cards.len() > 1); for card in cards { ...
function_block-function_prefixed
[]
Rust
python_ext/pyo3/src/resolution.rs
hoodmane/sseq
0f19a29c95486a629b0d054c703ca0a58999ae97
use std::sync::Arc; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use pyo3::prelude::*; use ext::resolution::ResolutionInner as ResolutionRust; use ext::chain_complex::{AugmentedChainComplex, ChainComplex, FiniteChainComplex, FreeChainComplex}; use python_algebra::module::{ ...
use std::sync::Arc; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use pyo3::prelude::*; use ext::resolution::ResolutionInner as ResolutionRust; use ext::chain_complex::{AugmentedChainComplex, ChainComplex, FiniteChainComplex, FreeChainComplex}; use python_algebra::module::{ ...
} pub fn number_of_gens_in_bidegree(&self, homological_degree : u32, internal_degree : i32) -> PyResult<usize> { self.check_has_computed_bidegree(homological_degree, internal_degree)?; Ok(self.inner()?.module(homological_degree).number_of_gens_in_degree(internal_degree)) ...
elf, hom_deg : u32, int_deg : i32) -> PyResult<u64> { self.check_has_computed_bidegree(hom_deg, int_deg)?; let self_inner = self.inner()?; let num_gens = self_inner.number_of_gens_in_bidegree(hom_deg, int_deg); let mut hasher = DefaultHasher::new(); hom_deg.hash(&mut hasher)...
function_block-random_span
[ { "content": "pub fn reduce_coefficient(p : u32, c : i32) -> u32 {\n\n let p = p as i32;\n\n (((c % p) + p) % p) as u32\n\n}\n\n\n", "file_path": "python_ext/pyo3/python_utils/src/lib.rs", "rank": 0, "score": 290762.9992508795 }, { "content": "#[allow(dead_code)]\n\nfn operation_drop(a...
Rust
lib/megstd/src/drawing/color.rs
neri/toe
8442f82bce551ce27b23b24336a285f25d422e98
use core::mem::transmute; pub trait ColorTrait: Sized + Copy + Clone + PartialEq + Eq {} #[repr(transparent)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct IndexedColor(pub u8); impl ColorTrait for IndexedColor {} impl IndexedColor { pub const MIN: Self = Self(u8::MIN); pub const MAX: Self = Sel...
use core::mem::transmute; pub trait ColorTrait: Sized + Copy + Clone + PartialEq + Eq {} #[repr(transparent)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct IndexedColor(pub u8); impl ColorTrait for IndexedColor {} impl IndexedColor { pub const MIN: Self = Self(u8::MIN); pub const MAX: Self = Sel...
f { AmbiguousColor::Indexed(v) => v.as_true_color(), AmbiguousColor::Argb32(v) => *v, } } } impl Into<IndexedColor> for AmbiguousColor { fn into(self) -> IndexedColor { match self { AmbiguousColor::Indexed(v) => v, AmbiguousColor::Argb32(v) => v.i...
rom_rgb(0xFFFFFF); #[inline] pub const fn from_rgb(rgb: u32) -> Self { Self { argb: rgb | 0xFF000000, } } #[inline] pub const fn from_argb(argb: u32) -> Self { Self { argb } } #[inline] pub const fn gray(white: u8, alpha: u8) -> Self { Self ...
random
[]
Rust
src/vcs.rs
kascote/rpure
7b12608ad46d2d81ead01abc2655153b431c1d09
use git2::{Repository, Status}; use std::env; use std::path::Path; #[derive(Debug)] pub enum VcsDirty { WTmodified, IDmodified, Green, } #[derive(Debug)] pub struct VcsStatus { pub name: String, pub dirty: String, pub dirty_status: VcsDirty, pub ahead: usize, pub behind: usize, pub...
use git2::{Repository, Status}; use std::env; use std::path::Path; #[derive(Debug)] pub enum VcsDirty { WTmodified, IDmodified, Green, } #[derive(Debug)] pub struct VcsStatus { pub name: String, pub dirty: String, pub dirty_status: VcsDirty, pub ahead: usize, pub behind: usize, pub...
(ahead, behind) }, Err(_) => (0, 0) }; return Some(status); } fn get_repo_name(repo: &Repository) -> String { let head = match repo.head() { Ok(r) => r, Err(_) => return String::from(""), }; if head.is_branch() { return head.shorthand().unwrap_or("...
turn Some((0, 0)); } let head_name = head.shorthand()?; let head_branch = (repo.find_branch(head_name, git2::BranchType::Local).ok())?; let upstream = match head_branch.upstream() { Ok(u) => u, Err(_) => { return Some((0, 0)) } }; let head_oid = head.ta...
function_block-random_span
[ { "content": "pub fn get_name() -> String {\n\n match env::var(\"VIRTUAL_ENV\") {\n\n Ok(venv_path) => {\n\n let venv_name = Path::new(&venv_path[..]).file_name();\n\n if let Some(name) = venv_name {\n\n if let Some(valid_name) = name.to_str() {\n\n ...
Rust
utils/indigo-service-uploader/rust/src/sd_import/sd_import.rs
tsingdao-Tp/Indigo
b2d73faebb6a450e9b3d34fed553fad4f9d0012f
extern crate postgres; extern crate time; extern crate num_cpus; extern crate threadpool; extern crate flate2; extern crate yaml_rust; extern crate postgres_binary_copy; extern crate rustc_serialize; mod sd_batch_uploader; mod sd_parser; use postgres::{Connection, SslMode, ConnectParams, ConnectTarget, UserInfo}; use...
extern crate postgres; extern crate time; extern crate num_cpus; extern crate threadpool; extern crate flate2; extern crate yaml_rust; extern crate postgres_binary_copy; extern crate rustc_serialize; mod sd_batch_uploader; mod sd_parser; use postgres::{Connection, SslMode, ConnectParams, ConnectTarget, UserInfo}; use...
} sd_reader.join().unwrap(); let end_t = PreciseTime::now(); let timer_ms = start_t.to(end_t).num_milliseconds() as f32 ; let timer_s = timer_ms / 1000f32; println!("Insert total time = {} ms ", timer_ms as i32); println!("Average insert time = {} structures p...
match status { 1u8 => { let sd_item: SdItem = map_rec.recv().unwrap(); sd_uploader.upload(sd_item); str_count += 1; } _ => break, }
if_condition
[ { "content": "fn import(file_name: &str, table_name: &str, config_name: Option<String>) {\n\n let conf_name = config_name.unwrap_or(\"config.yml\".to_string());\n\n let mut sd_import = SdImport::new(&conf_name);\n\n sd_import.insert(file_name, table_name);\n\n}\n\n\n", "file_path": "utils/indigo-se...
Rust
app/gui/src/ide/integration/file_system.rs
enso-org/enso
2676aa50a3cc86a1c0673a3e60a553134e350b1b
use crate::prelude::*; use crate::controller::graph::NewNodeInfo; use crate::controller::upload::pick_non_colliding_name; use engine_protocol::language_server; use engine_protocol::language_server::ContentRoot; use engine_protocol::language_server::FileSystemObject; use enso_frp as frp; use ensogl_component::file_b...
use crate::prelude::*; use crate::controller::graph::NewNodeInfo; use crate::controller::upload::pick_non_colliding_name; use engine_protocol::language_server; use engine_protocol::language_server::ContentRoot; use engine_protocol::language_server::FileSystemObject; use enso_frp as frp; use ensogl_component::file_b...
pub async fn get_entries_list(&self) -> Result<Vec<Entry>, RpcError> { let response = self.connection.file_list(&self.path).await?; let entries = response.paths.into_iter().map(|fs_obj| match fs_obj { FileSystemObject::Directory { name, path } | FileSystemObject::Direc...
pub fn sub_view(&self, sub_dir: impl Str) -> DirectoryView { DirectoryView { connection: self.connection.clone_ref(), content_root: self.content_root.clone_ref(), path: Rc::new(self.path.append_im(sub_dir)), } }
function_block-full_function
[ { "content": "/// Return FRP endpoints for the parameters that define a shadow.\n\npub fn frp_from_style(style: &StyleWatchFrp, path: impl Into<style::Path>) -> ParametersFrp {\n\n let path: style::Path = path.into();\n\n ParametersFrp {\n\n base_color: style.get_color(&path),\n\n fading: ...
Rust
hsp3-analyzer-mini/ham-core/src/assists/completion.rs
vain0x/hsp3-ginger
c5924b60686d4bf1769569c013c8110f7636732c
use super::*; use crate::{ analysis::{HspSymbolKind, LocalScope, Scope, SymbolRc}, assists::from_document_position, lang_service::docs::Docs, parse::{p_param_ty::PParamCategory, PToken}, source::*, token::TokenKind, }; use lsp_types::{CompletionItem, CompletionItemKind, CompletionList, Documenta...
use super::*; use crate::{ analysis::{HspSymbolKind, LocalScope, Scope, SymbolRc}, assists::from_document_position, lang_service::docs::Docs, parse::{p_param_ty::PParamCategory, PToken}, source::*, token::TokenKind, }; use lsp_types::{CompletionItem, CompletionItemKind, CompletionList, Documenta...
items.swap_remove(i); } { let mut set = HashSet::new(); let retain = items .iter() .map(|item| set.insert(item.label.as_str())) .collect::<Vec<_>>(); let mut i = 0; items.retain(|_| { i += 1; retain[i - 1]...
lete_completion_list() -> CompletionList { CompletionList { is_incomplete: true, items: vec![], } } fn do_completion( uri: &Url, position: Position, docs: &Docs, wa: &mut WorkspaceAnalysis, ) -> Option<CompletionList> { let mut items = vec![]; let (doc, pos) = from_docu...
random
[ { "content": "fn add_symbol(kind: HspSymbolKind, name: &PToken, def_site: bool, ctx: &mut Ctx) {\n\n let NameScopeNsTriple {\n\n basename,\n\n scope_opt,\n\n ns_opt,\n\n } = resolve_name_scope_ns_for_def(\n\n &name.body.text,\n\n ImportMode::Local,\n\n &ctx.scope,...
Rust
muse/src/instrument.rs
khonsulabs/muse
26aadbc56b3c2029b5d1740da7aa3f9873cfd66d
use crate::{ envelope::PlayingState, manager::{Device, PlayingHandle}, node::{Instantiatable, LoadedInstrument}, note::Note, sampler::PreparedSampler, }; use crossbeam::atomic::AtomicCell; use std::{ sync::{Arc, RwLock}, time::Duration, }; #[cfg(feature = "serialization")] pub mod serializa...
use crate::{ envelope::PlayingState, manager::{Device, PlayingHandle}, node::{Instantiatable, LoadedInstrument}, note::Note, sampler::PreparedSampler, }; use crossbeam::atomic::AtomicCell; use std::{ sync::{Arc, RwLock}, time::Duration, }; #[cfg(feature = "serialization")] pub mod serializa...
self.playing_notes.retain(|pn| pn.note.step() as u8 != step); } } pub fn set_sustain(&mut self, active: bool) { self.sustain = active; if !active { self.playing_notes.retain(|n| n.is_playing()); } } }
self.controller.control_handles.stop() } fn sustain(&self) { self.controller.control_handles.sustain() } } impl<T> Drop for PlayingNote<T> { fn drop(&mut self) { self.stop(); let handle = std::mem::take(&mut self.handle); let control_handles = std::mem::take(&mut se...
random
[ { "content": "/// A mapping from a Rust type to its Muse [`Type`].\n\npub trait CustomType: Send + Sync + Debug + 'static {\n\n /// Returns the Muse type for this Rust type.\n\n fn muse_type(&self) -> &TypeRef;\n\n}\n\n\n", "file_path": "src/runtime/value.rs", "rank": 0, "score": 193705.002593...
Rust
gf256-macros/src/rs.rs
geky/gf256
57675335061b18e3614376981482fd7584454fd5
extern crate proc_macro; use darling; use darling::FromMeta; use syn; use syn::parse_macro_input; use proc_macro2::*; use std::collections::HashMap; use quote::quote; use std::iter::FromIterator; use crate::common::*; const RS_TEMPLATE: &'static str = include_str!("../templates/rs.rs"); #[derive(Debug, FromMeta)] ...
extern crate proc_macro; use darling; use darling::FromMeta; use syn; use syn::parse_macro_input; use proc_macro2::*; use std::collections::HashMap; use quote::quote; use std::iter::FromIterator; use crate::common::*; const RS_TEMPLATE: &'static str = include_str!("../templates/rs.rs"); #[derive(Debug, FromMeta)] ...
r().into(); } }; let output = quote! { #(#attrs)* #vis mod #rs { #template } #(#overrides)* }; output.into() }
use #u as #__u; }) } None => { overrides.push(quote! { use u8 as #__u; }); } } let replacements = HashMap::from_iter([ ...
function_block-random_span
[ { "content": "/// Generate `n` shares requiring `k` shares to reconstruct.\n\n///\n\n/// This scheme is limited to to the number of shares <= the number of\n\n/// non-zero elements in the field.\n\n///\n\npub fn generate(secret: &[__u], n: usize, k: usize) -> Vec<Vec<__u>> {\n\n // we only support up to 255 ...
Rust
src/cli/collections.rs
RekhaDS/couchbase-shell
81bdfd4a8e62bdb477857d31f7704d07d1f35da6
use crate::cli::util::{cluster_identifiers_from, validate_is_not_cloud}; use crate::client::ManagementRequest; use crate::state::State; use async_trait::async_trait; use log::debug; use nu_engine::CommandArgs; use nu_errors::ShellError; use nu_protocol::{Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value};...
use crate::cli::util::{cluster_identifiers_from, validate_is_not_cloud}; use crate::client::ManagementRequest; use crate::state::State; use async_trait::async_trait; use log::debug; use nu_engine::CommandArgs; use nu_errors::ShellError; use nu_protocol::{Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value};...
fn usage(&self) -> &str { "Fetches collections through the HTTP API" } fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { collections_get(self.state.clone(), args) } } fn collections_get( state: Arc<Mutex<State>>, args: CommandArgs, ) -> Result<OutputStrea...
xShape::String, "the name of the scope", None) .named( "clusters", SyntaxShape::String, "the clusters to query against", None, ) }
function_block-function_prefixed
[ { "content": "pub fn signature_dict(signature: Signature, tag: impl Into<Tag>) -> Value {\n\n let tag = tag.into();\n\n let mut sig = TaggedListBuilder::new(&tag);\n\n\n\n for arg in signature.positional.iter() {\n\n let is_required = matches!(arg.0, PositionalType::Mandatory(_, _));\n\n\n\n ...
Rust
c-uint256-tests/src/bindings.rs
jjyr/godwoken-scripts
d983fb351410eb6fbe02bb298af909193aeb5f22
/* automatically generated by rust-bindgen 0.59.2 */ pub const true_: u32 = 1; pub const false_: u32 = 0; pub const INT8_MIN: i32 = -128; pub const INT16_MIN: i32 = -32768; pub const INT32_MIN: i32 = -2147483648; pub const INT64_MIN: i64 = -9223372036854775808; pub const INT8_MAX: u32 = 127; pub const INT16_MAX: u32 =...
/* automatically generated by rust-bindgen 0.59.2 */ pub const true_: u32 = 1; pub const false_: u32 = 0; pub const INT8_MIN: i32 = -128; pub const INT16_MIN: i32 = -32768; pub const INT32_MIN: i32 = -2147483648; pub const INT64_MIN: i64 = -9223372036854775808; pub const INT8_MAX: u32 = 127; pub const INT16_MAX: u32 =...
t uint256_t { pub array: [u32; 8usize], } #[test] fn bindgen_test_layout_uint256_t() { assert_eq!( ::std::mem::size_of::<uint256_t>(), 32usize, concat!("Size of: ", stringify!(uint256_t)) ); assert_eq!( ::std::mem::align_of::<uint256_t>(), 4usize, concat!(...
c_char) -> ::std::os::raw::c_ulong; } extern "C" { pub fn strcmp( l: *const ::std::os::raw::c_char, r: *const ::std::os::raw::c_char, ) -> ::std::os::raw::c_int; } extern "C" { pub fn malloc(size: ::std::os::raw::c_ulong) -> *mut ::std::os::raw::c_void; } extern "C" { pub fn free(ptr: *m...
random
[ { "content": "pub fn since_timestamp(t: u64) -> Uint64 {\n\n let input_timestamp = Duration::from_millis(t).as_secs() + 1;\n\n (SINCE_BLOCK_TIMESTAMP_FLAG | input_timestamp).pack()\n\n}\n\n\n", "file_path": "tests/src/script_tests/utils/layer1.rs", "rank": 0, "score": 195985.14016819192 }, ...
Rust
src/message_decoder/mod.rs
silathdiir/pg_wire
f106d57abfd501e4f1a1f7f8c20418e2998c2be0
use crate::{ cursor::Cursor, message_decoder::state::{Payload, Tag}, messages::FrontendMessage, Result, }; use state::State; use std::mem::MaybeUninit; mod state; #[derive(Debug, PartialEq)] pub enum Status { Requesting(usize), Decoding, Done(FrontendMessage), } pub ...
use crate::{ cursor::Cursor, message_decoder::state::{Payload, Tag}, messages::FrontendMessage, Result, }; use state::State; use std::mem::MaybeUninit; mod state; #[derive(Debug, PartialEq)] pub enum Status { Requesting(usize), Decoding, Done(FrontendMessage), } pub ...
}
r .next_stage(Some(QUERY_BYTES)) .expect("proceed to the next stage"); decoder.next_stage(None).expect("proceed to the next stage"); assert_eq!(decoder.next_stage(None), Ok(Status::Requesting(1))); }
function_block-function_prefixed
[ { "content": "fn decode_execute(mut cursor: Cursor) -> Result<FrontendMessage> {\n\n let portal_name = cursor.read_cstr()?.to_owned();\n\n let max_rows = cursor.read_i32()?;\n\n Ok(FrontendMessage::Execute { portal_name, max_rows })\n\n}\n\n\n", "file_path": "src/messages.rs", "rank": 0, "s...
Rust
migrate/src/lib.rs
alekspickle/migrate
c0a95c0b81315e8588c58688bdb775b7dcf997d9
#![warn(missing_docs, unreachable_pub, rust_2018_idioms)] #![forbid(unsafe_code)] mod cli; mod error; pub use error::*; pub use migrate_core as core; use crate::core::MigrationRunMode; use error::{DynError, Error}; use migrate_core::{MigrationsSelection, PlanBuilder}; use structopt::StructOpt; #[cfg(doctest)] do...
#![warn(missing_docs, unreachable_pub, rust_2018_idioms)] #![forbid(unsafe_code)] mod cli; mod error; pub use error::*; pub use migrate_core as core; use crate::core::MigrationRunMode; use error::{DynError, Error}; use migrate_core::{MigrationsSelection, PlanBuilder}; use structopt::StructOpt; #[cfg(doctest)] do...
}
pub async fn run(self, plan_builder: PlanBuilder) -> Result<(), Error> { let (cli::PlanArgGroup { no_commit, no_run }, plan) = match self.0 { cli::Args::Up(cmd) => { let plan = plan_builder .build(&MigrationsSelection::Up { inclusive_bound:...
function_block-full_function
[]
Rust
wasm/lib/src/browser_module.rs
alexpantyukhin/RustPython
b0ee1947c775145db055413dce217dca1613712d
use crate::{convert, vm_class::AccessibleVM, wasm_builtins::window}; use futures::{future, Future}; use js_sys::Promise; use num_traits::cast::ToPrimitive; use rustpython_vm::obj::{objint, objstr}; use rustpython_vm::pyobject::{PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol}; use rustpython_vm::VirtualMachi...
use crate::{convert, vm_class::AccessibleVM, wasm_builtins::window}; use futures::{future, Future}; use js_sys::Promise; use num_traits::cast::ToPrimitive; use rustpython_vm::obj::{objint, objstr}; use rustpython_vm::pyobject::{PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol}; use rustpython_vm::VirtualMachi...
; let result = match result.expect("prompt() not to fail") { Some(result) => vm.new_str(result), None => vm.get_none(), }; Ok(result) } const BROWSER_NAME: &str = "browser"; pub fn mk_module(ctx: &PyContext) -> PyObjectRef { py_module!(ctx, BROWSER_NAME, { "fetch" => ctx.new_...
if let Some(default) = default { window().prompt_with_message_and_default( &objstr::get_value(message), &objstr::get_value(default), ) } else { window().prompt_with_message(&objstr::get_value(message)) }
if_condition
[ { "content": "fn str_str(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {\n\n arg_check!(vm, args, required = [(s, Some(vm.ctx.str_type()))]);\n\n Ok(s.clone())\n\n}\n\n\n", "file_path": "vm/src/obj/objstr.rs", "rank": 0, "score": 466286.87047549686 }, { "content": "pub fn subs...
Rust
src/serializer.rs
aep/korhal-image
6aa0cce631efe530d5f94a1b893c0efdc7712fec
use blockstore::{Block, BlockStore, BlockShard}; use chunker::*; use index::*; use pbr::ProgressBar; use readchain::{Take,Chain}; use serde::{Serialize, Deserialize}; use std::ffi::OsString; use std::io::{Stdout, Seek, SeekFrom, BufReader}; use std::path::Path; use std::fs::File; use elfkit; use sha2::{Sha256, Digest}...
use blockstore::{Block, BlockStore, BlockShard}; use chunker::*; use index::*; use pbr::ProgressBar; use readchain::{Take,Chain}; use serde::{Serialize, Deserialize}; use std::ffi::OsString; use std::io::{Stdout, Seek, SeekFrom, BufReader}; use std::path::Path; use std::fs::File; use elfkit; use sha2::{Sha256, Digest}...
fn print_progress_bar(bar: &mut ProgressBar<Stdout>, path: &OsString){ let s = path.to_str().unwrap(); if s.len() > 50 { bar.message(&format!("indexing ..{:48} ", &s[s.len()-48..])); } else { bar.message(&format!("indexing {:50} ", &s)); } }
function_block-full_function
[ { "content": "pub fn new(path: String) -> BlockStore {\n\n let mut bs = BlockStore{\n\n path: path,\n\n blocks: HashMap::new(),\n\n };\n\n bs.load();\n\n bs\n\n}\n\n\n\n\n\nimpl BlockStore {\n\n pub fn get<'a>(&'a self, hash: &Vec<u8>) -> Option<&'a Block> {\n\n self.blocks.g...
Rust
crates/category/tests/product_bug.rs
Nertsal/categories
3fd0a8b4f5c9a3df78c35126bb4af3a9ed10bae3
use category::{axioms, Bindings}; use category::{prelude::*, Equality}; use std::fmt::Debug; #[test] fn test_bug() { let rule_product = axioms::rule_product::<&str>().unwrap(); let mut category = Category::new(); let object_a = category.new_object(Object { tags: vec![], inner: ...
use category::{axioms, Bindings}; use category::{prelude::*, Equality}; use std::fmt::Debug; #[test] fn test_bug() { let rule_product = axioms::rule_product::<&str>().unwrap(); let mut category = Category::new(); let object_a = category.new_object(Object { tags: vec![], inner: ...
for (id, morphism) in category.morphisms.iter() { println!("{:4} - {:?}", id.raw(), morphism) } println!("Equalities:"); for (equality, inner) in category.equalities.iter() { println!( " {:?} = {:?}: {inner:?}", equality.left(), equality.right() )...
function_block-function_prefix_line
[ { "content": "fn print_category<O: Debug, M: Debug, E: Debug>(category: &Category<O, M, E>) {\n\n println!(\"\\n----- Category -----\");\n\n println!(\"Objects:\");\n\n for (id, object) in category.objects.iter() {\n\n println!(\"{:4} - {:?}\", id.raw(), object)\n\n }\n\n println!(\"Morphi...
Rust
db/src/impls/rangestore/kvdb.rs
shogochiai/plasma-rust-framework
e72cb12d80d3e3ab080746f9fb0576a242e9d194
use crate::error::{Error, ErrorKind}; use crate::range::Range; use crate::traits::db::DatabaseTrait; use crate::traits::rangestore::RangeStore; use kvdb::{DBTransaction, KeyValueDB}; use kvdb_memorydb::{create, InMemory}; pub struct RangeDb { db: InMemory, col: u32, } impl DatabaseTrait for RangeDb { fn o...
use crate::error::{Error, ErrorKind}; use crate::range::Range; use crate::traits::db::DatabaseTrait; use crate::traits::rangestore::RangeStore; use kvdb::{DBTransaction, KeyValueDB}; use kvdb_memorydb::{create, InMemory}; pub struct RangeDb { db: InMemory, col: u32, } impl DatabaseTrait for RangeDb { fn o...
Dammy)) } } pub fn put_batch(&self, ranges: &[Range]) -> Result<(), Error> { let mut tr = DBTransaction::new(); for range in ranges.iter() { let query = range.get_end().to_be_bytes(); tr.put(Some(self.col), &query, &rlp::encode(range)); } self.db.w...
u64) -> Result<Box<[Range]>, Error> { let ranges = self.get(start, end)?; let mut tr = DBTransaction::new(); for range in ranges.clone().iter() { let query = range.get_end().to_be_bytes(); tr.delete(Some(self.col), &query); } self.db.write(tr)?; i...
function_block-random_span
[ { "content": "fn create_object_id(start: u64, end: u64) -> Vec<u8> {\n\n let mut object_id_buf = BytesMut::with_capacity(64);\n\n object_id_buf.put_u64_le(start);\n\n object_id_buf.put_u64_le(end);\n\n object_id_buf.to_vec()\n\n}\n\n*/\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct StateObj...
Rust
crates/m-mazing-tile-util/src/main.rs
tmfink/m-mazing
e603dd081f56b897d49014dc45078db1ba9ec19b
use std::{fs::File, io::Read, path::PathBuf, sync::mpsc}; use anyhow::{Context, Result}; use clap::Parser; use m_mazing_core::bevy; use m_mazing_core::prelude::*; use notify::Watcher; use bevy::asset::AssetServerSettings; use bevy::ecs as bevy_ecs; use bevy::prelude::*; use bevy::render::camera::ScalingMode; mod g...
use std::{fs::File, io::Read, path::PathBuf, sync::mpsc}; use anyhow::{Context, Result}; use clap::Parser; use m_mazing_core::bevy; use m_mazing_core::prelude::*; use notify::Watcher; use bevy::asset::AssetServerSettings; use bevy::ecs as bevy_ecs; use bevy::prelude::*; use bevy::render::camera::ScalingMode; mod g...
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, SystemLabel)] enum MySystemLabels { Input, SpawnTile, } fn frame_init(mut refresh: ResMut<RefreshTile>) { refresh.0 = false; } #[allow(unused)] fn debug_system(query: Query<Entity>) { info!("entities: {}", query.iter().count()); } fn main() -> Resul...
TextStyle { font: font.clone(), font_size: 50.0, color: Color::BLACK, }, Default::default(), ), ...
function_block-function_prefix_line
[ { "content": "pub fn notify_tileset_change(mut should_refresh: ResMut<RefreshTile>, mut ctx: NonSendMut<Ctx>) {\n\n match ctx.notify_rx.try_recv() {\n\n Ok(Ok(event)) => {\n\n info!(\"new event {:?}\", event);\n\n should_refresh.0 = true;\n\n\n\n match ctx.refresh() {\...
Rust
common/machine.rs
camas/aoc2019
53b41dcf9990c9a4e460197b5e5031ec2158b453
use crate::common::get_digits; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use std::collections::HashMap; use std::ops::Range; use Instr::*; const MEM_CHUNK_SIZE: usize = 1000; pub struct Machine { memory: Memory, ip: usize, rel_base: usize, } impl Machine { pub fn new(mem: &[i64])...
use crate::common::get_digits; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use std::collections::HashMap; use std::ops::Range; use Instr::*; const MEM_CHUNK_SIZE: usize = 1000; pub struct Machine { memory: Memory, ip: usize, rel_base: usize, } impl Machine {
pub fn run(&mut self, input: impl FnMut() -> i64, output: impl FnMut(i64)) { self.run_until(Instr::Halt, input, output); } #[allow(clippy::cognitive_complexity)] pub fn run_until( &mut self, halt_instr: Instr, mut input: impl FnMut() -> i64, mut outpu...
pub fn new(mem: &[i64]) -> Machine { Machine { memory: Memory::from(&mem), ip: 0, rel_base: 0, } }
function_block-full_function
[]
Rust
tests/admin_general.rs
gearbot/Gearbot-Animal-API
e103efc146324d411e641938617fc9eba69b5447
use animal_api::*; use animal_facts::*; mod generator; use crate::generator::*; use actix_web::web::{self, Bytes, Data}; use actix_web::{test, App}; #[actix_rt::test] async fn no_admins_loaded() { let dir = make_dir(); let mut state = gen_state(&dir); state.config.admins = Vec::new(); let req_json = ...
use animal_api::*; use animal_facts::*; mod generator; use crate::generator::*; use actix_web::web::{self, Bytes, Data}; use actix_web::{test, App}; #[actix_rt::test] async fn no_admins_loaded() { let dir = make_dir(); let mut state = gen_state(&dir); state.config.admins = Vec::new(); let req_json = ...
#[actix_rt::test] async fn list_facts() { let dir = make_dir(); let uri = "/admin/fact/list"; let state = gen_state(&dir); let req_json = AdminFactRequest { fact_id: None, fact_content: None, animal_type: Animal::Cat, key: gen_admin_all_perms().key, }; let raw ...
ke_dir(); let mut state = gen_state(&dir); state.fact_lists.dog_facts = None; let req_json = AdminFactRequest { fact_id: Some(6682463169732688062), fact_content: None, animal_type: Animal::Dog, key: state.config.admins[4].key.clone(), }; assert_eq!( ...
function_block-function_prefixed
[ { "content": "pub fn get_cat_fact(app_data: Data<APIState>) -> HttpResponse {\n\n if let Some(fact_list) = &app_data.fact_lists.cat_facts {\n\n let mut rng = thread_rng();\n\n let list_lock = fact_list.read().unwrap();\n\n\n\n // This should never panic since `Some()` means there is >= 1...
Rust
examples/bank-emulator/integration-tests/src/fees.rs
m10io/sdk
62f773304da0567986d5fc33c282649238c9f5c2
use m10_bank_emulator::models::*; use rust_decimal::Decimal; use super::base_url; use super::utils::*; #[tokio::test] async fn fees_routes() { let jwt = default_user_jwt().await; let client = reqwest::Client::default(); let tr_fees = FeeMetadata { schedule: FeeSchedule { fees: vec![ ...
use m10_bank_emulator::models::*; use rust_decimal::Decimal; use super::base_url; use super::utils::*; #[tokio::test] async fn fees_routes() { let jwt = default_user_jwt().await; let client = reqwest::Client::default(); let tr_fees = FeeMetadata { schedule: FeeSchedule { fees: vec![ ...
t .expect("get withdraw fee amount response") .assert_json::<FeeResponse>() .await; assert_eq!(63, resp.fees[0].amount); client .get(format!("{}/api/v1/fees/ttt/deposit/60600", base_url())) .bearer_auth(&jwt) .send() .await .expect("get ...
function_block-function_prefixed
[ { "content": "fn with_additional_protos(mut protos: Vec<String>, additional_paths: &[&str]) -> Vec<String> {\n\n for path in additional_paths {\n\n protos.push(proto_path(path).display().to_string());\n\n }\n\n protos\n\n}\n", "file_path": "rust/protos/build.rs", "rank": 0, "score": ...
Rust
src/bin/mpc.rs
ys-nuem/rust-gurobi-example
a94bf00d1452a4753c0dc0fd6ea83d67fb0d735f
#![allow(non_snake_case)] #![allow(dead_code)] extern crate gurobi; #[macro_use] extern crate itertools; use gurobi::*; use itertools::*; struct MPCModel(gurobi::Model); impl std::ops::Deref for MPCModel { type Target = gurobi::Model; fn deref(&self) -> &gurobi::Model { &self.0 } } impl std::ops::DerefMut...
#![allow(non_snake_case)] #![allow(dead_code)] extern crate gurobi; #[macro_use] extern crate itertools; use gurobi::*; use itertools::*; struct MPCModel(gurobi::Model); impl std::ops::Deref for MPCModel { type Target = gurobi::Model; fn deref(&self) -> &gurobi::Model { &self.0 } } impl std::ops::DerefMut...
; input.push(u); } let u_t = input.last().cloned().unwrap(); let x_t = 0.99 * x_t + u_t + 0.01; state.push(x_t); } println!("input = {:?}", input); }
match sol.status { Status::Optimal => *sol.u.get(0).unwrap(), _ => { println!("step {}: cannot retrieve an optimal MIP solution", t); 0.0 } }
if_condition
[ { "content": "# rust-gurobi-example", "file_path": "README.md", "rank": 0, "score": 2911.5059799016285 } ]
Rust
nft_api/src/ingest/main.rs
jarry-xiao/merkle-wallet
079c4c7b51ee9f90ad98c13a660ff97727db7127
extern crate core; use hyper::{Body, Client, Request, Response, Server, StatusCode}; use futures_util::future::join3; use redis::streams::{StreamId, StreamKey, StreamReadOptions, StreamReadReply}; use redis::{Commands, Value}; use routerify::prelude::*; use routerify::{Middleware, Router, RouterService}; use anchor_...
extern crate core; use hyper::{Body, Client, Request, Response, Server, StatusCode}; use futures_util::future::join3; use redis::streams::{StreamId, StreamKey, StreamReadOptions, StreamReadReply}; use redis::{Commands, Value}; use routerify::prelude::*; use routerify::{Middleware, Router, RouterService}; use anchor_...
let mut conn = conn_res.unwrap(); let streams = vec!["GM_CL", "GMC_OP"]; let group_name = "ingester"; for key in &streams { let created: Result<(), _> = conn.xgroup_create_mkstream(*key, group_name, "$"); if let Err(e) = created { println!("Group already exists: {:?}", e) ...
await; if f.is_err() { println!("Error {:?}", f.err().unwrap()); } i += 1; } match txn.commit().await { Ok(_r) => { println!("Sa...
random
[ { "content": "/// Recomputes root of the Merkle tree from Node & proof\n\npub fn recompute(mut leaf: Node, proof: &[Node], index: u32) -> Node {\n\n for (i, s) in proof.iter().enumerate() {\n\n if index >> i & 1 == 0 {\n\n let res = hashv(&[&leaf, s.as_ref()]);\n\n leaf.copy_from...
Rust
tapdance-rust-logic/src/util.rs
refraction-networking/tapdance
39262efa194b520f3187ad98cab8efb953eccf39
extern crate libc; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use mio::Ready; use mio::unix::UnixReady; use pnet::packet::Packet; use pnet::packet::tcp::{TcpOptionNumbers, TcpPacket}; pub fn all_unix_events() -> UnixReady { UnixReady::from(Ready::readable() | Ready::writable()) | Uni...
extern crate libc; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use mio::Ready; use mio::unix::UnixReady; use pnet::packet::Packet; use pnet::packet::tcp::{TcpOptionNumbers, TcpPacket}; pub fn all_unix_events() -> UnixReady { UnixReady::from(Ready::readable() | Ready::writable()) | Uni...
pub fn mem_used_kb() -> u64 { let my_pid: i32 = unsafe { libc::getpid() }; let f = match File::open(format!("/proc/{}/status", my_pid)) { Ok(f) => f, Err(e) => { error!("Failed to open /proc/{}/status: {:?}", my_pid, e); return 0; } }; let buf_f = BufReader::new...
pub fn tcp_seq_lt(a: u32, b: u32) -> bool { if a == b { false } else { let res = a < b; if tcp_seq_is_wrapped(a, b) { !res } else { res } } }
function_block-full_function
[ { "content": "// Pass in 1st, 2nd bytes of the TL (big-endian). Returns is_proto, len.\n\n// The len returned might be 0, meaning extended TL.\n\npub fn parse_typelen(byte1: u8, byte2: u8) -> (bool, usize)\n\n{\n\n let tl = unsafe { mem::transmute::<[u8;2], i16>([byte2, byte1]) };\n\n if tl >= 0 {\n\n ...
Rust
src/models/withdrawal.rs
nervina-labs/compact-nft-aggregator
f5d4afebd732fdcd55c7590ddfc5af0eb30b2eda
use super::helper::{parse_cota_id_and_token_index_pairs, parse_lock_hash}; use crate::models::block::get_syncer_tip_block_number; use crate::models::helper::{generate_crc, PAGE_SIZE}; use crate::models::scripts::get_script_map_by_ids; use crate::models::{DBResult, DBTotalResult}; use crate::schema::withdraw_cota_nft_kv...
use super::helper::{parse_cota_id_and_token_index_pairs, parse_lock_hash}; use crate::models::block::get_syncer_tip_block_number; use crate::models::helper::{generate_crc, PAGE_SIZE}; use crate::models::scripts::get_script_map_by_ids; use crate::models::{DBResult, DBTotalResult}; use crate::schema::withdraw_cota_nft_kv...
fn parse_withdraw_db(withdrawals: Vec<WithdrawCotaNft>) -> DBResult<WithdrawDb> { let block_height = get_syncer_tip_block_number()?; if withdrawals.is_empty() { return Ok((vec![], block_height)); } let receiver_lock_script_ids: Vec<i64> = withdrawals .iter() .map(|withdrawal| w...
pub fn get_sender_lock_by_script_id( script_id: i64, cota_id_: [u8; 20], token_index_: [u8; 4], ) -> Result<Option<String>, Error> { let start_time = Local::now().timestamp_millis(); let conn = &POOL.clone().get().expect("Mysql pool connection error"); let cota_id_hex = hex::encode(cota_id_); ...
function_block-full_function
[ { "content": "pub fn parse_cota_id_and_token_index_pairs(pairs: Vec<([u8; 20], [u8; 4])>) -> Vec<(String, u32)> {\n\n pairs\n\n .into_iter()\n\n .map(|pair| (hex::encode(pair.0), u32::from_be_bytes(pair.1)))\n\n .collect()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\...
Rust
src/cluster/cut.rs
FridgeSeal/blip
0a202eb0061d8e2ac34a4bd501cfa08051cb4087
use super::{proto, Metadata, State}; use futures::stream::{unfold, Stream}; use rand::{thread_rng, Rng}; use std::{ collections::HashMap, convert::TryInto, net::SocketAddr, ops::Index, result, sync::{Arc, Weak}, }; use thiserror::Error; use tokio::sync::{ broadcast::{error::RecvError, Rece...
use super::{proto, Metadata, State}; use futures::stream::{unfold, Stream}; use rand::{thread_rng, Rng}; use std::{ collections::HashMap, convert::TryInto, net::SocketAddr, ops::Index, result, sync::{Arc, Weak}, }; use thiserror::Error; use tokio::sync::{ broadcast::{error::RecvError, Rece...
impl Member { #[inline] pub(crate) fn new(addr: SocketAddr, tls: Option<Arc<ClientTlsConfig>>, meta: Metadata) -> Self { let chan = endpoint(addr, tls.as_deref()) .connect_lazy() .unwrap(); #[rustfmt::skip] let m = Self { addr, tls, meta, chan }; ...
fn endpoint(addr: SocketAddr, tls: Option<&ClientTlsConfig>) -> transport::Endpoint { match tls.cloned() { Some(tls) => format!("https://{}", addr) .try_into() .map(|e: transport::Endpoint| e.tls_config(tls).unwrap()), None => format!("http://{}", addr).try_into(), } ...
function_block-full_function
[ { "content": "type ResolvedMember = Result<Member, MemberResolutionError>;\n\n\n", "file_path": "src/cluster/mod.rs", "rank": 0, "score": 134911.461126479 }, { "content": "pub fn addr_in(subnet: u32, host: u32) -> SocketAddr {\n\n let mut addr = (subnet & 0x1fff) << 12; // 11 bits of subn...
Rust
src/interpreter/internal.rs
wareya/gammakit
63d217f8ebc291844b8df69db12a03b9c906bef4
use crate::interpreter::*; impl Interpreter { pub (super) fn stack_len(&mut self) -> usize { self.top_frame.len() } pub (super) fn stack_pop_val(&mut self) -> Option<Value> { self.top_frame.pop_val() } pub (super) fn stack_pop_var(&mut self) -> Option<Variable> { ...
use crate::interpreter::*; impl Interpreter { pub (super) fn stack_len(&mut self) -> usize { self.top_frame.len() } pub (super) fn stack_pop_val(&mut self) -> Option<Value> { self.top_frame.pop_val() } pub (super) fn stack_pop_var(&mut self) -> Option<Variable> { ...
s not holding function data; {:?}", funcdata)) } Ok(()) } }
Ok(()) } pub (super) fn handle_func_call_or_expr(&mut self, isexpr : bool) -> Result<(), String> { let argcount = self.read_usize(); if cfg!(stack_len_debugging) && argcount+1 > self.stack_len() { return plainerr("internal error: fewer ...
random
[ { "content": "type CompilerBinding<'a> = fn(&mut CompilerState<'a>, &ASTNode) -> Result<(), String>;\n\n\n", "file_path": "src/compiler.rs", "rank": 0, "score": 132890.84490723212 }, { "content": "pub fn default_step_result() -> StepResult\n\n{\n\n Ok(())\n\n}\n\n/// Type signature of fun...
Rust
src/terrain/main.rs
fkaa/gfx_examples
dea8a8393e34d011873b9f9c39f945dc6755f3e2
extern crate cgmath; #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate glutin; extern crate time; extern crate rand; extern crate genmesh; extern crate noise; use rand::Rng; use cgmath::FixedArray; use cgmath::{Matrix4, Point3, Vector3}; use cgmath::{Transform, AffineMatrix3}; use gfx::trai...
extern crate cgmath; #[macro_use] extern crate gfx; extern crate gfx_window_glutin; extern crate glutin; extern crate time; extern crate rand; extern crate genmesh; extern crate noise; use rand::Rng; use cgmath::FixedArray; use cgmath::{Matrix4, Point3, Vector3}; use cgmath::{Transform, AffineMatrix3}; use gfx::trai...
pub fn main() { let (mut stream, mut device, mut factory) = gfx_window_glutin::init( glutin::Window::new().unwrap()); stream.out.window.set_title("Terrain example"); let rand_seed = rand::thread_rng().gen(); let seed = Seed::new(rand_seed); let plane = Plane::subdivide(256, 256); let ...
calculate_color(height: f32) -> [f32; 3] { if height > 8.0 { [0.9, 0.9, 0.9] } else if height > 0.0 { [0.7, 0.7, 0.7] } else if height > -5.0 { [0.2, 0.7, 0.2] } else { [0.2, 0.2, 0.7] } }
function_block-function_prefixed
[ { "content": "fn calculate_color(height: f32) -> [f32; 3] {\n\n if height > 8.0 {\n\n [0.9, 0.9, 0.9] // white\n\n } else if height > 0.0 {\n\n [0.7, 0.7, 0.7] // greay\n\n } else if height > -5.0 {\n\n [0.2, 0.7, 0.2] // green\n\n } else {\n\n [0.2, 0.2, 0.7] // blue\n\n...
Rust
src/search/aggregations/bucket/diversified_sampler_aggregation.rs
ypenglyn/elasticsearch-dsl-rs
bff3508055fb20eb54bde78edffa69da3ccbf4eb
use crate::search::*; use crate::util::*; use std::convert::TryInto; #[derive(Debug, Clone, Serialize, PartialEq)] pub struct DiversifiedSamplerAggregation { diversified_sampler: DiversifiedSamplerAggregationInner, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] aggs: Aggregations, } #[derive(D...
use crate::search::*; use crate::util::*; use std::convert::TryInto; #[derive(Debug, Clone, Serialize, PartialEq)] pub struct DiversifiedSamplerAggregation { diversified_sampler: DiversifiedSamplerAggregationInner, #[serde(skip_serializing_if = "ShouldSkip::should_skip")] aggs: Aggregations, } #[derive(D...
pub fn max_docs_per_value(mut self, max_docs_per_value: impl TryInto<u64>) -> Self { if let Ok(max_docs_per_value) = max_docs_per_value.try_into() { self.diversified_sampler.max_docs_per_value = Some(max_docs_per_value); } self } ...
f, shard_size: impl TryInto<u64>) -> Self { if let Ok(shard_size) = shard_size.try_into() { self.diversified_sampler.shard_size = Some(shard_size); } self }
function_block-function_prefixed
[ { "content": "#[doc(hidden)]\n\npub trait Origin: Debug + PartialEq + Serialize + Clone {\n\n type Scale: Debug + PartialEq + Serialize + Clone;\n\n type Offset: Debug + PartialEq + Serialize + Clone;\n\n}\n\n\n\nimpl Origin for DateTime<Utc> {\n\n type Scale = Time;\n\n type Offset = Time;\n\n}\n\n...
Rust
utoipa-gen/src/schema/component/attr.rs
juhaku/utoipa
070b00c13b41040e9605c62a0d7c3b5fcf04899c
use std::mem; use proc_macro2::{Ident, TokenStream}; use proc_macro_error::{abort, ResultExt}; use quote::{quote, ToTokens}; use syn::{ parenthesized, parse::{Parse, ParseBuffer}, Attribute, Error, ExprPath, Token, }; use crate::{ parse_utils, schema::{ComponentPart, GenericType}, AnyValue, };...
use std::mem; use proc_macro2::{Ident, TokenStream}; use proc_macro_error::{abort, ResultExt}; use quote::{quote, ToTokens}; use syn::{ parenthesized, parse::{Parse, ParseBuffer}, Attribute, Error, ExprPath, Token, }; use crate::{ parse_utils, schema::{ComponentPart, GenericType}, AnyValue, };...
impl<T> ToTokens for ComponentAttr<T> where T: quote::ToTokens, { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.extend(self.inner.to_token_stream()) } } impl ToTokens for Enum { fn to_tokens(&self, tokens: &mut TokenStream) { if let Some(ref default) = self.default { ...
pub fn parse_component_attr<T: Sized + Parse>(attributes: &[Attribute]) -> Option<T> { attributes .iter() .find(|attribute| attribute.path.get_ident().unwrap() == "component") .map(|attribute| attribute.parse_args::<T>().unwrap_or_abort()) }
function_block-full_function
[]
Rust
cosmos-abci/abci/src/lib.rs
couragetec/courage_substrate_cosmos
d9b2038436ac8933e6dadda960cd66a543c851d3
mod defaults; pub mod grpc; pub mod utils; pub use defaults::*; pub use grpc::*; use lazy_static::lazy_static; use owning_ref::MutexGuardRefMut; use std::sync::Mutex; use mockall::automock; lazy_static! { static ref ABCI_INTERFACE_INSTANCE: Mutex<Option<AIType>> = Mutex::new(None); } type AIType = Box<dyn Abci...
mod defaults; pub mod grpc; pub mod utils; pub use defaults::*; pub use grpc::*; use lazy_static::lazy_static; use owning_ref::MutexGuardRefMut; use std::sync::Mutex; use mockall::automock; lazy_static! { static ref ABCI_INTERFACE_INSTANCE: Mutex<Option<AIType>> = Mutex::new(None); } type AIType = Box<dyn Abci...
pub fn get_abci_instance<'ret>( ) -> Result<MutexGuardRefMut<'ret, Option<AIType>, AIType>, Box<dyn std::error::Error>> { let instance = ABCI_INTERFACE_INSTANCE.lock()?; if instance.is_none() { panic!("abci instance has not been set, execute set_abci_instance before calling this function"); ...
function_block-full_function
[ { "content": "/// Method for getting gRPC url form active env.\n\npub fn get_server_url() -> String {\n\n crate::utils::get_option_from_node_args(crate::utils::NodeOptionVariables::AbciServerUrl)\n\n .unwrap_or_else(|| DEFAULT_ABCI_URL.to_owned())\n\n}\n\n\n", "file_path": "cosmos-abci/abci/src/de...
Rust
contracts/link-token/src/contract.rs
hackbg/chainlink-terra-cosmwasm-contracts
a1a82fa5db9942f8c8e6ec5d0b8fe7effb830f84
use cosmwasm_std::{ to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Uint128, }; use cw20::{Cw20Coin, TokenInfoResponse}; use cw20_base::{ allowances::{ execute_decrease_allowance, execute_increase_allowance, execute_transfer_from, query_allowance, }, contract::{c...
use cosmwasm_std::{ to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, Uint128, }; use cw20::{Cw20Coin, TokenInfoResponse}; use cw20_base::{ allowances::{ execute_decrease_allowance, execute_increase_allowance, execute_transfer_from, query_allowance, }, contract::{c...
pub fn query_token_info(deps: Deps) -> StdResult<TokenInfoResponse> { let info = TOKEN_INFO.load(deps.storage)?; Ok(info.into()) } #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{coins, Uint128}; #[test] fn ...
QueryMsg::TokenInfo {} => to_binary(&query_token_info(deps)?), QueryMsg::Allowance { owner, spender } => { to_binary(&query_allowance(deps, owner, spender)?) } } }
function_block-function_prefix_line
[ { "content": "pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {\n\n match msg {\n\n QueryMsg::IsValid {\n\n previous_answer,\n\n answer,\n\n } => to_binary(&is_valid(deps, previous_answer, answer)?),\n\n QueryMsg::GetFlaggingThreshold {} => t...
Rust
merkle_tree/src/lib.rs
mikong/mori
75879172eeb7e733c62d472bafc6c6792d3b754a
use std::mem; use sha2::{Sha256, Digest}; use sha2::digest::generic_array::GenericArray; use sha2::digest::generic_array::typenum::U32; use sha2::digest::generic_array::sequence::Concat; type HashResult = GenericArray<u8, U32>; #[derive(Debug, PartialEq)] pub enum Position { Left, Right, } #[derive(Debug)] ...
use std::mem; use sha2::{Sha256, Digest}; use sha2::digest::generic_array::GenericArray; use sha2::digest::generic_array::typenum::U32; use sha2::digest::generic_array::sequence::Concat; type HashResult = GenericArray<u8, U32>; #[derive(Debug, PartialEq)] pub enum Position { Left, Right, } #[derive(Debug)] ...
_iter.next().unwrap(); assert_eq!(pos, &Position::Right); assert_eq!(*hash, GenericArray::clone_from_slice(&hd)); let (pos, hash) = proof_iter.next().unwrap(); assert_eq!(pos, &Position::Left); assert_eq!(*hash, GenericArray::clone_from_slice(&hab)); let (pos, hash) = p...
pub fn root_hash(&self) -> HashResult { match self { MerkleTree::NonEmpty(node) => node.element, MerkleTree::Empty => panic!("Merkle tree can't be empty"), } } pub fn validate( target: HashResult, proof: Vec<(Position, HashResult)>, ...
random
[ { "content": "type NodeId = usize;\n\n\n\nimpl<K, V> Node<K, V> {\n\n pub fn new(key: K, value: V, color: Color) -> Self {\n\n Node {\n\n key,\n\n value,\n\n left: None,\n\n right: None,\n\n color,\n\n size: 1,\n\n }\n\n }\n\n...
Rust
src/generate/generator.rs
nurmohammed840/virtue
b645e092861377a1b11b97c681de9e9acb5a0d22
use super::{GenerateMod, Impl, ImplFor, StreamBuilder}; use crate::parse::{GenericConstraints, Generics}; use crate::prelude::{Ident, TokenStream}; #[must_use] pub struct Generator { pub(crate) name: Ident, pub(crate) generics: Option<Generics>, pub(crate) generic_constraints: Option<GenericConstraints>, ...
use super::{GenerateMod, Impl, ImplFor, StreamBuilder}; use crate::parse::{GenericConstraints, Generics}; use crate::prelude::{Ident, TokenStream}; #[must_use] pub struct Generator { pub(crate) name: Ident, pub(crate) generics: Option<Generics>, pub(crate) generic_constraints: Option<GenericConstraints>, ...
} } false } pub fn finish(mut self) -> crate::prelude::Result<TokenStream> { Ok(std::mem::take(&mut self.stream).stream) } } impl Drop for Generator { fn drop(&mut self) { if !self.stream.stream.is_empty() && !std::thread::panicking() { epr...
if let Some(parent) = path.parent() { path = parent.to_owned(); } else { break; }
if_condition
[]
Rust
src/smr/tests/proposal_test.rs
zeroqn/overlord
4bf43c4c4e94691e54bae586a07b82e39e13622a
use crate::smr::smr_types::{Lock, SMREvent, SMRTrigger, Step, TriggerType}; use crate::smr::tests::{gen_hash, trigger_test, InnerState, StateMachineTestCase}; use crate::{error::ConsensusError, types::Hash}; #[tokio::test(threaded_scheduler)] async fn test_proposal_trigger() { let mut index = 1; let mut test_c...
use crate::smr::smr_types::{Lock, SMREvent, SMRTrigger, Step, TriggerType}; use crate::smr::tests::{gen_hash, trigger_test, InnerState, StateMachineTestCase}; use crate::{error::ConsensusError, types::Hash}; #[tokio::test(threaded_scheduler)] async fn test_proposal_trigger() { let mut index = 1; let mut test_c...
ash = gen_hash(); let lock = Lock::new(1, lock_hash.clone()); test_cases.push(StateMachineTestCase::new( InnerState::new(2, Step::Propose, lock_hash.clone(), Some(lock)), SMRTrigger::new(lock_hash.clone(), TriggerType::Proposal, Some(1), 0), SMREvent::PrevoteVote { height: ...
voteVote { height: 0u64, round: 2u64, block_hash: lock_hash.clone(), lock_round: Some(1), }, None, Some((1, lock_hash)), )); let hash = gen_hash(); let lock_hash = gen_hash(); let lock = Lock::new(...
random
[ { "content": "fn gen_hash() -> Hash {\n\n Hash::from((0..16).map(|_| random::<u8>()).collect::<Vec<_>>())\n\n}\n", "file_path": "tests/test_utils.rs", "rank": 0, "score": 137237.66059652547 }, { "content": "fn gen_hash() -> Hash {\n\n Hash::from((0..16).map(|_| random::<u8>()).collect:...
Rust
tracing-journald/tests/journal.rs
jswrenn/tracing
388fff8371fef1ec0f75bc495fe1ad4cfa045f7b
#![cfg(target_os = "linux")] use std::collections::HashMap; use std::process::Command; use std::time::Duration; use serde::Deserialize; use tracing::{debug, error, info, info_span, warn}; use tracing_journald::Subscriber; use tracing_subscriber::subscribe::CollectExt; use tracing_subscriber::Registry; fn journalctl_...
#![cfg(target_os = "linux")] use std::collections::HashMap; use std::process::Command; use std::time::Duration; use serde::Deserialize; use tracing::{debug, error, info, info_span, warn}; use tracing_journald::Subscriber; use tracing_subscriber::subscribe::CollectExt; use tracing_subscriber::Registry; fn journalctl_...
) { with_journald(|| { error!( test.name = "multiline_message_trailing_newline", "A trailing newline\n" ); let message = retry_read_one_line_from_journal("multiline_message_trailing_newline"); assert_eq!(message["MESSAGE"], "A trailing newline\n"); as...
} } } impl PartialEq<&str> for Field { fn eq(&self, other: &&str) -> bool { match self { Field::Text(s) => s == other, Field::Binary(_) => false, Field::Array(_) => false, } } } impl PartialEq<[u8]> for Field { fn eq(&self, other: &[u8]) -> bool {...
random
[ { "content": "#[allow(clippy::manual_async_fn)]\n\n#[instrument(level = \"debug\")]\n\nfn instrumented_manual_async() -> impl Future<Output = ()> {\n\n async move {}\n\n}\n\n\n", "file_path": "tracing/test_static_max_level_features/tests/test.rs", "rank": 1, "score": 282858.3962827644 }, { ...
Rust
src/bin/day24/main.rs
MattiasBuelens/advent-of-code-2019
01a88977bc7b6471bdc84aebd41e1e8d3920946d
use std::collections::{HashMap, HashSet}; fn main() { let grid: Grid = Grid::parse(include_str!("input")); println!("Answer to part 1: {}", part1(grid.clone())); println!("Answer to part 2: {}", part2(grid.clone())); } #[derive(Debug, Eq, PartialEq, Copy, Clone)] enum Tile { EMPTY, BUG, } impl Ti...
use std::collections::{HashMap, HashSet}; fn main() { let grid: Grid = Grid::parse(include_str!("input")); println!("Answer to part 1: {}", part1(grid.clone())); println!("Answer to part 2: {}", part2(grid.clone())); } #[derive(Debug, Eq, PartialEq, Copy, Clone)] enum Tile { EMPTY, BUG, } impl Ti...
_key(&level) { let new_grid = new_grids.entry(level).or_insert(Default::default()); new_grid.tiles[y][x] = new_tile; } } } } self.grids = new_grids; } fn count_bugs(&self) -> usize { self.gri...
y + 1 < SIZE { neighbours.push(self.tiles[y + 1][x]); } neighbours } fn step(&mut self) { let mut new_tiles: [[Tile; SIZE]; SIZE] = Default::default(); for y in 0..SIZE { for x in 0..SIZE { let neighbour_bugs = self .ge...
random
[ { "content": "pub fn parse_list<T, E>(input: &str, separator: char) -> Vec<T>\n\nwhere\n\n T: FromStr<Err = E>,\n\n E: Debug,\n\n{\n\n return input\n\n .trim()\n\n .split(separator)\n\n .map(|x| x.parse().expect(\"invalid input\"))\n\n .collect();\n\n}\n", "file_path": "...
Rust
src/decode.rs
12101111/6502
b333d946539f04fee8680f5b1b73de40c1102b3c
use super::address::AM::{self, *}; #[derive(Debug, Clone, Copy)] #[allow(non_camel_case_types)] pub enum OP { LDA, LDX, LDY, STA, STX, STY, TAX, TAY, TXA, TYA, TSX, TXS, PHA, PHP...
use super::address::AM::{self, *}; #[derive(Debug, Clone, Copy)] #[allow(non_camel_case_types)] pub enum OP { LDA, LDX, LDY, STA, STX, STY, TAX, TAY, TXA, TYA, TSX, TXS, PHA, PHP...
),(STA, ZPX, 4),(STX, ZPY, 4),(SAX, ZPY, 4), /*0x98*/(TYA, IMP, 2),(STA, ABY, 5),(TXS, IMP, 2),(TAS, ABY, 5),(SHY, ABX, 5),(STA, ABX, 5),(SHX, ABY, 5),(AHX, ABY, 5), /*0xA0*/(LDY, IMM, 2),(LDA, ZIX, 6),(LDX, IMM, 2),(LAX, ZIX, 6),(LDY, ZPG, 3),(LDA, ZPG, 3),(LDX, ZPG, 3),(LAX, ZPG, 3), /*0xA8*/(TAY, IMP, 2),(LDA, IMM, ...
8),(BIT, ZPG, 3),(AND, ZPG, 3),(ROL, ZPG, 5),(RLA, ZPG, 5), /*0x28*/(PLP, IMP, 4),(AND, IMM, 2),(ROL, ACC, 2),(ANC, IMM, 2),(BIT, ABS, 4),(AND, ABS, 4),(ROL, ABS, 6),(RLA, ABS, 6), /*0x30*/(BMI, REL, 2),(AND, ZIY, 5),(STP, NON, 2),(RLA, ZIY, 8),(NOP, ZPX, 4),(AND, ZPX, 4),(ROL, ZPX, 6),(RLA, ZPX, 6), /*0x38*/(SEC, IMP...
random
[ { "content": "pub trait Memory {\n\n fn reset(&mut self);\n\n fn loadb(&mut self, addr: u16) -> u8;\n\n fn try_loadb(&self, addr: u16) -> Option<u8>;\n\n fn storeb(&mut self, addr: u16, val: u8);\n\n fn add_cycles(&mut self, val: usize);\n\n fn get_cycles(&self) -> usize;\n\n}\n\n\n\npub struc...
Rust
src/day14/data/mod.rs
Fryuni/advent-of-code-2021
832121aba87516b4c2727eee9869348e1a5a7840
/* * MIT License * * Copyright (c) 2021 Luiz Ferraz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modi...
/* * MIT License * * Copyright (c) 2021 Luiz Ferraz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modi...
} #[derive(Debug)] pub struct Data { pub template: Polymer, pub rules: PolymerizationRules, } impl Debug for Polymer { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("Polymer(")?; for c in &self.0 { f.write_char(*c)?; } f.write_str(")") ...
pub fn into_element_counters(self) -> HashMap<char, usize> { let mut counters: HashMap<char, usize> = HashMap::new(); for ((a, _), count) in self.0 { counters.entry(a).or_default().add_assign(count); } counters }
function_block-function_prefix_line
[ { "content": "fn iter_matrix() -> impl Iterator<Item = (usize, usize)> {\n\n (0..10).cartesian_product(0..10)\n\n}\n\n\n\nimpl State {\n\n const FLASHED: usize = 20;\n\n\n\n pub fn advance_state(&mut self) -> usize {\n\n // println!(\"Initial state:\\n{:?}\", self);\n\n\n\n // Advance all...
Rust
crates/melody_cli/src/main.rs
ikroeber/melody
693832f659482d100000da84d6fc55b8ff43dd07
pub mod consts; pub mod macros; pub mod output; pub mod utils; use clap::Parser; use consts::COMMAND_MARKER; use melody_compiler::{compiler, ParseError}; use output::{ print_output, print_output_pretty, print_repl_welcome, print_source_line, prompt, report_clear, report_exit, report_missing_path, report_no_lin...
pub mod consts; pub mod macros; pub mod output; pub mod utils; use clap::Parser; use consts::COMMAND_MARKER; use melody_compiler::{compiler, ParseError}; use output::{ print_output, print_output_pretty, print_repl_welcome, print_source_line, prompt, report_clear, report_exit, report_missing_path, report_no_lin...
redo_lines.clear(); let output = raw_output.unwrap(); print_output_pretty(format!("{output}\n")) } }
if let Err(error) = raw_output { let ParseError { token, line: _, line_index: _, } = error; report_repl_parse_error(token); valid_lines.pop(); continue 'repl; }
if_condition
[]
Rust
crates/wasm-bindgen-cli-support/src/lib.rs
lukewagner/wasm-bindgen
7384bd1967e325101b09234753598122c71eaefe
#[macro_use] extern crate failure; extern crate parity_wasm; extern crate wasm_bindgen_shared as shared; extern crate serde_json; extern crate wasm_gc; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use failure::Error; use parity_wasm::elements::*; mod js; pub mod wasm2es6js; pub struct Bind...
#[macro_use] extern crate failure; extern crate parity_wasm; extern crate wasm_bindgen_shared as shared; extern crate serde_json; extern crate wasm_gc; use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use failure::Error; use parity_wasm::elements::*; mod js; pub mod wasm2es6js; pub struct Bind...
ts, imported_structs, custom_type_names, } = p; ret.structs.extend(structs); ret.free_functions.extend(free_functions); ret.imports.extend(imports); ret.imported_structs.extend(imported_structs); if custom_type_names...
tom_type_names: Vec::new(), }; let data = match data { Some(data) => data, None => return ret, }; for i in (0..data.entries().len()).rev() { { let value = data.entries()[i].value(); if !value.starts_with(b"wbg:") { continue } ...
function_block-random_span
[ { "content": "fn bindgen_imported_struct(import: &ast::ImportStruct, tokens: &mut Tokens) {\n\n let name = import.name;\n\n\n\n let mut methods = Tokens::new();\n\n\n\n for &(_is_method, ref f) in import.functions.iter() {\n\n let import_name = shared::mangled_import_name(\n\n Some(&i...
Rust
blocky-net/src/chat/component.rs
JAD3N/minecraft
cfa74fa48ca9c1399eb02cd11332f86121e7bd85
use super::{Style, TextComponent, TranslatableComponent, TranslatableComponentArg}; use crate::{AsJson, FromJson}; use thiserror::Error; #[derive(Error, Debug)] pub enum ComponentError { #[error("failed to parse json")] Parse, } pub trait ComponentClone { fn clone_box(&self) -> Box<dyn Component>; } pub ...
use super::{Style, TextComponent, TranslatableComponent, TranslatableComponentArg}; use crate::{AsJson, FromJson}; use thiserror::Error; #[derive(Error, Debug)] pub enum ComponentError { #[error("failed to parse json")] Parse, } pub trait ComponentClone { fn clone_box(&self) -> Box<dyn Component>; } pub ...
} #[macro_export] macro_rules! component { ($svis:vis struct $name:ident { $($fvis:vis $fname:ident: $fty:ty),* $(,)? }) => { #[derive(Clone)] $svis struct $name { siblings: Vec<Box<dyn Component>>, style: Style, $($fvis $fname: $fty),* } impl $...
fn from_json(value: &serde_json::Value) -> Result<Self, Self::Err> { if value.is_string() { Ok(Box::new(TextComponent::new(value.as_str().unwrap()))) } else if value.is_object() { let obj = value.as_object().unwrap(); let mut c: Box<dyn Component> = if let Some(text) ...
function_block-function_prefix_line
[ { "content": "pub trait FromJson {\n\n type Err;\n\n fn from_json(value: &serde_json::Value) -> Result<Self, Self::Err> where Self: Sized;\n\n}\n", "file_path": "blocky-net/src/lib.rs", "rank": 2, "score": 121584.79989159183 }, { "content": "pub trait AsJson {\n\n fn as_json(&self) ...
Rust
src/plugins.rs
ivmarkov/edge-frame
c3c8c270189d5f497180774c138de0717d919bb5
use std::collections; use enumset::*; use yew::prelude::Html; use yew::prelude::Properties; use embedded_svc::edge_config::role::Role; use crate::lambda::Lambda; #[derive(EnumSetType, Debug, PartialOrd)] #[cfg_attr(feature = "std", derive(Hash))] pub enum InsertionPoint { Drawer, Appbar, } #[derive(EnumSe...
use std::collections; use enumset::*; use yew::prelude::Html; use yew::prelude::Properties; use embedded_svc::edge_config::role::Role; use crate::lambda::Lambda; #[derive(EnumSetType, Debug, PartialOrd)] #[cfg_attr(feature = "std", derive(Hash))] pub enum InsertionPoint { Drawer, Appbar, } #[derive(EnumSe...
} #[derive(PartialEq, Clone, Debug)] pub struct ContentPlugin<R> where R: PartialEq + Clone, { pub component: Lambda<PluginProps<R>, Html>, pub api_uri_prefix: String, } impl<R> ContentPlugin<R> where R: PartialEq + Clone, { pub fn map<F, RAPP>(&self, mapper: F) -> ContentPlugin<RAPP> where ...
pub fn map<F, RAPP>(&self, mapper: F) -> NavigationPlugin<RAPP> where F: Fn(&RAPP) -> R + 'static, RAPP: PartialEq + Clone, R: 'static, { NavigationPlugin { category: self.category, insertion_point: self.insertion_point, component: map(&self.co...
function_block-full_function
[ { "content": "pub fn with_path_segment(uri: &str, segment: &str) -> Result<String> {\n\n let mut url = url::Url::parse(uri)?;\n\n\n\n {\n\n let mut segments = url\n\n .path_segments_mut()\n\n .map_err(|_| anyhow!(\"url cannot be used as a base\"))?;\n\n segments.push(se...
Rust
src/didcomm/mod.rs
chriamue/identity-cloud-agent
810d4498b26547b28e474cdaf5d44c2481d32109
use crate::connection::{invitation::Invitation, Connections, Termination, TerminationResponse}; use crate::credential::{issue::Issuance, Credentials}; use crate::message::MessageRequest; use crate::ping::{PingRequest, PingResponse}; use crate::webhook::Webhook; use async_trait::async_trait; use reqwest::RequestBuilder;...
use crate::connection::{invitation::Invitation, Connections, Termination, TerminationResponse}; use crate::credential::{issue::Issuance, Credentials}; use crate::message::MessageRequest; use crate::ping::{PingRequest, PingResponse}; use crate::webhook::Webhook; use async_trait::async_trait; use reqwest::RequestBuilder;...
}
let ping_request: PingRequest = PingRequest { type_: "https://didcomm.org/trust-ping/2.0/ping".to_string(), id: "foo".to_string(), from: "bar".to_string(), body, }; let ping_request: String = serde_json::to_string(&ping_request).unwrap(); let resp...
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\npub trait Webhook: Send + Sync {\n\n fn request(&self, topic: &str, body: &Value) -> RequestBuilder;\n\n async fn post(&self, topic: &str, body: &Value) -> Result<reqwest::Response, reqwest::Error>;\n\n}\n", "file_path": "src/webhook/mod.rs", "rank": 0, "score":...
Rust
src/kernel/x86/x86avxbitreversal.rs
yvt/yfft-rs
2ba9934e9a3213a528e7ba4573fe08b96609d20b
use super::super::Num; use super::utils::{if_compatible, AlignInfo, AlignReqKernel, AlignReqKernelWrapper}; use super::{Kernel, KernelParams, SliceAccessor}; use packed_simd::{u32x4, u64x2, u64x4}; use std::{mem, ptr}; pub unsafe fn new_x86_avx_bit_reversal_kernel<T>(indices: &Vec<usize>) -> Option<Box<Kernel<T>>> w...
use super::super::Num; use super::utils::{if_compatible, AlignInfo, AlignReqKernel, AlignReqKernelWrapper}; use super::{Kernel, KernelParams, SliceAccessor}; use packed_simd::{u32x4, u64x2, u64x4}; use std::{mem, ptr}; pub unsafe fn new_x86_avx_bit_reversal_kernel<T>(indices: &Vec<usize>) -> Option<Box<Kernel<T>>> w...
#[derive(Debug)] struct AvxDWordBitReversalKernel { indices: Vec<usize>, } impl<T: Num> AlignReqKernel<T> for AvxDWordBitReversalKernel { fn transform<I: AlignInfo>(&self, params: &mut KernelParams<T>) { assert_eq!(mem::size_of::<T>(), 4); let indices = unsafe { SliceAccessor::new(&self.indi...
WordBitReversalKernel { indices: indices.clone(), })) as Box<Kernel<f32>>, ) }) }
function_block-function_prefixed
[ { "content": "pub trait Num:\n\n Clone\n\n + Debug\n\n + AddAssign\n\n + SubAssign\n\n + MulAssign\n\n + DivAssign\n\n + Default\n\n + num_traits::Float\n\n + num_traits::FloatConst\n\n + num_traits::Zero\n\n + 'static\n\n + Sync\n\n + Send\n\n{\n\n}\n\nimpl<T> Num for T w...
Rust
client/src/renderer/glium/traits.rs
BonsaiDen/shooter-rs
0ce5d02065be9ded30e29fdf133ad7a615f29323
use glium::{glutin, DisplayBuild, Surface}; use shared::Lithium::{ Client, ClientHandler, EntityState, EntityRegistry, Event, BaseLevel, Renderer }; use super::GliumRenderer; impl Renderer for GliumRenderer { fn run< H: ClientHandler<Self, G, L, E, S>, E: Event, S: EntityState, ...
use glium::{glutin, DisplayBuild, Surface}; use shared::Lithium::{ Client, ClientHandler, EntityState, EntityRegistry, Event, BaseLevel, Renderer }; use super::GliumRenderer; impl Renderer for GliumRenderer { fn run< H: ClientHandler<Self, G, L, E, S>, E: Event, S: EntityState, ...
fn time(&self) -> f64 { self.time } fn set_time(&mut self, time: f64) { self.time = time; } fn delta_time(&self) -> f32{ self.dt } fn set_delta_time(&mut self, dt: f32) { self.dt = dt; } fn delta_u(&self) -> f32 { self.u } f...
while renderer.running() { if renderer.should_draw() { let frame_time = renderer.time(); let tick_rate = renderer.tick_rate(); if frames_per_tick == 0 { if client.tick(&mut renderer) { frames_per_tick = renderer.f...
function_block-function_prefix_line
[ { "content": "fn run() {\n\n\n\n let args = clap::App::new(\"shooter-client\")\n\n .version(&crate_version!())\n\n .author(\"Ivo Wetzel <ivo.wetzel@googlemail.com>\")\n\n .about(\"Shooter-Client\")\n\n .arg(clap::Arg::with_name(\"address:port\")\n\n .help(\"Remote serve...
Rust
jissen/2nd/code4/src/main.rs
Hota822/Rust
05a7756cfec474052161b3886b035a326a58f49a
fn main() { f4_2(); f4_3(); } fn f4_3() { let t1 = (88, true); assert_eq!(t1.0, 88); let mut t2 = (88, true); t2.1 = false; assert_eq!(t2.1, false); let (n1, b1) = t2; println!("({}, {})", n1, b1); let ((_, _), (n2, _)) = ((1, 2), (3, 4)); println!("{}", n2); let m...
fn main() { f4_2(); f4_3(); } fn f4_3() { let t1 = (88, true); assert_eq!(t1.0, 88); let mut t2 = (88, true); t2.1 = false; assert_eq!(t2.1, false); let (n1, b1) = t2; println!("({}, {})", n1, b1); let ((_, _), (n2, _)) = ((1, 2), (3, 4)); println!("{}", n2); let m...
let s1 = "a"; let s2 = "あ"; let s3 = "😀"; println!("{}, {}, {}", s1.len(), s2.len(), s3.len()); let s = "abcあいう"; assert_eq!(s.get(0..1), Some("a")); assert_eq!(s.get(3..6), Some("あ")); assert_eq!(s.get(3..5), None); assert_eq!(s.get(3..=6), None ); let s = "かか\u{3099}く"; ...
if let Some(apples) = apple_line { assert!(apples.starts_with("red")); assert!(apples.contains("apple")); println!("{:?}", apples.find("green")); let mut apple_iter = apples.split(","); assert_eq!(apple_iter.next(), Some("red apple")); let green = apple_iter.next...
if_condition
[ { "content": "fn print_info(name: &str, sl: &[char]) {\n\n println!(\" {:9} - {}, {:?}, {:?}, {:?}\",\n\n name,\n\n sl.len(),\n\n sl.first(),\n\n sl.get(1),\n\n sl.last()\n\n );\n\n}\n\n\n", "file_path": "jissen/1st/code4/src/main.rs", "rank": 0, "score": 41...
Rust
src/lt.rs
Others/fountain_codes
798ea7240b1714958a5cf7e5af0f0c2048ce011e
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt::{self, Debug, Formatter}; use std::hash::{Hash, Hasher}; use std::io::{self, Cursor}; use std::ops::{BitXor, BitXorAssign, Index}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::{Client, CreationError, Data, Decoder, Encoder, M...
use std::cmp; use std::collections::{HashMap, HashSet}; use std::fmt::{self, Debug, Formatter}; use std::hash::{Hash, Hasher}; use std::io::{self, Cursor}; use std::ops::{BitXor, BitXorAssign, Index}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::{Client, CreationError, Data, Decoder, Encoder, M...
impl Encoder<LtPacket> for LtSource { fn create_packet(&self) -> LtPacket { let block_count = self.blocks.len(); let mut blocks: Vec<u32> = Vec::with_capacity(block_count); for i in 0..block_count{ blocks.push(i as u32); } choose_blocks_to_combine(&self.distri...
r i in 0..blocks_to_combine { let j = distribution.query_interior_rng_usize(i, blocks.len()); blocks.swap(i, j); } blocks.truncate(blocks_to_combine as usize); }
function_block-function_prefixed
[ { "content": "pub trait Source<P: Packet> : Encoder<P> + Sized {\n\n fn new(metadata: Metadata, data: Data) -> Result<Self, CreationError>;\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 2, "score": 67255.24559277261 }, { "content": "pub trait Decoder<P: Packet> {\n\n fn receive_packe...
Rust
src/xcb/xconn.rs
psychon/penrose
69912708f7982b7d6a61b9fa549040fb4c3625fb
/*! * API wrapper for talking to the X server using XCB * * The crate used by penrose for talking to the X server is rust-xcb, which * is a set of bindings for the C level XCB library that are autogenerated * from an XML spec. The XML files can be found * [here](https://github.com/rtbo/rust-xcb/tree/master/x...
/*! * API wrapper for talking to the X server using XCB * * The crate used by penrose for talking to the X server is rust-xcb, which * is a set of bindings for the C level XCB library that are autogenerated * from an XML spec. The XML files can be found * [here](https://github.com/rtbo/rust-xcb/tree/master/x...
fn update_known_clients(&self, clients: &[WinId]) { self.api.replace_prop( self.api.root(), Atom::NetClientList, PropVal::Window(clients), ); self.api.replace_prop( self.api.root(), Atom::NetClientListStacking, PropVal...
t = self.api.root(); self.api.replace_prop( root, Atom::NetNumberOfDesktops, PropVal::Cardinal(&[workspaces.len() as u32]), ); self.api.replace_prop( root, Atom::NetDesktopNames, PropVal::Str(&workspaces.join("\0")), ...
function_block-function_prefixed
[ { "content": "fn process_property_notify(id: WinId, atom: String, is_root: bool) -> Vec<EventAction> {\n\n match Atom::from_str(&atom) {\n\n Ok(a) if [Atom::WmName, Atom::NetWmName].contains(&a) => {\n\n vec![EventAction::ClientNameChanged(id, is_root)]\n\n }\n\n _ => vec![Eve...
Rust
src/fcfg1/config_if_adc.rs
luojia65/cc2640r2f
03a5bfca3e739dbb8310e2b0dabb07a8ca572fe5
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CONFIG_IF_ADC { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R,...
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CONFIG_IF_ADC { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R,...
INT3ADJR { bits } } #[doc = "Bits 16:19 - 19:16\\] Internal. Only to be used through TI provided API."] #[inline] pub fn ff1adj(&self) -> FF1ADJR { let bits = { const MASK: u8 = 15; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 ...
let bits = { const MASK: u8 = 15; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 };
assignment_statement
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
rust/xaynet-server/src/storage/s3.rs
abargiela/xaynet
2c87c5fd3f02f68dc9aefaaeb3a0371afa005722
use crate::settings::{S3BucketsSettings, S3Settings}; use rusoto_core::{credential::StaticProvider, request::TlsError, HttpClient, RusotoError}; use rusoto_s3::{ CreateBucketError, CreateBucketOutput, CreateBucketRequest, DeleteObjectsError, ListObjectsV2Error, PutObjectError, PutObjectOutpu...
use crate::settings::{S3BucketsSettings, S3Settings}; use rusoto_core::{credential::StaticProvider, request::TlsError, HttpClient, RusotoError}; use rusoto_s3::{ CreateBucketError, CreateBucketOutput, CreateBucketRequest, DeleteObjectsError, ListObjectsV2Error, PutObjectError, PutObjectOutpu...
ifiers: Vec<ObjectIdentifier>, ) -> Result<DeleteObjectsOutput, RusotoError<DeleteObjectsError>> { let req = DeleteObjectsRequest { bucket: bucket.to_string(), delete: Delete { objects: identifiers, ..Default::default() ...
ccess_key); let dispatcher = HttpClient::new()?; Ok(Self { buckets: Arc::new(settings.buckets), s3_client: S3Client::new_with(dispatcher, credentials_provider, settings.region), }) } pub async fn upload_global_model(&self, key: &str, global_model: &Model) -...
random
[ { "content": "fn error_code_type_error(response: &Value) -> RedisError {\n\n redis_type_error(\n\n \"Response status not valid integer\",\n\n Some(format!(\"Response was {:?}\", response)),\n\n )\n\n}\n\n\n\n/// Implements ['FromRedisValue'] and ['ToRedisArgs'] for types that implement ['Byt...
Rust
src/agent/onefuzz-agent/src/local/tui.rs
henryzz0/onefuzz
cb0701b2f2daf5b7b6d71bec9acd8dc0e329e1c3
use crate::local::common::UiEvent; use anyhow::{Context, Result}; use crossterm::{ event::{self, Event, KeyCode}, execute, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, }; use futures::{StreamExt, TryStreamExt}; use log::Level; use onefuzz::utils::try_wait_all_...
use crate::local::common::UiEvent; use anyhow::{Context, Result}; use crossterm::{ event::{self, Event, KeyCode}, execute, terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, }; use futures::{StreamExt, TryStreamExt}; use log::Level; use onefuzz::utils::try_wait_all_...
async fn ticking(ui_event_tx: mpsc::UnboundedSender<TerminalEvent>) -> Result<()> { let mut interval = tokio::time::interval(TICK_RATE); loop { interval.tick().await; if let Err(_err) = ui_event_tx.send(TerminalEvent::Tick) { break; } } ...
pub async fn run(self, timeout: Option<Duration>) -> Result<()> { enable_raw_mode()?; let mut stdout = io::stdout(); execute!(stdout, EnterAlternateScreen)?; let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; terminal.clear()?; ...
function_block-full_function
[ { "content": "pub fn digest_file_blocking(file: impl AsRef<Path>) -> Result<String> {\n\n let file = file.as_ref();\n\n let data = std::fs::read(file)\n\n .with_context(|| format!(\"unable to read file to generate digest: {}\", file.display()))?;\n\n Ok(hex::encode(Sha256::digest(&data)))\n\n}\n...
Rust
tests/auth_test.rs
andygrove/rust-etcd
c1e51b3dff285ab62fd4424b3d4607b33721f774
use etcd::auth::{self, AuthChange, NewUser, Role, RoleUpdate, UserUpdate}; use etcd::{BasicAuth, Client}; use futures::future::Future; use tokio::runtime::Runtime; #[test] fn auth() { let client = Client::new(&["http://etcd:2379"], None).unwrap(); let client_2 = client.clone(); let client_3 = client.clone(...
use etcd::auth::{self, AuthChange, NewUser, Role, RoleUpdate, UserUpdate}; use etcd::{BasicAuth, Client}; use futures::future::Future; use tokio::runtime::Runtime; #[test] fn auth() { let client = Client::new(&["http://etcd:2379"], None).unwrap(); let client_2 = client.clone(); let client_3 = client.clone(...
let role_name = &rkt_user.role_names()[0]; assert_eq!(role_name, "rkt"); let mut update_rkt_user = UserUpdate::new("rkt"); update_rkt_user.update_password("secret2"); update_rkt_user.grant_role("root"); auth::update_user(&authed_client_...
function_block-function_prefix_line
[]
Rust
src/bulk_string/mod.rs
WatchDG/rust-resp-protocol
b36689915d7fd3456a80165297a14d9e1a1257b6
use crate::RespError; use bytes::{BufMut, Bytes, BytesMut}; pub const EMPTY_BULK_STRING: BulkString = BulkString(Bytes::from_static(b"$0\r\n\r\n")); pub const NULL_BULK_STRING: BulkString = BulkString(Bytes::from_static(b"$-1\r\n")); #[derive(Debug, Clone, PartialEq)] pub struct BulkString(Bytes); impl BulkString { ...
use crate::RespError; use bytes::{BufMut, Bytes, BytesMut}; pub const EMPTY_BULK_STRING: BulkString = BulkString(Bytes::from_static(b"$0\r\n\r\n")); pub const NULL_BULK_STRING: BulkString = BulkString(Bytes::from_static(b"$-1\r\n")); #[derive(Debug, Clone, PartialEq)] pub struct BulkString(Bytes); impl BulkString { ...
} impl<'a> PartialEq<BulkString> for &'a BulkString { fn eq(&self, other: &BulkString) -> bool { self.0 == other.bytes() } fn ne(&self, other: &BulkString) -> bool { self.0 != other.bytes() } } #[cfg(test)] mod tests_bulk_string { use crate::{BulkString, EMPTY_BULK_STRING, NULL_BU...
pub fn parse(input: &[u8], start: &mut usize, end: &usize) -> Result<Self, RespError> { let mut index = *start; Self::while_valid(input, &mut index, end)?; let value = Self::from_slice(&input[*start..index]); *start = index; Ok(value) }
function_block-full_function
[ { "content": " #[inline]\n\n pub fn from_bytes(input: Bytes) -> Self {\n\n Self(input)\n\n }\n\n\n\n #[inline]\n\n pub fn from_slice(input: &[u8]) -> Self {\n\n let bytes = Bytes::copy_from_slice(input);\n\n Self::from_bytes(bytes)\n\n }\n\n\n\n #[inline]\n\n pub uns...
Rust
src/lib.rs
niuhuan/pixirust
8eeeebaf4e9cb9e7351a6f625c247375d8396644
pub mod entities; mod test; mod utils; pub use anyhow::Error; pub use anyhow::Result; pub use entities::*; use serde_json::json; use utils::*; const APP_SERVER: &'static str = "app-api.pixiv.net"; const APP_SERVER_IP: &'static str = "210.140.131.199"; const OAUTH_SERVER: &'static str = "oauth.secure.pixiv.net"; const...
pub mod entities; mod test; mod utils; pub use anyhow::Error; pub use anyhow::Result; pub use entities::*; use serde_json::json; use utils::*; const APP_SERVER: &'static str = "app-api.pixiv.net"; const APP_SERVER_IP: &'static str = "210.140.131.199"; const OAUTH_SERVER: &'static str = "oauth.secure.pixiv.net"; const...
/{}", APP.server).as_str()) { self.agent .get(url.replacen(APP.server, APP.ip.clone(), 1)) .header("Host", APP.server) } else { self.agent.get(url) } } false => self.agent.get(...
erde_json::from_str(resp.text().await?.as_str())?), _ => { let err: LoginErrorResponse = serde_json::from_str(resp.text().await?.as_str())?; Err(Error::msg(err.errors.system.message)) } } ...
random
[ { "content": "pub fn sha256(src: String) -> Vec<u8> {\n\n let mut hasher = Sha256::new();\n\n hasher.update(src.as_bytes());\n\n hasher.finalize().to_vec()\n\n}\n\n\n\n//////////////////////////////////////////////////\n", "file_path": "src/utils.rs", "rank": 0, "score": 71134.40215482653 ...
Rust
codecs/src/aper/mod.rs
nplrkn/hampi
0b07137ecef245d462c9f942bb219ad7bac2f434
#![allow(dead_code)] pub mod error; pub use error::Error as AperCodecError; pub mod decode; pub mod encode; pub trait AperCodec { type Output; fn decode(data: &mut AperCodecData) -> Result<Self::Output, AperCodecError>; fn encode(&self, _data: &mut AperCodecData) -> Result<(), AperCodecError> { ...
#![allow(dead_code)] pub mod error; pub use error::Error as AperCodecError; pub mod decode; pub mod encode; pub trait AperCodec { type Output; fn decode(data: &mut AperCodecData) -> Result<Self::Output, AperCodecError>; fn encode(&self, _data: &mut AperCodecData) -> Result<(), AperCodecError> { ...
FF }; let inner = inner as i64; inner as i128 } 64 => { let inner = self.bits[self.decode_offset..self.decode_offset + bits] .load_be::<u128>() as i64; ...
s_deref().unwrap(); let _ = self.advance_maybe_err(1, true)?; Ok(bit) } fn decode_bits_as_integer( &mut self, bits: usize, signed: bool, ) -> Result<i128, AperCodecError> { let remaining = self.bits.len() - self.decode_offset; if remaining < bits { ...
random
[ { "content": "/// Decode a Boolean\n\n///\n\n/// Decode a Boolean value. Returns the decoded value as a `bool`.\n\npub fn decode_bool(data: &mut AperCodecData) -> Result<bool, AperCodecError> {\n\n data.decode_bool()\n\n}\n\n\n", "file_path": "codecs/src/aper/decode/mod.rs", "rank": 0, "score": 2...
Rust
sdk/finspacedata/src/json_ser.rs
StevenBlack/aws-sdk-rust
f4a1458f0154318c47d7e6a4ac55226f400fbfbc
pub fn serialize_structure_crate_input_create_changeset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateChangesetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_1) = &input.change_type { object.key("changeType")....
pub fn serialize_structure_crate_input_create_changeset_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::CreateChangesetInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_1) = &input.change_type { object.key("changeType")....
r()); } Ok(()) } pub fn serialize_structure_crate_input_update_user_input( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::input::UpdateUserInput, ) -> Result<(), aws_smithy_http::operation::SerializationError> { if let Some(var_71) = &input.api_access { object.key...
ay_33.value().string(item_34.as_str()); } } array_33.finish(); } if let Some(var_35) = &input.client_token { object.key("clientToken").string(var_35.as_str()); } if let Some(var_36) = &input.description { object.key("description").string(var_36.as_str()); ...
random
[]
Rust
src/view/rikai.rs
Netdex/niinii
d2fa91f3c16b1bdc20d7799a79e1d354247cd55e
use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use ichiran::romanize::*; use imgui::*; use super::deepl::DeepLView; use super::mixins::*; use super::settings::{DisplayRubyText, SettingsView}; use crate::backend::renderer::Env; use crate::gloss::Gloss; use crate::translation::Translation; use crate:...
use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use ichiran::romanize::*; use imgui::*; use super::deepl::DeepLView; use super::mixins::*; use super::settings::{DisplayRubyText, SettingsView}; use crate::backend::renderer::Env; use crate::gloss::Gloss; use crate::translation::Translation; use crate:...
text(""); self.add_root(env, ui, settings, &gloss.root); if *show_raw { Window::new("Raw") .size([300., 110.], Condition::FirstUseEver) .opened(show_raw) .build(ui, || { RawView::new(&gloss.root...
self.translation.as_ref() } fn term_window( &self, env: &mut Env, ui: &Ui, settings: &SettingsView, romanized: &Romanized, ) -> bool { let mut opened = true; Window::new(&romanized.term().text().to_string()) .size_constraints([300.0...
random
[ { "content": "fn add_gloss(ui: &Ui, gloss: &Gloss) {\n\n TreeNode::new(&format!(\"Gloss ({} {})\", gloss.pos(), gloss.gloss()))\n\n .default_open(false)\n\n .build(ui, || {\n\n wrap_bullet(ui, &format!(\"pos: {}\", gloss.pos()));\n\n wrap_bullet(ui, &format!(\"gloss: {}\",...
Rust
src/pixel_task.rs
SharpCoder/hexagon2
0a565a263e5a3513c15e7e10ef75a9b6cd64efdb
use teensycore::*; use teensycore::clock::*; use teensycore::debug::blink_accumulate; use teensycore::math::rand; use teensycore::system::str::Str; use teensycore::system::str::StringOps; use teensycore::system::vector::Array; use teensycore::system::vector::Vector; use crate::date_time::DateTime; use crate::get_shader...
use teensycore::*; use teensycore::clock::*; use teensycore::debug::blink_accumulate; use teensycore::math::rand; use teensycore::system::str::Str; use teensycore::system::str::StringOps; use teensycore::system::vector::Array; use teensycore::system::vector::Vector; use crate::date_time::DateTime; use crate::get_shader...
fn get_next_effect(&self, shader: &Shader) -> Effect { let idx = rand() % self.effects.size() as u64; let next_effect = self.effects.get(idx as usize).unwrap(); if next_effect.disabled || next_effect.max_color_segments.unwrap...
if crate::USE_WIFI { let appropriate_shader = get_shader_configs().get_shader(crate::get_world_time()); match self.find_shader(&appropriate_shader) { None => return self.shaders.get(0).unwrap(), Some(shader) => { if shader.disabled { ...
function_block-function_prefix_line
[ { "content": "pub fn parse_http_request(rx_buffer: &Str, header: &mut Str, content: &mut Str) -> bool {\n\n // Ensure buffers are setup\n\n header.clear();\n\n content.clear();\n\n\n\n debug_str(b\"HELLO YES THIS IS DOG\");\n\n \n\n let mut content_length_cmp = str!(b\"Content-Length: \");\n\n...
Rust
src/lib.rs
tickbh/td_rthreadpool
d7f23f07b56777afdef2e3c89324339d2ee97a32
extern crate libc; use std::panic; use std::panic::AssertUnwindSafe; use std::sync::mpsc::{channel, Sender, Receiver, SyncSender, sync_channel, RecvError}; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; mod mutex; pub use mutex::{ReentrantMutex, ReentrantMutexGuard}; trait FnBox { fn call_box...
extern crate libc; use std::panic; use std::panic::AssertUnwindSafe; use std::sync::mpsc::{channel, Sender, Receiver, SyncSender, sync_channel, RecvError}; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; mod mutex; pub use mutex::{ReentrantMutex, ReentrantMutexGuard}; trait FnBox { fn call_box...
{ return; } } Err(..) => { retu...
.spawn(move || { loop { let result = panic::catch_unwind(AssertUnwindSafe(|| { let message = { let lock = job_...
random
[ { "content": "#[test]\n\nfn join_all_with_thread_panic() {\n\n let mut pool = ThreadPool::new(TEST_TASKS);\n\n for _ in 0..4 {\n\n pool.execute(move || {\n\n panic!();\n\n });\n\n }\n\n\n\n sleep(Duration::from_millis(1000));\n\n\n\n let active_count = pool.active_count()...
Rust
tests/asm.rs
jonas-schievink/x87
c24fe7ee4fd51ebb8411187a7e200bd80c9ea87c
#![feature(asm, untagged_unions)] #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[macro_use] extern crate x87; #[macro_use] extern crate proptest; extern crate env_logger; extern crate ieee754; use x87::{X87State, f80}; use ieee754::Ieee754; union X87StateUnion { raw: [u8; 108], structured: X87...
#![feature(asm, untagged_unions)] #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] #[macro_use] extern crate x87; #[macro_use] extern crate proptest; extern crate env_logger; extern crate ieee754; use x87::{X87State, f80}; use ieee754::Ieee754; union X87StateUnion { raw: [u8; 108], structured: X87...
fn add32(lhs_bits: u32, rhs_bits: u32) { let (lhs, rhs) = (f32::from_bits(lhs_bits), f32::from_bits(rhs_bits)); let mut native_f32_sum = 0.0f32; let mut native_f80_sum = [0u8; 10]; run_host_asm!(r" flds $1 flds $0 faddp fsts $2 fstpt $3 " : "=*m"(&lhs)...
p fstpl $0 " : "=*m"(&mut result80), "=*m"(&lhs), "=*m"(&rhs)); println!("{}+{}={}", lhs, rhs, result80); let result64 = lhs + rhs; assert_eq!(result64.to_bits(), result80.to_bits() + 1, "host FPU returned wrong result"); let (l80, r80) = (f80::from(lhs), f80::from(rhs)); let f80s...
function_block-function_prefixed
[]
Rust
05_recon/src/types.rs
lazear/types-and-programming-languages
0787493713b41639878db206e76d82fa8f29a77a
use std::collections::{HashMap, HashSet, VecDeque}; #[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Hash)] pub struct TypeVar(pub u32, pub u32); #[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Hash)] pub struct Tycon { id: usize, arity: usize, } #[derive(Clone, PartialEq, PartialOrd, Eq, Hash)] pu...
use std::collections::{HashMap, HashSet, VecDeque}; #[derive(Copy, Clone, Default, PartialEq, PartialOrd, Eq, Hash)] pub struct TypeVar(pub u32, pub u32); #[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Hash)] pub struct Tycon { id: usize, arity: usize, } #[derive(Clone, PartialEq, PartialOrd, Eq, Hash)] pu...
TypeVar { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str(&fresh_name(self.0)) } } impl std::fmt::Debug for Type { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Type::Var(x) => write!(f, "{:?}", x), Type::...
) as char; (0..x / 26) .map(|_| 'z') .chain(std::iter::once(last)) .collect::<String>() } impl std::fmt::Debug for
random
[ { "content": "fn var_bind(var: TypeVar, ty: Type) -> Result<HashMap<TypeVar, Type>, String> {\n\n if ty.occurs(var) {\n\n return Err(format!(\"Fails occurs check! {:?} {:?}\", var, ty));\n\n }\n\n let mut sub = HashMap::new();\n\n match ty {\n\n Type::Var(x) if x == var => {}\n\n ...
Rust
circuit/src/execution-delivery/src/lib.rs
xylix/t3rn
fda43863b640fae63988042addadc21a1bfa32de
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; use frame_support::traits::Get; use frame_system::offchain::{AppCrypto, CreateSignedTransaction, SignedPayload, SigningTypes}; use sp_core::crypto::KeyTypeId; use sp_runtime::{ transaction_validity::{InvalidTransaction, TransactionValidity,...
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; use frame_support::traits::Get; use frame_system::offchain::{AppCrypto, CreateSignedTransaction, SignedPayload, SigningTypes}; use sp_core::crypto::KeyTypeId; use sp_runtime::{ transaction_validity::{InvalidTransaction, TransactionValidity,...
ong io schedule"); for phase in inter_schedule.phases.clone() { for step in phase.steps { Self::deposit_event(Event::NewPhase(who.clone(), 0, step.compose.name.clone(...
<Self::BlockNumber>; #[pallet::constant] type UnsignedPriority: Get<TransactionPriority>; } #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet<T>(_); #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>...
random
[ { "content": "#[cfg(not(test))]\n\npub trait TestAuxiliaries {}\n\n#[cfg(not(test))]\n\nimpl<T> TestAuxiliaries for T {}\n\n\n", "file_path": "gateway/pallet-escrow-gateway/escrow-engine/versatile-wasm/src/gas.rs", "rank": 1, "score": 203546.12681136615 }, { "content": "#[cfg(not(test))]\n\n...
Rust
key_config/src/old_key_map.rs
NordGeit/MMAccel
a45b2f8eecb795cb784d3a89be70ee41e60c84a9
use crate::*; use std::io::BufRead; fn str_to_vk(k: &str) -> Option<u32> { match k.trim() { "esc" => Some(VK_ESCAPE.0 as u32), "tab" => Some(VK_TAB.0 as u32), "capslock" => Some(VK_CAPITAL.0 as u32), "shift" => Some(VK_SHIFT.0 as u32), "ctrl" => Some(VK_CONTROL.0 as u32), ...
use crate::*; use std::io::BufRead; fn str_to_vk(k: &str) -> Option<u32> { match k.trim() { "esc" => Some(VK_ESCAPE.0 as u32), "tab" => Some(VK_TAB.0 as u32), "capslock" => Some(VK_CAPITAL.0 as u32), "shift" => Some(VK_SHIFT.0 as u32), "ctrl" => Some(VK_CO
wrap(); let prev = data.0.iter().find(|item| item.id == "FramePrev").unwrap(); let mut keys = Keys::new(); keys.vk(b'A' as _); assert!(prev.keys.as_ref().unwrap() == &keys); let next = data.0.iter().find(|item| item.id == "FrameNext").unwrap(); let mut keys = Keys::new();...
NTROL.0 as u32), "alt" => Some(VK_MENU.0 as u32), "backspace" => Some(VK_BACK.0 as u32), "enter" => Some(VK_RETURN.0 as u32), "space" => Some(VK_SPACE.0 as u32), "printscreen" => Some(VK_SNAPSHOT.0 as u32), "pause" => Some(VK_PAUSE.0 as u32), "insert" => Some(VK_I...
random
[ { "content": "fn error(msg: &str) {\n\n message_box(None, msg, \"d3d9.dll エラー\", MB_OK | MB_ICONERROR);\n\n}\n\n\n\n#[inline]\n\nunsafe fn mmaccel_run(base_addr: usize) {\n\n if let Some(mmaccel) = MMACCEL.get() {\n\n let f = mmaccel.get::<unsafe fn(usize)>(b\"mmaccel_run\").unwrap();\n\n f(...
Rust
src/processor.rs
jswh/wslexe
964319b2cb2b830c54289138db7c2deeb3b938b9
use std::borrow::Cow; use std::env; use std::io::{self, Write}; use std::path::{Component, Path, Prefix, PrefixComponent}; use std::process; use std::process::{Command, Stdio}; use regex::bytes::Regex; fn get_drive_letter(pc: &PrefixComponent) -> Option<String> { let drive_byte = match pc.kind() { Prefix:...
use std::borrow::Cow; use std::env; use std::io::{self, Write}; use std::path::{Component, Path, Prefix, PrefixComponent}; use std::process; use std::process::{Command, Stdio}; use regex::bytes::Regex; fn get_drive_letter(pc: &PrefixComponent) -> Option<String> { let drive_byte = match pc.kind() { Prefix:...
fn shell_escape(arg: String) -> String { if arg.contains(" ") { return vec![String::from("\""), arg, String::from("\"")].join(""); } arg.replace("\n", "$'\n'"); arg.replace(";", "$';'") } pub fn execute(interactive: bool) { let mut exe_path = env::current_exe().unwrap(); exe_...
n translate_path_to_win(line: &[u8]) -> Cow<[u8]> { lazy_static! { static ref WSLPATH_RE: Regex = Regex::new(r"(?m-u)/mnt/(?P<drive>[A-Za-z])(?P<path>/\S*)") .expect("Failed to compile WSLPATH regex"); } WSLPATH_RE.replace_all(line, &b"${drive}:${path}"[..]) }
function_block-function_prefixed
[ { "content": "fn main() {\n\n processor::execute(false)\n\n}\n", "file_path": "src/main.rs", "rank": 10, "score": 18098.30613938591 }, { "content": "fn main() {\n\n processor::execute(true)\n\n}\n", "file_path": "src/main_i.rs", "rank": 11, "score": 18098.30613938591 }, ...
Rust
packages/server/src/middleware/tests.rs
sogrim/technion-sogrim
6d9f86266252ac0b7348725a295aabca9eba5222
use crate::{config::CONFIG, init_mongodb_client, middleware, resources::user::User}; use actix_rt::test; use actix_web::{ http::StatusCode, test::{self}, web::{self, Bytes}, App, }; use actix_web_lab::middleware::from_fn; use dotenv::dotenv; use mongodb::Client; #[test] async fn test_from_request_no_db...
use crate::{config::CONFIG, init_mongodb_client, middleware, resources::user::User}; use actix_rt::test; use actix_web::{ http::StatusCode, test::{self}, web::{self, Bytes}, App, }; use actix_web_lab::middleware::from_fn; use dotenv::dotenv; use mongodb::Client; #[test] async fn test_from_request_no_db...
t_header(("authorization", "bugo-the-debugo")) .send_request(&app) .await; assert!(resp.status().is_server_error()); assert_eq!( Bytes::from("JwtDecoder not initialized"), test::read_body(resp).await ); } #[test] async fn test_auth_mw_client_errors() { let token_cl...
middleware::auth::authenticate)) .service(web::resource("/").route(web::get().to(|| async { "Shouldn't get here" }))), ) .await; let resp = test::TestRequest::get() .uri("/") .inser
function_block-random_span
[ { "content": "pub fn parse_copy_paste_data(data: &str) -> Result<Vec<CourseStatus>, AppError> {\n\n // Sanity validation\n\n if !(data.starts_with(\"גיליון ציונים\") && data.contains(\"סוף גיליון ציונים\"))\n\n {\n\n return Err(AppError::Parser(\"Invalid copy paste data\".into()));\n\n }\n\n\...
Rust
nonebot_rs/src/matcher/matchers/action.rs
abrahum/nonebot-rs
8c090098a10f574637fcad16fd74357e875bd43e
use super::{Matchers, MatchersBTreeMap, MatchersHashMap}; use crate::event::{MessageEvent, MetaEvent, NoticeEvent, RequestEvent}; use crate::matcher::{action::MatchersAction, Matcher}; use std::collections::{BTreeMap, HashMap}; use tokio::sync::broadcast; impl Matchers { pub fn new( message: Option<Ma...
use super::{Matchers, MatchersBTreeMap, MatchersHashMap}; use crate::event::{MessageEvent, MetaEvent, NoticeEvent, RequestEvent}; use crate::matcher::{action::MatchersAction, Matcher}; use std::collections::{BTreeMap, HashMap}; use tokio::sync::broadcast; impl Matchers { pub fn new( message: Option<Ma...
} self } pub fn add_notice_matcher(&mut self, matcher: Matcher<NoticeEvent>) -> &mut Self { Matchers::add_matcher(&mut self.notice, matcher, self.action_sender.clone()); self } pub fn add_request_matcher(&mut self, matcher: Matcher<RequestEvent>) -> &mut Self { ...
).await; lock_handler.load_config(data.clone()); } } } } f(&self.message, &self.config).await; f(&self.notice, &self.config).await; f(&self.request, &self.config).await; f(&self.meta, &self.config).await; ...
random
[ { "content": "#[doc(hidden)]\n\nfn command_start_(event: &mut MessageEvent, config: BotConfig) -> bool {\n\n let raw_message = remove_space(&event.get_raw_message());\n\n let command_starts = config.command_starts;\n\n if command_starts.is_empty() {\n\n return true;\n\n }\n\n for sc in &co...
Rust
src/bitwidth.rs
Robbepop/apin
0b863c6f5dfcee22e6c2f4ead88bce9814788fc2
use crate::{ mem::NonZeroUsize, storage::Storage, BitPos, Digit, Error, Result, ShiftAmount, }; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct BitWidth(NonZeroUsize); impl BitWidth { #[inline] pub fn w1() -> Self { BitWidth(NonZeroUsize:...
use crate::{ mem::NonZeroUsize, storage::Storage, BitPos, Digit, Error, Result, ShiftAmount, }; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct BitWidth(NonZeroUsize); impl BitWidth { #[inline] pub fn w1() -> Self { BitWidth(NonZeroUsize:...
#[inline] pub(crate) fn is_valid_pos<P>(self, pos: P) -> bool where P: Into<BitPos>, { pos.into().to_usize() < self.to_usize() } #[inline] pub(crate) fn is_valid_shift_amount<S>(self, shift_amount: S) -> bool where S: Into<ShiftAmount>, { ...
h == 0 { return Err(Error::invalid_zero_bitwidth()) } Ok(BitWidth(NonZeroUsize::new(width).unwrap())) }
function_block-function_prefixed
[]
Rust
src/borrows.rs
TimonPost/legion
43acaaa1b68e177636c618f63aaf6f5cf8f10558
use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::ops::DerefMut; use std::slice::Iter; use std::slice::IterMut; use std::sync::atomic::{AtomicIsize, Ordering}; pub enum Borrow<'a> { Read { state: &'a AtomicIsize }, Write { state: &'a AtomicIsize }, } impl<'a> Borrow<'a> { pub ...
use std::fmt::Debug; use std::fmt::Display; use std::ops::Deref; use std::ops::DerefMut; use std::slice::Iter; use std::slice::IterMut; use std::sync::atomic::{AtomicIsize, Ordering}; pub enum Borrow<'a> { Read { state: &'a AtomicIsize }, Write { state: &'a AtomicIsize }, } impl<'a> Borrow<'a> { pub ...
i: usize) -> Option<BorrowedMut<'a, T>> { let slice = self.slice; let state = self.state; slice.get_mut(i).map(|x| BorrowedMut::new(x, state)) } } impl<'a, T: 'a> Deref for BorrowedMutSlice<'a, T> { type Target = [T]; fn deref(&self) -> &Self::Target { self.slice } } ...
if x < 0 => Err("resource already borrowed as mutable"), _ => Err("resource already borrowed as immutable"), } } } impl<'a> Drop for Borrow<'a> { fn drop(&mut self) { match *self { Borrow::Read { state } => { state.fetch_sub(1, Ordering::SeqCst); ...
random
[ { "content": "/// A type which can fetch a strongly-typed view of the data contained\n\n/// within a `Chunk`.\n\npub trait View<'a>: Sized + Send + Sync + 'static {\n\n /// The iterator over the chunk data.\n\n type Iter: Iterator + 'a;\n\n\n\n /// Pulls data out of a chunk.\n\n fn fetch(chunk: &'a ...
Rust
src/route.rs
quarterblue/-kademlia-dht
de82d5407922f97a6b7885c9dea4828b7ed04f55
use crate::node::{Bit, ByteString, Node, ID_LENGTH}; use std::cell::RefCell; use std::iter::Iterator; use std::rc::Rc; use std::rc::Weak; const K_BUCKET_SIZE: usize = 4; type LeafNode = Option<Rc<RefCell<Vertex>>>; #[derive(Debug)] pub struct KBucket { node_bucket: Vec<Node>, depth: usize, } impl KBucket ...
use crate::node::{Bit, ByteString, Node, ID_LENGTH}; use std::cell::RefCell; use std::iter::Iterator; use std::rc::Rc; use std::rc::Weak; const K_BUCKET_SIZE: usize = 4; type LeafNode = Option<Rc<RefCell<Vertex>>>; #[derive(Debug)] pub struct KBucket { node_bucket: Vec<Node>, depth: usize, } impl KBucket ...
vertex.borrow_mut().left = left_vert; vertex.borrow_mut().right = right_vert; } Vertex::add_node(vertex, node, node_iter, &node_id, false); } ...
match node_iter_next { 1 => { if !matches!(vert.bit, Bit::One) { split = false; } } ...
random
[ { "content": "pub fn deserialize_message(v: Vec<u8>) -> Message {\n\n bincode::deserialize(&v).expect(\"Could not serialize message\")\n\n}\n\n\n", "file_path": "src/rpc.rs", "rank": 1, "score": 65682.53778056285 }, { "content": "pub fn serialize_message(msg: Message) -> Vec<u8> {\n\n ...
Rust
sulis_module/src/generator/terrain_tiles.rs
ThyWoof/sulis
e89eda94a1a72228224e1926d307aa4c9228bdcb
use std::collections::HashMap; use std::io::Error; use std::rc::Rc; use crate::{ area::tile::{EdgeRules, TerrainKind, TerrainRules, Tile}, Module, }; use sulis_core::util::unable_to_create_error; #[derive(Clone)] pub struct TerrainTiles { pub id: String, pub base: Rc<Tile>, pub base_weight: u32,...
use std::collections::HashMap; use std::io::Error; use std::rc::Rc; use crate::{ area::tile::{EdgeRules, TerrainKind, TerrainRules, Tile}, Module, }; use sulis_core::util::unable_to_create_error; #[derive(Clone)] pub struct TerrainTiles { pub id: String, pub base: Rc<Tile>, pub base_weight: u32,...
} fn get_edge(prefix: &str, id: &str, edge_postfix: &str, dir_postfix: &str) -> Option<Rc<Tile>> { let tile_id = format!("{}{}{}{}", prefix, id, edge_postfix, dir_postfix); match Module::tile(&tile_id) { None => { trace!( "Edge tile with '{}', '...
Ok(EdgesList { inner_nw, inner_ne, inner_sw, inner_se, outer_n, outer_s, outer_e, outer_w, outer_se, outer_ne, outer_sw, outer_nw, outer_all, inner_ne_s...
call_expression
[]
Rust
src/i2s/rx_timing.rs
ForsakenHarmony/esp32c3-pac
7d9eb9a5b5a51077d1d1eb6c6efd186064b7149b
#[doc = "Reader of register RX_TIMING"] pub type R = crate::R<u32, super::RX_TIMING>; #[doc = "Writer for register RX_TIMING"] pub type W = crate::W<u32, super::RX_TIMING>; #[doc = "Register RX_TIMING `reset()`'s with value 0"] impl crate::ResetValue for super::RX_TIMING { type Type = u32; #[inline(always)] ...
#[doc = "Reader of register RX_TIMING"] pub type R = crate::R<u32, super::RX_TIMING>; #[doc = "Writer for register RX_TIMING"] pub type W = crate::W<u32, super::RX_TIMING>; #[doc = "Register RX_TIMING `reset()`'s with value 0"] impl crate::ResetValue for super::RX_TIMING { type Type = u32; #[inline(always)] ...
w: self } } #[doc = "Bits 16:17"] #[inline(always)] pub fn rx_ws_out_dm(&mut self) -> RX_WS_OUT_DM_W { RX_WS_OUT_DM_W { w: self } } #[doc = "Bits 0:1"] #[inline(always)] pub fn rx_sd_in_dm(&mut self) -> RX_SD_IN_DM_W { RX_SD_IN_DM_W { w: self } } }
} impl<'a> RX_WS_OUT_DM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } #[doc = "Reader of field `RX_SD_IN_DM`"] pub type RX_SD_...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
src/entity/manager.rs
Connicpu/conniecs
b914ff8a5ebc8214869f588aa21e2a11d695f306
use index_pool::IndexPool; use vec_map::VecMap; use std::collections::hash_map::HashMap; use std::marker::PhantomData; use std::mem; use crate::component::ComponentManager; use crate::entity::iter::{EntityIter, IndexedEntityIter}; use crate::entity::{BuildData, Entity, EntityBuilder, EntityData, Id, IndexedEntity}; u...
use index_pool::IndexPool; use vec_map::VecMap; use std::collections::hash_map::HashMap; use std::marker::PhantomData; use std::mem; use crate::component::ComponentManager; use crate::entity::iter::{EntityIter, IndexedEntityIter}; use crate::entity::{BuildData, Entity, EntityBuilder, EntityData, Id, IndexedEntity}; u...
} pub fn iter(&self) -> EntityIter<C> { EntityIter::Indexed(IndexedEntityIter { iter: self.indices.all_indices(), values: &self.indexed_entities, }) } pub fn count(&self) -> usize { self.indices.maximum() } pub fn indexed(&self, entity: Entity)...
if self.entities.contains_key(&entity) { self.event_queue.push(Event::RemoveEntity(entity)); true } else { false }
if_condition
[ { "content": "fn activated(_: &mut IVSystem, _: EntityData, _: &Components, _: &mut Services) {\n\n ATOMIC_BOOP.store(true, std::sync::atomic::Ordering::SeqCst);\n\n}\n\n\n", "file_path": "tests/aspects.rs", "rank": 0, "score": 173722.56101871424 }, { "content": "pub trait EntityBuilder<C...
Rust
tests/integration.rs
saltyrtc/saltyrtc-task-relayed-data-rs
c290b4ae7e1cbed145b16c34b17e1f6bf8380465
extern crate env_logger; #[macro_use] extern crate log; extern crate saltyrtc_client; extern crate saltyrtc_task_relayed_data; extern crate tokio_core; extern crate tokio_timer; use std::boxed::Box; use std::env; use std::fs::File; use std::io::Read; use std::path::Path; use std::sync::{Arc, RwLock}; use std::time::...
extern crate env_logger; #[macro_use] extern crate log; extern crate saltyrtc_client; extern crate saltyrtc_task_relayed_data; extern crate tokio_core; extern crate tokio_timer; use std::boxed::Box; use std::env; use std::fs::File; use std::io::Read; use std::path::Path; use std::sync::{Arc, RwLock}; use std::time::...
let rd_task_responder: &mut RelayedDataTask = (&mut **t_responder as &mut dyn Task) .downcast_mut::<RelayedDataTask>() .expect("Chosen task is not a RelayedDataTask"); let tx_initiator = rd_task_initiator.get_sender().unwrap(); let tx_responder = rd_task_respon...
let rd_task_initiator: &mut RelayedDataTask = (&mut **t_initiator as &mut dyn Task) .downcast_mut::<RelayedDataTask>() .expect("Chosen task is not a RelayedDataTask");
assignment_statement
[ { "content": "fn build_tests() -> (MutexGuard<'static, ()>, PathBuf) {\n\n let guard = match C_TEST_MUTEX.lock() {\n\n Ok(guard) => guard,\n\n Err(poisoned) => poisoned.into_inner(),\n\n };\n\n\n\n let out_dir = env!(\"OUT_DIR\");\n\n let build_dir = Path::new(out_dir).join(\"build\");...
Rust
src/test/instruction_tests/instr_vdbpsadbw.rs
ftilde/rust-x86asm
f6584b8cfe8e75d978bf7b83a67c69444fd3f161
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vdbpsadbw_1() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, ...
use instruction_def::*; use test::run_test; use Operand::*; use Reg::*; use RegScale::*; use RegType::*; use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; #[test] fn vdbpsadbw_1() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, ...
mask: Some(MaskReg::K7), broadcast: None, }, &[98, 243, 125, 207, 66, 20, 198, 73], OperandSize::Dword, ) } #[test] fn vdbpsadbw_11() { run_test( &Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM26)), oper...
me(Direct(XMM2)), operand4: Some(Literal8(93)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None, }, &[98, 243, 69, 142, 66, 202, 93], Oper...
random
[ { "content": "fn encode32_helper2(mnemonic: Mnemonic, operand1: Operand, operand2: Operand, expected: &Vec<u8>) {\n\n let instr = Instruction {\n\n mnemonic: mnemonic,\n\n operand1: Some(operand1),\n\n operand2: Some(operand2),\n\n operand3: None,\n\n operand4: None,\n\n ...
Rust
src/parser.rs
opp11/chemtool2
d8cace048c5adf2ed61ab503534c287304a57644
use std::str::CharRange; use elem::{PerElem, Molecule}; use error::{CTResult, CTError}; use error::CTErrorKind::InputError; pub struct Parser { pos: usize, input: String, paren_level: u32, } impl Parser { pub fn new(input: &str) -> Parser { Parser { pos: 0, input: String::from_str(input...
use std::str::CharRange; use elem::{PerElem, Molecule}; use error::{CTResult, CTError}; use error::CTErrorKind::InputError; pub struct Parser { pos: usize, input: String, paren_level: u32, } impl Parser { pub fn new(input: &str) -> Parser { Parser { pos: 0, input: String::from_str(input...
fn parse_element(&mut self) -> CTResult<Vec<PerElem>> { if self.eof() { return Err(CTError { kind: InputError, desc: "Found no periodic element".to_string(), pos: Some((self.pos, 1)) }); } let start_pos = self...
fn parse_periodic(&mut self) -> CTResult<Vec<PerElem>> { let mut elem = try!(self.parse_element()); if !self.eof() && self.peek_char().is_numeric() { let coef = try!(self.parse_coefficient()); for e in elem.iter_mut() { e.coef *= coef; } } ...
function_block-full_function
[ { "content": "/// Sorts the PerElems and groups those with the same name field.\n\n///\n\n/// Grouping of two (or more) PerElems means adding the coef field of the\n\n/// duplicate to the one already found, and then throwing away the duplicate.\n\n/// E.g. CH3CH3 would turn into C2H6.\n\npub fn group_elems(mut ...
Rust
rsnes/src/smp.rs
nat-rix/rsnes
05b68de39041e68fa65184c1842c1cd7108543d6
use crate::{ backend::AudioBackend as Backend, spc700::Spc700, timing::{Cycles, APU_CPU_TIMING_PROPORTION_NTSC, APU_CPU_TIMING_PROPORTION_PAL}, }; use save_state::{InSaveState, SaveStateDeserializer, SaveStateSerializer}; use save_state_macro::InSaveState; use std::sync::mpsc::{channel, Receiver, RecvError,...
use crate::{ backend::AudioBackend as Backend, spc700::Spc700, timing::{Cycles, APU_CPU_TIMING_PROPORTION_NTSC, APU_CPU_TIMING_PROPORTION_PAL}, }; use save_
mple) } } match action { Some(Action::WriteInputPort { addr, data }) => { spc.input[usize::from(addr & 3)] = data } Some(Action::ReadOutputPort { addr }) => { ...
state::{InSaveState, SaveStateDeserializer, SaveStateSerializer}; use save_state_macro::InSaveState; use std::sync::mpsc::{channel, Receiver, RecvError, Sender}; #[derive(Debug, Clone)] enum Action { WriteInputPort { addr: u8, data: u8 }, ReadOutputPort { addr: u8 }, } #[derive(Debug, Clone)] enum ThreadComma...
random
[ { "content": "pub trait AccessType<B: crate::backend::AudioBackend, FB: crate::backend::FrameBuffer> {\n\n fn read<D: Data>(device: &mut Device<B, FB>, addr: Addr24) -> D;\n\n fn write<D: Data>(device: &mut Device<B, FB>, addr: Addr24, val: D);\n\n fn cpu(device: &Device<B, FB>) -> &Cpu;\n\n fn cpu_...
Rust
src/serialization/database.rs
MDeiml/attomath
4aac4dad3cd776dd2cb1602aa930c04c315d5186
use crate::{error::ProofError, expression::SingleSubstitution, Identifier, Theorem}; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq)] pub struct Database { names: HashMap<String, (usize, usize)>, theorems: Vec<(Theorem, Proof<usize>, Option<String>)>, last_name: usize, } #[derive(Debug, Part...
use crate::{error::ProofError, expression::SingleSubstitution, Identifier, Theorem}; use std::collections::HashMap; #[derive(Debug, PartialEq, Eq)] pub struct Database { names: HashMap<String, (usize, usize)>, theorems: Vec<(Theorem, Proof<usize>, Option<String>)>, last_name: usize, } #[derive(Debug, Part...
fn reverse_id(&self, id: usize, current_id: usize) -> (Option<&str>, Option<usize>) { if let Some(name) = &self.theorems[id].2 { (Some(name), None) } else if id == current_id - 1 { (None, None) } else if id >= self.last_name { (None, Some(id - self.last_...
pub fn substitute(&mut self, theorem: Theorem) -> Result<(), DatabaseError> { let last = &mut self .theorems .last_mut() .ok_or(DatabaseError::TheoremNotFound(None, None))? .0; let mut theorem_standardized = theorem.clone(); theorem_standardized.st...
function_block-full_function
[ { "content": "pub fn or_fail<I, O, E: ParseError<I>, F>(mut f: F) -> impl FnMut(I) -> IResult<I, O, E>\n\nwhere\n\n F: Parser<I, O, E>,\n\n{\n\n move |input| {\n\n f.parse(input).map_err(|error| match error {\n\n nom::Err::Error(e) => nom::Err::Failure(e),\n\n e => e,\n\n ...
Rust
socrates-core/src/service/registry.rs
ckaran/socrates-rs
450f364e38cf663367c36991a99cd8b689d76768
use hashbrown::HashMap; use super::*; pub struct RegisteredService { core_props: ServiceCoreProps, type_id: TypeId, name: Arc<str>, owner_id: DynamodId, used_by_count: HashMap<DynamodId, u32>, service_object: Arc<dyn Service>, } impl RegisteredService { pub fn make_service_ref(&self) -> ...
use hashbrown::HashMap; use super::*; pub struct RegisteredService { core_props: ServiceCoreProps, type_id: TypeId, name: Arc<str>, owner_id: Dyn
.expect("unsynced registry!"); let svc_ref = rs.make_service_ref(); if !rs.used_by_count.is_empty() { self.zombies.insert(svc_id, rs); } else { println!("Dropping service (no users): {:?}", rs.make_...
amodId, used_by_count: HashMap<DynamodId, u32>, service_object: Arc<dyn Service>, } impl RegisteredService { pub fn make_service_ref(&self) -> ServiceRef { ServiceRef { core: self.core_props.clone(), name: (*(self.name)).into(), type_id: self.type_id, ...
random
[ { "content": "pub trait Named {\n\n fn type_name() -> &'static str;\n\n}\n\n\n", "file_path": "socrates-core/src/service/service.rs", "rank": 0, "score": 67362.85685948143 }, { "content": "#[inline(always)]\n\npub fn service_name<T: Named + ?Sized>() -> &'static str {\n\n <T>::type_nam...
Rust
src/gf/gf_num.rs
irreducible-polynoms/irrpoly-rust
b4d5e023fb02ddf32e4fd56b417a5cc89b2295f2
use crate::Gf; use std::vec::Vec; use std::fmt; use std::ops; use std::cmp; #[derive(Debug, Clone)] pub struct GfNum { field: Gf, num: usize, } impl fmt::Display for GfNum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.num) } } impl GfNum { pub fn new(fie...
use crate::Gf; use std::vec::Vec; use std::fmt; use std::ops; use std::cmp; #[derive(Debug, Clone)] pub struct GfNum { field: Gf, num: usize, } impl fmt::Display for GfNum { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.num) } } impl GfNum { pub fn new(fie...
} impl ops::SubAssign<GfNum> for GfNum { fn sub_assign(&mut self, other: GfNum) { debug_assert_eq!(self.field(), other.field(), "Numbers from different fields"); let base = self.field().base(); self.num = (base + self.num - other.num) % base; } } impl ops::SubAssign<usize> for GfNum {...
s.field().base(); GfNum { field: rhs.field, num: (base + rhs.num - (self % base)) % base } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn not_a_field() {\n\n assert!(Gf::new(0).is_err());\n\n assert!(Gf::new(1).is_err());\n\n assert!(Gf::new(4).is_err());\n\n assert!(Gf::new(isize::max_value() as usize).is_err());\n\n}\n\n\n", "file_path": "src/gf/tests.rs", "rank": 0, "score": 54802.98112542429...
Rust
src/equalizer.rs
joaocarvalhoopen/Audio_filters_in_Rust
00639f0c30078a5fd3f39a690243f5742743ae02
use crate::iir_filter::ProcessingBlock; use crate::iir_filter::IIRFilter; use crate::butterworth_filter::make_peak_eq_constant_q; pub struct Equalizer { sample_rate: u32, bands_vec: Vec<f64>, bands_gain_vec: Vec<f64>, gain_max_db: f64, gain_min_db: f64, q_factor: f6...
use crate::iir_filter::ProcessingBlock; use crate::iir_filter::IIRFilter; use crate::butterworth_filter::make_peak_eq_constant_q; pub struct Equalizer { sample_rate: u32, bands_vec: Vec<f64>, bands_gain_vec: Vec<f64>, gain_max_db: f64, gain_min_db: f64, q_factor: f6...
self.iir_filters_vec.push(iir_filter); } } fn change_filter(& mut self, index: usize) { assert!(index < self.bands_vec.len()); let frequency_center = self.bands_vec[index]; let gain_db = self.bands_gain_vec[index]; let q_factor = Some(self.q_factor); ...
or band in & self.bands_vec { let frequency_center = *band; let gain_db = 0.0; let iir_filter = make_peak_eq_constant_q(frequency_center, self.sample_rate, gain_db, Some(self.q_factor));
function_block-random_span
[ { "content": "/// Creates a low-pass filter\n\n///\n\n/// In Python: \n\n/// >>> filter = make_lowpass(1000, 48000)\n\n/// >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE\n\n/// [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.004277569313094809,\n\n/// 0.00855...
Rust
sandbox/src/tilemap.rs
aengusmcmillin/Gouda
4aed65c94ad4147372d71c08622dacf01f5eac4e
use gouda::rendering::{drawable::{TextureDrawable, QuadDrawable}, Renderer, Scene, texture::RenderableTexture}; use gouda::ecs::{ECS, Entity, GenIndex}; use std::rc::Rc; use crate::camera::Camera; use gouda::bmp::Bitmap; use gouda::mouse_capture::{MouseCaptureArea, MouseCaptureLayer, ActiveCaptureLayer}; use gouda::typ...
use gouda::rendering::{drawable::{TextureDrawable, QuadDrawable}, Renderer, Scene, texture::RenderableTexture}; use gouda::ecs::{ECS, Entity, GenIndex}; use std::rc::Rc; use crate::camera::Camera; use gouda::bmp::Bitmap; use gouda::mouse_capture::{MouseCaptureArea, MouseCaptureLayer, ActiveCaptureLayer}; use gouda::typ...
fn create_tile(ecs: &mut ECS, color: [f32; 3], x: usize, y: usize) -> Entity { let renderer = ecs.read_res::<Rc<Renderer>>(); let quad = QuadDrawable::new(false, renderer, color, [-5. + x as f32 * 1., -3. + y as f32 * 1., 0.], [0.5, 0.5, 1.], [0.; 3]); let tile = Tile { color_d...
occupied: false, x: x as i32 - 5, y: y as i32 - 3, neighbors: [None; 4], }; ecs.build_entity().add(tile).add(MouseCaptureArea::new(Bounds{x: x as i32 * 80, y: y as i32 * 80 + 160, w: 80, h: 80})).entity() }
function_block-function_prefix_line
[ { "content": "pub fn win32_process_keyboard(keyboard: &mut KeyboardInput, vkcode: i32, was_down: bool, is_down: bool) {\n\n if was_down != is_down {\n\n if vkcode == VK_UP {\n\n win32_process_keyboard_message(\n\n &mut keyboard.special_keys[SpecialKeys::UpArrow],\n\n ...
Rust
src/lib.rs
DownToZero-Cloud/dtz-identity-auth
a93d6ca8472680fd8d1d7f6dc4082e5726aa5438
#![deny(missing_docs)] #![feature(adt_const_params)] use serde::{Serialize,Deserialize}; use axum::{ async_trait, extract::{FromRequest, RequestParts}, http::header::HeaderValue, http::{StatusCode}, }; use uuid::Uuid; use jwt::PKeyWithDigest; use openssl::hash::MessageDigest; use openssl::pkey::PKey; use jwt::...
#![deny(missing_docs)] #![feature(adt_const_params)] use serde::{Serialize,Deserialize}; use axum::{ async_trait, extract::{FromRequest, RequestParts}, http::header::HeaderValue, http::{StatusCode}, }; use uuid::Uuid; use jwt::PKeyWithDigest; use openssl::hash::MessageDigest; use openssl::pkey::PKey; use jwt::...
}else { let query = req.uri().query().unwrap_or_default(); let value: GetAuthParams = serde_urlencoded::from_str(query).unwrap(); if value.api_key.is_some() { if value.context_id.is_some() { profile = verifiy_api_key(&value.api_key.unwrap(), Some(&value.context_id.unwrap())).await.unwr...
if header_context_id.is_some() { profile = verifiy_api_key(header_api_key.to_str().unwrap(), Some(header_context_id.unwrap().to_str().unwrap())).await.unwrap(); }else{ profile = verifiy_api_key(header_api_key.to_str().unwrap(), None).await.unwrap(); }
if_condition
[ { "content": "# 0.4.10 2022-04-30\n\n\n\n* fix unparsable cookie\n\n\n\n# 0.4.9 2022-04-20\n\n\n\n* fail on invalid jwts\n\n\n\n# 0.4.8 2022-04-17\n\n\n\n* add verify_role functions\n\n\n\n# 0.4.7 2022-03-11\n\n\n\n* support foreign cookies\n\n\n\n# 0.4.6 2022-03-11\n\n\n\n* update deps\n\n\n\n# 0.4.4 2022-03-1...
Rust
examples/capture-test.rs
petrosagg/differential-dataflow
2e38abbb62aedf02cb9b6b5debb73c29b6e97dbb
extern crate rand; extern crate timely; extern crate differential_dataflow; extern crate serde; extern crate rdkafka; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use timely::dataflow::operators::probe::Handle; use differential_dataflow::input::Input; use differential_dataflow::Collection; use dif...
extern crate rand; extern crate timely; extern crate differential_dataflow; extern crate serde; extern crate rdkafka; use rand::{Rng, SeedableRng, StdRng}; use timely::dataflow::*; use timely::dataflow::operators::probe::Handle; use differential_dataflow::input::Input; use differential_dataflow::Collection; use dif...
pub mod kafka { use serde::{Serialize, Deserialize}; use timely::scheduling::SyncActivator; use rdkafka::{ClientContext, config::ClientConfig}; use rdkafka::consumer::{BaseConsumer, ConsumerContext}; use rdkafka::error::{KafkaError, RDKafkaError}; use differential_dataflow::capture::Writer; ...
e>) -> Collection<G, (Node, u32)> where G::Timestamp: Lattice+Ord { let nodes = roots.map(|x| (x, 0)); nodes.iterate(|inner| { let edges = edges.enter(&inner.scope()); let nodes = nodes.enter(&inner.scope()); inner.join_map(&edges, |_k,l,d| (*d, l+1)) .concat(&...
function_block-function_prefixed
[ { "content": "// Type aliases for differential execution.\n\ntype Time = u32;\n", "file_path": "doop/src/main.rs", "rank": 0, "score": 294510.99856603285 }, { "content": "type Node = u32;\n\n\n", "file_path": "src/trace/implementations/graph.rs", "rank": 1, "score": 289060.656315...
Rust
src/lib.rs
incident-recipient/gherkin-rust
7668c349ced30d5332821538ce321737cdbbacec
mod parser; pub mod tagexpr; pub use peg::error::ParseError; pub use peg::str::LineCol; use typed_builder::TypedBuilder; use std::path::{Path, PathBuf}; #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Background { pub steps: Vec<Step>, #[builder(default)] pub span: (usi...
mod parser; pub mod tagexpr; pub use peg::error::ParseError; pub use peg::str::LineCol; use typed_builder::TypedBuilder; use std::path::{Path, PathBuf}; #[derive(Debug, Clone, TypedBuilder, P
e { Some(v) => Some(&v), None => None, } } } impl std::fmt::Display for Step { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} {}", &self.raw_type, &self.value) } }
artialEq, Hash, Eq)] pub struct Background { pub steps: Vec<Step>, #[builder(default)] pub span: (usize, usize), #[builder(default)] pub position: (usize, usize), } #[derive(Debug, Clone, TypedBuilder, PartialEq, Hash, Eq)] pub struct Examples { pub table: Table, #[...
random
[ { "content": "//! let op: TagOperation = \"@a and @b\".parse()?;\n\n//! # Ok(())\n\n//! # }\n\n//! ```\n\n\n\nuse std::str::FromStr;\n\n\n\nimpl FromStr for TagOperation {\n\n type Err = peg::error::ParseError<peg::str::LineCol>;\n\n\n\n fn from_str(s: &str) -> Result<Self, Self::Err> {\n\n crate::...