lang
stringclasses
10 values
seed
stringlengths
5
2.12k
rust
let mut rate = 1000; let mut off = 0; let mut avail = INBLOCK as isize; let fin: Vec<f32> = (0..INBLOCK * 2) .map(|i| ((i as f32) / PERIOD * 2.0 * PI).sin() * 0.9) .collect(); let mut fout = vec![0f32; INBLOCK * 4]; let st = unsafe { speex_resampler_init(1, RATE, RATE, 4, ptr::null_mut()) }; unsafe { speex_resampler_set_rate(st, RATE, rate) }; unsafe { speex_resampler_skip_zeros(st) }; loop {
rust
// check client heartbeats if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT { // heartbeat timed out log::error!("Websocket Client heartbeat failed, disconnecting!"); // stop actor ctx.stop(); act.monitor_address.do_send( DeRegisterGPSWebSocketClient{uuid: act.uuid} ); // don't try to send a ping
rust
test_utils::check_lsra("lsra_split_unused", 5, 2); } #[test] fn lsra_split_unused_2() { test_utils::check_lsra("lsra_split_unused_2", 5, 2);
rust
pub const TCA_ROOT_TIME_DELTA: int = 4; pub const EM_NONE: u32 = 0; pub const EM_M32: u32 = 1; pub const EM_SPARC: u32 = 2; pub const EM_386: u32 = 3; pub const EM_68K: u32 = 4; pub const EM_88K: u32 = 5; pub const EM_486: u32 = 6; pub const EM_860: u32 = 7; pub const EM_MIPS: u32 = 8;
rust
printf: Arc<Mutex<sudo_plugin_sys::sudo_printf_non_null_t>>, _conversation: sudo_plugin_sys::sudo_conv_t, } impl Plugin { /// Initializes a `Plugin` from the arguments provided to the /// underlying C `open` callback function. Verifies the API version /// advertised by the underlying `sudo` is supported by this library, /// parses all provided options, and wires up communication
rust
#[test] fn echo_function() { let mut tr = crate::TemplateRenderer::with_template("<!$ echo test>"); tr.set_placeholder_fn("echo", Box::new(Echo())); assert_eq!(tr.render().unwrap(), "test"); tr.set_template("<!$ echo test with spaces> and extra text"); assert_eq!(tr.render().unwrap(), "test with spaces and extra text"); } struct Counter(usize); impl crate::PlaceholderFunction for Counter { fn placeholder_fn_handler<'a>(&mut self, _name: &'a str, _arg: &'a str) -> Result<String, String> {
rust
mod overflowing_add; mod overflowing_sub; use super::*;
rust
} it "should add edge to graph" { expect!(graph.edges()).to(be_equal_to(1)); }
rust
fn lol() { //~ ERROR incorrect function inside `extern` block println!(""); } } fn main() {}
rust
panic!("$ref not supported yet"); } }; let content_diff = ContentDiff::from_content(&base_response.content, &head_response.content); if content_diff.has_changes() { Self {
rust
match Ed25519Verify::execute(&input, cost) { Ok((_, _)) => { panic!("Test not expected to pass"); } Err(e) => { assert_eq!(e, ExitError::Other("input must contain 128 bytes".into())); Ok(())
rust
} extern "C" { pub fn BeginMode3D(camera: Camera3D); } extern "C" { pub fn EndMode3D(); } extern "C" { pub fn BeginTextureMode(target: RenderTexture2D); }
rust
///Memory can be read from this address up to `<base> + <region size>` /// ///You can get this pointer by accessing inner structure `self.0.BaseAddress` pub fn base_addr(&self) -> usize { self.0.BaseAddress as usize } #[inline] ///Returns Allocation base. /// ///You can get this pointer by accessing inner structure `self.0.AllocationBase` pub fn alloc_base(&self) -> usize { self.0.AllocationBase as usize }
rust
pub_date.timestamp(), author, image, subtitle, summary, content, duration,
rust
/// identify the source of a fragment #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub enum FragmentOrigin { /// trace back the origin of a fragment to a given /// network node. This will allow tracking back the /// origins of the fragment and eventually blacklisting
rust
/// A cheap conversion to a `CSlice`. pub trait AsCSlice<'a, T> { /// Performs the conversion. fn as_c_slice(&'a self) -> CSlice<'a, T>; } /// A cheap conversion to a `CMutSlice`. pub trait AsCMutSlice<'a, T> { /// Performs the conversion. fn as_c_mut_slice(&'a mut self) -> CMutSlice<'a, T>;
rust
return is_integer(num); } false } fn name(&self) -> String { "type: integer".to_string() } } fn is_integer(num: &Number) -> bool {
rust
use std::any::Any; use std::hash::Hash; use std::{convert::Infallible, path::PathBuf}; use thiserror::Error; use crate::Uri; /// Possible Errors when interacting with `lychee_lib` #[derive(Error, Debug)] #[non_exhaustive]
rust
// Need to move old range to a new range and init the new range let vm_initializer_for_new_range = { let copy_end = vma.end(); let copy_range = VMRange::new(old_range.start(), copy_end)?; let reread_file_start_offset = copy_end - vma.start(); VMInitializer::CopyOldAndReadNew {
rust
try!(self.put_rule(&self.config.rule)); try!(self.put_ecs_task_target( role_arn, ecs_cluster_arn, task_definition_arn, &self.config, )); output::PrintLine::success("Finished putting the scheduled task"); Ok(()) } }
rust
fn into(self) -> String { self.0.into_string() } } #[cfg(has_string_into_boxed_string)]
rust
// Copyright 2022 EinsteinDB Project Authors. Licensed under Apache-2.0. //! Type definitions mod eval_type; mod field_type; pub use self::eval_type::EvalType;
rust
} impl TryFrom<&[u8]> for Address { type Error = (); fn try_from(b: &[u8]) -> Result<Self, Self::Error> {
rust
#[clap(short, long, default_value = "ws://tokera.sh/db")] pub db_url: url::Url, /// URL of the authentication servers #[clap(long, default_value = "ws://tokera.sh/auth")] pub auth_url: url::Url, /// URL of the session servers that clients will connect to #[clap(long, default_value = "ws://tokera.sh/inst")] pub inst_url: url::Url, /// Ensures that this combined server(s) runs as a specific node_id #[clap(short, long)] pub node_id: Option<u32>, /// Location where the native binary files are stored
rust
pub underlying_provision_cash_settl_payment_date_type: Option<UnderlyingProvisionCashSettlPaymentDateType>, } #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)] pub enum UnderlyingProvisionCashSettlPaymentDateType { /// Unadjusted #[serde(rename = "0")] Unadjusted, /// Adjusted #[serde(rename = "1")]
rust
pub mod shared_obj; pub mod thread_test;
rust
} } /// Generate diagnostics for dependencies of a module, attempting to resolve /// dependencies on the local file system or in the DENO_DIR cache. async fn generate_deps_diagnostics( snapshot: Arc<language_server::StateSnapshot>, collection: Arc<Mutex<DiagnosticCollection>>, ) -> Result<DiagnosticVec, AnyError> { tokio::task::spawn(async move { let mut diagnostics_vec = Vec::new(); for document in snapshot.documents.documents(true, true) { if !snapshot.config.specifier_enabled(document.specifier()) { continue;
rust
async fn main() { server(([127, 0, 0, 1],19999).into()).await; }
rust
fn bench_sin_angle(c: &mut Criterion) { c.bench_function("sin_angle", |b| { b.iter(|| black_box(Angle::pi()).sin::<f64>()) }); } fn bench_sin_builtin(c: &mut Criterion) { c.bench_function("sin_buitin", |b| b.iter(|| black_box(f64::pi()).sin())); }
rust
} } impl From<IoError> for Error { fn from(err: IoError) -> Self { Error::Io(err)
rust
stdin() .read_line(&mut shelf_answer) .expect("Failed to read your input"); &shelf_answer });
rust
let mut program = aoc_2019_2::read_memory_from_file("input.txt"); program[0] = 2; let mut vacuum_cleaner = aoc_2019_17::VacuumCleaner::new(&program); vacuum_cleaner.execute(); } fn solve_part_one() { let program = aoc_2019_2::read_memory_from_file("input.txt"); let scaffolding = aoc_2019_17::Scaffolding::new(&program); let map = scaffolding.extract_scaffolding().unwrap(); let intersections = aoc_2019_17::find_intersections(&map); let result: isize = intersections .iter() .map(|&aoc_common::math::Point(x, y)| x * y)
rust
// run-fail // error-pattern: thread 'main' panicked at '`async fn` resumed after completion' // edition:2018 // ignore-wasm no panic or subprocess support // ignore-emscripten no panic or subprocess support
rust
/// Adds memory tracking for [`Image`] assets. #[derive(Debug, Default)] pub struct ImageMemoryUsagePlugin; impl Plugin for ImageMemoryUsagePlugin { fn build(&self, app: &mut bevy::prelude::App) { app.register_asset_with_estimator::<Image, ImageSizeEstimator>(); } } #[derive(Debug, Default)] struct ImageSizeEstimator; impl DataSizeEstimator<Image> for ImageSizeEstimator {
rust
/// /// The second form uses a base expression and then a series of "when" clauses that match on a /// literal value. /// /// CASE expression /// WHEN value THEN result /// [WHEN ...] /// [ELSE result] /// END Case { /// Optional base expression that can be compared to literal values in the "when" expressions expr: Option<Box<Expr>>, /// One or more when/then expressions when_then_expr: Vec<(Box<Expr>, Box<Expr>)>,
rust
//! //! Configuration errors return specific information to help //! the developer to build correct code. All runtime errors //! return the generic empty `Error` struct, because granular //! error reporting in cryptographic libraries can be fraught. use std::fmt;
rust
use crate::temporal::api::workflowservice::v1::workflow_service_client::WorkflowServiceClient; type ServiceClient = WorkflowServiceClient<tonic::transport::Channel>; struct Poller { client: WorkflowServiceClient<tonic::transport::Channel>, } type AsyncResult<'a> = Pin<Box<dyn Future<Output=Result<(), Box<dyn std::error::Error>>> + 'a>>;
rust
<gh_stars>0 use actix_web::error::ErrorNotFound; pub fn user_not_found() -> actix_web::Error { ErrorNotFound("USER_NOT_FOUND")
rust
use std::io::{Read, Write}; /// This string identifies a golden image, and must precede the magic string. const GOLDEN_STRING: &str = "XPIcbOUrpG"; /// This string, INVERTED BYTEWISE must terminate any valid image, before the signature. /// /// Note: Why inverted? Because if we used it as-is, no code that includes this /// constant could be used as a firmware image, as it contains the magic string /// halfway through. pub const MAGIC_STRING: &str = "HSc7c2ptydZH2QkqZWPcJgG3JtnJ6VuA";
rust
let mut transactions: Vec<Transaction> = vec![]; for result in self.file_csv.records() { if let Ok(row) = result { let sposted = row.get(pos_posted) .expect("Can't find the Posted At column"); let dtposted = NaiveDate::parse_from_str(sposted, "%Y-%m-%d") .expect("Cant't parse the posted at date"); let samount = row.get(pos_amount) .expect("Can't find the amount column"); let mut amount = samount.replace(",", ".").parse::<f32>() .expect("Can't parse the amount value");
rust
} } Err(_) => { return Value::Error { error: ShellError::UnsupportedInput( "Cannot convert input string as datetime. Might be missing timezone or offset".to_string(), *span, ), } } }, }; out }
rust
} } println!( "Percentile {}: {} ({}/{})", percentile, Local .timestamp(percentile_timestamp, 0) .format("%Y/%m/%d") .to_string(), sum, total_sims ); }
rust
assert_eq!( Var(0).whnf(Subst::comp( Subst::comp(Subst::cons(Type::closure(Var(0), Id), Shift), Shift), Shift )), (Var(2), Id) ); assert_eq!( Var(1).whnf(Subst::comp( Subst::cons( Type::closure(Var(0), Id),
rust
pub fn dump_cpu_record(file_path: impl AsRef<Path>) { let f = File::create(file_path).unwrap(); let mut f = LineWriter::new(f); let data = CPU_RECORD.lock().unwrap(); for line in data.iter() { f.write(format!("{:?}\n", line).as_bytes()) .expect("write file failed"); } f.flush().expect("flush file failed"); }
rust
fn from_delta_table(path: &str) -> Result<DataFrame, DeltaTableError>; fn from_delta_table_with_version( path: &str, version: delta::DeltaDataTypeVersion, ) -> Result<DataFrame, DeltaTableError>; } impl DeltaDataframe for DataFrame { fn from_loaded_delta_table( delta_table: delta::DeltaTable, ) -> Result<DataFrame, DeltaTableError> { let mut batches = vec![];
rust
// 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
rust
&self.ty } fn validate(&self, params: &HashMap<String, Value>) -> Result<(), String> { if !params.contains_key("callback_url") { return Err("'callback_url' is missing.".to_string()); } Ok(()) } async fn trigger( &mut self,
rust
} use serde::de::Visitor; use std::fmt::Formatter; pub struct U64Visitor; impl Visitor<'_> for U64Visitor { type Value = u64; fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { formatter.write_str("64-bit unsigned integer") }
rust
//! It features flat-closures, as opposed to the standard linked-closure. //! This method is derived from Might et al.'s 2010 paper on the m-CFA algorithm. //! //! This is an Abstracted Abstract Machine, based off of the //! DVH paper of a similar name (see readme). //! //! Using this method, we have a polynomial CFA algorithm! //! //! I also use the continuation-allocator from Pushdown For Free by Gilray et al. //! This allows perfect stack precision for our continuation allocation. mod domains; mod evaluate; mod prims;
rust
const DEFAULT: Self; } trait Foo: Sized {} trait FooExt: Foo { type T: ConstDefault; } trait Bar<F: FooExt> { const T: F::T; } impl<F: FooExt> Bar<F> for () {
rust
Arc::new(VeryUnsafeCell::new( Obj { radios, parent_events: RadioGroupEvents::new(parent_ref, ctrl_ids), }, )), ); parent_ref.privileged_events_ref().wm(parent_ref.create_wm(), { let me = new_self.clone(); move |_| { me.create(); 0 } });
rust
.send(message) .await .map_err(|mailbox_error| { error::ErrorInternalServerError(format!("Failed to reach actor: {:?}", mailbox_error)) })? .map_err(|sgx_error| { error::ErrorInternalServerError(format!("Failed to call enclave: {:?}", sgx_error))
rust
use multiplayer::MultiplayerGame; /// /// Implements methods for server storage. /// #[tonic::async_trait] pub trait GameStore { /// Add game to storage. async fn add_game(&mut self, game : MultiplayerGame);
rust
} // single or double quotes Some('"') | Some('\'') => { pos += 1; let token_start = pos; let mut ch1 = iter.next(); loop { match ch1 { Some(ch2) => { pos += 1; ch1 = iter.next(); if ch2 == ch.unwrap() {
rust
} } doc.0.push(pulldown_cmark::Event::End(pulldown_cmark::Tag::List(None))); } } /// Convert a clap Command to markdown documentation. pub fn app_to_markdown(app: &Command, title: &str) -> Result<String> { let mut document = MarkdownDocument(Vec::new());
rust
code: OutputRaw("a\n".into()), }, Statement { position: lines(2, 1, 5, 1), code: Cond { indent: 0, conditional: vec![ (Expr {
rust
} else if packet % 3 == 0 { Some(1) } else if packet % 5 == 0 { Some(2) } else { Some(3) } } fn num_ports(&mut self) -> usize {
rust
use super::*; use crate::utils::test_tools::{ map_nested_to_string, map_to_string, assert_equivalent }; #[test] fn test_word_squares_1() { let input = map_to_string(&[ "area","lead","wall","lady","ball" ]); let output = map_nested_to_string( &[ vec![ "wall", "area", "lead", "lady"
rust
stop_dialog.set_title(Some(&format!("{} ({})", flg!("window_progress_title"), flg!("progress_stop_additional_message")))); send_stop_message(&stop_sender); } }); let button_stop_in_dialog = gui_data.progress_window.button_stop_in_dialog.clone(); let stop_dialog = gui_data.progress_window.window_progress.clone(); let stop_sender = gui_data.stop_sender.clone();
rust
#[test] fn encode_and_extract() { use super::*; use std::fs::File; use std::io::prelude::*; use file_diff::diff; let mut encoder = Encoder::new(); encoder.add_file("tempeh.jpg", Box::new(File::open("test/image/tempeh.jpg").unwrap())); encoder.add_file("imperial.ogg", Box::new(File::open("test/music/imperial.ogg").unwrap())); encoder.write(File::create("test/output/encode_and_read.pakt").unwrap());
rust
ClickTask, } pub fn update(msg: Msg, model: &mut Model) { match msg { Msg::ClickTask => {} } } pub fn view(model: &Model) -> Node<Msg> { div![ "Title",
rust
pub mod messages; pub mod retransmit; pub mod tree; pub mod udp; mod utils; pub use config::Config; pub use error::{Error, Result}; /// Trait used to serialize/deserialize data to/from wire pub trait Wire<'a>: Sized {
rust
// value conversion ratio - currently unsupported put_i64(0, target_buffer); let counts_payload_length = self.fill_buffer_from_counts_array(target_buffer);
rust
.with(d2, "D2", &[]); world.add_resource(EventChannel::<winit::Event>::new()); render::init::<ImageTarget>(&mut world, &mut dispatcher, dimensions, "D3", "D2"); let mut dispatcher = dispatcher.build(); dispatcher.run_now(&mut world.res); world.maintain();
rust
FibonacciFuture { a: 0, b: 1, i: 0, cnt, } } }
rust
portal_id: self.portal_id, input, }; self.events.borrow_mut().push_back(event); Ok(()) } } } #[cfg(target_os = "rust_os")]
rust
fn end_height(data: &Self::NodeData) -> u64 { data.v1.end_height } fn combine_inner( subtree_commitment: [u8; 32], left: &Self::NodeData, right: &Self::NodeData, ) -> Self::NodeData {
rust
bdd::SatResult::Error => panic!("SAT check error"), } } pub fn do_bddsat(f: &Formula) { let r = bddsat(f); let sr = cnf::write_sat_result(&r, &mut io::stdout()); sr.unwrap_or_else(|e| println!("{}", e)); let vr = cnf::write_sat_valid(f, &r, &mut io::stdout()); vr.unwrap_or_else(|e| println!("{}", e));
rust
} struct UserIP { command: String, nickname: String, }
rust
impl Solution { pub fn count_even(num: i32) -> i32 { let mut tmp: i32 = num; let mut check: i32 = 0; while (tmp > 0) { check += tmp % 10; tmp /= 10; }
rust
pub fn infnan(x: f64) -> bool; } } #[cfg(test)] mod test { use crate::utility; #[test] fn test_utility_minsd() { assert_eq!(utility::minsd(2.0, 3.0), 2.0) }
rust
f: &mut std::fmt::Formatter, tokens: TokenStream, ) -> std::fmt::Result { let mut tokens = tokens.into_iter().peekable(); let mut joint = false; let mut first = true; let mut plain_comment = false; while let Some(tt) = tokens.next() {
rust
fn split_file(data: FileSlice) -> io::Result<(FileSlice, FileSlice)> { let (data, footer_len_bytes) = data.split_from_end(size_of::<u64>()); let serialized_offset: OwnedBytes = footer_len_bytes.read_bytes()?; let mut serialized_offset_buf = serialized_offset.as_slice(); let offset = u64::deserialize(&mut serialized_offset_buf)? as usize; Ok(data.split(offset)) } #[cfg(test)]
rust
} /// A handler for GET /opds/v1.2/catalog. Returns an OPDS catalog as an XML document #[get("/catalog")] pub fn catalog(_ctx: &Context, _auth: StumpAuth) -> ApiResult<XmlResponse> { let entries = vec![ OpdsEntry::new( "keepReading".to_string(), chrono::Utc::now().into(), "Keep Reading".to_string(), Some(String::from("Continue reading your in progress books")), None, Some(vec![OpdsLink { link_type: OpdsLinkType::Navigation,
rust
if tmp == curr { break; } curr = tmp; } count } static mut mutator: *mut ImmixMutatorLocal = std::ptr::null::<ImmixMutatorLocal>() as *mut ImmixMutatorLocal;
rust
// UNSAFE: We're using FFI, so we don't know how the pointer is used. // Hopefully, the JavaScript-side should clone that value synchronously. // // Also, we're transmuting so that &(f64, f64) is actually treated like // a *const u8 (immutable raw pointer to an u8) as it's what the JS // callback expects. This should not matter: Rust types are not // communicated to JavaScript anyway. unsafe { onAttribute(attr_name, mem::transmute(self), 16); }; } }
rust
if action.is_err() { // cannot pass any data from action.error here - ends up with // "FnOnce called more than once" error from wasm-bindgen for // "foreign_call" testcase. result = Err(RuntimeError("Error while parsing input".to_string())); } else { // not sure about clone here let current_state = STATE.with(|service| service.borrow().clone()); result = match action.unwrap() { Action::Transfer { qty, target } => transfer(current_state, qty, target),
rust
fn ok_struct(struct1: Struct) { let _ = struct1; let Struct { field1, field2, .. } = struct1; let Struct { field1, field2 } = struct1;
rust
{ //if values.map.is_empty() { // return Err(Error::EmptyPackage); //} self.write_and_wait(b"=begin="); let packet_size = P::to_usize(); let vl_size : usize = NAME_SZ+4+packet_size*4;
rust
let parent = parent.clone(); self.store_individual_coalescence(&dispersal.global_lineage_reference, &parent, dispersal.prior_time); } } } else if let Some(parent) = dispersal.interaction.parent() { self.store_individual_coalescence(&dispersal.global_lineage_reference, &parent, dispersal.event_time.into()); } self.last_dispersal_event = Some(dispersal.clone()); self.last_parent_prior_time = Some( (dispersal.global_lineage_reference.clone(), dispersal.prior_time) );
rust
timestamper.insert(row).await.map_err(|e| SourceError { source_name: source_name.clone(), error: SourceErrorDetails::FileIO(e.to_string()), })?; } } info!(
rust
/// An iterator over shared references to the elements of the `BinaryHeap`. #[derive(Debug, Clone, Copy)] pub struct Iter<'a, T> where T: PackedLayout + Ord, { /// The heap elements to iterate over. elements: &'a ChildrenVec<T>,
rust
#[derive(Clone, Debug, PartialEq)] pub struct Extension { pub t: i8, pub data: Vec<u8>, }
rust
} } impl<T> Stream for Collector<T> where T: Scraper + Unpin + 'static, <T as Scraper>::State: Unpin + Send + Sync + 'static, <T as Scraper>::Output: Unpin, { type Item = Result<T::Output>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let pin = self.get_mut(); loop {
rust
use std::cmp::Ordering; use std::str::FromStr; use std::num::Wrapping; const MIN: u32 = 0; const MAX: u32 = 5; fn main(){ let input = std::io::stdin(); let value = generate_number(); loop {
rust
} pub fn slice_to_fake_arr<'a>(slice: &'a [u8]) -> FakeArrRef<'a> { FakeArrSlice { real: Wtfisthis::Slic(slice), offset: 0, len: slice.len() as Ulen,
rust
#[derive(Debug, Default, Clone, Copy, PartialEq)] pub struct Frame2 { pub x: Frame, pub y: Frame, } #[derive(Debug, Default, Clone, Copy, PartialEq)] pub struct Frame { pub view: Range, pub bounds: Range, }
rust
use crate::lexer::Lexer; use crate::parser::parse; static PROMPT: &str = ">>"; pub struct Repl<O: Write> {
rust
//TODO: for each lifeline make an automaton // to do so hide all other lifelines, canonize the remainder and inductively build the automaton for lf_id in 0..gen_ctx.get_lf_num() { let lf_name = gen_ctx.get_lf_name(lf_id).unwrap(); let mut lfs_to_remove : HashSet<usize> = (0..(gen_ctx.get_lf_num())).collect(); lfs_to_remove.remove(&lf_id);
rust
pub fn to_bytes<T: Num>(numbers: &[T]) -> &[u8] { let size = numbers.len() * std::mem::size_of::<T>(); unsafe { std::slice::from_raw_parts(numbers.as_ptr() as *const _, size) } } pub fn from_bytes<T: Num>(bytes: &[u8]) -> &[T] { let size = bytes.len() / std::mem::size_of::<T>(); unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const _, size) }
rust
use rand::{prelude::SliceRandom, thread_rng}; use rayon_logs::prelude::*; use rayon_logs::ThreadPoolBuilder; fn main() { let mut ra = thread_rng(); let mut v: Vec<u32> = (0..100_000).collect(); let answer = v.clone(); v.shuffle(&mut ra); let p = ThreadPoolBuilder::new().build().expect("builder failed");
rust
use thiserror::Error; use vicuno::{Library, LibraryError}; #[derive(Debug, StructOpt)]
rust
// let mut first = true; // for b in data.iter() { // if first { first = false; } else { out.push(':'); } // out.push_str(&format!("{:02X}", *b)); // } // return out; // } // fn to_int_arr_str(data: &[u8]) -> String { // let mut out = String::new(); // let mut first = true; // for bytes in data.chunks(4) {
rust
//! let mut rtt = Rtt::attach(Arc::new(Mutex::new(session)))?; //! //! // Read from a channel //! if let Some(input) = rtt.up_channels().take(0) { //! let mut buf = [0u8; 1024]; //! let count = input.read(&mut buf[..])?; //! //! println!("Read data: {:?}", &buf[..count]); //! } //! //! // Write to a channel //! if let Some(output) = rtt.down_channels().take(0) {
rust
const K: usize = 13; const KMER_SPACE: usize = 4_usize.pow(K as u32); const BLOCK_SIZE: u64 = 2u64.pow(16); in_place_fastx::fastq_sequential!(
rust
Enum { type_name: u16, const_name: u16 }, Class(u16), Annotation(Annotation), Array(Vec<ElementValue>), } #[derive(Clone, Debug)] pub struct TypeAnnotation { pub target: TypeAnnotationTarget, pub path: Vec<TypePathSegment>, pub annotation: Annotation,
rust
//! Test 2 : evaluate solver speed with the different methods //! //! Reference results : //! //! Solver parsing :
rust
} } impl<'a, W: Write> DerefMut for Indented<'a, W> { fn deref_mut(&mut self) -> &mut Formatter<W> { self.0 }
rust
} impl Parse for CtrsInput { fn parse(stream: ParseStream) -> Result<Self> { stream.parse::<Token![macro]>()?; stream.parse::<Token![crate]>()?; let name = stream.parse::<Ident>()?; stream.parse::<Token![;]>()?; let mut items = <Vec<Item>>::new(); while !stream.is_empty() { items.push(stream.parse()?); } Ok(CtrsInput {name, items})
rust
//! Version 1 of Ocean's web API. /// The default URL to which API calls are made: `https://api.oceanpkg.org/v1/`. pub const DEFAULT_URL: &str = "https://api.oceanpkg.org/v1/"; #[cfg(feature = "reqwest")] mod download; #[cfg(feature = "reqwest")] mod login; #[cfg(feature = "reqwest")] mod ship; #[cfg(feature = "reqwest")]