conversations listlengths 2 3 | source stringclasses 1 value | stack stringclasses 1 value |
|---|---|---|
[
{
"from": "system",
"value": "Add `ByteStream` for entire files of a byte slice\n"
},
{
"from": "human",
"value": "use nom::IResult;\n\npub trait StreamProducer {\n fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>\n where F: FnOnce(&[u8]) -> IResult<&[u8], T>;\n}\n"
},
{
"from": "gpt",
"value": "use nom::{IResult, Needed};\n\npub enum ErrorKind {\n EndOfInput,\n Unknown,\n}\n\npub trait StreamProducer {\n fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>\n where F: FnOnce(&[u8]) -> IResult<&[u8], T>;\n}\n\npub struct ByteStream<'a> {\n offset: usize,\n bytes: &'a [u8],\n}\n\nimpl<'a> ByteStream<'a> {\n pub fn new(bytes: &'a [u8]) -> Self {\n ByteStream {\n offset: 0,\n bytes: bytes,\n }\n }\n\n #[inline]\n pub fn len(&self) -> usize {\n self.bytes.len() - self.offset\n }\n\n #[inline]\n pub fn is_empty(&self) -> bool {\n self.len() == 0\n }\n}\n\nimpl<'a> StreamProducer for ByteStream<'a> {\n fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>\n where F: FnOnce(&[u8]) -> IResult<&[u8], T> {\n if self.is_empty() {\n return Err(ErrorKind::EndOfInput);\n }\n\n match f(&self.bytes[self.offset..]) {\n IResult::Done(i, o) => {\n self.offset += self.len() - i.len();\n\n Ok(o)\n }\n IResult::Incomplete(n) => {\n let mut needed = self.len();\n\n if let Needed::Size(size) = n {\n needed = size;\n }\n\n Err(ErrorKind::Incomplete(needed))\n }\n IResult::Error(_) => Err(ErrorKind::Unknown),\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add Sealed supertrait to private AsDynError trait\n"
},
{
"from": "human",
"value": "use std::error::Error;\nuse std::panic::UnwindSafe;\n\npub trait AsDynError<'a> {\n fn as_dyn_error(&self) -> &(dyn Error + 'a);\n}\n\nimpl<'a, T: Error + 'a> AsDynError<'a> for T {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n\nimpl<'a> AsDynError<'a> for dyn Error + 'a {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n\nimpl<'a> AsDynError<'a> for dyn Error + Send + 'a {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n\nimpl<'a> AsDynError<'a> for dyn Error + Send + Sync + 'a {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n\nimpl<'a> AsDynError<'a> for dyn Error + Send + Sync + UnwindSafe + 'a {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n"
},
{
"from": "gpt",
"value": "use self::private::Sealed;\nuse std::error::Error;\nuse std::panic::UnwindSafe;\n\npub trait AsDynError<'a>: Sealed {\n fn as_dyn_error(&self) -> &(dyn Error + 'a);\n}\n\nimpl<'a, T: Error + 'a> AsDynError<'a> for T {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n\nimpl<'a> AsDynError<'a> for dyn Error + 'a {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n\nimpl<'a> AsDynError<'a> for dyn Error + Send + 'a {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n\nimpl<'a> AsDynError<'a> for dyn Error + Send + Sync + 'a {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n\nimpl<'a> AsDynError<'a> for dyn Error + Send + Sync + UnwindSafe + 'a {\n #[inline]\n fn as_dyn_error(&self) -> &(dyn Error + 'a) {\n self\n }\n}\n\nmod private {\n use super::*;\n\n pub trait Sealed {}\n impl<'a, T: Error + 'a> Sealed for T {}\n impl<'a> Sealed for dyn Error + 'a {}\n impl<'a> Sealed for dyn Error + Send + 'a {}\n impl<'a> Sealed for dyn Error + Send + Sync + 'a {}\n impl<'a> Sealed for dyn Error + Send + Sync + UnwindSafe + 'a {}\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Drop type annotation from example\n"
},
{
"from": "human",
"value": "extern crate ndarray;\nextern crate ndarray_linalg;\n\nuse ndarray::*;\nuse ndarray_linalg::*;\n\nfn main() {\n let a = arr2(&[[3.0, 1.0, 1.0], [1.0, 3.0, 1.0], [1.0, 1.0, 3.0]]);\n let (e, vecs): (Array1<_>, Array2<_>) = a.clone().eigh(UPLO::Upper).unwrap();\n println!(\"eigenvalues = \\n{:?}\", e);\n println!(\"V = \\n{:?}\", vecs);\n let av = a.dot(&vecs);\n println!(\"AV = \\n{:?}\", av);\n}\n"
},
{
"from": "gpt",
"value": "extern crate ndarray;\nextern crate ndarray_linalg;\n\nuse ndarray::*;\nuse ndarray_linalg::*;\n\nfn main() {\n let a = arr2(&[[3.0, 1.0, 1.0], [1.0, 3.0, 1.0], [1.0, 1.0, 3.0]]);\n let (e, vecs) = a.clone().eigh(UPLO::Upper).unwrap();\n println!(\"eigenvalues = \\n{:?}\", e);\n println!(\"V = \\n{:?}\", vecs);\n let av = a.dot(&vecs);\n println!(\"AV = \\n{:?}\", av);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "chore(cli): Move non-essential status output to STDERR\n"
},
{
"from": "human",
"value": "pub mod cli;\npub mod i18n;\npub mod make;\npub mod setup;\npub mod shell;\nuse fluent::{FluentArgs, FluentValue};\n\npub static DEFAULT_LOCALE: &'static str = \"en-US\";\n\n#[derive(Debug)]\npub struct Config {\n pub version: String,\n pub verbose: bool,\n pub debug: bool,\n pub locale: i18n::Locale,\n}\n\npub fn header(config: &crate::Config, key: &str) {\n let mut args = FluentArgs::new();\n args.insert(\"version\", FluentValue::from(config.version.as_str()));\n println!(\"==> {} \\n\", config.locale.translate(\"welcome\", Some(&args)));\n println!(\"--> {} \\n\", config.locale.translate(key, None));\n}\n"
},
{
"from": "gpt",
"value": "pub mod cli;\npub mod i18n;\npub mod make;\npub mod setup;\npub mod shell;\nuse fluent::{FluentArgs, FluentValue};\n\npub static DEFAULT_LOCALE: &'static str = \"en-US\";\n\n#[derive(Debug)]\npub struct Config {\n pub version: String,\n pub verbose: bool,\n pub debug: bool,\n pub locale: i18n::Locale,\n}\n\npub fn header(config: &crate::Config, key: &str) {\n let mut args = FluentArgs::new();\n args.insert(\"version\", FluentValue::from(config.version.as_str()));\n eprintln!(\"==> {} \\n\", config.locale.translate(\"welcome\", Some(&args)));\n eprintln!(\"--> {} \\n\", config.locale.translate(key, None));\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix a test that broke on a recent nightly\n"
},
{
"from": "human",
"value": "#![feature(plugin)]\n#![plugin(plague)]\n\nplague! {\n for [ //~ERROR: this function takes 0 parameters but 2 parameters were supplied\n (1, 2),\n ]\n test fn foo() {\n }\n}\n\nfn main() {}\n"
},
{
"from": "gpt",
"value": "#![feature(plugin)]\n#![plugin(plague)]\n\nplague! {\n for [\n (1, 2), //~ERROR: this function takes 0 parameters but 2 parameters were supplied\n ]\n test fn foo() {\n }\n}\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Define struct to represent template metadata\n"
},
{
"from": "human",
"value": "extern crate askama;\nextern crate proc_macro;\nextern crate syn;\n\nuse proc_macro::TokenStream;\n\nfn get_path_from_attrs(attrs: &[syn::Attribute]) -> String {\n let attr = attrs.iter().find(|a| a.name() == \"template\").unwrap();\n if let syn::MetaItem::List(_, ref inner) = attr.value {\n if let syn::NestedMetaItem::MetaItem(ref item) = inner[0] {\n if let &syn::MetaItem::NameValue(ref key, ref val) = item {\n assert_eq!(key.as_ref(), \"path\");\n if let &syn::Lit::Str(ref s, _) = val {\n return s.clone();\n }\n }\n }\n }\n panic!(\"template path not found in struct attributes\");\n}\n\n#[proc_macro_derive(Template, attributes(template))]\npub fn derive_template(input: TokenStream) -> TokenStream {\n let ast = syn::parse_derive_input(&input.to_string()).unwrap();\n match ast.body {\n syn::Body::Struct(ref data) => data,\n _ => panic!(\"#[derive(Template)] can only be used with structs\"),\n };\n let path = get_path_from_attrs(&ast.attrs);\n askama::build_template(&path, &ast).parse().unwrap()\n}\n"
},
{
"from": "gpt",
"value": "extern crate askama;\nextern crate proc_macro;\nextern crate syn;\n\nuse proc_macro::TokenStream;\n\nstruct TemplateMeta {\n path: String,\n}\n\nfn get_path_from_attrs(attrs: &[syn::Attribute]) -> TemplateMeta {\n let mut path = None;\n let attr = attrs.iter().find(|a| a.name() == \"template\").unwrap();\n if let syn::MetaItem::List(_, ref inner) = attr.value {\n for nm_item in inner {\n if let &syn::NestedMetaItem::MetaItem(ref item) = nm_item {\n if let &syn::MetaItem::NameValue(ref key, ref val) = item {\n match key.as_ref() {\n \"path\" => if let &syn::Lit::Str(ref s, _) = val {\n path = Some(s.clone());\n } else {\n panic!(\"template path must be string literal\");\n },\n _ => { panic!(\"unsupported annotation key found\") }\n }\n }\n }\n }\n }\n if path.is_none() {\n panic!(\"template path not found in struct attributes\");\n }\n TemplateMeta { path: path.unwrap() }\n}\n\n#[proc_macro_derive(Template, attributes(template))]\npub fn derive_template(input: TokenStream) -> TokenStream {\n let ast = syn::parse_derive_input(&input.to_string()).unwrap();\n match ast.body {\n syn::Body::Struct(ref data) => data,\n _ => panic!(\"#[derive(Template)] can only be used with structs\"),\n };\n let meta = get_path_from_attrs(&ast.attrs);\n askama::build_template(&meta.path, &ast).parse().unwrap()\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "CG: Use new version of gtk:init() that returns a Result\n"
},
{
"from": "human",
"value": "extern crate gtk;\n\nuse gtk::traits::*;\n\nfn main() {\n if !gtk::init_check() {\n println!(\"Cannot start because GTK is not working / available\");\n return;\n }\n\n match gtk::Window::new(gtk::WindowType::TopLevel) {\n None => println!(\"Unable to create a GTK window.\"),\n Some(window) => {\n window.set_title(\"Rubbem\");\n window.set_window_position(gtk::WindowPosition::Center);\n\n window.connect_delete_event(|_, _| {\n gtk::main_quit();\n gtk::signal::Inhibit(false)\n });\n\n window.show_all();\n gtk::main();\n }\n }\n}\n"
},
{
"from": "gpt",
"value": "extern crate gtk;\n\nuse gtk::traits::*;\n\nfn main() {\n match gtk::init() {\n Err(_) => println!(\"Cannot start because GTK is not working / available.\"),\n Ok(_) => gtk_main()\n }\n}\n\nfn gtk_main()\n{\n match gtk::Window::new(gtk::WindowType::TopLevel) {\n None => println!(\"Unable to create a GTK window.\"),\n Some(window) => gtk_window(window)\n }\n}\n\nfn gtk_window(window: gtk::Window)\n{\n window.set_title(\"Rubbem\");\n window.set_window_position(gtk::WindowPosition::Center);\n\n window.connect_delete_event(|_, _| {\n gtk::main_quit();\n gtk::signal::Inhibit(false)\n });\n\n window.show_all();\n gtk::main();\n}\n\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add as_boolean and as_symbol to AnyObject\n"
},
{
"from": "human",
"value": "use std::convert::From;\n\nuse types::Value;\n\nuse super::array::Array;\nuse super::class::Class;\nuse super::fixnum::Fixnum;\nuse super::hash::Hash;\nuse super::string::RString;\n\nuse super::traits::Object;\n\n#[derive(Clone)]\npub struct AnyObject {\n value: Value\n}\n\nimpl AnyObject {\n pub fn as_array(&self) -> Array {\n Array::from(self.value())\n }\n\n pub fn as_class(&self) -> Class {\n Class::from(self.value())\n }\n\n pub fn as_fixnum(&self) -> Fixnum {\n Fixnum::from(self.value())\n }\n\n pub fn as_hash(&self) -> Hash {\n Hash::from(self.value())\n }\n\n pub fn as_string(&self) -> RString {\n RString::from(self.value())\n }\n}\n\nimpl From<Value> for AnyObject {\n fn from(value: Value) -> Self {\n AnyObject {\n value: value\n }\n }\n}\n\nimpl Object for AnyObject {\n fn value(&self) -> Value {\n self.value\n }\n}\n"
},
{
"from": "gpt",
"value": "use types::Value;\n\nuse super::array::Array;\nuse super::boolean::Boolean;\nuse super::class::Class;\nuse super::fixnum::Fixnum;\nuse super::hash::Hash;\nuse super::string::RString;\nuse super::symbol::Symbol;\n\nuse super::traits::Object;\n\n#[derive(Clone)]\npub struct AnyObject {\n value: Value\n}\n\nimpl AnyObject {\n pub fn as_array(&self) -> Array {\n Array::from(self.value)\n }\n\n pub fn as_boolean(&self) -> Boolean {\n Boolean::from(self.value)\n }\n\n pub fn as_class(&self) -> Class {\n Class::from(self.value)\n }\n\n pub fn as_fixnum(&self) -> Fixnum {\n Fixnum::from(self.value)\n }\n\n pub fn as_hash(&self) -> Hash {\n Hash::from(self.value)\n }\n\n pub fn as_string(&self) -> RString {\n RString::from(self.value)\n }\n\n pub fn as_symbol(&self) -> Symbol {\n Symbol::from(self.value)\n }\n}\n\nimpl From<Value> for AnyObject {\n fn from(value: Value) -> Self {\n AnyObject {\n value: value\n }\n }\n}\n\nimpl Object for AnyObject {\n fn value(&self) -> Value {\n self.value\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix point-mutations for newest rust\n"
},
{
"from": "human",
"value": "pub fn hamming_distance(a: &str, b: &str) -> uint {\n a.chars().zip(b.chars()).filter(|&(a, b)| a != b).count()\n}\n"
},
{
"from": "gpt",
"value": "pub fn hamming_distance(a: &str, b: &str) -> usize {\n a.chars().zip(b.chars()).filter(|&(a, b)| a != b).count()\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add test for Type containing macro metavariable\n"
},
{
"from": "human",
"value": "use syn::Type;\n\n#[test]\nfn test_mut_self() {\n syn::parse_str::<Type>(\"fn(mut self)\").unwrap();\n syn::parse_str::<Type>(\"fn(mut self: ())\").unwrap();\n syn::parse_str::<Type>(\"fn(mut self: ...)\").unwrap_err();\n syn::parse_str::<Type>(\"fn(mut self: mut self)\").unwrap_err();\n syn::parse_str::<Type>(\"fn(mut self::T)\").unwrap_err();\n}\n"
},
{
"from": "gpt",
"value": "#[macro_use]\nmod macros;\n\nuse proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree};\nuse quote::quote;\nuse std::iter::FromIterator;\nuse syn::Type;\n\n#[test]\nfn test_mut_self() {\n syn::parse_str::<Type>(\"fn(mut self)\").unwrap();\n syn::parse_str::<Type>(\"fn(mut self: ())\").unwrap();\n syn::parse_str::<Type>(\"fn(mut self: ...)\").unwrap_err();\n syn::parse_str::<Type>(\"fn(mut self: mut self)\").unwrap_err();\n syn::parse_str::<Type>(\"fn(mut self::T)\").unwrap_err();\n}\n\n#[test]\nfn test_macro_variable_type() {\n // mimics the token stream corresponding to `$ty<T>`\n let tokens = TokenStream::from_iter(vec![\n TokenTree::Group(Group::new(Delimiter::None, quote! { ty })),\n TokenTree::Punct(Punct::new('<', Spacing::Alone)),\n TokenTree::Ident(Ident::new(\"T\", Span::call_site())),\n TokenTree::Punct(Punct::new('>', Spacing::Alone)),\n ]);\n\n snapshot!(tokens as Type, @r###\"\n Type::Path {\n path: Path {\n segments: [\n PathSegment {\n ident: \"ty\",\n arguments: PathArguments::AngleBracketed {\n args: [\n Type(Type::Path {\n path: Path {\n segments: [\n PathSegment {\n ident: \"T\",\n arguments: None,\n },\n ],\n },\n }),\n ],\n },\n },\n ],\n },\n }\n \"###);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix gen_hashmap! and improve it's performance"
},
{
"from": "human",
"value": "#![allow(unused_macros)]\n\nmacro_rules! gen_hashmap {\n\n {$($key: expr => $value: expr),*} => {\n\n {\n let mut hashmap = HashMap::new();\n\n $(\n hashmap.insert($key, $value);\n )*\n\n hashmap\n }\n }\n}"
},
{
"from": "gpt",
"value": "#![allow(unused_macros)]\n\nmacro_rules! gen_hashmap {\n\n (@single $($e: tt)*) => (());\n\n (@count $($e: expr)*) => (<[()]>::len(&[$(gen_hashmap!(@single $e)),*]));\n\n ($($key: expr => $value: expr,)+) => (gen_hashmap!($($key => $value),+));\n\n {$($key: expr => $value: expr),*} => {\n\n {\n let count = gen_hashmap!(@count $($key)*);\n let mut hashmap = ::std::collections::HashMap::with_capacity(count);\n\n $(\n hashmap.insert($key, $value);\n )*\n\n hashmap\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add DAO functionality to add category\n"
},
{
"from": "human",
"value": "extern crate dotenv;\nextern crate diesel;\n\nuse self::dotenv::dotenv;\nuse std::env;\nuse self::diesel::prelude::*;\nuse self::diesel::pg::PgConnection;\n\npub fn establish_connection() -> PgConnection {\n dotenv().ok();\n\n let database_url = env::var(\"DATABASE_URL\").expect(\"DATABASE_URL must be set\");\n PgConnection::establish(&database_url).expect(&format!(\"Error connecting to {}\", database_url))\n}\n"
},
{
"from": "gpt",
"value": "extern crate dotenv;\nextern crate diesel;\n\nuse self::dotenv::dotenv;\nuse std::env;\nuse self::diesel::prelude::*;\nuse self::diesel::pg::PgConnection;\nuse super::model::*;\n\ntype Result<T> = self::diesel::QueryResult<T>;\n\npub struct Dao {\n conn: PgConnection,\n}\n\nimpl Dao {\n pub fn new() -> Self {\n Dao { conn: establish_connection() }\n }\n\n pub fn create_category(&self, text: &str) -> Result<Category> {\n use super::schema::category;\n let new_category = NewCategory { text };\n diesel::insert(&new_category)\n .into(category::table)\n .get_result(&self.conn)\n }\n}\n\nfn establish_connection() -> PgConnection {\n dotenv().ok();\n\n let database_url = env::var(\"DATABASE_URL\").expect(\"DATABASE_URL must be set\");\n PgConnection::establish(&database_url).expect(&format!(\"Error connecting to {}\", database_url))\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use process::abort() instead of libc::abort() for wasm32\n"
},
{
"from": "human",
"value": "//! Package up unwind recovery. Note that if you are in some sensitive\n//! place, you can use the `AbortIfPanic` helper to protect against\n//! accidental panics in the rayon code itself.\n\nuse libc;\nuse std::any::Any;\nuse std::panic::{self, AssertUnwindSafe};\nuse std::io::stderr;\nuse std::io::prelude::*;\nuse std::thread;\n\n/// Executes `f` and captures any panic, translating that panic into a\n/// `Err` result. The assumption is that any panic will be propagated\n/// later with `resume_unwinding`, and hence `f` can be treated as\n/// exception safe.\npub fn halt_unwinding<F, R>(func: F) -> thread::Result<R>\n where F: FnOnce() -> R\n{\n panic::catch_unwind(AssertUnwindSafe(func))\n}\n\npub fn resume_unwinding(payload: Box<Any + Send>) -> ! {\n panic::resume_unwind(payload)\n}\n\npub struct AbortIfPanic;\n\nimpl Drop for AbortIfPanic {\n fn drop(&mut self) {\n unsafe {\n let _ = writeln!(&mut stderr(), \"Rayon: detected unexpected panic; aborting\");\n libc::abort();\n }\n }\n}\n"
},
{
"from": "gpt",
"value": "//! Package up unwind recovery. Note that if you are in some sensitive\n//! place, you can use the `AbortIfPanic` helper to protect against\n//! accidental panics in the rayon code itself.\n\n#[cfg(any(not(target_arch = \"wasm32\"), target_os = \"emscripten\"))]\nuse libc;\n#[cfg(all(target_arch = \"wasm32\", not(target_os = \"emscripten\")))]\nuse std::process;\nuse std::any::Any;\nuse std::panic::{self, AssertUnwindSafe};\nuse std::io::stderr;\nuse std::io::prelude::*;\nuse std::thread;\n\n/// Executes `f` and captures any panic, translating that panic into a\n/// `Err` result. The assumption is that any panic will be propagated\n/// later with `resume_unwinding`, and hence `f` can be treated as\n/// exception safe.\npub fn halt_unwinding<F, R>(func: F) -> thread::Result<R>\n where F: FnOnce() -> R\n{\n panic::catch_unwind(AssertUnwindSafe(func))\n}\n\npub fn resume_unwinding(payload: Box<Any + Send>) -> ! {\n panic::resume_unwind(payload)\n}\n\npub struct AbortIfPanic;\n\nimpl Drop for AbortIfPanic {\n fn drop(&mut self) {\n let _ = writeln!(&mut stderr(), \"Rayon: detected unexpected panic; aborting\");\n #[cfg(any(not(target_arch = \"wasm32\"), target_os = \"emscripten\"))]\n unsafe {\n libc::abort();\n }\n #[cfg(all(target_arch = \"wasm32\", not(target_os = \"emscripten\")))]\n process::abort();\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "bug: Fix unix import in tests for windows\n"
},
{
"from": "human",
"value": "use assert_cmd::prelude::*;\nuse std::process::{Command, Stdio};\n\nuse anyhow::{Context, Result};\nuse nix::sys::signal::{kill, Signal};\nuse nix::unistd::Pid;\n\nmod helper;\n\nuse helper::*;\n\n#[cfg(target_os = \"linux\")]\n#[test]\n/// Spin up the daemon and send a SIGTERM shortly afterwards.\n/// This should trigger the graceful shutdown and kill the process.\nfn test_ctrlc() -> Result<()> {\n let (_settings, tempdir) = helper::base_setup()?;\n\n let mut child = Command::cargo_bin(\"pueued\")?\n .arg(\"--config\")\n .arg(tempdir.path().join(\"pueue.yml\").to_str().unwrap())\n .arg(\"-vvv\")\n .stdout(Stdio::piped())\n .spawn()?;\n\n let pid = get_pid(tempdir.path())?;\n\n // Send SIGTERM signal to process via nix\n let nix_pid = Pid::from_raw(pid);\n kill(nix_pid, Signal::SIGTERM).context(\"Failed to send SIGTERM to pid\")?;\n\n // Sleep for 500ms and give the daemon time to shut down\n helper::sleep_ms(500);\n\n let result = child.try_wait();\n assert!(matches!(result, Ok(Some(_))));\n let code = result.unwrap().unwrap();\n assert!(matches!(code.code(), Some(1)));\n\n Ok(())\n}\n"
},
{
"from": "gpt",
"value": "use assert_cmd::prelude::*;\nuse std::process::{Command, Stdio};\n\nuse anyhow::{Context, Result};\n\nmod helper;\n\nuse helper::*;\n\n#[cfg(target_os = \"linux\")]\n#[test]\n/// Spin up the daemon and send a SIGTERM shortly afterwards.\n/// This should trigger the graceful shutdown and kill the process.\nfn test_ctrlc() -> Result<()> {\n let (_settings, tempdir) = helper::base_setup()?;\n\n let mut child = Command::cargo_bin(\"pueued\")?\n .arg(\"--config\")\n .arg(tempdir.path().join(\"pueue.yml\").to_str().unwrap())\n .arg(\"-vvv\")\n .stdout(Stdio::piped())\n .spawn()?;\n\n let pid = get_pid(tempdir.path())?;\n\n use nix::sys::signal::{kill, Signal};\n // Send SIGTERM signal to process via nix\n let nix_pid = nix::unistd::Pid::from_raw(pid);\n kill(nix_pid, Signal::SIGTERM).context(\"Failed to send SIGTERM to pid\")?;\n\n // Sleep for 500ms and give the daemon time to shut down\n helper::sleep_ms(500);\n\n let result = child.try_wait();\n assert!(matches!(result, Ok(Some(_))));\n let code = result.unwrap().unwrap();\n assert!(matches!(code.code(), Some(1)));\n\n Ok(())\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Allow specifying an output file on the command line\n"
},
{
"from": "human",
"value": "use std::io;\nuse std::collections::HashSet;\n\nextern crate syn;\nextern crate clap;\n\nuse clap::{Arg, App};\n\nmod rust_lib;\nmod bindgen;\n\nfn main() {\n let matches = App::new(\"cbindgen\")\n .version(\"0.1.0\")\n .about(\"Generate C bindings for a Rust library\")\n .arg(Arg::with_name(\"INPUT\")\n .help(\"The crate or source file to generate bindings for\")\n .required(true)\n .index(1))\n .get_matches();\n\n let crate_or_src = matches.value_of(\"INPUT\").unwrap();\n\n let glyph_instance = bindgen::Prebuilt::new(\n String::from(\"GlyphInstance\"),\n String::from(\nr###\"struct WrGlyphInstance {\n uint32_t index;\n Point2D point;\n\n bool operator==(const WrGlyphInstance& aOther) const {\n return index == aOther.index &&\n point == aOther.point;\n }\n};\"###));\n\n let lib = bindgen::Library::load(crate_or_src,\n vec![glyph_instance],\n HashSet::new());\n let built = lib.build().unwrap();\n\n built.write(&mut io::stdout());\n}\n"
},
{
"from": "gpt",
"value": "use std::io;\nuse std::fs::File;\nuse std::collections::HashSet;\n\nextern crate syn;\nextern crate clap;\n\nuse clap::{Arg, App};\n\nmod rust_lib;\nmod bindgen;\n\nfn main() {\n let matches = App::new(\"cbindgen\")\n .version(\"0.1.0\")\n .about(\"Generate C bindings for a Rust library\")\n .arg(Arg::with_name(\"INPUT\")\n .help(\"the crate or source file to generate bindings for\")\n .required(true)\n .index(1))\n .arg(Arg::with_name(\"OUTPUT\")\n .help(\"the path to output the directories to\")\n .required(false)\n .index(2))\n .get_matches();\n\n let crate_or_src = matches.value_of(\"INPUT\").unwrap();\n\n let glyph_instance = bindgen::Prebuilt::new(\n String::from(\"GlyphInstance\"),\n String::from(\nr###\"struct WrGlyphInstance {\n uint32_t index;\n Point2D point;\n\n bool operator==(const WrGlyphInstance& aOther) const {\n return index == aOther.index &&\n point == aOther.point;\n }\n};\"###));\n\n let lib = bindgen::Library::load(crate_or_src,\n vec![glyph_instance],\n HashSet::new());\n let built = lib.build().unwrap();\n\n if let Some(out_file) = matches.value_of(\"OUTPUT\") {\n built.write(&mut File::create(out_file).unwrap());\n } else {\n built.write(&mut io::stdout());\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Allow for the port to be set by env variable\n"
},
{
"from": "human",
"value": "extern crate ratel;\nextern crate iron;\n\nuse std::io::Read;\nuse iron::prelude::*;\nuse iron::status;\nuse ratel::error::ParseError;\n\nfn compile(source: String, minify: bool) -> Result<String, ParseError> {\n let mut ast = match ratel::parser::parse(source) {\n Ok(ast) => ast,\n Err(error) => return Err(error),\n };\n\n let settings = ratel::transformer::Settings::target_es5();\n ratel::transformer::transform(&mut ast, settings);\n\n Ok(ratel::codegen::generate_code(&ast, minify))\n}\n\nfn main() {\n fn handler(req: &mut Request) -> IronResult<Response> {\n let mut source = String::new();\n\n match req.body.read_to_string(&mut source) {\n Ok(_) => {},\n Err(_) => return Ok(Response::with((status::BadRequest, \":(\"))),\n }\n\n Ok(match compile(source, false) {\n Ok(source) => Response::with((status::Ok, source)),\n Err(error) => Response::with((status::UnprocessableEntity, format!(\"{:?}\", error))),\n })\n }\n\n let _server = Iron::new(handler).http(\"0.0.0.0:3000\").unwrap();\n println!(\"On 3000\");\n}\n"
},
{
"from": "gpt",
"value": "extern crate ratel;\nextern crate iron;\n\nuse std::io::Read;\nuse iron::prelude::*;\nuse iron::status;\nuse ratel::error::ParseError;\n\nconst DEFAULT_PORT: u16 = 3000;\n\nfn compile(source: String, minify: bool) -> Result<String, ParseError> {\n let mut ast = match ratel::parser::parse(source) {\n Ok(ast) => ast,\n Err(error) => return Err(error),\n };\n\n let settings = ratel::transformer::Settings::target_es5();\n ratel::transformer::transform(&mut ast, settings);\n\n Ok(ratel::codegen::generate_code(&ast, minify))\n}\n\nfn main() {\n fn handler(req: &mut Request) -> IronResult<Response> {\n let mut source = String::new();\n\n match req.body.read_to_string(&mut source) {\n Ok(_) => {},\n Err(_) => return Ok(Response::with((status::BadRequest, \":(\"))),\n }\n\n Ok(match compile(source, false) {\n Ok(source) => Response::with((status::Ok, source)),\n Err(error) => Response::with((status::UnprocessableEntity, format!(\"{:?}\", error))),\n })\n }\n\n\n let port = option_env!(\"PORT\").map(|port| port.parse().expect(\"Invalid port\"))\n .unwrap_or(DEFAULT_PORT);\n\n let address = format!(\"0.0.0.0:{}\", port);\n\n let _server = Iron::new(handler).http(address.as_str()).expect(\"Cannot start the server\");\n\n println!(\"Listening on port {}\", port);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Read token from environment variable\n"
},
{
"from": "human",
"value": "fn main() {\n println!(\"Hello, world!\");\n}\n"
},
{
"from": "gpt",
"value": "use std::{env, process};\n\nfn main() {\n let token = match env::var(\"GITHUB_SWEEP_TOKEN\") {\n Ok(val) => val,\n Err(e) => {\n println!(\"Error reading GITHUB_SWEEP_TOKEN environment variable: {}\", e);\n process::exit(1)\n }\n };\n\n println!(\"{}\", token);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Improve error printing in example\n"
},
{
"from": "human",
"value": "extern crate xswag_syntax_java as syntax;\nextern crate xswag_base as base;\n\nuse base::diag;\n\n// FIXME: import is currently wrong\nconst SRC: &'static str = \"\\\npackage yolo.swag;\n\nimport AlgoTools.IO;\nimport java.lang-*;\n\npublic private class Cheese {\n\tprivate public % yolo;\n}\n\n\n\";\n\nfn main() {\n let file = base::code::FileMap::new(\"<test>\", SRC);\n let (res, errors) = syntax::parse_compilation_unit(&file);\n\n println!(\"{:#?}\", res);\n for e in &errors {\n \tdiag::print(&e, &file, diag::PrintOptions::default());\n }\n // println!(\"{:#?}\", errors);\n}\n"
},
{
"from": "gpt",
"value": "extern crate xswag_syntax_java as syntax;\nextern crate xswag_base as base;\n\nuse base::diag;\n\n// FIXME: import is currently wrong\nconst SRC: &'static str = \"\\\npackage yolo.swag;\n\nimport AlgoTools.IO;\nimport java.lang-*;\n\npublic private class Cheese {\n\tprivate public % yolo;\n};\n\n;\nclass Bread {}\n\n\n\";\n\nfn main() {\n let file = base::code::FileMap::new(\"<test>\", SRC);\n let (res, errors) = syntax::parse_compilation_unit(&file);\n\n\tmatch res {\n\t\tOk(ast) => print!(\"{:#?}\", ast),\n\t\tErr(e) => {\n\t\t\t// println!(\"{:#?}\", e);\n\t\t\tdiag::print(&e, &file, diag::PrintOptions::default());\n\t\t}\n\t}\n for e in &errors {\n \tdiag::print(&e, &file, diag::PrintOptions::default());\n }\n // println!(\"{:#?}\", res);\n // println!(\"{:#?}\", errors);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add clone derive for PngError\n"
},
{
"from": "human",
"value": "use std::error::Error;\nuse std::fmt;\n\n#[derive(Debug)]\npub struct PngError {\n description: String,\n}\n\nimpl Error for PngError {\n fn description(&self) -> &str {\n &self.description\n }\n}\n\nimpl fmt::Display for PngError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.description)\n }\n}\n\nimpl PngError {\n pub fn new(description: &str) -> PngError {\n PngError { description: description.to_owned() }\n }\n}\n"
},
{
"from": "gpt",
"value": "use std::error::Error;\nuse std::fmt;\n\n#[derive(Debug,Clone)]\npub struct PngError {\n description: String,\n}\n\nimpl Error for PngError {\n fn description(&self) -> &str {\n &self.description\n }\n}\n\nimpl fmt::Display for PngError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(f, \"{}\", self.description)\n }\n}\n\nimpl PngError {\n pub fn new(description: &str) -> PngError {\n PngError { description: description.to_owned() }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "[doc] Hide the ioctl FFI declaration\n"
},
{
"from": "human",
"value": "extern crate libc as real_libc;\n#[macro_use]\nextern crate bitflags;\n\n#[cfg(target_os = \"linux\")]\n#[path = \"platform/linux.rs\"]\n#[macro_use]\nmod platform;\n\npub use platform::*;\n\n/// A hack to get the macros to work nicely.\n#[doc(hidden)]\npub use real_libc as libc;\n\nextern \"C\" {\n pub fn ioctl(fd: libc::c_int, req: libc::c_ulong, ...) -> libc::c_int;\n}\n\n#[cfg(not(target_os = \"linux\"))]\nuse platform_not_supported;\n"
},
{
"from": "gpt",
"value": "extern crate libc as real_libc;\n#[macro_use]\nextern crate bitflags;\n\n#[cfg(target_os = \"linux\")]\n#[path = \"platform/linux.rs\"]\n#[macro_use]\nmod platform;\n\npub use platform::*;\n\n/// A hack to get the macros to work nicely.\n#[doc(hidden)]\npub use real_libc as libc;\n\nextern \"C\" {\n #[doc(hidden)]\n pub fn ioctl(fd: libc::c_int, req: libc::c_ulong, ...) -> libc::c_int;\n}\n\n#[cfg(not(target_os = \"linux\"))]\nuse platform_not_supported;\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Change unstable flags for changes to Rust nightly.\n"
},
{
"from": "human",
"value": "#![feature(core)]\n\nextern crate interpolate;\nextern crate num;\n\npub mod vector;\npub mod rect;\npub mod circle;\npub mod grid;\npub mod wrapping_grid;\n\npub use vector::Vec2;\npub use rect::Rect;\npub use circle::Circle;\npub use grid::Grid;\npub use wrapping_grid::WrappingGrid;\n"
},
{
"from": "gpt",
"value": "#![feature(cmp_partial)]\n\nextern crate interpolate;\nextern crate num;\n\npub mod vector;\npub mod rect;\npub mod circle;\npub mod grid;\npub mod wrapping_grid;\n\npub use vector::Vec2;\npub use rect::Rect;\npub use circle::Circle;\npub use grid::Grid;\npub use wrapping_grid::WrappingGrid;\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Replace match blocks with try! macro\n"
},
{
"from": "human",
"value": "//! A crate for parsing Markdown in Rust\n#![crate_name = \"markdown\"]\n#![deny(missing_docs)]\n// #![deny(warnings)]\n\n#![cfg_attr(feature=\"clippy\", feature(plugin))]\n#![cfg_attr(feature=\"clippy\", plugin(clippy))]\n\nextern crate regex;\n\n#[macro_use]\nextern crate pipeline;\n\nuse std::fs::File;\nuse std::path::Path;\nuse std::io::{Read, Error};\n\nmod parser;\nmod html;\n\nuse parser::Block;\n\n/// Converts a Markdown string to HTML\npub fn to_html(text: &str) -> String {\n let result = parser::parse(text);\n html::to_html(&result)\n}\n\n/// Converts a Markdown string to a tokenset of Markdown items\npub fn tokenize(text: &str) -> Vec<Block> {\n parser::parse(text)\n}\n\n/// Opens a file and converts its contents to HTML\npub fn file_to_html(path: &Path) -> Result<String, Error> {\n let mut file = match File::open(path) {\n Ok(file) => file,\n Err(e) => return Err(e),\n };\n\n let mut text = String::new();\n match file.read_to_string(&mut text) {\n Ok(_) => (),\n Err(e) => return Err(e),\n }\n\n let result = parser::parse(&text);\n Ok(html::to_html(&result))\n}\n"
},
{
"from": "gpt",
"value": "//! A crate for parsing Markdown in Rust\n#![crate_name = \"markdown\"]\n#![deny(missing_docs)]\n// #![deny(warnings)]\n\n#![cfg_attr(feature=\"clippy\", feature(plugin))]\n#![cfg_attr(feature=\"clippy\", plugin(clippy))]\n\nextern crate regex;\n\n#[macro_use]\nextern crate pipeline;\n\nuse std::fs::File;\nuse std::path::Path;\nuse std::io::{self, Read};\n\nmod parser;\nmod html;\n\nuse parser::Block;\n\n/// Converts a Markdown string to HTML\npub fn to_html(text: &str) -> String {\n let result = parser::parse(text);\n html::to_html(&result)\n}\n\n/// Converts a Markdown string to a tokenset of Markdown items\npub fn tokenize(text: &str) -> Vec<Block> {\n parser::parse(text)\n}\n\n/// Opens a file and converts its contents to HTML\npub fn file_to_html(path: &Path) -> io::Result<String> {\n let mut file = try!(File::open(path));\n\n let mut text = String::new();\n try!(file.read_to_string(&mut text));\n\n let result = parser::parse(&text);\n Ok(html::to_html(&result))\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Handle one instruction that goes one block\n"
},
{
"from": "human",
"value": "pub fn distance(input: &str) -> i32 {\n 3\n}"
},
{
"from": "gpt",
"value": "pub fn distance(input: &str) -> u32 {\n let mut chars = input.chars();\n if let (Some(turn_dir), Some(num_blocks)) = (chars.next(), chars.next()) {\n let num_blocks: u32 = num_blocks.to_string()\n .parse()\n .expect(\"Cannot parse\");\n return num_blocks\n }\n panic!(\"oh no!\");\n}\n\n#[cfg(test)]\nmod test {\n use super::*;\n\n #[test]\n fn right_one_is_one() {\n assert_eq!(distance(\"R1\"), 1);\n }\n\n #[test]\n fn r1_r1_is_two() {\n assert_eq!(distance(\"R1 R1\"), 2);\n }\n\n}"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove now unused rustc_serialize crate.\n"
},
{
"from": "human",
"value": "//! Implementation of the `Synth` struct for basic polyphonic, multi-oscillator envelope synthesis.\n\nextern crate envelope as envelope_lib;\nextern crate gaussian;\npub extern crate instrument;\nextern crate panning;\nextern crate pitch_calc as pitch;\nextern crate time_calc as time;\nextern crate rand;\nextern crate rustc_serialize;\nextern crate sample;\nextern crate utils;\n\npub use dynamic::Synth as Dynamic;\npub use envelope::{Envelope, Point};\npub use envelope::Trait as EnvelopeTrait;\npub use oscillator::{AmpEnvelope, FreqEnvelope, Oscillator, Waveform};\npub use synth::Synth;\n\npub mod dynamic;\npub mod envelope;\npub mod oscillator;\nmod synth;\n\n#[cfg(feature=\"dsp-chain\")]\nmod dsp_node;\n\n#[cfg(feature=\"serde_serialization\")]\nmod serde;\n"
},
{
"from": "gpt",
"value": "//! Implementation of the `Synth` struct for basic polyphonic, multi-oscillator envelope synthesis.\n\nextern crate envelope as envelope_lib;\nextern crate gaussian;\npub extern crate instrument;\nextern crate panning;\nextern crate pitch_calc as pitch;\nextern crate time_calc as time;\nextern crate rand;\nextern crate sample;\nextern crate utils;\n\npub use dynamic::Synth as Dynamic;\npub use envelope::{Envelope, Point};\npub use envelope::Trait as EnvelopeTrait;\npub use oscillator::{AmpEnvelope, FreqEnvelope, Oscillator, Waveform};\npub use synth::Synth;\n\npub mod dynamic;\npub mod envelope;\npub mod oscillator;\nmod synth;\n\n#[cfg(feature=\"dsp-chain\")]\nmod dsp_node;\n\n#[cfg(feature=\"serde_serialization\")]\nmod serde;\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": ":art: Change the return value to the generic single type \n\n"
},
{
"from": "human",
"value": "extern crate serde;\nextern crate serde_json;\n\nuse hyper::Client;\nuse hyper::client::{Body, Response};\nuse hyper::header::Headers;\nuse hyper::status::StatusCode;\nuse jira_request::*;\nuse std::io::Read;\n\npub fn send<R: JIRARequest, T: serde::de::Deserialize>(request: R) -> Result<Vec<T>, String> {\n let client = Client::new();\n let url = format!(\"{}{}\", &request.base_url(), &request.path());\n\n let mut res: Response = client.request(request.method(), &url)\n .headers(request.headers().unwrap_or(Headers::new()))\n .body(&request.body().unwrap_or(\"\".to_string()))\n .send()\n .map_err(|e| e.to_string())?;\n\n let mut body = String::new();\n res.read_to_string(&mut body).map_err(|e| e.to_string())?;\n match res.status {\n StatusCode::Ok => serde_json::from_str::<Vec<T>>(&body).map_err(|e| e.to_string()),\n _ => Err(body)\n }\n}"
},
{
"from": "gpt",
"value": "extern crate serde;\nextern crate serde_json;\n\nuse hyper::Client;\nuse hyper::client::{Body, Response};\nuse hyper::header::Headers;\nuse hyper::status::StatusCode;\nuse jira_request::*;\nuse std::io::Read;\n\npub fn send<R: JIRARequest, T: serde::de::Deserialize>(request: R) -> Result<T, String> {\n let client = Client::new();\n let url = format!(\"{}{}\", &request.base_url(), &request.path());\n\n let mut res: Response = client.request(request.method(), &url)\n .headers(request.headers().unwrap_or(Headers::new()))\n .body(&request.body().unwrap_or(\"\".to_string()))\n .send()\n .map_err(|e| e.to_string())?;\n\n let mut body = String::new();\n res.read_to_string(&mut body).map_err(|e| e.to_string())?;\n match res.status {\n StatusCode::Ok => serde_json::from_str::<T>(&body).map_err(|e| e.to_string()),\n _ => Err(body)\n }\n}"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix deprecation warning for bare trait obbject.\n"
},
{
"from": "human",
"value": "// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse address::Address;\nuse std::fmt::Debug;\nuse std::io;\nuse std::ops::Range;\n\n#[allow(missing_docs)]\npub enum Error {\n NoSegment,\n IOError(io::Error),\n}\n\n#[allow(missing_docs)]\npub trait Segment: Debug {\n fn range(&self) -> Range<Address>;\n\n fn contains(&self, address: Address, length: u64) -> bool;\n\n fn read_bytes(&self, address: Address, length: u64) -> Result<&[u8], Error>;\n}\n\n#[allow(missing_docs)]\n#[derive(Debug, Default)]\npub struct Memory<'m> {\n segments: Vec<&'m Segment>,\n}\n\nimpl<'m> Memory<'m> {\n #[allow(missing_docs)]\n pub fn new() -> Self {\n Default::default()\n }\n\n #[allow(missing_docs)]\n pub fn read_bytes(&self, address: Address, length: u64) -> Result<&[u8], Error> {\n self.segments\n .iter()\n .find(|&s| s.contains(address, length))\n .map_or(Err(Error::NoSegment), |s| s.read_bytes(address, length))\n }\n}\n"
},
{
"from": "gpt",
"value": "// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse address::Address;\nuse std::fmt::Debug;\nuse std::io;\nuse std::ops::Range;\n\n#[allow(missing_docs)]\npub enum Error {\n NoSegment,\n IOError(io::Error),\n}\n\n#[allow(missing_docs)]\npub trait Segment: Debug {\n fn range(&self) -> Range<Address>;\n\n fn contains(&self, address: Address, length: u64) -> bool;\n\n fn read_bytes(&self, address: Address, length: u64) -> Result<&[u8], Error>;\n}\n\n#[allow(missing_docs)]\n#[derive(Debug, Default)]\npub struct Memory<'m> {\n segments: Vec<&'m dyn Segment>,\n}\n\nimpl<'m> Memory<'m> {\n #[allow(missing_docs)]\n pub fn new() -> Self {\n Default::default()\n }\n\n #[allow(missing_docs)]\n pub fn read_bytes(&self, address: Address, length: u64) -> Result<&[u8], Error> {\n self.segments\n .iter()\n .find(|&s| s.contains(address, length))\n .map_or(Err(Error::NoSegment), |s| s.read_bytes(address, length))\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix build with 'nightly' feature\n"
},
{
"from": "human",
"value": "//! termion is a pure Rust library for reading, manipulating, and handling terminals.\n//!\n//! This crate is not stable, yet. However, if you do want stability, you should specify the\n//! revision (commit hash) in your `Cargo.toml`, this way builds are complete reproducible, and won't\n//! break.\n#![warn(missing_docs)]\n\n\n#[cfg(not(target_os = \"redox\"))]\nextern crate libc;\n\n#[cfg(not(target_os = \"redox\"))]\nmod termios;\n\nmod control;\npub use control::TermWrite;\n\nmod async;\npub use async::{AsyncReader, async_stdin};\n\nmod input;\npub use input::{TermRead, Key};\n#[cfg(feature = \"nightly\")]\npub use input::Keys;\n\nmod raw;\npub use raw::{IntoRawMode, RawTerminal};\n\nmod size;\npub use size::terminal_size;\n\nmod color;\npub use color::Color;\n\nmod style;\npub use style::Style;\n"
},
{
"from": "gpt",
"value": "//! termion is a pure Rust library for reading, manipulating, and handling terminals.\n//!\n//! This crate is not stable, yet. However, if you do want stability, you should specify the\n//! revision (commit hash) in your `Cargo.toml`, this way builds are complete reproducible, and won't\n//! break.\n#![warn(missing_docs)]\n\n#![cfg_attr(feature = \"nightly\", feature(io))]\n\n\n#[cfg(not(target_os = \"redox\"))]\nextern crate libc;\n\n#[cfg(not(target_os = \"redox\"))]\nmod termios;\n\nmod control;\npub use control::TermWrite;\n\nmod async;\npub use async::{AsyncReader, async_stdin};\n\nmod input;\npub use input::{TermRead, Key};\n#[cfg(feature = \"nightly\")]\npub use input::Keys;\n\nmod raw;\npub use raw::{IntoRawMode, RawTerminal};\n\nmod size;\npub use size::terminal_size;\n\nmod color;\npub use color::Color;\n\nmod style;\npub use style::Style;\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use last expression instead of return\n"
},
{
"from": "human",
"value": "\npub fn edit_distance(a: &str, b: &str) -> i32 {\n\n let row: Vec<i32> = vec![0; b.len() + 1];\n let mut matrix: Vec<Vec<i32>> = vec![row; a.len() + 1];\n\n // initialize string a\n for i in (0..a.len()) {\n matrix[i+1][0] = matrix[i][0] + 1;\n }\n\n // initialize string b\n for i in (0..b.len()) {\n matrix[0][i+1] = matrix[0][i] + 1;\n }\n\n // calculate matrix\n for (i, ca) in a.char_indices() {\n for (j, cb) in b.char_indices() {\n\n let mut alternatives = [\n // deletion\n matrix[i][j+1] + 1,\n // insertion\n matrix[i+1][j] + 1,\n // match or substituion\n matrix[i][j] + if ca == cb { 0 } else { 1 }];\n alternatives.sort();\n matrix[i+1][j+1] = *alternatives.first().unwrap();\n }\n }\n\n return matrix[a.len()][b.len()];\n}\n\n#[cfg(test)]\nmod test {\n use super::edit_distance;\n\n #[test]\n fn simple() {\n assert_eq!(edit_distance(\"kitten\", \"sitting\"), 3);\n assert_eq!(edit_distance(\"Tier\", \"Tor\"), 2);\n }\n}\n"
},
{
"from": "gpt",
"value": "\npub fn edit_distance(a: &str, b: &str) -> i32 {\n\n let row: Vec<i32> = vec![0; b.len() + 1];\n let mut matrix: Vec<Vec<i32>> = vec![row; a.len() + 1];\n\n // initialize string a\n for i in (0..a.len()) {\n matrix[i+1][0] = matrix[i][0] + 1;\n }\n\n // initialize string b\n for i in (0..b.len()) {\n matrix[0][i+1] = matrix[0][i] + 1;\n }\n\n // calculate matrix\n for (i, ca) in a.char_indices() {\n for (j, cb) in b.char_indices() {\n\n let mut alternatives = [\n // deletion\n matrix[i][j+1] + 1,\n // insertion\n matrix[i+1][j] + 1,\n // match or substituion\n matrix[i][j] + if ca == cb { 0 } else { 1 }];\n alternatives.sort();\n matrix[i+1][j+1] = *alternatives.first().unwrap();\n }\n }\n\n matrix[a.len()][b.len()]\n}\n\n#[cfg(test)]\nmod test {\n use super::edit_distance;\n\n #[test]\n fn simple() {\n assert_eq!(edit_distance(\"kitten\", \"sitting\"), 3);\n assert_eq!(edit_distance(\"Tier\", \"Tor\"), 2);\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix the tests for OneOrMany.\n"
},
{
"from": "human",
"value": "//use serde::de::Deserialize;\nuse super::super::link::HalLink;\nuse super::super::resource::OneOrMany;\nuse serde_json::{from_str, to_string};\nuse serde::*;\n\n#[derive(Serialize, Deserialize)]\nstruct Boh<T:Clone>\n{\n oom: OneOrMany<T>\n}\n\n#[test]\nfn ensure_one_object_gets_serialized_as_one() {\n let boh: Boh<String> = Boh { oom: OneOrMany::new().with(&\"test\".to_owned()) };\n assert_eq!(to_string(&boh).unwrap(), r#\"{\"oom\":\"test\"}\"#);\n}\n\n#[test]\nfn ensure_two_objects_get_serialized_as_array() {\n\n let boh: Boh<String> = Boh { oom: OneOrMany::new().with(&\"test\".to_owned()).with(&\"test2\".to_owned()) };\n assert_eq!(to_string(&boh).unwrap(), r#\"{\"oom\":[\"test\",\"test2\"]}\"#);\n}\n\n\n#[test]\nfn ensure_array_gets_deserialized() {\n let s = r#\"{\"oom\":[\"test\",\"test2\"]}\"#;\n let boh: Boh<String> = from_str(s).unwrap();\n assert_eq!(2, boh.oom.len());\n assert_eq!(\"test\", boh.oom[0]);\n assert_eq!(\"test2\", boh.oom[1]);\n\n}"
},
{
"from": "gpt",
"value": "//use serde::de::Deserialize;\nuse super::super::link::HalLink;\nuse super::super::resource::OneOrMany;\nuse serde_json::{from_str, to_string};\nuse serde::*;\n\n#[derive(Serialize, Deserialize)]\nstruct Boh\n{\n oom: OneOrMany<String>\n}\n\n#[test]\nfn ensure_one_object_gets_serialized_as_one() {\n let boh = Boh { oom: OneOrMany::new().with(&\"test\".to_owned()) };\n assert_eq!(to_string(&boh).unwrap(), r#\"{\"oom\":\"test\"}\"#);\n}\n\n#[test]\nfn ensure_two_objects_get_serialized_as_array() {\n\n let boh = Boh { oom: OneOrMany::new().with(&\"test\".to_owned()).with(&\"test2\".to_owned()) };\n assert_eq!(to_string(&boh).unwrap(), r#\"{\"oom\":[\"test\",\"test2\"]}\"#);\n}\n\n\n#[test]\nfn ensure_array_gets_deserialized() {\n let s = r#\"{\"oom\":[\"test\",\"test2\"]}\"#;\n let boh: Boh = from_str(s).unwrap();\n assert_eq!(2, boh.oom.len());\n assert_eq!(\"test\", boh.oom.many()[0]);\n assert_eq!(\"test2\", boh.oom.many()[1]);\n\n}"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add stub root module documentation\n"
},
{
"from": "human",
"value": "extern crate time;\nextern crate serde;\nextern crate serde_json;\n\nmod user;\nmod message;\npub mod json;\n\npub use self::user::*;\npub use self::message::*;\n"
},
{
"from": "gpt",
"value": "//! `chattium-oxide-client` and `chattium-oxide-server` common files\n//!\n//! chattium-oxide-client: https://github.com/nabijaczleweli/chattium-oxide-client\n//! chattium-oxide-server: https://github.com/nabijaczleweli/chattium-oxide-server\n\nextern crate time;\nextern crate serde;\nextern crate serde_json;\n\nmod user;\nmod message;\npub mod json;\n\npub use self::user::*;\npub use self::message::*;\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Drop the dependency on a macros crate\n"
},
{
"from": "human",
"value": "#![feature(backtrace)]\n\nmod as_error;\nmod exception;\nmod context;\n\n#[doc(inline)]\n/// Annotations a function that \"throws\" a Result.\n///\n/// Inside functions tagged with `throws`, you can use `?` and the `throw!` macro to return errors,\n/// but you don't need to wrap the successful return values in `Ok`.\n///\n/// `throws` can optionally take a type as an argument, which will be the error type returned by\n/// this function. By default, the function will throw `Exception`.\npub use fehler_macros::throws;\n\n#[doc(inline)]\n/// Derive for the Error trait.\n///\n/// If the type contains a `Backtrace`, it will generate the `backtrace` method to find it.\n///\n/// If this wraps a different, underlying error, you can tag that field with `#[error::source]`,\n/// which will generate the `cause` and `source` methods correctly.\npub use fehler_macros::Error;\n\npub use crate::as_error::AsError;\npub use crate::exception::{Exception, Errors};\npub use crate::context::Context;\n\n/// Throw an error.\n///\n/// This macro is equivalent to `Err($err)?`.\n#[macro_export]\nmacro_rules! throw {\n ($err:expr) => (return std::result::Result::Err(std::convert::From::from($err)))\n}\n\n/// Construct an ad-hoc exception from a string.\n///\n/// This evaluates to an `Exception`. It can take either just a string, or a format string with\n/// arguments. It also can take any custom type which implements `Debug` and `Display`.\n#[macro_export]\nmacro_rules! error {\n ($e:expr) => { $crate::Exception::new_adhoc($e) };\n ($($arg:tt)*) => { $crate::Exception::new_adhoc(format!($($arg)*)) };\n}\n"
},
{
"from": "gpt",
"value": "#![feature(backtrace)]\n\nmod as_error;\nmod exception;\nmod context;\n\npub use crate::as_error::AsError;\npub use crate::exception::{Exception, Errors};\npub use crate::context::Context;\n\n/// Throw an error.\n///\n/// This macro is equivalent to `Err($err)?`.\n#[macro_export]\nmacro_rules! throw {\n ($err:expr) => (return std::result::Result::Err(std::convert::From::from($err)))\n}\n\n/// Construct an ad-hoc exception from a string.\n///\n/// This evaluates to an `Exception`. It can take either just a string, or a format string with\n/// arguments. It also can take any custom type which implements `Debug` and `Display`.\n#[macro_export]\nmacro_rules! error {\n ($e:expr) => { $crate::Exception::new_adhoc($e) };\n ($($arg:tt)*) => { $crate::Exception::new_adhoc(format!($($arg)*)) };\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add example to module documentation.\n"
},
{
"from": "human",
"value": "//! Implementation of the Micro Transport Protocol.[^spec]\n//!\n//! [^spec]: http://www.bittorrent.org/beps/bep_0029.html\n\n// __________ ____ ____\n// /_ __/ __ \\/ __ \\/ __ \\\n// / / / / / / / / / / / /\n// / / / /_/ / /_/ / /_/ /\n// /_/ \\____/_____/\\____/\n//\n// - Lossy UDP socket for testing purposes: send and receive ops are wrappers\n// that stochastically drop or reorder packets.\n// - Sending FIN on drop\n// - Handle packet loss\n// - Path MTU discovery (RFC4821)\n\n#![deny(missing_docs)]\n#![feature(core, collections, io)]\n\nextern crate rand;\nextern crate time;\n#[macro_use] extern crate log;\n\n// Public API\npub use socket::UtpSocket;\npub use stream::UtpStream;\n\nmod util;\nmod bit_iterator;\nmod packet;\nmod socket;\nmod stream;\n"
},
{
"from": "gpt",
"value": "//! Implementation of the Micro Transport Protocol.[^spec]\n//!\n//! [^spec]: http://www.bittorrent.org/beps/bep_0029.html\n\n//! # Examples\n//!\n//! ```\n//! extern crate utp;\n//!\n//! use utp::UtpStream;\n//! use std::io::{Read, Write};\n//!\n//! fn main() {\n//! // Connect to an hypothetical local server running on port 8080\n//! let addr = \"127.0.0.1:8080\";\n//! let mut stream = match UtpStream::connect(addr) {\n//! Ok(stream) => stream,\n//! Err(e) => panic!(\"{}\", e),\n//! };\n//!\n//! // Send a string\n//! match stream.write(\"Hi there!\".as_bytes()) {\n//! Ok(_) => (),\n//! Err(e) => println!(\"Write failed with {}\", e)\n//! }\n//!\n//! // Close the stream\n//! match stream.close() {\n//! Ok(()) => println!(\"Connection closed\"),\n//! Err(e) => println!(\"{}\", e)\n//! }\n//! }\n//! ```\n\n// __________ ____ ____\n// /_ __/ __ \\/ __ \\/ __ \\\n// / / / / / / / / / / / /\n// / / / /_/ / /_/ / /_/ /\n// /_/ \\____/_____/\\____/\n//\n// - Lossy UDP socket for testing purposes: send and receive ops are wrappers\n// that stochastically drop or reorder packets.\n// - Sending FIN on drop\n// - Handle packet loss\n// - Path MTU discovery (RFC4821)\n\n#![deny(missing_docs)]\n#![feature(core, collections, io)]\n\nextern crate rand;\nextern crate time;\n#[macro_use] extern crate log;\n\n// Public API\npub use socket::UtpSocket;\npub use stream::UtpStream;\n\nmod util;\nmod bit_iterator;\nmod packet;\nmod socket;\nmod stream;\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add Table type, Read, Write trait\n"
},
{
"from": "human",
"value": "pub mod ascii_writer;\npub mod markdown_writer;\n"
},
{
"from": "gpt",
"value": "pub mod ascii_writer;\npub mod markdown_writer;\n\npub struct Table {\n rows: Vec<Vec<String>>,\n has_headers: bool,\n}\n\npub struct Error {}\n\npub trait Read {\n fn read(&mut self) -> Result<Table, Error>;\n}\n\npub trait Write {\n fn write(&self, table: Table) -> Result<(), Error>;\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Make DeleteStatement and UpdateStatement public\n"
},
{
"from": "human",
"value": "#[macro_use]\nextern crate nom;\n\nextern crate serde;\n#[macro_use]\nextern crate serde_derive;\n\npub use self::arithmetic::{ArithmeticBase, ArithmeticExpression, ArithmeticOperator};\npub use self::common::{FieldExpression, Literal, Operator, SqlType, TableKey};\npub use self::column::{Column, ColumnConstraint, ColumnSpecification, FunctionExpression};\npub use self::condition::{ConditionBase, ConditionExpression, ConditionTree};\npub use self::create::CreateTableStatement;\npub use self::insert::InsertStatement;\npub use self::join::{JoinConstraint, JoinOperator, JoinRightSide};\npub use self::parser::*;\npub use self::compound_select::{CompoundSelectOperator, CompoundSelectStatement};\npub use self::select::{GroupByClause, JoinClause, LimitClause, OrderClause, OrderType,\n SelectStatement};\npub use self::table::Table;\npub use self::set::SetStatement;\n\npub mod parser;\n\n#[macro_use]\nmod keywords;\nmod arithmetic;\nmod column;\nmod common;\nmod condition;\nmod create;\nmod insert;\nmod join;\nmod select;\nmod compound_select;\nmod table;\nmod delete;\nmod update;\nmod set;\n"
},
{
"from": "gpt",
"value": "#[macro_use]\nextern crate nom;\n\nextern crate serde;\n#[macro_use]\nextern crate serde_derive;\n\npub use self::arithmetic::{ArithmeticBase, ArithmeticExpression, ArithmeticOperator};\npub use self::common::{FieldExpression, Literal, Operator, SqlType, TableKey};\npub use self::column::{Column, ColumnConstraint, ColumnSpecification, FunctionExpression};\npub use self::condition::{ConditionBase, ConditionExpression, ConditionTree};\npub use self::create::CreateTableStatement;\npub use self::delete::DeleteStatement;\npub use self::insert::InsertStatement;\npub use self::join::{JoinConstraint, JoinOperator, JoinRightSide};\npub use self::parser::*;\npub use self::compound_select::{CompoundSelectOperator, CompoundSelectStatement};\npub use self::select::{GroupByClause, JoinClause, LimitClause, OrderClause, OrderType,\n SelectStatement};\npub use self::table::Table;\npub use self::set::SetStatement;\npub use self::update::UpdateStatement;\n\npub mod parser;\n\n#[macro_use]\nmod keywords;\nmod arithmetic;\nmod column;\nmod common;\nmod condition;\nmod create;\nmod insert;\nmod join;\nmod select;\nmod compound_select;\nmod table;\nmod delete;\nmod update;\nmod set;\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Make the wrapper type for Uri cloneable\n"
},
{
"from": "human",
"value": "use hyper::Uri as HyperUri;\nuse std::path::Path;\n\n/// A convenience type that can be used to construct Unix Domain Socket URIs\n///\n/// This type implements `Into<hyper::Uri>`.\n///\n/// # Example\n/// ```\n/// use hyperlocal::Uri;\n/// use hyper::Uri as HyperUri;\n///\n/// let uri: HyperUri = Uri::new(\"/tmp/hyperlocal.sock\", \"/\").into();\n/// ```\n#[derive(Debug)]\npub struct Uri {\n hyper_uri: HyperUri,\n}\n\nimpl Uri {\n /// Create a new `[Uri]` from a socket address and a path\n pub fn new(socket: impl AsRef<Path>, path: &str) -> Self {\n let host = hex::encode(socket.as_ref().to_string_lossy().as_bytes());\n let host_str = format!(\"unix://{}:0{}\", host, path);\n let hyper_uri: HyperUri = host_str.parse().unwrap();\n\n Self { hyper_uri }\n }\n}\n\nimpl From<Uri> for HyperUri {\n fn from(uri: Uri) -> Self {\n uri.hyper_uri\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::Uri;\n use hyper::Uri as HyperUri;\n\n #[test]\n fn test_unix_uri_into_hyper_uri() {\n let unix: HyperUri = Uri::new(\"foo.sock\", \"/\").into();\n let expected: HyperUri = \"unix://666f6f2e736f636b:0/\".parse().unwrap();\n assert_eq!(unix, expected);\n }\n}\n"
},
{
"from": "gpt",
"value": "use hyper::Uri as HyperUri;\nuse std::path::Path;\n\n/// A convenience type that can be used to construct Unix Domain Socket URIs\n///\n/// This type implements `Into<hyper::Uri>`.\n///\n/// # Example\n/// ```\n/// use hyperlocal::Uri;\n/// use hyper::Uri as HyperUri;\n///\n/// let uri: HyperUri = Uri::new(\"/tmp/hyperlocal.sock\", \"/\").into();\n/// ```\n#[derive(Debug, Clone)]\npub struct Uri {\n hyper_uri: HyperUri,\n}\n\nimpl Uri {\n /// Create a new `[Uri]` from a socket address and a path\n pub fn new(socket: impl AsRef<Path>, path: &str) -> Self {\n let host = hex::encode(socket.as_ref().to_string_lossy().as_bytes());\n let host_str = format!(\"unix://{}:0{}\", host, path);\n let hyper_uri: HyperUri = host_str.parse().unwrap();\n\n Self { hyper_uri }\n }\n}\n\nimpl From<Uri> for HyperUri {\n fn from(uri: Uri) -> Self {\n uri.hyper_uri\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::Uri;\n use hyper::Uri as HyperUri;\n\n #[test]\n fn test_unix_uri_into_hyper_uri() {\n let unix: HyperUri = Uri::new(\"foo.sock\", \"/\").into();\n let expected: HyperUri = \"unix://666f6f2e736f636b:0/\".parse().unwrap();\n assert_eq!(unix, expected);\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use eprintln from Rust 1.19\n"
},
{
"from": "human",
"value": "/*\n * Copyright (c) 2015-2017 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nmacro_rules! eprintln (\n ($($arg:tt)*) => { {\n use std::io::Write;\n\n writeln!(&mut ::std::io::stderr(), $($arg)*).expect(\"write failed\");\n } }\n);\n\n// writeln_paced is similar to writeln except it reduces the risk of loggregator missing some entries\n// by sleeping before each write. Also, it panics if the underlying writeln fails.\nmacro_rules! writeln_paced (\n ($($arg:tt)*) => { {\n use std::{thread, time};\n #[allow(unused_imports)]\n use std::io::Write;\n\n thread::sleep(time::Duration::from_millis(1));\n\n writeln!($($arg)*).expect(\"write failed\");\n } }\n);\n"
},
{
"from": "gpt",
"value": "/*\n * Copyright (c) 2015-2017 the original author or authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// writeln_paced is similar to writeln except it reduces the risk of loggregator missing some entries\n// by sleeping before each write. Also, it panics if the underlying writeln fails.\nmacro_rules! writeln_paced (\n ($($arg:tt)*) => { {\n use std::{thread, time};\n #[allow(unused_imports)]\n use std::io::Write;\n\n thread::sleep(time::Duration::from_millis(1));\n\n writeln!($($arg)*).expect(\"write failed\");\n } }\n);\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Simplify code to find template path\n"
},
{
"from": "human",
"value": "extern crate askama;\nextern crate proc_macro;\nextern crate syn;\n\nuse proc_macro::TokenStream;\n\nfn get_path_from_attrs(attrs: &Vec<syn::Attribute>) -> String {\n for attr in attrs {\n if attr.name() == \"template\" {\n match attr.value {\n syn::MetaItem::List(_, ref inner) => {\n match inner[0] {\n syn::NestedMetaItem::MetaItem(ref item) => {\n match item {\n &syn::MetaItem::NameValue(ref key, ref val) => {\n assert_eq!(key.as_ref(), \"path\");\n match val {\n &syn::Lit::Str(ref s, _) => { return s.clone(); },\n _ => panic!(\"template path must be a string\"),\n }\n },\n _ => panic!(\"template annotation must contain key/value pair\"),\n }\n },\n _ => panic!(\"template annotation must contain item\"),\n }\n },\n _ => panic!(\"template annotation must be of List type\"),\n }\n }\n }\n panic!(\"template annotation not found\");\n}\n\n#[proc_macro_derive(Template, attributes(template))]\npub fn derive_template(input: TokenStream) -> TokenStream {\n let source = input.to_string();\n\n let ast = syn::parse_derive_input(&source).unwrap();\n let _ctx = match ast.body {\n syn::Body::Struct(ref data) => data,\n _ => panic!(\"#[derive(Template)] can only be used with structs\"),\n };\n\n let path = get_path_from_attrs(&ast.attrs);\n askama::build_template(&path, &ast).parse().unwrap()\n}\n"
},
{
"from": "gpt",
"value": "extern crate askama;\nextern crate proc_macro;\nextern crate syn;\n\nuse proc_macro::TokenStream;\n\nfn get_path_from_attrs(attrs: &[syn::Attribute]) -> String {\n let attr = attrs.iter().find(|a| a.name() == \"template\").unwrap();\n if let syn::MetaItem::List(_, ref inner) = attr.value {\n if let syn::NestedMetaItem::MetaItem(ref item) = inner[0] {\n if let &syn::MetaItem::NameValue(ref key, ref val) = item {\n assert_eq!(key.as_ref(), \"path\");\n if let &syn::Lit::Str(ref s, _) = val {\n return s.clone();\n }\n }\n }\n }\n panic!(\"template path not found in struct attributes\");\n}\n\n#[proc_macro_derive(Template, attributes(template))]\npub fn derive_template(input: TokenStream) -> TokenStream {\n let source = input.to_string();\n\n let ast = syn::parse_derive_input(&source).unwrap();\n let _ctx = match ast.body {\n syn::Body::Struct(ref data) => data,\n _ => panic!(\"#[derive(Template)] can only be used with structs\"),\n };\n\n let path = get_path_from_attrs(&ast.attrs);\n askama::build_template(&path, &ast).parse().unwrap()\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use `compile_error!` instead of `use num_cpus`\n"
},
{
"from": "human",
"value": "#[cfg(doctest)]\nuse num_cpus as _;\n\n#[cfg(test)]\ncompile_error!(\"Miri should not touch me\");\n"
},
{
"from": "gpt",
"value": "#[cfg(doctest)]\ncompile_error!(\"rustdoc should not touch me\");\n\n#[cfg(test)]\ncompile_error!(\"Miri should not touch me\");\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use the new pkgconfig API\n"
},
{
"from": "human",
"value": "#[cfg(feature=\"pkg-config\")]\nextern crate \"pkg-config\" as pkg_config;\n\nfn main() {\n if !build_pkgconfig() {\n println!(\"cargo:rustc-flags=-l SDL2\");\n }\n}\n\n#[cfg(not(feature=\"pkg-config\"))]\nfn build_pkgconfig() -> bool {\n false\n}\n\n#[cfg(feature=\"pkg-config\")]\nfn build_pkgconfig() -> bool {\n let opts = pkg_config::default_options(\"sdl2\");\n if pkg_config::find_library_opts(\"sdl2\", &opts).is_err() {\n panic!(\"Could not find SDL2 via pkgconfig\");\n }\n true\n}\n"
},
{
"from": "gpt",
"value": "#[cfg(feature=\"pkg-config\")]\nextern crate \"pkg-config\" as pkg_config;\n\nfn main() {\n if !build_pkgconfig() {\n println!(\"cargo:rustc-flags=-l SDL2\");\n }\n}\n\n#[cfg(not(feature=\"pkg-config\"))]\nfn build_pkgconfig() -> bool {\n false\n}\n\n#[cfg(feature=\"pkg-config\")]\nfn build_pkgconfig() -> bool {\n if pkg_config::find_library(\"sdl2\").is_err() {\n panic!(\"Could not find SDL2 via pkgconfig\");\n }\n true\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add macro_use to allow usages of panic! and sorts\n"
},
{
"from": "human",
"value": "#![crate_name = \"kernel\"]\n#![crate_type = \"staticlib\"]\n#![no_std]\n#![feature(asm, lang_items)]\n#![feature(core)]\n\nextern crate core;\nextern crate rlibc;\n\n#[path = \"arch/x86/\"]\npub mod platform {\n\tpub mod vga;\n\tpub mod cpu;\n\tpub mod mmu;\n\tmod io;\n\tpub mod keyboard;\n}\n\npub mod kernel {\n\tpub mod main;\n\tpub mod interrupts;\n\tmod stdio;\n\tmod keyboard;\n}\n\n// Remove this when https://github.com/rust-lang/rust/issues/21827 is solved\nmod std {\n pub mod option {\n pub use core::option::*;\n }\n pub mod iter {\n pub use core::iter::*;\n }\n}\n\n#[lang = \"stack_exhausted\"] extern fn stack_exhausted() {}\n#[lang = \"eh_personality\"] extern fn eh_personality() {}\n"
},
{
"from": "gpt",
"value": "#![crate_name = \"kernel\"]\n#![crate_type = \"staticlib\"]\n#![no_std]\n#![feature(asm, lang_items)]\n#![feature(core)]\n\n#[macro_use] extern crate core;\nextern crate rlibc;\n\n#[path = \"arch/x86/\"]\npub mod platform {\n\tpub mod vga;\n\tpub mod cpu;\n\tpub mod mmu;\n\tmod io;\n\tpub mod keyboard;\n}\n\npub mod kernel {\n\tpub mod main;\n\tpub mod interrupts;\n\tmod stdio;\n\tmod keyboard;\n}\n\n// Remove this when https://github.com/rust-lang/rust/issues/21827 is solved\nmod std {\n pub mod option {\n pub use core::option::*;\n }\n pub mod iter {\n pub use core::iter::*;\n }\n}\n\n#[lang = \"stack_exhausted\"] extern fn stack_exhausted() {}\n#[lang = \"eh_personality\"] extern fn eh_personality() {}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove unsafe use of unsafe and instead panic\n"
},
{
"from": "human",
"value": "use std::str::{from_utf8_unchecked, FromStr};\n\npub fn to_string(s: &[u8]) -> &str {\n unsafe { from_utf8_unchecked(s) }\n}\npub fn to_u32(s: &str) -> u32 {\n FromStr::from_str(s).unwrap()\n}\n\npub fn buf_to_u32(s: &[u8]) -> u32 {\n to_u32(to_string(s))\n}\n"
},
{
"from": "gpt",
"value": "use std::str::{self, FromStr};\n\npub fn buf_to_u32(s: &[u8]) -> u32 {\n let s = str::from_utf8(s).expect(\"Invalid data, expected UTF-8 string\");\n FromStr::from_str(s).expect(\"Invalid string, expected ASCII reprensation of a number\")\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove Debug implementation for now.\n\nDebugStruct only stabilized in 1.2.0\n"
},
{
"from": "human",
"value": "extern crate encoding;\n\nuse std::fmt;\n\nuse self::encoding::types::EncodingRef;\n\n/// ParseOptions allows setting options for parsing MO catalogs.\npub struct ParseOptions {\n force_encoding: Option<EncodingRef>,\n}\n\nimpl ParseOptions {\n /// Returns a new instance of ParseOptions with default options.\n pub fn new() -> Self {\n ParseOptions { force_encoding: None }\n }\n\n /// Forces a use of a specific encoding\n /// when parsing strings from a catalog.\n /// If this option is not enabled,\n /// the parser tries to use the encoding specified in the metadata\n /// or UTF-8 if metadata is non-existent.\n pub fn force_encoding(&mut self, encoding: EncodingRef) -> &mut Self {\n self.force_encoding = Some(encoding);\n self\n }\n}\n\n// Cannot derive as Encoding does not implement Debug.\nimpl fmt::Debug for ParseOptions {\n fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {\n let mut debug_fmt = fmt.debug_struct(\"ParseOptions\");\n match self.force_encoding {\n opt @ Some(_) => {\n debug_fmt.field(\"force_encoding\", &opt.map(|e| e.name()));\n }\n opt @ None => {\n // HACK: convert Option<EncodingRef> to Option<()> with map()\n // to get a Debug impl.\n debug_fmt.field(\"force_encoding\", &opt.map(|_| ()));\n }\n }\n debug_fmt.finish()\n }\n}\n"
},
{
"from": "gpt",
"value": "extern crate encoding;\n\nuse std::fmt;\n\nuse self::encoding::types::EncodingRef;\n\n/// ParseOptions allows setting options for parsing MO catalogs.\n#[allow(missing_debug_implementations)]\npub struct ParseOptions {\n force_encoding: Option<EncodingRef>,\n}\n\nimpl ParseOptions {\n /// Returns a new instance of ParseOptions with default options.\n pub fn new() -> Self {\n ParseOptions { force_encoding: None }\n }\n\n /// Forces a use of a specific encoding\n /// when parsing strings from a catalog.\n /// If this option is not enabled,\n /// the parser tries to use the encoding specified in the metadata\n /// or UTF-8 if metadata is non-existent.\n pub fn force_encoding(&mut self, encoding: EncodingRef) -> &mut Self {\n self.force_encoding = Some(encoding);\n self\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix parsing JSON containing URLs with escaping\n\nScenario: PHP escapes slashes when encoding JSON. Any escaping in a string\nmeans Serde cannot return a string slice anymore, only an owned string. Our URL\nparsing was relying on deserializing as a string slice.\n"
},
{
"from": "human",
"value": "use url::Url;\nuse serde::de::{Deserialize, Deserializer, Error as DeserializeError};\nuse serde::ser::{Serialize, Serializer};\n\n\n/// Unit struct which can be used to serialize a Url.\n///\n/// `#[serde(with = \"UrlDef\")]`\npub struct UrlDef;\nimpl UrlDef {\n pub fn deserialize<'de, D>(deserializer: D) -> Result<Url, D::Error>\n where D: Deserializer<'de> {\n <&str>::deserialize(deserializer).and_then(|s| {\n s.parse().map_err(|e| DeserializeError::custom(format!(\"invalid URL: {}\", e)))\n })\n }\n\n pub fn serialize<S>(url: &Url, serializer: S) -> Result<S::Ok, S::Error>\n where S: Serializer {\n url.as_str().serialize(serializer)\n }\n}\n"
},
{
"from": "gpt",
"value": "use url::Url;\nuse serde::de::{Deserialize, Deserializer, Error as DeserializeError};\nuse serde::ser::{Serialize, Serializer};\n\n\n/// Unit struct which can be used to serialize a Url.\n///\n/// `#[serde(with = \"UrlDef\")]`\npub struct UrlDef;\nimpl UrlDef {\n pub fn deserialize<'de, D>(deserializer: D) -> Result<Url, D::Error>\n where D: Deserializer<'de> {\n <String>::deserialize(deserializer).and_then(|s| {\n s.parse().map_err(|e| DeserializeError::custom(format!(\"invalid URL: {}\", e)))\n })\n }\n\n pub fn serialize<S>(url: &Url, serializer: S) -> Result<S::Ok, S::Error>\n where S: Serializer {\n url.as_str().serialize(serializer)\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add comment to unsafe use.\n"
},
{
"from": "human",
"value": "// Copyright 2019 The Exonum Team\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//! An implementation of an array list of items.\n//!\n//! The given section contains methods related to `ListIndex` and the iterator\n//! over the items of this list.\n\nmacro_rules! concat_keys {\n (@capacity $key:expr) => ( $key.size() );\n (@capacity $key:expr, $($tail:expr),+) => (\n $key.size() + concat_keys!(@capacity $($tail),+)\n );\n ($($key:expr),+) => ({\n let capacity = concat_keys!(@capacity $($key),+);\n let mut buf = Vec::with_capacity(capacity);\n\n #[allow(unsafe_code)]\n unsafe {\n buf.set_len(capacity);\n }\n\n let mut _pos = 0;\n $(\n _pos += $key.write(&mut buf[_pos.._pos + $key.size()]);\n )*\n buf\n });\n}\n"
},
{
"from": "gpt",
"value": "// Copyright 2019 The Exonum Team\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n//! An implementation of an array list of items.\n//!\n//! The given section contains methods related to `ListIndex` and the iterator\n//! over the items of this list.\n\nmacro_rules! concat_keys {\n (@capacity $key:expr) => ( $key.size() );\n (@capacity $key:expr, $($tail:expr),+) => (\n $key.size() + concat_keys!(@capacity $($tail),+)\n );\n ($($key:expr),+) => ({\n let capacity = concat_keys!(@capacity $($key),+);\n let mut buf = Vec::with_capacity(capacity);\n\n // Unsafe `set_len` here is safe because we never read from `buf`\n // before we write all elements to it.\n #[allow(unsafe_code)]\n unsafe {\n buf.set_len(capacity);\n }\n\n let mut _pos = 0;\n $(\n _pos += $key.write(&mut buf[_pos.._pos + $key.size()]);\n )*\n buf\n });\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add a newline after pretty printing\n"
},
{
"from": "human",
"value": "extern crate ppbert;\n\nuse std::io;\nuse std::io::Read;\n\nuse ppbert::parser;\nuse ppbert::pretty;\n\nfn main() {\n let mut stdin = io::stdin();\n let mut buf: Vec<u8> = Vec::new();\n\n let _ = stdin.read_to_end(&mut buf);\n let mut parser = parser::Parser::new(buf);\n match parser.parse() {\n Ok(ref term) => { pretty::print(term, 0); }\n Err(error) => { println!(\"ppbert: {}\", error); }\n }\n}\n"
},
{
"from": "gpt",
"value": "extern crate ppbert;\n\nuse std::io;\nuse std::io::Read;\n\nuse ppbert::parser;\nuse ppbert::pretty;\n\nfn main() {\n let mut stdin = io::stdin();\n let mut buf: Vec<u8> = Vec::new();\n\n let _ = stdin.read_to_end(&mut buf);\n let mut parser = parser::Parser::new(buf);\n match parser.parse() {\n Ok(ref term) => {\n pretty::print(term, 0);\n println!();\n }\n Err(error) => { println!(\"ppbert: {}\", error); }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Simplify command parsing; Add input loop\n"
},
{
"from": "human",
"value": "mod diff;\n\nuse std::io;\n\nenum Mode {\n Command,\n Input,\n}\n\nstruct Range {\n start: i32,\n end: i32,\n}\n\n\nfn command_line(line: &String, mode: &mut Mode) {\n match line.trim() {\n \"a\" => *mode = Mode::Input,\n \"q\" => std::process::exit(0),\n _ => println!(\"Command: {}\", line),\n }\n}\n\nfn input_line(line: &String, mode: &mut Mode) {\n match line.trim() {\n \".\" => *mode = Mode::Command,\n _ => println!(\"Input: {}\", line),\n }\n}\n\nfn append_after(lines: Vec<String>, range: Range, diff: &mut diff::Diff) {\n diff.add_lines(range.start, lines);\n}\n\nfn main() {\n let mut mode = Mode::Command;\n loop {\n let mut line = String::new();\n match io::stdin().read_line(&mut line) {\n Ok(_) => (),\n Err(_) => {\n println!(\"?\");\n continue\n },\n }\n match mode {\n Mode::Command => command_line(&line, &mut mode),\n Mode::Input => input_line(&line, &mut mode),\n }\n }\n}\n"
},
{
"from": "gpt",
"value": "mod diff;\n\nuse std::io;\n\nstruct Range {\n start: i32,\n end: i32,\n}\n\nfn input() -> Vec<String> {\n let mut lines: Vec<String> = Vec::new();\n loop {\n let mut line = String::new();\n io::stdin().read_line(&mut line)\n .ok()\n .expect(\"Error reading line\");\n match line.trim() {\n \".\" => {\n break\n },\n _ => {\n lines.push(line)\n }\n }\n }\n return lines;\n}\n\nfn command(line: &String, line_num: &mut i32, diff: &mut diff::Diff) {\n // parse the command line to get\n // Line num or range\n // command\n match line.trim() {\n \"a\" => {\n append_after(Range{start: *line_num, end: *line_num}, diff);\n },\n \"q\" => std::process::exit(0),\n _ => println!(\"Command: {}\", line),\n }\n}\n\nfn append_after(range: Range, diff: &mut diff::Diff) {\n diff.add_lines(range.end+1, input());\n}\n\nfn main() {\n let prompt = \":\";\n let mut diff = diff::Diff::new();\n let mut line_num: i32 = 1;\n loop {\n let mut line = String::new();\n match io::stdin().read_line(&mut line) {\n Ok(_) => (),\n Err(_) => {\n println!(\"?\");\n continue\n },\n }\n command(&line, &mut line_num, &mut diff);\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Call init_logger after parsing the args.\n"
},
{
"from": "human",
"value": "use std::io::Write;\n\nextern crate watchexec;\n\nuse watchexec::{cli, error, run};\n\nfn main() -> error::Result<()> {\n run(cli::get_args()?)\n}\n\nfn init_logger(debug: bool) {\n let mut log_builder = env_logger::Builder::new();\n let level = if debug {\n log::LevelFilter::Debug\n } else {\n log::LevelFilter::Warn\n };\n\n log_builder\n .format(|buf, r| writeln!(buf, \"*** {}\", r.args()))\n .filter(None, level)\n .init();\n}\n"
},
{
"from": "gpt",
"value": "use std::io::Write;\n\nextern crate watchexec;\n\nuse watchexec::{cli, error, run};\n\nfn main() -> error::Result<()> {\n let args = cli::get_args()?;\n init_logger(args.debug);\n run(args)\n}\n\nfn init_logger(debug: bool) {\n let mut log_builder = env_logger::Builder::new();\n let level = if debug {\n log::LevelFilter::Debug\n } else {\n log::LevelFilter::Warn\n };\n\n log_builder\n .format(|buf, r| writeln!(buf, \"*** {}\", r.args()))\n .filter(None, level)\n .init();\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add options struct & optionals\n\nWhy you made the change:\n\nI did this so that the code would be a bit cleaner.\n"
},
{
"from": "human",
"value": "extern crate argparse;\n\nuse argparse::{ArgumentParser, StoreTrue, Store, StoreOption, Print};\n\nfn main() {\n let mut debug = false;\n let mut path = \"\".to_string();\n let mut file: Option<String> = None;\n { // block limits of borrows by refer() method calls\n let mut ap = ArgumentParser::new();\n ap.add_option(&[\"-v\", \"--version\"], Print(env!(\"CARGO_PKG_VERSION\").to_string()), \"show version\");\n ap.refer(&mut debug).add_option(&[\"-d\", \"--debug\"], StoreTrue, \"enable debug output\");\n ap.refer(&mut file).add_option(&[\"-f\", \"--file\"], StoreOption, \"possible alternates file, - for stdin\");\n ap.refer(&mut path).add_argument(\"PATH\", Store, \"path to find alternate for\").required();\n ap.parse_args_or_exit();\n }\n\n println!(\"required path: {}\", path);\n\n if let Some(unwrapped_file) = file {\n println!(\"file: {}\", unwrapped_file);\n }\n\n println!(\"debug: {}\", debug);\n}\n"
},
{
"from": "gpt",
"value": "extern crate argparse;\n\nuse argparse::{ArgumentParser, StoreTrue, Store, StoreOption, Print};\nuse std::io::BufRead;\n\nstruct Options {\n debug: bool,\n path: String,\n file: Option<String>\n}\n\nfn main() {\n let mut options = Options {\n debug: false,\n path: \"\".to_string(),\n file: None\n };\n\n { // block limits of borrows by refer() method calls\n let mut ap = ArgumentParser::new();\n ap.add_option(&[\"-v\", \"--version\"], Print(env!(\"CARGO_PKG_VERSION\").to_string()), \"show version\");\n ap.refer(&mut options.debug).add_option(&[\"-d\", \"--debug\"], StoreTrue, \"enable debug output\");\n ap.refer(&mut options.file).add_option(&[\"-f\", \"--file\"], StoreOption, \"possible alternates file, - for stdin\");\n ap.refer(&mut options.path).add_argument(\"PATH\", Store, \"path to find alternate for\").required();\n ap.parse_args_or_exit();\n }\n\n println!(\"required path: {}\", options.path);\n\n if let Some(unwrapped_file) = options.file {\n println!(\"file: {}\", unwrapped_file);\n if unwrapped_file == \"-\" {\n let stdin = std::io::stdin();\n for line in stdin.lock().lines() {\n println!(\"{}\", line.unwrap());\n }\n } else {\n println!(\"Figure out how open and read actual file\");\n }\n }\n\n println!(\"debug: {}\", options.debug);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add comparision between guess and secret_number\n"
},
{
"from": "human",
"value": "extern crate rand;\n\nuse std::io;\nuse rand::Rng;\n\nfn main() {\n println!(\"Hello in my guessing game!\");\n\n let secret_number = rand::thread_rng().gen_range(1, 101);\n\n println!(\"The secret number is: {}\", secret_number);\n\n println!(\"Input your guess, please:\");\n\n let mut guess = String::new();\n\n io::stdin().read_line(&mut guess)\n .expect(\"Failed to read line!\");\n\n println!(\"Your guess is: {}\", guess);\n}\n"
},
{
"from": "gpt",
"value": "extern crate rand;\n\nuse std::io;\nuse std::cmp::Ordering;\nuse rand::Rng;\n\nfn main() {\n println!(\"Hello in my guessing game!\");\n\n let secret_number = rand::thread_rng().gen_range(1, 101);\n\n println!(\"The secret number is: {}\", secret_number);\n\n println!(\"Input your guess, please:\");\n\n let mut guess = String::new();\n\n io::stdin().read_line(&mut guess)\n .expect(\"Failed to read line!\");\n\n let guess: u32 = guess.trim().parse()\n .expect(\"It's not a valid number :(\");\n\n println!(\"Your guess is: {}\", guess);\n\n match guess.cmp(&secret_number) {\n Ordering::Less => println!(\"Too low!\"),\n Ordering::Greater => println!(\"Too big!\"),\n Ordering::Equal => println!(\"Great guess! You win!\")\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use new std::net module in day 9.\n"
},
{
"from": "human",
"value": "#![feature(io)]\n\nextern crate anymap;\n\nuse std::old_io::net::ip::IpAddr;\nuse anymap::AnyMap;\n\n#[derive(Debug)]\nenum HostAddress {\n DomainName(String),\n Ip(IpAddr),\n}\n\n#[derive(Debug)]\nstruct Port(u32);\n\n#[derive(Debug)]\nstruct ConnectionLimit(u32);\n\nfn main() {\n println!(\"24 days of Rust - anymap (day 9)\");\n let mut config = AnyMap::new();\n config.insert(HostAddress::DomainName(\"siciarz.net\".to_string()));\n config.insert(Port(666));\n config.insert(ConnectionLimit(32));\n println!(\"{:?}\", config.get::<HostAddress>());\n println!(\"{:?}\", config.get::<Port>());\n assert!(config.get::<String>().is_none());\n assert!(config.get::<u32>().is_none());\n config.insert(HostAddress::Ip(IpAddr::Ipv4Addr(127, 0, 0, 1)));\n println!(\"{:?}\", config.get::<HostAddress>());\n if config.contains::<Option<f32>>() {\n println!(\"There's no optional float in the configuration...\");\n }\n let dummy: Option<f32> = None;\n config.insert(dummy);\n if config.contains::<Option<f32>>() {\n println!(\"There's an optional 32-bit float in the configuration...\");\n }\n if !config.contains::<Option<f64>>() {\n println!(\"...but not an optional 64-bit float.\");\n }\n}\n"
},
{
"from": "gpt",
"value": "#![feature(net)]\n\nextern crate anymap;\n\nuse std::net::IpAddr;\nuse anymap::AnyMap;\n\n#[derive(Debug)]\nenum HostAddress {\n DomainName(String),\n Ip(IpAddr),\n}\n\n#[derive(Debug)]\nstruct Port(u32);\n\n#[derive(Debug)]\nstruct ConnectionLimit(u32);\n\nfn main() {\n println!(\"24 days of Rust - anymap (day 9)\");\n let mut config = AnyMap::new();\n config.insert(HostAddress::DomainName(\"siciarz.net\".to_string()));\n config.insert(Port(666));\n config.insert(ConnectionLimit(32));\n println!(\"{:?}\", config.get::<HostAddress>());\n println!(\"{:?}\", config.get::<Port>());\n assert!(config.get::<String>().is_none());\n assert!(config.get::<u32>().is_none());\n config.insert(HostAddress::Ip(IpAddr::new_v4(127, 0, 0, 1)));\n println!(\"{:?}\", config.get::<HostAddress>());\n if config.contains::<Option<f32>>() {\n println!(\"There's no optional float in the configuration...\");\n }\n let dummy: Option<f32> = None;\n config.insert(dummy);\n if config.contains::<Option<f32>>() {\n println!(\"There's an optional 32-bit float in the configuration...\");\n }\n if !config.contains::<Option<f64>>() {\n println!(\"...but not an optional 64-bit float.\");\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove type annotations that can be inferred\n"
},
{
"from": "human",
"value": "#![allow(unstable)]\n\nextern crate getopts;\nextern crate selecta;\n\nuse getopts::{optopt,getopts};\nuse selecta::configuration::Configuration;\nuse selecta::search::Search;\nuse selecta::tty::TTY;\nuse selecta::tty::IO;\nuse selecta::screen::Screen;\n\nfn main() {\n let initial_query = extract_initial_query();\n let lines = read_lines();\n\n let config = Configuration::from_inputs(lines, initial_query, Some(20));\n let mut search = Search::blank(config);\n\n let mut tty = TTY::new();\n let mut screen = Screen::new();\n\n screen.print(&search);\n\n while !search.is_done() {\n let input = tty.read();\n match input {\n Some(n) => {\n search = screen.handle_keystroke(search, n.as_slice());\n },\n None => break,\n };\n screen.print(&search);\n }\n println!(\"{}\\n\", search.selection.unwrap_or(\"None\".to_string()));\n screen.ansi.show_cursor();\n}\n\nfn extract_initial_query() -> Option<String> {\n let args: Vec<String> = std::os::args();\n let opts = &[\n optopt(\"s\", \"search\", \"initial search query\", \"\"),\n ];\n let matches = getopts(args.tail(), opts).unwrap();\n\n matches.opt_str(\"s\")\n}\n\nfn read_lines() -> Vec<String> {\n std::io::stdio::stdin().lock().lines().map( |line| {\n line.unwrap().trim().to_string()\n }).collect()\n}\n"
},
{
"from": "gpt",
"value": "#![allow(unstable)]\n\nextern crate getopts;\nextern crate selecta;\n\nuse getopts::{optopt,getopts};\nuse selecta::configuration::Configuration;\nuse selecta::search::Search;\nuse selecta::tty::TTY;\nuse selecta::tty::IO;\nuse selecta::screen::Screen;\n\nfn main() {\n let initial_query = extract_initial_query();\n let lines = read_lines();\n\n let config = Configuration::from_inputs(lines, initial_query, Some(20));\n let mut search = Search::blank(config);\n\n let mut tty = TTY::new();\n let mut screen = Screen::new();\n\n screen.print(&search);\n\n while !search.is_done() {\n let input = tty.read();\n match input {\n Some(n) => {\n search = screen.handle_keystroke(search, n.as_slice());\n },\n None => break,\n };\n screen.print(&search);\n }\n println!(\"{}\\n\", search.selection.unwrap_or(\"None\".to_string()));\n screen.ansi.show_cursor();\n}\n\nfn extract_initial_query() -> Option<String> {\n let args = std::os::args();\n let opts = &[\n optopt(\"s\", \"search\", \"initial search query\", \"\"),\n ];\n let matches = getopts(args.tail(), opts).unwrap();\n\n matches.opt_str(\"s\")\n}\n\nfn read_lines() -> Vec<String> {\n std::io::stdio::stdin().lock().lines().map( |line| {\n line.unwrap().trim().to_string()\n }).collect()\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Clean up the raw module a bit\n"
},
{
"from": "human",
"value": "mod raw {\n extern crate libc;\n\n #[allow(non_camel_case_types)]\n pub type wl_display = libc::c_void;\n\n #[link(name = \"wayland-client\")]\n extern {\n pub fn wl_display_connect(name: *const u8) -> *mut wl_display;\n pub fn wl_display_disconnect(display: *mut wl_display);\n }\n}\n\npub struct Display {\n ptr: *mut raw::wl_display\n}\n\nimpl Display {\n pub fn new() -> Display {\n unsafe {\n let ptr = raw::wl_display_connect(std::ptr::null());\n assert!(!ptr.is_null());\n Display { ptr: ptr }\n }\n }\n}\n\nimpl Drop for Display {\n fn drop(&mut self) {\n unsafe {\n raw::wl_display_disconnect(self.ptr);\n }\n }\n}\n\nfn main() {\n let logfile_path = match std::os::homedir() {\n Some(ref p) => p.join(\".eyl-shell.log\"),\n None => fail!(\"finding homedir\")\n };\n let mut logfile = std::io::File::create(&logfile_path);\n let display = Display::new();\n match logfile.write(b\"Connected to display\\n\") {\n Ok(()) => (),\n Err(_) => fail!(\"writing to logfile\")\n }\n}\n"
},
{
"from": "gpt",
"value": "mod raw {\n extern crate libc;\n\n use self::libc::{c_char, c_void};\n\n #[allow(non_camel_case_types)]\n pub type wl_display = c_void;\n\n #[link(name = \"wayland-client\")]\n extern {\n pub fn wl_display_connect(name: *const c_char) -> *mut wl_display;\n pub fn wl_display_disconnect(display: *mut wl_display);\n }\n}\n\npub struct Display {\n ptr: *mut raw::wl_display\n}\n\nimpl Display {\n pub fn new() -> Display {\n unsafe {\n let ptr = raw::wl_display_connect(std::ptr::null());\n assert!(!ptr.is_null());\n Display { ptr: ptr }\n }\n }\n}\n\nimpl Drop for Display {\n fn drop(&mut self) {\n unsafe {\n raw::wl_display_disconnect(self.ptr);\n }\n }\n}\n\nfn main() {\n let logfile_path = match std::os::homedir() {\n Some(ref p) => p.join(\".eyl-shell.log\"),\n None => fail!(\"finding homedir\")\n };\n let mut logfile = std::io::File::create(&logfile_path);\n let display = Display::new();\n match logfile.write(b\"Connected to display\\n\") {\n Ok(()) => (),\n Err(_) => fail!(\"writing to logfile\")\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Swap Vec<f64> with [f64, N]\n"
},
{
"from": "human",
"value": "fn schwefel(solution: &Vec<f64>) -> f64 {\n return 418.9829_f64 * solution.len() as f64\n + solution.iter().fold(0_f64, |sum, x| sum + x * x.abs().sqrt().sin());\n}\n\nfn main() {\n println!(\"Hello, world!\");\n}\n"
},
{
"from": "gpt",
"value": "const N: usize = 50;\n\nfn schwefel(solution: &[f64; N]) -> f64 {\n return 418.9829_f64 * N as f64\n + solution.iter().fold(0_f64, |sum, x| sum + x * x.abs().sqrt().sin());\n}\n\nfn main() {\n println!(\"Hello, world!\");\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Change runtime of REPL to proxy through program\n"
},
{
"from": "human",
"value": "mod vm;\nmod command;\nmod parse;\nmod program;\n\nuse vm::VM;\nuse std::io::Write;\n\nfn main() {\n let mut vm = VM::new();\n loop {\n print!(\"{}\", \"bf> \");\n std::io::stdout().flush().unwrap();\n\n let mut line = String::new();\n let commands = match std::io::stdin().read_line(&mut line) {\n Ok(0) => break,\n Ok(_) => parse::parse(&line),\n Err(error) => panic!(error),\n };\n vm.apply_many(&commands);\n }\n}\n"
},
{
"from": "gpt",
"value": "mod vm;\nmod command;\nmod parse;\nmod program;\n\nuse vm::VM;\nuse program::Program;\nuse std::io::Write;\n\nfn main() {\n let mut vm = VM::new();\n let mut program = Program::new();\n loop {\n print!(\"{}\", \"bf> \");\n std::io::stdout().flush().unwrap();\n\n let mut line = String::new();\n let commands = match std::io::stdin().read_line(&mut line) {\n Ok(0) => break,\n Ok(_) => parse::parse(&line),\n Err(error) => panic!(error),\n };\n program.append(&commands);\n program.execute(&mut vm);\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Print nicer error messages for myself\n"
},
{
"from": "human",
"value": "extern crate sassers;\nextern crate docopt;\n\nuse docopt::Docopt;\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn main() {\n const VERSION: &'static str = env!(\"CARGO_PKG_VERSION\");\n static USAGE: &'static str = \"\nUsage:\n sassers [-t <style>] <inputfile>\n sassers [-vh]\n\nOptions:\n -h, --help Show this message\n -v, --version Show the version\n -t <style>, --style <style> Output style [default: nested]\n \";\n\n let args = Docopt::new(USAGE)\n .and_then(|d| d.parse())\n .unwrap_or_else(|e| e.exit());\n\n if args.get_bool(\"-v\") {\n println!(\"{}\", VERSION);\n } else {\n let style = args.get_str(\"-t\");\n let inputfile = args.get_str(\"<inputfile>\");\n\n let mut sass = String::new();\n File::open(&Path::new(&inputfile)).unwrap().read_to_string(&mut sass).unwrap();\n\n match sassers::compile(&sass, style) {\n Ok(compiled) => println!(\"{}\", compiled),\n Err(msg) => println!(\"Compilation failed: {}\", msg),\n }\n }\n}\n"
},
{
"from": "gpt",
"value": "extern crate sassers;\nextern crate docopt;\n\nuse docopt::Docopt;\nuse std::fs::File;\nuse std::io::Read;\nuse std::path::Path;\n\nfn main() {\n const VERSION: &'static str = env!(\"CARGO_PKG_VERSION\");\n static USAGE: &'static str = \"\nUsage:\n sassers [-t <style>] <inputfile>\n sassers [-vh]\n\nOptions:\n -h, --help Show this message\n -v, --version Show the version\n -t <style>, --style <style> Output style [default: nested]\n \";\n\n let args = Docopt::new(USAGE)\n .and_then(|d| d.parse())\n .unwrap_or_else(|e| e.exit());\n\n if args.get_bool(\"-v\") {\n println!(\"{}\", VERSION);\n } else {\n let style = args.get_str(\"-t\");\n let inputfile = args.get_str(\"<inputfile>\");\n\n let mut sass = String::new();\n let mut file = match File::open(&Path::new(&inputfile)) {\n Ok(f) => f,\n Err(msg) => panic!(\"File not found! {}\", msg),\n };\n match file.read_to_string(&mut sass) {\n Ok(_) => {\n match sassers::compile(&sass, style) {\n Ok(compiled) => println!(\"{}\", compiled),\n Err(msg) => println!(\"Compilation failed: {}\", msg),\n }\n },\n Err(msg) => panic!(\"Could not read file! {}\", msg),\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add a function for parsing command-line arguments\n"
},
{
"from": "human",
"value": "fn main() {\n println!(\"Hello, world!\")\n}\n"
},
{
"from": "gpt",
"value": "extern crate getopts;\nuse getopts::{optopt, optflag, OptGroup};\nuse std::os;\n\n\nuse device_info::{DefaultDevice, DefaultInterface, UserDefinedDevice, UserDefinedName, DeviceInfo};\nmod device_info;\n\n\nenum ParseArgsResult {\n HelpRequested,\n DevicesObtained(DeviceInfo),\n CommandLineError(getopts::Fail_)\n}\n\n\n// Returns either a Devices struct filled either with the default values, or None if the help option is present\nfn parse_args(opts: &[OptGroup], args: &[String]) -> ParseArgsResult {\n match getopts::getopts(args, opts) {\n Err(e) => CommandLineError(e),\n\n Ok(options) => {\n if options.opt_present(\"h\") {\n HelpRequested\n } else {\n DevicesObtained(DeviceInfo::new(match options.opt_str(\"d\") {\n Some(s) => UserDefinedDevice(s),\n None => DefaultDevice\n },\n match options.opt_str(\"i\") {\n Some(s) => UserDefinedName(s),\n None => DefaultInterface,\n }))\n }\n }\n }\n}\n\n\nfn main() {\n println!(\"Hello, world!\")\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Make the Key enum printable for debugging\n"
},
{
"from": "human",
"value": "use std::io;\n\npub use self::posix::PosixInputHandler;\n\nmod posix;\n\nconst CMD_PROMPT: &'static str = \">> \";\n\nenum Key {\n Esc,\n Enter,\n Tab,\n\n Up,\n Down,\n Left,\n Right,\n Home,\n End,\n Insert,\n PgUp,\n PgDown,\n\n Backspace,\n Delete,\n\n Char(char),\n F(u32),\n\n Unknown,\n}\n\npub enum InputCmd {\n None,\n Quit,\n Equation(String),\n}\n\npub trait InputHandler {\n fn start(&mut self) -> io::Result<()>;\n fn stop(&mut self) -> io::Result<()>;\n fn handle_input(&mut self) -> InputCmd;\n fn print_prompt(&self);\n}"
},
{
"from": "gpt",
"value": "use std::io;\n\npub use self::posix::PosixInputHandler;\n\nmod posix;\n\nconst CMD_PROMPT: &'static str = \">> \";\n\n#[derive(Debug)]\nenum Key {\n Esc,\n Enter,\n Tab,\n\n Up,\n Down,\n Left,\n Right,\n Home,\n End,\n Insert,\n PgUp,\n PgDown,\n\n Backspace,\n Delete,\n\n Char(char),\n F(u32),\n\n Unknown,\n}\n\npub enum InputCmd {\n None,\n Quit,\n Equation(String),\n}\n\npub trait InputHandler {\n fn start(&mut self) -> io::Result<()>;\n fn stop(&mut self) -> io::Result<()>;\n fn handle_input(&mut self) -> InputCmd;\n fn print_prompt(&self);\n}"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix Option camel case in a compile-fail test\n\nThe compile fails for another reason, that triggers before the the failure for non-camel cased option, some or none undefined errors.\n"
},
{
"from": "human",
"value": "// Copyright 2012 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nfn matcher(x: option<int>) {\n match x {\n ref some(i) => {} //~ ERROR expected identifier, found enum pattern\n none => {}\n }\n}\n\nfn main() {}\n"
},
{
"from": "gpt",
"value": "// Copyright 2012 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nfn matcher(x: Option<int>) {\n match x {\n ref Some(i) => {} //~ ERROR expected identifier, found enum pattern\n None => {}\n }\n}\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Change logic of increment and continue branch\n"
},
{
"from": "human",
"value": "use std::io::{self, Write};\nuse std::fs::File;\n\nuse flac::stream::StreamReader;\nuse flac::metadata::{self, Picture};\n\npub const USAGE: &'static str = \"\nUsage: metadata picture [options] <filename>\n metadata picture --help\n\nOptions:\n --export=FILE Export to file.\n --index=NUMBER Index of the current metadata type.\n -h, --help Show this message.\n\";\n\n#[derive(Debug, RustcDecodable)]\npub struct Arguments {\n arg_filename: String,\n flag_export: Option<String>,\n flag_index: Option<usize>,\n}\n\nfn export_picture(picture: &Picture, filename: &str) -> io::Result<()> {\n File::create(filename).and_then(|mut file| file.write_all(&picture.data))\n}\n\npub fn run(args: &Arguments) {\n let stream = StreamReader::<File>::from_file(&args.arg_filename)\n .expect(\"Couldn't parse file\");\n\n let mut index = 0;\n let end_index = args.flag_index.unwrap_or(0);\n\n for meta in stream.metadata() {\n match meta.data {\n metadata::Data::Picture(ref p) => {\n if index != end_index {\n index += 1;\n\n continue;\n }\n\n if let Some(ref filename) = args.flag_export {\n export_picture(p, filename).expect(\"couldn't write to file\");\n\n break;\n }\n }\n _ => continue,\n }\n }\n}\n"
},
{
"from": "gpt",
"value": "use std::io::{self, Write};\nuse std::fs::File;\n\nuse flac::stream::StreamReader;\nuse flac::metadata::{self, Picture};\n\npub const USAGE: &'static str = \"\nUsage: metadata picture [options] <filename>\n metadata picture --help\n\nOptions:\n --export=FILE Export to file.\n --index=NUMBER Index of the current metadata type.\n -h, --help Show this message.\n\";\n\n#[derive(Debug, RustcDecodable)]\npub struct Arguments {\n arg_filename: String,\n flag_export: Option<String>,\n flag_index: Option<usize>,\n}\n\nfn export_picture(picture: &Picture, filename: &str) -> io::Result<()> {\n File::create(filename).and_then(|mut file| file.write_all(&picture.data))\n}\n\npub fn run(args: &Arguments) {\n let stream = StreamReader::<File>::from_file(&args.arg_filename)\n .expect(\"Couldn't parse file\");\n\n let mut index = 0;\n let end_index = args.flag_index.unwrap_or(0);\n\n for meta in stream.metadata() {\n match meta.data {\n metadata::Data::Picture(ref p) => {\n if index < end_index {\n index += 1;\n\n continue;\n }\n\n if let Some(ref filename) = args.flag_export {\n export_picture(p, filename).expect(\"couldn't write to file\");\n\n break;\n }\n }\n _ => continue,\n }\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use real array instead of text array to save tags\n"
},
{
"from": "human",
"value": "use storage::file::FileHeaderSpec as FHS;\nuse storage::file::FileHeaderData as FHD;\n\npub fn get_spec() -> FHS {\n FHS::Map { keys: vec![ url_key(), tags_key() ] }\n}\n\nfn url_key() -> FHS {\n FHS::Key { name: String::from(\"URL\"), value_type: Box::new(FHS::Text) }\n}\n\nfn tags_key() -> FHS {\n FHS::Key { name: String::from(\"TAGS\"), value_type: Box::new(text_array()) }\n}\n\nfn text_array() -> FHS {\n FHS::Array { allowed_types: vec![FHS::Text] }\n}\n\n\npub fn build_header(url: &String, tags: &Vec<String>) -> FHD {\n FHD::Map {\n keys: vec![\n FHD::Key {\n name: String::from(\"URL\"),\n value: Box::new(FHD::Text(url.clone()))\n },\n FHD::Key {\n name: String::from(\"TAGS\"),\n value: Box::new(FHD::Text(tags.connect(\",\")))\n }\n ]\n }\n}\n\n"
},
{
"from": "gpt",
"value": "use storage::file::FileHeaderSpec as FHS;\nuse storage::file::FileHeaderData as FHD;\n\npub fn get_spec() -> FHS {\n FHS::Map { keys: vec![ url_key(), tags_key() ] }\n}\n\nfn url_key() -> FHS {\n FHS::Key { name: String::from(\"URL\"), value_type: Box::new(FHS::Text) }\n}\n\nfn tags_key() -> FHS {\n FHS::Key { name: String::from(\"TAGS\"), value_type: Box::new(text_array()) }\n}\n\nfn text_array() -> FHS {\n FHS::Array { allowed_types: vec![FHS::Text] }\n}\n\n\npub fn build_header(url: &String, tags: &Vec<String>) -> FHD {\n FHD::Map {\n keys: vec![\n FHD::Key {\n name: String::from(\"URL\"),\n value: Box::new(FHD::Text(url.clone()))\n },\n FHD::Key {\n name: String::from(\"TAGS\"),\n value: Box::new(build_tag_array(tags))\n }\n ]\n }\n}\n\nfn build_tag_array(tags: &Vec<String>) -> FHD {\n let texttags = tags.into_iter().map(|t| FHD::Text(t.clone())).collect();\n FHD::Array { values: Box::new(texttags) }\n}\n\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove unused parts of UrlDef\n"
},
{
"from": "human",
"value": "use url::Url;\nuse serde::de::{Deserialize, Deserializer, Error as DeserializeError};\nuse serde::ser::{Serialize, Serializer};\n\n\n/// Type which can be used to serialize a Url.\n///\n/// `#[serde(with = \"UrlDef\")]`\npub struct UrlDef(Url);\n\nimpl UrlDef {\n pub fn deserialize<'de, D>(deserializer: D) -> Result<Url, D::Error>\n where D: Deserializer<'de> {\n <&str>::deserialize(deserializer).and_then(|s| {\n s.parse().map_err(|e| DeserializeError::custom(format!(\"invalid URL: {}\", e)))\n })\n }\n\n pub fn serialize<S>(url: &Url, serializer: S) -> Result<S::Ok, S::Error>\n where S: Serializer {\n url.as_str().serialize(serializer)\n }\n}\n\nimpl From<UrlDef> for Url {\n fn from(def: UrlDef) -> Url {\n def.0\n }\n}\n"
},
{
"from": "gpt",
"value": "use url::Url;\nuse serde::de::{Deserialize, Deserializer, Error as DeserializeError};\nuse serde::ser::{Serialize, Serializer};\n\n\n/// Unit struct which can be used to serialize a Url.\n///\n/// `#[serde(with = \"UrlDef\")]`\npub struct UrlDef;\nimpl UrlDef {\n pub fn deserialize<'de, D>(deserializer: D) -> Result<Url, D::Error>\n where D: Deserializer<'de> {\n <&str>::deserialize(deserializer).and_then(|s| {\n s.parse().map_err(|e| DeserializeError::custom(format!(\"invalid URL: {}\", e)))\n })\n }\n\n pub fn serialize<S>(url: &Url, serializer: S) -> Result<S::Ok, S::Error>\n where S: Serializer {\n url.as_str().serialize(serializer)\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add a bunch more property tests\n\nSearching for hex codes, and for control characters.\n"
},
{
"from": "human",
"value": "#[macro_use]\nextern crate proptest;\nextern crate chars;\n\nuse chars::human_names;\n\nuse proptest::prelude::*;\nuse proptest::test_runner::Config;\nuse std::fmt::Write;\n\nproptest! {\n#![proptest_config(Config::with_cases(100000))]\n#[test]\nfn find_any_by_name(ch in prop::char::any()) {\n let mut chstr = String::new();\n chstr.write_char(ch).unwrap();\n\n let found = human_names::from_arg(&chstr);\n assert!(found.len() >= 1);\n assert!(found.contains(&ch));\n}\n}\n"
},
{
"from": "gpt",
"value": "#[macro_use]\nextern crate proptest;\nextern crate chars;\n\nuse chars::human_names;\n\nuse proptest::prelude::*;\nuse std::fmt::Write;\n\nproptest! {\n #[test]\n fn find_any_by_identity(ch in prop::char::any()) {\n let mut chstr = String::new();\n chstr.write_char(ch).unwrap();\n\n let found = human_names::from_arg(&chstr);\n assert!(found.len() >= 1);\n assert!(found.contains(&ch));\n }\n\n #[test]\n fn find_any_by_hex(ch in prop::char::any()) {\n let num = ch as u32;\n let found = human_names::from_arg(&format!(\"0x{:04x}\", num));\n println!(\"num: {:?}\", num);\n assert_eq!(found.len(), 1);\n assert_eq!(found[0], ch);\n\n let found = human_names::from_arg(&format!(\"U+{:04x}\", num));\n assert_eq!(found.len(), 1);\n assert_eq!(found[0], ch);\n\n let found = human_names::from_arg(&format!(\"{:04x}\", num));\n assert!(found.len() >= 1);\n assert!(found.contains(&ch));\n }\n\n #[test]\n fn find_control_chars(ch in prop::char::range(0 as char, 0x1f as char)) {\n let query = format!(\"^{}\", (b'@' + (ch as u8 & 0x1f)) as char);\n let found = human_names::from_arg(&query);\n assert_eq!(found.len(), 1, \"nothing found for query: {:?}\", query);\n assert_eq!(found[0], ch, \"query: {:?}\", query);\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove unused variable from Alphametics stub\n"
},
{
"from": "human",
"value": "use std::collections::HashMap;\n\npub fn solve(puzzle: &str) -> Option<HashMap<char, u8>> {\n unimplemented!()\n}\n"
},
{
"from": "gpt",
"value": "use std::collections::HashMap;\n\npub fn solve(_: &str) -> Option<HashMap<char, u8>> {\n unimplemented!()\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add license to stable check\n\nso that this passes tidy on rust master\n"
},
{
"from": "human",
"value": "use std::error::Error;\nuse std::env;\nuse std::fs;\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::path::Path;\n\nfn main() {\n let arg = env::args().nth(1).unwrap_or_else(|| {\n println!(\"Please pass a src directory as the first argument\");\n std::process::exit(1);\n });\n\n match check_directory(&Path::new(&arg)) {\n Ok(()) => println!(\"passed!\"),\n Err(e) => {\n println!(\"Error: {}\", e);\n std::process::exit(1);\n }\n }\n}\n\nfn check_directory(dir: &Path) -> Result<(), Box<Error>> {\n for entry in fs::read_dir(dir)? {\n let entry = entry?;\n let path = entry.path();\n\n if path.is_dir() {\n continue;\n }\n\n let mut file = File::open(&path)?;\n let mut contents = String::new();\n file.read_to_string(&mut contents)?;\n\n if contents.contains(\"#![feature\") {\n // attributes.md contains this and it is legitimate\n if !contents.contains(\"#![feature(feature1, feature2, feature3)]\") {\n return Err(From::from(format!(\"Feature flag found in {:?}\", path)));\n }\n }\n }\n\n Ok(())\n}\n"
},
{
"from": "gpt",
"value": "// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nuse std::error::Error;\nuse std::env;\nuse std::fs;\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::path::Path;\n\nfn main() {\n let arg = env::args().nth(1).unwrap_or_else(|| {\n println!(\"Please pass a src directory as the first argument\");\n std::process::exit(1);\n });\n\n match check_directory(&Path::new(&arg)) {\n Ok(()) => println!(\"passed!\"),\n Err(e) => {\n println!(\"Error: {}\", e);\n std::process::exit(1);\n }\n }\n}\n\nfn check_directory(dir: &Path) -> Result<(), Box<Error>> {\n for entry in fs::read_dir(dir)? {\n let entry = entry?;\n let path = entry.path();\n\n if path.is_dir() {\n continue;\n }\n\n let mut file = File::open(&path)?;\n let mut contents = String::new();\n file.read_to_string(&mut contents)?;\n\n if contents.contains(\"#![feature\") {\n // attributes.md contains this and it is legitimate\n if !contents.contains(\"#![feature(feature1, feature2, feature3)]\") {\n return Err(From::from(format!(\"Feature flag found in {:?}\", path)));\n }\n }\n }\n\n Ok(())\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Return PathBuf instead of &Path\n"
},
{
"from": "human",
"value": "// Here lists all the paths that will be used by wiz\nuse std::path::{ Path, PathBuf };\n\n///\n/// Appends `append` to `path`.\n///\npub trait PathAppend {\n fn append(&mut self, input: &str) -> &Path;\n}\n\nimpl PathAppend for PathBuf {\n fn append(&mut self, input: &str) -> &Path {\n self.push(input);\n self.as_path()\n }\n}\n\npub const DOWNLOAD_DIR: &'static str = \"downloaded/\";\npub const EXTRACT_DIR: &'static str = \"extracted/\";\npub const PACKAGE_INSTALL_DIR: &'static str = \"installed_package/\";\npub const PACKAGE_LIST_DIR: &'static str = \"package_lists/\";"
},
{
"from": "gpt",
"value": "// Here lists all the paths that will be used by wiz\nuse std::path::{ Path, PathBuf };\n\n///\n/// Appends `append` to `path`.\n///\npub trait PathAppend {\n fn append(&self, input: &str) -> PathBuf;\n}\n\nimpl PathAppend for PathBuf {\n fn append(&self, input: &str) -> PathBuf {\n let mut buf = self.to_path_buf().clone();\n buf.push(input);\n buf.clone()\n }\n}\n\npub const DOWNLOAD_DIR: &'static str = \"downloaded/\";\npub const EXTRACT_DIR: &'static str = \"extracted/\";\npub const PACKAGE_INSTALL_DIR: &'static str = \"installed_package/\";\npub const PACKAGE_LIST_DIR: &'static str = \"package_lists/\";"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Implement BlasVector on Vec and slice\n"
},
{
"from": "human",
"value": "// Copyright 2014 Michael Yang. All rights reserved.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\npub mod ll;\npub mod ops;\n\npub trait BlasVector<T> {\n fn inc(&self) -> i32;\n fn len(&self) -> i32;\n fn as_ptr(&self) -> *const T;\n fn as_mut_ptr(&mut self) -> *mut T;\n}\n"
},
{
"from": "gpt",
"value": "// Copyright 2014 Michael Yang. All rights reserved.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\nuse std::raw::Repr;\n\npub mod ll;\npub mod ops;\n\npub trait BlasVector<T> {\n fn inc(&self) -> i32;\n fn len(&self) -> i32;\n fn as_ptr(&self) -> *const T;\n fn as_mut_ptr(&mut self) -> *mut T;\n}\n\nimpl<T> BlasVector<T> for Vec<T> {\n #[inline]\n fn inc(&self) -> i32 { 1i32 }\n\n #[inline]\n fn len(&self) -> i32 {\n let l: Option<i32> = NumCast::from(self.len());\n match l {\n Some(l) => l,\n None => panic!(),\n }\n }\n\n #[inline]\n fn as_ptr(&self) -> *const T { self.as_slice().as_ptr() }\n\n #[inline]\n fn as_mut_ptr(&mut self) -> *mut T { self.as_mut_slice().as_mut_ptr() }\n}\n\nimpl<'a, T> BlasVector<T> for &'a [T] {\n #[inline]\n fn inc(&self) -> i32 { 1i32 }\n\n #[inline]\n fn len(&self) -> i32 {\n let l: Option<i32> = NumCast::from(self.len());\n match l {\n Some(l) => l,\n None => panic!(),\n }\n }\n\n #[inline]\n fn as_ptr(&self) -> *const T { self.repr().data }\n\n #[inline]\n fn as_mut_ptr(&mut self) -> *mut T { self.repr().data as *mut T }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use automatic dereference in benchmark\n"
},
{
"from": "human",
"value": "#[macro_use]\nextern crate perl_xs;\n#[macro_use]\nextern crate perl_sys;\n\nuse perl_xs::{ SV, AV, IV, NV };\n\nxs! {\n package XSBench::RS;\n \n sub rs_sum_loop(ctx, param: SV) {\n let array: AV = param.deref_av().expect(\"not an array ref\");\n let mut sum = 0.0;\n for i in 0..array.top_index() + 1 {\n if let Some(val) = array.fetch(i) {\n sum += val;\n }\n }\n xs_return!(ctx, sum);\n }\n\n sub rs_sum_iter(ctx, param: SV) {\n let array: AV = param.deref_av().expect(\"not an array ref\");\n let sum: NV = array.iter().map(|v| v.unwrap_or(0.0)).sum();\n xs_return!(ctx, sum);\n }\n\n sub rs_gcd(ctx, a: IV, b: IV) {\n let mut a = a;\n let mut b = b;\n while b > 0 {\n let t = a;\n a = b;\n b = t % b;\n }\n\n let res = if a < 0 {\n -a\n } else {\n a\n };\n\n xs_return!(ctx, res);\n }\n}\n\nxs! {\n bootstrap boot_XSBench__RS;\n use self;\n}\n"
},
{
"from": "gpt",
"value": "#[macro_use]\nextern crate perl_xs;\n#[macro_use]\nextern crate perl_sys;\n\nuse perl_xs::{ AV, IV, NV };\n\nxs! {\n package XSBench::RS;\n \n sub rs_sum_loop(ctx, array: AV) {\n let mut sum = 0.0;\n for i in 0..array.top_index() + 1 {\n if let Some(val) = array.fetch(i) {\n sum += val;\n }\n }\n xs_return!(ctx, sum);\n }\n\n sub rs_sum_iter(ctx, array: AV) {\n let sum: NV = array.iter().map(|v| v.unwrap_or(0.0)).sum();\n xs_return!(ctx, sum);\n }\n\n sub rs_gcd(ctx, a: IV, b: IV) {\n let mut a = a;\n let mut b = b;\n while b > 0 {\n let t = a;\n a = b;\n b = t % b;\n }\n\n let res = if a < 0 {\n -a\n } else {\n a\n };\n\n xs_return!(ctx, res);\n }\n}\n\nxs! {\n bootstrap boot_XSBench__RS;\n use self;\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove current directory from begginnig of displayed paths\n"
},
{
"from": "human",
"value": "// Copyright (C) 2016 Élisabeth HENRY.\n//\n// This file is part of Crowbook.\n//\n// Crowbook is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Lesser General Public License as published\n// by the Free Software Foundation, either version 2.1 of the License, or\n// (at your option) any later version.\n//\n// Crowbook is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public License\n// along with Crowbook. If not, see <http://www.gnu.org/licenses/>.\n\n//! Misc utility functions used across crowbook\n\nuse std;\nuse std::path::Path;\n\n/// Try to canonicalize a path using std::fs::canonicalize, and returns the\n/// unmodified path if it fails (e.g. if the path doesn't exist (yet))\npub fn canonicalize<P: AsRef<Path>>(path: P) -> String {\n if let Ok(path) = std::fs::canonicalize(path.as_ref()) {\n format!(\"{}\", path.display())\n } else {\n format!(\"{}\", path.as_ref().display())\n }\n}\n"
},
{
"from": "gpt",
"value": "// Copyright (C) 2016 Élisabeth HENRY.\n//\n// This file is part of Crowbook.\n//\n// Crowbook is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Lesser General Public License as published\n// by the Free Software Foundation, either version 2.1 of the License, or\n// (at your option) any later version.\n//\n// Crowbook is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public License\n// along with Crowbook. If not, see <http://www.gnu.org/licenses/>.\n\n//! Misc utility functions used across crowbook\n\nuse std;\nuse std::path::Path;\nuse std::io::Result;\n\n/// Try to canonicalize a path using std::fs::canonicalize, and returns the\n/// unmodified path if it fails (e.g. if the path doesn't exist (yet))\npub fn canonicalize<P: AsRef<Path>>(path: P) -> String {\n try_canonicalize(path.as_ref())\n .unwrap_or(format!(\"{}\", path.as_ref().display()))\n}\n\n\nfn try_canonicalize<P: AsRef<Path>>(path: P) -> Result<String> {\n let path = std::fs::canonicalize(path.as_ref())?;\n let cwd = std::env::current_dir()?;\n Ok(if let Ok(path) = path.strip_prefix(&cwd) {\n format!(\"{}\", path.display())\n } else {\n format!(\"{}\", path.display())\n })\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Enable static linking support (similar to openssl-sys)\n"
},
{
"from": "human",
"value": "fn main () {\n println!(\"cargo:rustc-flags=-l sodium\");\n}\n"
},
{
"from": "gpt",
"value": "use std::env;\n\nfn main () {\n if let Some(lib_dir) = env::var(\"SODIUM_LIB_DIR\").ok() {\n \tprintln!(\"cargo:rustc-flags=-L native={}\", lib_dir);\n }\n\n let mode = if env::var_os(\"SODIUM_STATIC\").is_some() {\n \t\"static\"\n } else {\n \t\"dylib\"\n };\n\n println!(\"cargo:rustc-flags=-l {0}=sodium\", mode);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add tests for all heading levels\n"
},
{
"from": "human",
"value": "use super::builder::Builder;\nuse ast::HeadingLevel;\n\n///\n/// HTML generation might need to be customized to invividual use.\n/// A `Format` allows to customize output generation (e.g. custom tags, classes, ...)\n/// TODO: I need some feedback on the name `Format`\n/// TODO: API is only a draft\n///\npub trait Format {\n fn heading(&self, builder: &mut Builder, level: HeadingLevel, content: String);\n}\n\npub struct DefaultFormat;\n\nimpl Format for DefaultFormat {\n fn heading(&self, builder: &mut Builder, level: HeadingLevel, content: String) {\n let tag = match level {\n HeadingLevel::Level1 => \"h1\",\n HeadingLevel::Level2 => \"h2\",\n HeadingLevel::Level3 => \"h3\",\n HeadingLevel::__NonExhaustive => unreachable!(),\n };\n\n builder.text_tag(tag, content);\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use ast::HeadingLevel;\n\n #[test]\n fn default_heading() {\n let format = DefaultFormat;\n let mut builder = Builder::new();\n\n format.heading(\n &mut builder,\n HeadingLevel::Level1,\n \"hello world\".to_string(),\n );\n\n assert_eq!(\"<h1>hello world</h1>\", format!(\"{}\", builder.consume()));\n }\n}"
},
{
"from": "gpt",
"value": "use super::builder::Builder;\nuse ast::HeadingLevel;\n\n///\n/// HTML generation might need to be customized to invividual use.\n/// A `Format` allows to customize output generation (e.g. custom tags, classes, ...)\n/// TODO: I need some feedback on the name `Format`\n/// TODO: API is only a draft\n///\npub trait Format {\n fn heading(&self, builder: &mut Builder, level: HeadingLevel, content: String);\n}\n\npub struct DefaultFormat;\n\nimpl Format for DefaultFormat {\n fn heading(&self, builder: &mut Builder, level: HeadingLevel, content: String) {\n let tag = match level {\n HeadingLevel::Level1 => \"h1\",\n HeadingLevel::Level2 => \"h2\",\n HeadingLevel::Level3 => \"h3\",\n HeadingLevel::__NonExhaustive => unreachable!(),\n };\n\n builder.text_tag(tag, content);\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use ast::HeadingLevel;\n\n #[test]\n fn default_heading() {\n let format = DefaultFormat;\n let mut builder = Builder::new();\n\n format.heading(\n &mut builder,\n HeadingLevel::Level1,\n \"hello world\".to_string(),\n );\n\n format.heading(&mut builder, HeadingLevel::Level2, \"level 2\".to_string());\n format.heading(&mut builder, HeadingLevel::Level3, \"level 3\".to_string());\n\n assert_eq!(\"<h1>hello world</h1><h2>level 2</h2><h3>level 3</h3>\", format!(\"{}\", builder.consume()));\n }\n}"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Update mini-macro post proc macro stabilization\n\nhttps://github.com/rust-lang/rust/pull/52081 stabilized proc macros, but\nquote is still unstable, so you need to explicitly enable that feature.\n"
},
{
"from": "human",
"value": "#![feature(proc_macro, proc_macro_non_items)]\nextern crate proc_macro;\n\nuse proc_macro::{TokenStream, quote};\n\n#[proc_macro_derive(ClippyMiniMacroTest)]\npub fn mini_macro(_: TokenStream) -> TokenStream {\n quote!(\n #[allow(unused)] fn needless_take_by_value(s: String) { println!(\"{}\", s.len()); }\n )\n}"
},
{
"from": "gpt",
"value": "#![feature(use_extern_macros, proc_macro_quote, proc_macro_non_items)]\nextern crate proc_macro;\n\nuse proc_macro::{TokenStream, quote};\n\n#[proc_macro_derive(ClippyMiniMacroTest)]\npub fn mini_macro(_: TokenStream) -> TokenStream {\n quote!(\n #[allow(unused)] fn needless_take_by_value(s: String) { println!(\"{}\", s.len()); }\n )\n}"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Test where the old infrastructure failed to detect the (applicable) impl of `FnMut` for\nsome reason.\n"
},
{
"from": "human",
"value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nfn f<'r>(p: &'r mut fn(p: &mut ())) {\n p(()) //~ ERROR expected function, found `&'r mut fn(&mut ())`\n}\n\nfn main() {}\n"
},
{
"from": "gpt",
"value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\n#![feature(overloaded_calls)]\n\nfn f<'r>(p: &'r mut fn(p: &mut ())) {\n p(()) //~ ERROR mismatched types: expected `&mut ()`, found `()`\n}\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add documentation for own Result type\n"
},
{
"from": "human",
"value": "//! Module containing `Result` type\n\nuse std::result::Result as RResult;\n\nuse error::TaskError;\n\npub type Result<T> = RResult<T, TaskError>;\n"
},
{
"from": "gpt",
"value": "//! Module containing `Result` type\n\nuse std::result::Result as RResult;\n\nuse error::TaskError;\n\n/// Result type wrapping the standard std::result::Result type\npub type Result<T> = RResult<T, TaskError>;\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Rename JsStr to JsStrStruct, among other things\n"
},
{
"from": "human",
"value": "use std::string::String;\nuse std::vec::Vec;\nuse js_types::js_type::{JsTrait, JsT};\n\n// `undefined`\npub struct JsUndef;\nimpl JsTrait for JsUndef {}\n\n// `null`\npub struct JsNull;\nimpl JsTrait for JsNull {}\n\n// `bool`\npub struct JsBool(pub bool);\nimpl JsTrait for JsBool {}\n\n// `number`\npub struct JsNum(pub f64);\nimpl JsTrait for JsNum {}\n\n// `symbol`\npub struct JsSym(pub String);\nimpl JsTrait for JsSym {}\n\n// `array`\npub type JsArr<T> = Vec<T>;\nimpl<T> JsTrait for JsArr<T> {}\n\n// `string`\npub struct JsStr {\n text: String,\n}\n\nimpl JsStr {\n const MAX_STR_LEN: u64 = 9007199254740991; // 2^53 - 1\n\n pub fn new(s: &str) -> JsStr {\n assert!((s.len() as u64) < JsStr::MAX_STR_LEN);\n JsStr { text: s.to_string(), }\n }\n}\n\nimpl JsTrait for JsStr {}\n\n"
},
{
"from": "gpt",
"value": "use std::string::String;\nuse std::vec::Vec;\n\n// `string`\npub struct JsStrStruct {\n pub text: String,\n}\n\nimpl JsStrStruct {\n const MAX_STR_LEN: u64 = 9007199254740991; // 2^53 - 1\n\n pub fn new(s: &str) -> JsStrStruct {\n assert!((s.len() as u64) < JsStrStruct::MAX_STR_LEN);\n JsStrStruct { text: s.to_string(), }\n }\n}\n\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove locking around log! statements\n"
},
{
"from": "human",
"value": "use ::arch::debug;\nuse core::fmt::{Error,Write};\nuse spin::{MutexGuard,StaticMutex,STATIC_MUTEX_INIT};\n\npub struct Writer<'a> {\n _state: MutexGuard<'a, ()>\n}\n\nstatic LOGGING_LOCK: StaticMutex = STATIC_MUTEX_INIT;\n\nimpl<'a> Writer<'a> {\n\tpub fn get(module: &str) -> Writer {\n\t\tlet mut ret = Writer { _state: LOGGING_LOCK.lock() };\n\t\t\n\t\t{\n\t\t\tuse core::fmt::Write;\n\t\t\tlet _ = write!(&mut ret, \"[{}] \", module);\n\t\t}\n\t\t\n\t\tret\n\t}\n}\n\nimpl<'a> Write for Writer<'a>\n{\n\tfn write_str(&mut self, s: &str) -> Result<(), Error> {\n debug::puts(s);\n\t\tOk(())\n\t}\n}\n\n"
},
{
"from": "gpt",
"value": "use ::arch::debug;\nuse core::fmt::{Error,Write};\n\npub struct Writer;\n\nimpl Writer {\n\tpub fn get(module: &str) -> Writer {\n use core::fmt::Write;\n let mut writer = Writer;\n let _ = write!(&mut writer, \"[{}] \", module);\n writer\n\t}\n}\n\nimpl Write for Writer {\n\tfn write_str(&mut self, s: &str) -> Result<(), Error> {\n debug::puts(s);\n\t\tOk(())\n\t}\n}\n\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix error message in compile-fail test\n"
},
{
"from": "human",
"value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nstruct NoCloneOrEq;\n\n#[deriving(PartialEq)]\nstruct E {\n x: NoCloneOrEq //~ ERROR does not implement any method in scope named `eq`\n //~^ ERROR does not implement any method in scope named `ne`\n}\n#[deriving(Clone)]\nstruct C {\n x: NoCloneOrEq //~ ERROR does not implement any method in scope named `clone`\n}\n\n\nfn main() {}\n"
},
{
"from": "gpt",
"value": "// Copyright 2014 The Rust Project Developers. See the COPYRIGHT\n// file at the top-level directory of this distribution and at\n// http://rust-lang.org/COPYRIGHT.\n//\n// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or\n// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license\n// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your\n// option. This file may not be copied, modified, or distributed\n// except according to those terms.\n\nstruct NoCloneOrEq;\n\n#[deriving(PartialEq)]\nstruct E {\n x: NoCloneOrEq //~ ERROR does not implement any method in scope named `eq`\n //~^ ERROR does not implement any method in scope named `ne`\n}\n#[deriving(Clone)]\nstruct C {\n x: NoCloneOrEq\n //~^ ERROR the trait `core::clone::Clone` is not implemented for the type `NoCloneOrEq`\n}\n\n\nfn main() {}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix compile on riscv again\n"
},
{
"from": "human",
"value": "intrinsics! {\n // Implementation from gcc\n // https://raw.githubusercontent.com/gcc-mirror/gcc/master/libgcc/config/epiphany/mulsi3.c\n pub extern \"C\" fn __mulsi3(a: u32, b: u32) -> u32 {\n let (mut a, mut b) = (a, b);\n let mut r: usize = 0;\n\n while a > 0 {\n if a & 1 > 0 {\n r += b;\n }\n a >>= 1;\n b <<= 1;\n }\n\n r\n }\n}\n"
},
{
"from": "gpt",
"value": "intrinsics! {\n // Implementation from gcc\n // https://raw.githubusercontent.com/gcc-mirror/gcc/master/libgcc/config/epiphany/mulsi3.c\n pub extern \"C\" fn __mulsi3(a: u32, b: u32) -> u32 {\n let (mut a, mut b) = (a, b);\n let mut r = 0;\n\n while a > 0 {\n if a & 1 > 0 {\n r += b;\n }\n a >>= 1;\n b <<= 1;\n }\n\n r\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Remove unused parameter from Actor::kill()\n"
},
{
"from": "human",
"value": "use util::units::Point;\n\npub struct Actor {\n name: String,\n pos: Point,\n health: int,\n max_health: int,\n repr: char,\n}\n\nimpl Actor {\n\n pub fn new(name: String, pos: Point, max_health: int, repr: char) -> Actor {\n Actor {\n name: name,\n pos: pos,\n health: max_health,\n max_health: max_health,\n repr: repr,\n }\n }\n\n pub fn pos(&self) -> &Point {\n &self.pos\n }\n\n pub fn is_dead(&self) -> bool {\n self.health <= 0\n }\n\n pub fn hurt(&mut self, amount: int) {\n self.health -= amount;\n }\n\n pub fn heal(&mut self, amount: int) {\n self.health += amount;\n }\n\n pub fn kill(&mut self, amount: int) {\n self.health = 0;\n }\n\n}\n"
},
{
"from": "gpt",
"value": "use util::units::Point;\n\npub struct Actor {\n name: String,\n pos: Point,\n health: int,\n max_health: int,\n repr: char,\n}\n\nimpl Actor {\n\n pub fn new(name: String, pos: Point, max_health: int, repr: char) -> Actor {\n Actor {\n name: name,\n pos: pos,\n health: max_health,\n max_health: max_health,\n repr: repr,\n }\n }\n\n pub fn pos(&self) -> &Point {\n &self.pos\n }\n\n pub fn is_dead(&self) -> bool {\n self.health <= 0\n }\n\n pub fn hurt(&mut self, amount: int) {\n self.health -= amount;\n }\n\n pub fn heal(&mut self, amount: int) {\n self.health += amount;\n }\n\n pub fn kill(&mut self) {\n self.health = 0;\n }\n\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use map_or to simplify code\n\nIt looks better\n"
},
{
"from": "human",
"value": "use std::collections::HashMap;\n\nfn anagrams(word: &str) -> HashMap<char, u32> {\n let mut result: HashMap<char, u32> = HashMap::new();\n\n for k in word.chars() {\n let v = match result.get(&k) {\n Some(v) => v + 1,\n None => 1,\n };\n\n result.insert(k, v);\n }\n\n result\n}\n\npub fn anagrams_for(word: &str, input: &[&'static str]) -> Vec<&'static str> {\n let lword = word.to_lowercase();\n\n let dict = anagrams(&lword);\n\n let mut result: Vec<&str> = Vec::new();\n\n for s in input {\n let ls = s.to_lowercase();\n\n if ls == lword {\n continue;\n }\n\n if anagrams(&ls) == dict {\n result.push(s);\n }\n }\n\n result\n}\n"
},
{
"from": "gpt",
"value": "use std::collections::HashMap;\n\nfn anagrams(word: &str) -> HashMap<char, u32> {\n let mut result: HashMap<char, u32> = HashMap::new();\n\n for k in word.chars() {\n let v = result.get(&k).map_or(1, |v| v + 1);\n\n result.insert(k, v);\n }\n\n result\n}\n\npub fn anagrams_for(word: &str, input: &[&'static str]) -> Vec<&'static str> {\n let lword = word.to_lowercase();\n\n let dict = anagrams(&lword);\n\n let mut result: Vec<&str> = Vec::new();\n\n for s in input {\n let ls = s.to_lowercase();\n\n if ls == lword {\n continue;\n }\n\n if anagrams(&ls) == dict {\n result.push(s);\n }\n }\n\n result\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add ucontext and clone_args for loongarch64\n"
},
{
"from": "human",
"value": "s_no_extra_traits! {\n #[allow(missing_debug_implementations)]\n #[repr(align(16))]\n pub struct max_align_t {\n priv_: [f64; 4]\n }\n}\n"
},
{
"from": "gpt",
"value": "s_no_extra_traits! {\n #[allow(missing_debug_implementations)]\n #[repr(align(16))]\n pub struct max_align_t {\n priv_: [f64; 4]\n }\n}\n\ns! {\n pub struct ucontext_t {\n pub uc_flags: ::c_ulong,\n pub uc_link: *mut ucontext_t,\n pub uc_stack: ::stack_t,\n pub uc_sigmask: ::sigset_t,\n pub uc_mcontext: mcontext_t,\n }\n\n #[repr(align(16))]\n pub struct mcontext_t {\n pub sc_pc: ::c_ulonglong,\n pub sc_regs: [::c_ulonglong; 32],\n pub sc_flags: ::c_ulong,\n pub sc_extcontext: [u64; 0],\n }\n\n #[repr(align(8))]\n pub struct clone_args {\n pub flags: ::c_ulonglong,\n pub pidfd: ::c_ulonglong,\n pub child_tid: ::c_ulonglong,\n pub parent_tid: ::c_ulonglong,\n pub exit_signal: ::c_ulonglong,\n pub stack: ::c_ulonglong,\n pub stack_size: ::c_ulonglong,\n pub tls: ::c_ulonglong,\n pub set_tid: ::c_ulonglong,\n pub set_tid_size: ::c_ulonglong,\n pub cgroup: ::c_ulonglong,\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add ordering constraints to Alphabet. Add make_{non}terminal to DualAlphabet\n"
},
{
"from": "human",
"value": "extern crate expression;\n#[cfg(test)]\nextern crate expression_num;\n\npub mod parametric;\n\nuse std::fmt::Debug;\n\n/// Used to name symbols and variables.\npub trait Alphabet: Debug + PartialEq + Eq + Clone {}\n\nimpl Alphabet for &'static str {}\nimpl Alphabet for char {}\nimpl Alphabet for u8 {}\nimpl Alphabet for u16 {}\nimpl Alphabet for u32 {}\nimpl Alphabet for u64 {}\nimpl Alphabet for usize {}\n\n/// An alphabet that distinguishes between terminal\n/// and non-terminal symbols.\npub trait DualAlphabet: Alphabet {\n type Terminal: Alphabet;\n type NonTerminal: Alphabet;\n\n fn nonterminal(&self) -> Option<Self::NonTerminal>;\n fn terminal(&self) -> Option<Self::Terminal>;\n}\n"
},
{
"from": "gpt",
"value": "extern crate expression;\n#[cfg(test)]\nextern crate expression_num;\n\npub mod parametric;\n\nuse std::fmt::Debug;\n\n/// Used to name symbols and variables.\npub trait Alphabet: Debug + PartialEq + Eq + PartialOrd + Ord + Clone {}\n\nimpl Alphabet for &'static str {}\nimpl Alphabet for char {}\nimpl Alphabet for u8 {}\nimpl Alphabet for u16 {}\nimpl Alphabet for u32 {}\nimpl Alphabet for u64 {}\nimpl Alphabet for usize {}\n\n/// An alphabet that distinguishes between terminal\n/// and non-terminal symbols.\npub trait DualAlphabet: Alphabet {\n type Terminal: Alphabet;\n type NonTerminal: Alphabet;\n\n /// If the character is a non-terminal, return Some(..). Otherwise return None.\n fn nonterminal(&self) -> Option<Self::NonTerminal>;\n\n /// If the character is a terminal, return Some(..). Otherwise return None.\n fn terminal(&self) -> Option<Self::Terminal>;\n\n /// Constructs non-terminal\n fn make_nonterminal(nt: Self::NonTerminal) -> Self;\n\n /// Constructs terminal\n fn make_terminal(t: Self::Terminal) -> Self;\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix parsing empty C string.\n"
},
{
"from": "human",
"value": "extern crate libc;\n\nuse self::libc::c_char;\n\nuse std::ffi::CStr;\nuse std::str::Utf8Error;\nuse std::ffi::CString;\n\npub struct CStringUtils {}\n\nimpl CStringUtils {\n pub fn c_str_to_string(cstr: *const c_char) -> Result<Option<String>, Utf8Error> {\n if cstr.is_null() {\n return Ok(None)\n }\n\n unsafe {\n match CStr::from_ptr(cstr).to_str() {\n Ok(str) => Ok(Some(str.to_string())),\n Err(err) => Err(err)\n }\n }\n }\n\n pub fn string_to_cstring(s: String) -> CString {\n CString::new(s).unwrap()\n }\n}\n\nmacro_rules! check_useful_c_str {\n ($x:ident, $e:expr) => {\n let $x = match CStringUtils::c_str_to_string($x) {\n Ok(Some(val)) => val,\n Ok(None) => return $e,\n Err(_) => return $e\n };\n\n if $x.is_empty() {\n return $e\n }\n }\n}\n\nmacro_rules! check_useful_opt_c_str {\n ($x:ident, $e:expr) => {\n let $x = match CStringUtils::c_str_to_string($x) {\n Ok(Some(val)) => if val.is_empty() { None } else { Some(val) },\n Ok(None) => None,\n Err(_) => return $e\n };\n }\n}"
},
{
"from": "gpt",
"value": "extern crate libc;\n\nuse self::libc::c_char;\n\nuse std::ffi::CStr;\nuse std::str::Utf8Error;\nuse std::ffi::CString;\n\npub struct CStringUtils {}\n\nimpl CStringUtils {\n pub fn c_str_to_string(cstr: *const c_char) -> Result<Option<String>, Utf8Error> {\n if cstr.is_null() {\n return Ok(None);\n }\n\n unsafe {\n match CStr::from_ptr(cstr).to_str() {\n Ok(str) => Ok(Some(str.to_string())),\n Err(err) => Err(err)\n }\n }\n }\n\n pub fn string_to_cstring(s: String) -> CString {\n CString::new(s).unwrap()\n }\n}\n\nmacro_rules! check_useful_c_str {\n ($x:ident, $e:expr) => {\n let $x = match CStringUtils::c_str_to_string($x) {\n Ok(Some(val)) => val,\n _ => return $e,\n };\n\n if $x.is_empty() {\n return $e\n }\n }\n}\n\nmacro_rules! check_useful_opt_c_str {\n ($x:ident, $e:expr) => {\n let $x = match CStringUtils::c_str_to_string($x) {\n Ok(opt_val) => opt_val,\n Err(_) => return $e\n };\n }\n}"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add some logs to test the key pressed event\n"
},
{
"from": "human",
"value": "use nain_events::{EventCategory, KeyPressedEvent};\nuse nain_log as log;\n\npub trait Application {\n fn run(&self) {\n println!(\"Welcome to the Nain engine!\");\n\n let event = KeyPressedEvent::new(2, 5);\n log::trace!(\"{}\", event);\n\n loop {}\n }\n}\n"
},
{
"from": "gpt",
"value": "use nain_events::{Event, EventCategory, KeyPressedEvent};\nuse nain_log as log;\n\npub trait Application {\n fn run(&self) {\n println!(\"Welcome to the Nain engine!\");\n\n let event = KeyPressedEvent::new(2, 5);\n\n log::trace!(\"{}\", event);\n log::trace!(\"{}\", event.get_name());\n\n if event.is_in_category(EventCategory::Keyboard) {\n log::trace!(\"Event category: {}\", stringify!(EventCategory::Keyboard));\n }\n\n loop {}\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Build patterns in OUT_DIR only\n"
},
{
"from": "human",
"value": "extern crate glob;\n\nuse glob::glob;\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::fmt;\n\nfn main() {\n let mut output = String::new();\n\n fmt::write(\n &mut output,\n format_args!(\"pub static PATTERNS: &[(&'static str, &'static str)] = &[\\n\"),\n ).unwrap();\n\n for line in glob(\"patterns/*.pattern\").unwrap() // load filepaths\n // extract the filepath\n .map(|e| e.unwrap())\n // open file for path\n .map(|path| File::open(path).unwrap()) \n // flatten to actual lines\n .flat_map(|f| BufReader::new(f).lines()) \n .map(|line| line.unwrap())\n // filter comments\n .filter(|line| !line.starts_with(\"#\"))\n // filter empty lines\n .filter(|line| !line.is_empty())\n {\n let (key, value) = line.split_at(line.find(\" \").unwrap());\n fmt::write(\n &mut output,\n format_args!(\"\\t(\\\"{}\\\", r#\\\"{}\\\"#),\\n\", key, &value[1..]),\n ).unwrap();\n }\n\n fmt::write(&mut output, format_args!(\"];\\n\")).unwrap();\n\n let mut file = File::create(\"src/patterns.rs\").unwrap();\n file.write_all(output.as_bytes()).unwrap();\n}\n"
},
{
"from": "gpt",
"value": "extern crate glob;\n\nuse glob::glob;\nuse std::fs::File;\nuse std::io::prelude::*;\nuse std::io::BufReader;\nuse std::fmt;\nuse std::env;\nuse std::path::Path;\n\nfn main() {\n let mut output = String::new();\n\n fmt::write(\n &mut output,\n format_args!(\"pub static PATTERNS: &[(&'static str, &'static str)] = &[\\n\"),\n ).unwrap();\n\n for line in glob(\"patterns/*.pattern\").unwrap() // load filepaths\n // extract the filepath\n .map(|e| e.unwrap())\n // open file for path\n .map(|path| File::open(path).unwrap()) \n // flatten to actual lines\n .flat_map(|f| BufReader::new(f).lines()) \n .map(|line| line.unwrap())\n // filter comments\n .filter(|line| !line.starts_with(\"#\"))\n // filter empty lines\n .filter(|line| !line.is_empty())\n {\n let (key, value) = line.split_at(line.find(\" \").unwrap());\n fmt::write(\n &mut output,\n format_args!(\"\\t(\\\"{}\\\", r#\\\"{}\\\"#),\\n\", key, &value[1..]),\n ).unwrap();\n }\n\n fmt::write(&mut output, format_args!(\"];\\n\")).unwrap();\n\n let out_dir = env::var(\"OUT_DIR\").unwrap();\n let dest_path = Path::new(&out_dir).join(\"patterns.rs\");\n let mut file = File::create(&dest_path).unwrap();\n file.write_all(output.as_bytes()).unwrap();\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use env::arg instead of env macro\n"
},
{
"from": "human",
"value": "extern crate crowbook_localize;\nuse crowbook_localize::{Localizer, Extractor};\n\nuse std::path::Path;\n\nfn main() {\n println!(\"cargo:rerun-if-changed=build.rs\");\n println!(\"cargo:rerun-if-changed=lang/fr.po\");\n let mut extractor = Extractor::new();\n extractor.add_messages_from_dir(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/src\")).unwrap();\n extractor.write_pot_file(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/lang/crowbook.pot\")).unwrap();\n \n let mut localizer = Localizer::new(&extractor);\n localizer.add_lang(\"fr\", include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/lang/fr.po\"))).unwrap();\n let dest_path = Path::new(env!(\"OUT_DIR\")).join(\"localize_macros.rs\");\n localizer.write_macro_file(dest_path.to_str().unwrap()).unwrap();\n}\n"
},
{
"from": "gpt",
"value": "extern crate crowbook_localize;\nuse crowbook_localize::{Localizer, Extractor};\n\nuse std::path::Path;\nuse std::env;\n\n\nfn main() {\n// println!(\"cargo:rerun-if-changed=build.rs\");\n// println!(\"cargo:rerun-if-changed=lang/fr.po\");\n let mut extractor = Extractor::new();\n extractor.add_messages_from_dir(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/src\")).unwrap();\n extractor.write_pot_file(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/lang/crowbook.pot\")).unwrap();\n \n let mut localizer = Localizer::new(&extractor);\n localizer.add_lang(\"fr\", include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/lang/fr.po\"))).unwrap();\n let out_dir_path = env::var(\"OUT_DIR\").unwrap();\n let out_dir = Path::new(&out_dir_path);\n let dest_path = out_dir.join(\"localize_macros.rs\");\n localizer.write_macro_file(dest_path.to_str().unwrap()).unwrap();\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add 'Series' to supported metadata\n"
},
{
"from": "human",
"value": "use chrono::{DateTime, FixedOffset};\nuse serde_derive::Deserialize;\n\n#[derive(Deserialize)]\npub(super) struct Page {\n title: Option<String>,\n subtitle: Option<String>,\n summary: Option<String>,\n qualifiers: Option<Qualifiers>,\n date: Option<DateTime<FixedOffset>>,\n updated: Option<DateTime<FixedOffset>>,\n permalink: Option<String>,\n thanks: Option<String>,\n tags: Vec<String>,\n featured: bool,\n layout: Option<String>,\n}\n\n#[derive(Deserialize)]\nstruct Qualifiers {\n audience: Option<String>,\n epistemic: Option<String>,\n}\n\n#[derive(Deserialize)]\nstruct Book {\n title: String,\n author: String,\n editors: Vec<String>,\n translators: Vec<String>,\n cover: Option<String>,\n link: Option<String>,\n year: u16,\n review: Review,\n}\n\n#[derive(Deserialize)]\nstruct Review {\n rating: Rating,\n summary: String,\n}\n\n#[derive(Deserialize)]\nenum Rating {\n NotRecommended,\n WithQualifications,\n Recommended,\n Required,\n}\n\nimpl std::fmt::Display for Rating {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(\n f,\n \"{}\",\n match self {\n Rating::NotRecommended => \"Not recommended\",\n Rating::WithQualifications => \"Recommended with qualifications\",\n Rating::Recommended => \"Recommended\",\n Rating::Required => \"Required\",\n }\n )\n }\n}\n"
},
{
"from": "gpt",
"value": "use chrono::{DateTime, FixedOffset};\nuse serde_derive::Deserialize;\n\n#[derive(Deserialize)]\npub(super) struct Page {\n title: Option<String>,\n subtitle: Option<String>,\n summary: Option<String>,\n qualifiers: Option<Qualifiers>,\n date: Option<DateTime<FixedOffset>>,\n updated: Option<DateTime<FixedOffset>>,\n permalink: Option<String>,\n thanks: Option<String>,\n tags: Vec<String>,\n featured: bool,\n layout: Option<String>,\n series: Option<Series>,\n}\n\n#[derive(Deserialize)]\nstruct Qualifiers {\n audience: Option<String>,\n epistemic: Option<String>,\n}\n\n#[derive(Deserialize)]\nstruct Book {\n title: String,\n author: String,\n editors: Vec<String>,\n translators: Vec<String>,\n cover: Option<String>,\n link: Option<String>,\n year: u16,\n review: Review,\n}\n\n#[derive(Deserialize)]\nstruct Review {\n rating: Rating,\n summary: String,\n}\n\n#[derive(Deserialize)]\nenum Rating {\n NotRecommended,\n WithQualifications,\n Recommended,\n Required,\n}\n\nimpl std::fmt::Display for Rating {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(\n f,\n \"{}\",\n match self {\n Rating::NotRecommended => \"Not recommended\",\n Rating::WithQualifications => \"Recommended with qualifications\",\n Rating::Recommended => \"Recommended\",\n Rating::Required => \"Required\",\n }\n )\n }\n}\n\n#[derive(Deserialize)]\nstruct Series {\n name: String,\n part: u8,\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Rename method of Spanned to avoid conflict with syn Spanned\n"
},
{
"from": "human",
"value": "use crate::ToTokens;\nuse proc_macro2::{Span, TokenStream};\n\npub trait Spanned {\n fn span(&self) -> Span;\n}\n\nimpl Spanned for Span {\n fn span(&self) -> Span {\n *self\n }\n}\n\nimpl<T: ToTokens> Spanned for T {\n fn span(&self) -> Span {\n join_spans(self.into_token_stream())\n }\n}\n\nfn join_spans(tokens: TokenStream) -> Span {\n let mut iter = tokens.into_iter().filter_map(|tt| {\n // FIXME: This shouldn't be required, since optimally spans should\n // never be invalid. This filter_map can probably be removed when\n // https://github.com/rust-lang/rust/issues/43081 is resolved.\n let span = tt.span();\n let debug = format!(\"{:?}\", span);\n if debug.ends_with(\"bytes(0..0)\") {\n None\n } else {\n Some(span)\n }\n });\n\n let first = match iter.next() {\n Some(span) => span,\n None => return Span::call_site(),\n };\n\n #[cfg(procmacro2_semver_exempt)]\n return iter\n .fold(None, |_prev, next| Some(next))\n .and_then(|last| first.join(last))\n .unwrap_or(first);\n\n // We can't join spans without procmacro2_semver_exempt so just grab the\n // first one.\n #[cfg(not(procmacro2_semver_exempt))]\n return first;\n}\n"
},
{
"from": "gpt",
"value": "use crate::ToTokens;\nuse proc_macro2::{Span, TokenStream};\n\npub trait Spanned {\n fn __span(&self) -> Span;\n}\n\nimpl Spanned for Span {\n fn __span(&self) -> Span {\n *self\n }\n}\n\nimpl<T: ToTokens> Spanned for T {\n fn __span(&self) -> Span {\n join_spans(self.into_token_stream())\n }\n}\n\nfn join_spans(tokens: TokenStream) -> Span {\n let mut iter = tokens.into_iter().filter_map(|tt| {\n // FIXME: This shouldn't be required, since optimally spans should\n // never be invalid. This filter_map can probably be removed when\n // https://github.com/rust-lang/rust/issues/43081 is resolved.\n let span = tt.span();\n let debug = format!(\"{:?}\", span);\n if debug.ends_with(\"bytes(0..0)\") {\n None\n } else {\n Some(span)\n }\n });\n\n let first = match iter.next() {\n Some(span) => span,\n None => return Span::call_site(),\n };\n\n #[cfg(procmacro2_semver_exempt)]\n return iter\n .fold(None, |_prev, next| Some(next))\n .and_then(|last| first.join(last))\n .unwrap_or(first);\n\n // We can't join spans without procmacro2_semver_exempt so just grab the\n // first one.\n #[cfg(not(procmacro2_semver_exempt))]\n return first;\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix deprecation by deriving from Debug rather than Show.\n"
},
{
"from": "human",
"value": "#[derive(PartialEq, Show)]\npub enum Category {\n Whitespace,\n Identifier,\n Brace,\n Parenthesis,\n AssignmentOperator,\n IntegerLiteral,\n StringLiteral,\n}\n\npub struct Token {\n pub lexeme: String,\n pub category: Category,\n}\n"
},
{
"from": "gpt",
"value": "#[derive(PartialEq, Debug)]\npub enum Category {\n Whitespace,\n Identifier,\n Brace,\n Parenthesis,\n AssignmentOperator,\n IntegerLiteral,\n StringLiteral,\n}\n\npub struct Token {\n pub lexeme: String,\n pub category: Category,\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add test which uses assert!\n"
},
{
"from": "human",
"value": "#[derive(Debug)]\npub struct Rectangle {\n length: u32,\n width: u32\n}\n\nimpl Rectangle {\n pub fn can_hold(&self, other: &Rectangle) -> bool {\n self.length > other.length && self.width > other.width\n }\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn it_works() {\n }\n\n #[test]\n fn it_panics() {\n panic!(\"Make this test fail!\");\n }\n}\n"
},
{
"from": "gpt",
"value": "#[derive(Debug)]\npub struct Rectangle {\n length: u32,\n width: u32\n}\n\nimpl Rectangle {\n pub fn can_hold(&self, other: &Rectangle) -> bool {\n self.length > other.length && self.width > other.width\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n #[test]\n fn larger_can_hold_smaller() {\n let larger = Rectangle { length: 8, width: 8};\n let smaller = Rectangle { length:5, width: 5};\n\n assert!(larger.can_hold(&smaller));\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "stdlib: Modify union-find to guarantee that root nodes are always less than or equal to leaf nodes; add a \"prune\" method\n"
},
{
"from": "human",
"value": "import option::none;\nimport option::some;\n\n// A very naive implementation of union-find with unsigned integer nodes.\n\ntype node = option::t[uint];\ntype ufind = rec(mutable vec[mutable node] nodes);\n\nfn make() -> ufind {\n let vec[mutable node] v = [mutable none[uint]];\n vec::pop(v); // FIXME: botch\n ret rec(mutable nodes=v);\n}\n\nfn make_set(&ufind ufnd) -> uint {\n auto idx = vec::len(ufnd.nodes);\n ufnd.nodes += [mutable none[uint]];\n ret idx;\n}\n\nfn find(&ufind ufnd, uint n) -> uint {\n alt (ufnd.nodes.(n)) {\n case (none[uint]) { ret n; }\n case (some[uint](?m)) {\n // TODO: \"be\"\n ret find(ufnd, m);\n }\n }\n}\n\nfn union(&ufind ufnd, uint m, uint n) {\n auto m_root = find(ufnd, m);\n auto n_root = find(ufnd, n);\n auto ptr = some[uint](n_root);\n ufnd.nodes.(m_root) = ptr;\n}\n\n"
},
{
"from": "gpt",
"value": "import option::none;\nimport option::some;\n\n// A very naive implementation of union-find with unsigned integer nodes.\n// Maintains the invariant that the root of a node is always equal to or less\n// than the node itself.\n\ntype node = option::t[uint];\ntype ufind = rec(mutable vec[mutable node] nodes);\n\nfn make() -> ufind {\n let vec[mutable node] v = [mutable none[uint]];\n vec::pop(v); // FIXME: botch\n ret rec(mutable nodes=v);\n}\n\nfn make_set(&ufind ufnd) -> uint {\n auto idx = vec::len(ufnd.nodes);\n ufnd.nodes += [mutable none[uint]];\n ret idx;\n}\n\nfn find(&ufind ufnd, uint n) -> uint {\n alt (ufnd.nodes.(n)) {\n case (none[uint]) { ret n; }\n case (some[uint](?m)) { be find(ufnd, m); }\n }\n}\n\nfn union(&ufind ufnd, uint m, uint n) {\n auto m_root = find(ufnd, m);\n auto n_root = find(ufnd, n);\n if (m_root < n_root) {\n ufnd.nodes.(n_root) = some[uint](m_root);\n } else {\n ufnd.nodes.(m_root) = some[uint](n_root);\n }\n}\n\n// Removes all sets with IDs greater than or equal to the given value.\nfn prune(&ufind ufnd, uint n) {\n // TODO: Use \"slice\" once we get rid of \"mutable?\"\n while (n != 0u) {\n vec::pop[node](ufnd.nodes);\n n -= 1u;\n }\n}\n\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Build script tweak: using Path::display() correctly now.\n"
},
{
"from": "human",
"value": "use std::process::Command;\n\nextern crate pkg_config;\n\nconst C_IN: &'static str = \"include/include_ffi.h\";\nconst RS_OUT: &'static str = \"src/raw.rs\";\n\nfn main() {\n let libffi = pkg_config::probe_library(\"libffi\").expect(\"libffi\");\n\n let mut command = Command::new(\"bindgen\");\n command.arg(format!(\"--output={}\", RS_OUT))\n .arg(C_IN)\n .arg(\"--\");\n for path in &libffi.include_paths {\n command.arg(format!(\"-I{}\", path.display()));\n }\n\n let status = command.status().expect(\"bindgen\");\n assert!(status.success());\n\n for lib in &libffi.libs {\n println!(\"cargo:rustc-link-lib={}\", lib);\n }\n\n for path in &libffi.link_paths {\n println!(\"cargo:rustc-link-search={}\", path.to_str().unwrap());\n }\n}\n\n"
},
{
"from": "gpt",
"value": "use std::process::Command;\n\nextern crate pkg_config;\n\nconst C_IN: &'static str = \"include/include_ffi.h\";\nconst RS_OUT: &'static str = \"src/raw.rs\";\n\nfn main() {\n let libffi = pkg_config::probe_library(\"libffi\").expect(\"libffi\");\n\n let mut command = Command::new(\"bindgen\");\n command.arg(format!(\"--output={}\", RS_OUT))\n .arg(C_IN)\n .arg(\"--\");\n for path in &libffi.include_paths {\n command.arg(format!(\"-I{}\", path.display()));\n }\n\n let status = command.status().expect(\"bindgen\");\n assert!(status.success());\n\n for lib in &libffi.libs {\n println!(\"cargo:rustc-link-lib={}\", lib);\n }\n\n for path in &libffi.link_paths {\n println!(\"cargo:rustc-link-search={}\", path.display());\n }\n}\n\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix typo ('commited', needs 2nd 't')\n\nJust fixing a small typo in examples/transactions.rs. (The word \"committed\" should have a double-m a double-t. Right now, this code misspells it with just one t.)"
},
{
"from": "human",
"value": "// Copyright 2015, Igor Shaula\n// Licensed under the MIT License <LICENSE or\n// http://opensource.org/licenses/MIT>. This file\n// may not be copied, modified, or distributed\n// except according to those terms.\nextern crate winreg;\nuse std::io;\nuse winreg::RegKey;\nuse winreg::enums::*;\nuse winreg::transaction::Transaction;\n\nfn main() {\n let t = Transaction::new().unwrap();\n let hkcu = RegKey::predef(HKEY_CURRENT_USER);\n let key = hkcu.create_subkey_transacted(\"Software\\\\RustTransaction\", &t).unwrap();\n key.set_value(\"TestQWORD\", &1234567891011121314u64).unwrap();\n key.set_value(\"TestDWORD\", &1234567890u32).unwrap();\n\n println!(\"Commit transaction? [y/N]:\");\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input = input.trim_right().to_owned();\n if input == \"y\" || input == \"Y\" {\n t.commit().unwrap();\n println!(\"Transaction commited.\");\n }\n else {\n // this is optional, if transaction wasn't commited,\n // it will be rolled back on disposal\n t.rollback().unwrap();\n\n println!(\"Transaction wasn't commited, it will be rolled back.\");\n }\n}\n"
},
{
"from": "gpt",
"value": "// Copyright 2015, Igor Shaula\n// Licensed under the MIT License <LICENSE or\n// http://opensource.org/licenses/MIT>. This file\n// may not be copied, modified, or distributed\n// except according to those terms.\nextern crate winreg;\nuse std::io;\nuse winreg::RegKey;\nuse winreg::enums::*;\nuse winreg::transaction::Transaction;\n\nfn main() {\n let t = Transaction::new().unwrap();\n let hkcu = RegKey::predef(HKEY_CURRENT_USER);\n let key = hkcu.create_subkey_transacted(\"Software\\\\RustTransaction\", &t).unwrap();\n key.set_value(\"TestQWORD\", &1234567891011121314u64).unwrap();\n key.set_value(\"TestDWORD\", &1234567890u32).unwrap();\n\n println!(\"Commit transaction? [y/N]:\");\n let mut input = String::new();\n io::stdin().read_line(&mut input).unwrap();\n input = input.trim_right().to_owned();\n if input == \"y\" || input == \"Y\" {\n t.commit().unwrap();\n println!(\"Transaction committed.\");\n }\n else {\n // this is optional, if transaction wasn't committed,\n // it will be rolled back on disposal\n t.rollback().unwrap();\n\n println!(\"Transaction wasn't committed, it will be rolled back.\");\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix use of sleep function after api change\n"
},
{
"from": "human",
"value": "// Implements http://rosettacode.org/wiki/Concurrent_computing\n// not_tested\nuse std::io::timer::sleep;\nuse std::rand::random;\n\nfn main() {\n let strings = vec![\"Enjoy\", \"Rosetta\", \"Code\"];\n\n for s in strings.move_iter(){\n spawn(proc() {\n // We use a random u8 (so an integer from 0 to 255)\n sleep(random::<u8>() as u64);\n println!(\"{}\", s);\n });\n }\n}\n"
},
{
"from": "gpt",
"value": "// Implements http://rosettacode.org/wiki/Concurrent_computing\n// not_tested\nuse std::io::timer::sleep;\nuse std::rand::random;\nuse std::time::duration::Duration;\n\nfn main() {\n let strings = vec![\"Enjoy\", \"Rosetta\", \"Code\"];\n\n for s in strings.move_iter(){\n spawn(proc() {\n // We use a random u8 (so an integer from 0 to 255)\n sleep(Duration::milliseconds(random::<u8>() as i32));\n println!(\"{}\", s);\n });\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Fix syntax for non-doc comments, and use `crate::` instead of `std::`.\n"
},
{
"from": "human",
"value": "use std::mem::size_of;\nuse std::os::wasi::io::RawFd;\n\n#[test]\nfn test_raw_fd_layout() {\n /// `OwnedFd` and `BorrowedFd` use `rustc_layout_scalar_valid_range_start`\n /// and `rustc_layout_scalar_valid_range_end`, with values that depend on\n /// the bit width of `RawFd`. If this ever changes, those values will need\n /// to be updated.\n assert_eq!(size_of::<RawFd>(), 4);\n}\n"
},
{
"from": "gpt",
"value": "use crate::mem::size_of;\nuse crate::os::wasi::io::RawFd;\n\n#[test]\nfn test_raw_fd_layout() {\n // `OwnedFd` and `BorrowedFd` use `rustc_layout_scalar_valid_range_start`\n // and `rustc_layout_scalar_valid_range_end`, with values that depend on\n // the bit width of `RawFd`. If this ever changes, those values will need\n // to be updated.\n assert_eq!(size_of::<RawFd>(), 4);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Refactor tokenize to use str::words\n"
},
{
"from": "human",
"value": "extern mod std;\n\n#[test]\nfn test_tokenize() {\n assert tokenize( ~\"(1 2 3)\" ) == ~[~\"(\", ~\"1\", ~\"2\", ~\"3\", ~\")\"];\n}\n\n#[test]\nfn test_tokenize_empty() {\n assert tokenize( ~\"\" ) == ~[];\n}\n\n#[test]\nfn test_tokenize_no_spaces() {\n assert tokenize( ~\"one\" ) == ~[~\"one\"];\n}\n\n#[test]\nfn test_addspaces() {\n assert addspaces( ~\"(1 2 3)\" ) == ~\" ( 1 2 3 ) \"\n}\n\nfn addspaces( input:&str ) -> ~str {\n str::replace(str::replace(input, \")\", \" ) \"), \"(\", \" ( \")\n}\n\nfn tokenize( input:&str ) -> ~[~str] {\n str::split_str_nonempty(addspaces(input), \" \")\n}\n\nenum Expression {\n Value(int),\n Symbol(~str),\n List(~[Expression])\n }\n\nfn main() {\n let Blah:Expression = List(~[Value(1), List(~[Value(1), Symbol(~\"xyz\")])]);\n io::println( \"(begin 1 2)\" )\n}\n"
},
{
"from": "gpt",
"value": "extern mod std;\n\n#[test]\nfn test_tokenize() {\n assert tokenize( ~\"(1 2 3)\" ) == ~[~\"(\", ~\"1\", ~\"2\", ~\"3\", ~\")\"];\n}\n\n#[test]\nfn test_tokenize_empty() {\n assert tokenize( ~\"\" ) == ~[];\n}\n\n#[test]\nfn test_tokenize_no_spaces() {\n assert tokenize( ~\"one\" ) == ~[~\"one\"];\n}\n\n#[test]\nfn test_addspaces() {\n assert addspaces( ~\"(1 2 3)\" ) == ~\" ( 1 2 3 ) \"\n}\n\nfn addspaces( input:&str ) -> ~str {\n str::replace(str::replace(input, \")\", \" ) \"), \"(\", \" ( \")\n}\n\nfn tokenize( input:&str ) -> ~[~str] {\n str::words(addspaces(input))\n}\n\nenum Expression {\n Value(int),\n Symbol(~str),\n List(~[Expression])\n }\n\nfn main() {\n let Blah:Expression = List(~[Value(1), List(~[Value(1), Symbol(~\"xyz\")])]);\n io::println( \"(begin 1 2)\" )\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Use ast.generics.split_for_impl() to correctly generate impl with any generic parameters\n"
},
{
"from": "human",
"value": "#![feature(proc_macro)]\n#![feature(proc_macro_lib)]\n#![recursion_limit = \"128\"]\n\n#[macro_use] extern crate quote;\n\nextern crate proc_macro;\nextern crate syn;\n\nuse proc_macro::TokenStream;\n\n// Yield mock generated code for template\n// Hello, {{name}} ({{age}})\n#[proc_macro_derive(StacheDisplay)]\npub fn stache_display(input: TokenStream) -> TokenStream {\n let s = input.to_string();\n let ast = syn::parse_macro_input(&s).unwrap();\n\n let type_name = &ast.ident;\n let generics = &ast.generics;\n\n let gen = quote! {\n impl #generics std::fmt::Display for #type_name #generics {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n use display_html_safe::DisplayHtmlSafe;\n\n f.write_str(\"Hello, \")?;\n DisplayHtmlSafe::fmt(&self.name, f)?;\n f.write_str(\" (\")?;\n DisplayHtmlSafe::fmt(&self.age, f)?;\n f.write_str(\")\\n\")?;\n Ok(())\n }\n }\n };\n\n gen.parse().unwrap()\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn it_works() {\n }\n}\n"
},
{
"from": "gpt",
"value": "#![feature(proc_macro)]\n#![feature(proc_macro_lib)]\n#![recursion_limit = \"128\"]\n\n#[macro_use] extern crate quote;\n\nextern crate proc_macro;\nextern crate syn;\n\nuse proc_macro::TokenStream;\n\n// Yield mock generated code for template\n// Hello, {{name}} ({{age}})\n#[proc_macro_derive(StacheDisplay)]\npub fn stache_display(input: TokenStream) -> TokenStream {\n let s = input.to_string();\n let ast = syn::parse_macro_input(&s).unwrap();\n\n let name = &ast.ident;\n let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();\n\n let gen = quote! {\n impl #impl_generics std::fmt::Display for #name #ty_generics #where_clause {\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n use display_html_safe::DisplayHtmlSafe;\n\n f.write_str(\"Hello, \")?;\n DisplayHtmlSafe::fmt(&self.name, f)?;\n f.write_str(\" (\")?;\n DisplayHtmlSafe::fmt(&self.age, f)?;\n f.write_str(\")\\n\")?;\n Ok(())\n }\n }\n };\n\n gen.parse().unwrap()\n}\n\n#[cfg(test)]\nmod tests {\n #[test]\n fn it_works() {\n }\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add spec links for xul properties\n"
},
{
"from": "human",
"value": "/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\n<%namespace name=\"helpers\" file=\"/helpers.mako.rs\" />\n<% from data import Method %>\n\n// Non-standard properties that Gecko uses for XUL elements.\n<% data.new_style_struct(\"XUL\", inherited=False) %>\n\n${helpers.single_keyword(\"-moz-box-align\", \"stretch start center baseline end\",\n products=\"gecko\", gecko_ffi_name=\"mBoxAlign\",\n gecko_enum_prefix=\"StyleBoxAlign\",\n gecko_inexhaustive=True,\n animatable=False)}\n\n${helpers.predefined_type(\"-moz-box-flex\", \"Number\", \"0.0\", \"parse_non_negative\",\n products=\"gecko\", gecko_ffi_name=\"mBoxFlex\",\n needs_context=False,\n animatable=False)}\n"
},
{
"from": "gpt",
"value": "/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n\n<%namespace name=\"helpers\" file=\"/helpers.mako.rs\" />\n<% from data import Method %>\n\n// Non-standard properties that Gecko uses for XUL elements.\n<% data.new_style_struct(\"XUL\", inherited=False) %>\n\n${helpers.single_keyword(\"-moz-box-align\", \"stretch start center baseline end\",\n products=\"gecko\", gecko_ffi_name=\"mBoxAlign\",\n gecko_enum_prefix=\"StyleBoxAlign\",\n gecko_inexhaustive=True,\n animatable=False,\n spec=\"Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-align)\")}\n\n${helpers.predefined_type(\"-moz-box-flex\", \"Number\", \"0.0\", \"parse_non_negative\",\n products=\"gecko\", gecko_ffi_name=\"mBoxFlex\",\n needs_context=False,\n animatable=False,\n spec=\"Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-flex)\")}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Test is_scalar/is_array/is_compound for scalar types\n"
},
{
"from": "human",
"value": "#[macro_use]\nextern crate pod_typeinfo;\n\nuse std::mem;\n\nuse pod_typeinfo::Type::*;\nuse pod_typeinfo::{Type, TypeInfo};\n\n#[test]\nfn test_scalar_types() {\n fn check_type<T: TypeInfo>(ty: Type) {\n assert_eq!(<T as TypeInfo>::type_info(), ty);\n assert_eq!(ty.size(), mem::size_of::<T>());\n }\n check_type::<i8>(Int8);\n check_type::<i16>(Int16);\n check_type::<i32>(Int32);\n check_type::<i64>(Int64);\n check_type::<u8>(UInt8);\n check_type::<u16>(UInt16);\n check_type::<u32>(UInt32);\n check_type::<u64>(UInt64);\n check_type::<isize>(ISize);\n check_type::<usize>(USize);\n check_type::<f32>(Float32);\n check_type::<f64>(Float64);\n check_type::<bool>(Bool);\n check_type::<char>(Char);\n\n}\n"
},
{
"from": "gpt",
"value": "#[macro_use]\nextern crate pod_typeinfo;\n\nuse std::mem;\n\nuse pod_typeinfo::Type::*;\nuse pod_typeinfo::{Type, TypeInfo};\n\n#[test]\nfn test_scalar_types() {\n fn check_scalar_type<T: TypeInfo>(ty: Type) {\n assert_eq!(<T as TypeInfo>::type_info(), ty);\n assert_eq!(ty.size(), mem::size_of::<T>());\n assert!(ty.is_scalar() && !ty.is_array() && !ty.is_compound());\n }\n check_scalar_type::<i8>(Int8);\n check_scalar_type::<i16>(Int16);\n check_scalar_type::<i32>(Int32);\n check_scalar_type::<i64>(Int64);\n check_scalar_type::<u8>(UInt8);\n check_scalar_type::<u16>(UInt16);\n check_scalar_type::<u32>(UInt32);\n check_scalar_type::<u64>(UInt64);\n check_scalar_type::<isize>(ISize);\n check_scalar_type::<usize>(USize);\n check_scalar_type::<f32>(Float32);\n check_scalar_type::<f64>(Float64);\n check_scalar_type::<bool>(Bool);\n check_scalar_type::<char>(Char);\n\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add single listing to issue example.\n"
},
{
"from": "human",
"value": "\nextern crate gitlab_api as gitlab;\n\nuse std::env;\n#[macro_use]\nextern crate log;\nextern crate env_logger;\n\nuse gitlab::GitLab;\n// use gitlab::Pagination;\nuse gitlab::issues;\n\n\nfn main() {\n env_logger::init().unwrap();\n info!(\"starting up\");\n\n let hostname = match env::var(\"GITLAB_HOSTNAME\") {\n Ok(val) => val,\n Err(_) => {\n let default = String::from(\"gitlab.com\");\n println!(\"Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.\",\n default);\n default\n }\n };\n\n let token = match env::var(\"GITLAB_TOKEN\") {\n Ok(val) => val,\n Err(_) => {\n panic!(\"Please set environment variable 'GITLAB_TOKEN'. Take it from \\\n http://{}/profile/account\",\n hostname);\n }\n };\n\n let gl = GitLab::new_https(&hostname, &token);\n\n let issues = gl.issues(issues::Listing::new()).unwrap();\n println!(\"issues: {:?}\", issues);\n\n let listing = issues::Listing::new().state(issues::ListingState::Opened).clone();\n let opened_issues = gl.issues(listing).unwrap();\n println!(\"opened_issues: {:?}\", opened_issues);\n\n let listing = issues::Listing::new().state(issues::ListingState::Closed).clone();\n let closed_issues = gl.issues(listing).unwrap();\n println!(\"closed_issues: {:?}\", closed_issues);\n}\n"
},
{
"from": "gpt",
"value": "\nextern crate gitlab_api as gitlab;\n\nuse std::env;\n#[macro_use]\nextern crate log;\nextern crate env_logger;\n\nuse gitlab::GitLab;\n// use gitlab::Pagination;\nuse gitlab::issues;\n\n\nfn main() {\n env_logger::init().unwrap();\n info!(\"starting up\");\n\n let hostname = match env::var(\"GITLAB_HOSTNAME\") {\n Ok(val) => val,\n Err(_) => {\n let default = String::from(\"gitlab.com\");\n println!(\"Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.\",\n default);\n default\n }\n };\n\n let token = match env::var(\"GITLAB_TOKEN\") {\n Ok(val) => val,\n Err(_) => {\n panic!(\"Please set environment variable 'GITLAB_TOKEN'. Take it from \\\n http://{}/profile/account\",\n hostname);\n }\n };\n\n let gl = GitLab::new_https(&hostname, &token);\n\n let issues = gl.issues(issues::Listing::new()).unwrap();\n println!(\"issues: {:?}\", issues);\n\n let listing = issues::Listing::new().state(issues::ListingState::Opened).clone();\n let opened_issues = gl.issues(listing).unwrap();\n println!(\"opened_issues: {:?}\", opened_issues);\n\n let listing = issues::Listing::new().state(issues::ListingState::Closed).clone();\n let closed_issues = gl.issues(listing).unwrap();\n println!(\"closed_issues: {:?}\", closed_issues);\n\n let listing = issues::single::Listing::new(142, 739);\n let issue = gl.issue(listing).unwrap();\n println!(\"issue: {:?}\", issue);\n}\n"
}
] | rust | chosen |
[
{
"from": "system",
"value": "Add extra compile fail error\n"
},
{
"from": "human",
"value": "#[macro_use]\nextern crate diesel;\n\nuse diesel::*;\n\ntable! {\n int_primary_key {\n id -> Serial,\n }\n}\n\ntable! {\n string_primary_key {\n id -> VarChar,\n }\n}\n\nfn main() {\n let connection = Connection::establish(\"\").unwrap();\n let one = connection.find(int_primary_key::table, \"1\".to_string()).unwrap();\n //~^ ERROR E0277\n //~| ERROR E0277\n let string = connection.find(string_primary_key::table, 1).unwrap();\n //~^ ERROR E0277\n //~| ERROR E0277\n}\n"
},
{
"from": "gpt",
"value": "#[macro_use]\nextern crate diesel;\n\nuse diesel::*;\n\ntable! {\n int_primary_key {\n id -> Serial,\n }\n}\n\ntable! {\n string_primary_key {\n id -> VarChar,\n }\n}\n\nfn main() {\n let connection = Connection::establish(\"\").unwrap();\n let one = connection.find(int_primary_key::table, \"1\".to_string()).unwrap();\n //~^ ERROR E0277\n //~| ERROR E0277\n //~| ERROR E0277\n //~| ERROR E0277\n //~| ERROR E0277\n let string = connection.find(string_primary_key::table, 1).unwrap();\n //~^ ERROR E0277\n //~| ERROR E0277\n //~| ERROR E0277\n //~| ERROR E0277\n //~| ERROR E0277\n}\n"
}
] | rust | chosen |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.