lang
stringclasses
10 values
seed
stringlengths
5
2.12k
rust
use std::process::Command; fn main() { let status = Command::new("ping").arg("-c 3").arg("8.8.8.8").status().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) }); println!("process exited with: {}", status); } fn get_addr() { }
rust
let mut pyld = Payload::new(); let mut points = Vec::with_capacity(1024); for _ in 0..rng.gen_range::<usize>(0, 100) { let mut telem = Telemetry::new(); telem.set_name(rng.choose(&name_cache).unwrap().to_string()); let smpl_top = rng.gen_range::<usize>(0, 10); let mut smpls = Vec::with_capacity(smpl_top); for _ in 0..smpl_top { smpls.push(rng.gen::<f64>()) }
rust
// let _terminal = init_terminal(renderer); let mut executor = Executor::new(); executor.spawn(Task::new(keyboard::print_keypresses())); executor.run(); } loop {}
rust
} impl P2InlineAsmReg { pub fn emit( self, out: &mut dyn fmt::Write, _arch: InlineAsmArch, _modifier: Option<char>, ) -> fmt::Result { out.write_str(self.name()) } }
rust
#[cfg(target_arch = "wasm32")] mod wasm; #[cfg(target_arch = "wasm32")] pub use wasm::*; mod next_vec; pub use next_vec::*;
rust
edge_pos: usize, } #[derive(Debug, Clone)] pub struct SuffixTree<'t> { word: Cow<'t, str>,
rust
impl View for State { fn view<L: Layout>(&self, layout: &mut L, ctx: &mut RenderContext) { let mut layout = ColumnLayout::new(layout, ctx); layout.add(Label::new(self.path)); layout.spacing(10.0); { let mut row = RowLayout::new(layout, ctx) } } }
rust
fn power_consumption(numbers: &mut [u16]) { // Assume that the leading digit in the original input is not 0 let digits = count_binary_digits(*numbers.iter().max().unwrap());
rust
use std::io; pub(super) fn run() -> io::Result<()> { unimplemented!() }
rust
let mut split = line.split(" => "); let lhs = split.next().unwrap(); let rhs = split.next().unwrap(); let (name, units) = split_f(rhs); let requires: Vec<Chemical> = lhs .split(", ") .map(split_f) .map(|(name, units)| Chemical { name, units }) .collect();
rust
} } } #[cfg(any(feature = "v1_18", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_18")))] #[doc(hidden)] impl FromGlib<ffi::GstAggregatorStartTimeSelection> for AggregatorStartTimeSelection { unsafe fn from_glib(value: ffi::GstAggregatorStartTimeSelection) -> Self { skip_assert_initialized!(); match value { ffi::GST_AGGREGATOR_START_TIME_SELECTION_ZERO => Self::Zero, ffi::GST_AGGREGATOR_START_TIME_SELECTION_FIRST => Self::First,
rust
impl Handler for TemplateHandler { fn handle(&self, req: &mut Request) -> IronResult<Response> { let params = req.get_ref::<Params>().unwrap(); let param_template_data = DataMap::from(params); let mut resp = Response::new(); let data: Value = param_template_data.into(); resp.set_mut(Template::new(self.path, data)).set_mut(status::Ok); Ok(resp) } }
rust
required: required.clone(), }, ); }
rust
StateMachineWrapper::Identifier(s.into()) } (StateMachineWrapper::InputElementDiv(s), Equivalence::F) => { StateMachineWrapper::Identifier(s.into()) } (StateMachineWrapper::InputElementDiv(s), Equivalence::O) => { StateMachineWrapper::Identifier(s.into()) }
rust
const TEST_MODE_VENDOR_USE_ONLY_10: u16 = 0b0000_0001_0000_0000; // A8 = 1, A7 = 0 const TEST_MODE_VENDOR_USE_ONLY_01: u16 = 0b0000_0000_1000_0000; // A8 = 0, A7 = 1 // Write burst length const WRITE_BURST_LENGTH_BURST: u16 = 0b0000_0000_0000_0000; // A9 = 0
rust
pub fn elapsed(&self) -> Duration { let delta = SystemTime::now().duration_since(self.last_resume); self.last_elapsed + delta.unwrap() } } pub fn daemon(config: &Config, listener: TcpListener, path: PathBuf) -> crate::Result<()> { // Play song immediately.
rust
/// Size of [`input_event`] from system const INPUT_EVENT_SIZE: usize = mem::size_of::<input_event>(); /// Create asynchronous event stream from `file` pub async fn new_stream(file: File) -> io::Result<impl Stream<Item = io::Result<InputEvent>>> { let mut file = Box::pin(file);
rust
pub struct TagRow { pub album_id: Uuid, pub disc_id: Option<u8>, pub track_id: Option<u8>, pub name: String,
rust
\n}\ \n@media screen and (min-width: 1) and (max-width: 2) {\ \n foo {\ \n bar: baz;\ \n }\ \n baz {\ \n bar: foo;\ \n }\ \n}\ \n" ); }
rust
static LOGGER: UnityLogger = UnityLogger; pub fn init() -> Result<(), SetLoggerError> { log::set_logger(&LOGGER).map(|()| log::set_max_level(LevelFilter::Info)) }
rust
//use std::path::PathBuf; //use std::env; fn main() { let target = std::env::var("TARGET").unwrap(); if target.contains("wasm32") { //https://users.rust-lang.org/t/how-to-static-link-c-lib-to-wasm/36558/5 std::env::set_var("CC", "clang");
rust
Ok(()) } fn push_repo(tmp_directory_path: &std::path::PathBuf) -> Result<()> { println!("Pushing local clone."); crate::common::git::run_command(vec!["add", "-A"], &tmp_directory_path)?; crate::common::git::commit("Update OpenFare profile.", &tmp_directory_path)?; crate::common::git::run_command(vec!["push", "origin"], &tmp_directory_path)?; Ok(()) } fn insert_profile(
rust
node_index: usize, ) -> &'result mut WeightType { let key = ToOwnedUsize { value: node_index }; self.entry_ref(&key) .or_insert_with(|| WeightType::infinity()) } fn set(&mut self, node_index: usize, weight: WeightType) { let key = ToOwnedUsize { value: node_index }; self.insert(key, weight); }
rust
let number = "3"; // don't change this line println!("Number {}", number); // We need to implement the shadowing concept here. Shadowing allows you // to define the variable with existing name along with different data type { let number: i32 = 3; } println!("Number {}", number); }
rust
for i in a..b { if i < 0 { total_time += c; } else if i == 0 { total_time += d + e;
rust
} pub const MAIN_SEP_STR: &str = "/"; pub const MAIN_SEP: char = '/';
rust
} Node::Class(_, ref name, ref super_, ref body) => { self.strip_node(name); self.strip_node(super_); self.strip_node(body); } Node::CSend(_, ref recv, _, ref args) | Node::Send(_, ref recv, _, ref args) => { self.strip_node(recv); self.strip_nodes(args); } Node::Def(_, _, ref args, ref body) => { self.strip_node(args);
rust
IResult::Error(e) => IResult::Error(e), IResult::Incomplete(i) => IResult::Incomplete(i) } } ); ($i:expr, $func:path) => ( { throwaway_input!($func($i)) } );
rust
} }; } pub struct Or_rm8_r8; impl<T: CpuStateManager> InstructionHandler<T> for Or_rm8_r8 { or_rm_r!(u8); }
rust
pub featured: bool, pub feature_level: i32, pub partnered: bool, pub transcoding_profile_id: Option<u32>, pub suspended: bool, pub name: String, pub audience: String, pub viewers_total: u64, pub viewers_current: u64, pub num_followers: u64, pub description: Option<String>, pub type_id: Option<u32>,
rust
pub mod client; pub mod update;
rust
pub fn set_cache_type(&mut self, caching: CacheType) { self.entry = (self.entry & !0b11000) | match caching { CacheType::WriteBack => 0, CacheType::WriteThrough => 0b01000, CacheType::Uncacheable => 0b11000, }; } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum CacheType { WriteBack,
rust
flag_enabled: false, flag_negate: false, flag_reload: false, target_period: 0x0000, cur_period: 0x0000,
rust
} // ------------------------------------------------------------ // init tests. The Shares are the entities that receive newly minted settcurrencies/stablecoins. #[test] fn init_test() { new_test_ext().execute_with(|| {
rust
typedef struct ArrayMe { int i[5]; } ArrayMe_t; ArrayMe_t *s; void verify() { bool failed = false; for (uint32_t index = 0; index < 5; index++) { _RS_ASSERT(s->i[index] == index); }
rust
pub fn one_is_bigger(one:String,two:String) -> bool { let one_as_num = convert_to_num(one); let two_as_num = convert_to_num(two); if one_as_num.len() > two_as_num.len(){ return true; } if one_as_num.len() < two_as_num.len(){ return false; } let one_as_bytes = one_as_num.into_bytes(); let two_as_bytes = two_as_num.into_bytes();
rust
use derive_more::From; use entity::RawIdx; use ir::primitive::Value; /// The stack. #[derive(Debug, Default)] pub struct Stack { registers: Vec<Register>, } impl Stack {
rust
} } pub fn write_char(&mut self, x: usize, y: usize, c: char, color: PixelColor) { if let Some(font) = fonts::get_font(c) { for (dy, row) in font.bytes().iter().enumerate() { for dx in 0..8 {
rust
&context.server.analysis.types, ) .to_markdown(&context.server.analysis.navigator) } else if usage.declaration.node.is_method() { let behaviour = context.server.behaviour_at(location)?; behaviour.to_markdown(&context.server.analysis.navigator) } else { let type_ = context.server.type_at(location);
rust
} MissingImplBehavior::PanicImmediately => Box::new(AlwaysPanic {}), }; PrintContext {
rust
s: String::from("s") }; // s1是un mut的,所以这里编译不过 // s1.s.push_str("aaa"); struct TestRefCell2{ s: RefCell<String>, } let s2 = TestRefCell2 {
rust
#[serde_as(as = "DurationSeconds<u64>")] pub metrics_interval: Duration, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub metric_orders: Vec<MetricOrder>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub headers: Vec<(String, String)>, #[serde(default = "FlinkSettings::default_max_retries")]
rust
/// These are the individual instructions that our VM interprets. #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[rustfmt::skip] pub enum Op { // ## VM control
rust
#[async_trait] impl<'a> Executor for ExecIndexOnlyScan<'a> { async fn next(&mut self) -> Result<Option<Tuple>, buffer::Error> { let (skey_bytes, pkey_bytes) = match self.index_iter.prev().await? { Some(pair) => pair, None => return Ok(None), }; let mut skey = vec![]; tuple::decode(&skey_bytes, &mut skey); if !(self.while_cond)(&skey) { return Ok(None); }
rust
400...599 => Red.paint(status_str), _ => Yellow.paint(status_str), }; info!("{} {} {} - {:.3}ms", request.method(), request.uri().path(), status, (elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 * 1e-9) * 1000 as f64); }); let timeout = if request_timeout > 0 { Box::new(tokio::timer::Timeout::new(futures::empty::<Response<Body>, ServerError>(), Duration::from_millis(request_timeout)).then(|_| {
rust
fn set_message(&mut self, v: String) { self.message = v; } } impl crate::ResponseCheckTx for tendermint::abci::ResponseCheckTx { fn get_code(&self) -> u32 { self.code }
rust
#[test] fn test() { assert_eq!( runner().ok("// libsass issue 659: never output empty blocks\ \n// https://github.com/sass/libsass/issues/659\n\
rust
fn try_from(value: Vector3<f32>) -> Result<Self, Self::Error> { Ok(Self(Vector3::new( value.x.try_into()?, value.y.try_into()?, value.z.try_into()?, )))
rust
compile! { #[ignore = "very slow"] c_err_too_many_locals, (0..=(u16::MAX as usize)) .map(|i| format!("let l{};\n", i)) .collect::<std::string::String>(), Err([e]) if e.is::<TooManyLocals>(),
rust
macro_rules! visitor { ($regex:expr, $src:expr) => { struct Visitor<'a> { ran: bool, #[allow(dead_code)] src: &'a str,
rust
pub fn as_array(self) -> [u8; 3] { [self.r, self.g, self.b] } } impl From<Vec3> for Color { #[inline] fn from(a: Vec3) -> Self { Color { r: (a.x * 255.99) as u8, g: (a.y * 255.99) as u8, b: (a.z * 255.99) as u8, }
rust
.call() .into_json_deserialize::<Vec<Zone>>() .expect("Can't retrieve zones list") } pub fn get_zone(&self, id: u64) -> Zone { ureq::get(&format!("{}/zones/{}", BASE_URL, id)) .auth_kind("Bearer", &self.token) .set("Accept", "application/json")
rust
#![warn(clippy::integer_division)] fn main() { let two = 2; let n = 1 / 2; let o = 1 / two; let p = two / 4;
rust
rustdoc::broken_intra_doc_links, rustdoc::private_doc_tests, trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_lifetimes,
rust
let mut rule = Rule::new(name, ranges.next().unwrap()); for range in ranges { rule.add(range); } rule }); } assert_eq!(lines.next().unwrap(), "your ticket:"); let your_ticket = parse_ticket(lines.next().unwrap()); assert_eq!(lines.next().unwrap(), ""); assert_eq!(lines.next().unwrap(), "nearby tickets:"); let nearby_tickets = lines.map(parse_ticket).collect(); Input { rules,
rust
#[issue_79825::assert_input] trait Alias = Sized; fn main() {}
rust
} _ => return Err(PFCPError::Unknown), } Ok(element) } pub fn encode(mut self) -> Vec<u8> {
rust
Cow::from(s).into() } } impl Default for PositiveNumber<'_> { fn default() -> Self {
rust
mod config; mod errors; mod inserter; mod plugin; collectd_plugin::collectd_plugin!(plugin::PgCollectd);
rust
use rslint_parser::{ ast::{JsAnyArrayElement, JsArrayExpression, JsArrayHole}, AstSeparatedList, }; impl ToFormatElement for JsArrayExpression { fn to_format_element(&self, formatter: &Formatter) -> FormatResult<FormatElement> { let elements = self.elements(); Ok(group_elements(formatter.format_delimited( &self.l_brack_token()?, |open_token_trailing, close_token_leading| { // Specifically do not use format_separated as array expressions need // separators inserted after empty expressions regardless of the // formatting since this makes a semantic difference
rust
// get document we never created let result = api_service::request( &account, GetDocumentRequest { id: Uuid::new_v4(), content_version: 0 }, ); assert_matches!( result,
rust
loop { if num_done == num_thrs { break } match rc_primes.recv() { Ok(Some(p)) => primes.push(p),
rust
description.read = Some(my_DSP_callback as fn(&_, &mut _, &mut _, _, _, _) -> _); description.name = "test".to_owned(); let dsp = match fmod.create_DSP_with_description(&mut description) { Ok(dsp) => dsp, Err(e) => {
rust
pub fn grid_end(&mut self) { self.end_container(); } pub fn flexgrid_begin(&mut self, id: &str, widths: &[Coord], height: Coord) -> &mut Self { self.try_commit(); self.prefix_id(id);
rust
use anyhow::Result; use config::Config; fn setup_logging() -> Result<()> { todo!() } fn main() { if !Config::exists().unwrap() { println!("Creating new configuration"); Config::create_new().unwrap(); println!( "Created new configuration file at \"{}\", please edit it before running again.", Config::get_path().unwrap().display()
rust
use std::io; use std::ops::{Deref, DerefMut}; use std::path::{Path, PathBuf}; pub mod fs;
rust
waker.wake().expect("unable to wake"); expect_waker_event(&mut poll, &mut events, token); } #[test] fn waker_multiple_wakeups_same_thread() {
rust
year: 2000, month: zero_indexed_month + 1, date: (days_since_epoch as u16 % 32) + zero_indexed_month, }; } // Remove January and February and start the year with March - we'll // add January and February back later. // This means we don't have to worry about this year being a leap year, // nor do we have to worry about a month with 28 days. let adjusted_days = days_since_epoch - 60;
rust
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 pub mod data_cache; pub mod dependency_analyzer; mod outcome_array; pub mod parallel_transaction_executor; pub mod scheduler;
rust
#[derive(Validate)] //~^ ERROR: proc-macro derive panicked //~^^ HELP: Invalid argument for `must_match` validator of field `password`: the other field doesn't exist in struct struct Test { #[validate(must_match = "password2")] password: String, } fn main() {}
rust
enum Command { #[clap(name = "grab", about = "Download thread")] Grab { #[clap(help = "URL of thread to download")] url: String,
rust
#[derive(Copy, Clone)] struct ColorVertex { color: [f32; 4], } implement_vertex!(ColorVertex, color);
rust
Low level I/O primitives form the building blocks of the on-disk Nakala index format. They're responsible for encoding integers, varints, length prefixed strings and more. */ pub use read::Cursor as ReadCursor; pub use write::Cursor as WriteCursor;
rust
} fn double_line_layout( &self, default_font: Font, small_font: Font, token_type: TokenType, metrics: &dyn FontMetrics, max_width: i32, cursor: Option<usize>, ) -> Option<Layout> {
rust
#[test] fn next_done() { let model = rvs::parse(&Default::default(), "a = Pattern(0, 1, 2, 3); b = a;").unwrap(); let b = model.get_variable_by_name("b").unwrap(); let mut b = b.borrow_mut(); let expected: Vec<bool> = vec![false, false, false, true] .into_iter() .cycle()
rust
//! } //! //! #[async_trait::async_trait] //! impl AsyncTestContext for MyAsyncContext { //! async fn setup() -> MyAsyncContext { //! MyAsyncContext { value: "Hello, world!".to_string() }
rust
validator_commission, nominator_exposure, total_exposure, is_validator, );
rust
cadastro_cliente.Cadastro_cliente cadastro_cliente.cadastro
rust
} } fn get_root(&mut self) -> &mut Self::Root { self } fn num_constraints(&self) -> usize {
rust
#[cfg(test)] mod div_tests; #[cfg(test)] mod from_str_tests; #[cfg(test)] mod from_tests; #[cfg(test)] mod mod_tests; #[cfg(test)] mod mul_tests; #[cfg(test)] mod rem_tests; #[cfg(test)]
rust
)] standalone: bool, #[structopt( help = "The book to render.", parse(from_os_str), default_value = "." )] root: PathBuf, #[structopt( short = "c", long = "colour",
rust
use crate::matrices::lower_triangular_matrix; use crate::matrices::lower_triangular_matrix::LowerTriangularMatrix; use crate::matrices::matrix::Matrix; pub struct Container { pub size: usize, pub matrs: Vec<Box<dyn BaseMatrix>>, }
rust
mod play; mod sampler; mod wavio; pub use midi::*; pub use mixer::*; pub use play::*; pub use sampler::*; pub use wavio::*; /// The audio sample rate is currently fixed at 48000 /// samples per second. This constant will be made a
rust
} impl<'a, T: HashVersion> HashVersion for &'a mut T { #[inline(always)] fn hash_version<H: Hasher>(&self, state: &mut H) { T::hash_version(self, state) } } impl<T: HashVersion> HashVersion for Box<T> { #[inline(always)]
rust
} } async fn delete_from_library( &self,
rust
// debug!("DirEntryExt::new return with len{} {:x}", result.len(), result[last].ext_attr); return result; } #[inline] pub fn is_end(&self) -> bool { return self.ext_attr & DirEntryExt::EXT_END == DirEntryExt::EXT_END; }
rust
/// Hidden: The cells that make up the double,triple,quad /// /// The tuple is all the indexes used to create the subset. #[derive(Debug)] enum Subset { Naked(usize, Vec<usize>), Hidden(usize, Vec<usize>), } fn gen_subset<T: std::iter::Iterator<Item = usize>>( sudoku: &Sudoku,
rust
use proc_macro_hack::proc_macro_hack; #[proc_macro_hack] pub use corpus_queries_impl::datapond_query;
rust
format!( "{}", BuildError::ModuleCircularDependency(FilePath::new(vec!["foo", "bar", "baz"])) ), "circular module dependency detected: foo/bar/baz" ); } #[test] fn display_package_circular_dependency() { assert_eq!( format!( "{}",
rust
impl PartialEq for NoteOut { fn eq(&self, other: &Self) -> bool { self.id == other.id && self.category_id == other.category_id && self.title == other.title && self.data == other.data } } impl From<&Note> for NoteOut { fn from(note: &Note) -> Self { NoteOut { id: note.id, category_id: note.category_id,
rust
use cosmwasm_std::{Addr, Decimal}; use cw_storage_plus::Item; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct SwapFeeConfig { pub fee_admin: Addr, /// The percent fee amount from every token swap to any other pub enable_swap_fee: bool, /// The percent fee amount from every token swap to any other pub swap_percent_fee: Decimal, /// The fee receiver address pub fee_receiver: Addr, } pub const SWAP_FEE_CONFIG: Item<SwapFeeConfig> = Item::new("swap_fee_config");
rust
state.flushed_position = end_position + 2; state.nodes.push(::Node::MagicWord { end: state.flushed_position, start: state.scan_position, }); state.scan_position = state.flushed_position; return; } } state.scan_position += 1; }
rust
pub(crate) const USERINFO: &AsciiSet = &PATH .add(b'/') .add(b':') .add(b';') .add(b'=') .add(b'@') .add(b'[') .add(b'\\') .add(b']')
rust
/// /// - When `s` is empty. pub fn from(s: String) -> Result<Self, &'static str> { if s.is_empty() { Err("string cannot be empty") } else { Ok(NeString(s)) } } }
rust
use callysto::futures::StreamExt; use callysto::kafka::cconsumer::CStream; use callysto::kafka::enums::OffsetReset; use callysto::prelude::message::*; use callysto::prelude::*; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; use tracing::info; #[derive(Clone)] struct SharedState { value: Arc<AtomicU32>, }
rust
} let x = 1; let y = 2; let selected = select(&x, &y); println!("{}", selected);
rust
fn view(eye: Vector3<f32>, dir: Vector3<f32>) -> Matrix4<f32> { let f = dir.normalize(); // let s = f.cross(up).normalize(); let s = Vector3::new(-f.z, 0.0, f.x); let mag = (s.x * s.x + s.z * s.z).sqrt().recip(); let s = Vector3::new(s.x * mag, 0.0, s.z * mag);
rust
pub mod configuration; pub mod services; pub mod startup;
rust
whitelist: Vec<String>, } impl GateKeeper { /// Creates a new instance, blocking features defined in the constructor.
rust
let mode = std::env::args().nth(1).expect("mode unavailable"); let name = std::env::args().nth(2).expect("name unavailable"); let nodes: u32 = std::env::args().nth(3).expect("nodes unavailable").parse().expect("nodes not parseable"); match mode.as_str() { "vertex" => { label_propagation(&NodesEdgesMemMapper::new(&name), nodes) }, "hilbert" => { label_propagation(&UpperLowerMemMapper::new(&name), nodes) }, "compressed" => { label_propagation(&DeltaCompressedReaderMapper::new(|| BufReader::new(File::open(&name).unwrap())), nodes) },