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
bsa/src/lib.rs
chisui/elderscrolls-rust
896728d2b5eca20acf9609302ff8d466cb2a4347
#![allow(incomplete_features)] #![feature(associated_type_defaults, wrapping_int_impl, specialization)] #[macro_use] mod bin; mod compress; mod str; pub mod read; pub mod write; mod hash; pub mod version; pub mod v001; mod v10x; pub mod v103; pub mod v104; pub mod v105; use std::io::{self, Read, Seek, Write}; use bin:...
#![allow(incomplete_features)] #![feature(associated_type_defaults, wrapping_int_impl, specialization)] #[macro_use] mod bin; mod compress; mod str; pub mod read; pub mod write; mod hash; pub mod version; pub mod v001; mod v10x; pub mod v103; pub mod v104; pub mod v105; use std::io::{self, Read, Seek, Write}; use bin:...
ader()), ForSomeVersion10X::V105(bsa) => ForSomeVersion10X::V105(bsa.header()), } } fn list(&mut self) -> io::Result<Vec<read::Dir>> { match self { ForSomeVersion10X::V103(bsa) => bsa.list(), ForSomeVersion10X::V104(bsa) => bsa.list(), ForSomeVers...
::V001), ForSomeVersion::V10X(bsa) => bsa.list().map(SomeRoot::V10X), } } fn extract<W: Write>(&mut self, file: &read::File, writer: W) -> io::Result<()> { match self { ForSomeVersion::V001(bsa) => bsa.extract(file, writer), ForSomeVersion::V10X(bsa) => bsa.e...
random
[ { "content": "/// default implementation for read_fixed using Fixed and read_struct.\n\npub fn read_fixed_default<A: Fixed + Pod, R: Read + Seek>(mut reader: R) -> Result<A> {\n\n A::move_to_start(&mut reader)?;\n\n read_struct(reader)\n\n}\n\nmacro_rules! derive_readable_fixed_via_default {\n\n ( $t:t...
Rust
src/nonce.rs
k-cleary/git-rsl
e5012abb3c4db8249efda54f896fb896e8976312
use std::fmt; use std::fs::OpenOptions; use std::hash::{Hash, Hasher}; use std::io::{Read, Write}; use git2::Repository; use rand::os::OsRng; use rand::{Rand, Rng}; use serde_json; use errors::*; #[derive(Eq, PartialEq, Debug, Copy, Clone, Serialize, Deserialize)] pub struct Nonce { bytes: [u8; 32], } impl Non...
use std::fmt; use std::fs::OpenOptions; use std::hash::{Hash, Hasher}; use std::io::{Read, Write}; use git2::Repository; use rand::os::OsRng; use rand::{Rand, Rng}; use serde_json; use errors::*; #[derive(Eq, PartialEq, Debug, Copy, Clone, Serialize, Deserialize)] pub struct Nonce { bytes: [u8; 32], } impl Non...
rde_json::to_string(self).unwrap(); write!(f, "{}", text) } } pub trait HasNonce { fn read_nonce(&self) -> Result<Nonce>; fn write_nonce(&self, nonce: &Nonce) -> Result<()>; } impl HasNonce for Repository { fn read_nonce(&self) -> Result<Nonce> { let mut buffer = String::new(); ...
Nonce { bytes } } pub fn try_from_str(string: &str) -> Result<Nonce> { let result = serde_json::from_str(string).chain_err(|| "couldn't parse nonce from string")?; Ok(result) } pub fn to_string(&self) -> Result<String> { let string = serde_json::to_string(self).chain_err(|| "u...
random
[ { "content": "/// Deserializes a lowercase hex string to a `Vec<u8>`.\n\npub fn hex_to_buffer<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n use serde::de::Error;\n\n String::deserialize(deserializer)\n\n .and_then(|string| Vec::from_hex(&string...
Rust
cargo/vendor/time-macros-0.2.4/src/date.rs
btwiuse/invctrl
b3b47ad75510bd48bb235f1813cc6eb391579a00
use std::iter::Peekable; use proc_macro::{token_stream, TokenTree}; use crate::helpers::{ consume_any_ident, consume_number, consume_punct, days_in_year, days_in_year_month, weeks_in_year, ymd_to_yo, ywd_to_yo, }; use crate::to_tokens::ToTokenTree; use crate::Error; #[cfg(feature = "large-dates")] const MAX_...
use std::iter::Peekable; use proc_macro::{token_stream, TokenTree}; use crate::helpers::{ consume_any_ident, consume_number, consume_punct, days_in_year, days_in_year_month, weeks_in_year, ymd_to_yo, ywd_to_yo, }; use crate::to_tokens::ToTokenTree; use crate::Error; #[cfg(feature = "large-dates")] const MAX_...
; } let (year, ordinal) = ywd_to_yo(year, week, day); return Ok(Date { year, ordinal }); } let (month_or_ordinal_span, month_or_ordinal) = consume_number::<u16>("month or ordinal", chars)?; #[allow(clippy::branches_sharing_code)] if consume_punct('-', chars...
Err(Error::InvalidComponent { name: "day", value: day.to_string(), span_start: Some(day_span), span_end: Some(day_span), })
call_expression
[ { "content": "#[derive(Message)]\n\n#[rtype(result = \"()\")]\n\nstruct WsMessage(ws::Message);\n\n\n\nimpl Handler<WsMessage> for Terminal {\n\n type Result = ();\n\n fn handle(&mut self, msg: WsMessage, ctx: &mut Self::Context) {\n\n self.receive_from_client(msg.0, ctx);\n\n }\n\n}\n\n\n", ...
Rust
src/report/repo_info.rs
foresterre/optopodi
8ba91fe1613013391905b64c0b5620261b636343
use fehler::throws; use log::debug; use serde::Deserialize; use stable_eyre::eyre::{Error, WrapErr}; use std::{collections::HashMap, path::Path}; use crate::{metrics, util::percentage}; use super::{issue_closure::IssueClosure, repo_participant::RepoParticipant, Report, ReportConfig}; #[derive(Clone, Debug, Deseriali...
use fehler::throws; use log::debug; use serde::Deserialize; use stable_eyre::eyre::{Error, WrapErr}; use std::{collections::HashMap, path::Path}; use crate::{metrics, util::percentage}; use super::{issue_closure::IssueClosure, repo_participant::RepoParticipant, Report, ReportConfig}; #[derive(Clone, Debug, Deseriali...
pub(super) fn get(&self, repo: &str) -> &RepoInfo { &self.repos[repo] } } impl RepoInfo { pub(super) fn is_high_contributor( &self, config: &ReportConfig, participant: &RepoParticipant, ) -> bool { let hc = &config.high_contributor; let participated_in...
fn parse_repo_infos(repo_infos: &Path) -> RepoInfos { let mut rdr = csv::Reader::from_path(repo_infos) .wrap_err_with(|| format!("Failed to create reader from path: {:?}", &repo_infos))?; let mut map = HashMap::new(); for result in rdr.deserialize() { let record: RepoInfo...
function_block-full_function
[ { "content": "#[derive(Debug, Deserialize)]\n\nstruct ReportConfig {\n\n github: GithubConfig,\n\n high_contributor: HighContributorConfig,\n\n data_source: DataSourceConfig,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ReportData {\n\n repo_participants: repo_participant::RepoParticipants,\n\n rep...
Rust
tests/test.rs
aki-akaguma/aki-xcat
9d5f7e52b6d4e7563781f75ac9787c32b8003672
const TARGET_EXE_PATH: &'static str = env!(concat!("CARGO_BIN_EXE_", env!("CARGO_PKG_NAME"))); macro_rules! help_msg { () => { concat!( version_msg!(), "\n", indoc::indoc!( r#" Usage: aki-xcat [options] [<file>...] t...
const TARGET_EXE_PATH: &'static str = env!(concat!("CARGO_BIN_EXE_", env!("CARGO_PKG_NAME"))); macro_rules! help_msg { () => { concat!( version_msg!(), "\n", indoc::indoc!( r#" Usage: aki-xcat [options] [<file>...] t...
#[cfg(feature = "xz2")] #[cfg(feature = "zstd")] #[cfg(feature = "lz4")] #[test] fn test_plain_gz_xz_zst_lz4_num() { let oup = exec_target( TARGET_EXE_PATH, &[ "-n", fixture_plain!(), fixture_gz!(), ...
ain_gz_xz_zst_lz4() { let oup = exec_target( TARGET_EXE_PATH, &[ fixture_plain!(), fixture_gz!(), fixture_xz!(), fixture_zstd!(), fixture_lz4!(), ], ); assert_eq!(oup.stderr, ""); ...
function_block-function_prefixed
[ { "content": "fn do_cat_proc_file<F>(path_s: &str, line_num: usize, f: &mut F) -> anyhow::Result<usize>\n\nwhere\n\n F: FnMut(&mut dyn BufRead, &str, usize) -> anyhow::Result<usize>,\n\n{\n\n let mut file = File::open(path_s).with_context(|| format!(\"can not open file: {path_s}\"))?;\n\n //\n\n let...
Rust
src/lib.rs
expenses/zshp
0f2094c83c6c01b8eb81ba523883bf194af66c8c
extern crate byteorder; use byteorder::{ByteOrder, BigEndian, LittleEndian}; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::default::Default; #[derive(Debug)] pub struct ShpFile { pub header: ShpHeader, pub records: Vec<ShpRecord>, } #[derive(Debug)] pub struct ShpHead...
extern crate byteorder; use byteorder::{ByteOrder, BigEndian, LittleEndian}; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::default::Default; #[derive(Debug)] pub struct ShpFile { pub header: ShpHeader, pub records: Vec<ShpRecord>, } #[derive(Debug)] pub struct ShpHead...
} #[derive(Debug)] pub struct MultiPointShape { pub xmin: f64, pub xmax: f64, pub ymin: f64, pub ymax: f64, pub num_points: i32, pub points: Vec<PointShape>, } impl MultiPointShape { pub fn parse(content: &[u8]) -> MultiPointShape { let xmin = LittleEndian::read_f64(&content[0..8]);...
pub fn parse(content: &[u8]) -> PointShape { PointShape { x: LittleEndian::read_f64(&content[0..8]), y: LittleEndian::read_f64(&content[8..16]), } }
function_block-full_function
[]
Rust
src/raw/array_buf.rs
abr-egn/bson-rust
17dc6328875281791feff7c54caea15767d95b22
use std::{ borrow::{Borrow, Cow}, fmt::Debug, iter::FromIterator, }; use serde::{Deserialize, Serialize}; use crate::{RawArray, RawBsonRef, RawDocumentBuf}; use super::{bson::RawBson, serde::OwnedOrBorrowedRawArray, RawArrayIter}; #[derive(Clone, PartialEq)] pub struct RawArrayBuf { inner: RawDocume...
use std::{ borrow::{Borrow, Cow}, fmt::Debug, iter::FromIterator, }; use serde::{Deserialize, Serialize}; use crate::{RawArray, RawBsonRef, RawDocumentBuf}; use super::{bson::RawBson, serde::OwnedOrBorrowedRawArray, RawA
a, RawArray> { fn from(rd: &'a RawArrayBuf) -> Self { Cow::Borrowed(rd.as_ref()) } } impl<T: Into<RawBson>> FromIterator<T> for RawArrayBuf { fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { let mut array_buf = RawArrayBuf::new(); for item in iter { array_buf.p...
rrayIter}; #[derive(Clone, PartialEq)] pub struct RawArrayBuf { inner: RawDocumentBuf, len: usize, } impl RawArrayBuf { pub fn new() -> RawArrayBuf { Self { inner: RawDocumentBuf::new(), len: 0, } } pub(crate) fn from_raw_document_buf(do...
random
[ { "content": "#[derive(Debug, Deserialize)]\n\nstruct CowStr<'a>(#[serde(borrow)] Cow<'a, str>);\n\n\n\n/// Wrapper type that can deserialize either an owned or a borrowed raw BSON document.\n\n#[derive(Debug)]\n\npub(crate) enum OwnedOrBorrowedRawDocument<'a> {\n\n Owned(RawDocumentBuf),\n\n Borrowed(&'a...
Rust
graphene/src/auto/vec2.rs
euclio/gtk-rs-core
dc58ff16f0342c1f3273ea2d8c2d5279c047339a
use glib::translate::*; glib::wrapper! { #[derive(Debug)] pub struct Vec2(BoxedInline<ffi::graphene_vec2_t>); match fn { copy => |ptr| glib::gobject_ffi::g_boxed_copy(ffi::graphene_vec2_get_type(), ptr as *mut _) as *mut ffi::graphene_vec2_t, free => |ptr| glib::gobject_ffi::g_boxed_free...
use glib::translate::*; glib::wrapper! { #[derive(Debug)] pub struct Vec2(BoxedInline<ffi::graphene_vec2_t>); match fn { copy => |ptr| glib::gobject_ffi::g_boxed_copy(ffi::graphene_vec2_get_type(), ptr as *mut _) as *mut ffi::graphene_vec2_t, free => |ptr| glib::gobject_ffi::g_boxed_free...
2_one()) } } #[doc(alias = "graphene_vec2_x_axis")] pub fn x_axis() -> Vec2 { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::graphene_vec2_x_axis()) } } #[doc(alias = "graphene_vec2_y_axis")] pub fn y_axis() -> Vec2 { assert_initialized_main_thread!(); ...
res } } #[doc(alias = "graphene_vec2_one")] pub fn one() -> Vec2 { assert_initialized_main_thread!(); unsafe { from_glib_none(ffi::graphene_vec
random
[ { "content": "/// Overrides pointer mutability.\n\n///\n\n/// Use when the C API should be specifying a const pointer but doesn't.\n\npub fn mut_override<T>(ptr: *const T) -> *mut T {\n\n ptr as *mut T\n\n}\n\n\n", "file_path": "glib/src/translate.rs", "rank": 0, "score": 272635.49373199604 }, ...
Rust
envy-utils/src/consts.rs
crazyacking/envy
afb3dd0650a77bbd7a8ed288b81d2b9db5f717fb
#![allow(clippy::float_cmp)] use crate::{clip, is_direct_expn_of, sext, unsext}; use if_chain::if_chain; use rustc_ast::ast::{self, LitFloatType, LitKind}; use rustc_data_structures::sync::Lrc; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{BinOp, BinOpKind, Block, Expr, ExprKind, HirId, QPath, UnOp}; use rustc_l...
#![allow(clippy::float_cmp)] use crate::{clip, is_direct_expn_of, sext, unsext}; use if_chain::if_chain; use rustc_ast::ast::{self, LitFloatType, LitKind}; use rustc_data_structures::sync::Lrc; use rustc_hir::def::{DefKind, Res}; us
l == r, (&Self::F64(l), &Self::F64(r)) => { l.to_bits() == r.to_bits() }, (&Self::F32(l), &Self::F32(r)) => { f64::from(l).to_bits() == f64::from(r).t...
e rustc_hir::{BinOp, BinOpKind, Block, Expr, ExprKind, HirId, QPath, UnOp}; use rustc_lint::LateContext; use rustc_middle::mir::interpret::Scalar; use rustc_middle::ty::subst::{Subst, SubstsRef}; use rustc_middle::ty::{self, FloatTy, ScalarInt, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::Sym...
random
[ { "content": "//! boom: Option<u64>,\n\n//! }\n\n//!\n\n//! match envy::from_env::<Config>() {\n\n//! Ok(config) => println!(\"{:#?}\", config),\n\n//! Err(error) => eprintln!(\"{:#?}\", error),\n\n//! }\n\n//! ```\n\n//!\n\n//! Special treatment is given to collections. For config fields that store...
Rust
pijama_core/src/machine/eval.rs
seanchen1991/pijama
d2f1be0a01b30b7ccfeb06fb0a0d5a3f463e5d1e
use pijama_ast::{BinOp, Literal, Primitive, UnOp}; use crate::{ lir::Term::{self, *}, machine::{arithmetic::Arithmetic, Machine}, }; use std::{borrow::Borrow, io::Write}; macro_rules! eval_in_place { ($self:ident, $term:ident, $ret:expr) => {{ let (changed, new_t) = $self.eval(*$term); *$...
use pijama_ast::{BinOp, Literal, Primitive, UnOp}; use crate::{ lir::Term::{self, *}, machine::{arithmetic::Arithmetic, Machine}, }; use std::{borrow::Borrow, io::Write}; macro_rules! eval_in_place { ($self:ident, $term:ident, $ret:expr) => {{ let (changed, new_t) = $self.eval(*$term); *$...
fn step_bin_op(&mut self, op: BinOp, mut t1: Box<Term>, mut t2: Box<Term>) -> (bool, Term) { use BinOp::*; match (op, t1.borrow(), t2.borrow()) { (And, Lit(0), _) => (true, false.into()), (Or, Lit(1), _) => (true, true.into()), ...
fn step_cond(&mut self, mut t1: Box<Term>, t2: Box<Term>, t3: Box<Term>) -> (bool, Term) { if let lit @ Term::Lit(_) = t1.borrow() { if lit.as_bool() { (true, *t2) } else { (true, *t3) } } else...
function_block-function_prefix_line
[ { "content": "fn arithmetic(c: &mut Criterion) {\n\n let input = include_str!(\"arithmetic.pj\");\n\n let term = compile(input).unwrap();\n\n let mut machine = MachineBuilder::default().build();\n\n c.bench_function(\"arithmetic\", |b| b.iter(|| machine.evaluate(term.clone())));\n\n}\n\n\n", "fi...
Rust
src/vec.rs
saethlin/rust-aliasable
6ec223b468834c35b9d58ccbe22cdc38cf76758f
use core::mem::ManuallyDrop; use core::ops::{Deref, DerefMut}; use core::pin::Pin; use core::ptr::NonNull; use core::{fmt, slice}; pub use alloc::vec::Vec as UniqueVec; pub struct AliasableVec<T> { ptr: NonNull<T>, len: usize, cap: usize, } impl<T> AliasableVec<T> { pub fn from_unique(unique: ...
use core::mem::ManuallyDrop; use core::ops::{Deref, DerefMut}; use core::pin::Pin; use core::ptr::NonNull; use core::{fmt, slice}; pub use alloc::vec::Vec as UniqueVec; pub struct AliasableVec<T> { ptr: NonNull<T>, len: usize, cap: usize, } impl<T> AliasableVec<T> { pub fn from_unique(unique: ...
pub fn into_unique_pin(pin: Pin<AliasableVec<T>>) -> Pin<UniqueVec<T>> { unsafe { let aliasable = Pin::into_inner_unchecked(pin); Pin::new_unchecked(AliasableVec::into_unique(aliasable)) } } pub fn from_unique_pin(pin: Pin<UniqueVec<T>>...
pub fn into_unique(aliasable: AliasableVec<T>) -> UniqueVec<T> { let mut aliasable = ManuallyDrop::new(aliasable); unsafe { aliasable.reclaim_as_unique_vec() } }
function_block-full_function
[ { "content": " inner: NonNull<T>,\n\n // We use `T` here to ensure `T` is invariant.\n\n _lifetime: PhantomData<&'a mut T>,\n\n}\n\n\n\nimpl<'a, T: ?Sized> AliasableMut<'a, T> {\n\n /// Construct an `AliasableMut` from an `&mut`.\n\n #[inline]\n\n pub fn from_unique(ptr: &'a mut T) -> Self {\n...
Rust
src/message/mod.rs
nnao45/twitter-stream-message
2b6090feef41710addcb16add070122ee07ffe26
mod event; mod warning; pub use self::event::{Event, EventKind}; pub use self::warning::{Warning, WarningCode}; use std::borrow::Cow; use std::fmt; use serde::de::{ Deserialize, Deserializer, Error as SerdeError, IgnoredAny, MapAccess, Unexpected, Visitor, }; use serde::de::value::MapAc...
mod event; mod warning; pub use self::event::{Event, EventKind}; pub use self::warning::{Warning, WarningCode}; use std::borrow::Cow; use std::fmt; use serde::de::{ Deserialize, Deserializer, Error as SerdeError, IgnoredAny, MapAccess, Unexpected, Visitor, }; use serde::de::value::MapAc...
r; impl<'x> Visitor<'x> for DeleteVisitor { type Value = Delete; fn visit_map<A: MapAccess<'x>>(self, mut a: A) -> Result<Delete, A::Error> { #[derive(Deserialize)] struct Status { id: StatusId, user_id: UserId }; ...
m_str(json) } } impl<'de: 'a, 'a> Deserialize<'de> for StreamMessage<'a> { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct SMVisitor; impl<'a> Visitor<'a> for SMVisitor { type Value = StreamMessage<'a>; fn visit_map<...
random
[ { "content": "pub fn deserialize_datetime<'x, D: Deserializer<'x>>(d: D) -> Result<DateTime, D::Error> {\n\n struct DTVisitor;\n\n\n\n impl<'x> Visitor<'x> for DTVisitor {\n\n type Value = DateTime;\n\n\n\n fn visit_str<E: SerdeError>(self, s: &str) -> Result<DateTime, E> {\n\n pa...
Rust
src/atsame70q21b/rtc/rtc_sccr.rs
tstellanova/atsame7x-pac
f7e24c71181651c141d0727379147c388661ce0e
#[doc = "Writer for register RTC_SCCR"] pub type W = crate::W<u32, super::RTC_SCCR>; #[doc = "Register RTC_SCCR `reset()`'s with value 0"] impl crate::ResetValue for super::RTC_SCCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `ACKCLR...
#[doc = "Writer for register RTC_SCCR"] pub type W = crate::W<u32, super::RTC_SCCR>; #[doc = "Register RTC_SCCR `reset()`'s with value 0"] impl crate::ResetValue for super::RTC_SCCR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `ACKCLR...
ine(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a...
et_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.b...
random
[ { "content": "#[doc = \"Reset value of the register\"]\n\n#[doc = \"\"]\n\n#[doc = \"This value is initial value for `write` method.\"]\n\n#[doc = \"It can be also directly writed to register by `reset` method.\"]\n\npub trait ResetValue {\n\n #[doc = \"Register size\"]\n\n type Type;\n\n #[doc = \"Res...
Rust
crates/flowistry/src/mir/control_dependencies.rs
connorff/flowistry
29af5fb143c4b7be9b6a4239f5dd98e6dae7da82
use std::fmt; use rustc_data_structures::graph::{ self, dominators, iterate, vec_graph::VecGraph, WithSuccessors, }; use rustc_index::{ bit_set::{BitSet, HybridBitSet, SparseBitMatrix}, vec::IndexVec, }; use rustc_middle::mir::*; #[derive(Clone)] pub struct BodyReversed<'tcx> { body: Body<'tcx>, exit_node: ...
use std::fmt; use rustc_data_structures::graph::{ self, dominators, iterate, vec_graph::VecGraph, WithSuccessors, }; use rustc_index::{ bit_set::{BitSet, HybridBitSet, SparseBitMatrix}, vec::IndexVec, }; use rustc_middle::mir::*; #[derive(Clone)] pub struct BodyReversed<'tcx> { body: Body<'tcx>, exit_node: ...
pub fn dependent_on(&self, block: BasicBlock) -> Option<&HybridBitSet<BasicBlock>> { self.0.row(block) } } #[cfg(test)] mod test { use log::debug; use rustc_data_structures::fx::{FxHashMap as HashMap, FxHashSet as HashSet}; use test_log::test; use super::*; use crate::{mir::utils::BodyExt, test_ut...
pub fn build(body: Body) -> Self { let (post_dominators, body_reversed) = compute_post_dominators(body); let body = &body_reversed.body; let idom = |x| { post_dominators .is_reachable(x) .then(|| post_dominators.immediate_dominator(x)) }; let edges = body .basic_blocks()...
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\npub fn connected_components<N, E, Ix>(g: &DiGraph<N, E, Ix>) -> Vec<Vec<NodeIndex<Ix>>>\n\nwhere\n\n Ix: IndexType,\n\n{\n\n let mut vertex_sets = UnionFind::<NodeIndex<Ix>>::new(g.node_bound());\n\n for edge in g.edge_references() {\n\n vertex_sets.union(edge.source()...
Rust
src/canvas/renderer.rs
unpatched/internet-broadcasting-service
24ac1d39775bd1b27c1a774d828fa5b00f790281
use canvas; use gfx; use gfx::format::{ U8Norm, Srgba8, Swizzle, Format, ChannelType, DepthStencil, Rgba8, Srgb, R8_G8_B8_A8, SurfaceType, Uint, }; use gfx::buffer::{ Role, CreationError, }; use gfx::memory::Usage; use gfx::{ Resources, Factory, Bind, ...
use canvas; use gfx; use gfx::format::{ U8Norm, Srgba8, Swizzle, Format, ChannelType, DepthStencil, Rgba8, Srgb, R8_G8_B8_A8, SurfaceType, Uint, }; use gfx::buffer::{ Role, CreationError, }; use gfx::memory::Usage; use gfx::{ Resources, Factory, Bind, ...
pub fn update_tex(&mut self, upload_buf: &Buffer<R,u8>) { self.encoder.copy_buffer_to_texture_raw(upload_buf.raw(), 0, &self.tex.raw(), None, self.iic.clone()); } pub fn update_dbuf(&mut self, download_buf: &Buffer<R,u8>) { self.encoder.copy_texture_to_buffer_raw(&self.tex.raw(), None, se...
Ok(x) => x, Err(e) => { return Err(CanvasError::UnableToViewTextureAsShaderResource(e)) }, }; let (vertex_buffer, slice) = factory.create_vertex_buffer_with_slice(&SCREEN, ()); let data = pipe::Data ...
function_block-function_prefix_line
[ { "content": "// Used to convert f32 slices to u8 slices.\n\n// useful for audio from portaudio -> ffmpeg.\n\nfn f32_slice_as_u8_slice(slice: &[f32]) -> &[u8] {\n\n unsafe {\n\n ::std::slice::from_raw_parts(slice.as_ptr() as _, slice.len() * 4)\n\n }\n\n}\n\n\n", "file_path": "examples/encode...
Rust
src/worker.rs
funmaker/mandelrust
827300000503230eeb38bd221dab9ed0a69f625a
extern crate time; use time::*; use std::f32::consts::PI as PI; use std::sync::{Arc, Barrier, Mutex}; use std::ops::*; use fixed::*; use super::TEXTURE; pub struct Job { pbo: &'static mut[u8], row: usize, width: usize, heigth: usize, scale: (f8_120, f8_120), center: (f8_120, f8_120), } impl J...
extern crate time; use time::*; use std::f32::consts::PI as PI; use std::sync::{Arc, Barrier, Mutex}; use std::ops::*; use fixed::*; use super::TEXTURE; pub struct Job { pbo: &'static mut[u8], row: usize, width: usize, heigth: usize, scale: (f8_120, f8_120), center: (f8_120, f8_120), } impl J...
pixel[3] = 255; }else{ let color = interpolate(&TEXTURE, i); pixel[0] = color.0; pixel[1] = color.1; pixel[2] = color.2; pixel[3] = 255; } ...
match job { Some(job) => self.do_job(job), None => { self.barrier.wait(); self.barrier.wait(); continue; } }; } } fn do_job( &mut self, job: Job) { use std::num::Zero...
random
[ { "content": "pub fn map_buffer(size: usize) -> &'static mut[u8]{ unsafe{\n\n let pbo_p = gl::MapBuffer(gl::PIXEL_UNPACK_BUFFER, gl::WRITE_ONLY);\n\n slice::from_raw_parts_mut(mem::transmute(pbo_p), size)\n\n}}\n\n\n", "file_path": "src/gl_utils.rs", "rank": 0, "score": 106031.73806946946 },...
Rust
src/synth_int.rs
NLnetLabs/rotonda-store
6dce6a7e6d0675bb14dc33afd962f8c429d7b6b4
use std::cmp::Ordering; use std::convert::TryInto; use std::fmt::{Binary, Debug}; use std::sync::atomic::AtomicU64; use crate::af::Zero; #[derive(Copy, Clone)] pub struct U256(pub u128, pub u128); impl U256 { pub fn to_be_bytes(self) -> [u8; 32] { [self.0.to_be_bytes(), self.1.to_be_bytes()] ...
use std::cmp::Ordering; use std::convert::TryInto; use std::fmt::{Binary, Debug}; use std::sync::atomic::AtomicU64; use crate::af::Zero; #[derive(Copy, Clone)] pub struct U256(pub u128, pub u128); impl U256 { pub fn to_be_bytes(self) -> [u8; 32] { [self.0.to_be_bytes(), self.1.to_be_bytes()] ...
} impl std::ops::BitAnd<Self> for U512 { type Output = Self; fn bitand(self, rhs: Self) -> Self::Output where Self: Eq, { Self( self.0 & rhs.0, self.1 & rhs.1, self.2 & rhs.2, self.3 & rhs.3, ) } } #[allow(dead_code)] pub str...
fn bitor(self, rhs: Self) -> Self::Output { Self( self.0 | rhs.0, self.1 | rhs.1, self.2 | rhs.2, self.3 | rhs.3, ) }
function_block-full_function
[ { "content": "type Stride8 = U512;\n\n\n\n// ----------- Stride Trait -------------------------------------------------\n\n\n", "file_path": "src/tree.rs", "rank": 0, "score": 97725.9510490288 }, { "content": "type Stride7 = U256;\n", "file_path": "src/tree.rs", "rank": 1, "score...
Rust
crates/steam-web-api/src/macros.rs
Nexure/SteamHelper-rs
2335baf050b1a30a3adcfbe9363e7451bee86f7a
#[cfg(feature = "async")] use async_trait::async_trait; #[cfg(feature = "async")] use futures::future; #[derive(serde::Serialize, Debug)] pub(crate) struct FormWrapper<'a, T: serde::Serialize> { #[serde(flatten)] pub(crate) parameters: T, pub(crate) key: &'a str, } #[cfg(feature = "async")] macro_rules! ...
#[cfg(feature = "async")] use async_trait::async_trait; #[cfg(feature = "async")] use futures::future; #[derive(serde::Serialize, Debug)] pub(crate) struct FormWrapper<'a, T: serde::Serialize> { #[serde(flatten)] pub(crate) parameters: T, pub(crate) key: &'a str, } #[cfg(feature = "async")] macro_rules! ...
tatus(); headers_error_check(status_code, headers)?; response.text().await.map_err(|e| e.into()) } _ => unimplemented!(), } } } }; } #[allow(unused)] macro_rules! impl_conversions { (@$...
status(); headers_error_check(status_code, headers)?; response.text().await.map_err(|e| e.into()) } &reqwest::Method::POST => { let data = self.recover_params_as_form(); let url = sel...
random
[ { "content": "/// Formats the captcha GID into the complete URL.\n\n/// E.g: https://steamcommunity.com/login/rendercaptcha/?gid=3851100575032057891\n\npub fn format_captcha_url(captcha_guid: &str) -> String {\n\n CAPTCHA_URL.to_owned() + captcha_guid\n\n}\n\n\n", "file_path": "crates/steam-auth/src/util...
Rust
pk3/src/lib.rs
ssnover/pkmn_tools
87efa605449817a339a323057dbdac0c5b4653aa
use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; use num_derive::{FromPrimitive, ToPrimitive}; use num_traits::FromPrimitive; use std::convert::TryInto; use std::io::prelude::*; use std::io::{Cursor, SeekFrom}; use pkmn_utils::Species; pub mod held_item; pub use held_item::HeldItem; pub const PK3_SIZE: usize ...
use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; use num_derive::{FromPrimitive, ToPrimitive}; use num_traits::FromPrimitive; use std::convert::TryInto; use std::io::prelude::*; use std::io::{Cursor, SeekFrom}; use pkmn_utils::Species; pub mod held_item; pub use held_item::HeldItem; pub const PK3_SIZE: usize ...
#[repr(u16)] #[derive(FromPrimitive, ToPrimitive)] pub enum Language { Japanese = 0x0201, English = 0x0202, French = 0x0203, Italian = 0x0204, German = 0x0205, Korean = 0x0206, Spanish = 0x0207, }
0..=5 => rearranged_data.extend_from_slice(&pk3_data[32..44]), 6 | 7 | 12 | 13 | 18 | 19 => rearranged_data.extend_from_slice(&pk3_data[44..56]), 8 | 10 | 14 | 16 | 20 | 22 => rearranged_data.extend_from_slice(&pk3_data[56..68]), 9 | 11 | 15 | 17 | 21 | 23 => rearranged_data.extend_from_slice(&p...
function_block-function_prefix_line
[ { "content": "pub fn get_team_pokemon(save_data: &[u8]) -> Vec<Vec<u8>> {\n\n let save_offset = match determine_latest_game_save(save_data) {\n\n GameSave::A => SAVE_A_OFFSET,\n\n GameSave::B => SAVE_B_OFFSET,\n\n };\n\n\n\n let mut cursor = Cursor::new(save_data);\n\n cursor.seek(Seek...
Rust
src/game_data.rs
m-cat/taurus
1a3422d5e31caa7052ffbae5d1622bd053eeb8c6
use crate::actor::Actor; use crate::console::{ConsoleSettings, DrawConsole}; use crate::constants; use crate::coord::Coord; use crate::defs::GameRatio; use crate::material::MaterialInfo; use crate::tile::TileInfo; use crate::ui::UiSettings; use crate::{handle_error, GameResult, DATABASE}; use failure::ResultExt; use ...
use crate::actor::Actor; use crate::console::{ConsoleSettings, DrawConsole}; use crate::constants; use crate::coord::Coord; use crate::defs::GameRatio; use crate::material::MaterialInfo; use crate::tile::TileInfo; use crate::ui::UiSettings; use crate::{handle_error, GameResult, DATABASE}; use failure::ResultExt; use ...
Info>, usize)> = Vec::new(); let mut min = usize::max_value(); for material_val in materials.values() { if let Value::Obj(ref material_data) = *material_val { let material = Arc::new( MaterialInfo::new(self, material_data) .context...
t<GameData> { let settings = DATABASE.read().unwrap().get_obj("settings")?; let console_settings = ConsoleSettings::new(&settings)?; let ui_settings = UiSettings::new(&settings)?; let mut game_data = GameData { console_settings, ui_settings, message_...
random
[]
Rust
src/pixiv/request.rs
hbina/rustpixiv
a7df82ea7f6afecb867636b60d2cdeec968fd365
use crate::utils::BytesWriter; use http::{uri::Uri, HeaderMap, Method}; use std::io::Write; #[derive(Debug, Clone)] pub struct PixivRequest { pub method: Method, pub url: Uri, pub headers: HeaderMap, pub params: std::collections::HashMap<&'static str, String>, pub form: std::collections::HashMap<...
use crate::utils::BytesWriter; use http::{uri::Uri, HeaderMap, Method}; use std::io::Write; #[derive(Debug, Clone)] pub struct PixivRequest { pub method: Method, pub url: Uri, pub headers: HeaderMap, pub params: std::collections::HashMap<&'static str, String>, pub form: std::collections::HashMap<...
pub fn add_header<T, U>(mut self, key: T, val: U) -> Self where T: Into<http::header::HeaderName>, U: Into<http::header::HeaderValue>, { self.headers.insert(key.into(), val.into()); self } pub fn add_header_str<'a, T>(mut self, key: T, val: &'a str) ...
t { method, url: url, headers: HeaderMap::new(), params: std::collections::HashMap::new(), form: std::collections::HashMap::new(), }; result.add_header( http::header::REFERER, http::header::HeaderValue::from_static("http...
function_block-function_prefixed
[ { "content": "use serde::{Deserialize, Serialize};\n\n\n\n#[derive(Deserialize, Serialize, Debug, Clone)]\n\npub struct ImageUrl {\n\n pub large: Option<String>,\n\n pub medium: Option<String>,\n\n pub small: Option<String>,\n\n pub square_medium: Option<String>,\n\n}\n\n\n\nimpl IntoIterator for Im...
Rust
src/cargo/ops/cargo_upload.rs
jakerr/cargo
f0762dfc1340c24ad87fa59027d5308c96867393
use std::collections::HashMap; use std::io::File; use std::os; use std::str; use serialize::json::{mod, ToJson}; use curl::http; use git2; use core::source::Source; use core::{Package, MultiShell, SourceId, RegistryKind}; use ops; use sources::{PathSource, RegistrySource}; use util::config; use util::{CargoResult, hu...
use std::collections::HashMap; use std::io::File; use std::os; use std::str; use serialize::json::{mod, ToJson}; use curl::http; use git2; use core::source::Source; use core::{Package, MultiShell, SourceId, RegistryKind}; use ops; use sources::{PathSource, RegistrySource}; use util::config; use util::{CargoResult, hu...
pub fn http_handle() -> CargoResult<http::Handle> { Ok(match try!(http_proxy()) { Some(proxy) => http::handle().proxy(proxy), None => http::handle(), }) } pub fn http_proxy() -> CargoResult<Option<String>> { let configs = try!(config::all_configs(os::getcwd())); match configs.find_equ...
pub fn upload_configuration() -> CargoResult<UploadConfig> { let configs = try!(config::all_configs(os::getcwd())); let registry = match configs.find_equiv(&"registry") { None => return Ok(UploadConfig { host: None, token: None }), Some(registry) => try!(registry.table().chain_error(|| { ...
function_block-full_function
[ { "content": "fn tar(pkg: &Package, src: &PathSource, shell: &mut MultiShell,\n\n dst: &Path) -> CargoResult<()> {\n\n\n\n if dst.exists() {\n\n return Err(human(format!(\"destination already exists: {}\",\n\n dst.display())))\n\n }\n\n let tmpfile = try!(Fi...
Rust
examples/flex-table.rs
maurerdietmar/druid-widget-nursery
f302b2d668dac7801af7b1e4e6f22e1b3accce42
use druid::widget::{ Align, Container, CrossAxisAlignment, Flex, Label, Stepper, TextBox, WidgetExt, }; use druid::{theme, AppLauncher, Color, Data, Env, Lens, UnitPoint, Widget, WindowDesc}; use druid_widget_nursery::table::{ FlexTable, TableCellVerticalAlignment, TableColumnWidth, TableRow, }; #[derive(Cl...
use druid::widget::{ Align, Container, CrossAxisAlignment, Flex, Label, Stepper, TextBox, WidgetExt, }; use druid::{theme, AppLauncher, Color, Data, Env, Lens, UnitPoint, Widget, WindowDesc}; use druid_widget_nursery::table::{ FlexTable, TableCellVerticalAlignment, TableColumnWidth, TableRow, }; #[derive(Cl...
.border(Color::WHITE, 1.) } fn make_row_alignment_example() -> impl Widget<DemoState> { let mut table = FlexTable::new() .inner_border(theme::BORDER_LIGHT, 1.) .default_column_width(TableColumnWidth::Intrinsic); use TableCellVerticalAlignment::*; let mut row = TableRow::new().verti...
n_horizontal(UnitPoint::RIGHT)) .with_child( TextBox::new() .with_placeholder("Password") .expand_width() .lens(DemoState::input_password), ), )
function_block-random_span
[ { "content": "fn build_ui() -> impl Widget<f64> {\n\n Flex::column()\n\n .with_spacer(30.0)\n\n .with_child(Slider::new().with_range(0.0, 80.0))\n\n .with_spacer(10.0)\n\n .with_flex_child(\n\n AdvancedSlider::new()\n\n .with_range(10.0, 70.0)\n\n ...
Rust
src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
bharrisau/rust
a80a610a4c30b6f5f60862afcb4588d03439f66c
use borrow_check::nll::region_infer::RegionInferenceContext; use borrow_check::nll::ToRegionVid; use rustc::hir::def_id::DefId; use rustc::mir::{Local, Mir}; use rustc::ty::{self, RegionVid, TyCtxt}; use rustc_data_structures::indexed_vec::Idx; use rustc_errors::DiagnosticBuilder; use syntax::ast::Name; use syntax::s...
use borrow_check::nll::region_infer::RegionInferenceContext; use borrow_check::nll::ToRegionVid; use rustc::hir::def_id::DefId; use rustc::mir::{Local, Mir}; use rustc::ty::{self, RegionVid, TyCtxt}; use rustc_data_structures::indexed_vec::Idx; use rustc_errors::DiagnosticBuilder; use syntax::ast::Name; use syntax::s...
}
fn synthesize_region_name(&self, counter: &mut usize) -> InternedString { let c = *counter; *counter += 1; Name::intern(&format!("'{:?}", c)).as_interned_str() }
function_block-full_function
[]
Rust
src/auth/www_authenticate.rs
06chaynes/http-types
e0ae15c814b5503120110b693375ec9c5335ece4
use crate::bail_status as bail; use crate::headers::{HeaderName, HeaderValue, Headers, WWW_AUTHENTICATE}; use crate::{auth::AuthenticationScheme, headers::Header}; #[derive(Debug)] pub struct WwwAuthenticate { scheme: AuthenticationScheme, realm: String, } impl WwwAuthenticate { pub fn new(scheme: Au...
use crate::bail_status as bail; use crate::headers::{HeaderName, HeaderValue, Headers, WWW_AUTHENTICATE}; use crate::{auth::AuthenticationScheme, headers::Header}; #[derive(Debug)] pub struct WwwAuthenticate { scheme: AuthenticationScheme, realm: String, } impl WwwAuthenticate { pub fn new(scheme: Au...
pub fn scheme(&self) -> AuthenticationScheme { self.scheme } pub fn set_scheme(&mut self, scheme: AuthenticationScheme) { self.scheme = scheme; } pub fn realm(&self) -> &str { self.realm.as_str() } pub fn set_realm(&mut self, realm: String) { ...
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> { let headers = match headers.as_ref().get(WWW_AUTHENTICATE) { Some(headers) => headers, None => return Ok(None), }; let value = headers.iter().last().unwrap(); le...
function_block-full_function
[ { "content": "/// Apply a set of default protections.\n\n///\n\n// /// ## Examples\n\n// /// ```\n\n// /// use http_types::Response;\n\n// ///\n\n// /// let mut res = Response::new(StatusCode::Ok);\n\n// /// http_types::security::default(&mut headers);\n\n// /// assert_eq!(headers[\"X-Content-Type-Options\"], \...
Rust
src/search.rs
alexander-hill/slide-puzzle
5f288a9154b1793a87fb40593cc65271edafd7c6
use game::{Board, Move}; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap}; pub fn a_star(start: Board, goal: &Board, moves: &[Move]) -> Option<Vec<Move>> { if start == *goal { return Some(Vec::new()); } let mut fringe = BinaryHeap::new(); let mut movements = HashMap:...
use game::{Board, Move}; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap}; pub fn a_star(start: Board, goal: &Board, moves: &[Move]) -> Option<Vec<Move>> { if start == *goal { return Some(Vec::new()); } let mut fringe = BinaryHeap::new(); let mut movements = HashMap:...
#[test] fn board_2() { let start = Board::from_vec(vec![1, 2, 3, 7, 4, 5, 0, 8, 6]).unwrap(); let solution = vec![Up, Right, Right, Down]; assert_eq!(Some(solution), a_star(start, &goal(), &moves())); } #[test] fn board_3() { let start = Board::from_vec(vec![1, 2,...
c(vec![1, 2, 3, 4, 0, 5, 7, 8, 6]).unwrap(); let solution = vec![Right, Down]; assert_eq!(Some(solution), a_star(start, &goal(), &moves())); }
function_block-function_prefixed
[ { "content": "/// Computes the length of a board’s size, or returns `None` if the number of\n\n/// cells is not a square number.\n\n///\n\n/// Not particularly optimized, I don’t care.\n\nfn board_size(num_cells: usize) -> Option<usize> {\n\n let root = (num_cells as f64).sqrt();\n\n\n\n if (root * root) ...
Rust
server/tests/vm-smoke.rs
tere-shell/tere
cff0e25c4e9f390da166d3dd8768a84e9f815302
#![cfg(feature = "internal-dangerous-tests")] use std::collections::HashSet; use std::convert::TryFrom; use std::path::Path; use tere_server::ipc; use tere_server::ipc::seqpacket::SeqPacket; mod systemd; #[test] fn pty_dynamic_user_isolation() { use tere_server::proto::pty as p; let dbus = systemd::Dbus::n...
#![cfg(feature = "internal-dangerous-tests")] use std::collections::HashSet; use std::convert::TryFrom; use std::path::Path; use tere_server::ipc; use tere_server::ipc::seqpacket::SeqPacket; mod systemd; #[test] fn pty_dynamic_user_isolation() { use tere_server::proto::pty as p; let dbus = systemd::Dbus::n...
#[test] fn sessions_create() { use tere_server::ipc::IPC; let path = Path::new("/run/tere/socket/sessions.socket"); let conn = SeqPacket::connect(path).expect("connect"); let client_socket = { use tere_server::proto::sessions as p; ipc::handshake::handshake_as_client(&conn, p::CLIENT_...
let path = &unit.object_path.as_str(); let service = dbus .get_systemd_service_for_path(path) .expect("getting D-Bus proxy for systemd service"); service.main_pid().expect("getting systemd service MainPID") }) .filter(|pid| *pid !...
function_block-function_prefix_line
[ { "content": "fn path_from_nul_terminated_buf(buf: &[u8]) -> Option<&std::path::Path> {\n\n // std::ffi::CStr and friends all assume the buffer contains no interior NULs, can't use them here.\n\n let end = buf.iter().position(|c| *c == 0u8)?;\n\n let s = OsStr::from_bytes(&buf[..end]);\n\n Some(std:...
Rust
crates/modor_graphics/src/backend/targets/texture.rs
modor-engine/modor
447ae453030de44ed93a2ab03a66261080304ce4
use crate::backend::targets::{CreatedTarget, Target}; use crate::utils; use std::mem; use std::num::NonZeroU32; use wgpu::{ Adapter, Backends, Buffer, CommandEncoder, Device, Extent3d, ImageCopyBuffer, Instance, MapMode, Queue, Texture, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, Text...
use crate::backend::targets::{CreatedTarget, Target}; use crate::utils; use std::mem; use std::num::NonZeroU32; use wgpu::{ Adapter, Backends, Buffer, CommandEncoder, Device, Extent3d, ImageCopyBuffer, Instance, MapMode, Queue, Texture, TextureDescriptor, TextureDimension, TextureFormat, TextureUsages, Text...
fn calculate_unpadded_row_bytes(width: u32) -> u64 { let bytes_per_pixel = mem::size_of::<u32>() as u64; u64::from(width) * bytes_per_pixel } fn calculate_padded_row_bytes(unpadded_bytes_per_row: u64) -> u64 { let align = u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT); let ...
fn create_buffer(device: &Device, height: u32, padded_bytes_per_row: u64) -> Buffer { device.create_buffer(&wgpu::BufferDescriptor { label: Some("modor_target_output_buffer"), size: (padded_bytes_per_row * u64::from(height)), usage: wgpu::BufferUsages::MAP_READ | wgpu::Buffer...
function_block-full_function
[ { "content": "fn retrieve_device(adapter: &Adapter) -> (Device, Queue) {\n\n utils::block_on(adapter.request_device(\n\n &DeviceDescriptor {\n\n features: Features::empty(),\n\n limits: {\n\n #[cfg(target_arch = \"wasm32\")]\n\n {\n\n ...
Rust
src/outcome.rs
sourcefrog/cargo-mutants
a97cbd7155f45a343d3457879306d060d2dec5d3
use std::fmt; use std::fs; use std::time::Duration; use anyhow::Context; use serde::ser::SerializeStruct; use serde::Serialize; use serde::Serializer; use crate::exit_code; use crate::log_file::LogFile; use crate::*; #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize)] pub enum Phase { Check, Buil...
use std::fmt; use std::fs; use std::time::Duration; use anyhow::Context; use serde::ser::SerializeStruct; use serde::Serialize; use serde::Serializer; use crate::exit_code; use crate::log_file::LogFile; use crate::*; #[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize)] pub enum Phase { Check, Buil...
}
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut ss = serializer.serialize_struct("PhaseResult", 3)?; ss.serialize_field("phase", &self.phase)?; ss.serialize_field("duration", &self.duration.as_secs_f64())?; ss.seria...
function_block-full_function
[ { "content": "/// Return a styled string reflecting the moral value of this outcome.\n\npub fn style_outcome(outcome: &Outcome) -> StyledObject<&'static str> {\n\n use CargoResult::*;\n\n use Scenario::*;\n\n match &outcome.scenario {\n\n SourceTree | Baseline => match outcome.last_phase_result(...
Rust
util/build/info/build.rs
jgreat/mobilecoin
7df58d88f67e3b92122b814acae9c08498429092
use cargo_emit::rerun_if_env_changed; use std::{ env, fs, path::{Path, PathBuf}, process::Command, }; fn get_git_commit(current_dir: impl AsRef<Path>) -> String { match Command::new("git") .args(&["describe", "--always", "--dirty=-modified"]) .current_dir(current_dir) .output(...
use cargo_emit::rerun_if_env_changed; use std::{ env, fs, path::{Path, PathBuf}, process::Command, }; fn get_git_commit(current_dir: impl AsRef<Path>) -> String { match Command::new("git") .args(&["describe", "--always", "--dirty=-modified"]) .current_dir(current_dir) .output(...
if let Ok(current_contents) = fs::read_to_string(out_file.clone()) { eprintln!("current contents:\n{}", current_contents); eprintln!("gen contents:\n{}", gen_contents); if current_contents == gen_contents { return; } } let mut file = fs::File::creat...
function_block-function_prefix_line
[ { "content": "// Report fixed string, with no formatting work\n\npub fn report_panic_str(message: &'static str) {\n\n unsafe { report_panic_message(message.as_ptr(), message.len()) }\n\n}\n\n\n\n// This is the ocall that we use to make to report panic text\n\n// See src/sgx/edl/\n\nextern \"C\" {\n\n pub ...
Rust
src/lib.rs
alopatindev/cargo-lim
f3793a66f5515b55b84da616f29ea51484aa49c5
#[doc(hidden)] pub mod models; mod cargo_toml; mod io; mod messages; mod options; mod process; #[doc(hidden)] pub use process::NO_EXIT_CODE; use crate::models::{EditorData, SourceFile}; use anyhow::{Context, Result}; use cargo_metadata::{Message, MetadataCommand}; use io::Buffers; use messages::{transform_and_proc...
#[doc(hidden)] pub mod models; mod cargo_toml; mod io; mod messages; mod options; mod process; #[doc(hidden)] pub use process::NO_EXIT_CODE; use crate::models::{EditorData, SourceFile}; use anyhow::{Context, Result}; use cargo_metadata::{Message, MetadataCommand}; use io::Buffers; use messages::{transform_and_proc...
}; let mut parsed_messages = Messages::parse_with_timeout_on_error(&mut buffers, Some(&cargo_process), &options)?; let exit_code = if parsed_messages.child_killed() { buffers.writeln_to_stdout("")?; let exit_code = cargo_process.wait()?; parsed_messages.merge(Messages::par...
open_affected_files_in_external_app( buffers, source_files_in_consistent_order, &options, workspace_root, )
call_expression
[]
Rust
humblegen/src/backend/elm.rs
49nord/humblegen-rs
85022454f5bf4d2bb6b2767b59c899401fe79178
#![allow(clippy::write_literal)] use crate::{ast, Artifact, LibError, Spec}; use anyhow::Result; use inflector::cases::camelcase::to_camel_case; use std::io::{self, BufWriter}; use std::{ fs::{self, File}, io::Write, path::{Path, PathBuf}, }; const BACKEND_NAME: &str = "elm"; pub mod decoder_generation...
#![allow(clippy::write_literal)] use crate::{ast, Artifact, LibError, Spec}; use anyhow::Result; use inflector::cases::camelcase::to_camel_case; use std::io::{self, BufWriter}; use std::{ fs::{self, File}, io::Write, path::{Path, PathBuf}, }; const BACKEND_NAME: &str = "elm"; pub mod decoder_generation...
pub fn generate_decoders(&self, spec: &Spec, outdir: &Path) -> Result<(), LibError> { let mut file = self.make_file(spec, outdir, "Decode")?; write!( file.start_line()?, "import {}.Data exposing (..)", self.module_prefix )?; write!( f...
e!( file.start_line()?, include_str!("./elm/preamble_types.elm"), module_prefix = self.module_prefix )?; file.empty_lines(2)?; for spec_item in spec.iter() { match spec_item { ast::SpecItem::StructDef(sdef) => { ...
function_block-function_prefixed
[ { "content": "/// Generate elm code for encoder functions for `spec`.\n\npub fn generate_struct_and_enum_encoders(spec: &ast::Spec) -> String {\n\n spec.iter()\n\n .filter_map(|spec_item| match spec_item {\n\n ast::SpecItem::StructDef(sdef) => {\n\n let json_encoder = generat...
Rust
qrcode-server/src/main.rs
philipgreat/rust-exercises
c1a84b5deb2026f2bc5082d7a199a5c863a24612
use actix_web::{middleware, get, web, App, HttpServer, Responder,HttpResponse,HttpRequest}; use urlencoding::decode; use actix_web::http::header::ContentType; use qrcode::{QrCode}; use image::Luma; use image::DynamicImage; use image::ImageOutputFormat; use qrcode::render::svg; use std::io::Cursor; fn serve_svg(co...
use actix_web::{middleware, get, web, App, HttpServer, Responder,HttpResponse,HttpRequest}; use urlencoding::decode; use actix_web::http::header::ContentType; use qrcode::{QrCode}; use image::Luma; use image::DynamicImage; use image::ImageOutputFormat; use qrcode::render::svg; use std::io::Cursor; fn serve_svg(co...
#[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| App::new().wrap(middleware::Logger::default()) .service(index).service(genqrcode).service(qrsvc)) .bind("0.0.0.0:9090")? .run() .await } /* fn image(){ let code = QrCode::new(b"https:...
async fn genqrcode(_req: HttpRequest) -> HttpResponse { let code = QrCode::new(b"https://www.google.com/").unwrap(); let image = code.render::<Luma<u8>>().build(); let mut w = Cursor::new(Vec::new()); DynamicImage::ImageLuma8(image) .write_to(&mut w, ImageOutputFormat::Png...
function_block-full_function
[ { "content": "fn index() -> impl Responder {\n\n let content = include_str!(\"index.html\");\n\n\n\n HttpResponse::Ok()\n\n .header(\"content-type\", \"text/html\")\n\n .body(content)\n\n}\n\n\n", "file_path": "server-sent-events/src/main.rs", "rank": 0, "score": 137299.972811296...
Rust
src/main.rs
nhiro3303/rust_game_2d
e46a8dea70bb6102db049f7b5434efbf5cac671e
use std::mem; use std::os::raw::c_void; use std::time::Duration; use c_str_macro::c_str; use cgmath::{perspective, vec3}; use gl::types::{GLfloat, GLsizei, GLsizeiptr}; use imgui::im_str; use sdl2::event::Event; use sdl2::keyboard::Keycode; use std::f32; mod shader; mod vertex; use shader::Shader; use vertex::Ver...
use std::mem; use std::os::raw::c_void; use std::time::Duration; use c_str_macro::c_str; use cgmath::{perspective, vec3}; use gl::types::{GLfloat, GLsizei, GLsizeiptr}; use imgui::im_str; use sdl2::event::Event; use sdl2::keyboard::Keycode; use std::f32; mod shader; mod vertex; use shader::Shader; use vertex::Ver...
; shader.use_program(); shader.set_mat4(c_str!("uModel"), &model_matrix); shader.set_mat4(c_str!("uView"), &view_matrix); shader.set_mat4(c_str!("uProjection"), &projection_matrix); vertex.draw(); imgui_sdl2_context.prepare_frame( ...
perspective( cgmath::Deg(45.0f32), WINDOW_WIDTH as f32 / WINDOW_HEIGHT as f32, 0.1, 100.0, )
call_expression
[ { "content": "#[allow(dead_code)]\n\ntype Matrix4 = cgmath::Matrix4<f32>;\n\n\n\npub struct Shader {\n\n pub id: u32,\n\n}\n\n\n\n#[allow(dead_code)]\n\nimpl Shader {\n\n #[rustfmt::skip]\n\n pub fn new(vertex_path: &str, fragment_path: &str)->Shader {\n\n let mut shader = Shader {id: 0};\n\n\n\...
Rust
storage/src/block_index_db.rs
NilFoundation/rust-ton
ea970ca3a96f93f2ad48576fd5d8f5503ad2040d
use crate::{ block_handle_db::BlockHandle, lt_db::LtDb, lt_desc_db::LtDescDb, types::{LtDbEntry, LtDbKey, LtDesc, ShardIdentKey} }; use std::{cmp::Ordering, convert::TryInto, path::Path, sync::RwLock}; use ton_block::{AccountIdPrefixFull, BlockIdExt, MAX_SPLIT_DEPTH, ShardIdent, UnixTime32}; use ton_types::{fa...
use crate::{ block_handle_db::BlockHandle, lt_db::LtDb, lt_desc_db::LtDescDb, types::{LtDbEntry, LtDbKey, LtDesc, ShardIdentKey} }; use std::{cmp::Ordering, convert::TryInto, path::Path, sync::RwLock}; use ton_block::{AccountIdPrefixFull, BlockIdExt, MAX_SPLIT_DEPTH, ShardIdent, UnixTime32}; use ton_types::{fa...
pub fn get_block_by_seq_no(&self, account_id: &AccountIdPrefixFull, seq_no: u32) -> Result<BlockIdExt> { self.get_block( account_id, |desc| seq_no.cmp(&desc.last_seq_no()), |entry| seq_no.cmp(&(entry.block_id_ext().seqno as u32)), true ) } p...
k( account_id, |desc| unix_time.0.cmp(&desc.last_unix_time()), |entry| unix_time.0.cmp(&entry.unix_time()), false ) }
function_block-function_prefixed
[]
Rust
src/lib.rs
anti-social/lgtv-rust
40325ef63f604e8af6bf3507647ef5159d1d85bc
#![recursion_limit="1024"] use failure::{Error, format_err}; use futures::Future; use futures::channel::oneshot; use async_std::future::timeout; use async_std::sync::{channel, Sender}; use std::time::Duration; use url::Url; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; mod cmd; pub use cmd::...
#![recursion_limit="1024"] use failure::{Error, format_err}; use futures::Future; use futures::channel::oneshot; use async_std::future::timeout; use async_std::sync::{channel, Sender}; use std::time::Duration; use url::Url; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; mod cmd; pub use cmd::...
} } pub struct Lgtv { _url: Url, read_timeout: Option<Duration>, wait_conn_tx: Sender<oneshot::Sender<()>>, cmd_tx: Sender<TvCmd>, is_connected: Arc<AtomicBool>, } impl Lgtv { pub fn builder() -> LgtvBuilder { LgtvBuilder::default() } pub async fn wait_conn(&self) { ...
Ok(Lgtv { _url: url, read_timeout: self.read_timeout, wait_conn_tx, cmd_tx, is_connected, })
call_expression
[ { "content": "fn mk_uri(base: &str, cmd: &str) -> String {\n\n format!(\"{}/{}\", base, cmd)\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum TvCmd {\n\n TurnOff(oneshot::Sender<Result<(), Error>>),\n\n OpenChannel(u8, oneshot::Sender<Result<(), Error>>),\n\n GetVolume(oneshot::Sender<Result<u8, Error>>),\n...
Rust
src/framework/mod.rs
chrisliebaer/poise
872eb64e82990dc3bd061d318068da58fc01b570
mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::dispatch_message; async fn check_permissions<U, E>( ctx: crate::Context<'_, U, E>, required_permissions: ser...
mod prefix; mod slash; mod builder; pub use builder::*; use crate::serenity::client::{bridge::gateway::ShardManager, Client}; use crate::serenity_prelude as serenity; use crate::*; pub use prefix::dispatch_message; async fn check_permissions<U, E>( ctx: crate::Context<'_, U, E>, required_permissions: ser...
async fn get_user_data(&self) -> &U { loop { match self.user_data.get() { Some(x) => break x, None => tokio::time::sleep(std::time::Duration::from_millis(100)).await, } } } async fn event(&self, ctx: serenity::Conte...
pub fn shard_manager(&self) -> std::sync::Arc<tokio::sync::Mutex<ShardManager>> { self.shard_manager .lock() .unwrap() .clone() .expect("fatal: shard manager not stored in framework initialization") }
function_block-full_function
[ { "content": "fn update_message(message: &mut serenity::Message, update: serenity::MessageUpdateEvent) {\n\n message.id = update.id;\n\n message.channel_id = update.channel_id;\n\n message.guild_id = update.guild_id;\n\n\n\n if let Some(kind) = update.kind {\n\n message.kind = kind;\n\n }\...
Rust
src/router/gossip/router.rs
grunch/lnp-core
689c1ad24dfe52b7e17fcdff835a3ddab4b2ae4b
use amplify::DumbDefault; use internet2::presentation::sphinx::Hop; use p2p::legacy::{ ChannelId, HopRealm, Messages, PaymentOnion, PaymentRequest, ShortChannelId, }; use strict_encoding::{strict_deserialize, strict_serialize}; use super::GossipChannelInfo; use crate::router::gossip::LocalChannelInfo; use crate:...
use amplify::DumbDefault; use internet2::presentation::sphinx::Hop; use p2p::legacy::{ ChannelId, HopRealm, Messages, PaymentOnion, PaymentRequest, ShortChannelId, }; use strict_encoding::{strict_deserialize, strict_serialize}; use super::GossipChannelInfo; use crate::router::gossip::LocalChannelInfo; use crate:...
Messages::RevokeAndAck(_) => {} */ _ => {} } Ok(()) } fn update_from_local(&mut self, message: &UpdateMsg) -> Result<(), Error> { match message { UpdateMsg::DirectChannelAdd(info) => { self.add_direct_channel(*info); ...
{ channel_id, .. }) => {} Messages::ChannelReestablish(_) => {} Messages::ClosingSigned(_) => {} Messages::CommitmentSigned(_) => {}
random
[ { "content": "/// Trait for any data that can be used as a part of the channel state\n\npub trait State: StrictEncode + StrictDecode + DumbDefault {\n\n fn to_funding(&self) -> Funding;\n\n fn set_funding(&mut self, funding: &Funding);\n\n}\n\n\n\npub type ExtensionQueue<N> = BTreeMap<N, Box<dyn ChannelEx...
Rust
prata/src/publisher.rs
roboscienceorg/Prata
684eb549da229f35ff9c533f252af395b0125fdf
extern crate serde_json; extern crate serde; extern crate serde_derive; use std::collections::HashMap; use pyo3::prelude::*; #[path = "messaging.rs"] mod messaging; type IPPort = (String, u16); /** * Publishers send data to channels * channelInfo (HashMap<String, IPPort>) - Channel names maped to their add...
extern crate serde_json; extern crate serde; extern crate serde_derive; use std::collections::HashMap; use pyo3::prelude::*; #[path = "messaging.rs"] mod messaging; type IPPort = (String, u16); /** * Publishers send data to channels * channelInfo (HashMap<String, IPPort>) - Channel names maped to their add...
/** * Sends data to a channel * ChannelName (String) - Name of channel to send to * Mess (String) - Message to send */ pub fn publish(&mut self, ChannelName : String, Mess: String) { if self.channelInfo.contains_key(&ChannelName) == false { self....
pub fn disconnect(&mut self, Name: String) { if self.channelInfo.contains_key(&Name) { let mx = messaging::Message {messageType: 'd',ip: self.ip.to_string(),port: self.port,message: Name.to_string()}; let _ = messaging::send(self.masterip.to_string(), self.masterpor...
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\npub fn connect(ip: String, p: u16 ) -> Master\n\n{\n\n return Master {ipAddress: ip, port: p, threading: true}\n\n}\n", "file_path": "prata/src/master.rs", "rank": 0, "score": 278494.3875700656 }, { "content": "#[allow(dead_code)]\n\npub fn send(toAddre...
Rust
src/main.rs
michaeljones/slipstream
4e6cd39c5c1dd481d2d8d99e13083017ce6bc683
extern crate clap; extern crate json; extern crate yaml_rust; #[macro_use] extern crate conrod; #[macro_use] extern crate conrod_derive; use yaml_rust::{Yaml, YamlLoader}; use std::rc::Rc; use std::cell::RefCell; use std::fs::File; use std::io::Read; use std::collections::HashMap; use std::collections::HashSet; use ...
extern crate clap; extern crate json; extern crate yaml_rust; #[macro_use] extern crate conrod; #[macro_use] extern crate conrod_derive; use yaml_rust::{Yaml, YamlLoader}; use std::rc::Rc; use std::cell::RefCell; use std::fs::File; use std::io::Read; use std::collections::HashMap; use std::collections::HashSet; use ...
DTH, HEIGHT); run(&mut params); } _ => { println!("Unknown action: {:?}", action); } } } else { println!("Usage: mango <new|run|edit> [filename]"); } }
function_block-function_prefixed
[ { "content": "pub fn gui(ui: &mut conrod::Ui, mut params: &mut Params, width: u32, height: u32) {\n\n let mut events_loop = glium::glutin::EventsLoop::new();\n\n\n\n let window = glium::glutin::WindowBuilder::new()\n\n .with_title(\"mango\")\n\n .with_dimensions(width, height);\n\n\n\n le...
Rust
crates/nu-command/src/dataframe/eager/join.rs
chen244/engine-q
f28f28183b620b7efefdfebfa9675d0623b4ccbc
use nu_engine::CallExt; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::prelude::JoinType; use crate::dataframe::values::utils::convert_columns_string; use super::super::values::{...
use nu_engine::CallExt; use nu_protocol::{ ast::Call, engine::{Command, EngineState, Stack}, Category, Example, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape, Value, }; use polars::prelude::JoinType; use crate::dataframe::values::utils::convert_columns_string; use super::super::values::{...
l_col_span, ) }) .map(|df| PipelineData::Value(NuDataFrame::dataframe_into_value(df, call.head), None)) } fn check_column_datatypes<T: AsRef<str>>( df_l: &polars::prelude::DataFrame, df_r: &polars::prelude::DataFrame, l_cols: &[T], l_col_span: Span, r_co...
input: PipelineData, ) -> Result<PipelineData, ShellError> { command(engine_state, stack, call, input) } } fn command( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let r_df: Value = call.req(engine_state, st...
random
[ { "content": "// Adds a separator to the vector of values using the column names from the\n\n// dataframe to create the Values Row\n\npub fn add_separator(values: &mut Vec<Value>, df: &DataFrame, span: Span) {\n\n let mut cols = vec![];\n\n let mut vals = vec![];\n\n\n\n for name in df.get_column_names...
Rust
Chapter02/src/bin/hashset.rs
PacktPublishing/Rust-Standard-Library-Cookbook
7bfa07011379e1fb235f18579c380e6bf100de85
use std::collections::HashSet; fn main() { let mut books = HashSet::new(); books.insert("Harry Potter and the Philosopher's Stone"); books.insert("The Name of the Wind"); books.insert("A Game of Thrones"); let is_new = books.insert("The Lies of Locke Lamora"); if is_ne...
use std::collections::HashSet; fn main() { let mut books = HashSet::new(); books.insert("Harry Potter and the Philosopher's Stone"); books.insert("The Name of the Wind"); books.insert("A Game of Thrones"); let is_new = books.insert("The Lies of Locke Lamora"); if is_ne...
e_to_five.is_disjoint(&three_to_eight); println!( "is {:?} disjoint from {:?}?: {}", one_to_five, three_to_eight, is_disjoint ); let is_subset = one_to_five.is_subset(&five_to_ten); println!( "is {:?} a subset of {:?}?: {}", one_to_five, five...
function_block-function_prefixed
[ { "content": "fn get_name_attribute(ast: &syn::DeriveInput) -> Option<&str> {\n\n const ATTR_NAME: &str = \"hello_world_name\";\n\n\n\n // Go through all attributes and find one with our name\n\n if let Some(attr) = ast.attrs.iter().find(|a| a.name() == ATTR_NAME) {\n\n // Check if it's in the f...
Rust
src/check/rules/clause/lhs.rs
ice1000/narc-rs
ed0a4537051ee0b5c906f1366e473db855b2bc45
use std::{convert::TryFrom, rc::Rc}; use voile_util::uid::{DBI, UID}; use crate::{ check::{ monad::{TCE, TCMS, TCS}, pats::CoreCopat, rules::{ clause::{ eqs::{classify_eqs, AsBind, PatVars}, split::{split_con, split_proj}, state::L...
use std::{convert::TryFrom, rc::Rc}; use voile_util::uid::{DBI, UID}; use crate::{ check::{ monad::{TCE, TCMS, TCS}, pats::CoreCopat, rules::{ clause::{ eqs::{classify_eqs, AsBind, PatVars}, split::{split_con, split_proj}, state::L...
d(..)) | Proj(..) => unreachable!(), } } if let Some(copat) = lhs.problem.take_first_todo_pat() { let proj = match copat { Copat::Proj(proj) => proj, e => return Err(TCE::CantElim(e)), }; let (lhs, tcs) = split_proj(tcs, lhs, proj)?; retur...
function_block-function_prefixed
[ { "content": "fn split_tele(mut tele: Tele, DBI(til): DBI) -> (Tele, Bind, Tele) {\n\n debug_assert!(tele.len() > til + 1);\n\n let pos = tele.len() - til + 1;\n\n let delta2 = tele.split_off(pos + 1);\n\n let dom = tele.remove(tele.len() - 1);\n\n (tele, dom, delta2)\n\n}\n\n\n\n/// [Agda](https...
Rust
raytracer/src/aarect.rs
Junxix/raytracer-2021
851085d55edb04c286f67524cf9398fcaed91e54
use crate::aabb::*; use crate::hittable::*; use crate::material::*; use crate::ray::*; use std::sync::Arc; pub struct XyRect { mp: Arc<dyn Material>, x0: f64, x1: f64, y0: f64, y1: f64, k: f64, } impl XyRect { /*pub fn new0() -> Self { Self { mp: Arc::new(Lambertian::new...
use crate::aabb::*; use crate::hittable::*; use crate::material::*; use crate::ray::*; use std::sync::Arc; pub struct XyRect { mp: Arc<dyn Material>, x0: f64, x1: f64, y0: f64, y1: f64, k: f64, } impl XyRect { /*pub fn new0() -> Self { Self { mp: Arc::new(Lambertian::new...
} /*use crate::aabb::AABB; use crate::hittable::HitRecord; use crate::material::Material; use crate::vec3::point3; use crate::{Hittable, Ray, Vec3}; use std::rc::Rc; use std::sync::Arc; pub struct XYRect { mp: Arc<dyn Material>, x0: f64, x1: f64, y0: f64, y1: f64, k: f64, } impl XYRect { ...
fn bounding_box(&self, time0: f64, time1: f64, output_box: &mut AABB) -> bool { let _x = time0; let _y = time1; *output_box = AABB::new( point3::new(self.k - 0.0001, self.y0, self.z0), point3::new(self.k + 0.0001, self.y1, self.z1), ); true }
function_block-full_function
[ { "content": "pub fn clamp(x: f64, min: f64, max: f64) -> f64 {\n\n if x < min {\n\n return min;\n\n }\n\n if x > max {\n\n return max;\n\n }\n\n x\n\n}\n", "file_path": "rtweekend.rs", "rank": 0, "score": 145968.37651438068 }, { "content": "pub fn clamp(x: f64, ...
Rust
interface/src/lib.rs
quvarxa/pikemon
73f1b74f2ecc3dec01df967f7db1daa1c93e292a
extern crate gb_emu; extern crate rustc_serialize; extern crate num; use std::collections::VecDeque; use std::collections::HashMap; use gb_emu::mmu::Memory; use gb_emu::graphics; use data::{Party, BattleData}; pub mod offsets; pub mod values; pub mod data; pub mod extract; pub mod text; pub mod hacks; #[derive(Pa...
extern crate gb_emu; extern crate rustc_serialize; extern crate num; use std::collections::VecDeque; use std::collections::HashMap; use gb_emu::mmu::Memory; use gb_emu::graphics; use data::{Party, BattleData}; pub mod offsets; pub mod values; pub mod data;
spritesheet: &[u8], sprite_data: &data::SpriteData) -> bool { const SPRITE_HEIGHT: usize = 16; const SPRITE_WIDTH: usize = 16; if sprite_data.y >= graphics::HEIGHT as isize || sprite_data.y + SPRITE_HEIGHT as isize <= 0 || sprite_data.x >= graphics::WIDTH as isize || sprite_data.x + SPRITE_WID...
pub mod extract; pub mod text; pub mod hacks; #[derive(PartialEq)] enum DataState { Normal, Hacked, } #[derive(PartialEq)] pub enum InterfaceState { Normal, Waiting, } pub type PlayerId = u32; #[derive(PartialEq)] pub enum NetworkRequest { None, Battle(PlayerId), } pub struct InterfaceData ...
random
[ { "content": "pub fn battle_data(mem: &Memory) -> BattleData {\n\n let base_offset = offsets::PLAYER_BATTLE_DATA_START;\n\n (0..BATTLE_DATA_SIZE as u16).map(|i| mem.lb(base_offset + i)).collect()\n\n}\n\n\n", "file_path": "interface/src/extract.rs", "rank": 1, "score": 87012.8937143617 }, ...
Rust
src/build.rs
mosmeh/suffine
aa515bd73f310127ba91e478afae1cfd461cd9d6
use crate::Result; use byteorder::{ByteOrder, NativeEndian, ReadBytesExt, WriteBytesExt}; use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufReader, BufWriter, Write}; use suffix::SuffixTable; use tempfile::NamedTempFile; #[derive(PartialEq, Debug)] pub struc...
use crate::Result; use byteorder::{ByteOrder, NativeEndian, ReadBytesExt, WriteBytesExt}; use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufReader, BufWriter, Write}; use suffix::SuffixTable; use tempfile::NamedTempFile; #[derive(PartialEq, Debug)] pub struc...
struct Block<'a> { text: &'a str, reader: BufReader<File>, begin: usize, front_index: u32, } impl Eq for Block<'_> {} impl PartialEq for Block<'_> { fn eq(&self, _: &Self) -> bool { unimplemented!() } } impl Ord for Block<'_> { fn cmp(&self, _: &Self) -> Ordering { unimp...
table() .iter() .filter(|&&x| (x as usize) < len && text.is_char_boundary(x as usize)); let mut num_written = 0; for x in sa { buffer.write(*x)?; num_written += 1; } Ok(num_written) }
function_block-function_prefix_line
[ { "content": "fn main() -> Result<()> {\n\n let text_filename = std::env::args()\n\n .nth(1)\n\n .ok_or_else(|| anyhow!(\"input filename required\"))?;\n\n let index_filename = std::env::args()\n\n .nth(2)\n\n .ok_or_else(|| anyhow!(\"output filename required\"))?;\n\n\n\n l...
Rust
src/bsdf/microfacet.rs
ItsHoff/Rusty
f0418d775442d553b69d8e342a15c597a7786451
use cgmath::prelude::*; use cgmath::Vector3; use crate::color::Color; use crate::consts; use crate::float::*; use crate::pt_renderer::PathType; use crate::sample; use super::fresnel::{self, FresnelBSDF}; use super::util; use super::BsdfTrait; #[derive(Clone, Debug)] struct Ggx { alpha: Float, } impl Ggx { f...
use cgmath::prelude::*; use cgmath::Vector3; use crate::color::Color; use crate::consts; use crate::float::*; use crate::pt_renderer::PathType; use crate::sample; use super::fresnel::{self, FresnelBSDF}; use super::util; use super::BsdfTrait; #[derive(Clone, Debug)] struct Ggx { alpha: Float, } impl Ggx { f...
til::cos_t(wo).abs(); let idn = util::cos_t(wi).abs(); let denom = 4.0 * wh.dot(wi).abs() * odn.max(idn); let f_specular = d * fresnel::schlick(wo, self.specular) / denom; let p5 = |xdn: Float| 1.0 - (1.0 - xdn / 2.0).powi(5); let factor = 28.0 * self.diffuse / (23.0 * consts::PI...
e( &self, wo: Vector3<Float>, _path_type: PathType, ) -> Option<(Color, Vector3<Float>, Float)> { let wh = self.microfacets.sample_wh(wo); let wi = util::reflect(wo, wh); if !util::same_hemisphere(wo, wi) { return None; } let pdf = self.pdf...
random
[ { "content": "pub fn schlick(w: Vector3<Float>, specular: Color) -> Color {\n\n let cos_t = util::cos_t(w).abs();\n\n specular + (1.0 - cos_t).powi(5) * (Color::white() - specular)\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct FresnelBSDF<R: BsdfTrait, T: BsdfTrait> {\n\n pub brdf: R,\n\n pub bt...
Rust
src/second.rs
drconopoima/linked-list-rust
75742fb3f6b2b6ef34d9bdc1f619bf746baebbc1
type Link<T> = Option<Box<ListNode<T>>>; #[derive(Debug)] pub struct ListNode<T> { value: T, next: Link<T>, } #[derive(Debug)] pub struct LinkedList<T> { pub length: usize, head: Link<T>, } impl<T> LinkedList<T> { pub fn new() -> Self { LinkedList { ...
type Link<T> = Option<Box<ListNode<T>>>; #[derive(Debug)] pub struct ListNode<T> { value: T, next: Link<T>, } #[derive(Debug)] pub struct LinkedList<T> { pub length: usize, head: Link<T>, } impl<T> LinkedList<T> { pub fn new() -> Self { LinkedList { ...
} pub struct IterMut<'a, T> { next: Option<&'a mut ListNode<T>>, } impl<T> LinkedList<T> { pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> { IterMut { next: self.head.as_mut().map(|node| &mut **node), } } } impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut...
fn next(&mut self) -> Option<Self::Item> { self.next.take().map(|node| { self.next = node.next.as_ref().map::<&ListNode<T>, _>(|node| &**node); &node.value }) }
function_block-full_function
[ { "content": "#[derive(Debug)]\n\nstruct ListNode<T> {\n\n value: T,\n\n next: Link<T>,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct LinkedList<T> {\n\n // Number of non-empty nodes in list\n\n // @field length\n\n // @type {usize}\n\n length: usize,\n\n // Pointer to first node in the list.\...
Rust
src/main.rs
ahamlinman/jyt
91532cfd68559b291e9d1b379513883765ac2bfe
use std::error::Error; use std::fs::File; use std::io::{self, BufWriter, Write}; use std::path::PathBuf; use std::process; use clap::ErrorKind::{HelpDisplayed, VersionDisplayed}; use structopt::StructOpt; use jyt::{jyt, Format, InputHandle}; fn main() { let opt = match Opt::from_args_safe() { Ok(opt) => opt, ...
use std::error::Error; use std::fs::File; use std::io::{self, BufWriter, Write}; use std::path::PathBuf; use std::process; use clap::ErrorKind::{HelpDisplayed, VersionDisplayed}; use structopt::StructOpt; use jyt::{jyt, Format, InputHandle}; fn main() { let opt = match Opt::from_args_safe() { Ok(opt) => opt, ...
fn input(&self) -> io::Result<InputHandle> { match &self.input_filename { None => Ok(InputHandle::from_reader(io::stdin())), Some(path) if path.to_str() == Some("-") => Ok(InputHandle::from_reader(io::stdin())), Some(path) => { let file = File::open(path)?; ...
Some(path) => match path.extension().map(|ext| ext.to_str()).flatten() { Some("json") => Some(Format::Json), Some("yaml" | "yml") => Some(Format::Yaml), Some("toml") => Some(Format::Toml), Some("msgpack") => Some(Format::Msgpack), _ => None, }, } }
function_block-function_prefix_line
[ { "content": "fn transcode_input<O>(input: InputHandle, from: Format, output: O) -> Result<(), Box<dyn Error>>\n\nwhere\n\n O: Output,\n\n{\n\n match from {\n\n Format::Json => json::transcode(input, output),\n\n Format::Yaml => yaml::transcode(input, output),\n\n Format::Toml => toml::transcode(inpu...
Rust
src/connectivity/lowpan/lib/openthread_rust/src/ot/types/border_router_config.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use crate::prelude_internal::*; use core::fmt::{Debug, Formatter}; #[derive(Default, Clone, Copy)] #[repr(transparent)] pub struct BorderRouterConfig(pub otBorderRouterConfig); impl_ot_castable!(BorderRouterConfig, otBorderRouterConfig); impl Debug for BorderRouterConfig { fn fmt(&self, f: &mut Formatter<'_>)...
use crate::prelude_internal::*; use core::fmt::{Debug, Formatter}; #[derive(Default, Clone, Copy)] #[repr(transparent)] pub struct BorderRouterConfig(pub otBorderRouterConfig); impl_ot_castable!(BorderRouterConfig, otBorderRouterConfig); impl Debug for BorderRouterConfig { fn fmt(&self, f: &mut Formatter<'_>)...
} pub fn set_default_route_preference(&mut self, pref: Option<RoutePreference>) { if let Some(pref) = pref { self.0.set_mDefaultRoute(true); self.0.set_mPreference(pref as i32); } else { self.0.set_mDefaultRoute(false); } } ...
if self.0.mDefaultRoute() { Some(RoutePreference::from_i32(self.0.mPreference()).expect("Invalid route preference")) } else { None }
if_condition
[]
Rust
src/interrupt.rs
gifnksm/sabios
a0729dbdaafbbc318c6bc13636a3a17a842c782b
use crate::{emergency_console, println, sync::OnceCell, timer, xhc}; use core::{ fmt::Write as _, sync::atomic::{AtomicBool, Ordering}, }; use volatile::Volatile; use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame, PageFaultErrorCode}; #[derive(Debug, Clone, Copy)] #[repr(u8)] pub(crat...
use crate::{emergency_console, println, sync::OnceCell, timer, xhc}; use core::{ fmt::Write as _, sync::atomic::{AtomicBool, Ordering}, }; use volatile::Volatile; use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame, PageFaultErrorCode}; #[derive(Debug, Clone, Copy)] #[repr(u8)] pub(crat...
extern "x86-interrupt" fn double_fault_handler( stack_frame: InterruptStackFrame, error_code: u64, ) -> ! { let _guard = InterruptContextGuard::new(); emergency_console::with_console(|console| { let _ = writeln!(console, "EXCEPTION: DOUBLE FAULT",); let _ = writeln!(console, "Error Cod...
t _ = writeln!(console, "EXCEPTION: STACK NOT PRESENT"); let _ = writeln!(console, "Error Code: {:x}", error_code); let _ = writeln!(console, "{:#?}", stack_frame); }); }
function_block-function_prefixed
[ { "content": "fn map_xhc_mmio(mapper: &mut OffsetPageTable, xhc_mmio_base: u64) -> Result<()> {\n\n // Map [xhc_mmio_base..(xhc_mmio_base+64kib)] as identity map\n\n let mut allocator = memory::lock_memory_manager();\n\n paging::make_identity_mapping(mapper, &mut *allocator, xhc_mmio_base, 16)\n\n}\n\n...
Rust
ulib/src/malloc.rs
dancrossnyc/rxv64
7c33fb201e4a4ed55d6c630faf575f751306ab06
use core::cmp; use core::mem; use core::ptr; use core::slice; extern "C" { fn sbrk(nbytes: isize) -> *mut u8; } #[repr(C)] #[derive(Debug)] struct Header { next: *mut Header, nunits: usize, } impl Header { pub fn as_slice_mut(&mut self) -> &'static mut [u8] { let ptr = unsafe { (self as *mu...
use core::cmp; use core::mem; use core::ptr; use core::slice; extern "C" { fn sbrk(nbytes: isize) -> *mut u8; } #[repr(C)] #[derive(Debug)] struct Header { next: *mut Header, nunits: usize, } impl Header { pub fn as_slice_mut(&mut self) -> &'static mut [u8] { let ptr = unsafe { (self as *mu...
let mut current = unsafe { p.as_mut().unwrap() }; if current.end() == tp { current.nunits += tag.nunits; current.next = tag.next; } else { current.next = tp; } *free_list = Some(p); return p; ...
if tag.end() == p { let next = unsafe { np.as_ref().unwrap() }; tag.nunits += next.nunits; tag.next = next.next; } else { tag.next = np; }
if_condition
[ { "content": "pub fn namex(mut path: &[u8]) -> Result<&'static Inode> {\n\n let mut ip = if !path.is_empty() && path[0] == b'/' {\n\n let sb = unsafe { superblock() };\n\n Inode::get(param::ROOTDEV, ROOTINO, sb)?\n\n } else {\n\n proc::myproc().cwd().dup()\n\n };\n\n while let S...
Rust
graph_kahn.rs
vkovalchuk/rust-play
72404a7102de0287e9caaf4163ae4369f07c73bb
use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; use std::collections::{HashSet, HashMap}; use std::env; use std::fmt; #[derive(Clone, Eq, PartialEq, Hash)] struct Node(String); impl Node { fn new(s: &str) -> Node { Node(String::from(s)) } } impl fmt::Debug ...
use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; use std::collections::{HashSet, HashMap}; use std::env; use std::fmt; #[derive(Clone, Eq, PartialEq, Hash)] struct Node(String); impl Node { fn new(s: &str) -> Node { Node(String::from(s)) } } impl fmt::Debug ...
fn register_node(n: &str, node_indices: &mut HashMap<Node, usize>) -> usize { let node_key = Node::new(n); match node_indices.get(&node_key) { Some(&old_index) => old_index, None => { let new_index = node_indices.len(); node_indices.i...
fn read(fname: String) -> Graph { let mut node_indices = HashMap::new(); let mut edges = vec![]; let fdata = File::open(&Path::new(&fname)).unwrap(); let lines = io::BufReader::new(fdata).lines(); let mut i = 0; for ln_iter in lines { let mut ln = ln_...
function_block-full_function
[ { "content": "// #[derive(Debug)]\n\nstruct Node {\n\n value: & 'static str,\n\n parent: RefCell<Weak<Node>>,\n\n children: RefCell<Vec<Rc<Node>>>,\n\n}\n\n\n", "file_path": "dltree.rs", "rank": 2, "score": 81768.7160473318 }, { "content": "pub fn ts() -> String {\n\n use std::fm...
Rust
drepr/engine/src/execution_plans/classes_map_plan/class_map_plan.rs
scorpio975/d-repr
1d08024192642233d42d29e1d05f8713ee265bca
use hashbrown::{HashSet}; use serde::{Deserialize, Serialize}; use readers::is_enum_type_impl; use crate::alignments::inference::AlignmentInference; use crate::execution_plans::classes_map_plan::data_prop::DataProp; use crate::execution_plans::classes_map_plan::literal_prop::LiteralProp; use crate::execution_plans::cl...
use hashbrown::{HashSet}; use serde::{Deserialize, Serialize}; use readers::is_enum_type_impl; use crate::alignments::inference::AlignmentInference; use crate::execution_plans::classes_map_plan::data_prop::DataProp; use crate::execution_plans::classes_map_plan::literal_prop::LiteralProp; use crate::execution_plans::cl...
erence: &AlignmentInference) -> usize { let mut data_nodes = vec![]; let mut attrs = vec![]; let mut uri_attr = None; for &eid in &desc.semantic_model.outgoing_edges[class_id] { let target = desc.semantic_model.edges[eid].get_target(&desc.semantic_model); if target.is_data_n...
pseudo_id: subj_pseudo_id, real_id: (&desc.attributes[uri_dnode.attr_id], inference.get_alignments(subj, uri_dnode.attr_id)), is_optional: edges_optional[desc.semantic_model.get_edge(class_id, uri_dnode.attr_id).unwrap().edge_id], missing_values, }) } ...
random
[ { "content": "pub fn generic_optional_oprop_map(readers: &[Box<dyn RAReader>], writer: &mut dyn StreamClassWriter, oplan: &ObjectProp, oalign: &mut AlignmentFunc, subj_id: &str, subj_val: &Value, subj_idx: &[Index], o_idx: &mut [Index], is_subj_blank: bool, is_new_subj: bool) {\n\n match oalign {\n\n Alignm...
Rust
host/src/protocol.rs
edge-analytics/fpga-sleep-tracker
50efd114500e134297be5229775a9ec6809abb53
use crate::{error::FpgaDriverError, traits::Data, FpgaDriverResult}; pub const PROTO_HEADER_BYTES: usize = 1; pub const PROTO_ADDRESS_BYTES: usize = 2; pub const PROTO_META_BYTES: usize = PROTO_HEADER_BYTES + PROTO_ADDRESS_BYTES; pub const PROTO_PAYLOAD_MAX_SIZE: usize = 15; pub const PROTO_MAX_PACKET_SIZE: usize = ...
use crate::{error::FpgaDriverError, traits::Data, FpgaDriverResult}; pub const PROTO_HEADER_BYTES: usize = 1; pub const PROTO_ADDRESS_BYTES: usize = 2; pub const PROTO_META_BYTES: usize = PROTO_HEADER_BYTES + PROTO_ADDRESS_BYTES; pub const PROTO_PAYLOAD_MAX_SIZE: usize = 15; pub const PROTO_MAX_PACKET_SIZE: usize = ...
pub fn contiguous_write(payload: Box<[u8]>, target_reg_address: u16) -> FpgaDriverResult<Self> { let num_bytes = payload.len(); if num_bytes > PROTO_PAYLOAD_MAX_SIZE { return Err(FpgaDriverError::ProtocolMaxPayloadBytesExceeded { max_supported: PROTO_PAYLOAD_MAX_SIZ...
pub fn contiguous_read<D: Data>(target_reg_address: u16) -> FpgaDriverResult<Self> { let num_bytes = std::mem::size_of::<D>(); if num_bytes > PROTO_PAYLOAD_MAX_SIZE { return Err(FpgaDriverError::ProtocolMaxPayloadBytesExceeded { max_supported: PROTO_PAYLOAD_MAX_SIZE, ...
function_block-full_function
[ { "content": "#[derive(StructOpt)]\n\n#[structopt(name = \"sleep\", about = \"FPGA sleep app CLI driver.\")]\n\nenum Opt {\n\n /// Acquire data for an unbounded amount of time (hit enter to stop).\n\n Unbounded,\n\n /// Acquire data for the specified number of seconds.\n\n Bounded {\n\n /// T...
Rust
client/filesystem_mgr/src/file_info_handler.rs
duanjh7/yigfs
36d8f641af3ad942aa46aeb2f2f48472c3ac535e
extern crate rbtree; use rbtree::RBTree; use std::collections::HashMap; use std::sync::Arc; use crate::file_info::FileInfo; use common::error::Errno; use crossbeam_channel::{select, Receiver}; use log::{error, info}; use message::backend_mgr_op::ReqPiplineWriteSegmentBackendStore; use message::file_op::{MsgCloseFhFil...
extern crate rbtree; use rbtree::RBTree; use std::collections::HashMap; use std::sync::Arc; use crate::file_info::FileInfo; use common::error::Errno; use crossbeam_channel::{select, Receiver}; use log::{error, info}; use message::backend_mgr_op::ReqPiplineWriteSegmentBackendStore; use message::file_op::{MsgCloseFhFil...
}
h); let ret = self.senders_mgr.send_check_flush_to_meta(msg); if !ret.is_success() { error!("FileInfoHandler::send_flush_to_meta: failed to send flush for fh: {}, ino: {}, err: {:?}", fh, ino, ret); } }
function_block-function_prefixed
[]
Rust
pmxc_analyzer/src/lib.rs
vain0x/pattern-matching-exhaustivity-checking
400cc35696263711a09110f8c54fa5916179eeea
mod match_exhaustivity; mod syntax; use monaco::*; use std::rc::Rc; use syntax::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { fn alert(s: &str); } pub(crate) mod monaco { use serde::Serialize; pub mod editor { use super::*; #[derive(Serialize)] #[allow(unused)] ...
mod match_exhaustivity; mod syntax; use monaco::*; use std::rc::Rc; use syntax::*; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { fn alert(s: &str); } pub(crate) mod monaco { use serde::Serialize; pub mod editor { use super::*; #[derive(Serialize)] #[allow(unused)] ...
.line(), start_column: range.start().character(), end_line_number: range.end().line(), end_column: range.end().character(), }) .collect::<Vec<editor::MarkerData>>(); if !markers.is_empty() { return JsValue::from_serde(&markers).unwrap(); } let roo...
r: usize, pub end_column: usize, } } pub mod languages { use super::*; #[derive(Serialize)] pub struct State; #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct Token { pub start_index: u...
random
[ { "content": "fn gen_enum_decl(node: Rc<NodeData>) -> Option<EnumDecl> {\n\n if node.node() != Node::EnumDecl {\n\n return None;\n\n }\n\n\n\n let name_opt = node.first_ident();\n\n\n\n let ctors = node\n\n .filter_node(|child| child.node() == Node::CtorDecl)\n\n .into_iter()\n\...
Rust
rcc/src/ir/dataflow/reaching_definitions.rs
ChiangYintso/coco
f9d8a3685cbd3f2c0ee6b36e026e374dce0d99ac
use crate::analyser::sym_resolver::VarKind; use crate::ir::cfg::{BasicBlock, BasicBlockId, CFG}; use crate::ir::{IRInst, Operand, Place}; use crate::rcc::RccError; use bit_vector::BitVector; use std::collections::{HashMap, VecDeque}; pub struct ReachingDefinitionsAnalysis<'cfg> { cfg: &'cfg CFG, definitions: H...
use crate::analyser::sym_resolver::VarKind; use crate::ir::cfg::{BasicBlock, BasicBlockId, CFG}; use crate::ir::{IRInst, Operand, Place}; use crate::rcc::RccError; use bit_vector::BitVector; use std::collections::{HashMap, VecDeque}; pub struct ReachingDefinitionsAnalysis<'cfg> { cfg: &'cfg CFG, definitions: H...
; } Ok(()) } fn gen_kill(&mut self, dest: &Place, bb_id: BasicBlockId, inst_id: isize) { let out = &mut self.outs[bb_id]; if let Some(definitions) = self.definitions.get(&dest.label) { for &(definition_id, bb_id2, inst_id2) in definitions { out.set(de...
if has_definitions { Ok(()) } else { Err(RccError::from(format!( "`{}` may not have definition", place.label ))) }
if_condition
[ { "content": "/// Creates an iterator that produces tokens from the input string.\n\npub fn tokenize(mut input: String) -> Result<VecDeque<Token>, String> {\n\n let mut deque = VecDeque::new();\n\n while !input.is_empty() {\n\n let (token, len) = advance_token(&input);\n\n if token == Unknow...
Rust
src/protocols/basic.rs
songokas/clipboard-sync
82f4dda7dd478972ad1434e18bead4bea8cf2771
use log::debug; use std::net::SocketAddr; use std::sync::Arc; use std::time::Instant; use tokio::io::AsyncWriteExt; use tokio::net::TcpStream; use tokio::net::UdpSocket; use tokio::select; use tokio::time::{timeout, Duration}; use crate::defaults::{DATA_TIMEOUT, MAX_UDP_BUFFER, MAX_UDP_PAYLOAD}; use crate::errors::Con...
use log::debug; use std::net::SocketAddr; use std::sync::Arc; use std::time::Instant; use tokio::io::AsyncWriteExt; use tokio::net::TcpStream; use tokio::net::UdpSocket; use tokio::select; use tokio::time::{timeout, Duration}; use crate::defaults::{DATA_TIMEOUT, MAX_UDP_BUFFER, MAX_UDP_PAYLOAD}; use crate::errors::Con...
#[tokio::test] async fn test_data() { send_receive(5, 10).await; send_receive(16 * 1024 * 10, 16 * 1024 * 10).await; send_receive(10, 5).await; send_receive(16 * 1024 * 10, 10).await; } #[tokio::test] async fn test_timeout() { let client_str = "127....
await }), tokio::spawn(async move { send_data( client_sock, &encryptor, for_sending, &local_server, |d: Duration| d > Duration::from_millis(2000), ) ...
function_block-function_prefix_line
[ { "content": "pub fn obtain_server_socket(local_address: SocketAddr) -> Result<TcpListener, ConnectionError>\n\n{\n\n let socket = if local_address.is_ipv6() {\n\n TcpSocket::new_v6()?\n\n } else {\n\n TcpSocket::new_v4()?\n\n };\n\n socket.set_reuseaddr(true)?;\n\n #[cfg(target_os ...
Rust
src/gg20/mod.rs
leontiad/tofnd
f6786aae864a36b21e637b46caebae8844e3d1ac
use super::proto; use tokio::sync::mpsc; use tokio_stream::wrappers::UnboundedReceiverStream; use tonic::{Request, Response, Status}; pub mod proto_helpers; use tracing::{error, info, span, Level}; mod broadcast; mod key_presence; mod keygen; mod protocol; mod recover; pub mod service; mod sign; pub mod types; use ...
use super::proto; use tokio::sync::mpsc; use tokio_stream::wrappers::UnboundedReceiverStream; use tonic::{Request, Response, Status}; pub mod proto_helpers; use tracing::{error, info, span, Level}; mod broadcast; mod key_presence; mod keygen; mod protocol; mod recover; pub mod service; mod sign; pub mod types; use ...
_enter = span.enter(); let s = span.clone(); let gg20 = self.clone(); tokio::spawn(async move { if let Err(e) = gg20.handle_sign(stream, msg_sender.clone(), s).await { error!("sign failure: {:?}", e.to_string()); if let ...
(); let span = span!(Level::INFO, "Keygen"); let _enter = span.enter(); let s = span.clone(); let gg20 = self.clone(); tokio::spawn(async move { if let Err(e) = gg20.handle_keygen(stream_in, msg_sender.clone(), s).await { error!...
random
[ { "content": "/// create a new Gg20 gRPC server\n\npub fn new_service(cfg: Config, kv_manager: KvManager) -> impl proto::gg20_server::Gg20 {\n\n Gg20Service { kv_manager, cfg }\n\n}\n", "file_path": "src/gg20/service/mod.rs", "rank": 0, "score": 153522.56619606557 }, { "content": "fn gath...
Rust
src/driver/sensor/hts221/sensor.rs
lulf/drogue-device
69b26364cfe0a52abf120270a53646de0f0b0b5e
use crate::api::i2c::I2cAddress; use crate::domain::temperature::Celsius; use crate::driver::i2c::I2cPeripheral; use crate::driver::sensor::hts221::ready::DataReady; use crate::driver::sensor::hts221::register::calibration::*; use crate::driver::sensor::hts221::register::ctrl1::{BlockDataUpdate, Ctrl1, OutputDataRate};...
use crate::api::i2c::I2cAddress; use crate::domain::temperature::Celsius; use crate::driver::i2c::I2cPeripheral; use crate::driver::sensor::hts221::ready::DataReady; use crate::driver::sensor::hts221::register::calibration::*; use crate::driver::sensor::hts221::register::ctrl1::{BlockDataUpdate, Ctrl1, OutputDataRate};...
} impl<D, I> NotifyHandler<DataReady> for Sensor<D, I> where D: Device + EventHandler<SensorAcquisition<Celsius>>, I: WriteRead + Read + Write, { fn on_notify(self, message: DataReady) -> Completion<Self> { Completion::defer(async move { if self.i2c.is_some() { let i2c ...
fer(async move { if let Some(i2c) = self.i2c { if let Ok(calibration) = Calibration::read(self.address, i2c).await { self.calibration.replace(calibration); } } self }) }
function_block-function_prefixed
[ { "content": "struct OnLifecycle<A: Actor + 'static> {\n\n actor: &'static ActorContext<A>,\n\n event: Lifecycle,\n\n defer: Option<Completion<A>>,\n\n dispatched: bool,\n\n}\n\n\n\nimpl<A: Actor> OnLifecycle<A> {\n\n fn new(actor: &'static ActorContext<A>, event: Lifecycle) -> Self {\n\n ...
Rust
operators/benches/workflows.rs
koerberm/geoengine
61e0ec7a0c1136b4360b0f9c6306c34198e8ac3a
#![feature(bench_black_box)] use std::hint::black_box; use std::time::Instant; use futures::StreamExt; use geoengine_datatypes::dataset::DatasetId; use geoengine_datatypes::primitives::{Measurement, RasterQueryRectangle}; use geoengine_datatypes::raster::RasterDataType; use geoengine_datatypes::spatial_reference::Spat...
#![feature(bench_black_box)] use std::hint::black_box; use std::time::Instant; use futures::StreamExt; use geoengine_datatypes::dataset::DatasetId; use geoengine_datatypes::primitives::{Measurement, RasterQueryRectangle}; use geoengine_datatypes::raster::RasterDataType; use geoengine_datatypes::spatial_reference::Spat...
create_ndvi_meta_data(); let gdal_operator = GdalSource { params: GdalSourceParameters { dataset: id.clone(), }, }; let projection_operator = Reprojection { params: ReprojectionParams { target_spatial_reference: SpatialReference::epsg_4326(), }, ...
, spatial_resolution: SpatialResolution::new(0.01, 0.01).unwrap(), }, )]; let tiling_specs = vec![ TilingSpecification::new((0., 0.).into(), [256, 256].into()), TilingSpecification::new((0., 0.).into(), [512, 512].into()), ...
function_block-random_span
[ { "content": "// TODO: move test helper somewhere else?\n\npub fn add_ndvi_dataset(ctx: &mut MockExecutionContext) -> DatasetId {\n\n let id: DatasetId = InternalDatasetId::new().into();\n\n ctx.add_meta_data(id.clone(), Box::new(create_ndvi_meta_data()));\n\n id\n\n}\n\n\n", "file_path": "operator...
Rust
src/engine/mod.rs
stacktracehq/duck
799e0206005808c9af249898f59ecf87d2db30c5
use std::collections::HashMap; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::Arc; use std::thread::JoinHandle; use crate::builds::{Build, BuildStatus}; use crate::config::Configuration; use crate::providers::collectors::*; use crate::providers::observers::*; use crate::providers::*; use crate::utils...
use std::collections::HashMap; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::Arc; use std::thread::JoinHandle; use crate::builds::{Build, BuildStatus}; use crate::config::Configuration; use crate::providers::collectors::*; use crate::providers::observers::*; use crate::providers::*; use crate::utils...
fn propagate_to_observer(observer: &Box<dyn Observer>, observation: Observation) { match observer.observe(observation) { Result::Ok(_) => (), Result::Err(e) => { error!("An error occured when sending observation. {}", e); } }; }
function_block-full_function
[ { "content": "pub trait Collector: Send {\n\n fn info(&self) -> &CollectorInfo;\n\n fn collect(\n\n &self,\n\n handle: Arc<EventWaitHandle>,\n\n callback: &mut dyn FnMut(Build),\n\n ) -> DuckResult<()>;\n\n}\n\n\n\npub struct CollectorInfo {\n\n pub id: String,\n\n pub enable...
Rust
sourceview5/src/auto/language.rs
bilelmoussaoui/sourceview5-rs
be11d3ebd2e96a619d371ce49ceecf816baa27fb
use glib::object::ObjectType as ObjectType_; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct Language(Object<ffi::GtkSourceLanguage, ffi::GtkSourceLanguageClass>); match ...
use glib::object::ObjectType as ObjectType_; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { pub struct Language(Object<ffi::GtkSourceLanguage, ffi::GtkSourceLanguageClass>); match ...
} } pub fn connect_property_name_notify<F: Fn(&Language) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_name_trampoline<F: Fn(&Language) + 'static>( this: *mut ffi::GtkSourceLanguage, _param_spec: glib::ffi::gpointer, ...
connect_raw( self.as_ptr() as *mut _, b"notify::id\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_id_trampoline::<F> as *const (), )), Box_::into_raw(f), )
call_expression
[ { "content": "fn get_var(name: &str, default: &str) -> Result<Vec<String>, Box<dyn Error>> {\n\n match env::var(name) {\n\n Ok(value) => Ok(shell_words::split(&value)?),\n\n Err(env::VarError::NotPresent) => Ok(shell_words::split(default)?),\n\n Err(err) => Err(format!(\"{} {}\", name, e...
Rust
sdk/rust/oak_tests/src/lib.rs
rbehjati/oak
393757d2c441dab1a3f7d8bb7400f3dbffe9dbe5
use log::{debug, info}; use oak_abi::proto::oak::application::{ node_configuration::ConfigType, ApplicationConfiguration, NodeConfiguration, WebAssemblyConfiguration, }; use prost::Message; use std::{collections::HashMap, path::PathBuf, process::Command}; use tonic::transport::Certificate; pub fn compile_rus...
use log::{debug, info}; use oak_abi::proto::oak::application::{ node_configuration::ConfigType, ApplicationConfiguration, NodeConfiguration, WebAssemblyConfiguration, }; use prost::Message; use std::{collections::HashMap, path::PathBuf, process::Command}; use tonic::transport::Certificate; pub fn compile_rus...
; proxy .channel_close(rsp_read_handle) .expect("failed to close channel"); if rsp.data.is_empty() { info!("no pending message; poll again soon"); std::thread::sleep(std::time::Duration::from_millis(100)); continue; } let rsp = ...
match proxy.channel_read(rsp_read_handle) { Ok(Some(r)) => r, Ok(None) => { debug!("no pending gRPC response message; poll again soon"); std::thread::sleep(std::time::Duration::from_millis(100)); continue; } Err(e) => { ...
if_condition
[ { "content": "/// Generic function that handles request deserialization and response\n\n/// serialization (and sending down a channel) for a function that handles a\n\n/// request/response pair.\n\n///\n\n/// Panics if [de-]serialization or channel operations fail.\n\npub fn handle_req_rsp<C, R, Q>(mut node_fn:...
Rust
src/fs.rs
iwanders/playground-interp-no_std-rs
6b4fdc718dcce4d9484a7bff4ed66bc7aa2e255a
use crate::syscall; use crate::io::*; use crate::println; pub struct File { fd: u64, } impl File { pub fn create(path: &str) -> Result<Self, &'static str> { let fd = unsafe { syscall::open(path, syscall::O_CREAT | syscall::O_RDWR, 0o0640) }; if fd == 0 { return Err("Something...
use crate::syscall; use crate::io::*; use crate::println; pub struct File { fd: u64, } impl File { pub fn create(path: &str) -> Result<Self, &'static str> { let fd = unsafe { syscall::open(path, syscall::O_CREAT | syscall::O_RDWR, 0o0640) }; if fd == 0 { return Err("Something...
}
pub fn test_file_io() { let test_string = "Hello there"; { let f = File::open("/tmp/test_fs_file", "w").expect("should work?"); f.write(test_string.as_bytes()).expect("Should succeed."); } { let mut tmp_buffer: [u8; 1024] = [0; 1024];...
function_block-full_function
[ { "content": "pub fn mmap_chunk(amount: usize, prot: i32, flags: i32) -> Chunk {\n\n let p = unsafe {\n\n crate::syscall::mmap(0, amount, prot, flags | crate::syscall::MAP_ANONYMOUS, 0, 0)\n\n as *mut u8\n\n };\n\n Chunk {\n\n p,\n\n amount,\n\n is_mmap: true,\n\n...
Rust
dynamixel-tool/src/main.rs
xzz53/dynamixel-tool
9351ebaa0d03b2dfce6ada91839c9ef6a46fb440
pub mod cli; use anyhow::{anyhow, Context, Result}; use clap::CommandFactory; use clap_complete::{generate, shells::Bash}; use log::error; use std::io; use std::{convert::TryFrom, convert::TryInto, fmt::Display}; use cli::{Cli, StructOpt}; use dynamixel_utils::port; use dynamixel_utils::protocol::{self, Protocol, Pr...
pub mod cli; use anyhow::{anyhow, Context, Result}; use clap::CommandFactory; use clap_complete::{generate, shells::Bash}; use log::error; use std::io; use std::{convert::TryFrom, convert::TryInto, fmt::Display}; use cli::{Cli, StructOpt}; use dynamixel_utils::port; use dynamixel_utils::protocol::{self, Protocol, Pr...
fn cmd_write_uint32( proto: &mut dyn Protocol, ids: &[u8], address: u16, value: u32, ) -> Result<String> { ids.iter() .map(|&id| { proto .write(id, address, &value.to_le_bytes()) .with_context(|| format!("Failed to write uint32 to id {}", id)) ...
o .write(id, address, &value.to_le_bytes()) .with_context(|| format!("Failed to write uint16 to id {}", id)) }) .collect::<Result<Vec<_>, _>>() .map(|_| Ok(String::new()))? }
function_block-function_prefixed
[ { "content": "fn read1(port: &mut dyn SerialPort, id: u8, address: u16, count: u16) -> Result<Vec<u8>> {\n\n let mut buffer = [0u8; 255];\n\n let mut params = [0u8; 255];\n\n\n\n let len_write = encode_instruction_v2(\n\n &mut buffer,\n\n id,\n\n OPCODE_READ,\n\n &[address.t...
Rust
tests/src/script_tests/l2_scripts/sudt.rs
zeroqn/godwoken-scripts
984dcd67dd42ff8ae55935cad16074a694beffac
use super::{check_transfer_logs, new_block_info, run_contract, run_contract_get_result}; use gw_common::state::State; use gw_common::{h256_ext::H256Ext, H256}; use gw_generator::dummy_state::DummyState; use gw_generator::{error::TransactionError, traits::StateExt}; use gw_types::{ core::ScriptHashType, packed::...
use super::{check_transfer_logs, new_block_info, run_contract, run_contract_get_result}; use gw_common::state::State; use gw_common::{h256_ext::H256Ext, H256}; use gw_generator::dummy_state::DummyState; use gw_generator::{error::TransactionError, traits::StateExt}; use gw_types::{ core::ScriptHashType, packed::...
let return_data = run_contract( &rollup_config, &mut tree, a_id, sudt_id, args.as_bytes(), &block_info, ) .expect("execute"); let balance = { let mut buf = [0u...
let args = SUDTArgs::new_builder() .set( SUDTQuery::new_builder() .account_id(block_producer_id.pack()) .build(), ) .build();
assignment_statement
[ { "content": "pub fn build_type_id_script(name: &[u8]) -> ckb_types::packed::Script {\n\n ckb_types::packed::Script::new_builder()\n\n .code_hash(CKBPack::pack(&ALWAYS_SUCCESS_CODE_HASH.clone()))\n\n .args(CKBPack::pack(&Bytes::from(name.to_vec())))\n\n .build()\n\n}\n\n\n", "file_pa...
Rust
edb/raum/src/lib.rs
whtcorpsinc/einsteindb-prod
3b1c63a421ff37f1ca6bef4d67ef7f4c4c78a6d7
extern crate chrono; extern crate enum_set; extern crate failure; extern crate indexmap; extern crate ordered_float; extern crate uuid; extern crate allegrosql_promises; extern crate edbn; use allegrosql_promises::{ Attribute, SolitonId, KnownSolitonId, MinkowskiValueType, }; mod immuBlock_memTcam...
extern crate chrono; extern crate enum_set; extern crate failure; extern crate indexmap; extern crate ordered_float; extern crate uuid; extern crate allegrosql_promises; extern crate edbn; use allegrosql_promises::{ Attribute, SolitonId, KnownSolitonId, MinkowskiValueType, }; mod immuBlock_memTcam...
} impl HasSchemaReplicant for SchemaReplicant { fn causetid_for_type(&self, t: MinkowskiValueType) -> Option<KnownSolitonId> { self.get_causetid(&t.into_keyword()) } fn get_causetId<T>(&self, x: T) -> Option<&Keyword> where T: Into<SolitonId> { self.causetid_map.get(&x.into()) ...
pub fn update_component_attributes(&mut self) { let mut components: Vec<SolitonId>; components = self.attribute_map .iter() .filter_map(|(k, v)| if v.component { Some(*k) } else { None }) .collect(); components.sort_unsBl...
function_block-full_function
[ { "content": "/// Return 'false' if the given attribute might be used to describe a schemaReplicant attribute.\n\npub fn is_a_schemaReplicant_attribute(attribute: SolitonId) -> bool {\n\n match attribute {\n\n DB_CausetID |\n\n DB_CARDINALITY |\n\n DB_FULLTEXT |\n\n DB_INDEX |\n\n...
Rust
tests/server_test.rs
rekha-chitkara/john
0477efe104fad9279302afb42c46d9fb8c64d573
extern crate john; extern crate http; extern crate url; extern crate serialize; use john::{ClearCommand, PushCommand, PeekResult, PeekCommand}; use http::client::RequestWriter; use http::status; use url::Url; use serialize::json; fn get(url: String) -> (status::Status, String) { let parsed_url = Url::parse(url....
extern crate john; extern crate http; extern crate url; extern crate serialize; use john::{ClearCommand, PushCommand, PeekResult, PeekCommand}; use http::client::RequestWriter; use http::status; use url::Url; use serialize::json; fn get(url: String) -> (status::Status, String) { let parsed_url = Url::parse(url....
#[test] fn peek_on_empty_river_without_offset() { ClearCommand::new().execute("server_side_river"); match get(test_url("/peek/server_side_river")) { (status::NotFound, _) => {}, _ => panic!("Status should be status::NotFound") } } #[test] fn peek_on_full_river_without_offset() { Clear...
fn hello_route() { match get(test_url("/hello/world")) { (status::Ok, greeting) => assert_eq!("Hello, world!", greeting.as_slice()), _ => panic!("Status should be status::Ok") } }
function_block-full_function
[ { "content": "#[bench]\n\nfn continuous_push_to_river(b: &mut test::Bencher) {\n\n let push = john::PushCommand::new();\n\n\n\n b.iter(|| {\n\n push.execute(\"river for continuous push\", \"a huge message\");\n\n })\n\n}\n\n\n", "file_path": "tests/lib_test.rs", "rank": 3, "score": 7...
Rust
crates/accounts/src/kraken.rs
goshlanguage/mate
263dff2e13a0ceee11aa73dd8fbfcaec8858fe56
use super::traits::get::Get; use super::types::*; use krakenrs::{KrakenCredentials, KrakenRestAPI, KrakenRestConfig}; use log::info; use rust_decimal::prelude::*; use rust_decimal_macros::dec; use serde_json::{json, Map, Value}; use std::{convert::TryFrom, time::Duration}; #[derive(Clone)] pub struct KrakenAccount { ...
use super::traits::get::Get; use super::types::*; use krakenrs::{KrakenCredentials, KrakenRestAPI, KrakenRestConfig}; use log::info; use rust_decimal::prelude::*; use rust_decimal_macros::dec; use serde_json::{json, Map, Value}; use std::{convert::TryFrom, time::Duration}; #[derive(Clone)] pub struct KrakenAccount { ...
pub fn get_account_balance(&self) -> Decimal { let mut balance = dec!(0.0); let balances = self.client().get_account_balance().unwrap(); info!("Found account balances for: {:?}", balances.keys()); for key in balances.keys() { let ...
tAPI { let creds = KrakenCredentials { key: self.client_key.to_string(), secret: self.client_secret.to_string(), }; let conf = KrakenRestConfig { creds, timeout: Duration::new(30, 0), }; KrakenRestAPI::try_from(conf).expect("could...
function_block-function_prefixed
[ { "content": "/// get_creds returns the given key and secret if they are set, else checks for the existance of the vendor specific environment variables,\n\n///\n\n/// Vendor specific environment might include:\n\n/// tdameritrade: `TDA_CLIENT_ID` and `TDA_REFRESH_TOKEN`\n\n/// kraken: `KRAKEN_API_KEY` ...
Rust
engine/src/conversion/analysis/tdef.rs
clairetaylor352/autocxx
35654966c9c5b9185e1d3ec05322740996948686
use std::collections::HashSet; use autocxx_parser::IncludeCppConfig; use syn::ItemType; use crate::{ conversion::{ analysis::type_converter::{add_analysis, Annotated, TypeConversionContext, TypeConverter}, api::{AnalysisPhase, Api, ApiDetail, TypedefKind, UnanalyzedApi}, convert_error::{...
use std::collections::HashSet; use autocxx_parser::IncludeCppConfig; use syn::ItemType; use crate::{ conversion::{ analysis::type_converter::{add_analysis, Annotated, TypeConversionContext, TypeConverter}, api::{AnalysisPhase, Api, ApiDetail, TypedefKind, UnanalyzedApi}, convert_error::{...
is .into_iter() .chain(extra_apis.into_iter().chain(problem_apis).map(add_analysis)) .collect() } fn get_replacement_typedef( name: &QualifiedName, ity: ItemType, type_converter: &mut TypeConverter, extra_apis: &mut Vec<UnanalyzedApi>, deps: &mut HashSet<QualifiedName>, ) ->...
let ns = name.get_namespace(); let mut newdeps = api.deps; let detail = match api.detail { ApiDetail::ForwardDeclaration => Some(ApiDetail::ForwardDeclaration), ApiDetail::ConcreteType { rs_definition, cpp_definit...
random
[ { "content": "fn create_ignore_item(api: Api<FnAnalysis>, err: ConvertError) -> Api<FnAnalysis> {\n\n let id = api.name().get_final_ident();\n\n Api {\n\n name: api.name(),\n\n original_name: api.original_name,\n\n deps: HashSet::new(),\n\n detail: ApiDetail::IgnoredItem {\n\n ...
Rust
query/src/sql/planner/binder/select.rs
zhyass/databend
e54bef9ef4f6cb8c4a9c0b7be177f738f0cb7330
use std::sync::Arc; use async_recursion::async_recursion; use common_ast::parser::ast::Expr; use common_ast::parser::ast::Query; use common_ast::parser::ast::SelectStmt; use common_ast::parser::ast::SetExpr; use common_ast::parser::ast::TableReference; use common_exception::Result; use common_planners::ReadDataSourc...
use std::sync::Arc; use async_recursion::async_recursion; use common_ast::parser::ast::Expr; use common_ast::parser::ast::Query; use common_ast::parser::ast::SelectStmt; use common_ast::parser::ast::SetExpr; use common_ast::parser::ast::TableReference; use common_exception::Result; use common_planners::ReadDataSourc...
n.nullable, scalar: None, }; bind_context.add_column_binding(column_binding); } bind_context.expression = Some(SExpr::create_leaf(Arc::new(LogicalGet { table_index, columns: columns.into_iter().map(|col| col.column_index).collect(), ...
"".to_string(), tbl_args: None, push_downs: None, }; let table_index = self.metadata.add_table(database, table_meta, source); let mut result = self.bind_base_table(table_index).await?; if let Some(alias) = alias { ...
random
[ { "content": "fn get_description(table_info: &TableInfo, statistics: &Statistics) -> String {\n\n if statistics.read_rows > 0 {\n\n format!(\n\n \"(Read from {} table, {} Read Rows:{}, Read Bytes:{}, Partitions Scanned:{}, Partitions Total:{})\",\n\n table_info.desc,\n\n ...
Rust
src/syntax/ast.rs
timothee-haudebourg/turtle-syntax
ea73b5bed24f8171b1c2f96ff5cc013b5530e633
use std::convert::TryFrom; use ordered_float::NotNan; use crate::Loc; pub type Iri = String; pub type BlankNode = String; #[derive(Clone, Debug)] pub enum IriRef { Iri(Iri), Curie(Option<String>, String) } impl IriRef { pub fn curie_from_str(s: &str) -> IriRef { if let Some(i) = s.find(':') { ...
use std::convert::TryFrom; use ordered_float::NotNan; use crate::Loc; pub type Iri = String; pub type BlankNode = String; #[derive(Clone, Debug)] pub enum IriRef { Iri(Iri), Curie(Option<String>, String) } impl IriRef { pub fn curie_from_str(s: &str) -> IriRef { if let Some(i) = s.find(':') { ...
} let mut f = (*integer as f64 + (*decimal as f64 / (d_log10 + 1) as f64)) * 10.0f64.powf(*exp as f64); if !sign { f = -f; } Ok(grdf::Literal::Float(NotNan::new(f)?)) } } } }
Object::BlankNode(id.to_string()) } else { let (_, id) = id.split_at(1); Object::Iri(IriRef::Curie(Some(prefix.to_string()), id.to_string())) } } else { Object::Iri(IriRef::Curie(None, s.to_string())) } } } pub enum Litera...
random
[ { "content": "fn parse_verb_objects_list<L: Iterator<Item = lexer::Result<Loc<Token>>>>(lexer: &mut Peekable<L>, pos: Position) -> Result<Loc<Vec<Loc<VerbObjects>>>> {\n\n let mut span: Span = pos.into();\n\n let mut list = Vec::new();\n\n loop {\n\n if let Some(token) = peek(lexer)? {\n\n ...
Rust
tests/api/shared/api.rs
ivanovaleksey/iam
282683b4a550f1037c50d0fecc13376ec581ae63
use actix_web::{self, http, test::TestServer}; use frank_jwt; use iam; use serde::ser::Serialize; use serde_json; use uuid::Uuid; use shared::{self, IAM_ACCOUNT_ID}; pub use self::response::{BAD_REQUEST, FORBIDDEN, NOT_FOUND, UNAUTHORIZED}; pub mod request { use super::*; pub fn build_auth_request( ...
use actix_web::{self, http, test::TestServer}; use frank_jwt; use iam; use serde::ser::Serialize; use serde_json; use uuid::Uuid; use shared::{self, IAM_ACCOUNT_ID}; pub use self::response::{BAD_REQUEST, FORBIDDEN, NOT_FOUND, UNAUTHORIZED}; pub mod request { use super::*; pub fn build_auth_request( ...
builder.body(json).unwrap() } } mod response { use super::*; lazy_static! { pub static ref BAD_REQUEST: String = { let json = r#"{ "jsonrpc": "2.0", "error": { "code": 400, "message": "Bad request" ...
if let Some(account_id) = account_id { let auth_header = format!("Bearer {}", generate_iam_access_token(account_id)); builder.header(http::header::AUTHORIZATION, auth_header); }
if_condition
[ { "content": "pub fn strip_json(json: &str) -> String {\n\n json.replace('\\n', \"\")\n\n .replace(\" \", \"\")\n\n .replace(\"\\\": \", \"\\\":\")\n\n}\n", "file_path": "tests/api/shared/mod.rs", "rank": 0, "score": 351646.77411311446 }, { "content": "fn build_request(acco...
Rust
common/cosmwasm-smart-contracts/mixnet-contract/src/interval.rs
tommyv1987/nym
938eb2d0f0220a8411b6462b76480223140bc033
use serde::{Deserialize, Serialize}; use std::convert::TryInto; use std::fmt::{Display, Formatter}; use std::time::Duration; use time::OffsetDateTime; pub(crate) mod string_rfc3339_offset_date_time { use serde::de::Visitor; use serde::ser::Error; use serde::{Deserializer, Serialize, Serializer}; use ...
use serde::{Deserialize, Serialize}; use std::convert::TryInto; use std::fmt::{Display, Formatter}; use std::time::Duration; use time::OffsetDateTime; pub(crate) mod string_rfc3339_offset_date_time { use serde::de::Visitor; use serde::ser::Error; use serde::{Deserializer, Serialize, Serializer}; use ...
self.start(), self.end(), full_hours, rem ) } } #[cfg(test)] mod tests { use super::*; #[test] fn previous_interval() { let interval = Interval { id: 1, start: time::macros::datetime!(2021-08-23 12:00 UTC), ...
>) -> std::fmt::Result { let length = self.length().as_secs(); let full_hours = length / 3600; let rem = length % 3600; write!( f, "Interval {}: {} - {} ({}h {}s)", self.id,
function_block-random_span
[]
Rust
src/api/win32/mod.rs
vkahl/systray-rs
e4b3006b8720bc88155f66c1c82f17d7addf054a
mod winapipatch; use self::winapipatch::*; use crate::{SystrayError, SystrayEvent}; use std::{ self, cell::RefCell, ffi::OsStr, os::windows::ffi::OsStrExt, sync::mpsc::{channel, Sender}, thread, }; use winapi::{ self, ctypes::{c_ulong, c_ushort}, shared::{ basetsd::ULONG_PTR,...
mod winapipatch; use self::winapipatch::*; use crate::{SystrayError, SystrayEvent}; use std::{ self, cell::RefCell, ffi::OsStr, os::windows::ffi::OsStrExt, sync::mpsc::{channel, Sender}, thread, }; use winapi::{ self, ctypes::{c_ulong, c_ushort}, shared::{ basetsd::ULONG_PTR,...
pub fn set_icon_from_file(&self, icon_file: &str) -> Result<(), SystrayError> { let wstr_icon_file = to_wstring(&icon_file); let hicon; unsafe { hicon = winuser::LoadImageW( std::ptr::null_mut() as HINSTANCE, wstr_icon_file.as_ptr(), ...
pub fn set_icon_from_resource(&self, resource_name: &str) -> Result<(), SystrayError> { let icon; unsafe { icon = winuser::LoadImageW( self.info.hinstance, to_wstring(&resource_name).as_ptr(), IMAGE_ICON, 64, 64,...
function_block-full_function
[ { "content": "// Convenience function to clean up thread local unwrapping\n\nfn run_on_gtk_thread<F>(f: F)\n\nwhere\n\n F: std::ops::Fn(&GtkSystrayApp) -> () + Send + 'static,\n\n{\n\n // Note this is glib, not gtk. Calling gtk::idle_add will panic us due to\n\n // being on different threads. glib::idl...
Rust
src/event/value.rs
VJftw/vector
b2125418b19c031e68ce0da804ff08ec24117f1c
use crate::event::timestamp_to_string; use bytes::Bytes; use chrono::{DateTime, Utc}; use derive_is_enum_variant::is_enum_variant; use serde::{Serialize, Serializer}; use std::collections::BTreeMap; use std::convert::TryInto; #[derive(PartialEq, Debug, Clone, is_enum_variant)] pub enum Value { Bytes(Bytes), In...
use crate::event::timestamp_to_string; use bytes::Bytes; use chrono::{DateTime, Utc}; use derive_is_enum_variant::is_enum_variant; use serde::{Serialize, Serializer}; use std::collections::BTreeMap; use std::convert::TryInto; #[derive(PartialEq, Debug, Clone, is_enum_variant)] pub enum Value { Bytes(Bytes), In...
is test should never read Err'ing test fixtures."), }); }, _ => panic!("This test should never read Err'ing type folders."), }) } }
ytes(bytes) => bytes.clone(), Value::Timestamp(timestamp) => Bytes::from(timestamp_to_string(timestamp)), Value::Integer(num) => Bytes::from(format!("{}", num)), Value::Float(num) => Bytes::from(format!("{}", num)), Value::Boolean(b) => Bytes::from(format!("{}", b)), ...
random
[]
Rust
src/main.rs
mozkeeler/galvanize
6e2f6fb22b4e0c9c1187d9224f9dc0d13551a8ac
extern crate ring; extern crate rpassword; use ring::rand::SecureRandom; use ring::{aead, digest, error, pbkdf2, rand}; use std::env; use std::fs::{remove_file, rename, File}; use std::io::{stdin, stdout, Error, ErrorKind, Read, Write}; use std::num::NonZeroU32; fn encrypt(key: &[u8], plaintext: &[u8]) -> Result<Vec<...
extern crate ring; extern crate rpassword; use ring::rand::SecureRandom; use ring::{aead, digest, error, pbkdf2, rand}; use std::env; use std::fs::{remove_file, rename, File}; use std::io::{stdin, stdout, Error, ErrorKind, Read, Write}; use std::num::NonZeroU32; fn encrypt(key: &[u8], plaintext: &[u8]) -> Result<Vec<...
fn list_entries(entries: &[String]) { for (i, entry) in entries.iter().enumerate() { println!("{}: {}", i, entry); } } fn add_entry(entries: &mut Vec<String>) -> Result<(), Error> { Ok(entries.push(prompt("New entry")?)) } fn select_and_delete_entry(entries: &mut Vec<String>) -> Result<(), Error...
fn find_entries(entries: &[String]) -> Result<(), Error> { let term = prompt("Find")?; for (i, entry) in entries.iter().enumerate() { if entry.to_lowercase().find(&term.to_lowercase()).is_some() { println!("{}: {}", i, entry); } } Ok(()) }
function_block-full_function
[]
Rust
src/json/music.rs
compenguy/pandora-api
20dc68222ca4c8c7b41503474079852c417eb465
/*! Music support methods. */ use std::collections::HashMap; use pandora_api_derive::PandoraRequest; use serde::{Deserialize, Serialize}; use crate::errors::Error; use crate::json::{PandoraApiRequest, PandoraSession}; pub struct GetSearchRecommendationsUnsupported {} #[derive(Debug, Clone, Serialize, PandoraReques...
/*! Music support methods. */ use std::collections::HashMap; use pandora_api_derive::PandoraRequest; use serde::{Deserialize, Serialize}; use crate::errors::Error; use crate::json::{PandoraApiRequest, PandoraSession}; pub struct GetSearchRecommendationsUnsupported {} #[derive(Debug, Clone, Serialize, PandoraReques...
to look up a track to bookmark") .stations { for track in get_playlist(&mut session, &station.station_token) .await .expect("Failed completing request for playlist") .items .iter() .flat_map(|p| p.get_track()...
fault)] pub genre_stations: Vec<GenreMatch>, #[serde(flatten)] pub optional: HashMap<String, serde_json::value::Value>, } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SongMatch { pub song_name: String, pub artist_name: String, pub m...
random
[ { "content": "/// Returns the encrypted input using the given key.\n\n///\n\n/// The returned string is encoded in hexadecimal notation,\n\n/// which is a UTF-8 string, so it's fine to return it using\n\n/// the `String` type.\n\npub fn encrypt(key: &str, input: &str) -> String {\n\n let cipherbytes = cipher...
Rust
tools/kicad/kicad_functions/src/vdiv.rs
racklet/electronics-prototyping
81d913605657e897cc7579bf889cec9eb4f08474
use crate::util::err; use evalexpr::{ ContextWithMutableVariables, EvalexprError, EvalexprResult, HashMapContext, Node, Value, }; use regex::Regex; use resistor_calc::{RCalc, RRes, RSeries}; use std::cell::RefCell; use std::collections::HashSet; use std::ops::Deref; use std::panic::panic_any; fn parse_series(str: ...
use crate::util::err; use evalexpr::{ ContextWithMutableVariables, EvalexprError, EvalexprResult, HashMapContext, Node, Value, }; use regex::Regex; use resistor_calc::{RCalc, RRes, RSeries}; use std::cell::RefCell; use std::collections::HashSet; use std::ops::Deref; use std::panic::panic_any; fn parse_series(str: ...
} else { err(&format!("unsupported argument count: {}", tuple.len())) } } } fn calculate(config: &VoltageDividerConfig) -> Option<RRes> { let calc = RCalc::new(vec![config.series; config.count]); let mut context = HashMapContext::new(); if let Some(v) = &config.extra_param...
Ok(Self { target: target.as_number()?, expression, count, series: parse_series(&series.as_string()?)?, resistance_min, resistance_max, extra_parameters, })
call_expression
[ { "content": "/// Matching function for all custom functions provided by the kicad_rs evaluator\n\npub fn call_function(identifier: &str, argument: &Value) -> EvalexprResult<Value> {\n\n match identifier {\n\n \"idx\" => idx::index(argument),\n\n \"vdiv\" => vdiv::voltage_divider(argument),\n\n...
Rust
src/stash/iter.rs
RGB-WG/rgb-core
35b4c4c69a2fa350ab52143d69674425e0b89ca4
use std::collections::{btree_map, BTreeSet}; use std::slice; use bitcoin::Txid; use bp::dbc::Anchor; use commit_verify::lnpbp4; use crate::schema::{OwnedRightType, TransitionType}; use crate::{Consignment, ConsistencyError, GraphApi, Node, NodeId, Transition, TransitionBundle}; #[derive(Debug)] pub struct ChainIte...
use std::collections::{btree_map, BTreeSet}; use std::slice; use bitcoin::Txid; use bp::dbc::Anchor; use commit_verify::lnpbp4; use crate::schema::{OwnedRightType, TransitionType}; use crate::{Consignment, ConsistencyError, GraphApi, Node, NodeId, Transition, TransitionBundle}; #[derive(Debug)] pub struct ChainIte...
} impl Consignment { pub fn chain_iter(&self, start_with: NodeId, connected_by: OwnedRightType) -> ChainIter { let next_item = self .endpoint_transition_by_id(start_with) .into_iter() .next() .and_then(|_| self.transition_witness_by_...
next.map(|(anchor, bundle)| (anchor.txid, bundle.known_transitions())); if self.transitions.is_none() { return None; } } }
function_block-function_prefix_line
[ { "content": "#[cfg(feature = \"serde\")]\n\npub fn to_bech32_str<T, S>(buffer: &T, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n T: ToBech32,\n\n S: Serializer,\n\n{\n\n serializer.serialize_str(&buffer.to_bech32_string())\n\n}\n\n\n\n/// Deserializes a Bech32 to a `Vec<u8>`.\n", "file_pa...
Rust
src/layout.rs
timokroeger/kbremap
3be0e876c8c94878d9acdab67d8223f9ed022e46
const TAG_VIRTUAL_KEY: u8 = 0; const TAG_CHARACTER: u8 = 1; const TAG_MODIFIER: u8 = 2; const TAG_LAYER_LOCK: u8 = 3; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum KeyAction { Ignore, Character(char), VirtualKey(u8), } #[derive(Debug, Clone, Copy)] struct Key { scan_c...
const TAG_VIRTUAL_KEY: u8 = 0; const TAG_CHARACTER: u8 = 1; const TAG_MODIFIER: u8 = 2; const TAG_LAYER_LOCK: u8 = 3; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum KeyAction { Ignore, Character(char), VirtualKey(u8), } #[derive(Debug, Clone, Copy)] struct Key { scan_c...
}
pub fn layer_lock(&self, layer: u8) -> Option<u8> { let key = self.key_on_layer(layer)?; match key.tag { TAG_LAYER_LOCK => Some(key.action[3]), _ => None, } }
function_block-full_function
[ { "content": "pub fn send_key(key: KeyEvent) {\n\n unsafe {\n\n let mut inputs: [INPUT; 2] = mem::zeroed();\n\n\n\n let n_inputs = match key.key {\n\n KeyType::VirtualKey(vk) => {\n\n let mut kb_input = key_input_from_event(key);\n\n kb_input.wVk = vk.in...
Rust
beancount-render/src/lib.rs
matze/beancount
75f8e4b78bf4f55a4f21cdb81bd892ae985a2264
use beancount_core::*; use metadata::MetaValue; use std::borrow::Cow; use std::collections::HashMap; use std::{io, io::Write}; use thiserror::Error; #[cfg(test)] mod tests; #[derive(Copy, Clone, Eq, PartialEq, Hash, Default, Debug)] pub struct BasicRenderer {} impl BasicRenderer { pub fn new() -> Self { ...
use beancount_core::*; use metadata::MetaValue; use std::borrow::Cow; use std::collections::HashMap; use std::{io, io::Write}; use thiserror::Error; #[cfg(test)] mod tests; #[derive(Copy, Clone, Eq, PartialEq, Hash, Default, Debug)] pub struct BasicRenderer {} impl BasicRenderer { pub fn new() -> Self { ...
}
fn render( &self, incomplete_amount: &'a IncompleteAmount<'_>, w: &mut W, ) -> Result<(), Self::Error> { match (&incomplete_amount.num, &incomplete_amount.currency) { (Some(num), Some(currency)) => write!(w, "{} {}", num, currency), (None, Some(currency)) => w...
function_block-full_function
[ { "content": "#[test]\n\nfn test_note() -> anyhow::Result<()> {\n\n test_conversion(\"2013-11-03 note Liabilities:CreditCard \\\"Called about fraudulent card.\\\"\\n\")?;\n\n Ok(())\n\n}\n\n\n", "file_path": "beancount-render/src/tests.rs", "rank": 3, "score": 168717.9608855697 }, { "c...
Rust
eif_defs/src/lib.rs
costisin/aws-nitro-enclaves-cli
de77067677ef2287661063b4529e937b52115a60
#![deny(warnings)] use byteorder::{BigEndian, ByteOrder}; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use std::mem::size_of; pub const EIF_MAGIC: [u8; 4] = [46, 101, 105, 102]; pub const MAX_NUM_SECTIONS: usize = 32; pub const EIF_HDR_ARCH_ARM64: u16 = 0x1; ...
#![deny(warnings)] use byteorder::{BigEndian, ByteOrder}; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; use std::mem::size_of; pub const EIF_MAGIC: [u8; 4] = [46, 101, 105, 102]; pub const MAX_NUM_SECTIONS: usize = 32; pub const EIF_HDR_ARCH_ARM64: u16 = 0x1; ...
} #[derive(Clone, Copy, Debug, FromPrimitive, PartialEq)] #[repr(u16)] pub enum EifSectionType { EifSectionInvalid, EifSectionKernel, EifSectionCmdline, EifSectionRamdisk, EifSectionSignature, } #[derive(Clone, Copy, Debug)] pub struct EifSectionHeader { pub section_type: EifSectionType, ...
pub const fn size() -> usize { 4 * size_of::<u16>() + 2 * size_of::<u32>() + 2 * size_of::<u64>() + size_of::<[u8; 4]>() + 2 * size_of::<[u64; MAX_NUM_SECTIONS]>() }
function_block-full_function
[ { "content": "pub fn recv_loop(fd: RawFd, buf: &mut [u8], len: u64) -> Result<(), String> {\n\n let len: usize = len.try_into().map_err(|err| format!(\"{:?}\", err))?;\n\n let mut recv_bytes = 0;\n\n\n\n while recv_bytes < len {\n\n let size = match recv(fd, &mut buf[recv_bytes..len], MsgFlags::...
Rust
solana-programs/reward-manager/cli/src/utils.rs
Tenderize/audius-protocol
aa15844e3f12812fe8aaa81e2cb6e5c5fa89ff51
use crate::{Config, Error}; use regex::Regex; use serde::Deserialize; use sha3::Digest; use solana_program::instruction::Instruction; use solana_sdk::{ native_token::lamports_to_sol, secp256k1_instruction::{ construct_eth_pubkey, SecpSignatureOffsets, DATA_START, SIGNATURE_SERIALIZED_SIZE, }, s...
use crate::{Config, Error}; use regex::Regex; use serde::Deserialize; use sha3::Digest; use solana_program::instruction::Instruction; use solana_sdk::{ native_token::lamports_to_sol, secp256k1_instruction::{ construct_eth_pubkey, SecpSignatureOffsets, DATA_START, SIGNATURE_SERIALIZED_SIZE, }, s...
ecent_blockhash()?; check_fee_payer_balance( config, fee_calculator.calculate_fee(&transaction.message()) + additional_balance_required, )?; transaction.sign(&self.signers, recent_blockhash); Ok(Some(transaction)) } } pub fn sign_message(message: &[u8], sig...
action>, Error> { let mut transaction = OnchainTransaction::new_with_payer( self.instructions.as_ref(), Some(&config.fee_payer.pubkey()), ); let (recent_blockhash, fee_calculator) = config.rpc_client.get_r
random
[]
Rust
johan-oelrich-rust/day08/src/a.rs
joelfak/advent_of_code_2019
d5031078c53c181835b4bf86458b360542f0122e
pub fn run() -> String { let data = loader::load_as("./day/08/input.csv", |l| l).collect::<Vec<String>>()[0].clone(); let image = Image::from_string(25, 6, data); write_image(&image); "whee!".to_owned() } fn write_image(image: &Image) { let composit = image.merge(); for ih in 0..image.height { for iw i...
pub fn run() -> String { let data = loader::load_as("./day/08/input.csv", |l| l).collect::<Vec<String>>()[0].clone(); let image = Image::from_string(25, 6, data); write_image(&image); "whee!".to_owned() } fn write_image(image: &Image) { let composit = image.merge(); for ih in 0..image.height { for iw i...
#[test] fn image_3() { let data = loader::load_as("../day/08/input.csv", |l| l).collect::<Vec<String>>()[0].clone(); let image = Image::from_string(25, 6, data); let layer = image.layers_with_fewest(0).pop().unwrap(); assert_eq!(layer.count(1), 17); } #[test] fn image_4() { let data = loa...
fn image_2() { let data = loader::load_as("../day/08/input.csv", |l| l).collect::<Vec<String>>()[0].clone(); let image = Image::from_string(25, 6, data); let layers = image.layers_with_fewest(0); assert_eq!(layers.len(), 1); }
function_block-full_function
[ { "content": "pub fn run() -> String {\n\n format!(\"{}\", wire::solve_day03b())\n\n}\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n fn truth() {\n\n let actual = wire::solve_day03b();\n\n\n\n assert_eq!(actual, 7534);\n\n }\n\n}\n", "file_path": "johan-oelrich-rust/day03/src/b.rs", "rank": 1,...
Rust
src/main.rs
AltSysrq/hexeline
fe727eed0b195fef01fc4e26a0c27995eeb579d9
#![cfg_attr(not(test), allow(unused_features))] #![feature(test, platform_intrinsics, core_intrinsics, repr_simd, stdsimd)] #![allow(dead_code)] extern crate arc_swap; extern crate arrayvec; extern crate bit_set; #[macro_use] extern crate bitflags; extern crate cgmath as cg; extern crate env_logger; extern crate gl;...
#![cfg_attr(not(test), allow(unused_features))] #![feature(test, platform_intrinsics, core_intrinsics, repr_simd, stdsimd)] #![allow(dead_code)] extern crate arc_swap; extern crate arrayvec; extern crate bit_set; #[macro_use] extern crate bitflags; extern crate cgmath as cg; extern crate env_logger; extern crate gl;...
, y: 1.0 } }, ]; let vbo = Vbo::<vert::Pos2Tc2>::new(gl::ARRAY_BUFFER).unwrap(); let vbo_active = vbo.activate(); vbo_active.data(&vertices, gl::STREAM_DRAW); let vao = Vao::new(&shaders.texture, &vbo_active).unwrap(); texture.bind(); let uniform = uni::MTex { matrix: *matrix, ...
creen.drawable_size().0 as GLsizei, screen.drawable_size().1 as GLsizei); } let projection_matrix = cg::ortho::<f32>(0.0, screen.drawable_size().0 as f32, screen.drawable_size().1 as f32, 0.0, -1.0, 1.0); let ...
random
[ { "content": "// We may want something more sophisticated than nearest scaling. For now, use\n\n// the simplest thing that works.\n\nfn scale_half(px: &[u32], w: &mut u32, pitch: &mut u32, h: &mut u32)\n\n -> Vec<u32> {\n\n let nw = max(1, *w / 2);\n\n let nh = max(1, *h / 2);\n\n let mut ...
Rust
src/keyparser.rs
johanot/concealed
1c849a4429c6679305f1c65b5f2071268f6b8721
use chrono::prelude::*; use lazy_static::lazy_static; use regex::Regex; use std::cmp::Ordering; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use std::string::ToString; use strum::EnumString; use strum::ToString; use walkdir::WalkD...
use chrono::prelude::*; use lazy_static::lazy_static; use regex::Regex; use std::cmp::Ordering; use std::collections::HashMap; use std::fs::File; use std::io::prelude::*; use std::io::{BufRead, BufReader}; use std::path::PathBuf; use std::string::ToString; use strum::EnumString; use strum::ToString; use walkdir::WalkD...
".to_string(), }; let priv_key = Secret { name: "foo.private".to_string(), value: "not important for this test".to_string(), }; println!("{:?}", &parse(&pub_key, &priv_key).unwrap()); } } /* Example key below ; This is a zone-signing key, keyid 44426, for f...
, &base_name]) } None => child.args(&[ "-a", "RSASHA512", "-b", &bits.to_string(), "-n", "ZONE", zone, ]), }; child.spawn_ok()?.wait()?; old_pub_key_path.map(|p| fs::remove_file(p).unwrap()); ol...
random
[ { "content": "fn render_zonefile(name: &str, zone: &Zone, serial: u32) -> (String, String) {\n\n\n\n #[derive(Template)]\n\n #[template(path = \"template.zone\", escape = \"none\")]\n\n struct ZoneTemplate<'a> {\n\n name: &'a str,\n\n zone: &'a Zone,\n\n serial: u32,\n\n }\n\n\n...
Rust
src/main.rs
masterkoppa/media-server-diff
484e4106cb89c585062752e95fe0088c84b40924
extern crate clap; extern crate ffmpeg_next as ffmpeg; extern crate walkdir; use clap::Parser; use rayon::prelude::*; use std::path::PathBuf; use std::time::Duration; use tracing::{debug, info, instrument, warn}; use walkdir::{DirEntry, WalkDir}; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = No...
extern crate clap; extern crate ffmpeg_next as ffmpeg; extern crate walkdir; use clap::Parser; use rayon::prelude::*; use std::path::PathBuf; use std::time::Duration; use tracing::{debug, info, instrument, warn}; use walkdir::{DirEntry, WalkDir}; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = No...
#[test] fn test_hours_format() { let hours = Duration::from_secs(28797); assert_eq!(format_duration(&hours), String::from("07:59:57")); let single_hour = Duration::from_secs(60 * 60); assert_eq!(format_duration(&single_hour), String::from("01:00:00")); } #[test] f...
t_duration(&days), String::from("01:07:59:57")); let single_day = Duration::from_secs(60 * 60 * 24); assert_eq!(format_duration(&single_day), String::from("01:00:00:00")); }
function_block-function_prefixed
[]
Rust
src/markdown.rs
stevelr/mdsite
62a44804d0c1e289ddfba8fcfc94d762d4c8d32d
use crate::{Error, Result, TomlMap}; use serde::{de::DeserializeOwned, Serialize}; use toml::value::Value; pub(crate) const TOML_START: &str = "+++\n"; pub(crate) const TOML_END: &str = "\n+++\n"; pub(crate) const YAML_START: &str = "---\n"; pub(crate) const YAML_END: &str = "\n---\n"; #[derive(Debug, PartialEq)] p...
use crate::{Error, Result, TomlMap}; use serde::{de::DeserializeOwned, Serialize}; use toml::value::Value; pub(crate) const TOML_START: &str = "+++\n"; pub(crate) const TOML_END: &str = "\n+++\n"; pub(crate) const YAML_START: &str = "---\n"; pub(crate) const YAML_END: &str = "\n---\n"; #[derive(Debug, PartialEq)] p...
assert_eq!(body, "hello"); let (front, body) = split_markdown("---\nthing: one\n---\n"); assert_eq!(front, Frontmatter::Yaml("thing: one")); assert_eq!(body, ""); let (front, body) = split_markdown("---\n \n---\n\n hello \n"); assert_eq!(front, Frontmatter::Empty); assert_eq!...
md> { Toml(&'md str), Yaml(&'md str), Empty, } impl<'md> Frontmatter<'md> { pub fn is_empty(&self) -> bool { matches!(self, Self::Empty) } pub fn parse<T: DeserializeOwned>(&self) -> Result<T> { match self { Self::Toml(buf) => { Ok(toml::fro...
random
[ { "content": "/// Parse content markdown and generate html, with optional generation of TOC\n\n/// Markdown parameter should not have frontmatter\n\npub fn markdown_to_html(markdown_in: &str) -> Result<ParseResult> {\n\n use pulldown_cmark::CowStr;\n\n let mut enable_toc = false;\n\n\n\n let mut option...
Rust
src/routes.rs
crisidev/qrsync
2163ddd9e8e3d9a840beffb877c0f87efe03df2f
use std::fs; use std::path::{Path, PathBuf}; use std::str; use rocket::http::ContentType; use rocket::response::content::{Css, Html, Plain}; use rocket::response::{Redirect, Responder, Result as RocketResult}; use rocket::{Data, Request, State}; use rocket_download_response::DownloadResponse; use rocket_multipart_fo...
use std::fs; use std::path::{Path, PathBuf}; use std::str; use rocket::http::ContentType; use rocket::response::content::{Css, Html, Plain}; use rocket::response::{Redirect, Responder, Result as RocketResult}; use rocket::{Data, Request, State}; use rocket_download_response::DownloadResponse; use rocket_multipart_fo...
} } #[get("/<file_name>")] pub fn get_send(file_name: String, state: State<RequestCtx>) -> Result<DownloadResponse, Redirect> { match state.download_file(file_name) { Ok(data) => Ok(data), Err(_) => Err(Redirect::found("/error")), } } #[post("/receive", format = "multipart/form-data", dat...
match fs::copy(src, dst) { Ok(_) => info!( "Received file with content-type {} stored in {}", content_type, dst.display() ), Err(e) => error!( "Unable to store file {} to {}: {}", self.file_name ...
if_condition
[ { "content": "\n\nimpl QrSyncError {\n\n pub fn new(message: &str, kind: Option<&str>) -> QrSyncError {\n\n let kind_value = kind.unwrap_or(\"qrsync\");\n\n QrSyncError {\n\n kind: String::from(kind_value),\n\n message: message.to_string(),\n\n }\n\n }\n\n}\n\n\n...
Rust
rust/xaynet-server/src/storage/store.rs
Robert-Steiner/xaynet
63ea2ac8b2793ada3b2f16cddecab808a2d77369
use async_trait::async_trait; use crate::{ state_machine::coordinator::CoordinatorState, storage::{ CoordinatorStorage, LocalSeedDictAdd, MaskScoreIncr, ModelStorage, StorageResult, SumPartAdd, }, }; use xaynet_core::{ common::RoundSeed, mask::{Mask...
use async_trait::async_trait; use crate::{ state_machine::coordinator::CoordinatorState, storage::{ CoordinatorStorage, LocalSeedDictAdd, MaskScoreIncr, ModelStorage, StorageResult, SumPartAdd, }, }; use xaynet_core::{ common::RoundSeed, mask::{Mask...
async fn sum_dict(&mut self) -> StorageResult<Option<SumDict>> { self.coordinator.sum_dict().await } async fn add_local_seed_dict( &mut self, update_pk: &UpdateParticipantPublicKey, local_seed_dict: &LocalSeedDict, ) -> StorageResult<LocalSeedDictAdd> { self.co...
async fn add_sum_participant( &mut self, pk: &SumParticipantPublicKey, ephm_pk: &SumParticipantEphemeralPublicKey, ) -> StorageResult<SumPartAdd> { self.coordinator.add_sum_participant(pk, ephm_pk).await }
function_block-full_function
[ { "content": "pub fn coordinator_state() -> CoordinatorState {\n\n CoordinatorState::new(pet_settings(), mask_settings(), model_settings())\n\n}\n\n\n", "file_path": "rust/xaynet-server/src/state_machine/tests/utils.rs", "rank": 0, "score": 216154.1274924237 }, { "content": "#[cfg(feature...
Rust
src/plonk/better_cs/verifier.rs
matterinc/bellman
07480cfdd215d23d7985f808124a70d3eb9f0b6d
use crate::pairing::ff::{Field, PrimeField}; use crate::pairing::{Engine}; use crate::{SynthesisError}; use crate::plonk::polynomials::*; use crate::worker::Worker; use crate::plonk::domains::*; use std::marker::PhantomData; use super::cs::*; use super::keys::{Proof, VerificationKey}; use crate::source::{DensityTra...
use crate::pairing::ff::{Field, PrimeField}; use crate::pairing::{Engine}; use crate::{SynthesisError}; use crate::plonk::polynomials::*; use crate::worker::Worker; use crate::plonk::domains::*; use std::marker::PhantomData; use super::cs::*; use super::keys::{Proof, VerificationKey}; use crate::source::{DensityTra...
pub fn verify_and_aggregate<E: Engine, P: PlonkConstraintSystemParams<E>, T: Transcript<E::Fr>>( proof: &Proof<E, P>, verification_key: &VerificationKey<E, P>, transcript_init_params: Option< <T as Prng<E::Fr> >:: InitializationParameters>, ) -> Result<(bool, [E::G1Affine; 2]), SynthesisError> { use c...
ationKey<E, P>, transcript_init_params: Option< <T as Prng<E::Fr> >:: InitializationParameters>, ) -> Result<bool, SynthesisError> { let (valid, _) = verify_and_aggregate::<E, P, T>(proof, verification_key, transcript_init_params)?; Ok(valid) }
function_block-function_prefixed
[ { "content": "pub fn make_verification_key<E: Engine, P: PlonkConstraintSystemParams<E>>(\n\n setup: &SetupPolynomials<E, P>,\n\n crs: &Crs<E, CrsForMonomialForm>\n\n) -> Result<VerificationKey<E, P>, SynthesisError> {\n\n let worker = Worker::new();\n\n\n\n let verification_key = VerificationKey::f...
Rust
src/main.rs
Celeo/bless_you_bot
ccd6c737fd17e0770728674244e5f3b18caff461
use log::{debug, error, info}; use once_cell::sync::Lazy; use regex::Regex; use serenity::{ model::{channel::Message, gateway::Ready}, prelude::*, }; use std::{env, path::Path, process}; const WORDS_FILE_RAW: &str = include_str!(concat!(env!("OUT_DIR"), "/words_alpha.txt")); const MINIMUM_MESSAGE_LENGTH: usize...
use log::{debug, error, info}; use once_cell::sync::Lazy; use regex::Regex; use serenity::{ model::{channel::Message, gateway::Ready}, prelude::*, }; use std::{env, path::Path, process}; const WORDS_FILE_RAW: &str = include_str!(concat!(env!("OUT_DIR"), "/words_alpha.txt")); const MINIMUM_MESSAGE_LENGTH: usize...
debug!("Token loaded from environment variable"); let mut client = Client::builder(&token) .event_handler(Handler) .await .expect("Could not create client"); debug!("Bot set up"); if let Err(e) = client.start().await { error!("Error starting client: {}", e); } } #...
let token = match env::var("DISCORD_TOKEN") { Ok(t) => t, Err(_) => { error!("Environment variable 'DISCORD_TOKEN' is not set"); process::exit(1); } };
assignment_statement
[ { "content": "fn main() -> Result<(), Error> {\n\n let words_dir = Path::new(ENGLISH_WORDS_DIR);\n\n if !words_dir.exists() {\n\n eprintln!(\n\n \"'{}' directory not found, init git submodules\",\n\n ENGLISH_WORDS_DIR\n\n );\n\n exit(1);\n\n }\n\n let words...
Rust
src/streaming_kzg/tests.rs
huyuncong/poly-commit
aff482a76fa8dd562a4f2817e798d4e61499d48f
use ark_bls12_381::{Bls12_381, Fr}; use ark_poly::univariate::DensePolynomial; use ark_poly::UVPolynomial; use ark_std::vec::Vec; use ark_std::{UniformRand, Zero}; use crate::streaming_kzg::space::CommitterKeyStream; use crate::streaming_kzg::time::CommitterKey; use crate::streaming_kzg::{vanishing_polynomial, Verifie...
use ark_bls12_381::{Bls12_381, Fr}; use ark_poly::univariate::DensePolynomial; use ark_poly::UVPolynomial; use ark_std::vec::Vec; use ark_std::{UniformRand, Zero}; use crate::streaming_kzg::space::CommitterKeyStream; use crate::streaming_kzg::time::CommitterKey; use crate::streaming_kzg::{vanishing_polynomial, Verifie...
fn test_open_multi_points() { use crate::ark_std::UniformRand; use ark_bls12_381::{Bls12_381, Fr}; use ark_ff::Field; use ark_poly::univariate::DensePolynomial; use ark_poly::UVPolynomial; use ark_std::test_rng; let max_msm_buffer = 1 << 20; let rng = &mut test_rng(); let polyn...
function_block-full_function
[ { "content": "fn skip_leading_zeros_and_convert_to_bigints<F: PrimeField, P: UVPolynomial<F>>(\n\n p: &P,\n\n) -> (usize, Vec<F::BigInt>) {\n\n let mut num_leading_zeros = 0;\n\n while num_leading_zeros < p.coeffs().len() && p.coeffs()[num_leading_zeros].is_zero() {\n\n num_leading_zeros += 1;\n...
Rust
rpfm_lib/src/packedfile/unit_variant/mod.rs
im-mortal/rpfm
9956993c807959ab26d2b34a7b0ed60150d25bc4
/*! Module with all the code to interact with binary Unit Variants. Binary unit variants are the unit variants used from Empire to Shogun 2. !*/ use serde_derive::{Serialize, Deserialize}; use rpfm_error::{ErrorKind, Result}; use rpfm_macros::{GetRef, GetRefMut, Set}; use crate::common::{decoder::Decoder, encoder...
/*! Module with all the code to interact with binary Unit Variants. Binary unit variants are the unit variants used from Empire to Shogun 2. !*/ use serde_derive::{Serialize, Deserialize}; use rpfm_error::{ErrorKind, Result}; use rpfm_macros::{GetRef, GetRefMut, Set}; use crate::common::{decoder::Decoder, encoder...
pub fn read_header(packed_file_data: &[u8], mut index: &mut usize) -> Result<(u32, u32, u32)> { if let Ok(signature) = packed_file_data.decode_string_u8(0, SIGNATURE.len()) { if signature != SIGNATURE { return Err(ErrorKind::PackedFileIsNotUnitVariant.into()) }...
pub fn read(packed_file_data: &[u8]) -> Result<Self> { let mut index = SIGNATURE.len(); let (version, categories_count, unknown_1) = Self::read_header(packed_file_data, &mut index)?; let mut categories = vec![]; for _ in 0..categories_count { let (name, _) = packed...
function_block-full_function
[ { "content": "/// This function parses strings to booleans, properly.\n\npub fn parse_str_as_bool(string: &str) -> Result<bool> {\n\n let str_lower_case = string.to_lowercase();\n\n if str_lower_case == \"true\" || str_lower_case == \"1\" {\n\n Ok(true)\n\n }\n\n else if str_lower_case == \"f...
Rust
lowering/src/lir/gen_instr.rs
comprakt/comprakt
2315e85972e63ea327c4d115ffe623253b520440
use super::*; use libfirm_rs::{ nodes::{Node, NodeTrait, ProjKind}, types::{Ty, TyTrait}, Entity, }; use std::{collections::HashSet, convert::TryInto}; pub struct GenInstrBlock { visisted: HashSet<Node>, graph: Ptr<BlockGraph>, body: Vec<Instruction>, leave: Vec<Leave>, } impl GenInstrBloc...
use super::*; use libfirm_rs::{ nodes::{Node, NodeTrait, ProjKind}, types::{Ty, TyTrait}, Entity, }; use std::{collections::HashSet, convert::TryInto}; pub struct GenInstrBlock { visisted: HashSet<Node>, graph: Ptr<BlockGraph>, body: Vec<Instruction>, leave: Vec<Leave>, } impl GenInstrBloc...
} #[allow(clippy::cyclomatic_complexity)] fn gen_value_walk_callback( &mut self, graph: Ptr<BlockGraph>, block: Ptr<B...
match node { Node::Const(c) => Operand::Imm(c.tarval()), Node::Size(s) => Operand::Imm(libfirm_rs::Tarval::mj_size(i64::from(s.ty().size()))), n => Operand::Var(self.gen_dst_var(n)), }
if_condition
[ { "content": "pub fn label_with_dom_info(graph: Graph, node: &Node, highlight: &Node) -> Label {\n\n // TODO: no side effects in debug code\n\n graph.assure_loopinfo();\n\n\n\n let mut label = dom_info_box(node);\n\n\n\n let highlight_block = if let Node::Block(block) = highlight {\n\n *block...
Rust
src/lib.rs
JoshPiper/gm_environ
872f63ceb31c02b61fa313cc5d074b9c0efa5fc4
#![feature(c_unwind)] use std::collections::HashMap; use std::env; #[cfg(feature = "gmcl")] use gmod::gmcl::override_stdout; use gmod::lua::{State}; use gmod::lua_function; use lazy_static::lazy_static; #[macro_use] extern crate gmod; #[macro_use] extern crate debug_print; #[cfg(not(windows))] const PATH_SEP: &str =...
#![feature(c_unwind)] use std::collections::HashMap; use std::env; #[cfg(feature = "gmcl")] use gmod::gmcl::override_stdout; use gmod::lua::{State}; use gmod::lua_function; use lazy_static::lazy_static; #[macro_use] extern crate gmod; #[macro_use] extern crate debug_print; #[cfg(not(windows))] const PATH_SEP: &str =...
1 } }; rtn } unsafe fn push_table(lua: State, split: Vec<&str>){ lua.create_table(split.len() as i32, 0); let mut i = 0; for s in split { let s = s.trim(); if s != "" { i += 1; lua.push_string(s); lua.raw_seti(-2, i); ...
match env_var { Ok(val) => { debug_println!("{} -> {}: {}", env!("CARGO_CRATE_NAME"), str_idx, val); lua.push_string(val.as_str()) } Err(err) => { debug_println!("{} -> {} failed: {}", env!("CARGO_CRATE_NAME"), s...
if_condition
[ { "content": "# gm_environ\n\n\n\nUsing Environment Variables in Garry's Mod.\n\n\n\n## Installation\n\n\n\nDownload a copy of the module from the releases (or compile from source)\n\nMove the downloaded file to `<Garry's Mod Installation>/lua/bin/gm<state>_environ_<platform>.dll`\n\n\n\nState can be either cl ...
Rust
src/completion/completers.rs
zzeroo/mg
87821ee43f1ac9505f15468db6301aa1c1c465a9
/* * Copyright (c) 2016 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy,...
/* * Copyright (c) 2016 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy,...
setting_values: T::get_value_completions(), _phantom: PhantomData, } } } impl<T> Completer for SettingCompleter<T> { fn complete_result(&self, value: &str) -> String { if let Some(ref name) = self.selected_name { format!("set {} = {}", name, value) } els...
d, ref help)| command.to_lowercase().contains(&input) || help.to_lowercase().contains(&input)) .map(|&(ref col1, ref col2)| CompletionResult::new(&[col1, col2])) .collect() } } pub struct NoCompleter { } impl NoCompleter { #[allow(unknown_lints, ...
random
[ { "content": "/// Convert a shortcut of keys to a `String`.\n\npub fn shortcut_to_string(keys: &[Key], show_count: bool) -> String {\n\n if show_count {\n\n let strings: Vec<_> = keys.iter().map(ToString::to_string).collect();\n\n strings.join(\"\")\n\n }\n\n else {\n\n String::new...