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
finiteelement_macros/src/autoimplementable.rs
thenlevy/codenano
3857afa5d28b4d354b6d31a0287434b08ed726ed
use crate::formal::{Float, FormalVector}; use proc_macro::TokenStream; use std::collections::HashMap; pub trait AutoImplementable<F: Float> { fn elt_list() -> Vec<String>; fn cst_list() -> Vec<String>; fn formal_map() -> HashMap<String, FormalVector<F>>; ...
use crate::formal::{Float, FormalVector}; use proc_macro::TokenStream; use std::collections::HashMap; pub trait AutoImplementable<F: Float> { fn elt_list() -> Vec<String>; fn cst_list() -> Vec<String>; fn formal_map() -> HashMap<String, FormalVector<F>>; ...
#[doc(hidden)] fn appl_force(struct_name: String, point_name: String, arg_list: String) -> String { vec![("x", "0"), ("y", "1"), ("z", "2")] .iter() .map(|(s, s_)| { format!( "forces[3 * self.{0} + {3}] = forces[3 * self.{0} + {3}] + {4}_force_{0}_{1}({2});", ...
fn struct_def<F: Float, T: AutoImplementable<F>>() -> String { let elt = T::elt_list() .iter() .map(|s| format!("pub {}: usize,", s)) .collect::<Vec<String>>() .join("\n"); let cst = T::cst_list() .iter() .map(|s| format!("pub {}: F,", s)) .collect::<Vec<S...
function_block-full_function
[ { "content": "/// A trait for updating the forces vector and its jacobian in a finite element system.\n\n///\n\n/// The piece of code that implements that trait can be generated by procedurals macros.\n\npub trait FiniteElement<F: Float> {\n\n /// Updates the force vector.\n\n ///\n\n /// For each poin...
Rust
saltwater-parser/lex/tests.rs
afonso360/saltwater
d1361619394327aad25a87c5205d776e619b060d
use super::{CompileResult, LiteralToken, Locatable, Token}; use crate::data::hir::LiteralValue; use crate::data::lex::test::{cpp, cpp_no_newline}; use crate::intern::InternedStr; use arcstr::Substr; type LexType = CompileResult<Locatable<Token>>; fn lex(input: &str) -> Option<LexType> { let mut lexed = lex_all(in...
use super::{CompileResult, LiteralToken, Locatable, Token}; use crate::data::hir::LiteralValue; use crate::data::lex::test::{cpp, cpp_no_newline}; use crate::intern::InternedStr; use arcstr::Substr; type LexType = CompileResult<Locatable<Token>>; fn lex(input: &str) -> Option<LexType> { let mut lexed = lex_all(in...
; assert_overflow("'\\xfff'"); assert_overflow("'\\xfffffffffffffffffffffffffff'"); assert_overflow(r"'\xff00000000000000ff'"); } #[test] fn test_no_newline() { assert!(cpp_no_newline("").next().is_none()); let mut tokens: Vec<_> = cpp_no_newline(" ").filter(is_not_whitespace).collect(); assert...
match lex(c).unwrap().unwrap_err().data { Error::Lex(LexError::CharEscapeOutOfRange(Radix::Hexadecimal)) => {} _ => panic!("expected overflow error for {}", c), }
if_condition
[ { "content": "fn state_machine<B: BufRead>(reader: &mut B) -> Result<String, io::Error> {\n\n const COMMENT: &str = \"// \";\n\n let mut expected_out = String::new();\n\n for line in reader.lines() {\n\n let line = dbg!(line?);\n\n if line == \"// END\" {\n\n break;\n\n ...
Rust
tools/mkinitrd/src/main.rs
neri/toe
8442f82bce551ce27b23b24336a285f25d422e98
use byteorder::*; use std::{env, fs::File, io::Read, io::Write, path::Path, process}; fn usage() -> ! { let mut args = env::args_os(); let arg = args.next().unwrap(); let path = Path::new(&arg); let lpc = path.file_name().unwrap(); eprintln!("{} [OPTIONS] OUTPUT [FILES...]", lpc.to_str().unwrap()...
use byteorder::*; use std::{env, fs::File, io::Read, io::Write, path::Path, process}; fn usage() -> ! { let mut args = env::args_os(); let arg = args.next().unwrap(); let path = Path::new(&arg); let lpc = path.file_name().unwrap(); eprintln!("{} [OPTIONS] OUTPUT [FILES...]", lpc.to_str().unwrap()...
} pub fn as_bytes(&self) -> &[u8; 32] { unsafe { core::mem::transmute(self) } } } pub struct InitRamfs { blob: Vec<u8>, dir: Vec<DirEnt>, } impl InitRamfs { const PADDING: usize = 16; pub const fn new() -> Self { Self { blob: Vec::new(), dir: Vec:...
Some(Self { flag, name: array, _reserved: (0, 0), offset: 0, file_size: 0, })
call_expression
[]
Rust
watchman/rust/serde_bser/src/value.rs
ryaminal/watchman
c64b61db1de9c4964504e988bbdf7f671486c628
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::bytestring::ByteString; use serde::de::{Deserialize, MapAccess, SeqAccess, Visitor}; use serde::Serialize; use std::coll...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::bytestring::ByteString; use serde::de::{Deserialize, MapAccess, SeqAccess, Visitor}; use serde::Serialize; use std::coll...
}
n()))?; for (k, v) in m { map.serialize_key(k)?; map.serialize_value(v)?; } map.end() } } }
function_block-function_prefixed
[ { "content": " @Test\n\n public void throwIfMapKeyNotString() throws IOException {\n\n thrown.expect(IOException.class);\n\n thrown.expectMessage(\"Unrecognized BSER object key type 3, expected string\");\n\n BserDeserializer deserializer = new BserDeserializer(BserDeserializer.KeyOrdering.UNSORTED);...
Rust
src/structs/drawing/charts/chart_space.rs
SamuelMarks/umya-spreadsheet
78e7142e2f385f081e23b983d520f2165e7dd129
use super::Date1904; use super::EditingLanguage; use super::RoundedCorners; use structs::office2010::drawing::charts::Style; use super::Chart; use super::ShapeProperties; use super::PrintSettings; use structs::Spreadsheet; use writer::driver::*; use quick_xml::Reader; use quick_xml::events::{Event, BytesStart}; use qu...
use super::Date1904; use super::EditingLanguage; use super::RoundedCorners; use structs::office2010::drawing::charts::Style; use super::Chart; use super::ShapeProperties; use super::PrintSettings; use structs::Spreadsheet; use writer::driver::*; use quick_xml::Reader; use quick_xml::events::{Event, BytesStart}; use qu...
pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>, spreadsheet: &Spreadsheet) { write_start_tag(writer, "c:chartSpace", vec![ ("xmlns:c", "http://schemas.openxmlformats.org/drawingml/2006/chart"), ("xmlns:a", "http://schemas.openxmlformats.org/drawingml/20...
pub(crate) fn set_attributes<R: std::io::BufRead>( &mut self, reader:&mut Reader<R>, _e:&BytesStart, ) { let mut buf = Vec::new(); loop { match reader.read_event(&mut buf) { Ok(Event::Start(ref e)) => { match e.name() { ...
function_block-full_function
[ { "content": "pub fn read<R: io::Read + io::Seek>(arv: &mut zip::ZipArchive<R>, spreadsheet:&mut Spreadsheet) -> result::Result<(), XlsxError> {\n\n let r = io::BufReader::new(arv.by_name(FILE_PATH)?);\n\n let mut reader = Reader::from_reader(r);\n\n reader.trim_text(true);\n\n let mut buf = Vec::ne...
Rust
crates/holochain/src/core/workflow/produce_dht_ops_workflow.rs
pjkundert/holochain
e0681530633b07c6cfe49948ef653a77a043bdbe
use super::error::WorkflowResult; use crate::core::queue_consumer::OneshotWriter; use crate::core::queue_consumer::TriggerSender; use crate::core::queue_consumer::WorkComplete; use holochain_lmdb::buffer::KvBufFresh; use holochain_lmdb::db::AUTHORED_DHT_OPS; use holochain_lmdb::prelude::BufferedStore; use holochain_lmd...
use super::error::WorkflowResult; use crate::core::queue_consumer::OneshotWriter; use crate::core::queue_consumer::TriggerSender; use crate::core::queue_consumer::WorkComplete; use holochain_lmdb::buffer::KvBufFresh; use holochain_lmdb::db::AUTHORED_DHT_OPS; use holochain_lmdb::prelude::BufferedStore; use holochain_lmd...
}) .collect(), ); } env_ref .with_commit(|writer| source_chain.flush_to_txn(writer)) .unwrap(); all_ops .iter() .flatten() .map(|o| DhtOp...
if let DhtOp::StoreEntry(_, _, _) = op { false } else { true }
if_condition
[ { "content": "pub fn dump_state(env: EnvironmentRead) -> WorkspaceResult<IntegrationStateDump> {\n\n let workspace = IncomingDhtOpsWorkspace::new(env.clone())?;\n\n let (validation_limbo, integration_limbo, integrated) = fresh_reader!(env, |r| {\n\n let v = workspace.validation_limbo.iter(&r)?.coun...
Rust
src/db_manager/redis_db_manager.rs
fossabot/ktra
5dd9fb5b3b5d65a6665492105eca3ea827158d6d
#![cfg(feature = "db-redis")] use crate::config::DbConfig; use crate::error::Error; use crate::models::{Entry, Metadata, Query, Search, User}; use argon2::{self, hash_encoded, verify_encoded}; use async_trait::async_trait; use futures::TryFutureExt; use redis::{AsyncCommands, Client}; use semver::Version; use serde::d...
#![cfg(feature = "db-redis")] use crate::config::DbConfig; use crate::error::Error; use crate::models::{Entry, Metadata, Query, Search, User}; use argon2::{self, hash_encoded, verify_encoded}; use async_trait::async_trait; use futures::TryFutureExt; use redis::{AsyncCommands, Client}; use semver::Version; use serde::d...
let name = metadata.name.clone(); let version = metadata.vers.clone(); let mut entry = self.entry(&name).await?; if entry.is_empty() { entry.owner_ids_mut().push(owner_id); } if !entry.owner_ids().contains(&owner_id) { return Err...
ry.owner_ids_mut().extend(ids); entry.owner_ids_mut().sort_unstable(); entry.owner_ids_mut().dedup(); }) .await } #[tracing::instrument(skip(self, name, logins))] pub async fn remove_owners(&self, name: &str, logins: &[String]) -> Result<(), Error> { self.edi...
random
[ { "content": "#[tracing::instrument(skip(name))]\n\npub fn check_crate_name(name: &str) -> Result<(), Error> {\n\n let name = name.to_lowercase();\n\n let length = name.chars().count();\n\n let first_char_check = name\n\n .chars()\n\n .next()\n\n .map_or(false, |c| c.is_ascii_alpha...
Rust
third_party/rust_crates/vendor/tinyvec/tests/tinyvec.rs
evanacox/fuchsia
5fb7a5aa2fedca4e44f264df04664b49883c6fe3
#![cfg(feature = "alloc")] #![allow(bad_style)] #![allow(clippy::redundant_clone)] #[cfg(feature = "serde")] use serde_test::{assert_tokens, Token}; use std::iter::FromIterator; use tinyvec::*; #[test] fn TinyVec_swap_remove() { let mut tv: TinyVec<[i32; 10]> = Default::default(); tv.push(1); tv.pu...
#![cfg(feature = "alloc")] #![allow(bad_style)] #![allow(clippy::redundant_clone)] #[cfg(feature = "serde")] use serde_test::{assert_tokens, Token}; use std::iter::FromIterator; use tinyvec::*; #[test] fn TinyVec_swap_remove() { let mut tv: TinyVec<[i32; 10]> = Default::default(); tv.push(1); tv.pu...
; } #[test] fn TinyVec_pretty_debug() { let tv: TinyVec<[i32; 6]> = tiny_vec![1, 2, 3]; let s = format!("{:#?}", tv); let expected = format!("{:#?}", tv.as_slice()); assert_eq!(s, expected); }
assert_tokens( &tv, &[ Token::Seq { len: Some(4) }, Token::I32(1), Token::I32(2), Token::I32(3), Token::I32(4), Token::SeqEnd, ], )
call_expression
[]
Rust
src/count.rs
jeremypruitt/tcount
302e6a3d9063a31e127c8b93f822e5d9c47a27d9
use crate::error::{Error, Result}; use crate::language::Language; use crate::query::{Query, QueryKind}; use crate::tree::TreeIterator; use regex::Regex; use std::collections::HashMap; use std::fs; use std::ops::AddAssign; use std::path::Path; use tree_sitter::{Node, Parser, QueryCursor}; #[derive(Debug, Eq, PartialEq,...
use crate::error::{Error, Result}; use crate::language::Language; use crate::query::{Query, QueryKind}; use crate::tree::TreeIterator; use regex::Regex; use std::collections::HashMap; use std::fs; use std::ops::AddAssign; use std::path::Path; use tree_sitter::{Node, Parser, QueryCursor}; #[derive(Debug, Eq, PartialEq,...
#[test] fn counting_queries() { let queries = queries(); let got = Counts::from_path( "tests/fixtures/rust1.rs", &Language::Rust, &Vec::new(), &Vec::new(), &queries, ); let expected = Counts { nfiles: 1, ...
fn counting_node_kind_patterns() { let queries = Vec::new(); let got = Counts::from_path( "tests/fixtures/rust1.rs", &Language::Rust, &vec!["block_comment".into(), "line_comment".into()], &vec![Regex::new(".*comment").unwrap()], &queries, ...
function_block-full_function
[ { "content": "pub fn print_languages(langs: Vec<(&Language, Vec<String>, &Vec<String>)>) {\n\n let mut table = Table::new();\n\n table.set_format(format_builder().build());\n\n\n\n let mut titles = Vec::with_capacity(3);\n\n titles.push(title_cell(\"Language\"));\n\n titles.push(title_cell(\"Exte...
Rust
converter/rust-converter/src/main.rs
jehna/wikigolf
8ff02136602a794dc48c1dd15de5eaf41f8b64fd
extern crate nom; use csv::WriterBuilder; use nom::{ branch::alt, bytes::complete::{escaped_transform, is_not, tag, take_till}, character::complete::{anychar, char, digit1}, combinator::{map, map_res}, multi::{many1, many_till, separated_list}, sequence::{delimited, preceded, terminated, tuple}, IResult,...
extern crate nom; use csv::WriterBuilder; use nom::{ branch::alt, bytes::complete::{escaped_transform, is_not, tag, take_till}, character::complete::{anychar, char, digit1}, combinator::{map, map_res}, multi::{many1, many_till, separated_list}, sequence::{delimited, preceded, terminated, tuple}, IResult,...
fn main() -> Result<(), std::io::Error> { let args: Vec<String> = std::env::args().collect(); if args.len() < 3 { eprintln!("No file provided.\n\nUsage:\nrust-wiki-link-parser directory locale"); } let directory = &args[1]; let locale = &args[2]; let pages_in_filename = format!( "{directory}/{loc...
fn print_values_read_for_debug(lines_read: &mut u64) { *lines_read = *lines_read + 1; if *lines_read % 100000 == 0 { eprintln!("Items processed: {}", lines_read); } }
function_block-full_function
[ { "content": "interface ResultsProps {\n\n results: string[]\n\n lang: string\n", "file_path": "frontend/components/Results.tsx", "rank": 11, "score": 25375.670788122272 }, { "content": "interface PageSelectorProps {\n\n onChange: (value: string) => void\n\n lang: string\n\n disabled?: ...
Rust
boa/src/syntax/parser/statement/iteration/for_statement.rs
rumpl/boa
7779c1a6f1f5d467c3307ab0cff1aa412a990db5
use crate::{ syntax::{ ast::{ node::{iteration::IterableLoopInitializer, ForInLoop, ForLoop, ForOfLoop, Node}, Const, Keyword, Punctuator, }, lexer::{Error as LexError, Position, TokenKind}, parser::{ expression::Expression, statement...
use crate::{ syntax::{ ast::{ node::{iteration::IterableLoopInitializer, ForInLoop, ForLoop, ForOfLoop, Node}, Const, Keyword, Punctuator, }, lexer::{Error as LexError, Position, TokenKind}, parser::{ expression::Expression, statement...
fn node_to_iterable_loop_initializer( node: &Node, position: Position, ) -> Result<IterableLoopInitializer, ParseError> { match node { Node::Identifier(name) => Ok(IterableLoopInitializer::Identifier(*name)), Node::VarDeclList(ref list) => match list.as_ref() { [var] => { ...
function_block-full_function
[ { "content": "fn expect_tokens<R>(lexer: &mut Lexer<R>, expected: &[TokenKind], interner: &mut Interner)\n\nwhere\n\n R: Read,\n\n{\n\n for expect in expected.iter() {\n\n assert_eq!(&lexer.next(interner).unwrap().unwrap().kind(), &expect);\n\n }\n\n\n\n assert!(\n\n lexer.next(interne...
Rust
src/y2021d08.rs
LLBlumire/advent-of-code
03597b3d3a55cc8aea774596ec2d02865b7d603c
use std::collections::BTreeSet; use aoc::*; #[derive(Debug)] struct ParsedInput { segments: Vec<SegmentDisplayInfo>, } #[derive(Debug)] struct SegmentDisplayInfo { full_cycle: Vec<SegmentInstruction>, output: Vec<SegmentInstruction>, } #[derive(Debug)] struct SegmentInstruction { wires: BTreeSet<Seg...
use std::collections::BTreeSet; use aoc::*; #[derive(Debug)] struct ParsedInput { segments: Vec<SegmentDisplayInfo>, } #[derive(Debug)] struct SegmentDisplayInfo { full_cycle: V
b gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce "# .trim(); assert_task!(parse, task1, test, 26); assert_task!(parse, task2, test, 61229); } aoc_main!(parse, task1, task2);
ec<SegmentInstruction>, output: Vec<SegmentInstruction>, } #[derive(Debug)] struct SegmentInstruction { wires: BTreeSet<SegmentWire>, } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)] #[repr(usize)] enum SegmentWire { A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, }...
random
[ { "content": "struct ParsedInput {\n\n commands: Vec<Command>,\n\n}\n\n\n", "file_path": "src/y2015d06.rs", "rank": 2, "score": 103984.23450214264 }, { "content": "struct ParsedInput {\n\n digits: Vec<u8>,\n\n}\n\n\n", "file_path": "src/y2017d01.rs", "rank": 3, "score": 103...
Rust
src/theme/ui_styles.rs
ijf8090/exa
505808fd9fb749f01c4377607d56fa26f91eb84d
use ansi_term::Style; use crate::theme::lsc::Pair; #[derive(Debug, Default, PartialEq)] pub struct UiStyles { pub colourful: bool, pub filekinds: FileKinds, pub perms: Permissions, pub size: Size, pub users: Users, pub links: Links, pub git: Git, pub punc...
use ansi_term::Style; use crate::theme::lsc::Pair; #[derive(Debug, Default, PartialEq)] pub struct UiStyles { pub colourful: bool, pub filekinds: FileKinds, pub perms: Permissions, pub size: Size, pub users: Users, pub links: Links, pub git: Git, pub punc...
elf.git.renamed = pair.to_style(), "gt" => self.git.typechange = pair.to_style(), "xx" => self.punctuation = pair.to_style(), "da" => self.date = pair.to_style(), "in" => self.inode = pair.to_styl...
=> self.broken_symlink = pair.to_style(), _ => return false, } true } pub fn set_exa(&mut self, pair: &Pair<'_>) -> bool { match pair.key { "ur" => self.perms.user_read = pair.to_...
random
[ { "content": "/// Converts the style used to paint a file name into the style that should be\n\n/// used to paint an icon.\n\n///\n\n/// - The background colour should be preferred to the foreground colour, as\n\n/// if one is set, it’s the more “obvious” colour choice.\n\n/// - If neither is set, just use th...
Rust
metrics-core/src/percentile.rs
1a1a11a/rpc-perf
cad086dbec2f016bd0664a464b08c0c00003bb54
#![allow(missing_docs)] const MAX_PERCENTILE: u32 = 1_000_000_000u32; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] pub struct Percentile { val: u32, } macro_rules! p { ($val:expr) => { Percentile { val: $val } }; } impl Percentile { pub fn new(val:...
#![allow(missing_docs)] const MAX_PERCENTILE: u32 = 1_000_000_000u32; #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] pub struct Percentile { val: u32, } macro_rules! p { ($val:expr) => { Percentile { val: $val } }; } impl Percentile { pub fn new(val:...
} pub const fn p25() -> Self { p!(Self::maximum().val / 4) } pub const fn p50() -> Self { p!(Self::maximum().val / 2) } pub const fn p75() -> Self { p!(Self::p25().val * 3) } pub const fn p90() -> Self { ...
pub const fn into_inner(self) -> u32 { self.val } pub fn from_float(val: f64) -> Self { Self { val: (val.min(1.0).max(0.0) * (MAX_PERCENTILE as f64)) as u32, } } pub fn as_float(self) -> f64 { (self.val as f64) / (MAX_PERCENTILE ...
random
[]
Rust
codegen/src/ast_clone.rs
sandkoan/gluon
92093b9de96a058e01886a27f1284239f1d1e08b
use std::str::FromStr; use { proc_macro2::{Span, TokenStream}, syn::{ self, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed, Generics, Ident, Variant, }, }; use crate::{ attr, shared::{map_lifetimes, map_type_params, split_for_impl}, }; pub fn de...
use std::str::FromStr; use { proc_macro2::{Span, TokenStream}, syn::{ self, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed, Generics, Ident, Variant, }, }; use crate::{ attr, shared::{map_lifetimes, map_type_params, split_for_impl}, }; pub fn de...
let field_initializers = first .into_iter() .chain(second) .chain(fields) .enumerate() .map(|(idx, field)| { let field_ty = &field.ty; let idx = syn::Index::from(idx); quote! { <#field_ty as gluon_base::ast::AstClone...
match (&first, &second) { (Some(field), None) => { let field_ty = &field.ty; return quote! { #ident ( <#field_ty as gluon_base::ast::AstClone<'__vm, _>>::ast_clone(&self.0, arena) ) }; } _ => (), }
if_condition
[ { "content": "fn gen_impl(container: &Container, ident: Ident, generics: Generics, data: &Data) -> TokenStream {\n\n let trait_bounds = &map_type_params(&generics, |ty| {\n\n quote! { #ty: _gluon_api::VmType, #ty::Type: Sized }\n\n });\n\n\n\n let (impl_generics, ty_generics, where_clause) = spl...
Rust
hphp/hack/src/rupro/lib/reason.rs
dmitryvinn/hhvm
c7f106b7029b8bf6b4121bcdf573a488e6c5e884
use ocamlrep::{Allocator, OpaqueValue, ToOcamlRep}; use pos::{BPos, NPos, Pos, Positioned, Symbol, TypeConstName, TypeName}; use std::hash::Hash; use crate::visitor::Walkable; pub use oxidized::typing_reason::{ArgPosition, BlameSource}; pub trait Reason: Eq + Hash + Clone + ToOcamlRep + Walkable<Self> + std::f...
use ocamlrep::{Allocator, OpaqueValue, ToOcamlRep}; use pos::{BPos, NPos, Pos, Positioned, Symbol, TypeConstName, TypeName}; use std::hash::Hash; use crate::visitor::Walkable; pub use oxidized::typing_reason::{ArgPosition, BlameSource}; pub trait Reason: Eq + Hash + Clone + ToOcamlRep + Walkable<Self> + std::f...
fn to_oxidized(&self) -> oxidized::typing_reason::Reason { unimplemented!() } } impl Walkable<BReason> for BReason {} impl ToOcamlRep for BReason { fn to_ocamlrep<'a, A: Allocator>(&self, _alloc: &'a A) -> OpaqueValue<'a> { unimplemented!() } } #[derive(Debug, Clone, PartialEq, Eq, ...
fn pos(&self) -> &BPos { use ReasonImpl::*; match &*self.0 { Rnone => unimplemented!(), Rwitness(p) | RwitnessFromDecl(p) | Rhint(p) => p, r => unimplemented!("BReason::pos: {:?}", r), } }
function_block-full_function
[]
Rust
rkyv/src/validation/validators/mod.rs
djkoloski/archive
3f8e895701cd15f6f20f428864638b12a3774030
mod archive; mod shared; mod util; use crate::{ validation::{ check_archived_root_with_context, check_archived_value_with_context, ArchiveContext, CheckTypeError, SharedContext, }, Archive, Fallible, }; pub use archive::*; use bytecheck::CheckBytes; use core::{alloc::Layout, any::TypeId, ...
mod archive; mod shared; mod util; use crate::{ validation::{ check_archived_root_with_context, check_archived_value_with_context, ArchiveContext, CheckTypeError, SharedContext, }, Archive, Fallible, }; pub use archive::*; use bytecheck::CheckBytes; use core::{alloc::Layout, any::TypeId, ...
} } #[cfg(feature = "std")] const _: () = { use std::error::Error; impl Error for DefaultValidatorError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { Self::ArchiveError(e) => Some(e as &dyn Error), Self::SharedError(e) => Some(e as...
match self { Self::ArchiveError(e) => write!(f, "{}", e), Self::SharedError(e) => write!(f, "{}", e), }
if_condition
[ { "content": "/// A context that can validate shared archive memory.\n\n///\n\n/// Shared pointers require this kind of context to validate.\n\npub trait SharedContext: Fallible {\n\n /// Registers the given `ptr` as a shared pointer with the given type.\n\n ///\n\n /// Returns `true` if the pointer wa...
Rust
src/exports/logger.rs
Zrus/arrow-client
61ead64b10cf8bba451d6798abacd58ce89e3233
#![allow(clippy::missing_safety_doc)] use std::ptr; use std::ffi::CString; use std::fmt::Arguments; use std::os::raw::{c_char, c_int, c_void}; use std::sync::{Arc, Mutex}; use crate::utils::logger::file::FileLogger; use crate::utils::logger::stderr::StderrLogger; #[cfg(not(target_os = "windows"))] use crate::util...
#![allow(clippy::missing_safety_doc)] use std::ptr; use std::ffi::CString; use std::fmt::Arguments; use std::os::raw::{c_char, c_int, c_void}; use std::sync::{Arc, Mutex}; use crate::utils::logger::file::FileLogger; use crate::utils::logger::stderr::StderrLogger; #[cfg(not(target_os = "windows"))] use crate::util...
*logger; Box::into_raw(Box::new(logger.clone())) } #[no_mangle] pub unsafe extern "C" fn ac__logger__free(logger: *mut BoxLogger) { Box::from_raw(logger); }
let logger = FileLogger::new(path, limit as _, rotations as _); match logger { Ok(logger) => Box::into_raw(Box::new(BoxLogger::new(logger))), Err(_) => ptr::null_mut(), } } #[no_mangle] pub unsafe extern "C" fn ac__logger__clone(logger: *const BoxLogger) -> *mut BoxLogger { let logger = &
random
[ { "content": "/// Type alias.\n\ntype ConnectionStateCallback = unsafe extern \"C\" fn(opaque: *mut c_void, state: c_int);\n\n\n", "file_path": "src/exports/mod.rs", "rank": 0, "score": 342242.7629668564 }, { "content": "/// Type alias.\n\ntype NetworkScannerStateCallback = unsafe extern \"C...
Rust
src/scene/post_office.rs
hivemind-braincell/meowdy
8f6b5563cacddc8d3e17e240080156d8ea9bae9d
use bevy::prelude::*; use rand::Rng; use tracing::instrument; use crate::{assets::Images, GameState, Meowney}; const ARENA_WIDTH: i32 = 5; const ARENA_HEIGHT: i32 = 5; #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)] pub struct Position { x: i32, y: i32, } #[derive(Component)] pub struct MoveTimer(pu...
use bevy::prelude::*; use rand::Rng; use tracing::instrument; use crate::{assets::Images, GameState, Meowney}; const ARENA_WIDTH: i32 = 5; const ARENA_HEIGHT: i32 = 5; #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)] pub struct Position { x: i32, y: i32, } #[derive(Component)] pub struct MoveTimer(pu...
pub fn position_translation(mut q: Query<(&Position, &mut Transform)>) { let scale = 24.; for (pos, mut transform) in q.iter_mut() { transform.translation = Vec3::new( pos.x as f32 * scale, pos.y as f32 * scale, transform.translation.z, ); } } pub fn g...
pub fn food_spawner( mut commands: Commands, images: Res<Images>, mut spawn_reader: EventReader<SpawnFood>, ) { if spawn_reader.iter().next().is_some() { info!("spawning food"); let mut rng = rand::thread_rng(); let x = rng.gen_range(-ARENA_WIDTH..=ARENA_WIDTH); let y = ...
function_block-full_function
[ { "content": "pub fn setup(mut commands: Commands, images: Res<Images>, camera: Query<Entity, With<Camera>>) {\n\n commands\n\n .spawn()\n\n .insert_bundle(SpriteBundle {\n\n transform: Transform::from_translation(Vec3::new(0., 0., 0.)),\n\n texture: images.end_1.clone(),\...
Rust
src/codegen/mod.rs
drXor/jas
17f658e35c6de5c20b33197fcc15b046bdaedf1c
pub mod labels; pub mod constants; pub mod attrs; pub mod fields; pub mod methods; pub mod eval; pub mod convert; use crate::codegen::labels::LabelKind; use crate::phase::Phase; use crate::sections::ClassSection; use crate::reporting::*; use classfile::raw; use classfile::indexing::*; use classfile::consts as flags;...
pub mod labels; pub mod constants; pub mod attrs; pub mod fields; pub mod methods; pub mod eval; pub mod convert; use crate::codegen::labels::LabelKind; use crate::phase::Phase; use crate::sections::ClassSection; use crate::reporting::*; use classfile::raw; use classfile::indexing::*; use classfile::consts as flags;...
tribute { name, info: raw::AttributeInfo::BootstrapMethods(bootstrap_methods), }); } reports.complete(( self.file_name(), raw::Class { minor_version: self.minor_major_version.unwrap().0, major_version: s...
ls(&mut self, &section)); let ClassSection { this_class, super_class, top_level, constants, fields, methods, .. } = section; report_try!(reports; attrs::expand_this_and_super(&mut self, this_class, super_class)); r...
random
[ { "content": "pub fn expand_labels(gen: &mut Generator, section: &ClassSection) -> Reported<()> {\n\n\n\n let mut reports = Reported::new();\n\n\n\n macro_rules! insert_label {\n\n ($label:expr, $kind:expr) => {\n\n if gen.labels.contains_key(&$label.name) {\n\n // TODO: p...
Rust
src/decoder/flac.rs
TENX-S/rodio
a55b84b71e5577b972236ac4fcdd98f762c47ada
use std::io::{Read, Seek, SeekFrom}; use std::mem; use std::time::Duration; use crate::Source; use claxon::FlacReader; pub struct FlacDecoder<R> where R: Read + Seek, { reader: FlacReader<R>, current_block: Vec<i32>, current_block_channel_len: usize, current_block_off: usize, bits_per_sample:...
use std::io::{Read, Seek, SeekFrom}; use std::mem; use std::time::Duration; use crate::Source; use claxon::FlacReader; pub struct FlacDecoder<R> where R: Read + Seek, { reader: FlacReader<R>, current_block: Vec<i32>, current_block_channel_len: usize, current_block_off: usize, bits_per_sample:...
} pub fn into_inner(self) -> R { self.reader.into_inner() } } impl<R> Source for FlacDecoder<R> where R: Read + Seek, { #[inline] fn current_frame_len(&self) -> Option<usize> { None } #[inline] fn channels(&self) -> u16 { self.channels } #[inline] ...
Ok(FlacDecoder { reader: reader, current_block: Vec::with_capacity( spec.max_block_size as usize * spec.channels as usize, ), current_block_channel_len: 1, current_block_off: 0, bits_per_sample: spec.bits_per_sample, sam...
call_expression
[ { "content": "/// Returns true if the stream contains WAV data, then resets it to where it was.\n\nfn is_wave<R>(mut data: R) -> bool\n\nwhere\n\n R: Read + Seek,\n\n{\n\n let stream_pos = data.seek(SeekFrom::Current(0)).unwrap();\n\n\n\n if WavReader::new(data.by_ref()).is_err() {\n\n data.seek...
Rust
examples/simple/src/lib.rs
rzerres/orbclient
118b36d687b74fe66aad2c3ff4fb6ef8e7f008a3
extern crate console_error_panic_hook; extern crate orbclient; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use orbclient::{animation_loop, log, Color, EventOption, GraphicsPath, Mode, Renderer, Window}; #[wasm_bindgen(start)] pub fn start() { console_error_panic_hook::set_once(); let (width, hei...
extern crate console_error_panic_hook; extern crate orbclient; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use orbclient::{animation_loop, log, Color, EventOption, GraphicsPath, Mode, Renderer, Window}; #[wasm_bindgen(start)] pub fn start() { console_error_panic_hook::set_once(); let (width, hei...
; }
animation_loop(move || { for event in window.events() { match event.to_option() { EventOption::Quit(_quit_event) => return false, EventOption::Mouse(evt) => log(format!( "At position {:?} pixel color is : {:?}", (evt.x, evt.y), ...
call_expression
[ { "content": "/// Gets the browser window.\n\npub fn window() -> Result<WebWindow, String> {\n\n web_sys::window().ok_or(\"body: no global `windows` exists.\".to_string())\n\n}\n\n\n", "file_path": "src/sys/web.rs", "rank": 1, "score": 111713.57670412652 }, { "content": "pub fn gauss_blur...
Rust
src/origin/origin_platform.rs
PhilipK/steam_shortcuts_sync
5e8e4f2451d0a4ec6e8b24c27465ec69a2749aad
use crate::platform::{Platform, SettingsValidity}; use failure::*; use nom::bytes::complete::take_until; use std::{ fs::DirEntry, path::{Path, PathBuf}, }; use super::{origin_game::OriginGame, OriginSettings}; pub struct OriginPlatform { pub settings: OriginSettings, } impl Platform<OriginGame, OriginErr...
use crate::platform::{Platform, SettingsValidity}; use failure::*; use nom::bytes::complete::take_until; use std::{ fs::DirEntry, path::{Path, PathBuf}, }; use super::{origin_game::OriginGame, OriginSettings}; pub struct OriginPlatform { pub settings: OriginSettings, } impl Platform<OriginGame, OriginErr...
use winreg::RegKey; let hklm = RegKey::predef(HKEY_CLASSES_ROOT); if let Ok(launcher_key) = hklm.open_subkey("eadm\\shell\\open\\command") { let launcher_string: Result<String, _> = launcher_key.get_value(""); if let Ok(launcher_string) = launcher_string { let path = Path::...
et Ok(program_data) = program_data { let origin_folder = Path::new(&program_data).join("Origin"); if origin_folder.exists() { res.local_content_path = origin_folder; } else { return None; } let exe_path = get_exe_path(); if exe_path.is_none() { ...
random
[ { "content": "pub fn restore_backup(steam_settings: &SteamSettings, shortcut_path: &Path) -> bool {\n\n let file_name = shortcut_path.file_name().unwrap();\n\n let paths = get_shortcuts_paths(steam_settings);\n\n if let Ok(paths) = paths {\n\n for user in paths {\n\n if let Some(user_...
Rust
protocols/floodsub/src/protocol.rs
c410-f3r/rust-libp2p
8c119269d620f7de3956590ab45a14c9f5acd266
use crate::rpc_proto; use crate::topic::TopicHash; use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, PeerId, upgrade}; use protobuf::{ProtobufError, Message as ProtobufMessage}; use std::{error, fmt, io, iter}; use tokio_io::{AsyncRead, AsyncWrite}; #[derive(Debug, Clone, Default)] pub struct FloodsubC...
use crate::rpc_proto; use crate::topic::TopicHash; use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, PeerId, upgrade}; use protobuf::{ProtobufError, Message as ProtobufMessage}; use std::{error, fmt, io, iter}; use tokio_io::{AsyncRead, AsyncWrite}; #[derive(Debug, Clone, Default)] pub struct FloodsubC...
} #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct FloodsubMessage { pub source: PeerId, pub data: Vec<u8>, pub sequence_number: Vec<u8>, pub topics: Vec<TopicHash>, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct FloodsubSubscription { pub a...
proto.mut_publish().push(msg); } for topic in self.subscriptions { let mut subscription = rpc_proto::RPC_SubOpts::new(); subscription.set_subscribe(topic.action == FloodsubSubscriptionAction::Subscribe); subscription.set_topicid(topic.topic.into_string()); ...
function_block-function_prefix_line
[ { "content": "/// Converts a received protobuf message into a corresponding `KadRequestMsg`.\n\n///\n\n/// Fails if the protobuf message is not a valid and supported Kademlia request message.\n\nfn proto_to_req_msg(mut message: proto::Message) -> Result<KadRequestMsg, io::Error> {\n\n match message.get_field...
Rust
crates/mockiato-codegen/src/parse/method_decl_parser.rs
myelin-ai/mockiato
c7fce605aa3d82deed77cc511577495226139120
use std::collections::hash_map::RandomState; use std::collections::HashSet; use proc_macro2::Ident; use syn::spanned::Spanned; use syn::visit::{visit_type, Visit}; use syn::{GenericParam, Generics, Path, Signature, TraitItem, TraitItemMethod, Type, TypePath}; use crate::diagnostic::DiagnosticBuilder; use crate::parse...
use std::collections::hash_map::RandomState; use std::collections::HashSet; use proc_macro2::Ident; use syn::spanned::Spanned; use syn::visit::{visit_type, Visit}; use syn::{GenericParam, Generics, Path, Signature, TraitItem, TraitItemMethod, Type, TypePath}; use crate::diagnostic::DiagnosticBuilder; use crate::parse...
} } fn error_for_reference_to_generic_type(ty: &Type) -> Error { DiagnosticBuilder::error(ty.span(), "References to generic types are not supported") .build() .into() } fn find_references_to_generic_types<'a>( signature: &'a Signature, generic_types_on_trait: &'a HashSet<Ident>, ) -> ...
Err(references_to_generic_types .into_iter() .map(error_for_reference_to_generic_type) .collect())
call_expression
[ { "content": "fn first_argument_is_not_self_error(span: Span) -> Error {\n\n let error_message =\n\n \"The first parameter of a method must be self, so that the trait is object-safe\";\n\n DiagnosticBuilder::error(span, error_message).build().into()\n\n}\n\n\n\n#[derive(Debug)]\n\npub(crate) struct...
Rust
src/models/bbs.rs
itok01/hyper2ch
0934ca476f504dd6428fb8577ae0c57c8aba0651
use crate::db; use tokio_postgres::Error; pub struct Bbs { pub id: i64, pub name: String, pub path_name: String, pub description: String, pub category: String, pub hidden: bool, } pub const CREATE_BBS_TABLE: &str = " CREATE TABLE bbs ( id BIGSERIAL PRIMARY KEY, name TEX...
use crate::db; use tokio_postgres::Error; pub struct Bbs { pub id: i64, pub name: String, pub path_name: String, pub description: String, pub category: String, pub hidden: bool, } pub const CREATE_BBS_TABLE: &str = " CREATE TABLE bbs ( id BIGSERIAL PRIMARY KEY, name TEX...
} pub async fn find(id: i64) -> Result<Bbs, Error> { let (client, connection) = db::connect().await?; tokio::spawn(async move { if let Err(e) = connection.await { eprintln!("connection error: {}", e); } }); let row = client ...
Ok(Bbs { id, name: name.to_string(), path_name: path_name.to_string(), description: description.to_string(), category: category.to_string(), hidden, })
call_expression
[ { "content": "-- Sets up a trigger for the given table to automatically set a column called\n", "file_path": "migrations/00000000000000_diesel_initial_setup/up.sql", "rank": 0, "score": 168058.24338074052 }, { "content": "/// Get appropriate database name\n\npub fn get_db_name() -> String {\...
Rust
sdk/src/registration/linux.rs
Ewpratten/discord-sdk
2af8089eb1021fe99cfde9d7a00731203388ab4e
use crate::Error; pub fn register_app(app: super::Application) -> Result<(), Error> { use super::LaunchCommand; fn inner(app: super::Application) -> anyhow::Result<()> { use anyhow::Context as _; let mut desktop_path = app_dirs2::get_data_root(app_dirs2::AppDataType::UserData) .co...
use crate::Error; pub fn register_app(app: super::Application) -> Result<(), Error> { use super::LaunchCommand; fn inner(app: super::Application) -> anyhow::Result<()> { use anyhow::Context as _; let mut desktop_path = app_dirs2::get_data_root(app_dirs2::AppDataType::UserData) .co...
let mut mime_list_path = app_dirs2::data_root(app_dirs2::AppDataType::UserConfig) .context("unable to acquire user config directory")?; mime_list_path.push("mimeapps.list"); let discord_scheme = format!( "x-scheme-handler/discord-{id}=discord-{id}.d...
{ let md = std::fs::metadata(&desktop_path) .with_context(|| format!("unable to locate \"{}\"", desktop_path.display()))?; anyhow::ensure!( md.is_dir(), "\"{}\" was found, but it's not a directory", desktop_path.display() ...
function_block-random_span
[ { "content": "pub fn register_app(app: super::Application) -> Result<(), Error> {\n\n use super::LaunchCommand;\n\n\n\n fn inner(app: super::Application) -> anyhow::Result<()> {\n\n match app.command {\n\n LaunchCommand::Url(url) => {\n\n create_shim(app.id, url.into())?;\...
Rust
src/lib.rs
NeoLegends/vecshard
3b763754b718f035f9be19b672a01dcb4f7e22f2
/*! Split Vecs in O(1) time. You can split a [`Vec`] into two using [`Vec::split_off`](std::vec::Vec::split_off), but since most allocators can't just go and split up an allocation, this needs to allocate space for a second [`Vec`] and, even worse, copy the relevant elements over, which takes O(n) time. You could also...
/*! Split Vecs in O(1) time. You can split a [`Vec`] into two using [`Vec::split_off`](std::vec::Vec::split_off), but since most allocators can't just go and split up an allocation, this needs to allocate space for a second [`Vec`] and, even worse, copy the relevant elements over, which takes O(n) time. You could
:Shard, Self::Shard); } struct VecDropper<T> { ptr: *mut T, capacity: usize, } impl<T> Drop for VecDropper<T> { fn drop(&mut self) { unsafe { mem::drop(Vec::from_raw_parts(self.ptr, 0, self.capacity)); } } } pub struct VecShard<T> { dropper: A...
also split it into slices using `Vec::split_at` or `Vec::split_at_mut`, but this will not give you owned data you can move around or move out of at will. This crate provides a way to split a [`Vec`] into two owned [`VecShard`]s that behave similar to Vecs that takes constant time. The catch is that the [`VecShard`]s u...
random
[ { "content": "#[test]\n\nfn into_vecs() {\n\n let (left, right) = vec![1, 11, 21, 1211, 111221, 312211].split_inplace_at(3);\n\n\n\n // this one needs to allocate a new Vec, since right still exists\n\n let lvec: Vec<_> = left.into();\n\n // this one is now the only shard left and can re-use the all...
Rust
crates/web-sys/src/features/gen_RtcDataChannelInit.rs
AntonyBlakey/wasm-bindgen
87d54b5be2d0ac3ce8ba5f3ac49af226f4da747e
#![allow(unused_imports)] use super::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "wasm-bindgen" { # [wasm_bindgen (extends = :: js_sys :: Object , js_name = RTCDataChannelInit)] #[derive(Debug, Clone, PartialEq, Eq)] #[doc = "The `RtcDataChannelInit` dictionary."] #[doc = ""] #[doc = "*T...
#![allow(unused_imports)] use super::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "wasm-bindgen" { # [wasm_bindgen (extends = :: js_sys :: Object , js_name = RTCDataChannelInit)] #[derive(Debug, Clone, PartialEq, Eq)] #[doc = "The `RtcDataChannelInit` dictionary."] #[doc = ""] #[doc = "*T...
flect::set( self.as_ref(), &JsValue::from("negotiated"), &JsValue::from(val), ); debug_assert!( r.is_ok(), "setting properties should never fail on our dictionary objects" ); let _ = r; self } #[doc = "Change the...
r.is_ok(), "setting properties should never fail on our dictionary objects" ); let _ = r; self } #[doc = "Change the `maxRetransmits` field of this object."] #[doc = ""] #[doc = "*This API requires the following crate features to be activated: `RtcDataChannelIn...
random
[ { "content": "#[wasm_bindgen]\n\npub fn ret_u16() -> u16 {\n\n 3\n\n}\n\n\n", "file_path": "crates/cli/tests/reference/interface-types-integers.rs", "rank": 0, "score": 416302.9120197283 }, { "content": "fn add_features(features: &mut BTreeSet<String>, ty: &impl TraverseType) {\n\n ty....
Rust
src/error.rs
a1ien/jaylink
09de031fb4cc3f76f24e4a361977ec6efb6838bd
use std::fmt; type BoxedError = Box<dyn std::error::Error + Send + Sync>; #[allow(unused_imports)] use crate::{scan_usb, Capabilities, JayLink}; #[non_exhaustive] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ErrorKind { Usb, DeviceNotFound, ...
use std::fmt; type BoxedError = Box<dyn std::error::Error + Send + Sync>; #[allow(unused_imports)] use crate::{scan_usb, Capabilities, JayLink}; #[non_exhaustive] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ErrorKind { Usb, DeviceNotFound, ...
fn fmt_while(&self) -> String { if let Some(while_) = self.while_ { format!(" while {}", while_) } else { String::new() } } pub fn kind(&self) -> ErrorKind { self.kind } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Format...
nd: ErrorKind, inner: impl Into<BoxedError>, while_: &'static str, ) -> Self { Self { kind, inner: inner.into(), while_: Some(while_), } }
function_block-function_prefixed
[ { "content": "/// Scans for J-Link USB devices.\n\n///\n\n/// The returned iterator will yield all devices made by Segger, without filtering the product ID.\n\npub fn scan_usb() -> Result<impl Iterator<Item = UsbDeviceInfo>> {\n\n log_libusb_info();\n\n\n\n Ok(rusb::devices()\n\n .jaylink_err()?\n\...
Rust
examples/repl.rs
gabidi/magical-bitcoin-wallet
0739c6d80c2cf0e9414794940d3434047edc5ecb
use std::fs; use std::path::PathBuf; use std::sync::Arc; use rustyline::error::ReadlineError; use rustyline::Editor; use clap::AppSettings; #[allow(unused_imports)] use log::{debug, error, info, trace, LevelFilter}; use bitcoin::Network; use magical::bitcoin; use magical::blockchain::ElectrumBlockchain; use magi...
use std::fs; use std::path::PathBuf; use std::sync::Arc; use rustyline::error::ReadlineError; use rustyline::Editor; use clap::AppSettings; #[allow(unused_imports)] use log::{debug, error, info, trace, LevelFilter}; use bitcoin::Network; use magical::bitcoin; use magical::blockchain::ElectrumBlockchain; use magi...
{ Ok(line) => { if line.trim() == "" { continue; } rl.add_history_entry(line.as_str()); let matches = repl_app.get_matches_from_safe_borrow(line.split(" ")); if let Err(err) = mat...
riptor, network, tree, ElectrumBlockchain::from(client), ) .unwrap(); let wallet = Arc::new(wallet); if let Some(_sub_matches) = matches.subcommand_matches("repl") { let mut rl = Editor::<()>::new(); loop { let readline = ...
function_block-random_span
[ { "content": "fn main() {\n\n let desc = \"wsh(or_d(\\\n\n multi(\\\n\n 2,[d34db33f/44'/0'/0']xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/*,tprv8ZgxMBicQKsPduL5QnGihpprdHyypMGi4DhimjtzYemu7se5YQNcZfA...
Rust
examples/amqp/api/src/lib.rs
webwire/webwire-rust
5bafd76fd05595ace3a0b427f3f2e3fbf2bcaf00
#[allow(dead_code)] pub mod chat { #[derive( Clone, Debug, Eq, PartialEq, :: serde :: Serialize, :: serde :: Deserialize, :: validator :: Validate, )] pub struct ClientMessage { pub text: String, } #[derive( Clone, Debug...
#[allow(dead_code)] pub mod chat { #[derive( Clone, Debug, Eq, PartialEq, :: serde :: Serialize, :: serde :: Deserialize, :: validator :: Validate, )] pub struct ClientMessage { pub text: String, } #[derive( Clone, Debug...
Ok(response) }), _ => Box::pin(::futures::future::ready(Err( ::webwire::ProviderError::MethodNotFound, ))), } } } pub struct ServerConsumer<'a>( pub &'a (dyn ::webwire::Consumer + ::std::marker::Sync + ::std::marker...
uture<'static, Result<::bytes::Bytes, ::webwire::ProviderError>> { let service = self.0(session.clone()); match method { "send" => Box::pin(async move { let input = serde_json::from_slice::<ClientMessage>(&input) .map_err(::webw...
random
[ { "content": "#[async_trait]\n\npub trait SessionHandler<S: Send + Sync> {\n\n /// Authorize the incoming request returning a session on\n\n /// success or an `AuthError` if the remote side could not be\n\n /// authenticated.\n\n async fn auth(&self, auth: Option<Auth>) -> Result<S, AuthError>;\n\n ...
Rust
src/interrupts.rs
archshift/crossbar9
9acf7bcefad6a394eb7085e29ce46d33b4369bc7
use io::irq; extern { static ldr_pc_pc_neg4: u32; fn wrap_handle_irq(); fn wrap_handle_fiq(); fn wrap_handle_swi(); fn wrap_handle_und(); fn wrap_handle_pre(); fn wrap_handle_dta(); pub fn wait_for_interrupt(); fn disable_interrupts() -> bool; fn enable_interrupts(); } pub fn w...
use io::irq; extern { static ldr_pc_pc_neg4: u32; fn wrap_handle_irq(); fn wrap_handle_fiq(); fn wrap_handle_swi(); fn wrap_handle_und(); fn wrap_handle_pre(); fn wrap_handle_dta(); pub fn wait_for_interrupt(); fn disable_interrupts() -> bool; fn enable_interrupts(); }
#[no_mangle] pub extern fn init_interrupts() { without_interrupts(|| { static VECTOR_MAPPINGS: [(u32, unsafe extern fn()); 6] = [ (0x08000000, wrap_handle_irq), (0x08000008, wrap_handle_fiq), (0x08000010, wrap_handle_swi), (0x08000018, wrap_handle_und), ...
pub fn without_interrupts<T, F: FnOnce() -> T>(f: F) -> T { let was_enabled = unsafe { disable_interrupts() }; let ret = f(); if was_enabled { unsafe { enable_interrupts() }; } ret }
function_block-full_function
[ { "content": "pub fn try_msleep(ms: u32) -> Result<(), &'static str> {\n\n try_usleep((ms * 1000) as u64)\n\n}\n\n\n", "file_path": "src/realtime.rs", "rank": 0, "score": 187069.2642210074 }, { "content": "pub fn try_sleep(sec: u32) -> Result<(), &'static str> {\n\n let timer = unsafe ...
Rust
crates/nu-cli/src/commands/histogram.rs
babysnakes/nushell
c59f860b4894edf650f7b32e29997da95f73548b
use crate::commands::WholeStreamCommand; use crate::prelude::*; use nu_errors::ShellError; use nu_protocol::{ ColumnPath, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value, }; use nu_source::Tagged; pub struct Histogram; #[async_trait] impl WholeStreamCommand for Histogram { fn na...
use crate::commands::WholeStreamCommand; use crate::prelude::*; use nu_errors::ShellError; use nu_protocol::{ ColumnPath, ReturnSuccess, Signature, SyntaxShape, TaggedDictBuilder, UntaggedValue, Value, }; use nu_source::Tagged; pub struct Histogram; #[async_trait] impl WholeStreamCommand for Histogram { fn na...
Box::new(move |(_, _, error)| error), ); match eval { Ok(with_value) => Ok(with_value), Err(reason) => Err(reason), } }) } fn splitter( by: Option<Tagged<String>>, ) -> Box<dyn Fn(usize, &Value) -> Result<String, ShellError> + Send> { match by {...
let column_value = labels .get(idx) .ok_or_else(|| { ShellError::labeled_error( "Unable to load group labels", "unabled to load group labels", &name, ...
random
[ { "content": "pub fn get_column_path(path: &ColumnPath, obj: &Value) -> Result<Value, ShellError> {\n\n let fields = path.clone();\n\n\n\n get_data_by_column_path(\n\n obj,\n\n path,\n\n Box::new(move |(obj_source, column_path_tried, error)| {\n\n let path_members_span = sp...
Rust
compiler/src/codegen/structs.rs
merlincinematic/rasn
f87915b2559f97c89fc91a0ae77333c35954ce0d
use crate::codegen::imports::Visibility; use crate::parser::{Prefix, TagKind}; use std::fmt; pub struct Struct { visibility: Visibility, name: String, fields: Vec<Field>, attributes: Vec<Attribute>, } impl Struct { pub fn new<I: Into<String>>(visibility: Visibility, name: I) -> Self { Self...
use crate::codegen::imports::Visibility; use crate::parser::{Prefix, TagKind}; use std::fmt; pub struct Struct { visibility: Visibility, name: String, fields: Vec<Field>, attributes: Vec<Attribute>, } impl Struct { pub fn new<I: Into<String>>(visibility: Visibility, name: I) -> Self { Self...
} pub struct Field { visibility: Visibility, attributes: Vec<Attribute>, name: String, optional: bool, ty: String, } impl fmt::Display for Field { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if !self.attributes.is_empty() { itertools::join( ...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if !self.attributes.is_empty() { itertools::join(self.attributes.iter().map(ToString::to_string), "\n").fmt(f)?; writeln!(f)?; } writeln!(f, "{}struct {} {{", self.visibility, self.name)?; if !self.fields.is...
function_block-full_function
[]
Rust
src/error.rs
advection/kafka-client
9951d74e5268f0cd253e36a0ef561a84e50c1e59
use std::io; use std::fmt; #[cfg(feature = "security")] use rustls::TLSError; use failure::Fail; use crate::failure::{Context, Backtrace}; #[derive(Debug, Fail)] pub enum KafkaErrorKind { #[fail(display = "KafkaError: {:?}", _0)] Kafka(KafkaErrorCode), #[fail(display = "Topic Partitio...
use std::io; use std::fmt; #[cfg(feature = "security")] use rustls::TLSError; use failure::Fail; use crate::failure::{Context, Backtrace}; #[derive(Debug, Fail)] pub enum KafkaErrorKind { #[fail(display = "KafkaError: {:?}", _0)] Kafka(KafkaErrorCode), #[fail(display = "Topic Partitio...
rKind::StringDecodeError => KafkaErrorKind::StringDecodeError.into(), KafkaErrorKind::NoHostReachable => KafkaErrorKind::NoHostReachable.into(), KafkaErrorKind::NoTopicsAssigned => KafkaErrorKind::NoTopicsAssigned.into(), KafkaErrorKind::InvalidDuration => KafkaErrorKind::InvalidDura...
y available")] LeaderNotAvailable = 5, #[fail(display = "This error is thrown if the client attempts to send messages")] NotLeaderForPartition = 6, #[fail(display = "RequestTimedOut")] RequestTimedOut = 7, #[fail(display = "BrokerNotAvailable")] BrokerNotAvailable...
random
[ { "content": "/// Safely converts a Duration into the number of milliseconds as a\n\n/// i32 as often required in the kafka protocol.\n\npub fn to_millis_i32(d: Duration) -> Result<i32, KafkaError> {\n\n use std::i32;\n\n let m = d\n\n .as_secs()\n\n .saturating_mul(1_000)\n\n .satura...
Rust
lucet-module/src/globals.rs
williamoverton/lucet
fb52d58ac88fb17940602dce5b7352fd91bf8a33
use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GlobalSpec<'a> { #[serde(borrow)] global: Global<'a>, export_names: Vec<&'a str>, } impl<'a> GlobalSpec<'a> { pub fn new(global: Global<'a>, export_names: Vec<&'a str>) -> Self { Self { ...
use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GlobalSpec<'a> { #[serde(borrow)] global: Global<'a>, export_names: Vec<&'a str>, } impl<'a> GlobalSpec<'a> { pub fn new(global: Global<'a>, export_names: Vec<&'a str>) -> Self { Self { ...
} } #[derive(Copy, Clone)] pub union GlobalValue { pub i_32: i32, pub i_64: i64, pub f_32: f32, pub f_64: f64, } impl std::fmt::Debug for GlobalValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { w...
} impl GlobalDef { pub fn init_val(&self) -> GlobalValue { match self { GlobalDef::I32(i) => GlobalValue { i_32: *i }, GlobalDef::I64(i) => GlobalValue { i_64: *i }, GlobalDef::F32(f) => GlobalValue { f_32: *f }, GlobalDef::F64(f) => GlobalValue { f_64: *f }...
random
[ { "content": "pub fn test_module_c(dir: &str, cfile: &str) -> Result<Arc<DlModule>, Error> {\n\n let c_path = guest_file(dir, cfile);\n\n let bindings_path = guest_file(dir, \"bindings.json\");\n\n c_test(c_path, bindings_path)\n\n}\n\n\n", "file_path": "lucet-runtime/lucet-runtime-tests/src/build....
Rust
src/rust/k1cfa/evaluate/eval.rs
sinistersnare/aams
367b43f4241f3cbfc5907970693157f0487cdd40
use crate::Expr; use crate::k1cfa::common::{ apply_state, eval_state, kalloc, Closure, ConcreteVal, EvalState, Kont, Prim, State, Val, Var, matches_boolean, matches_number, }; use crate::k1cfa::evaluate::matching::*; use crate::k1cfa::prims::apply_prim; fn is_atomic(ctrl: &Expr) -> bool { match ctrl { ...
use crate::Expr; use crate::k1cfa::common::{ apply_state, eval_state, kalloc, Closure, ConcreteVal, EvalState, Kont, Prim, State, Val, Var, matches_boolean, matches_number, }; use crate::k1cfa::evaluate::matching::*; use crate::k1cfa::prims::apply_prim; fn is_atomic(ctrl: &Expr) -> bool { match ctrl { ...
pub fn eval_step(st: &EvalState) -> State { let EvalState { ctrl, store, env, kaddr, } = st.clone(); if is_atomic(&ctrl) { apply_state(atomic_eval(st), store, kaddr) } else { match ctrl { Expr::List(ref list) => { if let Some((ec, et, ef)) = matches...
fn handle_function_application_expr(list: &[Expr], st: &EvalState) -> State { let EvalState { ctrl, env, store, kaddr, .. } = st.clone(); let mut args = list.to_vec(); let func = args.remove(0); let next_kaddr = kalloc(ctrl.clone(), env.clone()); let next_k = Kont::App( ...
function_block-full_function
[ { "content": "fn call_kont_helper(k: Kont, mut arg_vals: Vec<Val>, env: Env, store: Store, ctx: Expr) -> State {\n\n let arg = arg_vals.remove(0);\n\n if !arg_vals.is_empty() {\n\n panic!(\n\n \"continuation given wrong number of args: {:?}\",\n\n arg_vals.len() + 1\n\n );\n\n }\...
Rust
libindy_vdr/tests/attrib.rs
Patrik-Stas/indy-vdr
d30afea013d37b41237ee04adea9f059e06ae783
#[macro_use] mod utils; inject_dependencies!(); use indy_vdr::common::did::DidValue; use indy_vdr::ledger::constants; use crate::utils::fixtures::*; use crate::utils::helpers; const ATTRIB_RAW_DATA_FIELD: &'static str = r#"endpoint"#; const ATTRIB_HASH_DATA: &'static str = r#"83d907821df1c87db829e96569a11f6fc2e...
#[macro_use] mod utils; inject_dependencies!(); use indy_vdr::common::did::DidValue; use indy_vdr::ledger::constants; use crate::utils::fixtures::*; use crate::utils::helpers; const ATTRIB_RAW_DATA_FIELD: &'static str = r#"endpoint"#; const ATTRIB_HASH_DATA: &'static str = r#"83d907821df1c87db829e96569a11f6fc2e...
#[rstest] fn test_pool_build_get_attrib_requests_works_for_hash_value( request_builder: RequestBuilder, my_did: DidValue, ) { let attrib_request = request_builder .build_get_attrib_request( None, &my_di...
fn test_pool_build_get_attrib_requests_works_for_raw_value( request_builder: RequestBuilder, my_did: DidValue, ) { let attrib_request = request_builder .build_get_attrib_request( None, &my_did, Some(A...
function_block-full_function
[ { "content": "pub fn check_response_type(response: &str, expected_type: &str) {\n\n let response_: serde_json::Value = serde_json::from_str(response).unwrap();\n\n assert_eq!(response_[\"op\"].as_str().unwrap(), expected_type);\n\n}\n\n\n", "file_path": "libindy_vdr/tests/utils/helpers.rs", "rank"...
Rust
src/bin/solkit/play_stg.rs
VladimirMarkelov/solkit
e58cb22b12f846276a702f412726984577eed94a
use std::collections::HashMap; use crossterm::event::{Event, KeyCode, KeyModifiers, MouseButton, MouseEvent}; use crossterm::terminal; use solkit::card::{Card, Suit}; use solkit::engine::{Direction, Game, Pos}; use solkit::err::SolError; use solkit::gconf::{self, FaceOrder, Playable, SuitOrder}; use crate::primitive...
use std::collections::HashMap; use crossterm::event::{Event, KeyCode, KeyModifiers, MouseButton, MouseEvent}; use crossterm::terminal; use solkit::card::{Card, Suit}; use solkit::engine::{Direction, Game, Pos}; use solkit::err::SolError; use solkit::gconf::{self, FaceOrder, Playable, SuitOrder}; use crate::primitive...
fn on_activate(&self, ctx: &mut Context) { ctx.unpause(); } fn on_deactivate(&self, ctx: &mut Context) { ctx.pause(); } }
fn draw(&self, ctx: &mut Context, scr: &mut Screen, theme: &dyn Theme) -> Result<(), SolError> { let (fg, bg) = theme.base_colors(); scr.colors(fg, bg); scr.clear(); draw_area(scr, &self.game, &ctx.state, theme)?; self.draw_stats(ctx, scr, theme); if ctx.won { ...
function_block-full_function
[ { "content": "pub fn str_to_suit(s: &str) -> Result<Suit, SolError> {\n\n match s {\n\n \"spade\" | \"spades\" => Ok(Suit::Spade),\n\n \"club\" | \"clubs\" => Ok(Suit::Club),\n\n \"diamond\" | \"diamonds\" => Ok(Suit::Diamond),\n\n \"heart\" | \"hearts\" => Ok(Suit::Heart),\n\n ...
Rust
src/compsci/dates.rs
LibRapid/LibRapidRust
84476e80ef891615e05dba1de4a9f2dc4abf696d
pub struct Date { year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8, leap_year: bool, } impl Date { #[must_use] pub fn new_ymd(year: i32, month: u8, day: u8) -> Option<Date> { if is_valid_...
pub struct Date { year: i32, month: u8, day: u8, hour: u8, minute: u8, second: u8, leap_year: bool, } impl Date { #[must_use] pub fn new_ymd(year: i32, month: u8, day: u8) -> Option<Date> { if is_valid_...
; } return None; } pub fn with_hms(&mut self, hour: u8, minute: u8, second: u8) { match is_valid_hms(hour, minute, second) { true => { self.hour = hour; self.minute = minute; ...
Some(Date { year, month, day, hour: 0, minute: 0, second: 0, leap_year: is_leap_year(year) })
call_expression
[ { "content": "fn intersection_bench(iterations: u128, set_size: i32) {\n\n let _v: Vec<i32> = (0..set_size).collect();\n\n let _v2: Vec<i32> = (set_size / 2..=set_size * 2).collect();\n\n let s1 = VecSet::new(&_v);\n\n let s2: VecSet<i32> = VecSet::new(&_v2);\n\n let mut s3: VecSet<i32>;\n\n\n\n ...
Rust
tests/handler.rs
mleonhard/beatrice-rs
d97d049681cd53ca6ff5e900a384c6989cd6c3be
use crate::test_util::{ assert_ends_with, assert_starts_with, check_elapsed, read_for, read_response, read_to_string, TestServer, }; use beatrice::{ContentType, Response}; use std::io::{Read, Write}; use std::time::{Duration, Instant}; mod test_util; fn req_with_len(body_len: usize) -> String { format!("M...
use crate::test_util::{ assert_ends_with, assert_starts_with, check_elapsed, read_for, read_response, read_to_string, TestServer, }; use beatrice::{ContentType, Response}; use std::io::{Read, Write}; use std::time::{Duration, Instant}; mod test_util; fn req_with_len(body_len: usize) -> String { format!("M...
#[test] fn client_incomplete_read() { let server = TestServer::start(|_req| { Response::text( 200, std::iter::repeat(b'a').take(1_000_000).collect::<Vec<u8>>(), ) }) .unwrap(); let mut tcp_stream = server.connect_and_send("M / HTTP/1.1\r\n\r\n").unwrap(); ...
ct().unwrap(); let before = Instant::now(); tcp_stream .write_all(b"M / HTTP/1.1\r\ncontent-length:66000\r\nexpect: 100-continue\r\n\r\n") .unwrap(); assert_eq!( read_response(&mut tcp_stream).unwrap(), "HTTP/1.1 100 Continue\r\ncontent-length: 0\r\n\r\n" ); check_ela...
function_block-function_prefixed
[ { "content": "#[allow(clippy::missing_errors_doc)]\n\n#[allow(clippy::missing_panics_doc)]\n\npub fn read_response(tcp_stream: &mut std::net::TcpStream) -> Result<String, std::io::Error> {\n\n let deadline = Instant::now() + Duration::from_secs(10);\n\n let mut bytes = Vec::new();\n\n loop {\n\n ...
Rust
src/signals.rs
vernonrj/ffts_with_rust
5224b2da529784941450e7de4a7cac8a8ae80e26
use std::f64::consts::PI; use std::ops::{Bound, RangeBounds}; use crate::generate::Generator; use num_complex::Complex; /** * Add multiple signals together */ #[derive(Default)] pub struct Sum { signals: Vec<Box<Generator>>, } impl Sum { pub fn new() -> Self { Sum { signals: Vec::new() } } pub fn add<G...
use std::f64::consts::PI; use std::ops::{Bound, RangeBounds}; use crate::generate::Generator; use num_complex::Complex; /** * Add multiple signals together */ #[derive(Default)] pub struct Sum { signals: Vec<Box<Generator>>, } impl Sum { pub fn new() -> Self { Sum { signals: Vec::new() } } pub fn add<G...
.output(0.25).re, 10.0); assert_eq!(s.output(0.5).re, 0.0); assert_eq!(s.output(0.75).re, -10.0); assert_eq!(s.output(1.0).re, 0.0); }
d)] pub struct Sine { pub frequency: f64, pub amplitude: f64, } impl Generator for Sine { fn output(&self, time: f64) -> Complex<f64> { ((time * self.frequency * 2.0 * PI).sin() * self.amplitude).into() } } /** * Sawtooth generator */ #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct...
random
[ { "content": "pub fn trace<I, G>(gen: G, times: I) -> impl Iterator<Item=Complex<f64>>\n\n where I: IntoIterator<Item=f64>,\n\n G: Generator,\n\n{\n\n times.into_iter().map(move |value| gen.output(value))\n\n}\n\n\n", "file_path": "src/generate.rs", "rank": 0, "score": 108710.99502185...
Rust
nature_of_code/chp_03_oscillation/3_11_spring.rs
jpopesculian/nannou
44e6ae445021e1ae315082ba461dde563a63b594
use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Spring { anchor: Point2, len: f32, k: f32, } impl Spring { fn new(x: f32, y: f32, l: f32) -> Self { Spring { anchor: pt2(x, y), len: l, k: 0.2, } ...
use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Spring { anchor: Point2, len: f32, k: f32, } impl Spring { fn new(x: f32, y: f32, l: f32) -> Self { Spring { anchor: pt2(x, y), len: l, k: 0.2, } ...
} fn display(&self, draw: &Draw) { draw.rect() .xy(self.anchor) .w_h(10.0, 10.0) .color(GREY) .stroke(BLACK) .stroke_weight(2.0); } fn display_line(&self, draw: &Draw, bob: &Bob) { draw.line() .start(bob.position)...
if d < min_len { dir = dir.normalize(); dir *= min_len; b.position = self.anchor + dir; b.velocity *= 0.0; } else if d > max_len { dir = dir.normalize(); dir *= max_len; b.position = se...
if_condition
[ { "content": "// Recursive function\n\nfn cantor(draw: &Draw, x: f32, mut y: f32, len: f32) {\n\n let h = 30.0;\n\n\n\n // recursive exit condition\n\n if len >= 1.0 {\n\n // Draw line (as rectangle to make it easier to see)\n\n draw.rect()\n\n .x_y(x, y - h / 6.0)\n\n ...
Rust
rust/xaynet-server/src/services/messages/multipart/service.rs
Robert-Steiner/xaynet
63ea2ac8b2793ada3b2f16cddecab808a2d77369
use std::{ collections::{BTreeMap, HashMap}, task::Poll, }; use futures::{ future::{self, Ready}, task::Context, }; use tower::Service; use tracing::{debug, trace, warn}; use crate::services::messages::{multipart::buffer::MultipartMessageBuffer, ServiceError}; use xaynet_core::{ crypto::{PublicEnc...
use std::{ collections::{BTreeMap, HashMap}, task::Poll, }; use futures::{ future::{self, Ready}, task::Context, }; use tower::Service; use tracing::{debug, trace, warn}; use crate::services::messages::{multipart::buffer::MultipartMessageBuffer, ServiceError}; use xaynet_core::{ crypto::{PublicEnc...
}
let make_message1 = |chunk: &Chunk| Message::new_multipart(pk1, coordinator_pk, chunk.clone(), Tag::Sum); let pk2 = PublicSigningKey::from_slice(&[0x22; PublicSigningKey::LENGTH]).unwrap(); let message_id2 = MessageId { message_id: 1234, pa...
function_block-function_prefix_line
[ { "content": "pub fn message<F, P>(f: F) -> (Message, Vec<u8>)\n\nwhere\n\n F: Fn() -> (P, Vec<u8>),\n\n P: Into<Payload>,\n\n{\n\n let (payload, payload_bytes) = f();\n\n let payload: Payload = payload.into();\n\n let tag = match payload {\n\n Payload::Sum(_) => Tag::Sum,\n\n Paylo...
Rust
relay-server/src/utils/param_parser.rs
getsentry/semaphore
604fe06d517a2109a6b6ed85935c9641fb3848ff
use serde_json::Value; enum IndexingState { LookingForLeftParenthesis, Accumulating(usize), Starting, } pub fn update_nested_value<V>(target: &mut Value, path: &[&str], value: V) where V: Into<String>, { let map = match target { Value::Object(map) => map, _ => return, }; l...
use serde_json::Value; enum IndexingState { LookingForLeftParenthesis, Accumulating(usize), Starting, } pub fn update_nested_value<V>(target: &mut Value, path: &[&str], value: V) where V: Into<String>, { let map = match target { Value::Object(map) => map, _ => return, }; l...
}
fn test_aggregator_override() { let mut aggregator = ChunkedFormDataAggregator::new(); aggregator.insert(0, "hello,"); aggregator.insert(0, "bye"); assert!(!aggregator.is_empty()); assert_eq!(aggregator.join(), "bye"); }
function_block-full_function
[ { "content": "/// Parses tags in the format `tag1,tag2:value`.\n\n///\n\n/// Tag values are optional. For tags with missing values, an empty `\"\"` value is assumed.\n\nfn parse_tags(string: &str) -> Option<BTreeMap<String, String>> {\n\n let mut map = BTreeMap::new();\n\n\n\n for pair in string.split(','...
Rust
vm/src/protocol/buffer.rs
Dolpheyn/RustPython
6e39473fce0e28c43acfbd153d4848c4f9c4020c
use crate::common::borrow::{BorrowedValue, BorrowedValueMut}; use crate::common::rc::PyRc; use crate::PyThreadingConstraint; use crate::{PyObjectRef, PyResult, TryFromBorrowedObject, TypeProtocol, VirtualMachine}; use std::{borrow::Cow, fmt::Debug}; pub trait BufferInternal: Debug + PyThreadingConstraint { ...
use crate::common::borrow::{BorrowedValue, BorrowedValueMut}; use crate::common::rc::PyRc; use crate::PyThreadingConstraint; use crate::{PyObjectRef, PyResult, TryFromBorrowedObject, TypeProtocol, VirtualMachine}; use std::{borrow::Cow, fmt::Debug}; pub trait BufferInternal: Debug + PyThreadingConstraint { ...
ions.clone()) } } pub trait BufferResizeGuard<'a> { type Resizable: 'a; fn try_resizable(&'a self, vm: &VirtualMachine) -> PyResult<Self::Resizable>; }
PyBuffer { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<Self> { let obj_cls = obj.class(); for cls in obj_cls.iter_mro() { if let Some(f) = cls.slots.as_buffer.as_ref() { return f(obj, vm); } } Err(vm.new_typ...
random
[ { "content": "fn parse_number(text: &str) -> Result<(Option<usize>, &str), &'static str> {\n\n let num_digits: usize = get_num_digits(text);\n\n if num_digits == 0 {\n\n return Ok((None, text));\n\n }\n\n if let Ok(num) = text[..num_digits].parse::<usize>() {\n\n Ok((Some(num), &text[n...
Rust
src/youtube.rs
museun/dono_server
4f5d8279224cb428c22f051fe64b8d8f6739604d
use log::*; use once_cell::sync::Lazy; use once_cell::sync_lazy; use regex::Regex; use serde::{Deserialize, Serialize}; use crate::database; use crate::error::{Error, Result}; use crate::server; use crate::FromRow; static PATTERN: Lazy<Regex> = sync_lazy! { Regex::new( r#"(:?^(:?http?.*?youtu...
use log::*; use once_cell::sync::Lazy; use once_cell::sync_lazy; use regex::Regex; use serde::{Deserialize, Serialize}; use crate::database; use crate::error::{Error, Result}; use crate::server; use crate::FromRow; static PATTERN: Lazy<Regex> = sync_lazy! { Regex::new( r#"(:?^(:?http?.*?youtu...
fn build_query(id: &str) -> Result<String> { let map = &[ ("id", id), ("part", "snippet,contentDetails"), ( "fields", "items(id, snippet(title), contentDetails(duration))", ), ("key", API_KEY.as_str()), ...
let data = serde_json::from_slice::<Response>(&data).map_err(Error::Serialize)?; let item = &data.items.get(0).ok_or_else(|| Error::InvalidYoutubeData)?; Ok(Self { title: item.snippet.title.to_string(), duration: from_iso8601(item.details.duration), }) }
function_block-function_prefix_line
[ { "content": "pub fn get_connection() -> rusqlite::Connection {\n\n rusqlite::Connection::open(DB_PATH.get().unwrap()).expect(\"connect to database\")\n\n}\n\n\n\n// let mut stmt = conn.prepare(include_str!(\"../sql/youtube/get_current.sql\"))?;\n\n// let mut stmt = conn.prepare(include_str!(\"../sql/youtube...
Rust
tests/socket.rs
ammarzuberi/socket2-rs
dc82e662cda027f69abb75917777943fbffb8463
#[cfg(any(windows, all(feature = "all", target_vendor = "apple")))] use std::io; #[cfg(unix)] use std::os::unix::io::AsRawFd; #[cfg(windows)] use std::os::windows::io::AsRawSocket; #[cfg(windows)] use winapi::shared::minwindef::DWORD; #[cfg(windows)] use winapi::um::handleapi::GetHandleInformation; #[cfg(windows)] use...
#[cfg(any(windows, all(feature = "all", target_vendor = "apple")))] use std::io; #[cfg(unix)] use std::os::unix::io::AsRawFd; #[cfg(windows)] use std::os::windows::io::AsRawSocket; #[cfg(windows)] use winapi::shared::minwindef::DWORD; #[cfg(windows)] use winapi::um::handleapi::GetHandleInformation; #[cfg(windows)] use...
if res != 0 { let err = io::Error::last_os_error(); panic!("unexpected error: {}", err); } assert_eq!(length as usize, size_of::<libc::c_int>()); assert_eq!(flags, want as _, "non-blocking option"); }
let res = unsafe { libc::getsockopt( socket.as_raw_fd(), libc::SOL_SOCKET, libc::SO_NOSIGPIPE, &mut flags as *mut _ as *mut _, &mut length, ) };
assignment_statement
[ { "content": "fn ms2dur(raw: DWORD) -> Option<Duration> {\n\n if raw == 0 {\n\n None\n\n } else {\n\n let secs = raw / 1000;\n\n let nsec = (raw % 1000) * 1000000;\n\n Some(Duration::new(secs as u64, nsec as u32))\n\n }\n\n}\n\n\n\npub(crate) fn to_in_addr(addr: &Ipv4Addr) -...
Rust
core/src/core/pmmr/readonly_pmmr.rs
markoverride/grin
180cfd7b4c5985e9eafdd8bc5ef6f55f12993e67
use std::marker; use crate::core::hash::Hash; use crate::core::pmmr::pmmr::{bintree_rightmost, ReadablePMMR}; use crate::core::pmmr::{is_leaf, Backend}; use crate::ser::PMMRable; pub struct ReadonlyPMMR<'a, T, B> where T: PMMRable, B: Backend<T>, { last_pos: u64, backend: &'a B, _marker: marker::PhantomD...
use std::marker; use crate::core::hash::Hash; use crate::core::pmmr::pmmr::{bintree_rightmost, ReadablePMMR}; use crate::core::pmmr::{is_leaf, Backend}; use crate::ser::PMMRable; pub struct ReadonlyPMMR<'a, T, B> where T: PMMRable, B: Backend<T>, { last_pos: u64, backend: &'a B, _marker: marker::PhantomD...
em = u64> + '_> { self.backend.leaf_idx_iter(from_idx) } fn n_unpruned_leaves(&self) -> u64 { self.backend.n_unpruned_leaves() } }
Some(p) => p, None => self.last_pos, }; if pmmr_index == 0 { pmmr_index = 1; } while return_vec.len() < max_count as usize && pmmr_index <= last_pos { if let Some(t) = self.get_data(pmmr_index) { return_vec.push(t); } pmmr_index += 1; } (pmmr_index.saturating_sub(1), return_vec) } ...
random
[ { "content": "/// Gets the postorder traversal index of all peaks in a MMR given its size.\n\n/// Starts with the top peak, which is always on the left\n\n/// side of the range, and navigates toward lower siblings toward the right\n\n/// of the range.\n\npub fn peaks(num: u64) -> Vec<u64> {\n\n\tif num == 0 {\n...
Rust
src/proto/tcp.rs
andreycizov/rust-sockfw
c40296dc7b092d1837ac4de84c5360917f8ee1be
use mio::tcp::{TcpListener as MioTcpListener, TcpStream}; use std::io::{Error as IoError, ErrorKind, Read, Write}; use std::net::SocketAddr; use mio::{Poll, Token, Ready, PollOpt}; use clap::{App, Arg, ArgMatches}; use crate::{Listener, MidChan, Chan, FwError, NextState, Pollable}; use crate::args::Parsable; use crate...
use mio::tcp::{TcpListener as MioTcpListener, TcpStream}; use std::io::{Error as IoError, ErrorKind, Read, Write}; use std::net::SocketAddr; use mio::{Poll, Token, Ready, PollOpt}; use clap::{App, Arg, ArgMatches}; use crate::{Listener, MidChan, Chan, FwError, NextState, Pollable}; use crate::args::Parsable; use crate...
StreamConf::parser(app) } fn parse(matches: &ArgMatches) -> Result<TcpListener, FwError<TcpErr>> { let addr = matches.value_of("addr").ok_or("address not found")?; let addr = addr.parse::<SocketAddr>().map_err(|_| "invalid socket address")?; let conf = StreamConf::parse(&matc...
let app = app .arg( Arg::with_name("addr") .required(true) .index(1) );
assignment_statement
[ { "content": "pub trait ArgMatchesExt<R> {\n\n fn parse(self) -> R;\n\n}\n\n\n", "file_path": "src/args.rs", "rank": 0, "score": 71415.25747649762 }, { "content": "pub trait Chan {\n\n type Err: Debug;\n\n fn send(&mut self, buff: &[u8]) -> Result<usize, FwError<Self::Err>>;\n\n ...
Rust
src/numtheory.rs
canufeel/rust-threshold-secret-sharing
b6d110fba65d632e7dc83a21af56a62f6f2ef624
pub fn gcd(a: i64, b: i64) -> (i64, i64, i64) { if b == 0 { (a, 1, 0) } else { let n = a / b; let c = a % b; let r = gcd(b, c); (r.0, r.2, r.1 - r.2 * n) } } #[test] fn test_gcd() { assert_eq!(gcd(12, 16), (4, -1, 1)); } pub fn mod_inverse(k: i64, prime: i64) ...
pub fn gcd(a: i64, b: i64) -> (i64, i64, i64) { if b == 0 { (a, 1, 0) } else { let n = a / b; let c = a % b; let r = gcd(b, c); (r.0, r.2, r.1 - r.2 * n) } } #[test] fn test_gcd() { assert_eq!(gcd(12, 16), (4, -1, 1)); } pub fn mod_inverse(k: i64, prime: i64) ...
coefs = poly.coefficients; newton_coefs.iter() .zip(newton_points) .map(|(coef, point)| (coef * point) % prime) .fold(0, |a, b| (a + b) % prime) } fn compute_newton_coefficients(points: &[i64], values: &[i64], prime: i64) -> Vec<i64> { assert_eq!(points.len(), values.len()); l...
); assert_eq!(values, vec![8, 16, 4, 13, 16]); let recovered_poly = newton_interpolation_general(&points, &values, prime); let recovered_values: Vec<i64> = points.iter().map(|&point| newton_evaluate(&recovered_poly, point, prime)).collect(); assert_eq!(recovered_values, values); assert_eq!...
random
[ { "content": "/// 2-radix FFT.\n\n///\n\n/// * zp is the modular field\n\n/// * data is the data to transform\n\n/// * omega is the root-of-unity to use\n\n///\n\n/// `data.len()` must be a power of 2. omega must be a root of unity of order\n\n/// `data.len()`\n\npub fn fft2<F: Field>(zp: &F, data: &mut [F::U],...
Rust
src/compiler/src/symbol_table.rs
ghaiklor/nand-2-tetris
8238c71a7d076a90a58506d4de2e966c34f989df
use std::collections::HashMap; #[derive(Debug)] pub enum SymbolKind { Field, Static, Argument, Local, } #[derive(Debug)] pub struct Symbol<'a> { pub r#type: &'a str, pub kind: &'a SymbolKind, pub index: u16, } #[derive(Default, Debug)] pub struct SymbolTable<'a> { class_symbols: HashM...
use std::collections::HashMap; #[derive(Debug)] pub enum SymbolKind { Field, Static, Argument, Local, } #[derive(Debug)] pub struct Symbol<'a> { pub r#type: &'a str, pub kind: &'a SymbolKind, pub index: u16, } #[derive(Default, Debug)] pub struct SymbolTable<'a> { class_symbols: HashM...
gument" => SymbolKind::Argument, "field" => SymbolKind::Field, "static" => SymbolKind::Static, "local" => SymbolKind::Local, _ => panic!("Unknown kind {}", kind), } } pub fn kind_to_str(kind: &SymbolKind) -> &'a str { match kind { Symb...
self.field_index += 1; self.class_symbols.insert(name, symbol); } SymbolKind::Argument => { self.argument_index += 1; self.subroutine_symbols.insert(name, symbol); } SymbolKind::Local => { se...
random
[ { "content": "pub fn resolve<'a>(instructions: &'a [Instruction]) -> HashMap<&'a str, u16> {\n\n let mut symbols: HashMap<&str, u16> = HashMap::new();\n\n let mut next_address: u16 = 15;\n\n\n\n init_symbol_table(&mut symbols);\n\n\n\n for instruction in instructions {\n\n if let Instruction:...
Rust
examples3d/convex_decomposition3.rs
wsuchy/nphysics
07391d4a04e4f3d3fd2ea2362870236029163706
extern crate kiss3d; extern crate nalgebra as na; extern crate ncollide3d; extern crate nphysics3d; extern crate nphysics_testbed3d; extern crate rand; use std::path::Path; use na::{Isometry3, Point3, Translation3, Vector3}; use kiss3d::loader::obj; use ncollide3d::shape::{Compound, ConvexHull, Cuboid, ShapeHandle}; u...
extern crate kiss3d; extern crate nalgebra as na; extern crate ncollide3d; extern crate nphysics3d; extern crate nphysics_testbed3d; extern crate rand
w(0.0, 0.0, 0.0)); testbed.run(); } fn models() -> Vec<String> { vec![ "media/models/camel_decimated.obj".to_string(), "media/models/chair.obj".to_string(), "media/models/cup_decimated.obj".to_string(), "media/models/feline_decimated.obj".to_string(), "media/mod...
; use std::path::Path; use na::{Isometry3, Point3, Translation3, Vector3}; use kiss3d::loader::obj; use ncollide3d::shape::{Compound, ConvexHull, Cuboid, ShapeHandle}; use ncollide3d::procedural::TriMesh; use ncollide3d::transformation; use ncollide3d::bounding_volume::{self, BoundingVolume, AABB}; use nphysics3d::wor...
random
[ { "content": "fn na_vec_to_b2_vec(v: &Vector2<f32>) -> b2::Vec2 {\n\n b2::Vec2 { x: v.x, y: v.y }\n\n}\n\n\n", "file_path": "src_testbed/box2d_world.rs", "rank": 1, "score": 35070.47408538946 }, { "content": "fn b2_vec_to_na_vec(v: &b2::Vec2) -> Vector2<f32> {\n\n Vector2::new(v.x, v.y...
Rust
ignition-blob/src/main.rs
mvanbem/ignition
d22dffd786ff10f69ffa5f8d36cd46fd06288e00
use ignition_blob_proto::blob_pb; use std::convert::TryInto; use std::io::{self, SeekFrom}; use std::path::PathBuf; use testable_file_system::{real_file_system, FileSystem}; use thiserror::Error; use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; use tokio::sync::mpsc; use tokio_stream::wrappers::ReceiverStrea...
use ignition_blob_proto::blob_pb; use std::convert::TryInto; use std::io::{self, SeekFrom}; use std::path::PathBuf; use testable_file_system::{real_file_system, FileSystem}; use thiserror::Error; use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; use tokio::sync::mpsc; use tokio_stream::wrappers::ReceiverStrea...
fn unexpected_io_error(e: impl std::error::Error) -> Status { log::error!("unexpected I/O error: {}", e); Status::internal(&format!("unexpected I/O error: {}", e)) } struct BlobServiceImpl<F: FileSystem> { file_system: F, } #[tonic::async_trait] impl<F: FileSystem + 'static> blob_pb::blob_service_server...
async fn main() -> Result<(), Box<dyn std::error::Error>> { simple_logger::SimpleLogger::new() .with_level(log::LevelFilter::Info) .init() .unwrap(); let addr = "[::1]:3030".parse()?; tonic::transport::Server::builder() .add_service(blob_pb::blob_service_server::BlobService...
function_block-full_function
[ { "content": "struct SendPointer<T>(*const T);\n\n\n\nunsafe impl<T> Send for SendPointer<T> {}\n\n\n", "file_path": "ignition-host/src/process/pipe.rs", "rank": 0, "score": 54240.710682554054 }, { "content": "#[proc_macro_derive(WriteTo, attributes(ignition_9p_wire))]\n\npub fn derive_write...
Rust
client-core/src/cipher/mock_abci_transaction_obfuscation.rs
chatch/chain
9ef4e2914688a80bb91c954f27bd2e4aeaede293
use parity_scale_codec::{Decode, Encode}; use chain_core::tx::data::TxId; use chain_core::tx::{TxAux, TxWithOutputs}; use client_common::tendermint::Client; use client_common::{ ErrorKind, PrivateKey, Result, ResultExt, SignedTransaction, Transaction, SECP, }; use enclave_protocol::{ DecryptionRequest, Decrypt...
use parity_scale_codec::{Decode, Encode}; use chain_core::tx::data::TxId; use chain_core::tx::{TxAux, TxWithOutputs}; use client_common::tendermint::Client; use client_common::{ ErrorKind, PrivateKey, Result, ResultExt, SignedTransaction, Transaction, SECP, }; use enclave_protocol::{ DecryptionRequest, Decrypt...
fn encrypt(&self, transaction: SignedTransaction) -> Result<TxAux> { match transaction { SignedTransaction::TransferTransaction(tx, witness) => { self.encrypt_request(EncryptionRequest::TransferTx(tx, witness)) } SignedTransaction::DepositStakeTransactio...
fn decrypt( &self, transaction_ids: &[TxId], private_key: &PrivateKey, ) -> Result<Vec<Transaction>> { let request = SECP.with(|secp| { DecryptionRequest::create( &secp, transaction_ids.to_owned(), [0u8; 32], ...
function_block-full_function
[ { "content": "pub fn get_ecdsa_witness<C: Signing>(\n\n secp: &Secp256k1<C>,\n\n txid: &TxId,\n\n secret_key: &SecretKey,\n\n) -> EcdsaSignature {\n\n let message = Message::from_slice(&txid[..]).expect(\"32 bytes\");\n\n let sig = secp.sign_recoverable(&message, &secret_key);\n\n return sig;\...
Rust
src/util/math.rs
tiffany1618/imgproc-rs
69c5fd4c0b82d4155adc065f076907d70d0e45e4
use crate::error; use crate::image::{Number, SubImage, BaseImage}; use crate::error::ImgProcResult; use std::f64::consts::{PI, E}; use rulinalg::matrix::{Matrix, BaseMatrix}; pub fn vector_mul<T: Number>(mat: &[T], input: &[T]) -> ImgProcResult<Vec<T>> { let rows = input.len(); let mat_cols = mat.len() / rows...
use crate::error; use crate::image::{Number, SubImage, BaseImage}; use crate::error::ImgProcResult; use std::f64::consts::{PI, E}; use rulinalg::matrix::{Matrix, BaseMatrix}; pub fn vector_mul<T: Number>(mat: &[T], input: &[T]) -> ImgProcResult<Vec<T>> { let rows = input.len(); let mat_cols = mat.len() / rows...
pub fn distance(x_1: u32, y_1: u32, x_2: u32, y_2: u32) -> f64 { let x_dist = (x_1 as f64) - (x_2 as f64); let y_dist = (y_1 as f64) - (y_2 as f64); ((x_dist * x_dist) + (y_dist * y_dist)).sqrt() } pub fn gaussian_fn(x: f64, sigma: f64) -> ImgProcResult<f64> { error::check_non_neg(sigma, "sigma")?; ...
let mut output = vec![0.0; input.info().channels as usize]; for y in 0..size { for x in 0..size { let index = y * size + x; for (j, val) in output.iter_mut().enumerate() { *val += kernel[index] * input[index][j]; } } } Ok(output) }
function_block-function_prefix_line
[ { "content": "#[cfg(not(feature = \"rayon\"))]\n\nfn bilateral_direct_pixel(input: &Image<f64>, output: &mut Vec<f64>, range: f64, spatial_mat: &[f64], size: u32, x: u32, y: u32) {\n\n let p_n = input.get_neighborhood_2d(x, y, size as u32);\n\n let p_in = input.get_pixel(x, y);\n\n output.clear();\n\n\...
Rust
src/terminal/termion.rs
dnaka91/inquire
2c7a276376695d1869a30d1e16fd55b67c5e9d0a
use core::fmt; use std::io::{stdin, stdout, Result, Stdin, Stdout, Write}; use termion::{ color::{self, Color}, cursor, event::Key, input::{Keys, TermRead}, raw::{IntoRawMode, RawTerminal}, terminal_size, }; use crate::{ error::{InquireError, InquireResult}, ui::{Attributes, Styled}, }...
use core::fmt; use std::io::{stdin, stdout, Result, Stdin, Stdout, Write}; use termion::{ color::{self, Color}, cursor, event::Key, input::{Keys, TermRead}, raw::{IntoRawMode, RawTerminal}, terminal_size, }; use crate::{ error::{InquireError, InquireResult}, ui::{Attributes, Styled}, }...
g writing wow", std::str::from_utf8(&write).unwrap()); } #[test] fn style_management() { let mut write: Vec<u8> = Vec::new(); let read = Vec::new(); let mut read = read.iter(); { let mut terminal = TermionTerminal::new_with_io(&mut write, &mut read); ...
uper::Attributes; use super::TermionTerminal; #[test] fn writer() { let mut write: Vec<u8> = Vec::new(); let read = Vec::new(); let mut read = read.iter(); { let mut terminal = TermionTerminal::new_with_io(&mut write, &mut read); terminal.write("tes...
random
[ { "content": "pub fn get_default_terminal() -> InquireResult<impl Terminal> {\n\n #[cfg(feature = \"crossterm\")]\n\n return crossterm::CrosstermTerminal::new();\n\n\n\n #[cfg(all(feature = \"termion\", not(feature = \"crossterm\")))]\n\n return termion::TermionTerminal::new();\n\n\n\n #[cfg(all(...
Rust
src/ffi/solver.rs
andersk/ipasir-rs
5af2f04dde65cf13d6de3faa1dacf734511060bf
pub use crate::{ ffi::sys::*, Result, Sign, Var, Lit, InvalidLitVal, Clause, LitIter, SolverErrorKind, SolverError, SolveResponse, ResponseError, LitValue, IpasirSolver, SolveControl, }; use std::{ os::raw::{ c_int, c_void, }, ff...
pub use crate::{ ffi::sys::*, Result, Sign, Var, Lit, InvalidLitVal, Clause, LitIter, SolverErrorKind, SolverError, SolveResponse, ResponseError, LitValue, IpasirSolver, SolveControl, }; use std::{ os::raw::{ c_int, c_void, }, ff...
fn assume(&mut self, lit: Lit) { unsafe{ ipasir_assume(self.raw_mut(), lit.to_raw()) } } fn solve(&mut self) -> Result<SolveResponse> { match unsafe{ ipasir_solve(self.raw_mut()) } { 0 => Ok(SolveResponse::Interrupted), 10 => Ok(SolveResponse::Sat), 20 ...
fn add_clause<I, L>(&mut self, lits: I) where I: IntoIterator<Item = L>, L: Into<Lit>, { for lit in lits.into_iter() { unsafe { ipasir_add(self.raw_mut(), lit.into().to_raw()) } } unsafe { ipasir_add(self.raw_mut(), 0) } }
function_block-full_function
[ { "content": "/// The IPASIR interface a SAT solver has to implement to be conforming.\n\npub trait IpasirSolver {\n\n /// Returns name and version of the incremental SAT solving implementation.\n\n fn signature(&self) -> &'static str;\n\n\n\n /// Return a new incremental SAT solver.\n\n ///\n\n ...
Rust
exercises/decimal/tests/decimal.rs
hunger/rust
0df41e20d0ddf7927dce28a78e50c1366980cb17
use decimal::Decimal; fn decimal(input: &str) -> Decimal { Decimal::try_from(input).expect("That was supposed to be a valid value") } const BIGS: [&'static str; 3] = [ "100000000000000000000000000000000000000000000.00000000000000000000000000000000000000001", "100000000000000000000000000000000000000000000....
use decimal::Decimal; fn decimal(input: &str) -> Decimal { Decimal::try_from(input).expect("That was supposed to be a valid value") } const BIGS: [&'static str; 3] = [ "100000000000000000000000000000000000000000000.00000000000000000000000000000000000000001", "100000000000000000000000000000000000000000000....
#[test] #[ignore] fn test_cleanup_precision() { assert_eq!( decimal("10000000000000000000000000000000000000000000000.999999999999999999999999998",) + decimal( "10000000000000000000000000000000000000000000000.000000000000000000000000002", ), decimal("20000000...
fn test_add_vary_precision() { assert_eq!( decimal("100000000000000000000000000000000000000000000") + decimal("0.00000000000000000000000000000000000000001"), decimal(BIGS[0]) ) }
function_block-function_prefix_line
[ { "content": "// The input data constructor. Returns a list of codon, name pairs.\n\nfn make_pairs() -> Vec<(&'static str, &'static str)> {\n\n let grouped = vec![\n\n (\"isoleucine\", vec![\"AUU\", \"AUC\", \"AUA\"]),\n\n (\"valine\", vec![\"GUU\", \"GUC\", \"GUA\", \"GUG\"]),\n\n (\"ph...
Rust
src/parser.rs
cfsamson/xml-stringify
40caf0e43bb639040781bc400e4b2a5b4aeb7f2a
use crate::values::{ValuePos, Values}; use std::str::Chars; #[derive(Debug)] enum Token { WhiteSpace, LeftCroc, RightCroc, Equalsign, Slash, Tick, NewLine, Char, } impl Token { fn from(c: char) -> Token { use Token::*; match c { ' ' => WhiteSpace, ...
use crate::values::{ValuePos, Values}; use std::str::Chars; #[derive(Debug)] enum Token { WhiteSpace, LeftCroc, RightCroc, Equalsign, Slash, Tick, NewLine, Char, } impl Token { fn from(c: char) -> Token { use Token::*; match c { ' ' => WhiteSpace, ...
unt: 0, start_pos: None, end_pos: 0, bytepos: 0, } } pub fn parse(mut self) -> Values<'a> { while let Some(ch) = self.input.next() { self.step(ch); } self.values } fn extract(&mut self) { let start = self.sta...
original: input, input: input.chars(), state: ParseState::OutsideBracket, values: Values::new(input), charco
function_block-random_span
[ { "content": "fn parse_via_quick_xml(text: &str) {\n\n let mut r = quick_xml::Reader::from_str(text);\n\n r.check_comments(true);\n\n let mut buf = Vec::new();\n\n let mut ns_buf = Vec::new();\n\n loop {\n\n match r.read_namespaced_event(&mut buf, &mut ns_buf) {\n\n Ok((_, quick...
Rust
src/api/groups/groups.rs
kalzoo/rust-gitlab
f08c301293bf8267cd01f0892a89db8dba4f8cf6
use std::collections::BTreeSet; use derive_builder::Builder; use crate::api::common::{AccessLevel, SortOrder}; use crate::api::endpoint_prelude::*; use crate::api::ParamValue; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GroupOrderBy { Name, Path, Id, } impl Default for GroupOr...
use std::collections::BTreeSet; use derive_builder::Builder; use crate::api::common::{AccessLevel, SortOrder}; use crate::api::endpoint_prelude::*; use crate::api::ParamValue; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum GroupOrderBy { Name, Path, Id, } impl Default for GroupOr...
} impl<'a> Endpoint for Groups<'a> { fn method(&self) -> Method { Method::GET } fn endpoint(&self) -> Cow<'static, str> { "groups".into() } fn parameters(&self) -> QueryParams { let mut params = QueryParams::default(); params .push_opt("search", self....
pub fn skip_groups<I>(&mut self, iter: I) -> &mut Self where I: Iterator<Item = u64>, { self.skip_groups .get_or_insert_with(BTreeSet::new) .extend(iter); self }
function_block-full_function
[ { "content": "/// Escape a string for usage as a single URL path component.\n\npub fn path_escaped(input: &'_ str) -> impl fmt::Display + '_ {\n\n utf8_percent_encode(input, PATH_SEGMENT_ENCODE_SET)\n\n}\n\n\n\nimpl<'a> fmt::Display for NameOrId<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Resu...
Rust
day16/src/lib.rs
PurpleMyst/aoc-2021
a7d5b590b3c03e799174f84beaa0b195e7e84750
use std::fmt::Display; use nom::bits::complete::take; use nom::combinator::{map, map_opt}; use nom::multi::fold_many0; use nom::sequence::tuple; use nom::InputLength; use either::Either; use nom_supreme::error::ErrorTree; type IResult<I, O> = nom::IResult<I, O, ErrorTree<I>>; #[derive(Debug, PartialEq, Eq)] struct ...
use std::fmt::Display; use nom::bits::complete::take; use nom::combinator::{map, map_opt}; use nom::multi::fold_many0; use nom::sequence::tuple; use nom::InputLength; use either::Either; use nom_supreme::error::ErrorTree; type IResult<I, O> = nom::IResult<I, O, ErrorTree<I>>; #[derive(Debug, PartialEq, Eq)] struct ...
fn load_input(input: &str) -> Vec<u8> { input .trim() .as_bytes() .chunks_exact(2) .map(|c| u8::from_str_radix(std::str::from_utf8(c).unwrap(), 16).unwrap()) .collect() } fn sum_versions(packet: &Packet) -> usize { match packet { Packet::Literal(LiteralPacket {...
fn packet(input: (&[u8], usize)) -> IResult<(&[u8], usize), Packet> { let (input, header) = match packet_header(input)? { (input, Either::Left(header)) => (input, header), (input, Either::Right(literal)) => return Ok((input, Packet::Literal(literal))), }; let (input, children) = match heade...
function_block-full_function
[ { "content": "fn p2_score(b: u8) -> u64 {\n\n match b {\n\n b'(' => 1,\n\n b'[' => 2,\n\n b'{' => 3,\n\n b'<' => 4,\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "day10/src/lib.rs", "rank": 1, "score": 185181.3601294302 }, { "content": "fn ...
Rust
utils/rc-tests/tests/aead.rs
tanmay2004/hacspec
49a3e48fe7f4b3082df91bb232deb558eb0688f2
mod test_util; use test_util::*; use chacha20poly1305::ChaCha20Poly1305 as RustCrypto_ChaCha20Poly1305; use evercrypt_provider::Chacha20Poly1305 as Evercrypt_Chacha20Poly1305; use hacspec_provider::{ aead::consts::U12, Aead, AeadCore, Chacha20Poly1305 as Hacspec_Chacha20Poly1305, Key, NewAead, Nonce, Payload, ...
mod test_util; use test_util::*; use chacha20poly1305::ChaCha20Poly1305 as RustCrypto_ChaCha20Poly1305; use evercrypt_provider::Chacha20Poly1305 as Evercrypt_Chacha20Poly1305; use hacspec_provider::{ aead::consts::U12, Aead, AeadCore, Chacha20Poly1305 as Hacspec_Chacha20Poly1305, Key, NewAead, Nonce, Payload, ...
g, &aad, exp_tag, &exp_cipher, tests_run, invalid_iv, valid, ); } } } println!( "Ran {} out of {} tests and skipped {}.", tests_run, nu...
function_block-function_prefixed
[ { "content": "fn chacha20_counter_mode(key: &Key, counter: U32, nonce: &Nonce, msg: &Vec<U8>) -> Vec<U8> {\n\n let mut blocks: Vec<[U8; BLOCK_SIZE]> = msg\n\n .chunks(BLOCK_SIZE)\n\n .map(|block| {\n\n let mut new_block = [U8::zero(); BLOCK_SIZE];\n\n new_block[0..block.le...
Rust
query-engine/prisma/src/data_model_loader.rs
williamluke4/prisma-engine
54c4d8ce690254b5d0c77a21361896a6ca3fc4b7
use std::{fs::File, io::Read}; use serde::Deserialize; use serde_json; use datamodel::{Datamodel, Source}; use prisma_models::{DatamodelConverter, InternalDataModelTemplate}; use crate::{utilities, PrismaError, PrismaResult}; pub struct DatamodelV2Components { pub datamodel: Datamodel, pub data_sources: Vec...
use std::{fs::File, io::Read}; use serde::Deserialize; use serde_json; use datamodel::{Datamodel, Source}; use prisma_models::{DatamodelConverter, InternalDataModelTemplate}; use crate::{utilities, PrismaError, PrismaResult}; pub struct DatamodelV2Components { pub datamodel: Datamodel, pub data_sources: Vec...
"Decoding Base64 failed (might not be encoded): {:?}", e); Ok(Some(string)) } }, None => Ok(None), } } fn load_from_file(env_var: &str) -> PrismaResult<Option<String>> { match utilities::get_env(env_var).ok() { Some(path) => { let mut f = File::op...
: &str) -> PrismaResult<Option<String>> { match utilities::get_env(env_var).ok() { Some(string) => match base64::decode(&string) { Ok(bytes) => match String::from_utf8(bytes) { Ok(result) => { trace!("Successfully decoded {} from Base64.", env_var); ...
function_block-random_span
[ { "content": "/// Parses and validates a datamodel string, using core attributes only.\n\n/// In case of an error, a pretty, colorful string is returned.\n\npub fn parse_datamodel_or_pretty_error(datamodel_string: &str, file_name: &str) -> Result<Datamodel, String> {\n\n match parse_datamodel_with_sources(da...
Rust
src/lib.rs
saturn-xiv/palm
5135c70a009e3d2703bf13cff36bb836940f3113
#[macro_use] extern crate diesel; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; pub mod app; pub mod audio; pub mod auth; pub mod aws; pub mod cache; pub mod crypto; pub mod env; pub mod gpio; pub mod i18n; pub mod image_magick; pub mod jwt; pub mod mailer; pub mod...
#[macro_use] extern crate diesel; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] pub mod macros; pub mod app; pub mod audio; pub mod auth; pub mod aws; pub mod cache; pub mod crypto; pub mod env; pub mod gpio; pub mod i18n; pub mod image_magick; pub mod jwt; pub mod mailer; pub mod...
} pub const XML_HEADER: &str = r###"<?xml version="1.0" encoding="utf-8" ?>"###; pub trait ToXml { fn write<W: Write>(&self, wrt: &mut EventWriter<W>) -> XmlWriterResult<()>; } pub fn content_type<P: AsRef<Path>>(file: P) -> Result<mime::Mime> { let file = file.as_ref(); if let Some(it) = file.extension...
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { match s { Self::HTML => Ok(Self::Html), Self::MARKDOWN => Ok(Self::Markdown), Self::PLAIN_TEXT => Ok(Self::PlainText), _ => Err(Box::new(HttpError( StatusCode::BAD_REQUEST, ...
function_block-full_function
[ { "content": "pub fn i18n(db: &mut Db, lang: &str) -> Result<HashMap<String, String>> {\n\n let it = LocaleDao::by_lang(db, lang)?\n\n .iter()\n\n .map(|x| (x.code.clone(), x.message.clone()))\n\n .collect::<HashMap<_, _>>();\n\n Ok(it)\n\n}\n", "file_path": "camelia/src/controlle...
Rust
server/src/main1.rs
rtg-project/rtg
95b9fbc1de1f4a37cdccb5d90613091f58000622
#![allow(unused_variables)] use log::{debug, error, info, log_enabled, Level}; use std::env; use warp::{http::Response, Filter}; use juniper::{ graphql_object, EmptySubscription, FieldResult, GraphQLEnum, GraphQLInputObject, GraphQLObject, ScalarValue, }; use std::fmt::Display; struct DatabasePool; impl Dat...
#![allow(unused_variables)] use log::{debug, error, info, log_enabled, Level}; use std::env; use warp::{http::Response, Filter}; use juniper::{ graphql_object, EmptySubscription, FieldResult, GraphQLEnum, GraphQLInputObject, GraphQLObject, ScalarValue, }; use std::fmt::Display; struct DatabasePool; impl Dat...
human) } } struct Mutation; #[graphql_object( context = Context, scalar = S: ScalarValue + Display, )] impl Mutation { fn createHuman<S: ScalarValue + Display>( context: &Context, new_human: NewHuman, ) -> FieldResult<Human, S> { let db = context ...
t)] #[graphql(description = "A humanoid creature in the Star Wars universe")] struct NewHuman { name: String, appears_in: Vec<Episode>, home_planet: String, } struct Context { pool: DatabasePool, } impl juniper::Context for Context {} struct Query; #[graphql_object( context =...
random
[ { "content": "pub fn inflect_graphql_filter_type_name_from_name(name: &str) -> String {\n\n format!(\n\n \"{}WhereInput\",\n\n Inflector::to_pascal_case(&Inflector::to_singular(name))\n\n )\n\n}\n\n\n", "file_path": "model/src/inflection/entity.rs", "rank": 0, "score": 234540.23022827576 }...
Rust
rose-lib/src/io/writer.rs
wjsassi/rose-tools
31b5316e28c6fb0add6daa84d3d05eff516d6a8f
use std::cmp; use std::io; use std::io::{BufWriter, Seek, SeekFrom, Write}; use byteorder::{LittleEndian, WriteBytesExt}; use failure::Error; use crate::utils::{Color3, Color4, Quaternion, Vector2, Vector3, Vector4}; pub struct RoseWriter<W: Write> { pub writer: BufWriter<W>, } impl<W: Write> RoseWriter<W> { ...
use std::cmp; use std::io; use std::io::{BufWriter, Seek, SeekFrom, Write}; use byteorder::{LittleEndian, WriteBytesExt}; use failure::Error; use crate::utils::{Color3, Color4, Quaternion, Vector2, Vector3, Vector4}; pub struct RoseWriter<W: Write> { pub writer: BufWriter<W>, } impl<W: Write> RoseWriter<W> { ...
Ok(()) } fn write_cstring(&mut self, string: &str) -> Result<(), Error> { self.write_all(string.as_bytes())?; WriteRoseExt::write_u8(self, 0x00)?; Ok(()) } fn write_string_u8(&mut self, string: &str) -> Result<(), Error> { WriteRoseExt::write_u8(self, string.l...
if len > string_len { for _ in 0..(len - string_len) { WriteRoseExt::write_u8(self, 0x00)?; } }
if_condition
[ { "content": "/// Decodes a string by first trying to read as UTF-8, otherwise falls back\n\n/// to EUC-KR encoding using replacement characters where necessary. If the\n\n/// wide argument is set then it will only try to decode the string as UTF-16LE\n\nfn decode_string(b: Vec<u8>, wide: bool) -> String {\n\n ...
Rust
day11-rust/src/main.rs
jgosmann/aoc2021
ea507a44d7caeff0f5341946834fb329c87f0536
use std::error::Error; use std::io::{self, BufRead}; type Pos = (usize, usize); pub struct NeighborIterator { pos: Pos, upper_bounds: Pos, state: u8, } impl NeighborIterator { pub fn new(pos: Pos, upper_bounds: Pos) -> Self { Self { pos, upper_bounds, state...
use std::error::Error; use std::io::{self, BufRead}; type Pos = (usize, usize); pub struct NeighborIterator { pos: Pos, upper_bounds: Pos, state: u8, } impl NeighborIterator { pub fn new(pos: Pos, upper_bounds: Pos) -> Self { Self { pos, upper_bounds, state...
pub fn num_flashes(&self) -> usize { self.num_flashes } pub fn first_synchronized_flash(&self) -> Option<usize> { self.first_synchronized_flash } pub fn step_n(&mut self, n: usize) { (0..n).for_each(|_| self.step()); } pub fn step_until_first_synchronized_flash(&...
f { Self { grid, step_idx: 0, num_flashes: 0, first_synchronized_flash: None, } }
function_block-function_prefixed
[ { "content": "fn replicate(grid: &Vec<Vec<u8>>) -> Vec<Vec<u8>> {\n\n let replicated_cols: Vec<Vec<u8>> = grid\n\n .iter()\n\n .map(|row| {\n\n (0..5)\n\n .flat_map(|i| row.iter().map(move |&x| (x + i - 1) % 9 + 1))\n\n .collect()\n\n })\n\n ...
Rust
src/types/array.rs
reem/rust-postgres
4a9ca42b20a75a656a5424fc682adc767ebd2d39
use std::mem; use std::slice; #[deriving(PartialEq, Eq, Clone)] pub struct DimensionInfo { pub len: uint, pub lower_bound: int, } pub trait Array<T> { fn dimension_info<'a>(&'a self) -> &'a [DimensionInfo]; fn slice<'a>(&'a self, idx: int) -> ArraySlice<'a, T...
use std::mem; use std::slice; #[deriving(PartialEq, Eq, Clone)] pub struct DimensionInfo { pub len: uint, pub lower_bound: int, } pub trait Array<T> { fn dimension_info<'a>(&'a self) -> &'a [DimensionInfo]; fn slice<'a>(&'a self, idx: int) -> ArraySlice<'a, T...
fn get<'a>(&'a self, idx: int) -> &'a T { assert!(self.info.len() == 1, "Attempted to get from a multi-dimensional array"); self.raw_get(self.shift_idx(idx), 1) } } impl<T> MutableArray<T> for ArrayBase<T> { fn slice_mut<'a>(&'a mut self, idx: int) -> MutArraySlice<'a, T> ...
fn slice<'a>(&'a self, idx: int) -> ArraySlice<'a, T> { assert!(self.info.len() != 1, "Attempted to slice a one-dimensional array"); ArraySlice { parent: BaseParent(self), idx: self.shift_idx(idx), } }
function_block-full_function
[ { "content": "#[doc(hidden)]\n\npub trait BoundSided {\n\n /// Returns the bound side this type corresponds to\n\n // param is a hack to get around lack of hints for self type\n\n fn side(_: Option<Self>) -> BoundSide;\n\n}\n\n\n\n/// A tag type representing an upper bound\n\npub enum UpperBound {}\n\n...
Rust
src/bot.rs
nerosnm/oxbow
6b585e3ff3dad8cc1ce09192157ccdd5d31a59c2
mod builder; mod handler; use std::{collections::HashMap, ops::DerefMut}; use eyre::Result; use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use thiserror::Error; use tokio::sync::{broadcast, mpsc}; use tracing::{debug, info, instrument}; use twitch_irc::{login::RefreshingLoginCredentials, ClientConfig, TCPT...
mod builder; mod handler; use std::{collections::HashMap, ops::DerefMut}; use eyre::Result; use r2d2::Pool; use r2d2_sqlite::SqliteConnectionManager; use thiserror::Error; use tokio::sync::{broadcast, mpsc}; use tracing::{debug, info, instrument}; use twitch_irc::{login::RefreshingLoginCredentials, ClientConfig, TCPT...
} #[derive(Debug, Error)] pub enum BotError { #[error("migration error: {0}")] Migration(#[from] refinery::Error), #[error("authentication error: {0}")] Auth(#[from] crate::auth::AuthError), #[error("rusqlite error: {0}")] Rusqlite(#[from] rusqlite::Error), #[error("r2d2 error: {0}")] ...
ndler = ReceiveHandler { msg_rx, task_tx, prefix, twitch_name, parser: CommandParser::new(), }; handler.receive_loop().await; }); let res_tx = res_tx_orig.clone(); let comm...
function_block-function_prefixed
[ { "content": "/// Open a connection to the in-memory SQLite3 database.\n\npub fn in_memory() -> Result<Connection> {\n\n let conn = Connection::open_in_memory()?;\n\n\n\n Ok(conn)\n\n}\n\n\n\n/// Errors that could be encountered while performing database operations.\n\n#[derive(Debug, Error)]\n\npub enum ...
Rust
day16/src/common.rs
ljgago/advent-of-code-2020
1c11dc9119e6b6c22cc6ab92a9dd3d5e9be6f6cb
use std::ops::RangeInclusive; #[derive(Debug, PartialEq, Clone)] pub struct Rule { pub name: String, pub range1: RangeInclusive<usize>, pub range2: RangeInclusive<usize>, } #[derive(Debug, PartialEq, Clone)] pub struct Document { pub rules: Vec<Rule>, pub your_ticket: Vec<usize>, pub nearby_...
use std::ops::RangeInclusive; #[derive(Debug, PartialEq, Clone)] pub struct Rule { pub name: String, pub range1: RangeInclusive<usize>, pub range2: RangeInclusive<usize>, } #[derive(Debug, PartialEq, Clone)] pub struct Document { pub rules: Vec<Rule>, pub your_ticket: Vec<usize>, pub nearby_...
} }) .collect(); let vec_your_ticket: Vec<&str> = s[1] .trim() .lines() .collect(); let your_ticket: Vec<usize> = vec_your_ticket[1] .trim() .split(",") .map(|ticket| ticket.parse().unwrap()) .collect(); let vec_nearby_ti...
vec_rule: Vec<&str> = str_rule.trim().split(": ").collect(); let name: String = vec_rule[0].trim().to_owned(); let vec_range: Vec<&str> = vec_rule[1].trim().split(" or ").collect(); let vec_range1: Vec<&str> = vec_range[0].trim().split("-").collect(); let vec_range2: Vec...
random
[ { "content": "pub fn check_contain_color_bags(root: &str, target: &str, bags_hash: &HashMap<String, Vec<(String, usize)>>) -> bool {\n\n if *root == *target {\n\n return true;\n\n }\n\n if root == \"no other\" {\n\n return false;\n\n }\n\n\n\n let found: bool = bags_hash.get(root)\n...
Rust
src/lib.rs
librelois/fast-threadpool
1a271710677ecc43cbfe43234ec21c954dfdbef7
#![cfg_attr(test, recursion_limit = "256")] #![deny( clippy::unwrap_used, missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unstable_features, unused_import_braces, unused_qualifications )] mod config; mod handler; mod...
#![cfg_attr(test, recursion_limit = "256")] #![deny( clippy::unwrap_used, missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unstable_features, unused_import_braces, unused_qualifications )] mod config; mod handler; mod...
#[cfg(feature = "async")] pub fn async_handler(&self) -> ThreadPoolAsyncHandler<Shared> { ThreadPoolAsyncHandler::new(self.sender.clone()) } pub fn sync_handler(&self) -> ThreadPoolSyncHandler<Shared> { ThreadPoolSyncHandler::new(self.sender.clone()) } #[cfg(feature = ...
pub fn start(config: ThreadPoolConfig, shared: Shared) -> Self { let state = State::new(config); let (sender, receiver) = if let Some(queue_size) = config.queue_size { flume::bounded(queue_size) } else { flume::unbounded() }; for _ in 0..config.min_worker...
function_block-full_function
[ { "content": "use crate::*;\n\n\n\npub(crate) enum MsgForWorker<Shared: Clone + Send> {\n\n NewJob(Job<Shared>),\n\n Spawn,\n\n}\n\n\n\n#[derive(Clone)]\n\npub(crate) struct Worker<Shared: 'static + Clone + Send> {\n\n keep_alive: Duration,\n\n receiver: FlumeReceiver<MsgForWorker<Shared>>,\n\n s...
Rust
runtime/src/enclave_rpc/dispatcher.rs
OasisUnofficial/oasis-core
fb171c4892e08c83b06adab1ce345079e8280b82
use std::collections::HashMap; use anyhow::Result; use thiserror::Error; use super::{ context::Context, types::{Body, Request, Response}, }; #[derive(Error, Debug)] enum DispatchError { #[error("method not found: {method:?}")] MethodNotFound { method: String }, } pub trait ContextInitializer { ...
use std::collections::HashMap; use anyhow::Result; use thiserror::Error; use super::{ context::Context, types::{Body, Request, Response}, }; #[derive(Error, Debug)] enum DispatchError { #[error("method not found: {method:?}")] MethodNotFound { method: String }, } pub trait ContextInitializer { ...
body: Body::Error(format!("{}", error)), }, } } pub fn handle_km_policy_update(&self, signed_policy_raw: Vec<u8>) { if let Some(handler) = self.km_policy_handler.as_ref() { handler(signed_policy_raw) } } pub fn set_keymanager_po...
dler: MethodHandler<Rq, Rsp> + Send + Sync + 'static, { Method { dispatcher: Box::new(MethodHandlerDispatchImpl { descriptor: method, handler: Box::new(handler), }), } } pub fn get_name(&self) -> &String { &self.dispatcher...
random
[ { "content": "/// See `Kdf::get_or_create_keys`.\n\npub fn get_or_create_keys(req: &RequestIds, ctx: &mut RpcContext) -> Result<KeyPair> {\n\n // Authenticate the source enclave based on the MRSIGNER/MRENCLAVE/request\n\n // so that the keys are never released to an incorrect enclave.\n\n if !Policy::u...
Rust
fantoch_ps/src/protocol/common/table/clocks/keys/mod.rs
vitorenesduarte/planet_sim
aea6e324fdce7802976cbafa88a516ed40609ce9
mod sequential; mod atomic; mod locked; pub use atomic::AtomicKeyClocks; pub use locked::LockedKeyClocks; pub use sequential::SequentialKeyClocks; use crate::protocol::common::table::Votes; use fantoch::command::Command; use fantoch::id::{ProcessId, ShardId}; use std::fmt::Debug; pub trait KeyClocks: Debug + Clon...
mod sequential; mod atomic; mod locked; pub use atomic::AtomicKeyClocks; pub use locked::LockedKeyClocks; pub use sequential::SequentialKeyClocks; use crate::protocol::common::table::Votes; use fantoch::command::Command; use fantoch::id::{ProcessId, ShardId}; use std::fmt::Debug; pub trait KeyClocks: Debug + Clon...
fn keys_clocks_flow<KC: KeyClocks>(all_clocks_match: bool) { let process_id = 1; let shard_id = 0; let nfr = false; let mut clocks = KC::new(process_id, shard_id, nfr); let key_a = String::from("A"); let key_b = String::from("B"); ...
fn multi_put(rifl: Rifl, keys: Vec<String>) -> Command { Command::from( rifl, keys.into_iter().map(|key| (key.clone(), KVOp::Put(key))), ) }
function_block-full_function
[ { "content": "pub trait KeyClocks: Debug + Clone {\n\n /// Create a new `KeyClocks` instance.\n\n fn new(process_id: ProcessId, shard_id: ShardId) -> Self;\n\n\n\n // Generate the next clock.\n\n fn clock_next(&mut self) -> Clock;\n\n\n\n // Joins with remote clock.\n\n fn clock_join(&mut self...
Rust
src/main.rs
tanis2000/bone
f3284c290a315c3a4197403af42f62256ea45c31
extern crate clap; #[macro_use] extern crate derive_builder; extern crate handlebars; extern crate serde; #[macro_use] extern crate serde_json; mod cmd; mod utils; use clap::{Arg, App, SubCommand}; use cmd::init::{InitBuilder}; use cmd::update::{UpdateBuilder}; use cmd::upgrade::{UpgradeBuilder}; use cmd::build::{Bui...
extern crate clap; #[macro_use] extern crate derive_builder; extern crate handlebars; extern crate serde; #[macro_use] extern crate serde_json; mod cmd; mod utils; use clap::{Arg, App, SubCommand}; use cmd::init::{InitBuilder}; use cmd::update::{UpdateBuilder}; use cmd::upgrade::{UpgradeBuilder}; use cmd::build::{Bui...
}, Some("upgrade") => { let matches = matches.subcommand_matches("upgrade").unwrap(); let cmd = UpgradeBuilder::default() .app(String::new()) .dir(Some(matches.value_of("dir").unwrap().to_string())) .build(); match cmd { ...
match cmd { Ok(cmd) => { cmd.run(); }, Err(e) => { println!("{}", e); } }
if_condition
[ { "content": "binocle_window *window;\n", "file_path": "templates/binocle-c/src/main.c", "rank": 1, "score": 101733.4392347332 }, { "content": "function update()\n\n log.log(\"update loop\")\n\nend\n\n\n", "file_path": "templates/binocle-c/assets/main.lua", "rank": 2, "score":...
Rust
src/day23/mod.rs
jacobhyphenated/advent2021
891f83fc4ae946e5aa39732d4ee6da5562739afc
/* Day 23: Amphipod Solve a logic puzzle for a group of amphipods. A burrow is a hallway with 4 rooms, and different types of amphipods (A,B,C,D) in each room. Move the amphipods so that all the As are in the first room, Bs in the second, etc. Amphipods never stop in the hallway space immediately outside a room. Amph...
/* Day 23: Amphipod Solve a logic puzzle for a group of amphipods. A burrow is a hallway with 4 rooms, and different types of amphipods (A,B,C,D) in each room. Move the amphipods so that all the As are in the first room, Bs in the second, etc. Amphipods never stop in the hallway space immediately outside a room. Amph...
pub fn part_2_start() -> Burrow { let init = vec![vec![Amphipod::B, Amphipod::D, Amphipod::D, Amphipod::B], vec![Amphipod::A, Amphipod::C, Amphipod::B, Amphipod::C], vec![Amphipod::A, Amphipod::B, Amphipod::A, Amphipod::D], vec![Amphipod::D, Amphipod::A, Amphipod::C, Amphipod::C]]; Bu...
pub fn part_1_start() -> Burrow { let init = vec![vec![Amphipod::B, Amphipod::B], vec![Amphipod::A, Amphipod::C], vec![Amphipod::A, Amphipod::D], vec![Amphipod::D, Amphipod::C]]; Burrow::new(init) }
function_block-full_function
[ { "content": "// Part 1 & Part 2\n\n// Both parts ended up being so similar, that I combined both into one method\n\n// Returns a tuple - first value is part 1, second is part 2\n\n// Keeps a LIFO stack of the next closing character.\n\n// Each time an open character is encountered, the corresponding close char...
Rust
src/rules/no_async_promise_executor.rs
ross-weir/deno_lint
e1b3541ac732ddaaa485d1ad58800b701b1334a7
use super::Context; use super::LintRule; use swc_ecmascript::ast::{Expr, NewExpr, ParenExpr}; use swc_ecmascript::visit::noop_visit_type; use swc_ecmascript::visit::Node; use swc_ecmascript::visit::VisitAll; use swc_ecmascript::visit::VisitAllWith; pub struct NoAsyncPromiseExecutor; const CODE: &str = "no-async-prom...
use super::Context; use super::LintRule; use swc_ecmascript::ast::{Expr, NewExpr, ParenExpr}; use swc_ecmascript::visit::noop_visit_type; use swc_ecmascript::visit::Node; use swc_ecmascript::visit::VisitAll; use swc_ecmascript::visit::VisitAllWith; pub struct NoAsyncPromiseExecutor; const CODE: &str = "no-async-prom...
}
seExecutor, "new Promise(async function(resolve, reject) {});": [{ col: 0, message: MESSAGE, hint: HINT }], "new Promise(async function foo(resolve, reject) {});": [{ col: 0, message: MESSAGE, hint: HINT }], "new Promise(async (resolve, reject) => {});": [{ col: 0, message: MESSAGE, hint: HINT }], ...
function_block-function_prefixed
[ { "content": "pub fn parse(source_code: &str) -> Program {\n\n let ast_parser = ast_parser::AstParser::new();\n\n let syntax = ast_parser::get_default_ts_config();\n\n let (program, _comments) = ast_parser\n\n .parse_program(\"file_name.ts\", syntax, source_code)\n\n .unwrap();\n\n program\n\n}\n", ...
Rust
native/src/lib.rs
undecidedzogvisvitalispotent8stars360/zecwallet-lite
959a7012348f0f331473df72410bb318bc84cf69
#[macro_use] extern crate lazy_static; use neon::prelude::Context; use neon::prelude::FunctionContext; use neon::prelude::JsBoolean; use neon::prelude::JsNumber; use neon::prelude::JsResult; use neon::prelude::JsString; use neon::register_module; use zecwalletlitelib::lightclient::lightclient_config::LightClientConfig...
#[macro_use] extern crate lazy_static; use neon::prelude::Context; use neon::prelude::FunctionContext; use neon::prelude::JsBoolean; use neon::prelude::JsNumber; use neon::prelude::JsResult; use neon::prelude::JsString; use neon::register_module; use zecwalletlitelib::lightclient::lightclient_config::LightClientConfig...
fn litelib_initialize_new_from_phrase(mut cx: FunctionContext) -> JsResult<JsString> { let server_uri = cx.argument::<JsString>(0)?.value(&mut cx); let seed = cx.argument::<JsString>(1)?.value(&mut cx); let birthday = cx.argument::<JsNumber>(2)?.value(&mut cx); let overwrite = cx.argument::<JsBoolean>...
fn litelib_initialize_new(mut cx: FunctionContext) -> JsResult<JsString> { let server_uri = cx.argument::<JsString>(0)?.value(&mut cx); let resp = || { let server = LightClientConfig::get_server_or_default(Some(server_uri)); let (config, latest_block_height) = match LightClientConfig::create(se...
function_block-full_function
[ { "content": "const useTypeScript = fs.existsSync(paths.appTsConfig);\n", "file_path": "config/webpack.config.js", "rank": 7, "score": 70401.8031264443 }, { "content": "const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== \"false\";\n", "file_path": "config/webpack.config.js", ...
Rust
dmbc/src/currency/api/blocks.rs
rude69/blockchain
1f861b13531d4b3931d1cf3d4791366839896950
extern crate serde_json; use exonum::api::Api; use exonum::blockchain::{Blockchain, Block}; use exonum::explorer::{BlockchainExplorer, BlockInfo}; use currency::api::error::ApiError; use exonum::helpers::Height; use hyper::header::ContentType; use iron::headers::AccessControlAllowOrigin; use iron::prelude::*; use iron...
extern crate serde_json; use exonum::api::Api; use exonum::blockchain::{Blockchain, Block}; use exonum::explorer::{BlockchainExplorer, BlockInfo}; use currency::api::error::ApiError; use exonum::helpers::Height; use hyper::header::ContentType; use iron::headers::AccessControlAllowOrigin; use iron::prelude::*; use iron...
INFO_RESPONSES.inc(); Ok(res) }; router.get("/v1/blocks", blocks, "blocks_info"); router.get("/v1/blocks/:height", block, "height"); } }
self.clone(); let block = move |req: &mut Request| -> IronResult<Response> { INFO_REQUESTS.inc(); let params = req.extensions.get::<Router>().unwrap(); let result:Result<Option<BlockInfo>, ApiError> = match params.find("height") { Some(height_str) => { ...
random
[ { "content": "/// Move funds between wallets.\n\n///\n\n/// # Errors\n\n///\n\n/// Returns `InsufficientFunds` if the `from` wallet balance is less than `amount`.\n\npub fn move_coins(from: &mut Wallet, to: &mut Wallet, amount: u64) -> Result<(), Error> {\n\n if from.balance() < amount {\n\n return Er...
Rust
crates/tor-proto/src/circuit/sendme.rs
dgoulet-tor/arti
781dc4bd64f515f0c13ae9907c473c2bad8fbf71
use futures::lock::Mutex; use std::collections::VecDeque; use std::sync::Arc; use tor_cell::relaycell::msg::RelayMsg; use tor_cell::relaycell::RelayCell; use crate::{Error, Result}; pub(crate) type CircTag = [u8; 20]; pub(crate) type NoTag = (); pub(crate) type CircSendWindow = SendWindow<CircParams, CircTag>; ...
use futures::lock::Mutex; use std::collections::VecDeque; use std::sync::Arc; use tor_cell::relaycell::msg::RelayMsg; use tor_cell::relaycell::RelayCell; use crate::{Error, Result}; pub(crate) type CircTag = [u8; 20]; pub(crate) type NoTag = (); pub(crate) type CircSendWindow = SendWindow<CircParams, CircTag>; ...
50 { w.take(&"correct").await?; } assert_eq!(w.w.lock().await.window, 750); let n = w.put(Some("incorrect")).await; assert!(n.is_none()); let n = w.put(Some("correct")).await; assert_eq!(n, Some(850)); let n = w.put(Some("correct")).await; ...
pub(crate) fn put(&mut self) { self.window = self .window .checked_add(P::increment()) .expect("Overflow detected while attempting to increment window"); } } pub(crate) fn msg_counts_towards_windows(msg: &RelayMsg) -> bool { matches!(msg, RelayMsg::Data(_)) } pub(cr...
random
[ { "content": "fn xof_helper<X: ExtendableOutput + digest::Update>(mut x: X, input: &[u8], output: &[u8]) {\n\n use digest::XofReader;\n\n x.update(input);\n\n let mut r = x.finalize_xof();\n\n let mut buf = vec![0; output.len()];\n\n r.read(&mut buf);\n\n assert_eq!(&buf[..], output);\n\n}\n\n...
Rust
src/libstd/rt/test.rs
fabricedesre/rust
1b12dca7f97a51c6cbb4f47ea6e095d841a97c1a
use io::net::ip::{SocketAddr, Ipv4Addr, Ipv6Addr}; use clone::Clone; use container::Container; use iter::{Iterator, range}; use option::{Some, None}; use os; use path::GenericPath; use path::Path; use rand::Rng; use rand; use result::{Result, Ok, Err}; use rt::basic; use rt::comm::oneshot; use rt::deque::BufferPool;...
use io::net::ip::{SocketAddr, Ipv4Addr, Ipv6Addr}; use clone::Clone; use container::Container; use iter::{Iterator, range}; use option::{Some, None}; use os; use path::GenericPath; use path::Path; use rand::Rng; use rand; use result::{Result, Ok, Err}; use rt::basic; use rt::comm::oneshot; use rt::deque::BufferPool;...
pub fn new_test_sched() -> Scheduler { let mut pool = BufferPool::new(); let (worker, stealer) = pool.deque(); let mut sched = Scheduler::new(basic::event_loop(), worker, ~[stealer], SleeperList::new(...
let mut pool = BufferPool::new(); let (worker, stealer) = pool.deque(); let mut sched = Scheduler::new(new_event_loop(), worker, ~[stealer], SleeperList::new()); sched.no_sleep = true; return ...
function_block-function_prefix_line
[ { "content": "pub fn get_rpath_relative_to_output(os: abi::Os,\n\n output: &Path,\n\n lib: &Path)\n\n -> ~str {\n\n use std::os;\n\n\n\n assert!(not_win32(os));\n\n\n\n // Mac doesn't appear to support...
Rust
src/proto/mod.rs
songzhi/memcached-rs
b74419ee3cb86c9af23eb008950f5b5a0e7d6f9d
use std::collections::{BTreeMap, HashMap}; use std::convert::From; use std::error; use std::fmt::{self, Display}; use std::io; use semver::Version; pub use self::binary::BinaryProto; pub mod binary; mod binarydef; #[derive(Copy, Clone)] pub enum ProtoType { Binary, } #[derive(Debug)] pub enum Error { Bin...
use std::collections::{BTreeMap, HashMap}; use std::convert::From; use std::error; use std::fmt::{self, Display}; use std::io; use semver::Version; pub use self::binary::BinaryProto; pub mod binary; mod binarydef; #[derive(Copy, Clone)] pub enum ProtoType { Binary, } #[derive(Debug)] pub enum Error { Bin...
expiration: u32, ) -> MemCachedResult<()>; fn delete_noreply(&mut self, key: &[u8]) -> MemCachedResult<()>; fn replace_noreply( &mut self, key: &[u8], value: &[u8], flags: u32, expiration: u32, ) -> MemCachedResult<()>; fn increment_noreply( &...
u32, u64)>; fn increment_cas( &mut self, key: &[u8], amount: u64, initial: u64, expiration: u32, cas: u64, ) -> MemCachedResult<(u64, u64)>; fn decrement_cas( &mut self, key: &[u8], amount: u64, initial: u64, expiration...
random
[ { "content": "#[derive(Clone)]\n\nstruct ServerRef(Rc<RefCell<Server>>);\n\n\n\nimpl Node for ServerRef {\n\n fn name(&self) -> String {\n\n self.0.borrow().addr.clone()\n\n }\n\n}\n\n\n\nimpl Deref for ServerRef {\n\n type Target = Rc<RefCell<Server>>;\n\n\n\n fn deref(&self) -> &Rc<RefCell<...
Rust
artichoke-backend/src/extn/core/kernel/mod.rs
Elang89/artichoke
179acadc253d94d65c33a1e80430e5c43c8f1a05
use crate::convert::Convert; use crate::def::{ClassLike, Define}; use crate::eval::{Context, Eval}; use crate::extn::core::error::{ArgumentError, LoadError, RubyException, RuntimeError}; use crate::sys; use crate::types::Ruby; use crate::value::{Value, ValueLike}; use crate::{Artichoke, ArtichokeError}; pub mod requir...
use crate::convert::Convert; use crate::def::{ClassLike, Define}; use crate::eval::{Context, Eval}; use crate::extn::core::error::{ArgumentError, LoadError, RubyException, RuntimeError}; use crate::sys; use crate::types::Ruby; use crate::value::{Value, ValueLike}; use crate::{Artichoke, ArtichokeError}; pub mod requir...
catch do |obj_B| throw(obj_B, 123) # puts "This puts is not reached" end # puts "This puts is displayed" 456 end "#, ) .unwrap() .try_into::<i64>() .unwrap(); assert_eq!(result, 456); let result = interp .eval( ...
l_value() } } #[cfg(test)] mod tests { use crate::eval::Eval; use crate::file::File; use crate::load::LoadSources; use crate::value::ValueLike; use crate::{Artichoke, ArtichokeError}; #[test] fn require() { struct TestFile; impl File ...
random
[ { "content": "pub fn method(interp: &Artichoke, args: Args, value: &Value) -> Result<Value, Error> {\n\n let data = unsafe { Regexp::try_from_ruby(interp, value) }.map_err(|_| Error::Fatal)?;\n\n let string = if let Some(string) = args.string {\n\n string\n\n } else {\n\n return Ok(interp...
Rust
src/module/custom.rs
bnjbvr/walrus
18aed0eb76501f2371f509a52ee1a02637fb6a89
use crate::passes::Roots; use crate::tombstone_arena::{Id, Tombstone, TombstoneArena}; use crate::CodeTransform; use crate::IdsToIndices; use std::any::Any; use std::borrow::Cow; use std::fmt::{self, Debug}; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; pub trait CustomSection: WalrusAny + Debug + Sen...
use crate::passes::Roots; use crate::tombstone_arena::{Id, Tombstone, TombstoneArena}; use crate::CodeTransform; use crate::IdsToIndices; use std::any::Any; use std::borrow::Cow; use std::fmt::{self, Debug}; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; pub trait CustomSection: WalrusAny + Debug + Sen...
fn get_mut<T>(&mut self, id: T) -> Option<&mut T::CustomSection> where T: CustomSectionId, { self.arena .get_mut(id.into_inner_id()) .and_then(|s| T::section_mut(&mut **s.as_mut().unwrap())) } pub fn iter(&self) -> impl Iterator<Item = (UntypedCustomSectionI...
Any + Send + Sync) { self.walrus_as_any_mut() } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct RawCustomSection { pub name: String, pub data: Vec<u8>, } impl CustomSection for RawCustomSection { fn name(&self) -> &str { &self.name } fn data(&self, _: &IdsToInd...
random
[ { "content": "/// Like `Drop` but for after an item is marked deleted from a `TombstoneArena`.\n\n///\n\n/// Note that this is *not* setting the item to a tombstone (eg turning an\n\n/// `Option` into a `None`). Instead, this is an opportunity to clean up heap\n\n/// allocations or whatever other resource.\n\n/...
Rust
src/cargo/core/summary.rs
ldm0/cargo
862df617991a327579d1f8ee6b9e861e96fc96a9
use crate::core::{Dependency, PackageId, SourceId}; use crate::util::interning::InternedString; use crate::util::{CargoResult, Config}; use anyhow::bail; use semver::Version; use std::collections::{BTreeMap, HashMap, HashSet}; use std::fmt; use std::hash::{Hash, Hasher}; use std::mem; use std::rc::Rc; #[derive(Debug, ...
use crate::core::{Dependency, PackageId, SourceId}; use crate::util::interning::InternedString; use crate::util::{CargoResult, Config}; use anyhow::bail; use semver::Version; use std::collections::{BTreeMap, HashMap, HashSet}; use std::fmt; use std::hash::{Hash, Hasher}; use std::mem; use std::rc::Rc; #[derive(Debug, ...
#[derive(Clone, Debug)] pub enum FeatureValue { Feature(InternedString), Dep { dep_name: InternedString }, DepFeature { dep_name: InternedString, dep_feature: InternedString, dep_prefix: bool, }, } impl FeatureValue { pub fn new(feature: In...
pkg_id: PackageId, features: &BTreeMap<InternedString, Vec<InternedString>>, dependencies: &[Dependency], ) -> CargoResult<(FeatureMap, bool)> { use self::FeatureValue::*; let mut dep_map = HashMap::new(); for dep in dependencies.iter() { dep_map .entry(dep.name_in_toml()) ...
function_block-function_prefix_line
[ { "content": "/// This is a little complicated.\n\n/// This should return false if:\n\n/// - this is an artifact of the rustc distribution process for \"stable\" or for \"beta\"\n\n/// - this is an `#[test]` that does not opt in with `enable_nightly_features`\n\n/// - this is a integration test that uses `Proce...
Rust
api/src/v1/manage/content.rs
SciStarter/Circuit
da468ef31a4af3942bca1e5e658dcf40104aea89
use askama::Template; use common::model::{block::Block, person::Permission}; use common::Database; use http_types::Method; use serde::Deserialize; use tide_fluent_routes::{ routebuilder::{RouteBuilder, RouteBuilderExt}, RouteSegment, }; use crate::v1::redirect; use super::authorized_admin; pub fn routes(rout...
use askama::Template; use common::model::{block::Block, person::Permission}; use common::Database; use http_types::Method; use serde::Deserialize; use tide_fluent_routes::{ routebuilder::{RouteBuilder, RouteBuilderExt}, RouteSegment, }; use crate::v1::redirect; use super::authorized_admin; pub fn routes(rout...
}, } }; if let Method::Post = req.method() { let form: ContentItemForm = req.body_form().await?; let db = req.state(); block.tags = form.tags.trim().to_string(); block.label = form.label.trim().to_string(); block.content = form.content.trim().to_string(...
guage(mut req: tide::Request<Database>) -> tide::Result { let _admin = match authorized_admin(&req, &Permission::ManageContent).await { Ok(person) => person, Err(resp) => return Ok(resp), }; if let Method::Post = req.method() { let form: ContentLanguageForm = req.body_form().await?;...
random
[ { "content": "pub fn random_string() -> String {\n\n thread_rng()\n\n .sample_iter(&Alphanumeric)\n\n .take(32)\n\n .map(char::from)\n\n .collect()\n\n}\n\n\n", "file_path": "backend/src/v1/mod.rs", "rank": 0, "score": 229609.57037357212 }, { "content": "/// Ge...
Rust
octree_web_viewer/src/backend.rs
ksavinash9/point_cloud_viewer
25d70ec937eb058b6833054e3c340c40c4422a99
use byteorder::{LittleEndian, WriteBytesExt}; use cgmath::Matrix4; use iron::mime::Mime; use iron::prelude::*; use iron; use point_viewer::octree::{self, Octree}; use std::io::Read; use std::sync::{Arc, RwLock}; use json; use time; use urlencoded::UrlEncodedQuery; pub struct VisibleNodes { octree: Arc<RwLock<octre...
use byteorder::{LittleEndian, WriteBytesExt}; use cgmath::Matrix4; use iron::mime::Mime; use iron::prelude::*; use iron; use point_viewer::octree::{self, Octree}; use std::io::Read; use std::sync::{Arc, RwLock}; use json; use time; use urlencoded::UrlEncodedQuery; pub struct VisibleNodes { octree: Arc<RwLock<octre...
} fn pad(input: &mut Vec<u8>) { let pad = input.len() % 4; if pad == 0 { return; } for _ in 0..(4 - pad) { input.push(0); } } pub struct NodesData { octree: Arc<RwLock<octree::OnDiskOctree>>, } impl NodesData { pub fn new(octree: Arc<RwLock<octree::OnDiskOctree>>) -> Self...
reply.push_str(&visible_nodes_string); reply.push(']'); let content_type = "application/json".parse::<Mime>().unwrap(); Ok(Response::with((content_type, iron::status::Ok, reply))) }
function_block-function_prefix_line
[ { "content": "pub fn build_octree(output_directory: impl AsRef<Path>, resolution: f64, bounding_box: Aabb3<f32>, input: impl InternalIterator) {\n\n // TODO(ksavinash9): This function should return a Result.\n\n let octree_meta = &octree::OctreeMeta {\n\n bounding_box,\n\n resolution,\n\n ...
Rust
src/python_interpreter/config.rs
PyO3/pyo3-pack
9d197c49830bd721075b12c85c3981a6754273d5
use super::InterpreterKind; use crate::target::{Arch, Os}; use crate::Target; use anyhow::{format_err, Context, Result}; use fs_err as fs; use once_cell::sync::Lazy; use serde::Deserialize; use std::collections::HashMap; use std::io::{BufRead, BufReader}; use std::path::Path; static WELLKNOWN_SYSCONFIG: Lazy<HashMap<O...
use super::InterpreterKind; use crate::target::{Arch, Os}; use crate::Target; use anyhow::{format_err, Context, Result}; use fs_err as fs; use once_cell::sync::Lazy; use serde::Deserialize; use std::collections::HashMap; use std::io::{BufRead, BufReader}; use std::path::Path; static WELLKNOWN_SYSCONFIG: Lazy<HashMap<O...
ines.enumerate() { let line = line.context("failed to read line from config")?; let (key, value) = line .split_once('=') .with_context(|| format!("expected key=value pair on line {}", i + 1))?; match key { "implementation" => parse_valu...
.expect("invalid sysconfig-openbsd.json"); sysconfig.insert(Os::OpenBsd, sysconfig_openbsd); let sysconfig_netbsd = serde_json::from_slice(include_bytes!("sysconfig-netbsd.json")) .expect("invalid sysconfig-netbsd.json"); sysconfig.insert(Os::NetBsd, sysconfig_netbsd); ...
random
[ { "content": "/// If any, copies the data files from the data directory, resolving symlinks to their source.\n\n/// We resolve symlinks since we require this rather rigid structure while people might need\n\n/// to save or generate the data in other places\n\n///\n\n/// See https://peps.python.org/pep-0427/#fil...
Rust
radiate_matrix_tree/src/matrix_tree/evenv.rs
rkarp/radiate
fb2b4f1f349a5def6de2a6dfb55aa1e7d33b6bdb
extern crate radiate; use radiate::engine::environment::Envionment; #[derive(Debug, Clone, PartialEq)] pub struct TreeEnvionment { pub input_size: Option<i32>, pub outputs: Option<Vec<i32>>, pub start_height: Option<i32>, pub max_height: Option<i32>, pub network_mutation_rate: Option<f32>, p...
extern crate radiate; use radiate::engine::environment::Envionment; #[derive(Debug, Clone, PartialEq)] pub struct TreeEnvionment { pub input_size: Option<i32>, pub outputs: Option<Vec<i32>>, pub start_height: Option<i32>, pub max_height: Option<i32>, pub network_mutation_rate: Option<f32>, p...
#[allow(dead_code)] pub fn set_input_size(mut self, size: i32) -> Self { self.input_size = Some(size); self } #[allow(dead_code)] pub fn get_input_size(&self) -> i32 { self.input_size.unwrap_or_else(|| panic!("Input size not set")) } #[allow(dead_code)] pu...
ate: None, gut_rate: None, shuffle_rate: None, layer_mutate_rate: None, weight_mutate_rate: None, weight_transform_rate: None } }
function_block-function_prefixed
[ { "content": "/// Default environment for the NEAT algorithm as described in the paper.\n\n///\n\n/// These are very basic and are used to solve the xor problem for NEAT.\n\npub fn default_neat_env() -> NeatEnvironment {\n\n NeatEnvironment::new()\n\n .set_input_size(3)\n\n .set_output_size(1)\...
Rust
src/futures/model.rs
evopen/binance-rs
65ac54d633d07b12927017efadc51de5714e532e
use serde::{Deserialize, Serialize}; use crate::model::{string_or_float, string_or_float_opt, string_or_bool}; pub use crate::model::{ Asks, Bids, BookTickers, Filters, KlineSummaries, KlineSummary, RateLimit, ServerTime, SymbolPrice, Tickers, }; #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_...
use serde::{Deserialize, Serialize}; use crate::model::{string_or_float, string_or_float_opt, string_or_bool}; pub use crate::model::{ Asks, Bids, BookTickers, Filters, KlineSummaries, KlineSummary, RateLimit, ServerTime, SymbolPrice, Tickers, }; #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_...
ub symbol: String, #[serde(with = "string_or_float", rename = "unRealizedProfit")] pub unrealized_profit: f64, pub position_side: String, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct AccountBalance { pub account_alias: String, pub asset: String, ...
pub orig_qty: f64, #[serde(with = "string_or_float")] pub price: f64, pub side: String, pub reduce_only: bool, pub position_side: String, pub status: String, #[serde(with = "string_or_float", default = "default_stop_price")] pub stop_price: f64, pub close_position: bool, pub symb...
random
[ { "content": "pub fn build_signed_request_custom(mut parameters: BTreeMap<String, String>, recv_window: u64, start: SystemTime,\n\n) -> Result<String> {\n\n if recv_window > 0 {\n\n parameters.insert(\"recvWindow\".into(), recv_window.to_string());\n\n }\n\n if let Ok(timestamp) = get_timestamp(...
Rust
client/src/main.rs
mmihira/rchat
72c5757df322ca7fba68990617da9078d6f37ee5
extern crate names; extern crate msg_protocol; extern crate regex; extern crate serde_json; extern crate tui; extern crate termion; extern crate clap; mod read_worker; mod app_ui; use app_ui::AppMsg; use std::net::TcpStream; use std::io; use std::io::Write; use std::{thread}; use std::sync::mpsc::channel; use tui::T...
extern crate names; extern crate msg_protocol; extern crate regex; extern crate serde_json; extern crate tui; extern crate termion; extern crate clap; mod read_worker; mod app_ui; use app_ui::AppMsg; use std::net::TcpStream; use std::io; use std::io::Write; use std::{thread}; use std::sync::mpsc::channel; use tui::T...
fn draw_ui(mut terminal: &mut tui::Terminal<RawBackend>, app_ui: &app_ui::AppUi) { let size = terminal.size().unwrap(); Group::default() .direction(Direction::Vertical) .margin(1) .sizes(&[Size::Percent(80), Size::Percent(20)]) .render(&mut terminal, &size, |t, chunks| { ...
function_block-full_function
[ { "content": "fn main() {\n\n pretty_env_logger::init();\n\n\n\n let console_args = App::new(\"Chat server\")\n\n .about(\"Chat server\")\n\n .arg(Arg::with_name(\"host\")\n\n .short(\"h\")\n\n .help(\"Server address\")\n\n .takes_value(true))\n\n .get...
Rust
src/settings/toml/migrations.rs
seohot/wrangler
6134fe49afbc91d157284861bb15872668a52ef8
use std::collections::HashSet; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum MigrationTag { HasTag(String), NoTag, NoScript, Unknown, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum Migrations { Adhoc { ...
use std::collections::HashSet; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum MigrationTag { HasTag(String), NoTag, NoScript, Unknown, } #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] pub enum Migrations { Adhoc { ...
let api_migration = migrations.api_migration()?; assert_eq!( api_migration, Some(ApiMigration { old_tag: None, new_tag: Some(String::from("v1")), steps: vec![Migration { durable_objects: DurableObjectsMigration...
let migrations = Migrations::List { script_tag: MigrationTag::NoScript, migrations: vec![MigrationConfig { tag: String::from("v1"), migration: Migration { durable_objects: DurableObjectsMigration { new_classes: vec![Stri...
assignment_statement
[ { "content": "pub fn list(client: &impl ApiClient, target: &Target) -> Result<Vec<WorkersKvNamespace>> {\n\n let mut namespaces: Vec<WorkersKvNamespace> = Vec::new();\n\n let mut all_namespaces_added = false;\n\n let mut page_number = 1;\n\n while !all_namespaces_added {\n\n let params = List...
Rust
crates/reward/src/tests.rs
Polkadex-Substrate/interbtc
0ce5f7bab9e7b5b15a35c1df7282bb983055deb4
use crate::mock::*; use frame_support::{assert_err, assert_ok}; use rand::Rng; macro_rules! fixed { ($amount:expr) => { sp_arithmetic::FixedI128::from($amount) }; } #[test] fn should_distribute_rewards_equally() { run_test(|| { assert_ok!(Reward::deposit_stake(&ALICE, fixed!(50))); ...
use crate::mock::*; use frame_support::{assert_err, assert_ok}; use rand::Rng; macro_rules! fixed { ($amount:expr) => { sp_arithmetic::FixedI128::from($amount) }; } #[test] fn should_distribute_rewards_equally() { run_test(|| { assert_ok!(Reward::deposit_stake(&ALICE, fixed!(50))); ...
ard(INTERBTC, &ALICE).unwrap(); assert_ok!(Reward::withdraw_reward(INTERBTC, &ALICE), alice_reward); let bob_reward = Reward::compute_reward(INTERBTC, &BOB).unwrap(); assert_ok!(Reward::withdraw_reward(INTERBTC, &BOB), bob_reward); }) }
assert_ok!(Reward::distribute_reward(INTERBTC, fixed!(rng.gen::<u32>() as i128))); } let alice_reward = Reward::compute_rew
function_block-random_span
[ { "content": "pub fn run_test<T>(test: T)\n\nwhere\n\n T: FnOnce(),\n\n{\n\n ExtBuilder::build().execute_with(|| {\n\n System::set_block_number(1);\n\n test();\n\n });\n\n}\n", "file_path": "crates/staking/src/mock.rs", "rank": 0, "score": 183069.40321777016 }, { "cont...
Rust
leaf/src/proxy/tun/netstack/tcp_stream_impl.rs
GL-Wen/leaf
23dc682e34803f0c148a3f47e46c4bdb709827c4
use std::{cmp::min, io, net::SocketAddr, os::raw, pin::Pin, sync::Arc}; use anyhow::Result; use bytes::BytesMut; use futures::task::{Context, Poll}; use log::*; use tokio::{ io::{AsyncRead, AsyncWrite, ReadBuf}, sync::mpsc::unbounded_channel, }; use crate::common::mutex::AtomicMutex; use super::lwip::*; use ...
use std::{cmp::min, io, net::SocketAddr, os::raw, pin::Pin, sync::Arc}; use anyhow::Result; use bytes::BytesMut; use futures::task::{Context, Poll}; use log::*; use tokio::{ io::{AsyncRead, AsyncWrite, ReadBuf}, sync::mpsc::unbounded_channel, }; use crate::common::mutex::AtomicMutex; use super::lwip::*; use ...
Poll::Pending } else { Poll::Ready(Err(io::Error::new( io::ErrorKind::Interrupted, format!("netstack tcp_write error {}", err), ))) } } fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<io::Result<()>> { l...
if write_waker .as_ref() .map(|w| !w.will_wake(cx.waker())) .unwrap_or(true) { write_waker.replace(cx.waker().clone()); }
if_condition
[ { "content": "fn broken_pipe() -> io::Error {\n\n io::Error::new(io::ErrorKind::Interrupted, \"broken pipe\")\n\n}\n\n\n", "file_path": "leaf/src/proxy/ws/stream.rs", "rank": 1, "score": 333651.63240076345 }, { "content": "pub fn crypto_err() -> io::Error {\n\n io::Error::new(io::Error...
Rust
core/bin/zksync_event_listener/src/subscriber/filters/account.rs
smishraIOV/ri-aggregation
abcd90954335b6ee8513876de0118f567d979a32
use std::collections::HashSet; use serde::Deserialize; use zksync_types::{ event::{account::*, EventData, ZkSyncEvent}, AccountId, TokenId, }; #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct AccountFilter { pub accounts: Option<HashSet<AccountId>>, pub tokens: Option<Ha...
use std::collections::HashSet; use serde::Deserialize; use zksync_types::{ event::{account::*, EventData, ZkSyncEvent}, AccountId, TokenId, }; #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct AccountFilter { pub accounts: Option<HashSet<AccountId>>, pub tokens: Option<Ha...
} #[cfg(test)] mod tests { use super::*; use zksync_types::event::test_data::get_account_event; #[test] fn test_account_filter() { let mut account_filter = AccountFilter { accounts: None, tokens: None, status: None, }; let event = ...
vent: &ZkSyncEvent) -> bool { let account_event = match &event.data { EventData::Account(account_event) => account_event, _ => return false, }; if let Some(status) = &self.status { if account_event.status != *status { return false; ...
function_block-function_prefixed
[ { "content": "pub fn empty_account_as_field_elements<E: Engine>() -> Vec<E::Fr> {\n\n let acc = CircuitAccount::<Bn256>::default();\n\n let bits = acc.get_bits_le();\n\n\n\n use crate::franklin_crypto::circuit::multipack;\n\n\n\n multipack::compute_multipacking::<E>(&bits)\n\n}\n\n\n\n/// Representa...
Rust
noodles-bam/src/record/cigar.rs
natir/noodles
1ab5e60693ede58d800f247cd8ea3f561210e38e
pub mod op; mod ops; pub use self::{op::Op, ops::Ops}; use std::{fmt, io}; use noodles_sam::{self as sam, record::cigar::op::Kind}; #[derive(Clone, Default, Eq, PartialEq)] pub struct Cigar(Vec<u32>); impl Cigar { #[deprecated(since = "0.8.0", note = "Use `Ci...
pub mod op; mod ops; pub use self::{op::Op, ops::Ops}; use std::{fmt, io}; use noodles_sam::{self as sam, record::cigar::op::Kind}; #[derive(Clone, Default, Eq, PartialEq)] pub struct Cigar(Vec<u32>); impl Cigar { #[deprecated(since = "0.8.0", note = "Use `Ci...
}
let cigar = Cigar::from(vec![0x00000240, 0x00000084]); let actual = sam::record::Cigar::try_from(&cigar)?; let expected = sam::record::Cigar::from(vec![Op::new(Kind::Match, 36), Op::new(Kind::SoftClip, 8)]); assert_eq!(actual, expected); Ok(()) }
function_block-function_prefix_line
[ { "content": "fn read_cigar<B>(buf: &mut B, cigar: &mut Cigar, n_cigar_op: usize) -> io::Result<()>\n\nwhere\n\n B: Buf,\n\n{\n\n if buf.remaining() < mem::size_of::<u32>() * n_cigar_op {\n\n return Err(io::Error::from(io::ErrorKind::InvalidData));\n\n }\n\n\n\n let cigar = cigar.as_mut();\n\...
Rust
src/shells/elvish.rs
spacekookie/clap_generate
2785989c129c0d1a612453fae679d125f07fbbd7
use std::io::Write; use clap::App; use INTERNAL_ERROR_MSG; pub struct ElvishGen<'a, 'b, 'c> where 'a: 'b, 'b: 'c, { app: &'c App<'a, 'b>, } impl<'a, 'b, 'c> ElvishGen<'a, 'b, 'c> { pub fn new(p: &'c App<'a, 'b>) -> Self { ElvishGen { app: p } } pub fn generate_to<W: Write>(&self, buf: &mut W) {...
use std::io::Write; use clap::App; use INTERNAL_ERROR_MSG; pub struct ElvishGen<'a, 'b, 'c> where 'a: 'b, 'b: 'c, { app: &'c App<'a, 'b>, } impl<'a, 'b, 'c> ElvishGen<'a, 'b, 'c> { pub fn new(p: &'c App<'a, 'b>) -> Self { ElvishGen { app: p } } pub fn generate_to<W: Write>(&self, buf: &mut W) {...
} for subcommand in &p.subcommands { let data = &subcommand.name; let tooltip = get_tooltip(subcommand.about, data); completions.push_str(&preamble); completions.push_str(format!("{} '{}'", data, tooltip).as_str()); } let mut subcommands_cases = format!( r" ...
if let Some(data) = flag.long { let tooltip = get_tooltip(flag.help, data); completions.push_str(&preamble); completions.push_str(format!("--{} '{}'", data, tooltip).as_str()); }
if_condition
[ { "content": "// Gets all subcommands including child subcommands in the form of 'name' where the name\n\n// is a single word (i.e. \"install\") of the path to said subcommand (i.e.\n\n// \"rustup toolchain install\")\n\n//\n\n// Also note, aliases are treated as their own subcommands but duplicates of whateve...
Rust
src/std_api.rs
virt-do/unshare
7b0a2e8d906bcdb2efa62d3ce9580dc359b731fd
use std::collections::HashMap; use std::collections::HashSet; use std::default::Default; use std::env; use std::ffi::OsStr; use std::path::Path; use crate::ffi_util::ToCString; use crate::{Command, Fd, Stdio}; use libc::{gid_t, uid_t}; impl Command { pub fn new<...
use std::collections::HashMap; use std::collections::HashSet; use std::default::Default; use std::env; use std::ffi::OsStr; use std::path::Path; use crate::ffi_util::ToCString; use crate::{Command, Fd, Stdio}; use libc::{gid_t, uid_t}; impl Command { pub fn new<...
pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command { self.init_env_map(); self.environ.as_mut().unwrap().remove(key.as_ref()); self.pid_env_vars.remove(key.as_ref()); self } pub fn env_clear(&mut self) -> &mut Command { self.environ = S...
pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command where I: IntoIterator<Item = (K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>, { for (ref key, ref val) in vars { self.init_env_map(); self.environ .as_mut() .unwrap() ...
function_block-full_function
[ { "content": "pub fn dup_file_cloexec<F: AsRawFd>(file: &F) -> io::Result<Closing> {\n\n match fcntl(file.as_raw_fd(), FcntlArg::F_DUPFD_CLOEXEC(3)) {\n\n Ok(fd) => Ok(Closing::new(fd)),\n\n Err(nix::Error::Sys(errno)) => {\n\n return Err(io::Error::from_raw_os_error(errno as i32));\...
Rust
crates/turron-config/src/lib.rs
zkat/ruget
074704a08252001656a8b2328067eaf698e757be
use std::collections::HashMap; use std::fs; use std::path::PathBuf; pub use clap::ArgMatches; pub use config::Config as TurronConfig; pub use config::Value as ConfigValue; use config::{ConfigError, Environment, Source}; use kdl::{KdlNode, KdlValue}; use turron_common::miette::{self, Diagnostic, Result}; use turron_com...
use std::collections::HashMap; use std::fs; use std::path::PathBuf; pub use clap::ArgMatches; pub use config::Config as TurronConfig; pub use config::Value as ConfigValue; use config::{ConfigError, Environment, Source}; use kdl::{KdlNode, KdlValue}; use turron_common::miette::{self, Diagnostic, Result}; use turron_com...
hildren { table.insert(child.name.clone(), KdlDocument::node_value(child)); } table } } impl Source for KdlDocument { fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> { Box::new(self.clone()) } fn collect(&self) -> Result<HashMap<String, ConfigValue>, Confi...
} pub fn global(mut self, global: bool) -> Self { self.global = global; self } pub fn env(mut self, env: bool) -> Self { self.env = env; self } pub fn pkg_root(mut self, root: Option<PathBuf>) -> Self { self.pkg_root = root; self } pub fn g...
random
[ { "content": "pub fn parse_package_spec<I>(input: I) -> Result<PackageSpec, PackageSpecError>\n\nwhere\n\n I: AsRef<str>,\n\n{\n\n let input = input.as_ref();\n\n match all_consuming(package::package_spec)(input) {\n\n Ok((_, arg)) => Ok(arg),\n\n Err(err) => Err(match err {\n\n ...