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/scheme/pipe.rs
coros-os/kernel
72ea559da439119a6b1dfe7859fde0077d72140f
use alloc::sync::{Arc, Weak}; use alloc::collections::{BTreeMap, VecDeque}; use core::sync::atomic::{AtomicUsize, Ordering}; use spin::{Mutex, Once, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::event; use crate::scheme::{AtomicSchemeId, SchemeId}; use crate::sync::WaitCondition; use crate::syscall::error::{E...
use alloc::sync::{Arc, Weak}; use alloc::collections::{BTreeMap, VecDeque}; use core::sync::atomic::{AtomicUsize, Ordering}; use spin::{Mutex, Once, RwLock, RwLockReadGuard, RwLockWriteGuard}; use crate::event; use crate::scheme::{AtomicSchemeId, SchemeId}; use crate::sync::WaitCondition; use crate::syscall::error::{E...
} if Arc::weak_count(&self.vec) == 0 { return Ok(0); } else if self.flags.load(Ordering::SeqCst) & O_NONBLOCK == O_NONBLOCK { return Err(Error::new(EAGAIN)); } else if ! self.condition.wait() { return Err(Error::new(EINTR)...
if i > 0 { event::trigger(self.scheme_id, self.write_id, EVENT_WRITE); return Ok(i); }
if_condition
[ { "content": "/// Get the current working directory\n\npub fn getcwd(buf: &mut [u8]) -> Result<usize> {\n\n let contexts = context::contexts();\n\n let context_lock = contexts.current().ok_or(Error::new(ESRCH))?;\n\n let context = context_lock.read();\n\n let cwd = context.cwd.lock();\n\n let mut...
Rust
src/stream.rs
sclickk/KatWebX
254619271c89d71ca3bac6de16d57cf026f4013f
#![allow(clippy::cast_possible_wrap)] #![allow(clippy::cast_sign_loss)] #![allow(clippy::filter_map)] extern crate lazy_static; extern crate actix_web; extern crate futures; extern crate futures_cpupool; extern crate brotli; extern crate bytes; use futures::{Async, Future, Poll, Stream}; use bytes::Bytes; use std::...
#![allow(clippy::cast_possible_wrap)] #![allow(clippy::cast_sign_loss)] #![allow(clippy::filter_map)] extern crate lazy_static; extern crate actix_web; extern crate futures; extern crate futures_cpupool; extern crate brotli; extern crate bytes; use futures::{Async, Future, Poll, Stream}; use bytes::Bytes; use std::...
}
Ok(Async::Ready(Some(bytes))) } Async::NotReady => Ok(Async::NotReady), }; } let size = self.size; let offset = self.offset; let counter = self.counter; if size == counter { Ok(Async::Ready(None)) } else { ...
function_block-function_prefix_line
[ { "content": "pub fn dir_listing(path: &str, trim: &str) -> Box<Future<Item=HttpResponse, Error=Error>> {\n\n\tlet f;\n\n\n\n\tmatch fs::read_dir(path) {\n\n\t\tOk(fi) => {f = fi},\n\n\t\tErr(_) => {\n\n\t\t\treturn http_error(StatusCode::NOT_FOUND, \"404 Not Found\", &[\"The resource \", path, \" could not be ...
Rust
splinterd/src/node/runnable/mod.rs
vaporos/splinter
934e69a2c41b05e050a7a27d35775ab206f97825
pub(super) mod admin; pub(super) mod network; use std::net::{Ipv4Addr, SocketAddr}; use splinter::error::InternalError; use splinter::rest_api::actix_web_1::RestApi; use splinter::rest_api::actix_web_3::RunnableRestApi; use super::builder::admin::AdminSubsystemBuilder; use super::{Node, NodeRestApiVariant}; use s...
pub(super) mod admin; pub(super) mod network; use std::net::{Ipv4Addr, SocketAddr}; use splinter::error::InternalError; use splinter::rest_api::actix_web_1::RestApi; use splinter::rest_api::actix_web_3::RunnableRestApi; use super::builder::admin::AdminSubsystemBuilder; use super::{Node, NodeRestApiVariant}; use s...
}
if port_numbers.len() != 1 { return Err(InternalError::with_message(format!( "Expected a single port number but saw multiple: {:?}", port_numbers ))); } NodeRestApiVariant::ActixWeb1(rest_api_shutdow...
function_block-function_prefix_line
[ { "content": "pub fn admin_service_id(node_id: &str) -> String {\n\n format!(\"admin::{}\", node_id)\n\n}\n\n\n", "file_path": "libsplinter/src/admin/service/mod.rs", "rank": 0, "score": 383475.90772952675 }, { "content": "pub fn run(\n\n bind_url: &str,\n\n splinterd_url: String,\n...
Rust
crates/rust-analyzer/src/cli/analysis_stats.rs
Arthamys/rust-analyzer
9707acb59b3f1f74bcc2f806ea5eab59279fad5e
use std::{ env, path::PathBuf, time::{SystemTime, UNIX_EPOCH}, }; use hir::{ db::{AstDatabase, DefDatabase, HirDatabase}, AssocItem, Crate, HasSource, HirDisplay, ModuleDef, }; use hir_def::FunctionId; use hir_ty::{Ty, TypeWalk}; use ide_db::base_db::{ salsa::{self, ParallelDatabase}, Sou...
use std::{ env, path::PathBuf, time::{SystemTime, UNIX_EPOCH}, }; use hir::{ db::{AstDatabase, DefDatabase, HirDatabase}, AssocItem, Crate, HasSource, HirDisplay, ModuleDef, }; use hir_def::FunctionId; use hir_ty::{Ty, TypeWalk}; use ide_db::base_db::{ salsa::{self, ParallelDatabase}, Sou...
let src = sm.expr_syntax(expr_id); if let Ok(src) = src { let root = db.parse_or_expand(src.file_id).unwrap(); let node = src.map(|e| e.to_node(&root).syntax().clone()); ...
}", "Item Collection:", analysis_sw.elapsed()); if self.randomize { shuffle(&mut rng, &mut funcs); } let mut bar = match verbosity { Verbosity::Quiet | Verbosity::Spammy => ProgressReport::hidden(), _ if self.parallel => ProgressReport::hidden(), ...
random
[ { "content": "fn segment_iter(path: &ast::Path) -> impl Iterator<Item = ast::PathSegment> + Clone {\n\n // cant make use of SyntaxNode::siblings, because the returned Iterator is not clone\n\n successors(first_segment(path), |p| p.parent_path().parent_path().and_then(|p| p.segment()))\n\n}\n\n\n", "fi...
Rust
crates/building_blocks_storage/src/multiresolution/chunk_pyramid.rs
metarmask/building-blocks
e0609d1c58b8cb4033c5c058cd51aa2663835560
use crate::{ prelude::*, ArrayNx1, ChunkDownsampler, ChunkMap, ChunkMapBuilder, ChunkMapBuilderNx1, ChunkMapNx1, FastArrayCompressionNx1, LodChunkKey, OctreeChunkIndex, OctreeNode, SmallKeyHashMap, VisitStatus, }; use building_blocks_core::prelude::*; use std::borrow::Borrow; use std::fmt::Debug; pub str...
use crate::{ prelude::*, ArrayNx1, ChunkDownsampler, ChunkMap, ChunkMapBuilder, ChunkMapBuilderNx1, ChunkMapNx1, FastArrayCompressionNx1, LodChunkKey, OctreeChunkIndex, OctreeNode, SmallKeyHashMap, VisitStatus, }; use building_blocks_core::prelude::*; use std::borrow::Borrow; use std::fmt::Debug; pub str...
} fn two_elems_mut<T>(levels: &mut [T], level_a: u8, level_b: u8) -> [&mut T; 2] { assert!(level_b > level_a); let (head, tail) = levels.split_at_mut(level_b as usize); let map_a = &mut head[level_a as usize]; let map_b = &mut tail[level_b as usize - level_a as usize - 1]; [map_a, map_b] } pub ...
pub fn downsample_chunks_with_lod0_and_index<Samp, Lod0Ch, Lod0ChBorrow>( &mut self, get_lod0_chunk: impl Fn(Point3i) -> Option<Lod0Ch>, index: &OctreeChunkIndex, sampler: &Samp, extent: &Extent3i, ) where Lod0Ch: Borrow<Lod0ChBorrow>, Samp: ChunkDownsampler<[...
function_block-full_function
[ { "content": "/// The \"Greedy Meshing\" algorithm described by Mikola Lysenko in the [0fps\n\n/// article](https://0fps.net/2012/06/30/meshing-in-a-minecraft-game/).\n\n///\n\n/// All visible faces of voxels on the interior of `extent` will be part of some `Quad` returned via the `output` buffer. A\n\n/// 3x3x...
Rust
storage/backup/backup-cli/src/backup_types/tests.rs
villesundell/aptos-core
5d1ded81eb59515b62d32898ff77454d663c0ca4
use crate::{ backup_types::{ state_snapshot::{ backup::{StateSnapshotBackupController, StateSnapshotBackupOpt}, restore::{StateSnapshotRestoreController, StateSnapshotRestoreOpt}, }, transaction::{ backup::{TransactionBackupController, TransactionBackupO...
use crate::{ backup_types::{ state_snapshot::{ backup::{StateSnapshotBackupController, StateSnapshotBackupOpt}, restore::{StateSnapshotRestoreController, StateSnapshotRestoreOpt}, }, transaction::{ backup::{TransactionBackupController, TransactionBackupO...
; rt.shutdown_timeout(Duration::from_secs(1)); } proptest! { #![proptest_config(ProptestConfig::with_cases(10))] #[test] fn test_end_to_end(d in test_data_strategy()) { test_end_to_end_impl(d) } }
if let Some(state_snapshot_ver) = d.state_snapshot_ver { let first_replayed = state_snapshot_ver + 1; let num_replayed = d.target_ver - state_snapshot_ver; assert_eq!( d.db.get_transactions(first_replayed, num_replayed, d.target_ver, true) .unwrap(), ...
if_condition
[ { "content": "fn put_transaction_info(db: &AptosDB, version: Version, txn_info: &TransactionInfo) {\n\n let mut cs = ChangeSet::new();\n\n db.ledger_store\n\n .put_transaction_infos(version, &[txn_info.clone()], &mut cs)\n\n .unwrap();\n\n db.db.write_schemas(cs.batch).unwrap();\n\n}\n", ...
Rust
rtest_core/src/shadow_copy_destination.rs
PhilipDaniels/rtest
6a666646cdcde08a600913595c1f4bc5f2348a0e
use log::{error, info}; use std::{sync::Arc, path::{Path, PathBuf}}; use tempfile::TempDir; #[derive(Debug, Clone)] pub enum DestinationDirectory { SameAsSource, NamedDirectory(PathBuf), TempDirectory(Arc<TempDir>), } impl DestinationDirectory { pub fn is_copying(&self) -> bool { ...
use log::{error, info}; use std::{sync::Arc, path::{Path, PathBuf}}; use tempfile::TempDir; #[derive(Debug, Clone)] pub enum DestinationDirectory { SameAsSource, NamedDirectory(PathBuf), TempDirectory(Arc<TempDir>), } impl DestinationDirectory { pub fn is_copying(&self) -> bool { ...
pub fn with_named_directory(source_directory: PathBuf, destination: PathBuf) -> Self { Self { source_directory, destination: DestinationDirectory::NamedDirectory(destination), } } pub fn is_copying(&self) -> bool { self.destination.is_copying() } p...
pub fn with_temp_destination(source_directory: PathBuf) -> Self { let temp_dir = tempfile::tempdir().expect("Cannot create tempdir"); Self { source_directory, destination: DestinationDirectory::TempDirectory(Arc::new(temp_dir)), } }
function_block-full_function
[ { "content": "pub fn new() -> Configuration {\n\n let args = get_cli_arguments();\n\n info!(\"CLI {:?}\", args);\n\n\n\n let destination = args.make_shadow_copy_destination();\n\n Configuration {\n\n inner: Arc::new(InnerConfiguration { args, destination }),\n\n }\n\n}\n\n\n\nimpl InnerCon...
Rust
examples/pong.rs
hawk-labs/ws
65c33e6789dcc4925ccca13b51433b8e193a6115
extern crate env_logger; extern crate time; extern crate ws; use std::str::from_utf8; use ws::util::{Timeout, Token}; use ws::{ listen, CloseCode, Error, ErrorKind, Frame, Handler, Handshake, Message, OpCode, Result, Sender, }; const PING: Token = Token(1); const EXPIRE: Token = Token(2); fn main() { ...
extern crate env_logger; extern crate time; extern crate ws; use std::str::from_utf8; use ws::util::{Timeout, Token}; use ws::{ listen, CloseCode, Error, ErrorKind, Frame, Handler, Handshake, Message, OpCode, Result, Sender, }; const PING: Token = Token(1); const EXPIRE: Token = Token(2); fn main() { ...
fn on_new_timeout(&mut self, event: Token, timeout: Timeout) -> Result<()> { if event == EXPIRE { if let Some(t) = self.expire_timeout.take() { try!(self.out.cancel(t)) } self.expire_timeout = Some(timeout) } else { ...
w( ErrorKind::Internal, "Invalid timeout token encountered!", )), } }
function_block-function_prefixed
[ { "content": "fn main() {\n\n // Setup logging\n\n env_logger::init().unwrap();\n\n\n\n // Listen on an address and call the closure for each connection\n\n if let Err(error) = listen(\"127.0.0.1:3012\", |out| {\n\n // The handler needs to take ownership of out, so we use move\n\n move...
Rust
src/testing.rs
eddyb/finality-grandpa
e00b6237555c028650df7138a575037ef5702eaa
pub mod chain { use crate::{Chain, Error}; use crate::std::{collections::HashMap, vec::Vec}; pub const GENESIS_HASH: &str = "genesis"; const NULL_HASH: &str = "NULL"; struct BlockRecord { number: u32, parent: &'static str, } pub struct DummyChain { inner: HashMap<&'static str, BlockRecord>, leaves: ...
pub mod chain { use crate::{Chain, Error}; use crate::std::{collections::HashMap, vec::Vec}; pub const GENESIS_HASH: &str = "genesis"; const NULL_HASH: &str = "NULL"; struct BlockRecord { number: u32, parent: &'static str, } pub struct DummyChain { inner: HashMap<&'static str, BlockRecord>, leaves: ...
pub fn number(&self, hash: &'static str) -> u32 { self.inner.get(hash).unwrap().number } pub fn last_finalized(&self) -> (&'static str, u32) { self.finalized.clone() } pub fn set_last_finalized(&mut self, last_finalized: (&'static str, u32)) { self.finalized = last_finalized; } } impl Chain<...
pub fn push_blocks(&mut self, mut parent: &'static str, blocks: &[&'static str]) { if blocks.is_empty() { return } let base_number = self.inner.get(parent).unwrap().number + 1; if let Some(pos) = self.leaves.iter().position(|x| x == &parent) { self.leaves.remove(pos); } for (i, descendent) in bloc...
function_block-full_function
[ { "content": "/// Necessary environment for a voter.\n\n///\n\n/// This encapsulates the database and networking layers of the chain.\n\npub trait Environment<H: Eq, N: BlockNumberOps>: Chain<H, N> {\n\n\ttype Timer: Future<Item=(),Error=Self::Error>;\n\n\ttype Id: Hash + Clone + Eq + ::std::fmt::Debug;\n\n\tty...
Rust
diesel/src/expression/sql_literal.rs
marcelbuesing/diesel
42d5b831ac6b407c74a3659653f5b9d171730851
use std::marker::PhantomData; use backend::Backend; use expression::*; use query_builder::*; use query_dsl::RunQueryDsl; use result::QueryResult; #[derive(Debug, Clone, DieselNumericOps)] #[must_use = "Queries are only executed when calling `load`, `get_result`, or similar."] pub struct SqlLiteral<ST, T = ()> { ...
use std::marker::PhantomData; use backend::Backend; use expression::*; use query_builder::*; use query_dsl::RunQueryDsl; use result::QueryResult; #[derive(Debug, Clone, DieselNumericOps)] #[must_use = "Queries are only executed when calling `load`, `get_result`, or similar."] pub struct SqlLiteral<ST, T = ()> { ...
ub fn sql<ST>(sql: &str) -> SqlLiteral<ST> { SqlLiteral::new(sql.into(), ()) } #[derive(QueryId, Debug, Clone, Copy)] #[must_use = "Queries are only executed when calling `load`, `get_result`, or similar."] pub struct UncheckedBind<Query, Value> { query: Query, value: Value, } impl<Query, Value> Unchecke...
pub fn sql(self, sql: &str) -> SqlLiteral<ST, Self> { SqlLiteral::new(sql.into(), self) } } impl<ST, T> Expression for SqlLiteral<ST, T> { type SqlType = ST; } impl<ST, T, DB> QueryFragment<DB> for SqlLiteral<ST, T> where DB: Backend, T: QueryFragment<DB>, { fn walk_ast(&self...
random
[ { "content": "/// Construct a full SQL query using raw SQL.\n\n///\n\n/// This function exists for cases where a query needs to be written that is not\n\n/// supported by the query builder. Unlike most queries in Diesel, `sql_query`\n\n/// will deserialize its data by name, not by index. That means that you can...
Rust
consensus/src/chained_bft/liveness/timeout_msg.rs
xpeerchain/xpeerchain
27b2d9a0b3243b1834cf713ee7199f720fa7b3c3
use crate::chained_bft::{ common::{Author, Round}, consensus_types::quorum_cert::QuorumCert, liveness::timeout_msg::PacemakerTimeoutCertificateVerificationError::*, }; use canonical_serialization::{CanonicalSerialize, CanonicalSerializer, SimpleSerializer}; use crypto::{ hash::{CryptoHash, CryptoHashe...
use crate::chained_bft::{ common::{Author, Round}, consensus_types::quorum_cert::QuorumCert, liveness::timeout_msg::PacemakerTimeoutCertificateVerificationError::*, }; use canonical_serialization::{CanonicalSerialize, CanonicalSerializer, SimpleSerializer}; use crypto::{ hash::{CryptoHash, CryptoHashe...
pub fn highest_quorum_certificate(&self) -> &QuorumCert { &self.highest_quorum_certificate } pub fn highest_ledger_info(&self) -> &QuorumCert { &self.highest_ledger_info } pub fn pacemaker_timeout(&self) -> &PacemakerTimeout { &self.pacemaker_timeout } ...
pub fn digest(&self) -> HashValue { Self::new_round_digest( self.highest_quorum_certificate.certified_block_id(), self.pacemaker_timeout.digest(), ) }
function_block-function_prefix_line
[ { "content": "/// A type for key material that can be publicly shared, and in asymmetric\n\n/// fashion, can be obtained from a [`PrivateKey`][PrivateKey]\n\n/// reference.\n\n/// This convertibility requirement ensures the existence of a\n\n/// deterministic, canonical public key construction from a private ke...
Rust
rboot/src/page_table.rs
pdeantihuman/rcore-fork
c27736422f5c6dbb1d2224b8b0e2261988d6e650
use x86_64::structures::paging::{ mapper::*, FrameAllocator, Mapper, Page, PageSize, PageTableFlags, PhysFrame, Size2MiB, Size4KiB, }; use x86_64::{align_up, PhysAddr, VirtAddr}; use xmas_elf::{program, ElfFile}; pub fn map_elf( elf: &ElfFile, page_table: &mut impl Mapper<Size4KiB>, frame_allocat...
use x86_64::structures::paging::{ mapper::*, FrameAllocator, Mapper, Page, PageSize, PageTableFlags, PhysFrame, Size2MiB, Size4KiB, }; use x86_64::{align_up, PhysAddr, VirtAddr}; use xmas_elf::{program, ElfFile}; pub fn map_elf( elf: &ElfFile, page_table: &mut impl Mapper<Size4KiB>, frame_allocat...
fn map_segment( segment: &program::ProgramHeader, kernel_start: PhysAddr, page_table: &mut impl Mapper<Size4KiB>, frame_allocator: &mut impl FrameAllocator<Size4KiB>, ) -> Result<(), MapToError> { match segment.get_type().unwrap() { program::Type::Load => { debug!("mapping segm...
info!("mapping stack at {:#x}", addr); let stack_start = Page::containing_address(VirtAddr::new(addr)); let stack_end = stack_start + pages; let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE; for page in Page::range(stack_start, stack_end) { let frame = frame_allocator ...
function_block-function_prefix_line
[ { "content": "pub fn root_page_table_buffer() -> &'static mut MIPSPageTable {\n\n unsafe { &mut *(_root_page_table_ptr as *mut MIPSPageTable) }\n\n}\n\n\n\n/// implementation for the Entry trait in /crate/memory/src/paging/mod.rs\n\nimpl Entry for PageEntry {\n\n fn update(&mut self) {\n\n TLBEntry...
Rust
src/routes/user/avatar.rs
mellowagain/gitarena
c955008148f44800c1040075460b60b3caa29137
use crate::mail::Email; use crate::prelude::HttpRequestExtensions; use crate::user::WebUser; use crate::utils::reqwest_actix_stream::ResponseStream; use crate::{die, err}; use std::fs; use std::io::Cursor; use std::path::Path; use std::time::SystemTime; use actix_multipart::Multipart; use actix_web::web::Buf; use act...
use crate::mail::Email; use crate::prelude::HttpRequestExtensions; use crate::user::WebUser; use crate::utils::reqwest_actix_stream::ResponseStream; use crate::{die, err}; use std::fs; use std::io::Cursor; use std::path::Path; use std::time::SystemTime; use actix_multipart::Multipart; use actix_web::web::Buf; use act...
async fn send_image<P: AsRef<Path>>(path: P, request: &HttpRequest) -> Result<HttpResponse> { let path = path.as_ref(); let mut response = HttpResponse::Ok(); response.content_type("image/jpeg"); let meta_data = fs::metadata(path)?; if let Ok(modified_system_time) = meta_data.modified() { ...
let avatars_dir: String = from_config!("avatars.dir" => String); let mut field = match payload.try_next().await { Ok(Some(field)) => field, Ok(None) => die!(BAD_REQUEST, "No multipart field found"), Err(err) => return Err(err.into()) }; let content_disposition = field.content_dispo...
function_block-function_prefix_line
[ { "content": "fn query_string_without_offset(input: &QString) -> String {\n\n input.to_pairs()\n\n .iter()\n\n .filter(|(key, _)| key != &\"offset\")\n\n .map(|(key, value)| format!(\"{}={}\", key, value))\n\n .collect::<Vec<String>>()\n\n .join(\"&\")\n\n}\n", "file_pa...
Rust
tests/common/mod.rs
enarx/enarx
03cac7ce7a3ad483b4224ea6085c585a47ea499b
use process_control::{ChildExt, Output, Timeout}; use std::io::Write; use std::path::Path; use std::process::{Command, Stdio}; use std::time::Duration; pub const CRATE: &str = env!("CARGO_MANIFEST_DIR"); pub const KEEP_BIN: &str = env!("CARGO_BIN_EXE_enarx"); pub const OUT_DIR: &str = env!("OUT_DIR"); pub const TEST...
use process_control::{ChildExt, Output, Timeout}; use std::io::Write; use std::path::Path; use std::process::{Command, Stdio}; use std::time::Duration; pub const CRATE: &str = env!("CARGO_MANIFEST_DIR"); pub const KEEP_BIN: &str = env!("CARGO_BIN_EXE_enarx"); pub const OUT_DIR: &str = env!("OUT_DIR"); pub const TEST...
Output { let output = keepldr_exec(bin, input); check_output(&output, status.into(), expected_stdout, expected_stderr); output }
function_block-function_prefix_line
[ { "content": "pub fn enarx_run<'a>(wasm: &str, input: impl Into<Option<&'a [u8]>>) -> Output {\n\n let wasm_path = Path::new(CRATE)\n\n .join(OUT_DIR)\n\n .join(TEST_BINS_OUT)\n\n .join(wasm);\n\n\n\n let mut child = Command::new(&String::from(KEEP_BIN))\n\n .current_dir(CRATE)...
Rust
src/models/attr.rs
Nejat/web-reference
7ce9002d9a4683a24d438105152bcf3c7c11e2d4
use crate::prelude::*; #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(rename_all = "kebab-case"))] #[derive(Debug, Clone, Eq, PartialEq)] pub struct Attribute { pub na...
use crate::prelude::*; #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(any(feature = "serialize", feature = "deserialize"), serde(rename_all = "kebab-case"))] #[derive(Debug, Clone, Eq, PartialEq)] pub struct Attribute { pub na...
ongsTo { #[inline] #[must_use] pub fn has_tags(&self) -> bool { !(*self == Self::Global || *self == Self::NotSupported) } } #[cfg_attr(feature = "deserialize", derive(Deserialize))] #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(any(feature = "serialize", featu...
pty"))] #[cfg_attr(all(feature = "serialize", feature = "ordered-map", feature = "serde_json"), serde(with = "indexmap::serde_seq"))] #[cfg_attr(all(feature = "serialize", not(feature = "ordered-map")), serde(skip_serializing_if = "HashMap::is_empty"))] #[cfg_attr(feature = "deserialize", ser...
random
[ { "content": "fn scrape_event_details_page(url: &Url, event: &String) -> Result<(SupportedBrowsers, Map<String, String>)> {\n\n let doc_topic = format!(\"{event:?} Event Details\");\n\n\n\n let root = retrieve_document(url, &doc_topic)?;\n\n\n\n let browser_support = root.find(predicate::Name(\"h2\"))....
Rust
src/framework/standard/structures/check.rs
Maspenguin/serenity
49b7b161569cba243ebf8539c0598f976163b2dd
use std::fmt::Debug; use std::fmt; use crate::model::channel::Message; use crate::client::Context; use crate::framework::standard::{Args, CommandOptions}; use futures::future::BoxFuture; #[derive(Clone, Debug)] #[non_exhaustive] pub enum Reason { Unknown, User(String), Log(String), ...
use std::fmt::Debug; use std::fmt; use crate::model::channel::Message; use crate::client::Context; use crate::framework::standard::{Args, CommandOptions}; use futures::future::BoxFuture; #[derive(Clone, Debug)] #[non_exhaustive] pub enum Reason { Unknown, User(String), Log(String), ...
} impl From<Reason> for CheckResult { fn from(reason: Reason) -> Self { CheckResult::Failure(reason) } } pub type CheckFunction = for<'fut> fn( &'fut Context, &'fut Message, &'fut mut Args, &'fut CommandOptions, ) -> BoxFuture<'fut, CheckResult>; pub struct Check { pub name:...
fn from(succeeded: bool) -> Self { if succeeded { CheckResult::Success } else { CheckResult::Failure(Reason::Unknown) } }
function_block-full_function
[ { "content": "pub fn default_true() -> bool {\n\n true\n\n}\n\n\n", "file_path": "src/model/utils.rs", "rank": 0, "score": 243578.65910452488 }, { "content": "/// Turns a string into a vector of string arguments, splitting by spaces, but\n\n/// parsing content within quotes as one individ...
Rust
open-cl-low-level/src/command_queue/event/event.rs
elbow-jason/open_cl_rust
c1fb6c7eb3ec3109d9bf42d515a2a1f9bbe9f821
use super::{functions, Waitlist}; use crate::cl::{cl_event, CommandExecutionStatus, EventInfo, ObjectWrapper, ProfilingInfo}; use crate::{CommandQueue, Context, Number, Output}; use std::mem::ManuallyDrop; use std::time::Duration; use thiserror::Error; pub type Event = ObjectWrapper<cl_event>; pub unsafe trait EventP...
use super::{functions, Waitlist}; use crate::cl::{cl_event, CommandExecutionStatus, EventInfo, ObjectWrapper, ProfilingInfo}; use crate::{CommandQueue, Context, Number, Output}; use std::mem::ManuallyDrop; use std::time::Duration; use thiserror::Error; pub type Event = ObjectWrapper<cl_event>; pub unsafe trait EventP...
let (_sess, event) = get_event(); let output = unsafe { event.reference_count() }.expect("Failed to call event.reference_count()"); assert_eq!(output, 1); } #[test] fn event_method_command_queue_works() { let (_sess, event) = get_event(); let _output: Comm...
Session, Event) { unsafe { let mut session: Session = SessionBuilder::new().with_program_src(SRC).build().unwrap(); let mut kernel = Kernel::create(session.program(), "add_one").expect("Failed to Kernel::create/2"); let input_data: Vec<u64> = vec![1, 2, 3]; ...
random
[ { "content": "pub fn mem_from_data_and_context<T: Number>(data: &[T], context: &Context) -> Mem {\n\n unsafe { Mem::create_with_config::<T, &[T]>(context, data, MemConfig::for_data()).unwrap() }\n\n}\n\n\n", "file_path": "open-cl-low-level/src/ll_testing.rs", "rank": 0, "score": 371828.6602287722...
Rust
rust/src/schema.rs
bbigras/delta-rs
68061a25fd04f864b4fc79160867ba58b91e9813
#![allow(non_snake_case, non_camel_case_types)] use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::collections::HashMap; pub type Guid = String; pub type DeltaDataTypeLong = i64; pub type DeltaDataTypeVersion = DeltaDataTypeLong; pub type DeltaDataTypeTimestamp = DeltaDataTypeLong; pub type Delta...
#![allow(non_snake_case, non_camel_case_types)] use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::collections::HashMap; pub type Gu
lds } } #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] pub struct SchemaField { name: String, r#type: SchemaDataType, nullable: bool, metadata: HashMap<String, String>, } impl SchemaField { pub fn new( name: String, r#type: SchemaDataType, ...
id = String; pub type DeltaDataTypeLong = i64; pub type DeltaDataTypeVersion = DeltaDataTypeLong; pub type DeltaDataTypeTimestamp = DeltaDataTypeLong; pub type DeltaDataTypeInt = i32; static STRUCT_TAG: &str = "struct"; #[derive(Serialize, Deserialize, PartialEq, Debug, Default, Clone)] pub struct SchemaTypeStruc...
random
[ { "content": "pub fn create_add(\n\n partition_values: &HashMap<String, Option<String>>,\n\n path: String,\n\n size: i64,\n\n record_batch: &RecordBatch,\n\n) -> Result<Add, DeltaWriterError> {\n\n let stats = Stats {\n\n num_records: record_batch.num_rows() as i64,\n\n // TODO: cal...
Rust
src/crypto/pkey.rs
kinghajj/rust-openssl
19eab0e7d729159104a0959c7c1209f1e8951db2
use libc::{c_int, c_uint}; use std::mem; use std::ptr; use bio::{MemBio}; use crypto::hash::{HashType, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, RIPEMD160}; use ffi; use ssl::error::{SslError, StreamError}; enum Parts { Neither, Public, Both } pub enum Role { Encrypt, Decrypt, Sign, Verif...
use libc::{c_int, c_uint}; use std::mem; use std::ptr; use bio::{MemBio}; use crypto::hash::{HashType, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, RIPEMD160}; use ffi; use ssl::error::{SslError, StreamError}; enum Parts { Neither, Public, Both } pub enum Role { Encrypt, Decrypt, Sign, Verif...
#[test] fn test_gen_priv() { let mut k0 = super::PKey::new(); let mut k1 = super::PKey::new(); k0.gen(512u); k1.load_priv(k0.save_priv().as_slice()); assert_eq!(k0.save_priv(), k1.save_priv()); assert_eq!(k0.size(), k1.size()); assert!(k0.can(super::Encr...
ave_pub()); assert_eq!(k0.size(), k1.size()); assert!(k0.can(super::Encrypt)); assert!(k0.can(super::Decrypt)); assert!(k0.can(super::Verify)); assert!(k0.can(super::Sign)); assert!(k1.can(super::Encrypt)); assert!(!k1.can(super::Decrypt)); assert!(k1.can(...
function_block-function_prefixed
[ { "content": "pub fn decrypt(t: Type, key: &[u8], iv: Vec<u8>, data: &[u8]) -> Vec<u8> {\n\n let c = Crypter::new(t);\n\n c.init(Decrypt, key, iv);\n\n let mut r = c.update(data);\n\n let rest = c.final();\n\n r.extend(rest.into_iter());\n\n r\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use...
Rust
tests/tokio.rs
federicomenaquintero/bzip2-rs
18fd3e18bc1763219a7496e466a16bd213448fec
#![cfg(feature = "tokio")] extern crate tokio_core; extern crate bzip2; extern crate tokio_io; extern crate futures; extern crate rand; use std::thread; use std::net::{Shutdown, TcpListener}; use std::io::{Read, Write}; use bzip2::Compression; use bzip2::read; use bzip2::write; use futures::Future; use rand::{Rng, t...
#![cfg(feature = "tokio")] extern crate tokio_core; extern crate bzip2; extern crate tokio_io; extern crate futures; extern crate rand; use std::thread; use std::net::{Shutdown, TcpListener}; use std::io::{Read, Write}; use bzip2::Compression; use bzip2::read; use bzip2::write; use futures::Future; use rand::{Rng, t...
p(); }); let handle = core.handle(); let stream = TcpStream::connect(&addr, &handle); let copy = stream.and_then(|s| { let (a, b) = s.split(); let a = read::BzDecoder::new(a); let b = write::BzEncoder::new(b, Compression::default()); copy(a, b) }).then(|result| { ...
function_block-function_prefixed
[ { "content": "static \n\nBool testStream ( FILE *zStream )\n\n{\n\n BZFILE* bzf = NULL;\n\n Int32 bzerr, bzerr_dummy, ret, nread, streamNo, i;\n\n UChar obuf[5000];\n\n UChar unused[BZ_MAX_UNUSED];\n\n Int32 nUnused;\n\n void* unusedTmpV;\n\n UChar* unusedTmp;\n\n\n\n nUnused = 0;\n\n...
Rust
crates/lang/codegen/src/generator/as_dependency/call_builder.rs
LedgerProject/ink
7432565b7e91cbe41f47be57ee0a344429724cc8
use crate::{ generator, GenerateCode, }; use derive_more::From; use ir::Callable; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, quote_spanned, }; use syn::spanned::Spanned as _; #[derive(From)] pub struct CallBuilder<'a> { contract: &'a ir::Contract, } impl ...
use crate::{ generator, GenerateCode, }; use derive_more::From; use ir::Callable; use proc_macro2::TokenStream as TokenStream2; use quote::{ format_ident, quote, quote_spanned, }; use syn::spanned::Spanned as _; #[derive(From)] pub struct CallBuilder<'a> { contract: &'a ir::Contract, } impl ...
::ink_env::call::utils::ReturnType<#output> }, ); let output_span = output.span(); let output_type = quote_spanned!(output_span=> ::ink_env::call::CallBuilder< Environment, ::ink_env::call::utils::Set< <Environment as ::ink_env::Environment>::AccountI...
.callable() .inputs() .map(|input| (&input.pat, &input.ty)) .unzip(); let mut_token = message .receiver() .is_ref_mut() .then(|| Some(quote! { mut })); let build_cmd = match message.receiver() { ir::Receiver...
random
[ { "content": "/// Conducts the crypto hash of the given input and stores the result in `output`.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use ink_env::hash::{Sha2x256, HashOutput};\n\n/// let input: &[u8] = &[13, 14, 15];\n\n/// let mut output = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buff...
Rust
fdb/examples/get_mapped_range.rs
fdb-rs/fdb
e150892442d8e23a494089bafd93a8eb227b935a
use bytes::Bytes; use fdb::database::FdbDatabase; use fdb::error::FdbResult; use fdb::range::{Range, RangeOptions}; use fdb::transaction::{FdbTransaction, Transaction}; use fdb::tuple::Tuple; use fdb::{Key, Mapper, Value}; use tokio::runtime::Runtime; use tokio_stream::StreamExt; use std::env; use std::error::Error;...
use bytes::Bytes; use fdb::database::FdbDatabase; use fdb::error::FdbResult; use fdb::range::{Range, RangeOptions}; use fdb::transaction::{FdbTransaction, Transaction}; use fdb::tuple::Tuple; use fdb::{Key, Mapper, Value}; use tokio::runtime::Runtime; use tokio_stream::StreamExt; use std::env; use std::error::Error;...
fn insert_record_with_index(tr: &FdbTransaction, i: u32) { tr.set(index_entry_key(i), empty()); (0..SPLIT_SIZE).for_each(|j| { tr.set(record_key(i, j), record_value(i, j)); }); } async fn insert_record_with_indexes(n: u32, db: &FdbDatabase) -> FdbResult<()> { db.run(|tr| async move { ...
tup.add_string(rec_value_tup.0); tup.add_i64(rec_value_tup.1.into()); tup }; rec_value.pack().into() }
function_block-function_prefix_line
[ { "content": "/// Computes the first key that would sort outside the range prefixed\n\n/// by `prefix`.\n\n///\n\n/// The `prefix` must not be empty or contain only `0xFF` bytes. That\n\n/// is `prefix` must contain at least one byte not equal to `0xFF`.\n\n///\n\n/// This resulting [`Key`] serves as the exclus...
Rust
ontio-codegen/src/contract.rs
ontio/ontio-cdk
bb8d531c926c9e863215a5232ee8807b6554d121
use proc_macro2::Span; use quote::quote; use quote::ToTokens; pub fn quote(item: syn::Item) -> proc_macro2::TokenStream { match item { syn::Item::Trait(item_trait) => { let contract = Contract::from_item_trait(item_trait); let disp = generate_dispatcher(&contract); let t...
use proc_macro2::Span; use quote::quote; use quote::ToTokens; pub fn quote(item: syn::Item) -> proc_macro2::TokenStream { match item { syn::Item::Trait(item_trait) => { let contract = Contract::from_item_trait(item_trait); let disp = generate_dispatcher(&contract); let t...
syn::TraitItemMethod, } impl ContractAction { fn from_trait_method(method: syn::TraitItemMethod) -> Self { let mut m = method.clone(); m.attrs = Vec::new(); let params = method .sig .inputs .into_iter() .filter_map(|arg| match arg { ...
extern crate alloc; #trait_and_event #disp } } _ => { panic!("`#[contract]` can only be used on a trait"); } } } #[derive(Debug)] pub(crate) struct Contract { name: syn::Ident, fields: Vec<ContractField>, } impl Con...
random
[ { "content": "#[proc_macro]\n\npub fn keccak256(item: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(item as Lit);\n\n let data = match input {\n\n syn::Lit::Str(lit_str) => lit_str.value().as_bytes().to_vec(),\n\n syn::Lit::ByteStr(lit_str) => lit_str.value(),\n\n _...
Rust
src/offline/operators.rs
robert-chiniquy/rust-aws-iam
18ad3c12072ae498c1bc2656283160001b3fe0a1
use crate::model::{ConditionValue, GlobalConditionOperator, QString}; use crate::offline::variables::expand_string; use crate::offline::EvaluationError; use std::collections::HashMap; use std::fmt::Display; use std::fmt::Error; use std::fmt::Formatter; use std::string::ToString; use tracing::{error, instrument}; pub t...
use crate::model::{ConditionValue, GlobalConditionOperator, QString}; use crate::offline::variables::expand_string; use crate::offline::EvaluationError; use std::collections::HashMap; use std::fmt::Display; use std::fmt::Error; use std::fmt::Formatter; use std::string::ToString; use tracing::{error, instrument}; pub t...
fn expand_rhs_value( environment: &HashMap<QString, ConditionValue>, rhs: ConditionValue, ) -> Result<ConditionValue, EvaluationError> { match rhs { ConditionValue::String(input) => { let output = expand_string(environment, &input)?; Ok(ConditionValue::String(output)) ...
ExpectedValueType::Integer, ConditionValue::Integer(_)) | (ExpectedValueType::Float, ConditionValue::Float(_)) | (ExpectedValueType::Bool, ConditionValue::Bool(_)) => lhs, (ev, _) => return Err(EvaluationError::ExpectingVariableType(ev.to_string())), }; let rhs = match (value_type, rhs) ...
function_block-function_prefix_line
[ { "content": "///\n\n/// Read a `Policy` document from any implementation of `std::io::Read`.\n\n///\n\npub fn read_from_reader<R>(reader: R) -> Result<Policy, Error>\n\nwhere\n\n R: Read + Sized,\n\n{\n\n let reader = BufReader::new(reader);\n\n match serde_json::from_reader(reader) {\n\n Ok(po...
Rust
src/connectivity/bluetooth/lib/bt-a2dp/src/media_task.rs
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
use { bt_avdtp::MediaStream, fuchsia_bluetooth::types::PeerId, futures::{ future::{BoxFuture, Shared}, FutureExt, }, thiserror::Error, }; use crate::codec::MediaCodecConfig; use crate::inspect::DataStreamInspect; #[derive(Debug, Error, Clone)] #[non_exhaustive] pub enum MediaTask...
use { bt_avdtp::MediaStream, fuchsia_bluetooth::types::PeerId, futures::{ future::{BoxFuture, Shared}, FutureExt, }, thiserror::Error, }; use crate::codec::MediaCodecConfig; use crate::inspect::DataStreamInspect; #[derive(Debug, Error, Clone)] #[non_exhaustive] pub enum MediaTask...
} self.finished().now_or_never().unwrap() } } pub struct TestMediaTaskRunner { pub peer_id: PeerId, pub codec_config: MediaCodecConfig, pub sender: mpsc::Sender<TestMediaTask>, } impl MediaTaskRunner for T...
if let Some(sender) = lock.take() { let _ = sender.send(Ok(())); return Ok(()); }
if_condition
[]
Rust
src/gnss/gsv.rs
johann2/nmea-parser
0dd55af67546526399bbc026067e51da8ea3fdc1
/* Copyright 2020 Timo Saarinen 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 agreed to in writing, software d...
/* Copyright 2020 Timo Saarinen 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 agreed to in writing, software d...
; } } } Err(e) => { assert_eq!(e.to_string(), "OK"); } } assert_eq!(p.strings_count(), 0); } }
me(244.0)); assert_eq!(s11.snr, Some(0.0)); } _ => { assert_eq!(p.strings_count(), 3); assert!(false)
random
[ { "content": "/// A simple helper to pick a substring of length two from the given string.\n\nfn pick_s2(s: &str, i: usize) -> &str {\n\n let end = i + 2;\n\n s.get(i..end).unwrap_or(\"\")\n\n}\n\n\n\n/// Parse latitude from two string.\n\n/// Argument `lat_string` expects format DDMM.MMM representing lat...
Rust
src/mib_disks.rs
Svedrin/sunt
d873a27b786af2f065663e7cb4b74759a1eb1ad8
use std::collections::{BTreeMap,HashSet}; use value::Value; use oid::OID; use std::fs; use std::fs::File; use std::mem; use std::io::{BufReader,BufRead,Error}; use std::path::PathBuf; use std::ffi::CString; use libc; /** * device is some path under /dev. Resolve symlinks down to the actual /dev/something. */ fn reso...
use std::collections::{BTreeMap,HashSet}; use value::Value; use oid::OID; use std::fs; use std::fs::File; use std::mem; use std::io::{BufReader,BufRead,Error}; use std::path::PathBuf; use std::ffi::CString; use libc; /** * device is some path under /dev. Resolve symlinks down to the actual /dev/something. */ fn reso...
pub fn get_disks(values: &mut BTreeMap<OID, Value>, base_oid: &str) { if let Ok(diskstats) = File::open("/proc/diskstats") { let mut disk_idx = 1; for line in BufReader::new(diskstats).lines() { let line = line.unwrap(); let parts = line.split_whitespace()....
values.insert( OID::from_parts_and_instance(&[dsk_table_oid, "10"], disk_idx), Value::Integer((f_fused * 100 / fsstat.f_files) as i64) ); } disk_idx += 1; } } }
function_block-function_prefix_line
[ { "content": "pub fn get_system(values: &mut BTreeMap<OID, Value>, base_oid: &str) {\n\n if let Ok(info) = uname::uname() {\n\n values.insert(\n\n OID::from_parts(&[base_oid, \"1.0\"]),\n\n Value::OctetString(format!(\n\n \"{} {} {} {} {}\",\n\n info...
Rust
src/server/webrtc/webrtc_dispatcher.rs
OpenStarscape/OSpServerRs
9c18b21a10b4b206f3a743f520a4df3c2d9e301c
use super::*; enum DispatchTarget { Buffer(Vec<Vec<u8>>), OverflowedBuffer(usize), Handler(Box<dyn InboundBundleHandler>), } impl DispatchTarget { fn new() -> Self { Self::Buffer(Vec::new()) } fn dispatch(&mut self, data: &[u8]) { match self { ...
use super::*; enum DispatchTarget { Buffer(Vec<Vec<u8>>), OverflowedBuffer(usize), Handler(Box<dyn InboundBundleHandler>), } impl DispatchTarget { fn new() -> Self { Self::Buffer(Vec::new()) } fn dispatch(&mut self, data: &[u8]) { match self { ...
pub fn dispatch_inbound(&self, addr: &SocketAddr, data: &[u8]) { match self.lock() { Ok(mut locked) => match locked.session_map.get_mut(addr) { Some(target) => target.dispatch(data), None => { let mut target = DispatchTarget::new(); ...
pub fn set_inbound_handler( &self, addr: &SocketAddr, handler: Box<dyn InboundBundleHandler>, ) -> Result<(), Box<dyn Error>> { let mut locked = self.lock()?; locked .session_map .get_mut(addr) .ok_or(format!("can not set handler for unknow...
function_block-function_prefixed
[ { "content": "pub fn parse_args(builder: &mut ConfigBuilder, args: Vec<String>) -> Result<(), Box<dyn Error>> {\n\n let parsed = parse_list(&args)?;\n\n if parsed.help {\n\n let prog_name = args\n\n .first()\n\n .map(String::as_str)\n\n .unwrap_or(\"starscape-server...
Rust
tracing/benches/subscriber.rs
darinmorrison/tokio-tracing
4e87df54842aed979f79cbf2859f71d518e09674
extern crate criterion; extern crate tracing; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use tracing::Level; use std::{ fmt, sync::{Mutex, MutexGuard}, }; use tracing::{field, span, Event, Id, Metadata}; struct EnabledSubscriber; impl tracing::Subscriber for EnabledSubscriber { ...
extern crate criterion; extern crate tracing; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use tracing::Level; use std::{ fmt, sync::{Mutex, MutexGuard}, }; use tracing::{field, span, Event, Id, Metadata}; struct EnabledSubscriber; impl tracing::Subscriber for EnabledSubscriber { ...
fn bench_dispatch(c: &mut Criterion) { let mut group = c.benchmark_group("no/dispatch"); group.bench_function("get_ref", |b| { b.iter(|| { tracing::dispatcher::get_default(|current| { black_box(&current); }) }) }); group.bench_function("get_clone...
fn criterion_benchmark(c: &mut Criterion) { let mut c = c.benchmark_group("scoped/subscriber"); c.bench_function("span_no_fields", |b| { tracing::subscriber::with_default(EnabledSubscriber, || { b.iter(|| span!(Level::TRACE, "span")) }); }); c.bench_function("enter_span", |b...
function_block-full_function
[ { "content": "fn bench_thrpt(c: &mut Criterion, name: &'static str, mut f: impl FnMut(&mut Group<'_>, &usize)) {\n\n const N_SPANS: &[usize] = &[1, 10, 50];\n\n\n\n let mut group = c.benchmark_group(name);\n\n for spans in N_SPANS {\n\n group.throughput(Throughput::Elements(*spans as u64));\n\n ...
Rust
qt_ritual/src/bin/cluster_worker.rs
StephanvanSchaik/ritual
51b38cab65e4dd453a7da920a3bc00da749a8931
use flexi_logger::{LogSpecification, Logger}; use itertools::Itertools; use log::LevelFilter; use log::{info, warn}; use qt_ritual::lib_configs::{create_config, MOQT_INSTALL_DIR_ENV_VAR_NAME}; use qt_ritual_common::all_crate_names; use ritual::cluster_api::{Client, GroupKey, TaskOutput}; use ritual::config::CrateProper...
use flexi_logger::{LogSpecification, Logger}; use itertools::Itertools; use log::LevelFilter; use log::{info, warn}; use qt_ritual::lib_configs::{create_config, MOQT_INSTALL_DIR_ENV_VAR_NAME}; use qt_ritual_common::all_crate_names; use ritual::cluster_api::{Client, GroupKey, TaskOutput}; use ritual::config::CrateProper...
fn main() { run().fancy_unwrap(); }
fn run() -> Result<()> { Logger::with(LogSpecification::default(LevelFilter::Info).build()) .start() .unwrap_or_else(|e| panic!("Logger initialization failed: {}", e)); let temp_dir = TempDir::new("qt_ritual_cluster_worker")?; let moqt_present = env::var(MOQT_INSTALL_DIR_ENV_VAR_NAME).is_ok...
function_block-full_function
[ { "content": "/// A wrapper over `OsStr::to_str` with better error reporting\n\npub fn os_str_to_str(os_str: &OsStr) -> Result<&str> {\n\n os_str.to_str().ok_or_else(|| {\n\n err_msg(format!(\n\n \"String is not valid unicode: {}\",\n\n os_str.to_string_lossy()\n\n ))\n\n ...
Rust
language/tools/move-coverage/src/bin/coverage-summaries.rs
lxfind/move
2e7c37edada44436805e047dd26724a26c07635a
#![forbid(unsafe_code)] use clap::Parser; use move_binary_format::file_format::CompiledModule; use move_coverage::{ coverage_map::{CoverageMap, TraceMap}, format_csv_summary, format_human_summary, summary, }; use std::{ fs::{self, File}, io::{self, Write}, path::Path, }; #[derive(Debug, Parser)]...
#![forbid(unsafe_code)] use clap::Parser; use move_binary_format::file_format::CompiledModule; use move_coverage::{ coverage_map::{CoverageMap, TraceMap}, format_csv_summary, format_human_summary, summary, }; use std::{ fs::{self, File}, io::{self, Write}, path::Path, }; #[derive(Debug, Parser)]...
s, &unified_exec_map, summary::summarize_inst_cov, &mut summary_writer, ) } } }
function_block-function_prefixed
[ { "content": "pub fn output_map_to_file<M: Serialize, P: AsRef<Path>>(file_name: P, data: &M) -> Result<()> {\n\n let bytes = bcs::to_bytes(data)?;\n\n let mut file = File::create(file_name)?;\n\n file.write_all(&bytes)?;\n\n Ok(())\n\n}\n", "file_path": "language/tools/move-coverage/src/coverag...
Rust
host/src/kernel/mod.rs
virtuehive/traychain
8e3d869ec9354b7787452baf4fcb7d6f0a06d824
use std::convert::{TryFrom, TryInto}; use std::fmt; use std::pin::Pin; use futures::future::Future; use log::debug; use safecast::*; use tc_error::*; use tc_value::{Link, Value}; use tcgeneric::*; use crate::cluster::Cluster; use crate::object::{InstanceClass, InstanceExt}; use crate::route::{Public, Static}; use c...
use std::convert::{TryFrom, TryInto}; use std::fmt; use std::pin::Pin; use futures::future::Future; use log::debug; use safecast::*; use tc_error::*; use tc_value::{Link, Value}; use tcgeneric::*; use crate::cluster::Cluster; use crate::object::{InstanceClass, InstanceExt}; use crate::route::{Public, Static}; use c...
} impl fmt::Display for Kernel { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("host kernel") } } fn execute< 'a, R: Send, Fut: Future<Output = TCResult<R>> + Send, F: FnOnce(Txn, &'a InstanceExt<Cluster>) -> Fut + Send + 'a, >( txn: Txn, cluster: &'a Inst...
osted.get(path) { if suffix.is_empty() && key.is_none() { return cluster.delete(&txn, suffix, key).await; } debug!( "DELETE {}: {} from cluster {}", TCPath::from(suffix), key, cluster ...
function_block-function_prefixed
[]
Rust
src/pty/tokio.rs
IamTheCarl/pty-process
7bf8c35dfa835e70ad760aeaf9ce9c296b9f5f29
use crate::error::*; use std::io::{Read as _, Write as _}; use std::os::unix::io::{AsRawFd as _, FromRawFd as _}; pub struct Pty { pt: tokio::io::unix::AsyncFd<std::fs::File>, ptsname: std::path::PathBuf, } impl std::ops::Deref for Pty { type Target = tokio::io::unix::AsyncFd<std::fs::File>; fn dere...
use crate::error::*; use std::io::{Read as _, Write as _}; use std::os::unix::io::{AsRawFd as _, FromRawFd as _}; pub struct Pty { pt: tokio::io::unix::AsyncFd<std::fs::File>, ptsname: std::path::PathBuf, } impl std::ops::Deref for Pty { type Target = tokio::io::unix::AsyncFd<std::fs::File>; fn dere...
fn pt(&self) -> &Self::Pt { &self.pt } fn pt_mut(&mut self) -> &mut Self::Pt { &mut self.pt } fn pts(&self) -> Result<std::fs::File> { let fh = std::fs::OpenOptions::new() .read(true) .write(true) .open(&self.ptsname) .map_e...
let pt = unsafe { std::fs::File::from_raw_fd(pt_fd) }; let pt = tokio::io::unix::AsyncFd::new(pt).map_err(Error::AsyncPty)?; Ok(Self { pt, ptsname }) }
function_block-function_prefix_line
[ { "content": "pub trait Pty: ::std::ops::Deref + ::std::ops::DerefMut {\n\n type Pt;\n\n\n\n fn new() -> Result<Self>\n\n where\n\n Self: Sized;\n\n fn pt(&self) -> &Self::Pt;\n\n fn pt_mut(&mut self) -> &mut Self::Pt;\n\n fn pts(&self) -> Result<::std::fs::File>;\n\n fn resize(&self...
Rust
src/librustc/ty/print/obsolete.rs
MOZGIII/rust
e3976fff44e6ce14c2f92252e6a807800b9aa7c0
use rustc::hir::def_id::DefId; use rustc::mir::interpret::ConstValue; use rustc::ty::subst::SubstsRef; use rustc::ty::{self, ClosureSubsts, Const, GeneratorSubsts, Instance, Ty, TyCtxt}; use rustc::{bug, hir}; use std::fmt::Write; use std::iter; use syntax::ast; pub struct DefPathBasedNames<'tcx> { tcx: TyCtxt<'...
use rustc::hir::def_id::DefId; use rustc::mir::interpret::ConstValue; use rustc::ty::subst::SubstsRef; use rustc::ty::{self, ClosureSubsts, Const, GeneratorSubsts, Instance, Ty, TyCtxt}; use rustc::{bug, hir}; use std::fmt::Write; use std::iter; use syntax::ast; pub struct DefPathBasedNames<'tcx> { tcx: TyCtxt<'...
pub fn push_def_path(&self, def_id: DefId, output: &mut String) { let def_path = self.tcx.def_path(def_id); if !(self.omit_local_crate_name && def_id.is_local()) { output.push_str(&self.tcx.crate_name(def_path.krate).as_str()); output.push_str("::"); } ...
ConstValue::Scalar(..) | ConstValue::Slice { .. } | ConstValue::ByRef { .. } => { write!(output, "{:?}", c).unwrap() } _ => { if debug { write!(output, "{:?}", c).unwrap() } else { bug!( ...
function_block-function_prefix_line
[]
Rust
base_layer/p2p/src/services/liveness/mock.rs
TruszczynskiA/tari
4e592de56df04a8e224dd9bbf9fbe4fc6d56fed1
use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, RwLock, }; use futures::StreamExt; use log::*; use tari_crypto::tari_utilities::{acquire_read_lock, acquire_write_lock}; use tari_service_framework::{reply_channel, reply_channel::RequestContext}; use tokio::sync::{broadcast, broadcast::error::SendEr...
use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, RwLock, }; use futures::StreamExt; use log::*; use tari_crypto::tari_utilities::{acquire_read_lock, acquire_write_lock}; use tari_service_framework::{reply_channel, reply_channel::RequestContext}; use tokio::sync::{broadcast, broadcast::error::SendEr...
one))).unwrap(); }, GetNetworkAvgLatency => { reply.send(Ok(LivenessResponse::AvgLatency(None))).unwrap(); }, SetMetadataEntry(_, _) => { reply.send(Ok(LivenessResponse::Ok)).unwrap(); }, AddMonitoredPeer(_) => { ...
rain(..).collect() } pub fn call_count(&self) -> usize { self.call_count.load(Ordering::SeqCst) } } pub struct LivenessMock { receiver: reply_channel::TryReceiver<LivenessRequest, LivenessResponse, LivenessError>, mock_state: LivenessMockState, } impl LivenessMock { pub fn new( ...
random
[ { "content": "pub fn log_event_name(container_name: &str) -> String {\n\n format!(\"tari://docker_log_{}\", container_name)\n\n}\n\n\n", "file_path": "applications/launchpad/backend/src/commands/service.rs", "rank": 0, "score": 353404.5880692878 }, { "content": "pub fn key_value(line: &st...
Rust
src/main.rs
arkedge/hubhook
8da98f0bb3b4d1f180106f9b7717cf0e073a275f
use std::pin::Pin; use std::sync::Arc; use structopt::StructOpt; use serde::Deserialize; use regex::RegexBuilder; use actix_web::error::ErrorBadRequest; use actix_web::{web, App, Error, FromRequest, HttpRequest, HttpResponse, HttpServer, Result}; use futures::future::{Future, FutureExt}; use futures::stream::{Stre...
use std::pin::Pin; use std::sync::Arc; use structopt::StructOpt; use serde::Deserialize; use regex::RegexBuilder; use actix_web::error::ErrorBadRequest; use actix_web::{web, App, Error, FromRequest, HttpRequest, HttpResponse, HttpServer, Result}; use futures::future::{Future, FutureExt}; use futures::stream::{Stre...
mpl(query.unwrap(), payload)) } fn match_query_vec<T>(query: Option<&String>, payload: Vec<T>) -> Option<bool> where T: ToString, { query?; let query = query.unwrap(); for p in payload { if Rule::match_query_impl(query, &p.to_string()) { ret...
ub-signature-256").unwrap(); let sig = String::from_utf8(sig.as_bytes().to_vec()).unwrap(); let sig = sig.strip_prefix("sha256=").unwrap(); hex::decode(sig).unwrap() }; let req = req.clone(); let pd = payload.take(); async move { let opt =...
random
[ { "content": "fn users2str(assignees: &[github::common::User], delimiter: &str, to_link: bool) -> Option<String> {\n\n if assignees.is_empty() {\n\n return None;\n\n }\n\n\n\n Some(\n\n assignees\n\n .iter()\n\n .map(|a| a.login.to_string())\n\n .map(|a| {...
Rust
src/libstd/at_vec.rs
novalis/rust
c684df103e05a15d4e0403b5fca1197f16d15703
use clone::Clone; use container::Container; use iterator::Iterator; use option::{Option, Some, None}; use sys; use unstable::raw::Repr; use vec::{ImmutableVector, OwnedVector}; #[inline] pub fn capacity<T>(v: @[T]) -> uint { unsafe { let box = v.repr(); (*box).data.alloc / sys::size_of::<T>() ...
use clone::Clone; use container::Container; use iterator::Iterator; use option::{Option, Some, None}; use sys; use unstable::raw::Repr; use vec::{ImmutableVector, OwnedVector}; #[inline] pub fn capacity<T>(v: @[T]) -> uint { unsafe { let box = v.repr(); (*box).data.alloc / sys::size_of::<T>() ...
the vector. * * # Arguments * * * size - An option, maybe containing initial size of the vector to reserve * * builder - A function that will construct the vector. It receives * as an argument a function that will push an element * onto the vector being constructed. */ #[inline] pub fn ...
vector to reserve * * builder - A function that will construct the vector. It receives * as an argument a function that will push an element * onto the vector being constructed. */ #[inline] pub fn build_sized<A>(size: uint, builder: &fn(push: &fn(v: A))) -> @[A] { let mut vec = @[]; ...
random
[ { "content": "#[inline]\n\npub fn build_sized<A>(size: uint, builder: &fn(push: &fn(v: A))) -> ~[A] {\n\n let mut vec = with_capacity(size);\n\n builder(|x| vec.push(x));\n\n vec\n\n}\n\n\n\n/**\n\n * Builds a vector by calling a provided function with an argument\n\n * function that pushes an element ...
Rust
app/gui/controller/double-representation/src/tp.rs
luna/luna
a1bf0974ceec6e1a47f371956598f81d18596e88
use crate::prelude::*; use crate::identifier::ReferentName; use crate::module; use crate::project; use serde::Deserialize; use serde::Serialize; #[allow(missing_docs)] #[derive(Clone, Debug, Fail)] pub enum InvalidQualifiedName { #[fail(display = "The qualified name is empty.")] EmptyName { source: String ...
use crate::prelude::*; use crate::identifier::ReferentName; use crate::module; use crate::project; use serde::Deserialize; use serde::Serialize; #[allow(missing_docs)] #[derive(Clone, Debug, Fail)] pub enum InvalidQualifiedName { #[fail(display = "The qualified name is empty.")] EmptyName { source: String ...
} impl<'a> IntoIterator for &'a QualifiedName { type Item = &'a str; type IntoIter = impl Iterator<Item = &'a str>; fn into_iter(self) -> Self::IntoIter { self.segments() } } impl Display for QualifiedName { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let text = Str...
fn from(name: &QualifiedName) -> Self { let project_name = name.project_name.segments(); let segments = name.module_segments.iter().map(AsRef::<str>::as_ref); let name = std::iter::once(name.name.as_ref()); project_name.chain(segments).chain(name).join(".") }
function_block-full_function
[ { "content": "/// Fast-check if the pattern matches text.\n\n///\n\n/// This is faster way than calling `score_match(text,pattern,metric).is_some()`, therefore it's\n\n/// recommended to call this function before scoring when we are not sure if the pattern actually\n\n/// matches the text.\n\npub fn matches(tex...
Rust
testsuite/smoke-test/src/state_sync.rs
watssec/diem
d386dccba440966a5fa11d71aa1616deac9b5a5e
use crate::{ scripts_and_modules::{compile_program, enable_open_publishing}, smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, }; use diem_types::{ account_address::AccountAddress, epoch...
use crate::{ scripts_and_modules::{compile_program, enable_open_publishing}, smoke_test_environment::new_local_swarm, test_utils::{ assert_balance, create_and_fund_account, diem_swarm_utils::insert_waypoint, transfer_coins, }, }; use diem_types::{ account_address::AccountAddress, epoch...
#[test] fn test_startup_sync_state() { let mut swarm = new_local_swarm(4); let validator_peer_ids = swarm.validators().map(|v| v.peer_id()).collect::<Vec<_>>(); let client_1 = swarm .validator(validator_peer_ids[1]) .unwrap() .json_rpc_client(); let transaction_factory = swarm....
l_healthy(Instant::now() + Duration::from_secs(10)) .unwrap(); swarm .wait_for_all_nodes_to_catchup(Instant::now() + Duration::from_secs(60)) .unwrap(); let client_0 = swarm.validator(node_to_restart).unwrap().json_rpc_client(); assert_balance(&client_0, &account_0, 89); as...
function_block-function_prefixed
[]
Rust
generate_reflection/src/defaults_place.rs
rojo-rbx-original-copyright/rbx-dom
43d1134a3ac21677509e87a19120b52c607db638
use std::{ borrow::Cow, collections::{HashSet, VecDeque}, convert::TryInto, error::Error, fmt::{self, Write}, fs::{self, File}, io::BufReader, process::Command, sync::mpsc, time::Duration, }; use notify::{DebouncedEvent, Watcher}; use rbx_dom_weak::{RbxTree, RbxValueType}; use...
use std::{ borrow::Cow, collections::{HashSet, VecDeque}, convert::TryInto, error::Error, fmt::{self, Write}, fs::{self, File}, io::BufReader, process::Command, sync::mpsc, time::Duration, }; use notify::{DebouncedEvent, Watcher}; use rbx_dom_weak::{RbxTree, RbxValueType}; use...
struct FixtureInstance<'a> { name: &'a str, children: Vec<FixtureInstance<'a>>, } impl<'a> FixtureInstance<'a> { fn named(name: &'a str) -> Self { Self { name, children: Vec::new(), } } fn add_child(&mut self, child: FixtureInstance<'a>) { self.chi...
fn generate_fixture_place(database: &ReflectionDatabase) -> String { log::info!("Generating place with every instance..."); let mut output = String::new(); writeln!(&mut output, "<roblox version=\"4\">").unwrap(); for descriptor in database.0.classes.values() { let mut instance = FixtureInsta...
function_block-full_function
[ { "content": "/// Decodes an XML-format model or place from a string using the default decoder\n\n/// options.\n\npub fn from_str_default<S: AsRef<str>>(reader: S) -> Result<WeakDom, DecodeError> {\n\n decode_internal(reader.as_ref().as_bytes(), DecodeOptions::default())\n\n}\n\n\n", "file_path": "rbx_xm...
Rust
src/thread_key.rs
cmnord/swym
f7b635dfefa08b5aa8cfea739899b339fdca68ec
use crate::{ internal::{phoenix_tls::Phoenix, thread::Thread}, read::ReadTx, rw::RwTx, tx::{Error, Status}, }; use core::fmt::{self, Debug, Formatter}; #[derive(Clone)] pub struct ThreadKey { thread: Phoenix<Thread>, } impl Debug for ThreadKey { fn fmt(&self, formatter: &mut Formatter<'_>) -...
use crate::{ internal::{phoenix_tls::Phoenix, thread::Thread}, read::ReadTx, rw::RwTx, tx::{Error, Status}, }; use core::fmt::{self, Debug, Formatter}; #[derive(Clone)] pub struct ThreadKey { thread: Phoenix<Thread>, } impl Debug for ThreadKey { fn fmt(&self, formatter: &mut Formatter<'_>) -...
inline] pub fn try_rw<'tcell, F, O>(&'tcell self, f: F) -> Result<O, TryRwErr> where F: FnMut(&mut RwTx<'tcell>) -> Result<O, Status>, { Ok(self .thread .try_pin() .ok_or_else(|| TryRwErr::new())? .run_rw(f)) } } mod tls { use crate::i...
#[inline] pub fn read<'tcell, F, O>(&'tcell self, f: F) -> O where F: FnMut(&ReadTx<'tcell>) -> Result<O, Error>, { self.try_read(f) .expect("nested transactions are not yet supported") } ...
random
[ { "content": "/// Returns the thread local stats object, or None if the feature is disabled.\n\npub fn thread_stats() -> Option<impl Deref<Target = ThreadStats>> {\n\n if any_stats_active() {\n\n Some(THREAD_STAT.get())\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/stats....
Rust
write_buffer/src/codec.rs
Zurlys/influxdb_iox
ca5740e1c90f54fa41046f60fcf9c22ab9d067d5
use std::borrow::Cow; use std::sync::Arc; use http::{HeaderMap, HeaderValue}; use data_types::sequence::Sequence; use entry::{Entry, SequencedEntry}; use mutable_batch::{DbWrite, WriteMeta}; use mutable_batch_entry::sequenced_entry_to_write; use mutable_batch_pb::decode::decode_database_batch; use time::Time; use t...
use std::borrow::Cow; use std::sync::Arc; use http::{HeaderMap, HeaderValue}; use data_types::sequence::Sequence; use entry::{Entry, SequencedEntry}; use mutable_batch::{DbWrite, WriteMeta}; use mutable_batch_entry::sequenced_entry_to_write; use mutable_batch_pb::decode::decode_database_batch; use time::Time; use t...
}
fn headers_no_trace_collector_on_consumer_side() { let collector: Arc<dyn TraceCollector> = Arc::new(RingBufferTraceCollector::new(5)); let span_context = SpanContext::new(Arc::clone(&collector)); let iox_headers1 = IoxHeaders::new(ContentType::Entry, Some(span_context)); let encoded:...
function_block-full_function
[ { "content": "/// Convert a [`MutableBatch`] to [`TableBatch`]\n\npub fn encode_batch(table_name: &str, batch: &MutableBatch) -> TableBatch {\n\n TableBatch {\n\n table_name: table_name.to_string(),\n\n columns: batch\n\n .columns()\n\n .map(|(column_name, column)| encode_...
Rust
src/sys/tools/cs/lib/v1.rs
billchen1977/fuchsia
d443f9c7b03ad317d1700c2c9457be8ed1147b86
use { crate::get_capabilities, crate::io::Directory, futures::future::{BoxFuture, FutureExt}, }; static SPACER: &str = " "; static UNKNOWN: &str = "UNKNOWN"; async fn open_id_directories(id_dir: Directory) -> Vec<Directory> { let mut realms = vec![]; for id in id_dir.entries().await { a...
use { crate::get_capabilities, crate::io::Directory, futures::future::{BoxFuture, FutureExt}, }; static SPACER: &str = " "; static UNKNOWN: &str = "UNKNOWN"; async fn open_id_directories(id_dir: Directory) -> Vec<Directory> { let mut realms = vec![]; for id in id_dir.entries().await { a...
pub fn print_tree_recursive(&self, level: usize) { let space = SPACER.repeat(level - 1); println!("{}{} (realm)", space, self.name); for child in &self.child_components { child.print_tree_recursive(level + 1); } for child in &self.child_realms { chil...
mponents_dir = realm_dir.open_dir("c").expect("open_dir(`c`) failed!"); V1Realm { name, job_id, child_realms: visit_child_realms(child_realms_dir).await, child_components: visit_child_components(child_components_dir).await, } }
function_block-function_prefixed
[]
Rust
src/libos/src/time/timer_file.rs
qzheng527/ngo
635ce9ef2427fe1b602b40ec89aa3530b167169d
use super::*; use crate::fs::{AccessMode, Events, IoctlCmd, Observer, Pollee, Poller, StatusFlags}; use async_rt::task::{JoinHandle, SpawnOptions}; use async_rt::{wait::WaiterQueue, waiter_loop}; use atomic::{Atomic, Ordering}; use std::sync::{Arc, SgxMutex as Mutex}; use std::time::Duration; #[allow(non_camel_case_ty...
use super::*; use crate::fs::{AccessMode, Events, IoctlCmd, Observer, Pollee, Poller, StatusFlags}; use async_rt::task::{JoinHandle, SpawnOptions}; use async_rt::{wait::WaiterQueue, waiter_loop}; use atomic::{Atomic, Ordering}; use std::sync::{Arc, SgxMutex as Mutex}; use std::time::Duration; #[allow(non_camel_case_ty...
nc fn writev(&self, bufs: &[&[u8]]) -> Result<usize> { return_errno!(EINVAL, "timer fds do not support write"); } pub fn access_mode(&self) -> AccessMode { AccessMode::O_RDONLY } pub fn status_flags(&self) -> StatusFlags { let flags = self.flags.load(Ordering::Relaxed)...
Ok(()) } } bitflags! { pub struct TimerCreationFlags: i32 { const TFD_NONBLOCK = 1 << 11; const TFD_CLOEXEC = 1 << 19; } } bitflags! { pub struct TimerSetFlags: i32 { const TFD_TIMER_ABSTIME = 1 << 0; const TFD_TIMER_CANCEL_ON_SET =...
random
[ { "content": "// TODO: rename this to do_poll after the old version is removed\n\npub fn do_poll_new(poll_fds: &[PollFd], mut timeout: Option<&mut Duration>) -> Result<usize> {\n\n debug!(\"poll: poll_fds: {:?}, timeout: {:?}\", poll_fds, timeout);\n\n\n\n // Always clear the revents fields first\n\n f...
Rust
rpc/src/server.rs
jjs-dev/commons
f53ebfa3bd973aa711f79f4d824fa297ac21b1ad
use crate::{Direction, Receive, Transmit}; use std::future::Future; use std::sync::Arc; pub trait Handler<R: crate::Route>: Clone + Send + Sync + 'static { type Error: std::fmt::Display + Send + 'static; type Fut: Future<Output = Result<(), Self::Error>> + Send + 'static; fn handle( self,...
use crate::{Direction, Receive, Transmit}; use std::future::Future; use std::sync::Arc; pub trait Handler<R: crate::Route>: Clone + Send + Sync + 'static { type Error: std::fmt::Display + Send + 'static; type Fut: Future<Output = Result<(), Self::Error>> + Send + 'static; fn handle( self,...
fn call(&mut self, _req: T) -> Self::Future { futures_util::future::ready(Ok(self.0.clone())) } }
fn poll_ready( &mut self, _cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Result<(), Self::Error>> { std::task::Poll::Ready(Ok(())) }
function_block-full_function
[ { "content": "/// Type that can produce http request.\n\npub trait Transmit: Send + 'static {\n\n type BatchError: std::error::Error + Send + Sync + 'static;\n\n type BatchData;\n\n type BatchFuture: std::future::Future<Output = Result<(), Self::BatchError>>;\n\n\n\n fn from_body_sender(send: hyper:...
Rust
ui/src/gridview/render/generic.rs
HactarCE/NDCell
ca2e5f8aae39013a50276c5e9662719fde9c2c3e
use anyhow::{Context, Result}; use glium::glutin::event::ModifiersState; use glium::index::PrimitiveType; use glium::{uniform, Surface}; use palette::{Mix, Srgb, Srgba}; use std::cell::RefMut; use ndcell_core::prelude::*; use Axis::{X, Y}; use super::consts::*; use super::shaders; use super::vertices::MouseTargetVert...
use anyhow::{Context, Result}; use glium::glutin::event::ModifiersState; use glium::index::PrimitiveType; use glium::{uniform, Surface}; use palette::{Mix, Srgb, Srgba}; use std::cell::RefMut; use ndcell_core::prelude::*; use Axis::{X, Y}; use super::consts::*; use super::shaders; use super::vertices::MouseTargetVert...
pub(super) fn clip_int_rect_to_visible(&self, cells_rect: &BigRect<R::D>) -> IRect<R::D> { NdRect::span( self.clamp_int_pos_to_visible(&cells_rect.min()), self.clamp_int_pos_to_visible(&cells_rect.max()), ) } pub(super) fn clip_ndtree_to_visible<...
pub(super) fn clamp_int_pos_to_visible(&self, global_pos: &BigVec<R::D>) -> IVec<R::D> { let padding = self.xform.render_cell_layer.big_len() * 2; let lower = self.global_visible_rect.min() - &padding; let global_pos = NdVec::max(global_pos, &lower); let upper = self.global_vis...
function_block-full_function
[ { "content": "/// Imports an automaton from a string using the first format that works,\n\n/// returning the error resulting from each attempt if none succeeded.\n\npub fn import_automaton_from_string<R: ResolveRule + Clone>(\n\n s: &str,\n\n resolve_rule: R,\n\n) -> Result<Result<Automaton, R::Err>, Vec<...
Rust
src/dbtype/write_document_response.rs
benkard/couchdb-rs
faffb797ff4f7fd58889bcd1da6901d33638481e
use serde; use DocumentId; use Revision; pub type DeleteDocumentResponse = WriteDocumentResponse; pub type PostDatabaseResponse = WriteDocumentResponse; pub type PutDocumentResponse = WriteDocumentResponse; #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] struct WriteDocumentResponse { pub id: Docum...
use serde; use DocumentId; use Revision; pub type DeleteDocumentResponse = WriteDocumentResponse; pub type PostDatabaseResponse = WriteDocumentResponse; pub type PutDocumentResponse = WriteDocumentResponse; #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] struct WriteDocumentResponse { pub id: Docum...
#[test] fn write_document_response_deserialization_with_no_id_field() { let source = serde_json::builder::ObjectBuilder::new() .insert("ok", true) .insert("rev", "1-12345678123456781234567812345678") .unwrap(); let s = ...
let source = serde_json::builder::ObjectBuilder::new() .insert("id", "foo") .insert("ok", true) .insert("rev", "1-12345678123456781234567812345678") .unwrap(); let s = serde_json::to_string(&source).unwrap(); ...
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn get_document_ok_if_none_match_stale() {\n\n let (_server, client) = make_server_and_client();\n\n client.put_database(\"/baseball\").run().unwrap();\n\n let expected_content = serde_json::builder::ObjectBuilder::new()\n\n .insert(\"name\", \"Bab...
Rust
src/bin/model_predictive_trajectory_generator.rs
rsasaki0109/RustRobotics
ac47afc29cb04f7547297ad56abaedb6427a3924
extern crate nalgebra; use plotlib::page::Page; use plotlib::repr::Plot; use plotlib::view::ContinuousView; use plotlib::style::LineStyle; fn pi2pi(mut angle: f64) -> f64 { while angle > std::f64::consts::PI { angle -= 2. * std::f64::consts::PI } while angle < -std::f64::co...
extern crate nalgebra; use plotlib::page::Page; use plotlib::repr::Plot; use plotlib::view::ContinuousView; use plotlib::style::LineStyle; fn pi2pi(mut angle: f64) -> f64 { while angle > std::f64::const
struct State { x: f64, y: f64, yaw: f64, v: f64, l: f64, } impl State { fn new(x:(f64,f64,f64,f64), l: f64)-> State{ State { x: x.0, y: x.1, yaw: x.2, v: x.3, l: l } } fn update(&mut self, v: f64, delta: f64, dt: f64) { s...
s::PI { angle -= 2. * std::f64::consts::PI } while angle < -std::f64::consts::PI { angle += 2. * std::f64::consts::PI } angle }
function_block-function_prefixed
[ { "content": "pub fn calc_spline_course(x: Vec<f64>, y: Vec<f64>, ds: f64) -> \n\n(Vec<(f64,f64)>, Vec<f64>, Vec<f64>, Vec<f64>)\n\n{\n\n let sp = Spline2D::new(x, y);\n\n let s_end = sp.s[sp.s.len()-1]; \n\n let n = (s_end / ds) as usize;\n\n let mut r: Vec<(f64,f64)> = Vec::with_capacity(n);\n\n ...
Rust
engine/ha-renderer/src/material/graph/node.rs
age-rs/Oxygengine
52094b985fa5341c1da166b93f3724362fd14307
use crate::{ material::common::{ MaterialDataPrecision, MaterialDataType, MaterialShaderType, MaterialValue, MaterialValueType, }, math::vek::*, }; use core::{id::ID, Ignite}; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; pub type MaterialGraphNodeId = ID<Ma...
use crate::{ material::common::{ MaterialDataPrecision, MaterialDataType, MaterialShaderType, MaterialValue, MaterialValueType, }, math::vek::*, }; use core::{id::ID, Ignite}; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; pub type MaterialGraphNodeId = ID<Ma...
pub fn vs_clip_distance() -> Self { Self { name: "gl_ClipDistance".to_owned(), data_type: MaterialDataType::BuiltIn, value_type: MaterialValueType::Array(Box::new(MaterialValueType::Scalar), None), shader_type: MaterialShaderType::Vertex, input_c...
pub fn vs_point_size() -> Self { Self { name: "gl_PointSize".to_owned(), data_type: MaterialDataType::BuiltIn, value_type: MaterialValueType::Scalar, shader_type: MaterialShaderType::Vertex, input_connection: None, } }
function_block-full_function
[ { "content": "fn is_false(value: &bool) -> bool {\n\n !value\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct IgniteTypeDefinition {\n\n #[serde(default, skip_serializing_if = \"String::is_empty\")]\n\n pub namespace: String,\n\n #[serde(default, skip_serializing_if = \"Vec::is_emp...
Rust
rust/bin.rs
wudi/pngquant
7ffdc41525d80461d1f581644fbf9df135140c67
/* ** © 2019 by Kornel Lesiński. ** ** See COPYRIGHT file for license. */ #[cfg(feature = "openmp")] extern crate openmp_sys; extern crate imagequant_sys; extern crate libpng_sys; #[cfg(feature = "cocoa")] pub mod rwpng_cocoa; #[cfg(feature = "lcms2")] extern crate lcms2_sys; use imagequant_sys::liq_error::LIQ_OK;...
/* ** © 2019 by Kornel Lesiński. ** ** See COPYRIGHT file for license. */ #[cfg(feature = "openmp")] extern crate openmp_sys; extern crate imagequant_sys; extern c
opts.optflag("", "ordered", ""); opts.optflag("", "nofs", ""); opts.optflag("", "iebug", ""); opts.optflag("", "transbug", ""); opts.optflag("", "skip-if-larger", ""); opts.optflag("", "strip", ""); opts.optflag("V", "version", ""); opts.optflagopt("", "floyd", "0.0-1.0", ""); opts.o...
rate libpng_sys; #[cfg(feature = "cocoa")] pub mod rwpng_cocoa; #[cfg(feature = "lcms2")] extern crate lcms2_sys; use imagequant_sys::liq_error::LIQ_OK; use imagequant_sys::*; use libc::FILE; use crate::ffi::PNGQUANT_VERSION; use crate::ffi::pngquant_internal_print_config; use std::os::raw::{c_uint, c_char, c_void};...
random
[ { "content": "static bool replace_file(const char *from, const char *to, const bool force) {\n\n#if defined(_WIN32) || defined(WIN32) || defined(__WIN32__)\n\n if (force) {\n\n // On Windows rename doesn't replace\n\n unlink(to);\n\n }\n\n#endif\n\n return (0 == rename(from, to));\n", ...
Rust
benches/benchndarray.rs
djallen89/gremlin
ea252257b5b3bba4d27921cf6d5550a8188f2b1e
#[macro_use] extern crate criterion; use gremlin_lib; use gremlin_lib::{random_array, matrix_madd}; use ndarray::Array; use ndarray::linalg::general_mat_mul; use criterion::{Benchmark, Criterion}; fn bench_n_sq(crit: &mut Criterion, n: usize) { let my_name = format!("{:04}sq", n); let a: Vec<f64> = random_a...
#[macro_use] extern crate criterion; use gremlin_lib; use gremlin_lib::{random_array, matrix_madd}; use ndarray::Array; use ndarray::linalg::general_mat_mul; use criterion::{Benchmark, Criterion}; fn bench_n_sq(crit: &mut Criterion, n: usize) { let my_name = format!("{:04}sq", n); let a: Vec<f64> = random_a...
fn bench_nmp(n: usize, m: usize, p: usize, crit: &mut Criterion) { let my_name = format!("my dgemm {}x{}x{}", n, m, p); let other_name = format!("ndarray {}x{}x{}", n, m, p); let a: Vec<f64> = random_array(n, m, -100.0, 100.0); let b = random_array(m, p, -100.0, 100.0); let mut c = random_ar...
let bench_def; bench_def = Benchmark::new( my_name, move |bch| bch.iter(|| { general_mat_mul(1.0, &aarr, &barr, 1.0, &mut carr) })) .sample_size(10); crit.bench("final_dgemm_ndarray", bench_def); }
function_block-function_prefix_line
[ { "content": "fn bench_n_sq(crit: &mut Criterion, n: usize) {\n\n let my_name = format!(\"{:04}sq\", n);\n\n //let other_name = format!(\"ndarray {}sq\", n);\n\n \n\n let a: Vec<f64> = random_array(n, n, -10000.0, 10000.0);\n\n let b = random_array(n, n, -10000.0, 10000.0);\n\n let mut c = ran...
Rust
actix-server/src/builder.rs
shuoli84/actix-net
7c536449c2355eaf2da5cf428e26786005c28e11
use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; use std::{io, mem}; use actix_rt::net::TcpStream; use actix_rt::time::{sleep_until, Instant}; use actix_rt::{self as rt, System}; use log::{error, info}; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver}; u...
use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; use std::{io, mem}; use actix_rt::net::TcpStream; use actix_rt::time::{sleep_until, Instant}; use actix_rt::{self as rt, System}; use log::{error, info}; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver}; u...
self.threads = cfg.threads; Ok(self) } pub fn bind<F, U, N: AsRef<str>>(mut self, name: N, addr: U, factory: F) -> io::Result<Self> where F: ServiceFactory<TcpStream>, U: ToSocketAddrs, { let sockets = bind_addr(addr, self.backlog)?; for lst in so...
if let Some(apply) = cfg.apply { let mut srv = ConfiguredService::new(apply); for (name, lst) in cfg.services { let token = self.token.next(); srv.stream(token, name.clone(), lst.local_addr()?); self.sockets.push((token, name, MioListener::Tcp(lst)...
if_condition
[ { "content": "/// Sets the maximum per-worker number of concurrent connections.\n\n///\n\n/// All socket listeners will stop accepting connections when this limit is\n\n/// reached for each worker.\n\n///\n\n/// By default max connections is set to a 25k per worker.\n\npub fn max_concurrent_connections(num: usi...
Rust
src/reader.rs
alecorsino/lopdf
0a8fbc25e6b80104287fcb25b20e3d71544414a7
use log::error; use std::cmp; use std::fs::File; use std::io::{Error, ErrorKind, Read, Result}; use std::path::Path; use super::parser; use super::{Document, Object, ObjectId}; use crate::object_stream::ObjectStream; use crate::xref::XrefEntry; impl Document { #[inline] pub fn load<P: AsRef<Path>>(path: P) -> Res...
use log::error; use std::cmp; use std::fs::File; use std::io::{Error, ErrorKind, Read, Result}; use std::path::Path; use super::parser; use super::{Document, Object, ObjectId}; use crate::object_stream::ObjectStream; use crate::xref::XrefEntry; impl Document { #[inline] pub fn load<P: AsRef<Path>>(path: P) -> Res...
r[seek_pos] == pattern[index] { index += 1; } else if index > 0 { seek_pos -= index; index = 0; } seek_pos += 1; if index == pattern.len() { return Some(seek_pos - index); } } None } } #[test] fn load_document() { let mut doc = Document::load("assets/example.pdf").unwrap(); asse...
y(file.metadata()?.len() as usize); Self::load_internal(file, buffer) } #[inline] pub fn load_from<R: Read>(source: R) -> Result<Document> { let buffer = Vec::<u8>::new(); Self::load_internal(source, buffer) } fn load_internal<R: Read>(mut source: R, mut buffer: Vec<u8>) -> Result<Document> { source.re...
random
[]
Rust
pyrite-gba/src/sysctl.rs
ExPixel/Pyrite
bc19393ab750210e79769cdb4636a059405ad4be
use pyrite_common::{bits, bits_b}; macro_rules! set_timings { ($Width:ident, $Region:expr, 1, $FirstAccess:expr, $SecondAccess:expr) => { $Region.$Width = AccessCycles { nonsequential: 1 + $FirstAccess, sequential: 1 + $SecondAccess, }; }; ($Width:ident, $Region:exp...
use pyrite_common::{bits, bits_b}; macro_rules! set_timings { ($Width:ident, $Region:expr, 1, $FirstAccess:expr, $SecondAccess:expr) => { $Region.$Width = AccessCycles { nonsequential: 1 + $FirstAccess, sequential: 1 + $SecondAccess, }; }; ($Width:ident, $Region:exp...
pub fn set_imemctl_lo(&mut self, lo: u16) { let value = (self.reg_imemctl & 0xFFFF0000) | (lo as u32); self.set_imemctl(value); } pub fn set_imemctl_hi(&mut self, hi: u16) { let value = (self.reg_imemctl & 0x0000FFFF) | ((hi as u32) << 16); self.set_imemctl(value); } ...
ram_disabled: false, ram_external: true, reg_waitcnt: 0, reg_postflg: false, reg_imemctl: 0, } }
function_block-function_prefixed
[ { "content": "pub fn bools() -> impl Iterator<Item = bool> {\n\n [true, false].into_iter()\n\n}\n\n\n", "file_path": "crates/arm-emulator/tests/common/operands.rs", "rank": 0, "score": 252746.00910376554 }, { "content": "pub fn disasm(instr: u16, address: u32) -> ThumbInstr {\n\n let o...
Rust
src/materialized/src/http.rs
andrioni/materialize
c7997975a787f428b97d912e2e18836adb27e5cc
use std::pin::Pin; use std::time::Instant; use futures::future::{FutureExt, TryFutureExt}; use hyper::{service, Method, StatusCode}; use hyper_openssl::MaybeHttpsStream; use openssl::nid::Nid; use openssl::ssl::{Ssl, SslContext}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_openssl::SslStream; use ore::netio::...
use std::pin::Pin; use std::time::Instant; use futures::future::{FutureExt, TryFutureExt}; use hyper::{service, Method, StatusCode}; use hyper_openssl::MaybeHttpsStream; use openssl::nid::Nid; use openssl::ssl::{Ssl, SslContext}; use tokio::io::{AsyncRead, AsyncWrite}; use tokio_openssl::SslStream; use ore::netio::...
match (req.method(), req.uri().path()) { (&Method::GET, "/") => self.handle_home(req).boxed(), (&Method::GET, "/metrics") => self.handle_prometheus(req).boxed(), (&Method::GET, "/status") => s...
let user = match user { Ok(ref user) => user, Err(e) => { return async move { Ok(util::error_response(StatusCode::UNAUTHORIZED, e)) } .boxed() } };
assignment_statement
[ { "content": "// From postgres-types/src/private.rs.\n\nfn read_be_i32(buf: &mut &[u8]) -> Result<i32, Box<dyn Error + Sync + Send>> {\n\n if buf.len() < 4 {\n\n return Err(\"invalid buffer size\".into());\n\n }\n\n let mut bytes = [0; 4];\n\n bytes.copy_from_slice(&buf[..4]);\n\n *buf = &...
Rust
proc-macro/src/struct_impl.rs
aticu/pre
cb094121893fb1f7412ecfeb4b28fda84ce10f69
use proc_macro2::{Span, TokenStream}; use proc_macro_error::emit_error; use quote::{format_ident, quote, quote_spanned, TokenStreamExt}; use syn::{parse2, spanned::Spanned, Ident, ItemFn, PathArguments}; use crate::{ call::Call, helpers::{add_span_to_signature, combine_cfg}, precondition::{CfgPreconditio...
use proc_macro2::{Span, TokenStream}; use proc_macro_error::emit_error; use quote::{format_ident, quote, quote_spanned, TokenStreamExt}; use syn::{parse2, spanned::Spanned, Ident, ItemFn, PathArguments}; use crate::{ call::Call, helpers::{add_span_to_signature, combine_cfg}, precondition::{CfgPreconditio...
= function.sig.ident.clone(); let struct_def = quote_spanned! { span=> #[allow(non_camel_case_types)] #[allow(non_snake_case)] #[cfg(all(not(doc), #combined_cfg))] #vis struct #function_name { #preconditions_rendered } }; add_span_to_signature(s...
"__".to_string(), other => format!("_{:x}", other as u32), }) .collect() } let mut ident = match precondition.precondition() { Precondition::ValidPtr { ident, read_write, .. } => format_ident!( "_valid_ptr_{}_{}", iden...
random
[ { "content": "/// Parses an identifier that is valid for use in a precondition.\n\nfn parse_precondition_ident(input: ParseStream) -> syn::Result<Ident> {\n\n let lookahead = input.lookahead1();\n\n\n\n if lookahead.peek(Token![self]) {\n\n input.call(Ident::parse_any)\n\n } else if lookahead.pe...
Rust
datom/src/types/connection.rs
LutrisEng/datom-rs
dafe8c36ad75e4dd59531b15820717bd8d9293b6
use std::fmt::Debug; use chrono::Utc; use crate::{ builtin_idents, serial::{ deserialize_tr, serialize_aevt, serialize_avet, serialize_eavt, serialize_tr, serialize_vaet, tr_range, vec_range_slice, }, storage::Storage, ConnectionError, Database, Datom, EntityResult, Index, Transa...
use std::fmt::Debug; use chrono::Utc; use crate::{ builtin_idents, serial::{ deserialize_tr, serialize_aevt, serialize_avet, serialize_eavt, serialize_tr, serialize_vaet, tr_range, vec_range_slice, }, storage::Storage, ConnectionError, Database, Datom, EntityResult, Index, Transa...
&items).map_err(ConnectionError::from)?; Ok(TransactionResult { connection: self, before, after: self.as_of(t)?, data, }) } pub fn transact<T: Transactable>( &self, txable: T, ) -> Result<TransactionResult<'_, S>, Transact...
ion<S> {} pub type DynamicConnection = Connection<Box<dyn Storage>>; pub fn new_dynamic_connection<S: Storage + 'static>(storage: S) -> DynamicConnection { Connection::new(Box::new(storage)) } impl<S: Storage> Connection<S> { pub fn new(storage: S) -> Self { Self { storage, ...
random
[ { "content": "/// Serialize a [datom](crate::Datom) for a given [index](crate::Index)\n\npub fn serialize(datom: &Datom, index: Index) -> Vec<u8> {\n\n match index {\n\n Index::EAVT => serialize_eavt(datom),\n\n Index::AEVT => serialize_aevt(datom),\n\n Index::AVET => serialize_avet(dato...
Rust
src/aoc2020/day4.rs
Gussi/aoc2020-rust
1089db670aad4e2ff8055f497444d51fd3a3e36b
use std::io::Read; use regex::Regex; struct Passport { byr: Option<String>, iyr: Option<String>, eyr: Option<String>, hgt: Option<String>, hcl: Option<String>, ecl: Option<String>, pid: Option<String>, cid: Option<String>, } impl Passport { pub fn new() -> Self { P...
use std::io::Read; use regex::Regex; struct Passport { byr: Option<String>, iyr: Option<String>, eyr: Option<String>, hgt: Option<String>, hcl: Option<String>, ecl: Option<String>, pid: Option<String>, cid: Option<String>, } impl Passport { pub fn new() -> Self { P...
lter(|attrs| !attrs.is_empty()) .collect(); for attributes in passport_attributes { passports.push(Passport::from_attributes(attributes)); } break; } Ok(passports) }
function_block-function_prefixed
[ { "content": "pub fn part2() -> Result<usize, &'static str> {\n\n let world = input().unwrap();\n\n\n\n Ok([\n\n world.trees_on_slope(1, 1),\n\n world.trees_on_slope(3, 1),\n\n world.trees_on_slope(5, 1),\n\n world.trees_on_slope(7, 1),\n\n world.trees_on_slope(1, 2),\n\...
Rust
memflow/src/iter/mod.rs
Qemu-Gang/memflow
63affbb9eedf56a26b81ea60b10439b517eeb131
/*! Special purpose iterators for memflow. */ mod page_chunks; use crate::types::Address; pub use page_chunks::*; mod double_buffered_iterator; use double_buffered_iterator::*; mod doublepeek; pub use doublepeek::*; mod void; pub use void::FnExtend; pub trait FlowIters: Iterator { ...
/*! Special purpose iterators for memflow. */ mod page_chunks; use crate::types::Address; pub use page_chunks::*; mod double_buffered_iterator; use double_buffered_iterator::*; mod doublepeek; pub use doublepeek::*; mod void; pub use void::FnExtend; pub trait FlowIters: Iterator { ...
fn page_chunks_by<F: FnMut(Address, &Self, Option<&Self>) -> bool>( self, ...
where Self: SplitAtIndex + Sized, { PageChunkIterator::new(self, start_address, page_size, |_, _, _| true) }
function_block-function_prefix_line
[ { "content": "pub fn try_get_pe_size<T: VirtualMemory>(virt_mem: &mut T, probe_addr: Address) -> Result<usize> {\n\n let mut probe_buf = vec![0; size::kb(4)];\n\n virt_mem.virt_read_raw_into(probe_addr, &mut probe_buf)?;\n\n\n\n let pe_probe = PeView::from_bytes(&probe_buf).map_err(Error::PE)?;\n\n\n\n...
Rust
packages/tui/src/render.rs
DioxusLabs/dioxus
d9e14db434ee78465725d3ac24a455413f3fa963
use dioxus_native_core::layout_attributes::UnitSystem; use std::io::Stdout; use taffy::{ geometry::Point, prelude::{Layout, Size}, Taffy, }; use tui::{backend::CrosstermBackend, layout::Rect}; use crate::{ style::{RinkColor, RinkStyle}, style_attributes::{BorderEdge, BorderStyle}, widget::{Rink...
use dioxus_native_core::layout_attributes::UnitSystem; use std::io::Stdout; use taffy::{ geometry::Point, prelude::{Layout, Size}, Taffy, }; use tui::{backend::CrosstermBackend, layout::Rect}; use crate::{ style::{RinkColor, RinkStyle}, style_attributes::{BorderEdge, BorderStyle}, widget::{Rink...
fn get_radius(border: &BorderEdge, area: Rect) -> f32 { match border.style { BorderStyle::Hidden => 0.0, BorderStyle::None => 0.0, _ => match border.radius { UnitSystem::Percent(p) => p * area.width as f32 / 100.0, ...
fn draw_arc( pos: [u16; 2], starting_angle: f32, arc_angle: f32, radius: f32, symbols: &Set, buf: &mut RinkBuffer, color: &Option<RinkColor>, ) { if radius < 0.0 { return; } l...
function_block-full_function
[ { "content": "/// applies the entire html namespace defined in dioxus-html\n\npub fn apply_layout_attributes(name: &str, value: &str, style: &mut Style) {\n\n match name {\n\n \"align-content\"\n\n | \"align-items\"\n\n | \"align-self\" => apply_align(name, value, style),\n\n\n\n ...
Rust
src/bw/mod.rs
neivv/mtl
c2f5e5373483f238d076b2b016585eb2284a1d08
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] use std::ptr::null_mut; use std::slice; use std::sync::atomic::{AtomicUsize, Ordering}; use libc::c_void; use crate::samase; use bw_dat::{DatTable, UnitArray, UnitId, OrderId}; pub use bw_dat::structs::*; #[repr(C)] pub struct CampaignMission { ...
#![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] use std::ptr::null_mut; use std::slice; use std::sync::atomic::{AtomicUsize, Ordering}; use libc::c_void; use crate::samase; use bw_dat::{DatTable, UnitArray, UnitId, OrderId}; pub use bw_dat::structs::*; #[repr(C)] pub struct CampaignMission { ...
} pub unsafe fn set_iscript_animation(image: *mut Image, animation: u8) { let old_animation = (*image).iscript.animation; if (*image).flags & 0x10 == 0 && animation > 1 { return; } if old_animation == animation { if animation == 0x1 || animation == 0xb || animation == 0x13 { ...
distance( Point { x: 0, y: 0, }, Point { x: x_diff, y: y_diff, }, )
call_expression
[ { "content": "/// NOTE: Bw uses index, this uses pointer value for simpler code.\n\n///\n\n/// That however makes the returned value unsaveable / synchronizable, even though\n\n/// it won't affect comparisions as long as all sprites are in a single array\n\nfn sprite_sort_order(sprite: Sprite, position: &bw::Po...
Rust
bpf/aya-bpf/src/args.rs
Tuetuopay/aya
4f13576594de87d8c6c4da12a6783c23155e359d
use crate::{cty::c_void, helpers::bpf_probe_read_kernel}; #[cfg(not(bpf_target_arch = "aarch64"))] use crate::bindings::pt_regs; #[cfg(bpf_target_arch = "aarch64")] use crate::bindings::user_pt_regs as pt_regs; pub unsafe trait FromBtfArgument: Sized { unsafe fn from_argument(ct...
use crate::{cty::c_void, helpers::bpf_probe_read_kernel}; #[cfg(not(bpf_target_arch = "aarch64"))] use crate::bindings::pt_regs; #[cfg(bpf_target_arch = "aarch64")] use crate::bindings::user_pt_regs as pt_regs; pub unsafe trait FromBtfArgument: Sized { unsafe fn from_argument(ct...
} fn from_retval(ctx: &pt_regs) -> Option<Self> { unsafe { bpf_probe_read_kernel(&ctx.rax).map(|v| v as *const _).ok() } } } #[cfg(bpf_target_arch = "arm")] impl<T> FromPtRegs for *const T { fn from_argument(ctx: &pt_regs, n: usize) -> Option<Self> { if n <= 6 { unsafe { ...
match n { 0 => unsafe { bpf_probe_read_kernel(&ctx.rdi).map(|v| v as *const _).ok() }, 1 => unsafe { bpf_probe_read_kernel(&ctx.rsi).map(|v| v as *const _).ok() }, 2 => unsafe { bpf_probe_read_kernel(&ctx.rdx).map(|v| v as *const _).ok() }, 3 => unsafe { bpf_probe_read_ke...
if_condition
[ { "content": "#[xdp(name=\"pass\")]\n\npub fn pass(ctx: XdpContext) -> u32 {\n\n match unsafe { try_pass(ctx) } {\n\n Ok(ret) => ret,\n\n Err(_) => xdp_action::XDP_ABORTED,\n\n }\n\n}\n\n\n\nunsafe fn try_pass(_ctx: XdpContext) -> Result<u32, u32> {\n\n Ok(xdp_action::XDP_PASS)\n\n}\n\n\n...
Rust
garnet/bin/setui/src/tests/fakes/audio_core_service.rs
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
use crate::audio::default_audio_info; use crate::tests::fakes::base::Service; use anyhow::{format_err, Error}; use fidl::endpoints::{ServerEnd, ServiceMarker}; use fidl_fuchsia_media::{AudioRenderUsage, Usage}; use fuchsia_async as fasync; use fuchsia_zircon as zx; use futures::TryStreamExt; use parking_lot::RwLock; ...
use crate::audio::default_audio_info; use crate::tests::fakes::base::Service; use anyhow::{format_err, Error}; use fidl::endpoints::{ServerEnd, ServiceMarker}; use fidl_fuchsia_media::{AudioRenderUsage, Usage}; use fuchsia_async as fasync; use fuchsia_zircon as zx; use futures::TryStreamExt; use parking_lot::RwLock; ...
} }); }
nsert( AudioRenderUsage::from(stream.stream_type), (stream.user_volume_level, stream.user_volume_muted), ); } Self { audio_streams: Arc::new(RwLock::new(streams)) } } pub fn get_level_and_mute(&self, usage: AudioRenderUsage) -> Option<(f32, bool)> { ...
random
[]
Rust
tests/event_sorting.rs
timokoesters/state-res
acd829336ee71725822c9606b1d6d900509d28e9
use std::{cell::RefCell, collections::BTreeMap, convert::TryFrom}; use ruma::{ events::{ pdu::EventHash, room::{ join_rules::JoinRule, member::{MemberEventContent, MembershipState}, }, EventType, }, identifiers::{EventId, RoomId, RoomVersionId, UserId...
use std::{cell::RefCell, collections::BTreeMap, convert::TryFrom}; use ruma::{ events::{ pdu::EventHash, room::{ join_rules::JoinRule, member::{MemberEventContent, MembershipState}, }, EventType, }, identifiers::{EventId, RoomId, RoomVersionId, UserId...
"origin_server_ts": ts, "room_id": room_id(), "origin": "foo", "depth": 0, "hashes": { "sha256": "hello" }, "signatures": {}, }) }; serde_json::from_value(json).unwrap() } #[allow(non_snake_case)] fn INITIAL_EVENTS() -> BTreeMap<Even...
id, EventHash { sha256: "hello".into(), }, ) }) .collect::<Vec<_>>(); let prev_events = prev_events .iter() .map(AsRef::as_ref) .map(event_id) .map(|id| { ( id, ...
function_block-random_span
[ { "content": "fn event_id(id: &str) -> EventId {\n\n if id.contains('$') {\n\n return EventId::try_from(id).unwrap();\n\n }\n\n EventId::try_from(format!(\"${}:foo\", id)).unwrap()\n\n}\n\n\n", "file_path": "tests/event_auth.rs", "rank": 0, "score": 197446.86890025268 }, { "c...
Rust
src/webdriver.rs
jgraef/thirtyfour
91ae76402de019d707affe3d272a21d966e34a17
use async_trait::async_trait; use log::error; use serde::Serialize; use serde_json::Value; use std::marker::PhantomData; use crate::common::config::WebDriverConfig; use crate::http::connection_async::WebDriverHttpClientAsync; #[cfg(not(any(feature = "tokio-runtime", feature = "async-std-runtime")))] use crate::http::n...
use async_trait::async_trait; use log::error; use serde::Serialize; use serde_json::Value; use std::marker::PhantomData; use crate::common::config::WebDriverConfig; use crate::http::connection_async::WebDriverHttpClientAsync; #[cfg(not(any(feature = "tokio-runtime", feature = "async-std-runtime")))] use crate::http::n...
} impl WebDriver { pub fn persist(mut self) -> PersistedSession { self.quit_on_drop = false; PersistedSession { session_id: self.session.session_id().clone(), capabilities: self.capabilities.clone(), } } } }
e_server_addr: &str, ) -> WebDriverResult<GenericWebDriver<T>> where T: WebDriverHttpClientAsync + 'static, { let conn = T::create(remote_server_addr)?; let tx = spawn_session_task(Box::new(conn)); let driver = GenericWebDriver { ...
function_block-function_prefixed
[ { "content": "/// Merge two serde_json::Value structs.\n\n///\n\n/// From https://stackoverflow.com/questions/47070876/how-can-i-merge-two-json-objects-with-rust\n\nfn merge(a: &mut Value, b: Value) {\n\n match (a, b) {\n\n (a @ &mut Value::Object(_), Value::Object(b)) => {\n\n let a = a.as...
Rust
crates/holochain/src/core/ribosome/guest_callback/init.rs
pospi/holochain
ed0d4e8a88a7805a6f968ae56173f409de857623
use crate::core::ribosome::FnComponents; use crate::core::ribosome::HostAccess; use crate::core::ribosome::Invocation; use crate::core::ribosome::ZomesToInvoke; use crate::core::workflow::CallZomeWorkspaceLock; use derive_more::Constructor; use holo_hash::EntryHash; use holochain_keystore::KeystoreSender; use holochain...
use crate::core::ribosome::FnComponents; use crate::core::ribosome::HostAccess; use crate::core::ribosome::Invocation; use crate::core::ribosome::ZomesToInvoke; use crate::core::workflow::CallZomeWorkspaceLock; use derive_more::Constructor; use holo_hash::EntryHash; use holochain_keystore::KeystoreSender; use holochain...
} #[cfg(test)] mod test { use super::InitResult; use crate::core::ribosome::Invocation; use crate::core::ribosome::ZomesToInvoke; use crate::fixt::InitHostAccessFixturator; use crate::fixt::InitInvocationFixturator; use crate::fixt::ZomeNameFixturator; use ::fixt::prelude::*; use holoc...
c, _ => Self::UnresolvedDependencies(zome_name, ud.into_iter().collect()), }, InitCallbackResult::Pass => acc, }) }
function_block-function_prefixed
[ { "content": "/// Keeping with convention if Alice is pubkey 1\n\n/// and bob is pubkey 2 the this helps make test\n\n/// logging easier to read.\n\npub fn which_agent(key: &AgentPubKey) -> String {\n\n let key = key.to_string();\n\n let alice = fake_agent_pubkey_1().to_string();\n\n let bob = fake_age...
Rust
core/src/subgraph/provider.rs
dillonhows/graph-node
60c233fec2e483607be85e9f0c2bafc77ed91f62
use futures::sync::mpsc::{channel, Receiver, Sender}; use std::collections::HashSet; use std::sync::Mutex; use graph::data::subgraph::schema::attribute_index_definitions; use graph::prelude::{ DataSourceLoader as _, GraphQlRunner, SubgraphAssignmentProvider as SubgraphAssignmentProviderTrait, *, }; use crate:...
use futures::sync::mpsc::{channel, Receiver, Sender}; use std::collections::HashSet; use std::sync::Mutex; use graph::data::subgraph::schema::attribute_index_definitions; use graph::prelude::{ DataSourceLoader as _, GraphQlRunner, SubgraphAssignmentProvider as SubgraphAssignmentProviderTrait, *, }; use crate:...
; self_clone .store .clone() .build_entity_attribute_indexes(index_definitions) .map(|_| { info!( self_clone.logger,...
attribute_index_definitions( subgraph.id.clone(), subgraph.schema.document.clone(), )
call_expression
[ { "content": "/// Resolves links to subgraph manifests and resources referenced by them.\n\npub trait LinkResolver: Send + Sync + 'static {\n\n /// Fetches the link contents as bytes.\n\n fn cat(&self, link: &Link) -> Box<Future<Item = Vec<u8>, Error = failure::Error> + Send>;\n\n\n\n /// Read the cont...
Rust
tests/fetch.rs
nickzana/musicbrainz_rs
55ec1187ebe860a5afe538acefe9bae541cdc7d0
extern crate chrono; extern crate musicbrainz_rs; use chrono::NaiveDate; use musicbrainz_rs::entity::area::*; use musicbrainz_rs::entity::artist::ArtistType::*; use musicbrainz_rs::entity::artist::*; use musicbrainz_rs::entity::event::Event; use musicbrainz_rs::entity::instrument::*; use musicbrainz_rs::entity::label...
extern crate chrono; extern crate musicbrainz_rs; use chrono::NaiveDate; use musicbrainz_rs::entity::area::*; use musicbrainz_rs::entity::artist::ArtistType::*; use musicbrainz_rs::entity::artist::*; use musicbrainz_rs::entity::event::Event; use musicbrainz_rs::entity::instrument::*; use musicbrainz_rs::entity::label...
.id("2a0981fb-9593-3019-864b-ce934d97a16e") .execute(); assert_eq!( in_utero.unwrap(), ReleaseGroup { id: "2a0981fb-9593-3019-864b-ce934d97a16e".to_string(), primary_type_id: Some("f529b476-6e62-324f-b0aa-1f3e33d313fc".to_string()), primary_type: Some("...
n: None, isrcs: None, } ); } #[test] fn should_get_release_group_by_id() { let in_utero = ReleaseGroup::fetch()
random
[ { "content": "#[test]\n\nfn should_get_work_rating() {\n\n let hotel_california = Work::fetch()\n\n .id(\"22457dc0-ecbf-38f5-9056-11c858530a50\")\n\n .with_ratings()\n\n .execute()\n\n .unwrap();\n\n\n\n assert!(hotel_california.rating.is_some());\n\n}\n\n\n", "file_path": ...
Rust
stry-frontend-user/src/utils.rs
Txuritan/stry
e709b26084e97c452ff985675c28741affd45350
use { askama::Template, chrono::Utc, fluent::{concurrent::FluentBundle, FluentResource}, once_cell::sync::OnceCell, std::{collections::HashMap, fmt, future::Future, str::FromStr, sync::Arc}, stry_models::{Author, Character, Origin, Pairing, Tag, Warning}, unic_langid::LanguageIdentifier, ...
use { askama::Template, chrono::Utc, fluent::{concurrent::FluentBundle, FluentResource}, once_cell::sync::OnceCell, std::{collections::HashMap, fmt, future::Future, str::FromStr, sync::Arc}, stry_models::{Author, Character, Origin, Pairing, Tag, Warning}, unic_langid::LanguageIdentifier, ...
} pub fn color(&self) -> &str { match self { Resource::Author(_) => "color__blue", Resource::Character(_) => "color__purple", Resource::Origin(_) => "color__green", Resource::Pairing(_) => "color__yellow", Resource::Tag(_) => "color__silver",...
match self { Resource::Author(entity) => &entity.id, Resource::Character(entity) => &entity.id, Resource::Origin(entity) => &entity.id, Resource::Pairing(entity) => &entity.id, Resource::Tag(entity) => &entity.id, Resource::Warning(entity) => &enti...
if_condition
[ { "content": "// https://github.com/seanmonstar/warp/issues/131\n\nfn enable(is_enabled: bool) -> impl Filter<Extract = (), Error = Rejection> + Clone {\n\n warp::any()\n\n .and_then(move || async move {\n\n if is_enabled {\n\n Ok(())\n\n } else {\n\n ...
Rust
server/src/server.rs
Eitu33/mazehem
7e3d7140f85b98ffd0b015d1bc6571e7ea18e968
use crate::maze::Maze; use bincode::{deserialize, serialize}; use crossbeam_channel::{Receiver, Sender}; use indexmap::IndexMap; use laminar::{Packet, Socket, SocketEvent}; use std::net::SocketAddr; use types::cell::Cell; use types::constants::{HEIGHT, WIDTH}; use types::coord::Coord; use types::data::Data; use types::...
use crate::maze::Maze; use bincode::{deserialize, serialize}; use crossbeam_channel::{Receiver, Sender}; use indexmap::IndexMap; use laminar::{Packet, Socket, SocketEvent}; use std::net::SocketAddr; use types::cell::Cell; use types::constants::{HEIGHT, WIDTH}; use types::coord::Coord; use types::data::Data; use types::...
&Coord::new( self.players[i].coord.x.saturating_sub(1), self.players[i].coord.y, ), ) => { self.players[i].coord.x -= 1; } SerKey::Up if self.move_allowed( ...
coord.y, ), ) => { self.players[i].coord.x += 1; } SerKey::Down if self.move_allowed( i, &Coord::new( self.players[i].coord.x, s...
random
[]
Rust
crates/ra_ide/src/parent_module.rs
theHamsta/rust-analyzer
f7f01dd5f0a8254abeefb0156e2c4ebe1447bfb6
use hir::Semantics; use ra_db::{CrateId, FileId, FilePosition}; use ra_ide_db::RootDatabase; use ra_syntax::{ algo::find_node_at_offset, ast::{self, AstNode}, }; use test_utils::mark; use crate::NavigationTarget; pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec<NavigationTarget>...
use hir::Semantics; use ra_db::{CrateId, FileId, FilePosition}; use ra_ide_db::RootDatabase; use ra_syntax::{ algo::find_node_at_offset, ast::{self, AstNode}, }; use test_utils::mark; use crate::NavigationTarget; pub(crate) fn parent_module(db: &RootDatabase, position: FilePosition) -> Vec<NavigationTarget>...
let module = match module { None => return Vec::new(), Some(it) => it, }; let nav = NavigationTarget::from_module_to_decl(db, module); vec![nav] } pub(crate) fn crate_for(db: &RootDatabase, file_id: FileId) -> Vec<CrateId> { let sema = Semantics::new(db); let module = match sem...
let module = match module { Some(module) => sema.to_def(&module), None => sema.to_module_def(position.file_id), };
assignment_statement
[ { "content": "/// Parse a use 'tree', such as `some::path` in `use some::path;`\n\n/// Note that this is called both by `use_item` and `use_tree_list`,\n\n/// so handles both `some::path::{inner::path}` and `inner::path` in\n\n/// `use some::path::{inner::path};`\n\nfn use_tree(p: &mut Parser, top_level: bool) ...
Rust
tests/cors.rs
csmith/static-web-server
06cc3792299516f31e123462783392e2cb7b7f99
#![forbid(unsafe_code)] #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(dead_code)] #[cfg(test)] mod tests { use headers::HeaderMap; use http::Method; use static_web_server::cors; #[tokio::test] async fn allow_methods() { let cors = cors::new("*", "").unwrap(); let headers = ...
#![forbid(unsafe_code)] #![deny(warnings)] #![deny(rust_2018_idioms)] #![deny(dead_code)] #[cfg(test)] mod tests { use headers::HeaderMap; use http::Method; use static_web_server::cors; #[tokio::test] async fn allow_methods() { let cors = cors::new("*", "").unwrap(); let headers = ...
#[tokio::test] async fn headers_allowed() { let cors = cors::new("*", "").unwrap(); let mut headers = HeaderMap::new(); headers.insert("origin", "https://localhost".parse().unwrap()); headers.insert("access-control-request-method", "GET".parse().unwrap()); headers.inser...
async fn method_disallowed() { let cors = cors::new("*", "").unwrap(); let mut headers = HeaderMap::new(); headers.insert("origin", "https://localhost".parse().unwrap()); headers.insert("access-control-request-method", "POST".parse().unwrap()); let methods = [Method::GET, Method:...
function_block-full_function
[ { "content": "/// It appends security headers like `Strict-Transport-Security: max-age=63072000; includeSubDomains; preload` (2 years max-age),\n\n///`X-Frame-Options: DENY`, `X-XSS-Protection: 1; mode=block` and `Content-Security-Policy: frame-ancestors 'self'`.\n\npub fn append_headers(resp: &mut Response<Bod...
Rust
gdk4/src/auto/content_formats.rs
YaLTeR/gtk4-rs
a49bfe4b29c85cc8cc5c1a22f8c64b5835072d89
use glib::translate::*; use std::fmt; use std::mem; glib::glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ContentFormats(Shared<ffi::GdkContentFormats>); match fn { ref => |ptr| ffi::gdk_content_formats_ref(ptr), unref => |ptr| ffi::gdk_content_formats_u...
use glib::translate::*; use std::fmt; use std::mem; glib::glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ContentFormats(Shared<ffi::GdkContentFormats>); match fn { ref => |ptr| ffi::gdk_content_formats_ref(ptr), unref => |ptr| ffi::gdk_content_formats_u...
#[doc(alias = "gdk_content_formats_get_mime_types")] pub fn get_mime_types(&self) -> (Vec<glib::GString>, usize) { unsafe { let mut n_mime_types = mem::MaybeUninit::uninit(); let ret = FromGlibPtrContainer::from_glib_none(ffi::gdk_content_formats_get_mime_types(...
pub fn contain_mime_type(&self, mime_type: &str) -> bool { unsafe { from_glib(ffi::gdk_content_formats_contain_mime_type( self.to_glib_none().0, mime_type.to_glib_none().0, )) } }
function_block-full_function
[ { "content": "#[doc(alias = \"gdk_keyval_is_lower\")]\n\npub fn keyval_is_lower(keyval: u32) -> bool {\n\n assert_initialized_main_thread!();\n\n unsafe { from_glib(ffi::gdk_keyval_is_lower(keyval)) }\n\n}\n\n\n", "file_path": "gdk4/src/auto/functions.rs", "rank": 0, "score": 268056.06238241 ...
Rust
src/primary_writer.rs
brayniac/flexi_logger
92f30acc347d999f1722a3717b3586d5f2100e48
use crate::deferred_now::DeferredNow; use crate::filter::LogLineWriter; use crate::logger::Duplicate; use crate::writers::{FileLogWriter, FileLogWriterBuilder, LogWriter}; use crate::{FlexiLoggerError, FormatFunction}; use log::Record; use std::cell::RefCell; use std::io::{BufWriter, Write}; use std::sync::Mutex; #[al...
use crate::deferred_now::DeferredNow; use crate::filter::LogLineWriter; use crate::logger::Duplicate; use crate::writers::{FileLogWriter, FileLogWriterBuilder, LogWriter}; use crate::{FlexiLoggerError, FormatFunction}; use log::Record; use std::cell::RefCell; use std::io::{BufWriter, Write}; use std::sync::Mutex; #[al...
rr); }
} pub(crate) struct MultiWriter { duplicate_stderr: Duplicate, duplicate_stdout: Duplicate, format_for_stderr: FormatFunction, format_for_stdout: FormatFunction, o_file_writer: Option<Box<FileLogWriter>>, o_other_writer: Option<Box<dyn LogWriter>>, } impl MultiWriter { pub(crate) fn reset_...
random
[ { "content": "pub fn test_format(\n\n w: &mut dyn std::io::Write,\n\n now: &mut DeferredNow,\n\n record: &Record,\n\n) -> std::io::Result<()> {\n\n write!(\n\n w,\n\n \"XXXXX [{}] T[{:?}] {} [{}:{}] {}\",\n\n now.now().format(\"%Y-%m-%d %H:%M:%S%.6f %:z\"),\n\n std::threa...
Rust
cross-checks/rust-checks/runtime/src/hash/mod.rs
lu-zero/c2rust
776976b5e592c898fe4a6b0d2369d5bb021b4751
use std::hash::Hasher; use std::mem; #[cfg(feature="libc-hash")] use libc; pub mod djb2; pub mod simple; pub mod jodyhash; const MAX_DEPTH: usize = 8; pub trait CrossCheckHasher: Hasher + Default { fn write_bool(&mut self, i: bool) { self.write_u8(i as u8); } fn write_char(&mut self, i: char) ...
use std::hash::Hasher; use std::mem; #[cfg(feature="libc-hash")] use libc; pub mod djb2; pub mod simple; pub mod jodyhash; const MAX_DEPTH: usize = 8; pub trait CrossCheckHasher: Hasher + Default { fn write_bool(&mut self, i: bool) { self.write_u8(i as u8); } fn write_char(&mut self, i: char) ...
pt_hash!(A, B, C, D, E, F); impl_fnopt_hash!(A, B, C, D, E, F, G); impl_fnopt_hash!(A, B, C, D, E, F, G, H); impl_fnopt_hash!(A, B, C, D, E, F, G, H, I); impl_fnopt_hash!(A, B, C, D, E, F, G, H, I, J); impl_fnopt_hash!(A, B, C, D, E, F, G, H, I, J, K); impl_fnopt_hash!(A, B, C, D, E, F, G, H, I, J, K, L); macro_rules!...
HA, HS>(depth - 1) } } } macro_rules! impl_fnopt_hash { (<$($arg:ident),*> + $($pfx:tt)*) => { impl <Ret, $($arg),*> CrossCheckHash for $($pfx)* fn($($arg),*) -> Ret { #[inline] fn cross_check_hash_depth<HA, HS>(&self, depth: usize) -> u64 where HA: C...
random
[ { "content": "pub fn expect_xcheck(tag: u8, val: u64) {\n\n let xc = XCHECKS.with(|xc| xc.borrow_mut().pop_front().unwrap());\n\n assert_eq!(xc, XCheck(tag, val));\n\n}\n\n\n", "file_path": "cross-checks/rust-checks/rustc-plugin/tests/xcheck/mod.rs", "rank": 1, "score": 263543.34530907945 },...
Rust
src/parser/expr_parser.rs
iffyio/memdb
d86d1e477344c7184fe8ce87f0a12cf2b3a028d5
use crate::parser::ast::*; use crate::parser::lexer::token::Token; use crate::parser::parse::ParseHelper; use crate::parser::parse::{Input, ParseError}; pub struct Parser {} type Result<T> = std::result::Result<T, ParseError>; impl Parser { pub fn expr(input: &mut Input) -> Result<Expr> { ...
use crate::parser::ast::*; use crate::parser::lexer::token::Token; use crate::parser::parse::ParseHelper; use crate::parser::parse::{Input, ParseError}; pub struct Parser {} type Result<T> = std::result::Result<T, ParseError>; impl Parser { pub fn expr(input: &mut Input) -> Result<Expr> { ...
} #[cfg(test)] mod test { use super::*; use crate::parser::ast::Expr; #[test] fn parse_simple_addition() -> Result<()> { let mut input = Input::new(vec![Token::Integer(1), Token::Plus, Token::Integer(2)]); let e = Parser::expr(&mut input)?; assert_eq!( e, ...
n::Integer(num)) => Ok(Expr::Literal(LiteralExpr::Integer(num))), Some(Token::True) => Ok(Expr::Literal(LiteralExpr::Boolean(true))), Some(Token::False) => Ok(Expr::Literal(LiteralExpr::Boolean(false))), Some(Token::LeftParen) => { let expr = Parser::l0_expr(input)?; ...
function_block-function_prefixed
[ { "content": "pub fn type_check_expr(\n\n expr: &Expr,\n\n ctx: &HashMap<&String, &AttributeType>,\n\n) -> Result<AttributeType> {\n\n fn eval(attr: &String, ctx: &HashMap<&String, &AttributeType>) -> Result<AttributeType> {\n\n ctx.get(attr).map(|t| (*t).clone()).ok_or_else(|| {\n\n ...
Rust
rbx_types/src/legacy_compat.rs
CloneTrooper1019/rbx-dom
1aff01b1a493eda10ec3f4310b3f8a78d45269b4
use std::convert::TryFrom; use rbx_dom_weak::{ BrickColor as LegacyBrickColor, ColorSequence as LegacyColorSequence, ColorSequenceKeypoint as LegacyColorSequenceKeypoint, NumberSequence as LegacyNumberSequence, NumberSequenceKeypoint as LegacyNumberSequenceKeypoint, PhysicalProperties as LegacyPhysic...
use std::convert::TryFrom; use rbx_dom_weak::{ BrickColor as LegacyBrickColor, ColorSequence as LegacyColorSequence, ColorSequenceKeypoint as LegacyColorSequenceKeypoint, NumberSequence as LegacyNumberSequence, NumberSequenceKeypoint as LegacyNumberSequenceKeypoint, PhysicalProperties as LegacyPhysic...
}
s }, } } Variant::PhysicalProperties(value) => { let new_value = match value { PhysicalProperties::Custom(properties) => Some(LegacyPhysicalProperties { density: properties.density, friction: pro...
function_block-function_prefixed
[]
Rust
src/status.rs
taku-y/primitiv-rust
76edd080700683a458e43c89fff5579c090c3bc5
extern crate backtrace; use self::backtrace::Backtrace; use libc::c_uint; use primitiv_sys as _primitiv; use std::env; use std::ffi::CString; use std::fmt; use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::mem; use std::ptr; use std::result; #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, C...
extern crate backtrace; use self::backtrace::Backtrace; use libc::c_uint; use primitiv_sys as _primitiv; use std::env; use std::ffi::CString; use std::fmt; use std::fmt::Debug; use std::fmt::Display; use std::fmt::Formatter; use std::mem; use std::ptr; use std::result; #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, C...
atus { ($status:expr) => { match Result::from_api_status($status, 0) { Ok(_) => {} Err(s) => { panic!("{:?}", s); } } }; }
race) } else { None }, )) }, } } } pub(crate) type Result<T> = result::Result<T, Status>; macro_rules! check_api_st
random
[ { "content": "fn run<F>(name: &str, mut configure: F)\n\nwhere\n\n F: FnMut(&mut Command) -> &mut Command,\n\n{\n\n let mut command = Command::new(name);\n\n let configured = configure(&mut command);\n\n log!(\"Executing {:?}\", configured);\n\n if !configured.status().unwrap().success() {\n\n ...
Rust
examples/sqlite/all_about_inserts/src/lib.rs
likewhatevs/diesel
958b51a42bbd36d5d589e8f1eae312e2d43d6a95
extern crate chrono; #[macro_use] extern crate diesel; #[macro_use] extern crate serde_derive; extern crate serde_json; use chrono::NaiveDateTime; #[cfg(test)] use diesel::debug_query; use diesel::insert_into; use diesel::prelude::*; #[cfg(test)] use diesel::sqlite::Sqlite; use std::error::Error; mod schema { tab...
extern crate chrono; #[macro_use] extern crate diesel; #[macro_use] extern crate serde_derive; extern crate serde_json; use chrono::NaiveDateTime; #[cfg(test)] use diesel::debug_query; use diesel::insert_into; use diesel::prelude::*; #[cfg(test)] use diesel::sqlite::Sqlite; use std::error::Error; mod schema { tab...
expected_users, inserted_users); Ok(()) }); } #[test] fn examine_sql_from_insert_get_results_batch() { use schema::users::dsl::*; let load_query = users.order(id.desc()); let load_sql = "SELECT `users`.`id`, `users`.`name`, \ `users`...
)?; let expected_users = vec![ User { id: 1, name: "Sean".into(), hair_color: None, created_at: now, updated_at: now, }, User { id: 2, name: "Tess".into(), ...
function_block-random_span
[ { "content": "pub fn find_user_by_name(name: &str, connection: &TestConnection) -> User {\n\n users::table\n\n .filter(users::name.eq(name))\n\n .first(connection)\n\n .unwrap()\n\n}\n", "file_path": "diesel_tests/tests/schema.rs", "rank": 0, "score": 519513.1838812814 }, ...
Rust
validator_client/slashing_protection/src/interchange_test.rs
davidkassa/lighthouse
40cf8e31e04693a4cfb92e4b8d9d2663ef9928f7
use crate::{ interchange::{Interchange, SignedAttestation, SignedBlock}, test_utils::{pubkey, DEFAULT_GENESIS_VALIDATORS_ROOT}, SigningRoot, SlashingDatabase, }; use serde_derive::{Deserialize, Serialize}; use std::collections::HashSet; use tempfile::tempdir; use types::{Epoch, Hash256, PublicKeyBytes, Slot...
use crate::{ interchange::{Interchange, SignedAttestation, SignedBlock}, test_utils::{pubkey, DEFAULT_GENESIS_VALIDATORS_ROOT}, SigningRoot, SlashingDatabase, }; use serde_derive::{Deserialize, Serialize}; use std::collections::HashSet; use tempfile::tempdir; use types::{Epoch, Hash256, PublicKeyBytes, Slot...
} _ => (), } } } } } impl TestCase { pub fn new(interchange: Interchange) -> Self { TestCase { should_succeed: true, contains_slashable_data: false, interchange, blocks: vec![], attestat...
panic!( "test `{}` failed on import when it should have succeeded, error: {:?}", self.name, e ); } break; } } for (i, block) in test_c...
random
[ { "content": "/// Returns the value of `name` or an error if it is not in `matches` or does not parse\n\n/// successfully using `std::string::FromStr`.\n\npub fn parse_required<T>(matches: &ArgMatches, name: &str) -> Result<T, String>\n\nwhere\n\n T: FromStr,\n\n <T as FromStr>::Err: std::fmt::Display,\n\...
Rust
core/src/avm2/globals/math.rs
wook2014/ruffle
b7de03b5c8bd80452865053fd5fbc6c67f4e2186
use crate::avm2::activation::Activation; use crate::avm2::class::{Class, ClassAttributes}; use crate::avm2::method::{Method, NativeMethod}; use crate::avm2::names::{Namespace, QName}; use crate::avm2::object::Object; use crate::avm2::value::Value; use crate::avm2::Error; use gc_arena::{GcCell, MutationContext}; use r...
use crate::avm2::activation::Activation; use crate::avm2::class::{Class, ClassAttributes}; use crate::avm2::method::{Method, NativeMethod}; use crate::avm2::names::{Namespace, QName}; use crate::avm2::object::Object; use crate::avm2::value::Value; use crate::avm2::Error; use gc_arena::{GcCell, MutationContext}; use r...
ce_to_number(activation)?; if val.is_nan() { return Ok(f64::NAN.into()); } else if val < cur_min { cur_min = val; } } Ok(cur_min.into()) } fn pow<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Option<Object<'gc>>, args: &[Value<'gc>], ) -> Res...
espace::public(), "Object").into()), Method::from_builtin(instance_init), Method::from_builtin(class_init), mc, ); let mut write = class.write(mc); write.set_attributes(ClassAttributes::FINAL | ClassAttributes::SEALED); use std::f64::consts::*; const CONSTANTS: &[(&str, f64...
random
[ { "content": "pub fn root_error_handler<'gc>(activation: &mut Activation<'_, 'gc, '_>, error: Error<'gc>) {\n\n if let Error::ThrownValue(error) = &error {\n\n let message = error\n\n .coerce_to_string(activation)\n\n .unwrap_or_else(|_| \"undefined\".into());\n\n activati...
Rust
rust/zephyr-macros/src/lib.rs
RustyThingy/zephyr-rust
29e904cdcc4bd60cec6c3ffcb5072463a73873b9
extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::{Ident, Literal, TokenTree}; use quote::quote; fn get_single_arg(item: TokenStream) -> Ident { let item = proc_macro2::TokenStream::from(item); let arg = item.into_iter().next(); let ident = if let Some(TokenTree::Ident(ident)) = arg {...
extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::{Ident, Literal, TokenTree}; use quote::quote; fn get_single_arg(item: TokenStream) -> Ident { let item = proc_macro2::TokenStream::from(item); let arg = item.into_iter().next(); let ident = if let Some(TokenTree::Ident(ident)) = arg {...
ninit() }; #[allow(non_snake_case)] extern "C" fn #ctor() { use zephyr::semaphore::*; unsafe { #ident.init::<zephyr::context::Kernel>(#initial, #limit) } } #[used] #[link_section = ".ctors"] #[allow(non_upper_case_globals)] ...
function_block-function_prefixed
[ { "content": "#[inline(never)]\n\npub fn current_reactor_register(signal: &'static impl PollableKobj, context: &mut Context) {\n\n match REACTOR.try_with(|r| r.borrow_mut().as_mut().map(|r| r.register(signal, context))) {\n\n Ok(None) | Err(_) => panic!(\"register with no reactor\"),\n\n Ok(Som...
Rust
algorithms/linfa-linear/src/glm.rs
onehr/linfa
6065062f0573296c244485cfe494187268fff60c
mod distribution; mod link; use crate::error::Result; use crate::float::{ArgminParam, Float}; use distribution::TweedieDistribution; pub use link::Link; use argmin::core::{ArgminOp, Executor}; use argmin::solver::linesearch::MoreThuenteLineSearch; use argmin::solver::quasinewton::LBFGS; use ndarray::{array, s, stac...
mod distribution; mod link; use crate::error::Result; use crate::float::{ArgminParam, Float}; use distribution::TweedieDistribution; pub use link::Link; use argmin::core::{ArgminOp, Executor}; use argmin::solver::linesearch::MoreThuenteLineSearch; use argmin::solver::quasinewton::LBFGS; use ndarray::{array, s, stac...
} struct TweedieProblem<'a, A: Float> { x: ArrayView2<'a, A>, y: ArrayView1<'a, A>, fit_intercept: bool, link: &'a Link, dist: TweedieDistribution, alpha: f64, } impl<'a, A: Float> TweedieProblem<'a, A> { fn ypred(&self, p: &Array1<A>) -> (Array1<A>, Array1<A>, usize) { let mut of...
fn fit(&self, ds: &DatasetBase<ArrayBase<D, Ix2>, T>) -> Result<FittedTweedieRegressor<A>> { let (x, y) = (ds.records(), ds.try_single_target()?); let dist = TweedieDistribution::new(self.power)?; if self.alpha < 0. { return Err(linfa::Error::Parameters(format!( "Pe...
function_block-full_function
[ { "content": "/// Calculate the Pearson's Correlation Coefficient (or bivariate correlation)\n\n///\n\n/// The PCC describes the linear correlation between two variables. It is the covariance divided by\n\n/// the product of the standard deviations, therefore essentially a normalised measurement of the\n\n/// c...
Rust
crypto-ws-client/tests/bitfinex.rs
crypto-crawler/crypto-crawler-rs
e13e5493b530a7211479987c8b9209157ebdbaa2
#[macro_use] mod utils; #[cfg(test)] mod bitfinex_spot { use crypto_ws_client::{BitfinexWSClient, WSClient}; #[tokio::test(flavor = "multi_thread")] async fn subscribe() { gen_test_code!( BitfinexWSClient, subscribe, &vec![ ("trades".to_string(),...
#[macro_use] mod utils; #[cfg(test)] mod bitfinex_spot { use crypto_ws_client::{BitfinexWSClient, WSClient}; #[tokio::test(flavor = "multi_thread")] async fn subscribe() { gen_test_code!(
to_string()), ] ); } #[test] #[should_panic] fn subscribe_illegal_symbol() { gen_test_code!( BitfinexWSClient, subscribe, &vec![("trades".to_string(), "tXXXYYY".to_string())] ); } #[tokio::test(flavor = "multi_thread")] ...
BitfinexWSClient, subscribe, &vec![ ("trades".to_string(), "tBTCUST".to_string()), ("trades".to_string(), "tETHUST".
function_block-random_span
[ { "content": "fn channel_symbols_to_command(channel: &str, symbols: &[String], subscribe: bool) -> String {\n\n format!(\n\n r#\"{{\"id\":\"crypto-ws-client\",\"type\":\"{}\",\"topic\":\"{}:{}\",\"privateChannel\":false,\"response\":true}}\"#,\n\n if subscribe { \"subscribe\" } else { \"unsubsc...
Rust
tests/integration.rs
samcday/cargo-benchcmp
c7769315714a92188bcbafd722ebabe0f9af1b6c
extern crate second_law; macro_rules! new_scene { () => ({ use second_law; if cfg!(target_os = "windows") { second_law::Scene::new(format!("{}.exe", env!("CARGO_PKG_NAME"))) } else { second_law::Scene::new(env!("CARGO_PKG_NAME")) } }); } fn new_ucmd() ->...
extern crate second_law; macro_rules! new_scene { () => ({ use second_law; if cfg!(target_os
d() { new_ucmd() .args(&["bench_output_4.txt", "bench_output_8.txt", "--threshold", "2", "--improvements"]) .succeeds() .no_stdout() .stderr_is_fixture("zero_improvements.expected"); }
= "windows") { second_law::Scene::new(format!("{}.exe", env!("CARGO_PKG_NAME"))) } else { second_law::Scene::new(env!("CARGO_PKG_NAME")) } }); } fn new_ucmd() -> second_law::UCommand { let mut scene: second_law::Scene = new_scene!(); scene.subcmd_arg("benchcmp"); ...
random
[ { "content": "extern crate docopt;\n\n#[macro_use]\n\nextern crate lazy_static;\n\nextern crate regex;\n\n#[macro_use]\n\nextern crate prettytable;\n\n#[macro_use]\n\nextern crate serde_derive;\n\n#[cfg(test)]\n\n#[macro_use]\n\nextern crate quickcheck;\n\n\n\nuse std::io::{self, BufRead};\n\nuse std::fs::File;...
Rust
src/cast.rs
MucTepDayH16/substrate-fixed
be5f4d30b61309ee097837ff3c1e02f045b0e452
use crate::{ types::extra::{LeEqU128, LeEqU16, LeEqU32, LeEqU64, LeEqU8}, FixedI128, FixedI16, FixedI32, FixedI64, FixedI8, FixedU128, FixedU16, FixedU32, FixedU64, FixedU8, }; use az::{Cast, CheckedCast, OverflowingCast, SaturatingCast, StaticCast, WrappingCast}; use core::mem; #[cfg(feature = "f16")] us...
use crate::{ types::extra::{LeEqU128, LeEqU16, LeEqU32, LeEqU64, LeEqU8}, FixedI128, FixedI16, FixedI32, FixedI64, FixedI8, FixedU128, FixedU16, FixedU32, FixedU64, FixedU8, }; use az::{Cast, CheckedCast, OverflowingCast, SaturatingCast, StaticCast, WrappingCast}; use core::mem; #[cfg(feature = "f16")] us...
(i32, u32), (i64, u64), (i128, u128), (isize, usize), } )* }; } compile_time_int! { FixedI8, FixedU8(LeEqU8), FixedI16, FixedU16(LeEqU16), FixedI32, FixedU32(LeEqU32), FixedI64, FixedU64(LeEqU64), FixedI128, FixedU128(LeEqU128), } macro_rules!...
m! { $Fixed($LeEqU); i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64, } #[cfg(feature = "f16")] run_time_num! { $Fixed($LeEqU); f16, bf16, } )* }; } run_time_num! { FixedI8(LeEqU8), ...
random
[ { "content": "// ceil(i × log_10 2), works for input < 112_816\n\nfn ceil_log10_2_times(int_bits: u32) -> u32 {\n\n debug_assert!(int_bits < 112_816);\n\n ((u64::from(int_bits) * 0x4D10_4D43 + 0xFFFF_FFFF) >> 32) as u32\n\n}\n\n\n\npub(crate) trait Mul10: Sized {\n\n fn mul10_assign(&mut self) -> u8;\n...
Rust
service_crategen/src/commands/generate/mod.rs
richard-hulm/rusoto
e5f8c9746d82dc71d055577c55cef9f0847fd998
use std::collections::BTreeMap; use std::fs::{self, OpenOptions}; use std::io::{BufWriter, Read, Write}; use std::path::Path; use std::process::Command; use rayon::prelude::*; use toml; mod codegen; use crate::cargo; use crate::{Service, ServiceConfig, ServiceDefinition}; fn generate_examples(crate_dir_path: &Path)...
use std::collections::BTreeMap; use std::fs::{self, OpenOptions}; use std::io::{BufWriter, Read, Write}; use std::path::Path; use std::process::Command; use rayon::prelude::*; use toml; mod codegen; use crate::cargo; use crate::{Service, ServiceConfig, ServiceDefinition}; fn generate_examples(crate_dir_path: &Path)...
et mut readme_file = BufWriter::new( OpenOptions::new() .write(true) .truncate(true) .create(true) .open(crate_dir.join("README.md")) .expect("Unable to write README.md") ); writeln!(readme_file, r#" # Rusoto {short_name} Rust SDK ...
"Generating crate for {} @ {}...", service.full_name(), service.api_version()); if !crate_dir.exists() { fs::create_dir(&crate_dir).unwrap_or_else(|_| panic!("Unable to create directory at {}", crate_dir.display())); } let mut features = BTreeMap::new(); features.insert("de...
random
[ { "content": "pub fn generate_source(service: &Service<'_>, writer: &mut FileWriter) -> IoResult {\n\n // EC2 service protocol is similar to query but not the same. Rusoto is able to generate Rust code\n\n // from the service definition through the same QueryGenerator, but botocore uses a special class.\...
Rust
src/visitor.rs
sunshowers/syn-inline-mod
6be2c6a05153585e489e2ae004b42d7124691c40
use std::borrow::Cow; use std::path::Path; use syn::visit_mut::VisitMut; use syn::ItemMod; use crate::{FileResolver, FsResolver, ModContext, SourceLocation}; pub(crate) struct Visitor<'a, R: Clone> { path: &'a Path, root: bool, mod_context: ModContext, resolver: Cow<'a, ...
use std::borrow::Cow; use std::path::Path; use syn::visit_mut::VisitMut; use syn::ItemMod; use crate::{FileResolver, FsResolver, ModContext, SourceLocation}; pub(crate) struct Visitor<'a, R: Clone> { path: &'a Path, root: bool, mod_context: ModContext, resolver: Cow<'a, ...
string(), quote! { mod c { const PATH: &str = "./c.rs"; } } .to_string() ); } #[test] fn path_attr() { let path = std::path::Path::new("./lib.rs"); let mut visitor = Visitor::<PathCommentResolver...
ath::new("./lib.rs"); let mut visitor = Visitor::<PathCommentResolver>::new(&path, true, None); let mut file = syn::parse_file("mod c;").unwrap(); visitor.visit_file_mut(&mut file); assert_eq!( file.into_token_stream().to_
function_block-random_span
[ { "content": "/// Parse the source code in `src_file` and return a `syn::File` that has all modules\n\n/// recursively inlined.\n\n///\n\n/// This is equivalent to using an `InlinerBuilder` with the default settings.\n\npub fn parse_and_inline_modules(src_file: &std::path::Path) -> syn::File {\n\n InlinerBui...
Rust
lib/wasi/src/utils.rs
john-sharratt/wasmer
271e772030bb57ec9c07c641d2c1de85aac688bd
use super::types::*; use std::collections::BTreeSet; use wasmer::Module; #[allow(dead_code)] pub fn is_wasi_module(module: &Module) -> bool { get_wasi_version(module, false).is_some() } pub fn map_io_err(err: std::io::Error) -> __wasi_errno_t { use std::io::ErrorKind; match err.kind() { ErrorKind...
use super::types::*; use std::collections::BTreeSet; use wasmer::Module; #[allow(dead_code)] pub fn is_wasi_module(module: &Module) -> bool { get_wasi_version(module, false).is_some() } pub fn map_io_err(err: std::io::Error) -> __wasi_errno_t { use std::io::ErrorKind; match err.kind() { ErrorKind...
ue; } } } if strict && non_wasi_seen { None } else { Some(out) } } #[cfg(test)] mod test { use super::*; #[test] fn wasi_version_equality() { assert_eq!(WasiVersion::Snapshot0, WasiVersion::Snapshot0); assert_eq!(WasiVersion::Snapshot1, W...
out.insert(WasiVersion::Snapshot0); } SNAPSHOT1_NAMESPACE => { out.insert(WasiVersion::Snapshot1); } _ => { non_wasi_seen = tr
function_block-random_span
[ { "content": "pub trait Reg: Copy + Clone + Eq + PartialEq + Debug + Hash + Ord {\n\n fn is_callee_save(self) -> bool;\n\n fn is_reserved(self) -> bool;\n\n fn into_index(self) -> usize;\n\n fn from_index(i: usize) -> Result<Self, ()>;\n\n fn iterator() -> Iter<'static, Self>;\n\n fn to_dwarf(...
Rust
src/built_ins/inkey.rs
ngeor/rusty-basic
865bbdf424931c0360e62cc139eba15c733d60ee
pub mod linter { use crate::common::QErrorNode; use crate::linter::arg_validation::ArgValidation; use crate::parser::ExpressionNode; pub fn lint(args: &Vec<ExpressionNode>) -> Result<(), QErrorNode> { args.require_zero_arguments() } } pub mod interpreter { use crate::built_ins::BuiltIn...
pub mod linter { use crate::common::QErrorNode; use crate::linter::arg_validation::ArgValidation; use crate::parser::ExpressionNode; pub fn lint(args: &Vec<ExpressionNode>) -> Result<(), QErrorNode> { args.require_zero_arguments() } } pub mod interpreter { use crate::built_ins::BuiltIn...
#[test] fn test_mapping_uppercase_letters() { for ch in 'A'..'Z' { assert_eq!( handle_key(KeyCode::Char(ch), KeyModifiers::SHIFT), String::from(ch) ); } } #[test] fn test_mapping_fu...
s() { for ch in 'a'..'z' { assert_eq!( handle_key(KeyCode::Char(ch), KeyModifiers::NONE), String::from(ch) ); } }
function_block-function_prefixed
[ { "content": "pub fn interpret_with_env<T, F>(input: T, mut initializer: F) -> MockInterpreter\n\nwhere\n\n T: AsRef<[u8]> + 'static,\n\n F: FnMut(&mut MockInterpreter) -> (),\n\n{\n\n let (instruction_generator_result, user_defined_types) =\n\n generate_instructions_str_with_types(input);\n\n ...
Rust
ensicoin-serializer/src/deserializer.rs
EnsicoinDevs/ensicoin-serializer
9e16c70654685c398ab909f3590e6d190459dc89
use super::types::Sha256Result; use super::types::VarUint; use bytes::BytesMut; use std::net::{IpAddr, Ipv6Addr, SocketAddr}; #[derive(Debug)] pub enum Error { Message(String), BufferTooShort(&'static str, usize, usize), InvalidString(std::string::FromUtf8Error), } impl std::fmt::Display for Error {...
use super::types::Sha256Result; use super::types::VarUint; use bytes::BytesMut; use std::net::{IpAddr, Ipv6Addr, SocketAddr}; #[derive(Debug)] pub enum Error { Message(String), BufferTooShort(&'static str, usize, usize), InvalidString(std::string::FromUtf8Error), } impl std::fmt::Display for Error {...
#[test] fn deserialize_u32() { let mut v = Vec::new(); v.push(42); v.push(43); v.push(44); v.push(45); let mut de = Deserializer { buffer: BytesMut::from(v), }; let decoded = de.deserialize_u32().unwrap(); assert_eq!(707472429...
fn deserialize_u64() { let mut v = Vec::new(); v.push(42); v.push(43); v.push(44); v.push(45); v.push(46); v.push(47); v.push(48); v.push(49); let mut de = Deserializer { buffer: BytesMut::from(v), }; let decoded...
function_block-full_function
[ { "content": "pub fn hash_to_string(hash: &Sha256Result) -> String {\n\n hash.iter()\n\n .fold(String::new(), |acc, b| format!(\"{}{:02x}\", acc, b))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::hash_to_string;\n\n use crate::Sha256Result;\n\n\n\n #[test]\n\n fn zero_hash() {\n\n...
Rust
src/pattern.rs
kjvalencik/skia-canvas
21c33be552a3d2702185c72f36effff64cd58980
#![allow(unused_mut)] #![allow(unused_imports)] #![allow(unused_variables)] #![allow(non_snake_case)] #![allow(dead_code)] use std::cell::RefCell; use std::sync::{Arc, Mutex}; use neon::prelude::*; use skia_safe::{Shader, TileMode, TileMode::{Decal, Repeat}, SamplingOptions, Size, Image as SkImage, Pict...
#![allow(unused_mut)] #![allow(unused_imports)] #![allow(unused_variables)] #![allow(non_snake_case)] #![allow(dead_code)] use std::cell::RefCell; use std::sync::{Arc, Mutex}; use neon::prelude::*; use skia_safe::{Shader, TileMode, TileMode::{Decal, Repeat}, SamplingOptions, Size, Image as SkImage, Pict...
pub fn repr(mut cx: FunctionContext) -> JsResult<JsString> { let this = cx.argument::<BoxedCanvasPattern>(0)?; let mut this = this.borrow_mut(); let stamp = Arc::clone(&this.stamp); let stamp = stamp.lock().unwrap(); let style = if stamp.image.is_some(){ "Bitmap" }else{ "Canvas" }; Ok(cx.string(format!("...
let this = cx.argument::<BoxedCanvasPattern>(0)?; let matrix = matrix_arg(&mut cx, 1)?; let mut this = this.borrow_mut(); let stamp = Arc::clone(&this.stamp); let mut stamp = stamp.lock().unwrap(); stamp.matrix = matrix; Ok(cx.undefined()) }
function_block-function_prefix_line
[ { "content": "pub fn bool_arg_or(cx: &mut FunctionContext, idx: usize, default:bool) -> bool{\n\n match opt_bool_arg(cx, idx){\n\n Some(v) => v,\n\n None => default\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 2, "score": 333991.19107456284 }, { "content": "pub fn get_imag...
Rust
crates/futures-rs_01/src/sink/fanout.rs
Zha0Chan/crates-sgx
73dc6d9e130757d9e585ee757b3d94d5078512a9
use core::fmt::{Debug, Formatter, Result as FmtResult}; use core::mem::replace; use {Async, AsyncSink, Poll, Sink, StartSend}; pub struct Fanout<A: Sink, B: Sink> { left: Downstream<A>, right: Downstream<B> } impl<A: Sink, B: Sink> Fanout<A, B> { pub fn into_inner(self) -> (A, B) { ...
use core::fmt::{Debug, Formatter, Result as FmtResult}; use core::mem::replace; use {Async, AsyncSink, Poll, Sink, StartSend}; pub struct Fanout<A: Sink, B: Sink> { left: Downstream<A>, right: Downstream<B> } impl<A: Sink, B: Sink> Fanout<A, B> { pub fn into_inner(self) -> (A, B) { ...
} #[derive(Debug)] struct Downstream<S: Sink> { sink: S, state: AsyncSink<S::SinkItem> } impl<S: Sink> Downstream<S> { fn new(sink: S) -> Self { Downstream { sink: sink, state: AsyncSink::Ready } } fn is_ready(&self) -> bool { self.state.is_ready() } fn keep_flushing(&mu...
let left_async = self.left.close()?; let right_async = self.right.close()?; if left_async.is_ready() && right_async.is_ready() { Ok(Async::Ready(())) } else { Ok(Async::NotReady) } }
function_block-function_prefixed
[]
Rust
ormx-macros/src/table/parse.rs
baajur/ormx
4242dbe564cb8a668ce06f9d7528ba7addcd1318
use std::convert::TryFrom; use proc_macro2::Span; use syn::{Data, DeriveInput, Error, Ident, Result}; use crate::attrs::{parse_attrs, Insertable, TableAttr, TableFieldAttr}; use crate::utils::{missing_attr, set_once}; use super::{Table, TableField}; use crate::backend::Backend; use std::marker::PhantomData; macro_r...
use std::convert::TryFrom; use proc_macro2::Span; use syn::{Data, DeriveInput, Error, Ident, Result}; use crate::attrs::{parse_attrs, Insertable, TableAttr, TableFieldAttr}; use crate::utils::{missing_attr, set_once}; use super::{Table, TableField}; use crate::backend::Backend; use std::marker::PhantomData; macro_r...
none!( column, custom_type, get_one, get_optional, get_many, set, default ); for attr in parse_attrs::<TableFieldAttr>(&value.attrs)? { match attr { TableFieldAttr::Column(c) => set...
if reserved_ident { proc_macro_error::emit_warning!( ident.span(), "This is a reserved keyword, you might want to consider choosing a different name." ); }
if_condition
[]
Rust
server/src/human.rs
anguskwan/poker-rust-unity
e8c95bc0371a259ddfee34878319e0361abdce27
use std::sync::*; use std::thread; use std::net::TcpStream; use std::io::*; use player::*; use card::*; use std; pub struct Human { stream: Option<TcpStream>, msgs: Arc<Mutex<Vec<String>>>, name: Option<String>, dead: Arc<Mutex<bool>>, cards: Option<[Card; 2]>, money: i32, fold: bool, b...
use std::sync::*; use std::thread; use std::net::TcpStream; use std::io::*; use player::*; use card::*; use std; pub struct Human { stream: Option<TcpStream>, msgs: Arc<Mutex<Vec<String>>>, name: Option<String>, dead: Arc<Mutex<bool>>, cards: Option<[Card; 2]>, money: i32, fold: bool, b...
fn bet(&mut self, bet: i32){ if bet - self.bet > self.money { self.money = 0; }else{ self.money -= bet - self.bet; self.bet = bet; } } }
c::new())), name: None, dead: Arc::new(Mutex::new(false)), cards: None, money: 0, fold: false, bet: 0, }; Self::start_listening(stream_clone.unwrap(), human.msgs.clone(), human.dead.clone()); human } pub fn test_new...
random
[]
Rust
contract_test/json/src/lib.rs
60ke/wasm_contract_gen
47f1c42712c46ce7b7954ae0dfc4daacf789ecfc
#![no_std] #![allow(non_snake_case)] #![feature(proc_macro_hygiene)] use wasm_std::types::{U256, Address}; use wasm_mid; use lazy_static; use wasm2ct::types::*; use wasm2ct_derive::gen_contract; use wasm_std::{String}; use wasm2ct::types::{Stream,Sink}; use serde_json::{Result, Value}; use smallvec::{SmallVec, smallve...
#![no_std] #![allow(non_snake_case)] #![feature(proc_macro_hygiene)] use wasm_std::types::{U256, Address}; use wasm_mid; use lazy_static; use wasm2ct::types::*; use wasm2ct_derive::gen_contract; use wasm_std::{String}; use wasm2ct::types::{Stream,Sink}; use serde_json::{Result, Value}; use smallvec::{SmallVec, smallve...
rap(); let tar:String = v["name"].as_str().unwrap().into(); tar } fn ret_str(&mut self)->String{ let s1: TinyStr4 = "tEsT".parse().unwrap(); s1.to_ascii_uppercase().as_str().into() } } fn storage_write(key: &H256,a:String){ let mut sink = Sink::new(1); sink.p...
let data = "{\"name\":\"John Doe\",\"age\":43,\"phones\":[\"+44 1234567\",\"+44 2345678\"]}"; let v: Value = serde_json::from_str(data).unw
function_block-random_span
[ { "content": "/// Like [`call`], but this call and any of it's subcalls are disallowed to modify any storage.\n\n///\n\n/// It will return an error in this case.\n\n///\n\n/// [`call`]: fn.call.html\n\npub fn static_call(gas: u64, address: &Address, input: &[u8], result: &mut [u8]) -> Result<(), Error> {\n\n ...
Rust
src/int/mul.rs
varkor/compiler-builtins
9eafb677ada5c5c32873ca1c02a47feb64a87bb5
use core::ops; use int::Int; use int::LargeInt; trait Mul: LargeInt { fn mul(self, other: Self) -> Self { let half_bits = Self::BITS / 4; let lower_mask = !<<Self as LargeInt>::LowHalf>::ZERO >> half_bits; let mut low = (self.low() & lower_mask).wrapping_mul(other.low() & lower_mask); ...
use core::ops; use int::Int; use int::LargeInt; trait Mul: LargeInt { fn mul(self, other: Self) -> Sel
a.mulo(b, oflow) } } u128_lang_items! { #[lang = "i128_mul"] pub fn rust_i128_mul(a: i128, b: i128) -> i128 { __multi3(a, b) } #[lang = "i128_mulo"] pub fn rust_i128_mulo(a: i128, b: i128) -> (i128, bool) { let mut oflow = 0; let r = __muloti4(a, b, &mut oflow); ...
f { let half_bits = Self::BITS / 4; let lower_mask = !<<Self as LargeInt>::LowHalf>::ZERO >> half_bits; let mut low = (self.low() & lower_mask).wrapping_mul(other.low() & lower_mask); let mut t = low >> half_bits; low &= lower_mask; t += (self.low() >> half_bits).wrapping...
random
[ { "content": "fn mul<F: Float>(a: F, b: F) -> F\n\nwhere\n\n u32: CastInto<F::Int>,\n\n F::Int: CastInto<u32>,\n\n i32: CastInto<F::Int>,\n\n F::Int: CastInto<i32>,\n\n F::Int: WideInt,\n\n{\n\n let one = F::Int::ONE;\n\n let zero = F::Int::ZERO;\n\n\n\n let bits = F::BITS;\n\n let si...
Rust
samples/rust-app/src/lib.rs
bbolen/zephyr-rust
da9bf206355f7beb20df67ae116a1b6611b39838
#[macro_use] extern crate cstr; #[macro_use] extern crate log; extern crate zephyr_macros; extern crate zephyr; extern crate zephyr_logger; use std::cell::RefCell; use std::time::Duration; use core::ffi::c_void; use log::LevelFilter; use zephyr::device::DeviceSyscalls; use zephyr::mutex::*; use zephyr::semaphore::*...
#[macro_use] extern crate cstr; #[macro_use] extern crate log; extern crate zephyr_macros; extern crate zephyr; extern crate zephyr_logger; use std::cell::RefCell; use std::time::Duration; use core::ffi::c_void; use log::LevelFilter; use zephyr::device::DeviceSyscalls; use zephyr::mutex::*; use zephyr::semaphore::*...
}", *f.borrow()); assert!(*f.borrow() == 2); *f.borrow_mut() = 3; println!("main thread: now f = {}", *f.borrow()); assert!(*f.borrow() == 3); }); zephyr::user::k_str_out("Hello from Rust userspace with forced user-mode syscall\n"); zephyr::any::...
() { println!("std::sync::Mutex::new"); let lock = std::sync::Mutex::new(0u8); println!("std::sync::Mutex::lock"); *lock.lock().unwrap() = 1; } fn thread_join_std_mem_domain(_context: zephyr::context::Kernel) { use zephyr::context::Kernel as C; zephyr::static_mem_domain!(rust_std_domain).add_th...
random
[ { "content": "#!/usr/bin/env python3\n\n\n\nimport sys\n\n\n\ncount = int(sys.argv[1])\n\n\n\ninitializer = \"\\n\".join([f'\\tZ_MUTEX_INITIALIZER(rust_mutex_pool[{i}]),' for i in range(count)])\n\n\n\nsys.stdout.write(f'''\n\n#include <kernel.h>\n\n\n\nZ_STRUCT_SECTION_ITERABLE(k_mutex, rust_mutex_pool[{count}...
Rust
examples/mandelbrot/src/simd_par.rs
novacrazy/packed_simd
b05fbfd0f8f16741854099984a2b08a50b266cd5
#![allow(non_camel_case_types)] use crate::*; use packed_simd::*; type u64s = u64x8; type u32s = u32x8; type f64s = f64x8; type m64s = m64x8; #[derive(Copy, Clone)] struct Complex { real: f64s, imag: f64s, } impl Complex { #[inline] fn undiverged(&self) -> m64s { let Self { real: ...
#![allow(non_camel_case_types)] use crate::*; use packed_simd::*; type u64s = u64x8; type u32s = u32x8; type f64s = f64x8; type m64s = m64x8; #[derive(Copy, Clone)] struct Complex { real: f64s, imag: f64s, } impl Complex { #[inline] fn undiverged(&self) -> m64s { let Self { real: ...
t y = f64s::splat(yr.start + dy * (i as f64)); row.iter_mut().enumerate().for_each(|(j, count)| { let x = xs[j]; let z = Complex { real: x, imag: y }; *count = MandelbrotIter::new(z).count(); }); }); unsafe { let mut out: Vec<u32> = std::mem::transmut...
Self { start, current: start } } fn count(mut self) -> u32s { let mut z = self.start; let mut count = u64s::splat(0); for _ in 0..ITER_LIMIT { let undiverged = z.undiverged(); ...
random
[ { "content": "pub fn slice(x: &[f32]) -> f64 {\n\n assert_eq!(f32s::lanes(), f64s::lanes());\n\n assert_eq!(x.len() % f32s::lanes(), 0);\n\n\n\n let mut sum = f64s::splat(0.);\n\n for i in (0..x.len()).step_by(f32s::lanes()) {\n\n unsafe {\n\n use packed_simd::Cast;\n\n ...
Rust
backend/src/schema.rs
ruslansalikhov/exonum-cryptocurrency-multisig
07461d79ac936c8289674a369e3e9cc77ba83674
use exonum::{ crypto, crypto::{Hash, PublicKey}, storage::{Fork, ProofListIndex, ProofMapIndex, Snapshot}, }; use crate::{wallet::Wallet, transferproposal::TransferProposal, INITIAL_BALANCE}; #[derive(Debug)] pub struct Schema<T> { view: T, } impl<T> AsMut<T> for Schema<T> { fn as_mut(&mut self...
use exonum::{ crypto, crypto::{Hash, PublicKey}, storage::{Fork, ProofListIndex, ProofMapIndex, Snapshot}, }; use crate::{wallet::Wallet, transferproposal::TransferProposal, INITIAL_BALANCE}; #[derive(Debug)] pub struct Schema<T> { view: T, } impl<T> AsMut<T> for Schema<T> { fn as_mut(&mut self...
ash) }; self.wallets_mut().put(&crypto::hash(name.as_bytes()), wallet); } pub fn create_transfer_proposal(&mut self, from: &String, to: &String, amount: u64, seed: u64) { let transfer_proposal = TransferProposal::new(from, to, amount, seed, 1); self.transfer_proposals_mut()...
}; self.wallets_mut().put(&crypto::hash(wallet.name.as_bytes()), wallet.clone()); } pub fn decrease_wallet_balance(&mut self, wallet: Wallet, amount: u64, transaction: &Hash) { let wallet = { let mut history = self.wallet_history_mut(&crypto::hash(wallet.name.as_bytes...
random
[ { "content": "#[test]\n\nfn test_create_wallet() {\n\n let (mut testkit, api) = create_testkit();\n\n // Create and send a transaction via API\n\n let (tx, _, _) = api.create_wallet(ALICE_NAME, 1, 1);\n\n testkit.create_block();\n\n api.assert_tx_status(tx.hash(), &json!({ \"type\": \"success\" }...