lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
src/checkpoint.rs
resin-io-modules/libnm-rs
0183a43fc26506895868aaa3921bb38fb7a5b2bf
#[cfg(any(feature = "v1_12", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_12")))] use crate::Device; use crate::Object; #[cfg(any(feature = "v1_12", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_12")))] use glib::object::ObjectType as ObjectType_; #[cfg(any(feature = "v1...
#[cfg(any(feature = "v1_12", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_12")))] use crate::Device; use crate::Object; #[cfg(any(feature = "v1_12", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_12")))] use glib::object::ObjectType as ObjectType_; #[cfg(any(feature = "v1...
eated_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_created_trampoline<F: Fn(&Checkpoint) + 'static>( this: *mut ffi::NMCheckpoint, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(...
fg_attr(feature = "dox", doc(cfg(feature = "v1_12")))] #[doc(alias = "nm_checkpoint_get_rollback_timeout")] #[doc(alias = "get_rollback_timeout")] pub fn rollback_timeout(&self) -> u32 { unsafe { ffi::nm_checkpoint_get_rollback_timeout(self.to_glib_none().0) } } #[cfg(any(feature = "v1_12",...
random
[ { "content": "#[doc(alias = \"nm_utils_get_timestamp_msec\")]\n\npub fn utils_get_timestamp_msec() -> i64 {\n\n unsafe { ffi::nm_utils_get_timestamp_msec() }\n\n}\n\n\n\n/// Converts a hexadecimal string `hex` into an array of bytes. The optional\n\n/// separator ':' may be used between single or pairs of he...
Rust
src/core/ton_wallet/highload_wallet_v2.rs
broxus/nekoton
1c54cc64a2b4b266a9ba8b677fbf7542bc13bd2a
use std::convert::TryFrom; use anyhow::Result; use ed25519_dalek::PublicKey; use ton_block::{MsgAddrStd, MsgAddressInt, Serializable}; use ton_types::{BuilderData, Cell, IBitstring, SliceData, UInt256}; use nekoton_utils::*; use super::{TonWalletDetails, TransferAction}; use crate::core::models::{Expiration, ExpireA...
use std::convert::TryFrom; use anyhow::Result; use ed25519_dalek::PublicKey; use ton_block::{MsgAddrStd, MsgAddressInt, Serializable}; use ton_types::{BuilderData, Cell, IBitstring, SliceData, UInt256}; use nekoton_utils::*; use super::{TonWalletDetails, TransferAction}; use crate::core::models::{Expiration, ExpireA...
> { Ok(SignedMessage { message: self.message.clone(), expire_at: self.expire_at(), }) } } pub fn prepare_transfer( clock: &dyn Clock, public_key: &PublicKey, current_state: &ton_block::AccountStuff, gifts: Vec<Gift>, expiration: Expiration, ) -> Result<Tr...
e = ton_block::Message::with_ext_in_header(ton_block::ExternalInboundMessageHeader { dst, ..Default::default() }); message.set_state_init(init_data.make_state_init()?); let expire_at = ExpireAt::new(clock, expiration); let (hash, payload) = init_data.make_deploy_pay...
random
[ { "content": "pub fn compute_contract_address(public_key: &PublicKey, workchain_id: i8) -> MsgAddressInt {\n\n InitData::from_key(public_key)\n\n .with_wallet_id(WALLET_ID)\n\n .compute_addr(workchain_id)\n\n .trust_me()\n\n}\n\n\n\npub static DETAILS: TonWalletDetails = TonWalletDetails...
Rust
whitebox-tools-app/src/tools/data_tools/new_raster.rs
basaks/whitebox-tools
36c721da4201ff795eaf3fb679a6dc95e7083ba5
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: 11/07/2017 Last Modified: 27/08/2021 License: MIT */ use whitebox_raster::*; use crate::tools::*; use std::env; use std::f64; use std::io::{Error, ErrorKind}; use std::path; use whitebox_vector::Shapefile; pub st...
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay Created: 11/07/2017 Last Modified: 27/08/2021 License: MIT */ use whitebox_raster::*; use crate::tools::*; use std::env; use std::f64; use std::io::{Error, ErrorKind}; use std::path; use whitebox_vector::Shapefile; pub st...
}
n() { let mut arg = args[i].replace("\"", ""); arg = arg.replace("\'", ""); let cmd = arg.split("="); let vec = cmd.collect::<Vec<&str>>(); let mut keyval = false; if vec.len() > 1 { keyval = true; } let fla...
function_block-function_prefixed
[ { "content": "fn run(args: &Vec<String>) -> Result<(), std::io::Error> {\n\n let tool_name = get_tool_name();\n\n\n\n let sep: String = path::MAIN_SEPARATOR.to_string();\n\n\n\n // Read in the environment variables and get the necessary values\n\n let configurations = whitebox_common::configs::get_c...
Rust
core/library/src/communication/implementation/mock/requestor.rs
TilBlechschmidt/WebGrid
5d4512865631801144f966c1e9aeea6cbdb7598a
use crate::communication::event::QueueDescriptor; use crate::communication::request::{Request, RequestError, Requestor, ResponseCollectionTimeout}; use async_trait::async_trait; use pretty_assertions::assert_eq; use serde_json::Value; use std::collections::VecDeque; use std::sync::atomic::{AtomicUsize, Ordering}; use s...
use crate::communication::event::QueueDescriptor; use crate::communication::request::{Request, RequestError, Requestor, ResponseCollectionTimeout}; use async_trait::async_trait; use pretty_assertions::assert_eq; use serde_json::Value; use std::collections::VecDeque; use std::sync::atomic::{AtomicUsize, Ordering}; use s...
} } #[cfg(test)] mod does { use super::*; use crate::communication::event::Notification; use crate::communication::request::ResponseLocation; use pretty_assertions::assert_eq; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy)] struct ...
if !std::thread::panicking() { let remaining = self.remaining.load(Ordering::SeqCst); assert!( remaining == 0, "MockRequestor was dropped with {} expected requests remaining", remaining ); }
if_condition
[ { "content": "pub fn with_endpoint(endpoint: &str) -> Result<impl Collect + Send + Sync + 'static, TraceError> {\n\n global::set_text_map_propagator(TraceContextPropagator::new());\n\n\n\n let resource: Vec<KeyValue> = vec![\n\n semcov::resource::SERVICE_NAME.string(std::env::var(\"ID\").unwrap()),...
Rust
ironrdp/src/rdp/server_license/server_license_request/cert.rs
dheater/IronRDP
0ae846b6c3196496fb3ff049b7b896dec484c120
use std::io; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use super::{BlobHeader, BlobType, ServerLicenseError, KEY_EXCHANGE_ALGORITHM_RSA}; use crate::PduParsing; pub const SIGNATURE_ALGORITHM_RSA: u32 = 1; pub const PROP_CERT_NO_BLOBS_SIZE: usize = 8; pub const PROP_CERT_BLOBS_HEADERS_SIZE: usize = ...
use std::io; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use super::{BlobHeader, BlobType, ServerLicenseError, KEY_EXCHANGE_ALGORITHM_RSA}; use crate::PduParsing; pub const SIGNATURE_ALGORITHM_RSA: u32 = 1; pub const PROP_CERT_NO_BLOBS_SIZE: usize = 8; pub const PROP_CERT_BLOBS_HEADERS_SIZE: usize = ...
_SIZE) .sum(); let padding: usize = 8 + 4 * self.certificate_array.len(); X509_CERT_COUNT + certificates_length + padding } } #[derive(Debug, PartialEq)] pub struct ProprietaryCertificate { pub public_key: RsaPublicKey, pub signature: Vec<u8>, } impl PduParsing for ProprietaryC...
()?; if certificate_len > MAX_CERTIFICATE_LEN { return Err(ServerLicenseError::InvalidCertificateLength(certificate_len)); } let mut certificate = vec![0u8; certificate_len as usize]; stream.read_exact(&mut certificate)?; ...
random
[ { "content": "pub fn write_u32(mut stream: impl io::Write, value: u32) -> io::Result<usize> {\n\n if value <= 0xff {\n\n let size = write_length(&mut stream, 1)?;\n\n stream.write_u8(value as u8)?;\n\n\n\n Ok(size + 1)\n\n } else if value <= 0xffff {\n\n let size = write_length...
Rust
rts/motoko-rts/src/debug.rs
olaszakos/motoko
01867bdb76d6ceb7e986297464a41146f3d34839
#![allow(dead_code)] use crate::closure_table; use crate::print::*; use crate::types::*; #[cfg(feature = "gc")] use crate::gc; use core::fmt::Write; #[cfg(feature = "gc")] pub(crate) unsafe fn dump_heap() { print_closure_table(); print_static_roots(); print_heap(); } pub(crate) unsafe fn print_closure_...
#![allow(dead_code)] use crate::closure_table; use crate::print::*; use crate::types::*; #[cfg(feature = "gc")] use crate::gc; use core::fmt::Write; #[cfg(feature = "gc")] pub(crate) unsafe fn dump_heap() { print_closure_table(); print_static_roots(); print_heap(); } pub(crate) unsafe fn print_closure_...
pub(crate) unsafe fn print_boxed_object(buf: &mut WriteBuf, p: usize) { let _ = write!(buf, "{:#x}: ", p); let obj = p as *mut Obj; let tag = obj.tag(); if tag == 0 { return; } match tag { TAG_OBJECT => { let object = obj as *mut Object; let _ = write!(...
function_block-full_function
[ { "content": "// tolerant conversion\n\n// accepts lower case and fillers/padding '-', '='\n\n// values are one more than base32 value\n\n// 0 elements signify invalid alphabet letter\n\n// fillers/padding have upper bit set\n\n// Returns in range [1,32]\n\nfn conv(b: u8) -> u8 {\n\n if b == b'-' {\n\n ...
Rust
src/legacy/scintilla/lib_qt.rs
plyhun/plygui-scintilla
6543238d109c7cf44a8883d65f5bb4d12df0bd90
use super::development as scintilla_dev; use super::*; use plygui_qt::common::*; use scintilla_sys::*; pub type Scintilla = Member<Control<ScintillaQt>>; #[repr(C)] pub struct ScintillaQt { base: QtControlBase<Scintilla, ScintillaEditBase>, h_command: (bool, SlotSCNotificationPtr<'static>), } impl scintilla...
use super::development as scintilla_dev; use super::*; use plygui_qt::common::*; use scintilla_sys::*; pub type Scintilla = Member<Control<ScintillaQt>>; #[repr(C)] pub struct ScintillaQt { base: QtControlBase<Scintilla, ScintillaEditBase>, h_command: (bool, SlotSCNotificationPtr<'static>), } impl scintilla...
}; self.base.dirty = control.measured != old_size; (control.measured.0, control.measured.1, self.base.dirty) } fn invalidate(&mut self, _member: &mut MemberBase, _control: &mut ControlBase) { self.base.invalidate(); } } #[allow(dead_code)] pub(crate) fn spawn() -> Box<controls::C...
olBase, parent_width: u16, parent_height: u16) -> (u16, u16, bool) { let old_size = control.measured; control.measured = match control.visibility { types::Visibility::Gone => (0, 0), _ => { let w = match control.layout.width { layout::Size::Mat...
function_block-random_span
[ { "content": "fn event_handler<O: crate::Scintilla>(object: &mut QObject, event: &mut QEvent) -> bool {\n\n match unsafe { event.type_() } {\n\n QEventType::Resize => {\n\n if let Some(this) = cast_qobject_to_uimember_mut::<Scintilla>(object) {\n\n let size = unsafe { \n\n ...
Rust
src/dump-tjs.rs
shreevatsa/pdf-glyph-mapping
5edf553c8ef6ca794fea46fb2fedfabcbe7e4149
use anyhow::Result; use clap::Clap; use std::collections::HashMap; use std::io::Write; mod pdf_visit; mod text_state; #[derive(Clone)] pub enum Phase { Phase1Dump, Phase2Fix, } impl std::str::FromStr for Phase { type Err = std::num::ParseIntError; fn from_str(s: &str) -> std::result::Result<Self, Se...
use anyhow::Result; use clap::Clap; use std::collections::HashMap; use std::io::Write; mod pdf_visit; mod text_state; #[derive(Clone)] pub enum Phase { Phase1Dump, Phase2Fix, } impl std::str::FromStr for Phase { type Err = std::num::ParseIntError; fn from_str(s: &str) -> std::result::Result<Self, Se...
if let Some(guard) = guard { if let Ok(report) = guard.report().build() { let file = std::fs::File::create("flamegraph.svg")?; report.flamegraph(file)?; } } Ok(()) }
#[clap(long)] debug: bool, maps_dir: std::path::PathBuf, output_pdf_file: Option<std::path::PathBuf>, #[clap(long)] profile: bool, } let opts = Opts::parse(); let filename = opts.input_pdf_file; let start = std::time::Instant::now(); ...
random
[ { "content": "/// As mentioned above: This program reads a font file, and dumps bitmap images into a directory.\n\nfn main() -> Result<()> {\n\n let opts = Opts::parse();\n\n let font_file_contents = std::fs::read(&opts.font_file)?;\n\n let output_dir = Path::new(&opts.output_dir).join(opts.font_file.f...
Rust
konst_proc_macros/src/parsing.rs
rodrimati1992/konst
7b2b001cf4b4a67d85382f6c42bab214245db82f
#[allow(unused_imports)] use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; use proc_macro::token_stream::IntoIter as TSIterator; use crate::{utils::Error, Inputs, Pattern}; pub(crate) fn parse_inputs(ts: TokenStream) -> Result<Inputs, Error> { let iter = &mut ts.in...
#[allow(unused_imports)] use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; use proc_macro::token_stream::IntoIter as TSIterator; use crate::{utils::Error, Inputs, Pattern}; pub(crate) fn parse_inputs(ts: TokenStream) -> Result<Inputs, Error> { let iter = &mut ts.in...
rem, &format!("expected values from \\x00 to \\x7F, found: {}", hex), ) })?; out.push(num as char); } else { return Err(make_err(rem, "invalid ascii escape")); ...
ing { string, span })) } else { Err(Error::new( ident.span(), &format!("{}\nFound: {}", IN_MSG, ident), )) } } Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::None => { parse_lstr...
random
[ { "content": "fn output_patt(patt: &Pattern, out: &mut TokenStream) {\n\n use crate::utils::punct_token;\n\n\n\n match patt {\n\n Pattern::String { string, span } => {\n\n for b in string.bytes() {\n\n let mut lit = Literal::u8_unsuffixed(b);\n\n lit.set_spa...
Rust
Kernel/tests/filesystem/src/virt_storage.rs
thepowersgang/rust_os
18dc27eb2211bac8cf1e53163a5dd0ad64a15c0a
use ::kernel::metadevs::storage; use ::kernel::{log,log_log,log_error}; pub enum OverlayType { None, Temporary, Persistent, } pub fn add_volume(name: &str, path: &::std::path::Path, overlay_ty: OverlayType) -> Result<()/*::kernel::metadevs::storage::PhysicalVolumeReg*/, ::std::io::Error> { use ::std:...
use ::kernel::metadevs::storage; use ::kernel::{log,log_log,log_error}; pub enum OverlayType { None, Temporary, Persistent, } pub fn add_volume(name: &str, path: &::std::path::Path, overlay_ty: OverlayType) -> Result<()/*::kernel::metadevs::storage::PhysicalVolumeReg*/, ::std::io::Error> { use ::std:...
} impl storage::PhysicalVolume for Volume { fn name(&self) -> &str { &self.name } fn blocksize(&self) -> usize { self.block_size } fn capacity(&self) -> Option<u64> { Some(self.block_count) } fn read<'a>(&'a self, _prio: u8, idx: u64, num: usize, dst: &'a mut [u8]) -> storage::AsyncIoResult<'a,usize> { ...
match e.kind() { _ => { log_error!("cvt_error: unknown error {:?}", e); storage::IoError::Unknown("?") }, }
if_condition
[ { "content": "fn new_simple_lv(name: String, pv_id: usize, block_size: usize, base: u64, size: u64)\n\n{\n\n\tlet lvidx = S_NEXT_LV_IDX.fetch_add(1, ::core::sync::atomic::Ordering::Relaxed);\n\n\t\n\n\tassert!(size <= !0usize as u64);\n\n\tlet lv = Arc::new( LogicalVolume {\n\n\t\tindex: lvidx,\n\n\t\tname: nam...
Rust
src/html/preprocessor.rs
lunchboxav/unveil-rs
c5b9da09ab944c95778ff84c402f3c5490ef156c
pub(crate) struct Preprocessor; const RUST_CODE_TAG: &str = r#"<code class="language-rust">"#; const MD_CLASS_START: &str = r#"[class=&quot;"#; const MD_CLASS_END: &str = "&quot;]"; impl Preprocessor { pub fn insert_playpen_button(html: &str) -> String { let mut result = String::new(); let mut las...
pub(crate) struct Preprocessor; const RUST_CODE_TAG: &str = r#"<code class="language-rust">"#; const MD_CLASS_START: &str = r#"[class=&quot;"#; const MD_CLASS_END: &str = "&quot;]"; impl Preprocessor { pub fn insert_playpen_button(html: &str) -> String { let mut result = String::new(); let mut las...
1;"; } }.to_string(); assert_eq!(output, expected); } #[test] fn should_insert_playpen_buttons_on_multiple_block() { let input = format!( "{}let a = 1;</code><p>Foo</p>{}let a = 1;</code>", RUST_CODE_TAG, RUST_CODE_TAG ); ...
); let output = Preprocessor::insert_playpen_button(&input); let expected = html! { div(class="btn-code") { i(class="fas fa-copy bounce-in btn-copy", id="rust-code-block-0"); i(class="fas fa-play btn-playpen", onclick="play_playpen(this.id)", id=...
random
[ { "content": "pub fn create_dir(dirname: &str) {\n\n let dir = PathBuf::from(dirname);\n\n\n\n if !dir.exists() {\n\n std::fs::create_dir(dir).unwrap();\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\npub mod test {\n\n use crate::helper::fs::replace;\n\n use tempfile::NamedTempFile;\n\n\n\n #[test]\...
Rust
src/storage.rs
haraldng/omnipaxos
36dd86dfadaf91f442a3ad35c6cc01fd129d0f4a
use crate::leader_election::ballot_leader_election::Ballot; use std::{fmt::Debug, marker::PhantomData, sync::Arc}; #[derive(Clone, Debug, PartialEq)] pub enum Entry<T> where T: Clone, { Normal(T), StopSign(StopSign), } impl<T> Entry<T> where T: Clone, { pub fn is_stopsign(&self) -> ...
use crate::leader_election::ballot_leader_election::Ballot; use std::{fmt::Debug, marker::PhantomData, sync::Arc}; #[derive(Clone, Debug, PartialEq)] pub enum Entry<T> where T: Clone, { Normal(T), StopSign(StopSign), } impl<T> Entry<T> where T: Clone, { pub fn is_stopsign(&self) -> ...
pub fn append_on_decided_prefix(&mut self, seq: Vec<Entry<T>>) { let from_idx = self.get_decided_len(); match &mut self.sequence { PaxosSequence::Active(s) => { let mut sequence = seq; s.append_on_prefix(from_idx, &mut sequence); } ...
PaxosSequence::Active(s) => { s.append_on_prefix(from_idx, seq); s.get_sequence_len() } PaxosSequence::Stopped(s) => { assert!(seq.is_empty()); s.get_sequence_len() } _ => panic!("Got unexpected intermediate ...
function_block-function_prefix_line
[ { "content": "fn check_gc(vec_proposals: Vec<Entry<u64>>, seq_after: Vec<(&u64, Vec<Entry<u64>>)>, gc_idx: u64) {\n\n for i in 0..seq_after.len() {\n\n let (_, after) = seq_after.get(i).expect(\"After Sequence\");\n\n\n\n assert_eq!(vec_proposals.len(), (after.len() + gc_idx as usize));\n\n ...
Rust
src/axis.rs
clumsy/plotlib
2b627c2f821b567c810e93effb35d6eeb38199ad
/*! A module for managing axes */ #[derive(Debug, Clone)] pub struct Range { pub lower: f64, pub upper: f64, } impl Range { pub fn new(lower: f64, upper: f64) -> Range { Range { lower, upper } } pub(crate) fn is_valid(&self) -> bool { self.lower < self.upper } } #[derive(De...
/*! A module for managing axes */ #[derive(Debug, Clone)] pub struct Range { pub lower: f64, pub upper: f64, } impl Range { pub fn new(lower: f64, upper: f64) -> Range { Range { lower, upper } } pub(crate) fn is_valid(&self) -> bool { self.lower < self.upper } } #[derive(De...
assert_eq!(calculate_ticks(0.0, 8.0, 6), [0.0, 2.0, 4.0, 6.0, 8.0]); assert_eq!(calculate_ticks(0.0, 9.0, 6), [0.0, 2.0, 4.0, 6.0, 8.0]); assert_eq!( calculate_ticks(0.0, 10.0, 6), [0.0, 2.0, 4.0, 6.0, 8.0, 10.0] ); assert_eq!( calculate_ticks(0.0,...
{ self.label.as_ref() } pub fn ticks(&self) -> &Vec<String> { &self.ticks } } const BASE_STEPS: [u32; 4] = [1, 2, 4, 5]; #[derive(Debug, Clone)] struct TickSteps { next: f64, } impl TickSteps { fn start_at(start: f64) -> TickSteps { let start_options = TickSteps::sca...
random
[ { "content": "pub fn range(s: &[f64]) -> (f64, f64) {\n\n let mut min = f64::INFINITY;\n\n let mut max = f64::NEG_INFINITY;\n\n for &v in s {\n\n min = min.min(v);\n\n max = max.max(v);\n\n }\n\n (min, max)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[te...
Rust
src/helix/polls/end_poll.rs
Emilgardis/twitch_api2
1eafcf7baab4f6d0d0d34513d5d72b0ab3ec305d
use crate::helix::{parse_json, HelixRequestPatchError}; use super::*; use helix::RequestPatch; pub use types::PollStatus; #[derive(PartialEq, typed_builder::TypedBuilder, Deserialize, Serialize, Clone, Debug, Default)] #[non_exhaustive] pub struct EndPollRequest {} impl EndPollRequest { pub fn new() -> Se...
use crate::helix::{parse_json, HelixRequestPatchError}; use super::*; use helix::RequestPatch; pub use types::PollStatus; #[derive(PartialEq, typed_builder::TypedBuilder, Deserialize, Serialize, Clone, Debug, Default)] #[non_exhaustive] pub struct EndPollRequest {} impl EndPollRequest { pub fn new() -> Se...
, "channel_points_voting_enabled": true, "channel_points_per_vote": 100, "status": "TERMINATED", "duration": 1800, "started_at": "2021-03-19T06:08:33.871278372Z", "ended_at": "2021-03-19T06:11:26.746889614Z" } ] } "## .to_vec(); let http_response ...
lidResponse { reason: "expected at least one element in data", response: response.to_string(), status, uri: uri.clone(), }, )?) } http::StatusCode::BAD_REQUEST => E...
random
[ { "content": "/// A specific client default for setting some sane defaults for API calls and oauth2 usage\n\npub trait ClientDefault<'a>: Clone + Sized {\n\n /// Errors that can happen when assembling the client\n\n type Error: std::error::Error + Send + Sync + 'static;\n\n /// Construct [`Self`] with ...
Rust
xmpp-parsers/src/date.rs
Tellyo/gst-meet
1bd9b052ddf6917aff910a32d3f9ef60056188de
use crate::util::error::Error; use chrono::{DateTime as ChronoDateTime, FixedOffset}; use minidom::{IntoAttributeValue, Node}; use std::str::FromStr; #[derive(Debug, Clone, PartialEq)] pub struct DateTime(pub ChronoDateTime<FixedOffset>); impl DateTime { pub fn timezone(&self) -> FixedOffset { self...
use crate::util::error::Error; use chrono::{DateTime as ChronoDateTime, FixedOffset}; use minidom::{IntoAttributeValue, Node}; use std::str::FromStr; #[derive(Debug, Clone, PartialEq)] pub struct DateTime(pub ChronoDateTime<FixedOffset>); impl DateTime { pub fn timezone(&self) -> FixedOffset { self...
from_str("2017-05-27T12:11:02").unwrap_err(); let message = match error { Error::ChronoParseError(string) => string, _ => panic!(), }; assert_eq!(message.to_string(), "premature end of input"); } #[test] fn test_serialise() { let date = Da...
set::east(0)); } #[test] fn test_invalid_date() { let error = DateTime::from_str("2017-13-01T12:23:34Z").unwrap_err(); let message = match error { Error::ChronoParseError(string) => string, _ => panic!(), }; assert_eq!(message.to_string(), "i...
random
[ { "content": "fn get_c_output(name: &str) -> Result<String, Box<dyn Error>> {\n\n let tmpdir = Builder::new().prefix(\"abi\").tempdir()?;\n\n let exe = tmpdir.path().join(name);\n\n let c_file = Path::new(\"tests\").join(name).with_extension(\"c\");\n\n\n\n let cc = Compiler::new().expect(\"configured compi...
Rust
src/bitmap/bitmap_ops.rs
oebb-digirail/arrow2
5725fa3c18830f88ed0ed67067dda5c1d2080dca
use crate::bitmap::MutableBitmap; use std::ops::{BitAnd, BitOr, BitXor, Not}; use crate::trusted_len::TrustedLen; use super::{ utils::{BitChunk, BitChunkIterExact, BitChunksExact}, Bitmap, }; pub unsafe fn from_chunk_iter_unchecked<T: BitChunk, I: Iterator<Item = T>>( iterator: I, ) -> Vec<u8> { let ...
use crate::bitmap::MutableBitmap; use std::ops::{BitAnd, BitOr, BitXor, Not}; use crate::trusted_len::TrustedLen; use super::{ utils::{BitChunk, BitChunkIterExact, BitChunksExact}, Bitmap, }; pub unsafe fn from_chunk_iter_unchecked<T: BitChunk, I: Iterator<Item = T>>( iterator: I, ) -> Vec<
t lhs_chunks = lhs.chunks(); let rhs_chunks = rhs.chunks(); let rem_lhs = lhs_chunks.remainder(); let rem_rhs = rhs_chunks.remainder(); let chunks = lhs_chunks .zip(rhs_chunks) .map(|(left, right)| op(left, right)); let buffer = chunk_iter_to_vec(chunks.chain(std::iter::once(op(rem...
u8> { let (_, upper) = iterator.size_hint(); let upper = upper.expect("try_from_trusted_len_iter requires an upper limit"); let len = upper * std::mem::size_of::<T>(); let mut buffer = Vec::with_capacity(len); let mut dst = buffer.as_mut_ptr(); for item in iterator { let bytes = item.t...
random
[ { "content": "pub fn combine_validities(lhs: Option<&Bitmap>, rhs: Option<&Bitmap>) -> Option<Bitmap> {\n\n match (lhs, rhs) {\n\n (Some(lhs), None) => Some(lhs.clone()),\n\n (None, Some(rhs)) => Some(rhs.clone()),\n\n (None, None) => None,\n\n (Some(lhs), Some(rhs)) => Some(lhs &...
Rust
src/main/webapp/src/lib.rs
esieben1310/aiode
aac5fc7d97532df3fc9ce9116ad4cdd6ce73b8ad
use seed::{*, prelude::*}; use seed::browser::service::fetch::FailReason; use uuid::Uuid; use crate::CurrentModel::{Auth, Home, Start}; use crate::Msg::{AuthMsg, HomeMsg, SessionChecked, TokenChecked, TokenFetched}; use crate::page::auth::Msg::Complete; use crate::session::Client; use crate::Status::{AuthenticationReq...
use seed::{*, prelude::*}; use seed::browser::service::fetch::FailReason; use uuid::Uuid; use crate::CurrentModel::{Auth, Home, Start}; use crate::Msg::{AuthMsg, HomeMsg, SessionChecked, TokenChecked, TokenFetched}; use crate::page::auth::Msg::Complete; use crate::session::Client; use crate::Status::{AuthenticationReq...
nt); model.current_model = Home(page::home::Model); } else if let Auth(ref mut model) = model.current_model { page::auth::update(auth_msg, model, &mut orders.proxy(AuthMsg)); } } } } fn after_mount(_url: Url, orders: &mut impl Orders<Msg>) -> AfterMou...
update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) { let storage: storage::Storage = seed::storage::get_storage().expect("Failed to get seed storage"); match msg { SessionChecked(result) => { match result { Ok(valid_session) => { if valid_...
function_block-random_span
[ { "content": "pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {\n\n match msg {\n\n Msg::Clipboard => copy_to_clipboard(\"uuid_box\"),\n\n Msg::RefreshToken => {\n\n let storage: storage::Storage = seed::storage::get_storage().expect(\"Failed to get seed sto...
Rust
src/sdl2.rs
alex0809/chip8-rust
9c1117fd929ef0715b7da62e7909e99554c08651
extern crate sdl2; use std::thread::sleep; use std::time::{Duration, Instant}; use sdl2::audio::{AudioCallback, AudioSpecDesired}; use sdl2::event::Event; use sdl2::pixels::Color; use sdl2::rect::Point; use sdl2::render::Canvas; use sdl2::video::Window; use self::sdl2::audio::AudioDevice; use crate::config::*; use c...
extern crate sdl2; use std::thread::sleep; use std::time::{Duration, Instant}; use sdl2::audio::{AudioCallback, AudioSpecDesired}; use sdl2::event::Event; use sdl2::pixels::Color; use sdl2::rect::Point; use sdl2::render::Canvas; use sdl2::video::Window; use self::sdl2::audio::AudioDevice; use crate::config::*; use c...
fn redraw_screen( canvas: &mut Canvas<Window>, pixel_states: [[bool; SCREEN_Y]; SCREEN_X], ) -> Result<(), String> { for i in 0..pixel_states.len() { for j in 0..pixel_states[i].len() { if pixel_states[i][j] { canvas.set_draw_color(WHITE) } else { ...
pub fn for_interpreter(interpreter: &mut Interpreter, step_mode: bool) -> Result<(), String> { let sdl_context = sdl2::init()?; let video_subsystem = sdl_context.video()?; let audio_subsystem = sdl_context.audio()?; let audio_device = prepare_sound(&audio_subsystem); let window = video_subsystem ...
function_block-full_function
[ { "content": "extern crate rand;\n\n\n\nuse log::{debug, trace};\n\n\n\nuse rand::Rng;\n\n\n\nuse std::fs::File;\n\nuse std::io::Read;\n\n\n\nuse display::Display;\n\nuse keyboard::Keyboard;\n\nuse memory::Memory;\n\nuse stack::Stack;\n\n\n\nuse crate::config::{SCREEN_X, SCREEN_Y};\n\nuse crate::instruction::In...
Rust
crossterm_style/src/lib.rs
defiori/crossterm
3d92f62be470973772e2d3d83fd672c2613f0f87
#[macro_use] extern crate crossterm_utils; #[cfg(target_os = "windows")] extern crate crossterm_winapi; mod color; pub mod objectstyle; pub mod styledobject; mod ansi_color; #[cfg(target_os = "windows")] mod winapi_color; use self::ansi_color::AnsiColor; #[cfg(target_os = "windows")] use self::winapi_color::WinApi...
#[macro_use] extern crate crossterm_utils; #[cfg(target_os = "windows")] extern crate crossterm_winapi; mod color; pub mod objectstyle; pub mod styledobject; mod ansi_color; #[cfg(target_os = "windows")] mod winapi_color; use self::ansi_color::AnsiColor; #[cfg(target_os = "windows")] use self::winapi_color::WinApi...
}
magenta" => Ok(Color::Magenta), "dark_magenta" => Ok(Color::DarkMagenta), "cyan" => Ok(Color::Cyan), "dark_cyan" => Ok(Color::DarkCyan), "grey" => Ok(Color::Grey), "white" => Ok(Color::White), _ => Ok(Color::White), } }
function_block-function_prefix_line
[ { "content": "/// This function is used by 'ANSI' modules. Those modules are using an `Option` of `TerminalOutput`.\n\n/// Because it is an option it could be either 'None' or 'Some'.\n\n/// When the `TerminalOutput` is 'None' we write our 'ANSI' escape codes to the default `stdout()` if it is a `Some`\n\n/// -...
Rust
yoin-core/yoin-build/src/main.rs
anttirt/yoin
df7424f82e9f0b94b5b1fbb93124ae10cd9eaac8
extern crate encoding; extern crate clap; extern crate byteorder; use std::fs::{self, File}; use std::path::Path; use std::io::prelude::*; use std::io::{self, BufReader}; use std::convert::{AsRef, From}; use std::collections::HashMap; use clap::{App, Arg}; use encoding::{Encoding, DecoderTrap}; use encoding::all::EUC...
extern crate encoding; extern crate clap; extern crate byteorder; use std::fs::{self, File}; use std::path::Path; use std::io::prelude::*; use std::io::{self, BufReader}; use std::convert::{AsRef, From}; use std::collections::HashMap; use clap::{App, Arg}; use encoding::{Encoding, DecoderTrap}; use encoding::all::EUC...
} fn build_entries(morphs: &[String]) -> Result<(Vec<(&[u8], u32)>, Vec<u8>), Error> { let morphs = morphs.iter().map(|s| build_morph(s)); let mut inputs = Vec::new(); let mut bytes = Vec::new(); for morph in morphs { let morph = morph?; let index = bytes.len(); inputs.push((mo...
Ok(Morph { surface: surface, left_id: left_id, right_id: right_id, weight: weight, contents: contents, })
call_expression
[ { "content": "fn should_decode_zipped_data<P: AsRef<Path>>(dir: P, zipped: P) -> bool {\n\n let dir_meta = match fs::metadata(dir) {\n\n Ok(meta) => meta,\n\n Err(_) => return true,\n\n };\n\n let zipped_meta = match fs::metadata(zipped) {\n\n Ok(meta) => meta,\n\n Err(_) =>...
Rust
src/types/octave.rs
sofidi/musictheory-rs
c8196959917a79eeb372adf6405c52855a5b3dd6
use std::fmt; #[derive(Copy, Clone, PartialOrd, PartialEq)] pub enum Octave { DoubleContra, SubContra, Contra, Great, Small, OneLine, TwoLine, ThreeLine, FourLine, FiveLine, SixLine, SevenLine, } impl Octave { pub fn all() -> [Octave; 12] { use self::Octav...
use std::fmt; #[derive(Copy, Clone, PartialOrd, PartialEq)] pub enum Octave { DoubleContra, SubContra, Contra, Great, Small, OneLine, TwoLine, ThreeLine, FourLine, FiveLine, SixLine, SevenLine, } impl Octave { pub fn all() -> [Octave; 12] { use self::Octav...
pub(crate) fn to_index(&self) -> u8 { match *self { Octave::DoubleContra => 0, Octave::SubContra => 1, Octave::Contra => 2, Octave::Great => 3, Octave::Small => 4, Octave::OneLine => 5, Octave::TwoLine => 6, ...
pub(crate) fn from_index(index: u8) -> Option<Octave> { match index { 0 => Some(Octave::DoubleContra), 1 => Some(Octave::SubContra), 2 => Some(Octave::Contra), 3 => Some(Octave::Great), 4 => Some(Octave::Small), 5 => Some(Octave::OneLine), ...
function_block-full_function
[ { "content": "pub fn main() {\n\n let l = Note::A(Accidental::Natural);\n\n let r = Note::C(Accidental::Natural);\n\n let d = Interval::distance(l, r);\n\n println!(\"Interval::distance({}, {}) -> {:?}\", l, r, d);\n\n}\n", "file_path": "examples/test.rs", "rank": 0, "score": 68032.02822...
Rust
examples/adafruit_1in54_tricolor.rs
afajl/ssd1681
6164e1a5f5bb354f0f3115e69beaa205c4b29c77
#[cfg(not(target_os = "linux"))] fn main() {} #[cfg(target_os = "linux")] use linux_embedded_hal::{ spidev::{SpiModeFlags, SpidevOptions}, sysfs_gpio::Direction, Delay, Pin, Spidev, }; #[cfg(target_os = "linux")] use embedded_graphics::{ fonts::{Font6x8, Text}, prelude::*, primitives::{Circle,...
#[cfg(not(target_os = "linux"))] fn main() {} #[cfg(target_os = "linux")] use linux_embedded_hal::{ spidev::{SpiModeFlags, SpidevOptions}, sysfs_gpio::Direction, Delay, Pin, Spidev, }; #[cfg(target_os = "linux")] use embedded_graphics::{ fonts::{Font6x8, Text}, prelude::*, primitives::{Circle,...
#[cfg(target_os = "linux")] fn draw_rotation_and_rulers(display: &mut Display1in54) { display.set_rotation(DisplayRotation::Rotate0); draw_text(display, "rotation 0", 25, 25); draw_ruler(display); display.set_rotation(DisplayRotation::Rotate90); draw_text(display, "rotation 90", 25, 25); draw...
into_styled(PrimitiveStyle::with_fill(Red)) .draw(&mut display_red) .unwrap(); ssd1681.update_red_frame(&mut spi, display_red.buffer())?; println!("Update display"); ssd1681.display_frame(&mut spi)?; println!("Done"); Ok(()) }
function_block-function_prefix_line
[ { "content": "// Checks if a pos is outside the defined display\n\nfn outside_display(p: Point, width: u32, height: u32, rotation: DisplayRotation) -> bool {\n\n if p.x < 0 || p.y < 0 {\n\n return true;\n\n }\n\n let (x, y) = (p.x as u32, p.y as u32);\n\n match rotation {\n\n DisplayRo...
Rust
network-libp2p/src/discovery/message_codec/writer.rs
CyberFlameGO/core-rs-albatross
4731123d9311d62c0d62cf1af94e7aeec7dd000d
use std::{marker::PhantomData, pin::Pin}; use bytes::{Buf, BufMut, BytesMut}; use futures::{ ready, task::{Context, Poll}, AsyncWrite, Sink, }; use pin_project::pin_project; use beserial::{Serialize, SerializingError}; use super::header::Header; fn write_from_buf<W>( inner: &mut W, buffer: &mut ...
use std::{marker::PhantomData, pin::Pin}; use bytes::{Buf, BufMut, BytesMut}; use futures::{ ready, task::{Context, Poll}, AsyncWrite, Sink, }; use pin_project::pin_project; use beserial::{Serialize, SerializingError}; use super::header::Header; fn write_from_buf<W>( inner: &mut W, buffer: &mut ...
) } Poll::Ready(Ok(n)) => { buffer.advance(n); if buffer.remaining() > 0 { Poll::Pending } else { buffer.clear(); Poll::Ready(Ok(())) } } Poll::Re...
Err(SerializingError::from(std::io::Error::from( std::io::ErrorKind::UnexpectedEof, )))
call_expression
[ { "content": "fn unexpected_eof<T>() -> Poll<Option<Result<T, SerializingError>>> {\n\n Poll::Ready(Some(Err(SerializingError::from(std::io::Error::from(\n\n std::io::ErrorKind::UnexpectedEof,\n\n )))))\n\n}\n\n\n\nimpl<R, M> Stream for MessageReader<R, M>\n\nwhere\n\n R: AsyncRead,\n\n M: De...
Rust
linkerd/app/outbound/src/resolve.rs
kailun-qin/linkerd2-proxy
607cfea249216fabd549cfeabd5a565af028f172
#![allow(warnings)] use crate::target::{Concrete, EndpointFromMetadata}; use futures::{future, prelude::*, stream}; use linkerd_app_core::{ discovery_rejected, is_discovery_rejected, proxy::{ api_resolve::Metadata, core::{Resolve, ResolveService, Update}, discover::{self, Buffer, FromRe...
#![allow(warnings)] use crate::target::{Concrete, EndpointFromMetadata}; use futures::{future, prelude::*, stream}; use linkerd_app_core::{ discovery_rejected, is_discovery_rejected, proxy::{ api_resolve::Metadata, core::{Resolve, ResolveService, Update}, discover::{self, Buffer, FromRe...
type Stack<E, R, N> = Buffer<discover::Stack<N, ResolveStack<R>, E>>; pub fn layer<T, E, R, N>( resolve: R, watchdog: Duration, ) -> impl layer::Layer<N, Service = Stack<E, R, N>> + Clone where T: Clone, for<'t> &'t T: Into<std::net::SocketAddr>, R: Resolve<Addr, Endpoint = Metadata> + Clone, ...
R: Resolve<Addr, Endpoint = Metadata>, R::Future: Send, R::Resolution: Send, { map_endpoint::Resolve::new( EndpointFromMetadata, RecoverDefault(Filter::new(resolve.into_service(), AllowResolve)), ) }
function_block-function_prefix_line
[ { "content": "pub fn layer<C, R: Clone>(\n\n recover: R,\n\n) -> impl layer::Layer<C, Service = NewReconnect<C, R>> + Clone {\n\n layer::mk(move |connect| NewReconnect {\n\n connect,\n\n recover: recover.clone(),\n\n })\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct NewReconnect<C, R> ...
Rust
crate2nix/src/metadata.rs
walfie/crate2nix
570a556677b524514fbf0b1cbbc7a39961f083bd
use std::collections::{BTreeMap, HashMap, HashSet}; use anyhow::format_err; use anyhow::{Error, Result}; use cargo_metadata::Node; use cargo_metadata::Package; use cargo_metadata::PackageId; use cargo_metadata::{Metadata, NodeDep}; use itertools::Itertools; use serde::Deserialize; use serde::Serialize; #[derive(Deb...
use std::collections::{BTreeMap, HashMap, HashSet}; use anyhow::format_err; use anyhow::{Error, Result}; use cargo_metadata::Node; use cargo_metadata::Package; use cargo_metadata::PackageId; use cargo_metadata::{Metadata, NodeDep}; use itertools::Itertools; use serde::Deserialize; use serde::Serialize; #[derive(Deb...
pub fn lengthen_ref<'a>(&'a self, package_id: &'a PackageId) -> &'a PackageId { self.reverse.get(&package_id).unwrap_or_else(|| &package_id) } pub fn shorten_ref<'a>(&'a self, package_id: &'a PackageId) -> &'a PackageId { self.substitution .get(&package_id) .unwrap...
fn new<'a>(all_packages: impl Iterator<Item = &'a Package>) -> PackageIdShortener { let mut substitution = HashMap::new(); let mut reverse = HashMap::new(); for (_crate_name, group) in &all_packages .sorted_by_key(|p| &p.name) .group_by(|p| p.name.clone()) { ...
function_block-full_function
[ { "content": "/// Ensures that the given path either does not exist or contains a file that\n\n/// was generated by crate2nix.\n\npub fn check_generated_by_crate2nix(path: impl AsRef<Path>) -> Result<(), Error> {\n\n if !path.as_ref().exists() {\n\n return Ok(());\n\n }\n\n\n\n let reader = std:...
Rust
misc/rw-stream-sink/src/lib.rs
linted/rust-libp2p
f999fd506a3ff43746660b8d64edcd98d14f3686
extern crate bytes; extern crate futures; extern crate tokio_io; use bytes::{Buf, IntoBuf}; use futures::{Async, AsyncSink, Poll, Sink, Stream}; use std::cmp; use std::io::Error as IoError; use std::io::ErrorKind as IoErrorKind; use std::io::{Read, Write}; use tokio_io::{AsyncRead, AsyncWrite}; pub struct RwStreamS...
extern crate bytes; extern crate futures; extern crate tokio_io; use bytes::{Buf, IntoBuf}; use futures::{Async, AsyncSink, Poll, Sink, Stream}; use std::cmp; use std::io::Error as IoError; use std::io::ErrorKind as IoErrorKind; use std::io::{Read, Write}; use tokio_io::{AsyncRead, AsyncWrite}; pub struct RwStreamS...
#[test] fn skip_empty_stream_items() { let data: Vec<&[u8]> = vec![b"", b"foo", b"", b"bar", b"", b"baz", b""]; let mut rws = RwStreamSink::new(stream::iter_ok::<_, std::io::Error>(data)); let mut buf = [0; 9]; assert_eq!(9, rws.read(&mut buf).unwrap()); assert_eq!(b"fo...
assert_eq!(&data1, b"hello"); let mut data2 = Vec::new(); wrapper.read_to_end(&mut data2).unwrap(); assert_eq!(data2, b" world"); }
function_block-function_prefix_line
[ { "content": "#[inline]\n\npub fn generate_agreement(algorithm: KeyAgreement) -> impl Future<Item = (AgreementPrivateKey, Vec<u8>), Error = SecioError> {\n\n platform::generate_agreement(algorithm).map(|(pr, pu)| (AgreementPrivateKey(pr), pu))\n\n}\n\n\n\n/// Finish the agreement. On success, returns the sha...
Rust
kzg-bench/src/tests/fk20_proofs.rs
sifraitech/kzg
9ef31f2f7baa87500f688db6cbaf823d3cfd4951
use kzg::{ FFTFr, FFTSettings, FK20MultiSettings, FK20SingleSettings, Fr, KZGSettings, Poly, G1, G2, }; pub const SECRET: [u8; 32usize] = [ 0xa4, 0x73, 0x31, 0x95, 0x28, 0xc8, 0xb6, 0xea, 0x4d, 0x08, 0xcc, 0x53, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,...
use kzg::{ FFTFr, FFTSettings, FK20MultiSettings, FK20SingleSettings, Fr, KZGSettings, Poly, G1, G2, }; pub const SECRET: [u8; 32usize] = [ 0xa4, 0x73, 0x31, 0x95, 0x28, 0xc8, 0xb6, 0xea, 0x4d, 0x08, 0xcc, 0x53, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,...
, Vec<TG2>), ) { let coeffs: Vec<u64> = vec![1, 2, 3, 4, 7, 7, 7, 7, 13, 13, 13, 13, 13, 13, 13, 13]; let poly_len: usize = coeffs.len(); let n: usize = 8; let n_len: usize = 1 << n; let stride: usize = n_len / (2 * poly_len); let secrets_len = n_len + 1; assert!(n_len >= 2 * poly_len); ...
vals: &mut Vec<T>) where T: Clone, { let unused_bit_len = vals.len().leading_zeros() + 1; for i in 0..vals.len() - 1 { let r = i.reverse_bits() >> unused_bit_len; if r > i { let tmp = vals[r].clone(); vals[r] = vals[i].clone(); vals[i] = tmp; } ...
random
[ { "content": "pub fn generate_trusted_setup(n: usize, secret: [u8; 32usize]) -> (Vec<G1>, Vec<G2>) {\n\n let s = Scalar::from_bytes(&secret).unwrap();\n\n let mut s_pow = Scalar::one();\n\n\n\n let mut s1 = Vec::new();\n\n let mut s2 = Vec::new();\n\n for _ in 0..n {\n\n s1.push(G1_GENERAT...
Rust
material-yew/src/list.rs
c4dt/material-yew
a207947c37f54d43afcc59260652ec236b32463c
mod list_item; pub use list_item::*; mod check_list_item; pub use check_list_item::*; mod radio_list_item; pub use radio_list_item::*; mod list_index; pub use list_index::ListIndex; mod selected_detail; pub use selected_detail::{IndexDiff, SelectedDetail}; mod action_detail; pub use action_detail::ActionDetail; m...
mod list_item; pub use list_item::*; mod check_list_item; pub use check_list_item::*; mod radio_list_item; pub use radio_list_item::*; mod list_index; pub use list_index::ListIndex; mod selected_detail; pub use selected_detail::{IndexDiff, SelectedDetail}; mod action_detail; pub use action_detail::ActionDetail; m...
} } impl WeakComponentLink<MatList> { pub fn toggle(&self, index: usize, force: bool) { let list = (*self.borrow().as_ref().unwrap().get_component().unwrap()) .node_ref .cast::<List>() .unwrap(); list.toggle(index, force) } ...
if self.action_listener.is_none() { let onaction = self.props.onaction.clone(); self.action_listener = Some(EventListener::new(&list.clone(), "action", move |_| { let val: JsValue = list.index(); let index = ListIndex::from(val); onaction.emit(inde...
if_condition
[]
Rust
src/parse_file.rs
sanbox-irl/gm-docs-parser
220da77dbd7f3f752acf5f4d6088a9926eee7f78
use crate::{parse_fnames::convert_to_url, Markdown}; use gm_docs_parser::{GmManualFunction, GmManualFunctionParameter, GmManualVariable}; use log::*; use scraper::{html::Select, Html, Node, Selector}; use std::ops::Deref; use std::path::Path; #[derive(Debug)] pub enum DocEntry { Function(GmManualFunction), Var...
use crate::{parse_fnames::convert_to_url, Markdown}; use gm_docs_parser::{GmManualFunction, GmManualFunctionParameter, GmManualVariable}; use log::*; use scraper::{html::Select, Html, Node, Selector}; use std::ops::Deref; use std::path::Path; #[derive(Debug)] pub enum DocEntry { Function(GmManualFunction), Var...
fn parse_signature(sig: &str) -> (Vec<Arg>, bool, bool) { let start = sig.find('('); let end = sig.find(')'); let succeeded = start.is_some() && end.is_some(); if succeeded == false { return (vec![], false, false); } let start = start.unwrap(); let end = end.unwrap(); let mut o...
function_block-full_function
[ { "content": "#[throws(Box<dyn std::error::Error>)]\n\npub fn parse_constants(base_path: &Path, constants: &mut BTreeMap<String, GmManualConstant>) {\n\n for file in std::fs::read_dir(base_path)? {\n\n let file = file?;\n\n let file_type = file.file_type()?;\n\n\n\n if file_type.is_dir()...
Rust
src/scripts/syriac.rs
davelab6/allsorts
02c5f60463505058ede364acff79fdfd6b724aac
use crate::error::{ParseError, ShapingError}; use crate::gsub::{self, build_lookups, GlyphData, GlyphOrigin, RawGlyph}; use crate::layout::{GDEFTable, LangSys, LayoutCache, LayoutTable, GSUB}; use crate::tag; use std::convert::From; use unicode_joining_type::{get_joining_group, get_joining_type, JoiningGroup, Joinin...
use crate::error::{ParseError, ShapingError}; use crate::gsub::{self, build_lookups, GlyphData, GlyphOrigin, RawGlyph}; use crate::layout::{GDEFTable, LangSys, LayoutCache, LayoutTable, GSUB}; use crate::tag; u
i].is_transparent() { continue; } if syriac_glyphs[previous_i].is_left_joining() && syriac_glyphs[i].is_right_joining() { if syriac_glyphs[i].is_alaph() { syriac_glyphs[i].set_feature_tag(tag::MED2) } else { ...
se std::convert::From; use unicode_joining_type::{get_joining_group, get_joining_type, JoiningGroup, JoiningType}; #[derive(Clone)] struct SyriacData { joining_group: JoiningGroup, joining_type: JoiningType, feature_tag: u32, } impl GlyphData for SyriacData { fn merge(data1: SyriacData, _data2: Syriac...
random
[ { "content": "type SubstContext<'a> = ContextLookupHelper<'a, GSUB>;\n\n\n\nimpl Ligature {\n\n pub fn matches<T>(\n\n &self,\n\n match_type: MatchType,\n\n opt_gdef_table: Option<&GDEFTable>,\n\n i: usize,\n\n glyphs: &[RawGlyph<T>],\n\n ) -> bool {\n\n let mut l...
Rust
tremor-pipeline/src/op/generic/batch.rs
Voultapher/tremor-runtime
738f08e5b716826c5c959b4aa6bd4f8c34fde66e
use crate::{op::prelude::*, EventId, EventIdGenerator}; use std::mem::swap; use tremor_script::prelude::*; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Config { pub count: usize, #[serde(default = "Default::default")] pub timeout: Option<u64>, } impl ConfigImpl for Config {} #[d...
use crate::{op::prelude::*, EventId, EventIdGenerator}; use std::mem::swap; use tremor_script::prelude::*; #[derive(Debug, Clone, Deserialize, Serialize)] pub struct Config { pub count: usize, #[serde(default = "Default::default")] pub timeout: Option<u64>, } impl ConfigImpl for Config {} #[d...
} #[cfg(test)] mod test { use super::*; use simd_json_derive::Serialize; use tremor_script::Value; #[test] fn size() { let mut idgen = EventIdGenerator::new(0); let mut op = Batch { config: Config { count: 2, timeout: None, }...
fn on_signal( &mut self, _uid: u64, _state: &Value<'static>, signal: &mut Event, ) -> Result<EventAndInsights> { Ok(self .max_delay_ns .map_or_else(EventAndInsights::default, |delay_ns| { if signal.ingest_ns - self.first_ns > delay_ns {...
function_block-full_function
[ { "content": "#[allow(clippy::cast_sign_loss)]\n\npub fn _parse(datetime: &str, input_fmt: &str, has_timezone: bool) -> Result<u64> {\n\n if has_timezone {\n\n Ok(DateTime::parse_from_str(datetime, input_fmt)\n\n .map_err(|e| Error::from(format!(\"Datetime Parse Error: {:?}\", e)))?\n\n ...
Rust
dbl/src/lib.rs
alan-signal/utils
fb107e63cc995d1527de4ee9e89c9e5d307522a7
#![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_root_url = "https://docs.rs/dbl/0.3.1" )] extern crate generic_array; use generic_array::typenum::{U16, U32, ...
#![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_root_url = "https://docs.rs/dbl/0.3.1" )] extern crate generic_array; use generic_array::typenum::{U16, U32, ...
fn inv_dbl(self) -> Self { let mut val: [u64; 4] = unsafe { mem::transmute_copy(&self) }; to_be(&mut val); let a = (val[0] & 1) << 63; let b = (val[1] & 1) << 63; let c = (val[2] & 1) << 63; let d = val[3] & 1; val[0] >>= 1; val[1] >>= 1; v...
1; val[1] ^= c; val[2] <<= 1; val[2] ^= d; val[3] <<= 1; val[3] ^= a * C256; to_be(&mut val); unsafe { mem::transmute(val) } }
function_block-function_prefixed
[ { "content": "fn encode_vlq(mut val: usize, buf: &mut [u8; 4]) -> &[u8] {\n\n macro_rules! step {\n\n ($n:expr) => {\n\n buf[$n] = if $n == 3 {\n\n (val & (VAL_MASK as usize)) as u8\n\n } else {\n\n val -= 1;\n\n NEXT_MASK | (val & (VA...
Rust
crates/fluvio-spu/src/services/public/tests/produce.rs
mapbased/fluvio
e39ed0ef6d89c45182c1ea8894452454b71f36d8
use std::{env::temp_dir, time::Duration}; use dataplane::{ produce::{ DefaultProduceRequest, DefaultPartitionRequest, TopicProduceData, PartitionProduceData, }, api::RequestMessage, ErrorCode, RequestKind, Isolation, }; use fluvio_controlplane_metadata::{partition::Replica, topic::CompressionAl...
use std::{env::temp_dir, time::Duration}; use dataplane::{ produce::{ DefaultProduceRequest, DefaultPartitionRequest, TopicProduceData, PartitionProduceData, }, api::RequestMessage, ErrorCode, RequestKind, Isolation, }; use fluvio_controlplane_metadata::{partition::Replica, topic::CompressionAl...
30_u16) .generate("produce_waiting_replication"); let (leader_ctx, leader_replica) = config.leader_replica().await; let public_addr = config.leader_public_addr(); let public_server_end_event = create_public_server(public_addr.clone(), leader_ctx.clone()).run(); let private_server_end_e...
est) .try_into() .expect("filter records"); let mut produce_request = DefaultProduceRequest { isolation: Isolation::ReadCommitted, timeout: Duration::from_millis(300), ..Default::default() }; let partition_produce = DefaultPartitionRequest { partition_index:...
random
[ { "content": "pub fn create_partition_name(topic_name: &str, idx: &i32) -> String {\n\n format!(\"{}-{}\", topic_name, idx)\n\n}\n", "file_path": "crates/fluvio-dataplane-protocol/src/common.rs", "rank": 0, "score": 379177.2496189955 }, { "content": "/// create sample batches with variabl...
Rust
arch/src/lib.rs
sameo/crosvm-vfio
3a41dba3ed9c568aaa82220ef250bc05a31cc07e
pub mod android; pub mod fdt; use std::collections::BTreeMap; use std::error::Error as StdError; use std::fmt::{self, Display}; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom}; use std::os::unix::io::AsRawFd; use std::sync::Arc; use devices::virtio::VirtioDevice; use devices::{ Bus, BusDevice, BusE...
pub mod android; pub mod fdt; use std::collections::BTreeMap; use std::error::Error as StdError; use std::fmt::{self, Display}; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom}; use std::os::unix::io::AsRawFd; use std::sync::Arc; use devices::virtio::VirtioDevice; use devices::{ Bus, BusDevice, BusE...
es: {}", e) } } } } pub fn generate_pci_root( devices: Vec<(Box<dyn PciDevice>, Option<Minijail>)>, mmio_bus: &mut Bus, resources: &mut SystemAllocator, vm: &mut Vm, ) -> Result<(PciRoot, Vec<(u32, PciInterruptPin)>, BTreeMap<u32, String>), DeviceRegistrationError> { let mut...
e) => write!(f, "Allocating IO addresses: {}", e), AllocateDeviceAddrs(e) => write!(f, "Allocating device addresses: {}", e), AllocateIrq => write!(f, "Allocating IRQ number"), CreateMmioDevice(e) => write!(f, "failed to create mmio device: {}", e), Cmdline(e) => write!(f...
function_block-random_span
[ { "content": "/// Returns a string representation of the given virtio device type number.\n\npub fn type_to_str(type_: u32) -> Option<&'static str> {\n\n Some(match type_ {\n\n TYPE_NET => \"net\",\n\n TYPE_BLOCK => \"block\",\n\n TYPE_RNG => \"rng\",\n\n TYPE_BALLOON => \"balloon...
Rust
polar-core/src/inverter.rs
davidpelaez/oso
b8091a91f2a0d76585a5d791a49bb344a0b1c60c
use std::cell::RefCell; use std::collections::hash_map::Entry; use std::rc::Rc; use std::sync::atomic::{AtomicU64, Ordering}; use crate::bindings::{BindingManager, Bsp, FollowerId, VariableState}; use crate::counter::Counter; use crate::error::{PolarError, PolarResult}; use crate::events::QueryEvent; use crate::format...
use std::cell::RefCell; use std::collections::hash_map::Entry; use std::rc::Rc; use std::sync::atomic::{AtomicU64, Ordering}; use crate::bindings::{BindingManager, Bsp, FollowerId, VariableState}; use crate::counter::Counter; use crate::error::{PolarError, PolarResult}; use crate::events::QueryEvent; use crate::format...
fn reduce_constraints(bindings: Vec<Bindings>) -> Bindings { bindings .into_iter() .fold(Bindings::new(), |mut acc, bindings| { bindings .into_iter() .for_each(|(var, value)| match acc.entry(var.clone()) { Entry::Occupied(mut o) => ma...
into_iter() .map(|(k, v)| match v.value() { Value::Expression(e) => (k, e.invert().into_term()), _ => ( k.clone(), term!(op!(And, term!(op!(Neq, term!(k), v.clone())))), ), }) .collect::<Bindings>() }
function_block-function_prefix_line
[ { "content": "pub fn walk_field<V: Visitor>(visitor: &mut V, key: &Symbol, value: &Term) {\n\n visitor.visit_symbol(key);\n\n visitor.visit_term(value);\n\n}\n\n\n", "file_path": "polar-core/src/visitor.rs", "rank": 0, "score": 408327.29962332913 }, { "content": "pub fn walk_term<V: Vi...
Rust
src/main.rs
wyda/rust-ads
d29d6954ac168521c44f5c2e8aea72ceec63e2cb
use ads::client::{ ads_client::Connection, plc_types::{PlcTypes, Var}, }; use ads::proto::ads_state::AdsState; use ads::proto::{ads_transition_mode::AdsTransMode, ams_address::*}; use byteorder::{LittleEndian, ReadBytesExt}; use std::net::Ipv4Addr; use std::thread::sleep; use std::time::Duration; fn main() { ...
use ads::client::{ ads_client::Connection, plc_types::{PlcTypes, Var}, }; use ads::proto::ads_state::AdsState; use ads::proto::{ads_transition_mode::AdsTransMode, ams_address::*}; use byteorder::{LittleEndian, ReadBytesExt}; use std::net::Ipv4Addr; use std::thread::sleep; use std::time::Duration; fn main() { ...
e) => println!("Error reading by name {:?}", e), } let var = Var::new("Main.counter".to_string(), PlcTypes::DInt, None); value += 1; match connection.write_by_name(&var, 456, value.to_le_bytes().to_vec()) { Ok(r) => println!("Write successfull {:?}", r), Err(e) => println!("Error...
function_block-function_prefixed
[ { "content": " def handle_read_device_info():\n\n \"\"\"\n\n Create dummy response: version 1.2.3, device name 'TestServer'\n\n\n\n \"\"\"\n\n logger.info('Command received: READ_DEVICE_INFO')\n\n\n\n major_version = '\\x01'.encode('utf-8')\n\n ...
Rust
woori-db/src/controllers/json_history_test.rs
naomijub/wooridb
aefa200b4a2dec69166aa9de71126d277b4f8a1e
use crate::{auth::schemas::UserId, http::routes, schemas::tx::InsertEntityResponse}; use actix_http::body::ResponseBody; use actix_web::{body::Body, test, App}; use uuid::Uuid; #[actix_rt::test] async fn test_history_ok() { let mut app = test::init_service(App::new().configure(routes)).await; let req = test::T...
use crate::{auth::schemas::UserId, http::routes, schemas::tx::InsertEntityResponse}; use actix_http::body::ResponseBody; use actix_web::{body::Body, test, App}; use uuid::Uuid; #[actix_rt::test]
#[ignore] #[actix_rt::test] async fn query_and_tx_with_token() { let mut app = test::init_service(App::new().configure(routes)).await; let req = test::TestRequest::post() .set_payload("{\"admin_id\": \"your_admin\", \"admin_password\": \"your_password\", \"user_info\": {\"user_password\": \"my_pas...
async fn test_history_ok() { let mut app = test::init_service(App::new().configure(routes)).await; let req = test::TestRequest::post() .header("Content-Type", "application/wql") .set_payload("CREATE ENTITY test_history") .uri("/wql/tx") .to_request(); let _ = test::call_serv...
function_block-full_function
[ { "content": "trait BodyTest {\n\n fn as_str(&self) -> &str;\n\n}\n\n\n\nimpl BodyTest for ResponseBody<Body> {\n\n fn as_str(&self) -> &str {\n\n match self {\n\n ResponseBody::Body(ref b) => match b {\n\n Body::Bytes(ref by) => std::str::from_utf8(&by).unwrap(),\n\n ...
Rust
src/runge_kutta/embedded.rs
mellemahp/ridc_integrators
bafacd1ee5e963332cecee0baec3d863304c4215
extern crate nalgebra as na; use na::allocator::Allocator; use na::{DefaultAllocator, Dim, DimName, VectorN}; use super::adaptive::AdaptiveStep; use super::common::{RkOrder, StepResult, StepWithError}; use super::tableaus::{EmbeddedTableau, RkType}; #[derive(Debug, Clone, PartialEq)] pub struct EmbeddedRKStepper<D:...
extern crate nalgebra as na; use na::allocator::Allocator; use na::{DefaultAllocator, Dim, DimName, VectorN}; use super::adaptive::AdaptiveStep; use super::common::{RkOrder, StepResult, StepWithError}; use super::tableaus::{EmbeddedTableau, RkType}; #[derive(Debug, Clone, PartialEq)] pub struct EmbeddedRKStepper<D:...
}
fn test_bogacki_shampine() { let a_vals = Matrix4::new( 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.75, 0.0, 0.0, 2.0 / 9.0, 1.0 / 3.0, ...
function_block-full_function
[ { "content": "/// Checks that row-sum condition holds for a given tableau\n\n/// NOTE: As discussed (here)[https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20160005923.pdf]\n\n/// the row-sum condition does not need to hold for all tableaus. So, for generality we do not\n\n/// check for that condit...
Rust
examples/bluepill/examples/mediakeyboard.rs
jkristell/infrared
87de1f81ba3867409067e646fc2f08e4ffedb735
#![no_main] #![no_std] use cortex_m::asm; use dwt_systick_monotonic::DwtSystick; use embedded_hal::digital::v2::OutputPin; use infrared::{ protocol::NecApple, receiver::{Event, PinInput}, remotecontrol::{nec::Apple2009, Action, Button}, Receiver, }; use panic_rtt_target as _; use rtic::time::{duration:...
#![no_main] #![no_std] use cortex_m::asm; use dwt_systick_monotonic::DwtSystick; use embedded_hal::digital::v2::OutputPin; use infrared::{ protocol::NecApple, receiver::{Event, PinInput}, remotecontrol::{nec::Apple2009, Action, Button}, Receiver, }; use panic_rtt_target as _; use rtic::time::{duration:...
match action { Action::Play_Pause => MediaKey::PlayPause, Action::Up => MediaKey::VolumeIncrement, Action::Down => MediaKey::VolumeDecrement, Action::Right => MediaKey::NextTrack, Action::Left => MediaKey::PrevTrack, Action::Stop => MediaKey::Stop, _ => MediaKey::...
function_block-function_prefix_line
[ { "content": "// Our receivertype\n\ntype IrReceiver = Receiver<Rc6, Poll, PinInput<PB8<Input<Floating>>>, Button<Rc6Tv>>;\n\n\n\n// Globals\n\nstatic mut TIMER: Option<CountDownTimer<TIM2>> = None;\n\nstatic mut RECEIVER: Option<IrReceiver> = None;\n\n\n", "file_path": "examples/bluepill/examples/tutorial1...
Rust
src/session_service/timed_requests.rs
jrhea/discv5
7b3bd40591b62b8c002ffdb85de008aa9f82e2e5
use crate::session_service::Request; use futures::Stream; use log::error; use std::pin::Pin; use std::{ collections::HashMap, net::SocketAddr, task::{Context, Poll}, time::Duration, }; use tokio::time::{delay_queue, DelayQueue}; pub(crate) struct TimedRequests { requests: HashMap<S...
use crate::session_service::Request; use futures::Stream; use log::error; use std::pin::Pin; use std::{ collections::HashMap, net::SocketAddr, task::{Context, Poll}, time::Duration, }; use tokio::time::{delay_queue, DelayQueue}; pub(crate) struct TimedRequests { requests: HashMap<S...
error!("Request timeout error: {:?}", e); Poll::Pending } Poll::Ready(None) => Poll::Ready(None), Poll::Pending => Poll::Pending, } } }
meout_index.get_ref(); let dst = timeout_index.dst; if let Some(requests) = self.requests.get_mut(&dst) { if let Some(pos) = requests .iter() .position(|r| r.request_key == timeout_index.request_key) ...
random
[ { "content": "fn update_enr(discv5: &mut Discv5, key: &str, value: &[u8]) -> bool {\n\n if let Ok(_) = discv5.enr_insert(key, value.to_vec()) {\n\n return true;\n\n } else {\n\n return false;\n\n }\n\n}\n\n\n\n#[tokio::test]\n\nasync fn test_predicate_search() {\n\n init();\n\n let ...
Rust
macroslib/src/typemap/utils.rs
simlay/flapigen-rs
c82f5858baff16db8bb54ecf3f8bc9652327f21a
use proc_macro2::{Span, TokenStream}; use quote::quote; use rustc_hash::FxHashSet; use std::{ fs, path::{Path, PathBuf}, }; use syn::{spanned::Spanned, Ident, Type}; use crate::{ error::{panic_on_syn_error, DiagnosticError, Result}, file_cache::FileOperationsRegistrator, source_registry::SourceId, ...
use proc_macro2::{Span, TokenStream}; use quote::quote; use rustc_hash::FxHashSet; use std::{ fs, path::{Path, PathBuf}, }; use syn::{spanned::Spanned, Ident, Type}; use crate::{ error::{panic_on_syn_error, DiagnosticError, Result}, file_cache::FileOperationsRegistrator, source_registry::SourceId, ...
; } } } Ok(()) } pub(crate) fn boxed_type(tmap: &mut TypeMap, from: &RustType) -> RustType { for smart_pointer in &["Box", "Rc", "Arc"] { if let Some(inner_ty) = check_if_smart_pointer_return_inner_type(from, *smart_pointer) { let inner_ty: RustType = tmap.find_or_a...
Err(DiagnosticError::new( rule.src_id, opt.sp, format!( "unsupported option {}, avaible options {:?}", opt.as_str(), avaible_opts ), ))
call_expression
[ { "content": "fn calc_this_type_for_method(tm: &TypeMap, class: &ForeignClassInfo) -> Option<Type> {\n\n if let Some(constructor_ret_type) = class.self_desc.as_ref().map(|x| &x.constructor_ret_type) {\n\n Some(\n\n if_result_return_ok_err_types(\n\n &tm.ty_to_rust_type_checke...
Rust
tests/pso.rs
czonios/pso-rs
967ce097aabcc8e452accb175835a44bc84e17d5
use pso_rs::*; #[test] fn it_runs_non_parallel() { fn rosenbrock(p: &Particle, _flat_dim: usize, dimensions: &Vec<usize>) -> f64 { (0..dimensions[0] - 1) .map(|i| 100.0 * ((p[i + 1] - p[i]).powf(2.0)).powf(2.0) + (1.0 - p[i]).powf(2.0)) .sum() } let config = Config { ...
use pso_rs::*; #[test] fn it_runs_non_parallel() { fn rosenbrock(p: &Particle, _flat_dim: usize, dimensions: &Vec<usize>) -> f64 { (0..dimensions[0] - 1) .map(|i| 100.0 * ((p[i + 1] - p[i]).powf(2.0)).powf(2.0) + (1.0 - p[i]).powf(2.0)) .sum()
= 0.5828840628; model.population[0][3] = 0.2505889242; model.population[0][4] = 0.6193583398; model.population[0][5] = -0.1614607010; model.population[0][6] = -0.4082757926; model.population[0][7] = -0.2212115329; model.population[0][8] = -0.5067996704; model.population[0][9] = 0.5193221773;...
} let config = Config { t_max: 1, population_size: 1, progress_bar: false, parallelize: false, ..Config::default() }; let pso = pso_rs::run(config, rosenbrock, None).unwrap(); let mut model = pso.model; model.population[0][0] = 2.0; model.population[...
random
[ { "content": "/// Initializes and returns a PSO instance without running the optimization process\n\n///\n\n/// Useful for initializing an instance for running at a later time\n\npub fn init(\n\n config: Config,\n\n obj_f: fn(&Particle, usize, &Vec<usize>) -> f64,\n\n) -> Result<PSO, &'static str> {\n\n ...
Rust
src/uucore/src/lib/features/process.rs
cohosh/coreutils
192380d0ba9213285c432ba96ced4212ff2cf40b
use libc::{gid_t, pid_t, uid_t}; use std::fmt; use std::io; use std::process::Child; use std::process::ExitStatus as StdExitStatus; use std::thread; use std::time::{Duration, Instant}; pub fn geteuid() -> uid_t { unsafe { libc::geteuid() } } pub fn getegid() -> gid_t { unsafe { libc::getegid() } } pub fn g...
use libc::{gid_t, pid_t, uid_t}; use std::fmt; use std::io; use std::process::Child; use std::process::ExitStatus as StdExitStatus; use std::thread; use std::time::{Duration, Instant}; pub fn geteuid() -> uid_t { unsafe { libc::geteuid() } } pub fn getegid() -> gid_t { unsafe { libc::getegid() } } pub fn g...
>= timeout { break; } thread::sleep(Duration::from_millis(100)); } Ok(None) } }
ExitStatus::Signal(code) => Some(code), _ => None, } } } impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ExitStatus::Code(code) => write!(f, "exit code: {}", code), ExitStatus::Signal(code) => write!(f, ...
random
[ { "content": "pub fn supports_pid_checks(pid: self::Pid) -> bool {\n\n unsafe { !(libc::kill(pid, 0) != 0 && get_errno() == libc::ENOSYS) }\n\n}\n\n\n", "file_path": "src/uu/tail/src/platform/unix.rs", "rank": 0, "score": 315309.2337243075 }, { "content": "pub fn supports_pid_checks(_pid:...
Rust
lib/analysis/constants.rs
2over12/falcon
0e7472c75c353aa1b1bd7d67814a458691d401c9
use analysis::fixed_point; use error::*; use executor::eval; use il; use std::cmp::{Ordering, PartialOrd}; use std::collections::HashMap; pub fn constants<'r>( function: &'r il::Function, ) -> Result<HashMap<il::ProgramLocation, Constants>> { let constants = fixed_point::fixed_point_forward(ConstantsAnalysis...
use analysis::fixed_point; use error::*; use executor::eval; use il; use std::cmp::{Ordering, PartialOrd}; use std::collections::HashMap; pub fn constants<'r>( function: &'r il::Function, ) -> Result<HashMap<il::ProgramLocation, Constants>> { let constants = fixed_point::fixed_point_forward(ConstantsAnalysis...
fn join(self, other: &Constants) -> Constants { let mut result = self.clone(); for (scalar, constant) in other.constants.iter() { match self.constants.get(scalar) { Some(c) => { if c != constant { result.set_scalar(scalar.clon...
r(scalar, &constant.clone().into()) .unwrap() }) }) }, )?; eval(&expression).ok() }
function_block-function_prefixed
[ { "content": "/// Compute definition use chains for the given function.\n\npub fn def_use(function: &il::Function) -> Result<HashMap<il::ProgramLocation, LocationSet>> {\n\n let rd = reaching_definitions::reaching_definitions(function)?;\n\n\n\n let mut du: HashMap<il::ProgramLocation, LocationSet> = Hash...
Rust
src/db/edition.rs
netology-group/event
b6ac78c377a9a50056e7c1f7bbc32f5f5789e507
use chrono::serde::ts_seconds; use chrono::{DateTime, Utc}; use serde_derive::{Deserialize, Serialize}; use sqlx::postgres::PgConnection; use svc_agent::AgentId; use uuid::Uuid; use crate::db::room::{Builder as RoomBuilder, Object as Room, Time as RoomTime}; #[derive(Clone, Debug, Deserialize, Serialize)] pub(crate) ...
use chrono::serde::ts_seconds; use chrono::{DateTime, Utc}; use serde_derive::{Deserialize, Serialize}; use sqlx::postgres::PgConnection; use svc_agent::AgentId; use uuid::Uuid; use crate::db::room::{Builder as RoomBuilder, Object as Room, Time as RoomTime}; #[derive(Clone, Debug, Deserialize, Serialize)] pub(crate) ...
Ok(Some((edition, room))) } } } } #[derive(Debug)] pub(crate) struct InsertQuery<'a> { source_room_id: Uuid, created_by: &'a AgentId, } impl<'a> InsertQuery<'a> { pub(crate) fn new(source_room_id: Uuid, created_by: &'a AgentId) -> Self { Self { ...
let room = RoomBuilder::new() .id(row.room_id) .audience(row.room_audience) .source_room_id(row.room_source_room_id) .time(row.room_time) .tags(row.room_tags) .created_at(row.room_created_at) ...
assignment_statement
[ { "content": "fn try_room_id(object: &[String]) -> StdResult<Uuid, AppError> {\n\n let object: Vec<&str> = object.iter().map(AsRef::as_ref).collect();\n\n\n\n match object.as_slice() {\n\n [\"rooms\", room_id, \"events\"] => {\n\n Uuid::parse_str(room_id).map_err(|err| anyhow!(\"UUID par...
Rust
src/commands/new.rs
gitter-badger/cargo-compete
fdf2e9b2a8be189c1319fe7d3bee93f939a47188
use crate::{project::MetadataExt as _, shell::ColorChoice}; use anyhow::Context as _; use snowchains_core::web::{ PlatformKind, RetrieveTestCasesOutcome, RetrieveTestCasesOutcomeContest, RetrieveTestCasesOutcomeProblem, }; use std::path::PathBuf; use structopt::StructOpt; use strum::VariantNames as _; use url::...
use crate::{project::MetadataExt as _, shell::ColorChoice}; use anyhow::Context as _; use snowchains_core::web::{ PlatformKind, RetrieveTestCasesOutcome, RetrieveTestCasesOutcomeContest, RetrieveTestCasesOutcomeProblem, }; use std::path::PathBuf; use structopt::StructOpt; use strum::VariantNames as _; use url::...
} PlatformKind::Codeforces => { let contest = contest.with_context(|| "`contest` is required for Codeforces")?; let problems = problems.map(|ps| ps.into_iter().collect()); let outcome = crate::web::retrieve_testcases::dl_from_codeforces( &contest, ...
if open { crate::open::open( &urls, cargo_compete_config.open, &file_paths, &pkg_manifest_dir, &workspace_root, shell, )?; }
if_condition
[ { "content": "pub fn run(opt: OptCompete, ctx: Context<'_>) -> anyhow::Result<()> {\n\n match opt {\n\n OptCompete::Init(opt) => commands::init::run(opt, ctx),\n\n OptCompete::Migrate(OptCompeteMigrate::CargoAtcoder(opt)) => {\n\n commands::migrate_cargo_atcoder::run(opt, ctx)\n\n ...
Rust
src/main.rs
trentsummerfield/abc-breaking
6249e1f43d4e768bc64e73a292e824c1280b1a45
extern crate native_tls; use native_tls::TlsConnector; use std::net::TcpStream; use std::io::{Read, Write}; fn main() { let tls_connector = TlsConnector::new().unwrap(); let stream = TcpStream::connect("www.abc.net.au:443").expect("Could not connect to abc"); let mut connection = tls_connector.connect("ab...
extern crate native_tls; use native_tls::TlsConnector; use std::net::TcpStream; use std::io::{Read, Write}; fn main() { let tls_connector = TlsConnector::new().unwrap(); let stream = TcpStream::connect("www.abc.net.au:443").expect("Could not connect to abc"); let mut connection = tls_connector.connect("ab...
} return result; } fn select_text_tokens<'a, 'b>(tokens: &'a Vec<&'b str>) -> Vec<&'b str> { return tokens .iter() .map(|s| *s) .filter(|s| !s.starts_with("<")) .map(|s| s.trim()) .filter(|s| s.len() > 0) .collect();...
if capture { result.push(t); if t.starts_with("<li") { nested += 1; } else if t.starts_with("</li") { if nested == 0 { capture = false; } else { nested -= 1; } } ...
if_condition
[ { "content": "# abc-breaking\n\nGet breaking news from abc.net.au/news\n", "file_path": "README.md", "rank": 8, "score": 14638.086857084203 } ]
Rust
crates/nu-cli/src/commands/where_.rs
RedlineTriad/nushell
6817b472d0c6d34abd87325514dc9389594e1d64
use crate::command_registry::CommandRegistry; use crate::commands::WholeStreamCommand; use crate::evaluate::evaluate_baseline_expr; use crate::prelude::*; use nu_errors::ShellError; use nu_protocol::{ hir::Block, hir::ClassifiedCommand, ReturnSuccess, Scope, Signature, SyntaxShape, }; pub struct Where; #[derive(D...
use crate::command_registry::CommandRegistry; use crate::commands::WholeStreamCommand; use crate::evaluate::evaluate_baseline_expr; use crate::prelude::*
} else { None } } Err(e) => Some(Err(e)), }, Err(e) => Some(Err(e)), } } }) .to_output_stream()) } #[c...
; use nu_errors::ShellError; use nu_protocol::{ hir::Block, hir::ClassifiedCommand, ReturnSuccess, Scope, Signature, SyntaxShape, }; pub struct Where; #[derive(Deserialize)] pub struct WhereArgs { block: Block, } #[async_trait] impl WholeStreamCommand for Where { fn name(&self) -> &str { "where" ...
random
[ { "content": "#[test]\n\nfn copy_files_using_glob_two_parents_up_using_multiple_dots() {\n\n Playground::setup(\"cp_test_9\", |dirs, sandbox| {\n\n sandbox.within(\"foo\").within(\"bar\").with_files(vec![\n\n EmptyFile(\"jonathan.json\"),\n\n EmptyFile(\"andres.xml\"),\n\n ...
Rust
tremor-script/src/ast/test.rs
scrabsha/tremor-runtime
8361e2facafb49a73ac553a9bf7f52d65af1bc63
use matches::assert_matches; use super::*; use crate::{CustomFn, NodeMeta}; fn v(s: &'static str) -> ImutExpr<'static> { ImutExpr::literal(NodeMeta::dummy(), Value::from(s)) } fn p() -> ImutExpr<'static> { ImutExpr::Path(Path::State(StatePath { mid: NodeMeta::dummy(), segments: vec![], ...
use matches::assert_matches; use super::*; use crate::{CustomFn, NodeMeta}; fn v(s: &'static str) -> ImutExpr<'static> { ImutExpr::literal(NodeMeta::dummy(), Value::from(s)) } fn p() -> ImutExpr<'static> { ImutExpr::Path(Path::State(StatePath { mid: NodeMeta::dummy(), segments: vec![], ...
#[test] fn as_invoke() { let invocable = Invocable::Tremor(CustomFn { name: "f".into(), body: Vec::new(), args: Vec::new(), open: false, locals: 0, is_const: false, inline: false, }); let i = Invoke { mid: NodeMeta::dummy(), node_id: N...
fn as_list() { let i = v("snot"); assert!(i.as_list().is_none()); let i = ImutExpr::List(List { mid: Box::new(i.meta().clone()), exprs: vec![], }); assert!(i.as_list().is_some()); }
function_block-full_function
[ { "content": "fn ok(op_name: &'static str, k: Vec<u8>, v: Value<'static>) -> (Value<'static>, Value<'static>) {\n\n (\n\n v,\n\n literal!({\n\n \"kv\": {\n\n \"op\": op_name,\n\n \"ok\": Value::Bytes(k.into())\n\n }\n\n }),\n\n )\n\n...
Rust
src/kem.rs
BoOTheFurious/rust-hpke
02f4ad2780055f93a68cbd770337a8574cc7e97c
use crate::{ kdf::{extract_and_expand, Kdf as KdfTrait}, kex::{Deserializable, KeyExchange, Serializable, MAX_PUBKEY_SIZE}, util::kem_suite_id, HpkeError, }; use digest::FixedOutput; use generic_array::GenericArray; use rand_core::{CryptoRng, RngCore}; pub trait Kem: Sized { type Kex: KeyExchange;...
use crate::{ kdf::{extract_and_expand, Kdf as KdfTrait}, kex::{Deserializable, KeyExchange, Serializable, MAX_PUBKEY_SIZE}, util::kem_suite_id, HpkeError, }; use digest::FixedOutput; use generic_array::GenericArray; use rand_core::{CryptoRng, RngCore}; pub trait Kem: Sized { type Kex: KeyExchange;...
] mod p256_tests { use super::*; test_encap_correctness!(test_encap_correctness_p256, crate::kem::DhP256HkdfSha256); test_encapped_serialize!(test_encapped_serialize_p256, crate::kem::DhP256HkdfSha256); } }
.expect("shared secret is way too big"); buf }; Ok((shared_secret, encapped_key)) } pub(crate) fn encap<Kem: KemTrait, R>( pk_recip: &KemPubkey<Kem>, sender_id_keypair: Option<&(KemPrivkey<Kem>, KemPubkey<Kem>)>, csprng: &mut R, ) -> Result<(SharedSecret<Kem>, EncappedKey<Kem:...
random
[ { "content": "// def SetupAuthPSKI(pkR, info, psk, psk_id, skI):\n\n// shared_secret, enc = AuthEncap(pkR, skI)\n\n// return enc, KeySchedule(mode_auth_psk, shared_secret, info, psk, psk_id)\n\n/// Initiates an encryption context to the given recipient public key\n\n///\n\n/// Return Value\n\n/// ==========...
Rust
minicbor/src/encode.rs
jredrado/minicbor
15b16381c92e67c87d81bd5f3237f10f3cb8a6b1
mod encoder; mod error; pub mod write; pub use encoder::Encoder; pub use error::Error; pub use write::Write; pub trait Encode { fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), Error<W::Error>>; } impl<T: Encode + ?Sized> Encode for &T { fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Re...
mod encoder; mod error; pub mod write; pub use encoder::Encoder; pub use error::Error; pub use write::Write; pub trait Encode { fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), Error<W::Error>>; } impl<T: Encode + ?Sized> Encode for &T { fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Re...
(1) } 3 => { A(0) B(1) C(2) } 4 => { A(0) B(1) C(2) D(3) } 5 => { A(0) B(1) C(2) D(3) E(4) } 6 => { A(0) B(1) C(2) D(3) E(4) F(5) } 7 => { A(0) B(1) C(2) D(3) E(4) F(5) G(6) } 8 => { A(0) B(1) C(2) D(3) E(4) F(5) G(6) H(7) } 9 => { A(0) B(1) C(2) D(3) E(4) F(5) G(6) H(7) I(8) } 10...
&mut Encoder<W>) -> Result<(), Error<W::Error>> { e.array(0)?.ok() } } impl Encode for () { fn encode<W: Write>(&self, e: &mut Encoder<W>) -> Result<(), Error<W::Error>> { e.array(0)?.ok() } } #[cfg(target_pointer_width = "32")] impl Encode for usize { fn encode<W: Write>(&self, e: &mu...
random
[ { "content": "#[cfg(feature = \"derive\")]\n\npub fn encode<T, W>(xs: &T, e: &mut Encoder<W>) -> Result<(), encode::Error<W::Error>>\n\nwhere\n\n T: EncodeBytes,\n\n W: Write\n\n{\n\n T::encode_bytes(xs, e)\n\n}\n\n\n", "file_path": "minicbor/src/bytes.rs", "rank": 0, "score": 262865.194829...
Rust
tests/test_metainfo.rs
MateuszJanda/rdest
2b50e35f3db9fa644c683f3df706ae82bd8649cd
use rdest::hashmap; use rdest::{BValue, Error, File, Metainfo}; #[test] fn find_announce_incorrect() { assert_eq!( Metainfo::find_announce(&hashmap![b"announce".to_vec() => BValue::Int(5)]), Err(Error::MetaIncorrectOrMissing("announce")) ); } #[test] fn find_announce_ok() { assert_eq!( ...
use rdest::hashmap; use rdest::{BValue, Error, File, Metainfo}; #[test] fn find_announce_incorrect() { assert_eq!( Metainfo::find_announce(&hashmap![b"announce".to_vec() => BValue::Int(5)]), Err(Error::MetaIncorrectOrMissing("announce")) ); } #[test] fn find_announce_ok() { assert_eq!( ...
#[test] fn find_pieces_incorrect() { assert_eq!( Metainfo::find_pieces( &hashmap![b"info".to_vec() => BValue::Dict(hashmap![b"pieces".to_vec() => BValue::Int(12)])] ), Err(Error::MetaIncorrectOrMissing("pieces")) ); } #[test] fn find_pieces_not_divisible() { assert_eq!...
fn find_piece_length_ok() { assert_eq!( Metainfo::find_piece_length( &hashmap![b"info".to_vec() => BValue::Dict(hashmap![b"piece length".to_vec() => BValue::Int(12)])] ), Ok(12) ); }
function_block-full_function
[ { "content": "#[test]\n\nfn byte_str_zero_length() {\n\n assert_eq!(\n\n BDecoder::from_array(b\"0:\"),\n\n Ok(vec![BValue::ByteStr(vec![])])\n\n );\n\n}\n\n\n", "file_path": "tests/test_bdecoder.rs", "rank": 30, "score": 107489.47795656873 }, { "content": "#[test]\n\nfn ...
Rust
flo/src/animation_canvas/canvas_renderer.rs
adamnemecek/flowbetween
6c03b81d29dfc55bd46b4f686fdfb7f96efe38b2
use super::super::model::*; use flo_ui::*; use flo_canvas::*; use flo_binding::*; use flo_animation::*; use std::sync::*; use std::collections::HashMap; struct FrameLayer { layer_id: u32, layer_frame: Arc<dyn Frame>, active_brush: Option<(BrushDefinition, BrushDraw...
use super::super::model::*; use flo_ui::*; use flo_canvas::*; use flo_binding::*; use flo_animation::*; use std::sync::*; use std::collections::HashMap; struct FrameLayer { layer_id: u32, layer_frame: Arc<dyn Frame>, active_brush: Option<(BrushDefinition, BrushDraw...
} impl CanvasRenderer { pub fn new() -> CanvasRenderer { CanvasRenderer { frame_layers: HashMap::new(), overlay_layers: HashMap::new(), annotated_layer: None } } pub fn clear(&mut self) { self.frame_lay...
pub fn new() -> OverlayLayer { OverlayLayer { layers: HashMap::new(), active_layer: 0, drawing: Canvas::new() } }
function_block-function_prefix_line
[]
Rust
tests/src/script_tests/account_lock_scripts/eth_account_lock.rs
magicalne/godwoken-scripts
3ea1d8a4915848fe4d63dbac1cc69b63dd85db90
use crate::script_tests::utils::layer1::*; use crate::testing_tool::programs::{ ALWAYS_SUCCESS_CODE_HASH, ALWAYS_SUCCESS_PROGRAM, ETH_ACCOUNT_LOCK_PROGRAM, SECP256K1_DATA, }; use ckb_crypto::secp::{Generator, Privkey, Pubkey}; use ckb_error::assert_error_eq; use ckb_script::{ScriptError, TransactionScriptsVerifier}...
use crate::script_tests::utils::layer1::*; use crate::testing_tool::programs::{ ALWAYS_SUCCESS_CODE_HASH, ALWAYS_SUCCESS_PROGRAM, ETH_ACCOUNT_LOCK_PROGRAM, SECP256K1_DATA, }; use ckb_crypto::secp::{Generator, Privkey, Pubkey}; use ckb_error::assert_error_eq; use ckb_script::{ScriptError, TransactionScriptsVerifier}...
fn sign_message(key: &Privkey, message: [u8; 32]) -> Bytes { let message = { let mut hasher = Keccak256::new(); hasher.update("\x19Ethereum Signed Message:\n32"); hasher.update(&message); let buf = hasher.finalize(); let mut signing_message = [0u8; 32]; signing...
fn gen_tx(dummy: &mut DummyDataLoader, lock_args: Bytes, message: Bytes) -> TransactionView { let mut rng = thread_rng(); let script_out_point = { let tx_hash = { let mut buf = [0u8; 32]; rng.fill(&mut buf); buf.pack() }; OutPoint::new(tx_hash.clo...
function_block-full_function
[ { "content": "pub fn sha3_pubkey_hash(pubkey: &Pubkey) -> Bytes {\n\n let mut hasher = Keccak256::new();\n\n hasher.update(&pubkey.as_bytes());\n\n let buf = hasher.finalize();\n\n buf[12..].to_vec().into()\n\n}\n\n\n", "file_path": "tests/src/script_tests/account_lock_scripts/tron_account_lock....
Rust
src/lib.rs
Atul9/interpolate
36d9cb3ecf8f6a5c8b7091f201ea75b367f76d5a
#![crate_type = "proc-macro"] #![feature(proc_macro_hygiene, proc_macro_quote)] extern crate proc_macro; use proc_macro::{TokenStream, TokenTree, quote}; use std::str::FromStr; #[derive(Debug, Copy, Clone)] enum Position { Literal, ExpressionDelim, ExpressionWrapped, Rest, }...
#![crate_type = "proc-macro"] #![feature(proc_macro_hygiene, proc_macro_quote)] extern crate proc_macro; use proc_macro::{TokenStream, TokenTree, quote}; use std::str::FromStr; #[derive(Debug, Copy, Clone)] enum Position { Literal, ExpressionDelim, ExpressionWrapped, Rest, }...
text.get_unchecked(lit_start..delim), text.get_unchecked(exp_start..exp_end).trim().replace("{{", "{").replace("}}", "}"), )}; fmt_args.fmt.push_str(lit); fmt_args.fmt.push_str("{}"); fmt_args.args.push( proc_...
tate = Position::Literal; let mut fmt_args = FmtArgs::new(); let (mut lit_start, mut delim, mut exp_start, mut exp_end) = (0, text.len(), text.len(), text.len()); for (i, c) in text.char_indices() { match state { Position::Literal if c == '{' => { ...
random
[ { "content": "Interpolate\n\n==========\n\n\n\nA simple form of Rust string interpolation, e.g., `s!(\"Today is {date}\")`.\n\n\n\n[Documentation](http://docs.rs/interpolate)\n\n\n\n[![Crates.io](https://img.shields.io/crates/v/interpolate.svg?maxAge=2592000)](https://crates.io/crates/interpolate)\n\n\n\n\n\n##...
Rust
src/entry/mod.rs
protometa/accounts
25a2bbe21fe4b8ffbc2314160e7a1d55b24ed57f
mod raw; use super::money::Money; use anyhow::{bail, Context, Error, Result}; use chrono::prelude::*; use chrono_tz::UTC; use rrule::{Frequenzy, Options, RRule}; use rust_decimal::Decimal; use std::convert::{TryFrom, TryInto}; use std::iter::{self, Iterator}; use std::str::FromStr; #[derive(Debug)] pub struct Entry {...
mod raw; use super::money::Money; use anyhow::{bail, Context, Error, Result}; use chrono::prelude::*; use chrono_tz::UTC; use rrule::{Frequenzy, Options, RRule}; use rust_decimal::Decimal; use std::convert::{TryFrom, TryInto}; use std::iter::{self, Iterator}; use std::str::FromStr; #[derive(Debug)] pub struct Entry {...
} } impl FromStr for Entry { type Err = Error; fn from_str(doc: &str) -> Result<Self> { let mut raw_entry: raw::Entry = serde_yaml::from_str(doc) .with_context(|| format!("Failed to deserialize Entry:\n{}", doc))?; let id = format!( "{}|{}|{}|{}", raw_en...
Ok(Entry { id: raw_entry.id.clone().context("Id missing!")?, date: raw_entry.repeat.clone().map_or::<Result<_>, _>( Ok(EntryDate::SingleDate(date)), |rule_str| { let ed = match rule_str.to_uppercase().as_s...
call_expression
[ { "content": "type LineItem = (Vec<String>, Sign, Total);\n\n\n\nimpl ReportNode {\n\n pub async fn from_file(file: &str) -> Result<Self> {\n\n let doc = fs::read_to_string(file).await?;\n\n doc.parse()\n\n }\n\n\n\n pub fn apply_balance(\n\n &mut self,\n\n (account, balance...
Rust
garnet/bin/setui/src/agent/authority.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use crate::agent::{AgentError, BlueprintHandle, Context, Invocation, Lifespan, Payload}; use crate::base::SettingType; use crate::message::base::{Audience, MessengerType}; use crate::monitor; use crate::policy::PolicyType; use crate::service; use crate::service_context::ServiceContext; use anyhow::{format_err, Contex...
use crate::agent::{AgentError, BlueprintHandle, Context, Invocation, Lifespan, Payload}; use crate::base::SettingType; use crate::message::base::{Audience, MessengerType}; use crate::monitor; use crate::policy::PolicyType; use crate::service; use crate::service_context::ServiceContext; use anyhow::{format_err, Contex...
receptor = self .delegate .create(MessengerType::Unbound) .await .expect("agent receptor should be created") .1; let signature = agent_receptor.get_signature(); blueprint .create( Context::new( ag...
tion<monitor::environment::Actor>, } impl Authority { pub(crate) async fn create( delegate: service::message::Delegate, available_components: HashSet<SettingType>, available_policies: HashSet<PolicyType>, resource_monitor_actor: Option<monitor::environment::Actor>, ) -> Result<A...
random
[]
Rust
src/dec/sbac.rs
rainliu/revc
ee865eef0534dc7124eba9be68929a87b3c7f8f1
use super::bsr::*; use crate::api::*; use crate::def::*; use crate::tracer::*; /***************************************************************************** * SBAC structure *****************************************************************************/ #[derive(Default)] pub(crate) struct EvcdSbac { pub(crate) ...
use super::bsr::*; use crate::api::*; use crate::def::*; use crate::tracer::*; /***************************************************************************** * SBAC structure *****************************************************************************/ #[derive(Default)] pub(crate) struct EvcdSbac { pub(crate) ...
if symbol == 0 { break; } ctx_idx += 1; } } Ok(ctx_idx) } }
let symbol = self.decode_bin( bs, &mut models[if ctx_idx > num_ctx - 1 { num_ctx - 1 } else { ctx_idx } as usize], )?;
assignment_statement
[ { "content": "fn evce_eco_abs_mvd(bs: &mut EvceBsw, sbac: &mut EvceSbac, model: &mut SBAC_CTX_MODEL, sym: u32) {\n\n let val = sym;\n\n\n\n let mut nn = ((val + 1) >> 1);\n\n let mut len_i = 0;\n\n while len_i < 16 && nn != 0 {\n\n nn >>= 1;\n\n len_i += 1;\n\n }\n\n\n\n let info...
Rust
crates/mem-pool/src/mem_block.rs
driftluo/godwoken
667a4bc435a9894b131cd804daf6403fd5cd4026
use std::{collections::HashSet, time::Duration}; use gw_common::{merkle_utils::calculate_state_checkpoint, H256}; use gw_types::{ offchain::{CollectedCustodianCells, DepositInfo}, packed::{self, AccountMerkleState, BlockInfo, L2Block, TxReceipt}, prelude::*, }; pub struct MemBlockContent { pub withdra...
use std::{collections::HashSet, time::Duration}; use gw_common::{merkle_utils::calculate_state_checkpoint, H256}; use gw_types::{ offchain::{CollectedCustodianCells, DepositInfo}, packed::{self, AccountMerkleState, BlockInfo, L2Block, TxReceipt}, prelude::*, }; pub struct MemBlockContent { pub withdra...
; log::debug!( "[mem-block] push tx {} state {}", hex::encode(tx_hash.as_slice()), hex::encode(state_checkpoint.as_slice()) ); self.txs.push(tx_hash); self.txs_set.insert(tx_hash); self.state_checkpoints.push(state_checkpoint); } pub f...
calculate_state_checkpoint( &post_state.merkle_root().unpack(), post_state.count().unpack(), )
call_expression
[ { "content": "pub fn is_mature(number: u64, tx_index: u64, max_mature_number: u64) -> bool {\n\n // Not cellbase cell\n\n tx_index > 0\n\n // Live cells in genesis are all mature\n\n || number == 0\n\n || number <= max_mature_number\n\n}\n\n\n", "file_path": "crates/tools/src/deploy_g...
Rust
common/proptest-helpers/src/unit_tests/repeat_vec_tests.rs
GreyHyphen/dijets
8c94c5c079fd025929dbd0455fc0e76d62e418c2
use crate::RepeatVec; use proptest::{ collection::vec, prelude::*, sample::Index as PropIndex, test_runner::TestCaseResult, }; use proptest_derive::Arbitrary; use std::{ collections::HashSet, fmt, iter, sync::atomic::{AtomicUsize, Ordering}, }; trait RepeatVecMethods<T>: fmt::Debug { fn len(&self...
use crate::RepeatVec; use proptest::{ collection::vec, prelude::*, sample::Index as PropIndex, test_runner::TestCaseResult, }; use proptest_derive::Arbitrary; use std::{ collections::HashSet, fmt, iter, sync::atomic::{AtomicUsize, Ordering}, }; trait RepeatVecMethods<T>: fmt::Debug { fn len(&self...
epeatVecMethods<&'static str>) { let mut repeat_vec = repeat_vec; repeat_vec.extend("foo", 3); repeat_vec.extend("bar", 4); repeat_vec.extend("baz", 0); assert_eq!(repeat_vec.len(), 7); assert_eq!(repeat_vec.get(0), Some((&"foo", 0))); assert_eq!(repeat_vec.get(1), Some((&"foo", 1)));...
*offset)) } } #[derive(Clone, Debug, Eq, Hash, PartialEq)] struct Counter(usize); impl Counter { fn next() -> Self { static COUNTER_NEXT: AtomicUsize = AtomicUsize::new(0); Counter(COUNTER_NEXT.fetch_add(1, Ordering::AcqRel)) } fn strategy() -> impl Strategy<Value = Self> { ...
random
[ { "content": "#[inline]\n\npub fn pick_slice_idxs(max: usize, indexes: &[impl AsRef<PropIndex>]) -> Vec<usize> {\n\n pick_idxs(max, indexes, indexes.len())\n\n}\n\n\n\n/// Wrapper for `proptest`'s [`Index`][proptest::sample::Index] that allows `AsRef` to work.\n\n///\n\n/// There is no blanket `impl<T> AsRef...
Rust
src/main.rs
DanielKulkamp/simurust
81343eeb7bf1d6be153ca0f31915d17868bdb09a
use std::cmp::Ordering; use std::fs; use std::collections::HashMap; use rand::{thread_rng, Rng}; #[derive(Debug)] struct Team { name: String, games: i32, wins: i32, draws: i32, losses: i32, goals_for: i32, goals_against: i32, goal_difference: i32, home_wins: i32, home_draws: i32...
use std::cmp::Ordering; use std::fs; use std::collections::HashMap; use rand::{thread_rng, Rng}; #[derive(Debug)] struct Team { name: String, games: i32, wins: i32, draws: i32, losses: i32, goals_for: i32, goals_against: i32, goal_difference: i32, home_wins: i32, home_draws: i32...
.0 * (*relegation_map.get(team).unwrap() as f32) / (n_simulacoes as f32); println!("{}\t{:>5.2}\t{:>5.2}\t{:>5.2}",team, title, promotion, relegation); } println!("\nPor Pontuação:"); for i in 16..90 { println!("{}: Titulo: {:>5.2}, \tAcesso: {:>5.2}\tQueda: {:>5.2}", i, *title_poi...
s = vec!["CFC", "BOT", "AVA", "CRB", "GOI", "GUA", "CSA", "VAS", "REM", "SAM", "PON", "OPE", "NAU", "CRU", "VIL", "LON", "VIT", "BRU", "CON", "BRA"]; let mut promotion_map : HashMap<&str, i32> = HashMap::new(); let mut title_map : HashMap<&str, i32> = HashMap::new(); let mut relegation_map : Ha...
function_block-random_span
[ { "content": "# simurust", "file_path": "README.md", "rank": 2, "score": 6783.801413701147 } ]
Rust
crates/crunch-codegen/src/llvm/types/integer.rs
namibj/crunch-lang
0d02433cd72d8b1a7171ebac6df8b355e3f8f5c4
use crate::llvm::{ types::{AnyType, SealedAnyType, Type}, utils::{to_non_nul, Sealed}, values::{IntValue, Pointable, SealedAnyValue}, Context, Result, }; use llvm_sys::{ core::{ LLVMConstInt, LLVMGetIntTypeWidth, LLVMInt128TypeInContext, LLVMInt16TypeInContext, LLVMInt1TypeInContext,...
use crate::llvm::{ types::{AnyType, SealedAnyType, Type}, utils::{to_non_nul, Sealed}, values::{IntValue, Pointable, SealedAnyValue}, Context, Result, }; use llvm_sys::{ core::{ LLVMConstInt, LLVMGetIntTypeWidth, LLVMInt128TypeInContext, LLVMInt16TypeInContext, LLVMInt1TypeInContext,...
b struct I1(()); impl IntWidth for I1 {} impl Sealed for I1 {} pub struct Unknown(()); impl IntWidth for Unknown {} impl Sealed for Unknown {} macro_rules! int_width { ($($width:ty),* $(,)?) => { $( impl IntWidth for $width {} impl Sealed for $width {} )* }; } int_wi...
x, Unknown>> { unsafe { IntType::from_raw(LLVMIntTypeInContext(ctx.as_mut_ptr(), bits)) } } pub fn width(self) -> u32 { unsafe { LLVMGetIntTypeWidth(self.as_mut_ptr()) } } pub fn constant(self, value: u64, sign_extend: bool) -> Result<IntValue<'ctx>> { unsafe { ...
random
[ { "content": "pub fn std_pow32___Bitval32_2(base: &std_u32, exp: &u32) -> std_u32 {\n\n std_u32_pow32(base, exp)\n\n}\n", "file_path": "crates/crunch-typecheck/typecheck_ddlog/types/lib.rs", "rank": 0, "score": 305423.26403407566 }, { "content": "pub fn format_ddlog_str(s: &str, f: &mut f...
Rust
src/cue.rs
gyng/rcue
9ecd1ccbb764acfb7d54c3395525a4c85b43daea
use std::time::Duration; #[derive(Clone, Debug, PartialEq)] pub enum Command { Rem(String, String), Catalog(String), CdTextFile(String), Flags(Vec<String>), Isrc(String), Songwriter(String), Performer(String), Title(String...
use std::time::Duration; #[derive(Clone, Debug, PartialEq)] pub enum Command { Rem(String, String), Catalog(String), CdTextFile(String), Flags(Vec<String>), Isrc(String), Songwriter(String), Performer(String), Title(String...
}
pub fn new() -> Self { Self { files: Vec::new(), songwriter: None, cd_text_file: None, title: None, performer: None, catalog: None, comments: Vec::new(), unknown: Vec::new(), } }
function_block-full_function
[ { "content": "/// Unescapes a string in a CUE field.\n\n///\n\n/// Strings in a CUE field are delimited by double quotation marks (`\"`).\n\n///\n\n/// ```text\n\n/// // Example line from a CUE\n\n/// TITLE \"My \\\"Cute\\\" Song Title\"\n\n/// ```\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use rcue::util...
Rust
src/config/routing_map.rs
antimonyproject/antimony-core
2d581b3ec3283a3e70b86c7346e07d903059bbdc
use std::collections::HashMap; use config::physical_plan::PhysicalPlan; use tokio_core::net::TcpStream; use tokio_uds::UnixStream; use tokio_io::io::WriteHalf; use utils::message::Message; use futures::Future; use tokio_io; use tokio_core::reactor::Handle; #[derive(Debug)] pub enum RoutingConnection{ ...
use std::collections::HashMap; use config::physical_plan::PhysicalPlan; use tokio_core::net::TcpStream; use tokio_uds::UnixStream; use tokio_io::io::WriteHalf; use utils::message::Message; use futures::Future; use tokio_io; use tokio_core::reactor::Handle; #[derive(Debug)] pub enum RoutingConnection{ ...
.push(ConnId::Tcp(sm.to_string())); } }, None => {} } } } RoutingMap{streams: streams, connections: HashMap::new()} } pub fn register(&mut self, id: String, conn: RoutingConnection...
, components) in &physical_plan.topology{ for i in &components.instances{ match i.input_stream.as_ref(){ Some(input_stream) => { if !streams.contains_key(input_stream){ streams.insert(input_stream.clone(), HashMap::new()...
random
[ { "content": "struct LoggingWatcher;\n\nimpl Watcher for LoggingWatcher {\n\n fn handle(&self, _: WatchedEvent){}\n\n}\n\n\n\n#[derive(Clone)]\n\npub enum StorageType{\n\n Zookeeper\n\n}\n\n\n\npub struct Storage{\n\n zk_connection: Option<ZooKeeper>,\n\n pub topology_name: String,\n\n config: (S...
Rust
src/models/test_schedule.rs
csharad/paryxa
2f1b3fd933af34909efc503f834ecd5076db11c8
use chrono::{Duration, NaiveDateTime, Utc}; use diesel::{self, prelude::*}; use errors::SResult; use models::test_paper::TestPaper; use schema::test_schedules; use uuid::Uuid; #[derive(Identifiable, Queryable)] pub struct TestSchedule { pub id: i32, pub uuid: Uuid, pub test_paper_id: i32, pub time: Nai...
use chrono::{Duration, NaiveDateTime, Utc}; use diesel::{self, prelude::*}; use errors::SResult; use models::test_paper::TestPaper; use schema::test_schedules; use uuid::Uuid; #[derive(Identifiable, Queryable)] pub struct TestSchedule { pub id: i32, pub uuid: Uuid, pub test_paper_id: i32, pub time: Nai...
}
pub fn save(self, conn: &PgConnection) -> SResult<TestSchedule> { let schedule_patch = TestSchedulePatch { time: self.time, duration: self.duration, }; schedule_patch.save(self.id, conn) }
function_block-full_function
[ { "content": "/// Reads a `BasicUser` from a Basic Auth Request.\n\npub fn basic() -> impl Filter<Extract = (BasicUser,), Error = Rejection> + Copy {\n\n warp::header(\"Authorization\").and_then(parse_authorization)\n\n}\n\n\n", "file_path": "src/basic.rs", "rank": 2, "score": 99152.95404847476 ...
Rust
ycommon/src/runner_proto.rs
xuwaters/editor.sh
9bf4b6b06d091c6c3363cf2c91dc9e88692e3c91
use actix::prelude::Message; use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Clone, Deserialize, Serialize, Message)] #[serde(rename_all = "snake_case")] pub struct ServiceStats { pub rooms: Vec<String>, } #[derive(Debug, Clone, Deserialize, Serialize, Message)] #[serde(rename_all = "snake_case")] pub...
use actix::prelude::Message; use serde_derive::{Deserialize, Serialize}; #[derive(Debug, Clone, Deserialize, Serialize, Message)] #[serde(rename_all = "snake_case")] pub struct ServiceStats { pub rooms: Vec<String>, } #[derive(Debug, Clone, Deserialize, Serialize, Message)] #[serde(rename_all = "snake_case")] pub...
} #[derive(Debug, Clone, Deserialize, Serialize, Message)] #[serde(rename_all = "snake_case")] pub enum ServiceError { ErrServiceInternal, ErrInitRoomExists, } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub struct InitResp {} #[derive(Debug, Clone, Deserial...
fn into(self) -> Result<T, ServiceError> { match self { ServiceResult::Ok(v) => Result::Ok(v), ServiceResult::Err(e) => Result::Err(e), } }
function_block-full_function
[ { "content": "fn handle_room_socket(r: &HttpRequest<AppState>) -> Result<HttpResponse, Error> {\n\n ws::start(r, room::RoomClientSession::new())\n\n}\n", "file_path": "yeditor/src/app/server.rs", "rank": 0, "score": 188346.14834426434 }, { "content": "pub fn launch() -> Fallible<()> {\n\n...
Rust
src/vtok_agent/src/agent/mod.rs
andrewhop/aws-nitro-enclaves-acm
1b7d538da7ae1b470e2ce7d9464dabc3526c99fb
mod mngtok; use std::collections::HashSet; use std::process::Command; use std::rc::Rc; use std::sync::atomic::Ordering; use std::time::{Duration, Instant}; use log::{debug, error, info, warn}; use nix::{sys::signal, unistd}; use crate::config; use crate::gdata; use crate::imds; use crate::util; use crate::{enclave...
mod mngtok; use std::collections::HashSet; use std::process::Command; use std::rc::Rc; use std::sync::atomic::Ordering; use std::time::{Duration, Instant}; use log::{debug, error, info, warn}; use nix::{sys::signal, unistd}; use crate::config; use crate::gdata; use crate::imds; use crate::util; use crate::{enclave...
}
fn reload_nginx(force_start: bool, wait_ms: u64) { info!("Reloading NGINX config"); Command::new("systemctl") .args(&["show", "--property=MainPID", "nginx.service"]) .output() .map_err(Error::SystemdExecError) .and_then(|output| { if !outpu...
function_block-full_function
[ { "content": "pub fn partition() -> Result<String, Error> {\n\n get_with(|cache| cache.partition.clone())\n\n}\n\n\n", "file_path": "src/vtok_agent/src/imds.rs", "rank": 0, "score": 293499.4928571878 }, { "content": "pub fn region() -> Result<String, Error> {\n\n get_with(|cache| cache...
Rust
ctr/src/lib.rs
jpdoyle/stream-ciphers
b014bfa8f67099ebf42b0f4e158e52c0f45a2824
#![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" )] #![warn(missing_docs, rust_2018_idioms)] pub use cipher; use cipher::{ errors::{LoopError, OverflowError}, ...
#![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" )] #![warn(missing_docs, rust_2018_idioms)] pub use cipher; use cipher::{ errors::{LoopError, OverflowError}, ...
} impl<B, F> fmt::Debug for Ctr<B, F> where B: BlockEncrypt + BlockCipher<BlockSize = U16> + fmt::Debug, B::ParBlocks: ArrayLength<GenericArray<u8, U16>>, B::BlockSize: Div<F::Size>, F: CtrFlavor + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { write!(f...
s != 0 { let mut block = self.counter.generate_block(&self.nonce); self.cipher.encrypt_block(&mut block); self.buffer = block; } Ok(()) }
function_block-function_prefixed
[ { "content": "/// Compute nonce as used by AES-GCM-SIV\n\nfn nonce(bytes: &[u8; 16]) -> GenericArray<u8, U16> {\n\n let mut n = *bytes;\n\n n[15] |= 0x80;\n\n n.into()\n\n}\n\n\n", "file_path": "ctr/tests/ctr32/little_endian.rs", "rank": 0, "score": 210270.75177068854 }, { "content"...
Rust
cursive-core/src/views/scroll_view.rs
FliegendeWurst/cursive
20d9d321c16ff77f6c2b04f0a8f6cbc4f17c1ea0
use crate::{ direction::Direction, event::{AnyCb, Event, EventResult}, view::{scroll, ScrollStrategy, Selector, View}, Cursive, Printer, Rect, Vec2, With, }; use std::rc::Rc; pub struct ScrollView<V> { inner: V, core: scroll::Core, on_scroll: Rc<dyn Fn(&mut Self, Rect) -> EventResul...
use crate::{ direction::Direction, event::{AnyCb, Event, EventResult}, view::{scroll, ScrollStrategy, Selector, View}, Cursive, Printer, Rect, Vec2, With, }; use std::rc::Rc; pub struct ScrollView<V> { inner: V, core: scroll::Core, on_scroll: Rc<dyn Fn(&mut Self, Rect) -> EventResul...
} fn layout(&mut self, size: Vec2) { scroll::layout( self, size, self.inner.needs_relayout(), |s, si| s.inner.layout(si), |s, c| s.inner.required_size(c), ); } fn needs_relayout(&self) -> bool { self.core.needs_relayo...
match scroll::on_event( self, event, |s, e| s.inner.on_event(e), |s, si| s.inner.important_area(si), ) { EventResult::Ignored => EventResult::Ignored, other => other.and(self.on_scroll_callback()), }
if_condition
[ { "content": "/// Wraps a `FnMut` into a `Fn`\n\n///\n\n/// This can be used to use a `FnMut` when a callack expects a `Fn`.\n\n///\n\n/// # Note\n\n///\n\n/// If the resulting `Fn` is called recursively, subsequent calls will be\n\n/// no-ops.\n\npub fn immutify<F: FnMut(&mut Cursive)>(\n\n f: F,\n\n) -> im...
Rust
examples/cryptocurrency-advanced/backend/src/transactions.rs
if1242/blockchaincup_case_3_plains
1173cb3e72fb556741d0ef728b45afe528217345
use exonum::blockchain::{ExecutionError, ExecutionResult, Transaction}; use exonum::crypto::{CryptoHash, PublicKey}; use exonum::messages::Message; use exonum::storage::Fork; use CRYPTOCURRENCY_SERVICE_ID; use schema::CurrencySchema; use wallet::Detail; #[derive(Debug, Fail)] #[repr(u8)] pub enum Error { ...
use exonum::blockchain::{ExecutionError, ExecutionResult, Transaction}; use exonum::crypto::{CryptoHash, PublicKey}; use exonum::messages::Message; use exonum::storage::Fork; use CRYPTOCURRENCY_SERVICE_ID; use schema::CurrencySchema; use wallet::Detail; #[derive(Debug, Fail)] #[repr(u8)] pub enum Error { ...
}
f.name(); schema.create_wallet(pub_key, name, &hash); Ok(()) } else { Err(Error::WalletAlreadyExists)? } }
function_block-function_prefixed
[ { "content": "pub fn set_index_type(name: &str, index_type: IndexType, is_family: bool, view: &mut Fork) {\n\n if name == INDEXES_METADATA_TABLE_NAME {\n\n panic!(\"Attempt to access an internal storage infrastructure\");\n\n }\n\n let mut metadata = BaseIndex::indexes_metadata(view);\n\n if ...
Rust
nnsplit/src/tract_backend.rs
UncleLiaoNN/nnsplit
1cbbf612abc00f0d26ce3d86bb66d1cc3feb4dee
use crate::{NNSplitLogic, NNSplitOptions}; use ndarray::prelude::*; use std::error::Error; use tract_onnx::prelude::*; struct TractBackend { model: TypedModel, n_outputs: usize, length_divisor: usize, } impl TractBackend { fn new(model: TypedModel, length_divisor: usize) -> TractResult<Self> { ...
use crate::{NNSplitLogic, NNSplitOptions}; use ndarray::prelude::*; use std::error::Error; use tract_onnx::prelude::*; struct TractBackend { model: TypedModel, n_outputs: usize, length_divisor: usize, } impl TractBackend { fn new(model: TypedModel, length_divisor: usize) -> TractResult<Self> { ...
} pub fn new<P: AsRef<std::path::Path>>( model_path: P, options: NNSplitOptions, ) -> Result<Self, Box<dyn Error>> { let model_proto = onnx().proto_model_for_path(model_path)?; NNSplit::from_model(model_proto, options) } #[cfg(feature = "model-...
Ok(NNSplit { backend, logic: NNSplitLogic::new(options, serde_json::from_str(&split_sequence_string)?), })
call_expression
[ { "content": "/// Loads the file for the given model, either retrieving it from the cache or downloading it if it is not found.\n\npub fn get_resource(\n\n model_name: &str,\n\n file: &str,\n\n) -> Result<(impl std::io::Read, Option<PathBuf>), ResourceError> {\n\n let base_url = url::Url::parse(MODEL_D...
Rust
modulus_table/src/main.rs
MrFlynn/CS-Utilities
9cc33024cb6229631daff802e231c505a05a2258
#[macro_use] extern crate clap; use clap::App; extern crate colored; use colored::*; use std::process::exit; use std::error::Error; use std::io::prelude::*; use std::fs::File; use std::path::Path; fn create_multiplication_table(size: usize) -> Vec<Vec<i32>> { let mut table = vec![vec![0; size]; size]; ...
#[macro_use] extern crate clap; use clap::App; extern crate colored; use colored::*; use std::process::exit; use std::error::Error; use std::io::prelude::*; use std::fs::File; use std::path::Path; fn create_multiplication_table(size: usize) -> Vec<Vec<i32>> { let mut table = vec![vec![0; size]; size]; ...
let table = create_multiplication_table(mod_base - 1); let inv = create_inverse_table(&table); if matches.is_present("csv") { let mut mult_table_str: String = String::new(); for row in table.iter() { let row_str: String = vec_to_string(row.to_v...
if let Some(base) = matches.value_of("base") { mod_base = base.parse::<usize>().unwrap(); } else { println!("No base provided. Run modulus_table --help."); exit(1); }
if_condition
[ { "content": "fn invert_bits(input_str: String) -> i32 {\n\n // Allocate new string.\n\n let mut inv = String::new();\n\n\n\n // Iterate through each character in the string and 'invert' each bit.\n\n for c in input_str.chars() {\n\n match c {\n\n '0' => inv.push('1'),\n\n ...
Rust
src/libos/src/net/unix/mod.rs
lucassong-mh/ngo
f02dc4b9db31dbece407e3ec152ffd4b160ba9c1
use super::socket_file::UntrustedUnixStream; use super::*; use crate::prelude::*; use crate::util::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use self::trusted::Stream as TrustedStream; use self::trusted::TrustedAddr; use self::untrusted::UNTRUSTED_SOCKS; use async_io::event::{Events, Observer, Poller}; use as...
use super::socket_file::UntrustedUnixStream; use super::*; use crate::prelude::*; use crate::util::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use self::trusted::Stream as TrustedStream; use self::trusted::TrustedAddr; use self::untrusted::UNTRUSTED_SOCKS; use async_io::event::{Events, Observer, Poller}; use as...
} pub fn domain(&self) -> Domain { apply_fn_on_any_stream!(self.inner(), |stream| { stream.domain() }) } fn get_host_socket_file_path( libos_path: &TrustedAddr, host_path: UnixAddr, is_socket_file: bool, ) -> UnixAddr { if is_socket_file { host_...
match &*self.inner() { StreamInner::Trusted(stream) => stream.nonblocking(), StreamInner::Untrusted(u_stream) => { u_stream.status_flags().contains(StatusFlags::O_NONBLOCK) } }
if_condition
[ { "content": "pub fn allow_debug() -> bool {\n\n let self_report = create_report(None, None).expect(\"create a self report should never fail\");\n\n (self_report.body.attributes.flags & SGX_FLAGS_DEBUG) == SGX_FLAGS_DEBUG\n\n}\n", "file_path": "src/libos/src/util/sgx/mod.rs", "rank": 0, "score...
Rust
netidx-tools/src/publisher.rs
dtolnay-contrib/netidx
40fd1189d0d6df684e3b575421186e135e9c3208
use anyhow::{anyhow, Result}; use futures::{ channel::mpsc::{self, Receiver}, prelude::*, }; use fxhash::FxBuildHasher; use log::{error, warn}; use netidx::{ config::Config, path::Path, pool::Pooled, publisher::{BindCfg, Id, Publisher, Typ, Val, Value, WriteRequest}, resolver::Auth, util...
use anyhow::{anyhow, Result}; use futures::{ channel::mpsc::{self, Receiver}, prelude::*, }; use fxhash::FxBuildHasher; use log::{error, warn}; use netidx::{ config::Config, path::Path, pool::Pooled, publisher::{BindCfg, Id, Publisher, Typ, Val, Value, WriteRequest}, resolver::Auth, util...
pub(crate) fn run(config: Config, bcfg: BindCfg, timeout: Option<u64>, auth: Auth) { let rt = Runtime::new().expect("failed to init runtime"); rt.block_on(async { let timeout = timeout.map(Duration::from_secs); let mut by_path: HashMap<Path, Arc<Val>> = HashMap::new(); let by_id: ById = ...
function_block-full_function
[ { "content": "pub fn decode_varint(buf: &mut impl Buf) -> Result<u64, PackError> {\n\n let mut value = 0;\n\n let mut i = 0;\n\n while i < 10 {\n\n let byte = buf.get_u8();\n\n value |= u64::from(byte & 0x7F) << (i * 7);\n\n if byte <= 0x7F {\n\n return Ok(value);\n\n ...
Rust
stream/src/status.rs
weibocom/breeze
0c8ee87d3fa2ac16125d7b9690b69d375d6ef438
use crate::AtomicWaker; use std::cell::RefCell; use std::io::{Error, ErrorKind, Result}; use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering::*}; use std::task::{Context, Poll}; use protocol::{Request, RequestId, Response}; #[repr(u8)] #[derive(Clone, Copy)] pub enum ItemStatus { Init = 0u8, RequestReceiv...
use crate::AtomicWaker; use std::cell::RefCell; use std::io::{Error, ErrorKind, Result}; use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering::*}; use std::task::{Context, Poll}; use protocol::{Request, RequestId, Response}; #[repr(u8)] #[derive(Clone, Copy)] pub enum ItemStatus { Init = 0u8, RequestReceiv...
#[inline(always)] pub fn take_request(&self, seq: usize) -> Option<(usize, Request)> { if self.try_status_cas(RequestReceived as u8, RequestSent as u8) { log::debug!("take request. {} seq:{} ", self.rid.borrow(), seq); if let Some(req) = self.request.take() { ...
pub fn place_request(&self, req: &Request) { debug_assert_eq!(self.status.load(Acquire), ItemStatus::Init as u8); self.status_cas(Init as u8, RequestReceived as u8); *self.request.borrow_mut() = Some(req.clone()); self.rid.replace(req.id()); }
function_block-full_function
[ { "content": "pub fn init(path: &str, l: &str) -> Result<()> {\n\n let mut file = PathBuf::new();\n\n file.push(path);\n\n file.push(\"breeze.log\");\n\n\n\n let mut gzfile = PathBuf::new();\n\n gzfile.push(path);\n\n gzfile.push(\"breeze.log{}.gz\");\n\n\n\n const MAX_LOG_SIZE: u64 = 1 * 1...
Rust
fluence-faas/src/json/json_to_ivalues.rs
fluencelabs/fce
7b0686ab2e70e6a92d6bd81b3cd49221704037a8
/* * Copyright 2020 Fluence Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or a...
/* * Copyright 2020 Fluence Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or a...
"expected array of {:?} types, got {:?}", value_type, jvalue ))), }?; Ok(IValue::Array(value)) } IType::I32 => to_ivalue!(jvalue, I32), IType::I64 => to_ivalue!(jvalue, I64), IType::Record(record_type_id) => { le...
::ExactSizeIterator; pub(crate) fn json_to_ivalues<'a, 'b>( json_args: JValue, arg_types: impl Iterator<Item = (&'a String, &'a IType)> + ExactSizeIterator, record_types: &'b MRecordTypes, ) -> FaaSResult<Vec<IValue>> { let ivalues = match json_args { JValue::Object(json_map) => json_map_to_iva...
random
[ { "content": "fn as_semver(version_as_bytes: &[u8]) -> Result<semver::Version, super::SDKVersionError> {\n\n match std::str::from_utf8(version_as_bytes) {\n\n Ok(str) => Ok(semver::Version::from_str(str)?),\n\n Err(e) => Err(SDKVersionError::VersionNotValidUtf8(e)),\n\n }\n\n}\n", "file_...
Rust
src/vga_buffer.rs
YamanQD/quack_os
f7be8a51765e9467f7cde538304e5c90df7cf45f
#[allow(dead_code)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(u8)] enum Color { Black = 0x0, Blue = 0x1, Green = 0x2, Cyan = 0x3, Red = 0x4, Magenta = 0x5, Brown = 0x6, LightGray = 0x7, DarkGray = 0x8, LightBlue = 0x9, LightGreen = 0xa, LightCyan = 0xb...
#[allow(dead_code)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(u8)] enum Color { Black = 0x0, Blue = 0x1, Green = 0x2, Cyan = 0x3, Red = 0x4, Magenta = 0x5, Brown = 0x6, LightGray = 0x7, DarkGray = 0x8, LightBlue = 0x9, LightGreen = 0xa, LightCyan = 0xb...
fn new_line(&mut self) { for row in 1..BUFFER_HEIGHT { for col in 0..BUFFER_WIDTH { let character = self.buffer.chars[row][col].read(); self.buffer.chars[row - 1][col].write(character); } } self.clear_row(BUFFER_HEI...
r) { for byte in s.bytes() { match byte { 0x20..=0x7E | b'\n' => self.write_byte(byte), _ => self.write_byte(0xFE), } } }
function_block-function_prefixed
[ { "content": "#[panic_handler]\n\nfn panic(info: &PanicInfo) -> ! {\n\n println!(\"{}\", info);\n\n // Infinite loop for diverging function\n\n loop {}\n\n}\n", "file_path": "src/main.rs", "rank": 5, "score": 19035.673330103582 }, { "content": "#![no_std] // Disable standard library...
Rust
verifier/src/verification.rs
Silur/winterfell
cc0852f04d3d751a7e664772912c4977103a203d
use super::{compose_constraints, evaluate_constraints, VerifierChannel}; use common::CompositionCoefficients; use common::{errors::VerifierError, Air, EvaluationFrame, PublicCoin}; use crypto::Hasher; use fri::VerifierChannel as FriVerifierChannel; use math::field::{FieldElement, StarkField}; pub fn perform_verifica...
use super::{compose_constraints, evaluate_constraints, VerifierChannel}; use common::CompositionCoefficients; use common::{errors::VerifierError, Air, EvaluationFrame, PublicCoin}; use crypto::Hasher; use fri::VerifierChannel as FriVerifierChannel; use math::field::{FieldElement, StarkField}; pub fn perform_verifica...
fn get_conjugate_values<A: Air, E: FieldElement + From<A::BaseElement>>( air: &A, trace_state: &[E], z: E, ) -> Option<(E, Vec<E>)> { if air.context().options().field_extension().is_none() { None } else { Some(( z.conjugate(), trace_state.iter().map(|v| v.co...
ental_degree.into()); composition *= cc.trace_degree.0 + xp * cc.trace_degree.1; result.push(composition); } result }
function_block-function_prefixed
[ { "content": "/// Uses FFT algorithm to interpolate a polynomial from provided `values` over the domain defined\n\n/// by `inv_twiddles` and offset by `domain_offset` factor.\n\npub fn interpolate_poly_with_offset<B, E>(values: &mut [E], inv_twiddles: &[B], domain_offset: B)\n\nwhere\n\n B: StarkField,\n\n ...
Rust
zluda/src/impl/module.rs
Massendefekt/ZLUDA
897fbcbdb8acf7fbb4d9a42227fb7da0cf825eac
use std::{ collections::hash_map, collections::HashMap, ffi::c_void, ffi::CStr, ffi::CString, mem, os::raw::c_char, ptr, slice, }; use super::{ device, function::Function, function::{FunctionData, LegacyArguments}, CUresult, GlobalState, HasLivenessCookie, LiveCheck, }; use ptx; pub type Modul...
use std::{ collections::hash_map, collections::HashMap, ffi::c_void, ffi::CStr, ffi::CString, mem, os::raw::c_char, ptr, slice, }; use super::{ device, function::Function, function::{FunctionData, LegacyArguments}, CUresult, GlobalState, HasLivenessCookie, LiveCheck, }; use ptx; pub type Modul...
let name = unsafe { CStr::from_ptr(name) }.to_owned(); let function: *mut Function = GlobalState::lock_current_context(|ctx| { let module = unsafe { &mut *hmod }.as_result_mut()?; let device = unsafe { &mut *ctx.device }; let compiled_module = match module.device_binaries.entry(device.i...
if hfunc == ptr::null_mut() || hmod == ptr::null_mut() || name == ptr::null() { return Err(CUresult::CUDA_ERROR_INVALID_VALUE); }
if_condition
[ { "content": "pub fn total_mem_v2(bytes: *mut usize, dev_idx: Index) -> Result<(), CUresult> {\n\n if bytes == ptr::null_mut() {\n\n return Err(CUresult::CUDA_ERROR_INVALID_VALUE);\n\n }\n\n let mem_props = GlobalState::lock_device(dev_idx, |dev| {\n\n let mem_props = dev.get_memory_prope...
Rust
tests/test_prefix.rs
jethrogb/rust-bindgen
88f4ee0004090eabc5a58e9d51fe7d418dfe932a
use bindgen::{Builder,BindgenOptions}; use support::assert_bind_eq; #[test] fn remove_prefix() { let opts = BindgenOptions { remove_prefix: "test_".into(), ..Default::default() }; assert_bind_eq(opts, "headers/prefix.h", " #[repr(C)] #[derive(Copy, Clone)] #[derive(D...
use bindgen::{Builder,BindgenOptions}; use support::assert_bind_eq; #[test] fn remove_prefix() { let opts = BindgenOptions { remove_prefix: "test_".into(), ..Default::default() }; assert_bind_eq(opts, "headers/prefix.h", " #[repr(C)] #[derive(Copy, Clone)] #[derive(D...
onst B: enum_ = 1; #[repr(C)] #[derive(Copy, Clone)] #[derive(Debug)] pub struct union { pub _bindgen_data_: [u32; 1usize], } impl union { pub unsafe fn s(&mut self) -> *mut struct_ { let raw: *mut u8 = ::std::mem::transmute(&self._...
pub fn fn2() -> union; #[link_name = \"test_fn3\"] pub fn fn3() -> struct_; #[link_name = \"test_fn4\"] pub fn fn4() -> enum_; } "); } #[test] fn remove_prefix_no_enum() { let opts = BindgenOptions { remove_prefix: "test_".into(), rust_e...
random
[ { "content": "pub fn generate_bindings(mut options: BindgenOptions,\n\n filename: &str)\n\n -> Result<Vec<P<ast::Item>>, ()> {\n\n if filename.ends_with(\"hpp\") {\n\n options.clang_args.push(\"-std=c++11\".to_string());\n\n options.clang_args.pus...
Rust
src/example_api/mod.rs
jeroenvanmaanen/rusty-dendrite
ba2125ca70d6cf0f094a45b245a14f3c99f6d840
use anyhow::{Error,Result}; use bytes::Bytes; use log::{debug}; use prost::Message; use tokio::sync::mpsc; use tonic::{Request, Response, Status}; use crate::axon_utils::{AxonServerHandle, CommandSink, QuerySink, init_command_sender, query_events}; use crate::grpc_example::greeter_service_server::GreeterService; use cr...
use anyhow::{Error,Result}; use bytes::Bytes; use log::{debug}; use prost::Message; use tokio::sync::mpsc; use tonic::{Request, Response, Status}; use crate::axon_utils::{AxonServerHandle, CommandSink, QuerySink, init_command_sender, query_events}; use crate::grpc_example::greeter_service_server::GreeterService; use cr...
, search_response); for greeting in search_response.greetings { debug!("Greeting: {:?}", greeting); tx.send(Ok(greeting)).await.ok(); } } debug!("Next!"); } debug!("Done!") ...
w(&query)).await.map_err(to_status)?; tokio::spawn(async move { for serialized_object in query_response { if let Ok(search_response) = SearchResponse::decode(Bytes::from(serialized_object.data)) { debug!("Search response: {:?}"
function_block-random_span
[ { "content": "fn create_output_stream(client_id: String, initial_token: i64, mut rx: Receiver<AxonEventProcessed>) -> impl Stream<Item = GetEventsRequest> {\n\n stream! {\n\n debug!(\"Event Processor: stream: start: {:?}\", rx);\n\n\n\n let permits_batch_size: i64 = 3;\n\n let mut permit...
Rust
pageserver/src/storage_sync/download.rs
poojanilangekar/zenith
f47c5ed982de31ddc76d7b64b9b7b28480a21a03
use std::{collections::HashSet, fmt::Debug, path::Path}; use anyhow::Context; use futures::stream::{FuturesUnordered, StreamExt}; use remote_storage::{path_with_suffix_extension, RemoteStorage}; use tokio::{ fs, io::{self, AsyncWriteExt}, }; use tracing::{debug, error, info, warn}; use crate::{ config::...
use std::{collections::HashSet, fmt::Debug, path::Path}; use anyhow::Context; use futures::stream::{FuturesUnordered, StreamExt}; use remote_storage::{path_with_suffix_extension, RemoteStorage}; use tokio::{ fs, io::{self, AsyncWriteExt}, }; use tracing::{debug, error, info, warn}; use crate::{ config::...
#[tokio::test] async fn test_download_index_part() -> anyhow::Result<()> { let harness = RepoHarness::create("test_download_index_part")?; let sync_id = ZTenantTimelineId::new(harness.tenant_id, TIMELINE_ID); let storage = LocalFs::new( tempdir()?.path().to_path_buf(), ...
sync_id, SyncData::new( 0, LayersDownload { layers_to_skip: HashSet::new(), }, ), ) .await; assert!( matches!(empty_remote_timeline_download, DownloadedTimeline::Abort), "Should no...
function_block-function_prefix_line
[ { "content": "#[async_trait::async_trait]\n\npub trait Layer: std::fmt::Debug + std::fmt::Display + Send + Sync + 'static {\n\n /// Range of keys that this layer covers\n\n fn get_key_range(&self) -> Range<Key>;\n\n\n\n /// Inclusive start bound of the LSN range that this layer holds\n\n /// Exclusi...
Rust
lib/api/src/sys/tunables.rs
WAFoundation/wasmer
6093af4e07e1bb7735ac218189e89bfab4341a56
use crate::sys::{MemoryType, Pages, TableType}; use std::ptr::NonNull; use std::sync::Arc; use target_lexicon::PointerWidth; use wasmer_compiler::{Target, Tunables}; use wasmer_vm::MemoryError; use wasmer_vm::{ LinearMemory, LinearTable, Memory, MemoryStyle, Table, TableStyle, VMMemoryDefinition, VMTableDefinit...
use crate::sys::{MemoryType, Pages, TableType}; use std::ptr::NonNull; use std::sync::Arc; use target_lexicon::PointerWidth; use wasmer_compiler::{Target, Tunables}; use wasmer_vm::MemoryError; use wasmer_vm::{ LinearMemory, LinearTable, Memory, MemoryStyle, Table, TableStyle, VMMemoryDefinition, VMTableDefinit...
fn table_style(&self, _table: &TableType) -> TableStyle { TableStyle::CallerChecksSignature } fn create_host_memory( &self, ty: &MemoryType, style: &MemoryStyle, ) -> Result<Arc<dyn Memory>, MemoryError> { Ok(Arc::new(LinearMemory::new(ty, style)?)) ...
p_or_else(Pages::max_value); if maximum <= self.static_memory_bound { MemoryStyle::Static { bound: self.static_memory_bound, offset_guard_size: self.static_memory_offset_guard_size, } } else { MemoryStyle::Dynamic { ...
function_block-function_prefixed
[ { "content": "/// Returns the length of a libcall trampoline.\n\npub fn libcall_trampoline_len(target: &Target) -> usize {\n\n match target.triple().architecture {\n\n Architecture::Aarch64(_) => AARCH64_TRAMPOLINE.len(),\n\n Architecture::X86_64 => X86_64_TRAMPOLINE.len(),\n\n arch => p...
Rust
src/http/ratelimiting.rs
kangalioo/serenity
f00f1c0ec0736999ffe2619840ae89690daa41f9
pub use super::routing::Route; use reqwest::{Client, Response}; use reqwest::{header::HeaderMap, StatusCode}; use crate::internal::prelude::*; use tokio::sync::{Mutex, RwLock}; use std::{ collections::HashMap, sync::Arc, str::{ self, FromStr, }, time::SystemTime, i64, u64,...
pub use super::routing::Route; use reqwest::{Client, Response}; use reqwest::{header::HeaderMap, StatusCode}; use crate::internal::prelude::*; use tokio::sync::{Mutex, RwLock}; use std::{ collections::HashMap, sync::Arc, str::{ self, FromStr, }, time::SystemTime, i64, u64,...
#[cfg(test)] mod tests { use crate::{ error::Error, http::HttpError, }; use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use std::{ error::Error as StdError, result::Result as StdResult, }; use super::parse_header; type Result<T> = StdResult<T, Bo...
fn parse_header<T: FromStr>(headers: &HeaderMap, header: &str) -> Result<Option<T>> { let header = match headers.get(header) { Some(v) => v, None => return Ok(None), }; let unicode = str::from_utf8(&header.as_bytes()).map_err(|_| { Error::from(HttpError::RateLimitUtf8) })?; ...
function_block-full_function
[ { "content": "/// Validates that a token is likely in a valid format.\n\n///\n\n/// This performs the following checks on a given token:\n\n///\n\n/// - At least one character long;\n\n/// - Contains 3 parts (split by the period char `'.'`);\n\n/// - The second part of the token is at least 6 characters long;\n...
Rust
local-cluster/tests/local_cluster_slow_2.rs
YandriHN/solana
456e6711f0c24b13ae5e923ff8cd2af3caab496d
#![allow(clippy::integer_arithmetic)] use { common::*, log::*, serial_test::serial, solana_core::validator::ValidatorConfig, solana_gossip::gossip_service::discover_cluster, solana_ledger::{ancestor_iterator::AncestorIterator, blockstore::Blockstore}, solana_local_cluster::{ cluste...
#![allow(clippy::integer_arithmetic)] use { common::*, log::*, serial_test::serial, solana_core::validator::ValidatorConfig, solana_gossip::gossip_service::discover_cluster, solana_ledger::{ancestor_iterator::AncestorIterator, blockstore::Blockstore}, solana_local_cluster::{ cluste...
sleep(Duration::from_millis(1000)); } info!("Kill B"); b_info = cluster.exit_node(&b_pubkey); info!("Resolve the partition"); { let a_blockstore = open_blockstore(&a_ledger_path); let b_blockstore = open_blockstore(&b_ledger_path); copy_blocks(last_vote_on...
if let Some(index) = ancestors.position(|x| x == common_ancestor_slot) { if index > 7 { info!( "B has forked for enough lockout: {:?}", AncestorIterator::new(last_vote, &blockstore).collect::<Vec<Slot>>() ); break; ...
if_condition
[ { "content": "pub fn last_vote_in_tower(tower_path: &Path, node_pubkey: &Pubkey) -> Option<(Slot, Hash)> {\n\n restore_tower(tower_path, node_pubkey).map(|tower| tower.last_voted_slot_hash().unwrap())\n\n}\n\n\n", "file_path": "local-cluster/tests/common.rs", "rank": 0, "score": 493791.7931054288...
Rust
example/serialization/src/main.rs
Guvante/legion
2adcf95e3353e12efff3b1b2fb5bb20d5d243927
use legion::{ entity::EntityAllocator, prelude::*, storage::{ ArchetypeDescription, ComponentMeta, ComponentResourceSet, ComponentTypeId, TagMeta, TagStorage, TagTypeId, }, }; use serde::{ de::{self, DeserializeSeed, IgnoredAny, Visitor}, Deserialize, Deserializer, Serialize, Ser...
use legion::{ entity::EntityAllocator, prelude::*, storage::{ ArchetypeDescription, ComponentMeta, ComponentResourceSet, ComponentTypeId, TagMeta, TagStorage, TagTypeId, }, }; use serde::{ de::{self, DeserializeSeed, IgnoredAny, Visitor}, Deserialize, Deserializer, Serialize, Ser...
let serializable = legion::serialize::ser::serializable_world(&deserialized_world, &ser_helper); let roundtrip_data = serde_json::to_string(&serializable).unwrap(); assert_eq!(roundtrip_data, serialized_data); }
let ser_helper = SerializeImpl { tag_types: de_helper.tag_types, comp_types: de_helper.comp_types, entity_map: RefCell::new(HashMap::from_iter( de_helper .entity_map .into_inner() .into_iter() .map(|(uuid, e)| (...
assignment_statement
[ { "content": "struct TagStorageDeserializer<'a, 'b, WD: WorldDeserializer> {\n\n user: &'b WD,\n\n tag_storage: &'a mut TagStorage,\n\n tag_type: &'a TagTypeId,\n\n tag_meta: &'a TagMeta,\n\n}\n\nimpl<'de, 'a, 'b, WD: WorldDeserializer> DeserializeSeed<'de>\n\n for TagStorageDeserializer<'a, 'b, ...
Rust
examples/page_props.rs
Erutuon/parse-mediawiki-sql
90b8114627d7d03f55298a8a7037e4148faf9d8a
use std::{collections::BTreeMap as Map, convert::TryFrom, path::PathBuf}; use anyhow::Result; use parse_mediawiki_sql::{ field_types::PageNamespace, schemas::{Page, PageProperty}, utils::{memory_map, Mmap, NamespaceMap, NamespaceMapExt as _}, }; use pico_args::Arguments; use serde::Serialize; use smartstri...
use std::{collections::BTreeMap as Map, convert::TryFrom, path::PathBuf}; use anyhow::Result; use parse_mediawiki_sql::{ field_types::PageNamespace, schemas::{Page, PageProperty}, utils::{memory_map, Mmap, NamespaceMap, NamespaceMapExt as _}, }; use pico_args::Arguments; use serde::Serialize; use smartstri...
pub fn serialize_displaytitles(mut args: Arguments) -> Result<()> { let dump_dir = opt_path_from_args(&mut args, ["-d", "--dump-dir"])?; let props_sql = unsafe { memory_map_from_args_in_dir(&mut args, ["-P", "--props"], "page_props.sql", &dump_dir)? }; let page_sql = unsafe { memory_ma...
d, .. }| { if let Some(props) = id_to_props.remove(&id) { if namespaces.is_empty() || namespaces.contains(&namespace) { map.insert(namespace_map.pretty_title(namespace, &title), props); } } map }, )...
function_block-function_prefixed
[ { "content": "#[allow(clippy::redundant_closure)]\n\nfn opt_path_from_args(args: &mut Arguments, keys: [&'static str; 2]) -> Result<Option<PathBuf>> {\n\n Ok(args.opt_value_from_os_str(keys, |opt| PathBuf::try_from(opt))?)\n\n}\n\n\n", "file_path": "examples/categorylinks.rs", "rank": 1, "score":...
Rust
pin-project-internal/src/pinned_drop.rs
taiki-e/pin-project
0a0c7dbd9e2168ee4f0263003fda2e24b10e2a5a
use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ parse_quote, parse_quote_spanned, spanned::Spanned, visit_mut::VisitMut, Error, FnArg, GenericArgument, ImplItem, ItemImpl, Pat, PatIdent, Path, PathArguments, Result, ReturnType, Signature, Token, Type, TypePath, TypeRefer...
use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ parse_quote, parse_quote_spanned, spanned::Spanned, visit_mut::VisitMut, Error, FnArg, GenericArgument, ImplItem, ItemImpl, Pat, PatIdent, Path, PathArguments, Result, ReturnType, Signature, Token, Type, TypePath, TypeRefer...
fn expand_impl(item: &mut ItemImpl) { fn get_arg_pat(arg: &mut FnArg) -> Option<&mut PatIdent> { if let FnArg::Typed(arg) = arg { if let Pat::Ident(ident) = &mut *arg.pat { return Some(ident); } } None } item.attrs.push(parse_quote!(#[doc...
function_block-full_function
[ { "content": "#[proc_macro_attribute]\n\npub fn pinned_drop(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(input);\n\n pinned_drop::attribute(&args.into(), input).into()\n\n}\n\n\n\n// Not public API.\n", "file_path": "pin-project-internal/src/lib.rs", ...
Rust
src/base/window.rs
LarsHaalck/unsegen
af099de3f16cb457c468ddfd0379332adad7c0c3
use super::{CursorTarget, GraphemeCluster, Style, StyleModifier}; use base::basic_types::*; use base::cursor::{UNBOUNDED_HEIGHT, UNBOUNDED_WIDTH}; use ndarray::{Array, ArrayViewMut, Axis, Ix, Ix2}; use std::cmp::max; use std::fmt; use std::ops::{Bound, RangeBounds}; #[derive(Clone, Debug, PartialEq)] #[allow(missing_...
use super::{CursorTarget, GraphemeCluster, Style, StyleModifier}; use base::basic_types::*; use base::cursor::{UNBOUNDED_HEIGHT, UNBOUNDED_WIDTH}; use ndarray::{Array, ArrayViewMut, Axis, Ix, Ix2}; use std::cmp::max; use std::fmt; use std::ops::{Bound, RangeBounds}; #[derive(Clone, Debug, PartialEq)] #[allow(missing_...
; let x_range_end = match x_range.end_bound() { Bound::Unbounded => self.get_width().from_origin(), Bound::Included(i) => *i - 1, Bound::Excluded(i) => *i, }; let y_range_start = match y_range.start_bound() { Bound::Unbounded => RowIndex::new(0), ...
match x_range.start_bound() { Bound::Unbounded => ColIndex::new(0), Bound::Included(i) => *i, Bound::Excluded(i) => *i - 1, }
if_condition
[ { "content": "/// Calculate the (monospace) width of the given string.\n\n///\n\n/// A thin convenience wrapper around unicode_width.\n\npub fn text_width(text: &str) -> Width {\n\n use unicode_width::UnicodeWidthStr;\n\n Width::new(UnicodeWidthStr::width(text) as _).unwrap()\n\n}\n", "file_path": "sr...
Rust
libsplinter/src/admin/rest_api/actix/proposals_circuit_id.rs
isabeltomb/splinter
9a516e08cfaa7cbfb80fad9c512347a044757174
use actix_web::{error::BlockingError, web, Error, HttpRequest, HttpResponse}; use futures::Future; use crate::admin::rest_api::error::ProposalFetchError; use crate::admin::service::proposal_store::ProposalStore; use crate::protocol; use crate::rest_api::{ErrorResponse, Method, ProtocolVersionRangeGuard, Resource}; ...
use actix_web::{error::BlockingError, web, Error, HttpRequest, HttpResponse}; use futures::Future; use crate::admin::rest_api::error::ProposalFetchError; use crate::admin::service::proposal_store::ProposalStore; use crate::protocol; use crate::rest_api::{ErrorResponse, Method, ProtocolVersionRangeGuard, Resource}; ...
nable to join rest api thread"); } #[derive(Clone)] struct MockProposalStore; impl ProposalStore for MockProposalStore { fn proposals( &self, _filters: Vec<ProposalFilter>, ) -> Result<ProposalIter, ProposalStoreError> { unimplemented!() } ...
RL"); let req = Client::new() .get(url) .header("SplinterProtocolVersion", protocol::ADMIN_PROTOCOL_VERSION); let resp = req.send().expect("Failed to perform request"); assert_eq!(resp.status(), StatusCode::NOT_FOUND); shutdown_handle .shutdown() ...
random
[ { "content": "pub fn get_authorization_token(request: &HttpRequest) -> Result<String, RequestError> {\n\n let auth_header = require_header(\"Authorization\", &request)?;\n\n Ok(auth_header\n\n .split_whitespace()\n\n .last()\n\n .ok_or_else(|| {\n\n RequestError::InvalidHea...
Rust
gstreamer-audio/src/audio_decoder.rs
cotigao/gstreamer-rs
962da8a63d1b61bbdf44f4486f55fb6c13864c36
use glib::object::IsA; use glib::translate::*; use gst; use gst_audio_sys; use std::mem; use std::ptr; use AudioDecoder; use AudioInfo; extern "C" { fn _gst_audio_decoder_error( dec: *mut gst_audio_sys::GstAudioDecoder, weight: i32, domain: glib_sys::GQuark, code: i32, txt...
use glib::object::IsA; use glib::translate::*; use gst; use gst_audio_sys; use std::mem; use std::ptr; use AudioDecoder; use AudioInfo; extern "C" { fn _gst_audio_decoder_error( dec: *mut gst_audio_sys::GstAudioDecoder, weight: i32, domain: glib_sys::GQuark, code: i32, txt...
} #[macro_export] macro_rules! gst_audio_decoder_error( ($obj:expr, $weight:expr, $err:expr, ($msg:expr), [$debug:expr]) => { { use $crate::AudioDecoderExtManual; $obj.error( $weight, $err, Some($msg), Some($debug), file!(), m...
T, message: Option<&str>, debug: Option<&str>, file: &str, function: &str, line: u32, ) -> Result<gst::FlowSuccess, gst::FlowError> { let ret: gst::FlowReturn = unsafe { from_glib(_gst_audio_decoder_error( self.as_ref().to_glib_none().0, ...
function_block-function_prefixed
[ { "content": "#[cfg(any(feature = \"v1_14\", feature = \"dox\"))]\n\npub fn debug_add_ring_buffer_logger(max_size_per_thread: u32, thread_timeout: u32) {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n gst_sys::gst_debug_add_ring_buffer_logger(max_size_per_thread, thread_timeout);\n\n }\...
Rust
src/transitions.rs
crabvk/congruity
9fd0e20d0ae9855d0be16c16452b5746894f190d
use super::states::*; use crate::types::{AccountAddress, Amount}; use crate::{command::Command, db, rpc, states::Dialogue, BotType}; use log::*; use teloxide::payloads::SendMessageSetters; use teloxide::types::{KeyboardButton, KeyboardMarkup, KeyboardRemove}; use teloxide::utils::command::BotCommand; use teloxide::{pre...
use super::states::*; use crate::types::{AccountAddress, Amount}; use crate::{command::Command, db, rpc, states::Dialogue, BotType}; use log::*; use teloxide::payloads::SendMessageSetters; use teloxide::types::{KeyboardButton, KeyboardMarkup, KeyboardRemove}; use teloxide::utils::command::BotCommand; use teloxide::{pre...
fn build_keyboard(buttons: &[String]) -> KeyboardMarkup { let buttons = buttons.iter().map(|text| { [KeyboardButton { text: text.to_string(), request: None, }] }); KeyboardMarkup::new(buttons) .resize_keyboard(true) .one_time_keyboard(true) } #[tel...
async fn get_account_balance( addr: &AccountAddress, cx: TransitionIn<BotType>, ) -> ResponseResult<Message> { match rpc::get_account_balance(&addr.to_string()).await { Ok(Some(amount)) => { let amount: Amount = amount.parse().unwrap(); let answer = format!("{} CCD", amount.t...
function_block-full_function
[ { "content": "fn parse_payload(payload: &str) -> (i64, String, &str) {\n\n let mut triple = payload.split(\"|\");\n\n let index_id: i64 = triple.next().unwrap().parse().unwrap();\n\n let address = hex::decode(&triple.next().unwrap()[2..])\n\n .unwrap()\n\n .to_base58check(1);\n\n let s...
Rust
artichoke-backend/src/extn/core/kernel/require.rs
willglynn/artichoke
e3cb1d05f598040aa92a02e1bebe87a427dee6ba
use bstr::ByteSlice; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use crate::extn::prelude::*; use crate::ffi; use crate::fs::RUBY_LOAD_PATH; use crate::state::parser::Context; use crate::Parser; const RUBY_EXTENSION: &str = "rb"; pub fn load(interp: &mut Artichoke, filename: Value) -> Result<Value, Except...
use bstr::ByteSlice; use std::ffi::OsStr; use std::path::{Path, PathBuf}; use crate::extn::prelude::*; use crate::ffi; use crate::fs::RUBY_LOAD_PATH; use crate::state::parser::Context; use crate::Parser; const RUBY_EXTENSION: &str = "rb"; pub fn load(interp: &mut Artichoke, filename: Value) -> Result<Value, Except...
} fn load_error(interp: &Artichoke, filename: &[u8]) -> Result<LoadError, Exception> { let mut message = String::from("cannot load such file -- "); string::format_unicode_debug_into(&mut message, filename)?; Ok(LoadError::new(interp, message)) }
let borrow = interp.0.borrow(); let context = borrow .parser .peek_context() .ok_or_else(|| Fatal::new(interp, "relative require with no context stack"))?; let path = ffi::bytes_to_os_str(context.filename())?; let path = Path::new(path); if le...
function_block-function_prefix_line
[ { "content": "pub fn load(interp: &mut Artichoke, path: Value) -> Result<Value, Exception> {\n\n kernel::require::load(interp, path)\n\n}\n\n\n", "file_path": "artichoke-backend/src/extn/core/kernel/trampoline.rs", "rank": 1, "score": 579488.3188036411 }, { "content": "/// Determine if an...
Rust
dice-compiler/src/visitor/expr_block.rs
Mr-Byte/Dice
926ec5c0e8d7d162d1a3ac7e0488eff7dc44357e
use super::NodeVisitor; use crate::{ compiler::Compiler, compiler_stack::CompilerKind, scope_stack::{ScopeKind, State}, visitor::ClassKind, }; use dice_core::{ error::{codes::NEW_MUST_CALL_SUPER_FROM_SUBCLASS, Error}, protocol::{class::SELF, ProtocolSymbol}, span::Span, }; use dice_syntax::{...
use super::NodeVisitor; use crate::{ compiler::Compiler, compiler_stack::CompilerKind, scope_stack::{ScopeKind, State}, visitor::ClassKind, }; use dice_core::{ error::{codes::NEW_MUST_CALL_SUPER_FROM_SUBCLASS, Error}, protocol::{class::SELF, ProtocolSymbol}, span::Span, }; use dice_syntax::{...
if let Some(type_) = &arg.type_ { emit_bytecode! { self.assembler()?, arg.span => [ {self.visit(&type_.name)?}; if type_.is_nullable => [ ASSERT_TYPE_OR_NULL_FOR_LOCAL slot; ...
let slot = self.context()?.scope_stack().add_local( arg.name.clone(), State::Local { is_mutable: false, is_initialized: true, }, )? as u8;
assignment_statement
[ { "content": "fn pop(_runtime: &mut dyn Runtime, args: &[Value]) -> Result<Value, Error> {\n\n if let [Value::Array(arr), ..] = args {\n\n let result = arr.pop().unwrap_or(Value::Unit);\n\n\n\n Ok(result)\n\n } else {\n\n Ok(Value::Null)\n\n }\n\n}\n\n\n", "file_path": "dice-ru...
Rust
cms/src/model/schema.rs
LightHero/lightspeed
d18a89e6eea654293b0560315e1316b56ffc6298
use c3p0::Model; use lightspeed_core::error::{ErrorDetails, LightSpeedError}; use lightspeed_core::service::validator::order::{validate_ge, validate_le}; use lightspeed_core::service::validator::{Validable, ERR_NOT_UNIQUE}; use once_cell::sync::OnceCell; use regex::Regex; use serde::{Deserialize, Serialize}; pub type ...
use c3p0::Model; use lightspeed_core::error::{ErrorDetails, LightSpeedError}; use lightspeed_core::service::validator::order::{validate_ge, validate_le}; use lightspeed_core::service::validator::{Validable, ERR_NOT_UNIQUE}; use once_cell::sync::OnceCell; use regex::Regex; use serde::{Deserialize, Serialize}; pub type ...
field_names.push(&schema_field.name); schema_field.validate(&mut scoped_err)?; } Ok(()) } } #[derive(Clone, Serialize, Deserialize)] pub struct SchemaField { pub name: String, pub description: String, pub required: bool, pub field_type: SchemaFieldType, } ...
if field_names.contains(&&schema_field.name) { scoped_err.add_detail("name", ERR_NOT_UNIQUE); }
if_condition
[ { "content": "/// Validates whether the string given is a url\n\npub fn validate_url<S: Into<String>>(error_details: &mut ErrorDetails, field_name: S, val: &str) {\n\n if !validator::validate_url(val) {\n\n error_details.add_detail(field_name.into(), ErrorDetail::new(NOT_VALID_URL, vec![]))\n\n }\n...
Rust
common/src/options.rs
Silur/winterfell
cc0852f04d3d751a7e664772912c4977103a203d
use fri::FriOptions; use math::field::StarkField; use serde::{Deserialize, Serialize}; #[repr(u8)] #[derive(Copy, Clone, Serialize, Deserialize)] pub enum FieldExtension { None = 1, Quadratic = 2, } #[repr(u8)] #[derive(Copy, Clone, Serialize, Deserialize)] pub enum HashFunction { Blake3_256 = 1, Sh...
use fri::FriOptions; use math::field::StarkField; use serde::{Deserialize, Serialize}; #[repr(u8)] #[derive(Copy, Clone, Serialize, Deserialize)] pub enum FieldExtension { None = 1, Quadratic = 2, } #[repr(u8)] #[derive(Copy, Clone, Serialize, Deserialize)] pub enum HashFunction { Blake3_256 = 1, Sh...
pub fn num_queries(&self) -> usize { self.num_queries as usize } pub fn blowup_factor(&self) -> usize { 1 << (self.blowup_factor as usize) } pub fn grinding_factor(&self) -> u32 { self.grindi...
blowup_factor cannot be greater than 256" ); assert!( grinding_factor <= 32, "grinding factor cannot be greater than 32" ); ProofOptions { num_queries: num_queries as u8, blowup_factor: blowup_factor.trailing_zeros() as u8, gr...
function_block-function_prefix_line
[ { "content": "/// Returns base 2 logarithm of `n`, where `n` is a power of two.\n\npub fn log2(n: usize) -> u32 {\n\n assert!(n.is_power_of_two(), \"n must be a power of two\");\n\n n.trailing_zeros()\n\n}\n\n\n\n// HELPER FUNCTIONS\n\n// -------------------------------------------------------------------...
Rust
src/secret.rs
raipay/secp256k1-abc
b23e74219f5c425eada0f53a52f9b51fdb3b23b2
use ::core::fmt; use ::{SecretKey, schnorrsig::KeyPair, to_hex}; use constants::SECRET_KEY_SIZE; macro_rules! impl_display_secret { ($thing:ident) => { #[cfg(feature = "std")] impl ::core::fmt::Debug for $thing { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Resul...
use ::core::fmt; use ::{SecretKey, schnorrsig::KeyPair, to_hex}; use constants::SECRET_KEY_SIZE; macro_rules! impl_display_secret { ($thing:ident) => { #[cfg(feature = "std")] impl ::core::fmt::Debug for $thing { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Resul...
DisplaySecret { secret: self.serialize_secret() } } }
0x4b, 0x35, 0x02, 0xaa, 0x6d, 0x0f, 0x79, 0xcb, 0x63, 0xe6, 0xf8, 0x66, 0x22 ]; let mut hasher = ::std::collections::hash_map::DefaultHasher::new(); hasher.write(DEBUG_HASH_TAG); hasher.write(DEBUG_HASH_TAG); hasher.w...
random
[ { "content": "#[start]\n\nfn start(_argc: isize, _argv: *const *const u8) -> isize {\n\n let mut buf = [AlignedType::zeroed(); 70_000];\n\n let size = Secp256k1::preallocate_size();\n\n unsafe { libc::printf(\"needed size: %d\\n\\0\".as_ptr() as _, size) };\n\n\n\n let mut secp = Secp256k1::prealloc...
Rust
src/angle.rs
SiegeEngine/siege-math
99e155f0a9c49d25d42d15638a4026a5d5f25d1a
use num_traits::NumCast; use serde::{Serialize, Deserialize}; use std::ops::{Mul, Div, Add, Sub, Neg}; use float_cmp::ApproxEq; use crate::FullFloat; use crate::vector::Vec2; #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Serialize, Deserialize)] pub struct Angle<F>(F); impl<...
use num_traits::NumCast; use serde::{Serialize, Deserialize}; use std::ops::{Mul, Div, Add, Sub, Neg}; use float_cmp::ApproxEq; use crate::FullFloat; use crate::vector::Vec2; #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Serialize, Deserialize)] pub struct Angle<F>(F); impl<...
}
from_degrees(370.0_f32); a1.normalize(); assert!(a1.as_degrees().approx_eq(10.0_f32, (2.0 * EPSILON, 2))); let mut a1 = Angle::from_degrees(-370.0_f32); a1.normalize(); assert!(a1.as_degrees().approx_eq(350.0_f32, (2.0 * EPSILON, 2))); }
function_block-function_prefixed
[ { "content": "// This trait allows us to write code generic across both\n\n// floating point types\n\npub trait FullFloat: Float + FloatConst + Default +\n\n NumAssignOps + NumCast + Ulps + ApproxEq\n\n{ }\n\nimpl FullFloat for f32 {}\n\nimpl FullFloat for f64 {}\n", "file_path": "src/lib.rs", "rank"...
Rust
tests/test_binary.rs
greencashew/audioserve
707ef3d145129aab6d6860a94ba0f0030e581f8d
#![allow(dead_code)] use anyhow::{Error, Result}; use escargot::CargoBuild; use headers::HeaderValue; use reqwest::{blocking::Client, header::HeaderMap, StatusCode}; use serde_json::Value; use std::io; fn make_url(path: &str, port: u16) -> String { format!("http://localhost:{}", port) + path } fn extract_value<'...
#![allow(dead_code)] use anyhow::{Error, Result}; use escargot::CargoBuild; use headers::HeaderValue; use reqwest::{blocking::Client, header::HeaderMap, StatusCode}; use serde_json::Value; use std::io; fn make_url(path: &str, port: u16) -> String { format!("http://localhost:{}", port) + path } fn extract_value<'...
fn array_len(v: &Value) -> Result<usize> { if let Value::Array(a) = v { Ok(a.len()) } else { Err(Error::msg("value is not array")) } } macro_rules! assert_header { ($resp:ident, $key: expr, $val: expr) => { let v = $resp .headers() .get($key) ...
if let Value::Number(n) = v { n.as_f64().ok_or_else(|| Error::msg("not float value")) } else { Err(Error::msg("value is not float")) } }
function_block-function_prefix_line
[ { "content": "fn extract_collection_number(path: &str) -> Result<(&str, usize), ()> {\n\n let matches = COLLECTION_NUMBER_RE.captures(&path);\n\n if let Some(matches) = matches {\n\n let cnum = matches.get(1).unwrap();\n\n // match gives us char position it's safe to slice\n\n let new...
Rust
cashweb-registry/tests/test_http_endpoint.rs
LogosFoundation/cashweb
87b813591efbfe77424fb02aecbcffc9a6a58f77
use std::ffi::OsString; use bitcoinsuite_bitcoind::instance::{BitcoindChain, BitcoindConf}; use bitcoinsuite_core::{ ecc::Ecc, lotus_txid, BitcoinCode, Hashed, LotusAddress, Net, Network, P2PKHSignatory, Script, SequenceNo, Sha256, ShaRmd160, SigHashType, SignData, SignField, TxBuilder, TxBuilderInput, TxB...
use std::ffi::OsString; use bitcoinsuite_bitcoind::instance::{BitcoindChain, BitcoindConf}; use bitcoinsuite_core::{ ecc::Ecc, lotus_txid, BitcoinCode, Hashed, LotusAddress, Net, Network, P2PKHSignatory, Script, SequenceNo, Sha256, ShaRmd160, SigHashType, SignData, SignField, TxBuilder, TxBuilderInput, TxB...
t response = client .get(format!("{}/metadata?end_timestamp=1234", url)) .send() .await?; assert_eq!(response.status(), StatusCode::OK); assert_eq!( proto::GetMetadataRangeResponse::decode(&mut response.bytes().await?)?, empty_response, ); let response = client ...
nd() .await?; assert_eq!(response.status(), StatusCode::BAD_REQUEST); check_proto_error( response, "invalid-query-param", "Invalid start_timestamp: \"abc\" is invalid: invalid digit found in string", false, ) .await?; let response = client .get(format...
random
[ { "content": "/// Build the burn [`bitcoinsuite_core::Script`] for the given pubkey and payload hash.\n\npub fn build_commitment_script(pubkey_raw: [u8; PUBKEY_LENGTH], payload_hash: &Sha256) -> Script {\n\n let commitment = calc_commitment(pubkey_raw, payload_hash);\n\n Script::from_ops(\n\n vec![...